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