]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/main.php
New method WikiRequst::fullPagename() to expand relative subpages to full
[SourceForge/phpwiki.git] / lib / main.php
1 <?php
2 rcs_id('$Id: main.php,v 1.82 2002-09-16 18:49:17 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     /**
147      * Convert (possibly) relative name of subpage to full name.
148      *
149      * @param string $relname
150      * @return string
151      */
152     function fullPagename ($relname) {
153         if ($relname[0] == SUBPAGE_SEPARATOR)
154             return $this->getArg('pagename') . $relname;
155         else
156             return $relname;
157     }
158      
159     function _handleAuthRequest ($auth_args) {
160         if (!is_array($auth_args))
161             return;
162
163         // Ignore password unless POST'ed.
164         if (!$this->isPost())
165             unset($auth_args['passwd']);
166
167         $user = $this->_user->AuthCheck($auth_args);
168
169         if (isa($user, 'WikiUser')) {
170             // Successful login (or logout.)
171             $this->_setUser($user);
172         }
173         elseif ($user) {
174             // Login attempt failed.
175             $fail_message = $user;
176             $auth_args['pass_required'] = true;
177             // If no password was submitted, it's not really
178             // a failure --- just need to prompt for password...
179             if (!isset($auth_args['passwd'])) {
180                  //$auth_args['pass_required'] = false;
181                  $fail_message = false;
182             }
183             $this->_user->PrintLoginForm($this, $auth_args, $fail_message);
184             $this->finish();    //NORETURN
185         }
186         else {
187             // Login request cancelled.
188         }
189     }
190
191     /**
192      * Attempt to sign in (bogo-login).
193      *
194      * Fails silently.
195      *
196      * @param $userid string Userid to attempt to sign in as.
197      * @access private
198      */
199     function _signIn ($userid) {
200         $user = $this->_user->AuthCheck(array('userid' => $userid));
201         if (isa($user, 'WikiUser')) {
202             $this->_setUser($user); // success!
203         }
204     }
205
206     function _setUser ($user) {
207         $this->_user = $user;
208         $this->setCookieVar('WIKI_ID', $user->_userid, 365);
209         $this->setSessionVar('wiki_user', $user);
210         if ($user->isSignedIn())
211             $user->_authhow = 'signin';
212
213         // Save userid to prefs..
214         $this->_prefs->set('userid',
215                            $user->isSignedIn() ? $user->getId() : '');
216     }
217
218     function _notAuthorized ($require_level) {
219         // User does not have required authority.  Prompt for login.
220         $what = $this->getActionDescription($this->getArg('action'));
221
222         if ($require_level >= WIKIAUTH_FORBIDDEN) {
223             $this->finish(fmt("%s is disallowed on this wiki.",
224                               $this->getDisallowedActionDescription($this->getArg('action'))));
225         }
226         elseif ($require_level == WIKIAUTH_BOGO)
227             $msg = fmt("You must sign in to %s.", $what);
228         elseif ($require_level == WIKIAUTH_USER)
229             $msg = fmt("You must log in to %s.", $what);
230         else
231             $msg = fmt("You must be an administrator to %s.", $what);
232         $pass_required = ($require_level >= WIKIAUTH_USER);
233
234         $this->_user->PrintLoginForm($this, compact('require_level','pass_required'), $msg);
235         $this->finish();    // NORETURN
236     }
237
238     function getActionDescription($action) {
239         static $actionDescriptions;
240         if (! $actionDescriptions) {
241             $actionDescriptions
242             = array('browse'     => _("browse pages in this wiki"),
243                     'diff'       => _("diff pages in this wiki"),
244                     'dumphtml'   => _("dump html pages from this wiki"),
245                     'dumpserial' => _("dump serial pages from this wiki"),
246                     'edit'       => _("edit pages in this wiki"),
247                     'loadfile'   => _("load files into this wiki"),
248                     'lock'       => _("lock pages in this wiki"),
249                     'remove'     => _("remove pages from this wiki"),
250                     'unlock'     => _("unlock pages in this wiki"),
251                     'upload'     => _("upload a zip dump to this wiki"),
252                     'verify'     => _("verify the current action"),
253                     'viewsource' => _("view the source of pages in this wiki"),
254                     'xmlrpc'     => _("access this wiki via XML-RPC"),
255                     'zip'        => _("download a zip dump from this wiki"),
256                     'ziphtml'    => _("download an html zip dump from this wiki")
257                     );
258         }
259         if (in_array($action, array_keys($actionDescriptions)))
260             return $actionDescriptions[$action];
261         else
262             return $action;
263     }
264     function getDisallowedActionDescription($action) {
265         static $disallowedActionDescriptions;
266         if (! $disallowedActionDescriptions) {
267             $disallowedActionDescriptions
268             = array('browse'     => _("Browsing pages"),
269                     'diff'       => _("Diffing pages"),
270                     'dumphtml'   => _("Dumping html pages"),
271                     'dumpserial' => _("Dumping serial pages"),
272                     'edit'       => _("Editing pages"),
273                     'loadfile'   => _("Loading files"),
274                     'lock'       => _("Locking pages"),
275                     'remove'     => _("Removing pages"),
276                     'unlock'     => _("Unlocking pages"),
277                     'upload'     => _("Uploading zip dumps"),
278                     'verify'     => _("Verify the current action"),
279                     'viewsource' => _("Viewing the source of pages"),
280                     'xmlrpc'     => _("XML-RPC access"),
281                     'zip'        => _("Downloading zip dumps"),
282                     'ziphtml'    => _("Downloading html zip dumps")
283                     );
284         }
285         if (in_array($action, array_keys($disallowedActionDescriptions)))
286             return $disallowedActionDescriptions[$action];
287         else
288             return $action;
289     }
290
291     function requiredAuthority ($action) {
292         // FIXME: clean up. 
293         // Todo: Check individual page permissions instead.
294         switch ($action) {
295             case 'browse':
296             case 'viewsource':
297             case 'diff':
298             case 'select':
299             case 'xmlrpc':    
300                 return WIKIAUTH_ANON;
301
302             case 'zip':
303                 if (defined('ZIPDUMP_AUTH') && ZIPDUMP_AUTH)
304                     return WIKIAUTH_ADMIN;
305                 return WIKIAUTH_ANON;
306
307             case 'ziphtml':
308                 if (defined('ZIPDUMP_AUTH') && ZIPDUMP_AUTH)
309                     return WIKIAUTH_ADMIN;
310                 return WIKIAUTH_ANON;
311
312             case 'edit':
313                 if (defined('REQUIRE_SIGNIN_BEFORE_EDIT') && REQUIRE_SIGNIN_BEFORE_EDIT)
314                     return WIKIAUTH_BOGO;
315                 return WIKIAUTH_ANON;
316                 // return WIKIAUTH_BOGO;
317
318             case 'upload':
319             case 'dumpserial':
320             case 'dumphtml':
321             case 'loadfile':
322             case 'remove':
323             case 'lock':
324             case 'unlock':
325                 return WIKIAUTH_ADMIN;
326             default:
327                 // Temp workaround for french single-word action pages 'Historique'
328                 // Some of this make sense as SubPage actions or buttons.
329                 $singleWordActionPages = 
330                     array("Historique", "Info",
331                           _("Preferences"), _("Administration"), 
332                           _("Today"), _("Help"));
333                 if (in_array($action, $singleWordActionPages))
334                     return WIKIAUTH_ANON; // ActionPage.
335                 global $WikiNameRegexp;
336                 if (preg_match("/$WikiNameRegexp\Z/A", $action))
337                     return WIKIAUTH_ANON; // ActionPage.
338                 else
339                     return WIKIAUTH_ADMIN;
340         }
341     }
342
343     function possiblyDeflowerVirginWiki () {
344         if ($this->getArg('action') != 'browse')
345             return;
346         if ($this->getArg('pagename') != HOME_PAGE)
347             return;
348
349         $page = $this->getPage();
350         $current = $page->getCurrentRevision();
351         if ($current->getVersion() > 0)
352             return;             // Homepage exists.
353
354         include('lib/loadsave.php');
355         SetupWiki($this);
356         $this->finish();        // NORETURN
357     }
358
359     function handleAction () {
360         $action = $this->getArg('action');
361         $method = "action_$action";
362         if (method_exists($this, $method)) {
363             $this->{$method}();
364         }
365         elseif ($this->isActionPage($action)) {
366             $this->actionpage($action);
367         }
368         else {
369             $this->finish(fmt("%s: Bad action", $action));
370         }
371     }
372
373
374     function finish ($errormsg = false) {
375         static $in_exit = 0;
376
377         if ($in_exit)
378             exit();        // just in case CloseDataBase calls us
379         $in_exit = true;
380
381         if (!empty($this->_dbi))
382             $this->_dbi->close();
383         unset($this->_dbi);
384
385
386         global $ErrorManager;
387         $ErrorManager->flushPostponedErrors();
388
389         if (!empty($errormsg)) {
390             PrintXML(HTML::br(),
391                      HTML::hr(),
392                      HTML::h2(_("Fatal PhpWiki Error")),
393                      $errormsg);
394             // HACK:
395             echo "\n</body></html>";
396         }
397
398         Request::finish();
399         exit;
400     }
401
402     function _deducePagename () {
403         if ($this->getArg('pagename'))
404             return $this->getArg('pagename');
405
406         if (USE_PATH_INFO) {
407             $pathinfo = $this->get('PATH_INFO');
408             $tail = substr($pathinfo, strlen(PATH_INFO_PREFIX));
409
410             if ($tail && $pathinfo == PATH_INFO_PREFIX . $tail) {
411                 return $tail;
412             }
413         }
414
415         $query_string = $this->get('QUERY_STRING');
416         if (preg_match('/^[^&=]+$/', $query_string)) {
417             return urldecode($query_string);
418         }
419
420         return HOME_PAGE;
421     }
422
423     function _deduceAction () {
424         if (!($action = $this->getArg('action'))) {
425             // Detect XML-RPC requests
426             if ($this->isPost()
427                 && $this->get('CONTENT_TYPE') == 'text/xml') {
428                 global $HTTP_RAW_POST_DATA;
429                 if (strstr($HTTP_RAW_POST_DATA, '<methodCall>')) {
430                     return 'xmlrpc';
431                 }
432             }
433
434             return 'browse';    // Default if no action specified.
435         }
436
437         if (method_exists($this, "action_$action"))
438             return $action;
439
440         // Allow for, e.g. action=LikePages
441         if ($this->isActionPage($action))
442             return $action;
443
444         // Check for _('PhpWikiAdministration').'/'._('Remove') actions
445         $pagename = $this->getArg('pagename');
446         if (strstr($pagename,_('PhpWikiAdministration')))
447             return $action;
448
449         trigger_error("$action: Unknown action", E_USER_NOTICE);
450         return 'browse';
451     }
452
453     function _deduceUsername () {
454         if ($userid = $this->getSessionVar('wiki_user')) {
455             if (!empty($this->_user))
456                 $this->_user->_authhow = 'session';
457             return $userid;
458         }
459         if ($userid = $this->getCookieVar('WIKI_ID')) {
460             if (!empty($this->_user))
461                 $this->_user->authhow = 'cookie';
462             return $userid;
463         }
464         return false;
465     }
466     
467     function isActionPage ($pagename) {
468         if (isSubPage($pagename)) 
469             $subpagename = subPageSlice($pagename,-1); // last element
470         else 
471             $subpagename = $pagename;
472         // Temp workaround for french single-word action page 'Historique'
473         $singleWordActionPages = array("Historique", "Info", _('Preferences'));
474         if (! in_array($subpagename, $singleWordActionPages)) {
475             // Allow for, e.g. action=LikePages
476             global $WikiNameRegexp;
477             if (!preg_match("/$WikiNameRegexp\\Z/A", $subpagename))
478                 return false;
479         }
480         $dbi = $this->getDbh();
481         $page = $dbi->getPage($pagename);
482         $rev = $page->getCurrentRevision();
483         // FIXME: more restrictive check for sane plugin?
484         if (strstr($rev->getPackedContent(), '<?plugin'))
485             return true;
486         trigger_error("$pagename: Does not appear to be an 'action page'", E_USER_NOTICE);
487         return false;
488     }
489
490     function action_browse () {
491         $this->compress_output();
492         include_once("lib/display.php");
493         displayPage($this);
494     }
495
496     function action_verify () {
497         $this->action_browse();
498     }
499
500     function actionpage ($action) {
501         $this->compress_output();
502         include_once("lib/display.php");
503         actionPage($this, $action);
504     }
505
506     function action_diff () {
507         $this->compress_output();
508         include_once "lib/diff.php";
509         showDiff($this);
510     }
511
512     function action_search () {
513         // This is obsolete: reformulate URL and redirect.
514         // FIXME: this whole section should probably be deleted.
515         if ($this->getArg('searchtype') == 'full') {
516             $search_page = _("FullTextSearch");
517         }
518         else {
519             $search_page = _("TitleSearch");
520         }
521         $this->redirect(WikiURL($search_page,
522                                 array('s' => $this->getArg('searchterm')),
523                                 'absolute_url'));
524     }
525
526     function action_edit () {
527         $this->compress_output();
528         include "lib/editpage.php";
529         $e = new PageEditor ($this);
530         $e->editPage();
531     }
532
533     function action_viewsource () {
534         $this->compress_output();
535         include "lib/editpage.php";
536         $e = new PageEditor ($this);
537         $e->viewSource();
538     }
539
540     function action_lock () {
541         $page = $this->getPage();
542         $page->set('locked', true);
543         $this->action_browse();
544     }
545
546     function action_unlock () {
547         // FIXME: This check is redundant.
548         //$user->requireAuth(WIKIAUTH_ADMIN);
549         $page = $this->getPage();
550         $page->set('locked', false);
551         $this->action_browse();
552     }
553
554     function action_remove () {
555         // FIXME: This check is redundant.
556         //$user->requireAuth(WIKIAUTH_ADMIN);
557         $pagename = $this->getArg('pagename');
558         if (strstr($pagename,_('PhpWikiAdministration'))) {
559             $this->action_browse();
560         } else {
561             include('lib/removepage.php');
562             RemovePage($this);
563         }
564     }
565
566
567     function action_upload () {
568         include_once("lib/loadsave.php");
569         LoadPostFile($this);
570     }
571
572     function action_xmlrpc () {
573         include_once("lib/XmlRpcServer.php");
574         $xmlrpc = new XmlRpcServer($this);
575         $xmlrpc->service();
576     }
577     
578     function action_zip () {
579         include_once("lib/loadsave.php");
580         MakeWikiZip($this);
581         // I don't think it hurts to add cruft at the end of the zip file.
582         echo "\n========================================================\n";
583         echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
584     }
585
586     function action_ziphtml () {
587         include_once("lib/loadsave.php");
588         MakeWikiZipHtml($this);
589         // I don't think it hurts to add cruft at the end of the zip file.
590         echo "\n========================================================\n";
591         echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
592     }
593
594     function action_dumpserial () {
595         include_once("lib/loadsave.php");
596         DumpToDir($this);
597     }
598
599     function action_dumphtml () {
600         include_once("lib/loadsave.php");
601         DumpHtmlToDir($this);
602     }
603
604     function action_loadfile () {
605         include_once("lib/loadsave.php");
606         LoadFileOrDir($this);
607     }
608 }
609
610 //FIXME: deprecated
611 function is_safe_action ($action) {
612     return WikiRequest::requiredAuthority($action) < WIKIAUTH_ADMIN;
613 }
614
615
616 function main () {
617     global $request;
618
619     $request = new WikiRequest();
620     $request->updateAuthAndPrefs();
621
622     /* FIXME: is this needed anymore?
623         if (USE_PATH_INFO && ! $request->get('PATH_INFO')
624             && ! preg_match(',/$,', $request->get('REDIRECT_URL'))) {
625             $request->redirect(SERVER_URL
626                                . preg_replace('/(\?|$)/', '/\1',
627                                               $request->get('REQUEST_URI'),
628                                               1));
629             exit;
630         }
631     */
632
633     // Enable the output of most of the warning messages.
634     // The warnings will screw up zip files though.
635     global $ErrorManager;
636     if (substr($request->getArg('action'), 0, 3) != 'zip') {
637         $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE);
638         //$ErrorManager->setPostponedErrorMask(0);
639     }
640
641     //FIXME:
642     //if ($user->is_authenticated())
643     //  $LogEntry->user = $user->getId();
644
645     $request->possiblyDeflowerVirginWiki();
646 if(defined('WIKI_XMLRPC')) return;
647     $request->handleAction();
648 if (defined('DEBUG') and DEBUG>1) phpinfo(INFO_VARIABLES);
649     $request->finish();
650 }
651
652 // Used for debugging purposes
653 function getmicrotime(){
654     list($usec, $sec) = explode(" ", microtime());
655     return ((float)$usec + (float)$sec);
656 }
657 if (defined('DEBUG')) $GLOBALS['debugclock'] = getmicrotime();
658
659 main();
660
661
662 // Local Variables:
663 // mode: php
664 // tab-width: 8
665 // c-basic-offset: 4
666 // c-hanging-comment-ender-p: nil
667 // indent-tabs-mode: nil
668 // End:
669 ?>