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