]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiUserNew.php
No need for sprintf
[SourceForge/phpwiki.git] / lib / WikiUserNew.php
1 <?php
2 /* Copyright (C) 2004,2005,2006,2007,2009,2010 $ThePhpWikiProgrammingTeam
3  * Copyright (C) 2009-2010 Marc-Etienne Vargenau, Alcatel-Lucent
4  * Copyright (C) 2009-2010 Roger Guignard, Alcatel-Lucent
5  *
6  * This file is part of PhpWiki.
7  *
8  * PhpWiki is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * PhpWiki is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License along
19  * with PhpWiki; if not, write to the Free Software Foundation, Inc.,
20  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21  */
22
23 /**
24  * This is a complete OOP rewrite of the old WikiUser code with various
25  * configurable external authentication methods.
26  *
27  * There's only one entry point, the function WikiUser which returns
28  * a WikiUser object, which contains the name, authlevel and user's preferences.
29  * This object might get upgraded during the login step and later also.
30  * There exist three preferences storage methods: cookie, homepage and db,
31  * and multiple password checking methods.
32  * See index.php for $USER_AUTH_ORDER[] and USER_AUTH_POLICY if
33  * ALLOW_USER_PASSWORDS is defined.
34  *
35  * Each user object must define the two preferences methods
36  *  getPreferences(), setPreferences(),
37  * and the following 1-4 auth methods
38  *  checkPass()  must be defined by all classes,
39  *  userExists() only if USER_AUTH_POLICY'=='strict'
40  *  mayChangePass()  only if the password is storable.
41  *  storePass()  only if the password is storable.
42  *
43  * WikiUser() given no name, returns an _AnonUser (anonymous user)
44  * object, who may or may not have a cookie.
45  * However, if the there's a cookie with the userid or a session,
46  * the user is upgraded to the matching user object.
47  * Given a user name, returns a _BogoUser object, who may or may not
48  * have a cookie and/or PersonalPage, one of the various _PassUser objects
49  * or an _AdminUser object.
50  * BTW: A BogoUser is a userid (loginname) as valid WikiWord, who might
51  * have stored a password or not. If so, his account is secure, if not
52  * anybody can use it, because the username is visible e.g. in RecentChanges.
53  *
54  * Takes care of passwords, all preference loading/storing in the
55  * user's page and any cookies. lib/main.php will query the user object to
56  * verify the password as appropriate.
57  *
58  * @author: Reini Urban (the tricky parts),
59  *          Carsten Klapp (started rolling the ball)
60  *
61  * Random architectural notes, sorted by date:
62  * 2004-01-25 rurban
63  * Test it by defining ENABLE_USER_NEW in config/config.ini
64  * 1) Now a ForbiddenUser is returned instead of false.
65  * 2) Previously ALLOW_ANON_USER = false meant that anon users cannot edit,
66  *    but may browse. Now with ALLOW_ANON_USER = false he may not browse,
67  *    which is needed to disable browse PagePermissions.
68  *    I added now ALLOW_ANON_EDIT = true to makes things clear.
69  *    (which replaces REQUIRE_SIGNIN_BEFORE_EDIT)
70  * 2004-02-27 rurban:
71  * 3) Removed pear prepare. Performance hog, and using integers as
72  *    handler doesn't help. Do simple sprintf as with adodb. And a prepare
73  *    in the object init is no advantage, because in the init loop a lot of
74  *    objects are tried, but not used.
75  * 4) Already gotten prefs are passed to the next object to avoid
76  *    duplicate getPreferences() calls.
77  * 2004-03-18 rurban
78  * 5) Major php-5 problem: $this re-assignment is disallowed by the parser
79  *    So we cannot just discrimate with
80  *      if (!check_php_version(5))
81  *          $this = $user;
82  *    A /php5-patch.php is provided, which patches the src automatically
83  *    for php4 and php5. Default is php4.
84  *    Update: not needed anymore. we use eval to fool the load-time syntax checker.
85  * 2004-03-24 rurban
86  * 6) enforced new cookie policy: prefs don't get stored in cookies
87  *    anymore, only in homepage and/or database, but always in the
88  *    current session. old pref cookies will get deleted.
89  * 2004-04-04 rurban
90  * 7) Certain themes should be able to extend the predefined list
91  *    of preferences. Display/editing is done in the theme specific userprefs.tmpl,
92  *    but storage must be extended to the Get/SetPreferences methods.
93  *    <theme>/themeinfo.php must provide CustomUserPreferences:
94  *      A list of name => _UserPreference class pairs.
95  * 2010-06-07 rurban
96  *    Fixed a nasty recursion bug (i.e. php crash), when user = new class
97  *    which returned false, did not return false on php-4.4.7. Check for
98  *    a object member now.
99  */
100
101 define('WIKIAUTH_FORBIDDEN', -1); // Completely not allowed.
102 define('WIKIAUTH_ANON', 0); // Not signed in.
103 define('WIKIAUTH_BOGO', 1); // Any valid WikiWord is enough.
104 define('WIKIAUTH_USER', 2); // Bogo user with a password.
105 define('WIKIAUTH_ADMIN', 10); // UserName == ADMIN_USER.
106 define('WIKIAUTH_UNOBTAINABLE', 100); // Permissions that no user can achieve
107
108 //if (!defined('COOKIE_EXPIRATION_DAYS')) define('COOKIE_EXPIRATION_DAYS', 365);
109 //if (!defined('COOKIE_DOMAIN'))          define('COOKIE_DOMAIN', '/');
110 if (!defined('EDITWIDTH_MIN_COLS')) define('EDITWIDTH_MIN_COLS', 30);
111 if (!defined('EDITWIDTH_MAX_COLS')) define('EDITWIDTH_MAX_COLS', 150);
112 if (!defined('EDITWIDTH_DEFAULT_COLS')) define('EDITWIDTH_DEFAULT_COLS', 80);
113
114 if (!defined('EDITHEIGHT_MIN_ROWS')) define('EDITHEIGHT_MIN_ROWS', 5);
115 if (!defined('EDITHEIGHT_MAX_ROWS')) define('EDITHEIGHT_MAX_ROWS', 80);
116 if (!defined('EDITHEIGHT_DEFAULT_ROWS')) define('EDITHEIGHT_DEFAULT_ROWS', 22);
117
118 define('TIMEOFFSET_MIN_HOURS', -26);
119 define('TIMEOFFSET_MAX_HOURS', 26);
120 if (!defined('TIMEOFFSET_DEFAULT_HOURS')) define('TIMEOFFSET_DEFAULT_HOURS', 0);
121
122 /* EMAIL VERIFICATION
123  * On certain nets or hosts the email domain cannot be determined automatically from the DNS.
124  * Provide some overrides here.
125  *    ( username @ ) domain => mail-domain
126  */
127 $EMailHosts = array('avl.com' => 'mail.avl.com');
128
129 /**
130  * There are be the following constants in config/config.ini to
131  * establish login parameters:
132  *
133  * ALLOW_ANON_USER         default true
134  * ALLOW_ANON_EDIT         default true
135  * ALLOW_BOGO_LOGIN        default true
136  * ALLOW_USER_PASSWORDS    default true
137  * PASSWORD_LENGTH_MINIMUM default 0
138  *
139  * To require user passwords for editing:
140  * ALLOW_ANON_USER  = true
141  * ALLOW_ANON_EDIT  = false   (before named REQUIRE_SIGNIN_BEFORE_EDIT)
142  * ALLOW_BOGO_LOGIN = false
143  * ALLOW_USER_PASSWORDS = true
144  *
145  * To establish a COMPLETELY private wiki, such as an internal
146  * corporate one:
147  * ALLOW_ANON_USER = false
148  * (and probably require user passwords as described above). In this
149  * case the user will be prompted to login immediately upon accessing
150  * any page.
151  *
152  * There are other possible combinations, but the typical wiki (such
153  * as http://PhpWiki.sf.net/phpwiki) would usually just leave all four
154  * enabled.
155  *
156  */
157
158 // The last object in the row is the bad guy...
159 if (!is_array($USER_AUTH_ORDER))
160     $USER_AUTH_ORDER = array("Forbidden");
161 else
162     $USER_AUTH_ORDER[] = "Forbidden";
163
164 // Local convenience functions.
165 function _isAnonUserAllowed()
166 {
167     return (defined('ALLOW_ANON_USER') && ALLOW_ANON_USER);
168 }
169
170 function _isBogoUserAllowed()
171 {
172     return (defined('ALLOW_BOGO_LOGIN') && ALLOW_BOGO_LOGIN);
173 }
174
175 function _isUserPasswordsAllowed()
176 {
177     return (defined('ALLOW_USER_PASSWORDS') && ALLOW_USER_PASSWORDS);
178 }
179
180 // Possibly upgrade userobject functions.
181 function _determineAdminUserOrOtherUser($UserName)
182 {
183     // Sanity check. User name is a condition of the definition of the
184     // _AdminUser, _BogoUser and _passuser.
185     if (!$UserName)
186         return $GLOBALS['ForbiddenUser'];
187
188     //FIXME: check admin membership later at checkPass. Now we cannot raise the level.
189     //$group = &WikiGroup::getGroup($GLOBALS['request']);
190     if ($UserName == ADMIN_USER)
191         return new _AdminUser($UserName);
192     /* elseif ($group->isMember(GROUP_ADMIN)) { // unneeded code
193         return _determineBogoUserOrPassUser($UserName);
194     }
195     */
196     else
197         return _determineBogoUserOrPassUser($UserName);
198 }
199
200 function _determineBogoUserOrPassUser($UserName)
201 {
202     global $ForbiddenUser;
203
204     // Sanity check. User name is a condition of the definition of
205     // _BogoUser and _PassUser.
206     if (!$UserName)
207         return $ForbiddenUser;
208
209     // Check for password and possibly upgrade user object.
210     // $_BogoUser = new _BogoUser($UserName);
211     if (_isBogoUserAllowed() and isWikiWord($UserName)) {
212         include_once 'lib/WikiUser/BogoLogin.php';
213         $_BogoUser = new _BogoLoginPassUser($UserName);
214         if ($_BogoUser->userExists() or $GLOBALS['request']->getArg('auth'))
215             return $_BogoUser;
216     }
217     if (_isUserPasswordsAllowed()) {
218         // PassUsers override BogoUsers if a password is stored
219         if (isset($_BogoUser) and isset($_BogoUser->_prefs)
220             and $_BogoUser->_prefs->get('passwd')
221         )
222             return new _PassUser($UserName, $_BogoUser->_prefs);
223         else {
224             $_PassUser = new _PassUser($UserName,
225                 isset($_BogoUser) ? $_BogoUser->_prefs : false);
226             if ($_PassUser->userExists() or $GLOBALS['request']->getArg('auth')) {
227                 if (isset($GLOBALS['request']->_user_class))
228                     $class = $GLOBALS['request']->_user_class;
229                 elseif (strtolower(get_class($_PassUser)) == "_passuser")
230                     $class = $_PassUser->nextClass(); else
231                     $class = get_class($_PassUser);
232                 if ($user = new $class($UserName, $_PassUser->_prefs)
233                     and $user->_userid
234                 ) {
235                     return $user;
236                 } else {
237                     return $_PassUser;
238                 }
239             }
240         }
241     }
242     // No Bogo- or PassUser exists, or
243     // passwords are not allowed, and bogo is disallowed too.
244     // (Only the admin can sign in).
245     return $ForbiddenUser;
246 }
247
248 /**
249  * Primary WikiUser function, called by lib/main.php.
250  *
251  * This determines the user's type and returns an appropriate user
252  * object. lib/main.php then querys the resultant object for password
253  * validity as necessary.
254  *
255  * If an _AnonUser object is returned, the user may only browse pages
256  * (and save prefs in a cookie).
257  *
258  * To disable access but provide prefs the global $ForbiddenUser class
259  * is returned. (was previously false)
260  *
261  */
262 function WikiUser($UserName = '')
263 {
264     global $ForbiddenUser, $HTTP_SESSION_VARS;
265
266     //Maybe: Check sessionvar for username & save username into
267     //sessionvar (may be more appropriate to do this in lib/main.php).
268     if ($UserName) {
269         $ForbiddenUser = new _ForbiddenUser($UserName);
270         // Found a user name.
271         return _determineAdminUserOrOtherUser($UserName);
272     } elseif (!empty($HTTP_SESSION_VARS['userid'])) {
273         // Found a user name.
274         $ForbiddenUser = new _ForbiddenUser($_SESSION['userid']);
275         return _determineAdminUserOrOtherUser($_SESSION['userid']);
276     } else {
277         // Check for autologin pref in cookie and possibly upgrade
278         // user object to another type.
279         $_AnonUser = new _AnonUser();
280         if ($UserName = $_AnonUser->_userid && $_AnonUser->_prefs->get('autologin')) {
281             // Found a user name.
282             $ForbiddenUser = new _ForbiddenUser($UserName);
283             return _determineAdminUserOrOtherUser($UserName);
284         } else {
285             $ForbiddenUser = new _ForbiddenUser();
286             if (_isAnonUserAllowed())
287                 return $_AnonUser;
288             return $ForbiddenUser; // User must sign in to browse pages.
289         }
290         return $ForbiddenUser; // User must sign in with a password.
291     }
292     /*
293     trigger_error("DEBUG: Note: End of function reached in WikiUser." . " "
294                   . "Unexpectedly, an appropriate user class could not be determined.");
295     return $ForbiddenUser; // Failsafe.
296     */
297 }
298
299 /**
300  * WikiUser.php use the name 'WikiUser'
301  */
302 function WikiUserClassname()
303 {
304     return '_WikiUser';
305 }
306
307 /**
308  * Upgrade olduser by copying properties from user to olduser.
309  * We are not sure yet, for which php's a simple $this = $user works reliably,
310  * (on php4 it works ok, on php5 it's currently disallowed on the parser level)
311  * that's why try it the hard way.
312  */
313 function UpgradeUser($user, $newuser)
314 {
315     if (isa($user, '_WikiUser') and isa($newuser, '_WikiUser')) {
316         // populate the upgraded class $newuser with the values from the current user object
317         //only _auth_level, _current_method, _current_index,
318         if (!empty($user->_level) and
319             $user->_level > $newuser->_level
320         )
321             $newuser->_level = $user->_level;
322         if (!empty($user->_current_index) and
323             $user->_current_index > $newuser->_current_index
324         ) {
325             $newuser->_current_index = $user->_current_index;
326             $newuser->_current_method = $user->_current_method;
327         }
328         if (!empty($user->_authmethod))
329             $newuser->_authmethod = $user->_authmethod;
330         $GLOBALS['request']->_user_class = get_class($newuser);
331         /*
332         foreach (get_object_vars($user) as $k => $v) {
333             if (!empty($v)) $olduser->$k = $v;
334         }
335         */
336         $newuser->hasHomePage(); // revive db handle, because these don't survive sessions
337         //$GLOBALS['request']->_user = $olduser;
338         return $newuser;
339     } else {
340         return false;
341     }
342 }
343
344 /**
345  * Probably not needed, since we use the various user objects methods so far.
346  * Anyway, here it is, looping through all available objects.
347  */
348 function UserExists($UserName)
349 {
350     global $request;
351     if (!($user = $request->getUser()))
352         $user = WikiUser($UserName);
353     if (!$user)
354         return false;
355     if ($user->userExists($UserName)) {
356         $request->_user = $user;
357         return true;
358     }
359     if (isa($user, '_BogoUser'))
360         $user = new _PassUser($UserName, $user->_prefs);
361     $class = $user->nextClass();
362     if ($user = new $class($UserName, $user->_prefs)) {
363         return $user->userExists($UserName);
364     }
365     $request->_user = $GLOBALS['ForbiddenUser'];
366     return false;
367 }
368
369 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
370
371 /**
372  * Base WikiUser class.
373  */
374 class _WikiUser
375 {
376     var $_userid = '';
377     var $_level = WIKIAUTH_ANON;
378     var $_prefs = false;
379     var $_HomePagehandle = false;
380
381     // constructor
382     function _WikiUser($UserName = '', $prefs = false)
383     {
384
385         $this->_userid = $UserName;
386         $this->_HomePagehandle = false;
387         if ($UserName) {
388             $this->hasHomePage();
389         }
390         if (empty($this->_prefs)) {
391             if ($prefs) $this->_prefs = $prefs;
392             else $this->getPreferences();
393         }
394     }
395
396     function UserName()
397     {
398         if (!empty($this->_userid)) {
399             return $this->_userid;
400         } else {
401             return '';
402         }
403     }
404
405     function getPreferences()
406     {
407         trigger_error("DEBUG: Note: undefined _WikiUser class trying to load prefs." . " "
408             . "New subclasses of _WikiUser must override this function.");
409         return false;
410     }
411
412     function setPreferences($prefs, $id_only)
413     {
414         trigger_error("DEBUG: Note: undefined _WikiUser class trying to save prefs."
415             . " "
416             . "New subclasses of _WikiUser must override this function.");
417         return false;
418     }
419
420     function userExists()
421     {
422         return $this->hasHomePage();
423     }
424
425     function checkPass($submitted_password)
426     {
427         // By definition, an undefined user class cannot sign in.
428         trigger_error("DEBUG: Warning: undefined _WikiUser class trying to sign in."
429             . " "
430             . "New subclasses of _WikiUser must override this function.");
431         return false;
432     }
433
434     // returns page_handle to user's home page or false if none
435     function hasHomePage()
436     {
437         if ($this->_userid) {
438             if (!empty($this->_HomePagehandle) and is_object($this->_HomePagehandle)) {
439                 return $this->_HomePagehandle->exists();
440             } else {
441                 // check db again (maybe someone else created it since
442                 // we logged in.)
443                 global $request;
444                 $this->_HomePagehandle = $request->getPage($this->_userid);
445                 return $this->_HomePagehandle->exists();
446             }
447         }
448         // nope
449         return false;
450     }
451
452     function createHomePage()
453     {
454         global $request;
455         $versiondata = array('author' => ADMIN_USER);
456         $request->_dbi->save(_("Automatically created user homepage to be able to store UserPreferences.") .
457                 "\n{{Template/UserPage}}",
458             1, $versiondata);
459         $request->_dbi->touch();
460         $this->_HomePagehandle = $request->getPage($this->_userid);
461     }
462
463     // innocent helper: case-insensitive position in _auth_methods
464     function array_position($string, $array)
465     {
466         $string = strtolower($string);
467         for ($found = 0; $found < count($array); $found++) {
468             if (strtolower($array[$found]) == $string)
469                 return $found;
470         }
471         return false;
472     }
473
474     function nextAuthMethodIndex()
475     {
476         if (empty($this->_auth_methods))
477             $this->_auth_methods = $GLOBALS['USER_AUTH_ORDER'];
478         if (empty($this->_current_index)) {
479             if (strtolower(get_class($this)) != '_passuser') {
480                 $this->_current_method = substr(get_class($this), 1, -8);
481                 $this->_current_index = $this->array_position($this->_current_method,
482                     $this->_auth_methods);
483             } else {
484                 $this->_current_index = -1;
485             }
486         }
487         $this->_current_index++;
488         if ($this->_current_index >= count($this->_auth_methods))
489             return false;
490         $this->_current_method = $this->_auth_methods[$this->_current_index];
491         return $this->_current_index;
492     }
493
494     function AuthMethod($index = false)
495     {
496         return $this->_auth_methods[$index === false
497             ? count($this->_auth_methods) - 1
498             : $index];
499     }
500
501     // upgrade the user object
502     function nextClass()
503     {
504         $method = $this->AuthMethod($this->nextAuthMethodIndex());
505         include_once("lib/WikiUser/$method.php");
506         return "_" . $method . "PassUser";
507     }
508
509     //Fixme: for _HttpAuthPassUser
510     function PrintLoginForm(&$request, $args, $fail_message = false,
511                             $seperate_page = false)
512     {
513         include_once 'lib/Template.php';
514         // Call update_locale in case the system's default language is not 'en'.
515         // (We have no user pref for lang at this point yet, no one is logged in.)
516         if ($GLOBALS['LANG'] != DEFAULT_LANGUAGE)
517             update_locale(DEFAULT_LANGUAGE);
518         $userid = $this->_userid;
519         $require_level = 0;
520         extract($args); // fixme
521
522         $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
523
524         $pagename = $request->getArg('pagename');
525         $nocache = 1;
526         $login = Template('login',
527             compact('pagename', 'userid', 'require_level',
528                 'fail_message', 'pass_required', 'nocache'));
529         // check if the html template was already processed
530         $seperate_page = $seperate_page ? true : !alreadyTemplateProcessed('html');
531         if ($seperate_page) {
532             $page = $request->getPage($pagename);
533             $revision = $page->getCurrentRevision();
534             return GeneratePage($login, _("Sign In"), $revision);
535         } else {
536             return $login->printExpansion();
537         }
538     }
539
540     /** Signed in but not password checked or empty password.
541      */
542     function isSignedIn()
543     {
544         return (isa($this, '_BogoUser') or isa($this, '_PassUser'));
545     }
546
547     /** This is password checked for sure.
548      */
549     function isAuthenticated()
550     {
551         //return isa($this,'_PassUser');
552         //return isa($this,'_BogoUser') || isa($this,'_PassUser');
553         return $this->_level >= WIKIAUTH_BOGO;
554     }
555
556     function isAdmin()
557     {
558         static $group;
559         if ($this->_level == WIKIAUTH_ADMIN) return true;
560         if (!$this->isSignedIn()) return false;
561         if (!$this->isAuthenticated()) return false;
562
563         if (!$group) $group = &$GLOBALS['request']->getGroup();
564         return ($this->_level > WIKIAUTH_BOGO and $group->isMember(GROUP_ADMIN));
565     }
566
567     /** Name or IP for a signed user. UserName could come from a cookie e.g.
568      */
569     function getId()
570     {
571         return ($this->UserName()
572             ? $this->UserName()
573             : $GLOBALS['request']->get('REMOTE_ADDR'));
574     }
575
576     /** Name for an authenticated user. No IP here.
577      */
578     function getAuthenticatedId()
579     {
580         return ($this->isAuthenticated()
581             ? $this->_userid
582             : ''); //$GLOBALS['request']->get('REMOTE_ADDR') );
583     }
584
585     function hasAuthority($require_level)
586     {
587         return $this->_level >= $require_level;
588     }
589
590     /* This is quite restrictive and not according the login description online.
591        Any word char (A-Za-z0-9_), " ", ".", "@" and "-"
592        The backends may loosen or tighten this.
593     */
594     function isValidName($userid = false)
595     {
596         if (!$userid) $userid = $this->_userid;
597         if (!$userid) return false;
598         if (defined('FUSIONFORGE') and FUSIONFORGE) {
599             return true;
600         }
601         return preg_match("/^[\-\w\.@ ]+$/U", $userid) and strlen($userid) < 32;
602     }
603
604     /**
605      * Called on an auth_args POST request, such as login, logout or signin.
606      * TODO: Check BogoLogin users with empty password. (self-signed users)
607      */
608     function AuthCheck($postargs)
609     {
610         // Normalize args, and extract.
611         $keys = array('userid', 'passwd', 'require_level', 'login', 'logout',
612             'cancel');
613         foreach ($keys as $key)
614             $args[$key] = isset($postargs[$key]) ? $postargs[$key] : false;
615         extract($args);
616         $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
617
618         if ($logout) { // Log out
619             if (LOGIN_LOG and is_writeable(LOGIN_LOG)) {
620                 global $request;
621                 $zone_offset = Request_AccessLogEntry::_zone_offset();
622                 $ncsa_time = date("d/M/Y:H:i:s", time());
623                 $entry = sprintf('%s - %s - [%s %s] "%s" %s - "%s" "%s"',
624                     (string)$request->get('REMOTE_HOST'),
625                     (string)$request->_user->_userid,
626                     $ncsa_time, $zone_offset,
627                     "logout " . get_class($request->_user),
628                     "401",
629                     (string)$request->get('HTTP_REFERER'),
630                     (string)$request->get('HTTP_USER_AGENT')
631                 );
632                 if (($fp = fopen(LOGIN_LOG, "a"))) {
633                     flock($fp, LOCK_EX);
634                     fputs($fp, "$entry\n");
635                     fclose($fp);
636                 }
637                 //error_log("$entry\n", 3, LOGIN_LOG);
638             }
639             if (method_exists($GLOBALS['request']->_user, "logout")) { //_HttpAuthPassUser
640                 $GLOBALS['request']->_user->logout();
641             }
642             $user = new _AnonUser();
643             $user->_userid = '';
644             $user->_level = WIKIAUTH_ANON;
645             return $user;
646         } elseif ($cancel)
647             return false; // User hit cancel button.
648         elseif (!$login && !$userid)
649             return false; // Nothing to do?
650
651         if (!$this->isValidName($userid))
652             return _("Invalid username.");
653         ;
654
655         $authlevel = $this->checkPass($passwd === false ? '' : $passwd);
656
657         if (LOGIN_LOG and is_writeable(LOGIN_LOG)) {
658             global $request;
659             $zone_offset = Request_AccessLogEntry::_zone_offset();
660             $ncsa_time = date("d/M/Y:H:i:s", time());
661             $manglepasswd = $passwd;
662             for ($i = 0; $i < strlen($manglepasswd); $i++) {
663                 $c = substr($manglepasswd, $i, 1);
664                 if (ord($c) < 32) $manglepasswd[$i] = "<";
665                 elseif ($c == '*') $manglepasswd[$i] = "*"; elseif ($c == '?') $manglepasswd[$i] = "?"; elseif ($c == '(') $manglepasswd[$i] = "("; elseif ($c == ')') $manglepasswd[$i] = ")"; elseif ($c == "\\") $manglepasswd[$i] = "\\"; elseif (ord($c) < 127) $manglepasswd[$i] = "x"; elseif (ord($c) >= 127) $manglepasswd[$i] = ">";
666             }
667             if ((DEBUG & _DEBUG_LOGIN) and $authlevel <= 0) $manglepasswd = $passwd;
668             $entry = sprintf('%s - %s - [%s %s] "%s" %s - "%s" "%s"',
669                 $request->get('REMOTE_HOST'),
670                 (string)$request->_user->_userid,
671                 $ncsa_time, $zone_offset,
672                 "login $userid/$manglepasswd => $authlevel " . get_class($request->_user),
673                 $authlevel > 0 ? "200" : "403",
674                 (string)$request->get('HTTP_REFERER'),
675                 (string)$request->get('HTTP_USER_AGENT')
676             );
677             if (($fp = fopen(LOGIN_LOG, "a"))) {
678                 flock($fp, LOCK_EX);
679                 fputs($fp, "$entry\n");
680                 fclose($fp);
681             }
682             //error_log("$entry\n", 3, LOGIN_LOG);
683         }
684
685         if ($authlevel <= 0) { // anon or forbidden
686             if ($passwd)
687                 return _("Invalid password.");
688             else
689                 return _("Invalid password or userid.");
690         } elseif ($authlevel < $require_level) { // auth ok, but not enough
691             if (!empty($this->_current_method) and strtolower(get_class($this)) == '_passuser') {
692                 // upgrade class
693                 $class = "_" . $this->_current_method . "PassUser";
694                 include_once 'lib/WikiUser/' . $this->_current_method . '.php';
695                 $user = new $class($userid, $this->_prefs);
696                 $this->_level = $authlevel;
697                 return $user;
698             }
699             $this->_userid = $userid;
700             $this->_level = $authlevel;
701             return _("Insufficient permissions.");
702         }
703
704         // Successful login.
705         //$user = $GLOBALS['request']->_user;
706         if (!empty($this->_current_method) and
707             strtolower(get_class($this)) == '_passuser'
708         ) {
709             // upgrade class
710             $class = "_" . $this->_current_method . "PassUser";
711             include_once 'lib/WikiUser/' . $this->_current_method . '.php';
712             $user = new $class($userid, $this->_prefs);
713             $user->_level = $authlevel;
714             return $user;
715         }
716         $this->_userid = $userid;
717         $this->_level = $authlevel;
718         return $this;
719     }
720
721 }
722
723 /**
724  * Not authenticated in user, but he may be signed in. Basicly with view access only.
725  * prefs are stored in cookies, but only the userid.
726  */
727 class _AnonUser
728     extends _WikiUser
729 {
730     var $_level = WIKIAUTH_ANON; // var in php-5.0.0RC1 deprecated
731
732     /** Anon only gets to load and save prefs in a cookie, that's it.
733      */
734     function getPreferences()
735     {
736         global $request;
737
738         if (empty($this->_prefs))
739             $this->_prefs = new UserPreferences;
740         $UserName = $this->UserName();
741
742         // Try to read deprecated 1.3.x style cookies
743         if ($cookie = $request->cookies->get_old(WIKI_NAME)) {
744             if (!$unboxedcookie = $this->_prefs->retrieve($cookie)) {
745                 trigger_error(_("Empty Preferences or format of UserPreferences cookie not recognised.")
746                         . "\n"
747                         . sprintf("%s='%s'", WIKI_NAME, $cookie)
748                         . "\n"
749                         . _("Default preferences will be used."),
750                     E_USER_NOTICE);
751             }
752             /**
753              * Only set if it matches the UserName who is
754              * signing in or if this really is an Anon login (no
755              * username). (Remember, _BogoUser and higher inherit this
756              * function too!).
757              */
758             if (!$UserName || $UserName == @$unboxedcookie['userid']) {
759                 $updated = $this->_prefs->updatePrefs($unboxedcookie);
760                 //$this->_prefs = new UserPreferences($unboxedcookie);
761                 $UserName = @$unboxedcookie['userid'];
762                 if (is_string($UserName) and (substr($UserName, 0, 2) != 's:'))
763                     $this->_userid = $UserName;
764                 else
765                     $UserName = false;
766             }
767             // v1.3.8 policy: don't set PhpWiki cookies, only plaintext WIKI_ID cookies
768             if (!headers_sent())
769                 $request->deleteCookieVar(WIKI_NAME);
770         }
771         // Try to read deprecated 1.3.4 style cookies
772         if (!$UserName and ($cookie = $request->cookies->get_old("WIKI_PREF2"))) {
773             if (!$unboxedcookie = $this->_prefs->retrieve($cookie)) {
774                 if (!$UserName || $UserName == $unboxedcookie['userid']) {
775                     $updated = $this->_prefs->updatePrefs($unboxedcookie);
776                     //$this->_prefs = new UserPreferences($unboxedcookie);
777                     $UserName = $unboxedcookie['userid'];
778                     if (is_string($UserName) and (substr($UserName, 0, 2) != 's:'))
779                         $this->_userid = $UserName;
780                     else
781                         $UserName = false;
782                 }
783                 if (!headers_sent())
784                     $request->deleteCookieVar("WIKI_PREF2");
785             }
786         }
787         if (!$UserName) {
788             // Try reading userid from old PhpWiki cookie formats:
789             if ($cookie = $request->cookies->get_old(getCookieName())) {
790                 if (is_string($cookie) and (substr($cookie, 0, 2) != 's:'))
791                     $UserName = $cookie;
792                 elseif (is_array($cookie) and !empty($cookie['userid']))
793                     $UserName = $cookie['userid'];
794             }
795             if (!$UserName and !headers_sent())
796                 $request->deleteCookieVar(getCookieName());
797             else
798                 $this->_userid = $UserName;
799         }
800
801         // initializeTheme() needs at least an empty object
802         /*
803          if (empty($this->_prefs))
804             $this->_prefs = new UserPreferences;
805         */
806         return $this->_prefs;
807     }
808
809     /** _AnonUser::setPreferences(): Save prefs in a cookie and session and update all global vars
810      *
811      * Allow for multiple wikis in same domain. Encode only the
812      * _prefs array of the UserPreference object. Ideally the
813      * prefs array should just be imploded into a single string or
814      * something so it is completely human readable by the end
815      * user. In that case stricter error checking will be needed
816      * when loading the cookie.
817      */
818     function setPreferences($prefs, $id_only = false)
819     {
820         if (!is_object($prefs)) {
821             if (is_object($this->_prefs)) {
822                 $updated = $this->_prefs->updatePrefs($prefs);
823                 $prefs =& $this->_prefs;
824             } else {
825                 // update the prefs values from scratch. This could leed to unnecessary
826                 // side-effects: duplicate emailVerified, ...
827                 $this->_prefs = new UserPreferences($prefs);
828                 $updated = true;
829             }
830         } else {
831             if (!isset($this->_prefs))
832                 $this->_prefs =& $prefs;
833             else
834                 $updated = $this->_prefs->isChanged($prefs);
835         }
836         if ($updated) {
837             if ($id_only and !headers_sent()) {
838                 global $request;
839                 // new 1.3.8 policy: no array cookies, only plain userid string as in
840                 // the pre 1.3.x versions.
841                 // prefs should be stored besides the session in the homepagehandle or in a db.
842                 $request->setCookieVar(getCookieName(), $this->_userid,
843                     COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
844                 //$request->setCookieVar(WIKI_NAME, array('userid' => $prefs->get('userid')),
845                 //                       COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
846             }
847         }
848         if (is_object($prefs)) {
849             $packed = $prefs->store();
850             $unpacked = $prefs->unpack($packed);
851             if (count($unpacked)) {
852                 foreach (array('_method', '_select', '_update', '_insert') as $param) {
853                     if (!empty($this->_prefs->{$param}))
854                         $prefs->{$param} = $this->_prefs->{$param};
855                 }
856                 $this->_prefs = $prefs;
857             }
858         }
859         return $updated;
860     }
861
862     function userExists()
863     {
864         return true;
865     }
866
867     function checkPass($submitted_password)
868     {
869         return false;
870         // this might happen on a old-style signin button.
871
872         // By definition, the _AnonUser does not HAVE a password
873         // (compared to _BogoUser, who has an EMPTY password).
874         trigger_error("DEBUG: Warning: _AnonUser unexpectedly asked to checkPass()." . " "
875             . "Check isa(\$user, '_PassUser'), or: isa(\$user, '_AdminUser') etc. first." . " "
876             . "New subclasses of _WikiUser must override this function.");
877         return false;
878     }
879
880 }
881
882 /**
883  * Helper class to finish the PassUser auth loop.
884  * This is added automatically to USER_AUTH_ORDER.
885  */
886 class _ForbiddenUser
887     extends _AnonUser
888 {
889     var $_level = WIKIAUTH_FORBIDDEN;
890
891     function checkPass($submitted_password)
892     {
893         return WIKIAUTH_FORBIDDEN;
894     }
895
896     function userExists()
897     {
898         if ($this->_HomePagehandle) return true;
899         return false;
900     }
901 }
902
903 /**
904  * Do NOT extend _BogoUser to other classes, for checkPass()
905  * security. (In case of defects in code logic of the new class!)
906  * The intermediate step between anon and passuser.
907  * We also have the _BogoLoginPassUser class with stricter
908  * password checking, which fits into the auth loop.
909  * Note: This class is not called anymore by WikiUser()
910  */
911 class _BogoUser
912     extends _AnonUser
913 {
914     function userExists()
915     {
916         if (isWikiWord($this->_userid)) {
917             $this->_level = WIKIAUTH_BOGO;
918             return true;
919         } else {
920             $this->_level = WIKIAUTH_ANON;
921             return false;
922         }
923     }
924
925     function checkPass($submitted_password)
926     {
927         // By definition, BogoUser has an empty password.
928         $this->userExists();
929         return $this->_level;
930     }
931 }
932
933 class _PassUser
934     extends _AnonUser
935     /**
936      * Called if ALLOW_USER_PASSWORDS and Anon and Bogo failed.
937      *
938      * The classes for all subsequent auth methods extend from this class.
939      * This handles the auth method type dispatcher according $USER_AUTH_ORDER,
940      * the three auth method policies first-only, strict and stacked
941      * and the two methods for prefs: homepage or database,
942      * if $DBAuthParams['pref_select'] is defined.
943      *
944      * Default is PersonalPage auth and prefs.
945      *
946      * @author: Reini Urban
947      * @tables: pref
948      */
949 {
950     var $_auth_dbi, $_prefs;
951     var $_current_method, $_current_index;
952
953     // check and prepare the auth and pref methods only once
954     function _PassUser($UserName = '', $prefs = false)
955     {
956         //global $DBAuthParams, $DBParams;
957         if ($UserName) {
958             /*if (!$this->isValidName($UserName))
959                 return false;*/
960             $this->_userid = $UserName;
961             if ($this->hasHomePage())
962                 $this->_HomePagehandle = $GLOBALS['request']->getPage($this->_userid);
963         }
964         $this->_authmethod = substr(get_class($this), 1, -8);
965         if ($this->_authmethod == 'a') $this->_authmethod = 'admin';
966
967         // Check the configured Prefs methods
968         $dbi = $this->getAuthDbh();
969         $dbh = $GLOBALS['request']->getDbh();
970         if ($dbi
971             and !$dbh->readonly
972                 and !isset($this->_prefs->_select)
973                     and $dbh->getAuthParam('pref_select')
974         ) {
975             if (!$this->_prefs) {
976                 $this->_prefs = new UserPreferences();
977                 $need_pref = true;
978             }
979             $this->_prefs->_method = $dbh->getParam('dbtype');
980             $this->_prefs->_select = $this->prepare($dbh->getAuthParam('pref_select'), "userid");
981             // read-only prefs?
982             if (!isset($this->_prefs->_update) and $dbh->getAuthParam('pref_update')) {
983                 $this->_prefs->_update = $this->prepare($dbh->getAuthParam('pref_update'),
984                     array("userid", "pref_blob"));
985             }
986         } else {
987             if (!$this->_prefs) {
988                 $this->_prefs = new UserPreferences();
989                 $need_pref = true;
990             }
991             $this->_prefs->_method = 'HomePage';
992         }
993
994         if (!$this->_prefs or isset($need_pref)) {
995             if ($prefs) $this->_prefs = $prefs;
996             else $this->getPreferences();
997         }
998
999         // Upgrade to the next parent _PassUser class. Avoid recursion.
1000         if (strtolower(get_class($this)) === '_passuser') {
1001             //auth policy: Check the order of the configured auth methods
1002             // 1. first-only: Upgrade the class here in the constructor
1003             // 2. old:       ignore USER_AUTH_ORDER and try to use all available methods as
1004             ///              in the previous PhpWiki releases (slow)
1005             // 3. strict:    upgrade the class after checking the user existance in userExists()
1006             // 4. stacked:   upgrade the class after the password verification in checkPass()
1007             // Methods: PersonalPage, HttpAuth, DB, Ldap, Imap, File
1008             //if (!defined('USER_AUTH_POLICY')) define('USER_AUTH_POLICY','old');
1009             if (defined('USER_AUTH_POLICY')) {
1010                 // policy 1: only pre-define one method for all users
1011                 if (USER_AUTH_POLICY === 'first-only') {
1012                     $class = $this->nextClass();
1013                     return new $class($UserName, $this->_prefs);
1014                 } // Use the default behaviour from the previous versions:
1015                 elseif (USER_AUTH_POLICY === 'old') {
1016                     // Default: try to be smart
1017                     // On php5 we can directly return and upgrade the Object,
1018                     // before we have to upgrade it manually.
1019                     if (!empty($GLOBALS['PHP_AUTH_USER']) or !empty($_SERVER['REMOTE_USER'])) {
1020                         include_once 'lib/WikiUser/HttpAuth.php';
1021                         return new _HttpAuthPassUser($UserName, $this->_prefs);
1022                     } elseif (in_array('Db', $dbh->getAuthParam('USER_AUTH_ORDER')) and
1023                         $dbh->getAuthParam('auth_check') and
1024                             ($dbh->getAuthParam('auth_dsn') or $dbh->getParam('dsn'))
1025                     ) {
1026                         return new _DbPassUser($UserName, $this->_prefs);
1027                     } elseif (in_array('LDAP', $dbh->getAuthParam('USER_AUTH_ORDER')) and
1028                         defined('LDAP_AUTH_HOST') and defined('LDAP_BASE_DN') and
1029                             function_exists('ldap_connect')
1030                     ) {
1031                         include_once 'lib/WikiUser/LDAP.php';
1032                         return new _LDAPPassUser($UserName, $this->_prefs);
1033                     } elseif (in_array('IMAP', $dbh->getAuthParam('USER_AUTH_ORDER')) and
1034                         defined('IMAP_AUTH_HOST') and function_exists('imap_open')
1035                     ) {
1036                         include_once 'lib/WikiUser/IMAP.php';
1037                             return new _IMAPPassUser($UserName, $this->_prefs);
1038                     } elseif (in_array('File', $dbh->getAuthParam('USER_AUTH_ORDER')) and
1039                         defined('AUTH_USER_FILE') and file_exists(AUTH_USER_FILE)
1040                     ) {
1041                         include_once 'lib/WikiUser/File.php';
1042                         return new _FilePassUser($UserName, $this->_prefs);
1043                     } else {
1044                         include_once 'lib/WikiUser/PersonalPage.php';
1045                         return new _PersonalPagePassUser($UserName, $this->_prefs);
1046                     }
1047                 } else
1048                     // else use the page methods defined in _PassUser.
1049                     return $this;
1050             }
1051         }
1052     }
1053
1054     function getAuthDbh()
1055     {
1056         global $request; //, $DBParams, $DBAuthParams;
1057
1058         $dbh = $request->getDbh();
1059         // session restauration doesn't re-connect to the database automatically,
1060         // so dirty it here, to force a reconnect.
1061         if (isset($this->_auth_dbi)) {
1062             if (($dbh->getParam('dbtype') == 'SQL') and empty($this->_auth_dbi->connection))
1063                 unset($this->_auth_dbi);
1064             if (($dbh->getParam('dbtype') == 'ADODB') and empty($this->_auth_dbi->_connectionID))
1065                 unset($this->_auth_dbi);
1066         }
1067         if (empty($this->_auth_dbi)) {
1068             if ($dbh->getParam('dbtype') != 'SQL'
1069                 and $dbh->getParam('dbtype') != 'ADODB'
1070                     and $dbh->getParam('dbtype') != 'PDO'
1071             )
1072                 return false;
1073             if (empty($GLOBALS['DBAuthParams']))
1074                 return false;
1075             if (!$dbh->getAuthParam('auth_dsn')) {
1076                 $dbh = $request->getDbh(); // use phpwiki database
1077             } elseif ($dbh->getAuthParam('auth_dsn') == $dbh->getParam('dsn')) {
1078                 $dbh = $request->getDbh(); // same phpwiki database
1079             } else { // use another external database handle. needs PHP >= 4.1
1080                 $local_params = array_merge($GLOBALS['DBParams'], $GLOBALS['DBAuthParams']);
1081                 $local_params['dsn'] = $local_params['auth_dsn'];
1082                 $dbh = WikiDB::open($local_params);
1083             }
1084             $this->_auth_dbi =& $dbh->_backend->_dbh;
1085         }
1086         return $this->_auth_dbi;
1087     }
1088
1089     function _normalize_stmt_var($var, $oldstyle = false)
1090     {
1091         static $valid_variables = array('userid', 'password', 'pref_blob', 'groupname');
1092         // old-style: "'$userid'"
1093         // new-style: '"\$userid"' or just "userid"
1094         $new = str_replace(array("'", '"', '\$', '$'), '', $var);
1095         if (!in_array($new, $valid_variables)) {
1096             trigger_error("Unknown DBAuthParam statement variable: " . $new, E_USER_ERROR);
1097             return false;
1098         }
1099         return !$oldstyle ? "'$" . $new . "'" : '\$' . $new;
1100     }
1101
1102     // TODO: use it again for the auth and member tables
1103     // sprintfstyle vs prepare style: %s or ?
1104     //   multiple vars should be executed via prepare(?,?)+execute,
1105     //   single vars with execute(sprintf(quote(var)))
1106     // help with position independency
1107     function prepare($stmt, $variables, $oldstyle = false, $sprintfstyle = true)
1108     {
1109         global $request;
1110         $dbi = $request->getDbh();
1111         $this->getAuthDbh();
1112         // "'\$userid"' => %s
1113         // variables can be old-style: '"\$userid"' or new-style: "'$userid'" or just "userid"
1114         // old-style strings don't survive pear/Config/IniConfig treatment, that's why we changed it.
1115         $new = array();
1116         if (is_array($variables)) {
1117             //$sprintfstyle = false;
1118             for ($i = 0; $i < count($variables); $i++) {
1119                 $var = $this->_normalize_stmt_var($variables[$i], $oldstyle);
1120                 if (!$var)
1121                     trigger_error(sprintf("DbAuthParams: Undefined or empty statement variable %s in %s",
1122                         $variables[$i], $stmt), E_USER_WARNING);
1123                 $variables[$i] = $var;
1124                 if (!$var) $new[] = '';
1125                 else {
1126                     $s = "%" . ($i + 1) . "s";
1127                     $new[] = $sprintfstyle ? $s : "?";
1128                 }
1129             }
1130         } else {
1131             $var = $this->_normalize_stmt_var($variables, $oldstyle);
1132             if (!$var)
1133                 trigger_error(sprintf("DbAuthParams: Undefined or empty statement variable %s in %s",
1134                     $variables, $stmt), E_USER_WARNING);
1135             $variables = $var;
1136             if (!$var) $new = '';
1137             else $new = $sprintfstyle ? '%s' : "?";
1138         }
1139         $prefix = $dbi->getParam('prefix');
1140         // probably prefix table names if in same database
1141         if ($prefix and isset($this->_auth_dbi) and isset($dbi->_backend->_dbh) and
1142             ($dbi->getAuthParam('auth_dsn') and $dbi->getParam('dsn') == $dbi->getAuthParam('auth_dsn'))
1143         ) {
1144             if (!stristr($stmt, $prefix)) {
1145                 $oldstmt = $stmt;
1146                 $stmt = str_replace(array(" user ", " pref ", " member "),
1147                     array(" " . $prefix . "user ",
1148                         " " . $prefix . "pref ",
1149                         " " . $prefix . "member "), $stmt);
1150                 //Do it automatically for the lazy admin? Esp. on sf.net it's nice to have
1151                 trigger_error("Need to prefix the DBAUTH tablename in config/config.ini:\n  $oldstmt \n=> $stmt",
1152                     E_USER_WARNING);
1153             }
1154         }
1155         // Preparate the SELECT statement, for ADODB and PearDB (MDB not).
1156         // Simple sprintf-style.
1157         $new_stmt = str_replace($variables, $new, $stmt);
1158         if ($new_stmt == $stmt) {
1159             if ($oldstyle) {
1160                 trigger_error(sprintf("DbAuthParams: Invalid statement in %s",
1161                     $stmt), E_USER_WARNING);
1162             } else {
1163                 trigger_error(sprintf("DbAuthParams: Old statement quoting style in %s",
1164                     $stmt), E_USER_WARNING);
1165                 $new_stmt = $this->prepare($stmt, $variables, 'oldstyle');
1166             }
1167         }
1168         return $new_stmt;
1169     }
1170
1171     function getPreferences()
1172     {
1173         if (!empty($this->_prefs->_method)) {
1174             if ($this->_prefs->_method == 'ADODB') {
1175                 // FIXME: strange why this should be needed...
1176                 include_once 'lib/WikiUser/Db.php';
1177                 include_once 'lib/WikiUser/AdoDb.php';
1178                 return _AdoDbPassUser::getPreferences();
1179             } elseif ($this->_prefs->_method == 'SQL') {
1180                 include_once 'lib/WikiUser/Db.php';
1181                 include_once 'lib/WikiUser/PearDb.php';
1182                 return _PearDbPassUser::getPreferences();
1183             } elseif ($this->_prefs->_method == 'PDO') {
1184                 include_once 'lib/WikiUser/Db.php';
1185                 include_once 'lib/WikiUser/PdoDb.php';
1186                 return _PdoDbPassUser::getPreferences();
1187             }
1188         }
1189
1190         // We don't necessarily have to read the cookie first. Since
1191         // the user has a password, the prefs stored in the homepage
1192         // cannot be arbitrarily altered by other Bogo users.
1193         _AnonUser::getPreferences();
1194         // User may have deleted cookie, retrieve from his
1195         // PersonalPage if there is one.
1196         if (!empty($this->_HomePagehandle)) {
1197             if ($restored_from_page = $this->_prefs->retrieve
1198             ($this->_HomePagehandle->get('pref'))
1199             ) {
1200                 $updated = $this->_prefs->updatePrefs($restored_from_page, 'init');
1201                 //$this->_prefs = new UserPreferences($restored_from_page);
1202                 return $this->_prefs;
1203             }
1204         }
1205         return $this->_prefs;
1206     }
1207
1208     function setPreferences($prefs, $id_only = false)
1209     {
1210         if (!empty($this->_prefs->_method)) {
1211             if ($this->_prefs->_method == 'ADODB') {
1212                 // FIXME: strange why this should be needed...
1213                 include_once 'lib/WikiUser/Db.php';
1214                 include_once 'lib/WikiUser/AdoDb.php';
1215                 return _AdoDbPassUser::setPreferences($prefs, $id_only);
1216             } elseif ($this->_prefs->_method == 'SQL') {
1217                 include_once 'lib/WikiUser/Db.php';
1218                 include_once 'lib/WikiUser/PearDb.php';
1219                 return _PearDbPassUser::setPreferences($prefs, $id_only);
1220             } elseif ($this->_prefs->_method == 'PDO') {
1221                 include_once 'lib/WikiUser/Db.php';
1222                 include_once 'lib/WikiUser/PdoDb.php';
1223                 return _PdoDbPassUser::setPreferences($prefs, $id_only);
1224             }
1225         }
1226         if ($updated = _AnonUser::setPreferences($prefs, $id_only)) {
1227             // Encode only the _prefs array of the UserPreference object
1228             // If no DB method exists to store the prefs we must store it in the page, not in the cookies.
1229             if (empty($this->_HomePagehandle)) {
1230                 $this->_HomePagehandle = $GLOBALS['request']->getPage($this->_userid);
1231             }
1232             if (!$this->_HomePagehandle->exists()) {
1233                 $this->createHomePage();
1234             }
1235             if (!empty($this->_HomePagehandle) and !$id_only) {
1236                 $this->_HomePagehandle->set('pref', $this->_prefs->store());
1237             }
1238         }
1239         return $updated;
1240     }
1241
1242     function mayChangePass()
1243     {
1244         return true;
1245     }
1246
1247     //The default method is getting the password from prefs.
1248     // child methods obtain $stored_password from external auth.
1249     function userExists()
1250     {
1251         //if ($this->_HomePagehandle) return true;
1252         if (strtolower(get_class($this)) == "_passuser") {
1253             $class = $this->nextClass();
1254             $user = new $class($this->_userid, $this->_prefs);
1255         } else {
1256             $user = $this;
1257         }
1258         /* new user => false does not return false, but the _userid is empty then */
1259         while ($user and $user->_userid) {
1260             $user = UpgradeUser($this, $user);
1261             if ($user->userExists()) {
1262                 $user = UpgradeUser($this, $user);
1263                 return true;
1264             }
1265             // prevent endless loop. does this work on all PHP's?
1266             // it just has to set the classname, what it correctly does.
1267             $class = $user->nextClass();
1268             if ($class == "_ForbiddenPassUser")
1269                 return false;
1270         }
1271         return false;
1272     }
1273
1274     //The default method is getting the password from prefs.
1275     // child methods obtain $stored_password from external auth.
1276     function checkPass($submitted_password)
1277     {
1278         $stored_password = $this->_prefs->get('passwd');
1279         if ($this->_checkPass($submitted_password, $stored_password)) {
1280             $this->_level = WIKIAUTH_USER;
1281             return $this->_level;
1282         } else {
1283             if ((USER_AUTH_POLICY === 'strict') and $this->userExists()) {
1284                 $this->_level = WIKIAUTH_FORBIDDEN;
1285                 return $this->_level;
1286             }
1287             return $this->_tryNextPass($submitted_password);
1288         }
1289     }
1290
1291     function _checkPassLength($submitted_password)
1292     {
1293         if (strlen($submitted_password) < PASSWORD_LENGTH_MINIMUM) {
1294             trigger_error(_("The length of the password is shorter than the system policy allows."));
1295             return false;
1296         }
1297         return true;
1298     }
1299
1300     /**
1301      * The basic password checker for all PassUser objects.
1302      * Uses global ENCRYPTED_PASSWD and PASSWORD_LENGTH_MINIMUM.
1303      * Empty passwords are always false!
1304      * PASSWORD_LENGTH_MINIMUM is enforced here and in the preference set method.
1305      * @see UserPreferences::set
1306      *
1307      * DBPassUser password's have their own crypt definition.
1308      * That's why DBPassUser::checkPass() doesn't call this method, if
1309      * the db password method is 'plain', which means that the DB SQL
1310      * statement just returns 1 or 0. To use CRYPT() or PASSWORD() and
1311      * don't store plain passwords in the DB.
1312      *
1313      * TODO: remove crypt() function check from config.php:396 ??
1314      */
1315     function _checkPass($submitted_password, $stored_password)
1316     {
1317         if (!empty($submitted_password)) {
1318             // This works only on plaintext passwords.
1319             if (!ENCRYPTED_PASSWD and (strlen($stored_password) < PASSWORD_LENGTH_MINIMUM)) {
1320                 // With the EditMetaData plugin
1321                 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."));
1322                 return false;
1323             }
1324             if (!$this->_checkPassLength($submitted_password)) {
1325                 return false;
1326             }
1327             if (ENCRYPTED_PASSWD) {
1328                 // Verify against encrypted password.
1329                 if (function_exists('crypt')) {
1330                     if (crypt($submitted_password, $stored_password) == $stored_password)
1331                         return true; // matches encrypted password
1332                     else
1333                         return false;
1334                 } else {
1335                     trigger_error(_("The crypt function is not available in this version of PHP.") . " "
1336                             . _("Please set ENCRYPTED_PASSWD to false in config/config.ini and probably change ADMIN_PASSWD."),
1337                         E_USER_WARNING);
1338                     return false;
1339                 }
1340             } else {
1341                 // Verify against cleartext password.
1342                 if ($submitted_password == $stored_password)
1343                     return true;
1344                 else {
1345                     // Check whether we forgot to enable ENCRYPTED_PASSWD
1346                     if (function_exists('crypt')) {
1347                         if (crypt($submitted_password, $stored_password) == $stored_password) {
1348                             trigger_error(_("Please set ENCRYPTED_PASSWD to true in config/config.ini."),
1349                                 E_USER_WARNING);
1350                             return true;
1351                         }
1352                     }
1353                 }
1354             }
1355         }
1356         return false;
1357     }
1358
1359     /** The default method is storing the password in prefs.
1360      *  Child methods (DB, File) may store in external auth also, but this
1361      *  must be explicitly enabled.
1362      *  This may be called by plugin/UserPreferences or by ->SetPreferences()
1363      */
1364     function changePass($submitted_password)
1365     {
1366         $stored_password = $this->_prefs->get('passwd');
1367         // check if authenticated
1368         if (!$this->isAuthenticated()) return false;
1369         if (ENCRYPTED_PASSWD) {
1370             $submitted_password = crypt($submitted_password);
1371         }
1372         // check other restrictions, with side-effects only.
1373         $result = $this->_checkPass($submitted_password, $stored_password);
1374         if ($stored_password != $submitted_password) {
1375             $this->_prefs->set('passwd', $submitted_password);
1376             //update the storage (session, homepage, ...)
1377             $this->SetPreferences($this->_prefs);
1378             return true;
1379         }
1380         //Todo: return an error msg to the caller what failed?
1381         // same password or no privilege
1382         return ENCRYPTED_PASSWD ? true : false;
1383     }
1384
1385     function _tryNextPass($submitted_password)
1386     {
1387         if (DEBUG & _DEBUG_LOGIN) {
1388             $class = strtolower(get_class($this));
1389             if (substr($class, -10) == "dbpassuser") $class = "_dbpassuser";
1390             $GLOBALS['USER_AUTH_ERROR'][$class] = 'wrongpass';
1391         }
1392         if (USER_AUTH_POLICY === 'strict') {
1393             $class = $this->nextClass();
1394             if ($user = new $class($this->_userid, $this->_prefs)) {
1395                 if ($user->userExists()) {
1396                     return $user->checkPass($submitted_password);
1397                 }
1398             }
1399         }
1400         if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1401             $class = $this->nextClass();
1402             if ($user = new $class($this->_userid, $this->_prefs))
1403                 return $user->checkPass($submitted_password);
1404         }
1405         return $this->_level;
1406     }
1407
1408     function _tryNextUser()
1409     {
1410         if (DEBUG & _DEBUG_LOGIN) {
1411             $class = strtolower(get_class($this));
1412             if (substr($class, -10) == "dbpassuser") $class = "_dbpassuser";
1413             $GLOBALS['USER_AUTH_ERROR'][$class] = 'nosuchuser';
1414         }
1415         if (USER_AUTH_POLICY === 'strict'
1416             or USER_AUTH_POLICY === 'stacked'
1417         ) {
1418             $class = $this->nextClass();
1419             while ($user = new $class($this->_userid, $this->_prefs)) {
1420                 $user = UpgradeUser($this, $user);
1421                 if ($user->userExists()) {
1422                     $user = UpgradeUser($this, $user);
1423                     return true;
1424                 }
1425                 if ($class == "_ForbiddenPassUser") return false;
1426                 $class = $this->nextClass();
1427             }
1428         }
1429         return false;
1430     }
1431
1432 }
1433
1434 /**
1435  * Insert more auth classes here...
1436  * For example a customized db class for another db connection
1437  * or a socket-based auth server.
1438  *
1439  */
1440
1441 /**
1442  * For security, this class should not be extended. Instead, extend
1443  * from _PassUser (think of this as unix "root").
1444  *
1445  * FIXME: This should be a singleton class. Only ADMIN_USER may be of class AdminUser!
1446  * Other members of the Administrators group must raise their level otherwise somehow.
1447  * Currently every member is a AdminUser, which will not work for the various
1448  * storage methods.
1449  */
1450 class _AdminUser
1451     extends _PassUser
1452 {
1453     function mayChangePass()
1454     {
1455         return false;
1456     }
1457
1458     function checkPass($submitted_password)
1459     {
1460         if ($this->_userid == ADMIN_USER)
1461             $stored_password = ADMIN_PASSWD;
1462         else {
1463             // Should not happen! Only ADMIN_USER should use this class.
1464             // return $this->_tryNextPass($submitted_password); // ???
1465             // TODO: safety check if really member of the ADMIN group?
1466             $stored_password = $this->_pref->get('passwd');
1467         }
1468         if ($this->_checkPass($submitted_password, $stored_password)) {
1469             $this->_level = WIKIAUTH_ADMIN;
1470             if (!empty($GLOBALS['HTTP_SERVER_VARS']['PHP_AUTH_USER']) and class_exists("_HttpAuthPassUser")) {
1471                 // fake http auth
1472                 _HttpAuthPassUser::_fake_auth($this->_userid, $submitted_password);
1473             }
1474             return $this->_level;
1475         } else {
1476             return $this->_tryNextPass($submitted_password);
1477             //$this->_level = WIKIAUTH_ANON;
1478             //return $this->_level;
1479         }
1480     }
1481
1482     function storePass($submitted_password)
1483     {
1484         if ($this->_userid == ADMIN_USER)
1485             return false;
1486         else {
1487             // should not happen! only ADMIN_USER should use this class.
1488             return parent::storePass($submitted_password);
1489         }
1490     }
1491 }
1492
1493 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1494 /**
1495  * Various data classes for the preference types,
1496  * to support get, set, sanify (range checking, ...)
1497  * update() will do the neccessary side-effects if a
1498  * setting gets changed (theme, language, ...)
1499  */
1500
1501 class _UserPreference
1502 {
1503     var $default_value;
1504
1505     function _UserPreference($default_value)
1506     {
1507         $this->default_value = $default_value;
1508     }
1509
1510     function sanify($value)
1511     {
1512         return (string)$value;
1513     }
1514
1515     function get($name)
1516     {
1517         if (isset($this->{$name}))
1518             return $this->{$name};
1519         else
1520             return $this->default_value;
1521     }
1522
1523     function getraw($name)
1524     {
1525         if (!empty($this->{$name})) {
1526             return $this->{$name};
1527         } else {
1528             return '';
1529         }
1530     }
1531
1532     // stores the value as $this->$name, and not as $this->value (clever?)
1533     function set($name, $value)
1534     {
1535         $return = 0;
1536         $value = $this->sanify($value);
1537         if ($this->get($name) != $value) {
1538             $this->update($value);
1539             $return = 1;
1540         }
1541         if ($value != $this->default_value) {
1542             $this->{$name} = $value;
1543         } else {
1544             unset($this->{$name});
1545         }
1546         return $return;
1547     }
1548
1549     // default: no side-effects
1550     function update($value)
1551     {
1552         ;
1553     }
1554 }
1555
1556 class _UserPreference_numeric
1557     extends _UserPreference
1558 {
1559     function _UserPreference_numeric($default, $minval = false,
1560                                      $maxval = false)
1561     {
1562         $this->_UserPreference((double)$default);
1563         $this->_minval = (double)$minval;
1564         $this->_maxval = (double)$maxval;
1565     }
1566
1567     function sanify($value)
1568     {
1569         $value = (double)$value;
1570         if ($this->_minval !== false && $value < $this->_minval)
1571             $value = $this->_minval;
1572         if ($this->_maxval !== false && $value > $this->_maxval)
1573             $value = $this->_maxval;
1574         return $value;
1575     }
1576 }
1577
1578 class _UserPreference_int
1579     extends _UserPreference_numeric
1580 {
1581     function _UserPreference_int($default, $minval = false, $maxval = false)
1582     {
1583         $this->_UserPreference_numeric((int)$default, (int)$minval, (int)$maxval);
1584     }
1585
1586     function sanify($value)
1587     {
1588         return (int)parent::sanify((int)$value);
1589     }
1590 }
1591
1592 class _UserPreference_bool
1593     extends _UserPreference
1594 {
1595     function _UserPreference_bool($default = false)
1596     {
1597         $this->_UserPreference((bool)$default);
1598     }
1599
1600     function sanify($value)
1601     {
1602         if (is_array($value)) {
1603             /* This allows for constructs like:
1604              *
1605              *   <input type="hidden" name="pref[boolPref][]" value="0" />
1606              *   <input type="checkbox" name="pref[boolPref][]" value="1" />
1607              *
1608              * (If the checkbox is not checked, only the hidden input
1609              * gets sent. If the checkbox is sent, both inputs get
1610              * sent.)
1611              */
1612             foreach ($value as $val) {
1613                 if ($val)
1614                     return true;
1615             }
1616             return false;
1617         }
1618         return (bool)$value;
1619     }
1620 }
1621
1622 class _UserPreference_language
1623     extends _UserPreference
1624 {
1625     function _UserPreference_language($default = DEFAULT_LANGUAGE)
1626     {
1627         $this->_UserPreference($default);
1628     }
1629
1630     // FIXME: check for valid locale
1631     function sanify($value)
1632     {
1633         // Revert to DEFAULT_LANGUAGE if user does not specify
1634         // language in UserPreferences or chooses <system language>.
1635         if ($value == '' or empty($value))
1636             $value = DEFAULT_LANGUAGE;
1637
1638         return (string)$value;
1639     }
1640
1641     function update($newvalue)
1642     {
1643         if (!$this->_init) {
1644             // invalidate etag to force fresh output
1645             $GLOBALS['request']->setValidators(array('%mtime' => false));
1646             update_locale($newvalue ? $newvalue : $GLOBALS['LANG']);
1647         }
1648     }
1649 }
1650
1651 class _UserPreference_theme
1652     extends _UserPreference
1653 {
1654     function _UserPreference_theme($default = THEME)
1655     {
1656         $this->_UserPreference($default);
1657     }
1658
1659     function sanify($value)
1660     {
1661         if (!empty($value) and FindFile($this->_themefile($value)))
1662             return $value;
1663         return $this->default_value;
1664     }
1665
1666     function update($newvalue)
1667     {
1668         global $WikiTheme;
1669         // invalidate etag to force fresh output
1670         if (!$this->_init)
1671             $GLOBALS['request']->setValidators(array('%mtime' => false));
1672         if ($newvalue)
1673             include_once($this->_themefile($newvalue));
1674         if (empty($WikiTheme))
1675             include_once($this->_themefile(THEME));
1676     }
1677
1678     function _themefile($theme)
1679     {
1680         return "themes/$theme/themeinfo.php";
1681     }
1682 }
1683
1684 class _UserPreference_notify
1685     extends _UserPreference
1686 {
1687     function sanify($value)
1688     {
1689         if (!empty($value))
1690             return $value;
1691         else
1692             return $this->default_value;
1693     }
1694
1695     /** update to global user prefs: side-effect on set notify changes
1696      * use a global_data notify hash:
1697      * notify = array('pagematch' => array(userid => ('email' => mail,
1698      *                                                'verified' => 0|1),
1699      *                                     ...),
1700      *                ...);
1701      */
1702     function update($value)
1703     {
1704         if (!empty($this->_init)) return;
1705         $dbh = $GLOBALS['request']->getDbh();
1706         $notify = $dbh->get('notify');
1707         if (empty($notify))
1708             $data = array();
1709         else
1710             $data =& $notify;
1711         // expand to existing pages only or store matches?
1712         // for now we store (glob-style) matches which is easier for the user
1713         $pages = $this->_page_split($value);
1714         // Limitation: only current user.
1715         $user = $GLOBALS['request']->getUser();
1716         if (!$user or !method_exists($user, 'UserName')) return;
1717         // This fails with php5 and a WIKI_ID cookie:
1718         $userid = $user->UserName();
1719         $email = $user->_prefs->get('email');
1720         $verified = $user->_prefs->_prefs['email']->getraw('emailVerified');
1721         // check existing notify hash and possibly delete pages for email
1722         if (!empty($data)) {
1723             foreach ($data as $page => $users) {
1724                 if (isset($data[$page][$userid]) and !in_array($page, $pages)) {
1725                     unset($data[$page][$userid]);
1726                 }
1727                 if (count($data[$page]) == 0)
1728                     unset($data[$page]);
1729             }
1730         }
1731         // add the new pages
1732         if (!empty($pages)) {
1733             foreach ($pages as $page) {
1734                 if (!isset($data[$page]))
1735                     $data[$page] = array();
1736                 if (!isset($data[$page][$userid])) {
1737                     // should we really store the verification notice here or
1738                     // check it dynamically at every page->save?
1739                     if ($verified) {
1740                         $data[$page][$userid] = array('email' => $email,
1741                             'verified' => $verified);
1742                     } else {
1743                         $data[$page][$userid] = array('email' => $email);
1744                     }
1745                 }
1746             }
1747         }
1748         // store users changes
1749         $dbh->set('notify', $data);
1750     }
1751
1752     /** split the user-given comma or whitespace delimited pagenames
1753      *  to array
1754      */
1755     function _page_split($value)
1756     {
1757         return preg_split('/[\s,]+/', $value, -1, PREG_SPLIT_NO_EMPTY);
1758     }
1759 }
1760
1761 class _UserPreference_email
1762     extends _UserPreference
1763 {
1764     function get($name)
1765     {
1766         // get e-mail address from FusionForge
1767         if ((defined('FUSIONFORGE') and FUSIONFORGE) && session_loggedin()) {
1768             $user = session_get_user();
1769             return $user->getEmail();
1770         } else {
1771             parent::get($name);
1772         }
1773     }
1774
1775     function sanify($value)
1776     {
1777         // e-mail address is already checked by FusionForge
1778         if (defined('FUSIONFORGE') and FUSIONFORGE) {
1779             return $value;
1780         }
1781         // check for valid email address
1782         if ($this->get('email') == $value and $this->getraw('emailVerified')) {
1783             return $value;
1784         }
1785         // hack!
1786         if ($value == 1 or $value === true) {
1787             return $value;
1788         }
1789         list($ok, $msg) = ValidateMail($value, 'noconnect');
1790         if ($ok) {
1791             return $value;
1792         } else {
1793             trigger_error("E-mail Validation Error: " . $msg, E_USER_WARNING);
1794             return $this->default_value;
1795         }
1796     }
1797
1798     /** Side-effect on email changes:
1799      * Send a verification mail or for now just a notification email.
1800      * For true verification (value = 2), we'd need a mailserver hook.
1801      */
1802     function update($value)
1803     {
1804         // e-mail address is already checked by FusionForge
1805         if (defined('FUSIONFORGE') and FUSIONFORGE) {
1806             return;
1807         }
1808         if (!empty($this->_init)) {
1809             return;
1810         }
1811         $verified = $this->getraw('emailVerified');
1812         // hack!
1813         if (($value == 1 or $value === true) and $verified) {
1814             return;
1815         }
1816         if (!empty($value) and !$verified) {
1817             list($ok, $msg) = ValidateMail($value);
1818             if ($ok and mail($value, "[" . WIKI_NAME . "] " . _("E-mail address confirmation"),
1819                 sprintf(_("Welcome to %s!\nYour e-mail account is verified and\nwill be used to send page change notifications.\nSee %s"),
1820                     WIKI_NAME, WikiURL($GLOBALS['request']->getArg('pagename'), '', true)))
1821             ) {
1822                 $this->set('emailVerified', 1);
1823             } else {
1824                 trigger_error($msg, E_USER_WARNING);
1825             }
1826         }
1827     }
1828 }
1829
1830 /** Check for valid email address
1831 fixed version from http://www.zend.com/zend/spotlight/ev12apr.php
1832 Note: too strict, Bug #1053681
1833  */
1834 function ValidateMail($email, $noconnect = false)
1835 {
1836     global $EMailHosts;
1837     $HTTP_HOST = $GLOBALS['request']->get('HTTP_HOST');
1838
1839     // if this check is too strict (like invalid mail addresses in a local network only)
1840     // uncomment the following line:
1841     //return array(true,"not validated");
1842     // see http://sourceforge.net/tracker/index.php?func=detail&aid=1053681&group_id=6121&atid=106121
1843
1844     $result = array();
1845
1846     // This is Paul Warren's (pdw@ex-parrot.com) monster regex for RFC822
1847     // addresses, from the Perl module Mail::RFC822::Address, reduced to
1848     // accept single RFC822 addresses without comments only. (The original
1849     // accepts groups and properly commented addresses also.)
1850     $lwsp = "(?:(?:\\r\\n)?[ \\t])";
1851
1852     $specials = '()<>@,;:\\\\".\\[\\]';
1853     $controls = '\\000-\\031';
1854
1855     $dtext = "[^\\[\\]\\r\\\\]";
1856     $domain_literal = "\\[(?:$dtext|\\\\.)*\\]$lwsp*";
1857
1858     $quoted_string = "\"(?:[^\\\"\\r\\\\]|\\\\.|$lwsp)*\"$lwsp*";
1859
1860     $atom = "[^$specials $controls]+(?:$lwsp+|\\Z|(?=[\\[\"$specials]))";
1861     $word = "(?:$atom|$quoted_string)";
1862     $localpart = "$word(?:\\.$lwsp*$word)*";
1863
1864     $sub_domain = "(?:$atom|$domain_literal)";
1865     $domain = "$sub_domain(?:\\.$lwsp*$sub_domain)*";
1866
1867     $addr_spec = "$localpart\@$lwsp*$domain";
1868
1869     $phrase = "$word*";
1870     $route = "(?:\@$domain(?:,\@$lwsp*$domain)*:$lwsp*)";
1871     $route_addr = "\\<$lwsp*$route?$addr_spec\\>$lwsp*";
1872     $mailbox = "(?:$addr_spec|$phrase$route_addr)";
1873
1874     $rfc822re = "/$lwsp*$mailbox/";
1875     unset($domain, $route_addr, $route, $phrase, $addr_spec, $sub_domain, $localpart,
1876     $atom, $word, $quoted_string);
1877     unset($dtext, $controls, $specials, $lwsp, $domain_literal);
1878
1879     if (!preg_match($rfc822re, $email)) {
1880         $result[0] = false;
1881         $result[1] = sprintf(_("E-mail address “%s” is not properly formatted"), $email);
1882         return $result;
1883     }
1884     if ($noconnect)
1885         return array(true, sprintf(_("E-mail address “%s” is properly formatted"), $email));
1886
1887     list ($Username, $Domain) = explode("@", $email);
1888     //Todo: getmxrr workaround on Windows or manual input field to verify it manually
1889     if (!isWindows() and getmxrr($Domain, $MXHost)) { // avoid warning on Windows.
1890         $ConnectAddress = $MXHost[0];
1891     } else {
1892         $ConnectAddress = $Domain;
1893         if (isset($EMailHosts[$Domain])) {
1894             $ConnectAddress = $EMailHosts[$Domain];
1895         }
1896     }
1897     $Connect = @fsockopen($ConnectAddress, 25);
1898     if ($Connect) {
1899         if (ereg("^220", $Out = fgets($Connect, 1024))) {
1900             fputs($Connect, "HELO $HTTP_HOST\r\n");
1901             $Out = fgets($Connect, 1024);
1902             fputs($Connect, "MAIL FROM: <" . $email . ">\r\n");
1903             $From = fgets($Connect, 1024);
1904             fputs($Connect, "RCPT TO: <" . $email . ">\r\n");
1905             $To = fgets($Connect, 1024);
1906             fputs($Connect, "QUIT\r\n");
1907             fclose($Connect);
1908             if (!ereg("^250", $From)) {
1909                 $result[0] = false;
1910                 $result[1] = "Server rejected address: " . $From;
1911                 return $result;
1912             }
1913             if (!ereg("^250", $To)) {
1914                 $result[0] = false;
1915                 $result[1] = "Server rejected address: " . $To;
1916                 return $result;
1917             }
1918         } else {
1919             $result[0] = false;
1920             $result[1] = "No response from server";
1921             return $result;
1922         }
1923     } else {
1924         $result[0] = false;
1925         $result[1] = "Cannot connect e-mail server.";
1926         return $result;
1927     }
1928     $result[0] = true;
1929     $result[1] = "E-mail address '$email' appears to be valid.";
1930     return $result;
1931 } // end of function
1932
1933 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1934
1935 /**
1936  * UserPreferences
1937  *
1938  * This object holds the $request->_prefs subobjects.
1939  * A simple packed array of non-default values get's stored as cookie,
1940  * homepage, or database, which are converted to the array of
1941  * ->_prefs objects.
1942  * We don't store the objects, because otherwise we will
1943  * not be able to upgrade any subobject. And it's a waste of space also.
1944  *
1945  */
1946 class UserPreferences
1947 {
1948     var $notifyPagesAll;
1949
1950     function UserPreferences($saved_prefs = false)
1951     {
1952         // userid stored too, to ensure the prefs are being loaded for
1953         // the correct (currently signing in) userid if stored in a
1954         // cookie.
1955         // Update: for db prefs we disallow passwd.
1956         // userid is needed for pref reflexion. current pref must know its username,
1957         // if some app needs prefs from different users, different from current user.
1958         $this->_prefs
1959             = array(
1960             'userid' => new _UserPreference(''),
1961             'passwd' => new _UserPreference(''),
1962             'autologin' => new _UserPreference_bool(),
1963             //'emailVerified' => new _UserPreference_emailVerified(),
1964             //fixed: store emailVerified as email parameter, 1.3.8
1965             'email' => new _UserPreference_email(''),
1966             'notifyPages' => new _UserPreference_notify(''), // 1.3.8
1967             'theme' => new _UserPreference_theme(THEME),
1968             'lang' => new _UserPreference_language(DEFAULT_LANGUAGE),
1969             'editWidth' => new _UserPreference_int(EDITWIDTH_DEFAULT_COLS,
1970                 EDITWIDTH_MIN_COLS,
1971                 EDITWIDTH_MAX_COLS),
1972             'noLinkIcons' => new _UserPreference_bool(), // 1.3.8
1973             'editHeight' => new _UserPreference_int(EDITHEIGHT_DEFAULT_ROWS,
1974                 EDITHEIGHT_MIN_ROWS,
1975                 EDITHEIGHT_MAX_ROWS),
1976             'timeOffset' => new _UserPreference_numeric(TIMEOFFSET_DEFAULT_HOURS,
1977                 TIMEOFFSET_MIN_HOURS,
1978                 TIMEOFFSET_MAX_HOURS),
1979             'ownModifications' => new _UserPreference_bool(),
1980             'majorModificationsOnly' => new _UserPreference_bool(),
1981             'relativeDates' => new _UserPreference_bool(),
1982             'googleLink' => new _UserPreference_bool(), // 1.3.10
1983             'doubleClickEdit' => new _UserPreference_bool(), // 1.3.11
1984         );
1985
1986         // This should be probably be done with $customUserPreferenceColumns
1987         // For now, we use FUSIONFORGE define
1988         if (defined('FUSIONFORGE') and FUSIONFORGE) {
1989             $fusionforgeprefs = array(
1990                 'pageTrail' => new _UserPreference_bool(),
1991                 'diffMenuItem' => new _UserPreference_bool(),
1992                 'pageInfoMenuItem' => new _UserPreference_bool(),
1993                 'pdfMenuItem' => new _UserPreference_bool(),
1994                 'lockMenuItem' => new _UserPreference_bool(),
1995                 'chownMenuItem' => new _UserPreference_bool(),
1996                 'setaclMenuItem' => new _UserPreference_bool(),
1997                 'removeMenuItem' => new _UserPreference_bool(),
1998                 'renameMenuItem' => new _UserPreference_bool(),
1999                 'revertMenuItem' => new _UserPreference_bool(),
2000                 'backLinksMenuItem' => new _UserPreference_bool(),
2001                 'watchPageMenuItem' => new _UserPreference_bool(),
2002                 'recentChangesMenuItem' => new _UserPreference_bool(),
2003                 'randomPageMenuItem' => new _UserPreference_bool(),
2004                 'likePagesMenuItem' => new _UserPreference_bool(),
2005                 'specialPagesMenuItem' => new _UserPreference_bool(),
2006             );
2007             $this->_prefs = array_merge($this->_prefs, $fusionforgeprefs);
2008         }
2009
2010         // add custom theme-specific pref types:
2011         // FIXME: on theme changes the wiki_user session pref object will fail.
2012         // We will silently ignore this.
2013         if (!empty($customUserPreferenceColumns))
2014             $this->_prefs = array_merge($this->_prefs, $customUserPreferenceColumns);
2015         /*
2016                 if (isset($this->_method) and $this->_method == 'SQL') {
2017                     //unset($this->_prefs['userid']);
2018                     unset($this->_prefs['passwd']);
2019                 }
2020         */
2021         if (is_array($saved_prefs)) {
2022             foreach ($saved_prefs as $name => $value)
2023                 $this->set($name, $value);
2024         }
2025     }
2026
2027     function __clone()
2028     {
2029         foreach ($this as $key => $val) {
2030             if (is_object($val) || (is_array($val))) {
2031                 $this->{$key} = unserialize(serialize($val));
2032             }
2033         }
2034     }
2035
2036     function _getPref($name)
2037     {
2038         if ($name == 'emailVerified')
2039             $name = 'email';
2040         if (!isset($this->_prefs[$name])) {
2041             if ($name == 'passwd2') return false;
2042             if ($name == 'passwd') return false;
2043             trigger_error("$name: unknown preference", E_USER_NOTICE);
2044             return false;
2045         }
2046         return $this->_prefs[$name];
2047     }
2048
2049     // get the value or default_value of the subobject
2050     function get($name)
2051     {
2052         if ($_pref = $this->_getPref($name))
2053             if ($name == 'emailVerified')
2054                 return $_pref->getraw($name);
2055             else
2056                 return $_pref->get($name);
2057         else
2058             return false;
2059     }
2060
2061     // check and set the new value in the subobject
2062     function set($name, $value)
2063     {
2064         $pref = $this->_getPref($name);
2065         if ($pref === false)
2066             return false;
2067
2068         /* do it here or outside? */
2069         if ($name == 'passwd' and
2070             defined('PASSWORD_LENGTH_MINIMUM') and
2071                 strlen($value) <= PASSWORD_LENGTH_MINIMUM
2072         ) {
2073             //TODO: How to notify the user?
2074             return false;
2075         }
2076         /*
2077         if ($name == 'theme' and $value == '')
2078            return true;
2079         */
2080         // Fix Fatal error for undefined value. Thanks to Jim Ford and Joel Schaubert
2081         if ((!$value and $pref->default_value)
2082             or ($value and !isset($pref->{$name})) // bug #1355533
2083             or ($value and ($pref->{$name} != $pref->default_value))
2084         ) {
2085             if ($name == 'emailVerified') $newvalue = $value;
2086             else $newvalue = $pref->sanify($value);
2087             $pref->set($name, $newvalue);
2088         }
2089         $this->_prefs[$name] =& $pref;
2090         return true;
2091     }
2092
2093     /**
2094      * use init to avoid update on set
2095      */
2096     function updatePrefs($prefs, $init = false)
2097     {
2098         $count = 0;
2099         if ($init) $this->_init = $init;
2100         if (is_object($prefs)) {
2101             $type = 'emailVerified';
2102             $obj =& $this->_prefs['email'];
2103             $obj->_init = $init;
2104             if ($obj->get($type) !== $prefs->get($type)) {
2105                 if ($obj->set($type, $prefs->get($type)))
2106                     $count++;
2107             }
2108             foreach (array_keys($this->_prefs) as $type) {
2109                 $obj =& $this->_prefs[$type];
2110                 $obj->_init = $init;
2111                 if ($prefs->get($type) !== $obj->get($type)) {
2112                     // special systemdefault prefs: (probably not needed)
2113                     if ($type == 'theme' and $prefs->get($type) == '' and
2114                         $obj->get($type) == THEME
2115                     ) continue;
2116                     if ($type == 'lang' and $prefs->get($type) == '' and
2117                         $obj->get($type) == DEFAULT_LANGUAGE
2118                     ) continue;
2119                     if ($this->_prefs[$type]->set($type, $prefs->get($type)))
2120                         $count++;
2121                 }
2122             }
2123         } elseif (is_array($prefs)) {
2124             //unset($this->_prefs['userid']);
2125             /*
2126         if (isset($this->_method) and
2127              ($this->_method == 'SQL' or $this->_method == 'ADODB')) {
2128                 unset($this->_prefs['passwd']);
2129         }
2130         */
2131             // emailVerified at first, the rest later
2132             $type = 'emailVerified';
2133             $obj =& $this->_prefs['email'];
2134             $obj->_init = $init;
2135             if (isset($prefs[$type]) and $obj->get($type) !== $prefs[$type]) {
2136                 if ($obj->set($type, $prefs[$type]))
2137                     $count++;
2138             }
2139             foreach (array_keys($this->_prefs) as $type) {
2140                 $obj =& $this->_prefs[$type];
2141                 $obj->_init = $init;
2142                 if (!isset($prefs[$type]) and isa($obj, "_UserPreference_bool"))
2143                     $prefs[$type] = false;
2144                 if (isset($prefs[$type]) and isa($obj, "_UserPreference_int"))
2145                     $prefs[$type] = (int)$prefs[$type];
2146                 if (isset($prefs[$type]) and $obj->get($type) != $prefs[$type]) {
2147                     // special systemdefault prefs:
2148                     if ($type == 'theme' and $prefs[$type] == '' and
2149                         $obj->get($type) == THEME
2150                     ) continue;
2151                     if ($type == 'lang' and $prefs[$type] == '' and
2152                         $obj->get($type) == DEFAULT_LANGUAGE
2153                     ) continue;
2154                     if ($obj->set($type, $prefs[$type]))
2155                         $count++;
2156                 }
2157             }
2158         }
2159         return $count;
2160     }
2161
2162     // For now convert just array of objects => array of values
2163     // Todo: the specialized subobjects must override this.
2164     function store()
2165     {
2166         $prefs = array();
2167         foreach ($this->_prefs as $name => $object) {
2168             if ($value = $object->getraw($name))
2169                 $prefs[$name] = $value;
2170             if ($name == 'email' and ($value = $object->getraw('emailVerified')))
2171                 $prefs['emailVerified'] = $value;
2172             if ($name == 'passwd' and $value and ENCRYPTED_PASSWD) {
2173                 if (strlen($value) != strlen(crypt('test')))
2174                     $prefs['passwd'] = crypt($value);
2175                 else // already crypted
2176                     $prefs['passwd'] = $value;
2177             }
2178         }
2179
2180         if (defined('FUSIONFORGE') and FUSIONFORGE) {
2181             // Merge current notifyPages with notifyPagesAll
2182             // notifyPages are pages to notify in the current project
2183             // while $notifyPagesAll is used to store all the monitored pages.
2184             if (isset($prefs['notifyPages'])) {
2185                 $this->notifyPagesAll[PAGE_PREFIX] = $prefs['notifyPages'];
2186                 $prefs['notifyPages'] = @serialize($this->notifyPagesAll);
2187             }
2188         }
2189
2190         return $this->pack($prefs);
2191     }
2192
2193     // packed string or array of values => array of values
2194     // Todo: the specialized subobjects must override this.
2195     function retrieve($packed)
2196     {
2197         if (is_string($packed) and (substr($packed, 0, 2) == "a:"))
2198             $packed = unserialize($packed);
2199         if (!is_array($packed)) return false;
2200         $prefs = array();
2201         foreach ($packed as $name => $packed_pref) {
2202             if (is_string($packed_pref)
2203                 and isSerialized($packed_pref)
2204                     and substr($packed_pref, 0, 2) == "O:"
2205             ) {
2206                 //legacy: check if it's an old array of objects
2207                 // Looks like a serialized object.
2208                 // This might fail if the object definition does not exist anymore.
2209                 // object with ->$name and ->default_value vars.
2210                 $pref = @unserialize($packed_pref);
2211                 if (is_object($pref))
2212                     $prefs[$name] = $pref->get($name);
2213                 // fix old-style prefs
2214             } elseif (is_numeric($name) and is_array($packed_pref)) {
2215                 if (count($packed_pref) == 1) {
2216                     list($name, $value) = each($packed_pref);
2217                     $prefs[$name] = $value;
2218                 }
2219             } else {
2220                 if (isSerialized($packed_pref))
2221                     $prefs[$name] = @unserialize($packed_pref);
2222                 if (empty($prefs[$name]) and isSerialized(base64_decode($packed_pref)))
2223                     $prefs[$name] = @unserialize(base64_decode($packed_pref));
2224                 // patched by frederik@pandora.be
2225                 if (empty($prefs[$name]))
2226                     $prefs[$name] = $packed_pref;
2227             }
2228         }
2229
2230         if (defined('FUSIONFORGE') and FUSIONFORGE) {
2231             // Restore notifyPages from notifyPagesAll
2232             // notifyPages are pages to notify in the current project
2233             // while $notifyPagesAll is used to store all the monitored pages.
2234             if (isset($prefs['notifyPages'])) {
2235                 $this->notifyPagesAll = $prefs['notifyPages'];
2236                 if (isset($this->notifyPagesAll[PAGE_PREFIX])) {
2237                     $prefs['notifyPages'] = $this->notifyPagesAll[PAGE_PREFIX];
2238                 } else {
2239                     $prefs['notifyPages'] = '';
2240                 }
2241             }
2242         }
2243
2244         return $prefs;
2245     }
2246
2247     /**
2248      * Check if the given prefs object is different from the current prefs object
2249      */
2250     function isChanged($other)
2251     {
2252         foreach ($this->_prefs as $type => $obj) {
2253             if ($obj->get($type) !== $other->get($type))
2254                 return true;
2255         }
2256         return false;
2257     }
2258
2259     function defaultPreferences()
2260     {
2261         $prefs = array();
2262         foreach ($this->_prefs as $key => $obj) {
2263             $prefs[$key] = $obj->default_value;
2264         }
2265         return $prefs;
2266     }
2267
2268     // array of objects
2269     function getAll()
2270     {
2271         return $this->_prefs;
2272     }
2273
2274     function pack($nonpacked)
2275     {
2276         return serialize($nonpacked);
2277     }
2278
2279     function unpack($packed)
2280     {
2281         if (!$packed)
2282             return false;
2283         //$packed = base64_decode($packed);
2284         if (substr($packed, 0, 2) == "O:") {
2285             // Looks like a serialized object
2286             return unserialize($packed);
2287         }
2288         if (substr($packed, 0, 2) == "a:") {
2289             return unserialize($packed);
2290         }
2291         //trigger_error("DEBUG: Can't unpack bad UserPreferences",
2292         //E_USER_WARNING);
2293         return false;
2294     }
2295
2296     function hash()
2297     {
2298         return wikihash($this->_prefs);
2299     }
2300 }
2301
2302 /** TODO: new pref storage classes
2303  *  These are currently user specific and should be rewritten to be pref specific.
2304  *  i.e. $this == $user->_prefs
2305  */
2306 /*
2307 class CookieUserPreferences
2308 extends UserPreferences
2309 {
2310     function CookieUserPreferences ($saved_prefs = false) {
2311         //_AnonUser::_AnonUser('',$saved_prefs);
2312         UserPreferences::UserPreferences($saved_prefs);
2313     }
2314 }
2315
2316 class PageUserPreferences
2317 extends UserPreferences
2318 {
2319     function PageUserPreferences ($saved_prefs = false) {
2320         UserPreferences::UserPreferences($saved_prefs);
2321     }
2322 }
2323
2324 class PearDbUserPreferences
2325 extends UserPreferences
2326 {
2327     function PearDbUserPreferences ($saved_prefs = false) {
2328         UserPreferences::UserPreferences($saved_prefs);
2329     }
2330 }
2331
2332 class AdoDbUserPreferences
2333 extends UserPreferences
2334 {
2335     function AdoDbUserPreferences ($saved_prefs = false) {
2336         UserPreferences::UserPreferences($saved_prefs);
2337     }
2338     function getPreferences() {
2339         // override the generic slow method here for efficiency
2340         _AnonUser::getPreferences();
2341         $this->getAuthDbh();
2342         if (isset($this->_select)) {
2343             $dbh = & $this->_auth_dbi;
2344             $rs = $dbh->Execute(sprintf($this->_select,$dbh->qstr($this->_userid)));
2345             if ($rs->EOF) {
2346                 $rs->Close();
2347             } else {
2348                 $prefs_blob = $rs->fields['pref_blob'];
2349                 $rs->Close();
2350                 if ($restored_from_db = $this->_prefs->retrieve($prefs_blob)) {
2351                     $updated = $this->_prefs->updatePrefs($restored_from_db);
2352                     //$this->_prefs = new UserPreferences($restored_from_db);
2353                     return $this->_prefs;
2354                 }
2355             }
2356         }
2357         if (empty($this->_prefs->_prefs) and $this->_HomePagehandle) {
2358             if ($restored_from_page = $this->_prefs->retrieve
2359                 ($this->_HomePagehandle->get('pref'))) {
2360                 $updated = $this->_prefs->updatePrefs($restored_from_page);
2361                 //$this->_prefs = new UserPreferences($restored_from_page);
2362                 return $this->_prefs;
2363             }
2364         }
2365         return $this->_prefs;
2366     }
2367 }
2368 */
2369
2370 // Local Variables:
2371 // mode: php
2372 // tab-width: 8
2373 // c-basic-offset: 4
2374 // c-hanging-comment-ender-p: nil
2375 // indent-tabs-mode: nil
2376 // End: