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