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