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