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