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