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