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