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