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