root/trunk/wifidog-auth/wifidog/classes/Node.php @ 601

Revision 601, 18.4 KB (checked in by fproulx, 8 years ago)

2005-04-29 Fran�ois Proulx <francois.proulx@…>

  • Removed all inline unuseful javascript code on submit buttons onclick='submit()'
  • This conflicted with the actual click on the submit button in Safari
  • Fixed check in Network for isOwner, only check superAdmin
  • Fixed bug so you can't add an existing content group to itself ( deadlock )
  • Started coding Pattern language narrative display
  • Property svn:eol-style set to native
  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
Line 
1<?php
2
3
4/********************************************************************\
5 * This program is free software; you can redistribute it and/or    *
6 * modify it under the terms of the GNU General Public License as   *
7 * published by the Free Software Foundation; either version 2 of   *
8 * the License, or (at your option) any later version.              *
9 *                                                                  *
10 * This program is distributed in the hope that it will be useful,  *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of   *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the    *
13 * GNU General Public License for more details.                     *
14 *                                                                  *
15 * You should have received a copy of the GNU General Public License*
16 * along with this program; if not, contact:                        *
17 *                                                                  *
18 * Free Software Foundation           Voice:  +1-617-542-5942       *
19 * 59 Temple Place - Suite 330        Fax:    +1-617-542-2652       *
20 * Boston, MA  02111-1307,  USA       gnu@gnu.org                   *
21 *                                                                  *
22 \********************************************************************/
23/**@file Node.php
24 * @author Copyright (C) 2005 Benoit Gr�goire <bock@step.polymtl.ca>
25 */
26 
27require_once BASEPATH.'include/common.php';
28require_once 'Content/ContentGroup.php';
29require_once BASEPATH.'classes/User.php';
30
31/** Abstract a Node.  A Node is an actual physical transmitter. */
32class Node implements GenericObject
33{
34        private $mRow;
35        private $id;
36        private static $current_node_id = null;
37
38        /** Instantiate a node object
39         * @param $id The id of the requested node
40         * @return a Node object, or null if there was an error
41         */
42        static function getObject($id)
43        {
44                $object = null;
45                $object = new self($id);
46                return $object;
47        }
48
49        /** Get the current node for which the portal is displayed or to which a user is physically connected.
50         * @param $real_node_only true or false.  If true, the real physical node where the user is connected is returned, and the node set by setCurrentNode is ignored.
51         * @return a Node object, or null if it can't be found.
52         */
53        static function getCurrentNode($real_node_only = false)
54        {
55                $object = null;
56                if (self :: $current_node_id != null && $real_node_only == false)
57                {
58                        $object = new self(self :: $current_node_id);
59                }
60                else
61                {
62                        $object = self::getCurrentRealNode();
63                }
64                return $object;
65        }
66
67        /** Set the current node where the user is to be considered connected to.  (For portal and content display purpuses, among other.
68         * @param $node Node.  The new current node.
69         * @return true  */
70        static function setCurrentNode(Node $node)
71        {
72                self :: $current_node_id = $node->GetId();
73                return true;
74        }
75
76        /** Get the current node to which a user is physically connected, if any.  This is done by an IP adress lookup against the last reported IP adress of the node
77         * @param        * @return a Node object, or null if it can't be found.
78         */
79        public static function getCurrentRealNode()
80        {
81                global $db;
82                $retval = null;
83                $sql = "SELECT node_id, last_heartbeat_ip from nodes WHERE last_heartbeat_ip='$_SERVER[REMOTE_ADDR]'";
84                $db->ExecSql($sql, $node_rows, false);
85                $num_match = count($node_rows);
86                if ($num_match == 0)
87                {
88
89                        // User is not physically connected to a node
90                        $retval = null;
91                }
92                else
93                        if ($num_match = 1)
94                        {
95                                // Only a single node matches, the user is presumed to be there
96                                $retval = new self($node_rows[0]['node_id']);
97                        }
98                        else
99                        {
100                                /* We have more than one node matching the IP (the nodes are behind the same NAT).
101                                 * We will try to discriminate by finding which node the user last authenticated against.
102                                 * If the IP matches, we can be pretty certain the user is there.
103                                 */
104                                $retval = null;
105                                $current_user = User :: getCurrentUser();
106                                if ($current_user != null)
107                                {
108                                        $current_user_id = $current_user->getId();
109                                        $_SERVER['REMOTE_ADDR'];
110                                        $sql = "SELECT node_id, last_heartbeat_ip from connections NATURAL JOIN nodes WHERE user_id='$current_user_id' ORDER BY last_updated DESC ";
111                                        $db->ExecSql($sql, $node_rows, false);
112                                        $node_row = $node_rows[0];
113                                        if($node_row!=null && $node_row['last_heartbeat_ip']==$_SERVER['REMOTE_ADDR'])
114                                        {
115                                                $retval = new self($node_row['node_id']);
116                                        }
117                                }
118                        }
119        return $retval;
120        }
121
122        public function delete(& $errmsg)
123        {
124                $retval = false;
125                $user = User :: getCurrentUser();
126                if ($this->isOwner($user) || $user->isSuperAdmin())
127                {
128                        $errmsg = _('Access denied!');
129                }
130                global $db;
131
132                if (!$db->ExecSqlUpdate("DELETE FROM nodes WHERE node_id='{$this->$id}'", false))
133                {
134                        $errmsg = _('Could not delete node!');
135                }
136                else
137                {
138                        $retval = true;
139                }
140                return $retval;
141        }
142
143        /** Create a new Node in the database
144         * @deprecated version - 18-Apr-2005
145         * @param $id The id to be given to the new node
146         * @return the newly created Node object, or null if there was an error
147         */
148        static function createNewObject()
149        {
150                global $db;
151
152                $node_id = $db->EscapeString(get_guid());
153                $name = $db->EscapeString('New node');
154
155                $sql = "INSERT INTO nodes (node_id, name) VALUES ('$node_id','$name')";
156
157                if (!$db->ExecSqlUpdate($sql, false))
158                {
159                        throw new Exception(_('Unable to insert new node into database!'));
160                }
161                $object = new self($node_id);
162                return $object;
163        }
164
165        /** Create a new Node in the database
166         * @deprecated version - 18-Apr-2005
167         * @param $id The id to be given to the new node
168         * @return the newly created Node object, or null if there was an error
169         */
170        static function createNode($node_id, $name, $rss_url, $home_page_url, $description, $map_url, $street_address, $public_phone_number, $public_email, $mass_transit_info, $node_deployment_status)
171        {
172                global $db;
173
174                $node_id = $db->EscapeString($node_id);
175                $name = $db->EscapeString($name);
176                $rss_url = $db->EscapeString($rss_url);
177                $home_page_url = $db->EscapeString($home_page_url);
178                $description = $db->EscapeString($description);
179                $map_url = $db->EscapeString($map_url);
180                $street_address = $db->EscapeString($street_address);
181                $public_phone_number = $db->EscapeString($public_phone_number);
182                $public_email = $db->EscapeString($public_email);
183                $mass_transit_info = $db->EscapeString($mass_transit_info);
184                $node_deployment_status = $db->EscapeString($node_deployment_status);
185
186                if (Node :: nodeExists($node_id))
187                        throw new Exception(_('This node already exists.'));
188
189                $sql = "INSERT INTO nodes (node_id, name, rss_url, creation_date, home_page_url, description, map_url, street_address, public_phone_number, public_email, mass_transit_info, node_deployment_status) VALUES ('$node_id','$name','$rss_url',NOW(),'$home_page_url','$description','$map_url','$street_address','$public_phone_number','$public_email','$mass_transit_info','$node_deployment_status')";
190
191                if (!$db->ExecSqlUpdate($sql, false))
192                {
193                        throw new Exception(_('Unable to insert new node into database!'));
194                }
195                $object = new self($node_id);
196                return $object;
197        }
198
199        /** Get an interface to pick a node.
200        * @param $user_prefix A identifier provided by the programmer to recognise it's generated html form
201        * @param $sql_additional_where Addidional where conditions to restrict the candidate objects
202        * @return html markup
203        */
204        public static function getSelectNodeUI($user_prefix, $sql_additional_where = null)
205        {
206                global $db;
207                $html = '';
208                $name = "{$user_prefix}";
209                $html .= "Node: \n";
210                $sql = "SELECT node_id, name from nodes WHERE 1=1 $sql_additional_where ORDER BY node_id";
211                $db->ExecSql($sql, $node_rows, false);
212                if ($node_rows != null)
213                {
214                        $i = 0;
215                        foreach ($node_rows as $node_row)
216                        {
217                                $tab[$i][0] = $node_row['node_id'];
218                                $tab[$i][1] = $node_row['node_id'].": ".$node_row['name'];
219                                $i ++;
220                        }
221                        $html .= FormSelectGenerator :: generateFromArray($tab, null, $name, null, false);
222                }
223                return $html;
224        }
225
226        /** Get the selected Network object.
227         * @param $user_prefix A identifier provided by the programmer to recognise it's generated form
228         * @return the Network object
229         */
230        static function processSelectNodeUI($user_prefix)
231        {
232                $object = null;
233                $name = "{$user_prefix}";
234                return new self($_REQUEST[$name]);
235        }
236
237        /** @param $node_id The id of the node */
238        function __construct($node_id)
239        {
240                global $db;
241
242                $node_id_str = $db->EscapeString($node_id);
243                $sql = "SELECT * FROM nodes WHERE node_id='$node_id_str'";
244                $db->ExecSqlUniqueRes($sql, $row, false);
245                if ($row == null)
246                {
247                        throw new Exception(_("The id $node_id_str could not be found in the database"));
248                }
249                $this->mRow = $row;
250                $this->id = $row['node_id'];
251        }
252
253        /** Return the name of the node
254         */
255        function getName()
256        {
257                return $this->mRow['name'];
258        }
259
260        function getID()
261        {
262                return $this->mRow['node_id'];
263        }
264
265        function getRSSURL()
266        {
267                return $this->mRow['rss_url'];
268        }
269
270        function getHomePageURL()
271        {
272                return $this->mRow['home_page_url'];
273        }
274
275        function getDescription()
276        {
277                return $this->mRow['description'];
278        }
279
280        function getMapURL()
281        {
282                return $this->mRow['map_url'];
283        }
284
285        function getAddress()
286        {
287                return $this->mRow['street_address'];
288        }
289
290        function getTelephone()
291        {
292                return $this->mRow['public_phone_number'];
293        }
294
295        function getTransitInfo()
296        {
297                return $this->mRow['mass_transit_info'];
298        }
299
300        function getEmail()
301        {
302                return $this->mRow['public_email'];
303        }
304
305        function getDeploymentStatus()
306        {
307                return $this->mRow['node_deployment_status'];
308        }
309
310        function setInfos($info_array)
311        {
312                global $db;
313
314                $infos_to_add = array ();
315                if ($info_array)
316                {
317                        foreach ($info_array as $column => $value)
318                        {
319                                $value = $db->EscapeString($value);
320                                array_push($infos_to_add, "$column='$value'");
321                        }
322                        $sql = "UPDATE nodes SET ";
323                        $sql .= implode(",", $infos_to_add);
324                        $sql .= " WHERE node_id='{$this->id}'";
325                        if (!$db->ExecSqlUpdate($sql, false))
326                        {
327                                throw new Exception(_('Unable to update database!'));
328                        }
329                }
330                else
331                {
332                        throw new Exception(_('No info to update node with!'));
333                }
334        }
335
336        /** Retreives the admin interface of this object.
337         * @return The HTML fragment for this interface */
338        public function getAdminUI()
339        {
340                $html = '';
341                $html .= "<div class='admin_container'>\n";
342                $html .= "<div class='admin_class'>Node (".get_class($this)." instance)</div>\n";
343
344                $html .= "<div class='admin_section_container'>\n";
345                $html .= "<div class='admin_section_title'>"._("Node content:")."</div>\n";
346
347                $html .= "<ul class='admin_section_list'>\n";
348                foreach ($this->getAllContent() as $content)
349                {
350                        $html .= "<li class='admin_section_list_item'>\n";
351                        $html .= "<div class='admin_section_data'>\n";
352                        $html .= $content->getListUI();
353                        $html .= "</div'>\n";
354                        $html .= "<div class='admin_section_tools'>\n";
355                        $name = "node_".$this->id."_content_".$content->GetId()."_erase";
356                        $html .= "<input type='submit' name='$name' value='"._("Remove")."'>";
357                        $html .= "</div>\n";
358                        $html .= "</li>\n";
359                }
360                $html .= "<li class='admin_section_list_item'>\n";
361                $name = "node_{$this->id}_new_content";
362                $html .= Content :: getSelectContentUI($name, "AND content_id NOT IN (SELECT content_id FROM node_has_content WHERE node_id='$this->id')");
363                $name = "node_{$this->id}_new_content_submit";
364                $html .= "<input type='submit' name='$name' value='"._("Add")."'>";
365                $html .= "</li>\n";
366                $html .= "</ul>\n";
367                $html .= "</div>\n";
368                $html .= "</div>\n";
369                return $html;
370        }
371
372        /** Process admin interface of this object.
373        */
374        public function processAdminUI()
375        {
376                $user = User::getCurrentUser();
377                if (!$this->isOwner($user) && !$user->isSuperAdmin())
378                {
379                        throw new Exception(_('Access denied!'));
380                }
381
382                foreach ($this->getAllContent() as $content)
383                {
384                        $name = "node_".$this->id."_content_".$content->GetId()."_erase";
385                        if (!empty ($_REQUEST[$name]))
386                        {
387                                $this->removeContent($content);
388                        }
389                }
390
391                $name = "node_{$this->id}_new_content_submit";
392                if (!empty ($_REQUEST[$name]))
393                {
394                        $name = "node_{$this->id}_new_content";
395                        $content = Content :: processSelectContentUI($name);
396            if($content)
397                $this->addContent($content);
398                }
399        }
400   
401    // Redirect to this node's portal page
402    public function getUserUI()
403    {
404        header("Location: ".BASE_SSL_PATH."portal/?gw_id=".$this->getId());
405    }
406
407        /** Add content to this node */
408        public function addContent(Content $content)
409        {
410                global $db;
411                $content_id = $db->EscapeString($content->getId());
412                $sql = "INSERT INTO node_has_content (node_id, content_id) VALUES ('$this->id','$content_id')";
413                $db->ExecSqlUpdate($sql, false);
414        }
415
416        /** Remove content from this node */
417        public function removeContent(Content $content)
418        {
419                global $db;
420                $content_id = $db->EscapeString($content->getId());
421                $sql = "DELETE FROM node_has_content WHERE node_id='$this->id' AND content_id='$content_id'";
422                $db->ExecSqlUpdate($sql, false);
423        }
424
425        /**Get an array of all Content linked to this node
426     * @param boolean $exclude_subscribed_content
427        * @param User $subscriber The User object used to discriminate the content
428    * @return an array of Content or an empty arrray */
429    function getAllContent($exclude_subscribed_content = false, $subscriber = null)
430        {
431                global $db;
432                $retval = array ();
433        // Get all network, but exclude user subscribed content if asked
434        if ($exclude_subscribed_content == true && $subscriber)
435            $sql = "SELECT content_id FROM node_has_content WHERE node_id='$this->id' AND content_id NOT IN (SELECT content_id FROM user_has_content WHERE user_id = '{$subscriber->getId()}') ORDER BY subscribe_timestamp";
436        else
437            $sql = "SELECT content_id FROM node_has_content WHERE node_id='$this->id' ORDER BY subscribe_timestamp";
438                $db->ExecSql($sql, $content_rows, false);
439       
440                if ($content_rows != null)
441                {
442                        foreach ($content_rows as $content_row)
443                        {
444                                $retval[] = Content :: getObject($content_row['content_id']);
445                        }
446                }
447                return $retval;
448        }
449   
450    /** Get an array of all artistic and locative Content for this hotspot
451    * @return an array of Content or an empty arrray */
452    function getAllLocativeArtisticContent()
453    {
454        global $db;
455        $retval = array ();
456        $sql = "SELECT * FROM content_group JOIN content ON (content.content_id = content_group.content_group_id) WHERE is_persistent = true AND is_artistic_content = true AND is_locative_content = true";
457        $db->ExecSql($sql, $content_rows, false);
458        if ($content_rows != null)
459        {
460            foreach ($content_rows as $content_row)
461            {
462                // Create a content group object and grab only those that have content for the current Node
463                $content_group = Content::getObject($content_row['content_group_id']);
464                if($content_group->getDisplayNumElements() >= 1)
465                {
466                    // Disable logging and allow content to expand ( if possible )
467                    $content_group->setExpandStatus(true);
468                    $content_group->setLoggingStatus(false);
469                    $retval[] = $content_group;
470                }
471            }
472        }
473        return $retval;
474    }
475
476        /** Return all the nodes
477         */
478        static function getAllNodes()
479        {
480                global $db;
481
482                $db->ExecSql("SELECT * FROM nodes", $nodes, false);
483
484                if ($nodes == null)
485                        throw new Exception(_("No nodes could not be found in the database"));
486
487                return $nodes;
488        }
489
490        static function getAllNodesOrdered($order_by)
491        {
492                global $db;
493
494                $db->ExecSql("SELECT * FROM nodes ORDER BY $order_by", $nodes, false);
495
496                if ($nodes == null)
497                        throw new Exception(_("No nodes could not be found in the database"));
498
499                return $nodes;
500        }
501
502        static function getAllNodesWithStatus()
503        {
504                global $db;
505
506                $db->ExecSql("SELECT node_id, name, last_heartbeat_user_agent, (NOW()-last_heartbeat_timestamp) AS since_last_heartbeat, last_heartbeat_ip, CASE WHEN ((NOW()-last_heartbeat_timestamp) < interval '5 minutes') THEN true ELSE false END AS online, creation_date FROM nodes ORDER BY node_id", $nodes, false);
507
508                if ($nodes == null)
509                        throw new Exception(_("No nodes could not be found in the database"));
510
511                return $nodes;
512        }
513
514        static function getAllDeploymentStatus()
515        {
516                global $db;
517
518                $db->ExecSql("SELECT * FROM node_deployment_status", $statuses, false);
519                if ($statuses == null)
520                        throw new Exception(_("No deployment statues  could be found in the database"));
521
522                $statuses_array = array ();
523                foreach ($statuses as $status)
524                        array_push($statuses_array, $status['node_deployment_status']);
525
526                return $statuses_array;
527        }
528
529    /** The list of users online at this node
530     * @return An array of User object, or en empty array */
531        function getOnlineUsers()
532        {
533                global $db;
534                $retval=array();
535                $db->ExecSql("SELECT users.user_id FROM users,connections WHERE connections.token_status='".TOKEN_INUSE."' AND users.user_id=connections.user_id AND connections.node_id='{$this->id}'", $users, false);
536                if($users != null)
537                {
538                        foreach ($users as $user_row)
539                        {
540                                $retval[] = User::getObject($user_row['user_id']);
541                        }
542                }
543                return $retval;
544        }
545
546        function getOwners()
547        {
548                global $db;
549
550                $db->ExecSql("SELECT user_id FROM node_owners WHERE node_id='{$this->id}'", $owners, false);
551                return $owners;
552        }
553
554        function addOwner($user_id)
555        {
556                /* TODO: VALIDER les champs de donnees node_id et user_id */
557
558                global $db;
559                if (!$db->ExecSqlUpdate("INSERT INTO node_owners (node_id, user_id) VALUES ('{$this->id}','{$user_id}')", false))
560                        throw new Exception(_('Could not add owner'));
561        }
562
563        function removeOwner($user_id)
564        {
565                global $db;
566                if (!$db->ExecSqlUpdate("DELETE FROM node_owners WHERE node_id='{$this->id}' AND user_id='{$user_id}'", false))
567                        throw new Exception(_('Could not remove owner'));
568        }
569
570        /** Is the user an owner of the Node?
571         * @return true our false*/
572        function isOwner(User $user)
573        {
574                global $db;
575                if ($user != null)
576                {
577                        $user_id = $user->getId();
578                        $retval = false;
579                        $db->ExecSqlUniqueRes("SELECT * FROM node_owners WHERE node_id='{$this->id}' AND user_id='{$user_id}'", $row, false);
580                        if ($row != null)
581                        {
582                                $retval = true;
583                        }
584                }
585                return $retval;
586        }
587
588        function nodeExists($id)
589        {
590                global $db;
591                $id_str = $db->EscapeString($id);
592                $sql = "SELECT * FROM nodes WHERE node_id='{$id_str}'";
593                $db->ExecSqlUniqueRes($sql, $row, false);
594                return $row;
595        }
596
597        function getInfoArray()
598        {
599                return $this->mRow;
600        }
601
602    /** Warning, the semantics of this function will change *
603     * @deprecated version - 2005-04-29 USE getOnlineUsers instead
604     * */
605        public static function getAllOnlineUsers()
606        {
607                global $db;
608                $db->ExecSql("SELECT * FROM connections,users,nodes WHERE token_status='".TOKEN_INUSE."' AND users.user_id=connections.user_id AND nodes.node_id=connections.node_id ORDER BY timestamp_in DESC", $online_users);
609                return $online_users;
610        }
611
612} // End class
613?>
Note: See TracBrowser for help on using the browser.