root/trunk/wifidog-auth/wifidog/classes/ProfileTemplate.php @ 1174

Revision 1174, 20.7 KB (checked in by fproulx, 6 years ago)

2007-01-16 François Proulx <francois.proulx@…>

  • ContentTypeFilter? : Now supports filters stored in the DB, backward compatible
  • ProfileTemplate?, ProfileTemplateField?, Profile : profiles support
  • Update schema to 53 for profiles
  • Network, User : Added support for profiles (not implemented for Network)
  • TODO: Integration in portal
  • Property svn:executable set to *
Line 
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 * Defines a profile template
38 *
39 * @package    WiFiDogAuthServer
40 * @subpackage ContentClasses
41 * @author     François Proulx <francois.proulx@gmail.com>
42 * @copyright  2007 François Proulx
43 * @link       http://www.wifidog.org/
44 */
45 
46require_once ('classes/ProfileTemplateField.php');
47require_once ('classes/ContentTypeFilter.php');
48
49class ProfileTemplate implements GenericObject {
50        /** Object cache for the object factory (getObject())*/
51    private static $instanceArray = array();
52   
53    private $id = null;
54    private $mRow;
55   
56    private function __construct($profile_template_id)
57        {
58                $db = AbstractDb::getObject();
59
60                // Init values
61                $row = null;
62
63                $profile_template_id = $db->escapeString($profile_template_id);
64                $sql = "SELECT * FROM profile_templates WHERE profile_template_id = '{$profile_template_id}';";
65                $db->execSqlUniqueRes($sql, $row, false);
66
67                if ($row == null) {
68                        throw new Exception("The profile template with id {$profile_template_id} could not be found in the database!");
69                }
70
71                $this->mRow = $row;
72                $this->id = $db->escapeString($row['profile_template_id']);
73        }
74
75    /**
76     * Get an instance of the object
77     *
78     * @param string $id The object id
79     *
80     * @return mixed The Content object, or null if there was an error
81     *               (an exception is also thrown)
82     *
83     * @see GenericObject
84     * @static
85     * @access public
86     */
87    public static function getObject($id)
88    {
89        if(!isset(self::$instanceArray[$id]))
90        {
91                self::$instanceArray[$id] = new self($id);
92        }
93        return self::$instanceArray[$id];
94    }
95   
96   
97    /**
98     * Get all profile templates ( can be restricted to a network )
99     * @param $network_id
100     */
101    public static function getAllProfileTemplates($network = null) {
102        $db = AbstractDb :: getObject();
103
104        // Init values
105        $whereClause = "";
106        $rows = null;
107        $objects = array ();
108
109        if (!empty ($network) && get_class($network) == "Network") {
110                $db->execSql("SELECT profile_template_id FROM network_has_profile_templates WHERE network_id = '{$network->getId()}'", $rows, false);
111        } else {
112                $db->execSql("SELECT profile_template_id FROM profile_templates", $rows, false);
113        }
114
115        if ($rows) {
116                foreach ($rows as $row) {
117                        $objects[] = self :: getObject($row['profile_template_id']);
118                }
119        }
120
121        return $objects;
122    }
123   
124    /**
125     * Retreives the Id of the object
126     *
127     * @return string The Id
128     */
129        public function getId()
130        {
131                return $this->id;
132        }
133       
134        /**
135     * Retrieves the profile template's label
136     *
137     * @return string profile template's label
138     *
139     * @access public
140     */
141    public function getLabel()
142    {
143        return $this->mRow['profile_template_label'];
144    }
145
146    /**
147     * Set the profile template's label
148     *
149     * @param string $value The new label
150     *
151     * @return bool True on success, false on failure
152     */
153    public function setLabel($value)
154    {
155       
156        $db = AbstractDb::getObject();
157
158        // Init values
159        $_retVal = true;
160
161        if ($value != $this->getLabel()) {
162            $value = $db->escapeString($value);
163            $_retVal = $db->execSqlUpdate("UPDATE profile_templates SET profile_template_label = '{$value}' WHERE profile_template_id = '{$this->getId()}'", false);
164            $this->refresh();
165        }
166
167        return $_retVal;
168    }
169       
170    /**
171     * Retrieves the profile template's creation date
172     *
173     * @return string profile template's creation date
174     *
175     * @access public
176     */
177    public function getCreationDate()
178    {
179        return $this->mRow['creation_date'];
180    }
181
182    /**
183     * Set the profile template's creation date
184     *
185     * @param string $value The new creation date
186     *
187     * @return bool True on success, false on failure
188     */
189    public function setCreationDate($value)
190    {
191       
192        $db = AbstractDb::getObject();
193
194        // Init values
195        $_retVal = true;
196
197        if ($value != $this->getCreationDate()) {
198            $value = $db->escapeString($value);
199            $_retVal = $db->execSqlUpdate("UPDATE profile_templates SET creation_date = '{$value}' WHERE profile_template_id = '{$this->getId()}'", false);
200            $this->refresh();
201        }
202
203        return $_retVal;
204    }
205   
206    /* Create a new ProfileTemplate object in the database
207         *
208         * @param string $profile_template_id The id of the new object. If absent,
209         * will be assigned a guid.
210         *
211         * @return mixed The newly created object, or null if there was an error
212         *
213         * @see GenericObject
214         *
215         * @static
216         * @access public
217         */
218        public static function createNewObject($profile_template_id = null)
219    {
220        $db = AbstractDb::getObject();
221        if (empty ($profile_template_id)) {
222            $profile_template_id = get_guid();
223        }
224        $profile_template_id = $db->escapeString($profile_template_id);
225
226        $sql = "INSERT INTO profile_templates (profile_template_id, creation_date) VALUES ('{$profile_template_id}', NOW())";
227
228        if (!$db->execSqlUpdate($sql, false)) {
229            throw new Exception(_('Unable to insert the new profile template in the database!'));
230        }
231        $object = self::getObject($profile_template_id);
232        return $object;
233    }
234       
235        /* Get an interface to create a new ProfileTemplate
236     * @return string HTML markup
237     */
238        public static function getCreateNewObjectUI() {}
239       
240       
241    /**
242     * Process the new object interface.
243     *
244     * Will return the new object if the user has the credentials and the form
245     * was fully filled.
246     *
247     * @return string The ProfileTemplate object or null if no new ProfileTemplate was created
248
249     */
250        public static function processCreateNewObjectUI() {}
251       
252        /**
253         * Get an interface to pick a ContentTypeFilter
254         *
255         * If there is only one server available, no interface is actually shown
256         *
257     * @param string $user_prefix         A identifier provided by the
258     *                                    programmer to recognise it's generated
259     *                                    html form
260     * @param object $pre_content_type_filter An optional ContenTypeFilter object
261     *
262     * @param string $additional_where    Additional SQL conditions for the
263     *                                    servers to select
264     *
265     * @return string HTML markup
266
267     */
268    public static function getSelectProfileTemplateUI($user_prefix, $pre_selected_profile_template = null, $additional_where = null, $type_interface = "select")
269    { 
270                $db = AbstractDb::getObject();
271
272        // Init values
273                $_html = "";
274                $_profile_template_rows = null;
275               
276                if ($pre_selected_profile_template) {
277                        $_selectedId = $pre_selected_profile_template->getId();
278                } else {
279                        $_selectedId = null;
280                }
281
282                $_sql = "SELECT * FROM profile_templates WHERE 1=1 $additional_where ORDER BY profile_template_label ASC";
283                $db->execSql($_sql, $_profile_template_rows, false);
284
285                if ($_profile_template_rows != null) {
286                        $_name = $user_prefix;
287
288                        $_html .= _("Profile template").": \n";
289       
290                        $_i = 0;
291                        foreach ($_profile_template_rows as $_profile_template_row) {
292                                $_tab[$_i][0] = $_profile_template_row['profile_template_id'];
293                                $_tab[$_i][1] = empty($_profile_template_row['profile_template_label']) ? "["._("No label")."] - ".$_profile_template_row['profile_template_id'] : $_profile_template_row['profile_template_label'];
294                                $_i ++;
295                        }
296
297                        $_html .= FormSelectGenerator::generateFromArray($_tab, $_selectedId, $_name, null, false);
298                       
299                        if ($type_interface == "add") {
300                        if (isset ($_tab)) {
301                                $name = "{$user_prefix}_add";
302                                $value = _("Add");
303                                $_html .= "<div class='admin_element_tools'>";
304                                $_html .= '<input type="submit" class="submit" name="' . $name . '" value="' . $value . '">';
305                                $_html .= "</div>";
306                        }
307                }
308                }
309               
310                return $_html;
311        }
312       
313       
314    /** Get the selected ProfileTemplate object.
315     * @param $user_prefix A identifier provided by the programmer to recognise it's generated form
316     * @return the ProfileTemplate object
317     */
318    static function processSelectProfileTemplateUI($user_prefix) {
319        $name = "{$user_prefix}";
320        if (!empty ($_REQUEST[$name]))
321                return ProfileTemplate :: getObject($_REQUEST[$name]);
322        else
323                return null;
324    }
325       
326        /**
327     * Get a flexible interface to manage a profile template linked to a node, a network
328     * or anything else
329     *
330     * @param string $user_prefix            A identifier provided by the
331     *                                       programmer to recognise it's
332     *                                       generated HTML form
333     * @param string $link_table             Table to link from
334     * @param string $link_table_obj_key_col Column in linked table to match
335     * @param string $link_table_obj_key     Key to be found in linked table
336     * @param string $default_display_page
337     * @param string $default_display_area
338     * @return string HTML markup
339   
340     */
341    public static function getLinkedProfileTemplateUI($user_prefix, $link_table, $link_table_obj_key_col, $link_table_obj_key) {
342
343        $db = AbstractDb :: getObject();
344
345        // Init values
346        $html = "";
347
348        $link_table = $db->escapeString($link_table);
349        $link_table_obj_key_col = $db->escapeString($link_table_obj_key_col);
350        $link_table_obj_key = $db->escapeString($link_table_obj_key);
351
352        /* Profile templates already linked */
353        $current_profile_templates_sql = "SELECT * FROM $link_table WHERE $link_table_obj_key_col = '$link_table_obj_key'";
354        $rows = null;
355        $db->execSql($current_profile_templates_sql, $rows, false);
356
357        $html .= "<table class='content_management_tools'>\n";
358        $html .= "<th>" . _('Profile template label') . '</th><th>' . _('Actions') . '</th>' . "\n";
359        if ($rows)
360        foreach ($rows as $row) {
361                $profile_template = self :: getObject($row['profile_template_id']);
362                $html .= "<tr class='already_linked_content'>\n";
363                $html .= "<td>\n";
364                $html .= $profile_template->getLabel();
365                $html .= "</td>\n";
366                $html .= "<td>\n";
367                $name = "{$user_prefix}_" . $profile_template->GetId() . "_edit";
368                $html .= "<input type='button' class='submit' name='$name' value='" . _("Edit") . "' onClick='window.open(\"" . GENERIC_OBJECT_ADMIN_ABS_HREF . "?object_class=ProfileTemplate&action=edit&object_id=" . $profile_template->GetId() . "\");'>\n";
369                $name = "{$user_prefix}_" . $profile_template->GetId() . "_erase";
370                $html .= "<input type='submit' class='submit' name='$name' value='" . _("Remove") . "'>";
371                $html .= "</td>\n";
372                $html .= "</tr>\n";
373        }
374
375        /* Add a profile template */
376        $html .= "<tr class='add_existing_content'>\n";
377        $html .= "<td colspan ='2'>\n";
378        $name = "{$user_prefix}_new_existing";
379        $profileTemplateSelector = self :: getSelectProfileTemplateUI($name, null, "AND profile_template_id NOT IN (SELECT profile_template_id FROM $link_table WHERE $link_table_obj_key_col='$link_table_obj_key')", "add");
380        $html .= $profileTemplateSelector;
381        $html .= "</td>\n";
382        $html .= "</tr>\n";
383
384        $html .= "</table>\n";
385        return $html;
386    }
387   
388    /** Get the selected ProfileTemplate object
389     * @param $user_prefix A identifier provided by the programmer to recognise it's generated form
390     * @return the ProfileTemplate object or null
391     */
392    static function processLinkedProfileTemplateUI($user_prefix, $link_table, $link_table_obj_key_col, $link_table_obj_key) {
393        $db = AbstractDb :: getObject();
394        $link_table = $db->escapeString($link_table);
395        $link_table_obj_key_col = $db->escapeString($link_table_obj_key_col);
396        $link_table_obj_key = $db->escapeString($link_table_obj_key);
397       
398        // Profile templates already linked
399        $current_content_sql = "SELECT * FROM $link_table WHERE $link_table_obj_key_col='$link_table_obj_key'";
400        $rows = null;
401        $db->execSql($current_content_sql, $rows, false);
402        if ($rows)
403        foreach ($rows as $row) {
404                $profile_template = ProfileTemplate :: getObject($row['profile_template_id']);
405                $profile_template_id = $db->escapeString($profile_template->getId());
406                $name = "{$user_prefix}_" . $profile_template->GetId() . "_erase";
407                if (!empty ($_REQUEST[$name])) {
408                        $sql = "DELETE FROM $link_table WHERE $link_table_obj_key_col='$link_table_obj_key' AND profile_template_id = '$profile_template_id';\n";
409                        $db->execSqlUpdate($sql, false);
410                }
411        }
412        // Link an existing profile template
413        $name = "{$user_prefix}_new_existing_add";
414        if (!empty ($_REQUEST[$name])) {
415                $name = "{$user_prefix}_new_existing";
416                $profile_template = ProfileTemplate :: processSelectProfileTemplateUI($name);
417                if ($profile_template) {
418                        $profile_template_id = $db->escapeString($profile_template->getId());
419                        $sql = "INSERT INTO $link_table (profile_template_id, $link_table_obj_key_col) VALUES ('$profile_template_id', '$link_table_obj_key');\n";
420                        $db->execSqlUpdate($sql, false);
421                }
422        }
423    }
424       
425        /**Get all fields
426     * @return an array of ProfileTemplateField or an empty arrray */
427    function getFields($additional_where = null) {
428        $db = AbstractDb :: getObject();
429        // Init values
430        $retval = array ();
431        $field_rows = null;
432
433        $sql = "SELECT profile_template_field_id FROM profile_template_fields WHERE profile_template_id = '{$this->getId()}' $additional_where ORDER BY display_order";
434        $db->execSql($sql, $field_rows, false);
435        if ($field_rows != null) {
436            foreach ($field_rows as $field_row) {
437                $retval[] = ProfileTemplateField :: getObject($field_row['profile_template_field_id']);
438            }
439        }
440        return $retval;
441    }
442       
443    /**
444     * Retreives the admin interface of this object
445     *
446     * @return string The HTML fragment for this interface
447     */
448        public function getAdminUI()
449        {
450            // Init values
451                $_html = '';
452
453                $_html .= "<fieldset class='admin_container ".get_class($this)."'>\n";
454                $_html .= "<legend>"._("Profile template management")."</legend>\n";
455        $_html .= "<ul class='admin_element_list'>\n";
456       
457                // profile_template_id
458                $_value = htmlspecialchars($this->getId(), ENT_QUOTES);
459
460                $_html .= "<li class='admin_element_item_container'>\n";
461                $_html .= "<div class='admin_element_label'>" . _("ProfileTemplate ID") . ":</div>\n";
462                $_html .= "<div class='admin_element_data'>\n";
463                $_html .= $_value;
464                $_html .= "</div>\n";
465                $_html .= "</li>\n";
466
467                // label
468                $_name = "profile_template_" . $this->getId() . "_label";
469                $_value = htmlspecialchars($this->getLabel(), ENT_QUOTES);
470
471                $_html .= "<li class='admin_element_item_container'>\n";
472                $_html .= "<div class='admin_element_label'>" . _("Label") . ":</div>\n";
473                $_html .= "<div class='admin_element_data'>\n";
474                $_html .= "<input type='text' size='50' value='$_value' name='$_name'>\n";
475                $_html .= "</div>\n";
476                $_html .= "</li>\n";
477
478                // creation date
479                $_value = htmlspecialchars($this->getCreationDate(), ENT_QUOTES);
480
481                $_html .= "<li class='admin_element_item_container'>\n";
482                $_html .= "<div class='admin_element_label'>" . _("Creation date") . ":</div>\n";
483                $_html .= "<div class='admin_element_data'>\n";
484                $_html .= $_value;
485                $_html .= "</div>\n";
486                $_html .= "</li>\n";
487
488                // profile template fields
489                $_html .= "<li class='admin_element_item_container'>\n";
490        $_html .= "<fieldset class='admin_element_group'>\n";
491        $_html .= "<legend>"._("Profile template fields")."</legend>\n";
492       
493        $_html .= "<ul class='admin_element_list'>\n";
494        foreach ($this->getFields() as $field) {
495            $_html .= "<li class='admin_element_item_container'>\n";
496            $_html .= $field->getAdminUI(null, sprintf(_("%s %d"), get_class($field), $field->getDisplayOrder()));
497            $_html .= "<div class='admin_element_tools'>\n";
498            $name = "profile_template_" . $this->id . "_field_" . $field->GetId() . "_erase";
499            $_html .= "<input type='submit' class='submit' name='$name' value='" . sprintf(_("Delete %s %d"), get_class($field), $field->getDisplayOrder()) . "'>";
500            $_html .= "</div>\n";
501            $_html .= "</li>\n";
502        }
503        $_html .= "<li class='admin_element_item_container'>\n";
504        $_html .= ProfileTemplateField :: getCreateFieldUI("profile_template_{$this->id}_new_field");
505        $_html .= "</li>\n";
506        $_html .= "</ul>\n";
507        $_html .= "</fieldset>\n";
508        $_html .= "</li>\n";
509       
510        $_html .= "</ul>\n";
511        $_html .= "</fieldset>\n";
512                return $_html;
513        }
514
515    /**
516     * Process admin interface of this object
517     *
518     * @return void
519     */
520        public function processAdminUI()
521        {
522        require_once('classes/User.php');
523
524        try {
525                if (!User::getCurrentUser()->isSuperAdmin()) {
526                        throw new Exception(_('Access denied!'));
527                }
528        } catch (Exception $e) {
529            $ui = MainUI::getObject();
530            $ui->setToolSection('ADMIN');
531            $ui->displayError($e->getMessage(), false);
532            exit;
533        }
534       
535        $errmsg = "";
536       
537                // label
538                $_name = "profile_template_" . $this->getId() . "_label";
539                $this->setLabel($_REQUEST[$_name]);     
540               
541                foreach ($this->getFields() as $field) {
542            $name = "profile_template_" . $this->id . "_field_" . $field->GetId() . "_erase";
543            if (!empty ($_REQUEST[$name]) && $_REQUEST[$name] == true) {
544                $field->delete($errmsg);
545            } else {
546                $field->processAdminUI();
547            }
548        }
549
550        ProfileTemplateField :: processCreateFieldUI("profile_template_{$this->id}_new_field", $this);
551        }
552
553    /**
554     * Delete this Object form the it's storage mechanism
555     *
556     * @param string &$errmsg Returns an explanation of the error on failure
557     *
558     * @return bool True on success, false on failure or access denied
559     */
560        public function delete(&$errmsg)
561        {
562            require_once('classes/User.php');
563       
564                $db = AbstractDb::getObject();
565
566            // Init values
567                $_retVal = false;
568
569                if (!User::getCurrentUser()->isSuperAdmin()) {
570                        $errmsg = _('Access denied (must have super admin access)');
571                } else {
572                        $_id = $db->escapeString($this->getId());
573
574                        if (!$db->execSqlUpdate("DELETE FROM profile_templates WHERE profile_template_id = '{$_id}'", false)) {
575                                $errmsg = _('Could not delete ProfileTemplate!');
576                        } else {
577                                $_retVal = true;
578                        }
579                }
580
581                return $_retVal;
582        }
583       
584       
585    /**
586     * Reloads the object from the database
587     *
588     * Should normally be called after a set operation
589     *
590     * @return void     */
591        protected function refresh()
592        {
593                $this->__construct($this->getId());
594        }
595   
596} //end class
597/*
598 * Local variables:
599 * tab-width: 4
600 * c-basic-offset: 4
601 * c-hanging-comment-ender-p: nil
602 * End:
603 */
Note: See TracBrowser for help on using the browser.