]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiUser.php
Again with the missing underscore!
[SourceForge/phpwiki.git] / lib / WikiUser.php
1 <?php rcs_id('$Id: WikiUser.php,v 1.21 2002-08-30 04:49:59 wainstead Exp $');
2
3 // It is anticipated that when userid support is added to phpwiki,
4 // this object will hold much more information (e-mail, home(wiki)page,
5 // etc.) about the user.
6    
7 // There seems to be no clean way to "log out" a user when using
8 // HTTP authentication.
9 // So we'll hack around this by storing the currently logged
10 // in username and other state information in a cookie.
11
12 define('WIKIAUTH_ANON', 0);
13 define('WIKIAUTH_BOGO', 1);     // any valid WikiWord is enough
14 define('WIKIAUTH_USER', 2);     // real auth from a database/file/server.
15
16 define('WIKIAUTH_ADMIN', 10);
17 define('WIKIAUTH_FORBIDDEN', 11); // Completely not allowed.
18
19 $UserPreferences = array(
20                          'userid'        => new _UserPreference(''), // really store this also?
21                          'passwd'        => new _UserPreference(''),
22                          'email'         => new _UserPreference(''),
23                          'emailVerified' => new _UserPreference_bool(),
24                          'notifyPages'   => new _UserPreference(''),
25                          'theme'         => new _UserPreference(THEME),
26                          'lang'          => new _UserPreference($LANG),
27                          'editWidth'     => new _UserPreference_int(80, 30, 150),
28                          'editHeight'    => new _UserPreference_int(22, 5, 80),
29                          'timeOffset'    => new _UserPreference_numeric(0, -26, 26),
30                          'relativeDates' => new _UserPreference_bool()
31                          );
32
33 class WikiUser {
34     var $_userid = false;
35     var $_level  = false;
36     var $_request, $_dbi, $_authdbi, $_homepage;
37     var $_authmethod = '', $_authhow = '';
38
39     /**
40      * Constructor.
41      */
42     function WikiUser ($userid = false, $authlevel = false) {
43         $this->_request = &$GLOBALS['request'];
44         $this->_dbi = &$this->_request->getDbh();
45
46         if (isa($userid, 'WikiUser')) {
47             $this->_userid   = $userid->_userid;
48             $this->_level    = $userid->_level;
49         }
50         else {
51             $this->_userid = $userid;
52             $this->_level = $authlevel;
53         }
54         if ($this->_userid)
55             $this->_homepage = $this->_dbi->getPage($this->_userid);
56         if (!$this->_ok()) {
57             // Paranoia: if state is at all inconsistent, log out...
58             $this->_userid = false;
59             $this->_level = false;
60             $this->_homepage = false;
61             $this->_authhow .= ' paranoia logout';
62         }
63     }
64
65     function auth_how() {
66         return $this->_authhow;
67     }
68
69     /** Invariant
70      */
71     function _ok () {
72         if (empty($this->_userid) || empty($this->_level)) {
73             // This is okay if truly logged out.
74             return $this->_userid === false && $this->_level === false;
75         }
76         // User is logged in...
77         
78         // Check for valid authlevel.
79         if (!in_array($this->_level, array(WIKIAUTH_BOGO, WIKIAUTH_USER, WIKIAUTH_ADMIN)))
80             return false;
81
82         // Check for valid userid.
83         if (!is_string($this->_userid))
84             return false;
85         return true;
86     }
87
88     function getId () {
89         return ( $this->isSignedIn()
90                  ? $this->_userid
91                  : $this->_request->get('REMOTE_ADDR') ); // FIXME: globals
92     }
93
94     function getAuthenticatedId() {
95         return ( $this->isAuthenticated()
96                  ? $this->_userid
97                  : $this->_request->get('REMOTE_ADDR') ); // FIXME: globals
98     }
99
100     function isSignedIn () {
101         return $this->_level >= WIKIAUTH_BOGO;
102     }
103         
104     function isAuthenticated () {
105         return $this->_level >= WIKIAUTH_USER;
106     }
107          
108     function isAdmin () {
109         return $this->_level == WIKIAUTH_ADMIN;
110     }
111
112     function hasAuthority ($require_level) {
113         return $this->_level >= $require_level;
114     }
115
116     
117     function AuthCheck ($postargs) {
118         // Normalize args, and extract.
119         $keys = array('userid', 'passwd', 'require_level', 'login', 'logout', 'cancel');
120         foreach ($keys as $key) 
121             $args[$key] = isset($postargs[$key]) ? $postargs[$key] : false;
122         extract($args);
123         $require_level = max(0, min(WIKIAUTH_ADMIN, (int) $require_level));
124
125         if ($logout)
126             return new WikiUser; // Log out
127         elseif ($cancel)
128             return false;        // User hit cancel button.
129         elseif (!$login && !$userid)
130             return false;       // Nothing to do?
131
132         $authlevel = $this->_pwcheck($userid, $passwd);
133         if (!$authlevel)
134             return _("Invalid password or userid.");
135         elseif ($authlevel < $require_level)
136             return _("Insufficient permissions.");
137
138         // Successful login.
139         $user = new WikiUser;
140         $user->_userid = $userid;
141         $user->_level = $authlevel;
142         return $user;
143     }
144     
145     function PrintLoginForm (&$request, $args, $fail_message = false, $seperate_page = true) {
146         include_once('lib/Template.php');
147         
148         $userid = '';
149         $require_level = 0;
150         extract($args); // fixme
151         
152         $require_level = max(0, min(WIKIAUTH_ADMIN, (int) $require_level));
153         
154         $pagename = $request->getArg('pagename');
155         $login = new Template('login', $request,
156                               compact('pagename', 'userid', 'require_level', 'fail_message', 'pass_required'));
157         if ($seperate_page) {
158             $top = new Template('html', $request, array('TITLE' =>  _("Sign In")));
159             return $top->printExpansion($login);
160         } else {
161             return $login;
162         }
163     }
164         
165     /**
166      * Check password.
167      */
168     function _pwcheck ($userid, $passwd) {
169         global $WikiNameRegexp;
170         
171         if (!empty($userid) && $userid == ADMIN_USER) {
172             // $this->_authmethod = 'pagedata';
173             if (defined('ENCRYPTED_PASSWD') && ENCRYPTED_PASSWD)
174                 if (!empty($passwd) && crypt($passwd, ADMIN_PASSWD) == ADMIN_PASSWD)
175                     return WIKIAUTH_ADMIN;
176             if (!empty($passwd)) {
177                 if ($passwd == ADMIN_PASSWD)
178                   return WIKIAUTH_ADMIN;
179                 else {
180                     // maybe we forgot to enable ENCRYPTED_PASSWD?
181                     if (function_exists('crypt') and crypt($passwd, ADMIN_PASSWD) == ADMIN_PASSWD) {
182                         trigger_error(_("You forgot to set ENCRYPTED_PASSWD to true. Please update your /index.php"), E_USER_WARNING);
183                         return WIKIAUTH_ADMIN;
184                     }
185                 }
186             }
187             return false;
188         }
189         // HTTP Authentification
190         elseif (ALLOW_HTTP_AUTH_LOGIN and !empty($PHP_AUTH_USER)) {
191             // if he ignored the password field, because he is already authentificated
192             // try the previously given password.
193             if (empty($passwd)) $passwd = $PHP_AUTH_PW;
194         }
195
196         // WikiDB_User DB/File Authentification from $DBAuthParams 
197         // Check if we have the user. If not try other methods.
198         if (ALLOW_USER_LOGIN) { // and !empty($passwd)) {
199             $request = $this->_request;
200             // first check if the user is known
201             if ($this->exists($userid)) {
202                 $this->_authmethod = 'pagedata';
203                 return ($this->checkPassword($passwd)) ? WIKIAUTH_USER : false;
204             } else {
205                 // else try others such as LDAP authentication:
206                 if (ALLOW_LDAP_LOGIN and !empty($passwd)) {
207                     if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
208                         $r = @ldap_bind($ldap); // this is an anonymous bind
209                         $st_search = "uid=$userid";
210                         // Need to set the right root search information. see ../index.php
211                         $sr = ldap_search($ldap, LDAP_AUTH_SEARCH, "$st_search");  
212                         $info = ldap_get_entries($ldap, $sr); // there may be more hits with this userid. try every
213                         for ($i=0; $i<$info["count"]; $i++) {
214                             $dn = $info[$i]["dn"];
215                             // The password is still plain text.
216                             if ($r = @ldap_bind($ldap, $dn, $passwd)) {
217                                 // ldap_bind will return TRUE if everything matches
218                                 ldap_close($ldap);
219                                 $this->_authmethod = 'LDAP';
220                                 return WIKIAUTH_USER;
221                             }
222                         }
223                     } else {
224                         trigger_error("Unable to connect to LDAP server " . LDAP_AUTH_HOST, E_USER_WARNING);
225                     }
226                 }
227                 // imap authentication. added by limako
228                 if (ALLOW_IMAP_LOGIN and !empty($passwd)) {
229                     $mbox = @imap_open( "{" . IMAP_AUTH_HOST . ":143}", $userid, $passwd, OP_HALFOPEN );
230                     if( $mbox ) {
231                         imap_close( $mbox );
232                         $this->_authmethod = 'IMAP';
233                         return WIKIAUTH_USER;
234                     }
235                 }
236             }
237         }
238         if (ALLOW_BOGO_LOGIN
239                 && preg_match('/\A' . $WikiNameRegexp . '\z/', $userid)) {
240             $this->_authmethod = 'BOGO';
241             return WIKIAUTH_BOGO;
242         }
243         return false;
244     }
245
246     // Todo: try our WikiDB backends.
247     function getPreferences() {
248         // Restore saved preferences.
249         // I'd rather prefer only to store the UserId in the cookie or session,
250         // and get the preferences from the db or page.
251         if (!($prefs = $this->_request->getCookieVar('WIKI_PREFS2')))
252             $prefs = $this->_request->getSessionVar('wiki_prefs');
253
254         if (!$this->_userid and !empty($GLOBALS['HTTP_COOKIE_VARS']['WIKI_ID'])) {
255             $this->_userid = $GLOBALS['HTTP_COOKIE_VARS']['WIKI_ID'];
256         }
257
258         // before we get his prefs we should check if he is signed in
259         if (!$prefs->_prefs and USE_PREFS_IN_PAGE and $this->homePage()) { // in page metadata
260             if ($pref = $this->_homepage->get('pref'))
261                 $prefs = unserialize($pref);
262         }
263         return new UserPreferences($prefs);
264     }
265
266     // No cookies anymore for all prefs, only the userid.
267     // PHP creates a session cookie in memory, which is much more efficient.
268     //
269     // Return the number of changed entries?
270     function setPreferences($prefs, $id_only = false) {
271         // update the id
272         $this->_request->setSessionVar('wiki_prefs', $prefs);
273         // $this->_request->setCookieVar('WIKI_PREFS2', $this->_prefs, 365);
274         // simple unpacked cookie
275         if ($this->_userid) setcookie('WIKI_ID', $this->_userid, 365, '/');
276
277         // We must ensure that any password is encrypted. 
278         // We don't need any plaintext password.
279         if (! $id_only ) {
280             if ($this->isSignedIn()) {
281                 if ($this->isAdmin()) $prefs->set('passwd',''); // this is already stored in index.php, 
282                 // and it might be plaintext! well oh well
283                 if ($homepage = $this->homePage()) {
284                     $homepage->set('pref',serialize($prefs->_prefs));
285                     return sizeof($prefs->_prefs);
286                 } else {
287                     trigger_error('No homepage for user found. Creating one...', E_USER_WARNING);
288                     $this->createHomepage($prefs);
289                     //$homepage->set('pref',serialize($prefs->_prefs));
290                     return sizeof($prefs->_prefs);
291                 }
292             } else {
293                 trigger_error('you must be signed in',E_USER_WARNING);
294             }
295         }
296         return 0;
297     }
298
299     // check for homepage with user flag.
300     // can be overriden from the auth backends
301     function exists() {
302         $homepage = $this->homePage();
303         return ($this->_userid and $homepage and $homepage->get('pref'));
304     }
305
306     // doesn't check for existance!!! hmm. 
307     // how to store metadata in not existing pages? how about versions?
308     function homePage() {
309         if (!$this->_userid) return false;
310         if ($this->_homepage) 
311             return $this->_homepage;
312         else {
313             $this->_homepage = $this->_dbi->getPage($this->_userid);
314             return $this->_homepage;
315         }
316     }
317
318     // create user by checking his homepage
319     function createUser ($pref, $createDefaultHomepage = true) {
320         if ($this->exists()) return;
321         if ($createDefaultHomepage) {
322             $this->createHomepage ($pref);
323         } else {
324             // empty page
325             include "lib/loadsave.php";
326             $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)),
327                               'versiondata' => array('author' => $this->_userid),
328                               'pagename' => $this->_userid,
329                               'content' => _('CategoryHomepage'));
330             SavePage (&$this->_request, $pageinfo, false, false);
331         }
332         $this->setPreferences($pref);
333     }
334
335     // create user and default user homepage
336     function createHomepage ($pref) {
337         $pagename = $this->_userid;
338         include "lib/loadsave.php";
339
340         // create default homepage:
341         //  properly expanded template and the pref metadata
342         $template = Template('homepage.tmpl',$this->_request);
343         $text  = $template->getExpansion();
344         $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)),
345                           'versiondata' => array('author' => $this->_userid),
346                           'pagename' => $pagename,
347                           'content' => $text);
348         SavePage (&$this->_request, $pageinfo, false, false);
349             
350         // create Calender
351         $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Preferences');
352         if (! isWikiPage($pagename)) {
353             $pageinfo = array('pagedata' => array(),
354                               'versiondata' => array('author' => $this->_userid),
355                               'pagename' => $pagename,
356                               'content' => "<?plugin Calender ?>\n");
357             SavePage (&$this->_request, $pageinfo, false, false);
358         }
359
360         // create Preferences
361         $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Preferences');
362         if (! isWikiPage($pagename)) {
363             $pageinfo = array('pagedata' => array(),
364                               'versiondata' => array('author' => $this->_userid),
365                               'pagename' => $pagename,
366                               'content' => "<?plugin UserPreferences ?>\n");
367             SavePage (&$this->_request, $pageinfo, false, false);
368         }
369     }
370
371     function tryAuthBackends() {
372         return ''; // crypt('') will never be ''
373     }
374
375     // Auth backends must store the crypted password where?
376     // Not in the preferences.
377     function checkPassword($passwd) {
378         $prefs = $this->getPreferences();
379         $stored_passwd = $prefs->get('passwd'); // crypted
380         if (empty($prefs->_prefs['passwd']))    // not stored in the page
381             // allow empty passwords? At least store a '*' then.
382             // try other backend. hmm.
383             $stored_passwd = $this->tryAuthBackends($this->_userid);
384         if (empty($stored_passwd)) {
385             trigger_error(sprintf(_("Old UserPage %s without stored password updated with empty password. Set a password in your UserPreferences."), $this->_userid), E_USER_NOTICE);
386             $prefs->set('passwd','*'); 
387             return true;
388         }
389         if ($stored_passwd == '*')
390             return true;
391         if (!empty($passwd) && crypt($passwd, $stored_passwd) == $stored_passwd)
392             return true;
393         else         
394             return false;
395     }
396
397     function changePassword($newpasswd, $passwd2 = false) {
398         if (! $this->mayChangePassword() ) {
399             trigger_error(sprintf("Attempt to change an external password for '%s'. Not allowed!",
400                                   $this->_userid), E_USER_ERROR);
401             return;
402         }
403         if ($passwd2 and $passwd2 != $newpasswd) {
404             trigger_error("The second passwort must be the same as the first to change it", E_USER_ERROR);
405             return;
406         }
407         $prefs = $this->getPreferences();
408         //$oldpasswd = $prefs->get('passwd');
409         $prefs->set('passwd', crypt($newpasswd));
410         $this->setPreferences($prefs);
411     }
412
413     function mayChangePassword() {
414         // on external DBAuth maybe. on IMAP or LDAP not
415         // on internal DBAuth yes
416         if (in_array($this->_authmethod, array('IMAP', 'LDAP'))) 
417             return false;
418         if ($this->isAdmin()) 
419             return false;
420         if ($this->_authmethod == 'pagedata')
421             return true;
422         if ($this->_authmethod == 'authdb')
423             return true;
424     }
425 }
426
427 // create user and default user homepage
428 function createUser ($userid, $pref) {
429     $user = new WikiUser ($userid);
430     $user->createUser($pref);
431 }
432
433 class _UserPreference 
434 {
435     function _UserPreference ($default_value) {
436         $this->default_value = $default_value;
437     }
438
439     function sanify ($value) {
440         return (string) $value;
441     }
442 }
443
444 class _UserPreference_numeric extends _UserPreference
445 {
446     function _UserPreference_numeric ($default, $minval = false, $maxval = false) {
447         $this->_UserPreference((double) $default);
448         $this->_minval = (double) $minval;
449         $this->_maxval = (double) $maxval;
450     }
451
452     function sanify ($value) {
453         $value = (double) $value;
454         if ($this->_minval !== false && $value < $this->_minval)
455             $value = $this->_minval;
456         if ($this->_maxval !== false && $value > $this->_maxval)
457             $value = $this->_maxval;
458         return $value;
459     }
460 }
461
462 class _UserPreference_int extends _UserPreference_numeric
463 {
464     function _UserPreference_int ($default, $minval = false, $maxval = false) {
465         $this->_UserPreference_numeric((int) $default, (int)$minval, (int)$maxval);
466     }
467
468     function sanify ($value) {
469         return (int) parent::sanify((int)$value);
470     }
471 }
472
473 class _UserPreference_bool extends _UserPreference
474 {
475     function _UserPreference_bool ($default = false) {
476         $this->_UserPreference((bool) $default);
477     }
478
479     function sanify ($value) {
480         if (is_array($value)) {
481             /* This allows for constructs like:
482              *
483              *   <input type="hidden" name="pref[boolPref][]" value="0" />
484              *   <input type="checkbox" name="pref[boolPref][]" value="1" />
485              *
486              * (If the checkbox is not checked, only the hidden input gets sent.
487              * If the checkbox is sent, both inputs get sent.)
488              */
489             foreach ($value as $val) {
490                 if ($val)
491                     return true;
492             }
493             return false;
494         }
495         return (bool) $value;
496     }
497 }
498
499 // don't save default preferences for efficiency.
500 class UserPreferences {
501     function UserPreferences ($saved_prefs = false) {
502         $this->_prefs = array();
503
504         if (isa($saved_prefs, 'UserPreferences')) {
505             foreach ($saved_prefs->_prefs as $name => $value)
506                 $this->set($name, $value);
507         } elseif (is_array($saved_prefs)) {
508             foreach ($saved_prefs as $name => $value)
509                 $this->set($name, $value);
510         }
511     }
512
513     function _getPref ($name) {
514         global $UserPreferences;
515         if (!isset($UserPreferences[$name])) {
516             if ($name == 'passwd2') return false;
517             trigger_error("$name: unknown preference", E_USER_NOTICE);
518             return false;
519         }
520         return $UserPreferences[$name];
521     }
522
523     function get ($name) {
524         if (isset($this->_prefs[$name]))
525             return $this->_prefs[$name];
526         if (!($pref = $this->_getPref($name)))
527             return false;
528         return $pref->default_value;
529     }
530
531     function set ($name, $value) {
532         if (!($pref = $this->_getPref($name)))
533             return false;
534         // don't set default values to safe space (in cookies, db and sesssion)
535         if ($value == $pref->default_value)
536             unset($this->_prefs[$name]);
537         else {
538             // update on changes
539             $newvalue = $pref->sanify($value);
540             if (!empty($this->_prefs[$name]) and $this->_prefs[$name] != $newvalue) {
541                 global $LANG;
542                 // check updates (theme, lang, ...)
543                 switch ($name) {
544                 case 'theme': 
545                     include_once("themes/$value/themeinfo.php"); 
546                     break;
547                 case 'lang':
548                     update_locale ($LANG);
549                     $GLOBALS['LANG'] = $value;
550                     break;
551                 }
552             }
553             $this->_prefs[$name] = $pref->sanify($value);
554         }
555     }
556 }
557
558 // Local Variables:
559 // mode: php
560 // tab-width: 8
561 // c-basic-offset: 4
562 // c-hanging-comment-ender-p: nil
563 // indent-tabs-mode: nil
564 // End:   
565 ?>