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