root/trunk/wifidog-auth/wifidog/classes/VirtualHost.php @ 1308

Revision 1308, 23.4 KB (checked in by benoitg, 6 years ago)
  • Some HTML validity fixes
RevLine 
[1249]1<?php
2
3/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
4
5// +-------------------------------------------------------------------+
6// | WiFiDog Authentication Server                                     |
7// | =============================                                     |
8// |                                                                   |
9// | The WiFiDog Authentication Server is part of the WiFiDog captive  |
10// | portal suite.                                                     |
11// +-------------------------------------------------------------------+
12// | PHP version 5 required.                                           |
13// +-------------------------------------------------------------------+
14// | Homepage:     http://www.wifidog.org/                             |
15// | Source Forge: http://sourceforge.net/projects/wifidog/            |
16// +-------------------------------------------------------------------+
17// | This program is free software; you can redistribute it and/or     |
18// | modify it under the terms of the GNU General Public License as    |
19// | published by the Free Software Foundation; either version 2 of    |
20// | the License, or (at your option) any later version.               |
21// |                                                                   |
22// | This program is distributed in the hope that it will be useful,   |
23// | but WITHOUT ANY WARRANTY; without even the implied warranty of    |
24// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the     |
25// | GNU General Public License for more details.                      |
26// |                                                                   |
27// | You should have received a copy of the GNU General Public License |
28// | along with this program; if not, contact:                         |
29// |                                                                   |
30// | Free Software Foundation           Voice:  +1-617-542-5942        |
31// | 59 Temple Place - Suite 330        Fax:    +1-617-542-2652        |
32// | Boston, MA  02111-1307,  USA       gnu@gnu.org                    |
33// |                                                                   |
34// +-------------------------------------------------------------------+
35
36/**
37 * @package    WiFiDogAuthServer
38 * @author     Max Horvath <max.horvath@maxspot.de>
39 * @author     Benoit Grégoire <bock@step.polymtl.ca>
40 * @copyright  2006 Max Horvath, maxspot GmbH
41 * @copyright  2007 Benoit Grégoire, Technologies Coeus inc.
42 * @version    Subversion $Id: $
43 * @link       http://www.wifidog.org/
44 */
45
46/**
47 * Load required classes
48 */
49require_once('classes/GenericObject.php');
[1267]50require_once('classes/Server.php');
[1249]51
52/**
53 * Administration interface for defining all Virtual hosts on the server running WiFiDog
54 *
55 * @package    WiFiDogAuthServer
56 * @author     Max Horvath <max.horvath@maxspot.de>
57 * @author     Benoit Grégoire <bock@step.polymtl.ca>
58 * @copyright  2006 Max Horvath, maxspot GmbH
59 * @copyright  2007 Benoit Grégoire, Technologies Coeus inc.
60 */
61class VirtualHost implements GenericObject
62{
63    /** Object cache for the object factory (getObject())*/
64    private static $instanceArray = array();
65    /**
66     * The server Id
67     *
68     * @var string
69
70     */
71    private $_id;
72
73    /**
74     * All information about the server
75     *
76     * @var array
77     *
78     * @access private
79     */
80    private $__row;
81
82    /**
83     * Constructor
84     *
85     * @param string $p_server_id Id of the vhost
86     *
87     * @access private
88     */
89    private function __construct($p_server_id)
90    {
91         
92        $db = AbstractDb::getObject();
93
94        // Init values
95        $_row = null;
96
97        $_serverId = $db->escapeString($p_server_id);
98        $sql = "SELECT * FROM virtual_hosts WHERE virtual_host_id='$_serverId'";
99        $db->execSqlUniqueRes($sql, $_row, false);
100
101        if ($_row == null) {
102            throw new Exception("The virtual host with id $_serverId could not be found in the database!");
103        }
104
105        $this->__row = $_row;
106
107        $this->_id = $db->escapeString($_row['virtual_host_id']);
108    }
109
110    /**
111     * Retreives the Id of the object
112     *
113     * @return string The Id
114     */
115    public function getId()
116    {
117        return $this->_id;
118    }
119
120    /** Get an instance of the object
121     *
122     * @param string $id The object id
123     *
124     * @return object The object, or null if there was an error (an exception
125     *                is also thrown)
126     *
127     * @see GenericObject
128
129     */
130    public static function &getObject($id)
131    {
132        if(!isset(self::$instanceArray[$id]))
133        {
134            self::$instanceArray[$id] = new self($id);
135        }
136        return self::$instanceArray[$id];
137    }
138
139    /**
140     * Get all servers configured on this WiFiDog instance
141     *
142     * @return array An array of server objects. The default server is returned
143     *               first
144     *
145     * @static
146     * @access public
147     */
148    public static function getAllServers()
149    {
150         
151        $db = AbstractDb::getObject();
152
153        // Init values
154        $retVal = array ();
155
156        $sql = "SELECT server_id FROM servers ORDER BY is_default_server DESC";
157        $serverRows = null;
158
159        $db->execSql($sql, $serverRows, false);
160
161        if ($serverRows == null) {
162            throw new Exception(_("Server::getAllServers: Fatal error: No servers in the database!"));
163        }
164
165        foreach ($serverRows as $serverRow) {
166            $retVal[] = self::getObject($serverRow['server_id']);
167        }
168
169        return $retVal;
170    }
171
172
173    /**
174     * Get the default server
175     *
176     * @return object A VirtualHost object, NEVER returns null
177     *
178     * @static
179     * @access public
180     */
181    public static function &getDefaultVirtualHost()
182    {
183         
184        $db = AbstractDb::getObject();
185
186        // Init values
187        $retVal = null;
188        $serverRow = null;
189
190        $sql = "SELECT default_virtual_host FROM server ORDER BY creation_date LIMIT 1";
191        $db->execSqlUniqueRes($sql, $serverRow, false);
192
193        if ($serverRow == null) {
194            throw new Exception("Server::getDefaultVirtualHost: Fatal error: Unable to find the default virtual host!");
195        }
196
197        $retVal = VirtualHost::getObject($serverRow['default_virtual_host']);
198        return $retVal;
199    }
200
201    /**
202     * Get the current virtual for which the portal is displayed or to which a
203     * user is physically connected.
204     *
205     * @param bool $silent If true, no exception will be thrown
206     *
207     * @return mixed A server object, returns null if server hasn't been found
208     *               in the database
209     */
210    public static function getCurrentVirtualHost()
211    {
212        if(empty($_SERVER['SERVER_NAME']))
213        {
214            return null; //We were probably called from the command line
215        }
216         
217        $db = AbstractDb::getObject();
218
219        // Init values
220        $retVal = null;
221        $serverRow = null;
222
223        $sql = "SELECT virtual_host_id FROM virtual_hosts WHERE hostname='{$_SERVER['SERVER_NAME']}'";
224        $db->execSqlUniqueRes($sql, $serverRow, false);
225
226        if ($serverRow == null) {
227            return null;
228        } else if ($serverRow != null) {
229            $retVal = self::getObject($serverRow['virtual_host_id']);
230        }
231        return $retVal;
232    }
233
234    /**
235     * Create a new Content object in the database
236     *
237     * @param string $server_id The server id of the new server. If absent,
238     *                           will be assigned a guid.
239     *
240     * @return mixed The newly created object, or null if there was an error
241     *
242     * @see GenericObject
243     *
244     * @static
245     * @access public
246     */
[1269]247    public static function createNewObject($hostname)
[1249]248    {
249         
250        $db = AbstractDb::getObject();
251
[1269]252        if (empty($id)) {
253            $id = get_guid();
[1249]254        }
255
[1269]256        $id = $db->escapeString($id);
257        $hostname = $db->escapeString($hostname);
258        $networkId = Network::getCurrentNetwork()->getId();
259        $sql = "INSERT INTO virtual_hosts (virtual_host_id, hostname, default_network) VALUES ('$id', '$hostname', '$networkId')";
[1249]260
261        if (!$db->execSqlUpdate($sql, false)) {
262            throw new Exception(_('Unable to insert the new server in the database!'));
263        }
264
[1269]265        $_object = self::getObject($id);
[1249]266
267        return $_object;
268
269    }
270
271    /**
272     * Get an interface to pick a server
273     *
274     * If there is only one server available, no interface is actually shown
275     *
276     * @param string $user_prefix         A identifier provided by the
277     *                                    programmer to recognise it's generated
278     *                                    html form
279     * @param object $pre_selected_server An optional server object. The server
280     *                                    to be pre-selected in the form object
281     * @param string $additional_where    Additional SQL conditions for the
282     *                                    servers to select
283     *
284     * @return string HTML markup
285
286     */
287    public static function getSelectUI($user_prefix, $pre_selected_server = null, $additional_where = null)
288    {
289
290        $db = AbstractDb::getObject();
291
292        // Init values
293        $html = "";
294        $_serverRows = null;
295
296        $name = $user_prefix;
297
298        $html .= _("Virtual host:")." \n";
299
300        if ($pre_selected_server) {
301            $selectedId = $pre_selected_server->getId();
302        } else {
303            $selectedId = null;
304        }
305
306        $additional_where = $db->escapeString($additional_where);
307
308        $sql = "SELECT virtual_host_id, hostname FROM virtual_hosts WHERE 1=1 $additional_where ORDER BY hostname";
309        $db->execSql($sql, $_serverRows, false);
310
311        if ($_serverRows == null) {
312            throw new Exception("Server::getSelectServerUI: Fatal error: No virtual hosts in the database!");
313        }
314
315        $_numberOfServers = count($_serverRows);
316
317        if ($_numberOfServers > 1) {
318            $_i = 0;
319
320            foreach ($_serverRows as $_serverRow) {
321                $_tab[$_i][0] = $_serverRow['virtual_host_id'];
322                $_tab[$_i][1] = $_serverRow['hostname'];
323                $_i ++;
324            }
325
326            $html .= FormSelectGenerator::generateFromArray($_tab, $selectedId, $name, null, false);
327        } else {
328            foreach ($_serverRows as $_serverRow) {
329                $html .= " $_serverRow[hostname] ";
330                $html .= "<input type='hidden' name='$name' value='{$_serverRow['virtual_host_id']}'>";
331            }
332        }
333
334        return $html;
335    }
336
337    /**
338     * Get the selected server object.
339     *
340     * @param string $user_prefix A identifier provided by the programmer to
341     *                            recognise it's generated form
342     *
343     * @return mixed The server object or null
344     *
345     * @static
346     * @access public
347     */
348    public static function processSelectUI($user_prefix)
349    {
350        // Init values
351        $retVal = null;
352
353        $name = "{$user_prefix}";
354
355        if (!empty($_REQUEST[$name])) {
356            $retVal = self::getObject($_REQUEST[$name]);
357        }
358
359        return $retVal;
360    }
361
362    /**
363     * Get an interface to create a new server
364     *
365     * @return string HTML markup
366
367     */
368    public static function getCreateNewObjectUI()
369    {
370        // Init values
371        $html = '';
372
[1269]373        $name = "new_vhost_hostname";
[1249]374
[1269]375        $html .= _("Add a new virtual host for hostname") . ": ";
376        $html .= "<input type='text' size='60' name='{$name}'>";
[1249]377
378        return $html;
379    }
380
381    /**
382     * Process the new object interface.
383     *
384     * Will return the new object if the user has the credentials and the form
385     * was fully filled.
386     *
387     * @return string The server object or null if no new server was created
388
389     */
390    public static function processCreateNewObjectUI()
391    {
392        require_once('classes/User.php');
393        // Init values
394        $retVal = null;
395
[1269]396        $name = "new_vhost_hostname";
[1249]397
398        if (!empty($_REQUEST[$name])) {
[1269]399            $hostname = $_REQUEST[$name];
[1249]400
[1269]401            if ($hostname) {
[1249]402                if (!User::getCurrentUser()->DEPRECATEDisSuperAdmin()) {
403                    throw new Exception(_("Access denied"));
404                }
[1269]405                $retVal = self::createNewObject($hostname);
[1249]406            }
407        }
408        return $retVal;
409    }
410
411    /**
412     * Retrieves the servers's creation date
413     *
414     * @return string Creation date of server
415     *
416     * @access public
417     */
418    public function getCreationDate()
419    {
420        return $this->__row['creation_date'];
421    }
422
423    /**
424     * Get this vhost's default network
425     *
426     * @return object A Network object, NEVER returns null.
427     */
428    public function &getDefaultNetwork()
429    {
430        return Network::getObject($this->__row['default_network']);
431    }
432
433    /**
434     * Set this vhost's default network
435     *
436     * @return bool True on success, false on failure
437     */
438    public function &setDefaultNetwork(Network $network)
439    {
440        $db = AbstractDb::getObject();
441
442        // Init values
443        $retVal = true;
444        if ($network != $this->getDefaultNetwork()) {
445            $value = $db->escapeString($network->getId());
446            $retVal = $db->execSqlUpdate("UPDATE virtual_hosts SET default_network = '{$value}' WHERE virtual_host_id = '{$this->getId()}'", false);
447            $this->refresh();
448        }
449        return $retVal;
450    }
451
452    /**
453     * Retreives the servers's hostname
454     *
455     * @return string Hostname of server
456     */
457    public function getHostname()
458    {
459        return $this->__row['hostname'];
460    }
461
462    /**
463     * Sets the servers's hostname
464     *
465     * @param string $value The new hostname of server
466     *
467     * @return bool True on success, false on failure
468     */
469    public function setHostname($value)
470    {
471         
472        $db = AbstractDb::getObject();
473
474        // Init values
475        $retVal = true;
476
477        if ($value != $this->getHostname()) {
478            $value = $db->escapeString($value);
479            $retVal = $db->execSqlUpdate("UPDATE virtual_hosts SET hostname = '{$value}' WHERE virtual_host_id = '{$this->getId()}'", false);
480            $this->refresh();
481        }
482
483        return $retVal;
484    }
485
486    /**
487     * Is this vhost the server's default?
488     *
489     * @return bool True or false
490     */
491    public function isDefaultVirtualHost()
492    {
493        // Init values
494        $retVal = false;
495
496        if (VirtualHost::getDefaultVirtualHost()->getId() == $this->getId()) {
497            $retVal = true;
498        }
499
500        return $retVal;
501    }
502
503    /**
504     * Does the server serve SSL encryption?
505     *
506     * @return bool True or false
507     */
508    public function isSSLAvailable()
509    {
510        // Init values
511        $retVal = false;
512
513        if ($this->__row['ssl_available'] == 't') {
514            $retVal = true;
515        }
516
517        return $retVal;
518    }
519
520    /**
521     * Set if the server serves SSL encryption
522     *
523     * @param bool $value The new value if the server serves SSL encryption
524     *
525     * @return bool True on success, false on failure
526     */
527    public function setSSLAvailable($value)
528    {
529         
530        $db = AbstractDb::getObject();
531
532        // Init values
533        $retVal = false;
534
535        if ($value != $this->isSSLAvailable()) {
536            if ($value) {
537                $value = "TRUE";
538            } else {
539                $value = "FALSE";
540            }
541
542            $retVal = $db->execSqlUpdate("UPDATE virtual_hosts SET ssl_available = {$value} WHERE virtual_host_id = '{$this->getId()}'", false);
543            $this->refresh();
544        }
545
546        return $retVal;
547    }
548
549    /**
550     * Retreives the servers's Google maps API key
551     *
552     * @return string Google maps API key of server
553     */
554    public function getGoogleAPIKey()
555    {
556        return $this->__row['gmaps_api_key'];
557    }
558
559    /**
560     * Sets the servers's Google maps API key
561     *
562     * @param string $value The new Google maps API key of server
563     *
564     * @return bool True on success, false on failure
565     */
566    public function setGoogleAPIKey($value)
567    {
568         
569        $db = AbstractDb::getObject();
570
571        // Init values
572        $retVal = true;
573
574        if ($value != $this->getGoogleAPIKey()) {
575            $value = $db->escapeString($value);
576            $retVal = $db->execSqlUpdate("UPDATE virtual_hosts SET gmaps_api_key = '{$value}' WHERE virtual_host_id = '{$this->getId()}'", false);
577            $this->refresh();
578        }
579
580        return $retVal;
581    }
582
583    /**
584     * Retreives the admin interface of this object
585     *
586     * @return string The HTML fragment for this interface
587     */
588    public function getAdminUI()
589    {
590        Security::requirePermission(Permission::P('SERVER_PERM_EDIT_ANY_VIRTUAL_HOST'), Server::getServer());
591        // Init values
592        $html = '';
593
594        $html .= "<fieldset class='admin_container ".get_class($this)."'>\n";
595        $html .= "<legend>"._("Virtual hosts management")."</legend>\n";
596        $html .= "<ul class='admin_element_list'>\n";
597
598        // creation_date
599        $name = "server_" . $this->getId() . "_creation_date";
600        $_value = htmlspecialchars($this->getCreationDate(), ENT_QUOTES);
601
602        $html .= "<li class='admin_element_item_container'>\n";
603        $html .= "<div class='admin_element_label'>" . _("Creation date") . ":</div>\n";
604        $html .= "<div class='admin_element_data'>\n";
605        $html .= "$_value\n";
606        $html .= "</div>\n";
607        $html .= "</li>\n";
608
609        // hostname
610        $name = "server_" . $this->getId() . "_hostname";
611        $_value = htmlspecialchars($this->getHostname(), ENT_QUOTES);
612
613        $html .= "<li class='admin_element_item_container'>\n";
614        $html .= "<div class='admin_element_label'>" . _("Hostname") . ":</div>\n";
615        $html .= "<div class='admin_element_data'>\n";
616        $html .= "<input type='text' size='50' value='$_value' name='$name'>\n";
617        $html .= "</div>\n";
618        $html .= "</li>\n";
619
620        //  default_network
621        $html .= "<li class='admin_element_item_container'>\n";
622        $html .= "<div class='admin_element_label'>" . _("Default network for this vhost") . ":</div>\n";
623        $html .= "<div class='admin_element_data'>\n";
624        $name = "vhost_" . $this->getId() . "_default_network";
625        $html .= Network::getSelectUI($name, array('preSelectedObject'=>$this->getDefaultNetwork()));
626        $html .= "</div>\n";
627        $html .= "</li>\n";
628
629        //  is_default_server
630        $name = "vhost_" . $this->getId() . "_is_default_vhost";
631
632        if ($this->isDefaultVirtualHost()) {
633            $_checked = "checked='checked'";
634        } else {
635            $_checked = "";
636        }
637
638        $html .= "<li class='admin_element_item_container'>\n";
639        $html .= "<div class='admin_element_label'>" . _("Make this Virtual Host the server's default?") . ":</div>\n";
640        $html .= "<div class='admin_element_data'>\n";
641        $html .= "<input type='radio' name='$name' $_checked>\n";
642        $html .= "</div>\n";
643        $html .= "</li>\n";
644
645        //  ssl_available
646        $name = "server_" . $this->getId() . "_ssl_available";
647
648        if ($this->isSSLAvailable()) {
649            $_checked = "checked='checked'";
650        } else {
651            $_checked = "";
652        }
653
654        $html .= "<li class='admin_element_item_container'>\n";
655        $html .= "<div class='admin_element_label'>" . _("Use SSL on this server?") . ":</div>\n";
656        $html .= "<div class='admin_element_data'>\n";
657        $html .= "<input type='checkbox' name='$name' $_checked>\n";
658        $html .= "</div>\n";
659        $html .= "</li>\n";
660
661        // gmaps_api_key
662        if (defined('GMAPS_HOTSPOTS_MAP_ENABLED') && GMAPS_HOTSPOTS_MAP_ENABLED == true) {
663            $name = "server_" . $this->getId() . "_gmaps_api_key";
664            $_value = htmlspecialchars($this->getGoogleAPIKey(), ENT_QUOTES);
665
666            $html .= "<li class='admin_element_item_container'>\n";
667            $html .= "<div class='admin_element_label'>" . _("Google public API key") . ":</div>\n";
668            $html .= "<div class='admin_element_data'>\n";
669            $html .= "<input type='text' size='50' value='$_value' name='$name'>\n";
670            $html .= "</div>\n";
671            $html .= "</li>\n";
672        }
673        $html .= "</ul>\n";
674        $html .= "</fieldset>\n";
675        return $html;
676    }
677
678    /**
679     * Process admin interface of this object
680     *
681     * @return void
682     */
683    public function processAdminUI()
684    {
685        require_once('classes/User.php');
686
687Security::requirePermission(Permission::P('SERVER_PERM_EDIT_ANY_VIRTUAL_HOST'), Server::getServer());
688        // hostname
689        $name = "server_" . $this->getId() . "_hostname";
690        $this->setHostname($_REQUEST[$name]);
691
692        //  default_network
693        $name = "vhost_" . $this->getId() . "_default_network";
694        $this->setDefaultNetwork(Network::processSelectUI($name));
695
696        //  is_default_server
697        $name = "vhost_" . $this->getId() . "_is_default_vhost";
698        if (!empty($_REQUEST[$name]) && $_REQUEST[$name] == 'on') {
699            $server=Server::getServer();
700            $server->setDefaultVirtualHost($this);
701        }
702
703        //  ssl_available
704        $name = "server_" . $this->getId() . "_ssl_available";
705        if (!empty($_REQUEST[$name]) && $_REQUEST[$name] == 'on') {
706            $this->setSSLAvailable(true);
707        } else {
708            $this->setSSLAvailable(false);
709        }
710
711        // gmaps_api_key
712        if (defined('GMAPS_HOTSPOTS_MAP_ENABLED') && GMAPS_HOTSPOTS_MAP_ENABLED == true) {
713            $name = "server_" . $this->getId() . "_gmaps_api_key";
714            $this->setGoogleAPIKey($_REQUEST[$name]);
715        }
716    }
717
718    /**
719     * Delete this Object form the it's storage mechanism
720     *
721     * @param string &$errmsg Returns an explanation of the error on failure
722     *
723     * @return bool True on success, false on failure or access denied
724     */
725    public function delete(&$errmsg)
726    {
727        require_once('classes/User.php');
728
729        $db = AbstractDb::getObject();
730
731        // Init values
732        $retVal = false;
733
734        if (!Security::hasPermission(Permission::P('SERVER_PERM_EDIT_ANY_VIRTUAL_HOST'), Server::getServer())) {
735            $errmsg = _('Access denied');
736        } else {
737            if ($this->isDefaultVirtualHost() === true) {
738                $errmsg = _('Cannot delete default virtual host, create another one and select it before removing this one.');
739            } else {
740                $_id = $db->escapeString($this->getId());
741
[1291]742                if (!$db->execSqlUpdate("DELETE FROM virtual_hosts WHERE virtual_host_id='{$_id}'", false)) {
[1249]743                    $errmsg = _('Could not delete server!');
744                } else {
745                    $retVal = true;
746                }
747            }
748        }
749
750        return $retVal;
751    }
752
753    /**
754     * Reloads the object from the database
755     *
756     * Should normally be called after a set operation
757     *
758     * @return void     */
759    protected function refresh()
760    {
761        $this->__construct($this->_id);
762    }
763
764    /** Menu hook function */
765    static public function hookMenu() {
766        $items = array();
767        $server = Server::getServer();
768        if(Security::hasPermission(Permission::P('SERVER_PERM_EDIT_ANY_VIRTUAL_HOST'), $server))
769        {
770            $items[] = array('path' => 'server/virtual_host',
771            'title' => _("Virtual Hosts"),
[1308]772            'url' => BASE_URL_PATH.htmlspecialchars("admin/generic_object_admin.php?object_class=VirtualHost&action=list")
[1249]773                );
774        }
775        return $items;
776    }
777
778}
779
780/*
781 * Local variables:
782 * tab-width: 4
783 * c-basic-offset: 4
784 * c-hanging-comment-ender-p: nil
785 * End:
786 */
Note: See TracBrowser for help on using the browser.