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