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