]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/main.php
Always use the english version of the ActionPage name for the
[SourceForge/phpwiki.git] / lib / main.php
1 <?php
2 rcs_id('$Id: main.php,v 1.84 2002-09-18 19:29:43 dairiki Exp $');
3
4 define ('USE_PREFS_IN_PAGE', true);
5
6 include "lib/config.php";
7 include "lib/stdlib.php";
8 require_once('lib/Request.php');
9 require_once("lib/WikiUser.php");
10 require_once('lib/WikiDB.php');
11
12 if (USE_DB_SESSION) {
13     require_once('lib/DB_Session.php');
14 }
15
16 class WikiRequest extends Request {
17     // var $_dbi;
18
19     function WikiRequest () {
20         $this->Request();
21         if (USE_DB_SESSION) {
22             $this->_dbi = $this->getDbh();
23             new DB_Session($this->_dbi->_backend->_dbh, $GLOBALS['DBParams']['db_session_table']);
24             $this->session = new Request_SessionVars;
25         }
26
27         // Normalize args...
28         $this->setArg('pagename', $this->_deducePagename());
29         $this->setArg('action', $this->_deduceAction());
30
31         // Restore auth state
32         $this->_user = new WikiUser($this->_deduceUsername());
33         // $this->_user = new WikiDB_User($this->_user->getId(), $this->getAuthDbh());
34         $this->_prefs = $this->_user->getPreferences();
35     }
36
37     // This really maybe should be part of the constructor, but since it
38     // may involve HTML/template output, the global $request really needs
39     // to be initialized before we do this stuff.
40     function updateAuthAndPrefs () {
41         global $Theme;
42         // Handle preference updates, an authentication requests, if any.
43         if ($new_prefs = $this->getArg('pref')) {
44             $this->setArg('pref', false);
45             if ($this->isPost() and !empty($new_prefs['passwd']) and 
46                 ($new_prefs['passwd2'] != $new_prefs['passwd'])) {
47                 $this->_prefs->set('passwd','');
48                 // $this->_prefs->set('passwd2',''); // This is not stored anyway
49                 include_once("themes/" . THEME . "/themeinfo.php");
50                 return false;
51             }
52             foreach ($new_prefs as $key => $val) {
53                 if ($key == 'passwd') {
54                   $val = crypt('passwd');
55                 }
56                 $this->_prefs->set($key, $val);
57             }
58         }
59
60         // Handle authentication request, if any.
61         if ($auth_args = $this->getArg('auth')) {
62             $this->setArg('auth', false);
63             include_once("themes/" . THEME . "/themeinfo.php");
64             $this->_handleAuthRequest($auth_args); // possible NORETURN
65         }
66         elseif ( ! $this->_user->isSignedIn() ) {
67             // If not auth request, try to sign in as saved user.
68             if (($saved_user = $this->getPref('userid')) != false) {
69                 include_once("themes/" . THEME . "/themeinfo.php");
70                 $this->_signIn($saved_user);
71             }
72         }
73
74         // Save preferences in session and cookie
75         $id_only = true;
76         $this->_user->setPreferences($this->_prefs, $id_only);
77         /*
78         if ($theme = $this->getPref('theme') ) {
79             // Load user-defined theme
80             include_once("themes/$theme/themeinfo.php");
81         } else {
82             // site theme
83             include_once("themes/" . THEME . "/themeinfo.php");
84         }
85         */
86         if (empty($Theme)) {
87             include_once("themes/" . THEME . "/themeinfo.php");
88         }
89         if (empty($Theme)) {
90             include_once("themes/default/themeinfo.php");
91         }
92         assert(!empty($Theme));
93
94         // Ensure user has permissions for action
95         $require_level = $this->requiredAuthority($this->getArg('action'));
96         if (! $this->_user->hasAuthority($require_level))
97             $this->_notAuthorized($require_level); // NORETURN
98     }
99
100     function getUser () {
101         return $this->_user;
102     }
103
104     function getPrefs () {
105         return $this->_prefs;
106     }
107
108     // Convenience function:
109     function getPref ($key) {
110         return $this->_prefs->get($key);
111     }
112
113     function getDbh () {
114         if (!isset($this->_dbi)) {
115             // needs PHP 4.1. better use $this->_user->...
116             $this->_dbi = WikiDB::open($GLOBALS['DBParams']);
117         }
118         return $this->_dbi;
119     }
120
121     function getAuthDbh () {
122         global $DBParams, $DBAuthParams;
123         if (!isset($this->_auth_dbi)) {
124             if ($DBParams['dbtype'] == 'dba' or empty($DBAuthParams['auth_dsn']))
125                 $this->_auth_dbi = $this->getDbh(); // use phpwiki database 
126             elseif ($DBAuthParams['auth_dsn'] == $DBParams['dsn'])
127                 $this->_auth_dbi = $this->getDbh(); // same phpwiki database 
128             else // use external database 
129                 // needs PHP 4.1. better use $this->_user->...
130                 $this->_auth_dbi = WikiDB_User::open($DBAuthParams);
131         }
132         return $this->_auth_dbi;
133     }
134
135     /**
136      * Get requested page from the page database.
137      *
138      * This is a convenience function.
139      */
140     function getPage () {
141         if (!isset($this->_dbi))
142             $this->getDbh();
143         return $this->_dbi->getPage($this->getArg('pagename'));
144     }
145
146     function _handleAuthRequest ($auth_args) {
147         if (!is_array($auth_args))
148             return;
149
150         // Ignore password unless POST'ed.
151         if (!$this->isPost())
152             unset($auth_args['passwd']);
153
154         $user = $this->_user->AuthCheck($auth_args);
155
156         if (isa($user, 'WikiUser')) {
157             // Successful login (or logout.)
158             $this->_setUser($user);
159         }
160         elseif ($user) {
161             // Login attempt failed.
162             $fail_message = $user;
163             $auth_args['pass_required'] = true;
164             // If no password was submitted, it's not really
165             // a failure --- just need to prompt for password...
166             if (!isset($auth_args['passwd'])) {
167                  //$auth_args['pass_required'] = false;
168                  $fail_message = false;
169             }
170             $this->_user->PrintLoginForm($this, $auth_args, $fail_message);
171             $this->finish();    //NORETURN
172         }
173         else {
174             // Login request cancelled.
175         }
176     }
177
178     /**
179      * Attempt to sign in (bogo-login).
180      *
181      * Fails silently.
182      *
183      * @param $userid string Userid to attempt to sign in as.
184      * @access private
185      */
186     function _signIn ($userid) {
187         $user = $this->_user->AuthCheck(array('userid' => $userid));
188         if (isa($user, 'WikiUser')) {
189             $this->_setUser($user); // success!
190         }
191     }
192
193     function _setUser ($user) {
194         $this->_user = $user;
195         $this->setCookieVar('WIKI_ID', $user->_userid, 365);
196         $this->setSessionVar('wiki_user', $user);
197         if ($user->isSignedIn())
198             $user->_authhow = 'signin';
199
200         // Save userid to prefs..
201         $this->_prefs->set('userid',
202                            $user->isSignedIn() ? $user->getId() : '');
203     }
204
205     function _notAuthorized ($require_level) {
206         // User does not have required authority.  Prompt for login.
207         $what = $this->getActionDescription($this->getArg('action'));
208
209         if ($require_level >= WIKIAUTH_FORBIDDEN) {
210             $this->finish(fmt("%s is disallowed on this wiki.",
211                               $this->getDisallowedActionDescription($this->getArg('action'))));
212         }
213         elseif ($require_level == WIKIAUTH_BOGO)
214             $msg = fmt("You must sign in to %s.", $what);
215         elseif ($require_level == WIKIAUTH_USER)
216             $msg = fmt("You must log in to %s.", $what);
217         else
218             $msg = fmt("You must be an administrator to %s.", $what);
219         $pass_required = ($require_level >= WIKIAUTH_USER);
220
221         $this->_user->PrintLoginForm($this, compact('require_level','pass_required'), $msg);
222         $this->finish();    // NORETURN
223     }
224
225     function getActionDescription($action) {
226         static $actionDescriptions;
227         if (! $actionDescriptions) {
228             $actionDescriptions
229             = array('browse'     => _("browse pages in this wiki"),
230                     'diff'       => _("diff pages in this wiki"),
231                     'dumphtml'   => _("dump html pages from this wiki"),
232                     'dumpserial' => _("dump serial pages from this wiki"),
233                     'edit'       => _("edit pages in this wiki"),
234                     'loadfile'   => _("load files into this wiki"),
235                     'lock'       => _("lock pages in this wiki"),
236                     'remove'     => _("remove pages from this wiki"),
237                     'unlock'     => _("unlock pages in this wiki"),
238                     'upload'     => _("upload a zip dump to this wiki"),
239                     'verify'     => _("verify the current action"),
240                     'viewsource' => _("view the source of pages in this wiki"),
241                     'xmlrpc'     => _("access this wiki via XML-RPC"),
242                     'zip'        => _("download a zip dump from this wiki"),
243                     'ziphtml'    => _("download an html zip dump from this wiki")
244                     );
245         }
246         if (in_array($action, array_keys($actionDescriptions)))
247             return $actionDescriptions[$action];
248         else
249             return $action;
250     }
251     function getDisallowedActionDescription($action) {
252         static $disallowedActionDescriptions;
253         if (! $disallowedActionDescriptions) {
254             $disallowedActionDescriptions
255             = array('browse'     => _("Browsing pages"),
256                     'diff'       => _("Diffing pages"),
257                     'dumphtml'   => _("Dumping html pages"),
258                     'dumpserial' => _("Dumping serial pages"),
259                     'edit'       => _("Editing pages"),
260                     'loadfile'   => _("Loading files"),
261                     'lock'       => _("Locking pages"),
262                     'remove'     => _("Removing pages"),
263                     'unlock'     => _("Unlocking pages"),
264                     'upload'     => _("Uploading zip dumps"),
265                     'verify'     => _("Verify the current action"),
266                     'viewsource' => _("Viewing the source of pages"),
267                     'xmlrpc'     => _("XML-RPC access"),
268                     'zip'        => _("Downloading zip dumps"),
269                     'ziphtml'    => _("Downloading html zip dumps")
270                     );
271         }
272         if (in_array($action, array_keys($disallowedActionDescriptions)))
273             return $disallowedActionDescriptions[$action];
274         else
275             return $action;
276     }
277
278     function requiredAuthority ($action) {
279         // FIXME: clean up. 
280         // Todo: Check individual page permissions instead.
281         switch ($action) {
282             case 'browse':
283             case 'viewsource':
284             case 'diff':
285             case 'select':
286             case 'xmlrpc':    
287                 return WIKIAUTH_ANON;
288
289             case 'zip':
290                 if (defined('ZIPDUMP_AUTH') && ZIPDUMP_AUTH)
291                     return WIKIAUTH_ADMIN;
292                 return WIKIAUTH_ANON;
293
294             case 'ziphtml':
295                 if (defined('ZIPDUMP_AUTH') && ZIPDUMP_AUTH)
296                     return WIKIAUTH_ADMIN;
297                 return WIKIAUTH_ANON;
298
299             case 'edit':
300                 if (defined('REQUIRE_SIGNIN_BEFORE_EDIT') && REQUIRE_SIGNIN_BEFORE_EDIT)
301                     return WIKIAUTH_BOGO;
302                 return WIKIAUTH_ANON;
303                 // return WIKIAUTH_BOGO;
304
305             case 'upload':
306             case 'dumpserial':
307             case 'dumphtml':
308             case 'loadfile':
309             case 'remove':
310             case 'lock':
311             case 'unlock':
312                 return WIKIAUTH_ADMIN;
313             default:
314                 global $WikiNameRegexp;
315                 if (preg_match("/$WikiNameRegexp\Z/A", $action))
316                     return WIKIAUTH_ANON; // ActionPage.
317                 else
318                     return WIKIAUTH_ADMIN;
319         }
320     }
321
322     function possiblyDeflowerVirginWiki () {
323         if ($this->getArg('action') != 'browse')
324             return;
325         if ($this->getArg('pagename') != HOME_PAGE)
326             return;
327
328         $page = $this->getPage();
329         $current = $page->getCurrentRevision();
330         if ($current->getVersion() > 0)
331             return;             // Homepage exists.
332
333         include('lib/loadsave.php');
334         SetupWiki($this);
335         $this->finish();        // NORETURN
336     }
337
338     function handleAction () {
339         $action = $this->getArg('action');
340         $method = "action_$action";
341         if (method_exists($this, $method)) {
342             $this->{$method}();
343         }
344         elseif ($page = $this->findActionPage($action)) {
345             $this->actionpage($page);
346         }
347         else {
348             $this->finish(fmt("%s: Bad action", $action));
349         }
350     }
351
352
353     function finish ($errormsg = false) {
354         static $in_exit = 0;
355
356         if ($in_exit)
357             exit();        // just in case CloseDataBase calls us
358         $in_exit = true;
359
360         if (!empty($this->_dbi))
361             $this->_dbi->close();
362         unset($this->_dbi);
363
364
365         global $ErrorManager;
366         $ErrorManager->flushPostponedErrors();
367
368         if (!empty($errormsg)) {
369             PrintXML(HTML::br(),
370                      HTML::hr(),
371                      HTML::h2(_("Fatal PhpWiki Error")),
372                      $errormsg);
373             // HACK:
374             echo "\n</body></html>";
375         }
376
377         Request::finish();
378         exit;
379     }
380
381     function _deducePagename () {
382         if ($this->getArg('pagename'))
383             return $this->getArg('pagename');
384
385         if (USE_PATH_INFO) {
386             $pathinfo = $this->get('PATH_INFO');
387             $tail = substr($pathinfo, strlen(PATH_INFO_PREFIX));
388
389             if ($tail && $pathinfo == PATH_INFO_PREFIX . $tail) {
390                 return $tail;
391             }
392         }
393
394         $query_string = $this->get('QUERY_STRING');
395         if (preg_match('/^[^&=]+$/', $query_string)) {
396             return urldecode($query_string);
397         }
398
399         return HOME_PAGE;
400     }
401
402     function _deduceAction () {
403         if (!($action = $this->getArg('action'))) {
404             // Detect XML-RPC requests
405             if ($this->isPost()
406                 && $this->get('CONTENT_TYPE') == 'text/xml') {
407                 global $HTTP_RAW_POST_DATA;
408                 if (strstr($HTTP_RAW_POST_DATA, '<methodCall>')) {
409                     return 'xmlrpc';
410                 }
411             }
412
413             return 'browse';    // Default if no action specified.
414         }
415
416         if (method_exists($this, "action_$action"))
417             return $action;
418
419         // Allow for, e.g. action=LikePages
420         if ($this->isActionPage($action))
421             return $action;
422
423         // Check for _('PhpWikiAdministration').'/'._('Remove') actions
424         $pagename = $this->getArg('pagename');
425         if (strstr($pagename,_('PhpWikiAdministration')))
426             return $action;
427
428         trigger_error("$action: Unknown action", E_USER_NOTICE);
429         return 'browse';
430     }
431
432     function _deduceUsername () {
433         if ($userid = $this->getSessionVar('wiki_user')) {
434             if (!empty($this->_user))
435                 $this->_user->_authhow = 'session';
436             return $userid;
437         }
438         if ($userid = $this->getCookieVar('WIKI_ID')) {
439             if (!empty($this->_user))
440                 $this->_user->authhow = 'cookie';
441             return $userid;
442         }
443         return false;
444     }
445     
446     function _isActionPage ($pagename) {
447         $dbi = $this->getDbh();
448         $page = $dbi->getPage($pagename);
449         $rev = $page->getCurrentRevision();
450         // FIXME: more restrictive check for sane plugin?
451         if (strstr($rev->getPackedContent(), '<?plugin'))
452             return true;
453         if (!$rev->hasDefaultContents())
454             trigger_error("$pagename: Does not appear to be an 'action page'", E_USER_NOTICE);
455         return false;
456     }
457
458     function findActionPage ($action) {
459         static $cache;
460
461         if (isset($cache) and isset($cache[$action]))
462             return $cache[$action];
463         
464         // Allow for, e.g. action=LikePages
465         global $WikiNameRegexp;
466         if (!preg_match("/$WikiNameRegexp\\Z/A", $action))
467             return $cache[$action] = false;
468
469         // check for translated version (users preferred language)
470         $translation = gettext($action);
471         if ($this->_isActionPage($translation))
472             return $cache[$action] = $translation;
473
474         // check for translated version (default language)
475         global $LANG;
476         if ($LANG != DEFAULT_LANGUAGE and $LANG != "en") {
477             $save_lang = $LANG;
478             update_locale(DEFAULT_LANGUAGE);
479             $default = gettext($action);
480             update_locale($save_lang);
481             if ($this->_isActionPage($default))
482                 return $cache[$action] = $default;
483         }
484         else {
485             $default = $translation;
486         }
487         
488         // check for english version
489         if ($action != $translation and $action != $default) {
490             if ($this->_isActionPage($action))
491                 return $cache[$action] = $action;
492         }
493
494         trigger_error("$action: Cannot find action page", E_USER_NOTICE);
495         return $cache[$action] = false;
496     }
497     
498     function isActionPage ($pagename) {
499         return $this->findActionPage($pagename);
500     }
501
502     function action_browse () {
503         $this->compress_output();
504         include_once("lib/display.php");
505         displayPage($this);
506     }
507
508     function action_verify () {
509         $this->action_browse();
510     }
511
512     function actionpage ($action) {
513         $this->compress_output();
514         include_once("lib/display.php");
515         actionPage($this, $action);
516     }
517
518     function action_diff () {
519         $this->compress_output();
520         include_once "lib/diff.php";
521         showDiff($this);
522     }
523
524     function action_search () {
525         // This is obsolete: reformulate URL and redirect.
526         // FIXME: this whole section should probably be deleted.
527         if ($this->getArg('searchtype') == 'full') {
528             $search_page = _("FullTextSearch");
529         }
530         else {
531             $search_page = _("TitleSearch");
532         }
533         $this->redirect(WikiURL($search_page,
534                                 array('s' => $this->getArg('searchterm')),
535                                 'absolute_url'));
536     }
537
538     function action_edit () {
539         $this->compress_output();
540         include "lib/editpage.php";
541         $e = new PageEditor ($this);
542         $e->editPage();
543     }
544
545     function action_viewsource () {
546         $this->compress_output();
547         include "lib/editpage.php";
548         $e = new PageEditor ($this);
549         $e->viewSource();
550     }
551
552     function action_lock () {
553         $page = $this->getPage();
554         $page->set('locked', true);
555         $this->action_browse();
556     }
557
558     function action_unlock () {
559         // FIXME: This check is redundant.
560         //$user->requireAuth(WIKIAUTH_ADMIN);
561         $page = $this->getPage();
562         $page->set('locked', false);
563         $this->action_browse();
564     }
565
566     function action_remove () {
567         // FIXME: This check is redundant.
568         //$user->requireAuth(WIKIAUTH_ADMIN);
569         $pagename = $this->getArg('pagename');
570         if (strstr($pagename,_('PhpWikiAdministration'))) {
571             $this->action_browse();
572         } else {
573             include('lib/removepage.php');
574             RemovePage($this);
575         }
576     }
577
578
579     function action_upload () {
580         include_once("lib/loadsave.php");
581         LoadPostFile($this);
582     }
583
584     function action_xmlrpc () {
585         include_once("lib/XmlRpcServer.php");
586         $xmlrpc = new XmlRpcServer($this);
587         $xmlrpc->service();
588     }
589     
590     function action_zip () {
591         include_once("lib/loadsave.php");
592         MakeWikiZip($this);
593         // I don't think it hurts to add cruft at the end of the zip file.
594         echo "\n========================================================\n";
595         echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
596     }
597
598     function action_ziphtml () {
599         include_once("lib/loadsave.php");
600         MakeWikiZipHtml($this);
601         // I don't think it hurts to add cruft at the end of the zip file.
602         echo "\n========================================================\n";
603         echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
604     }
605
606     function action_dumpserial () {
607         include_once("lib/loadsave.php");
608         DumpToDir($this);
609     }
610
611     function action_dumphtml () {
612         include_once("lib/loadsave.php");
613         DumpHtmlToDir($this);
614     }
615
616     function action_loadfile () {
617         include_once("lib/loadsave.php");
618         LoadFileOrDir($this);
619     }
620 }
621
622 //FIXME: deprecated
623 function is_safe_action ($action) {
624     return WikiRequest::requiredAuthority($action) < WIKIAUTH_ADMIN;
625 }
626
627
628 function main () {
629     global $request;
630
631     $request = new WikiRequest();
632     $request->updateAuthAndPrefs();
633
634     /* FIXME: is this needed anymore?
635         if (USE_PATH_INFO && ! $request->get('PATH_INFO')
636             && ! preg_match(',/$,', $request->get('REDIRECT_URL'))) {
637             $request->redirect(SERVER_URL
638                                . preg_replace('/(\?|$)/', '/\1',
639                                               $request->get('REQUEST_URI'),
640                                               1));
641             exit;
642         }
643     */
644
645     // Enable the output of most of the warning messages.
646     // The warnings will screw up zip files though.
647     global $ErrorManager;
648     if (substr($request->getArg('action'), 0, 3) != 'zip') {
649         $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE);
650         //$ErrorManager->setPostponedErrorMask(0);
651     }
652
653     //FIXME:
654     //if ($user->is_authenticated())
655     //  $LogEntry->user = $user->getId();
656
657     $request->possiblyDeflowerVirginWiki();
658 if(defined('WIKI_XMLRPC')) return;
659     $request->handleAction();
660 if (defined('DEBUG') and DEBUG>1) phpinfo(INFO_VARIABLES);
661     $request->finish();
662 }
663
664 // Used for debugging purposes
665 function getmicrotime(){
666     list($usec, $sec) = explode(" ", microtime());
667     return ((float)$usec + (float)$sec);
668 }
669 if (defined('DEBUG')) $GLOBALS['debugclock'] = getmicrotime();
670
671 main();
672
673
674 // Local Variables:
675 // mode: php
676 // tab-width: 8
677 // c-basic-offset: 4
678 // c-hanging-comment-ender-p: nil
679 // indent-tabs-mode: nil
680 // End:
681 ?>