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

Revision 566, 16.4 KB (checked in by benoitg, 8 years ago)

2005-04-25 Benoit Gr�goire <bock@…>

  • Integration merge, should work, but there will be display problems everywhere. Expect further commits today.
  • Almost 100% complete Network abstraction
  • Much better object encapsulation. Deprecated methods not removed yet.
  • Add MainUI class. Used to display the interface. Inner workings still need work.
  • 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 */
26require_once BASEPATH.'include/common.php';
27
28/** Abstract a Node.  A Node is an actual physical transmitter. */
29class Node implements GenericObject
30{
31        private $mRow;
32        private $id;
33        private static $current_node_id = null;
34
35        /** Instantiate a node object
36         * @param $id The id of the requested node
37         * @return a Node object, or null if there was an error
38         */
39        static function getObject($id)
40        {
41                $object = null;
42                $object = new self($id);
43                return $object;
44        }
45
46        /** Get the current node for which the portal is displayed or to which a user is physically connected.
47         * @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.
48         * @return a Node object, or null if it can't be found.
49         */
50        static function getCurrentNode($real_node_only = false)
51        {
52                $object = null;
53                if (self :: $current_node_id != null && $real_node_only == false)
54                {
55                        $object = new self(self :: $current_node_id);
56                }
57                else
58                {
59                        $object = self::getCurrentRealNode();
60                }
61                return $object;
62        }
63
64        /** Set the current node where the user is to be considered connected to.  (For portal and content display purpuses, among other.
65         * @param $node Node.  The new current node.
66         * @return true  */
67        static function setCurrentNode(Node $node)
68        {
69                self :: $current_node_id = $node->GetId();
70                return true;
71        }
72
73        /** 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
74         * @param        * @return a Node object, or null if it can't be found.
75         */
76        public static function getCurrentRealNode()
77        {
78                global $db;
79                $retval = null;
80                $sql = "SELECT node_id, last_heartbeat_ip from nodes WHERE last_heartbeat_ip='$_SERVER[REMOTE_ADDR]'";
81                $db->ExecSql($sql, $node_rows, false);
82                $num_match = count($node_rows);
83                if ($num_match == 0)
84                {
85
86                        // User is not physically connected to a node
87                        $retval = null;
88                }
89                else
90                        if ($num_match = 1)
91                        {
92                                // Only a single node matches, the user is presumed to be there
93                                $retval = new self($node_rows[0]['node_id']);
94                        }
95                        else
96                        {
97                                /* We have more than one node matching the IP (the nodes are behind the same NAT).
98                                 * We will try to discriminate by finding which node the user last authenticated against.
99                                 * If the IP matches, we can be pretty certain the user is there.
100                                 */
101                                $retval = null;
102                                $current_user = User :: getCurrentUser();
103                                if ($current_user != null)
104                                {
105                                        $current_user_id = $current_user->getId();
106                                        $_SERVER['REMOTE_ADDR'];
107                                        $sql = "SELECT node_id, last_heartbeat_ip from connections NATURAL JOIN nodes WHERE user_id='$current_user_id' ORDER BY last_updated DESC ";
108                                        $db->ExecSql($sql, $node_rows, false);
109                                        $node_row = $node_rows[0];
110                                        if($node_row!=null && $node_row['last_heartbeat_ip']==$_SERVER['REMOTE_ADDR'])
111                                        {
112                                                $retval = new self($node_row['node_id']);
113                                        }
114                                }
115                        }
116        return $retval;
117        }
118
119        public function delete(& $errmsg)
120        {
121                $retval = false;
122                $user = User :: getCurrentUser();
123                if ($this->isOwner($user) || $user->isSuperAdmin())
124                {
125                        $errmsg = _('Access denied!');
126                }
127                global $db;
128
129                if (!$db->ExecSqlUpdate("DELETE FROM nodes WHERE node_id='{$this->$id}'", false))
130                {
131                        $errmsg = _('Could not delete node!');
132                }
133                else
134                {
135                        $retval = true;
136                }
137                return $retval;
138        }
139
140        /** Create a new Node in the database
141         * @deprecated version - 18-Apr-2005
142         * @param $id The id to be given to the new node
143         * @return the newly created Node object, or null if there was an error
144         */
145        static function createNewObject()
146        {
147                global $db;
148
149                $node_id = $db->EscapeString(get_guid());
150                $name = $db->EscapeString('New node');
151
152                $sql = "INSERT INTO nodes (node_id, name) VALUES ('$node_id','$name')";
153
154                if (!$db->ExecSqlUpdate($sql, false))
155                {
156                        throw new Exception(_('Unable to insert new node into database!'));
157                }
158                $object = new self($node_id);
159                return $object;
160        }
161
162        /** Create a new Node in the database
163         * @deprecated version - 18-Apr-2005
164         * @param $id The id to be given to the new node
165         * @return the newly created Node object, or null if there was an error
166         */
167        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)
168        {
169                global $db;
170
171                $node_id = $db->EscapeString($node_id);
172                $name = $db->EscapeString($name);
173                $rss_url = $db->EscapeString($rss_url);
174                $home_page_url = $db->EscapeString($home_page_url);
175                $description = $db->EscapeString($description);
176                $map_url = $db->EscapeString($map_url);
177                $street_address = $db->EscapeString($street_address);
178                $public_phone_number = $db->EscapeString($public_phone_number);
179                $public_email = $db->EscapeString($public_email);
180                $mass_transit_info = $db->EscapeString($mass_transit_info);
181                $node_deployment_status = $db->EscapeString($node_deployment_status);
182
183                if (Node :: nodeExists($node_id))
184                        throw new Exception(_('This node already exists.'));
185
186                $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')";
187
188                if (!$db->ExecSqlUpdate($sql, false))
189                {
190                        throw new Exception(_('Unable to insert new node into database!'));
191                }
192                $object = new self($node_id);
193                return $object;
194        }
195
196        /** Get an interface to pick a node.
197        * @param $user_prefix A identifier provided by the programmer to recognise it's generated html form
198        * @param $sql_additional_where Addidional where conditions to restrict the candidate objects
199        * @return html markup
200        */
201        public static function getSelectNodeUI($user_prefix, $sql_additional_where = null)
202        {
203                global $db;
204                $html = '';
205                $name = "{$user_prefix}";
206                $html .= "Node: \n";
207                $sql = "SELECT node_id, name from nodes WHERE 1=1 $sql_additional_where ORDER BY node_id";
208                $db->ExecSql($sql, $node_rows, false);
209                if ($node_rows != null)
210                {
211                        $i = 0;
212                        foreach ($node_rows as $node_row)
213                        {
214                                $tab[$i][0] = $node_row['node_id'];
215                                $tab[$i][1] = $node_row['node_id'].": ".$node_row['name'];
216                                $i ++;
217                        }
218                        $html .= FormSelectGenerator :: generateFromArray($tab, null, $name, null, false);
219                }
220                return $html;
221        }
222
223        /** Get the selected Network object.
224         * @param $user_prefix A identifier provided by the programmer to recognise it's generated form
225         * @return the Network object
226         */
227        static function processSelectNodeUI($user_prefix)
228        {
229                $object = null;
230                $name = "{$user_prefix}";
231                return new self($_REQUEST[$name]);
232        }
233
234        /** @param $node_id The id of the node */
235        function __construct($node_id)
236        {
237                global $db;
238
239                $node_id_str = $db->EscapeString($node_id);
240                $sql = "SELECT * FROM nodes WHERE node_id='$node_id_str'";
241                $db->ExecSqlUniqueRes($sql, $row, false);
242                if ($row == null)
243                {
244                        throw new Exception(_("The id $node_id_str could not be found in the database"));
245                }
246                $this->mRow = $row;
247                $this->id = $row['node_id'];
248        }
249
250        /** Return the name of the node
251         */
252        function getName()
253        {
254                return $this->mRow['name'];
255        }
256
257        function getID()
258        {
259                return $this->mRow['node_id'];
260        }
261
262        function getRSSURL()
263        {
264                return $this->mRow['rss_url'];
265        }
266
267        function getHomePageURL()
268        {
269                return $this->mRow['home_page_url'];
270        }
271
272        function getDescription()
273        {
274                return $this->mRow['description'];
275        }
276
277        function getMapURL()
278        {
279                return $this->mRow['map_url'];
280        }
281
282        function getAddress()
283        {
284                return $this->mRow['street_address'];
285        }
286
287        function getTelephone()
288        {
289                return $this->mRow['public_phone_number'];
290        }
291
292        function getTransitInfo()
293        {
294                return $this->mRow['mass_transit_info'];
295        }
296
297        function getEmail()
298        {
299                return $this->mRow['public_email'];
300        }
301
302        function getDeploymentStatus()
303        {
304                return $this->mRow['node_deployment_status'];
305        }
306
307        function setInfos($info_array)
308        {
309                global $db;
310
311                $infos_to_add = array ();
312                if ($info_array)
313                {
314                        foreach ($info_array as $column => $value)
315                        {
316                                $value = $db->EscapeString($value);
317                                array_push($infos_to_add, "$column='$value'");
318                        }
319                        $sql = "UPDATE nodes SET ";
320                        $sql .= implode(",", $infos_to_add);
321                        $sql .= " WHERE node_id='{$this->id}'";
322                        if (!$db->ExecSqlUpdate($sql, false))
323                        {
324                                throw new Exception(_('Unable to update database!'));
325                        }
326                }
327                else
328                {
329                        throw new Exception(_('No info to update node with!'));
330                }
331        }
332
333        /** Retreives the admin interface of this object.
334         * @return The HTML fragment for this interface */
335        public function getAdminUI()
336        {
337                $html = '';
338                $html .= "<div class='admin_container'>\n";
339                $html .= "<div class='admin_class'>Node (".get_class($this)." instance)</div>\n";
340
341                $html .= "<div class='admin_section_container'>\n";
342                $html .= "<div class='admin_section_title'>"._("Node content:")."</div>\n";
343
344                $html .= "<ul class='admin_section_list'>\n";
345                foreach ($this->getAllContent() as $content)
346                {
347                        $html .= "<li class='admin_section_list_item'>\n";
348                        $html .= "<div class='admin_section_data'>\n";
349                        $html .= $content->getListUI();
350                        $html .= "</div'>\n";
351                        $html .= "<div class='admin_section_tools'>\n";
352                        $name = "node_".$this->id."_content_".$content->GetId()."_erase";
353                        $html .= "<input type='submit' name='$name' value='"._("Remove")."' onclick='submit();'>";
354                        $html .= "</div>\n";
355                        $html .= "</li>\n";
356                }
357                $html .= "<li class='admin_section_list_item'>\n";
358                $name = "node_{$this->id}_new_content";
359                $html .= Content :: getSelectContentUI($name, "AND content_id NOT IN (SELECT content_id FROM node_has_content WHERE node_id='$this->id')");
360                $name = "node_{$this->id}_new_content_submit";
361                $html .= "<input type='submit' name='$name' value='"._("Add")."' onclick='submit();'>";
362                $html .= "</li>\n";
363                $html .= "</ul>\n";
364                $html .= "</div>\n";
365                $html .= "</div>\n";
366                return $html;
367        }
368
369        /** Process admin interface of this object.
370        */
371        public function processAdminUI()
372        {
373                $user = User::getCurrentUser();
374                if (!$this->isOwner($user) || !$user->isSuperAdmin())
375                {
376                        throw new Exception(_('Access denied!'));
377                }
378
379                foreach ($this->getAllContent() as $content)
380                {
381                        $name = "node_".$this->id."_content_".$content->GetId()."_erase";
382                        if (!empty ($_REQUEST[$name]))
383                        {
384                                $this->removeContent($content);
385                        }
386                }
387
388                $name = "node_{$this->id}_new_content_submit";
389                if (!empty ($_REQUEST[$name]))
390                {
391                        $name = "node_{$this->id}_new_content";
392                        $content = Content :: processSelectContentUI($name);
393                        $this->addContent($content);
394                }
395        }
396
397        /** Add content to this node */
398        public function addContent(Content $content)
399        {
400                global $db;
401                $content_id = $db->EscapeString($content->getId());
402                $sql = "INSERT INTO node_has_content (node_id, content_id) VALUES ('$this->id','$content_id')";
403                $db->ExecSqlUpdate($sql, false);
404        }
405
406        /** Remove content from this node */
407        public function removeContent(Content $content)
408        {
409                global $db;
410                $content_id = $db->EscapeString($content->getId());
411                $sql = "DELETE FROM node_has_content WHERE node_id='$this->id' AND content_id='$content_id'";
412                $db->ExecSqlUpdate($sql, false);
413        }
414
415        /**Get an array of all Content linked to this node
416        * @return an array of Content or an empty arrray */
417        function getAllContent()
418        {
419                global $db;
420                $retval = array ();
421                $sql = "SELECT * FROM node_has_content WHERE node_id='$this->id' ORDER BY subscribe_timestamp";
422                $db->ExecSql($sql, $content_rows, false);
423                if ($content_rows != null)
424                {
425                        foreach ($content_rows as $content_row)
426                        {
427                                $retval[] = Content :: getObject($content_row['content_id']);
428                        }
429                }
430                return $retval;
431        }
432
433        /** Return all the nodes
434         */
435        static function getAllNodes()
436        {
437                global $db;
438
439                $db->ExecSql("SELECT * FROM nodes", $nodes, false);
440
441                if ($nodes == null)
442                        throw new Exception(_("No nodes could not be found in the database"));
443
444                return $nodes;
445        }
446
447        static function getAllNodesOrdered($order_by)
448        {
449                global $db;
450
451                $db->ExecSql("SELECT * FROM nodes ORDER BY $order_by", $nodes, false);
452
453                if ($nodes == null)
454                        throw new Exception(_("No nodes could not be found in the database"));
455
456                return $nodes;
457        }
458
459        static function getAllNodesWithStatus()
460        {
461                global $db;
462
463                $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);
464
465                if ($nodes == null)
466                        throw new Exception(_("No nodes could not be found in the database"));
467
468                return $nodes;
469        }
470
471        static function getAllDeploymentStatus()
472        {
473                global $db;
474
475                $db->ExecSql("SELECT * FROM node_deployment_status", $statuses, false);
476                if ($statuses == null)
477                        throw new Exception(_("No deployment statues  could be found in the database"));
478
479                $statuses_array = array ();
480                foreach ($statuses as $status)
481                        array_push($statuses_array, $status['node_deployment_status']);
482
483                return $statuses_array;
484        }
485
486/** The list of users online at this node
487 * @return An array of User object, or en empty array */
488        function getOnlineUsers()
489        {
490                global $db;
491                $retval=array();
492                $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);
493                if($users!=null)
494                {
495                        foreach ($users as $user_row)
496                        {
497                                $retval[]=getObject($user_row['user_id']);
498                        }
499                }
500                return $users;
501        }
502
503        function getOwners()
504        {
505                global $db;
506
507                $db->ExecSql("SELECT user_id FROM node_owners WHERE node_id='{$this->id}'", $owners, false);
508                return $owners;
509        }
510
511        function addOwner($user_id)
512        {
513                /* TODO: VALIDER les champs de donnees node_id et user_id */
514
515                global $db;
516                if (!$db->ExecSqlUpdate("INSERT INTO node_owners (node_id, user_id) VALUES ('{$this->id}','{$user_id}')", false))
517                        throw new Exception(_('Could not add owner'));
518        }
519
520        function removeOwner($user_id)
521        {
522                global $db;
523                if (!$db->ExecSqlUpdate("DELETE FROM node_owners WHERE node_id='{$this->id}' AND user_id='{$user_id}'", false))
524                        throw new Exception(_('Could not remove owner'));
525        }
526
527        /** Is the user an owner of the Node?
528         * @return true our false*/
529        function isOwner(User $user)
530        {
531                global $db;
532                if ($user != null)
533                {
534                        $user_id = $user->getId();
535                        $retval = false;
536                        $db->ExecSqlUniqueRes("SELECT * FROM node_owners WHERE node_id='{$this->id}' AND user_id='{$user_id}'", $row, false);
537                        if ($row != null)
538                        {
539                                $retval = true;
540                        }
541                }
542                return $retval;
543        }
544
545        function nodeExists($id)
546        {
547                global $db;
548                $id_str = $db->EscapeString($id);
549                $sql = "SELECT * FROM nodes WHERE node_id='{$id_str}'";
550                $db->ExecSqlUniqueRes($sql, $row, false);
551                return $row;
552        }
553
554        function getInfoArray()
555        {
556                return $this->mRow;
557        }
558
559/** Warning, the semantics of this function will change */
560        public static function getAllOnlineUsers()
561        {
562                global $db;
563                $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);
564                return $online_users;
565        }
566
567} // End class
568?>
Note: See TracBrowser for help on using the browser.