]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiUser.php
Fixed typo: missing underscore on _request
[SourceForge/phpwiki.git] / lib / WikiUser.php
1 <?php rcs_id('$Id: WikiUser.php,v 1.19 2002-08-24 22:09:14 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(''),
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     function setPreferences($prefs, $id_only = false) {
269         // update the id
270         $this->_request->setSessionVar('wiki_prefs', $prefs);
271         // $this->_request->setCookieVar('WIKI_PREFS2', $this->_prefs, 365);
272         // simple unpacked cookie
273         if ($this->_userid) setcookie('WIKI_ID', $this->_userid, 365, '/');
274
275         // We must ensure that any password is encrypted. 
276         // We don't need any plaintext password.
277         if (! $id_only and $this->isSignedIn() and ($homepage = $this->homePage())) {
278             if ($this->isAdmin()) 
279                 $prefs->set('passwd',''); // this is already stored in index.php, 
280                                           // and it might be plaintext! well oh well
281             $homepage->set('pref',serialize($prefs->_prefs));
282         }
283     }
284
285     // check for homepage with user flag.
286     // can be overriden from the auth backends
287     function exists() {
288         $homepage = $this->homePage();
289         return ($this->_userid and $homepage and $homepage->get('pref'));
290     }
291
292     // doesn't check for existance!!! hmm. 
293     // how to store metadata in not existing pages? how about versions?
294     function homePage() {
295         if (!$this->_userid) return false;
296         if ($this->_homepage) 
297             return $this->_homepage;
298         else {
299             $this->_homepage = $this->_dbi->getPage($this->_userid);
300             return $this->_homepage;
301         }
302     }
303
304     // create user by checking his homepage
305     function createUser ($pref, $createDefaultHomepage = true) {
306         if ($this->exists()) return;
307         if ($createDefaultHomepage) {
308             $this->createHomepage ($pref);
309         } else {
310             // empty page
311             include "lib/loadsave.php";
312             $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)),
313                               'versiondata' => array('author' => $this->_userid),
314                               'pagename' => $this->_userid,
315                               'content' => _('CategoryHomepage'));
316             SavePage (&$this->_request, $pageinfo, false, false);
317         }
318         $this->setPreferences($pref);
319     }
320
321     // create user and default user homepage
322     function createHomepage ($pref) {
323         $pagename = $this->_userid;
324         include "lib/loadsave.php";
325
326         // create default homepage:
327         //  properly expanded template and the pref metadata
328         $template = Template('homepage.tmpl',$this->_request);
329         $text  = $template->getExpansion();
330         $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)),
331                           'versiondata' => array('author' => $this->_userid),
332                           'pagename' => $pagename,
333                           'content' => $text);
334         SavePage (&$this->_request, $pageinfo, false, false);
335             
336         // create Calender
337         $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Preferences');
338         if (! isWikiPage($pagename)) {
339             $pageinfo = array('pagedata' => array(),
340                               'versiondata' => array('author' => $this->_userid),
341                               'pagename' => $pagename,
342                               'content' => "<?plugin Calender ?>\n");
343             SavePage (&$this->_request, $pageinfo, false, false);
344         }
345
346         // create Preferences
347         $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Preferences');
348         if (! isWikiPage($pagename)) {
349             $pageinfo = array('pagedata' => array(),
350                               'versiondata' => array('author' => $this->_userid),
351                               'pagename' => $pagename,
352                               'content' => "<?plugin UserPreferences ?>\n");
353             SavePage (&$this->_request, $pageinfo, false, false);
354         }
355     }
356
357     function tryAuthBackends() {
358         return ''; // crypt('') will never be ''
359     }
360
361     // Auth backends must store the crypted password where?
362     // Not in the preferences.
363     function checkPassword($passwd) {
364         $prefs = $this->getPreferences();
365         $stored_passwd = $prefs->get('passwd'); // crypted
366         if (empty($prefs->_prefs['passwd']))    // not stored in the page
367             // allow empty passwords? At least store a '*' then.
368             // try other backend
369             $stored_passwd = $this->tryAuthBackends($this->_userid);
370         if (empty($stored_passwd)) {
371             trigger_error(sprintf(_("WikiUser backend problem: Old UserPage %s. No password to check against! Update your UserPreferences."), $this->_userid), E_USER_NOTICE);
372             return true;
373             //return false;
374         }
375         if ($stored_passwd == '*')
376             return true;
377         if (!empty($passwd) && crypt($passwd, $stored_passwd) == $stored_passwd)
378             return true;
379         else         
380             return false;
381     }
382
383     function changePassword($newpasswd, $passwd2 = false) {
384         if (! $this->mayChangePassword() ) {
385             trigger_error(sprintf("Attempt to change an external password for '%s'. Not allowed!",
386                                   $this->_userid), E_USER_ERROR);
387             return;
388         }
389         if ($passwd2 and $passwd2 != $newpasswd) {
390             trigger_error("The second passwort must be the same as the first to change it", E_USER_ERROR);
391             return;
392         }
393         $prefs = $this->getPreferences();
394         //$oldpasswd = $prefs->get('passwd');
395         $prefs->set('passwd', crypt($newpasswd));
396         $this->setPreferences($prefs);
397     }
398
399     function mayChangePassword() {
400         // on external DBAuth maybe. on IMAP or LDAP not
401         // on internal DBAuth yes
402         if (in_array($this->_authmethod, array('IMAP', 'LDAP'))) 
403             return false;
404         if ($this->isAdmin()) 
405             return false;
406         if ($this->_authmethod == 'pagedata')
407             return true;
408         if ($this->_authmethod == 'authdb')
409             return true;
410     }
411 }
412
413 // create user and default user homepage
414 function createUser ($userid, $pref) {
415     $user = new WikiUser ($userid);
416     $user->createUser($pref);
417 }
418
419 class _UserPreference 
420 {
421     function _UserPreference ($default_value) {
422         $this->default_value = $default_value;
423     }
424
425     function sanify ($value) {
426         return (string) $value;
427     }
428 }
429
430 class _UserPreference_numeric extends _UserPreference
431 {
432     function _UserPreference_numeric ($default, $minval = false, $maxval = false) {
433         $this->_UserPreference((double) $default);
434         $this->_minval = (double) $minval;
435         $this->_maxval = (double) $maxval;
436     }
437
438     function sanify ($value) {
439         $value = (double) $value;
440         if ($this->_minval !== false && $value < $this->_minval)
441             $value = $this->_minval;
442         if ($this->_maxval !== false && $value > $this->_maxval)
443             $value = $this->_maxval;
444         return $value;
445     }
446 }
447
448 class _UserPreference_int extends _UserPreference_numeric
449 {
450     function _UserPreference_int ($default, $minval = false, $maxval = false) {
451         $this->_UserPreference_numeric((int) $default, (int)$minval, (int)$maxval);
452     }
453
454     function sanify ($value) {
455         return (int) parent::sanify((int)$value);
456     }
457 }
458
459 class _UserPreference_bool extends _UserPreference
460 {
461     function _UserPreference_bool ($default = false) {
462         $this->_UserPreference((bool) $default);
463     }
464
465     function sanify ($value) {
466         if (is_array($value)) {
467             /* This allows for constructs like:
468              *
469              *   <input type="hidden" name="pref[boolPref][]" value="0" />
470              *   <input type="checkbox" name="pref[boolPref][]" value="1" />
471              *
472              * (If the checkbox is not checked, only the hidden input gets sent.
473              * If the checkbox is sent, both inputs get sent.)
474              */
475             foreach ($value as $val) {
476                 if ($val)
477                     return true;
478             }
479             return false;
480         }
481         return (bool) $value;
482     }
483 }
484
485 // don't save default preferences for efficiency.
486 class UserPreferences {
487     function UserPreferences ($saved_prefs = false) {
488         $this->_prefs = array();
489
490         if (isa($saved_prefs, 'UserPreferences')) {
491             foreach ($saved_prefs->_prefs as $name => $value)
492                 $this->set($name, $value);
493         } elseif (is_array($saved_prefs)) {
494             foreach ($saved_prefs as $name => $value)
495                 $this->set($name, $value);
496         }
497     }
498
499     function _getPref ($name) {
500         global $UserPreferences;
501         if (!isset($UserPreferences[$name])) {
502             if ($name == 'passwd2') return false;
503             trigger_error("$name: unknown preference", E_USER_NOTICE);
504             return false;
505         }
506         return $UserPreferences[$name];
507     }
508
509     function get ($name) {
510         if (isset($this->_prefs[$name]))
511             return $this->_prefs[$name];
512         if (!($pref = $this->_getPref($name)))
513             return false;
514         return $pref->default_value;
515     }
516
517     function set ($name, $value) {
518         if (!($pref = $this->_getPref($name)))
519             return false;
520         // don't set default values to safe space (in cookies, db and sesssion)
521         if ($value == $pref->default_value)
522             unset($this->_prefs[$name]);
523         else {
524             // update on changes
525             $newvalue = $pref->sanify($value);
526             if (!empty($this->_prefs[$name]) and $this->_prefs[$name] != $newvalue) {
527                 global $LANG;
528                 // check updates (theme, lang, ...)
529                 switch ($name) {
530                 case 'theme': 
531                     include_once("themes/$value/themeinfo.php"); 
532                     break;
533                 case 'lang':
534                     $LANG = ($value == 'en') ? 'C' : $value;
535                     update_locale ($LANG);
536                     break;
537                 }
538             }
539             $this->_prefs[$name] = $pref->sanify($value);
540         }
541     }
542 }
543
544 // Local Variables:
545 // mode: php
546 // tab-width: 8
547 // c-basic-offset: 4
548 // c-hanging-comment-ender-p: nil
549 // indent-tabs-mode: nil
550 // End:   
551 ?>