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