]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiUser.php
Security bug fix for admin password, submitted by Julien Charbon.
[SourceForge/phpwiki.git] / lib / WikiUser.php
1 <?php //-*-php-*-
2 rcs_id('$Id: WikiUser.php,v 1.39 2003-10-28 21:13:46 carstenklapp 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_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                          'noLinkIcons'   => new _UserPreference_bool(),
35                          'editHeight'    => new _UserPreference_int(22, 5, 80),
36                          'timeOffset'    => new _UserPreference_numeric(0, -26, 26),
37                          'relativeDates' => new _UserPreference_bool()
38                          );
39
40 /**
41
42 */
43 class WikiUser {
44     var $_userid = false;
45     var $_level  = false;
46     var $_request, $_dbi, $_authdbi, $_homepage;
47     var $_authmethod = '', $_authhow = '';
48
49     /**
50      * Constructor.
51      * 
52      * Populates the instance variables and calls $this->_ok() 
53      * to ensure that the parameters are valid.
54      * @param mixed $userid String of username or WikiUser object.
55      * @param integer $authlevel Authorization level.
56      */
57     function WikiUser (&$request, $userid = false, $authlevel = false) {
58         $this->_request = &$request;
59         $this->_dbi = &$this->_request->getDbh();
60
61         if (isa($userid, 'WikiUser')) {
62             $this->_userid   = $userid->_userid;
63             $this->_level    = $userid->_level;
64         }
65         else {
66             $this->_userid = $userid;
67             $this->_level = $authlevel;
68         }
69         if (!$this->_ok()) {
70             // Paranoia: if state is at all inconsistent, log out...
71             $this->_userid = false;
72             $this->_level = false;
73             $this->_homepage = false;
74             $this->_authhow .= ' paranoia logout';
75         }
76         if ($this->_userid) {
77             $this->_homepage = $this->_dbi->getPage($this->_userid);
78         }
79     }
80
81     /**
82     * Get the string indicating how the user was authenticated.
83     * 
84     * Get the string indicating how the user was authenticated.
85     * Does not seem to be set - jbw
86     * @return string The method of authentication.
87     */
88     function auth_how() {
89         return $this->_authhow;
90     }
91
92     /**
93      * Invariant
94      * 
95      * If the WikiUser object has a valid authorization level and the 
96      * userid is a string returns true, else false.
97      * @return boolean If valid level and username string true, else false
98      */
99     function _ok () {
100         if ((in_array($this->_level, array(WIKIAUTH_BOGO,
101                                            WIKIAUTH_USER,
102                                            WIKIAUTH_ADMIN))
103             &&
104             (is_string($this->_userid)))) {
105             return true;
106         }
107         return false;
108     }
109
110     function getId () {
111         return ( $this->isSignedIn()
112                  ? $this->_userid
113                  : $this->_request->get('REMOTE_ADDR') ); // FIXME: globals
114     }
115
116     function getAuthenticatedId() {
117         return ( $this->isAuthenticated()
118                  ? $this->_userid
119                  : $this->_request->get('REMOTE_ADDR') ); // FIXME: globals
120     }
121
122     function isSignedIn () {
123         return $this->_level >= WIKIAUTH_BOGO;
124     }
125
126     function isAuthenticated () {
127         return $this->_level >= WIKIAUTH_USER;
128     }
129
130     function isAdmin () {
131         return $this->_level == WIKIAUTH_ADMIN;
132     }
133
134     function hasAuthority ($require_level) {
135         return $this->_level >= $require_level;
136     }
137
138     function AuthCheck ($postargs) {
139         // Normalize args, and extract.
140         $keys = array('userid', 'passwd', 'require_level', 'login', 'logout',
141                       'cancel');
142         foreach ($keys as $key)
143             $args[$key] = isset($postargs[$key]) ? $postargs[$key] : false;
144         extract($args);
145         $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
146
147         if ($logout)
148             return new WikiUser($this->_request); // Log out
149         elseif ($cancel)
150             return false;        // User hit cancel button.
151         elseif (!$login && !$userid)
152             return false;       // Nothing to do?
153
154         $authlevel = $this->_pwcheck($userid, $passwd);
155         if (!$authlevel)
156             return _("Invalid password or userid.");
157         elseif ($authlevel < $require_level)
158             return _("Insufficient permissions.");
159
160         // Successful login.
161         $user = new WikiUser($this->_request);
162         $user->_userid = $userid;
163         $user->_level = $authlevel;
164         return $user;
165     }
166
167     function PrintLoginForm (&$request, $args, $fail_message = false,
168                              $seperate_page = true) {
169         include_once('lib/Template.php');
170
171         $userid = '';
172         $require_level = 0;
173         extract($args); // fixme
174
175         $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
176
177         $pagename = $request->getArg('pagename');
178         $login = new Template('login', $request,
179                               compact('pagename', 'userid', 'require_level',
180                                       'fail_message', 'pass_required'));
181         if ($seperate_page) {
182             $top = new Template('html', $request,
183                                 array('TITLE' => _("Sign In")));
184             return $top->printExpansion($login);
185         } else {
186             return $login;
187         }
188     }
189
190     /**
191      * Check password.
192      */
193     function _pwcheck ($userid, $passwd) {
194         global $WikiNameRegexp;
195
196         if (!empty($userid) && $userid == ADMIN_USER) {
197             // $this->_authmethod = 'pagedata';
198             if (defined('ENCRYPTED_PASSWD') && ENCRYPTED_PASSWD)
199                 if ( !empty($passwd)
200                      && crypt($passwd, ADMIN_PASSWD) == ADMIN_PASSWD )
201                     return WIKIAUTH_ADMIN;
202                 else
203                     return false;
204             if (!empty($passwd)) {
205                 if ($passwd == ADMIN_PASSWD)
206                   return WIKIAUTH_ADMIN;
207                 else {
208                     // maybe we forgot to enable ENCRYPTED_PASSWD?
209                     if ( function_exists('crypt')
210                          && crypt($passwd, ADMIN_PASSWD) == ADMIN_PASSWD ) {
211                         trigger_error(_("You forgot to set ENCRYPTED_PASSWD to true. Please update your /index.php"),
212                                       E_USER_WARNING);
213                         return WIKIAUTH_ADMIN;
214                     }
215                 }
216             }
217             return false;
218         }
219         // HTTP Authentication
220         elseif (ALLOW_HTTP_AUTH_LOGIN && !empty($PHP_AUTH_USER)) {
221             // if he ignored the password field, because he is already
222             // authenticated try the previously given password.
223             if (empty($passwd))
224                 $passwd = $PHP_AUTH_PW;
225         }
226
227         // WikiDB_User DB/File Authentication from $DBAuthParams
228         // Check if we have the user. If not try other methods.
229         if (ALLOW_USER_LOGIN) { // && !empty($passwd)) {
230             $request = $this->_request;
231             // first check if the user is known
232             if ($this->exists($userid)) {
233                 $this->_authmethod = 'pagedata';
234                 return ($this->checkPassword($passwd)) ? WIKIAUTH_USER : false;
235             } else {
236                 // else try others such as LDAP authentication:
237                 if (ALLOW_LDAP_LOGIN && !empty($passwd)) {
238                     if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
239                         $r = @ldap_bind($ldap); // this is an anonymous bind
240                         $st_search = "uid=$userid";
241                         // Need to set the right root search information. see ../index.php
242                         $sr = ldap_search($ldap, LDAP_AUTH_SEARCH,
243                                           "$st_search");
244                         $info = ldap_get_entries($ldap, $sr); // there may be more hits with this userid. try every
245                         for ($i = 0; $i < $info["count"]; $i++) {
246                             $dn = $info[$i]["dn"];
247                             // The password is still plain text.
248                             if ($r = @ldap_bind($ldap, $dn, $passwd)) {
249                                 // ldap_bind will return TRUE if everything matches
250                                 ldap_close($ldap);
251                                 $this->_authmethod = 'LDAP';
252                                 return WIKIAUTH_USER;
253                             }
254                         }
255                     } else {
256                         trigger_error("Unable to connect to LDAP server "
257                                       . LDAP_AUTH_HOST, E_USER_WARNING);
258                     }
259                 }
260                 // imap authentication. added by limako
261                 if (ALLOW_IMAP_LOGIN && !empty($passwd)) {
262                     $mbox = @imap_open( "{" . IMAP_AUTH_HOST . ":143}",
263                                         $userid, $passwd, OP_HALFOPEN );
264                     if($mbox) {
265                         imap_close($mbox);
266                         $this->_authmethod = 'IMAP';
267                         return WIKIAUTH_USER;
268                     }
269                 }
270             }
271         }
272         if ( ALLOW_BOGO_LOGIN
273              && preg_match('/\A' . $WikiNameRegexp . '\z/', $userid) ) {
274             $this->_authmethod = 'BOGO';
275             return WIKIAUTH_BOGO;
276         }
277         return false;
278     }
279
280     // Todo: try our WikiDB backends.
281     function getPreferences() {
282         // Restore saved preferences.
283
284         // I'd rather prefer only to store the UserId in the cookie or
285         // session, and get the preferences from the db or page.
286         if (!($prefs = $this->_request->getCookieVar('WIKI_PREFS2')))
287             $prefs = $this->_request->getSessionVar('wiki_prefs');
288
289         //if (!$this->_userid && !empty($GLOBALS['HTTP_COOKIE_VARS']['WIKI_ID'])) {
290         //    $this->_userid = $GLOBALS['HTTP_COOKIE_VARS']['WIKI_ID'];
291         //}
292
293         // before we get his prefs we should check if he is signed in
294         if (USE_PREFS_IN_PAGE && $this->homePage()) { // in page metadata
295             if ($pref = $this->_homepage->get('pref')) {
296                 //trigger_error("pref=".$pref);//debugging
297                 $prefs = unserialize($pref);
298             }
299         }
300         return new UserPreferences($prefs);
301     }
302
303     // No cookies anymore for all prefs, only the userid. PHP creates
304     // a session cookie in memory, which is much more efficient.
305     //
306     // Return the number of changed entries?
307     function setPreferences($prefs, $id_only = false) {
308         // update the id
309         $this->_request->setSessionVar('wiki_prefs', $prefs);
310         // $this->_request->setCookieVar('WIKI_PREFS2', $this->_prefs, 365);
311         // simple unpacked cookie
312         if ($this->_userid) setcookie('WIKI_ID', $this->_userid, 365, '/');
313
314         // We must ensure that any password is encrypted.
315         // We don't need any plaintext password.
316         if (! $id_only ) {
317             if ($this->isSignedIn()) {
318                 if ($this->isAdmin())
319                     $prefs->set('passwd', '');
320                 // already stored in index.php, and it might be
321                 // plaintext! well oh well
322                 if ($homepage = $this->homePage()) {
323                     $homepage->set('pref', serialize($prefs->_prefs));
324                     return sizeof($prefs->_prefs);
325                 } else {
326                     trigger_error("No homepage for user found. Creating one...",
327                                   E_USER_WARNING);
328                     $this->createHomepage($prefs);
329                     //$homepage->set('pref', serialize($prefs->_prefs));
330                     return sizeof($prefs->_prefs);
331                 }
332             } else {
333                 trigger_error("you must be signed in", E_USER_WARNING);
334             }
335         }
336         return 0;
337     }
338
339     // check for homepage with user flag.
340     // can be overriden from the auth backends
341     function exists() {
342         $homepage = $this->homePage();
343         return ($this->_userid && $homepage && $homepage->get('pref'));
344     }
345
346     // doesn't check for existance!!! hmm.
347     // how to store metadata in not existing pages? how about versions?
348     function homePage() {
349         if (!$this->_userid)
350             return false;
351         if (!empty($this->_homepage)) {
352             return $this->_homepage;
353         } else {
354             $this->_homepage = $this->_dbi->getPage($this->_userid);
355             return $this->_homepage;
356         }
357     }
358
359     // create user by checking his homepage
360     function createUser ($pref, $createDefaultHomepage = true) {
361         if ($this->exists())
362             return;
363         if ($createDefaultHomepage) {
364             $this->createHomepage($pref);
365         } else {
366             // empty page
367             include "lib/loadsave.php";
368             $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)),
369                               'versiondata' => array('author' => $this->_userid),
370                               'pagename' => $this->_userid,
371                               'content' => _('CategoryHomepage'));
372             SavePage ($this->_request, $pageinfo, false, false);
373         }
374         $this->setPreferences($pref);
375     }
376
377     // create user and default user homepage
378     function createHomepage ($pref) {
379         $pagename = $this->_userid;
380         include "lib/loadsave.php";
381
382         // create default homepage:
383         //  properly expanded template and the pref metadata
384         $template = Template('homepage.tmpl', $this->_request);
385         $text  = $template->getExpansion();
386         $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)),
387                           'versiondata' => array('author' => $this->_userid),
388                           'pagename' => $pagename,
389                           'content' => $text);
390         SavePage ($this->_request, $pageinfo, false, false);
391
392         // create Calender
393         $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Preferences');
394         if (! isWikiPage($pagename)) {
395             $pageinfo = array('pagedata' => array(),
396                               'versiondata' => array('author' => $this->_userid),
397                               'pagename' => $pagename,
398                               'content' => "<?plugin Calender ?>\n");
399             SavePage ($this->_request, $pageinfo, false, false);
400         }
401
402         // create Preferences
403         $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Preferences');
404         if (! isWikiPage($pagename)) {
405             $pageinfo = array('pagedata' => array(),
406                               'versiondata' => array('author' => $this->_userid),
407                               'pagename' => $pagename,
408                               'content' => "<?plugin UserPreferences ?>\n");
409             SavePage ($this->_request, $pageinfo, false, false);
410         }
411     }
412
413     function tryAuthBackends() {
414         return ''; // crypt('') will never be ''
415     }
416
417     // Auth backends must store the crypted password where?
418     // Not in the preferences.
419     function checkPassword($passwd) {
420         $prefs = $this->getPreferences();
421         $stored_passwd = $prefs->get('passwd'); // crypted
422         if (empty($prefs->_prefs['passwd']))    // not stored in the page
423             // allow empty passwords? At least store a '*' then.
424             // try other backend. hmm.
425             $stored_passwd = $this->tryAuthBackends($this->_userid);
426         if (empty($stored_passwd)) {
427             trigger_error(sprintf(_("Old UserPage %s without stored password updated with empty password. Set a password in your UserPreferences."),
428                                   $this->_userid), E_USER_NOTICE);
429             $prefs->set('passwd','*');
430             return true;
431         }
432         if ($stored_passwd == '*')
433             return true;
434         if ( !empty($passwd)
435              && crypt($passwd, $stored_passwd) == $stored_passwd )
436             return true;
437         else
438             return false;
439     }
440
441     function changePassword($newpasswd, $passwd2 = false) {
442         if (! $this->mayChangePassword() ) {
443             trigger_error(sprintf("Attempt to change an external password for '%s'. Not allowed!",
444                                   $this->_userid), E_USER_ERROR);
445             return;
446         }
447         if ($passwd2 && $passwd2 != $newpasswd) {
448             trigger_error("The second password must be the same as the first to change it",
449                           E_USER_ERROR);
450             return;
451         }
452         $prefs = $this->getPreferences();
453         //$oldpasswd = $prefs->get('passwd');
454         $prefs->set('passwd', crypt($newpasswd));
455         $this->setPreferences($prefs);
456     }
457
458     function mayChangePassword() {
459         // on external DBAuth maybe. on IMAP or LDAP not
460         // on internal DBAuth yes
461         if (in_array($this->_authmethod, array('IMAP', 'LDAP')))
462             return false;
463         if ($this->isAdmin())
464             return false;
465         if ($this->_authmethod == 'pagedata')
466             return true;
467         if ($this->_authmethod == 'authdb')
468             return true;
469     }
470                          }
471
472 // create user and default user homepage
473 // FIXME: delete this, not used?
474 /*
475 function createUser ($userid, $pref) {
476     global $request;
477     $user = new WikiUser ($request, $userid);
478     $user->createUser($pref);
479 }
480 */
481
482 class _UserPreference
483 {
484     function _UserPreference ($default_value) {
485         $this->default_value = $default_value;
486     }
487
488     function sanify ($value) {
489         return (string)$value;
490     }
491
492     function update ($value) {
493     }
494 }
495
496 class _UserPreference_numeric
497 extends _UserPreference
498 {
499     function _UserPreference_numeric ($default, $minval = false,
500                                       $maxval = false) {
501         $this->_UserPreference((double)$default);
502         $this->_minval = (double)$minval;
503         $this->_maxval = (double)$maxval;
504     }
505
506     function sanify ($value) {
507         $value = (double)$value;
508         if ($this->_minval !== false && $value < $this->_minval)
509             $value = $this->_minval;
510         if ($this->_maxval !== false && $value > $this->_maxval)
511             $value = $this->_maxval;
512         return $value;
513     }
514 }
515
516 class _UserPreference_int
517 extends _UserPreference_numeric
518 {
519     function _UserPreference_int ($default, $minval = false, $maxval = false) {
520         $this->_UserPreference_numeric((int)$default, (int)$minval,
521                                        (int)$maxval);
522     }
523
524     function sanify ($value) {
525         return (int)parent::sanify((int)$value);
526     }
527 }
528
529 class _UserPreference_bool
530 extends _UserPreference
531 {
532     function _UserPreference_bool ($default = false) {
533         $this->_UserPreference((bool)$default);
534     }
535
536     function sanify ($value) {
537         if (is_array($value)) {
538             /* This allows for constructs like:
539              *
540              *   <input type="hidden" name="pref[boolPref][]" value="0" />
541              *   <input type="checkbox" name="pref[boolPref][]" value="1" />
542              *
543              * (If the checkbox is not checked, only the hidden input
544              * gets sent. If the checkbox is sent, both inputs get
545              * sent.)
546              */
547             foreach ($value as $val) {
548                 if ($val)
549                     return true;
550             }
551             return false;
552         }
553         return (bool) $value;
554     }
555 }
556
557 class _UserPreference_language
558 extends _UserPreference
559 {
560     function _UserPreference_language ($default = DEFAULT_LANGUAGE) {
561         $this->_UserPreference($default);
562     }
563
564     function sanify ($value) {
565         // FIXME: check for valid locale
566         return (string) $value;
567     }
568 }
569
570 class _UserPreference_theme
571 extends _UserPreference
572 {
573     function _UserPreference_theme ($default = THEME) {
574         $this->_UserPreference($default);
575     }
576
577     function sanify ($value) {
578         if (file_exists($this->_themefile($value)))
579             return $value;
580         return $this->default_value;
581     }
582
583     function update ($newvalue) {
584         global $Theme;
585         include_once($this->_themefile($newvalue));
586         if (empty($Theme))
587             include_once($this->_themefile(THEME));
588     }
589
590     function _themefile ($theme) {
591         return "themes/$theme/themeinfo.php";
592     }
593 }
594
595 // don't save default preferences for efficiency.
596 class UserPreferences {
597     function UserPreferences ($saved_prefs = false) {
598         $this->_prefs = array();
599
600         if (isa($saved_prefs, 'UserPreferences') && $saved_prefs->_prefs) {
601             foreach ($saved_prefs->_prefs as $name => $value)
602                 $this->set($name, $value);
603         } elseif (is_array($saved_prefs)) {
604             foreach ($saved_prefs as $name => $value)
605                 $this->set($name, $value);
606         }
607     }
608
609     function _getPref ($name) {
610         global $UserPreferences;
611         if (!isset($UserPreferences[$name])) {
612             if ($name == 'passwd2') return false;
613             trigger_error("$name: unknown preference", E_USER_NOTICE);
614             return false;
615         }
616         return $UserPreferences[$name];
617     }
618
619     function get ($name) {
620         if (isset($this->_prefs[$name]))
621             return $this->_prefs[$name];
622         if (!($pref = $this->_getPref($name)))
623             return false;
624         return $pref->default_value;
625     }
626
627     function set ($name, $value) {
628         if (!($pref = $this->_getPref($name)))
629             return false;
630
631         $newvalue = $pref->sanify($value);
632         $oldvalue = $this->get($name);
633
634         // update on changes
635         if ($newvalue != $oldvalue)
636             $pref->update($newvalue);
637
638         // don't set default values to save space (in cookies, db and
639         // sesssion)
640         if ($value == $pref->default_value)
641             unset($this->_prefs[$name]);
642         else
643             $this->_prefs[$name] = $newvalue;
644     }
645
646     function hash () {
647         return hash($this->_prefs);
648     }
649 }
650
651 // $Log: not supported by cvs2svn $
652 // Revision 1.38  2003/09/13 22:25:38  carstenklapp
653 // Hook for new user preference 'noLinkIcons'.
654 //
655 // Revision 1.37  2003/02/22 20:49:55  dairiki
656 // Fixes for "Call-time pass by reference has been deprecated" errors.
657 //
658 // Revision 1.36  2003/02/21 22:50:51  dairiki
659 // Ensure that language preference is a string.
660 //
661 // Revision 1.35  2003/02/16 20:04:47  dairiki
662 // Refactor the HTTP validator generation/checking code.
663 //
664 // This also fixes a number of bugs with yesterdays validator mods.
665 //
666 // Revision 1.34  2003/02/15 02:21:54  dairiki
667 // API Change!  Explicit $request argument added to contructor for WikiUser.
668 //
669 // This seemed the best way to fix a problem whereby the WikiDB
670 // was being opened twice.  (Which while being merely inefficient
671 // when using an SQL backend causes hangage when using a dba backend.)
672 //
673 // Revision 1.33  2003/01/22 03:21:40  zorloc
674 // Modified WikiUser constructor to move the DB request for the homepage to
675 // the end of the logic to prevent it from being requested and then dropped.
676 // Added more phpdoc comments.
677 //
678 // Revision 1.32  2003/01/21 07:40:50  zorloc
679 // Modified WikiUser::_ok() -- Inverted the logic so the default is to return
680 // false and to return true only in the desired condition.  Added phpdoc
681 // comments
682 //
683 // Revision 1.31  2003/01/15 05:37:20  carstenklapp
684 // code reformatting
685 //
686 // Revision 1.30  2003/01/15 04:59:27  carstenklapp
687 // Bugfix: Previously stored preferences were not loading when user
688 // signed in. (Fixed... I hope.)
689 //
690
691 // Local Variables:
692 // mode: php
693 // tab-width: 8
694 // c-basic-offset: 4
695 // c-hanging-comment-ender-p: nil
696 // indent-tabs-mode: nil
697 // End:
698 ?>