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