]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiUserNew.php
New FSF address
[SourceForge/phpwiki.git] / lib / WikiUserNew.php
1 <?php //-*-php-*-
2 //$Id$
3 /* Copyright (C) 2004,2005,2006,2007,2009,2010 $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 along
20 * with PhpWiki; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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  * 2010-06-07 rurban
96  *    Fixed a nasty recursion bug (i.e. php crash), when user = new class
97  *    which returned false, did not return false on php-4.4.7. Check for
98  *    a object member now.
99  */
100
101 define('WIKIAUTH_FORBIDDEN', -1); // Completely not allowed.
102 define('WIKIAUTH_ANON', 0);       // Not signed in.
103 define('WIKIAUTH_BOGO', 1);       // Any valid WikiWord is enough.
104 define('WIKIAUTH_USER', 2);       // Bogo user with a password.
105 define('WIKIAUTH_ADMIN', 10);     // UserName == ADMIN_USER.
106 define('WIKIAUTH_UNOBTAINABLE', 100);  // Permissions that no user can achieve
107
108 //if (!defined('COOKIE_EXPIRATION_DAYS')) define('COOKIE_EXPIRATION_DAYS', 365);
109 //if (!defined('COOKIE_DOMAIN'))          define('COOKIE_DOMAIN', '/');
110 if (!defined('EDITWIDTH_MIN_COLS'))     define('EDITWIDTH_MIN_COLS',     30);
111 if (!defined('EDITWIDTH_MAX_COLS'))     define('EDITWIDTH_MAX_COLS',    150);
112 if (!defined('EDITWIDTH_DEFAULT_COLS')) define('EDITWIDTH_DEFAULT_COLS', 80);
113
114 if (!defined('EDITHEIGHT_MIN_ROWS'))     define('EDITHEIGHT_MIN_ROWS',      5);
115 if (!defined('EDITHEIGHT_MAX_ROWS'))     define('EDITHEIGHT_MAX_ROWS',     80);
116 if (!defined('EDITHEIGHT_DEFAULT_ROWS')) define('EDITHEIGHT_DEFAULT_ROWS', 22);
117
118 define('TIMEOFFSET_MIN_HOURS', -26);
119 define('TIMEOFFSET_MAX_HOURS',  26);
120 if (!defined('TIMEOFFSET_DEFAULT_HOURS')) define('TIMEOFFSET_DEFAULT_HOURS', 0);
121
122 /* EMAIL VERIFICATION
123  * On certain nets or hosts the email domain cannot be determined automatically from the DNS.
124  * Provide some overrides here.
125  *    ( username @ ) domain => mail-domain
126  */
127 $EMailHosts = array('avl.com' => 'mail.avl.com');
128
129 /**
130  * There are be the following constants in config/config.ini to
131  * establish login parameters:
132  *
133  * ALLOW_ANON_USER         default true
134  * ALLOW_ANON_EDIT         default true
135  * ALLOW_BOGO_LOGIN        default true
136  * ALLOW_USER_PASSWORDS    default true
137  * PASSWORD_LENGTH_MINIMUM default 0
138  *
139  * To require user passwords for editing:
140  * ALLOW_ANON_USER  = true
141  * ALLOW_ANON_EDIT  = false   (before named REQUIRE_SIGNIN_BEFORE_EDIT)
142  * ALLOW_BOGO_LOGIN = false
143  * ALLOW_USER_PASSWORDS = true
144  *
145  * To establish a COMPLETELY private wiki, such as an internal
146  * corporate one:
147  * ALLOW_ANON_USER = false
148  * (and probably require user passwords as described above). In this
149  * case the user will be prompted to login immediately upon accessing
150  * any page.
151  *
152  * There are other possible combinations, but the typical wiki (such
153  * as http://PhpWiki.sf.net/phpwiki) would usually just leave all four
154  * enabled.
155  *
156  */
157
158 // The last object in the row is the bad guy...
159 if (!is_array($USER_AUTH_ORDER))
160     $USER_AUTH_ORDER = array("Forbidden");
161 else
162     $USER_AUTH_ORDER[] = "Forbidden";
163
164 // Local convenience functions.
165 function _isAnonUserAllowed() {
166     return (defined('ALLOW_ANON_USER') && ALLOW_ANON_USER);
167 }
168 function _isBogoUserAllowed() {
169     return (defined('ALLOW_BOGO_LOGIN') && ALLOW_BOGO_LOGIN);
170 }
171 function _isUserPasswordsAllowed() {
172     return (defined('ALLOW_USER_PASSWORDS') && ALLOW_USER_PASSWORDS);
173 }
174
175 // Possibly upgrade userobject functions.
176 function _determineAdminUserOrOtherUser($UserName) {
177     // Sanity check. User name is a condition of the definition of the
178     // _AdminUser, _BogoUser and _passuser.
179     if (!$UserName)
180         return $GLOBALS['ForbiddenUser'];
181
182     //FIXME: check admin membership later at checkPass. Now we cannot raise the level.
183     //$group = &WikiGroup::getGroup($GLOBALS['request']);
184     if ($UserName == ADMIN_USER)
185         return new _AdminUser($UserName);
186     /* elseif ($group->isMember(GROUP_ADMIN)) { // unneeded code
187         return _determineBogoUserOrPassUser($UserName);
188     }
189     */
190     else
191         return _determineBogoUserOrPassUser($UserName);
192 }
193
194 function _determineBogoUserOrPassUser($UserName) {
195     global $ForbiddenUser;
196
197     // Sanity check. User name is a condition of the definition of
198     // _BogoUser and _PassUser.
199     if (!$UserName)
200         return $ForbiddenUser;
201
202     // Check for password and possibly upgrade user object.
203     // $_BogoUser = new _BogoUser($UserName);
204     if (_isBogoUserAllowed() and isWikiWord($UserName)) {
205         include_once("lib/WikiUser/BogoLogin.php");
206         $_BogoUser = new _BogoLoginPassUser($UserName);
207         if ($_BogoUser->userExists() or $GLOBALS['request']->getArg('auth'))
208             return $_BogoUser;
209     }
210     if (_isUserPasswordsAllowed()) {
211         // PassUsers override BogoUsers if a password is stored
212         if (isset($_BogoUser) and isset($_BogoUser->_prefs)
213             and $_BogoUser->_prefs->get('passwd'))
214             return new _PassUser($UserName, $_BogoUser->_prefs);
215         else {
216             $_PassUser = new _PassUser($UserName,
217                                        isset($_BogoUser) ? $_BogoUser->_prefs : false);
218             if ($_PassUser->userExists() or $GLOBALS['request']->getArg('auth')) {
219                 if (isset($GLOBALS['request']->_user_class))
220                 $class = $GLOBALS['request']->_user_class;
221                 elseif (strtolower(get_class($_PassUser)) == "_passuser")
222                 $class = $_PassUser->nextClass();
223             else
224             $class = get_class($_PassUser);
225             if ($user = new $class($UserName, $_PassUser->_prefs)
226                 and $user->_userid) {
227                 return $user;
228                 } else {
229                     return $_PassUser;
230                 }
231             }
232         }
233     }
234     // No Bogo- or PassUser exists, or
235     // passwords are not allowed, and bogo is disallowed too.
236     // (Only the admin can sign in).
237     return $ForbiddenUser;
238 }
239
240 /**
241  * Primary WikiUser function, called by lib/main.php.
242  *
243  * This determines the user's type and returns an appropriate user
244  * object. lib/main.php then querys the resultant object for password
245  * validity as necessary.
246  *
247  * If an _AnonUser object is returned, the user may only browse pages
248  * (and save prefs in a cookie).
249  *
250  * To disable access but provide prefs the global $ForbiddenUser class
251  * is returned. (was previously false)
252  *
253  */
254 function WikiUser ($UserName = '') {
255     global $ForbiddenUser, $HTTP_SESSION_VARS;
256
257     //Maybe: Check sessionvar for username & save username into
258     //sessionvar (may be more appropriate to do this in lib/main.php).
259     if ($UserName) {
260         $ForbiddenUser = new _ForbiddenUser($UserName);
261         // Found a user name.
262         return _determineAdminUserOrOtherUser($UserName);
263     }
264     elseif (!empty($HTTP_SESSION_VARS['userid'])) {
265         // Found a user name.
266         $ForbiddenUser = new _ForbiddenUser($_SESSION['userid']);
267         return _determineAdminUserOrOtherUser($_SESSION['userid']);
268     }
269     else {
270         // Check for autologin pref in cookie and possibly upgrade
271         // user object to another type.
272         $_AnonUser = new _AnonUser();
273         if ($UserName = $_AnonUser->_userid && $_AnonUser->_prefs->get('autologin')) {
274             // Found a user name.
275             $ForbiddenUser = new _ForbiddenUser($UserName);
276             return _determineAdminUserOrOtherUser($UserName);
277         }
278         else {
279             $ForbiddenUser = new _ForbiddenUser();
280             if (_isAnonUserAllowed())
281                 return $_AnonUser;
282             return $ForbiddenUser; // User must sign in to browse pages.
283         }
284         return $ForbiddenUser;     // User must sign in with a password.
285     }
286     /*
287     trigger_error("DEBUG: Note: End of function reached in WikiUser." . " "
288                   . "Unexpectedly, an appropriate user class could not be determined.");
289     return $ForbiddenUser; // Failsafe.
290     */
291 }
292
293 /**
294  * WikiUser.php use the name 'WikiUser'
295  */
296 function WikiUserClassname() {
297     return '_WikiUser';
298 }
299
300
301 /**
302  * Upgrade olduser by copying properties from user to olduser.
303  * We are not sure yet, for which php's a simple $this = $user works reliably,
304  * (on php4 it works ok, on php5 it's currently disallowed on the parser level)
305  * that's why try it the hard way.
306  */
307 function UpgradeUser ($user, $newuser) {
308     if (isa($user,'_WikiUser') and isa($newuser,'_WikiUser')) {
309         // populate the upgraded class $newuser with the values from the current user object
310         //only _auth_level, _current_method, _current_index,
311         if (!empty($user->_level) and
312             $user->_level > $newuser->_level)
313             $newuser->_level = $user->_level;
314         if (!empty($user->_current_index) and
315             $user->_current_index > $newuser->_current_index) {
316             $newuser->_current_index = $user->_current_index;
317             $newuser->_current_method = $user->_current_method;
318         }
319         if (!empty($user->_authmethod))
320             $newuser->_authmethod = $user->_authmethod;
321     $GLOBALS['request']->_user_class = get_class($newuser);
322         /*
323         foreach (get_object_vars($user) as $k => $v) {
324             if (!empty($v)) $olduser->$k = $v;
325         }
326         */
327         $newuser->hasHomePage(); // revive db handle, because these don't survive sessions
328         //$GLOBALS['request']->_user = $olduser;
329         return $newuser;
330     } else {
331         return false;
332     }
333 }
334
335 /**
336  * Probably not needed, since we use the various user objects methods so far.
337  * Anyway, here it is, looping through all available objects.
338  */
339 function UserExists ($UserName) {
340     global $request;
341     if (!($user = $request->getUser()))
342         $user = WikiUser($UserName);
343     if (!$user)
344         return false;
345     if ($user->userExists($UserName)) {
346         $request->_user = $user;
347         return true;
348     }
349     if (isa($user,'_BogoUser'))
350         $user = new _PassUser($UserName,$user->_prefs);
351     $class = $user->nextClass();
352     if ($user = new $class($UserName, $user->_prefs)) {
353         return $user->userExists($UserName);
354     }
355     $request->_user = $GLOBALS['ForbiddenUser'];
356     return false;
357 }
358
359 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
360
361 /**
362  * Base WikiUser class.
363  */
364 class _WikiUser
365 {
366      var $_userid = '';
367      var $_level = WIKIAUTH_ANON;
368      var $_prefs = false;
369      var $_HomePagehandle = false;
370
371     // constructor
372     function _WikiUser($UserName='', $prefs=false) {
373
374         $this->_userid = $UserName;
375         $this->_HomePagehandle = false;
376         if ($UserName) {
377             $this->hasHomePage();
378         }
379         if (empty($this->_prefs)) {
380             if ($prefs) $this->_prefs = $prefs;
381             else $this->getPreferences();
382         }
383     }
384
385     function UserName() {
386         if (!empty($this->_userid))
387             return $this->_userid;
388     }
389
390     function getPreferences() {
391         trigger_error("DEBUG: Note: undefined _WikiUser class trying to load prefs." . " "
392                       . "New subclasses of _WikiUser must override this function.");
393         return false;
394     }
395
396     function setPreferences($prefs, $id_only) {
397         trigger_error("DEBUG: Note: undefined _WikiUser class trying to save prefs."
398                       . " "
399                       . "New subclasses of _WikiUser must override this function.");
400         return false;
401     }
402
403     function userExists() {
404         return $this->hasHomePage();
405     }
406
407     function checkPass($submitted_password) {
408         // By definition, an undefined user class cannot sign in.
409         trigger_error("DEBUG: Warning: undefined _WikiUser class trying to sign in."
410                       . " "
411                       . "New subclasses of _WikiUser must override this function.");
412         return false;
413     }
414
415     // returns page_handle to user's home page or false if none
416     function hasHomePage() {
417         if ($this->_userid) {
418             if (!empty($this->_HomePagehandle) and is_object($this->_HomePagehandle)) {
419                 return $this->_HomePagehandle->exists();
420             }
421             else {
422                 // check db again (maybe someone else created it since
423                 // we logged in.)
424                 global $request;
425                 $this->_HomePagehandle = $request->getPage($this->_userid);
426                 return $this->_HomePagehandle->exists();
427             }
428         }
429         // nope
430         return false;
431     }
432
433     function createHomePage() {
434         global $request;
435         $versiondata = array('author' => ADMIN_USER);
436         $request->_dbi->save(_("Automatically created user homepage to be able to store UserPreferences.").
437                              "\n{{Template/UserPage}}",
438                              1, $versiondata);
439         $request->_dbi->touch();
440         $this->_HomePagehandle = $request->getPage($this->_userid);
441     }
442
443     // innocent helper: case-insensitive position in _auth_methods
444     function array_position ($string, $array) {
445         $string = strtolower($string);
446         for ($found = 0; $found < count($array); $found++) {
447             if (strtolower($array[$found]) == $string)
448                 return $found;
449         }
450         return false;
451     }
452
453     function nextAuthMethodIndex() {
454         if (empty($this->_auth_methods))
455             $this->_auth_methods = $GLOBALS['USER_AUTH_ORDER'];
456         if (empty($this->_current_index)) {
457             if (strtolower(get_class($this)) != '_passuser') {
458                 $this->_current_method = substr(get_class($this),1,-8);
459                 $this->_current_index = $this->array_position($this->_current_method,
460                                                               $this->_auth_methods);
461             } else {
462                 $this->_current_index = -1;
463             }
464         }
465         $this->_current_index++;
466         if ($this->_current_index >= count($this->_auth_methods))
467             return false;
468         $this->_current_method = $this->_auth_methods[$this->_current_index];
469         return $this->_current_index;
470     }
471
472     function AuthMethod($index = false) {
473         return $this->_auth_methods[ $index === false
474                                      ? count($this->_auth_methods)-1
475                                      : $index];
476     }
477
478     // upgrade the user object
479     function nextClass() {
480         $method = $this->AuthMethod($this->nextAuthMethodIndex());
481         include_once("lib/WikiUser/$method.php");
482         return "_".$method."PassUser";
483     }
484
485     //Fixme: for _HttpAuthPassUser
486     function PrintLoginForm (&$request, $args, $fail_message = false,
487                              $seperate_page = false) {
488         include_once('lib/Template.php');
489         // Call update_locale in case the system's default language is not 'en'.
490         // (We have no user pref for lang at this point yet, no one is logged in.)
491         if ($GLOBALS['LANG'] != DEFAULT_LANGUAGE)
492             update_locale(DEFAULT_LANGUAGE);
493         $userid = $this->_userid;
494         $require_level = 0;
495         extract($args); // fixme
496
497         $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
498
499         $pagename = $request->getArg('pagename');
500         $nocache = 1;
501         $login = Template('login',
502                           compact('pagename', 'userid', 'require_level',
503                                   'fail_message', 'pass_required', 'nocache'));
504         // check if the html template was already processed
505         $seperate_page = $seperate_page ? true : !alreadyTemplateProcessed('html');
506         if ($seperate_page) {
507             $page = $request->getPage($pagename);
508             $revision = $page->getCurrentRevision();
509             return GeneratePage($login,_("Sign In"), $revision);
510         } else {
511             return $login->printExpansion();
512         }
513     }
514
515     /** Signed in but not password checked or empty password.
516      */
517     function isSignedIn() {
518         return (isa($this,'_BogoUser') or isa($this,'_PassUser'));
519     }
520
521     /** This is password checked for sure.
522      */
523     function isAuthenticated() {
524         //return isa($this,'_PassUser');
525         //return isa($this,'_BogoUser') || isa($this,'_PassUser');
526         return $this->_level >= WIKIAUTH_BOGO;
527     }
528
529     function isAdmin () {
530         static $group;
531         if ($this->_level == WIKIAUTH_ADMIN) return true;
532         if (!$this->isSignedIn()) return false;
533         if (!$this->isAuthenticated()) return false;
534
535         if (!$group) $group = &$GLOBALS['request']->getGroup();
536         return ($this->_level > WIKIAUTH_BOGO and $group->isMember(GROUP_ADMIN));
537     }
538
539     /** Name or IP for a signed user. UserName could come from a cookie e.g.
540      */
541     function getId () {
542         return ( $this->UserName()
543                  ? $this->UserName()
544                  : $GLOBALS['request']->get('REMOTE_ADDR') );
545     }
546
547     /** Name for an authenticated user. No IP here.
548      */
549     function getAuthenticatedId() {
550         return ( $this->isAuthenticated()
551                  ? $this->_userid
552                  : ''); //$GLOBALS['request']->get('REMOTE_ADDR') );
553     }
554
555     function hasAuthority ($require_level) {
556         return $this->_level >= $require_level;
557     }
558
559     /* This is quite restrictive and not according the login description online.
560        Any word char (A-Za-z0-9_), " ", ".", "@" and "-"
561        The backends may loosen or tighten this.
562     */
563     function isValidName ($userid = false) {
564         if (!$userid) $userid = $this->_userid;
565         if (!$userid) return false;
566         if (FUSIONFORGE) {
567             return true;
568         }
569         return preg_match("/^[\-\w\.@ ]+$/U", $userid) and strlen($userid) < 32;
570     }
571
572     /**
573      * Called on an auth_args POST request, such as login, logout or signin.
574      * TODO: Check BogoLogin users with empty password. (self-signed users)
575      */
576     function AuthCheck ($postargs) {
577         // Normalize args, and extract.
578         $keys = array('userid', 'passwd', 'require_level', 'login', 'logout',
579                       'cancel');
580         foreach ($keys as $key)
581             $args[$key] = isset($postargs[$key]) ? $postargs[$key] : false;
582         extract($args);
583         $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
584
585         if ($logout) { // Log out
586         if (LOGIN_LOG and is_writeable(LOGIN_LOG)) {
587         global $request;
588         $zone_offset = Request_AccessLogEntry::_zone_offset();
589         $ncsa_time = date("d/M/Y:H:i:s", time());
590         $entry = sprintf('%s - %s - [%s %s] "%s" %s - "%s" "%s"',
591                  (string) $request->get('REMOTE_HOST'),
592                  (string) $request->_user->_userid,
593                  $ncsa_time, $zone_offset,
594                  "logout ".get_class($request->_user),
595                  "401",
596                  (string) $request->get('HTTP_REFERER'),
597                  (string) $request->get('HTTP_USER_AGENT')
598                  );
599         if (($fp = fopen(LOGIN_LOG, "a"))) {
600             flock($fp, LOCK_EX);
601             fputs($fp, "$entry\n");
602             fclose($fp);
603         }
604         //error_log("$entry\n", 3, LOGIN_LOG);
605         }
606             if (method_exists($GLOBALS['request']->_user, "logout")) { //_HttpAuthPassUser
607               $GLOBALS['request']->_user->logout();
608             }
609             $user = new _AnonUser();
610             $user->_userid = '';
611             $user->_level = WIKIAUTH_ANON;
612             return $user;
613         } elseif ($cancel)
614             return false;        // User hit cancel button.
615         elseif (!$login && !$userid)
616             return false;       // Nothing to do?
617
618         if (!$this->isValidName($userid))
619             return _("Invalid username.");;
620
621         $authlevel = $this->checkPass($passwd === false ? '' : $passwd);
622
623     if (LOGIN_LOG and is_writeable(LOGIN_LOG)) {
624         global $request;
625         $zone_offset = Request_AccessLogEntry::_zone_offset();
626         $ncsa_time = date("d/M/Y:H:i:s", time());
627         $manglepasswd = $passwd;
628         for ($i=0; $i<strlen($manglepasswd); $i++) {
629         $c = substr($manglepasswd,$i,1);
630         if (ord($c) < 32) $manglepasswd[$i] = "<";
631         elseif ($c == '*') $manglepasswd[$i] = "*";
632         elseif ($c == '?') $manglepasswd[$i] = "?";
633         elseif ($c == '(') $manglepasswd[$i] = "(";
634         elseif ($c == ')') $manglepasswd[$i] = ")";
635         elseif ($c == "\\") $manglepasswd[$i] = "\\";
636         elseif (ord($c) < 127) $manglepasswd[$i] = "x";
637         elseif (ord($c) >= 127) $manglepasswd[$i] = ">";
638         }
639             if ((DEBUG & _DEBUG_LOGIN) and $authlevel <= 0) $manglepasswd = $passwd;
640         $entry = sprintf('%s - %s - [%s %s] "%s" %s - "%s" "%s"',
641                  $request->get('REMOTE_HOST'),
642                  (string) $request->_user->_userid,
643                  $ncsa_time, $zone_offset,
644                  "login $userid/$manglepasswd => $authlevel ".get_class($request->_user),
645                  $authlevel > 0 ? "200" : "403",
646                  (string) $request->get('HTTP_REFERER'),
647                  (string) $request->get('HTTP_USER_AGENT')
648                  );
649         if (($fp = fopen(LOGIN_LOG, "a"))) {
650         flock($fp, LOCK_EX);
651         fputs($fp, "$entry\n");
652         fclose($fp);
653         }
654         //error_log("$entry\n", 3, LOGIN_LOG);
655     }
656
657         if ($authlevel <= 0) { // anon or forbidden
658             if ($passwd)
659                 return _("Invalid password.");
660             else
661                 return _("Invalid password or userid.");
662         } elseif ($authlevel < $require_level) { // auth ok, but not enough
663             if (!empty($this->_current_method) and strtolower(get_class($this)) == '_passuser')
664             {
665                 // upgrade class
666                 $class = "_" . $this->_current_method . "PassUser";
667                 include_once("lib/WikiUser/".$this->_current_method.".php");
668                 $user = new $class($userid,$this->_prefs);
669                 if (!check_php_version(5))
670                     eval("\$this = \$user;");
671                 // /*PHP5 patch*/$this = $user;
672                 $this->_level = $authlevel;
673                 return $user;
674             }
675             $this->_userid = $userid;
676             $this->_level = $authlevel;
677             return _("Insufficient permissions.");
678         }
679
680         // Successful login.
681         //$user = $GLOBALS['request']->_user;
682         if (!empty($this->_current_method) and
683             strtolower(get_class($this)) == '_passuser')
684         {
685             // upgrade class
686             $class = "_" . $this->_current_method . "PassUser";
687             include_once("lib/WikiUser/".$this->_current_method.".php");
688             $user = new $class($userid, $this->_prefs);
689             if (!check_php_version(5))
690                 eval("\$this = \$user;");
691             // /*PHP5 patch*/$this = $user;
692             $user->_level = $authlevel;
693             return $user;
694         }
695         $this->_userid = $userid;
696         $this->_level = $authlevel;
697         return $this;
698     }
699
700 }
701
702 /**
703  * Not authenticated in user, but he may be signed in. Basicly with view access only.
704  * prefs are stored in cookies, but only the userid.
705  */
706 class _AnonUser
707 extends _WikiUser
708 {
709     var $_level = WIKIAUTH_ANON;     // var in php-5.0.0RC1 deprecated
710
711     /** Anon only gets to load and save prefs in a cookie, that's it.
712      */
713     function getPreferences() {
714         global $request;
715
716         if (empty($this->_prefs))
717             $this->_prefs = new UserPreferences;
718         $UserName = $this->UserName();
719
720         // Try to read deprecated 1.3.x style cookies
721         if ($cookie = $request->cookies->get_old(WIKI_NAME)) {
722             if (! $unboxedcookie = $this->_prefs->retrieve($cookie)) {
723                 trigger_error(_("Empty Preferences or format of UserPreferences cookie not recognised.")
724                               . "\n"
725                               . sprintf("%s='%s'", WIKI_NAME, $cookie)
726                               . "\n"
727                               . _("Default preferences will be used."),
728                               E_USER_NOTICE);
729             }
730             /**
731              * Only set if it matches the UserName who is
732              * signing in or if this really is an Anon login (no
733              * username). (Remember, _BogoUser and higher inherit this
734              * function too!).
735              */
736             if (! $UserName || $UserName == @$unboxedcookie['userid']) {
737                 $updated = $this->_prefs->updatePrefs($unboxedcookie);
738                 //$this->_prefs = new UserPreferences($unboxedcookie);
739                 $UserName = @$unboxedcookie['userid'];
740                 if (is_string($UserName) and (substr($UserName,0,2) != 's:'))
741                     $this->_userid = $UserName;
742                 else
743                     $UserName = false;
744             }
745             // v1.3.8 policy: don't set PhpWiki cookies, only plaintext WIKI_ID cookies
746             if (!headers_sent())
747                 $request->deleteCookieVar(WIKI_NAME);
748         }
749         // Try to read deprecated 1.3.4 style cookies
750         if (! $UserName and ($cookie = $request->cookies->get_old("WIKI_PREF2"))) {
751             if (! $unboxedcookie = $this->_prefs->retrieve($cookie)) {
752                 if (! $UserName || $UserName == $unboxedcookie['userid']) {
753                     $updated = $this->_prefs->updatePrefs($unboxedcookie);
754                     //$this->_prefs = new UserPreferences($unboxedcookie);
755                     $UserName = $unboxedcookie['userid'];
756                     if (is_string($UserName) and (substr($UserName,0,2) != 's:'))
757                         $this->_userid = $UserName;
758                     else
759                         $UserName = false;
760                 }
761                 if (!headers_sent())
762                     $request->deleteCookieVar("WIKI_PREF2");
763             }
764         }
765         if (! $UserName ) {
766             // Try reading userid from old PhpWiki cookie formats:
767             if ($cookie = $request->cookies->get_old(getCookieName())) {
768                 if (is_string($cookie) and (substr($cookie,0,2) != 's:'))
769                     $UserName = $cookie;
770                 elseif (is_array($cookie) and !empty($cookie['userid']))
771                     $UserName = $cookie['userid'];
772             }
773             if (! $UserName and !headers_sent())
774                 $request->deleteCookieVar(getCookieName());
775             else
776                 $this->_userid = $UserName;
777         }
778
779         // initializeTheme() needs at least an empty object
780         /*
781          if (empty($this->_prefs))
782             $this->_prefs = new UserPreferences;
783         */
784         return $this->_prefs;
785     }
786
787     /** _AnonUser::setPreferences(): Save prefs in a cookie and session and update all global vars
788      *
789      * Allow for multiple wikis in same domain. Encode only the
790      * _prefs array of the UserPreference object. Ideally the
791      * prefs array should just be imploded into a single string or
792      * something so it is completely human readable by the end
793      * user. In that case stricter error checking will be needed
794      * when loading the cookie.
795      */
796     function setPreferences($prefs, $id_only=false) {
797         if (!is_object($prefs)) {
798             if (is_object($this->_prefs)) {
799                 $updated = $this->_prefs->updatePrefs($prefs);
800                 $prefs =& $this->_prefs;
801             } else {
802                 // update the prefs values from scratch. This could leed to unnecessary
803                 // side-effects: duplicate emailVerified, ...
804                 $this->_prefs = new UserPreferences($prefs);
805                 $updated = true;
806             }
807         } else {
808             if (!isset($this->_prefs))
809                 $this->_prefs =& $prefs;
810             else
811                 $updated = $this->_prefs->isChanged($prefs);
812         }
813         if ($updated) {
814             if ($id_only and !headers_sent()) {
815                 global $request;
816                 // new 1.3.8 policy: no array cookies, only plain userid string as in
817                 // the pre 1.3.x versions.
818                 // prefs should be stored besides the session in the homepagehandle or in a db.
819                 $request->setCookieVar(getCookieName(), $this->_userid,
820                                        COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
821                 //$request->setCookieVar(WIKI_NAME, array('userid' => $prefs->get('userid')),
822                 //                       COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
823             }
824         }
825         if (is_object($prefs)) {
826             $packed = $prefs->store();
827             $unpacked = $prefs->unpack($packed);
828             if (count($unpacked)) {
829                 foreach (array('_method','_select','_update','_insert') as $param) {
830                     if (!empty($this->_prefs->{$param}))
831                         $prefs->{$param} = $this->_prefs->{$param};
832                 }
833                 $this->_prefs = $prefs;
834             }
835         }
836         return $updated;
837     }
838
839     function userExists() {
840         return true;
841     }
842
843     function checkPass($submitted_password) {
844         return false;
845         // this might happen on a old-style signin button.
846
847         // By definition, the _AnonUser does not HAVE a password
848         // (compared to _BogoUser, who has an EMPTY password).
849         trigger_error("DEBUG: Warning: _AnonUser unexpectedly asked to checkPass()." . " "
850                       . "Check isa(\$user, '_PassUser'), or: isa(\$user, '_AdminUser') etc. first." . " "
851                       . "New subclasses of _WikiUser must override this function.");
852         return false;
853     }
854
855 }
856
857 /**
858  * Helper class to finish the PassUser auth loop.
859  * This is added automatically to USER_AUTH_ORDER.
860  */
861 class _ForbiddenUser
862 extends _AnonUser
863 {
864     var $_level = WIKIAUTH_FORBIDDEN;
865
866     function checkPass($submitted_password) {
867         return WIKIAUTH_FORBIDDEN;
868     }
869
870     function userExists() {
871         if ($this->_HomePagehandle) return true;
872         return false;
873     }
874 }
875
876 /**
877  * Do NOT extend _BogoUser to other classes, for checkPass()
878  * security. (In case of defects in code logic of the new class!)
879  * The intermediate step between anon and passuser.
880  * We also have the _BogoLoginPassUser class with stricter
881  * password checking, which fits into the auth loop.
882  * Note: This class is not called anymore by WikiUser()
883  */
884 class _BogoUser
885 extends _AnonUser
886 {
887     function userExists() {
888         if (isWikiWord($this->_userid)) {
889             $this->_level = WIKIAUTH_BOGO;
890             return true;
891         } else {
892             $this->_level = WIKIAUTH_ANON;
893             return false;
894         }
895     }
896
897     function checkPass($submitted_password) {
898         // By definition, BogoUser has an empty password.
899         $this->userExists();
900         return $this->_level;
901     }
902 }
903
904 class _PassUser
905 extends _AnonUser
906 /**
907  * Called if ALLOW_USER_PASSWORDS and Anon and Bogo failed.
908  *
909  * The classes for all subsequent auth methods extend from this class.
910  * This handles the auth method type dispatcher according $USER_AUTH_ORDER,
911  * the three auth method policies first-only, strict and stacked
912  * and the two methods for prefs: homepage or database,
913  * if $DBAuthParams['pref_select'] is defined.
914  *
915  * Default is PersonalPage auth and prefs.
916  *
917  * @author: Reini Urban
918  * @tables: pref
919  */
920 {
921     var $_auth_dbi, $_prefs;
922     var $_current_method, $_current_index;
923
924     // check and prepare the auth and pref methods only once
925     function _PassUser($UserName='', $prefs=false) {
926         //global $DBAuthParams, $DBParams;
927         if ($UserName) {
928             /*if (!$this->isValidName($UserName))
929                 return false;*/
930             $this->_userid = $UserName;
931             if ($this->hasHomePage())
932                 $this->_HomePagehandle = $GLOBALS['request']->getPage($this->_userid);
933         }
934         $this->_authmethod = substr(get_class($this),1,-8);
935         if ($this->_authmethod == 'a') $this->_authmethod = 'admin';
936
937         // Check the configured Prefs methods
938         $dbi = $this->getAuthDbh();
939         $dbh = $GLOBALS['request']->getDbh();
940         if ( $dbi
941              and !$dbh->readonly
942              and !isset($this->_prefs->_select)
943              and $dbh->getAuthParam('pref_select'))
944         {
945             if (!$this->_prefs) {
946                 $this->_prefs = new UserPreferences();
947                 $need_pref = true;
948             }
949             $this->_prefs->_method = $dbh->getParam('dbtype');
950             $this->_prefs->_select = $this->prepare($dbh->getAuthParam('pref_select'), "userid");
951             // read-only prefs?
952             if ( !isset($this->_prefs->_update) and $dbh->getAuthParam('pref_update')) {
953                 $this->_prefs->_update = $this->prepare($dbh->getAuthParam('pref_update'),
954                                                         array("userid", "pref_blob"));
955             }
956         } else {
957             if (!$this->_prefs) {
958                 $this->_prefs = new UserPreferences();
959                 $need_pref = true;
960             }
961             $this->_prefs->_method = 'HomePage';
962         }
963
964         if (! $this->_prefs or isset($need_pref) ) {
965             if ($prefs) $this->_prefs = $prefs;
966             else $this->getPreferences();
967         }
968
969         // Upgrade to the next parent _PassUser class. Avoid recursion.
970         if ( strtolower(get_class($this)) === '_passuser' ) {
971             //auth policy: Check the order of the configured auth methods
972             // 1. first-only: Upgrade the class here in the constructor
973             // 2. old:       ignore USER_AUTH_ORDER and try to use all available methods as
974             ///              in the previous PhpWiki releases (slow)
975             // 3. strict:    upgrade the class after checking the user existance in userExists()
976             // 4. stacked:   upgrade the class after the password verification in checkPass()
977             // Methods: PersonalPage, HttpAuth, DB, Ldap, Imap, File
978             //if (!defined('USER_AUTH_POLICY')) define('USER_AUTH_POLICY','old');
979             if (defined('USER_AUTH_POLICY')) {
980                 // policy 1: only pre-define one method for all users
981                 if (USER_AUTH_POLICY === 'first-only') {
982                     $class = $this->nextClass();
983                     return new $class($UserName,$this->_prefs);
984                 }
985                 // Use the default behaviour from the previous versions:
986                 elseif (USER_AUTH_POLICY === 'old') {
987                     // Default: try to be smart
988                     // On php5 we can directly return and upgrade the Object,
989                     // before we have to upgrade it manually.
990                     if (!empty($GLOBALS['PHP_AUTH_USER']) or !empty($_SERVER['REMOTE_USER'])) {
991                         include_once("lib/WikiUser/HttpAuth.php");
992                         if (check_php_version(5))
993                             return new _HttpAuthPassUser($UserName,$this->_prefs);
994                         else {
995                             $user = new _HttpAuthPassUser($UserName,$this->_prefs);
996                             eval("\$this = \$user;");
997                             // /*PHP5 patch*/$this = $user;
998                             return $user;
999                         }
1000                     } elseif (in_array('Db', $dbh->getAuthParam('USER_AUTH_ORDER')) and
1001                               $dbh->getAuthParam('auth_check') and
1002                               ($dbh->getAuthParam('auth_dsn') or $dbh->getParam('dsn'))) {
1003                         if (check_php_version(5))
1004                             return new _DbPassUser($UserName,$this->_prefs);
1005                         else {
1006                             $user = new _DbPassUser($UserName,$this->_prefs);
1007                             eval("\$this = \$user;");
1008                             // /*PHP5 patch*/$this = $user;
1009                             return $user;
1010                         }
1011                     } elseif (in_array('LDAP', $dbh->getAuthParam('USER_AUTH_ORDER')) and
1012                               defined('LDAP_AUTH_HOST') and defined('LDAP_BASE_DN') and
1013                               function_exists('ldap_connect')) {
1014                         include_once("lib/WikiUser/LDAP.php");
1015                         if (check_php_version(5))
1016                             return new _LDAPPassUser($UserName,$this->_prefs);
1017                         else {
1018                             $user = new _LDAPPassUser($UserName,$this->_prefs);
1019                             eval("\$this = \$user;");
1020                             // /*PHP5 patch*/$this = $user;
1021                             return $user;
1022                         }
1023                     } elseif (in_array('IMAP', $dbh->getAuthParam('USER_AUTH_ORDER')) and
1024                               defined('IMAP_AUTH_HOST') and function_exists('imap_open')) {
1025                         include_once("lib/WikiUser/IMAP.php");
1026                         if (check_php_version(5))
1027                             return new _IMAPPassUser($UserName,$this->_prefs);
1028                         else {
1029                             $user = new _IMAPPassUser($UserName,$this->_prefs);
1030                             eval("\$this = \$user;");
1031                             // /*PHP5 patch*/$this = $user;
1032                             return $user;
1033                         }
1034                     } elseif (in_array('File', $dbh->getAuthParam('USER_AUTH_ORDER')) and
1035                               defined('AUTH_USER_FILE') and file_exists(AUTH_USER_FILE)) {
1036                         include_once("lib/WikiUser/File.php");
1037                         if (check_php_version(5))
1038                             return new _FilePassUser($UserName, $this->_prefs);
1039                         else {
1040                             $user = new _FilePassUser($UserName, $this->_prefs);
1041                             eval("\$this = \$user;");
1042                             // /*PHP5 patch*/$this = $user;
1043                             return $user;
1044                         }
1045                     } else {
1046                         include_once("lib/WikiUser/PersonalPage.php");
1047                         if (check_php_version(5))
1048                             return new _PersonalPagePassUser($UserName,$this->_prefs);
1049                         else {
1050                             $user = new _PersonalPagePassUser($UserName,$this->_prefs);
1051                             eval("\$this = \$user;");
1052                             // /*PHP5 patch*/$this = $user;
1053                             return $user;
1054                         }
1055                     }
1056                 }
1057                 else
1058                     // else use the page methods defined in _PassUser.
1059                     return $this;
1060             }
1061         }
1062     }
1063
1064     function getAuthDbh () {
1065         global $request; //, $DBParams, $DBAuthParams;
1066
1067         $dbh = $request->getDbh();
1068         // session restauration doesn't re-connect to the database automatically,
1069         // so dirty it here, to force a reconnect.
1070         if (isset($this->_auth_dbi)) {
1071             if (($dbh->getParam('dbtype') == 'SQL') and empty($this->_auth_dbi->connection))
1072                 unset($this->_auth_dbi);
1073             if (($dbh->getParam('dbtype') == 'ADODB') and empty($this->_auth_dbi->_connectionID))
1074                 unset($this->_auth_dbi);
1075         }
1076         if (empty($this->_auth_dbi)) {
1077             if ($dbh->getParam('dbtype') != 'SQL'
1078                 and $dbh->getParam('dbtype') != 'ADODB'
1079                 and $dbh->getParam('dbtype') != 'PDO')
1080                 return false;
1081             if (empty($GLOBALS['DBAuthParams']))
1082                 return false;
1083             if (!$dbh->getAuthParam('auth_dsn')) {
1084                 $dbh = $request->getDbh(); // use phpwiki database
1085             } elseif ($dbh->getAuthParam('auth_dsn') == $dbh->getParam('dsn')) {
1086                 $dbh = $request->getDbh(); // same phpwiki database
1087             } else { // use another external database handle. needs PHP >= 4.1
1088                 $local_params = array_merge($GLOBALS['DBParams'],$GLOBALS['DBAuthParams']);
1089                 $local_params['dsn'] = $local_params['auth_dsn'];
1090                 $dbh = WikiDB::open($local_params);
1091             }
1092             $this->_auth_dbi =& $dbh->_backend->_dbh;
1093         }
1094         return $this->_auth_dbi;
1095     }
1096
1097     function _normalize_stmt_var($var, $oldstyle = false) {
1098         static $valid_variables = array('userid','password','pref_blob','groupname');
1099         // old-style: "'$userid'"
1100         // new-style: '"\$userid"' or just "userid"
1101         $new = str_replace(array("'",'"','\$','$'),'',$var);
1102         if (!in_array($new, $valid_variables)) {
1103             trigger_error("Unknown DBAuthParam statement variable: ". $new, E_USER_ERROR);
1104             return false;
1105         }
1106         return !$oldstyle ? "'$".$new."'" : '\$'.$new;
1107     }
1108
1109     // TODO: use it again for the auth and member tables
1110     // sprintfstyle vs prepare style: %s or ?
1111     //   multiple vars should be executed via prepare(?,?)+execute,
1112     //   single vars with execute(sprintf(quote(var)))
1113     // help with position independency
1114     function prepare ($stmt, $variables, $oldstyle = false, $sprintfstyle = true) {
1115         global $request;
1116         $dbi = $request->getDbh();
1117         $this->getAuthDbh();
1118         // "'\$userid"' => %s
1119         // variables can be old-style: '"\$userid"' or new-style: "'$userid'" or just "userid"
1120         // old-style strings don't survive pear/Config/IniConfig treatment, that's why we changed it.
1121         $new = array();
1122         if (is_array($variables)) {
1123             //$sprintfstyle = false;
1124             for ($i=0; $i < count($variables); $i++) {
1125                 $var = $this->_normalize_stmt_var($variables[$i], $oldstyle);
1126                 if (!$var)
1127                     trigger_error(sprintf("DbAuthParams: Undefined or empty statement variable %s in %s",
1128                                           $variables[$i], $stmt), E_USER_WARNING);
1129                 $variables[$i] = $var;
1130                 if (!$var) $new[] = '';
1131                 else {
1132                     $s = "%" . ($i+1) . "s";
1133                     $new[] = $sprintfstyle ? $s : "?";
1134                 }
1135             }
1136         } else {
1137             $var = $this->_normalize_stmt_var($variables, $oldstyle);
1138             if (!$var)
1139                 trigger_error(sprintf("DbAuthParams: Undefined or empty statement variable %s in %s",
1140                                       $variables, $stmt), E_USER_WARNING);
1141             $variables = $var;
1142             if (!$var) $new = '';
1143             else $new = $sprintfstyle ? '%s' : "?";
1144         }
1145         $prefix = $dbi->getParam('prefix');
1146         // probably prefix table names if in same database
1147         if ($prefix and isset($this->_auth_dbi) and isset($dbi->_backend->_dbh) and
1148             ($dbi->getAuthParam('auth_dsn') and $dbi->getParam('dsn') == $dbi->getAuthParam('auth_dsn')))
1149         {
1150             if (!stristr($stmt, $prefix)) {
1151                 $oldstmt = $stmt;
1152                 $stmt = str_replace(array(" user "," pref "," member "),
1153                                     array(" ".$prefix."user ",
1154                                           " ".$prefix."pref ",
1155                                           " ".$prefix."member "), $stmt);
1156                 //Do it automatically for the lazy admin? Esp. on sf.net it's nice to have
1157                 trigger_error("Need to prefix the DBAUTH tablename in config/config.ini:\n  $oldstmt \n=> $stmt",
1158                               E_USER_WARNING);
1159             }
1160         }
1161         // Preparate the SELECT statement, for ADODB and PearDB (MDB not).
1162         // Simple sprintf-style.
1163         $new_stmt = str_replace($variables, $new, $stmt);
1164         if ($new_stmt == $stmt) {
1165             if ($oldstyle) {
1166                 trigger_error(sprintf("DbAuthParams: Invalid statement in %s",
1167                                   $stmt), E_USER_WARNING);
1168             } else {
1169                 trigger_error(sprintf("DbAuthParams: Old statement quoting style in %s",
1170                                   $stmt), E_USER_WARNING);
1171                 $new_stmt = $this->prepare($stmt, $variables, 'oldstyle');
1172             }
1173         }
1174         return $new_stmt;
1175     }
1176
1177     function getPreferences() {
1178         if (!empty($this->_prefs->_method)) {
1179             if ($this->_prefs->_method == 'ADODB') {
1180                 // FIXME: strange why this should be needed...
1181                 include_once("lib/WikiUser/Db.php");
1182                 include_once("lib/WikiUser/AdoDb.php");
1183                 return _AdoDbPassUser::getPreferences();
1184             } elseif ($this->_prefs->_method == 'SQL') {
1185                 include_once("lib/WikiUser/Db.php");
1186                 include_once("lib/WikiUser/PearDb.php");
1187                 return _PearDbPassUser::getPreferences();
1188             } elseif ($this->_prefs->_method == 'PDO') {
1189                 include_once("lib/WikiUser/Db.php");
1190                 include_once("lib/WikiUser/PdoDb.php");
1191                 return _PdoDbPassUser::getPreferences();
1192             }
1193         }
1194
1195         // We don't necessarily have to read the cookie first. Since
1196         // the user has a password, the prefs stored in the homepage
1197         // cannot be arbitrarily altered by other Bogo users.
1198         _AnonUser::getPreferences();
1199         // User may have deleted cookie, retrieve from his
1200         // PersonalPage if there is one.
1201         if (!empty($this->_HomePagehandle)) {
1202             if ($restored_from_page = $this->_prefs->retrieve
1203                 ($this->_HomePagehandle->get('pref'))) {
1204                 $updated = $this->_prefs->updatePrefs($restored_from_page,'init');
1205                 //$this->_prefs = new UserPreferences($restored_from_page);
1206                 return $this->_prefs;
1207             }
1208         }
1209         return $this->_prefs;
1210     }
1211
1212     function setPreferences($prefs, $id_only=false) {
1213         if (!empty($this->_prefs->_method)) {
1214             if ($this->_prefs->_method == 'ADODB') {
1215                 // FIXME: strange why this should be needed...
1216                 include_once("lib/WikiUser/Db.php");
1217                 include_once("lib/WikiUser/AdoDb.php");
1218                 return _AdoDbPassUser::setPreferences($prefs, $id_only);
1219             }
1220             elseif ($this->_prefs->_method == 'SQL') {
1221                 include_once("lib/WikiUser/Db.php");
1222                 include_once("lib/WikiUser/PearDb.php");
1223                 return _PearDbPassUser::setPreferences($prefs, $id_only);
1224             }
1225             elseif ($this->_prefs->_method == 'PDO') {
1226                 include_once("lib/WikiUser/Db.php");
1227                 include_once("lib/WikiUser/PdoDb.php");
1228                 return _PdoDbPassUser::setPreferences($prefs, $id_only);
1229             }
1230         }
1231         if ($updated = _AnonUser::setPreferences($prefs, $id_only)) {
1232             // Encode only the _prefs array of the UserPreference object
1233         // If no DB method exists to store the prefs we must store it in the page, not in the cookies.
1234             if (empty($this->_HomePagehandle)) {
1235                 $this->_HomePagehandle = $GLOBALS['request']->getPage($this->_userid);
1236         }
1237             if (! $this->_HomePagehandle->exists() ) {
1238                 $this->createHomePage();
1239             }
1240         if (!empty($this->_HomePagehandle) and !$id_only) {
1241                 $this->_HomePagehandle->set('pref', $this->_prefs->store());
1242             }
1243         }
1244         return $updated;
1245     }
1246
1247     function mayChangePass() {
1248         return true;
1249     }
1250
1251     //The default method is getting the password from prefs.
1252     // child methods obtain $stored_password from external auth.
1253     function userExists() {
1254         //if ($this->_HomePagehandle) return true;
1255         if (strtolower(get_class($this)) == "_passuser") {
1256             $class = $this->nextClass();
1257             $user = new $class($this->_userid, $this->_prefs);
1258         } else {
1259             $user = $this;
1260         }
1261         /* new user => false does not return false, but the _userid is empty then */
1262         while ($user and $user->_userid) {
1263             if (!check_php_version(5))
1264                 eval("\$this = \$user;");
1265             $user = UpgradeUser($this, $user);
1266             if ($user->userExists()) {
1267                 $user = UpgradeUser($this, $user);
1268                 return true;
1269             }
1270             // prevent endless loop. does this work on all PHP's?
1271             // it just has to set the classname, what it correctly does.
1272             $class = $user->nextClass();
1273             if ($class == "_ForbiddenPassUser")
1274                 return false;
1275         }
1276         return false;
1277     }
1278
1279     //The default method is getting the password from prefs.
1280     // child methods obtain $stored_password from external auth.
1281     function checkPass($submitted_password) {
1282         $stored_password = $this->_prefs->get('passwd');
1283         if ($this->_checkPass($submitted_password, $stored_password)) {
1284             $this->_level = WIKIAUTH_USER;
1285             return $this->_level;
1286         } else {
1287             if ((USER_AUTH_POLICY === 'strict') and $this->userExists()) {
1288                 $this->_level = WIKIAUTH_FORBIDDEN;
1289                 return $this->_level;
1290             }
1291             return $this->_tryNextPass($submitted_password);
1292         }
1293     }
1294
1295
1296     function _checkPassLength($submitted_password) {
1297         if (strlen($submitted_password) < PASSWORD_LENGTH_MINIMUM) {
1298             trigger_error(_("The length of the password is shorter than the system policy allows."));
1299             return false;
1300         }
1301         return true;
1302     }
1303
1304     /**
1305      * The basic password checker for all PassUser objects.
1306      * Uses global ENCRYPTED_PASSWD and PASSWORD_LENGTH_MINIMUM.
1307      * Empty passwords are always false!
1308      * PASSWORD_LENGTH_MINIMUM is enforced here and in the preference set method.
1309      * @see UserPreferences::set
1310      *
1311      * DBPassUser password's have their own crypt definition.
1312      * That's why DBPassUser::checkPass() doesn't call this method, if
1313      * the db password method is 'plain', which means that the DB SQL
1314      * statement just returns 1 or 0. To use CRYPT() or PASSWORD() and
1315      * don't store plain passwords in the DB.
1316      *
1317      * TODO: remove crypt() function check from config.php:396 ??
1318      */
1319     function _checkPass($submitted_password, $stored_password) {
1320         if (!empty($submitted_password)) {
1321             // This works only on plaintext passwords.
1322             if (!ENCRYPTED_PASSWD and (strlen($stored_password) < PASSWORD_LENGTH_MINIMUM)) {
1323                 // With the EditMetaData plugin
1324                 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."));
1325                 return false;
1326             }
1327             if (!$this->_checkPassLength($submitted_password)) {
1328                 return false;
1329             }
1330             if (ENCRYPTED_PASSWD) {
1331                 // Verify against encrypted password.
1332                 if (function_exists('crypt')) {
1333                     if (crypt($submitted_password, $stored_password) == $stored_password )
1334                         return true; // matches encrypted password
1335                     else
1336                         return false;
1337                 }
1338                 else {
1339                     trigger_error(_("The crypt function is not available in this version of PHP.") . " "
1340                                   . _("Please set ENCRYPTED_PASSWD to false in config/config.ini and probably change ADMIN_PASSWD."),
1341                                   E_USER_WARNING);
1342                     return false;
1343                 }
1344             }
1345             else {
1346                 // Verify against cleartext password.
1347                 if ($submitted_password == $stored_password)
1348                     return true;
1349                 else {
1350                     // Check whether we forgot to enable ENCRYPTED_PASSWD
1351                     if (function_exists('crypt')) {
1352                         if (crypt($submitted_password, $stored_password) == $stored_password) {
1353                             trigger_error(_("Please set ENCRYPTED_PASSWD to true in config/config.ini."),
1354                                           E_USER_WARNING);
1355                             return true;
1356                         }
1357                     }
1358                 }
1359             }
1360         }
1361         return false;
1362     }
1363
1364     /** The default method is storing the password in prefs.
1365      *  Child methods (DB, File) may store in external auth also, but this
1366      *  must be explicitly enabled.
1367      *  This may be called by plugin/UserPreferences or by ->SetPreferences()
1368      */
1369     function changePass($submitted_password) {
1370         $stored_password = $this->_prefs->get('passwd');
1371         // check if authenticated
1372         if (!$this->isAuthenticated()) return false;
1373         if (ENCRYPTED_PASSWD) {
1374             $submitted_password = crypt($submitted_password);
1375         }
1376         // check other restrictions, with side-effects only.
1377         $result = $this->_checkPass($submitted_password, $stored_password);
1378         if ($stored_password != $submitted_password) {
1379             $this->_prefs->set('passwd', $submitted_password);
1380             //update the storage (session, homepage, ...)
1381             $this->SetPreferences($this->_prefs);
1382             return true;
1383         }
1384         //Todo: return an error msg to the caller what failed?
1385         // same password or no privilege
1386         return ENCRYPTED_PASSWD ? true : false;
1387     }
1388
1389     function _tryNextPass($submitted_password) {
1390         if (DEBUG & _DEBUG_LOGIN) {
1391             $class = strtolower(get_class($this));
1392             if (substr($class,-10) == "dbpassuser") $class = "_dbpassuser";
1393             $GLOBALS['USER_AUTH_ERROR'][$class] = 'wrongpass';
1394         }
1395         if (USER_AUTH_POLICY === 'strict') {
1396             $class = $this->nextClass();
1397             if ($user = new $class($this->_userid,$this->_prefs)) {
1398                 if ($user->userExists()) {
1399                     return $user->checkPass($submitted_password);
1400                 }
1401             }
1402         }
1403         if (USER_AUTH_POLICY === 'stacked' or USER_AUTH_POLICY === 'old') {
1404             $class = $this->nextClass();
1405             if ($user = new $class($this->_userid,$this->_prefs))
1406                 return $user->checkPass($submitted_password);
1407         }
1408         return $this->_level;
1409     }
1410
1411     function _tryNextUser() {
1412         if (DEBUG & _DEBUG_LOGIN) {
1413             $class = strtolower(get_class($this));
1414             if (substr($class,-10) == "dbpassuser") $class = "_dbpassuser";
1415             $GLOBALS['USER_AUTH_ERROR'][$class] = 'nosuchuser';
1416         }
1417         if (USER_AUTH_POLICY === 'strict'
1418         or USER_AUTH_POLICY === 'stacked') {
1419             $class = $this->nextClass();
1420             while ($user = new $class($this->_userid, $this->_prefs)) {
1421                 if (!check_php_version(5))
1422                     eval("\$this = \$user;");
1423             $user = UpgradeUser($this, $user);
1424                 if ($user->userExists()) {
1425                     $user = UpgradeUser($this, $user);
1426                     return true;
1427                 }
1428                 if ($class == "_ForbiddenPassUser") return false;
1429                 $class = $this->nextClass();
1430             }
1431         }
1432         return false;
1433     }
1434
1435 }
1436
1437 /**
1438  * Insert more auth classes here...
1439  * For example a customized db class for another db connection
1440  * or a socket-based auth server.
1441  *
1442  */
1443
1444
1445 /**
1446  * For security, this class should not be extended. Instead, extend
1447  * from _PassUser (think of this as unix "root").
1448  *
1449  * FIXME: This should be a singleton class. Only ADMIN_USER may be of class AdminUser!
1450  * Other members of the Administrators group must raise their level otherwise somehow.
1451  * Currently every member is a AdminUser, which will not work for the various
1452  * storage methods.
1453  */
1454 class _AdminUser
1455 extends _PassUser
1456 {
1457     function mayChangePass() {
1458         return false;
1459     }
1460     function checkPass($submitted_password) {
1461         if ($this->_userid == ADMIN_USER)
1462             $stored_password = ADMIN_PASSWD;
1463         else {
1464             // Should not happen! Only ADMIN_USER should use this class.
1465             // return $this->_tryNextPass($submitted_password); // ???
1466             // TODO: safety check if really member of the ADMIN group?
1467             $stored_password = $this->_pref->get('passwd');
1468         }
1469         if ($this->_checkPass($submitted_password, $stored_password)) {
1470             $this->_level = WIKIAUTH_ADMIN;
1471             if (!empty($GLOBALS['HTTP_SERVER_VARS']['PHP_AUTH_USER']) and class_exists("_HttpAuthPassUser")) {
1472                 // fake http auth
1473                 _HttpAuthPassUser::_fake_auth($this->_userid, $submitted_password);
1474             }
1475             return $this->_level;
1476         } else {
1477             return $this->_tryNextPass($submitted_password);
1478             //$this->_level = WIKIAUTH_ANON;
1479             //return $this->_level;
1480         }
1481     }
1482
1483     function storePass($submitted_password) {
1484         if ($this->_userid == ADMIN_USER)
1485             return false;
1486         else {
1487             // should not happen! only ADMIN_USER should use this class.
1488             return parent::storePass($submitted_password);
1489         }
1490     }
1491 }
1492
1493 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1494 /**
1495  * Various data classes for the preference types,
1496  * to support get, set, sanify (range checking, ...)
1497  * update() will do the neccessary side-effects if a
1498  * setting gets changed (theme, language, ...)
1499 */
1500
1501 class _UserPreference
1502 {
1503     var $default_value;
1504
1505     function _UserPreference ($default_value) {
1506         $this->default_value = $default_value;
1507     }
1508
1509     function sanify ($value) {
1510         return (string)$value;
1511     }
1512
1513     function get ($name) {
1514         if (isset($this->{$name}))
1515         return $this->{$name};
1516         else
1517             return $this->default_value;
1518     }
1519
1520     function getraw ($name) {
1521         if (!empty($this->{$name}))
1522         return $this->{$name};
1523     }
1524
1525     // stores the value as $this->$name, and not as $this->value (clever?)
1526     function set ($name, $value) {
1527         $return = 0;
1528         $value = $this->sanify($value);
1529     if ($this->get($name) != $value) {
1530         $this->update($value);
1531         $return = 1;
1532     }
1533     if ($value != $this->default_value) {
1534         $this->{$name} = $value;
1535         } else {
1536             unset($this->{$name});
1537         }
1538         return $return;
1539     }
1540
1541     // default: no side-effects
1542     function update ($value) {
1543         ;
1544     }
1545 }
1546
1547 class _UserPreference_numeric
1548 extends _UserPreference
1549 {
1550     function _UserPreference_numeric ($default, $minval = false,
1551                                       $maxval = false) {
1552         $this->_UserPreference((double)$default);
1553         $this->_minval = (double)$minval;
1554         $this->_maxval = (double)$maxval;
1555     }
1556
1557     function sanify ($value) {
1558         $value = (double)$value;
1559         if ($this->_minval !== false && $value < $this->_minval)
1560             $value = $this->_minval;
1561         if ($this->_maxval !== false && $value > $this->_maxval)
1562             $value = $this->_maxval;
1563         return $value;
1564     }
1565 }
1566
1567 class _UserPreference_int
1568 extends _UserPreference_numeric
1569 {
1570     function _UserPreference_int ($default, $minval = false, $maxval = false) {
1571         $this->_UserPreference_numeric((int)$default, (int)$minval, (int)$maxval);
1572     }
1573
1574     function sanify ($value) {
1575         return (int)parent::sanify((int)$value);
1576     }
1577 }
1578
1579 class _UserPreference_bool
1580 extends _UserPreference
1581 {
1582     function _UserPreference_bool ($default = false) {
1583         $this->_UserPreference((bool)$default);
1584     }
1585
1586     function sanify ($value) {
1587         if (is_array($value)) {
1588             /* This allows for constructs like:
1589              *
1590              *   <input type="hidden" name="pref[boolPref][]" value="0" />
1591              *   <input type="checkbox" name="pref[boolPref][]" value="1" />
1592              *
1593              * (If the checkbox is not checked, only the hidden input
1594              * gets sent. If the checkbox is sent, both inputs get
1595              * sent.)
1596              */
1597             foreach ($value as $val) {
1598                 if ($val)
1599                     return true;
1600             }
1601             return false;
1602         }
1603         return (bool) $value;
1604     }
1605 }
1606
1607 class _UserPreference_language
1608 extends _UserPreference
1609 {
1610     function _UserPreference_language ($default = DEFAULT_LANGUAGE) {
1611         $this->_UserPreference($default);
1612     }
1613
1614     // FIXME: check for valid locale
1615     function sanify ($value) {
1616         // Revert to DEFAULT_LANGUAGE if user does not specify
1617         // language in UserPreferences or chooses <system language>.
1618         if ($value == '' or empty($value))
1619             $value = DEFAULT_LANGUAGE;
1620
1621         return (string) $value;
1622     }
1623
1624     function update ($newvalue) {
1625         if (! $this->_init ) {
1626             // invalidate etag to force fresh output
1627             $GLOBALS['request']->setValidators(array('%mtime' => false));
1628             update_locale($newvalue ? $newvalue : $GLOBALS['LANG']);
1629         }
1630     }
1631 }
1632
1633 class _UserPreference_theme
1634 extends _UserPreference
1635 {
1636     function _UserPreference_theme ($default = THEME) {
1637         $this->_UserPreference($default);
1638     }
1639
1640     function sanify ($value) {
1641         if (!empty($value) and FindFile($this->_themefile($value)))
1642             return $value;
1643         return $this->default_value;
1644     }
1645
1646     function update ($newvalue) {
1647         global $WikiTheme;
1648         // invalidate etag to force fresh output
1649         if (! $this->_init )
1650             $GLOBALS['request']->setValidators(array('%mtime' => false));
1651         if ($newvalue)
1652             include_once($this->_themefile($newvalue));
1653         if (empty($WikiTheme))
1654             include_once($this->_themefile(THEME));
1655     }
1656
1657     function _themefile ($theme) {
1658         return "themes/$theme/themeinfo.php";
1659     }
1660 }
1661
1662 class _UserPreference_notify
1663 extends _UserPreference
1664 {
1665     function sanify ($value) {
1666         if (!empty($value))
1667             return $value;
1668         else
1669             return $this->default_value;
1670     }
1671
1672     /** update to global user prefs: side-effect on set notify changes
1673      * use a global_data notify hash:
1674      * notify = array('pagematch' => array(userid => ('email' => mail,
1675      *                                                'verified' => 0|1),
1676      *                                     ...),
1677      *                ...);
1678      */
1679     function update ($value) {
1680         if (!empty($this->_init)) return;
1681         $dbh = $GLOBALS['request']->getDbh();
1682         $notify = $dbh->get('notify');
1683         if (empty($notify))
1684             $data = array();
1685         else
1686             $data =& $notify;
1687         // expand to existing pages only or store matches?
1688         // for now we store (glob-style) matches which is easier for the user
1689         $pages = $this->_page_split($value);
1690         // Limitation: only current user.
1691         $user = $GLOBALS['request']->getUser();
1692         if (!$user or !method_exists($user,'UserName')) return;
1693         // This fails with php5 and a WIKI_ID cookie:
1694         $userid = $user->UserName();
1695         $email  = $user->_prefs->get('email');
1696         $verified = $user->_prefs->_prefs['email']->getraw('emailVerified');
1697         // check existing notify hash and possibly delete pages for email
1698         if (!empty($data)) {
1699             foreach ($data as $page => $users) {
1700                 if (isset($data[$page][$userid]) and !in_array($page, $pages)) {
1701                     unset($data[$page][$userid]);
1702                 }
1703                 if (count($data[$page]) == 0)
1704                     unset($data[$page]);
1705             }
1706         }
1707         // add the new pages
1708         if (!empty($pages)) {
1709             foreach ($pages as $page) {
1710                 if (!isset($data[$page]))
1711                     $data[$page] = array();
1712                 if (!isset($data[$page][$userid])) {
1713                     // should we really store the verification notice here or
1714                     // check it dynamically at every page->save?
1715                     if ($verified) {
1716                         $data[$page][$userid] = array('email' => $email,
1717                                                       'verified' => $verified);
1718                     } else {
1719                         $data[$page][$userid] = array('email' => $email);
1720                     }
1721                 }
1722             }
1723         }
1724         // store users changes
1725         $dbh->set('notify',$data);
1726     }
1727
1728     /** split the user-given comma or whitespace delimited pagenames
1729      *  to array
1730      */
1731     function _page_split($value) {
1732         return preg_split('/[\s,]+/',$value,-1,PREG_SPLIT_NO_EMPTY);
1733     }
1734 }
1735
1736 class _UserPreference_email
1737 extends _UserPreference
1738 {
1739     function get($name) {
1740         // get e-mail address from FusionForge
1741         if (FUSIONFORGE && session_loggedin()) {
1742             $user = session_get_user();
1743             return $user->getEmail();
1744         } else {
1745             parent::get($name);
1746         }
1747     }
1748
1749     function sanify($value) {
1750         // e-mail address is already checked by FusionForge
1751         if (FUSIONFORGE) return $value;
1752         // check for valid email address
1753         if ($this->get('email') == $value and $this->getraw('emailVerified'))
1754             return $value;
1755         // hack!
1756         if ($value == 1 or $value === true)
1757             return $value;
1758         list($ok,$msg) = ValidateMail($value,'noconnect');
1759         if ($ok) {
1760             return $value;
1761         } else {
1762             trigger_error("E-mail Validation Error: ".$msg, E_USER_WARNING);
1763             return $this->default_value;
1764         }
1765     }
1766
1767     /** Side-effect on email changes:
1768      * Send a verification mail or for now just a notification email.
1769      * For true verification (value = 2), we'd need a mailserver hook.
1770      */
1771     function update($value) {
1772         // e-mail address is already checked by FusionForge
1773         if (FUSIONFORGE) return $value;
1774         if (!empty($this->_init)) return;
1775         $verified = $this->getraw('emailVerified');
1776         // hack!
1777         if (($value == 1 or $value === true) and $verified)
1778             return;
1779         if (!empty($value) and !$verified) {
1780             list($ok,$msg) = ValidateMail($value);
1781             if ($ok and mail($value,"[".WIKI_NAME ."] "._("Email Verification"),
1782                      sprintf(_("Welcome to %s!\nYour email account is verified and\nwill be used to send page change notifications.\nSee %s"),
1783                              WIKI_NAME, WikiURL($GLOBALS['request']->getArg('pagename'),'',true)))) {
1784                 $this->set('emailVerified',1);
1785             } else {
1786                 trigger_error($msg, E_USER_WARNING);
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 ) = explode("@", $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]="Cannot 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 FUSIONFORGE define
1948         if (FUSIONFORGE) {
1949             $fusionforgeprefs = 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, $fusionforgeprefs);
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 (FUSIONFORGE) {
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 (FUSIONFORGE) {
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 ?>