]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/main.php
CGI: no PATH_INFO fix
[SourceForge/phpwiki.git] / lib / main.php
1 <?php //-*-php-*-
2 rcs_id('$Id: main.php,v 1.148 2004-05-17 17:43:29 rurban Exp $');
3
4 define ('USE_PREFS_IN_PAGE', true);
5
6 //include "lib/config.php";
7 require_once(dirname(__FILE__)."/stdlib.php");
8 require_once('lib/Request.php');
9 require_once('lib/WikiDB.php');
10 if (ENABLE_USER_NEW)
11     require_once("lib/WikiUserNew.php");
12 else
13     require_once("lib/WikiUser.php");
14 require_once("lib/WikiGroup.php");
15 require_once("lib/PagePerm.php");
16
17 class WikiRequest extends Request {
18     // var $_dbi;
19
20     function WikiRequest () {
21         $this->_dbi = WikiDB::open($GLOBALS['DBParams']);
22         if (USE_DB_SESSION) {
23             include_once('lib/DB_Session.php');
24             $prefix = isset($GLOBALS['DBParams']['prefix']) ? $GLOBALS['DBParams']['prefix'] : '';
25             if (in_array('File',$GLOBALS['USER_AUTH_ORDER'])) {
26                 include_once('lib/pear/File_Passwd.php');
27             }
28             $dbi = $this->getDbh();
29             $this->_dbsession = & new DB_Session($dbi,$prefix . $GLOBALS['DBParams']['db_session_table']);
30         }
31 // Fixme: Does pear reset the error mask to 1? We have to find the culprit
32 $x = error_reporting();
33 $this->version = phpwiki_version();
34         $this->Request();
35
36         // Normalize args...
37         $this->setArg('pagename', $this->_deducePagename());
38         $this->setArg('action', $this->_deduceAction());
39
40         // Restore auth state. This doesn't check for proper authorization!
41         if (ENABLE_USER_NEW) {
42             $userid = $this->_deduceUsername(); 
43             if (isset($this->_user) and 
44                 !empty($this->_user->_authhow) and 
45                 $this->_user->_authhow == 'session')
46             {
47                 // users might switch in a session between the two objects.
48                 // restore old auth level here or in updateAuthAndPrefs?
49                 //$user = $this->getSessionVar('wiki_user');
50                 // revive db handle, because these don't survive sessions
51                 if (isset($this->_user) and 
52                      ( ! isa($this->_user,WikiUserClassname())
53                        or (strtolower(get_class($this->_user)) == '_passuser')))
54                 {
55                     $this->_user = WikiUser($userid,$this->_user->_prefs);
56                 }
57                 unset($this->_user->_HomePagehandle);
58                 $this->_user->hasHomePage();
59                 // update the lockfile filehandle
60                 if (  isa($this->_user,'_FilePassUser') and 
61                       $this->_user->_file->lockfile and 
62                       !$this->_user->_file->fplock  )
63                 {
64                     $this->_user = new _FilePassUser($userid,$this->_user->_prefs,$this->_user->_file->filename);
65                 }
66                 /*
67                 if (!isa($user,WikiUserClassname()) or empty($this->_user->_level)) {
68                     $user = UpgradeUser($this->_user,$user);
69                 }
70                 */
71                 $this->_prefs = & $this->_user->_prefs;
72             } else {
73                 $user = WikiUser($userid);
74                 $this->_user = & $user;
75                 $this->_prefs = & $this->_user->_prefs;
76             }
77         } else {
78             $this->_user = new WikiUser($this, $this->_deduceUsername());
79             $this->_prefs = $this->_user->getPreferences();
80         }
81     }
82
83     function initializeLang () {
84         if ($user_lang = $this->getPref('lang')) {
85             //trigger_error("DEBUG: initializeLang() ". $user_lang ." calling update_locale()...");
86             update_locale($user_lang);
87             FindLocalizedButtonFile(".",'missing_ok','reinit');
88         }
89     }
90
91     function initializeTheme () {
92         global $Theme;
93
94         // Load theme
95         if ($user_theme = $this->getPref('theme'))
96             include_once("themes/$user_theme/themeinfo.php");
97         if (empty($Theme) and defined('THEME'))
98             include_once("themes/" . THEME . "/themeinfo.php");
99         if (empty($Theme))
100             include_once("themes/default/themeinfo.php");
101         assert(!empty($Theme));
102     }
103
104     // This really maybe should be part of the constructor, but since it
105     // may involve HTML/template output, the global $request really needs
106     // to be initialized before we do this stuff.
107     function updateAuthAndPrefs () {
108
109         if (isset($this->_user) and (!isa($this->_user,WikiUserClassname()))) {
110             $this->_user = false;       
111         }
112         // Handle authentication request, if any.
113         if ($auth_args = $this->getArg('auth')) {
114             $this->setArg('auth', false);
115             $this->_handleAuthRequest($auth_args); // possible NORETURN
116         }
117         elseif ( ! $this->_user or 
118                  (isa($this->_user,WikiUserClassname()) and ! $this->_user->isSignedIn())) {
119             // If not auth request, try to sign in as saved user.
120             if (($saved_user = $this->getPref('userid')) != false) {
121                 $this->_signIn($saved_user);
122             }
123         }
124
125         // Save preferences in session and cookie
126         if (isset($this->_user) and 
127             (!isset($this->_user->_authhow) or $this->_user->_authhow != 'session')) {
128             $id_only = true; 
129             $this->_user->setPreferences($this->_prefs, $id_only);
130         } else {
131             $this->setSessionVar('wiki_user', $this->_user);
132             //$this->setSessionVar('wiki_prefs', $this->_prefs);
133         }
134
135         // Ensure user has permissions for action
136         $require_level = $this->requiredAuthority($this->getArg('action'));
137         if (! $this->_user->hasAuthority($require_level))
138             $this->_notAuthorized($require_level); // NORETURN
139     }
140
141     function getUser () {
142         if (isset($this->_user))
143             return $this->_user;
144         else
145             return $GLOBALS['ForbiddenUser'];
146     }
147
148     function getPrefs () {
149         return $this->_prefs;
150     }
151
152     // Convenience function:
153     function getPref ($key) {
154         if (isset($this->_prefs))
155             return $this->_prefs->get($key);
156     }
157
158     function getDbh () {
159         return $this->_dbi;
160     }
161
162     /**
163      * Get requested page from the page database.
164      * By default it will grab the page requested via the URL
165      *
166      * This is a convenience function.
167      * @param string $pagename Name of page to get.
168      * @return WikiDB_Page Object with methods to pull data from
169      * database for the page requested.
170      */
171     function getPage ($pagename = false) {
172         if (!isset($this->_dbi))
173             $this->getDbh();
174         if (!$pagename) 
175             $pagename = $this->getArg('pagename');
176         return $this->_dbi->getPage($pagename);
177     }
178
179     /** Get URL for POST actions.
180      *
181      * Officially, we should just use SCRIPT_NAME (or some such),
182      * but that causes problems when we try to issue a redirect, e.g.
183      * after saving a page.
184      *
185      * Some browsers (at least NS4 and Mozilla 0.97 won't accept
186      * a redirect from a page to itself.)
187      *
188      * So, as a HACK, we include pagename and action as query args in
189      * the URL.  (These should be ignored when we receive the POST
190      * request.)
191      */
192     function getPostURL ($pagename=false) {
193         if ($pagename === false)
194             $pagename = $this->getArg('pagename');
195         $action = $this->getArg('action');
196         if (!empty($_GET['start_debug'])) // zend ide support
197             return WikiURL($pagename, array('action' => $action, 'start_debug' => 1));
198         else
199             return WikiURL($pagename, array('action' => $action));
200     }
201     
202     function _handleAuthRequest ($auth_args) {
203         if (!is_array($auth_args))
204             return;
205
206         // Ignore password unless POST'ed.
207         if (!$this->isPost())
208             unset($auth_args['passwd']);
209
210         $olduser = $this->_user;
211         $user = $this->_user->AuthCheck($auth_args);
212         if (isa($user,WikiUserClassname())) {
213             // Successful login (or logout.)
214             $this->_setUser($user);
215         }
216         elseif (is_string($user)) {
217             // Login attempt failed.
218             $fail_message = $user;
219             $auth_args['pass_required'] = true;
220             // If no password was submitted, it's not really
221             // a failure --- just need to prompt for password...
222             if (!ALLOW_USER_PASSWORDS 
223                 and ALLOW_BOGO_LOGIN 
224                 and !isset($auth_args['passwd'])) 
225             {
226                 $fail_message = false;
227             }
228             $olduser->PrintLoginForm($this, $auth_args, $fail_message, 'newpage');
229             $this->finish();    //NORETURN
230         }
231         else {
232             // Login request cancelled.
233         }
234     }
235
236     /**
237      * Attempt to sign in (bogo-login).
238      *
239      * Fails silently.
240      *
241      * @param $userid string Userid to attempt to sign in as.
242      * @access private
243      */
244     function _signIn ($userid) {
245         if (ENABLE_USER_NEW) {
246             if (! $this->_user )
247                 $this->_user = new _BogoUser($userid);
248             if (! $this->_user )
249                 $this->_user = new _PassUser($userid);
250         }
251         $user = $this->_user->AuthCheck(array('userid' => $userid));
252         if (isa($user,WikiUserClassname())) {
253             $this->_setUser($user); // success!
254         }
255     }
256
257     // login or logout or restore state
258     function _setUser ($user) {
259         $this->_user = $user;
260         define('MAIN_setUser',true);
261         $this->setCookieVar('WIKI_ID', $user->getAuthenticatedId(), COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
262         $this->setSessionVar('wiki_user', $user);
263         if ($user->isSignedIn())
264             $user->_authhow = 'signin';
265
266         // Save userid to prefs..
267         if ( ! $this->_user->_prefs ) {
268             $this->_user->_prefs = $this->_user->getPreferences();
269             $this->_prefs =& $this->_user->_prefs;
270         }
271         $this->_prefs->set('userid',
272                            $user->isSignedIn() ? $user->getId() : '');
273         $this->initializeTheme();
274     }
275
276     /* Permission system */
277     function getLevelDescription($level) {
278         static $levels = false;
279         if (!$levels) 
280             $levels = array('-1'  => _("FORBIDDEN"),
281                              '0'  => _("ANON"),
282                              '1'  => _("BOGO"),
283                              '2'  => _("USER"),
284                              '10' => _("ADMIN"),
285                              '100'=> _("UNOBTAINABLE"));
286         return $levels[$level];
287     }
288     
289     function _notAuthorized ($require_level) {
290         // Display the authority message in the Wiki's default
291         // language, in case it is not english.
292         //
293         // Note that normally a user will not see such an error once
294         // logged in, unless the admin has altered the default
295         // disallowed wikiactions. In that case we should probably
296         // check the user's language prefs too at this point; this
297         // would be a situation which is not really handled with the
298         // current code.
299         if (empty($GLOBALS['LANG']))
300             update_locale(DEFAULT_LANGUAGE);
301
302         // User does not have required authority.  Prompt for login.
303         $what = $this->getActionDescription($this->getArg('action'));
304         $pass_required = ($require_level >= WIKIAUTH_USER);
305         if ($require_level == WIKIAUTH_UNOBTAINABLE) {
306             if (class_exists('PagePermission')) {
307                 $user =& $this->_user;
308                 $status = $user->isAuthenticated() ? _("authenticated") : _("not authenticated");
309                 $msg = fmt("%s is disallowed on this wiki for %s user '%s' (level: %s).",
310                            $this->getDisallowedActionDescription($this->getArg('action')),
311                            $status, $user->getId(),$this->getLevelDescription($user->_level));
312                 $user->PrintLoginForm($this, compact('require_level','pass_required'), $msg);
313                 $this->finish();
314             } else {
315                 $msg = fmt("%s is disallowed on this wiki.",
316                            $this->getDisallowedActionDescription($this->getArg('action')));
317                 $this->_user->PrintLoginForm($this, compact('require_level','pass_required'), $msg);
318                 $this->finish();
319             }
320         }
321         elseif ($require_level == WIKIAUTH_BOGO)
322             $msg = fmt("You must sign in to %s.", $what);
323         elseif ($require_level == WIKIAUTH_USER)
324             $msg = fmt("You must log in to %s.", $what);
325         else
326             $msg = fmt("You must be an administrator to %s.", $what);
327
328         $this->_user->PrintLoginForm($this, compact('require_level','pass_required'), $msg);
329         $this->finish();    // NORETURN
330     }
331
332     // Fixme: for PagePermissions we'll need other strings, 
333     // relevant to the requested page, not just for the action on the whole wiki.
334     function getActionDescription($action) {
335         static $actionDescriptions;
336         if (! $actionDescriptions) {
337             $actionDescriptions
338             = array('browse'     => _("view this page"),
339                     'diff'       => _("diff this page"),
340                     'dumphtml'   => _("dump html pages"),
341                     'dumpserial' => _("dump serial pages"),
342                     'edit'       => _("edit this page"),
343                     'create'     => _("create this page"),
344                     'loadfile'   => _("load files into this wiki"),
345                     'lock'       => _("lock this page"),
346                     'remove'     => _("remove this page"),
347                     'unlock'     => _("unlock this page"),
348                     'upload'     => _("upload a zip dump"),
349                     'verify'     => _("verify the current action"),
350                     'viewsource' => _("view the source of this page"),
351                     'xmlrpc'     => _("access this wiki via XML-RPC"),
352                     'soap'       => _("access this wiki via SOAP"),
353                     'zip'        => _("download a zip dump from this wiki"),
354                     'ziphtml'    => _("download an html zip dump from this wiki")
355                     );
356         }
357         if (in_array($action, array_keys($actionDescriptions)))
358             return $actionDescriptions[$action];
359         else
360             return $action;
361     }
362     function getDisallowedActionDescription($action) {
363         static $disallowedActionDescriptions;
364         if (! $disallowedActionDescriptions) {
365             $disallowedActionDescriptions
366             = array('browse'     => _("Browsing pages"),
367                     'diff'       => _("Diffing pages"),
368                     'dumphtml'   => _("Dumping html pages"),
369                     'dumpserial' => _("Dumping serial pages"),
370                     'edit'       => _("Editing pages"),
371                     'create'     => _("Creating pages"),
372                     'loadfile'   => _("Loading files"),
373                     'lock'       => _("Locking pages"),
374                     'remove'     => _("Removing pages"),
375                     'unlock'     => _("Unlocking pages"),
376                     'upload'     => _("Uploading zip dumps"),
377                     'verify'     => _("Verify the current action"),
378                     'viewsource' => _("Viewing the source of pages"),
379                     'xmlrpc'     => _("XML-RPC access"),
380                     'soap'       => _("SOAP access"),
381                     'zip'        => _("Downloading zip dumps"),
382                     'ziphtml'    => _("Downloading html zip dumps")
383                     );
384         }
385         if (in_array($action, array_keys($disallowedActionDescriptions)))
386             return $disallowedActionDescriptions[$action];
387         else
388             return $action;
389     }
390
391     function requiredAuthority ($action) {
392         $auth = $this->requiredAuthorityForAction($action);
393         if (!ALLOW_ANON_USER) return WIKIAUTH_USER;
394         
395         /*
396          * This is a hook for plugins to require authority
397          * for posting to them.
398          *
399          * IMPORTANT: this is not a secure check, so the plugin
400          * may not assume that any POSTs to it are authorized.
401          * All this does is cause PhpWiki to prompt for login
402          * if the user doesn't have the required authority.
403          */
404         if ($this->isPost()) {
405             $post_auth = $this->getArg('require_authority_for_post');
406             if ($post_auth !== false)
407                 $auth = max($auth, $post_auth);
408         }
409         return $auth;
410     }
411         
412     function requiredAuthorityForAction ($action) {
413         if (class_exists("PagePermission")) {
414             return requiredAuthorityForPage($action);
415         } else {
416           // FIXME: clean up. 
417           switch ($action) {
418             case 'browse':
419             case 'viewsource':
420             case 'diff':
421             case 'select':
422             case 'xmlrpc':
423             case 'search':
424             case 'pdf':
425                 return WIKIAUTH_ANON;
426
427             case 'zip':
428             case 'ziphtml':
429                 if (defined('ZIPDUMP_AUTH') && ZIPDUMP_AUTH)
430                     return WIKIAUTH_ADMIN;
431                 return WIKIAUTH_ANON;
432
433             case 'edit':
434             case 'soap':
435                 if (defined('REQUIRE_SIGNIN_BEFORE_EDIT') && REQUIRE_SIGNIN_BEFORE_EDIT)
436                     return WIKIAUTH_BOGO;
437                 return WIKIAUTH_ANON;
438                 // return WIKIAUTH_BOGO;
439
440             case 'create':
441                 $page = $this->getPage();
442                 $current = $page->getCurrentRevision();
443                 if ($current->hasDefaultContents())
444                     return $this->requiredAuthorityForAction('edit');
445                 return $this->requiredAuthorityForAction('browse');
446
447             case 'upload':
448             case 'dumpserial':
449             case 'dumphtml':
450             case 'loadfile':
451             case 'remove':
452             case 'lock':
453             case 'unlock':
454             case 'upgrade':
455                 return WIKIAUTH_ADMIN;
456             default:
457                 global $WikiNameRegexp;
458                 if (preg_match("/$WikiNameRegexp\Z/A", $action))
459                     return WIKIAUTH_ANON; // ActionPage.
460                 else
461                     return WIKIAUTH_ADMIN;
462           }
463         }
464     }
465     /* End of Permission system */
466
467     function possiblyDeflowerVirginWiki () {
468         if ($this->getArg('action') != 'browse')
469             return;
470         if ($this->getArg('pagename') != HOME_PAGE)
471             return;
472
473         $page = $this->getPage();
474         $current = $page->getCurrentRevision();
475         if ($current->getVersion() > 0)
476             return;             // Homepage exists.
477
478         include('lib/loadsave.php');
479         SetupWiki($this);
480         $this->finish();        // NORETURN
481     }
482
483     function handleAction () {
484         $action = $this->getArg('action');
485         $method = "action_$action";
486         if (method_exists($this, $method)) {
487             $this->{$method}();
488         }
489         elseif ($page = $this->findActionPage($action)) {
490             $this->actionpage($page);
491         }
492         else {
493             $this->finish(fmt("%s: Bad action", $action));
494         }
495     }
496     
497     function finish ($errormsg = false) {
498         static $in_exit = 0;
499
500         if ($in_exit)
501             exit();        // just in case CloseDataBase calls us
502         $in_exit = true;
503
504         global $ErrorManager;
505         $ErrorManager->flushPostponedErrors();
506
507         if (!empty($errormsg)) {
508             PrintXML(HTML::br(),
509                      HTML::hr(),
510                      HTML::h2(_("Fatal PhpWiki Error")),
511                      $errormsg);
512             // HACK:
513             echo "\n</body></html>";
514         }
515         if (is_object($this->_user)) {
516             $this->_user->page   = $this->getArg('pagename');
517             $this->_user->action = $this->getArg('action');
518             unset($this->_user->_HomePagehandle);
519             unset($this->_user->_auth_dbi);
520         }
521         if (!empty($this->_dbi)) {
522             session_write_close();
523             $this->_dbi->close();
524             unset($this->_dbi);
525         }
526         Request::finish();
527         exit;
528     }
529
530     function _deducePagename () {
531         if ($this->getArg('pagename'))
532             return $this->getArg('pagename');
533
534         if (USE_PATH_INFO) {
535             $pathinfo = $this->get('PATH_INFO');
536             if (empty($pathinfo)) { // fix for CGI
537                 $path = $this->get('REQUEST_URI');
538                 $script = $this->get('SCRIPT_NAME');
539                 $pathinfo = substr($path,strlen($script));
540                 $pathinfo = preg_replace('/\?.+$/','',$pathinfo);
541             }
542             $tail = substr($pathinfo, strlen(PATH_INFO_PREFIX));
543
544             if ($tail != '' and $pathinfo == PATH_INFO_PREFIX . $tail) {
545                 return $tail;
546             }
547         }
548         elseif ($this->isPost()) {
549             /*
550              * In general, for security reasons, HTTP_GET_VARS should be ignored
551              * on POST requests, but we make an exception here (only for pagename).
552              *
553              * The justification for this hack is the following
554              * asymmetry: When POSTing with USE_PATH_INFO set, the
555              * pagename can (and should) be communicated through the
556              * request URL via PATH_INFO.  When POSTing with
557              * USE_PATH_INFO off, this cannot be done --- the only way
558              * to communicate the pagename through the URL is via
559              * QUERY_ARGS (HTTP_GET_VARS).
560              */
561             global $HTTP_GET_VARS;
562             if (isset($HTTP_GET_VARS['pagename'])) { 
563                 return $HTTP_GET_VARS['pagename'];
564             }
565         }
566
567         /*
568          * Support for PhpWiki 1.2 style requests.
569          */
570         $query_string = $this->get('QUERY_STRING');
571         if (preg_match('/^[^&=]+$/', $query_string)) {
572             return urldecode($query_string);
573         }
574
575         return HOME_PAGE;
576     }
577
578     function _deduceAction () {
579         if (!($action = $this->getArg('action'))) {
580             // Detect XML-RPC requests
581             if ($this->isPost()
582                 && $this->get('CONTENT_TYPE') == 'text/xml') {
583                 global $HTTP_RAW_POST_DATA;
584                 if (strstr($HTTP_RAW_POST_DATA, '<methodCall>')) {
585                     return 'xmlrpc';
586                 }
587             }
588
589             return 'browse';    // Default if no action specified.
590         }
591
592         if (method_exists($this, "action_$action"))
593             return $action;
594
595         // Allow for, e.g. action=LikePages
596         if ($this->isActionPage($action))
597             return $action;
598
599         trigger_error("$action: Unknown action", E_USER_NOTICE);
600         return 'browse';
601     }
602
603     function _deduceUsername() {
604         global $HTTP_SERVER_VARS, $HTTP_ENV_VARS;
605         if (!empty($this->args['auth']) and !empty($this->args['auth']['userid']))
606             return $this->args['auth']['userid'];
607         if (!empty($HTTP_SERVER_VARS['PHP_AUTH_USER']))
608             return $HTTP_SERVER_VARS['PHP_AUTH_USER'];
609         if (!empty($HTTP_ENV_VARS['REMOTE_USER']))
610             return $HTTP_ENV_VARS['REMOTE_USER'];
611             
612         if ($user = $this->getSessionVar('wiki_user')) {
613             $this->_user = $user;
614             $this->_user->_authhow = 'session';
615             return ENABLE_USER_NEW ? $user->UserName() : $this->_user;
616         }
617         if ($userid = $this->getCookieVar('WIKI_ID')) {
618             if (!empty($userid) and substr($userid,0,2) != 's:') {
619                 $this->_user->authhow = 'cookie';
620                 return $userid;
621             }
622         }
623         return false;
624     }
625     
626     function _isActionPage ($pagename) {
627         $dbi = $this->getDbh();
628         $page = $dbi->getPage($pagename);
629         $rev = $page->getCurrentRevision();
630         // FIXME: more restrictive check for sane plugin?
631         if (strstr($rev->getPackedContent(), '<?plugin'))
632             return true;
633         if (!$rev->hasDefaultContents())
634             trigger_error("$pagename: Does not appear to be an 'action page'", E_USER_NOTICE);
635         return false;
636     }
637
638     function findActionPage ($action) {
639         static $cache;
640
641         // check for translated version, as per users preferred language
642         // (or system default in case it is not en)
643         $translation = gettext($action);
644
645         if (isset($cache) and isset($cache[$translation]))
646             return $cache[$translation];
647
648         // check for cached translated version
649         if ($this->_isActionPage($translation))
650             return $cache[$action] = $translation;
651
652         // Allow for, e.g. action=LikePages
653         global $WikiNameRegexp;
654         if (!preg_match("/$WikiNameRegexp\\Z/A", $action))
655             return $cache[$action] = false;
656
657         // check for translated version (default language)
658         global $LANG;
659         if ($LANG != DEFAULT_LANGUAGE and $LANG != "en") {
660             $save_lang = $LANG;
661             //trigger_error("DEBUG: findActionPage() ". DEFAULT_LANGUAGE." calling update_locale()...");
662             update_locale(DEFAULT_LANGUAGE);
663             $default = gettext($action);
664             //trigger_error("DEBUG: findActionPage() ". $save_lang." restoring save_lang, calling update_locale()...");
665             update_locale($save_lang);
666             if ($this->_isActionPage($default))
667                 return $cache[$action] = $default;
668         }
669         else {
670             $default = $translation;
671         }
672         
673         // check for english version
674         if ($action != $translation and $action != $default) {
675             if ($this->_isActionPage($action))
676                 return $cache[$action] = $action;
677         }
678
679         trigger_error("$action: Cannot find action page", E_USER_NOTICE);
680         return $cache[$action] = false;
681     }
682     
683     function isActionPage ($pagename) {
684         return $this->findActionPage($pagename);
685     }
686
687     function action_browse () {
688         $this->buffer_output();
689         include_once("lib/display.php");
690         displayPage($this);
691     }
692
693     function action_verify () {
694         $this->action_browse();
695     }
696
697     function actionpage ($action) {
698         $this->buffer_output();
699         include_once("lib/display.php");
700         actionPage($this, $action);
701     }
702
703     function action_diff () {
704         $this->buffer_output();
705         include_once "lib/diff.php";
706         showDiff($this);
707     }
708
709     function action_search () {
710         // This is obsolete: reformulate URL and redirect.
711         // FIXME: this whole section should probably be deleted.
712         if ($this->getArg('searchtype') == 'full') {
713             $search_page = _("FullTextSearch");
714         }
715         else {
716             $search_page = _("TitleSearch");
717         }
718         $this->redirect(WikiURL($search_page,
719                                 array('s' => $this->getArg('searchterm')),
720                                 'absolute_url'));
721     }
722
723     function action_edit () {
724         $this->buffer_output();
725         include "lib/editpage.php";
726         $e = new PageEditor ($this);
727         $e->editPage();
728     }
729
730     function action_create () {
731         $this->action_edit();
732     }
733     
734     function action_viewsource () {
735         $this->buffer_output();
736         include "lib/editpage.php";
737         $e = new PageEditor ($this);
738         $e->viewSource();
739     }
740
741     function action_lock () {
742         $page = $this->getPage();
743         $page->set('locked', true);
744         $this->_dbi->touch();
745         $this->action_browse();
746     }
747
748     function action_unlock () {
749         // FIXME: This check is redundant.
750         //$user->requireAuth(WIKIAUTH_ADMIN);
751         $page = $this->getPage();
752         $page->set('locked', false);
753         $this->_dbi->touch();
754         $this->action_browse();
755     }
756
757     function action_remove () {
758         // FIXME: This check is redundant.
759         //$user->requireAuth(WIKIAUTH_ADMIN);
760         $pagename = $this->getArg('pagename');
761         if (strstr($pagename,_('PhpWikiAdministration'))) {
762             $this->action_browse();
763         } else {
764             include('lib/removepage.php');
765             RemovePage($this);
766         }
767     }
768
769     function action_xmlrpc () {
770         include_once("lib/XmlRpcServer.php");
771         $xmlrpc = new XmlRpcServer($this);
772         $xmlrpc->service();
773     }
774     
775     function action_zip () {
776         include_once("lib/loadsave.php");
777         MakeWikiZip($this);
778         // I don't think it hurts to add cruft at the end of the zip file.
779         //echo "\n========================================================\n";
780         //echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
781     }
782
783     function action_ziphtml () {
784         include_once("lib/loadsave.php");
785         MakeWikiZipHtml($this);
786         // I don't think it hurts to add cruft at the end of the zip file.
787         echo "\n========================================================\n";
788         echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
789     }
790
791     function action_dumpserial () {
792         include_once("lib/loadsave.php");
793         DumpToDir($this);
794     }
795
796     function action_dumphtml () {
797         include_once("lib/loadsave.php");
798         DumpHtmlToDir($this);
799     }
800
801     function action_upload () {
802         include_once("lib/loadsave.php");
803         LoadPostFile($this);
804     }
805
806     function action_upgrade () {
807         include_once("lib/loadsave.php");
808         include_once("lib/upgrade.php");
809         DoUpgrade($this);
810     }
811
812     function action_loadfile () {
813         include_once("lib/loadsave.php");
814         LoadFileOrDir($this);
815     }
816
817     function action_pdf () {
818         include_once("lib/pdf.php");
819         ConvertAndDisplayPdf($this);
820     }
821     
822 }
823
824 //FIXME: deprecated
825 function is_safe_action ($action) {
826     return WikiRequest::requiredAuthorityForAction($action) < WIKIAUTH_ADMIN;
827 }
828
829 function validateSessionPath() {
830     // Try to defer any session.save_path PHP errors before any html
831     // is output, which causes some versions of IE to display a blank
832     // page (due to its strict mode while parsing a page?).
833     if (! is_writeable(ini_get('session.save_path'))) {
834         $tmpdir = '/tmp';
835         trigger_error
836             (sprintf(_("%s is not writable."),
837                      _("The session.save_path directory"))
838              . "\n"
839              . sprintf(_("Please ensure that %s is writable, or redefine %s in index.php."),
840                        sprintf(_("the directory '%s'"),
841                                ini_get('session.save_path')),
842                        'session.save_path')
843              . "\n"
844              . sprintf(_("Attempting to use the directory '%s' instead."),
845                        $tmpdir)
846              , E_USER_NOTICE);
847         if (! is_writeable($tmpdir)) {
848             trigger_error
849                 (sprintf(_("%s is not writable."), $tmpdir)
850                  . "\n"
851                  . _("Users will not be able to sign in.")
852                  , E_USER_NOTICE);
853         }
854         else
855             ini_set('session.save_path', $tmpdir);
856     }
857 }
858
859 function main () {
860     if (!USE_DB_SESSION)
861         validateSessionPath();
862
863     global $request;
864
865     if (DEBUG and extension_loaded("apd"))
866         apd_set_session_trace(9);
867     $request = new WikiRequest();
868
869     /*
870      * Allow for disabling of markup cache.
871      * (Mostly for debugging ... hopefully.)
872      *
873      * See also <?plugin WikiAdminUtils action=purge-cache ?>
874      */
875     if (!defined('WIKIDB_NOCACHE_MARKUP') and $request->getArg('nocache'))
876         define('WIKIDB_NOCACHE_MARKUP', $request->getArg('nocache'));
877     
878     // Initialize with system defaults in case user not logged in.
879     // Should this go into constructor?
880     $request->initializeTheme();
881
882     $request->updateAuthAndPrefs();
883     $request->initializeLang();
884     
885     // Enable the output of most of the warning messages.
886     // The warnings will screw up zip files though.
887     global $ErrorManager;
888     $action = $request->getArg('action');
889     if (substr($action, 0, 3) != 'zip') {
890         if ($action == 'pdf')
891             $ErrorManager->setPostponedErrorMask(0);
892         else
893             $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE);
894     }
895
896     //FIXME:
897     //if ($user->is_authenticated())
898     //  $LogEntry->user = $user->getId();
899
900     $request->possiblyDeflowerVirginWiki();
901     
902 if (defined('WIKI_XMLRPC') and WIKI_XMLRPC) return;
903 if (defined('WIKI_SOAP')   and WIKI_SOAP)   return;
904
905     $validators = array('wikiname' => WIKI_NAME,
906                         'args'     => hash($request->getArgs()),
907                         'prefs'    => hash($request->getPrefs()));
908     if (CACHE_CONTROL == 'STRICT') {
909         $dbi = $request->getDbh();
910         $timestamp = $dbi->getTimestamp();
911         $validators['mtime'] = $timestamp;
912         $validators['%mtime'] = (int)$timestamp;
913     }
914     // FIXME: we should try to generate strong validators when possible,
915     // but for now, our validator is weak, since equal validators do not
916     // indicate byte-level equality of content.  (Due to DEBUG timing output, etc...)
917     //
918     // (If DEBUG if off, this may be a strong validator, but I'm going
919     // to go the paranoid route here pending further study and testing.)
920     //
921     $validators['%weak'] = true;
922     $request->setValidators($validators);
923    
924     $request->handleAction();
925
926 if (defined('DEBUG') and DEBUG & 4) phpinfo(INFO_VARIABLES);
927     $request->finish();
928 }
929
930 $x = error_reporting(); // why is it 1 here? should be E_ALL
931 error_reporting(E_ALL);
932 main();
933
934
935 // $Log: not supported by cvs2svn $
936 // Revision 1.147  2004/05/15 19:48:33  rurban
937 // fix some too loose PagePerms for signed, but not authenticated users
938 //  (admin, owner, creator)
939 // no double login page header, better login msg.
940 // moved action_pdf to lib/pdf.php
941 //
942 // Revision 1.146  2004/05/15 18:31:01  rurban
943 // some action=pdf Request fixes: With MSIE it works now. Now the work with the page formatting begins.
944 //
945 // Revision 1.145  2004/05/12 10:49:55  rurban
946 // require_once fix for those libs which are loaded before FileFinder and
947 //   its automatic include_path fix, and where require_once doesn't grok
948 //   dirname(__FILE__) != './lib'
949 // upgrade fix with PearDB
950 // navbar.tmpl: remove spaces for IE &nbsp; button alignment
951 //
952 // Revision 1.144  2004/05/06 19:26:16  rurban
953 // improve stability, trying to find the InlineParser endless loop on sf.net
954 //
955 // remove end-of-zip comments to fix sf.net bug #777278 and probably #859628
956 //
957 // Revision 1.143  2004/05/06 17:30:38  rurban
958 // CategoryGroup: oops, dos2unix eol
959 // improved phpwiki_version:
960 //   pre -= .0001 (1.3.10pre: 1030.099)
961 //   -p1 += .001 (1.3.9-p1: 1030.091)
962 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
963 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
964 //   backend->backendType(), backend->database(),
965 //   backend->listOfFields(),
966 //   backend->listOfTables(),
967 //
968 // Revision 1.142  2004/05/04 22:34:25  rurban
969 // more pdf support
970 //
971 // Revision 1.141  2004/05/03 13:16:47  rurban
972 // fixed UserPreferences update, esp for boolean and int
973 //
974 // Revision 1.140  2004/05/02 21:26:38  rurban
975 // limit user session data (HomePageHandle and auth_dbi have to invalidated anyway)
976 //   because they will not survive db sessions, if too large.
977 // extended action=upgrade
978 // some WikiTranslation button work
979 // revert WIKIAUTH_UNOBTAINABLE (need it for main.php)
980 // some temp. session debug statements
981 //
982 // Revision 1.139  2004/05/02 15:10:07  rurban
983 // new finally reliable way to detect if /index.php is called directly
984 //   and if to include lib/main.php
985 // new global AllActionPages
986 // SetupWiki now loads all mandatory pages: HOME_PAGE, action pages, and warns if not.
987 // WikiTranslation what=buttons for Carsten to create the missing MacOSX buttons
988 // PageGroupTestOne => subpages
989 // renamed PhpWikiRss to PhpWikiRecentChanges
990 // more docs, default configs, ...
991 //
992 // Revision 1.138  2004/05/01 15:59:29  rurban
993 // more php-4.0.6 compatibility: superglobals
994 //
995 // Revision 1.137  2004/04/29 19:39:44  rurban
996 // special support for formatted plugins (one-liners)
997 //   like <small><plugin BlaBla ></small>
998 // iter->asArray() helper for PopularNearby
999 // db_session for older php's (no &func() allowed)
1000 //
1001 // Revision 1.136  2004/04/29 17:18:19  zorloc
1002 // Fixes permission failure issues.  With PagePermissions and Disabled Actions when user did not have permission WIKIAUTH_FORBIDDEN was returned.  In WikiUser this was ok because WIKIAUTH_FORBIDDEN had a value of 11 -- thus no user could perform that action.  But WikiUserNew has a WIKIAUTH_FORBIDDEN value of -1 -- thus a user without sufficent permission to do anything.  The solution is a new high value permission level (WIKIAUTH_UNOBTAINABLE) to be the default level for access failure.
1003 //
1004 // Revision 1.135  2004/04/26 12:15:01  rurban
1005 // check default config values
1006 //
1007 // Revision 1.134  2004/04/23 06:46:37  zorloc
1008 // Leave DB connection open when USE_DB_SESSION is true so that session info can be written to the DB.
1009 //
1010 // Revision 1.133  2004/04/20 18:10:31  rurban
1011 // config refactoring:
1012 //   FileFinder is needed for WikiFarm scripts calling index.php
1013 //   config run-time calls moved to lib/IniConfig.php:fix_configs()
1014 //   added PHPWIKI_DIR smart-detection code (Theme finder)
1015 //   moved FileFind to lib/FileFinder.php
1016 //   cleaned lib/config.php
1017 //
1018 // Revision 1.132  2004/04/19 21:51:41  rurban
1019 // php5 compatibility: it works!
1020 //
1021 // Revision 1.131  2004/04/19 18:27:45  rurban
1022 // Prevent from some PHP5 warnings (ref args, no :: object init)
1023 //   php5 runs now through, just one wrong XmlElement object init missing
1024 // Removed unneccesary UpgradeUser lines
1025 // Changed WikiLink to omit version if current (RecentChanges)
1026 //
1027 // Revision 1.130  2004/04/18 00:25:53  rurban
1028 // allow "0" pagename
1029 //
1030 // Revision 1.129  2004/04/07 23:13:19  rurban
1031 // fixed pear/File_Passwd for Windows
1032 // fixed FilePassUser sessions (filehandle revive) and password update
1033 //
1034 // Revision 1.128  2004/04/02 15:06:55  rurban
1035 // fixed a nasty ADODB_mysql session update bug
1036 // improved UserPreferences layout (tabled hints)
1037 // fixed UserPreferences auth handling
1038 // improved auth stability
1039 // improved old cookie handling: fixed deletion of old cookies with paths
1040 //
1041 // Revision 1.127  2004/03/25 17:00:31  rurban
1042 // more code to convert old-style pref array to new hash
1043 //
1044 // Revision 1.126  2004/03/24 19:39:03  rurban
1045 // php5 workaround code (plus some interim debugging code in XmlElement)
1046 //   php5 doesn't work yet with the current XmlElement class constructors,
1047 //   WikiUserNew does work better than php4.
1048 // rewrote WikiUserNew user upgrading to ease php5 update
1049 // fixed pref handling in WikiUserNew
1050 // added Email Notification
1051 // added simple Email verification
1052 // removed emailVerify userpref subclass: just a email property
1053 // changed pref binary storage layout: numarray => hash of non default values
1054 // print optimize message only if really done.
1055 // forced new cookie policy: delete pref cookies, use only WIKI_ID as plain string.
1056 //   prefs should be stored in db or homepage, besides the current session.
1057 //
1058 // Revision 1.125  2004/03/14 16:30:52  rurban
1059 // db-handle session revivification, dba fixes
1060 //
1061 // Revision 1.124  2004/03/12 15:48:07  rurban
1062 // fixed explodePageList: wrong sortby argument order in UnfoldSubpages
1063 // simplified lib/stdlib.php:explodePageList
1064 //
1065 // Revision 1.123  2004/03/10 15:41:27  rurban
1066 // use default pref mysql table
1067 //
1068 // Revision 1.122  2004/03/08 18:17:09  rurban
1069 // added more WikiGroup::getMembersOf methods, esp. for special groups
1070 // fixed $LDAP_SET_OPTIONS
1071 // fixed _AuthInfo group methods
1072 //
1073 // Revision 1.121  2004/03/01 13:48:45  rurban
1074 // rename fix
1075 // p[] consistency fix
1076 //
1077 // Revision 1.120  2004/03/01 10:22:41  rurban
1078 // initializeTheme optimize
1079 //
1080 // Revision 1.119  2004/02/26 20:45:06  rurban
1081 // check for ALLOW_ANON_USER = false
1082 //
1083 // Revision 1.118  2004/02/26 01:32:03  rurban
1084 // fixed session login with old WikiUser object. strangely, the errormask gets corruoted to 1, Pear???
1085 //
1086 // Revision 1.117  2004/02/24 17:19:37  rurban
1087 // debugging helpers only
1088 //
1089 // Revision 1.116  2004/02/24 15:17:14  rurban
1090 // improved auth errors with individual pages. the fact that you may not browse a certain admin page does not conclude that you may not browse the whole wiki. renamed browse => view
1091 //
1092 // Revision 1.115  2004/02/15 21:34:37  rurban
1093 // PageList enhanced and improved.
1094 // fixed new WikiAdmin... plugins
1095 // editpage, Theme with exp. htmlarea framework
1096 //   (htmlarea yet committed, this is really questionable)
1097 // WikiUser... code with better session handling for prefs
1098 // enhanced UserPreferences (again)
1099 // RecentChanges for show_deleted: how should pages be deleted then?
1100 //
1101 // Revision 1.114  2004/02/15 17:30:13  rurban
1102 // workaround for lost db connnection handle on session restauration (->_auth_dbi)
1103 // fixed getPreferences() (esp. from sessions)
1104 // fixed setPreferences() (update and set),
1105 // fixed AdoDb DB statements,
1106 // update prefs only at UserPreferences POST (for testing)
1107 // unified db prefs methods (but in external pref classes yet)
1108 //
1109 // Revision 1.113  2004/02/12 13:05:49  rurban
1110 // Rename functional for PearDB backend
1111 // some other minor changes
1112 // SiteMap comes with a not yet functional feature request: includepages (tbd)
1113 //
1114 // Revision 1.112  2004/02/09 03:58:12  rurban
1115 // for now default DB_SESSION to false
1116 // PagePerm:
1117 //   * not existing perms will now query the parent, and not
1118 //     return the default perm
1119 //   * added pagePermissions func which returns the object per page
1120 //   * added getAccessDescription
1121 // WikiUserNew:
1122 //   * added global ->prepare (not yet used) with smart user/pref/member table prefixing.
1123 //   * force init of authdbh in the 2 db classes
1124 // main:
1125 //   * fixed session handling (not triple auth request anymore)
1126 //   * don't store cookie prefs with sessions
1127 // stdlib: global obj2hash helper from _AuthInfo, also needed for PagePerm
1128 //
1129 // Revision 1.111  2004/02/07 10:41:25  rurban
1130 // fixed auth from session (still double code but works)
1131 // fixed GroupDB
1132 // fixed DbPassUser upgrade and policy=old
1133 // added GroupLdap
1134 //
1135 // Revision 1.110  2004/02/03 09:45:39  rurban
1136 // LDAP cleanup, start of new Pref classes
1137 //
1138 // Revision 1.109  2004/01/30 19:57:58  rurban
1139 // fixed DBAuthParams['pref_select']: wrong _auth_dbi object used.
1140 //
1141 // Revision 1.108  2004/01/28 14:34:14  rurban
1142 // session table takes the common prefix
1143 // + various minor stuff
1144 // reallow password changing
1145 //
1146 // Revision 1.107  2004/01/27 23:23:39  rurban
1147 // renamed ->Username => _userid for consistency
1148 // renamed mayCheckPassword => mayCheckPass
1149 // fixed recursion problem in WikiUserNew
1150 // fixed bogo login (but not quite 100% ready yet, password storage)
1151 //
1152 // Revision 1.106  2004/01/26 09:17:49  rurban
1153 // * changed stored pref representation as before.
1154 //   the array of objects is 1) bigger and 2)
1155 //   less portable. If we would import packed pref
1156 //   objects and the object definition was changed, PHP would fail.
1157 //   This doesn't happen with an simple array of non-default values.
1158 // * use $prefs->retrieve and $prefs->store methods, where retrieve
1159 //   understands the interim format of array of objects also.
1160 // * simplified $prefs->get() and fixed $prefs->set()
1161 // * added $user->_userid and class '_WikiUser' portability functions
1162 // * fixed $user object ->_level upgrading, mostly using sessions.
1163 //   this fixes yesterdays problems with loosing authorization level.
1164 // * fixed WikiUserNew::checkPass to return the _level
1165 // * fixed WikiUserNew::isSignedIn
1166 // * added explodePageList to class PageList, support sortby arg
1167 // * fixed UserPreferences for WikiUserNew
1168 // * fixed WikiPlugin for empty defaults array
1169 // * UnfoldSubpages: added pagename arg, renamed pages arg,
1170 //   removed sort arg, support sortby arg
1171 //
1172 // Revision 1.105  2004/01/25 03:57:15  rurban
1173 // WikiUserNew support (temp. ENABLE_USER_NEW constant)
1174 //
1175 // Revision 1.104  2003/12/26 06:41:16  carstenklapp
1176 // Bugfix: Try to defer OS errors about session.save_path and ACCESS_LOG,
1177 // so they don't prevent IE from partially (or not at all) rendering the
1178 // page. This should help a little for the IE user who encounters trouble
1179 // when setting up a new PhpWiki for the first time.
1180 //
1181 // Revision 1.103  2003/12/02 00:10:00  carstenklapp
1182 // Bugfix: Ongoing work to untangle UserPreferences/WikiUser/request code
1183 // mess: UserPreferences should take effect immediately now upon signing
1184 // in.
1185 //
1186 // Revision 1.102  2003/11/25 22:55:32  carstenklapp
1187 // Localization bugfix: For wikis where English is not the default system
1188 // language, make sure that the authority error message (i.e. "You must
1189 // sign in to edit pages in this wiki" etc.) is displayed in the wiki's
1190 // default language. Previously it would always display in English.
1191 // (Added call to update_locale() before displaying any messages prior to
1192 // the login prompt.)
1193 //
1194 // Revision 1.101  2003/11/25 21:49:44  carstenklapp
1195 // Bugfix: For a non-english wiki or when the user's preference is not
1196 // english, the wiki would always use the english ActionPage first if it
1197 // was present rather than the appropriate localised variant. (PhpWikis
1198 // running only in english or Wikis running ONLY without any english
1199 // ActionPages would not notice this bug, only when both english and
1200 // localised ActionPages were in the DB.) Now we check for the localised
1201 // variant first.
1202 //
1203 // Revision 1.100  2003/11/18 16:54:18  carstenklapp
1204 // Reformatting only: Tabs to spaces, added rcs log.
1205 //
1206
1207
1208 // Local Variables:
1209 // mode: php
1210 // tab-width: 8
1211 // c-basic-offset: 4
1212 // c-hanging-comment-ender-p: nil
1213 // indent-tabs-mode: nil
1214 // End:
1215 ?>