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