]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/main.php
Performance: Speedup SetupWiki by setting the action loadfile
[SourceForge/phpwiki.git] / lib / main.php
1 <?php //-*-php-*-
2 rcs_id('$Id$');
3 /*
4  Copyright 1999-2008 $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 demand-load it later. This way it's much slower, but needs slightly
62             // less memory than loading all.
63             if (ALLOW_BOGO_LOGIN)
64                 include_once("lib/WikiUser/BogoLogin.php");
65             // UserPreferences POST Update doesn't reach this.
66             foreach ($GLOBALS['USER_AUTH_ORDER'] as $method) {
67                 include_once("lib/WikiUser/$method.php");
68                 if ($method == 'Db')
69                     switch( DATABASE_TYPE ) {
70                         case 'SQL'  : include_once("lib/WikiUser/PearDb.php"); break;
71                         case 'ADODB': include_once("lib/WikiUser/AdoDb.php"); break;
72                         case 'PDO'  : include_once("lib/WikiUser/PdoDb.php"); break;
73                     }
74             }
75             unset($method);
76         }
77         if (USE_DB_SESSION) {
78             include_once('lib/DbSession.php');
79             $dbi =& $this->_dbi;
80             $this->_dbsession = new DbSession($dbi, $dbi->getParam('prefix') 
81                                               . $dbi->getParam('db_session_table'));
82         }
83
84 // Fixme: Does pear reset the error mask to 1? We have to find the culprit
85 //$x = error_reporting();
86
87         $this->version = phpwiki_version();
88         $this->Request(); // [90ms]
89
90         // Normalize args...
91         $this->setArg('pagename', $this->_deducePagename());
92         $this->setArg('action', $this->_deduceAction());
93
94         if ((DEBUG & _DEBUG_SQL)
95             or (DATABASE_OPTIMISE_FREQUENCY > 0 and 
96                 (time() % DATABASE_OPTIMISE_FREQUENCY == 0))) {
97             if ($this->_dbi->_backend->optimize())
98                 trigger_error(_("Optimizing database"), E_USER_NOTICE);
99         }
100
101         // Restore auth state. This doesn't check for proper authorization!
102         $userid = $this->_deduceUsername();     
103         if (ENABLE_USER_NEW) {
104             if (isset($this->_user) and 
105                 !empty($this->_user->_authhow) and 
106                 $this->_user->_authhow == 'session')
107             {
108                 // users might switch in a session between the two objects.
109                 // restore old auth level here or in updateAuthAndPrefs?
110                 //$user = $this->getSessionVar('wiki_user');
111                 // revive db handle, because these don't survive sessions
112                 if (isset($this->_user) and 
113                      ( ! isa($this->_user, WikiUserClassname())
114                        or (strtolower(get_class($this->_user)) == '_passuser')))
115                 {
116                     $this->_user = WikiUser($userid, $this->_user->_prefs);
117                 }
118                 // revive other db handle
119                 if (isset($this->_user->_prefs->_method)
120                     and ($this->_user->_prefs->_method == 'SQL' 
121                          or $this->_user->_prefs->_method == 'ADODB' 
122                          or $this->_user->_prefs->_method == 'PDO' 
123                          or $this->_user->_prefs->_method == 'HomePage')) {
124                     $this->_user->_HomePagehandle = $this->getPage($userid);
125                 }
126                 // need to update the lockfile filehandle
127                 if ( isa($this->_user, '_FilePassUser') 
128                      and $this->_user->_file->lockfile 
129                      and !$this->_user->_file->fplock )
130                 {
131                     //$level = $this->_user->_level;
132                     $this->_user = UpgradeUser($this->_user, 
133                                                new _FilePassUser($userid, 
134                                                                  $this->_user->_prefs, 
135                                                                  $this->_user->_file->filename));
136                     //$this->_user->_level = $level;
137                 }
138                 $this->_prefs = & $this->_user->_prefs;
139             } else {
140                 $user = WikiUser($userid);
141                 $this->_user = & $user;
142                 $this->_prefs = & $this->_user->_prefs;
143             }
144         } else {
145             $this->_user = new WikiUser($this, $userid);
146             $this->_prefs = $this->_user->getPreferences();
147         }
148     }
149
150     function initializeLang () {
151         // check non-default pref lang
152         if (empty($this->_prefs->_prefs['lang']))
153             return;
154         $_lang = $this->_prefs->_prefs['lang'];
155         if (isset($_lang->lang) and $_lang->lang != $GLOBALS['LANG']) {
156             $user_lang = $_lang->lang;
157             //check changed LANG and THEME inside a session. 
158             // (e.g. by using another baseurl)
159             if (isset($this->_user->_authhow) and $this->_user->_authhow == 'session')
160                 $user_lang = $GLOBALS['LANG'];
161             update_locale($user_lang);
162             FindLocalizedButtonFile(".",'missing_ok','reinit');
163         }
164         //if (empty($_lang->lang) and $GLOBALS['LANG'] != $_lang->default_value) ;
165     }
166
167     function initializeTheme ($when = 'default') {
168         global $WikiTheme;
169         // if when = 'default', then first time init (default theme, ...)
170         // if when = 'login', then check some callbacks
171         //                    and maybe the theme changed (other theme defined in pref)
172         // if when = 'logout', then check other callbacks
173         //                    and maybe the theme changed (back to default theme)
174
175         // Load non-default theme (when = login)
176         if (!empty($this->_prefs->_prefs['theme'])) {
177             $_theme = $this->_prefs->_prefs['theme'];
178             if (isset($_theme) and isset($_theme->theme))
179                 $user_theme = $_theme->theme;
180             elseif (isset($_theme) and isset($_theme->default_value))
181                 $user_theme = $_theme->default_value;
182             else
183                 $user_theme = '';
184         }
185         else 
186             $user_theme = $this->getPref('theme');
187
188         //check changed LANG and THEME inside a session. 
189         // (e.g. by using another baseurl)
190         if (isset($this->_user->_authhow) 
191             and $this->_user->_authhow == 'session' 
192             and !isset($_theme->theme) 
193             and defined('THEME') 
194             and $user_theme != THEME)
195         {
196             include_once("themes/" . THEME . "/themeinfo.php");
197         }
198         if (empty($WikiTheme) and $user_theme) {
199             if (strcspn($user_theme,"./\x00]") != strlen($user_theme)) {
200                 trigger_error(sprintf("invalid theme '%s': Invalid characters detected", $user_theme),
201                               E_USER_WARNING);
202                 $user_theme = "default";
203             }
204             if (!$user_theme) $user_theme = "default";
205             include_once("themes/$user_theme/themeinfo.php");
206         }
207         if (empty($WikiTheme) and defined('THEME'))
208             include_once("themes/" . THEME . "/themeinfo.php");
209         if (empty($WikiTheme))
210             include_once("themes/default/themeinfo.php");
211         assert(!empty($WikiTheme));
212
213         // Do not execute global init code anymore
214
215         // WikiTheme callbacks
216         if ($when == 'login') {
217             $WikiTheme->CbUserLogin($this, $this->_user->_userid);
218             if (!$this->_user->hasHomePage()) { // NewUser
219                 $WikiTheme->CbNewUserLogin($this, $this->_user->_userid);
220                 if (in_array($this->getArg('action'), array('edit','create')))
221                     $WikiTheme->CbNewUserEdit($this, $this->_user->_userid);
222             }
223         }
224         elseif ($when == 'logout') {
225             $WikiTheme->CbUserLogout($this, $this->_user->_userid);
226         }
227         elseif ($when == 'default') {
228             $WikiTheme->load();
229             if ($this->_user->_level > 0 and !$this->_user->hasHomePage()) { // NewUser
230                 if (in_array($this->getArg('action'), array('edit','create')))
231                     $WikiTheme->CbNewUserEdit($this, $this->_user->_userid);
232             }
233         }
234     }
235
236     // This really maybe should be part of the constructor, but since it
237     // may involve HTML/template output, the global $request really needs
238     // to be initialized before we do this stuff.
239     // [50ms]: 36ms if wikidb_page::exists
240     function updateAuthAndPrefs () {
241
242         if (isset($this->_user) and (!isa($this->_user, WikiUserClassname()))) {
243             $this->_user = false;       
244         }
245         // Handle authentication request, if any.
246         if ($auth_args = $this->getArg('auth')) {
247             $this->setArg('auth', false);
248             $this->_handleAuthRequest($auth_args); // possible NORETURN
249         }
250         elseif ( ! $this->_user 
251                  or (isa($this->_user, WikiUserClassname()) 
252                      and ! $this->_user->isSignedIn())) {
253             // If not auth request, try to sign in as saved user.
254             if (($saved_user = $this->getPref('userid')) != false) {
255                 $this->_signIn($saved_user);
256             }
257         }
258         
259         $action = $this->getArg('action');
260
261         // Save preferences in session and cookie
262         if ((defined('WIKI_XMLRPC') and !WIKI_XMLRPC) or $action != 'xmlrpc') {
263             if (isset($this->_user) and $this->_user->_userid) {
264                 if (!isset($this->_user->_authhow) or $this->_user->_authhow != 'session') {
265                     $this->_user->setPreferences($this->_prefs, true);
266                 }
267             }
268             $tmpuser = $this->_user; // clone it
269             $this->setSessionVar('wiki_user', $tmpuser);
270             unset($tmpuser);
271         }
272
273         // Ensure user has permissions for action
274         // HACK ALERT: We may not set the request arg to create, 
275         // since the pageeditor has an ugly logic for action == create.
276         if ($action == 'edit' or $action == 'create') {
277             $page = $this->getPage();
278             if (! $page->exists() )
279                 $action = 'create';
280             else
281                 $action = 'edit';
282         }
283         if (! ENABLE_PAGEPERM) { // Bug #1438392 by Matt Brown
284             $require_level = $this->requiredAuthority($action);
285             if (! $this->_user->hasAuthority($require_level))
286                 $this->_notAuthorized($require_level); // NORETURN
287         } else {
288             // novatrope patch to let only _AUTHENTICATED view pages.
289             // If there's not enough authority or forbidden, ask for a password, 
290             // unless it's explicitly unobtainable. Some bad magic though.
291             if ($this->requiredAuthorityForAction($action) == WIKIAUTH_UNOBTAINABLE) {
292                 $require_level = $this->requiredAuthority($action);
293                 $this->_notAuthorized($require_level); // NORETURN
294             }
295         }
296     }
297
298     function & getUser () {
299         if (isset($this->_user))
300             return $this->_user;
301         else
302             return $GLOBALS['ForbiddenUser'];
303     }
304     
305     function & getGroup () {
306         if (isset($this->_user) and isset($this->_user->_group))
307             return $this->_user->_group;
308         else {
309             // Debug Strict: Only variable references should be returned by reference
310             $this->_user->_group = WikiGroup::getGroup();
311             return $this->_user->_group;
312         }
313     }
314
315     function & getPrefs () {
316         return $this->_prefs;
317     }
318
319     // Convenience function:
320     function getPref ($key) {
321         if (isset($this->_prefs)) {
322             return $this->_prefs->get($key);
323         }
324     }
325     function & getDbh () {
326         return $this->_dbi;
327     }
328
329     /**
330      * Get requested page from the page database.
331      * By default it will grab the page requested via the URL
332      *
333      * This is a convenience function.
334      * @param string $pagename Name of page to get.
335      * @return WikiDB_Page Object with methods to pull data from
336      * database for the page requested.
337      */
338     function getPage ($pagename = false) {
339         //if (!isset($this->_dbi)) $this->getDbh();
340         if (!$pagename) 
341             $pagename = $this->getArg('pagename');
342         return $this->_dbi->getPage($pagename);
343     }
344
345     /** Get URL for POST actions.
346      *
347      * Officially, we should just use SCRIPT_NAME (or some such),
348      * but that causes problems when we try to issue a redirect, e.g.
349      * after saving a page.
350      *
351      * Some browsers (at least NS4 and Mozilla 0.97 won't accept
352      * a redirect from a page to itself.)
353      *
354      * So, as a HACK, we include pagename and action as query args in
355      * the URL.  (These should be ignored when we receive the POST
356      * request.)
357      */
358     function getPostURL ($pagename = false) {
359         global $HTTP_GET_VARS;
360
361         if ($pagename === false)
362             $pagename = $this->getArg('pagename');
363         $action = $this->getArg('action');
364         if (!empty($HTTP_GET_VARS['start_debug'])) // zend ide support
365             return WikiURL($pagename, array('action' => $action, 'start_debug' => 1));
366         elseif ($action == 'edit')
367             return WikiURL($pagename);
368         else
369             return WikiURL($pagename, array('action' => $action));
370     }
371     
372     function _handleAuthRequest ($auth_args) {
373         if (!is_array($auth_args))
374             return;
375
376         // Ignore password unless POST'ed.
377         if (!$this->isPost())
378             unset($auth_args['passwd']);
379
380         $olduser = $this->_user;
381         $user = $this->_user->AuthCheck($auth_args);
382         if (is_string($user)) {
383             // Login attempt failed.
384             $fail_message = $user;
385             $auth_args['pass_required'] = true;
386             // if clicked just on to the "sign in as:" button dont print invalid username.
387             if (!empty($auth_args['login']) and empty($auth_args['userid']))
388                 $fail_message = '';
389             // If no password was submitted, it's not really
390             // a failure --- just need to prompt for password...
391             if (!ALLOW_USER_PASSWORDS 
392                 and ALLOW_BOGO_LOGIN 
393                 and !isset($auth_args['passwd'])) 
394             {
395                 $fail_message = false;
396             }
397             $olduser->PrintLoginForm($this, $auth_args, $fail_message, 'newpage');
398             $this->finish();    //NORETURN
399         }
400         elseif (isa($user, WikiUserClassname())) {
401             // Successful login (or logout.)
402             $this->_setUser($user);
403         }
404         else {
405             // Login request cancelled.
406         }
407     }
408
409     /**
410      * Attempt to sign in (bogo-login).
411      *
412      * Fails silently.
413      *
414      * @param $userid string Userid to attempt to sign in as.
415      * @access private
416      */
417     function _signIn ($userid) {
418         if (ENABLE_USER_NEW) {
419             if (! $this->_user )
420                 $this->_user = new _BogoUser($userid);
421             // FIXME: is this always false? shouldn't we try passuser first?
422             if (! $this->_user ) 
423                 $this->_user = new _PassUser($userid);
424         } else {
425             if (! $this->_user )
426                 $this->_user = new WikiUser($this, $userid);
427         }
428         $user = $this->_user->AuthCheck(array('userid' => $userid));
429         if (isa($user, WikiUserClassname())) {
430             $this->_setUser($user); // success!
431         }
432     }
433
434     // login or logout or restore state
435     function _setUser (&$user) {
436         $this->_user =& $user;
437         if (defined('MAIN_setUser')) return; // don't set cookies twice
438         $this->setCookieVar(getCookieName(), $user->getAuthenticatedId(),
439                             COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
440         $isSignedIn = $user->isSignedIn();
441         if ($isSignedIn) {
442             $user->_authhow = 'signin';
443         }
444
445         // Save userid to prefs..
446         if ( empty($this->_user->_prefs)) {
447             $this->_user->_prefs = $this->_user->getPreferences();
448             $this->_prefs =& $this->_user->_prefs;
449         }
450         $this->_user->_group = $this->getGroup();
451         $this->setSessionVar('wiki_user', $user);
452         $this->_prefs->set('userid',
453                            $isSignedIn ? $user->getId() : '');
454         if (!ENABLE_USER_NEW) {
455             if (empty($this->_user->_request))
456                 $this->_user->_request =& $this;
457             if (empty($this->_user->_dbi))
458                 $this->_user->_dbi =& $this->_dbi;
459         }
460         $this->initializeTheme($isSignedIn ? 'login' : 'logout');
461         define('MAIN_setUser', true);
462     }
463
464     /* Permission system */
465     function getLevelDescription($level) {
466         static $levels = false;
467         if (!$levels) // This looks like a Visual Basic hack. For the very same reason. "0"
468             $levels = array('x-1' => _("FORBIDDEN"),
469                             'x0'  => _("ANON"),
470                             'x1'  => _("BOGO"),
471                             'x2'  => _("USER"),
472                             'x10' => _("ADMIN"),
473                             'x100'=> _("UNOBTAINABLE"));
474         if (!empty($level))
475             $level = '0';
476         if (!empty($levels["x".$level]))
477             return $levels["x".$level];
478         else
479             return _("ANON");
480     }
481     
482     function _notAuthorized ($require_level) {
483         // Display the authority message in the Wiki's default
484         // language, in case it is not english.
485         //
486         // Note that normally a user will not see such an error once
487         // logged in, unless the admin has altered the default
488         // disallowed wikiactions. In that case we should probably
489         // check the user's language prefs too at this point; this
490         // would be a situation which is not really handled with the
491         // current code.
492         if (empty($GLOBALS['LANG']))
493             update_locale(DEFAULT_LANGUAGE);
494
495         // User does not have required authority.  Prompt for login.
496         $what = $this->getActionDescription($this->getArg('action'));
497         $pass_required = ($require_level >= WIKIAUTH_USER);
498         if ($require_level == WIKIAUTH_UNOBTAINABLE) {
499             global $DisabledActions;
500             if ($DisabledActions and in_array($action, $DisabledActions)) {
501                 $msg = fmt("%s is disallowed on this wiki.",
502                            $this->getDisallowedActionDescription($this->getArg('action')));
503                 $this->finish();
504                 return;
505             }
506             // Is the reason a missing ACL or just wrong user or password?
507             if (class_exists('PagePermission')) {
508                 $user =& $this->_user;
509                 $status = $user->isAuthenticated() ? _("authenticated") : _("not authenticated");
510                 $msg = fmt("%s %s %s is disallowed on this wiki for %s user '%s' (level: %s).",
511                            _("Missing PagePermission:"),
512                            action2access($this->getArg('action')),
513                            $this->getArg('pagename'),
514                            $status, $user->getId(), $this->getLevelDescription($user->_level));
515                 // TODO: add link to action=setacl
516                 $user->PrintLoginForm($this, compact('pass_required'), $msg);
517                 $this->finish();
518                 return;
519             } else {
520                 $msg = fmt("%s is disallowed on this wiki.",
521                            $this->getDisallowedActionDescription($this->getArg('action')));
522                 $this->_user->PrintLoginForm($this, compact('require_level','pass_required'), $msg);
523                 $this->finish();
524                 return;
525             }
526         }
527         elseif ($require_level == WIKIAUTH_BOGO)
528             $msg = fmt("You must sign in to %s.", $what);
529         elseif ($require_level == WIKIAUTH_USER) {
530             // LoginForm should display the relevant messages...
531             $msg = "";
532             /*if (!ALLOW_ANON_USER)
533                 $msg = fmt("You must log in first to %s", $what);
534             else        
535                 $msg = fmt("You must log in to %s.", $what);
536             */
537         } elseif ($require_level == WIKIAUTH_ANON)
538             $msg = fmt("Access for you is forbidden to %s.", $what);
539         else
540             $msg = fmt("You must be an administrator to %s.", $what);
541
542         $this->_user->PrintLoginForm($this, compact('require_level','pass_required'), 
543                                      $msg);
544         if (!$GLOBALS['WikiTheme']->DUMP_MODE)
545             $this->finish();    // NORETURN
546     }
547
548     // Fixme: for PagePermissions we'll need other strings, 
549     // relevant to the requested page, not just for the action on the whole wiki.
550     function getActionDescription($action) {
551         static $actionDescriptions;
552         if (! $actionDescriptions) {
553             $actionDescriptions
554             = array('browse'     => _("view this page"),
555                     'diff'       => _("diff this page"),
556                     'dumphtml'   => _("dump html pages"),
557                     'dumpserial' => _("dump serial pages"),
558                     'edit'       => _("edit this page"),
559                     'rename'     => _("rename this page"),
560                     'revert'     => _("revert to a previous version of this page"),
561                     'create'     => _("create this page"),
562                     'loadfile'   => _("load files into this wiki"),
563                     'lock'       => _("lock this page"),
564                     'purge'      => _("purge this page"),
565                     'remove'     => _("remove this page"),
566                     'unlock'     => _("unlock this page"),
567                     'upload'     => _("upload a zip dump"),
568                     'verify'     => _("verify the current action"),
569                     'viewsource' => _("view the source of this page"),
570                     'xmlrpc'     => _("access this wiki via XML-RPC"),
571                     'soap'       => _("access this wiki via SOAP"),
572                     'zip'        => _("download a zip dump from this wiki"),
573                     'ziphtml'    => _("download a html zip dump from this wiki")
574                     );
575         }
576         if (in_array($action, array_keys($actionDescriptions)))
577             return $actionDescriptions[$action];
578         else
579             return _("use")." ".$action;
580     }
581     
582     /**
583      TODO: check against these cases:
584         if ($DisabledActions and in_array($action, $DisabledActions))
585             return WIKIAUTH_UNOBTAINABLE;
586
587         if (ENABLE_PAGEPERM and class_exists("PagePermission")) {
588            return requiredAuthorityForPage($action);
589            
590 => Browsing pages is disallowed on this wiki for authenticated user 'rurban' (level: BOGO).
591     */
592     function getDisallowedActionDescription($action) {
593         static $disallowedActionDescriptions;
594         
595         if (! $disallowedActionDescriptions) {
596             $disallowedActionDescriptions
597             = array('browse'     => _("Browsing pages"),
598                     'diff'       => _("Diffing pages"),
599                     'dumphtml'   => _("Dumping html pages"),
600                     'dumpserial' => _("Dumping serial pages"),
601                     'edit'       => _("Editing pages"),
602                     'revert'     => _("Reverting to a previous version of pages"),
603                     'create'     => _("Creating pages"),
604                     'loadfile'   => _("Loading files"),
605                     'lock'       => _("Locking pages"),
606                     'purge'      => _("Purging pages"),
607                     'remove'     => _("Removing pages"),
608                     'unlock'     => _("Unlocking pages"),
609                     'upload'     => _("Uploading zip dumps"),
610                     'verify'     => _("Verify the current action"),
611                     'viewsource' => _("Viewing the source of pages"),
612                     'xmlrpc'     => _("XML-RPC access"),
613                     'soap'       => _("SOAP access"),
614                     'zip'        => _("Downloading zip dumps"),
615                     'ziphtml'    => _("Downloading html zip dumps")
616                     );
617         }
618         if (in_array($action, array_keys($disallowedActionDescriptions)))
619             return $disallowedActionDescriptions[$action];
620         else
621             return $action;
622     }
623
624     function requiredAuthority ($action) {
625         $auth = $this->requiredAuthorityForAction($action);
626         if (!ALLOW_ANON_USER) return WIKIAUTH_USER;
627         
628         /*
629          * This is a hook for plugins to require authority
630          * for posting to them.
631          *
632          * IMPORTANT: This is not a secure check, so the plugin
633          * may not assume that any POSTs to it are authorized.
634          * All this does is cause PhpWiki to prompt for login
635          * if the user doesn't have the required authority.
636          */
637         if ($this->isPost()) {
638             $post_auth = $this->getArg('require_authority_for_post');
639             if ($post_auth !== false)
640                 $auth = max($auth, $post_auth);
641         }
642         return $auth;
643     }
644         
645     function requiredAuthorityForAction ($action) {
646         global $DisabledActions;
647         
648         if ($DisabledActions and in_array($action, $DisabledActions))
649             return WIKIAUTH_UNOBTAINABLE;
650             
651         if (ENABLE_PAGEPERM and class_exists("PagePermission")) {
652            return requiredAuthorityForPage($action);
653         } else {
654           // FIXME: clean up. 
655           switch ($action) {
656             case 'browse':
657             case 'viewsource':
658             case 'diff':
659             case 'select':
660             case 'search':
661             case 'pdf':
662             case 'captcha':
663             case 'wikitohtml':
664             case 'setpref':
665                 return WIKIAUTH_ANON;
666
667             case 'xmlrpc':
668             case 'soap':
669             case 'dumphtml':
670                 if (INSECURE_ACTIONS_LOCALHOST_ONLY and !is_localhost())
671                     return WIKIAUTH_ADMIN;
672                 return WIKIAUTH_ANON;
673
674             case 'ziphtml':
675                 if (ZIPDUMP_AUTH)
676                     return WIKIAUTH_ADMIN;
677                 if (INSECURE_ACTIONS_LOCALHOST_ONLY and !is_localhost())
678                     return WIKIAUTH_ADMIN;
679                 return WIKIAUTH_ANON;
680
681             case 'dumpserial':
682                 if (INSECURE_ACTIONS_LOCALHOST_ONLY and is_localhost())
683                     return WIKIAUTH_ANON;
684                 return WIKIAUTH_ADMIN;
685
686             case 'zip':
687                 if (ZIPDUMP_AUTH)
688                     return WIKIAUTH_ADMIN;
689                 return WIKIAUTH_ANON;
690
691             case 'edit':
692             case 'revert':
693             case 'rename':
694                 if (defined('REQUIRE_SIGNIN_BEFORE_EDIT') && REQUIRE_SIGNIN_BEFORE_EDIT)
695                     return WIKIAUTH_BOGO;
696                 return WIKIAUTH_ANON;
697                 // return WIKIAUTH_BOGO;
698
699             case 'create':
700                 $page = $this->getPage();
701                 $current = $page->getCurrentRevision();
702                 if ($current->hasDefaultContents())
703                     return $this->requiredAuthorityForAction('edit');
704                 return $this->requiredAuthorityForAction('browse');
705
706             case 'upload':
707             case 'loadfile':
708             case 'purge':
709             case 'remove':
710             case 'lock':
711             case 'unlock':
712             case 'upgrade':
713             case 'chown':
714             case 'setacl':
715                 return WIKIAUTH_ADMIN;
716
717             /* authcheck occurs only in the plugin.
718                required actionpage RateIt */
719             /*
720             case 'rate':
721             case 'delete_rating':
722                 // Perhaps this should be WIKIAUTH_USER
723                 return WIKIAUTH_BOGO;
724             */
725
726             default:
727                 global $WikiNameRegexp;
728                 if (preg_match("/$WikiNameRegexp\Z/A", $action))
729                     return WIKIAUTH_ANON; // ActionPage.
730                 else
731                     return WIKIAUTH_ADMIN;
732           }
733         }
734     }
735     /* End of Permission system */
736
737     function possiblyDeflowerVirginWiki () {
738         if ($this->getArg('action') != 'browse')
739             return;
740         if ($this->getArg('pagename') != HOME_PAGE)
741             return;
742
743         $page = $this->getPage();
744         $current = $page->getCurrentRevision();
745         if ($current->getVersion() > 0)
746             return;             // Homepage exists.
747
748         include_once('lib/loadsave.php');
749         $this->setArg('action', 'loadfile');
750         SetupWiki($this);
751         $this->finish();        // NORETURN
752     }
753     
754     // [574ms] mainly template:printexpansion: 393ms and template::expandsubtemplate [100+70+60ms]
755     function handleAction () {
756         $action = $this->getArg('action');
757         if ($this->isPost()  
758             and !$this->_user->isAdmin()
759             and $action != 'browse' 
760             and $action != 'wikitohtml' 
761             )
762         {
763             $page = $this->getPage();
764             if ( $page->get('moderation') ) {
765                 require_once("lib/WikiPlugin.php");
766                 $loader = new WikiPluginLoader();
767                 $plugin = $loader->getPlugin("ModeratedPage");
768                 if ($plugin->handler($this, $page)) {
769                     $CONTENT = HTML::div
770                         (
771                          array('class' => 'wiki-edithelp'),
772                          fmt("%s: action forwarded to a moderator.", 
773                              $action), 
774                          HTML::br(),
775                          _("This action requires moderator approval. Please be patient."));
776                     if (!empty($plugin->_tokens['CONTENT']))
777                         $plugin->_tokens['CONTENT']->pushContent
778                             (
779                              HTML::br(),
780                              _("You must wait for moderator approval."));
781                     else
782                         $plugin->_tokens['CONTENT'] = $CONTENT;
783                     require_once("lib/Template.php");
784                     $title = WikiLink($page->getName());
785                     $title->pushContent(' : ', WikiLink(_("ModeratedPage")));
786                     GeneratePage(Template('browse', $plugin->_tokens), 
787                                  $title,
788                                  $page->getCurrentRevision());
789                     $this->finish();
790                 }
791             }
792         }
793         $method = "action_$action";
794         if (method_exists($this, $method)) {
795             $this->{$method}();
796         }
797         elseif ($page = $this->findActionPage($action)) {
798             $this->actionpage($page);
799         }
800         else {
801             $this->finish(fmt("%s: Bad action", $action));
802         }
803     }
804     
805     function finish ($errormsg = false) {
806         static $in_exit = 0;
807
808         if ($in_exit)
809             exit();        // just in case CloseDataBase calls us
810         $in_exit = true;
811
812         global $ErrorManager;
813         $ErrorManager->flushPostponedErrors();
814
815         if (!empty($errormsg)) {
816             PrintXML(HTML::br(),
817                      HTML::hr(),
818                      HTML::h2(_("Fatal PhpWiki Error")),
819                      $errormsg);
820             // HACK:
821             echo "\n</body></html>";
822         }
823         if (is_object($this->_user)) {
824             $this->_user->page   = $this->getArg('pagename');
825             $this->_user->action = $this->getArg('action');
826             unset($this->_user->_HomePagehandle);
827             unset($this->_user->_auth_dbi);
828             unset($this->_user->_dbi);
829             unset($this->_user->_request);
830         }
831         Request::finish();
832         exit;
833     }
834
835     /**
836      * Generally pagename is rawurlencoded for older browsers or mozilla.
837      * Typing a pagename into the IE bar will utf-8 encode it, so we have to 
838      * fix that with fixTitleEncoding().
839      * If USE_PATH_INFO = true, the pagename is stripped from the "/DATA_PATH/PageName&arg=value" line.
840      * If false, we support either "/index.php?pagename=PageName&arg=value",
841      * or the first arg (1.2.x style): "/index.php?PageName&arg=value"
842      */
843     function _deducePagename () {
844         if (trim(rawurldecode($this->getArg('pagename'))))
845             return fixTitleEncoding(rawurldecode($this->getArg('pagename')));
846
847         if (USE_PATH_INFO) {
848             $pathinfo = $this->get('PATH_INFO');
849             if (empty($pathinfo)) { // fix for CGI
850                 $path = $this->get('REQUEST_URI');
851                 $script = $this->get('SCRIPT_NAME');
852                 $pathinfo = substr($path,strlen($script));
853                 $pathinfo = preg_replace('/\?.+$/','',$pathinfo);
854             }
855             $tail = substr($pathinfo, strlen(PATH_INFO_PREFIX));
856
857             if (trim($tail) != '' and $pathinfo == PATH_INFO_PREFIX . $tail) {
858                 return fixTitleEncoding($tail);
859             }
860         }
861         elseif ($this->isPost()) {
862             /*
863              * In general, for security reasons, HTTP_GET_VARS should be ignored
864              * on POST requests, but we make an exception here (only for pagename).
865              *
866              * The justification for this hack is the following
867              * asymmetry: When POSTing with USE_PATH_INFO set, the
868              * pagename can (and should) be communicated through the
869              * request URL via PATH_INFO.  When POSTing with
870              * USE_PATH_INFO off, this cannot be done --- the only way
871              * to communicate the pagename through the URL is via
872              * QUERY_ARGS (HTTP_GET_VARS).
873              */
874             global $HTTP_GET_VARS;
875             if (isset($HTTP_GET_VARS['pagename']) and trim($HTTP_GET_VARS['pagename'])) { 
876                 return fixTitleEncoding(rawurldecode($HTTP_GET_VARS['pagename']));
877             }
878         }
879
880         /*
881          * Support for PhpWiki 1.2 style requests.
882          * Strip off "&" args (?PageName&action=...&start_debug,...)
883          */
884         $query_string = $this->get('QUERY_STRING');
885         if (trim(rawurldecode($query_string)) and preg_match('/^([^&=]+)(&.+)?$/', $query_string, $m)) {
886             return fixTitleEncoding(rawurldecode($m[1]));
887         }
888
889         return fixTitleEncoding(HOME_PAGE);
890     }
891
892     function _deduceAction () {
893         if (!($action = $this->getArg('action'))) {
894             // TODO: improve this SOAP.php hack by letting SOAP use index.php 
895             // or any other virtual url as with xmlrpc
896             if (defined('WIKI_SOAP') and WIKI_SOAP)
897                 return 'soap';
898             // Detect XML-RPC requests.
899             if ($this->isPost()
900                 && ($this->get('CONTENT_TYPE') == 'text/xml' 
901                     or $this->get('CONTENT_TYPE') == 'application/xml')
902                 && strstr($GLOBALS['HTTP_RAW_POST_DATA'], '<methodCall>')
903                )
904             {
905                 return 'xmlrpc';
906             }
907             return 'browse';    // Default if no action specified.
908         }
909
910         if (method_exists($this, "action_$action"))
911             return $action;
912
913         // Allow for, e.g. action=LikePages
914         if ($this->isActionPage($action))
915             return $action;
916
917         // Handle untranslated actionpages in non-english
918         // (people playing with switching languages)
919         if (0 and $GLOBALS['LANG'] != 'en') {
920             require_once("lib/plugin/_WikiTranslation.php");
921             $trans = new WikiPlugin__WikiTranslation();
922             $en_action = $trans->translate($action,'en',$GLOBALS['LANG']);
923             if ($this->isActionPage($en_action))
924                 return $en_action;
925         }
926
927         trigger_error("$action: Unknown action", E_USER_NOTICE);
928         return 'browse';
929     }
930
931     function _deduceUsername() {
932         global $HTTP_SERVER_VARS, $HTTP_ENV_VARS;
933
934         if (!empty($this->args['auth']) and !empty($this->args['auth']['userid']))
935             return $this->args['auth']['userid'];
936
937         if ($user = $this->getSessionVar('wiki_user')) {
938             // Switched auth between sessions. 
939             // Note: There's no way to demandload a missing class-definition 
940             // afterwards! Stupid php.
941             if (isa($user, WikiUserClassname())) {
942                 $this->_user = $user;
943                 $this->_user->_authhow = 'session';
944                 return ENABLE_USER_NEW ? $user->UserName() : $this->_user;
945             }
946         }
947
948         // Sessions override http auth
949         if (!empty($HTTP_SERVER_VARS['PHP_AUTH_USER']))
950             return $HTTP_SERVER_VARS['PHP_AUTH_USER'];
951         // pubcookie et al
952         if (!empty($HTTP_SERVER_VARS['REMOTE_USER']))
953             return $HTTP_SERVER_VARS['REMOTE_USER'];
954         if (!empty($HTTP_ENV_VARS['REMOTE_USER']))
955             return $HTTP_ENV_VARS['REMOTE_USER'];
956
957         if ($userid = $this->getCookieVar(getCookieName())) {
958             if (!empty($userid) and substr($userid,0,2) != 's:') {
959                 $this->_user->authhow = 'cookie';
960                 return $userid;
961             }
962         }
963
964         if ($this->getArg('action') == 'xmlrpc') { // how about SOAP?
965             if (empty($GLOBALS['HTTP_RAW_POST_DATA']))
966                 trigger_error("Wrong always_populate_raw_post_data = Off setting in your php.ini\nCannot use xmlrpc!", E_USER_ERROR);
967             // wiki.putPage has special otional userid/passwd arguments. check that later.
968             $userid = '';
969             if (isset($HTTP_SERVER_VARS['REMOTE_USER']))
970                 $userid = $HTTP_SERVER_VARS['REMOTE_USER'];
971             elseif (isset($HTTP_SERVER_VARS['REMOTE_ADDR']))
972                 $userid = $HTTP_SERVER_VARS['REMOTE_ADDR'];
973             elseif (isset($HTTP_ENV_VARS['REMOTE_ADDR']))
974                 $userid = $HTTP_ENV_VARS['REMOTE_ADDR'];
975             elseif (isset($GLOBALS['REMOTE_ADDR']))
976                 $userid = $GLOBALS['REMOTE_ADDR'];
977             return $userid;
978         }
979
980         return false;
981     }
982     
983     function _isActionPage ($pagename, $verbose = true) {
984
985         global $AllActionPages;
986  
987         return (in_array($pagename, $AllActionPages));
988     }
989
990     function findActionPage ($action) {
991         static $cache;
992         if (!$action) return false;
993
994         // check for translated version, as per users preferred language
995         // (or system default in case it is not en)
996         $translation = gettext($action);
997
998         if (isset($cache) and isset($cache[$translation]))
999             return $cache[$translation];
1000
1001         // check for cached translated version
1002         if ($translation and $this->_isActionPage($translation, false))
1003             return $cache[$action] = $translation;
1004
1005         // Allow for, e.g. action=LikePages
1006         if (!isWikiWord($action))
1007             return $cache[$action] = false;
1008
1009         // check for translated version (default language)
1010         global $LANG;
1011         if ($LANG != "en") {
1012             require_once("lib/WikiPlugin.php");
1013             require_once("lib/plugin/_WikiTranslation.php");
1014             $trans = new WikiPlugin__WikiTranslation();
1015             $trans->lang = $LANG;
1016             $default = $trans->translate_to_en($action, $LANG);
1017             if ($default and $this->_isActionPage($default, false))
1018                 return $cache[$action] = $default;
1019         } else {
1020             $default = $translation;
1021         }
1022         
1023         // check for english version
1024         if ($action != $translation and $action != $default) {
1025             if ($this->_isActionPage($action))
1026                 return $cache[$action] = $action;
1027         }
1028
1029         trigger_error("$action: Cannot find action page", E_USER_NOTICE);
1030         return $cache[$action] = false;
1031     }
1032     
1033     function isActionPage ($pagename) {
1034         return $this->findActionPage($pagename);
1035     }
1036
1037     function action_browse () {
1038         $this->buffer_output();
1039         include_once("lib/display.php");
1040         displayPage($this);
1041     }
1042
1043     function action_verify () {
1044         $this->action_browse();
1045     }
1046
1047     function actionpage ($action) {
1048         $this->buffer_output();
1049         include_once("lib/display.php");
1050         actionPage($this, $action);
1051     }
1052
1053     function adminActionSubpage ($subpage) {
1054         $page = _("PhpWikiAdministration")."/".$subpage;
1055         $action = $this->findActionPage($page);
1056         if ($action) {
1057             if (!$this->getArg('s'))
1058                 $this->setArg('s', $this->getArg('pagename'));
1059             $this->setArg('verify',1);
1060             if ($this->getArg('action') != 'rename')
1061                 $this->setArg('action',  $action);
1062             $this->actionpage($action);
1063         } else {
1064             trigger_error($page.": Cannot find action page", E_USER_WARNING);
1065         }
1066     }
1067
1068     function action_chown () {
1069         $this->adminActionSubpage(_("Chown"));
1070     }
1071
1072     function action_setacl () {
1073         $this->adminActionSubpage(_("SetAcl"));
1074     }
1075
1076     function action_rename () {
1077         $this->adminActionSubpage(_("Rename"));
1078     }
1079
1080     function action_dump () {
1081         $action = $this->findActionPage(_("PageDump"));
1082         if ($action) {
1083             $this->actionpage($action);
1084         } else {
1085             // redirect to action=upgrade if admin?
1086             trigger_error(_("PageDump").": Cannot find action page", E_USER_WARNING);
1087         }
1088     }
1089
1090     function action_diff () {
1091         $this->buffer_output();
1092         include_once "lib/diff.php";
1093         showDiff($this);
1094     }
1095
1096     function action_search () {
1097         // Decide between title or fulltextsearch (e.g. both buttons available).
1098         // Reformulate URL and redirect.
1099         $searchtype = $this->getArg('searchtype');
1100         $args = array('s' => $this->getArg('searchterm') 
1101                                ? $this->getArg('searchterm') 
1102                                : $this->getArg('s'));
1103         if ($searchtype == 'full' or $searchtype == 'fulltext') {
1104             $search_page = _("FullTextSearch");
1105         }
1106         elseif ($searchtype == 'external') {
1107             $s = $args['s'];
1108             $link = new WikiPageName("Search:$s"); // Expand interwiki url. I use xapian-omega
1109             $this->redirect($link->url);
1110         }
1111         else {
1112             $search_page = _("TitleSearch");
1113             $args['auto_redirect'] = 1;
1114         }
1115         $this->redirect(WikiURL($search_page, $args, 'absolute_url'));
1116     }
1117
1118     function action_edit () {
1119         $this->buffer_output();
1120         include "lib/editpage.php";
1121         $e = new PageEditor ($this);
1122         $e->editPage();
1123     }
1124
1125     function action_create () {
1126         $this->action_edit();
1127     }
1128     
1129     function action_viewsource () {
1130         $this->buffer_output();
1131         include "lib/editpage.php";
1132         $e = new PageEditor ($this);
1133         $e->viewSource();
1134     }
1135
1136     function action_lock () {
1137         $page = $this->getPage();
1138         $page->set('locked', true);
1139         $this->_dbi->touch();
1140         // check ModeratedPage hook
1141         if ($moderated = $page->get('moderation')) {
1142             require_once("lib/WikiPlugin.php");
1143             $plugin = WikiPluginLoader::getPlugin("ModeratedPage");
1144             if ($retval = $plugin->lock_check($this, $page, $moderated))
1145                 $this->setArg('errormsg', $retval);
1146         } 
1147         // check if a link to ModeratedPage exists
1148         elseif ($action_page = $page->existLink(_("ModeratedPage"))) {
1149             require_once("lib/WikiPlugin.php");
1150             $plugin = WikiPluginLoader::getPlugin("ModeratedPage");
1151             if ($retval = $plugin->lock_add($this, $page, $action_page))
1152                 $this->setArg('errormsg', $retval);
1153         }
1154         $this->action_browse();
1155     }
1156
1157     function action_unlock () {
1158         $page = $this->getPage();
1159         $page->set('locked', false);
1160         $this->_dbi->touch();
1161         $this->action_browse();
1162     }
1163
1164     function action_purge () {
1165         $pagename = $this->getArg('pagename');
1166         if (strstr($pagename, _("PhpWikiAdministration"))) {
1167             $this->action_browse();
1168         } else {
1169             include('lib/purgepage.php');
1170             PurgePage($this);
1171         }
1172     }
1173
1174     function action_remove () {
1175         // This check is now redundant.
1176         //$user->requireAuth(WIKIAUTH_ADMIN);
1177         $pagename = $this->getArg('pagename');
1178         if (strstr($pagename, _("PhpWikiAdministration"))) {
1179             $this->action_browse();
1180         } else {
1181             include('lib/removepage.php');
1182             RemovePage($this);
1183         }
1184     }
1185
1186     function action_xmlrpc () {
1187         include_once("lib/XmlRpcServer.php");
1188         $xmlrpc = new XmlRpcServer($this);
1189         $xmlrpc->service();
1190     }
1191     
1192     function action_soap () {
1193         if (defined("WIKI_SOAP") and WIKI_SOAP) // already loaded
1194             return;
1195         /*
1196           allow VIRTUAL_PATH or action=soap SOAP access
1197          */
1198         include_once("SOAP.php");
1199     }
1200
1201     function action_revert () {
1202         include_once "lib/loadsave.php";
1203         RevertPage($this);
1204     }
1205
1206     function action_zip () {
1207         include_once("lib/loadsave.php");
1208         MakeWikiZip($this);
1209         // I don't think it hurts to add cruft at the end of the zip file.
1210         //echo "\n========================================================\n";
1211         //echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
1212     }
1213
1214     function action_ziphtml () {
1215         include_once("lib/loadsave.php");
1216         MakeWikiZipHtml($this);
1217         // I don't think it hurts to add cruft at the end of the zip file.
1218         echo "\n========================================================\n";
1219         echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
1220     }
1221
1222     function action_dumpserial () {
1223         include_once("lib/loadsave.php");
1224         DumpToDir($this);
1225     }
1226
1227     function action_dumphtml () {
1228         include_once("lib/loadsave.php");
1229         DumpHtmlToDir($this);
1230     }
1231
1232     function action_upload () {
1233         include_once("lib/loadsave.php");
1234         LoadPostFile($this);
1235     }
1236
1237     function action_upgrade () {
1238         include_once("lib/loadsave.php");
1239         include_once("lib/upgrade.php");
1240         DoUpgrade($this);
1241     }
1242
1243     function action_loadfile () {
1244         include_once("lib/loadsave.php");
1245         LoadFileOrDir($this);
1246     }
1247
1248     function action_pdf () {
1249         include_once("lib/pdf.php");
1250         ConvertAndDisplayPdf($this);
1251     }
1252
1253     function action_captcha () {
1254         include_once "lib/Captcha.php";
1255         $captcha = new Captcha();
1256         $captcha->image ( $captcha->captchaword() ); 
1257     }
1258     
1259     function action_wikitohtml () {
1260        include_once("lib/WysiwygEdit/Wikiwyg.php");
1261        $wikitohtml = new WikiToHtml( $this->getArg("content") , $this);
1262        $wikitohtml->send();
1263     }
1264
1265     function action_setpref () {
1266         $what = $this->getArg('pref');
1267         $value = $this->getArg('value');
1268         $prefs =& $this->_user->_prefs;
1269         $prefs->set($what, $value);
1270         $num = $this->_user->setPreferences($prefs);
1271     }
1272 }
1273
1274 //FIXME: deprecated with ENABLE_PAGEPERM (?)
1275 function is_safe_action ($action) {
1276     global $request;
1277     return $request->requiredAuthorityForAction($action) < WIKIAUTH_ADMIN;
1278 }
1279
1280 function validateSessionPath() {
1281     // Try to defer any session.save_path PHP errors before any html
1282     // is output, which causes some versions of IE to display a blank
1283     // page (due to its strict mode while parsing a page?).
1284     if (! is_writeable(ini_get('session.save_path'))) {
1285         $tmpdir = (defined('SESSION_SAVE_PATH') and SESSION_SAVE_PATH) ? SESSION_SAVE_PATH : '/tmp';
1286         if (!is_writeable($tmpdir))
1287             $tmpdir = '/tmp';
1288         trigger_error
1289             (sprintf(_("%s is not writable."),
1290                      _("The session.save_path directory"))
1291              . "\n"
1292              . sprintf(_("Please ensure that %s is writable, or redefine %s in config/config.ini."),
1293                        sprintf(_("the session.save_path directory '%s'"),
1294                                ini_get('session.save_path')),
1295                        'SESSION_SAVE_PATH')
1296              . "\n"
1297              . sprintf(_("Attempting to use the directory '%s' instead."),
1298                        $tmpdir)
1299              , E_USER_NOTICE);
1300         if (! is_writeable($tmpdir)) {
1301             trigger_error
1302                 (sprintf(_("%s is not writable."), $tmpdir)
1303                  . "\n"
1304                  . _("Users will not be able to sign in.")
1305                  , E_USER_NOTICE);
1306         }
1307         else
1308             @ini_set('session.save_path', $tmpdir);
1309     }
1310 }
1311
1312 function main () {
1313     if ( !USE_DB_SESSION )
1314         validateSessionPath();
1315
1316     global $request;
1317     if ((DEBUG & _DEBUG_APD) and extension_loaded("apd")) { 
1318         //apd_set_session_trace(9);
1319         apd_set_pprof_trace();
1320     }
1321
1322     // Postpone warnings
1323     global $ErrorManager;
1324     if (defined('E_STRICT')) // and (E_ALL & E_STRICT)) // strict php5?
1325         $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE|E_USER_WARNING|E_WARNING|E_STRICT);
1326     else
1327         $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE|E_USER_WARNING|E_WARNING);
1328     $request = new WikiRequest();
1329
1330     $action = $request->getArg('action');
1331     if (substr($action, 0, 3) != 'zip') {
1332         if ($action == 'pdf')
1333             $ErrorManager->setPostponedErrorMask(-1); // everything
1334         //else // reject postponing of warnings
1335         //    $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE);
1336     }
1337
1338     /*
1339      * Allow for disabling of markup cache.
1340      * (Mostly for debugging ... hopefully.)
1341      *
1342      * See also <?plugin WikiAdminUtils action=purge-cache ?>
1343      */
1344     if (!defined('WIKIDB_NOCACHE_MARKUP')) {
1345         if ($request->getArg('nocache')) // 1 or purge
1346             define('WIKIDB_NOCACHE_MARKUP', $request->getArg('nocache'));
1347         else
1348             define('WIKIDB_NOCACHE_MARKUP', false); // redundant, but explicit
1349     }
1350     
1351     // Initialize with system defaults in case user not logged in.
1352     // Should this go into the constructor?
1353     $request->initializeTheme('default');
1354     $request->updateAuthAndPrefs();
1355     $request->initializeLang();
1356     
1357     //FIXME:
1358     //if ($user->is_authenticated())
1359     //  $LogEntry->user = $user->getId();
1360
1361     // Memory optimization:
1362     // http://www.procata.com/blog/archives/2004/05/27/rephlux-and-php-memory-usage/
1363     // kill the global PEAR _PEAR_destructor_object_list
1364     if (!empty($_PEAR_destructor_object_list))
1365         $_PEAR_destructor_object_list = array();
1366     $request->possiblyDeflowerVirginWiki();
1367     
1368     $validators = array('wikiname' => WIKI_NAME,
1369                         'args'     => wikihash($request->getArgs()),
1370                         'prefs'    => wikihash($request->getPrefs()));
1371     if (CACHE_CONTROL == 'STRICT') {
1372         $dbi = $request->getDbh();
1373         $timestamp = $dbi->getTimestamp();
1374         $validators['mtime'] = $timestamp;
1375         $validators['%mtime'] = (int)$timestamp;
1376     }
1377     // FIXME: we should try to generate strong validators when possible,
1378     // but for now, our validator is weak, since equal validators do not
1379     // indicate byte-level equality of content.  (Due to DEBUG timing output, etc...)
1380     //
1381     // (If DEBUG if off, this may be a strong validator, but I'm going
1382     // to go the paranoid route here pending further study and testing.)
1383     // access hits and edit stats in the footer violate strong ETags also. 
1384     if (1 or DEBUG) {
1385         $validators['%weak'] = true;
1386     }
1387     $request->setValidators($validators);
1388    
1389     $request->handleAction();
1390
1391     if (DEBUG and DEBUG & _DEBUG_INFO) phpinfo(INFO_VARIABLES | INFO_MODULES);
1392     $request->finish();
1393 }
1394
1395 //$x = error_reporting();  // DEBUG: why is it 1 here? should be E_ALL
1396 if (defined('E_STRICT') and (E_ALL & E_STRICT)) // strict php5?
1397     error_reporting(E_ALL & ~E_STRICT);         // exclude E_STRICT
1398 else
1399     error_reporting(E_ALL); // php4
1400 // don't run the main loop for special requests (test, getimg, xmlrpc, soap, ...)
1401 if (!defined('PHPWIKI_NOMAIN') or !PHPWIKI_NOMAIN)
1402     main();
1403
1404 // Local Variables:
1405 // mode: php
1406 // tab-width: 8
1407 // c-basic-offset: 4
1408 // c-hanging-comment-ender-p: nil
1409 // indent-tabs-mode: nil
1410 // End:
1411 ?>