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