]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiUserNew.php
fixed problem with unnecessary emailVerification mails on session_init
[SourceForge/phpwiki.git] / lib / WikiUserNew.php
1 <?php //-*-php-*-
2 rcs_id('$Id: WikiUserNew.php,v 1.41 2004-03-27 13:39:58 rurban Exp $');
3 /* Copyright (C) 2004 $ThePhpWikiProgrammingTeam
4  */
5 /**
6  * This is a complete OOP rewrite of the old WikiUser code with various
7  * configurable external authentication methods.
8  *
9  * There's only one entry point, the function WikiUser which returns 
10  * a WikiUser object, which contains the user's preferences.
11  * This object might get upgraded during the login step and later also.
12  * There exist three preferences storage methods: cookie, homepage and db,
13  * and multiple password checking methods.
14  * See index.php for $USER_AUTH_ORDER[] and USER_AUTH_POLICY if 
15  * ALLOW_USER_PASSWORDS is defined.
16  *
17  * Each user object must define the two preferences methods 
18  *  getPreferences(), setPreferences(), 
19  * and the following 1-4 auth methods
20  *  checkPass()  must be defined by all classes,
21  *  userExists() only if USER_AUTH_POLICY'=='strict' 
22  *  mayChangePass()  only if the password is storable.
23  *  storePass()  only if the password is storable.
24  *
25  * WikiUser() given no name, returns an _AnonUser (anonymous user)
26  * object, who may or may not have a cookie. 
27  * However, if the there's a cookie with the userid or a session, 
28  * the user is upgraded to the matching user object.
29  * Given a user name, returns a _BogoUser object, who may or may not 
30  * have a cookie and/or PersonalPage, one of the various _PassUser objects 
31  * or an _AdminUser object.
32  * BTW: A BogoUser is a userid (loginname) as valid WikiWord, who might 
33  * have stored a password or not. If so, his account is secure, if not
34  * anybody can use it, because the username is visible e.g. in RecentChanges.
35  *
36  * Takes care of passwords, all preference loading/storing in the
37  * user's page and any cookies. lib/main.php will query the user object to
38  * verify the password as appropriate.
39  *
40  * @author: Reini Urban (the tricky parts), 
41  *          Carsten Klapp (started rolling the ball)
42  *
43  * Notes by 2004-01-25 03:43:45 rurban
44  * Test it by defining ENABLE_USER_NEW in index.php
45  * 1) Now a ForbiddenUser is returned instead of false.
46  * 2) Previously ALLOW_ANON_USER = false meant that anon users cannot edit, 
47  *    but may browse. Now with ALLOW_ANON_USER = false he may not browse, 
48  *    which is needed to disable browse PagePermissions.
49  *    I added now ALLOW_ANON_EDIT = true to makes things clear. 
50  *    (which replaces REQUIRE_SIGNIN_BEFORE_EDIT)
51  * 2004-02-27 rurban:
52  * 3) Removed pear prepare. Performance hog, and using integers as 
53  *    handler doesn't help. Do simple sprintf as with adodb. And a prepare
54  *    in the object init is no advantage, because in the init loop a lot of 
55  *    objects are tried, but not used.
56  * 4) Already gotten prefs are passed to the next object to avoid 
57  *    duplicate getPreferences() calls.
58  * 2004-03-18 17:32:21 rurban
59  * 5) Major php-5 problem: $this re-assignment is disallowed by the parser
60  *    So we cannot just discrimate with 
61  *      if (!check_php_version(5))
62  *          $this = $user;
63  * 2004-03-24 rurban
64  * 6) enforced new cookie policy: prefs don't get stored in cookies
65  *    anymore, only in homepage and/or database, but always in the 
66  *    current session. old pref cookies will get deleted.
67  */
68
69 define('WIKIAUTH_FORBIDDEN', -1); // Completely not allowed.
70 define('WIKIAUTH_ANON', 0);       // Not signed in.
71 define('WIKIAUTH_BOGO', 1);       // Any valid WikiWord is enough.
72 define('WIKIAUTH_USER', 2);       // Bogo user with a password.
73 define('WIKIAUTH_ADMIN', 10);     // UserName == ADMIN_USER.
74
75 if (!defined('COOKIE_EXPIRATION_DAYS')) define('COOKIE_EXPIRATION_DAYS', 365);
76 if (!defined('COOKIE_DOMAIN'))          define('COOKIE_DOMAIN', '/');
77
78 if (!defined('EDITWIDTH_MIN_COLS'))     define('EDITWIDTH_MIN_COLS',     30);
79 if (!defined('EDITWIDTH_MAX_COLS'))     define('EDITWIDTH_MAX_COLS',    150);
80 if (!defined('EDITWIDTH_DEFAULT_COLS')) define('EDITWIDTH_DEFAULT_COLS', 80);
81
82 if (!defined('EDITHEIGHT_MIN_ROWS'))     define('EDITHEIGHT_MIN_ROWS',      5);
83 if (!defined('EDITHEIGHT_MAX_ROWS'))     define('EDITHEIGHT_MAX_ROWS',     80);
84 if (!defined('EDITHEIGHT_DEFAULT_ROWS')) define('EDITHEIGHT_DEFAULT_ROWS', 22);
85
86 define('TIMEOFFSET_MIN_HOURS', -26);
87 define('TIMEOFFSET_MAX_HOURS',  26);
88 if (!defined('TIMEOFFSET_DEFAULT_HOURS')) define('TIMEOFFSET_DEFAULT_HOURS', 0);
89
90 /**
91  * There are be the following constants in index.php to 
92  * establish login parameters:
93  *
94  * ALLOW_ANON_USER         default true
95  * ALLOW_ANON_EDIT         default true
96  * ALLOW_BOGO_LOGIN        default true
97  * ALLOW_USER_PASSWORDS    default true
98  * PASSWORD_LENGTH_MINIMUM default 6 ?
99  *
100  * To require user passwords for editing:
101  * ALLOW_ANON_USER  = true
102  * ALLOW_ANON_EDIT  = false   (before named REQUIRE_SIGNIN_BEFORE_EDIT)
103  * ALLOW_BOGO_LOGIN = false
104  * ALLOW_USER_PASSWORDS = true
105  *
106  * To establish a COMPLETELY private wiki, such as an internal
107  * corporate one:
108  * ALLOW_ANON_USER = false
109  * (and probably require user passwords as described above). In this
110  * case the user will be prompted to login immediately upon accessing
111  * any page.
112  *
113  * There are other possible combinations, but the typical wiki (such
114  * as http://PhpWiki.sf.net/phpwiki) would usually just leave all four 
115  * enabled.
116  *
117  */
118
119 // The last object in the row is the bad guy...
120 if (!is_array($USER_AUTH_ORDER))
121     $USER_AUTH_ORDER = array("Forbidden");
122 else
123     $USER_AUTH_ORDER[] = "Forbidden";
124
125 // Local convenience functions.
126 function _isAnonUserAllowed() {
127     return (defined('ALLOW_ANON_USER') && ALLOW_ANON_USER);
128 }
129 function _isBogoUserAllowed() {
130     return (defined('ALLOW_BOGO_LOGIN') && ALLOW_BOGO_LOGIN);
131 }
132 function _isUserPasswordsAllowed() {
133     return (defined('ALLOW_USER_PASSWORDS') && ALLOW_USER_PASSWORDS);
134 }
135
136 // Possibly upgrade userobject functions.
137 function _determineAdminUserOrOtherUser($UserName) {
138     // Sanity check. User name is a condition of the definition of the
139     // _AdminUser, _BogoUser and _passuser.
140     if (!$UserName)
141         return $GLOBALS['ForbiddenUser'];
142
143     if ($UserName == ADMIN_USER)
144         return new _AdminUser($UserName);
145     else
146         return _determineBogoUserOrPassUser($UserName);
147 }
148
149 function _determineBogoUserOrPassUser($UserName) {
150     global $ForbiddenUser;
151
152     // Sanity check. User name is a condition of the definition of
153     // _BogoUser and _PassUser.
154     if (!$UserName)
155         return $ForbiddenUser;
156
157     // Check for password and possibly upgrade user object.
158     // $_BogoUser = new _BogoUser($UserName);
159     if (_isBogoUserAllowed()) {
160         $_BogoUser = new _BogoLoginPassUser($UserName);
161         if ($_BogoUser->userExists())
162             return $_BogoUser;
163     }
164     if (_isUserPasswordsAllowed()) {
165         // PassUsers override BogoUsers if a password is stored
166         if (isset($_BogoUser) and $_BogoUser->_prefs->get('passwd'))
167             return new _PassUser($UserName,$_BogoUser->_prefs);
168         else { 
169             $_PassUser = new _PassUser($UserName,isset($_BogoUser) ? $_BogoUser->_prefs : false);
170             if ($_PassUser->userExists())
171                 return $_PassUser;
172         }
173     }
174     // No Bogo- or PassUser exists, or
175     // passwords are not allowed, and bogo is disallowed too.
176     // (Only the admin can sign in).
177     return $ForbiddenUser;
178 }
179
180 /**
181  * Primary WikiUser function, called by lib/main.php.
182  * 
183  * This determines the user's type and returns an appropriate user
184  * object. lib/main.php then querys the resultant object for password
185  * validity as necessary.
186  *
187  * If an _AnonUser object is returned, the user may only browse pages
188  * (and save prefs in a cookie).
189  *
190  * To disable access but provide prefs the global $ForbiddenUser class 
191  * is returned. (was previously false)
192  * 
193  */
194 function WikiUser ($UserName = '') {
195     global $ForbiddenUser;
196
197     //Maybe: Check sessionvar for username & save username into
198     //sessionvar (may be more appropriate to do this in lib/main.php).
199     if ($UserName) {
200         $ForbiddenUser = new _ForbiddenUser($UserName);
201         // Found a user name.
202         return _determineAdminUserOrOtherUser($UserName);
203     }
204     elseif (!empty($_SESSION['userid'])) {
205         // Found a user name.
206         $ForbiddenUser = new _ForbiddenUser($_SESSION['userid']);
207         return _determineAdminUserOrOtherUser($_SESSION['userid']);
208     }
209     else {
210         // Check for autologin pref in cookie and possibly upgrade
211         // user object to another type.
212         $_AnonUser = new _AnonUser();
213         if ($UserName = $_AnonUser->_userid && $_AnonUser->_prefs->get('autologin')) {
214             // Found a user name.
215             $ForbiddenUser = new _ForbiddenUser($UserName);
216             return _determineAdminUserOrOtherUser($UserName);
217         }
218         else {
219             $ForbiddenUser = new _ForbiddenUser();
220             if (_isAnonUserAllowed())
221                 return $_AnonUser;
222             return $ForbiddenUser; // User must sign in to browse pages.
223         }
224         return $ForbiddenUser;     // User must sign in with a password.
225     }
226     /*
227     trigger_error("DEBUG: Note: End of function reached in WikiUser." . " "
228                   . "Unexpectedly, an appropriate user class could not be determined.");
229     return $ForbiddenUser; // Failsafe.
230     */
231 }
232
233 /**
234  * WikiUser.php use the name 'WikiUser'
235  */
236 function WikiUserClassname() {
237     return '_WikiUser';
238 }
239
240
241 /**
242  * Upgrade olduser by copying properties from user to olduser.
243  * We are not sure yet, for which php's a simple $this = $user works reliably,
244  * (on php4 it works ok, on php5 it's currently disallowed on the parser level)
245  * that's why try it the hard way.
246  */
247 function UpgradeUser ($olduser, $user) {
248     if (isa($user,'_WikiUser') and isa($olduser,'_WikiUser')) {
249         // populate the upgraded class $olduser with the values from the new user object
250         //only _auth_level, _current_method, _current_index,
251         if (!empty($user->_level) and 
252             $user->_level > $olduser->_level)
253             $olduser->_level = $user->_level;
254         if (!empty($user->_current_index) and
255             $user->_current_index > $olduser->_current_index) {
256             $olduser->_current_index = $user->_current_index;
257             $olduser->_current_method = $user->_current_method;
258         }
259         if (!empty($user->_authmethod))
260             $olduser->_authmethod = $user->_authmethod;
261         /*
262         foreach (get_object_vars($user) as $k => $v) {
263             if (!empty($v)) $olduser->$k = $v;  
264         }
265         */
266         $olduser->hasHomePage(); // revive db handle, because these don't survive sessions
267         $GLOBALS['request']->_user = $olduser;
268         return $olduser;
269     } else {
270         return false;
271     }
272 }
273
274 /**
275  * Probably not needed, since we use the various user objects methods so far.
276  * Anyway, here it is, looping through all available objects.
277  */
278 function UserExists ($UserName) {
279     global $request;
280     if (!($user = $request->getUser()))
281         $user = WikiUser($UserName);
282     if (!$user) 
283         return false;
284     if ($user->userExists($UserName)) {
285         $request->_user = $user;
286         return true;
287     }
288     if (isa($user,'_BogoUser'))
289         $user = new _PassUser($UserName,$user->_prefs);
290     $class = $user->nextClass();
291     if ($user = new $class($UserName,$user->_prefs)) {
292         return $user->userExists($UserName);
293     }
294     $request->_user = $GLOBALS['ForbiddenUser'];
295     return false;
296 }
297
298 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
299
300 /** 
301  * Base WikiUser class.
302  */
303 class _WikiUser
304 {
305      var $_userid = '';
306      var $_level = WIKIAUTH_FORBIDDEN;
307      var $_prefs = false;
308      var $_HomePagehandle = false;
309
310     // constructor
311     function _WikiUser($UserName='', $prefs=false) {
312
313         $this->_userid = $UserName;
314         $this->_HomePagehandle = false;
315         if ($UserName) {
316             $this->hasHomePage();
317         }
318         $this->_level = WIKIAUTH_FORBIDDEN;
319         if (empty($this->_prefs)) {
320             if ($prefs) $this->_prefs = $prefs;
321             else $this->getPreferences();
322         }
323     }
324
325     function UserName() {
326         if (!empty($this->_userid))
327             return $this->_userid;
328     }
329
330     function getPreferences() {
331         trigger_error("DEBUG: Note: undefined _WikiUser class trying to load prefs." . " "
332                       . "New subclasses of _WikiUser must override this function.");
333         return false;
334     }
335
336     function setPreferences($prefs, $id_only) {
337         trigger_error("DEBUG: Note: undefined _WikiUser class trying to save prefs." . " "
338                       . "New subclasses of _WikiUser must override this function.");
339         return false;
340     }
341
342     function userExists() {
343         return $this->hasHomePage();
344     }
345
346     function checkPass($submitted_password) {
347         // By definition, an undefined user class cannot sign in.
348         trigger_error("DEBUG: Warning: undefined _WikiUser class trying to sign in." . " "
349                       . "New subclasses of _WikiUser must override this function.");
350         return false;
351     }
352
353     // returns page_handle to user's home page or false if none
354     function hasHomePage() {
355         if ($this->_userid) {
356             if (!empty($this->_HomePagehandle) and is_object($this->_HomePagehandle)) {
357                 return $this->_HomePagehandle->exists();
358             }
359             else {
360                 // check db again (maybe someone else created it since
361                 // we logged in.)
362                 global $request;
363                 $this->_HomePagehandle = $request->getPage($this->_userid);
364                 return $this->_HomePagehandle->exists();
365             }
366         }
367         // nope
368         return false;
369     }
370
371     // innocent helper: case-insensitive position in _auth_methods
372     function array_position ($string, $array) {
373         $string = strtolower($string);
374         for ($found = 0; $found < count($array); $found++) {
375             if (strtolower($array[$found]) == $string)
376                 return $found;
377         }
378         return false;
379     }
380
381     function nextAuthMethodIndex() {
382         if (empty($this->_auth_methods)) 
383             $this->_auth_methods = $GLOBALS['USER_AUTH_ORDER'];
384         if (empty($this->_current_index)) {
385             if (get_class($this) != '_passuser') {
386                 $this->_current_method = substr(get_class($this),1,-8);
387                 $this->_current_index = $this->array_position($this->_current_method,
388                                                               $this->_auth_methods);
389             } else {
390                 $this->_current_index = -1;
391             }
392         }
393         $this->_current_index++;
394         if ($this->_current_index >= count($this->_auth_methods))
395             return false;
396         $this->_current_method = $this->_auth_methods[$this->_current_index];
397         return $this->_current_index;
398     }
399
400     function AuthMethod($index = false) {
401         return $this->_auth_methods[ $index === false ? 0 : $index];
402     }
403
404     // upgrade the user object
405     function nextClass() {
406         if (($next = $this->nextAuthMethodIndex()) !== false) {
407             $method = $this->AuthMethod($next);
408             return "_".$method."PassUser";
409             /*          
410             if ($user = new $class($this->_userid)) {
411                 // prevent from endless recursion.
412                 //$user->_current_method = $this->_current_method;
413                 //$user->_current_index = $this->_current_index;
414                 $user = UpgradeUser($user, $this);
415             }
416             return $user;
417             */
418         }
419         return "_ForbiddenPassUser";
420     }
421
422     //Fixme: for _HttpAuthPassUser
423     function PrintLoginForm (&$request, $args, $fail_message = false,
424                              $seperate_page = true) {
425         include_once('lib/Template.php');
426         // Call update_locale in case the system's default language is not 'en'.
427         // (We have no user pref for lang at this point yet, no one is logged in.)
428         update_locale(DEFAULT_LANGUAGE);
429         $userid = $this->_userid;
430         $require_level = 0;
431         extract($args); // fixme
432
433         $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
434
435         $pagename = $request->getArg('pagename');
436         $nocache = 1;
437         $login = new Template('login', $request,
438                               compact('pagename', 'userid', 'require_level',
439                                       'fail_message', 'pass_required', 'nocache'));
440         if ($seperate_page) {
441             $top = new Template('html', $request,
442                                 array('TITLE' => _("Sign In")));
443             return $top->printExpansion($login);
444         } else {
445             return $login;
446         }
447     }
448
449     /** Signed in but probably not password checked.
450      */
451     function isSignedIn() {
452         return (isa($this,'_BogoUser') or isa($this,'_PassUser'));
453     }
454
455     /** This is password checked for sure.
456      */
457     function isAuthenticated () {
458         //return isa($this,'_PassUser');
459         //return isa($this,'_BogoUser') || isa($this,'_PassUser');
460         return $this->_level >= WIKIAUTH_BOGO; // hmm.
461     }
462
463     function isAdmin () {
464         return $this->_level == WIKIAUTH_ADMIN;
465     }
466
467     /** Name or IP for a signed user. UserName could come from a cookie e.g.
468      */
469     function getId () {
470         return ( $this->UserName()
471                  ? $this->UserName()
472                  : $GLOBALS['request']->get('REMOTE_ADDR') ); // FIXME: globals
473     }
474
475     /** Name for an authenticated user. No IP here.
476      */
477     function getAuthenticatedId() {
478         return ( $this->isAuthenticated()
479                  ? $this->_userid
480                  : ''); //$GLOBALS['request']->get('REMOTE_ADDR') ); // FIXME: globals
481     }
482
483     function hasAuthority ($require_level) {
484         return $this->_level >= $require_level;
485     }
486
487     /**
488      * Called on an auth_args POST request, such as login, logout or signin.
489      */
490     function AuthCheck ($postargs) {
491         // Normalize args, and extract.
492         $keys = array('userid', 'passwd', 'require_level', 'login', 'logout',
493                       'cancel');
494         foreach ($keys as $key)
495             $args[$key] = isset($postargs[$key]) ? $postargs[$key] : false;
496         extract($args);
497         $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
498
499         if ($logout) { // Log out
500             $GLOBALS['request']->_user = new _AnonUser();
501             return $GLOBALS['request']->_user; 
502         } elseif ($cancel)
503             return false;        // User hit cancel button.
504         elseif (!$login && !$userid)
505             return false;       // Nothing to do?
506
507         $authlevel = $this->checkPass($passwd === false ? '' : $passwd);
508         if (!$authlevel)
509             return _("Invalid password or userid.");
510         elseif ($authlevel < $require_level)
511             return _("Insufficient permissions.");
512
513         // Successful login.
514         $user = $GLOBALS['request']->_user;
515         $user->_userid = $userid;
516         $user->_level = $authlevel;
517         return $user;
518     }
519
520 }
521
522 /**
523  * Not authenticated in user, but he may be signed in. Basicly with view access only.
524  * prefs are stored in cookies, but only the userid.
525  */
526 class _AnonUser
527 extends _WikiUser
528 {
529     var $_level = WIKIAUTH_ANON;        // var in php-5.0.0RC1 deprecated
530
531     /** Anon only gets to load and save prefs in a cookie, that's it.
532      */
533     function getPreferences() {
534         global $request;
535
536         if (empty($this->_prefs))
537             $this->_prefs = new UserPreferences;
538         $UserName = $this->UserName();
539
540         // Try to read deprecated 1.3.x style cookies
541         if ($cookie = $request->cookies->get_old(WIKI_NAME)) {
542             if (! $unboxedcookie = $this->_prefs->retrieve($cookie)) {
543                 trigger_error(_("Format of UserPreferences cookie not recognised.") . " "
544                               . _("Default preferences will be used."),
545                               E_USER_WARNING);
546             }
547             /**
548              * Only set if it matches the UserName who is
549              * signing in or if this really is an Anon login (no
550              * username). (Remember, _BogoUser and higher inherit this
551              * function too!).
552              */
553             if (! $UserName || $UserName == $unboxedcookie['userid']) {
554                 $updated = $this->_prefs->updatePrefs($unboxedcookie);
555                 //$this->_prefs = new UserPreferences($unboxedcookie);
556                 $this->_userid = $unboxedcookie['userid'];
557                 $UserName = $this->_userid;
558             }
559             // v1.3.8 policy: don't set PhpWiki cookies, only plaintext WIKI_ID cookies
560             $request->deleteCookieVar(WIKI_NAME);
561         }
562         // Try to read deprecated 1.3.4 style cookies
563         if (! $UserName and ($cookie = $request->cookies->get_old("WIKI_PREF2"))) {
564             if (! $unboxedcookie = $this->_prefs->retrieve($cookie)) {
565                 if (! $UserName || $UserName == $unboxedcookie['userid']) {
566                     $updated = $this->_prefs->updatePrefs($unboxedcookie);
567                     //$this->_prefs = new UserPreferences($unboxedcookie);
568                     $this->_userid = $unboxedcookie['userid'];
569                     $UserName = $this->_userid;
570                 }
571                 $request->deleteCookieVar("WIKI_PREF2");
572             }
573         }
574         if (! $UserName ) {
575             // Try reading userid from old PhpWiki cookie formats:
576             if ($cookie = $request->cookies->get_old('WIKI_ID')) {
577                 if (is_string($cookie))
578                     $this->_userid = $cookie;
579                 elseif (is_array($cookie) and !empty($cookie['userid']))
580                     $this->_userid = $cookie['userid'];
581             }
582             $UserName = $this->_userid;
583         }
584
585         // initializeTheme() needs at least an empty object
586         /*
587          if (empty($this->_prefs))
588             $this->_prefs = new UserPreferences;
589         */
590         return $this->_prefs;
591     }
592
593     /** _AnonUser::setPreferences(): Save prefs in a cookie and session and update all global vars
594      *
595      * Allow for multiple wikis in same domain. Encode only the
596      * _prefs array of the UserPreference object. Ideally the
597      * prefs array should just be imploded into a single string or
598      * something so it is completely human readable by the end
599      * user. In that case stricter error checking will be needed
600      * when loading the cookie.
601      */
602     function setPreferences($prefs, $id_only=false) {
603         if (!is_object($prefs)) {
604             if (is_object($this->_prefs)) {
605                 $updated = $this->_prefs->updatePrefs($prefs);
606                 $prefs =& $this->_prefs;
607             } else {
608                 // update the prefs values from scratch. This could leed to unnecessary
609                 // side-effects: duplicate emailVerified, ...
610                 $prefs = new UserPreferences($prefs);
611                 // check if different from the current prefs
612                 $updated = $this->_prefs->isChanged($prefs);
613             }
614         } else {
615             $updated = $this->_prefs->isChanged($prefs);
616         }
617         if ($updated) {
618             if ($id_only) {
619                 global $request;
620                 // new 1.3.8 policy: no array cookies, only plain userid string as in 
621                 // the pre 1.3.x versions.
622                 // prefs should be stored besides the session in the homepagehandle or in a db.
623                 $request->setCookieVar('WIKI_ID', $this->_userid,
624                                        COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
625                 //$request->setCookieVar(WIKI_NAME, array('userid' => $prefs->get('userid')),
626                 //                       COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
627             }
628         }
629         $packed = $prefs->store();
630         $unpacked = $prefs->unpack($packed);
631         if (count($unpacked)) {
632             global $request;
633             foreach (array('_method','_select','_update') as $param) {
634                 if (!empty($this->_prefs->{$param}))
635                     $prefs->{$param} = $this->_prefs->{$param};
636             }
637             $this->_prefs = $prefs;
638             $request->_prefs =& $this->_prefs; 
639             $request->_user->_prefs =& $this->_prefs;
640             if (isset($request->_user->_auth_dbi)) {
641                 $user = $request->_user;
642                 unset($user->_auth_dbi);
643                 $request->setSessionVar('wiki_user', $user);
644             } else {
645               //$request->setSessionVar('wiki_prefs', $this->_prefs);
646               $request->setSessionVar('wiki_user', $request->_user);
647             }
648         }
649         return $updated;
650     }
651
652     function userExists() {
653         return true;
654     }
655
656     function checkPass($submitted_password) {
657         return false;
658         // this might happen on a old-style signin button.
659
660         // By definition, the _AnonUser does not HAVE a password
661         // (compared to _BogoUser, who has an EMPTY password).
662         trigger_error("DEBUG: Warning: _AnonUser unexpectedly asked to checkPass()." . " "
663                       . "Check isa(\$user, '_PassUser'), or: isa(\$user, '_AdminUser') etc. first." . " "
664                       . "New subclasses of _WikiUser must override this function.");
665         return false;
666     }
667
668 }
669
670 /** 
671  * Helper class to finish the PassUser auth loop. 
672  * This is added automatically to USER_AUTH_ORDER.
673  */
674 class _ForbiddenUser
675 extends _AnonUser
676 {
677     var $_level = WIKIAUTH_FORBIDDEN;
678
679     function checkPass($submitted_password) {
680         return WIKIAUTH_FORBIDDEN;
681     }
682
683     function userExists() {
684         if ($this->_HomePagehandle) return true;
685         return false;
686     }
687 }
688 /** 
689  * The PassUser name gets created automatically. 
690  * That's why this class is empty, but must exist.
691  */
692 class _ForbiddenPassUser
693 extends _ForbiddenUser
694 {
695     function dummy() {
696         return;
697     }
698 }
699
700 /**
701  * Do NOT extend _BogoUser to other classes, for checkPass()
702  * security. (In case of defects in code logic of the new class!)
703  * The intermediate step between anon and passuser.
704  * We also have the _BogoLoginPassUser class with stricter 
705  * password checking, which fits into the auth loop.
706  * Note: This class is not called anymore by WikiUser()
707  */
708 class _BogoUser
709 extends _AnonUser
710 {
711     function userExists() {
712         if (isWikiWord($this->_userid)) {
713             $this->_level = WIKIAUTH_BOGO;
714             return true;
715         } else {
716             $this->_level = WIKIAUTH_ANON;
717             return false;
718         }
719     }
720
721     function checkPass($submitted_password) {
722         // By definition, BogoUser has an empty password.
723         $this->userExists();
724         return $this->_level;
725     }
726 }
727
728 class _PassUser
729 extends _AnonUser
730 /**
731  * Called if ALLOW_USER_PASSWORDS and Anon and Bogo failed.
732  *
733  * The classes for all subsequent auth methods extend from this class. 
734  * This handles the auth method type dispatcher according $USER_AUTH_ORDER, 
735  * the three auth method policies first-only, strict and stacked
736  * and the two methods for prefs: homepage or database, 
737  * if $DBAuthParams['pref_select'] is defined.
738  *
739  * Default is PersonalPage auth and prefs.
740  * 
741  * TODO: email verification
742  *
743  * @author: Reini Urban
744  * @tables: pref
745  */
746 {
747     var $_auth_dbi, $_prefs;
748     var $_current_method, $_current_index;
749
750     // check and prepare the auth and pref methods only once
751     function _PassUser($UserName='', $prefs=false) {
752         global $DBAuthParams, $DBParams;
753         if ($UserName) {
754             $this->_userid = $UserName;
755             if ($this->hasHomePage())
756                 $this->_HomePagehandle = $GLOBALS['request']->getPage($this->_userid);
757         }
758         $this->_authmethod = substr(get_class($this),1,-8);
759         if ($this->_authmethod == 'a') $this->_authmethod = 'admin';
760         if (! $this->_prefs) {
761             if ($prefs) $this->_prefs = $prefs;
762             else $this->getPreferences();
763         }
764
765         // Check the configured Prefs methods
766         if ( !isset($this->_prefs->_select) and !empty($DBAuthParams['pref_select']) 
767              and in_array($DBParams['dbtype'],array('SQL','ADODB'))) {
768             $this->_prefs->_method = $DBParams['dbtype'];
769             $this->getAuthDbh();
770             // preparate the SELECT statement
771             $this->_prefs->_select = str_replace('"$userid"','%s',$DBAuthParams['pref_select']);
772         //} else {
773         //    unset($this->_prefs->_select);
774         } else {
775             $this->_prefs->_method = 'HomePage';
776         }
777         if (  !isset($this->_prefs->_update) and !empty($DBAuthParams['pref_update'])
778              and in_array($DBParams['dbtype'],array('SQL','ADODB'))) {
779             $this->_prefs->_method = $DBParams['dbtype'];
780             $this->getAuthDbh();
781             // preparate the SELECT statement
782             $this->_prefs->_update = str_replace(array('"$userid"','"$pref_blob"'),
783                                                  array('%s','%s'),
784                                              $DBAuthParams['pref_update']);
785         }
786         
787         // Upgrade to the next parent _PassUser class. Avoid recursion.
788         if ( strtolower(get_class($this)) === '_passuser' ) {
789             //auth policy: Check the order of the configured auth methods
790             // 1. first-only: Upgrade the class here in the constructor
791             // 2. old:       ignore USER_AUTH_ORDER and try to use all available methods as 
792             ///              in the previous PhpWiki releases (slow)
793             // 3. strict:    upgrade the class after checking the user existance in userExists()
794             // 4. stacked:   upgrade the class after the password verification in checkPass()
795             // Methods: PersonalPage, HttpAuth, DB, Ldap, Imap, File
796             if (!defined('USER_AUTH_POLICY')) define('USER_AUTH_POLICY','old');
797             if (defined('USER_AUTH_POLICY')) {
798                 // policy 1: only pre-define one method for all users
799                 if (USER_AUTH_POLICY === 'first-only') {
800                     $class = $user->nextClass();
801                     return new $class($UserName,$user->_prefs);
802                 }
803                 // use the default behaviour from the previous versions:
804                 elseif (USER_AUTH_POLICY === 'old') {
805                     // default: try to be smart
806                     // On php5 we can directly return and upgrade the Object,
807                     // before we have to upgrade it manually.
808                     if (!empty($GLOBALS['PHP_AUTH_USER'])) {
809                         if (check_php_version(5))
810                             return new _HttpAuthPassUser($UserName,$this->_prefs);
811                         else {
812                             $user = new _HttpAuthPassUser($UserName,$this->_prefs);
813                             //todo: with php5 comment the following line.
814                             /*PHP5 patch*/$this = $user;
815                             return UpgradeUser($user,$this);
816                         }
817                     } elseif (!empty($DBAuthParams['auth_check']) and 
818                               (!empty($DBAuthParams['auth_dsn']) or !empty($GLOBALS ['DBParams']['dsn']))) {
819                         if (check_php_version(5))
820                             return new _DbPassUser($UserName,$this->_prefs);
821                         else {
822                             $user = new _DbPassUser($UserName,$this->_prefs);
823                             //todo: with php5 comment the following line.
824                             /*PHP5 patch*/$this = $user;
825                             return UpgradeUser($user,$this);
826                         }
827                     } elseif (defined('LDAP_AUTH_HOST') and defined('LDAP_BASE_DN') and function_exists('ldap_open')) {
828                         if (check_php_version(5))
829                             return new _LDAPPassUser($UserName,$this->_prefs);
830                         else {
831                             $user = new _LDAPPassUser($UserName,$this->_prefs);
832                             //todo: with php5 comment the following line.
833                             /*PHP5 patch*/$this = $user;
834                             return UpgradeUser($user,$this);
835                         }
836                     } elseif (defined('IMAP_AUTH_HOST') and function_exists('imap_open')) {
837                         if (check_php_version(5))
838                             return new _IMAPPassUser($UserName,$this->_prefs);
839                         else {
840                             $user = new _IMAPPassUser($UserName,$this->_prefs);
841                             //todo: with php5 comment the following line.
842                             /*PHP5 patch*/$this = $user;
843                             return UpgradeUser($user,$this);
844                         }
845                     } elseif (defined('AUTH_USER_FILE')) {
846                         if (check_php_version(5))
847                             return new _FilePassUser($UserName,$this->_prefs);
848                         else {
849                             $user = new _FilePassUser($UserName,$this->_prefs);
850                             //todo: with php5 comment the following line.
851                             /*PHP5 patch*/$this = $user;
852                             return UpgradeUser($user,$this);
853                         }
854                     } else {
855                         if (check_php_version(5))
856                             return new _PersonalPagePassUser($UserName,$this->_prefs);
857                         else {
858                             $user = new _PersonalPagePassUser($UserName,$this->_prefs);
859                             //todo: with php5 comment the following line.
860                             /*PHP5 patch*/$this = $user;
861                             return UpgradeUser($user,$this);
862                         }
863                     }
864                 }
865                 else 
866                     // else use the page methods defined in _PassUser.
867                     return $this;
868             }
869         }
870     }
871
872     function getAuthDbh () {
873         global $request, $DBParams, $DBAuthParams;
874
875         // session restauration doesn't re-connect to the database automatically, so dirty it here.
876         if (($DBParams['dbtype'] == 'SQL') and isset($this->_auth_dbi) and 
877              empty($this->_auth_dbi->connection))
878             unset($this->_auth_dbi);
879         if (($DBParams['dbtype'] == 'ADODB') and isset($this->_auth_dbi) and 
880              empty($this->_auth_dbi->_connectionID))
881             unset($this->_auth_dbi);
882
883         if (empty($this->_auth_dbi)) {
884             if ($DBParams['dbtype'] != 'SQL' and $DBParams['dbtype'] != 'ADODB')
885                 return false;
886             if (empty($DBAuthParams))
887                 return false;
888             if (empty($DBAuthParams['auth_dsn'])) {
889                 $dbh = $request->getDbh(); // use phpwiki database 
890             } elseif ($DBAuthParams['auth_dsn'] == $DBParams['dsn']) {
891                 $dbh = $request->getDbh(); // same phpwiki database 
892             } else { // use another external database handle. needs PHP >= 4.1
893                 $local_params = array_merge($DBParams,$DBAuthParams);
894                 $local_params['dsn'] = $local_params['auth_dsn'];
895                 $dbh = WikiDB::open($local_params);
896             }       
897             $this->_auth_dbi =& $dbh->_backend->_dbh;    
898         }
899         return $this->_auth_dbi;
900     }
901
902     // not used anymore. have to do the prefix fixing somewhere else
903     function prepare ($stmt, $variables) {
904         global $DBParams, $request;
905         // preparate the SELECT statement, for ADODB and PearDB (MDB not)
906         $this->getAuthDbh();
907         $place = ($DBParams['dbtype'] == 'ADODB') ? '%s' : '?';
908         if (is_array($variables)) {
909             $new = array();
910             foreach ($variables as $v) { $new[] = $place; }
911         } else {
912             $new = $place;
913         }
914         // probably prefix table names if in same database
915         if (!empty($DBParams['prefix']) and 
916             $this->_auth_dbi === $request->_dbi->_backend->_dbh) {
917             if (!stristr($DBParams['prefix'],$stmt)) {
918                 //Do it automatically for the lazy admin? Esp. on sf.net it's nice to have
919                 trigger_error("TODO: Need to prefix the DBAuthParam tablename in index.php: $stmt",
920                               E_USER_WARNING);
921                 $stmt = str_replace(array(" user "," pref "," member "),
922                                     array(" ".$prefix."user ",
923                                           " ".$prefix."prefs ",
924                                           " ".$prefix."member "),$stmt);
925             }
926         }
927         return $this->_auth_dbi->prepare(str_replace($variables,$new,$stmt));
928     }
929
930     function getPreferences() {
931         if (!empty($this->_prefs->_method)) {
932             if ($this->_prefs->_method == 'ADODB') {
933                 _AdoDbPassUser::_AdoDbPassUser($this->_userid,$this->_prefs);
934                 return _AdoDbPassUser::getPreferences();
935             } elseif ($this->_prefs->_method == 'SQL') {
936                 _PearDbPassUser::_PearDbPassUser($this->_userid,$this->_prefs);
937                 return _PearDbPassUser::getPreferences();
938             }
939         }
940
941         // We don't necessarily have to read the cookie first. Since
942         // the user has a password, the prefs stored in the homepage
943         // cannot be arbitrarily altered by other Bogo users.
944         _AnonUser::getPreferences();
945         // User may have deleted cookie, retrieve from his
946         // PersonalPage if there is one.
947         if ($this->_HomePagehandle) {
948             if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
949                 $updated = $this->_prefs->updatePrefs($restored_from_page,'init');
950                 //$this->_prefs = new UserPreferences($restored_from_page);
951                 return $this->_prefs;
952             }
953         }
954         return $this->_prefs;
955     }
956
957     function setPreferences($prefs, $id_only=false) {
958         if (!empty($this->_prefs->_method)) {
959             if ($this->_prefs->_method == 'ADODB') {
960                 _AdoDbPassUser::_AdoDbPassUser($this->_userid,$prefs);
961                 return _AdoDbPassUser::setPreferences($prefs, $id_only);
962             }
963             elseif ($this->_prefs->_method == 'SQL') {
964                 _PearDbPassUser::_PearDbPassUser($this->_userid,$prefs);
965                 return _PearDbPassUser::setPreferences($prefs, $id_only);
966             }
967         }
968         if (_AnonUser::setPreferences($prefs, $id_only)) {
969             // Encode only the _prefs array of the UserPreference object
970             if ($this->_HomePagehandle and !$id_only)
971                 $this->_HomePagehandle->set('pref', $prefs->store());
972         }
973         return;
974     }
975
976     function mayChangePass() {
977         return true;
978     }
979
980     //The default method is getting the password from prefs. 
981     // child methods obtain $stored_password from external auth.
982     function userExists() {
983         //if ($this->_HomePagehandle) return true;
984         $class = $this->nextClass();
985         while ($user = new $class($this->_userid,$this->_prefs)) {
986             //todo: with php5 comment the following line:
987             /*PHP5 patch*/$this = $user;
988             UpgradeUser($this,$user);
989             if ($user->userExists()) {
990                 return true;
991             }
992             // prevent endless loop. does this work on all PHP's?
993             // it just has to set the classname, what it correctly does.
994             $class = $user->nextClass();
995             if ($class == "_ForbiddenPassUser")
996                 return false;
997         }
998         return false;
999     }
1000
1001     //The default method is getting the password from prefs. 
1002     // child methods obtain $stored_password from external auth.
1003     function checkPass($submitted_password) {
1004         $stored_password = $this->_prefs->get('passwd');
1005         if ($this->_checkPass($submitted_password, $stored_password)) {
1006             $this->_level = WIKIAUTH_USER;
1007             return $this->_level;
1008         } else {
1009             return $this->_tryNextPass($submitted_password);
1010         }
1011     }
1012
1013     /**
1014      * The basic password checker for all PassUser objects.
1015      * Uses global ENCRYPTED_PASSWD and PASSWORD_LENGTH_MINIMUM.
1016      * Empty passwords are always false!
1017      * PASSWORD_LENGTH_MINIMUM is enforced here and in the preference set method.
1018      * @see UserPreferences::set
1019      *
1020      * DBPassUser password's have their own crypt definition.
1021      * That's why DBPassUser::checkPass() doesn't call this method, if 
1022      * the db password method is 'plain', which means that the DB SQL 
1023      * statement just returns 1 or 0. To use CRYPT() or PASSWORD() and 
1024      * don't store plain passwords in the DB.
1025      * 
1026      * TODO: remove crypt() function check from config.php:396 ??
1027      */
1028     function _checkPass($submitted_password, $stored_password) {
1029         if(!empty($submitted_password)) {
1030             if (strlen($stored_password) < PASSWORD_LENGTH_MINIMUM) {
1031                 // Todo. hmm...
1032                 trigger_error(_("The length of the stored password is shorter than the system policy allows. Sorry, you cannot login.\n You have to ask the System Administrator to reset your password."));
1033                 return false;
1034             }
1035             if (strlen($submitted_password) < PASSWORD_LENGTH_MINIMUM)
1036                 return false;
1037             if (defined('ENCRYPTED_PASSWD') && ENCRYPTED_PASSWD) {
1038                 // Verify against encrypted password.
1039                 if (function_exists('crypt')) {
1040                     if (crypt($submitted_password, $stored_password) == $stored_password )
1041                         return true; // matches encrypted password
1042                     else
1043                         return false;
1044                 }
1045                 else {
1046                     trigger_error(_("The crypt function is not available in this version of PHP.") . " "
1047                                   . _("Please set ENCRYPTED_PASSWD to false in index.php and probably change ADMIN_PASSWD."),
1048                                   E_USER_WARNING);
1049                     return false;
1050                 }
1051             }
1052             else {
1053                 // Verify against cleartext password.
1054                 if ($submitted_password == $stored_password)
1055                     return true;
1056                 else {
1057                     // Check whether we forgot to enable ENCRYPTED_PASSWD
1058                     if (function_exists('crypt')) {
1059                         if (crypt($submitted_password, $stored_password) == $stored_password) {
1060                             trigger_error(_("Please set ENCRYPTED_PASSWD to true in index.php."),
1061                                           E_USER_WARNING);
1062                             return true;
1063                         }
1064                     }
1065                 }
1066             }
1067         }
1068         return false;
1069     }
1070
1071     /** The default method is storing the password in prefs. 
1072      *  Child methods (DB,File) may store in external auth also, but this 
1073      *  must be explicitly enabled.
1074      *  This may be called by plugin/UserPreferences or by ->SetPreferences()
1075      */
1076     function changePass($submitted_password) {
1077         $stored_password = $this->_prefs->get('passwd');
1078         // check if authenticated
1079         if ($this->isAuthenticated() and $stored_password != $submitted_password) {
1080             $this->_prefs->set('passwd',$submitted_password);
1081             //update the storage (session, homepage, ...)
1082             $this->SetPreferences($this->_prefs);
1083             return true;
1084         }
1085         //Todo: return an error msg to the caller what failed? 
1086         // same password or no privilege
1087         return false;
1088     }
1089
1090     function _tryNextPass($submitted_password) {
1091         if (USER_AUTH_POLICY === 'strict') {
1092                 $class = $this->nextClass();
1093             if ($user = new $class($this->_userid,$this->_prefs)) {
1094                 if ($user->userExists()) {
1095                     return $user->checkPass($submitted_password);
1096                 }
1097             }
1098         }
1099         if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1100                 $class = $this->nextClass();
1101             if ($user = new $class($this->_userid,$this->_prefs))
1102                 return $user->checkPass($submitted_password);
1103         }
1104         return $this->_level;
1105     }
1106
1107     function _tryNextUser() {
1108         if (USER_AUTH_POLICY === 'strict') {
1109                 $class = $this->nextClass();
1110             while ($user = new $class($this->_userid,$this->_prefs)) {
1111                 //todo: with php5 comment the following line:
1112                 /*PHP5 patch*/$this = $user;
1113                 $user = UpgradeUser($this, $user);
1114                 if ($user->userExists()) {
1115                     return true;
1116                 }
1117                 $class = $this->nextClass();
1118             }
1119         }
1120         return false;
1121     }
1122
1123 }
1124
1125 /** Without stored password. A _BogoLoginPassUser with password 
1126  *  is automatically upgraded to a PersonalPagePassUser.
1127  */
1128 class _BogoLoginPassUser
1129 extends _PassUser
1130 {
1131     var $_authmethod = 'BogoLogin';
1132     function userExists() {
1133         if (isWikiWord($this->_userid)) {
1134             $this->_level = WIKIAUTH_BOGO;
1135             return true;
1136         } else {
1137             $this->_level = WIKIAUTH_ANON;
1138             return false;
1139         }
1140     }
1141
1142     /** A BogoLoginUser requires no password at all
1143      *  But if there's one stored, we should prefer PersonalPage instead
1144      */
1145     function checkPass($submitted_password) {
1146         if ($this->_prefs->get('passwd')) {
1147             $user = new _PersonalPagePassUser($this->_userid);
1148             if ($user->checkPass($submitted_password)) {
1149                 //todo: with php5 comment the following line:
1150                 /*PHP5 patch*/$this = $user;
1151                 $user = UpgradeUser($this, $user);
1152                 $this->_level = WIKIAUTH_USER;
1153                 return $this->_level;
1154             } else {
1155                 $this->_level = WIKIAUTH_ANON;
1156                 return $this->_level;
1157             }
1158         }
1159         $this->userExists();
1160         return $this->_level;
1161     }
1162 }
1163
1164
1165 /**
1166  * This class is only to simplify the auth method dispatcher.
1167  * It inherits almost all all methods from _PassUser.
1168  */
1169 class _PersonalPagePassUser
1170 extends _PassUser
1171 {
1172     var $_authmethod = 'PersonalPage';
1173
1174     function userExists() {
1175         return $this->_HomePagehandle and $this->_HomePagehandle->exists();
1176     }
1177         
1178     /** A PersonalPagePassUser requires PASSWORD_LENGTH_MINIMUM.
1179      *  BUT if the user already has a homepage with an empty password 
1180      *  stored, allow login but warn him to change it.
1181      */
1182     function checkPass($submitted_password) {
1183         if ($this->userExists()) {
1184             $stored_password = $this->_prefs->get('passwd');
1185             if (empty($stored_password)) {
1186                 trigger_error(sprintf(
1187                 _("\nYou stored an empty password in your '%s' page.\n").
1188                 _("Your access permissions are only for a BogoUser.\n").
1189                 _("Please set your password in UserPreferences."),
1190                                         $this->_userid), E_USER_NOTICE);
1191                 $this->_level = WIKIAUTH_BOGO;
1192                 return $this->_level;
1193             }
1194             if ($this->_checkPass($submitted_password, $stored_password))
1195                 return ($this->_level = WIKIAUTH_USER);
1196             return _PassUser::checkPass($submitted_password);
1197         }
1198         return WIKIAUTH_ANON;
1199     }
1200 }
1201
1202 /**
1203  * We have two possibilities here.
1204  * 1) The webserver location is already HTTP protected (usually Basic). Then just 
1205  *    use the username and do nothing
1206  * 2) The webserver location is not protected, so we enforce basic HTTP Protection
1207  *    by sending a 401 error and let the client display the login dialog.
1208  *    This makes only sense if HttpAuth is the last method in USER_AUTH_ORDER,
1209  *    since the other methods cannot be transparently called after this enforced 
1210  *    external dialog.
1211  *    Try the available auth methods (most likely Bogo) and sent this header back.
1212  *    header('Authorization: Basic '.base64_encode("$userid:$passwd")."\r\n";
1213  */
1214 class _HttpAuthPassUser
1215 extends _PassUser
1216 {
1217     function _HttpAuthPassUser($UserName='',$prefs=false) {
1218         if ($prefs) $this->_prefs = $prefs;
1219         if (!isset($this->_prefs->_method))
1220            _PassUser::_PassUser($UserName);
1221         if ($UserName) $this->_userid = $UserName;
1222         $this->_authmethod = 'HttpAuth';
1223         if ($this->userExists())
1224             return $this;
1225         else 
1226             return $GLOBALS['ForbiddenUser'];
1227     }
1228
1229     function _http_username() {
1230         if (!empty($_SERVER['PHP_AUTH_USER']))
1231             return $_SERVER['PHP_AUTH_USER'];
1232         if ($GLOBALS['HTTP_SERVER_VARS']['PHP_AUTH_USER'])
1233             return $GLOBALS['HTTP_SERVER_VARS']['PHP_AUTH_USER'];
1234         if ($GLOBALS['REMOTE_USER'])
1235             return $GLOBALS['REMOTE_USER'];
1236         if ($_ENV['REMOTE_USER'])
1237             return $_ENV['REMOTE_USER'];
1238         return '';
1239     }
1240     
1241     //force http auth authorization
1242     function userExists() {
1243         // todo: older php's
1244         $username = $this->_http_username();
1245         if (empty($username) or $username != $this->_userid) {
1246             header('WWW-Authenticate: Basic realm="'.WIKI_NAME.'"');
1247             header('HTTP/1.0 401 Unauthorized'); 
1248             exit;
1249         }
1250         $this->_userid = $username;
1251         $this->_level = WIKIAUTH_USER;
1252         return $this;
1253     }
1254         
1255     function checkPass($submitted_password) {
1256         return $this->userExists() ? WIKIAUTH_USER : WIKIAUTH_ANON;
1257     }
1258
1259     function mayChangePass() {
1260         return false;
1261     }
1262
1263     // hmm... either the server dialog or our own.
1264     function PrintLoginForm (&$request, $args, $fail_message = false,
1265                              $seperate_page = true) {
1266         header('WWW-Authenticate: Basic realm="'.WIKI_NAME.'"');
1267         header('HTTP/1.0 401 Unauthorized'); 
1268         exit;
1269
1270         include_once('lib/Template.php');
1271         // Call update_locale in case the system's default language is not 'en'.
1272         // (We have no user pref for lang at this point yet, no one is logged in.)
1273         update_locale(DEFAULT_LANGUAGE);
1274         $userid = $this->_userid;
1275         $require_level = 0;
1276         extract($args); // fixme
1277
1278         $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
1279
1280         $pagename = $request->getArg('pagename');
1281         $nocache = 1;
1282         $login = new Template('login', $request,
1283                               compact('pagename', 'userid', 'require_level',
1284                                       'fail_message', 'pass_required', 'nocache'));
1285         if ($seperate_page) {
1286             $top = new Template('html', $request,
1287                                 array('TITLE' => _("Sign In")));
1288             return $top->printExpansion($login);
1289         } else {
1290             return $login;
1291         }
1292     }
1293
1294 }
1295
1296
1297 /**
1298  * Baseclass for PearDB and ADODB PassUser's
1299  * Authenticate against a database, to be able to use shared users.
1300  *   internal: no different $DbAuthParams['dsn'] defined, or
1301  *   external: different $DbAuthParams['dsn']
1302  * The magic is done in the symbolic SQL statements in index.php, similar to
1303  * libnss-mysql.
1304  *
1305  * We support only the SQL and ADODB backends.
1306  * The other WikiDB backends (flat, cvs, dba, ...) should be used for pages, 
1307  * not for auth stuff. If one would like to use e.g. dba for auth, he should 
1308  * use PearDB (SQL) with the right $DBAuthParam['auth_dsn']. 
1309  * (Not supported yet, since we require SQL. SQLite would make since when 
1310  * it will come to PHP)
1311  *
1312  * @tables: user, pref
1313  *
1314  * Preferences are handled in the parent class _PassUser, because the 
1315  * previous classes may also use DB pref_select and pref_update.
1316  *
1317  * Flat files auth is handled by the auth method "File".
1318  */
1319 class _DbPassUser
1320 extends _PassUser
1321 {
1322     var $_authselect, $_authupdate, $_authcreate;
1323
1324     // This can only be called from _PassUser, because the parent class 
1325     // sets the auth_dbi and pref methods, before this class is initialized.
1326     function _DbPassUser($UserName='',$prefs=false) {
1327         if (!$this->_prefs) {
1328             if ($prefs) $this->_prefs = $prefs;
1329         }
1330         if (!isset($this->_prefs->_method))
1331            _PassUser::_PassUser($UserName);
1332         $this->_authmethod = 'Db';
1333         //$this->getAuthDbh();
1334         //$this->_auth_crypt_method = @$GLOBALS['DBAuthParams']['auth_crypt_method'];
1335         if ($GLOBALS['DBParams']['dbtype'] == 'ADODB') {
1336             if (check_php_version(5))
1337                 return new _AdoDbPassUser($UserName,$this->_prefs);
1338             else {
1339                 $user = new _AdoDbPassUser($UserName,$this->_prefs);
1340                 //todo: with php5 comment the following line:
1341                 /*PHP5 patch*/$this = $user;
1342                 return UpgradeUser($user, $this);
1343             }
1344         }
1345         elseif ($GLOBALS['DBParams']['dbtype'] == 'SQL') {
1346             if (check_php_version(5))
1347                 return new _PearDbPassUser($UserName,$this->_prefs);
1348             else {
1349                 $user = new _PearDbPassUser($UserName,$this->_prefs);
1350                 //todo: with php5 comment the following line:
1351                 /*PHP5 patch*/$this = $user;
1352                 return UpgradeUser($user, $this);
1353             }
1354         }
1355         return false;
1356     }
1357
1358     function mayChangePass() {
1359         return !isset($this->_authupdate);
1360     }
1361
1362 }
1363
1364 class _PearDbPassUser
1365 extends _DbPassUser
1366 /**
1367  * Pear DB methods
1368  * Now optimized not to use prepare, ...query(sprintf($sql,quote())) instead.
1369  * We use FETCH_MODE_ROW, so we don't need aliases in the auth_* SQL statements.
1370  *
1371  * @tables: user
1372  * @tables: pref
1373  */
1374 {
1375     function _PearDbPassUser($UserName='',$prefs=false) {
1376         global $DBAuthParams;
1377         if (!$this->_prefs and isa($this,"_PearDbPassUser")) {
1378             if ($prefs) $this->_prefs = $prefs;
1379         }
1380         if (!isset($this->_prefs->_method))
1381             _PassUser::_PassUser($UserName);
1382         $this->_userid = $UserName;
1383         // make use of session data. generally we only initialize this every time, 
1384         // but do auth checks only once
1385         $this->_auth_crypt_method = @$DBAuthParams['auth_crypt_method'];
1386         //$this->getAuthDbh();
1387         return $this;
1388     }
1389
1390     function getPreferences() {
1391         // override the generic slow method here for efficiency and not to 
1392         // clutter the homepage metadata with prefs.
1393         _AnonUser::getPreferences();
1394         $this->getAuthDbh();
1395         if (isset($this->_prefs->_select)) {
1396             $dbh = &$this->_auth_dbi;
1397             $db_result = $dbh->query(sprintf($this->_prefs->_select,$dbh->quote($this->_userid)));
1398             // patched by frederik@pandora.be
1399             $prefs = $db_result->fetchRow();
1400             $prefs_blob = $prefs["prefs"]; 
1401             if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
1402                 $updated = $this->_prefs->updatePrefs($restored_from_db);
1403                 //$this->_prefs = new UserPreferences($restored_from_db);
1404                 return $this->_prefs;
1405             }
1406         }
1407         if ($this->_HomePagehandle) {
1408             if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
1409                 $updated = $this->_prefs->updatePrefs($restored_from_page);
1410                 //$this->_prefs = new UserPreferences($restored_from_page);
1411                 return $this->_prefs;
1412             }
1413         }
1414         return $this->_prefs;
1415     }
1416
1417     function setPreferences($prefs, $id_only=false) {
1418         // if the prefs are changed
1419         if (_AnonUser::setPreferences($prefs, 1)) {
1420             global $request;
1421             $user = $request->_user;
1422             //unset($user->_auth_dbi);
1423             //$request->setSessionVar('wiki_user', $user);
1424             $this->getAuthDbh();
1425             $packed = $this->_prefs->store();
1426             if (!$id_only and isset($this->_prefs->_update)) {
1427                 $dbh = &$this->_auth_dbi;
1428                 
1429                 $dbh->simpleQuery(sprintf($this->_prefs->_update,
1430                                           $dbh->quote($packed),
1431                                           $dbh->quote($this->_userid)));
1432             } else {
1433                 //store prefs in homepage, not in cookie
1434                 if ($this->_HomePagehandle and !$id_only)
1435                     $this->_HomePagehandle->set('pref', $packed);
1436             }
1437             return count($this->_prefs->unpack($packed));
1438         }
1439         return 0;
1440     }
1441
1442     function userExists() {
1443         global $DBAuthParams;
1444         $this->getAuthDbh();
1445         $dbh = &$this->_auth_dbi;
1446         if (!$dbh) { // needed?
1447             return $this->_tryNextUser();
1448         }
1449         // Prepare the configured auth statements
1450         if (!empty($DBAuthParams['auth_check']) and empty($this->_authselect)) {
1451             $this->_authselect = str_replace(array('"$userid"','"$password"'),
1452                                              array('%s','%s'),
1453                                              $DBAuthParams['auth_check']);
1454         }
1455         if (empty($this->_authselect))
1456             trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'SQL'",
1457                           E_USER_WARNING);
1458         //NOTE: for auth_crypt_method='crypt' no special auth_user_exists is needed
1459         if ($this->_auth_crypt_method == 'crypt') {
1460             $rs = $dbh->query(sprintf($this->_authselect,$dbh->quote($this->_userid)));
1461             if ($rs->numRows())
1462                 return true;
1463         }
1464         else {
1465             if (! $GLOBALS['DBAuthParams']['auth_user_exists'])
1466                 trigger_error("\$DBAuthParams['auth_user_exists'] is missing",
1467                               E_USER_WARNING);
1468             $this->_authcheck = str_replace('"$userid"','%s',
1469                                              $DBAuthParams['auth_user_exists']);
1470             $rs = $dbh->query(sprintf($this->_authcheck,$dbh->quote($this->_userid)));
1471             if ($rs->numRows())
1472                 return true;
1473         }
1474         // maybe the user is allowed to create himself. Generally not wanted in 
1475         // external databases, but maybe wanted for the wiki database, for performance 
1476         // reasons
1477         if (empty($this->_authcreate) and !empty($DBAuthParams['auth_create'])) {
1478             $this->_authcreate = str_replace(array('"$userid"','"$password"'),array('%s','%s'),
1479                                               $DBAuthParams['auth_create']);
1480         }
1481         if (!empty($this->_authcreate)) return true;
1482
1483         return $this->_tryNextUser();
1484     }
1485  
1486     function checkPass($submitted_password) {
1487         global $DBAuthParams;
1488         $this->getAuthDbh();
1489         if (!$this->_auth_dbi) {  // needed?
1490             return $this->_tryNextPass($submitted_password);
1491         }
1492         if (empty($this->_authselect))
1493             trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'SQL'",
1494                           E_USER_WARNING);
1495
1496         //NOTE: for auth_crypt_method='crypt'  defined('ENCRYPTED_PASSWD',true) must be set
1497         $dbh = &$this->_auth_dbi;
1498         if ($this->_auth_crypt_method == 'crypt') {
1499             $stored_password = $dbh->getOne(sprintf($this->_authselect,$dbh->quote($this->_userid)));
1500             $result = $this->_checkPass($submitted_password, $stored_password);
1501         } else {
1502             $okay = $dbh->getOne(sprintf($this->_authselect,
1503                                          $dbh->quote($submitted_password),
1504                                          $dbh->quote($this->_userid)));
1505             $result = !empty($okay);
1506         }
1507
1508         if ($result) {
1509             $this->_level = WIKIAUTH_USER;
1510             return $this->_level;
1511         } else {
1512             return $this->_tryNextPass($submitted_password);
1513         }
1514     }
1515
1516     function mayChangePass() {
1517         global $DBAuthParams;
1518         return !empty($DBAuthParams['auth_update']);
1519     }
1520
1521     function storePass($submitted_password) {
1522         global $DBAuthParams;
1523         $dbh = &$this->_auth_dbi;
1524         if (!empty($DBAuthParams['auth_update']) and empty($this->_authupdate)) {
1525             $this->_authupdate = str_replace(array('"$userid"','"$password"'),
1526                                              array('%s','%s'),
1527                                              $DBAuthParams['auth_update']);
1528         }
1529         if (empty($this->_authupdate)) {
1530             trigger_error("Either \$DBAuthParams['auth_update'] not defined or \$DBParams['dbtype'] != 'SQL'",
1531                           E_USER_WARNING);
1532             return false;
1533         }
1534
1535         if ($this->_auth_crypt_method == 'crypt') {
1536             if (function_exists('crypt'))
1537                 $submitted_password = crypt($submitted_password);
1538         }
1539         $dbh->simpleQuery(sprintf($this->_authupdate,
1540                                   $dbh->quote($submitted_password),
1541                                   $dbh->quote($this->_userid)
1542                                   ));
1543     }
1544
1545 }
1546
1547 class _AdoDbPassUser
1548 extends _DbPassUser
1549 /**
1550  * ADODB methods
1551  * Simple sprintf, no prepare.
1552  *
1553  * Warning: Since we use FETCH_MODE_ASSOC (string hash) and not the also faster 
1554  * FETCH_MODE_ROW (numeric), we have to use the correct aliases in auth_* sql statements!
1555  *
1556  * TODO: Change FETCH_MODE in adodb WikiDB sublasses.
1557  *
1558  * @tables: user
1559  */
1560 {
1561     function _AdoDbPassUser($UserName='',$prefs=false) {
1562         if (!$this->_prefs and isa($this,"_AdoDbPassUser")) {
1563             if ($prefs) $this->_prefs = $prefs;
1564             if (!isset($this->_prefs->_method))
1565               _PassUser::_PassUser($UserName);
1566         }
1567         $this->_userid = $UserName;
1568         $this->_auth_crypt_method = $GLOBALS['DBAuthParams']['auth_crypt_method'];
1569         $this->getAuthDbh();
1570         // Don't prepare the configured auth statements anymore
1571         return $this;
1572     }
1573
1574     function getPreferences() {
1575         // override the generic slow method here for efficiency
1576         _AnonUser::getPreferences();
1577         $this->getAuthDbh();
1578         if (isset($this->_prefs->_select)) {
1579             $dbh = & $this->_auth_dbi;
1580             $rs = $dbh->Execute(sprintf($this->_prefs->_select,$dbh->qstr($this->_userid)));
1581             if ($rs->EOF) {
1582                 $rs->Close();
1583             } else {
1584                 $prefs_blob = $rs->fields['prefs'];
1585                 $rs->Close();
1586                 if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
1587                     $updated = $this->_prefs->updatePrefs($restored_from_db);
1588                     //$this->_prefs = new UserPreferences($restored_from_db);
1589                     return $this->_prefs;
1590                 }
1591             }
1592         }
1593         if ($this->_HomePagehandle) {
1594             if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
1595                 $updated = $this->_prefs->updatePrefs($restored_from_page);
1596                 //$this->_prefs = new UserPreferences($restored_from_page);
1597                 return $this->_prefs;
1598             }
1599         }
1600         return $this->_prefs;
1601     }
1602
1603     function setPreferences($prefs, $id_only=false) {
1604         // if the prefs are changed
1605         if (_AnonUser::setPreferences($prefs, 1)) {
1606             global $request;
1607             $packed = $this->_prefs->store();
1608             $user = $request->_user;
1609             unset($user->_auth_dbi);
1610             if (!$id_only and isset($this->_prefs->_update)) {
1611                 $this->getAuthDbh();
1612                 $dbh = &$this->_auth_dbi;
1613                 $db_result = $dbh->Execute(sprintf($this->_prefs->_update,
1614                                                    $dbh->qstr($packed),
1615                                                    $dbh->qstr($this->_userid)));
1616                 $db_result->Close();
1617             } else {
1618                 //store prefs in homepage, not in cookie
1619                 if ($this->_HomePagehandle and !$id_only)
1620                     $this->_HomePagehandle->set('pref', $packed);
1621             }
1622             return count($this->_prefs->unpack($packed));
1623         }
1624         return 0;
1625     }
1626  
1627     function userExists() {
1628         global $DBAuthParams;
1629         if (empty($this->_authselect) and !empty($DBAuthParams['auth_check'])) {
1630             $this->_authselect = str_replace(array('"$userid"','"$password"'),array('%s','%s'),
1631                                               $DBAuthParams['auth_check']);
1632         }
1633         if (empty($this->_authselect))
1634             trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'ADODB'",
1635                           E_USER_WARNING);
1636         //$this->getAuthDbh();
1637         $dbh = &$this->_auth_dbi;
1638         //NOTE: for auth_crypt_method='crypt' no special auth_user_exists is needed
1639         if ($this->_auth_crypt_method == 'crypt') {
1640             $rs = $dbh->Execute(sprintf($this->_authselect,$dbh->qstr($this->_userid)));
1641             if (!$rs->EOF) {
1642                 $rs->Close();
1643                 return true;
1644             } else {
1645                 $rs->Close();
1646             }
1647         }
1648         else {
1649             if (! $DBAuthParams['auth_user_exists'])
1650                 trigger_error("\$DBAuthParams['auth_user_exists'] is missing",
1651                               E_USER_WARNING);
1652             $this->_authcheck = str_replace('"$userid"','%s',
1653                                              $DBAuthParams['auth_user_exists']);
1654             $rs = $dbh->Execute(sprintf($this->_authcheck,$dbh->qstr($this->_userid)));
1655             if (!$rs->EOF) {
1656                 $rs->Close();
1657                 return true;
1658             } else {
1659                 $rs->Close();
1660             }
1661         }
1662         // maybe the user is allowed to create himself. Generally not wanted in 
1663         // external databases, but maybe wanted for the wiki database, for performance 
1664         // reasons
1665         if (!$this->_authcreate and !empty($DBAuthParams['auth_create'])) {
1666             $this->_authcreate = str_replace(array('"$userid"','"$password"'),array('%s','%s'),
1667                                               $DBAuthParams['auth_create']);
1668         }
1669         if (!empty($this->_authcreate)) return true;
1670         
1671         return $this->_tryNextUser();
1672     }
1673
1674     function checkPass($submitted_password) {
1675         global $DBAuthParams;
1676         if (empty($this->_authselect) and !empty($DBAuthParams['auth_check'])) {
1677             $this->_authselect = str_replace(array('"$userid"','"$password"'),array('%s','%s'),
1678                                               $DBAuthParams['auth_check']);
1679         }
1680         if (!isset($this->_authselect))
1681             trigger_error("Either \$DBAuthParams['auth_check'] is missing or \$DBParams['dbtype'] != 'ADODB'",
1682                           E_USER_WARNING);
1683         //$this->getAuthDbh();
1684         $dbh = &$this->_auth_dbi;
1685         //NOTE: for auth_crypt_method='crypt'  defined('ENCRYPTED_PASSWD',true) must be set
1686         if ($this->_auth_crypt_method == 'crypt') {
1687             $rs = $dbh->Execute(sprintf($this->_authselect,$dbh->qstr($this->_userid)));
1688             if (!$rs->EOF) {
1689                 $stored_password = $rs->fields['password'];
1690                 $rs->Close();
1691                 $result = $this->_checkPass($submitted_password, $stored_password);
1692             } else {
1693                 $rs->Close();
1694                 $result = false;
1695             }
1696         }
1697         else {
1698             $rs = $dbh->Execute(sprintf($this->_authselect,
1699                                         $dbh->qstr($submitted_password),
1700                                         $dbh->qstr($this->_userid)));
1701             $okay = $rs->fields['ok'];
1702             $rs->Close();
1703             $result = !empty($okay);
1704         }
1705
1706         if ($result) { 
1707             $this->_level = WIKIAUTH_USER;
1708             return $this->_level;
1709         } else {
1710             return $this->_tryNextPass($submitted_password);
1711         }
1712     }
1713
1714     function mayChangePass() {
1715         global $DBAuthParams;
1716         return !empty($DBAuthParams['auth_update']);
1717     }
1718
1719     function storePass($submitted_password) {
1720         global $DBAuthParams;
1721         if (!isset($this->_authupdate) and !empty($DBAuthParams['auth_update'])) {
1722             $this->_authupdate = str_replace(array('"$userid"','"$password"'),array("%s","%s"),
1723                                               $DBAuthParams['auth_update']);
1724         }
1725         if (!isset($this->_authupdate)) {
1726             trigger_error("Either \$DBAuthParams['auth_update'] not defined or \$DBParams['dbtype'] != 'ADODB'",
1727                           E_USER_WARNING);
1728             return false;
1729         }
1730
1731         if ($this->_auth_crypt_method == 'crypt') {
1732             if (function_exists('crypt'))
1733                 $submitted_password = crypt($submitted_password);
1734         }
1735         $this->getAuthDbh();
1736         $dbh = &$this->_auth_dbi;
1737         $rs = $dbh->Execute(sprintf($this->_authupdate,
1738                                     $dbh->qstr($submitted_password),
1739                                     $dbh->qstr($this->_userid)
1740                                     ));
1741         $rs->Close();
1742         return $rs;
1743     }
1744
1745 }
1746
1747 class _LDAPPassUser
1748 extends _PassUser
1749 /**
1750  * Define the vars LDAP_AUTH_HOST and LDAP_BASE_DN in index.php
1751  *
1752  * Preferences are handled in _PassUser
1753  */
1754 {
1755     function checkPass($submitted_password) {
1756         global $LDAP_SET_OPTION;
1757
1758         $this->_authmethod = 'LDAP';
1759         $userid = $this->_userid;
1760         if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
1761             if (defined('LDAP_AUTH_USER'))
1762                 if (defined('LDAP_AUTH_PASSWORD'))
1763                     // Windows Active Directory Server is strict
1764                     $r = @ldap_bind($ldap,LDAP_AUTH_USER,LDAP_AUTH_PASSWORD); 
1765                 else
1766                     $r = @ldap_bind($ldap,LDAP_AUTH_USER); 
1767             else
1768                 $r = @ldap_bind($ldap); // this is an anonymous bind
1769             if (!empty($LDAP_SET_OPTION)) {
1770                 foreach ($LDAP_SET_OPTION as $key => $value) {
1771                     ldap_set_option($ldap,$key,$value);
1772                 }
1773             }
1774             // Need to set the right root search information. see ../index.php
1775             $st_search = defined('LDAP_SEARCH_FIELD') 
1776                 ? LDAP_SEARCH_FIELD."=$userid"
1777                 : "uid=$userid";
1778             $sr = ldap_search($ldap, LDAP_BASE_DN, $st_search);
1779             $info = ldap_get_entries($ldap, $sr); 
1780             // there may be more hits with this userid.
1781             // of course it would be better to narrow down the BASE_DN
1782             for ($i = 0; $i < $info["count"]; $i++) {
1783                 $dn = $info[$i]["dn"];
1784                 // The password is still plain text.
1785                 if ($r = @ldap_bind($ldap, $dn, $submitted_password)) {
1786                     // ldap_bind will return TRUE if everything matches
1787                     ldap_close($ldap);
1788                     $this->_level = WIKIAUTH_USER;
1789                     return $this->_level;
1790                 }
1791             }
1792         } else {
1793             trigger_error(fmt("Unable to connect to LDAP server %s", LDAP_AUTH_HOST), 
1794                           E_USER_WARNING);
1795             //return false;
1796         }
1797
1798         return $this->_tryNextPass($submitted_password);
1799     }
1800
1801     function userExists() {
1802         global $LDAP_SET_OPTION;
1803
1804         $userid = $this->_userid;
1805         if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
1806             if (defined('LDAP_AUTH_USER'))
1807                 if (defined('LDAP_AUTH_PASSWORD'))
1808                     // Windows Active Directory Server is strict
1809                     $r = @ldap_bind($ldap,LDAP_AUTH_USER,LDAP_AUTH_PASSWORD); 
1810                 else
1811                     $r = @ldap_bind($ldap,LDAP_AUTH_USER); 
1812             else
1813                 $r = @ldap_bind($ldap); // this is an anonymous bind
1814             if (!empty($LDAP_SET_OPTION)) {
1815                 foreach ($LDAP_SET_OPTION as $key => $value) {
1816                     ldap_set_option($ldap,$key,$value);
1817                 }
1818             }
1819             // Need to set the right root search information. see ../index.php
1820             $st_search = defined('LDAP_SEARCH_FIELD') 
1821                 ? LDAP_SEARCH_FIELD."=$userid"
1822                 : "uid=$userid";
1823             $sr = ldap_search($ldap, LDAP_BASE_DN, $st_search);
1824             $info = ldap_get_entries($ldap, $sr); 
1825
1826             if ($info["count"] > 0) {
1827                 ldap_close($ldap);
1828                 return true;
1829             }
1830         } else {
1831             trigger_error(_("Unable to connect to LDAP server "). LDAP_AUTH_HOST, E_USER_WARNING);
1832         }
1833
1834         return $this->_tryNextUser();
1835     }
1836
1837     function mayChangePass() {
1838         return false;
1839     }
1840
1841 }
1842
1843 class _IMAPPassUser
1844 extends _PassUser
1845 /**
1846  * Define the var IMAP_AUTH_HOST in index.php (with port probably)
1847  *
1848  * Preferences are handled in _PassUser
1849  */
1850 {
1851     function checkPass($submitted_password) {
1852         $userid = $this->_userid;
1853         $mbox = @imap_open( "{" . IMAP_AUTH_HOST . "}",
1854                             $userid, $submitted_password, OP_HALFOPEN );
1855         if ($mbox) {
1856             imap_close($mbox);
1857             $this->_authmethod = 'IMAP';
1858             $this->_level = WIKIAUTH_USER;
1859             return $this->_level;
1860         } else {
1861             trigger_error(_("Unable to connect to IMAP server "). IMAP_AUTH_HOST, E_USER_WARNING);
1862         }
1863
1864         return $this->_tryNextPass($submitted_password);
1865     }
1866
1867     //CHECKME: this will not be okay for the auth policy strict
1868     function userExists() {
1869         return true;
1870         if (checkPass($this->_prefs->get('passwd')))
1871             return true;
1872             
1873         return $this->_tryNextUser();
1874     }
1875
1876     function mayChangePass() {
1877         return false;
1878     }
1879 }
1880
1881
1882 class _POP3PassUser
1883 extends _IMAPPassUser {
1884 /**
1885  * Define the var POP3_AUTH_HOST in index.php
1886  * Preferences are handled in _PassUser
1887  */
1888     function checkPass($submitted_password) {
1889         $userid = $this->_userid;
1890         $pass = $submitted_password;
1891         $host = defined('POP3_AUTH_HOST') ? POP3_AUTH_HOST : 'localhost';
1892         $port = defined('POP3_AUTH_PORT') ? POP3_AUTH_PORT : 110;
1893         $retval = false;
1894         $fp = fsockopen($host, $port, $errno, $errstr, 10);
1895         if ($fp) {
1896             // Get welcome string
1897             $line = fgets($fp, 1024);
1898             if (! strncmp("+OK ", $line, 4)) {
1899                 // Send user name
1900                 fputs($fp, "user $user\n");
1901                 // Get response
1902                 $line = fgets($fp, 1024);
1903                 if (! strncmp("+OK ", $line, 4)) {
1904                     // Send password
1905                     fputs($fp, "pass $pass\n");
1906                     // Get response
1907                     $line = fgets($fp, 1024);
1908                     if (! strncmp("+OK ", $line, 4)) {
1909                         $retval = true;
1910                     }
1911                 }
1912             }
1913             // quit the connection
1914             fputs($fp, "quit\n");
1915             // Get the sayonara message
1916             $line = fgets($fp, 1024);
1917             fclose($fp);
1918         }
1919         $this->_authmethod = 'POP3';
1920         if ($retval) {
1921             $this->_level = WIKIAUTH_USER;
1922         } else {
1923             $this->_level = WIKIAUTH_ANON;
1924         }
1925         return $this->_level;
1926     }
1927 }
1928
1929 class _FilePassUser
1930 extends _PassUser
1931 /**
1932  * Check users defined in a .htaccess style file
1933  * username:crypt\n...
1934  *
1935  * Preferences are handled in _PassUser
1936  */
1937 {
1938     var $_file, $_may_change;
1939
1940     // This can only be called from _PassUser, because the parent class 
1941     // sets the pref methods, before this class is initialized.
1942     function _FilePassUser($UserName='',$file='') {
1943         if (!$this->_prefs)
1944             _PassUser::_PassUser($UserName);
1945
1946         // read the .htaccess style file. We use our own copy of the standard pear class.
1947         include_once 'lib/pear/File_Passwd.php';
1948         // if passwords may be changed we have to lock them:
1949         $this->_may_change = defined('AUTH_USER_FILE_STORABLE') && AUTH_USER_FILE_STORABLE;
1950         if (empty($file) and defined('AUTH_USER_FILE'))
1951             $this->_file = new File_Passwd(AUTH_USER_FILE, !empty($this->_may_change));
1952         elseif (!empty($file))
1953             $this->_file = new File_Passwd($file, !empty($this->_may_change));
1954         else
1955             return false;
1956         return $this;
1957     }
1958  
1959     function mayChangePass() {
1960         return $this->_may_change;
1961     }
1962
1963     function userExists() {
1964         if (isset($this->_file->users[$this->_userid]))
1965             return true;
1966             
1967         return $this->_tryNextUser();
1968     }
1969
1970     function checkPass($submitted_password) {
1971         if ($this->_file->verifyPassword($this->_userid,$submitted_password)) {
1972             $this->_authmethod = 'File';
1973             $this->_level = WIKIAUTH_USER;
1974             return $this->_level;
1975         }
1976         
1977         return $this->_tryNextPass($submitted_password);
1978     }
1979
1980     function storePass($submitted_password) {
1981         if ($this->_may_change)
1982             return $this->_file->modUser($this->_userid,$submitted_password);
1983         else 
1984             return false;
1985     }
1986
1987 }
1988
1989 /**
1990  * Insert more auth classes here...
1991  * For example a customized db class for another db connection 
1992  * or a socket-based auth server
1993  *
1994  */
1995
1996
1997 /**
1998  * For security, this class should not be extended. Instead, extend
1999  * from _PassUser (think of this as unix "root").
2000  */
2001 class _AdminUser
2002 extends _PassUser
2003 {
2004     function mayChangePass() {
2005         return false;
2006     }
2007     function checkPass($submitted_password) {
2008         $stored_password = ADMIN_PASSWD;
2009         if ($this->_checkPass($submitted_password, $stored_password)) {
2010             $this->_level = WIKIAUTH_ADMIN;
2011             return $this->_level;
2012         } else {
2013             $this->_level = WIKIAUTH_ANON;
2014             return $this->_level;
2015         }
2016     }
2017     function storePass($submitted_password) {
2018         return false;
2019     }
2020 }
2021
2022 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2023 /**
2024  * Various data classes for the preference types, 
2025  * to support get, set, sanify (range checking, ...)
2026  * update() will do the neccessary side-effects if a 
2027  * setting gets changed (theme, language, ...)
2028 */
2029
2030 class _UserPreference
2031 {
2032     var $default_value;
2033
2034     function _UserPreference ($default_value) {
2035         $this->default_value = $default_value;
2036     }
2037
2038     function sanify ($value) {
2039         return (string)$value;
2040     }
2041
2042     function get ($name) {
2043         if (isset($this->{$name}))
2044             return $this->{$name};
2045         else 
2046             return $this->default_value;
2047     }
2048
2049     function getraw ($name) {
2050         if (!empty($this->{$name}))
2051             return $this->{$name};
2052     }
2053
2054     // stores the value as $this->$name, and not as $this->value (clever?)
2055     function set ($name, $value) {
2056         if ($this->get($name) != $value) {
2057             $this->update($value);
2058         }
2059         if ($value != $this->default_value) {
2060             $this->{$name} = $value;
2061         }
2062         else 
2063             unset($this->{$name});
2064     }
2065
2066     // default: no side-effects 
2067     function update ($value) {
2068         ;
2069     }
2070 }
2071
2072 class _UserPreference_numeric
2073 extends _UserPreference
2074 {
2075     function _UserPreference_numeric ($default, $minval = false,
2076                                       $maxval = false) {
2077         $this->_UserPreference((double)$default);
2078         $this->_minval = (double)$minval;
2079         $this->_maxval = (double)$maxval;
2080     }
2081
2082     function sanify ($value) {
2083         $value = (double)$value;
2084         if ($this->_minval !== false && $value < $this->_minval)
2085             $value = $this->_minval;
2086         if ($this->_maxval !== false && $value > $this->_maxval)
2087             $value = $this->_maxval;
2088         return $value;
2089     }
2090 }
2091
2092 class _UserPreference_int
2093 extends _UserPreference_numeric
2094 {
2095     function _UserPreference_int ($default, $minval = false, $maxval = false) {
2096         $this->_UserPreference_numeric((int)$default, (int)$minval, (int)$maxval);
2097     }
2098
2099     function sanify ($value) {
2100         return (int)parent::sanify((int)$value);
2101     }
2102 }
2103
2104 class _UserPreference_bool
2105 extends _UserPreference
2106 {
2107     function _UserPreference_bool ($default = false) {
2108         $this->_UserPreference((bool)$default);
2109     }
2110
2111     function sanify ($value) {
2112         if (is_array($value)) {
2113             /* This allows for constructs like:
2114              *
2115              *   <input type="hidden" name="pref[boolPref][]" value="0" />
2116              *   <input type="checkbox" name="pref[boolPref][]" value="1" />
2117              *
2118              * (If the checkbox is not checked, only the hidden input
2119              * gets sent. If the checkbox is sent, both inputs get
2120              * sent.)
2121              */
2122             foreach ($value as $val) {
2123                 if ($val)
2124                     return true;
2125             }
2126             return false;
2127         }
2128         return (bool) $value;
2129     }
2130 }
2131
2132 class _UserPreference_language
2133 extends _UserPreference
2134 {
2135     function _UserPreference_language ($default = DEFAULT_LANGUAGE) {
2136         $this->_UserPreference($default);
2137     }
2138
2139     // FIXME: check for valid locale
2140     function sanify ($value) {
2141         // Revert to DEFAULT_LANGUAGE if user does not specify
2142         // language in UserPreferences or chooses <system language>.
2143         if ($value == '' or empty($value))
2144             $value = DEFAULT_LANGUAGE;
2145
2146         return (string) $value;
2147     }
2148 }
2149
2150 class _UserPreference_theme
2151 extends _UserPreference
2152 {
2153     function _UserPreference_theme ($default = THEME) {
2154         $this->_UserPreference($default);
2155     }
2156
2157     function sanify ($value) {
2158         if (!empty($value) and FindFile($this->_themefile($value)))
2159             return $value;
2160         return $this->default_value;
2161     }
2162
2163     function update ($newvalue) {
2164         global $Theme;
2165         if ($newvalue)
2166             include_once($this->_themefile($newvalue));
2167         if (empty($Theme))
2168             include_once($this->_themefile(THEME));
2169     }
2170
2171     function _themefile ($theme) {
2172         return "themes/$theme/themeinfo.php";
2173     }
2174 }
2175
2176 class _UserPreference_notify
2177 extends _UserPreference
2178 {
2179     function sanify ($value) {
2180         if (!empty($value))
2181             return $value;
2182         else
2183             return $this->default_value;
2184     }
2185
2186     /** update to global user prefs: side-effect on set notify changes
2187      * use a global_data notify hash:
2188      * notify = array('pagematch' => array(userid => ('email' => mail, 
2189      *                                                'verified' => 0|1),
2190      *                                     ...),
2191      *                ...);
2192      */
2193     function update ($value) {
2194         $dbh = $GLOBALS['request']->getDbh();
2195         $notify = $dbh->get('notify');
2196         if (empty($notify))
2197             $data = array();
2198         else 
2199             $data = & $notify;
2200         // expand to existing pages only or store matches?
2201         // for now we store (glob-style) matches which is easier for the user
2202         $pages = $this->_page_split($value);
2203         $user = $GLOBALS['request']->getUser();
2204         $userid = $user->UserName();
2205         $email  = $user->_prefs->get('email');
2206         $verified = $user->_prefs->_prefs['email']->getraw('emailVerified');
2207         // check existing notify hash and possibly delete pages for email
2208         if (!empty($data)) {
2209             foreach ($data as $page => $users) {
2210                 if (isset($data[$page][$userid]) and !in_array($page, $pages)) {
2211                     unset($data[$page][$userid]);
2212                 }
2213                 if (count($data[$page]) == 0)
2214                     unset($data[$page]);
2215             }
2216         }
2217         // add the new pages
2218         if (!empty($pages)) {
2219             foreach ($pages as $page) {
2220                 if (!isset($data[$page]))
2221                     $data[$page] = array();
2222                 if (!isset($data[$page][$userid])) {
2223                     // should we really store the verification notice here or 
2224                     // check it dynamically at every page->save?
2225                     if ($verified) {
2226                         $data[$page][$userid] = array('email' => $email,
2227                                                       'verified' => $verified);
2228                     } else {
2229                         $data[$page][$userid] = array('email' => $email);
2230                     }
2231                 }
2232             }
2233         }
2234         // store users changes
2235         $dbh->set('notify',$data);
2236     }
2237
2238     /** split the user-given comma or whitespace delimited pagenames
2239      *  to array
2240      */
2241     function _page_split($value) {
2242         return preg_split('/[\s,]+/',$value,-1,PREG_SPLIT_NO_EMPTY);
2243     }
2244 }
2245
2246 class _UserPreference_email
2247 extends _UserPreference
2248 {
2249     function sanify ($value) {
2250         // check for valid email address
2251         if ($this->get('email') == $value and $this->getraw('emailVerified'))
2252             return $value;
2253         list($ok,$msg) = ValidateMail($value,'noconnect');
2254         if ($ok) {
2255             return $value;
2256         } else {
2257             trigger_error($msg, E_USER_WARNING);
2258             return $this->default_value;
2259         }
2260     }
2261
2262     // stores the value as $this->$name, and not as $this->value (clever?)
2263     function set ($name, $value) {
2264         $new = $this->get($name);
2265         if ($new and $name = 'email' and $new != $value) {
2266             // don't update on init     
2267             $this->update($value);
2268         }
2269         if ($value != $this->default_value) {
2270             $this->{$name} = $value;
2271         }
2272         else 
2273             unset($this->{$name});
2274     }
2275     
2276     /** Side-effect on email changes:
2277      * Send a verification mail or for now just a notification email.
2278      * For true verification (value = 2), we'd need a mailserver hook.
2279      */
2280     function update ($value) {
2281         $verified = $this->getraw('emailVerified');
2282         if (!empty($value) and !$verified) {
2283             list($ok,$msg) = ValidateMail($value);
2284             if ($ok and mail($value,"[".WIKI_NAME ."] "._("Email Verification"),
2285                      sprintf(_("Welcome to %s!\nYou email account is verified and\nwill be used to send pagechange notifications.\nSee %s"),
2286                              WIKI_NAME, WikiUrl($GLOBALS['request']->getArg('pagename'),'',true))))
2287                 $this->set('emailVerified',1);
2288         }
2289     }
2290 }
2291
2292 /** Check for valid email address
2293     fixed version from http://www.zend.com/zend/spotlight/ev12apr.php
2294  */
2295 function ValidateMail($email, $noconnect=false) {
2296     $HTTP_HOST = $_SERVER['HTTP_HOST'];
2297     $result = array();
2298     // well, technically ".a.a.@host.com" is also valid
2299     if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {
2300         $result[0] = false;
2301         $result[1] = "$email is not properly formatted";
2302         return $result;
2303     }
2304     if ($noconnect)
2305       return array(true,"$email is properly formatted");
2306
2307     list ( $Username, $Domain ) = split ("@",$email);
2308     //Todo: getmxrr workaround on windows or manual input field to verify it manually
2309     if (!isWindows() and getmxrr($Domain, $MXHost)) { // avoid warning on Windows. 
2310         $ConnectAddress = $MXHost[0];
2311     } else {
2312         $ConnectAddress = $Domain;
2313     }
2314     $Connect = fsockopen ( $ConnectAddress, 25 );
2315     if ($Connect) {
2316         if (ereg("^220", $Out = fgets($Connect, 1024))) {
2317             fputs ($Connect, "HELO $HTTP_HOST\r\n");
2318             $Out = fgets ( $Connect, 1024 );
2319             fputs ($Connect, "MAIL FROM: <".$email.">\r\n");
2320             $From = fgets ( $Connect, 1024 );
2321             fputs ($Connect, "RCPT TO: <".$email.">\r\n");
2322             $To = fgets ($Connect, 1024);
2323             fputs ($Connect, "QUIT\r\n");
2324             fclose($Connect);
2325             if (!ereg ("^250", $From)) {
2326                 $result[0]=false;
2327                 $result[1]="Server rejected address: ". $From;
2328                 return $result;
2329             }
2330             if (!ereg ( "^250", $To )) {
2331                 $result[0]=false;
2332                 $result[1]="Server rejected address: ". $To;
2333                 return $result;
2334             }
2335         } else {
2336             $result[0] = false;
2337             $result[1] = "No response from server";
2338             return $result;
2339           }
2340     }  else {
2341         $result[0]=false;
2342         $result[1]="Can not connect E-Mail server.";
2343         return $result;
2344     }
2345     $result[0]=true;
2346     $result[1]="$email appears to be valid.";
2347     return $result;
2348 } // end of function 
2349
2350 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2351
2352 /**
2353  * UserPreferences
2354  * 
2355  * This object holds the $request->_prefs subobjects.
2356  * A simple packed array of non-default values get's stored as cookie,
2357  * homepage, or database, which are converted to the array of 
2358  * ->_prefs objects.
2359  * We don't store the objects, because otherwise we will
2360  * not be able to upgrade any subobject. And it's a waste of space also.
2361  *
2362  */
2363 class UserPreferences
2364 {
2365     function UserPreferences($saved_prefs = false) {
2366         // userid stored too, to ensure the prefs are being loaded for
2367         // the correct (currently signing in) userid if stored in a
2368         // cookie.
2369         $this->_prefs
2370             = array(
2371                     'userid'        => new _UserPreference(''),
2372                     'passwd'        => new _UserPreference(''),
2373                     'autologin'     => new _UserPreference_bool(),
2374                     //'emailVerified' => new _UserPreference_emailVerified(),
2375                     //fixed: store emailVerified as email parameter
2376                     'email'         => new _UserPreference_email(''),
2377                     'notifyPages'   => new _UserPreference_notify(''),
2378                     'theme'         => new _UserPreference_theme(THEME),
2379                     'lang'          => new _UserPreference_language(DEFAULT_LANGUAGE),
2380                     'editWidth'     => new _UserPreference_int(EDITWIDTH_DEFAULT_COLS,
2381                                                                EDITWIDTH_MIN_COLS,
2382                                                                EDITWIDTH_MAX_COLS),
2383                     'noLinkIcons'   => new _UserPreference_bool(),
2384                     'editHeight'    => new _UserPreference_int(EDITHEIGHT_DEFAULT_ROWS,
2385                                                                EDITHEIGHT_MIN_ROWS,
2386                                                                EDITHEIGHT_DEFAULT_ROWS),
2387                     'timeOffset'    => new _UserPreference_numeric(TIMEOFFSET_DEFAULT_HOURS,
2388                                                                    TIMEOFFSET_MIN_HOURS,
2389                                                                    TIMEOFFSET_MAX_HOURS),
2390                     'relativeDates' => new _UserPreference_bool()
2391                     );
2392
2393         if (is_array($saved_prefs)) {
2394             foreach ($saved_prefs as $name => $value)
2395                 $this->set($name, $value);
2396         }
2397     }
2398
2399     function _getPref($name) {
2400         if ($name == 'emailVerified')
2401             $name = 'email';
2402         if (!isset($this->_prefs[$name])) {
2403             if ($name == 'passwd2') return false;
2404             trigger_error("$name: unknown preference", E_USER_NOTICE);
2405             return false;
2406         }
2407         return $this->_prefs[$name];
2408     }
2409     
2410     // get the value or default_value of the subobject
2411     function get($name) {
2412         if ($_pref = $this->_getPref($name))
2413             if ($name == 'emailVerified')
2414                 return $_pref->getraw($name);
2415             else
2416                 return $_pref->get($name);
2417         else
2418             return false;  
2419     }
2420
2421     // check and set the new value in the subobject
2422     function set($name, $value) {
2423         $pref = $this->_getPref($name);
2424         if ($pref === false)
2425             return false;
2426
2427         /* do it here or outside? */
2428         if ($name == 'passwd' and 
2429             defined('PASSWORD_LENGTH_MINIMUM') and 
2430             strlen($value) <= PASSWORD_LENGTH_MINIMUM ) {
2431             //TODO: How to notify the user?
2432             return false;
2433         }
2434         /*
2435         if ($name == 'theme' and $value == '')
2436            return true;
2437         */
2438         if (!isset($pref->{$value}) or $pref->{$value} != $pref->default_value) {
2439             $newvalue = $pref->sanify($value);
2440             $pref->set($name,$newvalue);
2441         }
2442         $this->_prefs[$name] = $pref;
2443         return true;
2444     }
2445
2446     function updatePrefs($prefs, $init = false) {
2447         $count = 0;
2448         if ($init) $this->_init = $init;
2449         if (is_object($prefs)) {
2450             $type = 'emailVerified'; $obj =& $this->_prefs['email'];
2451             if ($obj->get($type) !== $prefs->get($type)) {
2452                 $obj->set($type,$prefs->get($type));
2453                 $count++;
2454             }
2455             foreach (array_keys($this->_prefs) as $type) {
2456                 if ($this->_prefs[$type]->get($type) !== $prefs->get($type)) {
2457                     $this->_prefs[$type]->set($type,$prefs->get($type));
2458                     $count++;
2459                 }
2460             }
2461         } elseif (is_array($prefs)) {
2462             $type = 'emailVerified'; $obj =& $this->_prefs['email'];
2463             if (isset($prefs[$type]) and $obj->get($type) !== $prefs[$type]) {
2464                 $obj->set($type,$prefs[$type]);
2465                 $count++;
2466             }
2467             foreach (array_keys($this->_prefs) as $type) {
2468                 $obj =& $this->_prefs[$type];
2469                 if (isset($prefs[$type]) and $obj->get($type) != $prefs[$type]) {
2470                     $obj->set($type,$prefs[$type]);
2471                     $count++;
2472                 }
2473             }
2474         }
2475         return $count;
2476     }
2477
2478     // for now convert just array of objects => array of values
2479     // Todo: the specialized subobjects must override this.
2480     function store() {
2481         $prefs = array();
2482         foreach ($this->_prefs as $name => $object) {
2483             if ($value = $object->getraw($name))
2484                 $prefs[$name] = $value;
2485             if ($name == 'email' and ($value = $object->getraw('emailVerified')))
2486                 $prefs['emailVerified'] = $value;
2487         }
2488         return $this->pack($prefs);
2489     }
2490
2491     // packed string or array of values => array of values
2492     // Todo: the specialized subobjects must override this.
2493     function retrieve($packed) {
2494         if (is_string($packed) and (substr($packed, 0, 2) == "a:"))
2495             $packed = unserialize($packed);
2496         if (!is_array($packed)) return false;
2497         $prefs = array();
2498         foreach ($packed as $name => $packed_pref) {
2499             if (is_string($packed_pref) and substr($packed_pref, 0, 2) == "O:") {
2500                 //legacy: check if it's an old array of objects
2501                 // Looks like a serialized object. 
2502                 // This might fail if the object definition does not exist anymore.
2503                 // object with ->$name and ->default_value vars.
2504                 $pref =  @unserialize($packed_pref);
2505                 if (empty($pref))
2506                     $pref = @unserialize(base64_decode($packed_pref));
2507                 $prefs[$name] = $pref->get($name);
2508             // fix old-style prefs
2509             } elseif (is_numeric($name) and is_array($packed_pref)) {
2510                 if (count($packed_pref) == 1) {
2511                     list($name,$value) = each($packed_pref);
2512                     $prefs[$name] = $value;
2513                 }
2514             } else {
2515                 $prefs[$name] = @unserialize($packed_pref);
2516                 if (empty($prefs[$name]))
2517                     $prefs[$name] = @unserialize(base64_decode($packed_pref));
2518                 // patched by frederik@pandora.be
2519                 if (empty($prefs[$name]))
2520                     $prefs[$name] = $packed_pref;
2521             }
2522         }
2523         return $prefs;
2524     }
2525
2526     /**
2527      * Check if the given prefs object is different from the current prefs object
2528      */
2529     function isChanged($other) {
2530         foreach ($this->_prefs as $type => $obj) {
2531             if ($obj->get($type) !== $other->get($type))
2532                 return true;
2533         }
2534         return false;
2535     }
2536
2537     // array of objects
2538     function getAll() {
2539         return $this->_prefs;
2540     }
2541
2542     function pack($nonpacked) {
2543         return serialize($nonpacked);
2544     }
2545
2546     function unpack($packed) {
2547         if (!$packed)
2548             return false;
2549         //$packed = base64_decode($packed);
2550         if (substr($packed, 0, 2) == "O:") {
2551             // Looks like a serialized object
2552             return unserialize($packed);
2553         }
2554         if (substr($packed, 0, 2) == "a:") {
2555             return unserialize($packed);
2556         }
2557         //trigger_error("DEBUG: Can't unpack bad UserPreferences",
2558         //E_USER_WARNING);
2559         return false;
2560     }
2561
2562     function hash () {
2563         return hash($this->_prefs);
2564     }
2565 }
2566
2567 /** TODO: new pref storage classes
2568  *  These are currently user specific and should be rewritten to be pref specific.
2569  *  i.e. $this == $user->_prefs
2570  */
2571 class CookieUserPreferences
2572 extends UserPreferences
2573 {
2574     function CookieUserPreferences ($saved_prefs = false) {
2575         //_AnonUser::_AnonUser('',$saved_prefs);
2576         UserPreferences::UserPreferences($saved_prefs);
2577     }
2578 }
2579
2580 class PageUserPreferences
2581 extends UserPreferences
2582 {
2583     function PageUserPreferences ($saved_prefs = false) {
2584         UserPreferences::UserPreferences($saved_prefs);
2585     }
2586 }
2587
2588 class PearDbUserPreferences
2589 extends UserPreferences
2590 {
2591     function PearDbUserPreferences ($saved_prefs = false) {
2592         UserPreferences::UserPreferences($saved_prefs);
2593     }
2594 }
2595
2596 class AdoDbUserPreferences
2597 extends UserPreferences
2598 {
2599     function AdoDbUserPreferences ($saved_prefs = false) {
2600         UserPreferences::UserPreferences($saved_prefs);
2601     }
2602     function getPreferences() {
2603         // override the generic slow method here for efficiency
2604         _AnonUser::getPreferences();
2605         $this->getAuthDbh();
2606         if (isset($this->_select)) {
2607             $dbh = & $this->_auth_dbi;
2608             $rs = $dbh->Execute(sprintf($this->_select,$dbh->qstr($this->_userid)));
2609             if ($rs->EOF) {
2610                 $rs->Close();
2611             } else {
2612                 $prefs_blob = $rs->fields['pref_blob'];
2613                 $rs->Close();
2614                 if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
2615                     $updated = $this->_prefs->updatePrefs($restored_from_db);
2616                     //$this->_prefs = new UserPreferences($restored_from_db);
2617                     return $this->_prefs;
2618                 }
2619             }
2620         }
2621         if (empty($this->_prefs->_prefs) and $this->_HomePagehandle) {
2622             if ($restored_from_page = $this->_prefs->retrieve($this->_HomePagehandle->get('pref'))) {
2623                 $updated = $this->_prefs->updatePrefs($restored_from_page);
2624                 //$this->_prefs = new UserPreferences($restored_from_page);
2625                 return $this->_prefs;
2626             }
2627         }
2628         return $this->_prefs;
2629     }
2630 }
2631
2632
2633 // $Log: not supported by cvs2svn $
2634 // Revision 1.40  2004/03/25 22:54:31  rurban
2635 // fixed HttpAuth
2636 //
2637 // Revision 1.38  2004/03/25 17:37:36  rurban
2638 // helper to patch to and from php5 (workaround for stricter parser, no macros in php)
2639 //
2640 // Revision 1.37  2004/03/25 17:00:31  rurban
2641 // more code to convert old-style pref array to new hash
2642 //
2643 // Revision 1.36  2004/03/24 19:39:02  rurban
2644 // php5 workaround code (plus some interim debugging code in XmlElement)
2645 //   php5 doesn't work yet with the current XmlElement class constructors,
2646 //   WikiUserNew does work better than php4.
2647 // rewrote WikiUserNew user upgrading to ease php5 update
2648 // fixed pref handling in WikiUserNew
2649 // added Email Notification
2650 // added simple Email verification
2651 // removed emailVerify userpref subclass: just a email property
2652 // changed pref binary storage layout: numarray => hash of non default values
2653 // print optimize message only if really done.
2654 // forced new cookie policy: delete pref cookies, use only WIKI_ID as plain string.
2655 //   prefs should be stored in db or homepage, besides the current session.
2656 //
2657 // Revision 1.35  2004/03/18 22:18:31  rurban
2658 // workaround for php5 object upgrading problem
2659 //
2660 // Revision 1.34  2004/03/18 21:41:09  rurban
2661 // fixed sqlite support
2662 // WikiUserNew: PHP5 fixes: don't assign $this (untested)
2663 //
2664 // Revision 1.33  2004/03/16 15:42:04  rurban
2665 // more fixes for undefined property warnings
2666 //
2667 // Revision 1.32  2004/03/14 16:30:52  rurban
2668 // db-handle session revivification, dba fixes
2669 //
2670 // Revision 1.31  2004/03/12 23:20:58  rurban
2671 // pref fixes (base64)
2672 //
2673 // Revision 1.30  2004/03/12 20:59:17  rurban
2674 // important cookie fix by Konstantin Zadorozhny
2675 // new editpage feature: JS_SEARCHREPLACE
2676 //
2677 // Revision 1.29  2004/03/11 13:30:47  rurban
2678 // fixed File Auth for user and group
2679 // missing only getMembersOf(Authenticated Users),getMembersOf(Every),getMembersOf(Signed Users)
2680 //
2681 // Revision 1.28  2004/03/08 18:17:09  rurban
2682 // added more WikiGroup::getMembersOf methods, esp. for special groups
2683 // fixed $LDAP_SET_OPTIONS
2684 // fixed _AuthInfo group methods
2685 //
2686 // Revision 1.27  2004/03/01 09:35:13  rurban
2687 // fixed DbPassuser pref init; lost userid
2688 //
2689 // Revision 1.26  2004/02/29 04:10:56  rurban
2690 // new POP3 auth (thanks to BiloBilo: pentothal at despammed dot com)
2691 // fixed syntax error in index.php
2692 //
2693 // Revision 1.25  2004/02/28 22:25:07  rurban
2694 // First PagePerm implementation:
2695 //
2696 // $Theme->setAnonEditUnknownLinks(false);
2697 //
2698 // Layout improvement with dangling links for mostly closed wiki's:
2699 // If false, only users with edit permissions will be presented the
2700 // special wikiunknown class with "?" and Tooltip.
2701 // If true (default), any user will see the ?, but will be presented
2702 // the PrintLoginForm on a click.
2703 //
2704 // Revision 1.24  2004/02/28 21:14:08  rurban
2705 // generally more PHPDOC docs
2706 //   see http://xarch.tu-graz.ac.at/home/rurban/phpwiki/xref/
2707 // fxied WikiUserNew pref handling: empty theme not stored, save only
2708 //   changed prefs, sql prefs improved, fixed password update,
2709 //   removed REPLACE sql (dangerous)
2710 // moved gettext init after the locale was guessed
2711 // + some minor changes
2712 //
2713 // Revision 1.23  2004/02/27 13:21:17  rurban
2714 // several performance improvements, esp. with peardb
2715 // simplified loops
2716 // storepass seperated from prefs if defined so
2717 // stacked and strict still not working
2718 //
2719 // Revision 1.22  2004/02/27 05:15:40  rurban
2720 // more stability. detected by Micki
2721 //
2722 // Revision 1.21  2004/02/26 20:43:49  rurban
2723 // new HttpAuthPassUser class (forces http auth if in the auth loop)
2724 // fixed user upgrade: don't return _PassUser in the first hand.
2725 //
2726 // Revision 1.20  2004/02/26 01:29:11  rurban
2727 // important fixes: endless loops in certain cases. minor rewrite
2728 //
2729 // Revision 1.19  2004/02/25 17:15:17  rurban
2730 // improve stability
2731 //
2732 // Revision 1.18  2004/02/24 15:20:05  rurban
2733 // fixed minor warnings: unchecked args, POST => Get urls for sortby e.g.
2734 //
2735 // Revision 1.17  2004/02/17 12:16:42  rurban
2736 // started with changePass support. not yet used.
2737 //
2738 // Revision 1.16  2004/02/15 22:23:45  rurban
2739 // oops, fixed showstopper (endless recursion)
2740 //
2741 // Revision 1.15  2004/02/15 21:34:37  rurban
2742 // PageList enhanced and improved.
2743 // fixed new WikiAdmin... plugins
2744 // editpage, Theme with exp. htmlarea framework
2745 //   (htmlarea yet committed, this is really questionable)
2746 // WikiUser... code with better session handling for prefs
2747 // enhanced UserPreferences (again)
2748 // RecentChanges for show_deleted: how should pages be deleted then?
2749 //
2750 // Revision 1.14  2004/02/15 17:30:13  rurban
2751 // workaround for lost db connnection handle on session restauration (->_auth_dbi)
2752 // fixed getPreferences() (esp. from sessions)
2753 // fixed setPreferences() (update and set),
2754 // fixed AdoDb DB statements,
2755 // update prefs only at UserPreferences POST (for testing)
2756 // unified db prefs methods (but in external pref classes yet)
2757 //
2758 // Revision 1.13  2004/02/09 03:58:12  rurban
2759 // for now default DB_SESSION to false
2760 // PagePerm:
2761 //   * not existing perms will now query the parent, and not
2762 //     return the default perm
2763 //   * added pagePermissions func which returns the object per page
2764 //   * added getAccessDescription
2765 // WikiUserNew:
2766 //   * added global ->prepare (not yet used) with smart user/pref/member table prefixing.
2767 //   * force init of authdbh in the 2 db classes
2768 // main:
2769 //   * fixed session handling (not triple auth request anymore)
2770 //   * don't store cookie prefs with sessions
2771 // stdlib: global obj2hash helper from _AuthInfo, also needed for PagePerm
2772 //
2773 // Revision 1.12  2004/02/07 10:41:25  rurban
2774 // fixed auth from session (still double code but works)
2775 // fixed GroupDB
2776 // fixed DbPassUser upgrade and policy=old
2777 // added GroupLdap
2778 //
2779 // Revision 1.11  2004/02/03 09:45:39  rurban
2780 // LDAP cleanup, start of new Pref classes
2781 //
2782 // Revision 1.10  2004/02/01 09:14:11  rurban
2783 // Started with Group_Ldap (not yet ready)
2784 // added new _AuthInfo plugin to help in auth problems (warning: may display passwords)
2785 // fixed some configurator vars
2786 // renamed LDAP_AUTH_SEARCH to LDAP_BASE_DN
2787 // changed PHPWIKI_VERSION from 1.3.8a to 1.3.8pre
2788 // USE_DB_SESSION defaults to true on SQL
2789 // changed GROUP_METHOD definition to string, not constants
2790 // changed sample user DBAuthParams from UPDATE to REPLACE to be able to
2791 //   create users. (Not to be used with external databases generally, but
2792 //   with the default internal user table)
2793 //
2794 // fixed the IndexAsConfigProblem logic. this was flawed:
2795 //   scripts which are the same virtual path defined their own lib/main call
2796 //   (hmm, have to test this better, phpwiki.sf.net/demo works again)
2797 //
2798 // Revision 1.9  2004/01/30 19:57:58  rurban
2799 // fixed DBAuthParams['pref_select']: wrong _auth_dbi object used.
2800 //
2801 // Revision 1.8  2004/01/30 18:46:15  rurban
2802 // fix "lib/WikiUserNew.php:572: Notice[8]: Undefined variable: DBParams"
2803 //
2804 // Revision 1.7  2004/01/27 23:23:39  rurban
2805 // renamed ->Username => _userid for consistency
2806 // renamed mayCheckPassword => mayCheckPass
2807 // fixed recursion problem in WikiUserNew
2808 // fixed bogo login (but not quite 100% ready yet, password storage)
2809 //
2810 // Revision 1.6  2004/01/26 09:17:49  rurban
2811 // * changed stored pref representation as before.
2812 //   the array of objects is 1) bigger and 2)
2813 //   less portable. If we would import packed pref
2814 //   objects and the object definition was changed, PHP would fail.
2815 //   This doesn't happen with an simple array of non-default values.
2816 // * use $prefs->retrieve and $prefs->store methods, where retrieve
2817 //   understands the interim format of array of objects also.
2818 // * simplified $prefs->get() and fixed $prefs->set()
2819 // * added $user->_userid and class '_WikiUser' portability functions
2820 // * fixed $user object ->_level upgrading, mostly using sessions.
2821 //   this fixes yesterdays problems with loosing authorization level.
2822 // * fixed WikiUserNew::checkPass to return the _level
2823 // * fixed WikiUserNew::isSignedIn
2824 // * added explodePageList to class PageList, support sortby arg
2825 // * fixed UserPreferences for WikiUserNew
2826 // * fixed WikiPlugin for empty defaults array
2827 // * UnfoldSubpages: added pagename arg, renamed pages arg,
2828 //   removed sort arg, support sortby arg
2829 //
2830 // Revision 1.5  2004/01/25 03:05:00  rurban
2831 // First working version, but has some problems with the current main loop.
2832 // Implemented new auth method dispatcher and policies, all the external
2833 // _PassUser classes (also for ADODB and Pear DB).
2834 // The two global funcs UserExists() and CheckPass() are probably not needed,
2835 // since the auth loop is done recursively inside the class code, upgrading
2836 // the user class within itself.
2837 // Note: When a higher user class is returned, this doesn't mean that the user
2838 // is authorized, $user->_level is still low, and only upgraded on successful
2839 // login.
2840 //
2841 // Revision 1.4  2003/12/07 19:29:48  carstenklapp
2842 // Code Housecleaning: fixed syntax errors. (php -l *.php)
2843 //
2844 // Revision 1.3  2003/12/06 19:10:46  carstenklapp
2845 // Finished off logic for determining user class, including
2846 // PassUser. Removed ability of BogoUser to save prefs into a page.
2847 //
2848 // Revision 1.2  2003/12/03 21:45:48  carstenklapp
2849 // Added admin user, password user, and preference classes. Added
2850 // password checking functions for users and the admin. (Now the easy
2851 // parts are nearly done).
2852 //
2853 // Revision 1.1  2003/12/02 05:46:36  carstenklapp
2854 // Complete rewrite of WikiUser.php.
2855 //
2856 // This should make it easier to hook in user permission groups etc. some
2857 // time in the future. Most importantly, to finally get UserPreferences
2858 // fully working properly for all classes of users: AnonUser, BogoUser,
2859 // AdminUser; whether they have a NamesakePage (PersonalHomePage) or not,
2860 // want a cookie or not, and to bring back optional AutoLogin with the
2861 // UserName stored in a cookie--something that was lost after PhpWiki had
2862 // dropped the default http auth login method.
2863 //
2864 // Added WikiUser classes which will (almost) work together with existing
2865 // UserPreferences class. Other parts of PhpWiki need to be updated yet
2866 // before this code can be hooked up.
2867 //
2868
2869 // Local Variables:
2870 // mode: php
2871 // tab-width: 8
2872 // c-basic-offset: 4
2873 // c-hanging-comment-ender-p: nil
2874 // indent-tabs-mode: nil
2875 // End:
2876 ?>