]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiUser.php
Activated Id substitution for Subversion
[SourceForge/phpwiki.git] / lib / WikiUser.php
1 <?php //-*-php-*-
2 rcs_id('$Id$');
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 // $Log: not supported by cvs2svn $
762 // Revision 1.69  2008/02/14 18:32:36  rurban
763 // signin fixes for !ENABLE_USER_NEW (to overcome php-5.2 recursion login problems)
764 //
765 // Revision 1.68  2007/07/14 17:55:30  rurban
766 // SemanticWeb.php
767 //
768 // Revision 1.67  2006/03/19 15:01:01  rurban
769 // sf.net patch #1333957 by Matt Brown: Authentication cookie identical across all wikis on a host
770 //
771 // Revision 1.66  2006/03/07 20:45:44  rurban
772 // wikihash for php-5.1
773 //
774 // Revision 1.65  2005/06/05 05:38:02  rurban
775 // Default ENABLE_DOUBLECLICKEDIT = false. Moved to UserPreferences
776 //
777 // Revision 1.64  2005/02/08 13:25:50  rurban
778 // encrypt password. fix strict logic.
779 // both bugs reported by Mikhail Vladimirov
780 //
781 // Revision 1.63  2005/01/21 14:07:50  rurban
782 // reformatting
783 //
784 // Revision 1.62  2004/11/21 11:59:16  rurban
785 // remove final \n to be ob_cache independent
786 //
787 // Revision 1.61  2004/10/21 21:02:04  rurban
788 // fix seperate page login
789 //
790 // Revision 1.60  2004/06/15 09:15:52  rurban
791 // IMPORTANT: fixed passwd handling for passwords stored in prefs:
792 //   fix encrypted usage, actually store and retrieve them from db
793 //   fix bogologin with passwd set.
794 // fix php crashes with call-time pass-by-reference (references wrongly used
795 //   in declaration AND call). This affected mainly Apache2 and IIS.
796 //   (Thanks to John Cole to detect this!)
797 //
798 // Revision 1.59  2004/06/14 11:31:36  rurban
799 // renamed global $Theme to $WikiTheme (gforge nameclash)
800 // inherit PageList default options from PageList
801 //   default sortby=pagename
802 // use options in PageList_Selectable (limit, sortby, ...)
803 // added action revert, with button at action=diff
804 // added option regex to WikiAdminSearchReplace
805 //
806 // Revision 1.58  2004/06/04 20:32:53  rurban
807 // Several locale related improvements suggested by Pierrick Meignen
808 // LDAP fix by John Cole
809 // reanable admin check without ENABLE_PAGEPERM in the admin plugins
810 //
811 // Revision 1.57  2004/06/04 12:40:21  rurban
812 // Restrict valid usernames to prevent from attacks against external auth or compromise
813 // possible holes.
814 // Fix various WikiUser old issues with default IMAP,LDAP,POP3 configs. Removed these.
815 // Fxied more warnings
816 //
817 // Revision 1.56  2004/06/03 12:36:03  rurban
818 // fix eval warning on signin
819 //
820 // Revision 1.55  2004/06/03 09:39:51  rurban
821 // fix LDAP injection (wildcard in username) detected by Steve Christey, MITRE
822 //
823 // Revision 1.54  2004/04/29 17:18:19  zorloc
824 // 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.
825 //
826 // Revision 1.53  2004/04/10 05:34:35  rurban
827 // sf bug#830912
828 //
829 // Revision 1.52  2004/04/10 02:55:48  rurban
830 // fixed old WikiUser
831 //
832 // Revision 1.51  2004/04/06 20:00:10  rurban
833 // Cleanup of special PageList column types
834 // Added support of plugin and theme specific Pagelist Types
835 // Added support for theme specific UserPreferences
836 // Added session support for ip-based throttling
837 //   sql table schema change: ALTER TABLE session ADD sess_ip CHAR(15);
838 // Enhanced postgres schema
839 // Added DB_Session_dba support
840 //
841 // Revision 1.50  2004/02/26 01:32:03  rurban
842 // fixed session login with old WikiUser object. strangely, the errormask gets corruoted to 1, Pear???
843 //
844 // Revision 1.49  2004/02/15 21:34:37  rurban
845 // PageList enhanced and improved.
846 // fixed new WikiAdmin... plugins
847 // editpage, Theme with exp. htmlarea framework
848 //   (htmlarea yet committed, this is really questionable)
849 // WikiUser... code with better session handling for prefs
850 // enhanced UserPreferences (again)
851 // RecentChanges for show_deleted: how should pages be deleted then?
852 //
853 // Revision 1.48  2004/02/01 09:14:11  rurban
854 // Started with Group_Ldap (not yet ready)
855 // added new _AuthInfo plugin to help in auth problems (warning: may display passwords)
856 // fixed some configurator vars
857 // renamed LDAP_AUTH_SEARCH to LDAP_BASE_DN
858 // changed PHPWIKI_VERSION from 1.3.8a to 1.3.8pre
859 // USE_DB_SESSION defaults to true on SQL
860 // changed GROUP_METHOD definition to string, not constants
861 // changed sample user DBAuthParams from UPDATE to REPLACE to be able to
862 //   create users. (Not to be used with external databases generally, but
863 //   with the default internal user table)
864 //
865 // fixed the IndexAsConfigProblem logic. this was flawed:
866 //   scripts which are the same virtual path defined their own lib/main call
867 //   (hmm, have to test this better, phpwiki.sf.net/demo works again)
868 //
869 // Revision 1.47  2004/01/27 23:23:39  rurban
870 // renamed ->Username => _userid for consistency
871 // renamed mayCheckPassword => mayCheckPass
872 // fixed recursion problem in WikiUserNew
873 // fixed bogo login (but not quite 100% ready yet, password storage)
874 //
875 // Revision 1.46  2004/01/26 09:17:48  rurban
876 // * changed stored pref representation as before.
877 //   the array of objects is 1) bigger and 2)
878 //   less portable. If we would import packed pref
879 //   objects and the object definition was changed, PHP would fail.
880 //   This doesn't happen with an simple array of non-default values.
881 // * use $prefs->retrieve and $prefs->store methods, where retrieve
882 //   understands the interim format of array of objects also.
883 // * simplified $prefs->get() and fixed $prefs->set()
884 // * added $user->_userid and class '_WikiUser' portability functions
885 // * fixed $user object ->_level upgrading, mostly using sessions.
886 //   this fixes yesterdays problems with loosing authorization level.
887 // * fixed WikiUserNew::checkPass to return the _level
888 // * fixed WikiUserNew::isSignedIn
889 // * added explodePageList to class PageList, support sortby arg
890 // * fixed UserPreferences for WikiUserNew
891 // * fixed WikiPlugin for empty defaults array
892 // * UnfoldSubpages: added pagename arg, renamed pages arg,
893 //   removed sort arg, support sortby arg
894 //
895 // Revision 1.45  2003/12/09 20:00:43  carstenklapp
896 // Bugfix: The last BogoUserPrefs-bugfix prevented the admin from saving
897 // prefs into his own homepage, fixed broken logic. Tightened up BogoUser
898 // prefs saving ability by checking for true existance of homepage
899 // (previously a page revision of 0 also counted as valid, again due to
900 // somewhat flawed logic).
901 //
902 // Revision 1.44  2003/12/06 04:56:23  carstenklapp
903 // Security bugfix (minor): Prevent BogoUser~s from saving extraneous
904 // _pref object meta-data within locked pages.
905 //
906 // Previously, BogoUser~s who signed in with a (valid) WikiWord such as
907 // "HomePage" could actually save preferences into that page, even though
908 // it was already locked by the administrator. Thus, any subsequent
909 // WikiLink~s to that page would become prefixed with "that nice little"
910 // UserIcon, as if that page represented a valid user.
911 //
912 // Note that the admin can lock (even) non-existant pages as desired or
913 // necessary (i.e. any DB page whose revision==0), to prevent the
914 // arbitrary BogoUser from saving preference metadata into such a page;
915 // for example, the silly WikiName "@qmgi`Vcft_x|" (that is the
916 // \$examplechars presented in login.tmpl, in case it is not visible here
917 // in the CVS comments).
918 //
919 // http://phpwiki.sourceforge.net/phpwiki/
920 // %C0%F1%ED%E7%E9%E0%D6%E3%E6%F4%DF%F8%FC?action=lock
921 //
922 // To remove the prefs metadata from a page, the admin can use the
923 // EditMetaData plugin, enter pref as the key, leave the value box empty
924 // and then submit the change. For example:
925 //
926 // http://phpwiki.sourceforge.net/phpwiki/
927 // _EditMetaData?page=%C0%F1%ED%E7%E9%E0%D6%E3%E6%F4%DF%F8%FC
928 //
929 // (It seems a rethinking of WikiUserNew.php with its WikiUser and
930 // UserPreferences classes is in order. Ideally the WikiDB would
931 // transparently handle such a situation, perhaps BogoUser~s should
932 // simply be restricted to saving preferences into a cookie until his/her
933 // e-mail address has been verified.)
934 //
935 // Revision 1.43  2003/12/04 19:33:30  carstenklapp
936 // Bugfix: Under certain PhpWiki installations (such as the PhpWiki at
937 // SF), the user was unable to select a theme other than the server's
938 // default. (Use the more robust Theme::findFile instead of PHP's
939 // file_exists function to detect installed themes).
940 //
941 // Revision 1.42  2003/11/30 18:18:13  carstenklapp
942 // Minor code optimization: use include_once instead of require_once
943 // inside functions that might not always called.
944 //
945 // Revision 1.41  2003/11/21 21:32:39  carstenklapp
946 // Bugfix: When DEFAULT_LANGUAGE was not 'en', a user's language prefs
947 // would revert to 'en' when the default <system language> was selected
948 // in UserPreferences and the user saved his preferences. (Check for
949 // empty or blank language pref in sanify function of class
950 // _UserPreference_language and return DEFAULT_LANGUAGE if nothing or
951 // default selected in UserPreferences.)
952 //
953 // Revision 1.40  2003/11/21 16:54:58  carstenklapp
954 // Bugfix: login.tmpl was always displayed in English despite
955 // DEFAULT_LANGUAGE set in index.php. (Added call to
956 // update_locale(DEFAULT_LANGUAGE) before printing login form).
957 //
958 // Revision 1.39  2003/10/28 21:13:46  carstenklapp
959 // Security bug fix for admin password, submitted by Julien Charbon.
960 //
961 // Revision 1.38  2003/09/13 22:25:38  carstenklapp
962 // Hook for new user preference 'noLinkIcons'.
963 //
964 // Revision 1.37  2003/02/22 20:49:55  dairiki
965 // Fixes for "Call-time pass by reference has been deprecated" errors.
966 //
967 // Revision 1.36  2003/02/21 22:50:51  dairiki
968 // Ensure that language preference is a string.
969 //
970 // Revision 1.35  2003/02/16 20:04:47  dairiki
971 // Refactor the HTTP validator generation/checking code.
972 //
973 // This also fixes a number of bugs with yesterdays validator mods.
974 //
975 // Revision 1.34  2003/02/15 02:21:54  dairiki
976 // API Change!  Explicit $request argument added to contructor for WikiUser.
977 //
978 // This seemed the best way to fix a problem whereby the WikiDB
979 // was being opened twice.  (Which while being merely inefficient
980 // when using an SQL backend causes hangage when using a dba backend.)
981 //
982 // Revision 1.33  2003/01/22 03:21:40  zorloc
983 // Modified WikiUser constructor to move the DB request for the homepage to
984 // the end of the logic to prevent it from being requested and then dropped.
985 // Added more phpdoc comments.
986 //
987 // Revision 1.32  2003/01/21 07:40:50  zorloc
988 // Modified WikiUser::_ok() -- Inverted the logic so the default is to return
989 // false and to return true only in the desired condition.  Added phpdoc
990 // comments
991 //
992 // Revision 1.31  2003/01/15 05:37:20  carstenklapp
993 // code reformatting
994 //
995 // Revision 1.30  2003/01/15 04:59:27  carstenklapp
996 // Bugfix: Previously stored preferences were not loading when user
997 // signed in. (Fixed... I hope.)
998 //
999
1000 // Local Variables:
1001 // mode: php
1002 // tab-width: 8
1003 // c-basic-offset: 4
1004 // c-hanging-comment-ender-p: nil
1005 // indent-tabs-mode: nil
1006 // End:
1007 ?>