]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiUser.php
Bugfix: Previously stored preferences were not loading when user
[SourceForge/phpwiki.git] / lib / WikiUser.php
1 <?php rcs_id('$Id: WikiUser.php,v 1.30 2003-01-15 04:59:27 carstenklapp 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 (USE_PREFS_IN_PAGE and $this->homePage()) { // in page metadata
265             if ($pref = $this->_homepage->get('pref')) {
266                 //trigger_error("pref=".$pref);//debugging
267                 $prefs = unserialize($pref);
268             }
269         }
270         return new UserPreferences($prefs);
271     }
272
273     // No cookies anymore for all prefs, only the userid.
274     // PHP creates a session cookie in memory, which is much more efficient.
275     //
276     // Return the number of changed entries?
277     function setPreferences($prefs, $id_only = false) {
278         // update the id
279         $this->_request->setSessionVar('wiki_prefs', $prefs);
280         // $this->_request->setCookieVar('WIKI_PREFS2', $this->_prefs, 365);
281         // simple unpacked cookie
282         if ($this->_userid) setcookie('WIKI_ID', $this->_userid, 365, '/');
283
284         // We must ensure that any password is encrypted. 
285         // We don't need any plaintext password.
286         if (! $id_only ) {
287             if ($this->isSignedIn()) {
288                 if ($this->isAdmin()) $prefs->set('passwd',''); // this is already stored in index.php, 
289                 // and it might be plaintext! well oh well
290                 if ($homepage = $this->homePage()) {
291                     $homepage->set('pref',serialize($prefs->_prefs));
292                     return sizeof($prefs->_prefs);
293                 } else {
294                     trigger_error('No homepage for user found. Creating one...', E_USER_WARNING);
295                     $this->createHomepage($prefs);
296                     //$homepage->set('pref',serialize($prefs->_prefs));
297                     return sizeof($prefs->_prefs);
298                 }
299             } else {
300                 trigger_error('you must be signed in',E_USER_WARNING);
301             }
302         }
303         return 0;
304     }
305
306     // check for homepage with user flag.
307     // can be overriden from the auth backends
308     function exists() {
309         $homepage = $this->homePage();
310         return ($this->_userid and $homepage and $homepage->get('pref'));
311     }
312
313     // doesn't check for existance!!! hmm. 
314     // how to store metadata in not existing pages? how about versions?
315     function homePage() {
316         if (!$this->_userid) return false;
317         if (!empty($this->_homepage)) {
318             return $this->_homepage;
319         } else {
320             $this->_homepage = $this->_dbi->getPage($this->_userid);
321             return $this->_homepage;
322         }
323     }
324
325     // create user by checking his homepage
326     function createUser ($pref, $createDefaultHomepage = true) {
327         if ($this->exists()) return;
328         if ($createDefaultHomepage) {
329             $this->createHomepage ($pref);
330         } else {
331             // empty page
332             include "lib/loadsave.php";
333             $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)),
334                               'versiondata' => array('author' => $this->_userid),
335                               'pagename' => $this->_userid,
336                               'content' => _('CategoryHomepage'));
337             SavePage (&$this->_request, $pageinfo, false, false);
338         }
339         $this->setPreferences($pref);
340     }
341
342     // create user and default user homepage
343     function createHomepage ($pref) {
344         $pagename = $this->_userid;
345         include "lib/loadsave.php";
346
347         // create default homepage:
348         //  properly expanded template and the pref metadata
349         $template = Template('homepage.tmpl',$this->_request);
350         $text  = $template->getExpansion();
351         $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)),
352                           'versiondata' => array('author' => $this->_userid),
353                           'pagename' => $pagename,
354                           'content' => $text);
355         SavePage (&$this->_request, $pageinfo, false, false);
356             
357         // create Calender
358         $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Preferences');
359         if (! isWikiPage($pagename)) {
360             $pageinfo = array('pagedata' => array(),
361                               'versiondata' => array('author' => $this->_userid),
362                               'pagename' => $pagename,
363                               'content' => "<?plugin Calender ?>\n");
364             SavePage (&$this->_request, $pageinfo, false, false);
365         }
366
367         // create Preferences
368         $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Preferences');
369         if (! isWikiPage($pagename)) {
370             $pageinfo = array('pagedata' => array(),
371                               'versiondata' => array('author' => $this->_userid),
372                               'pagename' => $pagename,
373                               'content' => "<?plugin UserPreferences ?>\n");
374             SavePage (&$this->_request, $pageinfo, false, false);
375         }
376     }
377
378     function tryAuthBackends() {
379         return ''; // crypt('') will never be ''
380     }
381
382     // Auth backends must store the crypted password where?
383     // Not in the preferences.
384     function checkPassword($passwd) {
385         $prefs = $this->getPreferences();
386         $stored_passwd = $prefs->get('passwd'); // crypted
387         if (empty($prefs->_prefs['passwd']))    // not stored in the page
388             // allow empty passwords? At least store a '*' then.
389             // try other backend. hmm.
390             $stored_passwd = $this->tryAuthBackends($this->_userid);
391         if (empty($stored_passwd)) {
392             trigger_error(sprintf(_("Old UserPage %s without stored password updated with empty password. Set a password in your UserPreferences."), $this->_userid), E_USER_NOTICE);
393             $prefs->set('passwd','*'); 
394             return true;
395         }
396         if ($stored_passwd == '*')
397             return true;
398         if (!empty($passwd) && crypt($passwd, $stored_passwd) == $stored_passwd)
399             return true;
400         else         
401             return false;
402     }
403
404     function changePassword($newpasswd, $passwd2 = false) {
405         if (! $this->mayChangePassword() ) {
406             trigger_error(sprintf("Attempt to change an external password for '%s'. Not allowed!",
407                                   $this->_userid), E_USER_ERROR);
408             return;
409         }
410         if ($passwd2 and $passwd2 != $newpasswd) {
411             trigger_error("The second passwort must be the same as the first to change it", E_USER_ERROR);
412             return;
413         }
414         $prefs = $this->getPreferences();
415         //$oldpasswd = $prefs->get('passwd');
416         $prefs->set('passwd', crypt($newpasswd));
417         $this->setPreferences($prefs);
418     }
419
420     function mayChangePassword() {
421         // on external DBAuth maybe. on IMAP or LDAP not
422         // on internal DBAuth yes
423         if (in_array($this->_authmethod, array('IMAP', 'LDAP'))) 
424             return false;
425         if ($this->isAdmin()) 
426             return false;
427         if ($this->_authmethod == 'pagedata')
428             return true;
429         if ($this->_authmethod == 'authdb')
430             return true;
431     }
432 }
433
434 // create user and default user homepage
435 function createUser ($userid, $pref) {
436     $user = new WikiUser ($userid);
437     $user->createUser($pref);
438 }
439
440 class _UserPreference 
441 {
442     function _UserPreference ($default_value) {
443         $this->default_value = $default_value;
444     }
445
446     function sanify ($value) {
447         return (string) $value;
448     }
449
450     function update ($value) {
451     }
452 }
453
454 class _UserPreference_numeric extends _UserPreference
455 {
456     function _UserPreference_numeric ($default, $minval = false, $maxval = false) {
457         $this->_UserPreference((double) $default);
458         $this->_minval = (double) $minval;
459         $this->_maxval = (double) $maxval;
460     }
461
462     function sanify ($value) {
463         $value = (double) $value;
464         if ($this->_minval !== false && $value < $this->_minval)
465             $value = $this->_minval;
466         if ($this->_maxval !== false && $value > $this->_maxval)
467             $value = $this->_maxval;
468         return $value;
469     }
470 }
471
472 class _UserPreference_int extends _UserPreference_numeric
473 {
474     function _UserPreference_int ($default, $minval = false, $maxval = false) {
475         $this->_UserPreference_numeric((int) $default, (int)$minval, (int)$maxval);
476     }
477
478     function sanify ($value) {
479         return (int) parent::sanify((int)$value);
480     }
481 }
482
483 class _UserPreference_bool extends _UserPreference
484 {
485     function _UserPreference_bool ($default = false) {
486         $this->_UserPreference((bool) $default);
487     }
488
489     function sanify ($value) {
490         if (is_array($value)) {
491             /* This allows for constructs like:
492              *
493              *   <input type="hidden" name="pref[boolPref][]" value="0" />
494              *   <input type="checkbox" name="pref[boolPref][]" value="1" />
495              *
496              * (If the checkbox is not checked, only the hidden input gets sent.
497              * If the checkbox is sent, both inputs get sent.)
498              */
499             foreach ($value as $val) {
500                 if ($val)
501                     return true;
502             }
503             return false;
504         }
505         return (bool) $value;
506     }
507 }
508
509
510 class _UserPreference_language extends _UserPreference
511 {
512     function _UserPreference_language ($default = DEFAULT_LANGUAGE) {
513         $this->_UserPreference($default);
514     }
515
516     function sanify ($value) {
517         // FIXME: check for valid locale
518         return $value;
519     }
520 }
521
522 class _UserPreference_theme extends _UserPreference
523 {
524     function _UserPreference_theme ($default = THEME) {
525         $this->_UserPreference($default);
526     }
527
528     function sanify ($value) {
529         if (file_exists($this->_themefile($value)))
530             return $value;
531         return $this->default_value;
532     }
533
534     function update ($newvalue) {
535         global $Theme;
536         include_once($this->_themefile($newvalue));
537         if (empty($Theme))
538             include_once($this->_themefile(THEME));
539     }
540
541     function _themefile ($theme) {
542         return "themes/$theme/themeinfo.php"; 
543     }
544 }
545
546 // don't save default preferences for efficiency.
547 class UserPreferences {
548     function UserPreferences ($saved_prefs = false) {
549         $this->_prefs = array();
550
551         if (isa($saved_prefs, 'UserPreferences') and $saved_prefs->_prefs) {
552             foreach ($saved_prefs->_prefs as $name => $value)
553                 $this->set($name, $value);
554         } elseif (is_array($saved_prefs)) {
555             foreach ($saved_prefs as $name => $value)
556                 $this->set($name, $value);
557         }
558     }
559
560     function _getPref ($name) {
561         global $UserPreferences;
562         if (!isset($UserPreferences[$name])) {
563             if ($name == 'passwd2') return false;
564             trigger_error("$name: unknown preference", E_USER_NOTICE);
565             return false;
566         }
567         return $UserPreferences[$name];
568     }
569
570     function get ($name) {
571         if (isset($this->_prefs[$name]))
572             return $this->_prefs[$name];
573         if (!($pref = $this->_getPref($name)))
574             return false;
575         return $pref->default_value;
576     }
577
578     function set ($name, $value) {
579         if (!($pref = $this->_getPref($name)))
580             return false;
581
582         $newvalue = $pref->sanify($value);
583         $oldvalue = $this->get($name);
584
585         // update on changes
586         if ($newvalue != $oldvalue)
587             $pref->update($newvalue);
588         
589         // don't set default values to save space (in cookies, db and sesssion)
590         if ($value == $pref->default_value)
591             unset($this->_prefs[$name]);
592         else
593             $this->_prefs[$name] = $newvalue;
594     }
595 }
596
597 // $Log: not supported by cvs2svn $
598
599 // Local Variables:
600 // mode: php
601 // tab-width: 8
602 // c-basic-offset: 4
603 // c-hanging-comment-ender-p: nil
604 // indent-tabs-mode: nil
605 // End:   
606 ?>