]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiUserNew.php
Rename functional for PearDB backend
[SourceForge/phpwiki.git] / lib / WikiUserNew.php
1 <?php //-*-php-*-
2 rcs_id('$Id: WikiUserNew.php,v 1.13 2004-02-09 03:58:12 rurban Exp $');
3
4 // This is a complete OOP rewrite of the old WikiUser code with various
5 // configurable external authentification methods.
6 //
7 // There's only one entry point, the function WikiUser which returns 
8 // a WikiUser object, which contains the user's preferences.
9 // This object might get upgraded during the login step and later also.
10 // There exist three preferences storage methods: cookie, homepage and db,
11 // and multiple password checking methods.
12 // See index.php for $USER_AUTH_ORDER[] and USER_AUTH_POLICY if 
13 // ALLOW_USER_PASSWORDS is defined.
14 //
15 // Each user object must define the two preferences methods 
16 //  getPreferences(), setPreferences(), 
17 // and the following 1-3 auth methods: 
18 //  checkPass()  must be defined by all classes,
19 //  userExists() only if USER_AUTH_POLICY'=='strict' 
20 //  mayChangePass()  only if the password is storable.
21 //  storePass()  only if the password is storable.
22 //
23 // WikiUser() given no name, returns an _AnonUser (anonymous user)
24 // object, who may or may not have a cookie. 
25 // However, if the there's a cookie with the userid or a session, 
26 // the user is upgraded to the matching user object.
27 // Given a user name, returns a _BogoUser object, who may or may not 
28 // have a cookie and/or PersonalPage, a _PassUser object or an 
29 // _AdminUser object.
30 //
31 // Takes care of passwords, all preference loading/storing in the
32 // user's page and any cookies. lib/main.php will query the user object to
33 // verify the password as appropriate.
34 //
35 // Notes by 2004-01-25 03:43:45 rurban
36 // Currently this library doesn't look good enough with 
37 // the current configuration options.
38 // Test it by defining ENABLE_USER_NEW in index.php
39 // The problem is that the previous code was written to do auth checks 
40 // only on action != browse, and this code requires a good enough 
41 // user object even for browse. I don't think that this is a good idea.
42 // 1) Now a ForbiddenUser is returned instead of false.
43 // 2) Previously ALLOW_ANON_USER = false meant that anon users cannot edit, 
44 // but may browse. Now with ALLOW_ANON_USER = false he may not browse, 
45 // which is needed to disable browse PagePermissions. Hmm...
46 // I added now ALLOW_ANON_EDIT = true to makes things clear. 
47 // (which replaces REQUIRE_SIGNIN_BEFORE_EDIT)
48 /*
49  * Fixme: 2004-02-06 15:42:24 rurban
50  *   dbprefs edit with anonuser fails.
51 */
52
53 define('WIKIAUTH_FORBIDDEN', -1); // Completely not allowed.
54 define('WIKIAUTH_ANON', 0);       // Not signed in.
55 define('WIKIAUTH_BOGO', 1);       // Any valid WikiWord is enough.
56 define('WIKIAUTH_USER', 2);       // Bogo user with a password.
57 define('WIKIAUTH_ADMIN', 10);     // UserName == ADMIN_USER.
58
59 if (!defined('COOKIE_EXPIRATION_DAYS')) define('COOKIE_EXPIRATION_DAYS', 365);
60 if (!defined('COOKIE_DOMAIN'))          define('COOKIE_DOMAIN', '/');
61
62 if (!defined('EDITWIDTH_MIN_COLS'))     define('EDITWIDTH_MIN_COLS',     30);
63 if (!defined('EDITWIDTH_MAX_COLS'))     define('EDITWIDTH_MAX_COLS',    150);
64 if (!defined('EDITWIDTH_DEFAULT_COLS')) define('EDITWIDTH_DEFAULT_COLS', 80);
65
66 if (!defined('EDITHEIGHT_MIN_ROWS'))     define('EDITHEIGHT_MIN_ROWS',      5);
67 if (!defined('EDITHEIGHT_MAX_ROWS'))     define('EDITHEIGHT_MAX_ROWS',     80);
68 if (!defined('EDITHEIGHT_DEFAULT_ROWS')) define('EDITHEIGHT_DEFAULT_ROWS', 22);
69
70 define('TIMEOFFSET_MIN_HOURS', -26);
71 define('TIMEOFFSET_MAX_HOURS',  26);
72 if (!defined('TIMEOFFSET_DEFAULT_HOURS')) define('TIMEOFFSET_DEFAULT_HOURS', 0);
73
74 /**
75  * There are be the following constants in index.php to 
76  * establish login parameters:
77  *
78  * ALLOW_ANON_USER         default true
79  * ALLOW_ANON_EDIT         default true
80  * ALLOW_BOGO_LOGIN        default true
81  * ALLOW_USER_PASSWORDS    default true
82  * PASSWORD_LENGTH_MINIMUM default 6?
83  *
84  * To require user passwords for editing:
85  * ALLOW_ANON_USER  = true
86  * ALLOW_ANON_EDIT  = false   (before named REQUIRE_SIGNIN_BEFORE_EDIT)
87  * ALLOW_BOGO_LOGIN = false
88  * ALLOW_USER_PASSWORDS = true
89  *
90  * To establish a COMPLETELY private wiki, such as an internal
91  * corporate one:
92  * ALLOW_ANON_USER = false
93  * (and probably require user passwords as described above). In this
94  * case the user will be prompted to login immediately upon accessing
95  * any page.
96  *
97  * There are other possible combinations, but the typical wiki (such
98  * as PhpWiki.sf.net) would usually just leave all four enabled.
99  *
100  */
101
102 // The last object in the row is the bad guy...
103 if (!is_array($USER_AUTH_ORDER))
104     $USER_AUTH_ORDER = array("Forbidden");
105 else
106     $USER_AUTH_ORDER[] = "Forbidden";
107
108 // Local convenience functions.
109 function _isAnonUserAllowed() {
110     return (defined('ALLOW_ANON_USER') && ALLOW_ANON_USER);
111 }
112 function _isBogoUserAllowed() {
113     return (defined('ALLOW_BOGO_LOGIN') && ALLOW_BOGO_LOGIN);
114 }
115 function _isUserPasswordsAllowed() {
116     return (defined('ALLOW_USER_PASSWORDS') && ALLOW_USER_PASSWORDS);
117 }
118
119
120 // Possibly upgrade userobject functions.
121 function _determineAdminUserOrOtherUser($UserName) {
122     // Sanity check. User name is a condition of the definition of the
123     // _AdminUser, _BogoUser and _passuser.
124     if (!$UserName)
125         return $GLOBALS['ForbiddenUser'];
126
127     if ($UserName == ADMIN_USER)
128         return new _AdminUser($UserName);
129     else
130         return _determineBogoUserOrPassUser($UserName);
131 }
132
133 function _determineBogoUserOrPassUser($UserName) {
134     global $ForbiddenUser;
135
136     // Sanity check. User name is a condition of the definition of
137     // _BogoUser and _PassUser.
138     if (!$UserName)
139         return $ForbiddenUser;
140
141     // Check for password and possibly upgrade user object.
142     $_BogoUser = new _BogoUser($UserName);
143     if (_isUserPasswordsAllowed()) {
144         if (/*$has_password =*/ $_BogoUser->_prefs->get('passwd'))
145             return new _PassUser($UserName);
146         else { // PassUsers override BogoUsers if they exist
147             $_PassUser = new _PassUser($UserName);
148             if ($_PassUser->userExists())
149                 return $_PassUser;
150         }
151     }
152     // User has no password.
153     if (_isBogoUserAllowed())
154         return $_BogoUser;
155
156     // Passwords are not allowed, and Bogo is disallowed too. (Only
157     // the admin can sign in).
158     return $ForbiddenUser;
159 }
160
161 /**
162  * Primary WikiUser function, called by main.php.
163  * 
164  * This determines the user's type and returns an appropriate user
165  * object. main.php then querys the resultant object for password
166  * validity as necessary.
167  *
168  * If an _AnonUser object is returned, the user may only browse pages
169  * (and save prefs in a cookie).
170  *
171  * To disable access but provide prefs the global $ForbiddenUser class 
172  * is returned. (was previously false)
173  * 
174  */
175 function WikiUser ($UserName = '') {
176     global $ForbiddenUser;
177
178     //TODO: Check sessionvar for username & save username into
179     //sessionvar (may be more appropriate to do this in main.php).
180     if ($UserName) {
181         $ForbiddenUser = new _ForbiddenUser($UserName);
182         // Found a user name.
183         return _determineAdminUserOrOtherUser($UserName);
184     }
185     elseif (!empty($_SESSION['userid'])) {
186         // Found a user name.
187         $ForbiddenUser = new _ForbiddenUser($_SESSION['userid']);
188         return _determineAdminUserOrOtherUser($_SESSION['userid']);
189     }
190     else {
191         // Check for autologin pref in cookie and possibly upgrade
192         // user object to another type.
193         $_AnonUser = new _AnonUser();
194         if ($UserName = $_AnonUser->_userid && $_AnonUser->_prefs->get('autologin')) {
195             // Found a user name.
196             $ForbiddenUser = new _ForbiddenUser($UserName);
197             return _determineAdminUserOrOtherUser($UserName);
198         }
199         else {
200             $ForbiddenUser = new _ForbiddenUser();
201             if (_isAnonUserAllowed())
202                 return $_AnonUser;
203             return $ForbiddenUser; // User must sign in to browse pages.
204         }
205         return $ForbiddenUser;     // User must sign in with a password.
206     }
207     /*
208     trigger_error("DEBUG: Note: End of function reached in WikiUser." . " "
209                   . "Unexpectedly, an appropriate user class could not be determined.");
210     return $ForbiddenUser; // Failsafe.
211     */
212 }
213
214 function WikiUserClassname() {
215     return '_WikiUser';
216 }
217
218 function UpgradeUser ($olduser, $user) {
219     if (isa($user,'_WikiUser') and isa($olduser,'_WikiUser')) {
220         // populate the upgraded class $olduser with the values from the new user object
221         foreach (get_object_vars($user) as $k => $v) {
222             if (!empty($v)) $olduser->$k = $v;  
223         }
224         $GLOBALS['request']->_user = $olduser;
225         return $olduser;
226     } else {
227         return false;
228     }
229 }
230
231 function UserExists ($UserName) {
232     global $request;
233     if (!($user = $request->getUser()))
234         $user = WikiUser($UserName);
235     if (!$user) 
236         return false;
237     if ($user->userExists($UserName)) {
238         $request->_user = $user;
239         return true;
240     }
241     if (isa($user,'_BogoUser'))
242       $user = new _PassUser($UserName);
243     while ($user = $user->nextClass()) {
244         return $user->userExists($UserName);
245     }
246     $request->_user = $GLOBALS['ForbiddenUser'];
247     return false;
248 }
249
250 function CheckPass ($UserName, $Password) {
251     global $request;
252     if (!($user = $request->getUser()))
253         $user = WikiUser($UserName);
254     if (!$user) 
255         return false;
256     if ($user->checkPass($Password)) {
257         $request->_user = $user;
258         return true;
259     }
260     if (isa($user,'_BogoUser'))
261       $user = new _PassUser($UserName);
262     while ($user = $user->nextClass()) {
263         return $user->checkPass($Password);
264     }
265     $request->_user = $GLOBALS['ForbiddenUser'];
266     return false;
267 }
268
269
270 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
271
272 // Base WikiUser class.
273 class _WikiUser
274 {
275     var $_userid = '';
276
277     var $_level = WIKIAUTH_FORBIDDEN;
278     var $_prefs = false;
279     var $_HomePagehandle = false;
280
281     // constructor
282     function _WikiUser($UserName = '') {
283
284         $this->_userid = $UserName;
285         if ($UserName) {
286             $this->_HomePagehandle = $this->hasHomePage();
287         }
288         $this->getPreferences();
289     }
290
291     function UserName() {
292         if (!empty($this->_userid))
293             return $this->_userid;
294     }
295
296     function getPreferences() {
297         trigger_error("DEBUG: Note: undefined _WikiUser class trying to load prefs." . " "
298                       . "New subclasses of _WikiUser must override this function.");
299         return false;
300     }
301
302     function setPreferences($prefs, $id_only) {
303         trigger_error("DEBUG: Note: undefined _WikiUser class trying to save prefs." . " "
304                       . "New subclasses of _WikiUser must override this function.");
305         return false;
306     }
307
308     function userExists() {
309         return $this->hasHomePage();
310     }
311
312     function checkPass($submitted_password) {
313         // By definition, an undefined user class cannot sign in.
314         trigger_error("DEBUG: Warning: undefined _WikiUser class trying to sign in." . " "
315                       . "New subclasses of _WikiUser must override this function.");
316         return false;
317     }
318
319     // returns page_handle to user's home page or false if none
320     function hasHomePage() {
321         if ($this->_userid) {
322             if ($this->_HomePagehandle) {
323                 return $this->_HomePagehandle;
324             }
325             else {
326                 // check db again (maybe someone else created it since
327                 // we logged in.)
328                 global $request;
329                 $this->_HomePagehandle = $request->getPage($this->_userid);
330                 return $this->_HomePagehandle;
331             }
332         }
333         // nope
334         return false;
335     }
336
337     function nextAuthMethod() {
338         if (! $this->_current_method) {
339             if (get_class($this) != '_passuser') {
340                 $this->_current_method = substr(get_class($this),1,-8);
341             }
342             $this->_auth_methods = $GLOBALS['USER_AUTH_ORDER'];
343             $this->_current_index = -1;
344         }
345         $this->_current_index++;
346         if ($this->_current_index >= count($this->_auth_methods))
347             return false;
348         $this->_current_method = $this->_auth_methods[$this->_current_index];
349         return $this->_current_method;
350     }
351
352     // upgrade the user object
353     function nextClass() {
354         if ($method = $this->nextAuthMethod()) {
355             $class = "_".$method."PassUser";
356             if ($user = new $class($this->_userid)) {
357                 // prevent from endless recursion.
358                 //$user->_current_method = $this->_current_method;
359                 //$user->_current_index = $this->_current_index;
360                 $user = UpgradeUser($user, $this);
361             }
362             return $user;
363         }
364     }
365
366     function PrintLoginForm (&$request, $args, $fail_message = false,
367                              $seperate_page = true) {
368         include_once('lib/Template.php');
369         // Call update_locale in case the system's default language is not 'en'.
370         // (We have no user pref for lang at this point yet, no one is logged in.)
371         update_locale(DEFAULT_LANGUAGE);
372         $userid = $this->_userid;
373         $require_level = 0;
374         extract($args); // fixme
375
376         $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
377
378         $pagename = $request->getArg('pagename');
379         $nocache = 1;
380         $login = new Template('login', $request,
381                               compact('pagename', 'userid', 'require_level',
382                                       'fail_message', 'pass_required', 'nocache'));
383         if ($seperate_page) {
384             $top = new Template('html', $request,
385                                 array('TITLE' => _("Sign In")));
386             return $top->printExpansion($login);
387         } else {
388             return $login;
389         }
390     }
391
392     // signed in but probably not password checked
393     function isSignedIn() {
394         return (isa($this,'_BogoUser') or isa($this,'_PassUser'));
395     }
396
397     function isAuthenticated () {
398         //return isa($this,'_PassUser');
399         //return isa($this,'_BogoUser') || isa($this,'_PassUser');
400         return $this->_level >= WIKIAUTH_BOGO;
401     }
402
403     function isAdmin () {
404         return $this->_level == WIKIAUTH_ADMIN;
405     }
406
407     function getId () {
408         return ( $this->UserName()
409                  ? $this->UserName()
410                  : $GLOBALS['request']->get('REMOTE_ADDR') ); // FIXME: globals
411     }
412
413     function getAuthenticatedId() {
414         return ( $this->isAuthenticated()
415                  ? $this->_userid
416                  : ''); //$GLOBALS['request']->get('REMOTE_ADDR') ); // FIXME: globals
417     }
418
419     function hasAuthority ($require_level) {
420         return $this->_level >= $require_level;
421     }
422
423     function AuthCheck ($postargs) {
424         // Normalize args, and extract.
425         $keys = array('userid', 'passwd', 'require_level', 'login', 'logout',
426                       'cancel');
427         foreach ($keys as $key)
428             $args[$key] = isset($postargs[$key]) ? $postargs[$key] : false;
429         extract($args);
430         $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
431
432         if ($logout) { // Log out
433             $GLOBALS['request']->_user = new _AnonUser();
434             return $GLOBALS['request']->_user; 
435         } elseif ($cancel)
436             return false;        // User hit cancel button.
437         elseif (!$login && !$userid)
438             return false;       // Nothing to do?
439
440         $authlevel = checkPass($userid,$passwd);
441         if (!$authlevel)
442             return _("Invalid password or userid.");
443         elseif ($authlevel < $require_level)
444             return _("Insufficient permissions.");
445
446         // Successful login.
447         $user = $GLOBALS['request']->_user;
448         $user->_userid = $userid;
449         $user->_level = $authlevel;
450         return $user;
451     }
452
453 }
454
455 class _AnonUser
456 extends _WikiUser
457 {
458     var $_level = WIKIAUTH_ANON;
459
460     // Anon only gets to load and save prefs in a cookie, that's it.
461     function getPreferences() {
462         global $request;
463
464         if (empty($this->_prefs))
465             $this->_prefs = new UserPreferences;
466         $UserName = $this->UserName();
467         if ($cookie = $request->getCookieVar(WIKI_NAME)) {
468             if (! $unboxedcookie = $this->_prefs->retrieve($cookie)) {
469                 trigger_error(_("Format of UserPreferences cookie not recognised.") . " "
470                               . _("Default preferences will be used."),
471                               E_USER_WARNING);
472             }
473             // TODO: try reading userid from old PhpWiki cookie
474             // formats, then delete old cookie from browser!
475             //
476             //else {
477                 // try old cookie format.
478                 //$cookie = $request->getCookieVar('WIKI_ID');
479             //}
480
481             /**
482              * Only keep the cookie if it matches the UserName who is
483              * signing in or if this really is an Anon login (no
484              * username). (Remember, _BogoUser and higher inherit this
485              * function too!).
486              */
487             if (! $UserName || $UserName == $unboxedcookie['userid']) {
488                 $this->_prefs = new UserPreferences($unboxedcookie);
489                 $this->_userid = $unboxedcookie['userid'];
490             }
491         }
492         // initializeTheme() needs at least an empty object
493         if (! $this->_prefs )
494             $this->_prefs = new UserPreferences;
495         return $this->_prefs;
496     }
497
498     function setPreferences($prefs, $id_only=false) {
499         // Allow for multiple wikis in same domain. Encode only the
500         // _prefs array of the UserPreference object. Ideally the
501         // prefs array should just be imploded into a single string or
502         // something so it is completely human readable by the end
503         // user. In that case stricter error checking will be needed
504         // when loading the cookie.
505         setcookie(WIKI_NAME, $this->_prefs->store(),
506                   COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
507     }
508
509     function userExists() {
510         return true;
511     }
512
513     function checkPass($submitted_password) {
514         // By definition, the _AnonUser does not HAVE a password
515         // (compared to _BogoUser, who has an EMPTY password).
516         trigger_error("DEBUG: Warning: _AnonUser unexpectedly asked to checkPass()." . " "
517                       . "Check isa(\$user, '_PassUser'), or: isa(\$user, '_AdminUser') etc. first." . " "
518                       . "New subclasses of _WikiUser must override this function.");
519         return false;
520     }
521
522 }
523
524 class _ForbiddenUser
525 extends _AnonUser
526 {
527     var $_level = WIKIAUTH_FORBIDDEN;
528
529     function checkPass($submitted_password) {
530         return false;
531     }
532
533     function userExists() {
534         if ($this->_HomePagehandle) return true;
535         return false;
536     }
537 }
538 class _ForbiddenPassUser
539 extends _ForbiddenUser
540 {
541     function dummy() {
542         return;
543     }
544 }
545
546 /**
547  * Do NOT extend _BogoUser to other classes, for checkPass()
548  * security. (In case of defects in code logic of the new class!)
549  */
550 class _BogoUser
551 extends _AnonUser
552 {
553     function userExists() {
554         if (isWikiWord($this->_userid)) {
555             $this->_level = WIKIAUTH_BOGO;
556             return true;
557         } else {
558             $this->_level = WIKIAUTH_ANON;
559             return false;
560         }
561     }
562
563     function checkPass($submitted_password) {
564         // By definition, BogoUser has an empty password.
565         $this->userExists();
566         return $this->_level;
567     }
568 }
569
570 class _PassUser
571 extends _AnonUser
572 /**
573  * Called if ALLOW_USER_PASSWORDS and Anon and Bogo failed.
574  *
575  * The classes for all subsequent auth methods extend from
576  * this class. 
577  * This handles the auth method type dispatcher according $USER_AUTH_ORDER, 
578  * the three auth method policies first-only, strict and stacked
579  * and the two methods for prefs: homepage or database, 
580  * if $DBAuthParams['pref_select'] is defined.
581  *
582  * Default is PersonalPage auth and prefs.
583  * 
584  */
585 {
586     var $_auth_dbi, $_prefmethod, $_prefselect, $_prefupdate;
587     var $_current_method, $_current_index;
588
589     // check and prepare the auth and pref methods only once
590     function _PassUser($UserName = '') {
591         global $DBAuthParams, $DBParams;
592
593         if ($UserName) {
594             $this->_userid = $UserName;
595             $this->_HomePagehandle = $this->hasHomePage();
596         }
597         // Check the configured Prefs methods
598         if (  !empty($DBAuthParams['pref_select']) and 
599               $DBParams['dbtype'] == 'SQL' and 
600               !isset($this->_prefselect)) {
601             $this->_prefmethod = 'SQL'; // really pear db
602             $this->getAuthDbh();
603             // preparate the SELECT statement
604             $this->_prefselect = $this->_auth_dbi->prepare(
605                 str_replace('"$userid"','?',$DBAuthParams['pref_select'])
606             );
607         }
608         if (  !empty($DBAuthParams['pref_select']) and 
609               $DBParams['dbtype'] == 'ADODB' and
610               !isset($this->_prefselect)) {
611             $this->_prefmethod = 'ADODB'; // uses a simplier execute syntax
612             $this->getAuthDbh();
613             // preparate the SELECT statement
614             $this->_prefselect = str_replace('"$userid"','%s',$DBAuthParams['pref_select']);
615         }
616         if (  !empty($DBAuthParams['pref_update']) and 
617               $DBParams['dbtype'] == 'SQL' and
618               !isset($this->_prefupdate)) {
619             $this->_prefmethod = 'SQL';
620             $this->getAuthDbh();
621             $this->_prefupdate = $this->_auth_dbi->prepare(
622                 str_replace(array('"$userid"','"$pref_blob"'),array('?','?'),$DBAuthParams['pref_update'])
623             );
624         }
625         if (  !empty($DBAuthParams['pref_update']) and 
626               $DBParams['dbtype'] == 'ADODB' and
627               !isset($this->_prefupdate)) {
628             $this->_prefmethod = 'ADODB'; // uses a simplier execute syntax
629             $this->getAuthDbh();
630             // preparate the SELECT statement
631             $this->_prefupdate = str_replace(array('"$userid"','"$pref_blob"'),array('%s','%s'),$DBAuthParams['pref_update']);
632         }
633         $this->getPreferences();
634
635         // Upgrade to the next parent _PassUser class. Avoid recursion.
636         if ( get_class($this) === '_passuser' ) { // hopefully PHP will keep this lowercase
637             //auth policy: Check the order of the configured auth methods
638             // 1. first-only: Upgrade the class here in the constructor
639             // 2. old:       ignore USER_AUTH_ORDER and try to use all available methods as in the previous PhpWiki releases (slow)
640             // 3. strict:    upgrade the class after checking the user existance in userExists()
641             // 4. stacked:   upgrade the class after the password verification in checkPass()
642             // Methods: PersonalPage, HTTP_AUTH, DB, LDAP, IMAP, File
643             if (!defined('USER_AUTH_POLICY')) define('USER_AUTH_POLICY','old');
644             if (defined('USER_AUTH_POLICY')) {
645                 // policy 1: only pre-define one method for all users
646                 if (USER_AUTH_POLICY === 'first-only') {
647                     if ($user = $this->nextClass())
648                         return $user;
649                     else 
650                         return $GLOBALS['ForbiddenUser'];
651                 }
652                 // use the default behaviour from the previous versions:
653                 elseif (USER_AUTH_POLICY === 'old') {
654                     // default: try to be smart
655                     if (!empty($GLOBALS['PHP_AUTH_USER'])) {
656                         return new _HttpAuthPassUser($UserName);
657                     } elseif (!empty($DBAuthParams['auth_check']) and ($DBAuthParams['auth_dsn'] or $GLOBALS ['DBParams']['dsn'])) {
658                         return new _DbPassUser($UserName);
659                     } elseif (defined('LDAP_AUTH_HOST') and defined('LDAP_BASE_DN') and function_exists('ldap_open')) {
660                         return new _LDAPPassUser($UserName);
661                     } elseif (defined('IMAP_AUTH_HOST') and function_exists('imap_open')) {
662                         return new _IMAPPassUser($UserName);
663                     } elseif (defined('AUTH_USER_FILE')) {
664                         return new _FilePassUser($UserName);
665                     } else {
666                         return new _PersonalPagePassUser($UserName);
667                     }
668                 }
669                 else 
670                     // else use the page methods defined in _PassUser.
671                     return $this;
672             }
673         }
674     }
675
676     function getAuthDbh () {
677         global $request, $DBParams, $DBAuthParams;
678         if (empty($this->_auth_dbi)) {
679             if ($DBParams['dbtype'] == 'SQL' and empty($DBAuthParams['auth_dsn']))
680                 $dbh = $request->getDbh(); // use phpwiki database 
681             elseif ($DBAuthParams['auth_dsn'] == $DBParams['dsn'])
682                 $dbh = $request->getDbh(); // same phpwiki database 
683             else // use another external database handle. needs PHP >= 4.1
684                 $dbh = WikiDB::open($DBAuthParams);
685             $this->_auth_dbi = & $dbh->_backend->_dbh;    
686         }
687         return $this->_auth_dbi;
688     }
689
690     function prepare ($stmt, $variables) {
691         global $DBParams, $request;
692         // preparate the SELECT statement, for ADODB and PearDB (MDB not)
693         $this->getAuthDbh();
694         $place = ($DBParams['dbtype'] == 'ADODB') ? '%s' : '?';
695         if (is_array($variables)) {
696             $new = array();
697             foreach ($variables as $v) { $new[] = $place; }
698         } else {
699             $new = $place;
700         }
701         // probably prefix table names if in same database
702         if (!empty($DBParams['prefix']) and 
703             $this->_auth_dbi === $request->_dbi->_backend->_dbh) {
704             if (!stristr($DBParams['prefix'],$stmt)) {
705                 //Do it automatically for the lazy admin? Esp. on sf.net it's nice to have
706                 trigger_error("TODO: Need to prefix the DBAuthParam tablename in index.php: $stmt",
707                               E_USER_WARNING);
708                 $stmt = str_replace(array(" user "," pref "," member "),
709                                     array(" ".$prefix."user ",
710                                           " ".$prefix."prefs ",
711                                           " ".$prefix."member "),$stmt);
712             }
713         }
714         return $this->_auth_dbi->prepare(str_replace($variables,$new,$stmt));
715     }
716
717     //TODO: password changing
718     //TODO: email verification
719
720     function getPreferences() {
721
722         // We don't necessarily have to read the cookie first. Since
723         // the user has a password, the prefs stored in the homepage
724         // cannot be arbitrarily altered by other Bogo users.
725         _AnonUser::getPreferences();
726
727         // database prefs
728         if ((! $this->_prefs) and isset($this->_prefselect)) {
729             if ($this->_prefmethod == 'ADODB') {
730                 $dbh = & $this->_auth_dbi;
731                 $db_result = $dbh->Execute($this->_prefselect,$dbh->qstr($this->_userid));
732                 if (!$rs->EOF)
733                     $prefs_blob = $db_result->fields['pref_blob'];
734                 $db_result->Close();
735             }
736             else { // pear db methods
737                 $db_result = $this->_auth_dbi->execute($this->_prefselect,$this->_userid);
738                 list($prefs_blob) = $db_result->fetchRow();
739             }
740             if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
741                 $this->_prefs = new UserPreferences($restored_from_db);
742                 return $this->_prefs;
743             }
744         }
745         
746         // User may have deleted cookie, retrieve from his
747         // PersonalPage if there is one.
748         if ((! $this->_prefs) && $this->_HomePagehandle) {
749             if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
750                 $this->_prefs = new UserPreferences($restored_from_page);
751                 return $this->_prefs;
752             }
753         }
754         return $this->_prefs;
755     }
756
757     function setPreferences($prefs, $id_only=false) {
758         _AnonUser::setPreferences($prefs, $id_only);
759         // Encode only the _prefs array of the UserPreference object
760         $serialized = $this->_prefs->store();
761
762         // database prefs
763         if (!empty($prefs) and isset($this->_prefupdate)) {
764             if ($this->_prefmethod == 'ADODB') {
765                 $dbh =& $this->_auth_dbi;
766                 $db_result = $dbh->Execute($this->_prefupdate,
767                                            array($dbh->qstr($serialized),
768                                                  $dbh->qstr($this->_userid)));
769                 $db_result->Close();
770             }
771             else { // pear db methods
772                 //Fixme: The prepared params get reversed somehow! 
773                 //cannot find the pear bug for now
774                 $db_result = $this->_auth_dbi->execute($this->_prefupdate,
775                                                        array($serialized,$this->_userid));
776             }
777         }
778         else
779             $this->_HomePagehandle->set('pref', $serialized);
780     }
781
782     function mayChangePass() {
783         return true;
784     }
785
786     //The default method is getting the password from prefs. 
787     // child methods obtain $stored_password from external auth.
788     function userExists() {
789         //if ($this->_HomePagehandle) return true;
790         while ($user = $this->nextClass()) {
791               if ($user->userExists())
792                   return true;
793         }
794         return false;
795     }
796
797     //The default method is getting the password from prefs. 
798     // child methods obtain $stored_password from external auth.
799     function checkPass($submitted_password) {
800         $stored_password = $this->_prefs->get('passwd');
801         $result = $this->_checkPass($submitted_password, $stored_password);
802         if ($result) $this->_level = WIKIAUTH_USER;
803
804         if (!$result) {
805             if (USER_AUTH_POLICY === 'strict') {
806                 if ($user = $this->nextClass()) {
807                     if ($user = $user->userExists())
808                         return $user->checkPass($submitted_password);
809                 }
810             }
811             if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
812                 if ($user = $this->nextClass())
813                     return $user->checkPass($submitted_password);
814             }
815         }
816         return $this->_level;
817     }
818
819     //TODO: remove crypt() function check from config.php:396 ??
820     function _checkPass($submitted_password, $stored_password) {
821         if(!empty($submitted_password)) {
822             if (defined('ENCRYPTED_PASSWD') && ENCRYPTED_PASSWD) {
823                 // Verify against encrypted password.
824                 if (function_exists('crypt')) {
825                     if (crypt($submitted_password, $stored_password) == $stored_password )
826                         return true; // matches encrypted password
827                     else
828                         return false;
829                 }
830                 else {
831                     trigger_error(_("The crypt function is not available in this version of PHP.") . " "
832                                   . _("Please set ENCRYPTED_PASSWD to false in index.php and change ADMIN_PASSWD."),
833                                   E_USER_WARNING);
834                     return false;
835                 }
836             }
837             else {
838                 // Verify against cleartext password.
839                 if ($submitted_password == $stored_password)
840                     return true;
841                 else {
842                     // Check whether we forgot to enable ENCRYPTED_PASSWD
843                     if (function_exists('crypt')) {
844                         if (crypt($submitted_password, $stored_password) == $stored_password) {
845                             trigger_error(_("Please set ENCRYPTED_PASSWD to true in index.php."),
846                                           E_USER_WARNING);
847                             return true;
848                         }
849                     }
850                 }
851             }
852         }
853         return false;
854     }
855 }
856
857 class _BogoLoginUser
858 extends _PassUser
859 {
860     function userExists() {
861         if (isWikiWord($this->_userid)) {
862             $this->_level = WIKIAUTH_BOGO;
863             return true;
864         } else {
865             $this->_level = WIKIAUTH_ANON;
866             return false;
867         }
868     }
869
870     function checkPass($submitted_password) {
871         // A BogoLoginUser requires PASSWORD_LENGTH_MINIMUM.
872         if ($this->userExists())
873             return $this->_level;
874     }
875 }
876
877
878 class _PersonalPagePassUser
879 extends _PassUser
880 /**
881  * This class is only to simplify the auth method dispatcher.
882  * It inherits all methods from _PassUser.
883  */
884 {
885     function dummy() {}
886 }
887
888 class _DbPassUser
889 extends _PassUser
890 /**
891  * Authenticate against a database, to be able to use shared users.
892  *   internal: no different $DbAuthParams['dsn'] defined, or
893  *   external: different $DbAuthParams['dsn']
894  * The magic is done in the symbolic SQL statements in index.php
895  *
896  * We support only the SQL and ADODB backends.
897  * The other WikiDB backends (flat, cvs, dba, ...) should be used for pages, 
898  * not for auth stuff. If one would like to use e.g. dba for auth, he should 
899  * use PearDB (SQL) with the right $DBAuthParam['auth_dsn'].
900  * Flat files for auth use is handled by the auth method "File".
901  *
902  * Preferences are handled in the parent class.
903  */
904 {
905     var $_authselect, $_authupdate;
906
907     // This can only be called from _PassUser, because the parent class 
908     // sets the auth_dbi and pref methods, before this class is initialized.
909     function _DbPassUser($UserName='') {
910         if (!$this->_prefs)
911             _PassUser::_PassUser($UserName);
912         $this->_authmethod = 'DB';
913         $this->getAuthDbh();
914         $this->_auth_crypt_method = $GLOBALS['DBAuthParams']['auth_crypt_method'];
915
916         if ($GLOBALS['DBParams']['dbtype'] == 'ADODB') 
917             return new _AdoDbPassUser($UserName);
918         else 
919             return new _PearDbPassUser($UserName);
920     }
921
922     function mayChangePass() {
923         return !isset($this->_authupdate);
924     }
925
926 }
927
928 class _PearDbPassUser
929 extends _DbPassUser
930 /**
931  * Pear DB methods
932  */
933 {
934     function _PearDbPassUser($UserName='') {
935         global $DBAuthParams;
936         if (!$this->_prefs)
937             _PassUser::_PassUser($UserName);
938         $this->getAuthDbh();
939         $this->_auth_crypt_method = $GLOBALS['DBAuthParams']['auth_crypt_method'];
940         // Prepare the configured auth statements
941         if (!empty($DBAuthParams['auth_check']) and !isset($this->_authselect)) {
942             $this->_authselect = $this->_auth_dbi->prepare (
943                      str_replace(array('"$userid"','"$password"'),array('?','?'),
944                                   $DBAuthParams['auth_check'])
945                      );
946         }
947         if (!empty($DBAuthParams['auth_update']) and !isset($this->_authupdate)) {
948             $this->_authupdate = $this->_auth_dbi->prepare(
949                     str_replace(array('"$userid"','"$password"'),array('?','?'),
950                                 $DBAuthParams['auth_update'])
951                     );
952         }
953         return $this;
954     }
955
956     function getPreferences() {
957         // override the generic slow method here for efficiency and not to 
958         // clutter the homepage metadata with prefs.
959         _AnonUser::getPreferences();
960         if ((! $this->_prefs) && isset($this->_prefselect)) {
961             $db_result = $this->_auth_dbi->execute($this->_prefselect,$this->_userid);
962             list($prefs_blob) = $db_result->fetchRow();
963             if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
964                 $this->_prefs = new UserPreferences($restored_from_db);
965                 return $this->_prefs;
966             }
967         }
968         if ((! $this->_prefs) && $this->_HomePagehandle) {
969             if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
970                 $this->_prefs = new UserPreferences($restored_from_page);
971                 return $this->_prefs;
972             }
973         }
974         return $this->_prefs;
975     }
976
977     function setPreferences($prefs, $id_only=false) {
978         $serialized = $this->_prefs->store();
979         if (isset($this->_prefupdate)) {
980             //Fixme: The prepared params get reversed somehow! 
981             //cannot find the pear bug for now
982             $db_result = $this->_auth_dbi->execute($this->_prefupdate,
983                                                    array($serialized,$this->_userid));
984         } else {
985             _AnonUser::setPreferences($prefs, $id_only);
986             $this->_HomePagehandle->set('pref', $serialized);
987         }
988     }
989
990     function userExists() {
991         if (!$this->_authselect)
992             trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'SQL'",
993                           E_USER_WARNING);
994         $dbh = &$this->_auth_dbi;
995         //NOTE: for auth_crypt_method='crypt' no special auth_user_exists is needed
996         if ($this->_auth_crypt_method == 'crypt') {
997             $rs = $dbh->Execute($this->_authselect,$this->_userid) ;
998             if ($rs->numRows())
999                 return true;
1000         }
1001         else {
1002             if (! $GLOBALS['DBAuthParams']['auth_user_exists'])
1003                 trigger_error("\$DBAuthParams['auth_user_exists'] is missing",
1004                               E_USER_WARNING);
1005             $this->_authcheck = str_replace('"$userid"','?',
1006                                              $GLOBALS['DBAuthParams']['auth_user_exists']);
1007             $rs = $dbh->Execute($this->_authcheck,$this->_userid) ;
1008             if ($rs->numRows())
1009                 return true;
1010         }
1011         
1012         if (USER_AUTH_POLICY === 'strict') {
1013             if ($user = $this->nextClass()) {
1014                 return $user->userExists();
1015             }
1016         }
1017     }
1018  
1019     function checkPass($submitted_password) {
1020         if (!isset($this->_authselect))
1021             trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'SQL'",
1022                           E_USER_WARNING);
1023
1024         //NOTE: for auth_crypt_method='crypt'  defined('ENCRYPTED_PASSWD',true) must be set
1025         if ($this->_auth_crypt_method == 'crypt') {
1026             $db_result = $this->_auth_dbi->execute($this->_authselect,$this->_userid);
1027             list($stored_password) = $db_result->fetchRow();
1028             $result = $this->_checkPass($submitted_password, $stored_password);
1029         } else {
1030             //Fixme: The prepared params get reversed somehow! 
1031             //cannot find the pear bug for now
1032             $db_result = $this->_auth_dbi->execute($this->_authselect,
1033                                                    array($submitted_password,$this->_userid));
1034             list($okay) = $db_result->fetchRow();
1035             $result = !empty($okay);
1036         }
1037
1038         if ($result) {
1039             $this->_level = WIKIAUTH_USER;
1040         } else {
1041             if (USER_AUTH_POLICY === 'strict') {
1042                 if ($user = $this->nextClass()) {
1043                     if ($user = $user->userExists())
1044                         return $user->checkPass($submitted_password);
1045                 }
1046             }
1047             if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1048                 if ($user = $this->nextClass())
1049                     return $user->checkPass($submitted_password);
1050             }
1051         }
1052         return $this->_level;
1053     }
1054
1055     function storePass($submitted_password) {
1056         if (!isset($this->_authupdate)) {
1057             //CHECKME
1058             trigger_warning("Either \$DBAuthParams['auth_update'] not defined or \$DBParams['dbtype'] != 'SQL'",
1059                           E_USER_WARNING);
1060             return false;
1061         }
1062
1063         if ($this->_auth_crypt_method == 'crypt') {
1064             if (function_exists('crypt'))
1065                 $submitted_password = crypt($submitted_password);
1066         }
1067         //Fixme: The prepared params get reversed somehow! 
1068         //cannot find the pear bug for now
1069         $db_result = $this->_auth_dbi->execute($this->_authupdate,
1070                                                array($submitted_password,$this->_userid));
1071     }
1072
1073 }
1074
1075 class _AdoDbPassUser
1076 extends _DbPassUser
1077 /**
1078  * ADODB methods
1079  */
1080 {
1081     function _AdoDbPassUser($UserName='') {
1082         global $DBAuthParams;
1083         if (!$this->_prefs)
1084             _PassUser::_PassUser($UserName);
1085         $this->getAuthDbh();
1086         $this->_auth_crypt_method = $GLOBALS['DBAuthParams']['auth_crypt_method'];
1087         // Prepare the configured auth statements
1088         if (!empty($DBAuthParams['auth_check'])) {
1089             $this->_authselect = str_replace(array('"$userid"','"$password"'),array('%s','%s'),
1090                                               $DBAuthParams['auth_check']);
1091         }
1092         if (!empty($DBAuthParams['auth_update'])) {
1093             $this->_authupdate = str_replace(array('"$userid"','"$password"'),array('%s','%s'),
1094                                               $DBAuthParams['auth_update']);
1095         }
1096         return $this;
1097     }
1098
1099     function getPreferences() {
1100         // override the generic slow method here for efficiency
1101         _AnonUser::getPreferences();
1102         if ((! $this->_prefs) and isset($this->_prefselect)) {
1103             $dbh = & $this->_auth_dbi;
1104             $rs = $dbh->Execute($this->_prefselect,$dbh->qstr($this->_userid));
1105             if ($rs->EOF) {
1106                 $rs->Close();
1107             } else {
1108                 $prefs_blob = $rs->fields['pref_blob'];
1109                 $rs->Close();
1110                 if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
1111                     $this->_prefs = new UserPreferences($restored_from_db);
1112                     return $this->_prefs;
1113                 }
1114             }
1115         }
1116         if ((! $this->_prefs) && $this->_HomePagehandle) {
1117             if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
1118                 $this->_prefs = new UserPreferences($restored_from_page);
1119                 return $this->_prefs;
1120             }
1121         }
1122         return $this->_prefs;
1123     }
1124
1125     function setPreferences($prefs, $id_only=false) {
1126         $serialized = $this->_prefs->store();
1127         if (isset($this->_prefupdate)) {
1128             $dbh = & $this->_auth_dbi;
1129             $db_result = $dbh->Execute($this->_prefupdate,array($dbh->qstr($serialized),$dbh->qstr($this->_userid)));
1130             $db_result->Close();
1131         } else {
1132             _AnonUser::setPreferences($prefs, $id_only);
1133             $this->_HomePagehandle->set('pref', $serialized);
1134         }
1135     }
1136  
1137     function userExists() {
1138         if (!$this->_authselect)
1139             trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'ADODB'",
1140                           E_USER_WARNING);
1141         $dbh = &$this->_auth_dbi;
1142         //NOTE: for auth_crypt_method='crypt' no special auth_user_exists is needed
1143         if ($this->_auth_crypt_method == 'crypt') {
1144             $rs = $dbh->Execute($this->_authselect,$dbh->qstr($this->_userid));
1145             if (!$rs->EOF) {
1146                 $rs->Close();
1147                 return true;
1148             } else {
1149                 $rs->Close();
1150             }
1151         }
1152         else {
1153             if (! $GLOBALS['DBAuthParams']['auth_user_exists'])
1154                 trigger_error("\$DBAuthParams['auth_user_exists'] is missing",
1155                               E_USER_WARNING);
1156             $this->_authcheck = str_replace('"$userid"','%s',
1157                                              $GLOBALS['DBAuthParams']['auth_user_exists']);
1158             $rs = $dbh->Execute($this->_authcheck,$dbh->qstr($this->_userid));
1159             if (!$rs->EOF) {
1160                 $rs->Close();
1161                 return true;
1162             } else {
1163                 $rs->Close();
1164             }
1165         }
1166         
1167         if (USER_AUTH_POLICY === 'strict') {
1168             if ($user = $this->nextClass())
1169                 return $user->userExists();
1170         }
1171         return false;
1172     }
1173
1174     function checkPass($submitted_password) {
1175         if (!isset($this->_authselect))
1176             trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'ADODB'",
1177                           E_USER_WARNING);
1178         $dbh = &$this->_auth_dbi;
1179         //NOTE: for auth_crypt_method='crypt'  defined('ENCRYPTED_PASSWD',true) must be set
1180         if ($this->_auth_crypt_method == 'crypt') {
1181             $rs = $dbh->Execute($this->_authselect,$dbh->qstr($this->_userid));
1182             if (!$rs->EOF) {
1183                 $stored_password = $rs->fields['password'];
1184                 $rs->Close();
1185                 $result = $this->_checkPass($submitted_password, $stored_password);
1186             } else {
1187                 $rs->Close();
1188                 $result = false;
1189             }
1190         }
1191         else {
1192             $rs = $dbh->Execute($this->_authselect,array(
1193                                           $dbh->qstr($submitted_password),
1194                                           $dbh->qstr($this->_userid)));
1195             $okay = $rs->fields['ok'];
1196             $rs->Close();
1197             $result = !empty($okay);
1198         }
1199
1200         if ($result) { 
1201             $this->_level = WIKIAUTH_USER;
1202         } else {
1203             if (USER_AUTH_POLICY === 'strict') {
1204                 if ($user = $this->nextClass()) {
1205                     if ($user = $user->userExists())
1206                         return $user->checkPass($submitted_password);
1207                 }
1208             }
1209             if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1210                 if ($user = $this->nextClass())
1211                     return $user->checkPass($submitted_password);
1212             }
1213         }
1214         return $this->_level;
1215     }
1216
1217     function storePass($submitted_password) {
1218         if (!isset($this->_authupdate)) {
1219             //CHECKME
1220             trigger_warning("Either \$DBAuthParams['auth_update'] not defined or \$DBParams['dbtype'] != 'ADODB'",
1221                           E_USER_WARNING);
1222             return false;
1223         }
1224
1225         if ($this->_auth_crypt_method == 'crypt') {
1226             if (function_exists('crypt'))
1227                 $submitted_password = crypt($submitted_password);
1228         }
1229         $dbh = &$this->_auth_dbi;
1230         $rs = $dbh->Execute($this->_authupdate,array(
1231                                       $dbh->qstr($submitted_password),
1232                                       $dbh->qstr($this->_userid)));
1233         $rs->Close();
1234     }
1235
1236 }
1237
1238 class _LDAPPassUser
1239 extends _PassUser
1240 /**
1241  * Define the vars LDAP_HOST and LDAP_BASE_DN in index.php
1242  *
1243  * Preferences are handled in _PassUser
1244  */
1245 {
1246     function checkPass($submitted_password) {
1247         $this->_authmethod = 'LDAP';
1248         $userid = $this->_userid;
1249         if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
1250             $r = @ldap_bind($ldap); // this is an anonymous bind
1251             // Need to set the right root search information. see ../index.php
1252             $sr = ldap_search($ldap, LDAP_BASE_DN, "uid=$userid");
1253             $info = ldap_get_entries($ldap, $sr); // there may be more hits with this userid. try every
1254             for ($i = 0; $i < $info["count"]; $i++) {
1255                 $dn = $info[$i]["dn"];
1256                 // The password is still plain text.
1257                 if ($r = @ldap_bind($ldap, $dn, $passwd)) {
1258                     // ldap_bind will return TRUE if everything matches
1259                     ldap_close($ldap);
1260                     $this->_level = WIKIAUTH_USER;
1261                     return $this->_level;
1262                 }
1263             }
1264         } else {
1265             trigger_error(_("Unable to connect to LDAP server "). LDAP_AUTH_HOST, E_USER_WARNING);
1266         }
1267
1268         if (USER_AUTH_POLICY === 'strict') {
1269             if ($user = $this->nextClass()) {
1270                 if ($user = $user->userExists())
1271                     return $user->checkPass($submitted_password);
1272             }
1273         }
1274         if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1275             if ($user = $this->nextClass())
1276                 return $user->checkPass($submitted_password);
1277         }
1278         return false;
1279     }
1280
1281     function userExists() {
1282         $userid = $this->_userid;
1283         if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
1284             $r = @ldap_bind($ldap);                 // this is an anonymous bind
1285             $sr = ldap_search($ldap, LDAP_BASE_DN, "uid=$userid");
1286             $info = ldap_get_entries($ldap, $sr);
1287             if ($info["count"] > 0) {
1288                 ldap_close($ldap);
1289                 return true;
1290             }
1291         } else {
1292             trigger_error(_("Unable to connect to LDAP server "). LDAP_AUTH_HOST, E_USER_WARNING);
1293         }
1294
1295         if (USER_AUTH_POLICY === 'strict') {
1296             if ($user = $this->nextClass())
1297                 return $user->userExists();
1298         }
1299         return false;
1300     }
1301
1302     function mayChangePass() {
1303         return false;
1304     }
1305
1306 }
1307
1308 class _IMAPPassUser
1309 extends _PassUser
1310 /**
1311  * Define the var IMAP_HOST in index.php
1312  *
1313  * Preferences are handled in _PassUser
1314  */
1315 {
1316     function checkPass($submitted_password) {
1317         $userid = $this->_userid;
1318         $mbox = @imap_open( "{" . IMAP_AUTH_HOST . "}",
1319                             $userid, $submitted_password, OP_HALFOPEN );
1320         if ($mbox) {
1321             imap_close($mbox);
1322             $this->_authmethod = 'IMAP';
1323             $this->_level = WIKIAUTH_USER;
1324             return $this->_level;
1325         } else {
1326             trigger_error(_("Unable to connect to IMAP server "). IMAP_AUTH_HOST, E_USER_WARNING);
1327         }
1328         if (USER_AUTH_POLICY === 'strict') {
1329             if ($user = $this->nextClass()) {
1330                 if ($user = $user->userExists())
1331                     return $user->checkPass($submitted_password);
1332             }
1333         }
1334         if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1335             if ($user = $this->nextClass())
1336                 return $user->checkPass($submitted_password);
1337         }
1338         return false;
1339     }
1340
1341     //CHECKME: this will not be okay for the auth policy strict
1342     function userExists() {
1343         if (checkPass($this->_prefs->get('passwd')))
1344             return true;
1345             
1346         if (USER_AUTH_POLICY === 'strict') {
1347             if ($user = $this->nextClass())
1348                 return $user->userExists();
1349         }
1350     }
1351
1352     function mayChangePass() {
1353         return false;
1354     }
1355
1356 }
1357
1358 class _FilePassUser
1359 extends _PassUser
1360 /**
1361  * Check users defined in a .htaccess style file
1362  * username:crypt\n...
1363  *
1364  * Preferences are handled in _PassUser
1365  */
1366 {
1367     var $_file, $_may_change;
1368
1369     // This can only be called from _PassUser, because the parent class 
1370     // sets the pref methods, before this class is initialized.
1371     function _FilePassUser($UserName='',$file='') {
1372         if (!$this->_prefs)
1373             _PassUser::_PassUser($UserName);
1374
1375         // read the .htaccess style file. We use our own copy of the standard pear class.
1376         require 'lib/pear/File_Passwd.php';
1377         // if passwords may be changed we have to lock them:
1378         $this->_may_change = defined('AUTH_USER_FILE_STORABLE') && AUTH_USER_FILE_STORABLE;
1379         if (empty($file) and defined('AUTH_USER_FILE'))
1380             $this->_file = File_Passwd(AUTH_USER_FILE, !empty($this->_may_change));
1381         elseif (!empty($file))
1382             $this->_file = File_Passwd($file, !empty($this->_may_change));
1383         else
1384             return false;
1385         return $this;
1386     }
1387  
1388     function mayChangePass() {
1389         return $this->_may_change;
1390     }
1391
1392     function userExists() {
1393         if (isset($this->_file->users[$this->_userid]))
1394             return true;
1395             
1396         if (USER_AUTH_POLICY === 'strict') {
1397             if ($user = $this->nextClass())
1398                 return $user->userExists();
1399         }
1400     }
1401
1402     function checkPass($submitted_password) {
1403         if ($this->_file->verifyPassword($this->_userid,$submitted_password)) {
1404             $this->_authmethod = 'File';
1405             $this->_level = WIKIAUTH_USER;
1406             return $this->_level;
1407         }
1408         
1409         if (USER_AUTH_POLICY === 'strict') {
1410             if ($user = $this->nextClass()) {
1411                 if ($user = $user->userExists())
1412                     return $user->checkPass($submitted_password);
1413             }
1414         }
1415         if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1416             if ($user = $this->nextClass())
1417                 return $user->checkPass($submitted_password);
1418         }
1419         return false;
1420     }
1421
1422     function storePass($submitted_password) {
1423         if ($this->_may_change)
1424             return $this->_file->modUser($this->_userid,$submitted_password);
1425         else 
1426             return false;
1427     }
1428
1429 }
1430
1431 /**
1432  * Insert more auth classes here...
1433  *
1434  */
1435
1436
1437 /**
1438  * For security, this class should not be extended. Instead, extend
1439  * from _PassUser (think of this as unix "root").
1440  */
1441 class _AdminUser
1442 extends _PassUser
1443 {
1444     //var $_level = WIKIAUTH_ADMIN;
1445
1446     function checkPass($submitted_password) {
1447         $stored_password = ADMIN_PASSWD;
1448         if ($this->_checkPass($submitted_password, $stored_password)) {
1449             $this->_level = WIKIAUTH_ADMIN;
1450             return $this->_level;
1451         } else {
1452             $this->_level = WIKIAUTH_ANON;
1453             return false;
1454         }
1455     }
1456
1457 }
1458
1459 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1460 /**
1461  * Various data classes for the preference types, 
1462  * to support get, set, sanify (range checking, ...)
1463  * update() will do the neccessary side-effects if a 
1464  * setting gets changed (theme, language, ...)
1465 */
1466
1467 class _UserPreference
1468 {
1469     var $default_value;
1470
1471     function _UserPreference ($default_value) {
1472         $this->default_value = $default_value;
1473     }
1474
1475     function sanify ($value) {
1476         return (string)$value;
1477     }
1478
1479     function get ($name) {
1480         if (isset($this->$name))
1481             return $this->{$name};
1482         else 
1483             return $this->default_value;
1484     }
1485
1486     function getraw ($name) {
1487         if (!empty($this->{$name}))
1488             return $this->{$name};
1489     }
1490
1491     // stores the value as $this->$name, and not as $this->value (clever?)
1492     function set ($name, $value) {
1493         if ($value != $this->default_value)
1494             $this->$name = $value;
1495         else 
1496             unset($this->$name);
1497     }
1498
1499     // default: no side-effects 
1500     function update ($value) {
1501     }
1502 }
1503
1504 class _UserPreference_numeric
1505 extends _UserPreference
1506 {
1507     function _UserPreference_numeric ($default, $minval = false,
1508                                       $maxval = false) {
1509         $this->_UserPreference((double)$default);
1510         $this->_minval = (double)$minval;
1511         $this->_maxval = (double)$maxval;
1512     }
1513
1514     function sanify ($value) {
1515         $value = (double)$value;
1516         if ($this->_minval !== false && $value < $this->_minval)
1517             $value = $this->_minval;
1518         if ($this->_maxval !== false && $value > $this->_maxval)
1519             $value = $this->_maxval;
1520         return $value;
1521     }
1522 }
1523
1524 class _UserPreference_int
1525 extends _UserPreference_numeric
1526 {
1527     function _UserPreference_int ($default, $minval = false, $maxval = false) {
1528         $this->_UserPreference_numeric((int)$default, (int)$minval,
1529                                        (int)$maxval);
1530     }
1531
1532     function sanify ($value) {
1533         return (int)parent::sanify((int)$value);
1534     }
1535 }
1536
1537 class _UserPreference_bool
1538 extends _UserPreference
1539 {
1540     function _UserPreference_bool ($default = false) {
1541         $this->_UserPreference((bool)$default);
1542     }
1543
1544     function sanify ($value) {
1545         if (is_array($value)) {
1546             /* This allows for constructs like:
1547              *
1548              *   <input type="hidden" name="pref[boolPref][]" value="0" />
1549              *   <input type="checkbox" name="pref[boolPref][]" value="1" />
1550              *
1551              * (If the checkbox is not checked, only the hidden input
1552              * gets sent. If the checkbox is sent, both inputs get
1553              * sent.)
1554              */
1555             foreach ($value as $val) {
1556                 if ($val)
1557                     return true;
1558             }
1559             return false;
1560         }
1561         return (bool) $value;
1562     }
1563 }
1564
1565 class _UserPreference_language
1566 extends _UserPreference
1567 {
1568     function _UserPreference_language ($default = DEFAULT_LANGUAGE) {
1569         $this->_UserPreference($default);
1570     }
1571
1572     // FIXME: check for valid locale
1573     function sanify ($value) {
1574         // Revert to DEFAULT_LANGUAGE if user does not specify
1575         // language in UserPreferences or chooses <system language>.
1576         if ($value == '' or empty($value))
1577             $value = DEFAULT_LANGUAGE;
1578
1579         return (string) $value;
1580     }
1581 }
1582
1583 class _UserPreference_theme
1584 extends _UserPreference
1585 {
1586     function _UserPreference_theme ($default = THEME) {
1587         $this->_UserPreference($default);
1588     }
1589
1590     function sanify ($value) {
1591         if (file_exists($this->_themefile($value)))
1592             return $value;
1593         return $this->default_value;
1594     }
1595
1596     function update ($newvalue) {
1597         global $Theme;
1598         include_once($this->_themefile($newvalue));
1599         if (empty($Theme))
1600             include_once($this->_themefile(THEME));
1601     }
1602
1603     function _themefile ($theme) {
1604         return "themes/$theme/themeinfo.php";
1605     }
1606 }
1607
1608 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1609
1610 /**
1611  * UserPreferences
1612  * 
1613  * This object holds the $request->_prefs subobjects.
1614  * A simple packed array of non-default values get's stored as cookie,
1615  * homepage, or database, which are converted to the array of 
1616  * ->_prefs objects.
1617  * We don't store the objects, because otherwise we will
1618  * not be able to upgrade any subobject. And it's a waste of space also.
1619  */
1620 class UserPreferences
1621 {
1622     function UserPreferences ($saved_prefs = false) {
1623         // userid stored too, to ensure the prefs are being loaded for
1624         // the correct (currently signing in) userid if stored in a
1625         // cookie.
1626         $this->_prefs
1627             = array(
1628                     'userid'        => new _UserPreference(''),
1629                     'passwd'        => new _UserPreference(''),
1630                     'autologin'     => new _UserPreference_bool(),
1631                     'email'         => new _UserPreference(''),
1632                     'emailVerified' => new _UserPreference_bool(),
1633                     'notifyPages'   => new _UserPreference(''),
1634                     'theme'         => new _UserPreference_theme(THEME),
1635                     'lang'          => new _UserPreference_language(DEFAULT_LANGUAGE),
1636                     'editWidth'     => new _UserPreference_int(EDITWIDTH_DEFAULT_COLS,
1637                                                                EDITWIDTH_MIN_COLS,
1638                                                                EDITWIDTH_MAX_COLS),
1639                     'noLinkIcons'   => new _UserPreference_bool(),
1640                     'editHeight'    => new _UserPreference_int(EDITHEIGHT_DEFAULT_ROWS,
1641                                                                EDITHEIGHT_MIN_ROWS,
1642                                                                EDITHEIGHT_DEFAULT_ROWS),
1643                     'timeOffset'    => new _UserPreference_numeric(TIMEOFFSET_DEFAULT_HOURS,
1644                                                                    TIMEOFFSET_MIN_HOURS,
1645                                                                    TIMEOFFSET_MAX_HOURS),
1646                     'relativeDates' => new _UserPreference_bool()
1647                     );
1648
1649         if (is_array($saved_prefs)) {
1650             foreach ($saved_prefs as $name => $value)
1651                 $this->set($name, $value);
1652         }
1653     }
1654
1655     function _getPref ($name) {
1656         if (!isset($this->_prefs[$name])) {
1657             if ($name == 'passwd2') return false;
1658             trigger_error("$name: unknown preference", E_USER_NOTICE);
1659             return false;
1660         }
1661         return $this->_prefs[$name];
1662     }
1663     
1664     // get the value or default_value of the subobject
1665     function get ($name) {
1666         if ($_pref = $this->_getPref($name))
1667           return $_pref->get($name);
1668         else 
1669           return false;  
1670         /*      
1671         if (is_object($this->_prefs[$name]))
1672             return $this->_prefs[$name]->get($name);
1673         elseif (($value = $this->_getPref($name)) === false)
1674             return false;
1675         elseif (!isset($value))
1676             return $this->_prefs[$name]->default_value;
1677         else return $value;
1678         */
1679     }
1680
1681     // check and set the new value in the subobject
1682     function set ($name, $value) {
1683         $pref = $this->_getPref($name);
1684         if ($pref === false)
1685             return false;
1686
1687         /* do it here or outside? */
1688         if ($name == 'passwd' and 
1689             defined('PASSWORD_LENGTH_MINIMUM') and 
1690             strlen($value) <= PASSWORD_LENGTH_MINIMUM ) {
1691             //TODO: How to notify the user?
1692             return false;
1693         }
1694
1695         $newvalue = $pref->sanify($value);
1696         $oldvalue = $pref->get($name);
1697
1698         // update on changes
1699         if ($newvalue != $oldvalue)
1700             $pref->update($newvalue);
1701         return true;
1702
1703         // don't set default values to save space (in cookies, db and
1704         // sesssion)
1705         /*
1706         if ($value == $pref->default_value)
1707             unset($this->_prefs[$name]);
1708         else
1709             $this->_prefs[$name] = $pref;
1710         */
1711     }
1712
1713     // array of objects => array of values
1714     function store() {
1715         $prefs = array();
1716         foreach ($this->_prefs as $name => $object) {
1717             if ($value = $object->getraw($name))
1718                 $prefs[] = array($name => $value);
1719         }
1720         return $this->pack($prefs);
1721     }
1722
1723     // packed string or array of values => array of values
1724     function retrieve($packed) {
1725         if (is_string($packed) and (substr($packed, 0, 2) == "a:"))
1726             $packed = unserialize($packed);
1727         if (!is_array($packed)) return false;
1728         $prefs = array();
1729         foreach ($packed as $name => $packed_pref) {
1730             if (substr($packed_pref, 0, 2) == "O:") {
1731                 //legacy: check if it's an old array of objects
1732                 // Looks like a serialized object. 
1733                 // This might fail if the object definition does not exist anymore.
1734                 // object with ->$name and ->default_value vars.
1735                 $pref = unserialize($packed_pref);
1736                 $prefs[$name] = $pref->get($name);
1737             } else {
1738                 $prefs[$name] = unserialize($packed_pref);
1739             }
1740         }
1741         return $prefs;
1742     }
1743     
1744     // array of objects
1745     function getAll() {
1746         return $this->_prefs;
1747     }
1748
1749     function pack($nonpacked) {
1750         return serialize($nonpacked);
1751     }
1752
1753     function unpack($packed) {
1754         if (!$packed)
1755             return false;
1756         if (substr($packed, 0, 2) == "O:") {
1757             // Looks like a serialized object
1758             return unserialize($packed);
1759         }
1760         //trigger_error("DEBUG: Can't unpack bad UserPreferences",
1761         //E_USER_WARNING);
1762         return false;
1763     }
1764
1765     function hash () {
1766         return hash($this->_prefs);
1767     }
1768 }
1769
1770 class CookieUserPreferences
1771 extends UserPreferences
1772 {
1773     function CookieUserPreferences ($saved_prefs = false) {
1774         UserPreferences::UserPreferences($saved_prefs);
1775     }
1776 }
1777
1778 class PageUserPreferences
1779 extends UserPreferences
1780 {
1781     function PageUserPreferences ($saved_prefs = false) {
1782         UserPreferences::UserPreferences($saved_prefs);
1783     }
1784 }
1785
1786 class DbUserPreferences
1787 extends UserPreferences
1788 {
1789     function DbUserPreferences ($saved_prefs = false) {
1790         UserPreferences::UserPreferences($saved_prefs);
1791     }
1792 }
1793
1794
1795 // $Log: not supported by cvs2svn $
1796 // Revision 1.12  2004/02/07 10:41:25  rurban
1797 // fixed auth from session (still double code but works)
1798 // fixed GroupDB
1799 // fixed DbPassUser upgrade and policy=old
1800 // added GroupLdap
1801 //
1802 // Revision 1.11  2004/02/03 09:45:39  rurban
1803 // LDAP cleanup, start of new Pref classes
1804 //
1805 // Revision 1.10  2004/02/01 09:14:11  rurban
1806 // Started with Group_Ldap (not yet ready)
1807 // added new _AuthInfo plugin to help in auth problems (warning: may display passwords)
1808 // fixed some configurator vars
1809 // renamed LDAP_AUTH_SEARCH to LDAP_BASE_DN
1810 // changed PHPWIKI_VERSION from 1.3.8a to 1.3.8pre
1811 // USE_DB_SESSION defaults to true on SQL
1812 // changed GROUP_METHOD definition to string, not constants
1813 // changed sample user DBAuthParams from UPDATE to REPLACE to be able to
1814 //   create users. (Not to be used with external databases generally, but
1815 //   with the default internal user table)
1816 //
1817 // fixed the IndexAsConfigProblem logic. this was flawed:
1818 //   scripts which are the same virtual path defined their own lib/main call
1819 //   (hmm, have to test this better, phpwiki.sf.net/demo works again)
1820 //
1821 // Revision 1.9  2004/01/30 19:57:58  rurban
1822 // fixed DBAuthParams['pref_select']: wrong _auth_dbi object used.
1823 //
1824 // Revision 1.8  2004/01/30 18:46:15  rurban
1825 // fix "lib/WikiUserNew.php:572: Notice[8]: Undefined variable: DBParams"
1826 //
1827 // Revision 1.7  2004/01/27 23:23:39  rurban
1828 // renamed ->Username => _userid for consistency
1829 // renamed mayCheckPassword => mayCheckPass
1830 // fixed recursion problem in WikiUserNew
1831 // fixed bogo login (but not quite 100% ready yet, password storage)
1832 //
1833 // Revision 1.6  2004/01/26 09:17:49  rurban
1834 // * changed stored pref representation as before.
1835 //   the array of objects is 1) bigger and 2)
1836 //   less portable. If we would import packed pref
1837 //   objects and the object definition was changed, PHP would fail.
1838 //   This doesn't happen with an simple array of non-default values.
1839 // * use $prefs->retrieve and $prefs->store methods, where retrieve
1840 //   understands the interim format of array of objects also.
1841 // * simplified $prefs->get() and fixed $prefs->set()
1842 // * added $user->_userid and class '_WikiUser' portability functions
1843 // * fixed $user object ->_level upgrading, mostly using sessions.
1844 //   this fixes yesterdays problems with loosing authorization level.
1845 // * fixed WikiUserNew::checkPass to return the _level
1846 // * fixed WikiUserNew::isSignedIn
1847 // * added explodePageList to class PageList, support sortby arg
1848 // * fixed UserPreferences for WikiUserNew
1849 // * fixed WikiPlugin for empty defaults array
1850 // * UnfoldSubpages: added pagename arg, renamed pages arg,
1851 //   removed sort arg, support sortby arg
1852 //
1853 // Revision 1.5  2004/01/25 03:05:00  rurban
1854 // First working version, but has some problems with the current main loop.
1855 // Implemented new auth method dispatcher and policies, all the external
1856 // _PassUser classes (also for ADODB and Pear DB).
1857 // The two global funcs UserExists() and CheckPass() are probably not needed,
1858 // since the auth loop is done recursively inside the class code, upgrading
1859 // the user class within itself.
1860 // Note: When a higher user class is returned, this doesn't mean that the user
1861 // is authorized, $user->_level is still low, and only upgraded on successful
1862 // login.
1863 //
1864 // Revision 1.4  2003/12/07 19:29:48  carstenklapp
1865 // Code Housecleaning: fixed syntax errors. (php -l *.php)
1866 //
1867 // Revision 1.3  2003/12/06 19:10:46  carstenklapp
1868 // Finished off logic for determining user class, including
1869 // PassUser. Removed ability of BogoUser to save prefs into a page.
1870 //
1871 // Revision 1.2  2003/12/03 21:45:48  carstenklapp
1872 // Added admin user, password user, and preference classes. Added
1873 // password checking functions for users and the admin. (Now the easy
1874 // parts are nearly done).
1875 //
1876 // Revision 1.1  2003/12/02 05:46:36  carstenklapp
1877 // Complete rewrite of WikiUser.php.
1878 //
1879 // This should make it easier to hook in user permission groups etc. some
1880 // time in the future. Most importantly, to finally get UserPreferences
1881 // fully working properly for all classes of users: AnonUser, BogoUser,
1882 // AdminUser; whether they have a NamesakePage (PersonalHomePage) or not,
1883 // want a cookie or not, and to bring back optional AutoLogin with the
1884 // UserName stored in a cookie--something that was lost after PhpWiki had
1885 // dropped the default http auth login method.
1886 //
1887 // Added WikiUser classes which will (almost) work together with existing
1888 // UserPreferences class. Other parts of PhpWiki need to be updated yet
1889 // before this code can be hooked up.
1890 //
1891
1892 // Local Variables:
1893 // mode: php
1894 // tab-width: 8
1895 // c-basic-offset: 4
1896 // c-hanging-comment-ender-p: nil
1897 // indent-tabs-mode: nil
1898 // End:
1899 ?>