]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/main.php
The main script will now notice when you're directing and XML-RPC
[SourceForge/phpwiki.git] / lib / main.php
1 <?php
2 rcs_id('$Id: main.php,v 1.81 2002-09-14 22:28:33 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                 // Temp workaround for french single-word action pages 'Historique'
315                 // Some of this make sense as SubPage actions or buttons.
316                 $singleWordActionPages = 
317                     array("Historique", "Info",
318                           _("Preferences"), _("Administration"), 
319                           _("Today"), _("Help"));
320                 if (in_array($action, $singleWordActionPages))
321                     return WIKIAUTH_ANON; // ActionPage.
322                 global $WikiNameRegexp;
323                 if (preg_match("/$WikiNameRegexp\Z/A", $action))
324                     return WIKIAUTH_ANON; // ActionPage.
325                 else
326                     return WIKIAUTH_ADMIN;
327         }
328     }
329
330     function possiblyDeflowerVirginWiki () {
331         if ($this->getArg('action') != 'browse')
332             return;
333         if ($this->getArg('pagename') != HOME_PAGE)
334             return;
335
336         $page = $this->getPage();
337         $current = $page->getCurrentRevision();
338         if ($current->getVersion() > 0)
339             return;             // Homepage exists.
340
341         include('lib/loadsave.php');
342         SetupWiki($this);
343         $this->finish();        // NORETURN
344     }
345
346     function handleAction () {
347         $action = $this->getArg('action');
348         $method = "action_$action";
349         if (method_exists($this, $method)) {
350             $this->{$method}();
351         }
352         elseif ($this->isActionPage($action)) {
353             $this->actionpage($action);
354         }
355         else {
356             $this->finish(fmt("%s: Bad action", $action));
357         }
358     }
359
360
361     function finish ($errormsg = false) {
362         static $in_exit = 0;
363
364         if ($in_exit)
365             exit();        // just in case CloseDataBase calls us
366         $in_exit = true;
367
368         if (!empty($this->_dbi))
369             $this->_dbi->close();
370         unset($this->_dbi);
371
372
373         global $ErrorManager;
374         $ErrorManager->flushPostponedErrors();
375
376         if (!empty($errormsg)) {
377             PrintXML(HTML::br(),
378                      HTML::hr(),
379                      HTML::h2(_("Fatal PhpWiki Error")),
380                      $errormsg);
381             // HACK:
382             echo "\n</body></html>";
383         }
384
385         Request::finish();
386         exit;
387     }
388
389     function _deducePagename () {
390         if ($this->getArg('pagename'))
391             return $this->getArg('pagename');
392
393         if (USE_PATH_INFO) {
394             $pathinfo = $this->get('PATH_INFO');
395             $tail = substr($pathinfo, strlen(PATH_INFO_PREFIX));
396
397             if ($tail && $pathinfo == PATH_INFO_PREFIX . $tail) {
398                 return $tail;
399             }
400         }
401
402         $query_string = $this->get('QUERY_STRING');
403         if (preg_match('/^[^&=]+$/', $query_string)) {
404             return urldecode($query_string);
405         }
406
407         return HOME_PAGE;
408     }
409
410     function _deduceAction () {
411         if (!($action = $this->getArg('action'))) {
412             // Detect XML-RPC requests
413             if ($this->isPost()
414                 && $this->get('CONTENT_TYPE') == 'text/xml') {
415                 global $HTTP_RAW_POST_DATA;
416                 if (strstr($HTTP_RAW_POST_DATA, '<methodCall>')) {
417                     return 'xmlrpc';
418                 }
419             }
420
421             return 'browse';    // Default if no action specified.
422         }
423
424         if (method_exists($this, "action_$action"))
425             return $action;
426
427         // Allow for, e.g. action=LikePages
428         if ($this->isActionPage($action))
429             return $action;
430
431         // Check for _('PhpWikiAdministration').'/'._('Remove') actions
432         $pagename = $this->getArg('pagename');
433         if (strstr($pagename,_('PhpWikiAdministration')))
434             return $action;
435
436         trigger_error("$action: Unknown action", E_USER_NOTICE);
437         return 'browse';
438     }
439
440     function _deduceUsername () {
441         if ($userid = $this->getSessionVar('wiki_user')) {
442             if (!empty($this->_user))
443                 $this->_user->_authhow = 'session';
444             return $userid;
445         }
446         if ($userid = $this->getCookieVar('WIKI_ID')) {
447             if (!empty($this->_user))
448                 $this->_user->authhow = 'cookie';
449             return $userid;
450         }
451         return false;
452     }
453     
454     function isActionPage ($pagename) {
455         if (isSubPage($pagename)) 
456             $subpagename = subPageSlice($pagename,-1); // last element
457         else 
458             $subpagename = $pagename;
459         // Temp workaround for french single-word action page 'Historique'
460         $singleWordActionPages = array("Historique", "Info", _('Preferences'));
461         if (! in_array($subpagename, $singleWordActionPages)) {
462             // Allow for, e.g. action=LikePages
463             global $WikiNameRegexp;
464             if (!preg_match("/$WikiNameRegexp\\Z/A", $subpagename))
465                 return false;
466         }
467         $dbi = $this->getDbh();
468         $page = $dbi->getPage($pagename);
469         $rev = $page->getCurrentRevision();
470         // FIXME: more restrictive check for sane plugin?
471         if (strstr($rev->getPackedContent(), '<?plugin'))
472             return true;
473         trigger_error("$pagename: Does not appear to be an 'action page'", E_USER_NOTICE);
474         return false;
475     }
476
477     function action_browse () {
478         $this->compress_output();
479         include_once("lib/display.php");
480         displayPage($this);
481     }
482
483     function action_verify () {
484         $this->action_browse();
485     }
486
487     function actionpage ($action) {
488         $this->compress_output();
489         include_once("lib/display.php");
490         actionPage($this, $action);
491     }
492
493     function action_diff () {
494         $this->compress_output();
495         include_once "lib/diff.php";
496         showDiff($this);
497     }
498
499     function action_search () {
500         // This is obsolete: reformulate URL and redirect.
501         // FIXME: this whole section should probably be deleted.
502         if ($this->getArg('searchtype') == 'full') {
503             $search_page = _("FullTextSearch");
504         }
505         else {
506             $search_page = _("TitleSearch");
507         }
508         $this->redirect(WikiURL($search_page,
509                                 array('s' => $this->getArg('searchterm')),
510                                 'absolute_url'));
511     }
512
513     function action_edit () {
514         $this->compress_output();
515         include "lib/editpage.php";
516         $e = new PageEditor ($this);
517         $e->editPage();
518     }
519
520     function action_viewsource () {
521         $this->compress_output();
522         include "lib/editpage.php";
523         $e = new PageEditor ($this);
524         $e->viewSource();
525     }
526
527     function action_lock () {
528         $page = $this->getPage();
529         $page->set('locked', true);
530         $this->action_browse();
531     }
532
533     function action_unlock () {
534         // FIXME: This check is redundant.
535         //$user->requireAuth(WIKIAUTH_ADMIN);
536         $page = $this->getPage();
537         $page->set('locked', false);
538         $this->action_browse();
539     }
540
541     function action_remove () {
542         // FIXME: This check is redundant.
543         //$user->requireAuth(WIKIAUTH_ADMIN);
544         $pagename = $this->getArg('pagename');
545         if (strstr($pagename,_('PhpWikiAdministration'))) {
546             $this->action_browse();
547         } else {
548             include('lib/removepage.php');
549             RemovePage($this);
550         }
551     }
552
553
554     function action_upload () {
555         include_once("lib/loadsave.php");
556         LoadPostFile($this);
557     }
558
559     function action_xmlrpc () {
560         include_once("lib/XmlRpcServer.php");
561         $xmlrpc = new XmlRpcServer($this);
562         $xmlrpc->service();
563     }
564     
565     function action_zip () {
566         include_once("lib/loadsave.php");
567         MakeWikiZip($this);
568         // I don't think it hurts to add cruft at the end of the zip file.
569         echo "\n========================================================\n";
570         echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
571     }
572
573     function action_ziphtml () {
574         include_once("lib/loadsave.php");
575         MakeWikiZipHtml($this);
576         // I don't think it hurts to add cruft at the end of the zip file.
577         echo "\n========================================================\n";
578         echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
579     }
580
581     function action_dumpserial () {
582         include_once("lib/loadsave.php");
583         DumpToDir($this);
584     }
585
586     function action_dumphtml () {
587         include_once("lib/loadsave.php");
588         DumpHtmlToDir($this);
589     }
590
591     function action_loadfile () {
592         include_once("lib/loadsave.php");
593         LoadFileOrDir($this);
594     }
595 }
596
597 //FIXME: deprecated
598 function is_safe_action ($action) {
599     return WikiRequest::requiredAuthority($action) < WIKIAUTH_ADMIN;
600 }
601
602
603 function main () {
604     global $request;
605
606     $request = new WikiRequest();
607     $request->updateAuthAndPrefs();
608
609     /* FIXME: is this needed anymore?
610         if (USE_PATH_INFO && ! $request->get('PATH_INFO')
611             && ! preg_match(',/$,', $request->get('REDIRECT_URL'))) {
612             $request->redirect(SERVER_URL
613                                . preg_replace('/(\?|$)/', '/\1',
614                                               $request->get('REQUEST_URI'),
615                                               1));
616             exit;
617         }
618     */
619
620     // Enable the output of most of the warning messages.
621     // The warnings will screw up zip files though.
622     global $ErrorManager;
623     if (substr($request->getArg('action'), 0, 3) != 'zip') {
624         $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE);
625         //$ErrorManager->setPostponedErrorMask(0);
626     }
627
628     //FIXME:
629     //if ($user->is_authenticated())
630     //  $LogEntry->user = $user->getId();
631
632     $request->possiblyDeflowerVirginWiki();
633 if(defined('WIKI_XMLRPC')) return;
634     $request->handleAction();
635 if (defined('DEBUG') and DEBUG>1) phpinfo(INFO_VARIABLES);
636     $request->finish();
637 }
638
639 // Used for debugging purposes
640 function getmicrotime(){
641     list($usec, $sec) = explode(" ", microtime());
642     return ((float)$usec + (float)$sec);
643 }
644 if (defined('DEBUG')) $GLOBALS['debugclock'] = getmicrotime();
645
646 main();
647
648
649 // Local Variables:
650 // mode: php
651 // tab-width: 8
652 // c-basic-offset: 4
653 // c-hanging-comment-ender-p: nil
654 // indent-tabs-mode: nil
655 // End:
656 ?>