]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/main.php
Partial revert: put renaming in page history
[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                 && ((defined("WIKI_XMLRPC") and WIKI_XMLRPC)
902                     or ($this->get('CONTENT_TYPE') == 'text/xml' 
903                         or $this->get('CONTENT_TYPE') == 'application/xml')
904                     && strstr($GLOBALS['HTTP_RAW_POST_DATA'], '<methodCall>'))
905                )
906             {
907                 return 'xmlrpc';
908             }
909             return 'browse';    // Default if no action specified.
910         }
911
912         if (method_exists($this, "action_$action"))
913             return $action;
914
915         // Allow for, e.g. action=LikePages
916         if ($this->isActionPage($action))
917             return $action;
918
919         // Handle untranslated actionpages in non-english
920         // (people playing with switching languages)
921         if (0 and $GLOBALS['LANG'] != 'en') {
922             require_once("lib/plugin/_WikiTranslation.php");
923             $trans = new WikiPlugin__WikiTranslation();
924             $en_action = $trans->translate($action,'en',$GLOBALS['LANG']);
925             if ($this->isActionPage($en_action))
926                 return $en_action;
927         }
928
929         trigger_error("$action: Unknown action", E_USER_NOTICE);
930         return 'browse';
931     }
932
933     function _deduceUsername() {
934         global $HTTP_SERVER_VARS, $HTTP_ENV_VARS;
935
936         if (!empty($this->args['auth']) and !empty($this->args['auth']['userid']))
937             return $this->args['auth']['userid'];
938
939         if ($user = $this->getSessionVar('wiki_user')) {
940             // Switched auth between sessions. 
941             // Note: There's no way to demandload a missing class-definition 
942             // afterwards! Stupid php.
943             if (isa($user, WikiUserClassname())) {
944                 $this->_user = $user;
945                 $this->_user->_authhow = 'session';
946                 return ENABLE_USER_NEW ? $user->UserName() : $this->_user;
947             }
948         }
949
950         // Sessions override http auth
951         if (!empty($HTTP_SERVER_VARS['PHP_AUTH_USER']))
952             return $HTTP_SERVER_VARS['PHP_AUTH_USER'];
953         // pubcookie et al
954         if (!empty($HTTP_SERVER_VARS['REMOTE_USER']))
955             return $HTTP_SERVER_VARS['REMOTE_USER'];
956         if (!empty($HTTP_ENV_VARS['REMOTE_USER']))
957             return $HTTP_ENV_VARS['REMOTE_USER'];
958
959         if ($userid = $this->getCookieVar(getCookieName())) {
960             if (!empty($userid) and substr($userid,0,2) != 's:') {
961                 $this->_user->authhow = 'cookie';
962                 return $userid;
963             }
964         }
965
966         if ($this->getArg('action') == 'xmlrpc') { // how about SOAP?
967             if (empty($GLOBALS['HTTP_RAW_POST_DATA']))
968                 trigger_error("Wrong always_populate_raw_post_data = Off setting in your php.ini\nCannot use xmlrpc!", E_USER_ERROR);
969             // wiki.putPage has special otional userid/passwd arguments. check that later.
970             $userid = '';
971             if (isset($HTTP_SERVER_VARS['REMOTE_USER']))
972                 $userid = $HTTP_SERVER_VARS['REMOTE_USER'];
973             elseif (isset($HTTP_SERVER_VARS['REMOTE_ADDR']))
974                 $userid = $HTTP_SERVER_VARS['REMOTE_ADDR'];
975             elseif (isset($HTTP_ENV_VARS['REMOTE_ADDR']))
976                 $userid = $HTTP_ENV_VARS['REMOTE_ADDR'];
977             elseif (isset($GLOBALS['REMOTE_ADDR']))
978                 $userid = $GLOBALS['REMOTE_ADDR'];
979             return $userid;
980         }
981
982         return false;
983     }
984     
985     function _isActionPage ($pagename, $verbose = true) {
986
987         global $AllActionPages;
988  
989         return (in_array($pagename, $AllActionPages));
990     }
991
992     function findActionPage ($action) {
993         static $cache;
994         if (!$action) return false;
995
996         // check for translated version, as per users preferred language
997         // (or system default in case it is not en)
998         $translation = gettext($action);
999
1000         if (isset($cache) and isset($cache[$translation]))
1001             return $cache[$translation];
1002
1003         // check for cached translated version
1004         if ($translation and $this->_isActionPage($translation, false))
1005             return $cache[$action] = $translation;
1006
1007         // Allow for, e.g. action=LikePages
1008         if (!isWikiWord($action))
1009             return $cache[$action] = false;
1010
1011         // check for translated version (default language)
1012         global $LANG;
1013         if ($LANG != "en") {
1014             require_once("lib/WikiPlugin.php");
1015             require_once("lib/plugin/_WikiTranslation.php");
1016             $trans = new WikiPlugin__WikiTranslation();
1017             $trans->lang = $LANG;
1018             $default = $trans->translate_to_en($action, $LANG);
1019             if ($default and $this->_isActionPage($default, false))
1020                 return $cache[$action] = $default;
1021         } else {
1022             $default = $translation;
1023         }
1024         
1025         // check for english version
1026         if ($action != $translation and $action != $default) {
1027             if ($this->_isActionPage($action))
1028                 return $cache[$action] = $action;
1029         }
1030
1031         trigger_error("$action: Cannot find action page", E_USER_NOTICE);
1032         return $cache[$action] = false;
1033     }
1034     
1035     function isActionPage ($pagename) {
1036         return $this->findActionPage($pagename);
1037     }
1038
1039     function action_browse () {
1040         $this->buffer_output();
1041         include_once("lib/display.php");
1042         displayPage($this);
1043     }
1044
1045     function action_verify () {
1046         $this->action_browse();
1047     }
1048
1049     function actionpage ($action) {
1050         $this->buffer_output();
1051         include_once("lib/display.php");
1052         actionPage($this, $action);
1053     }
1054
1055     function adminActionSubpage ($subpage) {
1056         $page = _("PhpWikiAdministration")."/".$subpage;
1057         $action = $this->findActionPage($page);
1058         if ($action) {
1059             if (!$this->getArg('s'))
1060                 $this->setArg('s', $this->getArg('pagename'));
1061             $this->setArg('verify', 1); // only for POST
1062             if ($this->getArg('action') != 'rename')
1063                 $this->setArg('action',  $action);
1064             elseif($this->getArg('to') && empty($this->args['admin_rename'])) {
1065                 $this->args['admin_rename']
1066                   = array('from'   => $this->getArg('s'),
1067                           'to'     => $this->getArg('to'),
1068                           'action' => 'select');
1069             }
1070             $this->actionpage($action);
1071         } else {
1072             trigger_error($page.": Cannot find action page", E_USER_WARNING);
1073         }
1074     }
1075
1076     function action_chown () {
1077         $this->adminActionSubpage(_("Chown"));
1078     }
1079
1080     function action_setacl () {
1081         $this->adminActionSubpage(_("SetAcl"));
1082     }
1083
1084     function action_rename () {
1085         $this->adminActionSubpage(_("Rename"));
1086     }
1087
1088     function action_dump () {
1089         $action = $this->findActionPage(_("PageDump"));
1090         if ($action) {
1091             $this->actionpage($action);
1092         } else {
1093             // redirect to action=upgrade if admin?
1094             trigger_error(_("PageDump").": Cannot find action page", E_USER_WARNING);
1095         }
1096     }
1097
1098     function action_diff () {
1099         $this->buffer_output();
1100         include_once "lib/diff.php";
1101         showDiff($this);
1102     }
1103
1104     function action_search () {
1105         // Decide between title or fulltextsearch (e.g. both buttons available).
1106         // Reformulate URL and redirect.
1107         $searchtype = $this->getArg('searchtype');
1108         $args = array('s' => $this->getArg('searchterm') 
1109                                ? $this->getArg('searchterm') 
1110                                : $this->getArg('s'));
1111         if ($searchtype == 'full' or $searchtype == 'fulltext') {
1112             $search_page = _("FullTextSearch");
1113         }
1114         elseif ($searchtype == 'external') {
1115             $s = $args['s'];
1116             $link = new WikiPageName("Search:$s"); // Expand interwiki url. I use xapian-omega
1117             $this->redirect($link->url);
1118         }
1119         else {
1120             $search_page = _("TitleSearch");
1121             $args['auto_redirect'] = 1;
1122         }
1123         $this->redirect(WikiURL($search_page, $args, 'absolute_url'));
1124     }
1125
1126     function action_edit () {
1127         $this->buffer_output();
1128         include "lib/editpage.php";
1129         $e = new PageEditor ($this);
1130         $e->editPage();
1131     }
1132
1133     function action_create () {
1134         $this->action_edit();
1135     }
1136     
1137     function action_viewsource () {
1138         $this->buffer_output();
1139         include "lib/editpage.php";
1140         $e = new PageEditor ($this);
1141         $e->viewSource();
1142     }
1143
1144     function action_lock () {
1145         $page = $this->getPage();
1146         $page->set('locked', true);
1147         $this->_dbi->touch();
1148         // check ModeratedPage hook
1149         if ($moderated = $page->get('moderation')) {
1150             require_once("lib/WikiPlugin.php");
1151             $plugin = WikiPluginLoader::getPlugin("ModeratedPage");
1152             if ($retval = $plugin->lock_check($this, $page, $moderated))
1153                 $this->setArg('errormsg', $retval);
1154         } 
1155         // check if a link to ModeratedPage exists
1156         elseif ($action_page = $page->existLink(_("ModeratedPage"))) {
1157             require_once("lib/WikiPlugin.php");
1158             $plugin = WikiPluginLoader::getPlugin("ModeratedPage");
1159             if ($retval = $plugin->lock_add($this, $page, $action_page))
1160                 $this->setArg('errormsg', $retval);
1161         }
1162         $this->action_browse();
1163     }
1164
1165     function action_unlock () {
1166         $page = $this->getPage();
1167         $page->set('locked', false);
1168         $this->_dbi->touch();
1169         $this->action_browse();
1170     }
1171
1172     function action_purge () {
1173         $pagename = $this->getArg('pagename');
1174         if (strstr($pagename, _("PhpWikiAdministration"))) {
1175             $this->action_browse();
1176         } else {
1177             include('lib/purgepage.php');
1178             PurgePage($this);
1179         }
1180     }
1181
1182     function action_remove () {
1183         // This check is now redundant.
1184         //$user->requireAuth(WIKIAUTH_ADMIN);
1185         $pagename = $this->getArg('pagename');
1186         if (strstr($pagename, _("PhpWikiAdministration"))) {
1187             $this->action_browse();
1188         } else {
1189             include('lib/removepage.php');
1190             RemovePage($this);
1191         }
1192     }
1193
1194     function action_xmlrpc () {
1195         include_once("lib/XmlRpcServer.php");
1196         $xmlrpc = new XmlRpcServer($this);
1197         $xmlrpc->service();
1198     }
1199     
1200     function action_soap () {
1201         if (defined("WIKI_SOAP") and WIKI_SOAP) // already loaded
1202             return;
1203         /*
1204           allow VIRTUAL_PATH or action=soap SOAP access
1205          */
1206         include_once("SOAP.php");
1207     }
1208
1209     function action_revert () {
1210         include_once "lib/loadsave.php";
1211         RevertPage($this);
1212     }
1213
1214     function action_zip () {
1215         include_once("lib/loadsave.php");
1216         MakeWikiZip($this);
1217         // I don't think it hurts to add cruft at the end of the zip file.
1218         //echo "\n========================================================\n";
1219         //echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
1220     }
1221
1222     function action_ziphtml () {
1223         include_once("lib/loadsave.php");
1224         MakeWikiZipHtml($this);
1225         // I don't think it hurts to add cruft at the end of the zip file.
1226         echo "\n========================================================\n";
1227         echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
1228     }
1229
1230     function action_dumpserial () {
1231         include_once("lib/loadsave.php");
1232         DumpToDir($this);
1233     }
1234
1235     function action_dumphtml () {
1236         include_once("lib/loadsave.php");
1237         DumpHtmlToDir($this);
1238     }
1239
1240     function action_upload () {
1241         include_once("lib/loadsave.php");
1242         LoadPostFile($this);
1243     }
1244
1245     function action_upgrade () {
1246         include_once("lib/loadsave.php");
1247         include_once("lib/upgrade.php");
1248         DoUpgrade($this);
1249     }
1250
1251     function action_loadfile () {
1252         include_once("lib/loadsave.php");
1253         LoadFileOrDir($this);
1254     }
1255
1256     function action_pdf () {
1257         include_once("lib/pdf.php");
1258         ConvertAndDisplayPdf($this);
1259     }
1260
1261     function action_captcha () {
1262         include_once "lib/Captcha.php";
1263         $captcha = new Captcha();
1264         $captcha->image ( $captcha->captchaword() ); 
1265     }
1266     
1267     function action_wikitohtml () {
1268        include_once("lib/WysiwygEdit/Wikiwyg.php");
1269        $wikitohtml = new WikiToHtml( $this->getArg("content") , $this);
1270        $wikitohtml->send();
1271     }
1272
1273     function action_setpref () {
1274         $what = $this->getArg('pref');
1275         $value = $this->getArg('value');
1276         $prefs =& $this->_user->_prefs;
1277         $prefs->set($what, $value);
1278         $num = $this->_user->setPreferences($prefs);
1279     }
1280 }
1281
1282 //FIXME: deprecated with ENABLE_PAGEPERM (?)
1283 function is_safe_action ($action) {
1284     global $request;
1285     return $request->requiredAuthorityForAction($action) < WIKIAUTH_ADMIN;
1286 }
1287
1288 function validateSessionPath() {
1289     // Try to defer any session.save_path PHP errors before any html
1290     // is output, which causes some versions of IE to display a blank
1291     // page (due to its strict mode while parsing a page?).
1292     if (! is_writeable(ini_get('session.save_path'))) {
1293         $tmpdir = (defined('SESSION_SAVE_PATH') and SESSION_SAVE_PATH) ? SESSION_SAVE_PATH : '/tmp';
1294         if (!is_writeable($tmpdir))
1295             $tmpdir = '/tmp';
1296         trigger_error
1297             (sprintf(_("%s is not writable."),
1298                      _("The session.save_path directory"))
1299              . "\n"
1300              . sprintf(_("Please ensure that %s is writable, or redefine %s in config/config.ini."),
1301                        sprintf(_("the session.save_path directory '%s'"),
1302                                ini_get('session.save_path')),
1303                        'SESSION_SAVE_PATH')
1304              . "\n"
1305              . sprintf(_("Attempting to use the directory '%s' instead."),
1306                        $tmpdir)
1307              , E_USER_NOTICE);
1308         if (! is_writeable($tmpdir)) {
1309             trigger_error
1310                 (sprintf(_("%s is not writable."), $tmpdir)
1311                  . "\n"
1312                  . _("Users will not be able to sign in.")
1313                  , E_USER_NOTICE);
1314         }
1315         else
1316             @ini_set('session.save_path', $tmpdir);
1317     }
1318 }
1319
1320 function main () {
1321     if ( !USE_DB_SESSION )
1322         validateSessionPath();
1323
1324     global $request;
1325     if ((DEBUG & _DEBUG_APD) and extension_loaded("apd")) { 
1326         //apd_set_session_trace(9);
1327         apd_set_pprof_trace();
1328     }
1329
1330     // Postpone warnings
1331     global $ErrorManager;
1332     if (defined('E_STRICT')) // and (E_ALL & E_STRICT)) // strict php5?
1333         $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE|E_USER_WARNING|E_WARNING|E_STRICT);
1334     else
1335         $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE|E_USER_WARNING|E_WARNING);
1336     $request = new WikiRequest();
1337
1338     $action = $request->getArg('action');
1339     if (substr($action, 0, 3) != 'zip') {
1340         if ($action == 'pdf')
1341             $ErrorManager->setPostponedErrorMask(-1); // everything
1342         //else // reject postponing of warnings
1343         //    $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE);
1344     }
1345
1346     /*
1347      * Allow for disabling of markup cache.
1348      * (Mostly for debugging ... hopefully.)
1349      *
1350      * See also <<WikiAdminUtils action=purge-cache>>
1351      */
1352     if (!defined('WIKIDB_NOCACHE_MARKUP')) {
1353         if ($request->getArg('nocache')) // 1 or purge
1354             define('WIKIDB_NOCACHE_MARKUP', $request->getArg('nocache'));
1355         else
1356             define('WIKIDB_NOCACHE_MARKUP', false); // redundant, but explicit
1357     }
1358     
1359     // Initialize with system defaults in case user not logged in.
1360     // Should this go into the constructor?
1361     $request->initializeTheme('default');
1362     $request->updateAuthAndPrefs();
1363     $request->initializeLang();
1364     
1365     //FIXME:
1366     //if ($user->is_authenticated())
1367     //  $LogEntry->user = $user->getId();
1368
1369     // Memory optimization:
1370     // http://www.procata.com/blog/archives/2004/05/27/rephlux-and-php-memory-usage/
1371     // kill the global PEAR _PEAR_destructor_object_list
1372     if (!empty($_PEAR_destructor_object_list))
1373         $_PEAR_destructor_object_list = array();
1374     $request->possiblyDeflowerVirginWiki();
1375     
1376     $validators = array('wikiname' => WIKI_NAME,
1377                         'args'     => wikihash($request->getArgs()),
1378                         'prefs'    => wikihash($request->getPrefs()));
1379     if (CACHE_CONTROL == 'STRICT') {
1380         $dbi = $request->getDbh();
1381         $timestamp = $dbi->getTimestamp();
1382         $validators['mtime'] = $timestamp;
1383         $validators['%mtime'] = (int)$timestamp;
1384     }
1385     // FIXME: we should try to generate strong validators when possible,
1386     // but for now, our validator is weak, since equal validators do not
1387     // indicate byte-level equality of content.  (Due to DEBUG timing output, etc...)
1388     //
1389     // (If DEBUG if off, this may be a strong validator, but I'm going
1390     // to go the paranoid route here pending further study and testing.)
1391     // access hits and edit stats in the footer violate strong ETags also. 
1392     if (1 or DEBUG) {
1393         $validators['%weak'] = true;
1394     }
1395     $request->setValidators($validators);
1396    
1397     $request->handleAction();
1398
1399     if (DEBUG and DEBUG & _DEBUG_INFO) phpinfo(INFO_VARIABLES | INFO_MODULES);
1400     $request->finish();
1401 }
1402
1403 //$x = error_reporting();  // DEBUG: why is it 1 here? should be E_ALL
1404 if (defined('E_STRICT') and (E_ALL & E_STRICT)) // strict php5?
1405     error_reporting(E_ALL & ~E_STRICT);         // exclude E_STRICT
1406 else
1407     error_reporting(E_ALL); // php4
1408 // don't run the main loop for special requests (test, getimg, xmlrpc, soap, ...)
1409 if (!defined('PHPWIKI_NOMAIN') or !PHPWIKI_NOMAIN)
1410     main();
1411
1412 // Local Variables:
1413 // mode: php
1414 // tab-width: 8
1415 // c-basic-offset: 4
1416 // c-hanging-comment-ender-p: nil
1417 // indent-tabs-mode: nil
1418 // End:
1419 ?>