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