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