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