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