]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/main.php
session table takes the common prefix
[SourceForge/phpwiki.git] / lib / main.php
1 <?php //-*-php-*-
2 rcs_id('$Id: main.php,v 1.108 2004-01-28 14:34:14 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 if (ENABLE_USER_NEW)
10   require_once("lib/WikiUserNew.php");
11 else
12   require_once("lib/WikiUser.php");
13 require_once("lib/WikiGroup.php");
14 require_once('lib/WikiDB.php');
15
16 class WikiRequest extends Request {
17     // var $_dbi;
18
19     function WikiRequest () {
20         $this->_dbi = WikiDB::open($GLOBALS['DBParams']);
21
22         if (USE_DB_SESSION) {
23             include_once('lib/DB_Session.php');
24             $prefix = isset($GLOBALS['DBParams']['prefix']) ? $GLOBALS['DBParams']['prefix'] : '';
25             $this->_dbsession = & new DB_Session($this->getDbh(),
26                                                  $prefix . $GLOBALS['DBParams']['db_session_table']);
27         }
28         
29         $this->Request();
30
31         // Normalize args...
32         $this->setArg('pagename', $this->_deducePagename());
33         $this->setArg('action', $this->_deduceAction());
34
35         // Restore auth state. This doesn't check for proper authorization!
36         if (ENABLE_USER_NEW) {
37             $userid = $this->_deduceUsername(); 
38             $user = WikiUser($userid);
39             if (isset($this->_user)) 
40                 $user = UpgradeUser($this->_user,$user);
41             $this->_user = $user;
42             $this->_prefs = $this->_user->_prefs;
43         } else {
44             $this->_user = new WikiUser($this, $this->_deduceUsername());
45             $this->_prefs = $this->_user->getPreferences();
46         }
47     }
48
49     function initializeLang () {
50         if ($user_lang = $this->getPref('lang')) {
51             //trigger_error("DEBUG: initializeLang() ". $user_lang ." calling update_locale()...");
52             update_locale($user_lang);
53         }
54     }
55
56     function initializeTheme () {
57         global $Theme;
58
59         // Load theme
60         if ($user_theme = $this->getPref('theme'))
61             include_once("themes/$user_theme/themeinfo.php");
62         if (empty($Theme) and defined ('THEME'))
63             include_once("themes/" . THEME . "/themeinfo.php");
64         if (empty($Theme))
65             include_once("themes/default/themeinfo.php");
66         assert(!empty($Theme));
67     }
68
69
70     // This really maybe should be part of the constructor, but since it
71     // may involve HTML/template output, the global $request really needs
72     // to be initialized before we do this stuff.
73     function updateAuthAndPrefs () {
74         
75         // Handle preference updates, and authentication requests, if any.
76         if ($new_prefs = $this->getArg('pref')) {
77             $this->setArg('pref', false);
78             if ($this->isPost() and !empty($new_prefs['passwd']) and 
79                 ($new_prefs['passwd2'] != $new_prefs['passwd'])) {
80                 // FIXME: enh?
81                 $this->_prefs->set('passwd','');
82                 // $this->_prefs->set('passwd2',''); // This is not stored anyway
83                 return false;
84             }
85             foreach ($new_prefs as $key => $val) {
86                 if ($key == 'passwd') {
87                     // FIXME: enh?
88                     $val = crypt('passwd');
89                 }
90                 $this->_prefs->set($key, $val);
91             }
92         }
93
94         // FIXME: need to move authentication request processing
95         // up to be before pref request processing, I think,
96         // since logging in may change which preferences
97         // we're talking about...
98
99         // even we have disallow anon users?
100         // if (! $this->_user ) $this->_user = new _AnonUser(); 
101
102         // Handle authentication request, if any.
103         if ($auth_args = $this->getArg('auth')) {
104             $this->setArg('auth', false);
105             $this->_handleAuthRequest($auth_args); // possible NORETURN
106         }
107         elseif ( ! $this->_user or ! $this->_user->isSignedIn() ) {
108             // If not auth request, try to sign in as saved user.
109             if (($saved_user = $this->getPref('userid')) != false) {
110                 $this->_signIn($saved_user);
111             }
112         }
113
114         // Save preferences in session and cookie
115         // FIXME: hey! what about anonymous users?   Can't they have
116         // preferences too?
117
118         $id_only = true; 
119         $this->_user->setPreferences($this->_prefs, $id_only);
120
121         // Ensure user has permissions for action
122         $require_level = $this->requiredAuthority($this->getArg('action'));
123         if (! $this->_user->hasAuthority($require_level))
124             $this->_notAuthorized($require_level); // NORETURN
125     }
126
127     function getUser () {
128         return $this->_user;
129     }
130
131     function getPrefs () {
132         return $this->_prefs;
133     }
134
135     // Convenience function:
136     function getPref ($key) {
137         if (isset($this->_prefs))
138             return $this->_prefs->get($key);
139     }
140
141     function getDbh () {
142         return $this->_dbi;
143     }
144
145     function getAuthDbh () {
146         global $DBParams, $DBAuthParams;
147         if (!isset($this->_auth_dbi)) {
148             if ($DBParams['dbtype'] == 'dba' or empty($DBAuthParams['auth_dsn']))
149                 $this->_auth_dbi = $this->getDbh(); // use phpwiki database 
150             elseif ($DBAuthParams['auth_dsn'] == $DBParams['dsn'])
151                 $this->_auth_dbi = $this->getDbh(); // same phpwiki database 
152             else // use external database 
153                 // needs PHP 4.1. better use $this->_user->...
154                 $this->_auth_dbi = WikiDB_User::open($DBAuthParams);
155         }
156         return $this->_auth_dbi;
157     }
158
159     /**
160      * Get requested page from the page database.
161      * By default it will grab the page requested via the URL
162      *
163      * This is a convenience function.
164      * @param string $pagename Name of page to get.
165      * @return WikiDB_Page Object with methods to pull data from
166      * database for the page requested.
167      */
168     function getPage ($pagename = false) {
169         if (!isset($this->_dbi))
170             $this->getDbh();
171         if (!$pagename) 
172             $pagename = $this->getArg('pagename');
173         return $this->_dbi->getPage($pagename);
174     }
175
176     /** Get URL for POST actions.
177      *
178      * Officially, we should just use SCRIPT_NAME (or some such),
179      * but that causes problems when we try to issue a redirect, e.g.
180      * after saving a page.
181      *
182      * Some browsers (at least NS4 and Mozilla 0.97 won't accept
183      * a redirect from a page to itself.)
184      *
185      * So, as a HACK, we include pagename and action as query args in
186      * the URL.  (These should be ignored when we receive the POST
187      * request.)
188      */
189     function getPostURL ($pagename=false) {
190         if ($pagename === false)
191             $pagename = $this->getArg('pagename');
192         $action = $this->getArg('action');
193         if ($this->getArg('start_debug')) // zend ide support
194             return WikiURL($pagename, array('action' => $action, 'start_debug' => 1));
195         else
196             return WikiURL($pagename, array('action' => $action));
197     }
198     
199     function _handleAuthRequest ($auth_args) {
200         if (!is_array($auth_args))
201             return;
202
203         // Ignore password unless POST'ed.
204         if (!$this->isPost())
205             unset($auth_args['passwd']);
206
207         $olduser = $this->_user;
208         $user = $this->_user->AuthCheck($auth_args);
209         if (isa($user,WikiUserClassname())) {
210             // Successful login (or logout.)
211             $this->_setUser($user);
212         }
213         elseif (is_string($user)) {
214             // Login attempt failed.
215             $fail_message = $user;
216             $auth_args['pass_required'] = true;
217             // If no password was submitted, it's not really
218             // a failure --- just need to prompt for password...
219             if (!isset($auth_args['passwd'])) {
220                  //$auth_args['pass_required'] = false;
221                  $fail_message = false;
222             }
223             $olduser->PrintLoginForm($this, $auth_args, $fail_message);
224             $this->finish();    //NORETURN
225         }
226         else {
227             // Login request cancelled.
228         }
229     }
230
231     /**
232      * Attempt to sign in (bogo-login).
233      *
234      * Fails silently.
235      *
236      * @param $userid string Userid to attempt to sign in as.
237      * @access private
238      */
239     function _signIn ($userid) {
240         if (ENABLE_USER_NEW) {
241             if (! $this->_user )
242                 $this->_user = new _BogoUser($userid);
243             if (! $this->_user )
244                 $this->_user = new _PassUser($userid);
245         }
246         $user = $this->_user->AuthCheck(array('userid' => $userid));
247         if (isa($user,WikiUserClassname())) {
248             $this->_setUser($user); // success!
249         }
250     }
251
252     // login or logout or restore state
253     function _setUser ($user) {
254         $this->_user = $user;
255         $this->setCookieVar('WIKI_ID', $user->getAuthenticatedId(), 365);
256         $this->setSessionVar('wiki_user', $user);
257         if ($user->isSignedIn())
258             $user->_authhow = 'signin';
259
260         // Save userid to prefs..
261         if (!($this->_prefs = $this->_user->getPreferences()))
262             $this->_prefs = $this->_user->_prefs;
263         $this->_prefs->set('userid',
264                            $user->isSignedIn() ? $user->getId() : '');
265     }
266
267     function _notAuthorized ($require_level) {
268         // Display the authority message in the Wiki's default
269         // language, in case it is not english.
270         //
271         // Note that normally a user will not see such an error once
272         // logged in, unless the admin has altered the default
273         // disallowed wikiactions. In that case we should probably
274         // check the user's language prefs too at this point; this
275         // would be a situation which is not really handled with the
276         // current code.
277         update_locale(DEFAULT_LANGUAGE);
278
279         // User does not have required authority.  Prompt for login.
280         $what = $this->getActionDescription($this->getArg('action'));
281
282         if ($require_level == WIKIAUTH_FORBIDDEN) {
283             $this->finish(fmt("%s is disallowed on this wiki.",
284                               $this->getDisallowedActionDescription($this->getArg('action'))));
285         }
286         elseif ($require_level == WIKIAUTH_BOGO)
287             $msg = fmt("You must sign in to %s.", $what);
288         elseif ($require_level == WIKIAUTH_USER)
289             $msg = fmt("You must log in to %s.", $what);
290         else
291             $msg = fmt("You must be an administrator to %s.", $what);
292         $pass_required = ($require_level >= WIKIAUTH_USER);
293
294         $this->_user->PrintLoginForm($this, compact('require_level','pass_required'), $msg);
295         $this->finish();    // NORETURN
296     }
297
298     function getActionDescription($action) {
299         static $actionDescriptions;
300         if (! $actionDescriptions) {
301             $actionDescriptions
302             = array('browse'     => _("browse pages in this wiki"),
303                     'diff'       => _("diff pages in this wiki"),
304                     'dumphtml'   => _("dump html pages from this wiki"),
305                     'dumpserial' => _("dump serial pages from this wiki"),
306                     'edit'       => _("edit pages in this wiki"),
307                     'create'     => _("create pages in this wiki"),
308                     'loadfile'   => _("load files into this wiki"),
309                     'lock'       => _("lock pages in this wiki"),
310                     'remove'     => _("remove pages from this wiki"),
311                     'unlock'     => _("unlock pages in this wiki"),
312                     'upload'     => _("upload a zip dump to this wiki"),
313                     'verify'     => _("verify the current action"),
314                     'viewsource' => _("view the source of pages in this wiki"),
315                     'xmlrpc'     => _("access this wiki via XML-RPC"),
316                     'zip'        => _("download a zip dump from this wiki"),
317                     'ziphtml'    => _("download an html zip dump from this wiki")
318                     );
319         }
320         if (in_array($action, array_keys($actionDescriptions)))
321             return $actionDescriptions[$action];
322         else
323             return $action;
324     }
325     function getDisallowedActionDescription($action) {
326         static $disallowedActionDescriptions;
327         if (! $disallowedActionDescriptions) {
328             $disallowedActionDescriptions
329             = array('browse'     => _("Browsing pages"),
330                     'diff'       => _("Diffing pages"),
331                     'dumphtml'   => _("Dumping html pages"),
332                     'dumpserial' => _("Dumping serial pages"),
333                     'edit'       => _("Editing pages"),
334                     'create'     => _("Creating pages"),
335                     'loadfile'   => _("Loading files"),
336                     'lock'       => _("Locking pages"),
337                     'remove'     => _("Removing pages"),
338                     'unlock'     => _("Unlocking pages"),
339                     'upload'     => _("Uploading zip dumps"),
340                     'verify'     => _("Verify the current action"),
341                     'viewsource' => _("Viewing the source of pages"),
342                     'xmlrpc'     => _("XML-RPC access"),
343                     'zip'        => _("Downloading zip dumps"),
344                     'ziphtml'    => _("Downloading html zip dumps")
345                     );
346         }
347         if (in_array($action, array_keys($disallowedActionDescriptions)))
348             return $disallowedActionDescriptions[$action];
349         else
350             return $action;
351     }
352
353     function requiredAuthority ($action) {
354         $auth = $this->requiredAuthorityForAction($action);
355         
356         /*
357          * This is a hook for plugins to require authority
358          * for posting to them.
359          *
360          * IMPORTANT: this is not a secure check, so the plugin
361          * may not assume that any POSTs to it are authorized.
362          * All this does is cause PhpWiki to prompt for login
363          * if the user doesn't have the required authority.
364          */
365         if ($this->isPost()) {
366             $post_auth = $this->getArg('require_authority_for_post');
367             if ($post_auth !== false)
368                 $auth = max($auth, $post_auth);
369         }
370         return $auth;
371     }
372         
373     function requiredAuthorityForAction ($action) {
374         // FIXME: clean up. 
375         // Todo: Check individual page permissions instead.
376         switch ($action) {
377             case 'browse':
378             case 'viewsource':
379             case 'diff':
380             case 'select':
381             case 'xmlrpc':
382             case 'search':
383                 return WIKIAUTH_ANON;
384
385             case 'zip':
386             case 'ziphtml':
387                 if (defined('ZIPDUMP_AUTH') && ZIPDUMP_AUTH)
388                     return WIKIAUTH_ADMIN;
389                 return WIKIAUTH_ANON;
390
391             case 'edit':
392                 if (defined('REQUIRE_SIGNIN_BEFORE_EDIT') && REQUIRE_SIGNIN_BEFORE_EDIT)
393                     return WIKIAUTH_BOGO;
394                 return WIKIAUTH_ANON;
395                 // return WIKIAUTH_BOGO;
396
397             case 'create':
398                 $page = $this->getPage();
399                 $current = $page->getCurrentRevision();
400                 if ($current->hasDefaultContents())
401                     return $this->requiredAuthorityForAction('edit');
402                 return $this->requiredAuthorityForAction('browse');
403
404             case 'upload':
405             case 'dumpserial':
406             case 'dumphtml':
407             case 'loadfile':
408             case 'remove':
409             case 'lock':
410             case 'unlock':
411                 return WIKIAUTH_ADMIN;
412             default:
413                 global $WikiNameRegexp;
414                 if (preg_match("/$WikiNameRegexp\Z/A", $action))
415                     return WIKIAUTH_ANON; // ActionPage.
416                 else
417                     return WIKIAUTH_ADMIN;
418         }
419     }
420
421     function possiblyDeflowerVirginWiki () {
422         if ($this->getArg('action') != 'browse')
423             return;
424         if ($this->getArg('pagename') != HOME_PAGE)
425             return;
426
427         $page = $this->getPage();
428         $current = $page->getCurrentRevision();
429         if ($current->getVersion() > 0)
430             return;             // Homepage exists.
431
432         include('lib/loadsave.php');
433         SetupWiki($this);
434         $this->finish();        // NORETURN
435     }
436
437     function handleAction () {
438         $action = $this->getArg('action');
439         $method = "action_$action";
440         if (method_exists($this, $method)) {
441             $this->{$method}();
442         }
443         elseif ($page = $this->findActionPage($action)) {
444             $this->actionpage($page);
445         }
446         else {
447             $this->finish(fmt("%s: Bad action", $action));
448         }
449     }
450     
451     function finish ($errormsg = false) {
452         static $in_exit = 0;
453
454         if ($in_exit)
455             exit();        // just in case CloseDataBase calls us
456         $in_exit = true;
457
458         if (!empty($this->_dbi))
459             $this->_dbi->close();
460         unset($this->_dbi);
461
462
463         global $ErrorManager;
464         $ErrorManager->flushPostponedErrors();
465
466         if (!empty($errormsg)) {
467             PrintXML(HTML::br(),
468                      HTML::hr(),
469                      HTML::h2(_("Fatal PhpWiki Error")),
470                      $errormsg);
471             // HACK:
472             echo "\n</body></html>";
473         }
474
475         Request::finish();
476         exit;
477     }
478
479     function _deducePagename () {
480         if ($this->getArg('pagename'))
481             return $this->getArg('pagename');
482
483         if (USE_PATH_INFO) {
484             $pathinfo = $this->get('PATH_INFO');
485             $tail = substr($pathinfo, strlen(PATH_INFO_PREFIX));
486
487             if ($tail && $pathinfo == PATH_INFO_PREFIX . $tail) {
488                 return $tail;
489             }
490         }
491         elseif ($this->isPost()) {
492             /*
493              * In general, for security reasons, HTTP_GET_VARS should be ignored
494              * on POST requests, but we make an exception here (only for pagename).
495              *
496              * The justifcation for this hack is the following
497              * asymmetry: When POSTing with USE_PATH_INFO set, the
498              * pagename can (and should) be communicated through the
499              * request URL via PATH_INFO.  When POSTing with
500              * USE_PATH_INFO off, this cannot be done --- the only way
501              * to communicate the pagename through the URL is via
502              * QUERY_ARGS (HTTP_GET_VARS).
503              */
504             global $HTTP_GET_VARS;
505             if (isset($HTTP_GET_VARS['pagename'])) { 
506                 return $HTTP_GET_VARS['pagename'];
507             }
508         }
509
510         /*
511          * Support for PhpWiki 1.2 style requests.
512          */
513         $query_string = $this->get('QUERY_STRING');
514         if (preg_match('/^[^&=]+$/', $query_string)) {
515             return urldecode($query_string);
516         }
517
518         return HOME_PAGE;
519     }
520
521     function _deduceAction () {
522         if (!($action = $this->getArg('action'))) {
523             // Detect XML-RPC requests
524             if ($this->isPost()
525                 && $this->get('CONTENT_TYPE') == 'text/xml') {
526                 global $HTTP_RAW_POST_DATA;
527                 if (strstr($HTTP_RAW_POST_DATA, '<methodCall>')) {
528                     return 'xmlrpc';
529                 }
530             }
531
532             return 'browse';    // Default if no action specified.
533         }
534
535         if (method_exists($this, "action_$action"))
536             return $action;
537
538         // Allow for, e.g. action=LikePages
539         if ($this->isActionPage($action))
540             return $action;
541
542         trigger_error("$action: Unknown action", E_USER_NOTICE);
543         return 'browse';
544     }
545
546     function _deduceUsername() {
547         if (!empty($this->args['auth']) and !empty($this->args['auth']['userid']))
548             return $this->args['auth']['userid'];
549             
550         if ($user = $this->getSessionVar('wiki_user')) {
551             // users might switch in a session between the two objects
552             // restore old auth level?
553             if (isa($user,WikiUserClassname()) and !empty($user->_level)) {
554                 if (empty($this->_user)) {
555                     $c = get_class($user);
556                     $userid = $user->UserName();
557                     if (ENABLE_USER_NEW)
558                         $this->_user = new $c($userid);
559                     else
560                         $this->_user = new $c($this,$userid,$user->_level);
561                 }
562                 if ($user = UpgradeUser($this->_user,$user))
563                     $this->_user = $user;
564                 $this->_user->_authhow = 'session';
565                 
566             }
567             if (isa($user,WikiUserClassname()))
568                 return $user->UserName();
569         }
570         if ($userid = $this->getCookieVar('WIKI_ID')) {
571             if (!empty($this->_user))
572                 $this->_user->authhow = 'cookie';
573             return $userid;
574         }
575         return false;
576     }
577     
578     function _isActionPage ($pagename) {
579         $dbi = $this->getDbh();
580         $page = $dbi->getPage($pagename);
581         $rev = $page->getCurrentRevision();
582         // FIXME: more restrictive check for sane plugin?
583         if (strstr($rev->getPackedContent(), '<?plugin'))
584             return true;
585         if (!$rev->hasDefaultContents())
586             trigger_error("$pagename: Does not appear to be an 'action page'", E_USER_NOTICE);
587         return false;
588     }
589
590     function findActionPage ($action) {
591         static $cache;
592
593         // check for translated version, as per users preferred language
594         // (or system default in case it is not en)
595         $translation = gettext($action);
596
597         if (isset($cache) and isset($cache[$translation]))
598             return $cache[$translation];
599
600         // check for cached translated version
601         if ($this->_isActionPage($translation))
602             return $cache[$action] = $translation;
603
604         // Allow for, e.g. action=LikePages
605         global $WikiNameRegexp;
606         if (!preg_match("/$WikiNameRegexp\\Z/A", $action))
607             return $cache[$action] = false;
608
609         // check for translated version (default language)
610         global $LANG;
611         if ($LANG != DEFAULT_LANGUAGE and $LANG != "en") {
612             $save_lang = $LANG;
613             //trigger_error("DEBUG: findActionPage() ". DEFAULT_LANGUAGE." calling update_locale()...");
614             update_locale(DEFAULT_LANGUAGE);
615             $default = gettext($action);
616             //trigger_error("DEBUG: findActionPage() ". $save_lang." restoring save_lang, calling update_locale()...");
617             update_locale($save_lang);
618             if ($this->_isActionPage($default))
619                 return $cache[$action] = $default;
620         }
621         else {
622             $default = $translation;
623         }
624         
625         // check for english version
626         if ($action != $translation and $action != $default) {
627             if ($this->_isActionPage($action))
628                 return $cache[$action] = $action;
629         }
630
631         trigger_error("$action: Cannot find action page", E_USER_NOTICE);
632         return $cache[$action] = false;
633     }
634     
635     function isActionPage ($pagename) {
636         return $this->findActionPage($pagename);
637     }
638
639     function action_browse () {
640         $this->buffer_output();
641         include_once("lib/display.php");
642         displayPage($this);
643     }
644
645     function action_verify () {
646         $this->action_browse();
647     }
648
649     function actionpage ($action) {
650         $this->buffer_output();
651         include_once("lib/display.php");
652         actionPage($this, $action);
653     }
654
655     function action_diff () {
656         $this->buffer_output();
657         include_once "lib/diff.php";
658         showDiff($this);
659     }
660
661     function action_search () {
662         // This is obsolete: reformulate URL and redirect.
663         // FIXME: this whole section should probably be deleted.
664         if ($this->getArg('searchtype') == 'full') {
665             $search_page = _("FullTextSearch");
666         }
667         else {
668             $search_page = _("TitleSearch");
669         }
670         $this->redirect(WikiURL($search_page,
671                                 array('s' => $this->getArg('searchterm')),
672                                 'absolute_url'));
673     }
674
675     function action_edit () {
676         $this->buffer_output();
677         include "lib/editpage.php";
678         $e = new PageEditor ($this);
679         $e->editPage();
680     }
681
682     function action_create () {
683         $this->action_edit();
684     }
685     
686     function action_viewsource () {
687         $this->buffer_output();
688         include "lib/editpage.php";
689         $e = new PageEditor ($this);
690         $e->viewSource();
691     }
692
693     function action_lock () {
694         $page = $this->getPage();
695         $page->set('locked', true);
696         $this->action_browse();
697     }
698
699     function action_unlock () {
700         // FIXME: This check is redundant.
701         //$user->requireAuth(WIKIAUTH_ADMIN);
702         $page = $this->getPage();
703         $page->set('locked', false);
704         $this->action_browse();
705     }
706
707     function action_remove () {
708         // FIXME: This check is redundant.
709         //$user->requireAuth(WIKIAUTH_ADMIN);
710         $pagename = $this->getArg('pagename');
711         if (strstr($pagename,_('PhpWikiAdministration'))) {
712             $this->action_browse();
713         } else {
714             include('lib/removepage.php');
715             RemovePage($this);
716         }
717     }
718
719
720     function action_upload () {
721         include_once("lib/loadsave.php");
722         LoadPostFile($this);
723     }
724
725     function action_xmlrpc () {
726         include_once("lib/XmlRpcServer.php");
727         $xmlrpc = new XmlRpcServer($this);
728         $xmlrpc->service();
729     }
730     
731     function action_zip () {
732         include_once("lib/loadsave.php");
733         MakeWikiZip($this);
734         // I don't think it hurts to add cruft at the end of the zip file.
735         echo "\n========================================================\n";
736         echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
737     }
738
739     function action_ziphtml () {
740         include_once("lib/loadsave.php");
741         MakeWikiZipHtml($this);
742         // I don't think it hurts to add cruft at the end of the zip file.
743         echo "\n========================================================\n";
744         echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
745     }
746
747     function action_dumpserial () {
748         include_once("lib/loadsave.php");
749         DumpToDir($this);
750     }
751
752     function action_dumphtml () {
753         include_once("lib/loadsave.php");
754         DumpHtmlToDir($this);
755     }
756
757     function action_loadfile () {
758         include_once("lib/loadsave.php");
759         LoadFileOrDir($this);
760     }
761 }
762
763 //FIXME: deprecated
764 function is_safe_action ($action) {
765     return WikiRequest::requiredAuthorityForAction($action) < WIKIAUTH_ADMIN;
766 }
767
768 function validateSessionPath() {
769     // Try to defer any session.save_path PHP errors before any html
770     // is output, which causes some versions of IE to display a blank
771     // page (due to its strict mode while parsing a page?).
772     if (! is_writeable(ini_get('session.save_path'))) {
773         $tmpdir = '/tmp';
774         trigger_error
775             (sprintf(_("%s is not writable."),
776                      _("The session.save_path directory"))
777              . "\n"
778              . sprintf(_("Please ensure that %s is writable, or redefine %s in index.php."),
779                        sprintf(_("the directory '%s'"),
780                                ini_get('session.save_path')),
781                        'session.save_path')
782              . "\n"
783              . sprintf(_("Attempting to use the directory '%s' instead."),
784                        $tmpdir)
785              , E_USER_NOTICE);
786         if (! is_writeable($tmpdir)) {
787             trigger_error
788                 (sprintf(_("%s is not writable."), $tmpdir)
789                  . "\n"
790                  . _("Users will not be able to sign in.")
791                  , E_USER_NOTICE);
792         }
793         else
794             ini_set('session.save_path', $tmpdir);
795     }
796 }
797
798 function main () {
799     if (!USE_DB_SESSION)
800       validateSessionPath();
801
802     global $request;
803
804     $request = new WikiRequest();
805
806     /*
807      * Allow for disabling of markup cache.
808      * (Mostly for debugging ... hopefully.)
809      *
810      * See also <?plugin WikiAdminUtils action=purge-cache ?>
811      */
812     if (!defined('WIKIDB_NOCACHE_MARKUP') and $request->getArg('nocache'))
813         define('WIKIDB_NOCACHE_MARKUP', $request->getArg('nocache'));
814     
815     // Initialize with system defaults in case user not logged in.
816     // Should this go into constructor?
817     $request->initializeTheme();
818
819     $request->updateAuthAndPrefs();
820     // initialize again with user's prefs
821     $request->initializeTheme();
822     $request->initializeLang();
823     
824     // Enable the output of most of the warning messages.
825     // The warnings will screw up zip files though.
826     global $ErrorManager;
827     if (substr($request->getArg('action'), 0, 3) != 'zip') {
828         $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE);
829         //$ErrorManager->setPostponedErrorMask(0);
830     }
831
832     //FIXME:
833     //if ($user->is_authenticated())
834     //  $LogEntry->user = $user->getId();
835
836     $request->possiblyDeflowerVirginWiki();
837     
838 if(defined('WIKI_XMLRPC')) return;
839
840     $validators = array('wikiname' => WIKI_NAME,
841                         'args'     => hash($request->getArgs()),
842                         'prefs'    => hash($request->getPrefs()));
843     if (CACHE_CONTROL == 'STRICT') {
844         $dbi = $request->getDbh();
845         $timestamp = $dbi->getTimestamp();
846         $validators['mtime'] = $timestamp;
847         $validators['%mtime'] = (int)$timestamp;
848     }
849     // FIXME: we should try to generate strong validators when possible,
850     // but for now, our validator is weak, since equal validators do not
851     // indicate byte-level equality of content.  (Due to DEBUG timing output, etc...)
852     //
853     // (If DEBUG if off, this may be a strong validator, but I'm going
854     // to go the paranoid route here pending further study and testing.)
855     //
856     $validators['%weak'] = true;
857     
858     $request->setValidators($validators);
859    
860     $request->handleAction();
861
862 if (defined('DEBUG') and DEBUG>1) phpinfo(INFO_VARIABLES);
863     $request->finish();
864 }
865
866
867 main();
868
869
870 // $Log: not supported by cvs2svn $
871 // Revision 1.107  2004/01/27 23:23:39  rurban
872 // renamed ->Username => _userid for consistency
873 // renamed mayCheckPassword => mayCheckPass
874 // fixed recursion problem in WikiUserNew
875 // fixed bogo login (but not quite 100% ready yet, password storage)
876 //
877 // Revision 1.106  2004/01/26 09:17:49  rurban
878 // * changed stored pref representation as before.
879 //   the array of objects is 1) bigger and 2)
880 //   less portable. If we would import packed pref
881 //   objects and the object definition was changed, PHP would fail.
882 //   This doesn't happen with an simple array of non-default values.
883 // * use $prefs->retrieve and $prefs->store methods, where retrieve
884 //   understands the interim format of array of objects also.
885 // * simplified $prefs->get() and fixed $prefs->set()
886 // * added $user->_userid and class '_WikiUser' portability functions
887 // * fixed $user object ->_level upgrading, mostly using sessions.
888 //   this fixes yesterdays problems with loosing authorization level.
889 // * fixed WikiUserNew::checkPass to return the _level
890 // * fixed WikiUserNew::isSignedIn
891 // * added explodePageList to class PageList, support sortby arg
892 // * fixed UserPreferences for WikiUserNew
893 // * fixed WikiPlugin for empty defaults array
894 // * UnfoldSubpages: added pagename arg, renamed pages arg,
895 //   removed sort arg, support sortby arg
896 //
897 // Revision 1.105  2004/01/25 03:57:15  rurban
898 // WikiUserNew support (temp. ENABLE_USER_NEW constant)
899 //
900 // Revision 1.104  2003/12/26 06:41:16  carstenklapp
901 // Bugfix: Try to defer OS errors about session.save_path and ACCESS_LOG,
902 // so they don't prevent IE from partially (or not at all) rendering the
903 // page. This should help a little for the IE user who encounters trouble
904 // when setting up a new PhpWiki for the first time.
905 //
906 // Revision 1.103  2003/12/02 00:10:00  carstenklapp
907 // Bugfix: Ongoing work to untangle UserPreferences/WikiUser/request code
908 // mess: UserPreferences should take effect immediately now upon signing
909 // in.
910 //
911 // Revision 1.102  2003/11/25 22:55:32  carstenklapp
912 // Localization bugfix: For wikis where English is not the default system
913 // language, make sure that the authority error message (i.e. "You must
914 // sign in to edit pages in this wiki" etc.) is displayed in the wiki's
915 // default language. Previously it would always display in English.
916 // (Added call to update_locale() before displaying any messages prior to
917 // the login prompt.)
918 //
919 // Revision 1.101  2003/11/25 21:49:44  carstenklapp
920 // Bugfix: For a non-english wiki or when the user's preference is not
921 // english, the wiki would always use the english ActionPage first if it
922 // was present rather than the appropriate localised variant. (PhpWikis
923 // running only in english or Wikis running ONLY without any english
924 // ActionPages would not notice this bug, only when both english and
925 // localised ActionPages were in the DB.) Now we check for the localised
926 // variant first.
927 //
928 // Revision 1.100  2003/11/18 16:54:18  carstenklapp
929 // Reformatting only: Tabs to spaces, added rcs log.
930 //
931
932
933 // Local Variables:
934 // mode: php
935 // tab-width: 8
936 // c-basic-offset: 4
937 // c-hanging-comment-ender-p: nil
938 // indent-tabs-mode: nil
939 // End:
940 ?>