]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiUser.php
Default ENABLE_DOUBLECLICKEDIT = false. Moved to UserPreferences
[SourceForge/phpwiki.git] / lib / WikiUser.php
1 <?php //-*-php-*-
2 rcs_id('$Id: WikiUser.php,v 1.65 2005-06-05 05:38:02 rurban Exp $');
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         return ( $this->isSignedIn()
139                  ? $this->_userid
140                  : $this->_request->get('REMOTE_ADDR') ); // FIXME: globals
141     }
142
143     function getAuthenticatedId() {
144         return ( $this->isAuthenticated()
145                  ? $this->_userid
146                  : $this->_request->get('REMOTE_ADDR') ); // FIXME: globals
147     }
148
149     function isSignedIn () {
150         return $this->_level >= WIKIAUTH_BOGO;
151     }
152
153     function isAuthenticated () {
154         return $this->_level >= WIKIAUTH_BOGO;
155     }
156
157     function isAdmin () {
158         return $this->_level == WIKIAUTH_ADMIN;
159     }
160
161     function hasAuthority ($require_level) {
162         return $this->_level >= $require_level;
163     }
164
165     function isValidName ($userid = false) {
166         if (!$userid)
167             $userid = $this->_userid;
168         return preg_match("/^[\w\.@\-]+$/",$userid) and strlen($userid) < 32;
169     }
170
171     function AuthCheck ($postargs) {
172         // Normalize args, and extract.
173         $keys = array('userid', 'passwd', 'require_level', 'login', 'logout',
174                       'cancel');
175         foreach ($keys as $key)
176             $args[$key] = isset($postargs[$key]) ? $postargs[$key] : false;
177         extract($args);
178         $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
179
180         if ($logout)
181             return new WikiUser($this->_request); // Log out
182         elseif ($cancel)
183             return false;        // User hit cancel button.
184         elseif (!$login && !$userid)
185             return false;       // Nothing to do?
186
187         if (!$this->isValidName($userid))
188             return _("Invalid username.");
189
190         $authlevel = $this->_pwcheck($userid, $passwd);
191         if (!$authlevel)
192             return _("Invalid password or userid.");
193         elseif ($authlevel < $require_level)
194             return _("Insufficient permissions.");
195
196         // Successful login.
197         $user = new WikiUser($this->_request, $userid, $authlevel);
198         return $user;
199     }
200
201     function PrintLoginForm (&$request, $args, $fail_message = false,
202                              $seperate_page = true) {
203         include_once('lib/Template.php');
204         // Call update_locale in case the system's default language is not 'en'.
205         // (We have no user pref for lang at this point yet, no one is logged in.)
206         update_locale(DEFAULT_LANGUAGE);
207         $userid = '';
208         $require_level = 0;
209         extract($args); // fixme
210
211         $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
212
213         $pagename = $request->getArg('pagename');
214         $login = new Template('login', $request,
215                               compact('pagename', 'userid', 'require_level',
216                                       'fail_message', 'pass_required'));
217         if ($seperate_page) {
218             $request->discardOutput();
219             $page = $request->getPage($pagename);
220             $revision = $page->getCurrentRevision();
221             return GeneratePage($login,_("Sign In"),$revision);
222         } else {
223             return $login;
224         }
225     }
226
227     /**
228      * Check password.
229      */
230     function _pwcheck ($userid, $passwd) {
231         global $WikiNameRegexp;
232
233         if (!empty($userid) && $userid == ADMIN_USER) {
234             // $this->_authmethod = 'pagedata';
235             if (defined('ENCRYPTED_PASSWD') && ENCRYPTED_PASSWD)
236                 if ( !empty($passwd)
237                      && crypt($passwd, ADMIN_PASSWD) == ADMIN_PASSWD )
238                     return WIKIAUTH_ADMIN;
239                 else
240                     return false;
241             if (!empty($passwd)) {
242                 if ($passwd == ADMIN_PASSWD)
243                   return WIKIAUTH_ADMIN;
244                 else {
245                     // maybe we forgot to enable ENCRYPTED_PASSWD?
246                     if ( function_exists('crypt')
247                          && crypt($passwd, ADMIN_PASSWD) == ADMIN_PASSWD ) {
248                         trigger_error(_("You forgot to set ENCRYPTED_PASSWD to true. Please update your config/config.ini"),
249                                       E_USER_WARNING);
250                         return WIKIAUTH_ADMIN;
251                     }
252                 }
253             }
254             return false;
255         }
256         // HTTP Authentication
257         elseif (ALLOW_HTTP_AUTH_LOGIN && !empty($PHP_AUTH_USER)) {
258             // if he ignored the password field, because he is already
259             // authenticated try the previously given password.
260             if (empty($passwd))
261                 $passwd = $PHP_AUTH_PW;
262         }
263
264         // WikiDB_User DB/File Authentication from $DBAuthParams
265         // Check if we have the user. If not try other methods.
266         if (ALLOW_USER_LOGIN) { // && !empty($passwd)) {
267             if (!$this->isValidName($userid)) {
268                 trigger_error(_("Invalid username."), E_USER_WARNING);
269                 return false;
270             }
271             $request = $this->_request;
272             // first check if the user is known
273             if ($this->exists($userid)) {
274                 $this->_authmethod = 'pagedata';
275                 return ($this->checkPassword($passwd)) ? WIKIAUTH_USER : false;
276             } else {
277                 // else try others such as LDAP authentication:
278                 if (ALLOW_LDAP_LOGIN && defined(LDAP_AUTH_HOST) && !empty($passwd) && !strstr($userid,'*')) {
279                     if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
280                         $r = @ldap_bind($ldap); // this is an anonymous bind
281                         $st_search = "uid=$userid";
282                         // Need to set the right root search information. see ../index.php
283                         $sr = ldap_search($ldap, LDAP_BASE_DN,
284                                           "$st_search");
285                         $info = ldap_get_entries($ldap, $sr); // there may be more hits with this userid. try every
286                         for ($i = 0; $i < $info["count"]; $i++) {
287                             $dn = $info[$i]["dn"];
288                             // The password is still plain text.
289                             if ($r = @ldap_bind($ldap, $dn, $passwd)) {
290                                 // ldap_bind will return TRUE if everything matches
291                                 ldap_close($ldap);
292                                 $this->_authmethod = 'LDAP';
293                                 return WIKIAUTH_USER;
294                             }
295                         }
296                     } else {
297                         trigger_error("Unable to connect to LDAP server "
298                                       . LDAP_AUTH_HOST, E_USER_WARNING);
299                     }
300                 }
301                 // imap authentication. added by limako
302                 if (ALLOW_IMAP_LOGIN && !empty($passwd)) {
303                     $mbox = @imap_open( "{" . IMAP_AUTH_HOST . "}INBOX",
304                                         $userid, $passwd, OP_HALFOPEN );
305                     if($mbox) {
306                         imap_close($mbox);
307                         $this->_authmethod = 'IMAP';
308                         return WIKIAUTH_USER;
309                     }
310                 }
311             }
312         }
313         if ( ALLOW_BOGO_LOGIN
314              && preg_match('/\A' . $WikiNameRegexp . '\z/', $userid) ) {
315             $this->_authmethod = 'BOGO';
316             return WIKIAUTH_BOGO;
317         }
318         return false;
319     }
320
321     // Todo: try our WikiDB backends.
322     function getPreferences() {
323         // Restore saved preferences.
324
325         // I'd rather prefer only to store the UserId in the cookie or
326         // session, and get the preferences from the db or page.
327         if (!($prefs = $this->_request->getCookieVar('WIKI_PREFS2')))
328             $prefs = $this->_request->getSessionVar('wiki_prefs');
329
330         //if (!$this->_userid && !empty($GLOBALS['HTTP_COOKIE_VARS']['WIKI_ID'])) {
331         //    $this->_userid = $GLOBALS['HTTP_COOKIE_VARS']['WIKI_ID'];
332         //}
333
334         // before we get his prefs we should check if he is signed in
335         if (USE_PREFS_IN_PAGE && $this->homePage()) { // in page metadata
336             // old array
337             if ($pref = $this->_homepage->get('pref')) {
338                 //trigger_error("pref=".$pref);//debugging
339                 $prefs = unserialize($pref);
340             }
341         }
342         return new UserPreferences($prefs);
343     }
344
345     // No cookies anymore for all prefs, only the userid. PHP creates
346     // a session cookie in memory, which is much more efficient, 
347     // but not persistent. Get persistency with a homepage or DB Prefs
348     //
349     // Return the number of changed entries
350     function setPreferences($prefs, $id_only = false) {
351         if (!is_object($prefs)) {
352             $prefs = new UserPreferences($prefs);
353         }
354         // update the session and id
355         $this->_request->setSessionVar('wiki_prefs', $prefs);
356         // $this->_request->setCookieVar('WIKI_PREFS2', $this->_prefs, 365);
357         // simple unpacked cookie
358         if ($this->_userid) setcookie('WIKI_ID', $this->_userid, 365, '/');
359
360         // We must ensure that any password is encrypted.
361         // We don't need any plaintext password.
362         if (! $id_only ) {
363             if ($this->isSignedIn()) {
364                 if ($this->isAdmin())
365                     $prefs->set('passwd', '');
366                 // already stored in config/config.ini, and it might be
367                 // plaintext! well oh well
368                 if ($homepage = $this->homePage()) {
369                     // check for page revision 0
370                     if (! $this->_dbi->isWikiPage($this->_userid)) {
371                         trigger_error(_("Your home page has not been created yet so your preferences cannot not be saved."),
372                                       E_USER_WARNING);
373                     }
374                     else {
375                         if ($this->isAdmin() || !$homepage->get('locked')) {
376                             $homepage->set('pref', serialize($prefs->_prefs));
377                             return sizeof($prefs->_prefs);
378                         }
379                         else {
380                             // An "empty" page could still be
381                             // intentionally locked by admin to
382                             // prevent its creation.
383                             //                            
384                             // FIXME: This permission situation should
385                             // probably be handled by the DB backend,
386                             // once the new WikiUser code has been
387                             // implemented.
388                             trigger_error(_("Your home page is locked so your preferences cannot not be saved.")
389                                           . " " . _("Please contact your PhpWiki administrator for assistance."),
390                                           E_USER_WARNING);
391                         }
392                     }
393                 } else {
394                     trigger_error("No homepage for user found. Creating one...",
395                                   E_USER_WARNING);
396                     $this->createHomepage($prefs);
397                     //$homepage->set('pref', serialize($prefs->_prefs));
398                     return sizeof($prefs->_prefs);
399                 }
400             } else {
401                 trigger_error("you must be signed in", E_USER_WARNING);
402             }
403         }
404         return 0;
405     }
406
407     // check for homepage with user flag.
408     // can be overriden from the auth backends
409     function exists() {
410         $homepage = $this->homePage();
411         return ($this->_userid && $homepage && $homepage->get('pref'));
412     }
413
414     // doesn't check for existance!!! hmm.
415     // how to store metadata in not existing pages? how about versions?
416     function homePage() {
417         if (!$this->_userid)
418             return false;
419         if (!empty($this->_homepage)) {
420             return $this->_homepage;
421         } else {
422             $this->_homepage = $this->_dbi->getPage($this->_userid);
423             return $this->_homepage;
424         }
425     }
426
427     function hasHomePage() {
428         return !$this->homePage();
429     }
430
431     // create user by checking his homepage
432     function createUser ($pref, $createDefaultHomepage = true) {
433         if ($this->exists())
434             return;
435         if ($createDefaultHomepage) {
436             $this->createHomepage($pref);
437         } else {
438             // empty page
439             include "lib/loadsave.php";
440             $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)),
441                               'versiondata' => array('author' => $this->_userid),
442                               'pagename' => $this->_userid,
443                               'content' => _('CategoryHomepage'));
444             SavePage ($this->_request, $pageinfo, false, false);
445         }
446         $this->setPreferences($pref);
447     }
448
449     // create user and default user homepage
450     function createHomepage ($pref) {
451         $pagename = $this->_userid;
452         include "lib/loadsave.php";
453
454         // create default homepage:
455         //  properly expanded template and the pref metadata
456         $template = Template('homepage.tmpl', $this->_request);
457         $text  = $template->getExpansion();
458         $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)),
459                           'versiondata' => array('author' => $this->_userid),
460                           'pagename' => $pagename,
461                           'content' => $text);
462         SavePage ($this->_request, $pageinfo, false, false);
463
464         // create Calender
465         $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Preferences');
466         if (! isWikiPage($pagename)) {
467             $pageinfo = array('pagedata' => array(),
468                               'versiondata' => array('author' => $this->_userid),
469                               'pagename' => $pagename,
470                               'content' => "<?plugin Calender ?>\n");
471             SavePage ($this->_request, $pageinfo, false, false);
472         }
473
474         // create Preferences
475         $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Preferences');
476         if (! isWikiPage($pagename)) {
477             $pageinfo = array('pagedata' => array(),
478                               'versiondata' => array('author' => $this->_userid),
479                               'pagename' => $pagename,
480                               'content' => "<?plugin UserPreferences ?>\n");
481             SavePage ($this->_request, $pageinfo, false, false);
482         }
483     }
484
485     function tryAuthBackends() {
486         return ''; // crypt('') will never be ''
487     }
488
489     // Auth backends must store the crypted password where?
490     // Not in the preferences.
491     function checkPassword($passwd) {
492         $prefs = $this->getPreferences();
493         $stored_passwd = $prefs->get('passwd'); // crypted
494         if (empty($prefs->_prefs['passwd']))    // not stored in the page
495             // allow empty passwords? At least store a '*' then.
496             // try other backend. hmm.
497             $stored_passwd = $this->tryAuthBackends($this->_userid);
498         if (empty($stored_passwd)) {
499             trigger_error(sprintf(_("Old UserPage %s without stored password updated with empty password. Set a password in your UserPreferences."),
500                                   $this->_userid), E_USER_NOTICE);
501             $prefs->set('passwd','*');
502             return true;
503         }
504         if ($stored_passwd == '*')
505             return true;
506         if ( !empty($passwd)
507              && crypt($passwd, $stored_passwd) == $stored_passwd )
508             return true;
509         else
510             return false;
511     }
512
513     function changePassword($newpasswd, $passwd2 = false) {
514         if (! $this->mayChangePass() ) {
515             trigger_error(sprintf("Attempt to change an external password for '%s'. Not allowed!",
516                                   $this->_userid), E_USER_ERROR);
517             return false;
518         }
519         if ($passwd2 && $passwd2 != $newpasswd) {
520             trigger_error("The second password must be the same as the first to change it",
521                           E_USER_ERROR);
522             return false;
523         }
524         if (!$this->isAuthenticated()) return false;
525
526         $prefs = $this->getPreferences();
527         if (ENCRYPTED_PASSWD)
528             $prefs->set('passwd', crypt($newpasswd));
529         else 
530             $prefs->set('passwd', $newpasswd);
531         $this->setPreferences($prefs);
532         return true;
533     }
534
535     function mayChangePass() {
536         // on external DBAuth maybe. on IMAP or LDAP not
537         // on internal DBAuth yes
538         if (in_array($this->_authmethod, array('IMAP', 'LDAP')))
539             return false;
540         if ($this->isAdmin())
541             return false;
542         if ($this->_authmethod == 'pagedata')
543             return true;
544         if ($this->_authmethod == 'authdb')
545             return true;
546     }
547                          }
548
549 // create user and default user homepage
550 // FIXME: delete this, not used?
551 /*
552 function createUser ($userid, $pref) {
553     global $request;
554     $user = new WikiUser ($request, $userid);
555     $user->createUser($pref);
556 }
557 */
558
559 class _UserPreference
560 {
561     function _UserPreference ($default_value) {
562         $this->default_value = $default_value;
563     }
564
565     function sanify ($value) {
566         return (string)$value;
567     }
568
569     function update ($value) {
570     }
571 }
572
573 class _UserPreference_numeric
574 extends _UserPreference
575 {
576     function _UserPreference_numeric ($default, $minval = false,
577                                       $maxval = false) {
578         $this->_UserPreference((double)$default);
579         $this->_minval = (double)$minval;
580         $this->_maxval = (double)$maxval;
581     }
582
583     function sanify ($value) {
584         $value = (double)$value;
585         if ($this->_minval !== false && $value < $this->_minval)
586             $value = $this->_minval;
587         if ($this->_maxval !== false && $value > $this->_maxval)
588             $value = $this->_maxval;
589         return $value;
590     }
591 }
592
593 class _UserPreference_int
594 extends _UserPreference_numeric
595 {
596     function _UserPreference_int ($default, $minval = false, $maxval = false) {
597         $this->_UserPreference_numeric((int)$default, (int)$minval,
598                                        (int)$maxval);
599     }
600
601     function sanify ($value) {
602         return (int)parent::sanify((int)$value);
603     }
604 }
605
606 class _UserPreference_bool
607 extends _UserPreference
608 {
609     function _UserPreference_bool ($default = false) {
610         $this->_UserPreference((bool)$default);
611     }
612
613     function sanify ($value) {
614         if (is_array($value)) {
615             /* This allows for constructs like:
616              *
617              *   <input type="hidden" name="pref[boolPref][]" value="0" />
618              *   <input type="checkbox" name="pref[boolPref][]" value="1" />
619              *
620              * (If the checkbox is not checked, only the hidden input
621              * gets sent. If the checkbox is sent, both inputs get
622              * sent.)
623              */
624             foreach ($value as $val) {
625                 if ($val)
626                     return true;
627             }
628             return false;
629         }
630         return (bool) $value;
631     }
632 }
633
634 class _UserPreference_language
635 extends _UserPreference
636 {
637     function _UserPreference_language ($default = DEFAULT_LANGUAGE) {
638         $this->_UserPreference($default);
639     }
640
641     // FIXME: check for valid locale
642     function sanify ($value) {
643         // Revert to DEFAULT_LANGUAGE if user does not specify
644         // language in UserPreferences or chooses <system language>.
645         if ($value == '' or empty($value))
646             $value = DEFAULT_LANGUAGE;
647
648         return (string) $value;
649     }
650 }
651
652 class _UserPreference_theme
653 extends _UserPreference
654 {
655     function _UserPreference_theme ($default = THEME) {
656         $this->_UserPreference($default);
657     }
658
659     function sanify ($value) {
660         if (findFile($this->_themefile($value), true))
661             return $value;
662         return $this->default_value;
663     }
664
665     function update ($newvalue) {
666         global $WikiTheme;
667         include_once($this->_themefile($newvalue));
668         if (empty($WikiTheme))
669             include_once($this->_themefile(THEME));
670     }
671
672     function _themefile ($theme) {
673         return "themes/$theme/themeinfo.php";
674     }
675 }
676
677 // don't save default preferences for efficiency.
678 class UserPreferences {
679     function UserPreferences ($saved_prefs = false) {
680         $this->_prefs = array();
681
682         if (isa($saved_prefs, 'UserPreferences') && $saved_prefs->_prefs) {
683             foreach ($saved_prefs->_prefs as $name => $value)
684                 $this->set($name, $value);
685         } elseif (is_array($saved_prefs)) {
686             foreach ($saved_prefs as $name => $value)
687                 $this->set($name, $value);
688         }
689     }
690
691     function _getPref ($name) {
692         global $UserPreferences;
693         if (!isset($UserPreferences[$name])) {
694             if ($name == 'passwd2') return false;
695             trigger_error("$name: unknown preference", E_USER_NOTICE);
696             return false;
697         }
698         return $UserPreferences[$name];
699     }
700
701     function get ($name) {
702         if (isset($this->_prefs[$name]))
703             return $this->_prefs[$name];
704         if (!($pref = $this->_getPref($name)))
705             return false;
706         return $pref->default_value;
707     }
708
709     function set ($name, $value) {
710         if (!($pref = $this->_getPref($name)))
711             return false;
712
713         $newvalue = $pref->sanify($value);
714         $oldvalue = $this->get($name);
715
716         // update on changes
717         if ($newvalue != $oldvalue)
718             $pref->update($newvalue);
719
720         // don't set default values to save space (in cookies, db and
721         // sesssion)
722         if ($value == $pref->default_value)
723             unset($this->_prefs[$name]);
724         else
725             $this->_prefs[$name] = $newvalue;
726     }
727
728     function pack ($nonpacked) {
729         return serialize($nonpacked);
730     }
731     function unpack ($packed) {
732         if (!$packed)
733             return false;
734         if (substr($packed,0,2) == "O:") {
735             // Looks like a serialized object
736             return unserialize($packed);
737         }
738         //trigger_error("DEBUG: Can't unpack bad UserPreferences",
739         //E_USER_WARNING);
740         return false;
741     }
742
743     function hash () {
744         return hash($this->_prefs);
745     }
746 }
747
748 // $Log: not supported by cvs2svn $
749 // Revision 1.64  2005/02/08 13:25:50  rurban
750 // encrypt password. fix strict logic.
751 // both bugs reported by Mikhail Vladimirov
752 //
753 // Revision 1.63  2005/01/21 14:07:50  rurban
754 // reformatting
755 //
756 // Revision 1.62  2004/11/21 11:59:16  rurban
757 // remove final \n to be ob_cache independent
758 //
759 // Revision 1.61  2004/10/21 21:02:04  rurban
760 // fix seperate page login
761 //
762 // Revision 1.60  2004/06/15 09:15:52  rurban
763 // IMPORTANT: fixed passwd handling for passwords stored in prefs:
764 //   fix encrypted usage, actually store and retrieve them from db
765 //   fix bogologin with passwd set.
766 // fix php crashes with call-time pass-by-reference (references wrongly used
767 //   in declaration AND call). This affected mainly Apache2 and IIS.
768 //   (Thanks to John Cole to detect this!)
769 //
770 // Revision 1.59  2004/06/14 11:31:36  rurban
771 // renamed global $Theme to $WikiTheme (gforge nameclash)
772 // inherit PageList default options from PageList
773 //   default sortby=pagename
774 // use options in PageList_Selectable (limit, sortby, ...)
775 // added action revert, with button at action=diff
776 // added option regex to WikiAdminSearchReplace
777 //
778 // Revision 1.58  2004/06/04 20:32:53  rurban
779 // Several locale related improvements suggested by Pierrick Meignen
780 // LDAP fix by John Cole
781 // reanable admin check without ENABLE_PAGEPERM in the admin plugins
782 //
783 // Revision 1.57  2004/06/04 12:40:21  rurban
784 // Restrict valid usernames to prevent from attacks against external auth or compromise
785 // possible holes.
786 // Fix various WikiUser old issues with default IMAP,LDAP,POP3 configs. Removed these.
787 // Fxied more warnings
788 //
789 // Revision 1.56  2004/06/03 12:36:03  rurban
790 // fix eval warning on signin
791 //
792 // Revision 1.55  2004/06/03 09:39:51  rurban
793 // fix LDAP injection (wildcard in username) detected by Steve Christey, MITRE
794 //
795 // Revision 1.54  2004/04/29 17:18:19  zorloc
796 // Fixes permission failure issues.  With PagePermissions and Disabled Actions when user did not have permission WIKIAUTH_FORBIDDEN was returned.  In WikiUser this was ok because WIKIAUTH_FORBIDDEN had a value of 11 -- thus no user could perform that action.  But WikiUserNew has a WIKIAUTH_FORBIDDEN value of -1 -- thus a user without sufficent permission to do anything.  The solution is a new high value permission level (WIKIAUTH_UNOBTAINABLE) to be the default level for access failure.
797 //
798 // Revision 1.53  2004/04/10 05:34:35  rurban
799 // sf bug#830912
800 //
801 // Revision 1.52  2004/04/10 02:55:48  rurban
802 // fixed old WikiUser
803 //
804 // Revision 1.51  2004/04/06 20:00:10  rurban
805 // Cleanup of special PageList column types
806 // Added support of plugin and theme specific Pagelist Types
807 // Added support for theme specific UserPreferences
808 // Added session support for ip-based throttling
809 //   sql table schema change: ALTER TABLE session ADD sess_ip CHAR(15);
810 // Enhanced postgres schema
811 // Added DB_Session_dba support
812 //
813 // Revision 1.50  2004/02/26 01:32:03  rurban
814 // fixed session login with old WikiUser object. strangely, the errormask gets corruoted to 1, Pear???
815 //
816 // Revision 1.49  2004/02/15 21:34:37  rurban
817 // PageList enhanced and improved.
818 // fixed new WikiAdmin... plugins
819 // editpage, Theme with exp. htmlarea framework
820 //   (htmlarea yet committed, this is really questionable)
821 // WikiUser... code with better session handling for prefs
822 // enhanced UserPreferences (again)
823 // RecentChanges for show_deleted: how should pages be deleted then?
824 //
825 // Revision 1.48  2004/02/01 09:14:11  rurban
826 // Started with Group_Ldap (not yet ready)
827 // added new _AuthInfo plugin to help in auth problems (warning: may display passwords)
828 // fixed some configurator vars
829 // renamed LDAP_AUTH_SEARCH to LDAP_BASE_DN
830 // changed PHPWIKI_VERSION from 1.3.8a to 1.3.8pre
831 // USE_DB_SESSION defaults to true on SQL
832 // changed GROUP_METHOD definition to string, not constants
833 // changed sample user DBAuthParams from UPDATE to REPLACE to be able to
834 //   create users. (Not to be used with external databases generally, but
835 //   with the default internal user table)
836 //
837 // fixed the IndexAsConfigProblem logic. this was flawed:
838 //   scripts which are the same virtual path defined their own lib/main call
839 //   (hmm, have to test this better, phpwiki.sf.net/demo works again)
840 //
841 // Revision 1.47  2004/01/27 23:23:39  rurban
842 // renamed ->Username => _userid for consistency
843 // renamed mayCheckPassword => mayCheckPass
844 // fixed recursion problem in WikiUserNew
845 // fixed bogo login (but not quite 100% ready yet, password storage)
846 //
847 // Revision 1.46  2004/01/26 09:17:48  rurban
848 // * changed stored pref representation as before.
849 //   the array of objects is 1) bigger and 2)
850 //   less portable. If we would import packed pref
851 //   objects and the object definition was changed, PHP would fail.
852 //   This doesn't happen with an simple array of non-default values.
853 // * use $prefs->retrieve and $prefs->store methods, where retrieve
854 //   understands the interim format of array of objects also.
855 // * simplified $prefs->get() and fixed $prefs->set()
856 // * added $user->_userid and class '_WikiUser' portability functions
857 // * fixed $user object ->_level upgrading, mostly using sessions.
858 //   this fixes yesterdays problems with loosing authorization level.
859 // * fixed WikiUserNew::checkPass to return the _level
860 // * fixed WikiUserNew::isSignedIn
861 // * added explodePageList to class PageList, support sortby arg
862 // * fixed UserPreferences for WikiUserNew
863 // * fixed WikiPlugin for empty defaults array
864 // * UnfoldSubpages: added pagename arg, renamed pages arg,
865 //   removed sort arg, support sortby arg
866 //
867 // Revision 1.45  2003/12/09 20:00:43  carstenklapp
868 // Bugfix: The last BogoUserPrefs-bugfix prevented the admin from saving
869 // prefs into his own homepage, fixed broken logic. Tightened up BogoUser
870 // prefs saving ability by checking for true existance of homepage
871 // (previously a page revision of 0 also counted as valid, again due to
872 // somewhat flawed logic).
873 //
874 // Revision 1.44  2003/12/06 04:56:23  carstenklapp
875 // Security bugfix (minor): Prevent BogoUser~s from saving extraneous
876 // _pref object meta-data within locked pages.
877 //
878 // Previously, BogoUser~s who signed in with a (valid) WikiWord such as
879 // "HomePage" could actually save preferences into that page, even though
880 // it was already locked by the administrator. Thus, any subsequent
881 // WikiLink~s to that page would become prefixed with "that nice little"
882 // UserIcon, as if that page represented a valid user.
883 //
884 // Note that the admin can lock (even) non-existant pages as desired or
885 // necessary (i.e. any DB page whose revision==0), to prevent the
886 // arbitrary BogoUser from saving preference metadata into such a page;
887 // for example, the silly WikiName "@qmgi`Vcft_x|" (that is the
888 // \$examplechars presented in login.tmpl, in case it is not visible here
889 // in the CVS comments).
890 //
891 // http://phpwiki.sourceforge.net/phpwiki/
892 // %C0%F1%ED%E7%E9%E0%D6%E3%E6%F4%DF%F8%FC?action=lock
893 //
894 // To remove the prefs metadata from a page, the admin can use the
895 // EditMetaData plugin, enter pref as the key, leave the value box empty
896 // and then submit the change. For example:
897 //
898 // http://phpwiki.sourceforge.net/phpwiki/
899 // _EditMetaData?page=%C0%F1%ED%E7%E9%E0%D6%E3%E6%F4%DF%F8%FC
900 //
901 // (It seems a rethinking of WikiUserNew.php with its WikiUser and
902 // UserPreferences classes is in order. Ideally the WikiDB would
903 // transparently handle such a situation, perhaps BogoUser~s should
904 // simply be restricted to saving preferences into a cookie until his/her
905 // e-mail address has been verified.)
906 //
907 // Revision 1.43  2003/12/04 19:33:30  carstenklapp
908 // Bugfix: Under certain PhpWiki installations (such as the PhpWiki at
909 // SF), the user was unable to select a theme other than the server's
910 // default. (Use the more robust Theme::findFile instead of PHP's
911 // file_exists function to detect installed themes).
912 //
913 // Revision 1.42  2003/11/30 18:18:13  carstenklapp
914 // Minor code optimization: use include_once instead of require_once
915 // inside functions that might not always called.
916 //
917 // Revision 1.41  2003/11/21 21:32:39  carstenklapp
918 // Bugfix: When DEFAULT_LANGUAGE was not 'en', a user's language prefs
919 // would revert to 'en' when the default <system language> was selected
920 // in UserPreferences and the user saved his preferences. (Check for
921 // empty or blank language pref in sanify function of class
922 // _UserPreference_language and return DEFAULT_LANGUAGE if nothing or
923 // default selected in UserPreferences.)
924 //
925 // Revision 1.40  2003/11/21 16:54:58  carstenklapp
926 // Bugfix: login.tmpl was always displayed in English despite
927 // DEFAULT_LANGUAGE set in index.php. (Added call to
928 // update_locale(DEFAULT_LANGUAGE) before printing login form).
929 //
930 // Revision 1.39  2003/10/28 21:13:46  carstenklapp
931 // Security bug fix for admin password, submitted by Julien Charbon.
932 //
933 // Revision 1.38  2003/09/13 22:25:38  carstenklapp
934 // Hook for new user preference 'noLinkIcons'.
935 //
936 // Revision 1.37  2003/02/22 20:49:55  dairiki
937 // Fixes for "Call-time pass by reference has been deprecated" errors.
938 //
939 // Revision 1.36  2003/02/21 22:50:51  dairiki
940 // Ensure that language preference is a string.
941 //
942 // Revision 1.35  2003/02/16 20:04:47  dairiki
943 // Refactor the HTTP validator generation/checking code.
944 //
945 // This also fixes a number of bugs with yesterdays validator mods.
946 //
947 // Revision 1.34  2003/02/15 02:21:54  dairiki
948 // API Change!  Explicit $request argument added to contructor for WikiUser.
949 //
950 // This seemed the best way to fix a problem whereby the WikiDB
951 // was being opened twice.  (Which while being merely inefficient
952 // when using an SQL backend causes hangage when using a dba backend.)
953 //
954 // Revision 1.33  2003/01/22 03:21:40  zorloc
955 // Modified WikiUser constructor to move the DB request for the homepage to
956 // the end of the logic to prevent it from being requested and then dropped.
957 // Added more phpdoc comments.
958 //
959 // Revision 1.32  2003/01/21 07:40:50  zorloc
960 // Modified WikiUser::_ok() -- Inverted the logic so the default is to return
961 // false and to return true only in the desired condition.  Added phpdoc
962 // comments
963 //
964 // Revision 1.31  2003/01/15 05:37:20  carstenklapp
965 // code reformatting
966 //
967 // Revision 1.30  2003/01/15 04:59:27  carstenklapp
968 // Bugfix: Previously stored preferences were not loading when user
969 // signed in. (Fixed... I hope.)
970 //
971
972 // Local Variables:
973 // mode: php
974 // tab-width: 8
975 // c-basic-offset: 4
976 // c-hanging-comment-ender-p: nil
977 // indent-tabs-mode: nil
978 // End:
979 ?>