]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/main.php
check default config values
[SourceForge/phpwiki.git] / lib / main.php
1 <?php //-*-php-*-
2 rcs_id('$Id: main.php,v 1.135 2004-04-26 12:15:01 rurban Exp $');
3
4 define ('USE_PREFS_IN_PAGE', true);
5
6 //include "lib/config.php";
7 require_once("lib/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             $this->_dbsession = & new DB_Session($this->getDbh(),
29                                                  $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         
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);
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         $this->setCookieVar('WIKI_ID', $user->getAuthenticatedId(), 365);
261         $this->setSessionVar('wiki_user', $user);
262         if ($user->isSignedIn())
263             $user->_authhow = 'signin';
264
265         // Save userid to prefs..
266         if (!($this->_prefs = $this->_user->getPreferences()))
267             $this->_prefs = $this->_user->_prefs;
268         $this->_prefs->set('userid',
269                            $user->isSignedIn() ? $user->getId() : '');
270         $this->initializeTheme();
271     }
272
273     /* Permission system */
274
275     function _notAuthorized ($require_level) {
276         // Display the authority message in the Wiki's default
277         // language, in case it is not english.
278         //
279         // Note that normally a user will not see such an error once
280         // logged in, unless the admin has altered the default
281         // disallowed wikiactions. In that case we should probably
282         // check the user's language prefs too at this point; this
283         // would be a situation which is not really handled with the
284         // current code.
285         if (empty($GLOBALS['LANG']))
286             update_locale(DEFAULT_LANGUAGE);
287
288         // User does not have required authority.  Prompt for login.
289         $what = $this->getActionDescription($this->getArg('action'));
290
291         if ($require_level == WIKIAUTH_FORBIDDEN) {
292             $this->finish(fmt("%s is disallowed on this wiki.",
293                               $this->getDisallowedActionDescription($this->getArg('action'))));
294         }
295         elseif ($require_level == WIKIAUTH_BOGO)
296             $msg = fmt("You must sign in to %s.", $what);
297         elseif ($require_level == WIKIAUTH_USER)
298             $msg = fmt("You must log in to %s.", $what);
299         else
300             $msg = fmt("You must be an administrator to %s.", $what);
301         $pass_required = ($require_level >= WIKIAUTH_USER);
302
303         $this->_user->PrintLoginForm($this, compact('require_level','pass_required'), $msg);
304         $this->finish();    // NORETURN
305     }
306
307     // Fixme: for PagePermissions we'll need other strings, 
308     // relevant to the requested page, not just for the action on the whole wiki.
309     function getActionDescription($action) {
310         static $actionDescriptions;
311         if (! $actionDescriptions) {
312             $actionDescriptions
313             = array('browse'     => _("view this page"),
314                     'diff'       => _("diff this page"),
315                     'dumphtml'   => _("dump html pages"),
316                     'dumpserial' => _("dump serial pages"),
317                     'edit'       => _("edit this page"),
318                     'create'     => _("create this page"),
319                     'loadfile'   => _("load files into this wiki"),
320                     'lock'       => _("lock this page"),
321                     'remove'     => _("remove this page"),
322                     'unlock'     => _("unlock this page"),
323                     'upload'     => _("upload a zip dump"),
324                     'verify'     => _("verify the current action"),
325                     'viewsource' => _("view the source of this page"),
326                     'xmlrpc'     => _("access this wiki via XML-RPC"),
327                     'zip'        => _("download a zip dump from this wiki"),
328                     'ziphtml'    => _("download an html zip dump from this wiki")
329                     );
330         }
331         if (in_array($action, array_keys($actionDescriptions)))
332             return $actionDescriptions[$action];
333         else
334             return $action;
335     }
336     function getDisallowedActionDescription($action) {
337         static $disallowedActionDescriptions;
338         if (! $disallowedActionDescriptions) {
339             $disallowedActionDescriptions
340             = array('browse'     => _("Browsing pages"),
341                     'diff'       => _("Diffing pages"),
342                     'dumphtml'   => _("Dumping html pages"),
343                     'dumpserial' => _("Dumping serial pages"),
344                     'edit'       => _("Editing pages"),
345                     'create'     => _("Creating pages"),
346                     'loadfile'   => _("Loading files"),
347                     'lock'       => _("Locking pages"),
348                     'remove'     => _("Removing pages"),
349                     'unlock'     => _("Unlocking pages"),
350                     'upload'     => _("Uploading zip dumps"),
351                     'verify'     => _("Verify the current action"),
352                     'viewsource' => _("Viewing the source of pages"),
353                     'xmlrpc'     => _("XML-RPC access"),
354                     'zip'        => _("Downloading zip dumps"),
355                     'ziphtml'    => _("Downloading html zip dumps")
356                     );
357         }
358         if (in_array($action, array_keys($disallowedActionDescriptions)))
359             return $disallowedActionDescriptions[$action];
360         else
361             return $action;
362     }
363
364     function requiredAuthority ($action) {
365         $auth = $this->requiredAuthorityForAction($action);
366         if (!ALLOW_ANON_USER) return WIKIAUTH_USER;
367         
368         /*
369          * This is a hook for plugins to require authority
370          * for posting to them.
371          *
372          * IMPORTANT: this is not a secure check, so the plugin
373          * may not assume that any POSTs to it are authorized.
374          * All this does is cause PhpWiki to prompt for login
375          * if the user doesn't have the required authority.
376          */
377         if ($this->isPost()) {
378             $post_auth = $this->getArg('require_authority_for_post');
379             if ($post_auth !== false)
380                 $auth = max($auth, $post_auth);
381         }
382         return $auth;
383     }
384         
385     function requiredAuthorityForAction ($action) {
386         if (class_exists("PagePermission")) {
387             return requiredAuthorityForPage($action);
388         } else {
389           // FIXME: clean up. 
390           switch ($action) {
391             case 'browse':
392             case 'viewsource':
393             case 'diff':
394             case 'select':
395             case 'xmlrpc':
396             case 'search':
397                 return WIKIAUTH_ANON;
398
399             case 'zip':
400             case 'ziphtml':
401                 if (defined('ZIPDUMP_AUTH') && ZIPDUMP_AUTH)
402                     return WIKIAUTH_ADMIN;
403                 return WIKIAUTH_ANON;
404
405             case 'edit':
406                 if (defined('REQUIRE_SIGNIN_BEFORE_EDIT') && REQUIRE_SIGNIN_BEFORE_EDIT)
407                     return WIKIAUTH_BOGO;
408                 return WIKIAUTH_ANON;
409                 // return WIKIAUTH_BOGO;
410
411             case 'create':
412                 $page = $this->getPage();
413                 $current = $page->getCurrentRevision();
414                 if ($current->hasDefaultContents())
415                     return $this->requiredAuthorityForAction('edit');
416                 return $this->requiredAuthorityForAction('browse');
417
418             case 'upload':
419             case 'dumpserial':
420             case 'dumphtml':
421             case 'loadfile':
422             case 'remove':
423             case 'lock':
424             case 'unlock':
425             case 'upgrade':
426                 return WIKIAUTH_ADMIN;
427             default:
428                 global $WikiNameRegexp;
429                 if (preg_match("/$WikiNameRegexp\Z/A", $action))
430                     return WIKIAUTH_ANON; // ActionPage.
431                 else
432                     return WIKIAUTH_ADMIN;
433           }
434         }
435     }
436     /* End of Permission system */
437
438     function possiblyDeflowerVirginWiki () {
439         if ($this->getArg('action') != 'browse')
440             return;
441         if ($this->getArg('pagename') != HOME_PAGE)
442             return;
443
444         $page = $this->getPage();
445         $current = $page->getCurrentRevision();
446         if ($current->getVersion() > 0)
447             return;             // Homepage exists.
448
449         include('lib/loadsave.php');
450         SetupWiki($this);
451         $this->finish();        // NORETURN
452     }
453
454     function handleAction () {
455         $action = $this->getArg('action');
456         $method = "action_$action";
457         if (method_exists($this, $method)) {
458             $this->{$method}();
459         }
460         elseif ($page = $this->findActionPage($action)) {
461             $this->actionpage($page);
462         }
463         else {
464             $this->finish(fmt("%s: Bad action", $action));
465         }
466     }
467     
468     function finish ($errormsg = false) {
469         static $in_exit = 0;
470
471         if ($in_exit)
472             exit();        // just in case CloseDataBase calls us
473         $in_exit = true;
474
475         if (!empty($this->_dbi) && !USE_DB_SESSION)
476             $this->_dbi->close();
477         unset($this->_dbi);
478
479         global $ErrorManager;
480         $ErrorManager->flushPostponedErrors();
481
482         if (!empty($errormsg)) {
483             PrintXML(HTML::br(),
484                      HTML::hr(),
485                      HTML::h2(_("Fatal PhpWiki Error")),
486                      $errormsg);
487             // HACK:
488             echo "\n</body></html>";
489         }
490
491         Request::finish();
492         if (!empty($this->_dbi))
493             $this->_dbi->close();
494         unset($this->_dbi);
495         
496         exit;
497     }
498
499     function _deducePagename () {
500         if ($this->getArg('pagename'))
501             return $this->getArg('pagename');
502
503         if (USE_PATH_INFO) {
504             $pathinfo = $this->get('PATH_INFO');
505             $tail = substr($pathinfo, strlen(PATH_INFO_PREFIX));
506
507             if ($tail != '' and $pathinfo == PATH_INFO_PREFIX . $tail) {
508                 return $tail;
509             }
510         }
511         elseif ($this->isPost()) {
512             /*
513              * In general, for security reasons, HTTP_GET_VARS should be ignored
514              * on POST requests, but we make an exception here (only for pagename).
515              *
516              * The justifcation for this hack is the following
517              * asymmetry: When POSTing with USE_PATH_INFO set, the
518              * pagename can (and should) be communicated through the
519              * request URL via PATH_INFO.  When POSTing with
520              * USE_PATH_INFO off, this cannot be done --- the only way
521              * to communicate the pagename through the URL is via
522              * QUERY_ARGS (HTTP_GET_VARS).
523              */
524             global $HTTP_GET_VARS;
525             if (isset($HTTP_GET_VARS['pagename'])) { 
526                 return $HTTP_GET_VARS['pagename'];
527             }
528         }
529
530         /*
531          * Support for PhpWiki 1.2 style requests.
532          */
533         $query_string = $this->get('QUERY_STRING');
534         if (preg_match('/^[^&=]+$/', $query_string)) {
535             return urldecode($query_string);
536         }
537
538         return HOME_PAGE;
539     }
540
541     function _deduceAction () {
542         if (!($action = $this->getArg('action'))) {
543             // Detect XML-RPC requests
544             if ($this->isPost()
545                 && $this->get('CONTENT_TYPE') == 'text/xml') {
546                 global $HTTP_RAW_POST_DATA;
547                 if (strstr($HTTP_RAW_POST_DATA, '<methodCall>')) {
548                     return 'xmlrpc';
549                 }
550             }
551
552             return 'browse';    // Default if no action specified.
553         }
554
555         if (method_exists($this, "action_$action"))
556             return $action;
557
558         // Allow for, e.g. action=LikePages
559         if ($this->isActionPage($action))
560             return $action;
561
562         trigger_error("$action: Unknown action", E_USER_NOTICE);
563         return 'browse';
564     }
565
566     function _deduceUsername() {
567         if (!empty($this->args['auth']) and !empty($this->args['auth']['userid']))
568             return $this->args['auth']['userid'];
569         if (!empty($_SERVER['PHP_AUTH_USER']))
570             return $_SERVER['PHP_AUTH_USER'];
571         if (!empty($_ENV['REMOTE_USER']))
572             return $_ENV['REMOTE_USER'];
573             
574         if ($user = $this->getSessionVar('wiki_user')) {
575             $this->_user = $user;
576             $this->_user->_authhow = 'session';
577             return ENABLE_USER_NEW ? $user->UserName() : $this->_user;
578         }
579         if ($userid = $this->getCookieVar('WIKI_ID')) {
580             if (!empty($userid) and substr($userid,0,2) != 's:') {
581                 $this->_user->authhow = 'cookie';
582                 return $userid;
583             }
584         }
585         return false;
586     }
587     
588     function _isActionPage ($pagename) {
589         $dbi = $this->getDbh();
590         $page = $dbi->getPage($pagename);
591         $rev = $page->getCurrentRevision();
592         // FIXME: more restrictive check for sane plugin?
593         if (strstr($rev->getPackedContent(), '<?plugin'))
594             return true;
595         if (!$rev->hasDefaultContents())
596             trigger_error("$pagename: Does not appear to be an 'action page'", E_USER_NOTICE);
597         return false;
598     }
599
600     function findActionPage ($action) {
601         static $cache;
602
603         // check for translated version, as per users preferred language
604         // (or system default in case it is not en)
605         $translation = gettext($action);
606
607         if (isset($cache) and isset($cache[$translation]))
608             return $cache[$translation];
609
610         // check for cached translated version
611         if ($this->_isActionPage($translation))
612             return $cache[$action] = $translation;
613
614         // Allow for, e.g. action=LikePages
615         global $WikiNameRegexp;
616         if (!preg_match("/$WikiNameRegexp\\Z/A", $action))
617             return $cache[$action] = false;
618
619         // check for translated version (default language)
620         global $LANG;
621         if ($LANG != DEFAULT_LANGUAGE and $LANG != "en") {
622             $save_lang = $LANG;
623             //trigger_error("DEBUG: findActionPage() ". DEFAULT_LANGUAGE." calling update_locale()...");
624             update_locale(DEFAULT_LANGUAGE);
625             $default = gettext($action);
626             //trigger_error("DEBUG: findActionPage() ". $save_lang." restoring save_lang, calling update_locale()...");
627             update_locale($save_lang);
628             if ($this->_isActionPage($default))
629                 return $cache[$action] = $default;
630         }
631         else {
632             $default = $translation;
633         }
634         
635         // check for english version
636         if ($action != $translation and $action != $default) {
637             if ($this->_isActionPage($action))
638                 return $cache[$action] = $action;
639         }
640
641         trigger_error("$action: Cannot find action page", E_USER_NOTICE);
642         return $cache[$action] = false;
643     }
644     
645     function isActionPage ($pagename) {
646         return $this->findActionPage($pagename);
647     }
648
649     function action_browse () {
650         $this->buffer_output();
651         include_once("lib/display.php");
652         displayPage($this);
653     }
654
655     function action_verify () {
656         $this->action_browse();
657     }
658
659     function actionpage ($action) {
660         $this->buffer_output();
661         include_once("lib/display.php");
662         actionPage($this, $action);
663     }
664
665     function action_diff () {
666         $this->buffer_output();
667         include_once "lib/diff.php";
668         showDiff($this);
669     }
670
671     function action_search () {
672         // This is obsolete: reformulate URL and redirect.
673         // FIXME: this whole section should probably be deleted.
674         if ($this->getArg('searchtype') == 'full') {
675             $search_page = _("FullTextSearch");
676         }
677         else {
678             $search_page = _("TitleSearch");
679         }
680         $this->redirect(WikiURL($search_page,
681                                 array('s' => $this->getArg('searchterm')),
682                                 'absolute_url'));
683     }
684
685     function action_edit () {
686         $this->buffer_output();
687         include "lib/editpage.php";
688         $e = new PageEditor ($this);
689         $e->editPage();
690     }
691
692     function action_create () {
693         $this->action_edit();
694     }
695     
696     function action_viewsource () {
697         $this->buffer_output();
698         include "lib/editpage.php";
699         $e = new PageEditor ($this);
700         $e->viewSource();
701     }
702
703     function action_lock () {
704         $page = $this->getPage();
705         $page->set('locked', true);
706         $this->action_browse();
707     }
708
709     function action_unlock () {
710         // FIXME: This check is redundant.
711         //$user->requireAuth(WIKIAUTH_ADMIN);
712         $page = $this->getPage();
713         $page->set('locked', false);
714         $this->action_browse();
715     }
716
717     function action_remove () {
718         // FIXME: This check is redundant.
719         //$user->requireAuth(WIKIAUTH_ADMIN);
720         $pagename = $this->getArg('pagename');
721         if (strstr($pagename,_('PhpWikiAdministration'))) {
722             $this->action_browse();
723         } else {
724             include('lib/removepage.php');
725             RemovePage($this);
726         }
727     }
728
729     function action_xmlrpc () {
730         include_once("lib/XmlRpcServer.php");
731         $xmlrpc = new XmlRpcServer($this);
732         $xmlrpc->service();
733     }
734     
735     function action_zip () {
736         include_once("lib/loadsave.php");
737         MakeWikiZip($this);
738         // I don't think it hurts to add cruft at the end of the zip file.
739         echo "\n========================================================\n";
740         echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
741     }
742
743     function action_ziphtml () {
744         include_once("lib/loadsave.php");
745         MakeWikiZipHtml($this);
746         // I don't think it hurts to add cruft at the end of the zip file.
747         echo "\n========================================================\n";
748         echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
749     }
750
751     function action_dumpserial () {
752         include_once("lib/loadsave.php");
753         DumpToDir($this);
754     }
755
756     function action_dumphtml () {
757         include_once("lib/loadsave.php");
758         DumpHtmlToDir($this);
759     }
760
761     function action_upload () {
762         include_once("lib/loadsave.php");
763         LoadPostFile($this);
764     }
765
766     function action_upgrade () {
767         include_once("lib/loadsave.php");
768         include_once("lib/upgrade.php");
769         DoUpgrade($this);
770     }
771
772     function action_loadfile () {
773         include_once("lib/loadsave.php");
774         LoadFileOrDir($this);
775     }
776 }
777
778 //FIXME: deprecated
779 function is_safe_action ($action) {
780     return WikiRequest::requiredAuthorityForAction($action) < WIKIAUTH_ADMIN;
781 }
782
783 function validateSessionPath() {
784     // Try to defer any session.save_path PHP errors before any html
785     // is output, which causes some versions of IE to display a blank
786     // page (due to its strict mode while parsing a page?).
787     if (! is_writeable(ini_get('session.save_path'))) {
788         $tmpdir = '/tmp';
789         trigger_error
790             (sprintf(_("%s is not writable."),
791                      _("The session.save_path directory"))
792              . "\n"
793              . sprintf(_("Please ensure that %s is writable, or redefine %s in index.php."),
794                        sprintf(_("the directory '%s'"),
795                                ini_get('session.save_path')),
796                        'session.save_path')
797              . "\n"
798              . sprintf(_("Attempting to use the directory '%s' instead."),
799                        $tmpdir)
800              , E_USER_NOTICE);
801         if (! is_writeable($tmpdir)) {
802             trigger_error
803                 (sprintf(_("%s is not writable."), $tmpdir)
804                  . "\n"
805                  . _("Users will not be able to sign in.")
806                  , E_USER_NOTICE);
807         }
808         else
809             ini_set('session.save_path', $tmpdir);
810     }
811 }
812
813 function main () {
814     if (!USE_DB_SESSION)
815         validateSessionPath();
816
817     global $request;
818
819     if (DEBUG and extension_loaded("apd"))
820         apd_set_session_trace(9);
821     $request = new WikiRequest();
822
823     /*
824      * Allow for disabling of markup cache.
825      * (Mostly for debugging ... hopefully.)
826      *
827      * See also <?plugin WikiAdminUtils action=purge-cache ?>
828      */
829     if (!defined('WIKIDB_NOCACHE_MARKUP') and $request->getArg('nocache'))
830         define('WIKIDB_NOCACHE_MARKUP', $request->getArg('nocache'));
831     
832     // Initialize with system defaults in case user not logged in.
833     // Should this go into constructor?
834     $request->initializeTheme();
835
836     $request->updateAuthAndPrefs();
837     $request->initializeLang();
838     
839     // Enable the output of most of the warning messages.
840     // The warnings will screw up zip files though.
841     global $ErrorManager;
842     if (substr($request->getArg('action'), 0, 3) != 'zip') {
843         $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE);
844         //$ErrorManager->setPostponedErrorMask(0);
845     }
846
847     //FIXME:
848     //if ($user->is_authenticated())
849     //  $LogEntry->user = $user->getId();
850
851     $request->possiblyDeflowerVirginWiki();
852     
853 if (defined('WIKI_XMLRPC') and WIKI_XMLRPC) return;
854 if (defined('WIKI_SOAP')   and WIKI_SOAP)   return;
855
856     $validators = array('wikiname' => WIKI_NAME,
857                         'args'     => hash($request->getArgs()),
858                         'prefs'    => hash($request->getPrefs()));
859     if (CACHE_CONTROL == 'STRICT') {
860         $dbi = $request->getDbh();
861         $timestamp = $dbi->getTimestamp();
862         $validators['mtime'] = $timestamp;
863         $validators['%mtime'] = (int)$timestamp;
864     }
865     // FIXME: we should try to generate strong validators when possible,
866     // but for now, our validator is weak, since equal validators do not
867     // indicate byte-level equality of content.  (Due to DEBUG timing output, etc...)
868     //
869     // (If DEBUG if off, this may be a strong validator, but I'm going
870     // to go the paranoid route here pending further study and testing.)
871     //
872     $validators['%weak'] = true;
873     
874     $request->setValidators($validators);
875    
876     $request->handleAction();
877
878 if (defined('DEBUG') and DEBUG & 4) phpinfo(INFO_VARIABLES);
879     $request->finish();
880 }
881
882 $x = error_reporting(); // why is it 1 here? should be E_ALL
883 error_reporting(E_ALL);
884 main();
885
886
887 // $Log: not supported by cvs2svn $
888 // Revision 1.134  2004/04/23 06:46:37  zorloc
889 // Leave DB connection open when USE_DB_SESSION is true so that session info can be written to the DB.
890 //
891 // Revision 1.133  2004/04/20 18:10:31  rurban
892 // config refactoring:
893 //   FileFinder is needed for WikiFarm scripts calling index.php
894 //   config run-time calls moved to lib/IniConfig.php:fix_configs()
895 //   added PHPWIKI_DIR smart-detection code (Theme finder)
896 //   moved FileFind to lib/FileFinder.php
897 //   cleaned lib/config.php
898 //
899 // Revision 1.132  2004/04/19 21:51:41  rurban
900 // php5 compatibility: it works!
901 //
902 // Revision 1.131  2004/04/19 18:27:45  rurban
903 // Prevent from some PHP5 warnings (ref args, no :: object init)
904 //   php5 runs now through, just one wrong XmlElement object init missing
905 // Removed unneccesary UpgradeUser lines
906 // Changed WikiLink to omit version if current (RecentChanges)
907 //
908 // Revision 1.130  2004/04/18 00:25:53  rurban
909 // allow "0" pagename
910 //
911 // Revision 1.129  2004/04/07 23:13:19  rurban
912 // fixed pear/File_Passwd for Windows
913 // fixed FilePassUser sessions (filehandle revive) and password update
914 //
915 // Revision 1.128  2004/04/02 15:06:55  rurban
916 // fixed a nasty ADODB_mysql session update bug
917 // improved UserPreferences layout (tabled hints)
918 // fixed UserPreferences auth handling
919 // improved auth stability
920 // improved old cookie handling: fixed deletion of old cookies with paths
921 //
922 // Revision 1.127  2004/03/25 17:00:31  rurban
923 // more code to convert old-style pref array to new hash
924 //
925 // Revision 1.126  2004/03/24 19:39:03  rurban
926 // php5 workaround code (plus some interim debugging code in XmlElement)
927 //   php5 doesn't work yet with the current XmlElement class constructors,
928 //   WikiUserNew does work better than php4.
929 // rewrote WikiUserNew user upgrading to ease php5 update
930 // fixed pref handling in WikiUserNew
931 // added Email Notification
932 // added simple Email verification
933 // removed emailVerify userpref subclass: just a email property
934 // changed pref binary storage layout: numarray => hash of non default values
935 // print optimize message only if really done.
936 // forced new cookie policy: delete pref cookies, use only WIKI_ID as plain string.
937 //   prefs should be stored in db or homepage, besides the current session.
938 //
939 // Revision 1.125  2004/03/14 16:30:52  rurban
940 // db-handle session revivification, dba fixes
941 //
942 // Revision 1.124  2004/03/12 15:48:07  rurban
943 // fixed explodePageList: wrong sortby argument order in UnfoldSubpages
944 // simplified lib/stdlib.php:explodePageList
945 //
946 // Revision 1.123  2004/03/10 15:41:27  rurban
947 // use default pref mysql table
948 //
949 // Revision 1.122  2004/03/08 18:17:09  rurban
950 // added more WikiGroup::getMembersOf methods, esp. for special groups
951 // fixed $LDAP_SET_OPTIONS
952 // fixed _AuthInfo group methods
953 //
954 // Revision 1.121  2004/03/01 13:48:45  rurban
955 // rename fix
956 // p[] consistency fix
957 //
958 // Revision 1.120  2004/03/01 10:22:41  rurban
959 // initializeTheme optimize
960 //
961 // Revision 1.119  2004/02/26 20:45:06  rurban
962 // check for ALLOW_ANON_USER = false
963 //
964 // Revision 1.118  2004/02/26 01:32:03  rurban
965 // fixed session login with old WikiUser object. strangely, the errormask gets corruoted to 1, Pear???
966 //
967 // Revision 1.117  2004/02/24 17:19:37  rurban
968 // debugging helpers only
969 //
970 // Revision 1.116  2004/02/24 15:17:14  rurban
971 // 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
972 //
973 // Revision 1.115  2004/02/15 21:34:37  rurban
974 // PageList enhanced and improved.
975 // fixed new WikiAdmin... plugins
976 // editpage, Theme with exp. htmlarea framework
977 //   (htmlarea yet committed, this is really questionable)
978 // WikiUser... code with better session handling for prefs
979 // enhanced UserPreferences (again)
980 // RecentChanges for show_deleted: how should pages be deleted then?
981 //
982 // Revision 1.114  2004/02/15 17:30:13  rurban
983 // workaround for lost db connnection handle on session restauration (->_auth_dbi)
984 // fixed getPreferences() (esp. from sessions)
985 // fixed setPreferences() (update and set),
986 // fixed AdoDb DB statements,
987 // update prefs only at UserPreferences POST (for testing)
988 // unified db prefs methods (but in external pref classes yet)
989 //
990 // Revision 1.113  2004/02/12 13:05:49  rurban
991 // Rename functional for PearDB backend
992 // some other minor changes
993 // SiteMap comes with a not yet functional feature request: includepages (tbd)
994 //
995 // Revision 1.112  2004/02/09 03:58:12  rurban
996 // for now default DB_SESSION to false
997 // PagePerm:
998 //   * not existing perms will now query the parent, and not
999 //     return the default perm
1000 //   * added pagePermissions func which returns the object per page
1001 //   * added getAccessDescription
1002 // WikiUserNew:
1003 //   * added global ->prepare (not yet used) with smart user/pref/member table prefixing.
1004 //   * force init of authdbh in the 2 db classes
1005 // main:
1006 //   * fixed session handling (not triple auth request anymore)
1007 //   * don't store cookie prefs with sessions
1008 // stdlib: global obj2hash helper from _AuthInfo, also needed for PagePerm
1009 //
1010 // Revision 1.111  2004/02/07 10:41:25  rurban
1011 // fixed auth from session (still double code but works)
1012 // fixed GroupDB
1013 // fixed DbPassUser upgrade and policy=old
1014 // added GroupLdap
1015 //
1016 // Revision 1.110  2004/02/03 09:45:39  rurban
1017 // LDAP cleanup, start of new Pref classes
1018 //
1019 // Revision 1.109  2004/01/30 19:57:58  rurban
1020 // fixed DBAuthParams['pref_select']: wrong _auth_dbi object used.
1021 //
1022 // Revision 1.108  2004/01/28 14:34:14  rurban
1023 // session table takes the common prefix
1024 // + various minor stuff
1025 // reallow password changing
1026 //
1027 // Revision 1.107  2004/01/27 23:23:39  rurban
1028 // renamed ->Username => _userid for consistency
1029 // renamed mayCheckPassword => mayCheckPass
1030 // fixed recursion problem in WikiUserNew
1031 // fixed bogo login (but not quite 100% ready yet, password storage)
1032 //
1033 // Revision 1.106  2004/01/26 09:17:49  rurban
1034 // * changed stored pref representation as before.
1035 //   the array of objects is 1) bigger and 2)
1036 //   less portable. If we would import packed pref
1037 //   objects and the object definition was changed, PHP would fail.
1038 //   This doesn't happen with an simple array of non-default values.
1039 // * use $prefs->retrieve and $prefs->store methods, where retrieve
1040 //   understands the interim format of array of objects also.
1041 // * simplified $prefs->get() and fixed $prefs->set()
1042 // * added $user->_userid and class '_WikiUser' portability functions
1043 // * fixed $user object ->_level upgrading, mostly using sessions.
1044 //   this fixes yesterdays problems with loosing authorization level.
1045 // * fixed WikiUserNew::checkPass to return the _level
1046 // * fixed WikiUserNew::isSignedIn
1047 // * added explodePageList to class PageList, support sortby arg
1048 // * fixed UserPreferences for WikiUserNew
1049 // * fixed WikiPlugin for empty defaults array
1050 // * UnfoldSubpages: added pagename arg, renamed pages arg,
1051 //   removed sort arg, support sortby arg
1052 //
1053 // Revision 1.105  2004/01/25 03:57:15  rurban
1054 // WikiUserNew support (temp. ENABLE_USER_NEW constant)
1055 //
1056 // Revision 1.104  2003/12/26 06:41:16  carstenklapp
1057 // Bugfix: Try to defer OS errors about session.save_path and ACCESS_LOG,
1058 // so they don't prevent IE from partially (or not at all) rendering the
1059 // page. This should help a little for the IE user who encounters trouble
1060 // when setting up a new PhpWiki for the first time.
1061 //
1062 // Revision 1.103  2003/12/02 00:10:00  carstenklapp
1063 // Bugfix: Ongoing work to untangle UserPreferences/WikiUser/request code
1064 // mess: UserPreferences should take effect immediately now upon signing
1065 // in.
1066 //
1067 // Revision 1.102  2003/11/25 22:55:32  carstenklapp
1068 // Localization bugfix: For wikis where English is not the default system
1069 // language, make sure that the authority error message (i.e. "You must
1070 // sign in to edit pages in this wiki" etc.) is displayed in the wiki's
1071 // default language. Previously it would always display in English.
1072 // (Added call to update_locale() before displaying any messages prior to
1073 // the login prompt.)
1074 //
1075 // Revision 1.101  2003/11/25 21:49:44  carstenklapp
1076 // Bugfix: For a non-english wiki or when the user's preference is not
1077 // english, the wiki would always use the english ActionPage first if it
1078 // was present rather than the appropriate localised variant. (PhpWikis
1079 // running only in english or Wikis running ONLY without any english
1080 // ActionPages would not notice this bug, only when both english and
1081 // localised ActionPages were in the DB.) Now we check for the localised
1082 // variant first.
1083 //
1084 // Revision 1.100  2003/11/18 16:54:18  carstenklapp
1085 // Reformatting only: Tabs to spaces, added rcs log.
1086 //
1087
1088
1089 // Local Variables:
1090 // mode: php
1091 // tab-width: 8
1092 // c-basic-offset: 4
1093 // c-hanging-comment-ender-p: nil
1094 // indent-tabs-mode: nil
1095 // End:
1096 ?>