]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiUser.php
Modified WikiUser constructor to move the DB request for the homepage to
[SourceForge/phpwiki.git] / lib / WikiUser.php
1 <?php //-*-php-*-
2 rcs_id('$Id: WikiUser.php,v 1.33 2003-01-22 03:21:40 zorloc 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 ($userid = false, $authlevel = false) {
57         $this->_request = &$GLOBALS['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; // 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;
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 function createUser ($userid, $pref) {
471     $user = new WikiUser ($userid);
472     $user->createUser($pref);
473 }
474
475 class _UserPreference
476 {
477     function _UserPreference ($default_value) {
478         $this->default_value = $default_value;
479     }
480
481     function sanify ($value) {
482         return (string)$value;
483     }
484
485     function update ($value) {
486     }
487 }
488
489 class _UserPreference_numeric
490 extends _UserPreference
491 {
492     function _UserPreference_numeric ($default, $minval = false,
493                                       $maxval = false) {
494         $this->_UserPreference((double)$default);
495         $this->_minval = (double)$minval;
496         $this->_maxval = (double)$maxval;
497     }
498
499     function sanify ($value) {
500         $value = (double)$value;
501         if ($this->_minval !== false && $value < $this->_minval)
502             $value = $this->_minval;
503         if ($this->_maxval !== false && $value > $this->_maxval)
504             $value = $this->_maxval;
505         return $value;
506     }
507 }
508
509 class _UserPreference_int
510 extends _UserPreference_numeric
511 {
512     function _UserPreference_int ($default, $minval = false, $maxval = false) {
513         $this->_UserPreference_numeric((int)$default, (int)$minval,
514                                        (int)$maxval);
515     }
516
517     function sanify ($value) {
518         return (int)parent::sanify((int)$value);
519     }
520 }
521
522 class _UserPreference_bool
523 extends _UserPreference
524 {
525     function _UserPreference_bool ($default = false) {
526         $this->_UserPreference((bool)$default);
527     }
528
529     function sanify ($value) {
530         if (is_array($value)) {
531             /* This allows for constructs like:
532              *
533              *   <input type="hidden" name="pref[boolPref][]" value="0" />
534              *   <input type="checkbox" name="pref[boolPref][]" value="1" />
535              *
536              * (If the checkbox is not checked, only the hidden input
537              * gets sent. If the checkbox is sent, both inputs get
538              * sent.)
539              */
540             foreach ($value as $val) {
541                 if ($val)
542                     return true;
543             }
544             return false;
545         }
546         return (bool) $value;
547     }
548 }
549
550 class _UserPreference_language
551 extends _UserPreference
552 {
553     function _UserPreference_language ($default = DEFAULT_LANGUAGE) {
554         $this->_UserPreference($default);
555     }
556
557     function sanify ($value) {
558         // FIXME: check for valid locale
559         return $value;
560     }
561 }
562
563 class _UserPreference_theme
564 extends _UserPreference
565 {
566     function _UserPreference_theme ($default = THEME) {
567         $this->_UserPreference($default);
568     }
569
570     function sanify ($value) {
571         if (file_exists($this->_themefile($value)))
572             return $value;
573         return $this->default_value;
574     }
575
576     function update ($newvalue) {
577         global $Theme;
578         include_once($this->_themefile($newvalue));
579         if (empty($Theme))
580             include_once($this->_themefile(THEME));
581     }
582
583     function _themefile ($theme) {
584         return "themes/$theme/themeinfo.php";
585     }
586 }
587
588 // don't save default preferences for efficiency.
589 class UserPreferences {
590     function UserPreferences ($saved_prefs = false) {
591         $this->_prefs = array();
592
593         if (isa($saved_prefs, 'UserPreferences') && $saved_prefs->_prefs) {
594             foreach ($saved_prefs->_prefs as $name => $value)
595                 $this->set($name, $value);
596         } elseif (is_array($saved_prefs)) {
597             foreach ($saved_prefs as $name => $value)
598                 $this->set($name, $value);
599         }
600     }
601
602     function _getPref ($name) {
603         global $UserPreferences;
604         if (!isset($UserPreferences[$name])) {
605             if ($name == 'passwd2') return false;
606             trigger_error("$name: unknown preference", E_USER_NOTICE);
607             return false;
608         }
609         return $UserPreferences[$name];
610     }
611
612     function get ($name) {
613         if (isset($this->_prefs[$name]))
614             return $this->_prefs[$name];
615         if (!($pref = $this->_getPref($name)))
616             return false;
617         return $pref->default_value;
618     }
619
620     function set ($name, $value) {
621         if (!($pref = $this->_getPref($name)))
622             return false;
623
624         $newvalue = $pref->sanify($value);
625         $oldvalue = $this->get($name);
626
627         // update on changes
628         if ($newvalue != $oldvalue)
629             $pref->update($newvalue);
630
631         // don't set default values to save space (in cookies, db and
632         // sesssion)
633         if ($value == $pref->default_value)
634             unset($this->_prefs[$name]);
635         else
636             $this->_prefs[$name] = $newvalue;
637     }
638 }
639
640 // $Log: not supported by cvs2svn $
641 // Revision 1.32  2003/01/21 07:40:50  zorloc
642 // Modified WikiUser::_ok() -- Inverted the logic so the default is to return
643 // false and to return true only in the desired condition.  Added phpdoc
644 // comments
645 //
646 // Revision 1.31  2003/01/15 05:37:20  carstenklapp
647 // code reformatting
648 //
649 // Revision 1.30  2003/01/15 04:59:27  carstenklapp
650 // Bugfix: Previously stored preferences were not loading when user
651 // signed in. (Fixed... I hope.)
652 //
653
654 // Local Variables:
655 // mode: php
656 // tab-width: 8
657 // c-basic-offset: 4
658 // c-hanging-comment-ender-p: nil
659 // indent-tabs-mode: nil
660 // End:
661 ?>