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