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