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