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