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