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