]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiUser.php
var --> public
[SourceForge/phpwiki.git] / lib / WikiUser.php
1 <?php
2
3 // It is anticipated that when userid support is added to phpwiki,
4 // this object will hold much more information (e-mail,
5 // home(wiki)page, etc.) about the user.
6
7 // There seems to be no clean way to "log out" a user when using HTTP
8 // authentication. So we'll hack around this by storing the currently
9 // logged in username and other state information in a cookie.
10
11 // 2002-09-08 11:44:04 rurban
12 // Todo: Fix prefs cookie/session handling:
13 //       _userid and _homepage cookie/session vars still hold the
14 //       serialized string.
15 //       If no homepage, fallback to prefs in cookie as in 1.3.3.
16
17 define('WIKIAUTH_FORBIDDEN', -1); // Completely not allowed.
18 define('WIKIAUTH_ANON', 0);
19 define('WIKIAUTH_BOGO', 1); // any valid WikiWord is enough
20 define('WIKIAUTH_USER', 2); // real auth from a database/file/server.
21
22 define('WIKIAUTH_ADMIN', 10); // Wiki Admin
23 define('WIKIAUTH_UNOBTAINABLE', 100); // Permissions that no user can achieve
24
25 if (!defined('COOKIE_EXPIRATION_DAYS')) define('COOKIE_EXPIRATION_DAYS', 365);
26 if (!defined('COOKIE_DOMAIN')) define('COOKIE_DOMAIN', '/');
27
28 $UserPreferences = array(
29     'userid' => new _UserPreference(''), // really store this also?
30     'passwd' => new _UserPreference(''),
31     'email' => new _UserPreference(''),
32     'emailVerified' => new _UserPreference_bool(),
33     'notifyPages' => new _UserPreference(''),
34     'theme' => new _UserPreference_theme(THEME),
35     'lang' => new _UserPreference_language(DEFAULT_LANGUAGE),
36     'editWidth' => new _UserPreference_int(80, 30, 150),
37     'noLinkIcons' => new _UserPreference_bool(),
38     'editHeight' => new _UserPreference_int(22, 5, 80),
39     'timeOffset' => new _UserPreference_numeric(0, -26, 26),
40     'relativeDates' => new _UserPreference_bool(),
41     'googleLink' => new _UserPreference_bool(), // 1.3.10
42     'doubleClickEdit' => new _UserPreference_bool(), // 1.3.11
43 );
44
45 function WikiUserClassname()
46 {
47     return 'WikiUser';
48 }
49
50 function UpgradeUser($olduser, $user)
51 {
52     if (isa($user, 'WikiUser') and isa($olduser, 'WikiUser')) {
53         // populate the upgraded class with the values from the old object
54         foreach (get_object_vars($olduser) as $k => $v) {
55             $user->$k = $v;
56         }
57         $GLOBALS['request']->_user = $user;
58         return $user;
59     } else {
60         return false;
61     }
62 }
63
64 /**
65  *
66  */
67 class WikiUser
68 {
69     public $_userid = false;
70     public $_level = false;
71     public $_request, $_dbi, $_authdbi, $_homepage;
72     public $_authmethod = '', $_authhow = '';
73
74     /**
75      * Constructor.
76      *
77      * Populates the instance variables and calls $this->_ok()
78      * to ensure that the parameters are valid.
79      * @param mixed   $userid    String of username or WikiUser object.
80      * @param integer $authlevel Authorization level.
81      */
82     function WikiUser(&$request, $userid = false, $authlevel = false)
83     {
84         $this->_request =& $request;
85         $this->_dbi =& $this->_request->getDbh();
86
87         if (isa($userid, 'WikiUser')) {
88             $this->_userid = $userid->_userid;
89             $this->_level = $userid->_level;
90         } else {
91             $this->_userid = $userid;
92             $this->_level = $authlevel;
93         }
94         if (!$this->_ok()) {
95             // Paranoia: if state is at all inconsistent, log out...
96             $this->_userid = false;
97             $this->_level = false;
98             $this->_homepage = false;
99             $this->_authhow .= ' paranoia logout';
100         }
101         if ($this->_userid) {
102             $this->_homepage = $this->_dbi->getPage($this->_userid);
103         }
104     }
105
106     /**
107      * Get the string indicating how the user was authenticated.
108      *
109      * Get the string indicating how the user was authenticated.
110      * Does not seem to be set - jbw
111      * @return string The method of authentication.
112      */
113     function auth_how()
114     {
115         return $this->_authhow;
116     }
117
118     /**
119      * Invariant
120      *
121      * If the WikiUser object has a valid authorization level and the
122      * userid is a string returns true, else false.
123      * @return boolean If valid level and username string true, else false
124      */
125     function _ok()
126     {
127         if ((in_array($this->_level, array(WIKIAUTH_BOGO,
128             WIKIAUTH_USER,
129             WIKIAUTH_ADMIN))
130             &&
131             (is_string($this->_userid)))
132         ) {
133             return true;
134         }
135         return false;
136     }
137
138     function UserName()
139     {
140         return $this->_userid;
141     }
142
143     function getId()
144     {
145         if ($this->_userid)
146             return $this->_userid;
147         if (!empty($this->_request))
148             return $this->_request->get('REMOTE_ADDR');
149         if (empty($this->_request))
150             return Request::get('REMOTE_ADDR');
151         return ($this->isSignedIn()
152             ? $this->_userid
153             : $this->_request->get('REMOTE_ADDR')); // FIXME: globals
154     }
155
156     function getAuthenticatedId()
157     {
158         //assert($this->_request);
159         return ($this->isAuthenticated()
160             ? $this->_userid
161             : $this->_request->get('REMOTE_ADDR')); // FIXME: globals
162     }
163
164     function isSignedIn()
165     {
166         return $this->_level >= WIKIAUTH_BOGO;
167     }
168
169     function isAuthenticated()
170     {
171         return $this->_level >= WIKIAUTH_BOGO;
172     }
173
174     function isAdmin()
175     {
176         return $this->_level == WIKIAUTH_ADMIN;
177     }
178
179     function hasAuthority($require_level)
180     {
181         return $this->_level >= $require_level;
182     }
183
184     function isValidName($userid = false)
185     {
186         if (!$userid)
187             $userid = $this->_userid;
188         return preg_match("/^[\w\.@\-]+$/", $userid) and strlen($userid) < 32;
189     }
190
191     function AuthCheck($postargs)
192     {
193         // Normalize args, and extract.
194         $keys = array('userid', 'passwd', 'require_level', 'login', 'logout',
195             'cancel');
196         foreach ($keys as $key)
197             $args[$key] = isset($postargs[$key]) ? $postargs[$key] : false;
198         extract($args);
199         $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
200
201         if ($logout)
202             return new WikiUser($this->_request); // Log out
203         elseif ($cancel)
204             return false; // User hit cancel button.
205         elseif (!$login && !$userid)
206             return false; // Nothing to do?
207
208         if (!$this->isValidName($userid))
209             return _("Invalid username.");
210
211         $authlevel = $this->_pwcheck($userid, $passwd);
212         if (!$authlevel)
213             return _("Invalid password or userid.");
214         elseif ($authlevel < $require_level)
215             return _("Insufficient permissions.");
216
217         // Successful login.
218         $user = new WikiUser($this->_request, $userid, $authlevel);
219         return $user;
220     }
221
222     function PrintLoginForm(&$request, $args, $fail_message = false,
223                             $separate_page = true)
224     {
225         include_once 'lib/Template.php';
226         // Call update_locale in case the system's default language is not 'en'.
227         // (We have no user pref for lang at this point yet, no one is logged in.)
228         update_locale(DEFAULT_LANGUAGE);
229         $userid = '';
230         $require_level = 0;
231         extract($args); // fixme
232
233         $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
234
235         $pagename = $request->getArg('pagename');
236         $login = new Template('login', $request,
237             compact('pagename', 'userid', 'require_level',
238                 'fail_message', 'pass_required'));
239         if ($separate_page) {
240             $request->discardOutput();
241             $page = $request->getPage($pagename);
242             $revision = $page->getCurrentRevision();
243             return GeneratePage($login, _("Sign In"), $revision);
244         } else {
245             return $login;
246         }
247     }
248
249     /**
250      * Check password.
251      */
252     function _pwcheck($userid, $passwd)
253     {
254         global $WikiNameRegexp;
255
256         if (!empty($userid) && $userid == ADMIN_USER) {
257             // $this->_authmethod = 'pagedata';
258             if (defined('ENCRYPTED_PASSWD') && ENCRYPTED_PASSWD)
259                 if (!empty($passwd)
260                     && crypt($passwd, ADMIN_PASSWD) == ADMIN_PASSWD
261                 )
262                     return WIKIAUTH_ADMIN;
263                 else
264                     return false;
265             if (!empty($passwd)) {
266                 if ($passwd == ADMIN_PASSWD)
267                     return WIKIAUTH_ADMIN;
268                 else {
269                     // maybe we forgot to enable ENCRYPTED_PASSWD?
270                     if (function_exists('crypt')
271                         && crypt($passwd, ADMIN_PASSWD) == ADMIN_PASSWD
272                     ) {
273                         trigger_error(_("You forgot to set ENCRYPTED_PASSWD to true. Please update your config/config.ini"),
274                             E_USER_WARNING);
275                         return WIKIAUTH_ADMIN;
276                     }
277                 }
278             }
279             return false;
280         } // HTTP Authentication
281         elseif (ALLOW_HTTP_AUTH_LOGIN && !empty($PHP_AUTH_USER)) {
282             // if he ignored the password field, because he is already
283             // authenticated try the previously given password.
284             if (empty($passwd))
285                 $passwd = $PHP_AUTH_PW;
286         }
287
288         // WikiDB_User DB/File Authentication from $DBAuthParams
289         // Check if we have the user. If not try other methods.
290         if (ALLOW_USER_LOGIN) { // && !empty($passwd)) {
291             if (!$this->isValidName($userid)) {
292                 trigger_error(_("Invalid username."), E_USER_WARNING);
293                 return false;
294             }
295             $request = $this->_request;
296             // first check if the user is known
297             if ($this->exists($userid)) {
298                 $this->_authmethod = 'pagedata';
299                 return ($this->checkPassword($passwd)) ? WIKIAUTH_USER : false;
300             } else {
301                 // else try others such as LDAP authentication:
302                 if (ALLOW_LDAP_LOGIN && defined(LDAP_AUTH_HOST) && !empty($passwd) && !strstr($userid, '*')) {
303                     if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
304                         $r = @ldap_bind($ldap); // this is an anonymous bind
305                         $st_search = "uid=$userid";
306                         // Need to set the right root search information. see ../index.php
307                         $sr = ldap_search($ldap, LDAP_BASE_DN,
308                             "$st_search");
309                         $info = ldap_get_entries($ldap, $sr); // there may be more hits with this userid. try every
310                         for ($i = 0; $i < $info["count"]; $i++) {
311                             $dn = $info[$i]["dn"];
312                             // The password is still plain text.
313                             if ($r = @ldap_bind($ldap, $dn, $passwd)) {
314                                 // ldap_bind will return TRUE if everything matches
315                                 ldap_close($ldap);
316                                 $this->_authmethod = 'LDAP';
317                                 return WIKIAUTH_USER;
318                             }
319                         }
320                     } else {
321                         trigger_error("Unable to connect to LDAP server "
322                             . LDAP_AUTH_HOST, E_USER_WARNING);
323                     }
324                 }
325                 // imap authentication. added by limako
326                 if (ALLOW_IMAP_LOGIN && !empty($passwd)) {
327                     $mbox = @imap_open("{" . IMAP_AUTH_HOST . "}INBOX",
328                         $userid, $passwd, OP_HALFOPEN);
329                     if ($mbox) {
330                         imap_close($mbox);
331                         $this->_authmethod = 'IMAP';
332                         return WIKIAUTH_USER;
333                     }
334                 }
335             }
336         }
337         if (ALLOW_BOGO_LOGIN
338             && preg_match('/\A' . $WikiNameRegexp . '\z/', $userid)
339         ) {
340             $this->_authmethod = 'BOGO';
341             return WIKIAUTH_BOGO;
342         }
343         return false;
344     }
345
346     // Todo: try our WikiDB backends.
347     function getPreferences()
348     {
349         // Restore saved preferences.
350
351         // I'd rather prefer only to store the UserId in the cookie or
352         // session, and get the preferences from the db or page.
353         if (isset($this->_request)) {
354             if (!($prefs = $this->_request->getCookieVar('WIKI_PREFS2')))
355                 $prefs = $this->_request->getSessionVar('wiki_prefs');
356         }
357
358         //if (!$this->_userid && !empty($GLOBALS['HTTP_COOKIE_VARS']['WIKI_ID'])) {
359         //    $this->_userid = $GLOBALS['HTTP_COOKIE_VARS']['WIKI_ID'];
360         //}
361
362         // before we get his prefs we should check if he is signed in
363         if (USE_PREFS_IN_PAGE && $this->homePage()) { // in page metadata
364             // old array
365             if ($pref = $this->_homepage->get('pref')) {
366                 //trigger_error("pref=".$pref);//debugging
367                 $prefs = unserialize($pref);
368             }
369         }
370         return new UserPreferences($prefs);
371     }
372
373     // No cookies anymore for all prefs, only the userid. PHP creates
374     // a session cookie in memory, which is much more efficient,
375     // but not persistent. Get persistency with a homepage or DB Prefs
376     //
377     // Return the number of changed entries
378     function setPreferences($prefs, $id_only = false)
379     {
380         if (!is_object($prefs)) {
381             $prefs = new UserPreferences($prefs);
382         }
383         // update the session and id
384         $this->_request->setSessionVar('wiki_prefs', $prefs);
385         // $this->_request->setCookieVar('WIKI_PREFS2', $this->_prefs, 365);
386         // simple unpacked cookie
387         if ($this->_userid) setcookie(getCookieName(), $this->_userid, 365, '/');
388
389         // We must ensure that any password is encrypted.
390         // We don't need any plaintext password.
391         if (!$id_only) {
392             if ($this->isSignedIn()) {
393                 if ($this->isAdmin())
394                     $prefs->set('passwd', '');
395                 // already stored in config/config.ini, and it might be
396                 // plaintext! well oh well
397                 if ($homepage = $this->homePage()) {
398                     // check for page revision 0
399                     if (!$this->_dbi->isWikiPage($this->_userid)) {
400                         trigger_error(_("Your home page has not been created yet so your preferences cannot not be saved."),
401                             E_USER_WARNING);
402                     } else {
403                         if ($this->isAdmin() || !$homepage->get('locked')) {
404                             $homepage->set('pref', serialize($prefs->_prefs));
405                             return sizeof($prefs->_prefs);
406                         } else {
407                             // An "empty" page could still be
408                             // intentionally locked by admin to
409                             // prevent its creation.
410                             //
411                             // FIXME: This permission situation should
412                             // probably be handled by the DB backend,
413                             // once the new WikiUser code has been
414                             // implemented.
415                             trigger_error(_("Your home page is locked so your preferences cannot not be saved.")
416                                     . " " . _("Please contact your PhpWiki administrator for assistance."),
417                                 E_USER_WARNING);
418                         }
419                     }
420                 } else {
421                     trigger_error("No homepage for user found. Creating one...",
422                         E_USER_WARNING);
423                     $this->createHomepage($prefs);
424                     //$homepage->set('pref', serialize($prefs->_prefs));
425                     return sizeof($prefs->_prefs);
426                 }
427             } else {
428                 trigger_error("you must be signed in", E_USER_WARNING);
429             }
430         }
431         return 0;
432     }
433
434     // check for homepage with user flag.
435     // can be overriden from the auth backends
436     function exists()
437     {
438         $homepage = $this->homePage();
439         return ($this->_userid && $homepage && $homepage->get('pref'));
440     }
441
442     // doesn't check for existance!!! hmm.
443     // how to store metadata in not existing pages? how about versions?
444     function homePage()
445     {
446         if (!$this->_userid)
447             return false;
448         if (!empty($this->_homepage)) {
449             return $this->_homepage;
450         } else {
451             if (empty($this->_dbi)) {
452                 if (DEBUG) printSimpleTrace(debug_backtrace());
453             } else {
454                 $this->_homepage = $this->_dbi->getPage($this->_userid);
455             }
456             return $this->_homepage;
457         }
458     }
459
460     function hasHomePage()
461     {
462         return !$this->homePage();
463     }
464
465     // create user by checking his homepage
466     function createUser($pref, $createDefaultHomepage = true)
467     {
468         if ($this->exists())
469             return;
470         if ($createDefaultHomepage) {
471             $this->createHomepage($pref);
472         } else {
473             // empty page
474             include 'lib/loadsave.php';
475             $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)),
476                 'versiondata' => array('author' => $this->_userid),
477                 'pagename' => $this->_userid,
478                 'content' => _('CategoryHomepage'));
479             SavePage($this->_request, $pageinfo, false, false);
480         }
481         $this->setPreferences($pref);
482     }
483
484     // create user and default user homepage
485     function createHomepage($pref)
486     {
487         $pagename = $this->_userid;
488         include 'lib/loadsave.php';
489
490         // create default homepage:
491         //  properly expanded template and the pref metadata
492         $template = Template('homepage.tmpl', $this->_request);
493         $text = $template->getExpansion();
494         $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)),
495             'versiondata' => array('author' => $this->_userid),
496             'pagename' => $pagename,
497             'content' => $text);
498         SavePage($this->_request, $pageinfo, false, false);
499
500         // create Calendar
501         $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Calendar');
502         if (!isWikiPage($pagename)) {
503             $pageinfo = array('pagedata' => array(),
504                 'versiondata' => array('author' => $this->_userid),
505                 'pagename' => $pagename,
506                 'content' => "<?plugin Calendar ?>\n");
507             SavePage($this->_request, $pageinfo, false, false);
508         }
509
510         // create Preferences
511         $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Preferences');
512         if (!isWikiPage($pagename)) {
513             $pageinfo = array('pagedata' => array(),
514                 'versiondata' => array('author' => $this->_userid),
515                 'pagename' => $pagename,
516                 'content' => "<?plugin UserPreferences ?>\n");
517             SavePage($this->_request, $pageinfo, false, false);
518         }
519     }
520
521     function tryAuthBackends()
522     {
523         return ''; // crypt('') will never be ''
524     }
525
526     // Auth backends must store the crypted password where?
527     // Not in the preferences.
528     function checkPassword($passwd)
529     {
530         $prefs = $this->getPreferences();
531         $stored_passwd = $prefs->get('passwd'); // crypted
532         if (empty($prefs->_prefs['passwd'])) // not stored in the page
533             // allow empty passwords? At least store a '*' then.
534             // try other backend. hmm.
535             $stored_passwd = $this->tryAuthBackends($this->_userid);
536         if (empty($stored_passwd)) {
537             trigger_error(sprintf(_("Old UserPage %s without stored password updated with empty password. Set a password in your UserPreferences."),
538                 $this->_userid), E_USER_NOTICE);
539             $prefs->set('passwd', '*');
540             return true;
541         }
542         if ($stored_passwd == '*')
543             return true;
544         if (!empty($passwd)
545             && crypt($passwd, $stored_passwd) == $stored_passwd
546         )
547             return true;
548         else
549             return false;
550     }
551
552     function changePassword($newpasswd, $passwd2 = false)
553     {
554         if (!$this->mayChangePass()) {
555             trigger_error(sprintf("Attempt to change an external password for “%s”. Not allowed!",
556                 $this->_userid), E_USER_ERROR);
557             return false;
558         }
559         if ($passwd2 && $passwd2 != $newpasswd) {
560             trigger_error("The second password must be the same as the first to change it",
561                 E_USER_ERROR);
562             return false;
563         }
564         if (!$this->isAuthenticated()) return false;
565
566         $prefs = $this->getPreferences();
567         if (ENCRYPTED_PASSWD)
568             $prefs->set('passwd', crypt($newpasswd));
569         else
570             $prefs->set('passwd', $newpasswd);
571         $this->setPreferences($prefs);
572         return true;
573     }
574
575     function mayChangePass()
576     {
577         // on external DBAuth maybe. on IMAP or LDAP not
578         // on internal DBAuth yes
579         if (in_array($this->_authmethod, array('IMAP', 'LDAP')))
580             return false;
581         if ($this->isAdmin())
582             return false;
583         if ($this->_authmethod == 'pagedata')
584             return true;
585         if ($this->_authmethod == 'authdb')
586             return true;
587     }
588 }
589
590 // create user and default user homepage
591 // FIXME: delete this, not used?
592 /*
593 function createUser ($userid, $pref) {
594     global $request;
595     $user = new WikiUser ($request, $userid);
596     $user->createUser($pref);
597 }
598 */
599
600 class _UserPreference
601 {
602     function _UserPreference($default_value)
603     {
604         $this->default_value = $default_value;
605     }
606
607     function sanify($value)
608     {
609         return (string)$value;
610     }
611
612     function update($value)
613     {
614     }
615 }
616
617 class _UserPreference_numeric
618     extends _UserPreference
619 {
620     function _UserPreference_numeric($default, $minval = false,
621                                      $maxval = false)
622     {
623         $this->_UserPreference((double)$default);
624         $this->_minval = (double)$minval;
625         $this->_maxval = (double)$maxval;
626     }
627
628     function sanify($value)
629     {
630         $value = (double)$value;
631         if ($this->_minval !== false && $value < $this->_minval)
632             $value = $this->_minval;
633         if ($this->_maxval !== false && $value > $this->_maxval)
634             $value = $this->_maxval;
635         return $value;
636     }
637 }
638
639 class _UserPreference_int
640     extends _UserPreference_numeric
641 {
642     function _UserPreference_int($default, $minval = false, $maxval = false)
643     {
644         $this->_UserPreference_numeric((int)$default, (int)$minval,
645             (int)$maxval);
646     }
647
648     function sanify($value)
649     {
650         return (int)parent::sanify((int)$value);
651     }
652 }
653
654 class _UserPreference_bool
655     extends _UserPreference
656 {
657     function _UserPreference_bool($default = false)
658     {
659         $this->_UserPreference((bool)$default);
660     }
661
662     function sanify($value)
663     {
664         if (is_array($value)) {
665             /* This allows for constructs like:
666              *
667              *   <input type="hidden" name="pref[boolPref][]" value="0" />
668              *   <input type="checkbox" name="pref[boolPref][]" value="1" />
669              *
670              * (If the checkbox is not checked, only the hidden input
671              * gets sent. If the checkbox is sent, both inputs get
672              * sent.)
673              */
674             foreach ($value as $val) {
675                 if ($val)
676                     return true;
677             }
678             return false;
679         }
680         return (bool)$value;
681     }
682 }
683
684 class _UserPreference_language
685     extends _UserPreference
686 {
687     function _UserPreference_language($default = DEFAULT_LANGUAGE)
688     {
689         $this->_UserPreference($default);
690     }
691
692     // FIXME: check for valid locale
693     function sanify($value)
694     {
695         // Revert to DEFAULT_LANGUAGE if user does not specify
696         // language in UserPreferences or chooses <system language>.
697         if ($value == '' or empty($value))
698             $value = DEFAULT_LANGUAGE;
699
700         return (string)$value;
701     }
702 }
703
704 class _UserPreference_theme
705     extends _UserPreference
706 {
707     function _UserPreference_theme($default = THEME)
708     {
709         $this->_UserPreference($default);
710     }
711
712     function sanify($value)
713     {
714         if (findFile($this->_themefile($value), true))
715             return $value;
716         return $this->default_value;
717     }
718
719     function update($newvalue)
720     {
721         global $WikiTheme;
722         include_once($this->_themefile($newvalue));
723         if (empty($WikiTheme))
724             include_once($this->_themefile(THEME));
725     }
726
727     function _themefile($theme)
728     {
729         return "themes/$theme/themeinfo.php";
730     }
731 }
732
733 // don't save default preferences for efficiency.
734 class UserPreferences
735 {
736     function UserPreferences($saved_prefs = false)
737     {
738         $this->_prefs = array();
739
740         if (isa($saved_prefs, 'UserPreferences') && $saved_prefs->_prefs) {
741             foreach ($saved_prefs->_prefs as $name => $value)
742                 $this->set($name, $value);
743         } elseif (is_array($saved_prefs)) {
744             foreach ($saved_prefs as $name => $value)
745                 $this->set($name, $value);
746         }
747     }
748
749     function _getPref($name)
750     {
751         global $UserPreferences;
752         if (!isset($UserPreferences[$name])) {
753             if ($name == 'passwd2') return false;
754             trigger_error("$name: unknown preference", E_USER_NOTICE);
755             return false;
756         }
757         return $UserPreferences[$name];
758     }
759
760     function get($name)
761     {
762         if (isset($this->_prefs[$name]))
763             return $this->_prefs[$name];
764         if (!($pref = $this->_getPref($name)))
765             return false;
766         return $pref->default_value;
767     }
768
769     function set($name, $value)
770     {
771         if (!($pref = $this->_getPref($name)))
772             return false;
773
774         $newvalue = $pref->sanify($value);
775         $oldvalue = $this->get($name);
776
777         // update on changes
778         if ($newvalue != $oldvalue)
779             $pref->update($newvalue);
780
781         // don't set default values to save space (in cookies, db and
782         // sesssion)
783         if ($value == $pref->default_value)
784             unset($this->_prefs[$name]);
785         else
786             $this->_prefs[$name] = $newvalue;
787     }
788
789     function pack($nonpacked)
790     {
791         return serialize($nonpacked);
792     }
793
794     function unpack($packed)
795     {
796         if (!$packed)
797             return false;
798         if (substr($packed, 0, 2) == "O:") {
799             // Looks like a serialized object
800             return unserialize($packed);
801         }
802         //trigger_error("DEBUG: Can't unpack bad UserPreferences",
803         //E_USER_WARNING);
804         return false;
805     }
806
807     function hash()
808     {
809         return wikihash($this->_prefs);
810     }
811 }
812
813 // Local Variables:
814 // mode: php
815 // tab-width: 8
816 // c-basic-offset: 4
817 // c-hanging-comment-ender-p: nil
818 // indent-tabs-mode: nil
819 // End: