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