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