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