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

Revision 681, 19.0 KB (checked in by plec_, 8 years ago)

Remove wrong note (deprecated version) of createNewObject

  • 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         * @param $id The id to be given to the new node
145         * @return the newly created Node object, or null if there was an error
146         */
147        static function createNewObject()
148        {
149                global $db;
150
151                $node_id = $db->EscapeString(get_guid());
152                $name = $db->EscapeString('New node');
153
154                $sql = "INSERT INTO nodes (node_id, name) VALUES ('$node_id','$name')";
155
156                if (!$db->ExecSqlUpdate($sql, false))
157                {
158                        throw new Exception(_('Unable to insert new node into database!'));
159                }
160                $object = new self($node_id);
161                return $object;
162        }
163
164        /** Create a new Node in the database
165         * @deprecated version - 18-Apr-2005
166         * @param $id The id to be given to the new node
167         * @return the newly created Node object, or null if there was an error
168         */
169        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)
170        {
171                global $db;
172
173                $node_id = $db->EscapeString($node_id);
174                $name = $db->EscapeString($name);
175                $rss_url = $db->EscapeString($rss_url);
176                $home_page_url = $db->EscapeString($home_page_url);
177                $description = $db->EscapeString($description);
178                $map_url = $db->EscapeString($map_url);
179                $street_address = $db->EscapeString($street_address);
180                $public_phone_number = $db->EscapeString($public_phone_number);
181                $public_email = $db->EscapeString($public_email);
182                $mass_transit_info = $db->EscapeString($mass_transit_info);
183                $node_deployment_status = $db->EscapeString($node_deployment_status);
184
185                if (Node :: nodeExists($node_id))
186                        throw new Exception(_('This node already exists.'));
187
188                $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')";
189
190                if (!$db->ExecSqlUpdate($sql, false))
191                {
192                        throw new Exception(_('Unable to insert new node into database!'));
193                }
194                $object = new self($node_id);
195                return $object;
196        }
197
198        /** Get an interface to pick a node.
199        * @param $user_prefix A identifier provided by the programmer to recognise it's generated html form
200        * @param $sql_additional_where Addidional where conditions to restrict the candidate objects
201        * @return html markup
202        */
203        public static function getSelectNodeUI($user_prefix, $sql_additional_where = null)
204        {
205                global $db;
206                $html = '';
207                $name = "{$user_prefix}";
208                $html .= "Node: \n";
209                $sql = "SELECT node_id, name from nodes WHERE 1=1 $sql_additional_where ORDER BY node_id";
210                $db->ExecSql($sql, $node_rows, false);
211                if ($node_rows != null)
212                {
213                        $i = 0;
214                        foreach ($node_rows as $node_row)
215                        {
216                                $tab[$i][0] = $node_row['node_id'];
217                                $tab[$i][1] = $node_row['node_id'].": ".$node_row['name'];
218                                $i ++;
219                        }
220                        $html .= FormSelectGenerator :: generateFromArray($tab, null, $name, null, false);
221                }
222                return $html;
223        }
224
225        /** Get the selected Network object.
226         * @param $user_prefix A identifier provided by the programmer to recognise it's generated form
227         * @return the Network object
228         */
229        static function processSelectNodeUI($user_prefix)
230        {
231                $object = null;
232                $name = "{$user_prefix}";
233                return new self($_REQUEST[$name]);
234        }
235
236        /** @param $node_id The id of the node */
237        function __construct($node_id)
238        {
239                global $db;
240
241                $node_id_str = $db->EscapeString($node_id);
242                $sql = "SELECT * FROM nodes WHERE node_id='$node_id_str'";
243                $db->ExecSqlUniqueRes($sql, $row, false);
244                if ($row == null)
245                {
246                        throw new Exception(_("The id $node_id_str could not be found in the database"));
247                }
248                $this->mRow = $row;
249                $this->id = $row['node_id'];
250        }
251
252        /** Return the name of the node
253         */
254        function getName()
255        {
256                return $this->mRow['name'];
257        }
258
259        function getID()
260        {
261                return $this->mRow['node_id'];
262        }
263
264        function getRSSURL()
265        {
266                return $this->mRow['rss_url'];
267        }
268
269        function getHomePageURL()
270        {
271                return $this->mRow['home_page_url'];
272        }
273
274        function getDescription()
275        {
276                return $this->mRow['description'];
277        }
278
279        function getMapURL()
280        {
281                return $this->mRow['map_url'];
282        }
283
284        function getAddress()
285        {
286                return $this->mRow['street_address'];
287        }
288
289        function getTelephone()
290        {
291                return $this->mRow['public_phone_number'];
292        }
293
294        function getTransitInfo()
295        {
296                return $this->mRow['mass_transit_info'];
297        }
298
299        function getEmail()
300        {
301                return $this->mRow['public_email'];
302        }
303
304        function getDeploymentStatus()
305        {
306                return $this->mRow['node_deployment_status'];
307        }
308
309        function setInfos($info_array)
310        {
311                global $db;
312
313                $infos_to_add = array ();
314                if ($info_array)
315                {
316                        foreach ($info_array as $column => $value)
317                        {
318                                $value = $db->EscapeString($value);
319                                array_push($infos_to_add, "$column='$value'");
320                        }
321                        $sql = "UPDATE nodes SET ";
322                        $sql .= implode(",", $infos_to_add);
323                        $sql .= " WHERE node_id='{$this->id}'";
324                        if (!$db->ExecSqlUpdate($sql, false))
325                        {
326                                throw new Exception(_('Unable to update database!'));
327                        }
328                }
329                else
330                {
331                        throw new Exception(_('No info to update node with!'));
332                }
333        }
334
335        /** Retreives the admin interface of this object.
336         * @return The HTML fragment for this interface */
337        public function getAdminUI()
338        {
339                $html = '';
340                $html .= "<div class='admin_container'>\n";
341                $html .= "<div class='admin_class'>Node (".get_class($this)." instance)</div>\n";
342
343                $html .= "<div class='admin_section_container'>\n";
344                $html .= "<div class='admin_section_title'>"._("Statistics:")."</div>\n";
345               
346                $name = "node_".$this->id."_get_stats";
347                $html .= "<input type='submit' name='$name' value='"._("Get access statistics")."'>";
348               
349                $html .= "</div>\n";
350               
351                $html .= "<div class='admin_section_container'>\n";
352                $html .= "<div class='admin_section_title'>"._("Node content:")."</div>\n";
353
354                $html .= "<ul class='admin_section_list'>\n";
355                foreach ($this->getAllContent() as $content)
356                {
357                        $html .= "<li class='admin_section_list_item'>\n";
358                        $html .= "<div class='admin_section_data'>\n";
359                        $html .= $content->getListUI();
360                        $html .= "</div'>\n";
361                        $html .= "<div class='admin_section_tools'>\n";
362                        $name = "node_".$this->id."_content_".$content->GetId()."_erase";
363                        $html .= "<input type='submit' name='$name' value='"._("Remove")."'>";
364                        $html .= "</div>\n";
365                        $html .= "</li>\n";
366                }
367                $html .= "<li class='admin_section_list_item'>\n";
368                $name = "node_{$this->id}_new_content";
369                $html .= Content :: getSelectContentUI($name, "AND content_id NOT IN (SELECT content_id FROM node_has_content WHERE node_id='$this->id')");
370                $name = "node_{$this->id}_new_content_submit";
371                $html .= "<input type='submit' name='$name' value='"._("Add")."'>";
372                $html .= "</li>\n";
373                $html .= "</ul>\n";
374                $html .= "</div>\n";
375                $html .= "</div>\n";
376                return $html;
377        }
378
379        /** Process admin interface of this object.
380        */
381        public function processAdminUI()
382        {
383                $user = User::getCurrentUser();
384                if (!$this->isOwner($user) && !$user->isSuperAdmin())
385                {
386                        throw new Exception(_('Access denied!'));
387                }
388
389                $name = "node_{$this->id}_get_stats";
390                if (!empty ($_REQUEST[$name]))
391                        header("Location: hotspot_log.php?node_id=".urlencode($this->getId()));
392               
393                foreach ($this->getAllContent() as $content)
394                {
395                        $name = "node_".$this->id."_content_".$content->GetId()."_erase";
396                        if (!empty ($_REQUEST[$name]))
397                        {
398                                $this->removeContent($content);
399                        }
400                }
401
402                $name = "node_{$this->id}_new_content_submit";
403                if (!empty ($_REQUEST[$name]))
404                {
405                        $name = "node_{$this->id}_new_content";
406                        $content = Content :: processSelectContentUI($name);
407            if($content)
408                $this->addContent($content);
409                }
410        }
411   
412    // Redirect to this node's portal page
413    public function getUserUI()
414    {
415        header("Location: ".BASE_SSL_PATH."portal/?gw_id=".$this->getId());
416    }
417
418        /** Add content to this node */
419        public function addContent(Content $content)
420        {
421                global $db;
422                $content_id = $db->EscapeString($content->getId());
423                $sql = "INSERT INTO node_has_content (node_id, content_id) VALUES ('$this->id','$content_id')";
424                $db->ExecSqlUpdate($sql, false);
425        }
426
427        /** Remove content from this node */
428        public function removeContent(Content $content)
429        {
430                global $db;
431                $content_id = $db->EscapeString($content->getId());
432                $sql = "DELETE FROM node_has_content WHERE node_id='$this->id' AND content_id='$content_id'";
433                $db->ExecSqlUpdate($sql, false);
434        }
435
436        /**Get an array of all Content linked to this node
437     * @param boolean $exclude_subscribed_content
438        * @param User $subscriber The User object used to discriminate the content
439    * @return an array of Content or an empty arrray */
440    function getAllContent($exclude_subscribed_content = false, $subscriber = null)
441        {
442                global $db;
443                $retval = array ();
444        // Get all network, but exclude user subscribed content if asked
445        if ($exclude_subscribed_content == true && $subscriber)
446            $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";
447        else
448            $sql = "SELECT content_id FROM node_has_content WHERE node_id='$this->id' ORDER BY subscribe_timestamp";
449                $db->ExecSql($sql, $content_rows, false);
450       
451                if ($content_rows != null)
452                {
453                        foreach ($content_rows as $content_row)
454                        {
455                                $retval[] = Content :: getObject($content_row['content_id']);
456                        }
457                }
458                return $retval;
459        }
460   
461    /** Get an array of all artistic and locative Content for this hotspot
462    * @return an array of Content or an empty arrray */
463    function getAllLocativeArtisticContent()
464    {
465        global $db;
466        $retval = array ();
467        $sql = "SELECT * FROM content_group JOIN content ON (content.content_id = content_group.content_group_id) JOIN node_has_content ON (node_has_content.content_id = content_group.content_group_id AND node_has_content.node_id = '{$this->getId()}') WHERE is_persistent = true AND is_artistic_content = true AND is_locative_content = true";
468        $db->ExecSql($sql, $content_rows, false);
469        if ($content_rows != null)
470        {
471            foreach ($content_rows as $content_row)
472            {
473                // Create a content group object and grab only those that have content for the current Node
474                $content_group = Content::getObject($content_row['content_group_id']);
475                if($content_group->getDisplayNumElements() >= 1)
476                {
477                        if($content_group->isDisplayableAt($this))
478                        {
479                                                // Disable logging and allow content to expand ( if possible )
480                                                $content_group->setExpandStatus(true);
481                                                $content_group->setLoggingStatus(false);
482                                                $retval[] = $content_group;
483                        }
484                }
485            }
486        }
487        return $retval;
488    }
489
490        /** Return all the nodes
491         */
492        static function getAllNodes()
493        {
494                global $db;
495
496                $db->ExecSql("SELECT * FROM nodes", $nodes, false);
497
498                if ($nodes == null)
499                        throw new Exception(_("No nodes could not be found in the database"));
500
501                return $nodes;
502        }
503
504        static function getAllNodesOrdered($order_by)
505        {
506                global $db;
507
508                $db->ExecSql("SELECT * FROM nodes ORDER BY $order_by", $nodes, false);
509
510                if ($nodes == null)
511                        throw new Exception(_("No nodes could not be found in the database"));
512
513                return $nodes;
514        }
515
516        static function getAllNodesWithStatus()
517        {
518                global $db;
519
520                $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, node_deployment_status FROM nodes ORDER BY node_id", $nodes, false);
521
522                if ($nodes == null)
523                        throw new Exception(_("No nodes could not be found in the database"));
524
525                return $nodes;
526        }
527
528        static function getAllDeploymentStatus()
529        {
530                global $db;
531
532                $db->ExecSql("SELECT * FROM node_deployment_status", $statuses, false);
533                if ($statuses == null)
534                        throw new Exception(_("No deployment statues  could be found in the database"));
535
536                $statuses_array = array ();
537                foreach ($statuses as $status)
538                        array_push($statuses_array, $status['node_deployment_status']);
539
540                return $statuses_array;
541        }
542
543    /** The list of users online at this node
544     * @return An array of User object, or en empty array */
545        function getOnlineUsers()
546        {
547                global $db;
548                $retval=array();
549                $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);
550                if($users != null)
551                {
552                        foreach ($users as $user_row)
553                        {
554                                $retval[] = User::getObject($user_row['user_id']);
555                        }
556                }
557                return $retval;
558        }
559
560        function getOwners()
561        {
562                global $db;
563
564                $db->ExecSql("SELECT user_id FROM node_owners WHERE node_id='{$this->id}'", $owners, false);
565                return $owners;
566        }
567
568        function addOwner($user_id)
569        {
570                /* TODO: VALIDER les champs de donnees node_id et user_id */
571
572                global $db;
573                if (!$db->ExecSqlUpdate("INSERT INTO node_owners (node_id, user_id) VALUES ('{$this->id}','{$user_id}')", false))
574                        throw new Exception(_('Could not add owner'));
575        }
576
577        function removeOwner($user_id)
578        {
579                global $db;
580                if (!$db->ExecSqlUpdate("DELETE FROM node_owners WHERE node_id='{$this->id}' AND user_id='{$user_id}'", false))
581                        throw new Exception(_('Could not remove owner'));
582        }
583
584        /** Is the user an owner of the Node?
585         * @return true our false*/
586        function isOwner(User $user)
587        {
588                global $db;
589                if ($user != null)
590                {
591                        $user_id = $user->getId();
592                        $retval = false;
593                        $db->ExecSqlUniqueRes("SELECT * FROM node_owners WHERE node_id='{$this->id}' AND user_id='{$user_id}'", $row, false);
594                        if ($row != null)
595                        {
596                                $retval = true;
597                        }
598                }
599                return $retval;
600        }
601
602        function nodeExists($id)
603        {
604                global $db;
605                $id_str = $db->EscapeString($id);
606                $sql = "SELECT * FROM nodes WHERE node_id='{$id_str}'";
607                $db->ExecSqlUniqueRes($sql, $row, false);
608                return $row;
609        }
610
611        function getInfoArray()
612        {
613                return $this->mRow;
614        }
615
616    /** Warning, the semantics of this function will change *
617     * @deprecated version - 2005-04-29 USE getOnlineUsers instead
618     * */
619        public static function getAllOnlineUsers()
620        {
621                global $db;
622                $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);
623                return $online_users;
624        }
625
626} // End class
627?>
Note: See TracBrowser for help on using the browser.