]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/main.php
some minor php5 strictness fixes
[SourceForge/phpwiki.git] / lib / main.php
1 <?php //-*-php-*-
2 rcs_id('$Id: main.php,v 1.205 2005-01-29 20:41:47 rurban Exp $');
3 /*
4  Copyright 1999,2000,2001,2002,2004,2005 $ThePhpWikiProgrammingTeam
5
6  This file is part of PhpWiki.
7
8  PhpWiki is free software; you can redistribute it and/or modify
9  it under the terms of the GNU General Public License as published by
10  the Free Software Foundation; either version 2 of the License, or
11  (at your option) any later version.
12
13  PhpWiki is distributed in the hope that it will be useful,
14  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  GNU General Public License for more details.
17
18  You should have received a copy of the GNU General Public License
19  along with PhpWiki; if not, write to the Free Software
20  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 define ('USE_PREFS_IN_PAGE', true);
24
25 //include "lib/config.php";
26 require_once(dirname(__FILE__)."/stdlib.php");
27 require_once('lib/Request.php');
28 require_once('lib/WikiDB.php');
29 if (ENABLE_USER_NEW)
30     require_once("lib/WikiUserNew.php");
31 else
32     require_once("lib/WikiUser.php");
33 require_once("lib/WikiGroup.php");
34 if (ENABLE_PAGEPERM)
35     require_once("lib/PagePerm.php");
36
37 /**
38  * Check permission per page.
39  * Returns true or false.
40  */
41 function mayAccessPage ($access, $pagename) {
42     if (ENABLE_PAGEPERM)
43         return _requiredAuthorityForPagename($access, $pagename); // typically [10-20ms per page]
44     else
45         return true;
46 }
47
48 class WikiRequest extends Request {
49     // var $_dbi;
50
51     function WikiRequest () {
52         $this->_dbi = WikiDB::open($GLOBALS['DBParams']);
53          // first mysql request costs [958ms]! [670ms] is mysql_connect()
54         
55         if (in_array('File', $this->_dbi->getAuthParam('USER_AUTH_ORDER'))) {
56             // force our local copy, until the pear version is fixed.
57             include_once(dirname(__FILE__)."/pear/File_Passwd.php");
58         }
59         if (ENABLE_USER_NEW) {
60             // Preload all necessary userclasses. Otherwise session => __PHP_Incomplete_Class_Name
61             // There's no way to demandload it later. This way it's much slower but needs 
62             // less memory than loading all
63             if (ALLOW_BOGO_LOGIN)
64                 include_once("lib/WikiUser/BogoLogin.php");
65             foreach ($GLOBALS['USER_AUTH_ORDER'] as $method) {
66                 include_once("lib/WikiUser/$method.php");
67                 if ($method == 'Db')
68                     switch($GLOBALS['DBParams']['dbtype']) {
69                         case 'SQL' : include_once("lib/WikiUser/PearDb.php"); break;
70                         case 'ADODB': include_once("lib/WikiUser/AdoDb.php"); break;
71                     }
72             }
73             unset($method);
74         }
75         if (USE_DB_SESSION) {
76             include_once('lib/DbSession.php');
77             $dbi =& $this->_dbi;
78             $this->_dbsession = new DbSession($dbi, $dbi->getParam('prefix') . $dbi->getParam('db_session_table'));
79         }
80
81 // Fixme: Does pear reset the error mask to 1? We have to find the culprit
82 //$x = error_reporting();
83
84         $this->version = phpwiki_version();
85         $this->Request(); // [90ms]
86
87         // Normalize args...
88         $this->setArg('pagename', $this->_deducePagename());
89         $this->setArg('action', $this->_deduceAction());
90
91         if ((DEBUG & _DEBUG_SQL) or (time() % 50 == 0)) {
92             if ($this->_dbi->_backend->optimize())
93                 trigger_error(_("Optimizing database"), E_USER_NOTICE);
94         }
95
96         // Restore auth state. This doesn't check for proper authorization!
97         $userid = $this->_deduceUsername();     
98         if (ENABLE_USER_NEW) {
99             if (isset($this->_user) and 
100                 !empty($this->_user->_authhow) and 
101                 $this->_user->_authhow == 'session')
102             {
103                 // users might switch in a session between the two objects.
104                 // restore old auth level here or in updateAuthAndPrefs?
105                 //$user = $this->getSessionVar('wiki_user');
106                 // revive db handle, because these don't survive sessions
107                 if (isset($this->_user) and 
108                      ( ! isa($this->_user, WikiUserClassname())
109                        or (strtolower(get_class($this->_user)) == '_passuser')))
110                 {
111                     $this->_user = WikiUser($userid, $this->_user->_prefs);
112                 }
113                 // revive other db handle
114                 if (isset($this->_user->_prefs->_method)
115                     and ($this->_user->_prefs->_method == 'SQL' 
116                          or $this->_user->_prefs->_method == 'ADODB' 
117                          or $this->_user->_prefs->_method == 'HomePage')) {
118                     $this->_user->_HomePagehandle = $this->getPage($userid);
119                 }
120                 // need to update the lockfile filehandle
121                 if ( isa($this->_user,'_FilePassUser') 
122                      and $this->_user->_file->lockfile 
123                      and !$this->_user->_file->fplock )
124                 {
125                     //$level = $this->_user->_level;
126                     $this->_user = UpgradeUser($this->_user, 
127                                                new _FilePassUser($userid, 
128                                                                  $this->_user->_prefs, 
129                                                                  $this->_user->_file->filename));
130                     //$this->_user->_level = $level;
131                 }
132                 $this->_prefs = & $this->_user->_prefs;
133             } else {
134                 $user = WikiUser($userid);
135                 $this->_user = & $user;
136                 $this->_prefs = & $this->_user->_prefs;
137             }
138         } else {
139             $this->_user = new WikiUser($this, $userid);
140             $this->_prefs = $this->_user->getPreferences();
141         }
142     }
143
144     function initializeLang () {
145         $user_lang = $this->getPref('lang');
146         $_lang = @$this->_prefs->_prefs['lang'];
147         //check changed LANG and THEME inside a session. 
148         // (e.g. by using another baseurl)
149         if (isset($this->_user->_authhow) and 
150             $this->_user->_authhow == 'session' and 
151             !isset($_lang->lang) and 
152             $user_lang != $GLOBALS['LANG'])
153         {
154             $user_lang = $GLOBALS['LANG'];
155         }
156         if (isset($user_lang)) {
157             //trigger_error("DEBUG: initializeLang() ". $user_lang ." calling update_locale()...");
158             update_locale($user_lang);
159             FindLocalizedButtonFile(".",'missing_ok','reinit');
160         }
161     }
162
163     function initializeTheme () {
164         global $WikiTheme;
165
166         // Load theme
167         $user_theme = $this->getPref('theme');
168         $_theme = @$this->_prefs->_prefs['theme'];
169         //check changed LANG and THEME inside a session. 
170         // (e.g. by using another baseurl)
171         if (isset($this->_user->_authhow) and 
172             $this->_user->_authhow == 'session' and 
173             !isset($_theme->theme) and
174             defined('THEME') and 
175             $user_theme != THEME)
176         {
177             include_once("themes/" . THEME . "/themeinfo.php");
178         }
179         if (empty($WikiTheme) and isset($user_theme)) {
180             if (strcspn($user_theme,"./\x00]") != strlen($user_theme)) {
181                 trigger_error(sprintf("invalid theme '%s': Invalid characters detected", $user_theme),
182                               E_USER_WARNING);
183                 $user_theme = "default";
184             }
185             include_once("themes/$user_theme/themeinfo.php");
186         }
187         if (empty($WikiTheme) and defined('THEME'))
188             include_once("themes/" . THEME . "/themeinfo.php");
189         if (empty($WikiTheme))
190             include_once("themes/default/themeinfo.php");
191         assert(!empty($WikiTheme));
192     }
193
194     // This really maybe should be part of the constructor, but since it
195     // may involve HTML/template output, the global $request really needs
196     // to be initialized before we do this stuff.
197     // [50ms]: 36ms is wikidb_page::exists
198     function updateAuthAndPrefs () {
199
200         if (isset($this->_user) and (!isa($this->_user, WikiUserClassname()))) {
201             $this->_user = false;       
202         }
203         // Handle authentication request, if any.
204         if ($auth_args = $this->getArg('auth')) {
205             $this->setArg('auth', false);
206             $this->_handleAuthRequest($auth_args); // possible NORETURN
207         }
208         elseif ( ! $this->_user 
209                  or (isa($this->_user, WikiUserClassname()) 
210                      and ! $this->_user->isSignedIn())) {
211             // If not auth request, try to sign in as saved user.
212             if (($saved_user = $this->getPref('userid')) != false) {
213                 $this->_signIn($saved_user);
214             }
215         }
216         
217         $action = $this->getArg('action');
218
219         // Save preferences in session and cookie
220         if ((defined('WIKI_XMLRPC') and !WIKI_XMLRPC) or $action != 'xmlrpc') {
221             if (isset($this->_user)) {
222                 if (!isset($this->_user->_authhow) or $this->_user->_authhow != 'session') {
223                     $this->_user->setPreferences($this->_prefs, true);
224                 }
225             }
226             $this->setSessionVar('wiki_user', $this->_user);
227         }
228
229         // Ensure user has permissions for action
230         // HACK ALERT: We may not set the request arg to create, 
231         // since the pageeditor has an ugly logic for action == create.
232         if ($action == 'edit' or $action == 'create') {
233             $page = $this->getPage();
234             if (! $page->exists() )
235                 $action = 'create';
236             else
237                 $action = 'edit';
238         }
239         $require_level = $this->requiredAuthority($action);
240         if (! $this->_user->hasAuthority($require_level))
241             $this->_notAuthorized($require_level); // NORETURN
242     }
243
244     function & getUser () {
245         if (isset($this->_user))
246             return $this->_user;
247         else
248             return $GLOBALS['ForbiddenUser'];
249     }
250     
251     function & getGroup () {
252         if (isset($this->_user) and isset($this->_user->_group))
253             return $this->_user->_group;
254         else {
255             // Debug Strict: Only variable references should be returned by reference
256             $this->_user->_group = WikiGroup::getGroup();
257             return $this->_user->_group;
258         }
259     }
260
261     function & getPrefs () {
262         return $this->_prefs;
263     }
264
265     // Convenience function:
266     function getPref ($key) {
267         if (isset($this->_prefs)) {
268             return $this->_prefs->get($key);
269         }
270     }
271     function & getDbh () {
272         return $this->_dbi;
273     }
274
275     /**
276      * Get requested page from the page database.
277      * By default it will grab the page requested via the URL
278      *
279      * This is a convenience function.
280      * @param string $pagename Name of page to get.
281      * @return WikiDB_Page Object with methods to pull data from
282      * database for the page requested.
283      */
284     function getPage ($pagename = false) {
285         //if (!isset($this->_dbi)) $this->getDbh();
286         if (!$pagename) 
287             $pagename = $this->getArg('pagename');
288         return $this->_dbi->getPage($pagename);
289     }
290
291     /** Get URL for POST actions.
292      *
293      * Officially, we should just use SCRIPT_NAME (or some such),
294      * but that causes problems when we try to issue a redirect, e.g.
295      * after saving a page.
296      *
297      * Some browsers (at least NS4 and Mozilla 0.97 won't accept
298      * a redirect from a page to itself.)
299      *
300      * So, as a HACK, we include pagename and action as query args in
301      * the URL.  (These should be ignored when we receive the POST
302      * request.)
303      */
304     function getPostURL ($pagename=false) {
305         global $HTTP_GET_VARS;
306
307         if ($pagename === false)
308             $pagename = $this->getArg('pagename');
309         $action = $this->getArg('action');
310         if (!empty($HTTP_GET_VARS['start_debug'])) // zend ide support
311             return WikiURL($pagename, array('action' => $action, 'start_debug' => 1));
312         else
313             return WikiURL($pagename, array('action' => $action));
314     }
315     
316     function _handleAuthRequest ($auth_args) {
317         if (!is_array($auth_args))
318             return;
319
320         // Ignore password unless POST'ed.
321         if (!$this->isPost())
322             unset($auth_args['passwd']);
323
324         $olduser = $this->_user;
325         $user = $this->_user->AuthCheck($auth_args);
326         if (isa($user, WikiUserClassname())) {
327             // Successful login (or logout.)
328             $this->_setUser($user);
329         }
330         elseif (is_string($user)) {
331             // Login attempt failed.
332             $fail_message = $user;
333             $auth_args['pass_required'] = true;
334             // if clicked just on to the "sign in as:" button dont print invalid username.
335             if (!empty($auth_args['login']) and empty($auth_args['userid']))
336                 $fail_message = '';
337             // If no password was submitted, it's not really
338             // a failure --- just need to prompt for password...
339             if (!ALLOW_USER_PASSWORDS 
340                 and ALLOW_BOGO_LOGIN 
341                 and !isset($auth_args['passwd'])) 
342             {
343                 $fail_message = false;
344             }
345             $olduser->PrintLoginForm($this, $auth_args, $fail_message, 'newpage');
346             $this->finish();    //NORETURN
347         }
348         else {
349             // Login request cancelled.
350         }
351     }
352
353     /**
354      * Attempt to sign in (bogo-login).
355      *
356      * Fails silently.
357      *
358      * @param $userid string Userid to attempt to sign in as.
359      * @access private
360      */
361     function _signIn ($userid) {
362         if (ENABLE_USER_NEW) {
363             if (! $this->_user )
364                 $this->_user = new _BogoUser($userid);
365             // FIXME: is this always false? shouldn't we try passuser first?
366             if (! $this->_user ) 
367                 $this->_user = new _PassUser($userid);
368         }
369         $user = $this->_user->AuthCheck(array('userid' => $userid));
370         if (isa($user, WikiUserClassname())) {
371             $this->_setUser($user); // success!
372         }
373     }
374
375     // login or logout or restore state
376     function _setUser (&$user) {
377         $this->_user =& $user;
378         if (defined('MAIN_setUser')) return;
379         define('MAIN_setUser',true);
380         $this->setCookieVar('WIKI_ID', $user->getAuthenticatedId(),
381                             COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
382         if ($user->isSignedIn())
383             $user->_authhow = 'signin';
384
385         // Save userid to prefs..
386         if ( empty($this->_user->_prefs)) {
387             $this->_user->_prefs = $this->_user->getPreferences();
388             $this->_prefs =& $this->_user->_prefs;
389         }
390         $this->_user->_group = $this->getGroup();
391         $this->setSessionVar('wiki_user', $user);
392         $this->_prefs->set('userid',
393                            $user->isSignedIn() ? $user->getId() : '');
394         $this->initializeTheme();
395     }
396
397     /* Permission system */
398     function getLevelDescription($level) {
399         static $levels = false;
400         if (!$levels) 
401             $levels = array('x-1' => _("FORBIDDEN"),
402                             'x0'  => _("ANON"),
403                             'x1'  => _("BOGO"),
404                             'x2'  => _("USER"),
405                             'x10' => _("ADMIN"),
406                             'x100'=> _("UNOBTAINABLE"));
407         if (!empty($level))
408             $level = '0';
409         if (!empty($levels["x".$level]))
410             return $levels["x".$level];
411         else
412             return _("ANON");
413     }
414     
415     function _notAuthorized ($require_level) {
416         // Display the authority message in the Wiki's default
417         // language, in case it is not english.
418         //
419         // Note that normally a user will not see such an error once
420         // logged in, unless the admin has altered the default
421         // disallowed wikiactions. In that case we should probably
422         // check the user's language prefs too at this point; this
423         // would be a situation which is not really handled with the
424         // current code.
425         if (empty($GLOBALS['LANG']))
426             update_locale(DEFAULT_LANGUAGE);
427
428         // User does not have required authority.  Prompt for login.
429         $what = $this->getActionDescription($this->getArg('action'));
430         $pass_required = ($require_level >= WIKIAUTH_USER);
431         if ($require_level == WIKIAUTH_UNOBTAINABLE) {
432             global $DisabledActions;
433             if ($DisabledActions and in_array($action, $DisabledActions)) {
434                 $msg = fmt("%s is disallowed on this wiki.",
435                            $this->getDisallowedActionDescription($this->getArg('action')));
436                 $this->finish();
437                 return;
438             }
439             // Is the reason a missing ACL or just wrong user or password?
440             if (class_exists('PagePermission')) {
441                 $user =& $this->_user;
442                 $status = $user->isAuthenticated() ? _("authenticated") : _("not authenticated");
443                 $msg = fmt("%s %s %s is disallowed on this wiki for %s user '%s' (level: %s).",
444                            _("Missing PagePermission:"),
445                            action2access($this->getArg('action')),
446                            $this->getArg('pagename'),
447                            $status, $user->getId(), $this->getLevelDescription($user->_level));
448                 // TODO: add link to action=setacl
449                 $user->PrintLoginForm($this, compact('pass_required'), $msg);
450                 $this->finish();
451                 return;
452             } else {
453                 $msg = fmt("%s is disallowed on this wiki.",
454                            $this->getDisallowedActionDescription($this->getArg('action')));
455                 $this->_user->PrintLoginForm($this, compact('require_level','pass_required'), $msg);
456                 $this->finish();
457                 return;
458             }
459         }
460         elseif ($require_level == WIKIAUTH_BOGO)
461             $msg = fmt("You must sign in to %s.", $what);
462         elseif ($require_level == WIKIAUTH_USER)
463             $msg = fmt("You must log in to %s.", $what);
464         elseif ($require_level == WIKIAUTH_ANON)
465             $msg = fmt("Access for you is forbidden to %s.", $what);
466         else
467             $msg = fmt("You must be an administrator to %s.", $what);
468
469         $this->_user->PrintLoginForm($this, compact('require_level','pass_required'), $msg);
470         $this->finish();    // NORETURN
471     }
472
473     // Fixme: for PagePermissions we'll need other strings, 
474     // relevant to the requested page, not just for the action on the whole wiki.
475     function getActionDescription($action) {
476         static $actionDescriptions;
477         if (! $actionDescriptions) {
478             $actionDescriptions
479             = array('browse'     => _("view this page"),
480                     'diff'       => _("diff this page"),
481                     'dumphtml'   => _("dump html pages"),
482                     'dumpserial' => _("dump serial pages"),
483                     'edit'       => _("edit this page"),
484                     'revert'     => _("revert to a previous version of this page"),
485                     'create'     => _("create this page"),
486                     'loadfile'   => _("load files into this wiki"),
487                     'lock'       => _("lock this page"),
488                     'remove'     => _("remove this page"),
489                     'unlock'     => _("unlock this page"),
490                     'upload'     => _("upload a zip dump"),
491                     'verify'     => _("verify the current action"),
492                     'viewsource' => _("view the source of this page"),
493                     'xmlrpc'     => _("access this wiki via XML-RPC"),
494                     'soap'       => _("access this wiki via SOAP"),
495                     'zip'        => _("download a zip dump from this wiki"),
496                     'ziphtml'    => _("download an html zip dump from this wiki")
497                     );
498         }
499         if (in_array($action, array_keys($actionDescriptions)))
500             return $actionDescriptions[$action];
501         else
502             return $action;
503     }
504     
505     /**
506 TODO: check against these cases:
507         if ($DisabledActions and in_array($action, $DisabledActions))
508             return WIKIAUTH_UNOBTAINABLE;
509
510         if (ENABLE_PAGEPERM and class_exists("PagePermission")) {
511            return requiredAuthorityForPage($action);
512            
513 => Browsing pages is disallowed on this wiki for authenticated user 'rurban' (level: BOGO).
514     */
515     function getDisallowedActionDescription($action) {
516         static $disallowedActionDescriptions;
517         
518         if (! $disallowedActionDescriptions) {
519             $disallowedActionDescriptions
520             = array('browse'     => _("Browsing pages"),
521                     'diff'       => _("Diffing pages"),
522                     'dumphtml'   => _("Dumping html pages"),
523                     'dumpserial' => _("Dumping serial pages"),
524                     'edit'       => _("Editing pages"),
525                     'revert'     => _("Reverting to a previous version of pages"),
526                     'create'     => _("Creating pages"),
527                     'loadfile'   => _("Loading files"),
528                     'lock'       => _("Locking pages"),
529                     'remove'     => _("Removing pages"),
530                     'unlock'     => _("Unlocking pages"),
531                     'upload'     => _("Uploading zip dumps"),
532                     'verify'     => _("Verify the current action"),
533                     'viewsource' => _("Viewing the source of pages"),
534                     'xmlrpc'     => _("XML-RPC access"),
535                     'soap'       => _("SOAP access"),
536                     'zip'        => _("Downloading zip dumps"),
537                     'ziphtml'    => _("Downloading html zip dumps")
538                     );
539         }
540         if (in_array($action, array_keys($disallowedActionDescriptions)))
541             return $disallowedActionDescriptions[$action];
542         else
543             return $action;
544     }
545
546     function requiredAuthority ($action) {
547         $auth = $this->requiredAuthorityForAction($action);
548         if (!ALLOW_ANON_USER) return WIKIAUTH_USER;
549         
550         /*
551          * This is a hook for plugins to require authority
552          * for posting to them.
553          *
554          * IMPORTANT: this is not a secure check, so the plugin
555          * may not assume that any POSTs to it are authorized.
556          * All this does is cause PhpWiki to prompt for login
557          * if the user doesn't have the required authority.
558          */
559         if ($this->isPost()) {
560             $post_auth = $this->getArg('require_authority_for_post');
561             if ($post_auth !== false)
562                 $auth = max($auth, $post_auth);
563         }
564         return $auth;
565     }
566         
567     function requiredAuthorityForAction ($action) {
568         global $DisabledActions;
569         
570         if ($DisabledActions and in_array($action, $DisabledActions))
571             return WIKIAUTH_UNOBTAINABLE;
572             
573         if (ENABLE_PAGEPERM and class_exists("PagePermission")) {
574            return requiredAuthorityForPage($action);
575         } else {
576           // FIXME: clean up. 
577           switch ($action) {
578             case 'browse':
579             case 'viewsource':
580             case 'diff':
581             case 'select':
582             case 'xmlrpc':
583             case 'search':
584             case 'pdf':
585                 return WIKIAUTH_ANON;
586
587             case 'zip':
588             case 'ziphtml':
589                 if (defined('ZIPDUMP_AUTH') && ZIPDUMP_AUTH)
590                     return WIKIAUTH_ADMIN;
591                 return WIKIAUTH_ANON;
592
593             case 'edit':
594             case 'revert':
595             case 'soap':
596                 if (defined('REQUIRE_SIGNIN_BEFORE_EDIT') && REQUIRE_SIGNIN_BEFORE_EDIT)
597                     return WIKIAUTH_BOGO;
598                 return WIKIAUTH_ANON;
599                 // return WIKIAUTH_BOGO;
600
601             case 'create':
602                 $page = $this->getPage();
603                 $current = $page->getCurrentRevision();
604                 if ($current->hasDefaultContents())
605                     return $this->requiredAuthorityForAction('edit');
606                 return $this->requiredAuthorityForAction('browse');
607
608             case 'upload':
609             case 'dumpserial':
610             case 'dumphtml':
611             case 'loadfile':
612             case 'remove':
613             case 'lock':
614             case 'unlock':
615             case 'upgrade':
616             case 'chown':
617             case 'setacl':
618             case 'rename':
619                 return WIKIAUTH_ADMIN;
620
621             /* authcheck occurs only in the plugin.
622                required actionpage RateIt */
623             /*
624             case 'rate':
625             case 'delete_rating':
626                 // Perhaps this should be WIKIAUTH_USER
627                 return WIKIAUTH_BOGO;
628             */
629
630             default:
631                 global $WikiNameRegexp;
632                 if (preg_match("/$WikiNameRegexp\Z/A", $action))
633                     return WIKIAUTH_ANON; // ActionPage.
634                 else
635                     return WIKIAUTH_ADMIN;
636           }
637         }
638     }
639     /* End of Permission system */
640
641     function possiblyDeflowerVirginWiki () {
642         if ($this->getArg('action') != 'browse')
643             return;
644         if ($this->getArg('pagename') != HOME_PAGE)
645             return;
646
647         $page = $this->getPage();
648         $current = $page->getCurrentRevision();
649         if ($current->getVersion() > 0)
650             return;             // Homepage exists.
651
652         include('lib/loadsave.php');
653         SetupWiki($this);
654         $this->finish();        // NORETURN
655     }
656     
657     // [574ms] mainly template:printexpansion: 393ms and template::expandsubtemplate [100+70+60ms]
658     function handleAction () {
659         $action = $this->getArg('action');
660         if ($this->isPost() and !$this->_user->isAdmin() and $action != 'browse') {
661             $page = $this->getPage();
662             if ( $page->get('moderation') ) {
663                 require_once("lib/WikiPlugin.php");
664                 $loader = new WikiPluginLoader();
665                 $plugin = $loader->getPlugin("ModeratedPage");
666                 if ($plugin->handler($this, $page)) {
667                     $CONTENT = HTML::div(array('class' => 'wiki-edithelp'),
668                                                  fmt("%s: action forwarded to a moderator.", 
669                                                      $action), 
670                                          HTML::br(),
671                                          // better msg: "This action requires moderator approval. Please be patient."
672                                          _("You must wait for moderator approval."));
673                     if (!empty($plugin->_tokens['CONTENT']))
674                         $plugin->_tokens['CONTENT']->pushContent
675                             (
676                              HTML::br(),
677                              _("You must wait for moderator approval."));
678                     else
679                         $plugin->_tokens['CONTENT'] = $CONTENT;
680                     require_once("lib/Template.php");
681                     $title = WikiLink($page->getName());
682                     $title->pushContent(' : ', WikiLink(_("ModeratedPage")));
683                     GeneratePage(Template('browse', $plugin->_tokens), 
684                                  $title,
685                                  $page->getCurrentRevision());
686                     $this->finish();
687                 }
688             }
689         }
690         $method = "action_$action";
691         if (method_exists($this, $method)) {
692             $this->{$method}();
693         }
694         elseif ($page = $this->findActionPage($action)) {
695             $this->actionpage($page);
696         }
697         else {
698             $this->finish(fmt("%s: Bad action", $action));
699         }
700     }
701     
702     function finish ($errormsg = false) {
703         static $in_exit = 0;
704
705         if ($in_exit)
706             exit();        // just in case CloseDataBase calls us
707         $in_exit = true;
708
709         global $ErrorManager;
710         $ErrorManager->flushPostponedErrors();
711
712         if (!empty($errormsg)) {
713             PrintXML(HTML::br(),
714                      HTML::hr(),
715                      HTML::h2(_("Fatal PhpWiki Error")),
716                      $errormsg);
717             // HACK:
718             echo "\n</body></html>";
719         }
720         if (is_object($this->_user)) {
721             $this->_user->page   = $this->getArg('pagename');
722             $this->_user->action = $this->getArg('action');
723             unset($this->_user->_HomePagehandle);
724             unset($this->_user->_auth_dbi);
725         }
726         Request::finish();
727         exit;
728     }
729
730     /**
731      * Generally pagename is rawurlencoded for older browsers or mozilla.
732      * Typing a pagename into the IE bar will utf-8 encode it, so we have to 
733      * fix that with fixTitleEncoding().
734      * If USE_PATH_INFO = true, the pagename is stripped from the "/DATA_PATH/PageName&arg=value" line.
735      * If false, we support either "/index.php?pagename=PageName&arg=value",
736      * or the first arg (1.2.x style): "/index.php?PageName&arg=value"
737      */
738     function _deducePagename () {
739         if (trim(rawurldecode($this->getArg('pagename'))))
740             return fixTitleEncoding(rawurldecode($this->getArg('pagename')));
741
742         if (USE_PATH_INFO) {
743             $pathinfo = $this->get('PATH_INFO');
744             if (empty($pathinfo)) { // fix for CGI
745                 $path = $this->get('REQUEST_URI');
746                 $script = $this->get('SCRIPT_NAME');
747                 $pathinfo = substr($path,strlen($script));
748                 $pathinfo = preg_replace('/\?.+$/','',$pathinfo);
749             }
750             $tail = substr($pathinfo, strlen(PATH_INFO_PREFIX));
751
752             if (trim($tail) != '' and $pathinfo == PATH_INFO_PREFIX . $tail) {
753                 return fixTitleEncoding($tail);
754             }
755         }
756         elseif ($this->isPost()) {
757             /*
758              * In general, for security reasons, HTTP_GET_VARS should be ignored
759              * on POST requests, but we make an exception here (only for pagename).
760              *
761              * The justification for this hack is the following
762              * asymmetry: When POSTing with USE_PATH_INFO set, the
763              * pagename can (and should) be communicated through the
764              * request URL via PATH_INFO.  When POSTing with
765              * USE_PATH_INFO off, this cannot be done --- the only way
766              * to communicate the pagename through the URL is via
767              * QUERY_ARGS (HTTP_GET_VARS).
768              */
769             global $HTTP_GET_VARS;
770             if (isset($HTTP_GET_VARS['pagename']) and trim($HTTP_GET_VARS['pagename'])) { 
771                 return fixTitleEncoding(rawurldecode($HTTP_GET_VARS['pagename']));
772             }
773         }
774
775         /*
776          * Support for PhpWiki 1.2 style requests.
777          * Strip off "&" args (?PageName&action=...&start_debug,...)
778          */
779         $query_string = $this->get('QUERY_STRING');
780         if (trim(rawurldecode($query_string)) and preg_match('/^([^&=]+)(&.+)?$/', $query_string, $m)) {
781             return fixTitleEncoding(rawurldecode($m[1]));
782         }
783
784         return fixTitleEncoding(HOME_PAGE);
785     }
786
787     function _deduceAction () {
788         if (!($action = $this->getArg('action'))) {
789             // Detect XML-RPC requests. TODO: SOAP?
790             if ($this->isPost()
791                 && $this->get('CONTENT_TYPE') == 'text/xml'
792                 && strstr($GLOBALS['HTTP_RAW_POST_DATA'], '<methodCall>')
793                )
794             {
795                 return 'xmlrpc';
796             }
797             return 'browse';    // Default if no action specified.
798         }
799
800         if (method_exists($this, "action_$action"))
801             return $action;
802
803         // Allow for, e.g. action=LikePages
804         if ($this->isActionPage($action))
805             return $action;
806
807         // Handle untranslated actionpages in non-english
808         // (people playing with switching languages)
809         if (0 and $GLOBALS['LANG'] != 'en') {
810             require_once("lib/plugin/_WikiTranslation.php");
811             $trans = new WikiPlugin__WikiTranslation();
812             $en_action = $trans->translate($action,'en',$GLOBALS['LANG']);
813             if ($this->isActionPage($en_action))
814                 return $en_action;
815         }
816
817         trigger_error("$action: Unknown action", E_USER_NOTICE);
818         return 'browse';
819     }
820
821     function _deduceUsername() {
822         global $HTTP_SERVER_VARS, $HTTP_ENV_VARS;
823
824         if (!empty($this->args['auth']) and !empty($this->args['auth']['userid']))
825             return $this->args['auth']['userid'];
826
827         if (!empty($HTTP_SERVER_VARS['PHP_AUTH_USER']))
828             return $HTTP_SERVER_VARS['PHP_AUTH_USER'];
829         if (!empty($HTTP_ENV_VARS['REMOTE_USER']))
830             return $HTTP_ENV_VARS['REMOTE_USER'];
831             
832         if ($user = $this->getSessionVar('wiki_user')) {
833             // switched auth between sessions. 
834             // Note: There's no way to demandload a missing class-definition afterwards! (Stupid php)
835             if (isa($user, WikiUserClassname())) {
836                 $this->_user = $user;
837                 $this->_user->_authhow = 'session';
838                 return ENABLE_USER_NEW ? $user->UserName() : $this->_user;
839             }
840         }
841         if ($userid = $this->getCookieVar('WIKI_ID')) {
842             if (!empty($userid) and substr($userid,0,2) != 's:') {
843                 $this->_user->authhow = 'cookie';
844                 return $userid;
845             }
846         }
847
848         if ($this->getArg('action') == 'xmlrpc') { // how about SOAP?
849             // wiki.putPage has special otional userid/passwd arguments. check that later.
850             $userid = '';
851             if (isset($HTTP_SERVER_VARS['REMOTE_USER']))
852                 $userid = $HTTP_SERVER_VARS['REMOTE_USER'];
853             elseif (isset($HTTP_SERVER_VARS['REMOTE_ADDR']))
854                 $userid = $HTTP_SERVER_VARS['REMOTE_ADDR'];
855             elseif (isset($HTTP_ENV_VARS['REMOTE_ADDR']))
856                 $userid = $HTTP_ENV_VARS['REMOTE_ADDR'];
857             elseif (isset($GLOBALS['REMOTE_ADDR']))
858                 $userid = $GLOBALS['REMOTE_ADDR'];
859             return $userid;
860         }
861
862         return false;
863     }
864     
865     function _isActionPage ($pagename) {
866         $dbi = $this->getDbh();
867         $page = $dbi->getPage($pagename);
868         if (!$page) return false;
869         $rev = $page->getCurrentRevision();
870         // FIXME: more restrictive check for sane plugin?
871         if (strstr($rev->getPackedContent(), '<?plugin'))
872             return true;
873         if (!$rev->hasDefaultContents())
874             trigger_error("$pagename: Does not appear to be an 'action page'", E_USER_NOTICE);
875         return false;
876     }
877
878     function findActionPage ($action) {
879         static $cache;
880
881         // check for translated version, as per users preferred language
882         // (or system default in case it is not en)
883         $translation = gettext($action);
884
885         if (isset($cache) and isset($cache[$translation]))
886             return $cache[$translation];
887
888         // check for cached translated version
889         if ($this->_isActionPage($translation))
890             return $cache[$action] = $translation;
891
892         // Allow for, e.g. action=LikePages
893         if (!isWikiWord($action))
894             return $cache[$action] = false;
895
896         // check for translated version (default language)
897         global $LANG;
898         if ($LANG != "en") {
899             require_once("lib/WikiPlugin.php");
900             require_once("lib/plugin/_WikiTranslation.php");
901             $trans = new WikiPlugin__WikiTranslation();
902             $trans->lang = $LANG;
903             $default = $trans->translate_to_en($action, $LANG);
904             if ($this->_isActionPage($default))
905                 return $cache[$action] = $default;
906         } else {
907             $default = $translation;
908         }
909         
910         // check for english version
911         if ($action != $translation and $action != $default) {
912             if ($this->_isActionPage($action))
913                 return $cache[$action] = $action;
914         }
915
916         trigger_error("$action: Cannot find action page", E_USER_NOTICE);
917         return $cache[$action] = false;
918     }
919     
920     function isActionPage ($pagename) {
921         return $this->findActionPage($pagename);
922     }
923
924     function action_browse () {
925         $this->buffer_output();
926         include_once("lib/display.php");
927         displayPage($this);
928     }
929
930     function action_verify () {
931         $this->action_browse();
932     }
933
934     function actionpage ($action) {
935         $this->buffer_output();
936         include_once("lib/display.php");
937         actionPage($this, $action);
938     }
939
940     function adminActionSubpage ($subpage) {
941         $page = _("PhpWikiAdministration")."/".$subpage;
942         $action = $this->findActionPage($page);
943         if ($action) {
944             $this->setArg('s',$this->getArg('pagename'));
945             $this->setArg('verify',1);
946             $this->setArg('action',$action);
947             $this->actionpage($action);
948         } else {
949             trigger_error($page.": Cannot find action page", E_USER_WARNING);
950         }
951     }
952
953     function action_chown () {
954         $this->adminActionSubpage(_("Chown"));
955     }
956
957     function action_setacl () {
958         $this->adminActionSubpage(_("SetAcl"));
959     }
960
961     function action_rename () {
962         $this->adminActionSubpage(_("Rename"));
963     }
964
965     function action_dump () {
966         $action = $this->findActionPage(_("PageDump"));
967         if ($action) {
968             $this->actionpage($action);
969         } else {
970             // redirect to action=upgrade if admin?
971             trigger_error(_("PageDump").": Cannot find action page", E_USER_WARNING);
972         }
973     }
974
975     function action_diff () {
976         $this->buffer_output();
977         include_once "lib/diff.php";
978         showDiff($this);
979     }
980
981     function action_search () {
982         // This is obsolete: reformulate URL and redirect.
983         // FIXME: this whole section should probably be deleted.
984         if ($this->getArg('searchtype') == 'full') {
985             $search_page = _("FullTextSearch");
986         }
987         else {
988             $search_page = _("TitleSearch");
989         }
990         $this->redirect(WikiURL($search_page,
991                                 array('s' => $this->getArg('searchterm')),
992                                 'absolute_url'));
993     }
994
995     function action_edit () {
996         $this->buffer_output();
997         include "lib/editpage.php";
998         $e = new PageEditor ($this);
999         $e->editPage();
1000     }
1001
1002     function action_create () {
1003         $this->action_edit();
1004     }
1005     
1006     function action_viewsource () {
1007         $this->buffer_output();
1008         include "lib/editpage.php";
1009         $e = new PageEditor ($this);
1010         $e->viewSource();
1011     }
1012
1013     function action_lock () {
1014         $page = $this->getPage();
1015         $page->set('locked', true);
1016         $this->_dbi->touch();
1017         // check ModeratedPage hook
1018         if ($moderated = $page->get('moderated')) {
1019             require_once("lib/WikiPlugin.php");
1020             $plugin = WikiPluginLoader::getPlugin("ModeratedPage");
1021             if ($retval = $plugin->lock_check($this, $page, $moderated))
1022                 $this->setArg('errormsg', $retval);
1023         } 
1024         // check if a link to ModeratedPage exists
1025         elseif ($action_page = $page->existLink(_("ModeratedPage"))) {
1026             require_once("lib/WikiPlugin.php");
1027             $plugin = WikiPluginLoader::getPlugin("ModeratedPage");
1028             if ($retval = $plugin->lock_add($this, $page, $action_page))
1029                 $this->setArg('errormsg', $retval);
1030         }
1031         $this->action_browse();
1032     }
1033
1034     function action_unlock () {
1035         $page = $this->getPage();
1036         $page->set('locked', false);
1037         $this->_dbi->touch();
1038         $this->action_browse();
1039     }
1040
1041     function action_remove () {
1042         // FIXME: This check is redundant.
1043         //$user->requireAuth(WIKIAUTH_ADMIN);
1044         $pagename = $this->getArg('pagename');
1045         if (strstr($pagename,_('PhpWikiAdministration'))) {
1046             $this->action_browse();
1047         } else {
1048             include('lib/removepage.php');
1049             RemovePage($this);
1050         }
1051     }
1052
1053     function action_xmlrpc () {
1054         include_once("lib/XmlRpcServer.php");
1055         $xmlrpc = new XmlRpcServer($this);
1056         $xmlrpc->service();
1057     }
1058     
1059     function action_revert () {
1060         include_once "lib/loadsave.php";
1061         RevertPage($this);
1062     }
1063
1064     function action_zip () {
1065         include_once("lib/loadsave.php");
1066         MakeWikiZip($this);
1067         // I don't think it hurts to add cruft at the end of the zip file.
1068         //echo "\n========================================================\n";
1069         //echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
1070     }
1071
1072     function action_ziphtml () {
1073         include_once("lib/loadsave.php");
1074         MakeWikiZipHtml($this);
1075         // I don't think it hurts to add cruft at the end of the zip file.
1076         echo "\n========================================================\n";
1077         echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
1078     }
1079
1080     function action_dumpserial () {
1081         include_once("lib/loadsave.php");
1082         DumpToDir($this);
1083     }
1084
1085     function action_dumphtml () {
1086         include_once("lib/loadsave.php");
1087         DumpHtmlToDir($this);
1088     }
1089
1090     function action_upload () {
1091         include_once("lib/loadsave.php");
1092         LoadPostFile($this);
1093     }
1094
1095     function action_upgrade () {
1096         include_once("lib/loadsave.php");
1097         include_once("lib/upgrade.php");
1098         DoUpgrade($this);
1099     }
1100
1101     function action_loadfile () {
1102         include_once("lib/loadsave.php");
1103         LoadFileOrDir($this);
1104     }
1105
1106     function action_pdf () {
1107         include_once("lib/pdf.php");
1108         ConvertAndDisplayPdf($this);
1109     }
1110     
1111 }
1112
1113 //FIXME: deprecated
1114 /*
1115 Debug Strict: F:\prog\php\phpwiki-dev\phpwiki\lib\HtmlElement.php line 415 - Non-static method HTML::_setTagProperty() should not be called statically
1116 Debug Strict: F:\prog\php\phpwiki-dev\phpwiki\lib\HtmlElement.php line 432 - Non-static method HTML::_setTagProperty() should not be called statically
1117 Debug Strict: F:\prog\php\phpwiki-dev\phpwiki\lib\HtmlElement.php line 442 - Non-static method HTML::_setTagProperty() should not be called statically
1118 Debug Strict: F:\prog\php\phpwiki-dev\phpwiki\lib\WikiDB.php line 119 - Creating default object from empty value
1119 Debug Strict: F:\prog\php\phpwiki-dev\phpwiki\lib\main.php line 1112 - Non-static method WikiRequest::requiredAuthorityForAction() should not be called statically
1120 */
1121 function is_safe_action ($action) {
1122     global $request;
1123     return $request->requiredAuthorityForAction($action) < WIKIAUTH_ADMIN;
1124 }
1125
1126 function validateSessionPath() {
1127     // Try to defer any session.save_path PHP errors before any html
1128     // is output, which causes some versions of IE to display a blank
1129     // page (due to its strict mode while parsing a page?).
1130     if (! is_writeable(ini_get('session.save_path'))) {
1131         $tmpdir = defined('SESSION_SAVE_PATH') ? SESSION_SAVE_PATH : '/tmp';
1132         if (!is_writeable($tmpdir))
1133             $tmpdir = '/tmp';
1134         trigger_error
1135             (sprintf(_("%s is not writable."),
1136                      _("The session.save_path directory"))
1137              . "\n"
1138              . sprintf(_("Please ensure that %s is writable, or redefine %s in config/config.ini."),
1139                        sprintf(_("the session.save_path directory '%s'"),
1140                                ini_get('session.save_path')),
1141                        'SESSION_SAVE_PATH')
1142              . "\n"
1143              . sprintf(_("Attempting to use the directory '%s' instead."),
1144                        $tmpdir)
1145              , E_USER_NOTICE);
1146         if (! is_writeable($tmpdir)) {
1147             trigger_error
1148                 (sprintf(_("%s is not writable."), $tmpdir)
1149                  . "\n"
1150                  . _("Users will not be able to sign in.")
1151                  , E_USER_NOTICE);
1152         }
1153         else
1154             ini_set('session.save_path', $tmpdir);
1155     }
1156 }
1157
1158 function main () {
1159     if (!USE_DB_SESSION)
1160         validateSessionPath();
1161
1162     global $request;
1163     if ((DEBUG & _DEBUG_APD) and extension_loaded("apd"))
1164         apd_set_session_trace(9);
1165
1166     // Postpone warnings
1167     global $ErrorManager;
1168     if (defined('E_STRICT')) // and (E_ALL & E_STRICT)) // strict php5?
1169         $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE|E_USER_WARNING|E_WARNING|E_STRICT);
1170     else
1171         $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE|E_USER_WARNING|E_WARNING);
1172     $request = new WikiRequest();
1173
1174     $action = $request->getArg('action');
1175     if (substr($action, 0, 3) != 'zip') {
1176         if ($action == 'pdf')
1177             $ErrorManager->setPostponedErrorMask(-1); // everything
1178         //else // reject postponing of warnings
1179         //    $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE);
1180     }
1181
1182     /*
1183      * Allow for disabling of markup cache.
1184      * (Mostly for debugging ... hopefully.)
1185      *
1186      * See also <?plugin WikiAdminUtils action=purge-cache ?>
1187      */
1188     if (!defined('WIKIDB_NOCACHE_MARKUP') and $request->getArg('nocache'))
1189         define('WIKIDB_NOCACHE_MARKUP', $request->getArg('nocache'));
1190     
1191     // Initialize with system defaults in case user not logged in.
1192     // Should this go into constructor?
1193     $request->initializeTheme();
1194
1195     $request->updateAuthAndPrefs();
1196     $request->initializeLang();
1197     
1198     //FIXME:
1199     //if ($user->is_authenticated())
1200     //  $LogEntry->user = $user->getId();
1201
1202     // Memory optimization:
1203     // http://www.procata.com/blog/archives/2004/05/27/rephlux-and-php-memory-usage/
1204     // kill the global PEAR _PEAR_destructor_object_list
1205     if (!empty($_PEAR_destructor_object_list))
1206         $_PEAR_destructor_object_list = array();
1207     $request->possiblyDeflowerVirginWiki();
1208     
1209 // hack! define proper actions for these.
1210 if (defined('WIKI_XMLRPC') and WIKI_XMLRPC) return;
1211 if (defined('WIKI_SOAP')   and WIKI_SOAP)   return;
1212
1213     $validators = array('wikiname' => WIKI_NAME,
1214                         'args'     => hash($request->getArgs()),
1215                         'prefs'    => hash($request->getPrefs()));
1216     if (CACHE_CONTROL == 'STRICT') {
1217         $dbi = $request->getDbh();
1218         $timestamp = $dbi->getTimestamp();
1219         $validators['mtime'] = $timestamp;
1220         $validators['%mtime'] = (int)$timestamp;
1221     }
1222     // FIXME: we should try to generate strong validators when possible,
1223     // but for now, our validator is weak, since equal validators do not
1224     // indicate byte-level equality of content.  (Due to DEBUG timing output, etc...)
1225     //
1226     // (If DEBUG if off, this may be a strong validator, but I'm going
1227     // to go the paranoid route here pending further study and testing.)
1228     //
1229     $validators['%weak'] = true;
1230     $request->setValidators($validators);
1231    
1232     $request->handleAction();
1233
1234     if (DEBUG and DEBUG & _DEBUG_INFO) phpinfo(INFO_VARIABLES | INFO_MODULES);
1235     $request->finish();
1236 }
1237
1238 //$x = error_reporting();  // DEBUG: why is it 1 here? should be E_ALL
1239 if (defined('E_STRICT') and (E_ALL & E_STRICT)) // strict php5?
1240     error_reporting(E_ALL & ~E_STRICT);         // exclude E_STRICT
1241 else
1242     error_reporting(E_ALL); // php4
1243 // don't run the main loop for special requests (test, getimg, xmlrpc, soap, ...)
1244 if (!defined('PHPWIKI_NOMAIN') or !PHPWIKI_NOMAIN)
1245     main();
1246
1247
1248 // $Log: not supported by cvs2svn $
1249 // Revision 1.204  2005/01/25 07:35:42  rurban
1250 // add TODO comment
1251 //
1252 // Revision 1.203  2005/01/21 14:11:23  rurban
1253 // better moderation class tag
1254 //
1255 // Revision 1.202  2005/01/21 12:02:32  rurban
1256 // deduce username for xmlrpc also
1257 //
1258 // Revision 1.201  2005/01/20 10:18:17  rurban
1259 // reformatting
1260 //
1261 // Revision 1.200  2004/12/26 17:08:36  rurban
1262 // php5 fixes: case-sensitivity, no & new
1263 //
1264 // Revision 1.199  2004/12/19 00:58:01  rurban
1265 // Enforce PASSWORD_LENGTH_MINIMUM in almost all PassUser checks,
1266 // Provide an errormessage if so. Just PersonalPage and BogoLogin not.
1267 // Simplify httpauth logout handling and set sessions for all methods.
1268 // fix main.php unknown index "x" getLevelDescription() warning.
1269 //
1270 // Revision 1.198  2004/12/17 16:49:51  rurban
1271 // avoid Invalid username message on Sign In button click
1272 //
1273 // Revision 1.197  2004/12/17 16:39:55  rurban
1274 // enable sessions for HttpAuth
1275 //
1276 // Revision 1.196  2004/12/10 02:36:43  rurban
1277 // More help with the new native xmlrpc lib. no warnings, no user cookie on xmlrpc.
1278 //
1279 // Revision 1.195  2004/12/09 22:24:44  rurban
1280 // optimize on _DEBUG_SQL only. but now again on every 50th request, not just save.
1281 //
1282 // Revision 1.194  2004/11/30 17:46:49  rurban
1283 // added ModeratedPage POST action hook (part 2/3)
1284 //
1285 // Revision 1.193  2004/11/30 07:51:08  rurban
1286 // fixed SESSION_SAVE_PATH warning msg
1287 //
1288 // Revision 1.192  2004/11/21 11:59:20  rurban
1289 // remove final \n to be ob_cache independent
1290 //
1291 // Revision 1.191  2004/11/19 19:22:03  rurban
1292 // ModeratePage part1: change status
1293 //
1294 // Revision 1.190  2004/11/15 15:56:40  rurban
1295 // don't load PagePerm on ENABLE_PAGEPERM = false to save memory. Move mayAccessPage() to main.php
1296 //
1297 // Revision 1.189  2004/11/09 17:11:16  rurban
1298 // * revert to the wikidb ref passing. there's no memory abuse there.
1299 // * use new wikidb->_cache->_id_cache[] instead of wikidb->_iwpcache, to effectively
1300 //   store page ids with getPageLinks (GleanDescription) of all existing pages, which
1301 //   are also needed at the rendering for linkExistingWikiWord().
1302 //   pass options to pageiterator.
1303 //   use this cache also for _get_pageid()
1304 //   This saves about 8 SELECT count per page (num all pagelinks).
1305 // * fix passing of all page fields to the pageiterator.
1306 // * fix overlarge session data which got broken with the latest ACCESS_LOG_SQL changes
1307 //
1308 // Revision 1.188  2004/11/07 16:02:52  rurban
1309 // new sql access log (for spam prevention), and restructured access log class
1310 // dbh->quote (generic)
1311 // pear_db: mysql specific parts seperated (using replace)
1312 //
1313 // Revision 1.187  2004/11/05 22:08:52  rurban
1314 // Ok: Fix loading all required userclasses beforehand. This is much slower than before but safes a few bytes RAM
1315 //
1316 // Revision 1.186  2004/11/05 20:53:35  rurban
1317 // login cleanup: better debug msg on failing login,
1318 // checked password less immediate login (bogo or anon),
1319 // checked olduser pref session error,
1320 // better PersonalPage without password warning on minimal password length=0
1321 //   (which is default now)
1322 //
1323 // Revision 1.185  2004/11/01 13:55:05  rurban
1324 // fix against switching user new/old between sessions
1325 //
1326 // Revision 1.184  2004/11/01 10:43:57  rurban
1327 // seperate PassUser methods into seperate dir (memory usage)
1328 // fix WikiUser (old) overlarge data session
1329 // remove wikidb arg from various page class methods, use global ->_dbi instead
1330 // ...
1331 //
1332 // Revision 1.183  2004/10/14 19:23:58  rurban
1333 // remove debugging prints
1334 //
1335 // Revision 1.182  2004/10/12 13:13:19  rurban
1336 // php5 compatibility (5.0.1 ok)
1337 //
1338 // Revision 1.181  2004/10/07 16:08:58  rurban
1339 // fixed broken FileUser session handling.
1340 //   thanks to Arnaud Fontaine for detecting this.
1341 // enable file user Administrator membership.
1342 //
1343 // Revision 1.180  2004/10/04 23:39:34  rurban
1344 // just aesthetics
1345 //
1346 // Revision 1.179  2004/09/25 18:57:42  rurban
1347 // better ACL error message: view not browse, change not setacl, ...
1348 //
1349 // Revision 1.178  2004/09/25 16:27:36  rurban
1350 // better not allowed description: on global disallowed, and on missing pageperms
1351 //
1352 // Revision 1.177  2004/09/14 10:31:09  rurban
1353 // exclude E_STRICT for php5: untested. I believe this must be set earlier because the parsing step is already strict, and this is called at run-time
1354 //
1355 // Revision 1.176  2004/08/05 17:33:22  rurban
1356 // aesthetic typo
1357 //
1358 // Revision 1.175  2004/07/13 13:08:25  rurban
1359 // fix PEAR memory waste issues
1360 //
1361 // Revision 1.174  2004/07/08 13:50:32  rurban
1362 // various unit test fixes: print error backtrace on _DEBUG_TRACE; allusers fix; new PHPWIKI_NOMAIN constant for omitting the mainloop
1363 //
1364 // Revision 1.173  2004/07/05 12:57:54  rurban
1365 // add mysql timeout
1366 //
1367 // Revision 1.172  2004/07/03 08:04:19  rurban
1368 // fixed implicit PersonalPage login (e.g. on edit), fixed to check against create ACL on create, not edit
1369 //
1370 // Revision 1.171  2004/06/29 09:30:42  rurban
1371 // force string hash
1372 //
1373 // Revision 1.170  2004/06/25 14:29:20  rurban
1374 // WikiGroup refactoring:
1375 //   global group attached to user, code for not_current user.
1376 //   improved helpers for special groups (avoid double invocations)
1377 // new experimental config option ENABLE_XHTML_XML (fails with IE, and document.write())
1378 // fixed a XHTML validation error on userprefs.tmpl
1379 //
1380 // Revision 1.169  2004/06/20 14:42:54  rurban
1381 // various php5 fixes (still broken at blockparser)
1382 //
1383 // Revision 1.168  2004/06/17 10:39:18  rurban
1384 // fix reverse translation of possible actionpage
1385 //
1386 // Revision 1.167  2004/06/16 13:21:16  rurban
1387 // stabilize on failing ldap queries or bind
1388 //
1389 // Revision 1.166  2004/06/15 09:15:52  rurban
1390 // IMPORTANT: fixed passwd handling for passwords stored in prefs:
1391 //   fix encrypted usage, actually store and retrieve them from db
1392 //   fix bogologin with passwd set.
1393 // fix php crashes with call-time pass-by-reference (references wrongly used
1394 //   in declaration AND call). This affected mainly Apache2 and IIS.
1395 //   (Thanks to John Cole to detect this!)
1396 //
1397 // Revision 1.165  2004/06/14 11:31:37  rurban
1398 // renamed global $Theme to $WikiTheme (gforge nameclash)
1399 // inherit PageList default options from PageList
1400 //   default sortby=pagename
1401 // use options in PageList_Selectable (limit, sortby, ...)
1402 // added action revert, with button at action=diff
1403 // added option regex to WikiAdminSearchReplace
1404 //
1405 // Revision 1.164  2004/06/13 13:54:25  rurban
1406 // Catch fatals on the four dump calls (as file and zip, as html and mimified)
1407 // FoafViewer: Check against external requirements, instead of fatal.
1408 // Change output for xhtmldumps: using file:// urls to the local fs.
1409 // Catch SOAP fatal by checking for GOOGLE_LICENSE_KEY
1410 // Import GOOGLE_LICENSE_KEY and FORTUNE_DIR from config.ini.
1411 //
1412 // Revision 1.163  2004/06/13 11:35:32  rurban
1413 // check for create action on action=edit not to fool PagePerm checks
1414 //
1415 // Revision 1.162  2004/06/08 10:05:11  rurban
1416 // simplified admin action shortcuts
1417 //
1418 // Revision 1.161  2004/06/07 22:58:40  rurban
1419 // simplified chown, setacl, dump actions
1420 //
1421 // Revision 1.160  2004/06/07 22:44:14  rurban
1422 // added simplified chown, setacl actions
1423 //
1424 // Revision 1.159  2004/06/06 16:58:51  rurban
1425 // added more required ActionPages for foreign languages
1426 // install now english ActionPages if no localized are found. (again)
1427 // fixed default anon user level to be 0, instead of -1
1428 //   (wrong "required administrator to view this page"...)
1429 //
1430 // Revision 1.158  2004/06/04 20:32:53  rurban
1431 // Several locale related improvements suggested by Pierrick Meignen
1432 // LDAP fix by John Cole
1433 // reanable admin check without ENABLE_PAGEPERM in the admin plugins
1434 //
1435 // Revision 1.157  2004/06/04 12:40:21  rurban
1436 // Restrict valid usernames to prevent from attacks against external auth or compromise
1437 // possible holes.
1438 // Fix various WikiUser old issues with default IMAP,LDAP,POP3 configs. Removed these.
1439 // Fxied more warnings
1440 //
1441 // Revision 1.156  2004/06/03 17:58:16  rurban
1442 // support immediate LANG and THEME switch inside a session
1443 //
1444 // Revision 1.155  2004/06/03 10:18:19  rurban
1445 // fix FileUser locking issues, new config ENABLE_PAGEPERM
1446 //
1447 // Revision 1.154  2004/06/02 18:01:46  rurban
1448 // init global FileFinder to add proper include paths at startup
1449 //   adds PHPWIKI_DIR if started from another dir, lib/pear also
1450 // fix slashify for Windows
1451 // fix USER_AUTH_POLICY=old, use only USER_AUTH_ORDER methods (besides HttpAuth)
1452 //
1453 // Revision 1.153  2004/06/01 15:28:00  rurban
1454 // AdminUser only ADMIN_USER not member of Administrators
1455 // some RateIt improvements by dfrankow
1456 // edit_toolbar buttons
1457 //
1458 // Revision 1.152  2004/05/27 17:49:06  rurban
1459 // renamed DB_Session to DbSession (in CVS also)
1460 // added WikiDB->getParam and WikiDB->getAuthParam method to get rid of globals
1461 // remove leading slash in error message
1462 // added force_unlock parameter to File_Passwd (no return on stale locks)
1463 // fixed adodb session AffectedRows
1464 // added FileFinder helpers to unify local filenames and DATA_PATH names
1465 // editpage.php: new edit toolbar javascript on ENABLE_EDIT_TOOLBAR
1466 //
1467 // Revision 1.151  2004/05/25 12:40:48  rurban
1468 // trim the pagename
1469 //
1470 // Revision 1.150  2004/05/25 10:18:44  rurban
1471 // Check for UTF-8 URLs; Internet Explorer produces these if you
1472 // type non-ASCII chars in the URL bar or follow unescaped links.
1473 // Fixes sf.net bug #953949
1474 // src: languages/Language.php:checkTitleEncoding() from mediawiki
1475 //
1476 // Revision 1.149  2004/05/18 13:31:19  rurban
1477 // hold warnings until headers are sent. new Error-style with collapsed output of repeated messages
1478 //
1479 // Revision 1.148  2004/05/17 17:43:29  rurban
1480 // CGI: no PATH_INFO fix
1481 //
1482 // Revision 1.147  2004/05/15 19:48:33  rurban
1483 // fix some too loose PagePerms for signed, but not authenticated users
1484 //  (admin, owner, creator)
1485 // no double login page header, better login msg.
1486 // moved action_pdf to lib/pdf.php
1487 //
1488 // Revision 1.146  2004/05/15 18:31:01  rurban
1489 // some action=pdf Request fixes: With MSIE it works now. Now the work with the page formatting begins.
1490 //
1491 // Revision 1.145  2004/05/12 10:49:55  rurban
1492 // require_once fix for those libs which are loaded before FileFinder and
1493 //   its automatic include_path fix, and where require_once doesn't grok
1494 //   dirname(__FILE__) != './lib'
1495 // upgrade fix with PearDB
1496 // navbar.tmpl: remove spaces for IE &nbsp; button alignment
1497 //
1498 // Revision 1.144  2004/05/06 19:26:16  rurban
1499 // improve stability, trying to find the InlineParser endless loop on sf.net
1500 //
1501 // remove end-of-zip comments to fix sf.net bug #777278 and probably #859628
1502 //
1503 // Revision 1.143  2004/05/06 17:30:38  rurban
1504 // CategoryGroup: oops, dos2unix eol
1505 // improved phpwiki_version:
1506 //   pre -= .0001 (1.3.10pre: 1030.099)
1507 //   -p1 += .001 (1.3.9-p1: 1030.091)
1508 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
1509 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
1510 //   backend->backendType(), backend->database(),
1511 //   backend->listOfFields(),
1512 //   backend->listOfTables(),
1513 //
1514 // Revision 1.142  2004/05/04 22:34:25  rurban
1515 // more pdf support
1516 //
1517 // Revision 1.141  2004/05/03 13:16:47  rurban
1518 // fixed UserPreferences update, esp for boolean and int
1519 //
1520 // Revision 1.140  2004/05/02 21:26:38  rurban
1521 // limit user session data (HomePageHandle and auth_dbi have to invalidated anyway)
1522 //   because they will not survive db sessions, if too large.
1523 // extended action=upgrade
1524 // some WikiTranslation button work
1525 // revert WIKIAUTH_UNOBTAINABLE (need it for main.php)
1526 // some temp. session debug statements
1527 //
1528 // Revision 1.139  2004/05/02 15:10:07  rurban
1529 // new finally reliable way to detect if /index.php is called directly
1530 //   and if to include lib/main.php
1531 // new global AllActionPages
1532 // SetupWiki now loads all mandatory pages: HOME_PAGE, action pages, and warns if not.
1533 // WikiTranslation what=buttons for Carsten to create the missing MacOSX buttons
1534 // PageGroupTestOne => subpages
1535 // renamed PhpWikiRss to PhpWikiRecentChanges
1536 // more docs, default configs, ...
1537 //
1538 // Revision 1.138  2004/05/01 15:59:29  rurban
1539 // more php-4.0.6 compatibility: superglobals
1540 //
1541 // Revision 1.137  2004/04/29 19:39:44  rurban
1542 // special support for formatted plugins (one-liners)
1543 //   like <small><plugin BlaBla ></small>
1544 // iter->asArray() helper for PopularNearby
1545 // db_session for older php's (no &func() allowed)
1546 //
1547 // Revision 1.136  2004/04/29 17:18:19  zorloc
1548 // 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.
1549 //
1550 // Revision 1.135  2004/04/26 12:15:01  rurban
1551 // check default config values
1552 //
1553 // Revision 1.134  2004/04/23 06:46:37  zorloc
1554 // Leave DB connection open when USE_DB_SESSION is true so that session info can be written to the DB.
1555 //
1556 // Revision 1.133  2004/04/20 18:10:31  rurban
1557 // config refactoring:
1558 //   FileFinder is needed for WikiFarm scripts calling index.php
1559 //   config run-time calls moved to lib/IniConfig.php:fix_configs()
1560 //   added PHPWIKI_DIR smart-detection code (Theme finder)
1561 //   moved FileFind to lib/FileFinder.php
1562 //   cleaned lib/config.php
1563 //
1564 // Revision 1.132  2004/04/19 21:51:41  rurban
1565 // php5 compatibility: it works!
1566 //
1567 // Revision 1.131  2004/04/19 18:27:45  rurban
1568 // Prevent from some PHP5 warnings (ref args, no :: object init)
1569 //   php5 runs now through, just one wrong XmlElement object init missing
1570 // Removed unneccesary UpgradeUser lines
1571 // Changed WikiLink to omit version if current (RecentChanges)
1572 //
1573 // Revision 1.130  2004/04/18 00:25:53  rurban
1574 // allow "0" pagename
1575 //
1576 // Revision 1.129  2004/04/07 23:13:19  rurban
1577 // fixed pear/File_Passwd for Windows
1578 // fixed FilePassUser sessions (filehandle revive) and password update
1579 //
1580 // Revision 1.128  2004/04/02 15:06:55  rurban
1581 // fixed a nasty ADODB_mysql session update bug
1582 // improved UserPreferences layout (tabled hints)
1583 // fixed UserPreferences auth handling
1584 // improved auth stability
1585 // improved old cookie handling: fixed deletion of old cookies with paths
1586 //
1587 // Revision 1.127  2004/03/25 17:00:31  rurban
1588 // more code to convert old-style pref array to new hash
1589 //
1590 // Revision 1.126  2004/03/24 19:39:03  rurban
1591 // php5 workaround code (plus some interim debugging code in XmlElement)
1592 //   php5 doesn't work yet with the current XmlElement class constructors,
1593 //   WikiUserNew does work better than php4.
1594 // rewrote WikiUserNew user upgrading to ease php5 update
1595 // fixed pref handling in WikiUserNew
1596 // added Email Notification
1597 // added simple Email verification
1598 // removed emailVerify userpref subclass: just a email property
1599 // changed pref binary storage layout: numarray => hash of non default values
1600 // print optimize message only if really done.
1601 // forced new cookie policy: delete pref cookies, use only WIKI_ID as plain string.
1602 //   prefs should be stored in db or homepage, besides the current session.
1603 //
1604 // Revision 1.125  2004/03/14 16:30:52  rurban
1605 // db-handle session revivification, dba fixes
1606 //
1607 // Revision 1.124  2004/03/12 15:48:07  rurban
1608 // fixed explodePageList: wrong sortby argument order in UnfoldSubpages
1609 // simplified lib/stdlib.php:explodePageList
1610 //
1611 // Revision 1.123  2004/03/10 15:41:27  rurban
1612 // use default pref mysql table
1613 //
1614 // Revision 1.122  2004/03/08 18:17:09  rurban
1615 // added more WikiGroup::getMembersOf methods, esp. for special groups
1616 // fixed $LDAP_SET_OPTIONS
1617 // fixed _AuthInfo group methods
1618 //
1619 // Revision 1.121  2004/03/01 13:48:45  rurban
1620 // rename fix
1621 // p[] consistency fix
1622 //
1623 // Revision 1.120  2004/03/01 10:22:41  rurban
1624 // initializeTheme optimize
1625 //
1626 // Revision 1.119  2004/02/26 20:45:06  rurban
1627 // check for ALLOW_ANON_USER = false
1628 //
1629 // Revision 1.118  2004/02/26 01:32:03  rurban
1630 // fixed session login with old WikiUser object. strangely, the errormask gets corruoted to 1, Pear???
1631 //
1632 // Revision 1.117  2004/02/24 17:19:37  rurban
1633 // debugging helpers only
1634 //
1635 // Revision 1.116  2004/02/24 15:17:14  rurban
1636 // improved auth errors with individual pages. the fact that you may not browse a certain admin page does not conclude that you may not browse the whole wiki. renamed browse => view
1637 //
1638 // Revision 1.115  2004/02/15 21:34:37  rurban
1639 // PageList enhanced and improved.
1640 // fixed new WikiAdmin... plugins
1641 // editpage, Theme with exp. htmlarea framework
1642 //   (htmlarea yet committed, this is really questionable)
1643 // WikiUser... code with better session handling for prefs
1644 // enhanced UserPreferences (again)
1645 // RecentChanges for show_deleted: how should pages be deleted then?
1646 //
1647 // Revision 1.114  2004/02/15 17:30:13  rurban
1648 // workaround for lost db connnection handle on session restauration (->_auth_dbi)
1649 // fixed getPreferences() (esp. from sessions)
1650 // fixed setPreferences() (update and set),
1651 // fixed AdoDb DB statements,
1652 // update prefs only at UserPreferences POST (for testing)
1653 // unified db prefs methods (but in external pref classes yet)
1654 //
1655 // Revision 1.113  2004/02/12 13:05:49  rurban
1656 // Rename functional for PearDB backend
1657 // some other minor changes
1658 // SiteMap comes with a not yet functional feature request: includepages (tbd)
1659 //
1660 // Revision 1.112  2004/02/09 03:58:12  rurban
1661 // for now default DB_SESSION to false
1662 // PagePerm:
1663 //   * not existing perms will now query the parent, and not
1664 //     return the default perm
1665 //   * added pagePermissions func which returns the object per page
1666 //   * added getAccessDescription
1667 // WikiUserNew:
1668 //   * added global ->prepare (not yet used) with smart user/pref/member table prefixing.
1669 //   * force init of authdbh in the 2 db classes
1670 // main:
1671 //   * fixed session handling (not triple auth request anymore)
1672 //   * don't store cookie prefs with sessions
1673 // stdlib: global obj2hash helper from _AuthInfo, also needed for PagePerm
1674 //
1675 // Revision 1.111  2004/02/07 10:41:25  rurban
1676 // fixed auth from session (still double code but works)
1677 // fixed GroupDB
1678 // fixed DbPassUser upgrade and policy=old
1679 // added GroupLdap
1680 //
1681 // Revision 1.110  2004/02/03 09:45:39  rurban
1682 // LDAP cleanup, start of new Pref classes
1683 //
1684 // Revision 1.109  2004/01/30 19:57:58  rurban
1685 // fixed DBAuthParams['pref_select']: wrong _auth_dbi object used.
1686 //
1687 // Revision 1.108  2004/01/28 14:34:14  rurban
1688 // session table takes the common prefix
1689 // + various minor stuff
1690 // reallow password changing
1691 //
1692 // Revision 1.107  2004/01/27 23:23:39  rurban
1693 // renamed ->Username => _userid for consistency
1694 // renamed mayCheckPassword => mayCheckPass
1695 // fixed recursion problem in WikiUserNew
1696 // fixed bogo login (but not quite 100% ready yet, password storage)
1697 //
1698 // Revision 1.106  2004/01/26 09:17:49  rurban
1699 // * changed stored pref representation as before.
1700 //   the array of objects is 1) bigger and 2)
1701 //   less portable. If we would import packed pref
1702 //   objects and the object definition was changed, PHP would fail.
1703 //   This doesn't happen with an simple array of non-default values.
1704 // * use $prefs->retrieve and $prefs->store methods, where retrieve
1705 //   understands the interim format of array of objects also.
1706 // * simplified $prefs->get() and fixed $prefs->set()
1707 // * added $user->_userid and class '_WikiUser' portability functions
1708 // * fixed $user object ->_level upgrading, mostly using sessions.
1709 //   this fixes yesterdays problems with loosing authorization level.
1710 // * fixed WikiUserNew::checkPass to return the _level
1711 // * fixed WikiUserNew::isSignedIn
1712 // * added explodePageList to class PageList, support sortby arg
1713 // * fixed UserPreferences for WikiUserNew
1714 // * fixed WikiPlugin for empty defaults array
1715 // * UnfoldSubpages: added pagename arg, renamed pages arg,
1716 //   removed sort arg, support sortby arg
1717 //
1718 // Revision 1.105  2004/01/25 03:57:15  rurban
1719 // WikiUserNew support (temp. ENABLE_USER_NEW constant)
1720 //
1721 // Revision 1.104  2003/12/26 06:41:16  carstenklapp
1722 // Bugfix: Try to defer OS errors about session.save_path and ACCESS_LOG,
1723 // so they don't prevent IE from partially (or not at all) rendering the
1724 // page. This should help a little for the IE user who encounters trouble
1725 // when setting up a new PhpWiki for the first time.
1726 //
1727 // Revision 1.103  2003/12/02 00:10:00  carstenklapp
1728 // Bugfix: Ongoing work to untangle UserPreferences/WikiUser/request code
1729 // mess: UserPreferences should take effect immediately now upon signing
1730 // in.
1731 //
1732 // Revision 1.102  2003/11/25 22:55:32  carstenklapp
1733 // Localization bugfix: For wikis where English is not the default system
1734 // language, make sure that the authority error message (i.e. "You must
1735 // sign in to edit pages in this wiki" etc.) is displayed in the wiki's
1736 // default language. Previously it would always display in English.
1737 // (Added call to update_locale() before displaying any messages prior to
1738 // the login prompt.)
1739 //
1740 // Revision 1.101  2003/11/25 21:49:44  carstenklapp
1741 // Bugfix: For a non-english wiki or when the user's preference is not
1742 // english, the wiki would always use the english ActionPage first if it
1743 // was present rather than the appropriate localised variant. (PhpWikis
1744 // running only in english or Wikis running ONLY without any english
1745 // ActionPages would not notice this bug, only when both english and
1746 // localised ActionPages were in the DB.) Now we check for the localised
1747 // variant first.
1748 //
1749 // Revision 1.100  2003/11/18 16:54:18  carstenklapp
1750 // Reformatting only: Tabs to spaces, added rcs log.
1751 //
1752
1753
1754 // Local Variables:
1755 // mode: php
1756 // tab-width: 8
1757 // c-basic-offset: 4
1758 // c-hanging-comment-ender-p: nil
1759 // indent-tabs-mode: nil
1760 // End:
1761 ?>