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