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