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