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