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