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