root/wifidogadmin/wifidog/classes/Profile.php

Revision 479, 16.4 kB (checked in by insultant, 10 months ago)

--

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
38  *
39  * @package    WiFiDogAuthServer
40  * @subpackage ContentClasses
41  * @author     François Proulx <francois.proulx@gmail.com>, Benoit Grégoire
42  * @copyright  2007 François Proulx, 2007 Technologies Coeus inc.
43  * @link       http://www.wifidog.org/
44  */
45
46 require_once ('classes/ContentTypeFilter.php');
47 require_once ('classes/ProfileTemplateField.php');
48 require_once ('classes/ProfileTemplate.php');
49 require_once ('classes/ProfileField.php');
50
51 class Profile implements GenericObject {
52     /** Object cache for the object factory (getObject())*/
53     private static $instanceArray = array();
54
55     private $id = null;
56     private $_row;
57
58     private function __construct($profile_id)
59     {
60         $db = AbstractDb::getObject();
61
62         // Init values
63         $row = null;
64
65         $profile_id = $db->escapeString($profile_id);
66         $sql = "SELECT * FROM profiles WHERE profile_id = '{$profile_id}';";
67         $db->execSqlUniqueRes($sql, $row, false);
68
69         if ($row == null) {
70             throw new Exception("The profile with id {$profile_id} could not be found in the database!");
71         }
72
73         $this->_row = $row;
74         $this->id = $db->escapeString($row['profile_id']);
75     }
76
77     /**
78      * Get an instance of the object
79      *
80      * @param string $id The object id
81      *
82      * @return mixed The Profile object, or null if there was an error
83      *               (an exception is also thrown)
84      *
85      * @see GenericObject
86      * @static
87      * @access public
88      */
89     public static function &getObject($id)
90     {
91         if(!isset(self::$instanceArray[$id]))
92         {
93             self::$instanceArray[$id] = new self($id);
94         }
95         return self::$instanceArray[$id];
96     }
97
98     /**
99      * Retreives the Id of the object
100      *
101      * @return string The Id
102      */
103     public function getId()
104     {
105         return $this->id;
106     }
107
108     /**
109      * Retrieves the profile's creation date
110      *
111      * @return string profile's creation date
112      *
113      * @access public
114      */
115     public function getCreationDate()
116     {
117         return $this->_row['creation_date'];
118     }
119
120     /**
121      * Set the profile's creation date
122      *
123      * @param string $value The new creation date
124      *
125      * @return bool True on success, false on failure
126      */
127     public function setCreationDate($value)
128     {
129
130         $db = AbstractDb::getObject();
131
132         // Init values
133         $_retVal = true;
134
135         if ($value != $this->getCreationDate()) {
136             $value = $db->escapeString($value);
137             $_retVal = $db->execSqlUpdate("UPDATE profiles SET creation_date = '{$value}' WHERE profile_id = '{$this->getId()}'", false);
138             $this->refresh();
139         }
140
141         return $_retVal;
142     }
143
144     /**
145      * Retrieves the profile's visibility
146      *
147      * @return boolean
148      *
149      * @access public
150      */
151     public function isVisible()
152     {
153         if($this->_row['is_visible'] == "f")
154         return false;
155         else
156         return true;
157     }
158
159     /**
160      * Set the profile's visibility
161      *
162      * @param boolean $value
163      *
164      * @return bool True on success, false on failure
165      */
166     public function setVisible($value)
167     {
168         $db = AbstractDb::getObject();
169
170         // Init values
171         $_retVal = true;
172
173         if ($value != $this->isVisible()) {
174             if($value == true)
175             $_retVal = $db->execSqlUpdate("UPDATE profiles SET is_visible = true WHERE profile_id = '{$this->getId()}'", false);
176             else
177             $_retVal = $db->execSqlUpdate("UPDATE profiles SET is_visible = false WHERE profile_id = '{$this->getId()}'", false);
178             $this->refresh();
179         }
180
181         return $_retVal;
182     }
183
184     /* Create a new Profile object in the database
185      * @param string $profile_id the id of the new profile object
186      * @param string $profile_template
187      *
188      * @return mixed The newly created object, or null if there was an error
189      *
190      * @see GenericObject
191      *
192      * @static
193      * @access public
194      */
195     public static function createNewObject($profile_id = null, $profile_template = null)
196     {
197         if(!empty($profile_template) && get_class($profile_template) == "ProfileTemplate") {
198             $db = AbstractDb::getObject();
199             if (empty ($profile_id)) {
200                 $profile_id = get_guid();
201             }
202             
203             $profile_template_id = $profile_template->getId();
204             $sql = "INSERT INTO profiles (profile_id, profile_template_id, creation_date) VALUES ('{$profile_id}', '{$profile_template_id}', NOW());\n";
205             if (!$db->execSqlUpdate($sql, false)) {
206                 throw new Exception(_('Unable to insert the new profile in the database!'));
207             }
208             
209             $object = self::getObject($profile_id);
210             return $object;
211         } else
212         throw new Exception("You must provide a profile template object");
213     }
214
215     public static function getCreateNewObjectUI() {}
216     public static function processCreateNewObjectUI() {}
217
218     /**
219      * Retrieves the associated profile template
220      *
221      * @return ProfileTemplate object
222      *
223      * @access public
224      */
225     public function getTemplate()
226     {
227         $retval = ProfileTemplate :: getObject($this->_row['profile_template_id']);
228         return $retval;
229     }
230
231     /** Get all fields matching the given semantic ID
232      * @return an array of Content (realized ProfileTemplateField) or an empty arrray */
233     public function getFieldsBySemanticId($semantic_id)
234     {
235         $db = AbstractDb :: getObject();
236         // Init values
237         $retval = array ();
238         $field_rows = null;
239
240         $semantic_id = $db->escapeString($semantic_id);
241         $sql = "SELECT profile_field_id FROM profile_fields NATURAL JOIN profile_template_fields WHERE profile_id = '{$this->getId()}' AND semantic_id = '{$semantic_id}';";
242         $db->execSql($sql, $field_rows, false);
243         if ($field_rows != null) {
244             foreach ($field_rows as $field_row) {
245                 $retval[] = ProfileField :: getObject($field_row['profile_field_id']);
246             }
247         }
248
249         return $retval;
250     }
251
252     /** Get all fields
253      * @return an array of ProfileField (realized ProfileTemplateField) or an empty array.
254      * The array id is the template field used for the ProfileField */
255     function getFields()
256     {
257         $db = AbstractDb :: getObject();
258         // Init values
259         $retval = array ();
260         $field_rows = null;
261         $sql = "SELECT profile_field_id, profile_template_field_id FROM profile_fields NATURAL JOIN profile_template_fields WHERE profile_id = '{$this->getId()}' ORDER BY display_order";
262         $db->execSql($sql, $field_rows, false);
263         if ($field_rows != null) {
264             foreach ($field_rows as $field_row) {
265                 $retval[$field_row['profile_template_field_id']] = ProfileField :: getObject($field_row['profile_field_id']);
266             }
267         }
268
269         return $retval;
270     }
271
272     /** This method will remove a field by semantic ID from the array of ProfileFields passed as parameter,
273      * and return the poped field (or null)
274      * @param $id Semantic ID that is looked for
275      * @param $fields Array of ProfileFields, passed by reference
276      * @return a ProfileField object or null.
277      * The array id is the template field used for the ProfileField */
278     static public function popFieldBySemanticId($id, &$fields)
279     {
280         $db = AbstractDb :: getObject();
281             foreach ($fields as $key => $field) {
282                 $candidateId = $field->getProfileTemplateField()->getSemanticId();
283                 //echo "candidateId: $candidateId, id: $id<br/>\n";
284                 if($candidateId==$id){
285                     unset($fields[$key]);
286                     //pretty_print_r($field);
287                     return $field;
288                 }
289             }
290         return null;
291     }
292     /**
293      * Retreives the admin interface of this object
294      *
295      * @return string The HTML fragment for this interface
296      */
297     public function getAdminUI()
298     {
299         // Init values
300         $html = '';
301
302         // All sections
303         $profileSections = array();
304
305         // Metadata section
306         $profileMetadataItems = array();
307
308         //  is_visible
309         $title = _("Should this profile be publicly visible?");
310         $name = "profile_" . $this->getId() . "_is_visible";
311         $data = InterfaceElements::generateInputCheckbox($name, "", _("Yes"), $this->isVisible(), "profile_is_visible_radio");
312         $profileMetadataItems[] = InterfaceElements::genSectionItem($data, $title);
313
314         $profileSections[] = InterfaceElements::genSection($profileMetadataItems, _("Profile preferences"));
315
316         // Fields section
317         $profileFieldsUI = array();
318
319         $template = $this->getTemplate();
320         // Aggregate the fields UI
321         $profileFields = $this->getFields();
322         foreach ($template->getFields() as $templateField) {
323             if(!empty($profileFields[$templateField->getId()])) {
324                 //We already have a real field instanciated
325                 $field=$profileFields[$templateField->getId()];
326                 $profileFieldsUI[] = InterfaceElements::genSectionItem($field->getAdminUI());
327             }
328             else {
329                 //show the template admin UI
330                 //$profileFieldsUI[] = InterfaceElements::genSectionItem($templateField->getUserUI());
331
332                 // Init values
333                 $tmp_html = '';
334                 $admin_label = $templateField->getAdminLabelContent();
335                 if($admin_label != null) {
336                     $title = $admin_label->__toString();
337                 }
338                 else {
339                     $title = null;
340                 }
341                 $tmp_html .= "<fieldset class='admin_container " . get_class($this) . "'>\n";
342                 if (!empty ($title)) {
343                     $tmp_html .= "<legend>$title</legend>\n";
344                 }
345                 $futureProfileFieldId = get_guid();
346                 $name = "profile_template_field_{$templateField->getId()}_field_future_id";
347                 $tmp_html .= '<input type="hidden" name="' . $name . '" value="' . $futureProfileFieldId . '">';
348                 $userData['contentTypeFilter'] = $templateField->getContentTypeFilter();
349                 //echo "Profile::getAdminUI: userData";pretty_print_r($userData);
350                 $tmp_html .= ProfileField :: getNewUI($futureProfileFieldId, $userData);
351                 $tmp_html .= "</fieldset>\n";
352                 $profileFieldsUI[] = $tmp_html;
353             }
354         }
355         $profileSections[] = InterfaceElements::genSection($profileFieldsUI, _("Profile fields"));
356
357         $html .= InterfaceElements::genSection($profileSections, _("Profile"), false, false, get_class($this));
358
359         return $html;
360     }
361
362     /**
363      * Process admin interface of this object
364      *
365      * @return void
366      */
367     public function processAdminUI()
368     {
369         //  is_visible
370         $name = "profile_" . $this->getId() . "_is_visible";
371         if (!empty ($_REQUEST[$name]) && $_REQUEST[$name] == 'on')
372         $this->setVisible(true);
373         else
374         $this->setVisible(false);
375
376         $template = $this->getTemplate();
377         // Aggregate the fields UI
378         $profileFields = $this->getFields();
379         foreach ($template->getFields() as $templateField) {
380             if(!empty($profileFields[$templateField->getId()])) {
381                 //We already have a real field instanciated
382                 $field=$profileFields[$templateField->getId()];
383                 $field->processAdminUI();
384             }
385             else {
386                 //Create a new fielreate a new field (if appropriate)
387                 $name = "profile_template_field_{$templateField->getId()}_field_future_id";
388                 $futureProfileFieldId = $_REQUEST[$name];
389                 if(ProfileField :: processNewUI($futureProfileFieldId, true)==true)
390                 {
391                     ProfileField::createNewObject($this, $templateField, $futureProfileFieldId);
392                     ProfileField::processNewUI($futureProfileFieldId, false);
393                 }
394             }
395         }
396     }
397
398     public function getUserUI()
399     {
400         $html = "";
401         $html .= "<div class='Profile'>\n";
402         if($this->isVisible()) {
403             $fields = $this->getFields();
404             $field = self::popFieldBySemanticId('foaf:img', $fields);
405             if($field){
406                 $html .= $field->getUserUI();
407             }
408             $field = self::popFieldBySemanticId('foaf:nick', $fields);
409             if($field){
410                 $html .= $field->getUserUI();
411             }
412             $field = self::popFieldBySemanticId('foaf:name', $fields);
413             if($field){
414                 $html .= $field->getUserUI();
415             }
416             $html .= "<br class='clearbr' />";
417             //Print all the other fields
418             foreach ($fields as $field) {
419                 $html .= $field->getUserUI();
420             }
421         }
422         else {
423             $html .= "<h1>"._("Sorry, this user has hidden his profile  temporarily.")."</h1>\n";
424         }
425         $html .= "</div>\n";
426
427         return $html;
428     }
429     /**
430      * Delete this Object form the it's storage mechanism
431      *
432      * @param string &$errmsg Returns an explanation of the error on failure
433      *
434      * @return bool True on success, false on failure or access denied
435      */
436     public function delete(&$errmsg)
437     {
438         require_once('classes/User.php');
439
440         $db = AbstractDb::getObject();
441
442         // Init values
443         $_retVal = false;
444
445         if (!User::getCurrentUser()->DEPRECATEDisSuperAdmin()) {
446             $errmsg = _('Access denied (must have super admin access)');
447         } else {
448             $_id = $db->escapeString($this->getId());
449
450             if (!$db->execSqlUpdate("DELETE FROM profiles WHERE profile_id = '{$_id}'", false)) {
451                 $errmsg = _('Could not delete Profile!');
452             } else {
453                 $_retVal = true;
454             }
455         }
456
457         return $_retVal;
458     }
459
460
461     /**
462      * Reloads the object from the database
463      *
464      * Should normally be called after a set operation
465      *
466      * @return void     */
467     protected function refresh()
468     {
469         $this->__construct($this->getId());
470     }
471
472 } //end class
473 /*
474  * Local variables:
475  * tab-width: 4
476  * c-basic-offset: 4
477  * c-hanging-comment-ender-p: nil
478  * End:
479  */
Note: See TracBrowser for help on using the browser.