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