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