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