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