]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiUser.php
Minor cleanup of preference setting code for theme and language
[SourceForge/phpwiki.git] / lib / WikiUser.php
1 <?php rcs_id('$Id: WikiUser.php,v 1.25 2002-09-18 18:35:24 dairiki Exp $');
2
3 // It is anticipated that when userid support is added to phpwiki,
4 // this object will hold much more information (e-mail, home(wiki)page,
5 // etc.) about the user.
6    
7 // There seems to be no clean way to "log out" a user when using
8 // HTTP authentication.
9 // So we'll hack around this by storing the currently logged
10 // 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 serialized string.
15 //       If no homepage, fallback to prefs in cookie as in 1.3.3.
16
17
18 define('WIKIAUTH_ANON', 0);
19 define('WIKIAUTH_BOGO', 1);     // any valid WikiWord is enough
20 define('WIKIAUTH_USER', 2);     // real auth from a database/file/server.
21
22 define('WIKIAUTH_ADMIN', 10);
23 define('WIKIAUTH_FORBIDDEN', 11); // Completely not allowed.
24
25 $UserPreferences = array(
26                          'userid'        => new _UserPreference(''), // really store this also?
27                          'passwd'        => new _UserPreference(''),
28                          'email'         => new _UserPreference(''),
29                          'emailVerified' => new _UserPreference_bool(),
30                          'notifyPages'   => new _UserPreference(''),
31                          'theme'         => new _UserPreference_theme(THEME),
32                          'lang'          => new _UserPreference_language(DEFAULT_LANGUAGE),
33                          'editWidth'     => new _UserPreference_int(80, 30, 150),
34                          'editHeight'    => new _UserPreference_int(22, 5, 80),
35                          'timeOffset'    => new _UserPreference_numeric(0, -26, 26),
36                          'relativeDates' => new _UserPreference_bool()
37                          );
38
39 class WikiUser {
40     var $_userid = false;
41     var $_level  = false;
42     var $_request, $_dbi, $_authdbi, $_homepage;
43     var $_authmethod = '', $_authhow = '';
44
45     /**
46      * Constructor.
47      */
48     function WikiUser ($userid = false, $authlevel = false) {
49         $this->_request = &$GLOBALS['request'];
50         $this->_dbi = &$this->_request->getDbh();
51
52         if (isa($userid, 'WikiUser')) {
53             $this->_userid   = $userid->_userid;
54             $this->_level    = $userid->_level;
55         }
56         else {
57             $this->_userid = $userid;
58             $this->_level = $authlevel;
59         }
60         if ($this->_userid)
61             $this->_homepage = $this->_dbi->getPage($this->_userid);
62         if (!$this->_ok()) {
63             // Paranoia: if state is at all inconsistent, log out...
64             $this->_userid = false;
65             $this->_level = false;
66             $this->_homepage = false;
67             $this->_authhow .= ' paranoia logout';
68         }
69     }
70
71     function auth_how() {
72         return $this->_authhow;
73     }
74
75     /** Invariant
76      */
77     function _ok () {
78         if (empty($this->_userid) || empty($this->_level)) {
79             // This is okay if truly logged out.
80             return $this->_userid === false && $this->_level === false;
81         }
82         // User is logged in...
83         
84         // Check for valid authlevel.
85         if (!in_array($this->_level, array(WIKIAUTH_BOGO, WIKIAUTH_USER, WIKIAUTH_ADMIN)))
86             return false;
87
88         // Check for valid userid.
89         if (!is_string($this->_userid))
90             return false;
91         return true;
92     }
93
94     function getId () {
95         return ( $this->isSignedIn()
96                  ? $this->_userid
97                  : $this->_request->get('REMOTE_ADDR') ); // FIXME: globals
98     }
99
100     function getAuthenticatedId() {
101         return ( $this->isAuthenticated()
102                  ? $this->_userid
103                  : $this->_request->get('REMOTE_ADDR') ); // FIXME: globals
104     }
105
106     function isSignedIn () {
107         return $this->_level >= WIKIAUTH_BOGO;
108     }
109         
110     function isAuthenticated () {
111         return $this->_level >= WIKIAUTH_USER;
112     }
113          
114     function isAdmin () {
115         return $this->_level == WIKIAUTH_ADMIN;
116     }
117
118     function hasAuthority ($require_level) {
119         return $this->_level >= $require_level;
120     }
121
122     function AuthCheck ($postargs) {
123         // Normalize args, and extract.
124         $keys = array('userid', 'passwd', 'require_level', 'login', 'logout', 'cancel');
125         foreach ($keys as $key) 
126             $args[$key] = isset($postargs[$key]) ? $postargs[$key] : false;
127         extract($args);
128         $require_level = max(0, min(WIKIAUTH_ADMIN, (int) $require_level));
129
130         if ($logout)
131             return new WikiUser; // Log out
132         elseif ($cancel)
133             return false;        // User hit cancel button.
134         elseif (!$login && !$userid)
135             return false;       // Nothing to do?
136
137         $authlevel = $this->_pwcheck($userid, $passwd);
138         if (!$authlevel)
139             return _("Invalid password or userid.");
140         elseif ($authlevel < $require_level)
141             return _("Insufficient permissions.");
142
143         // Successful login.
144         $user = new WikiUser;
145         $user->_userid = $userid;
146         $user->_level = $authlevel;
147         return $user;
148     }
149     
150     function PrintLoginForm (&$request, $args, $fail_message = false, $seperate_page = true) {
151         include_once('lib/Template.php');
152         
153         $userid = '';
154         $require_level = 0;
155         extract($args); // fixme
156         
157         $require_level = max(0, min(WIKIAUTH_ADMIN, (int) $require_level));
158         
159         $pagename = $request->getArg('pagename');
160         $login = new Template('login', $request,
161                               compact('pagename', 'userid', 'require_level', 'fail_message', 'pass_required'));
162         if ($seperate_page) {
163             $top = new Template('html', $request, array('TITLE' =>  _("Sign In")));
164             return $top->printExpansion($login);
165         } else {
166             return $login;
167         }
168     }
169         
170     /**
171      * Check password.
172      */
173     function _pwcheck ($userid, $passwd) {
174         global $WikiNameRegexp;
175         
176         if (!empty($userid) && $userid == ADMIN_USER) {
177             // $this->_authmethod = 'pagedata';
178             if (defined('ENCRYPTED_PASSWD') && ENCRYPTED_PASSWD)
179                 if (!empty($passwd) && crypt($passwd, ADMIN_PASSWD) == ADMIN_PASSWD)
180                     return WIKIAUTH_ADMIN;
181             if (!empty($passwd)) {
182                 if ($passwd == ADMIN_PASSWD)
183                   return WIKIAUTH_ADMIN;
184                 else {
185                     // maybe we forgot to enable ENCRYPTED_PASSWD?
186                     if (function_exists('crypt') and crypt($passwd, ADMIN_PASSWD) == ADMIN_PASSWD) {
187                         trigger_error(_("You forgot to set ENCRYPTED_PASSWD to true. Please update your /index.php"), E_USER_WARNING);
188                         return WIKIAUTH_ADMIN;
189                     }
190                 }
191             }
192             return false;
193         }
194         // HTTP Authentification
195         elseif (ALLOW_HTTP_AUTH_LOGIN and !empty($PHP_AUTH_USER)) {
196             // if he ignored the password field, because he is already authentificated
197             // try the previously given password.
198             if (empty($passwd)) $passwd = $PHP_AUTH_PW;
199         }
200
201         // WikiDB_User DB/File Authentification from $DBAuthParams 
202         // Check if we have the user. If not try other methods.
203         if (ALLOW_USER_LOGIN) { // and !empty($passwd)) {
204             $request = $this->_request;
205             // first check if the user is known
206             if ($this->exists($userid)) {
207                 $this->_authmethod = 'pagedata';
208                 return ($this->checkPassword($passwd)) ? WIKIAUTH_USER : false;
209             } else {
210                 // else try others such as LDAP authentication:
211                 if (ALLOW_LDAP_LOGIN and !empty($passwd)) {
212                     if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
213                         $r = @ldap_bind($ldap); // this is an anonymous bind
214                         $st_search = "uid=$userid";
215                         // Need to set the right root search information. see ../index.php
216                         $sr = ldap_search($ldap, LDAP_AUTH_SEARCH, "$st_search");  
217                         $info = ldap_get_entries($ldap, $sr); // there may be more hits with this userid. try every
218                         for ($i=0; $i<$info["count"]; $i++) {
219                             $dn = $info[$i]["dn"];
220                             // The password is still plain text.
221                             if ($r = @ldap_bind($ldap, $dn, $passwd)) {
222                                 // ldap_bind will return TRUE if everything matches
223                                 ldap_close($ldap);
224                                 $this->_authmethod = 'LDAP';
225                                 return WIKIAUTH_USER;
226                             }
227                         }
228                     } else {
229                         trigger_error("Unable to connect to LDAP server " . LDAP_AUTH_HOST, E_USER_WARNING);
230                     }
231                 }
232                 // imap authentication. added by limako
233                 if (ALLOW_IMAP_LOGIN and !empty($passwd)) {
234                     $mbox = @imap_open( "{" . IMAP_AUTH_HOST . ":143}", $userid, $passwd, OP_HALFOPEN );
235                     if( $mbox ) {
236                         imap_close( $mbox );
237                         $this->_authmethod = 'IMAP';
238                         return WIKIAUTH_USER;
239                     }
240                 }
241             }
242         }
243         if (ALLOW_BOGO_LOGIN
244                 && preg_match('/\A' . $WikiNameRegexp . '\z/', $userid)) {
245             $this->_authmethod = 'BOGO';
246             return WIKIAUTH_BOGO;
247         }
248         return false;
249     }
250
251     // Todo: try our WikiDB backends.
252     function getPreferences() {
253         // Restore saved preferences.
254         // I'd rather prefer only to store the UserId in the cookie or session,
255         // and get the preferences from the db or page.
256         if (!($prefs = $this->_request->getCookieVar('WIKI_PREFS2')))
257             $prefs = $this->_request->getSessionVar('wiki_prefs');
258
259         //if (!$this->_userid and !empty($GLOBALS['HTTP_COOKIE_VARS']['WIKI_ID'])) {
260         //    $this->_userid = $GLOBALS['HTTP_COOKIE_VARS']['WIKI_ID'];
261         //}
262
263         // before we get his prefs we should check if he is signed in
264         if (!$prefs->_prefs and USE_PREFS_IN_PAGE and $this->homePage()) { // in page metadata
265             if ($pref = $this->_homepage->get('pref'))
266                 $prefs = unserialize($pref);
267         }
268         return new UserPreferences($prefs);
269     }
270
271     // No cookies anymore for all prefs, only the userid.
272     // PHP creates a session cookie in memory, which is much more efficient.
273     //
274     // Return the number of changed entries?
275     function setPreferences($prefs, $id_only = false) {
276         // update the id
277         $this->_request->setSessionVar('wiki_prefs', $prefs);
278         // $this->_request->setCookieVar('WIKI_PREFS2', $this->_prefs, 365);
279         // simple unpacked cookie
280         if ($this->_userid) setcookie('WIKI_ID', $this->_userid, 365, '/');
281
282         // We must ensure that any password is encrypted. 
283         // We don't need any plaintext password.
284         if (! $id_only ) {
285             if ($this->isSignedIn()) {
286                 if ($this->isAdmin()) $prefs->set('passwd',''); // this is already stored in index.php, 
287                 // and it might be plaintext! well oh well
288                 if ($homepage = $this->homePage()) {
289                     $homepage->set('pref',serialize($prefs->_prefs));
290                     return sizeof($prefs->_prefs);
291                 } else {
292                     trigger_error('No homepage for user found. Creating one...', E_USER_WARNING);
293                     $this->createHomepage($prefs);
294                     //$homepage->set('pref',serialize($prefs->_prefs));
295                     return sizeof($prefs->_prefs);
296                 }
297             } else {
298                 trigger_error('you must be signed in',E_USER_WARNING);
299             }
300         }
301         return 0;
302     }
303
304     // check for homepage with user flag.
305     // can be overriden from the auth backends
306     function exists() {
307         $homepage = $this->homePage();
308         return ($this->_userid and $homepage and $homepage->get('pref'));
309     }
310
311     // doesn't check for existance!!! hmm. 
312     // how to store metadata in not existing pages? how about versions?
313     function homePage() {
314         if (!$this->_userid) return false;
315         if (!empty($this->_homepage)) {
316             return $this->_homepage;
317         } else {
318             $this->_homepage = $this->_dbi->getPage($this->_userid);
319             return $this->_homepage;
320         }
321     }
322
323     // create user by checking his homepage
324     function createUser ($pref, $createDefaultHomepage = true) {
325         if ($this->exists()) return;
326         if ($createDefaultHomepage) {
327             $this->createHomepage ($pref);
328         } else {
329             // empty page
330             include "lib/loadsave.php";
331             $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)),
332                               'versiondata' => array('author' => $this->_userid),
333                               'pagename' => $this->_userid,
334                               'content' => _('CategoryHomepage'));
335             SavePage (&$this->_request, $pageinfo, false, false);
336         }
337         $this->setPreferences($pref);
338     }
339
340     // create user and default user homepage
341     function createHomepage ($pref) {
342         $pagename = $this->_userid;
343         include "lib/loadsave.php";
344
345         // create default homepage:
346         //  properly expanded template and the pref metadata
347         $template = Template('homepage.tmpl',$this->_request);
348         $text  = $template->getExpansion();
349         $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)),
350                           'versiondata' => array('author' => $this->_userid),
351                           'pagename' => $pagename,
352                           'content' => $text);
353         SavePage (&$this->_request, $pageinfo, false, false);
354             
355         // create Calender
356         $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Preferences');
357         if (! isWikiPage($pagename)) {
358             $pageinfo = array('pagedata' => array(),
359                               'versiondata' => array('author' => $this->_userid),
360                               'pagename' => $pagename,
361                               'content' => "<?plugin Calender ?>\n");
362             SavePage (&$this->_request, $pageinfo, false, false);
363         }
364
365         // create Preferences
366         $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Preferences');
367         if (! isWikiPage($pagename)) {
368             $pageinfo = array('pagedata' => array(),
369                               'versiondata' => array('author' => $this->_userid),
370                               'pagename' => $pagename,
371                               'content' => "<?plugin UserPreferences ?>\n");
372             SavePage (&$this->_request, $pageinfo, false, false);
373         }
374     }
375
376     function tryAuthBackends() {
377         return ''; // crypt('') will never be ''
378     }
379
380     // Auth backends must store the crypted password where?
381     // Not in the preferences.
382     function checkPassword($passwd) {
383         $prefs = $this->getPreferences();
384         $stored_passwd = $prefs->get('passwd'); // crypted
385         if (empty($prefs->_prefs['passwd']))    // not stored in the page
386             // allow empty passwords? At least store a '*' then.
387             // try other backend. hmm.
388             $stored_passwd = $this->tryAuthBackends($this->_userid);
389         if (empty($stored_passwd)) {
390             trigger_error(sprintf(_("Old UserPage %s without stored password updated with empty password. Set a password in your UserPreferences."), $this->_userid), E_USER_NOTICE);
391             $prefs->set('passwd','*'); 
392             return true;
393         }
394         if ($stored_passwd == '*')
395             return true;
396         if (!empty($passwd) && crypt($passwd, $stored_passwd) == $stored_passwd)
397             return true;
398         else         
399             return false;
400     }
401
402     function changePassword($newpasswd, $passwd2 = false) {
403         if (! $this->mayChangePassword() ) {
404             trigger_error(sprintf("Attempt to change an external password for '%s'. Not allowed!",
405                                   $this->_userid), E_USER_ERROR);
406             return;
407         }
408         if ($passwd2 and $passwd2 != $newpasswd) {
409             trigger_error("The second passwort must be the same as the first to change it", E_USER_ERROR);
410             return;
411         }
412         $prefs = $this->getPreferences();
413         //$oldpasswd = $prefs->get('passwd');
414         $prefs->set('passwd', crypt($newpasswd));
415         $this->setPreferences($prefs);
416     }
417
418     function mayChangePassword() {
419         // on external DBAuth maybe. on IMAP or LDAP not
420         // on internal DBAuth yes
421         if (in_array($this->_authmethod, array('IMAP', 'LDAP'))) 
422             return false;
423         if ($this->isAdmin()) 
424             return false;
425         if ($this->_authmethod == 'pagedata')
426             return true;
427         if ($this->_authmethod == 'authdb')
428             return true;
429     }
430 }
431
432 // create user and default user homepage
433 function createUser ($userid, $pref) {
434     $user = new WikiUser ($userid);
435     $user->createUser($pref);
436 }
437
438 class _UserPreference 
439 {
440     function _UserPreference ($default_value) {
441         $this->default_value = $default_value;
442     }
443
444     function sanify ($value) {
445         return (string) $value;
446     }
447
448     function update ($value) {
449     }
450 }
451
452 class _UserPreference_numeric extends _UserPreference
453 {
454     function _UserPreference_numeric ($default, $minval = false, $maxval = false) {
455         $this->_UserPreference((double) $default);
456         $this->_minval = (double) $minval;
457         $this->_maxval = (double) $maxval;
458     }
459
460     function sanify ($value) {
461         $value = (double) $value;
462         if ($this->_minval !== false && $value < $this->_minval)
463             $value = $this->_minval;
464         if ($this->_maxval !== false && $value > $this->_maxval)
465             $value = $this->_maxval;
466         return $value;
467     }
468 }
469
470 class _UserPreference_int extends _UserPreference_numeric
471 {
472     function _UserPreference_int ($default, $minval = false, $maxval = false) {
473         $this->_UserPreference_numeric((int) $default, (int)$minval, (int)$maxval);
474     }
475
476     function sanify ($value) {
477         return (int) parent::sanify((int)$value);
478     }
479 }
480
481 class _UserPreference_bool extends _UserPreference
482 {
483     function _UserPreference_bool ($default = false) {
484         $this->_UserPreference((bool) $default);
485     }
486
487     function sanify ($value) {
488         if (is_array($value)) {
489             /* This allows for constructs like:
490              *
491              *   <input type="hidden" name="pref[boolPref][]" value="0" />
492              *   <input type="checkbox" name="pref[boolPref][]" value="1" />
493              *
494              * (If the checkbox is not checked, only the hidden input gets sent.
495              * If the checkbox is sent, both inputs get sent.)
496              */
497             foreach ($value as $val) {
498                 if ($val)
499                     return true;
500             }
501             return false;
502         }
503         return (bool) $value;
504     }
505 }
506
507
508 class _UserPreference_language extends _UserPreference
509 {
510     function _UserPreference_language ($default = 'en') {
511         $this->_UserPreference($default);
512     }
513
514     function sanify ($value) {
515         // FIXME: check for valid locale
516     }
517
518     function update ($newvalue) {
519         update_locale ($newvalue);
520     }
521 }
522
523 class _UserPreference_theme extends _UserPreference
524 {
525     function _UserPreference_theme ($default = 'default') {
526         $this->_UserPreference($default);
527     }
528
529     function sanify ($value) {
530         if (file_exists($this->_themefile($value)))
531             return $value;
532         return $this->default;
533     }
534
535     function update ($newvalue) {
536         include($this->_themefile($value));
537     }
538
539     function _themefile ($theme) {
540         return "themes/$theme/themeinfo.php"; 
541     }
542 }
543
544 // don't save default preferences for efficiency.
545 class UserPreferences {
546     function UserPreferences ($saved_prefs = false) {
547         $this->_prefs = array();
548
549         if (isa($saved_prefs, 'UserPreferences') and $saved_prefs->_prefs) {
550             foreach ($saved_prefs->_prefs as $name => $value)
551                 $this->set($name, $value);
552         } elseif (is_array($saved_prefs)) {
553             foreach ($saved_prefs as $name => $value)
554                 $this->set($name, $value);
555         }
556     }
557
558     function _getPref ($name) {
559         global $UserPreferences;
560         if (!isset($UserPreferences[$name])) {
561             if ($name == 'passwd2') return false;
562             trigger_error("$name: unknown preference", E_USER_NOTICE);
563             return false;
564         }
565         return $UserPreferences[$name];
566     }
567
568     function get ($name) {
569         if (isset($this->_prefs[$name]))
570             return $this->_prefs[$name];
571         if (!($pref = $this->_getPref($name)))
572             return false;
573         return $pref->default_value;
574     }
575
576     function set ($name, $value) {
577         if (!($pref = $this->_getPref($name)))
578             return false;
579
580         $newvalue = $pref->sanify($value);
581         $oldvalue = $this->get($name);
582
583         // update on changes
584         if ($newvalue != $oldvalue)
585             $pref->update($newvalue);
586         
587         // don't set default values to save space (in cookies, db and sesssion)
588         if ($value == $pref->default_value)
589             unset($this->_prefs[$name]);
590         else
591             $this->_prefs[$name] = $newvalue;
592     }
593 }
594
595 // Local Variables:
596 // mode: php
597 // tab-width: 8
598 // c-basic-offset: 4
599 // c-hanging-comment-ender-p: nil
600 // indent-tabs-mode: nil
601 // End:   
602 ?>