]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/main.php
XMLRPC now works (I think)
[SourceForge/phpwiki.git] / lib / main.php
1 <?php
2 rcs_id('$Id: main.php,v 1.72 2002-08-30 21:36:37 lakka 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                     'verify'     => _("verify the current action"),
233                     'viewsource' => _("view the source of pages in this wiki"),
234                     'zip'        => _("download a zip dump from this wiki"),
235                     'ziphtml'    => _("download an html zip dump from this wiki")
236                     );
237         }
238         if (in_array($action, array_keys($actionDescriptions)))
239             return $actionDescriptions[$action];
240         else
241             return $action;
242     }
243     function getDisallowedActionDescription($action) {
244         static $disallowedActionDescriptions;
245         if (! $disallowedActionDescriptions) {
246             $disallowedActionDescriptions
247             = array('browse'     => _("Browsing pages"),
248                     'diff'       => _("Diffing pages"),
249                     'dumphtml'   => _("Dumping html pages"),
250                     'dumpserial' => _("Dumping serial pages"),
251                     'edit'       => _("Editing pages"),
252                     'loadfile'   => _("Loading files"),
253                     'lock'       => _("Locking pages"),
254                     'remove'     => _("Removing pages"),
255                     'unlock'     => _("Unlocking pages"),
256                     'upload'     => _("Uploading zip dumps"),
257                     'verify'     => _("Verify the current action"),
258                     'viewsource' => _("Viewing the source of pages"),
259                     'zip'        => _("Downloading zip dumps"),
260                     'ziphtml'    => _("Downloading html zip dumps")
261                     );
262         }
263         if (in_array($action, array_keys($disallowedActionDescriptions)))
264             return $disallowedActionDescriptions[$action];
265         else
266             return $action;
267     }
268
269     function requiredAuthority ($action) {
270         // FIXME: clean up. 
271         // Todo: Check individual page permissions instead.
272         switch ($action) {
273             case 'browse':
274             case 'viewsource':
275             case 'diff':
276             case 'select':
277                 return WIKIAUTH_ANON;
278
279             case 'zip':
280                 if (defined('ZIPDUMP_AUTH') && ZIPDUMP_AUTH)
281                     return WIKIAUTH_ADMIN;
282                 return WIKIAUTH_ANON;
283
284             case 'ziphtml':
285                 if (defined('ZIPDUMP_AUTH') && ZIPDUMP_AUTH)
286                     return WIKIAUTH_ADMIN;
287                 return WIKIAUTH_ANON;
288
289             case 'edit':
290                 if (defined('REQUIRE_SIGNIN_BEFORE_EDIT') && REQUIRE_SIGNIN_BEFORE_EDIT)
291                     return WIKIAUTH_BOGO;
292                 return WIKIAUTH_ANON;
293                 // return WIKIAUTH_BOGO;
294
295             case 'upload':
296             case 'dumpserial':
297             case 'dumphtml':
298             case 'loadfile':
299             case 'remove':
300             case 'lock':
301             case 'unlock':
302                 return WIKIAUTH_ADMIN;
303             default:
304                 // Temp workaround for french single-word action pages 'Historique'
305                 // Some of this make sense as SubPage actions or buttons.
306                 $singleWordActionPages = 
307                     array("Historique", "Info",
308                           _("Preferences"), _("Administration"), 
309                           _("Today"), _("Help"));
310                 if (in_array($action, $singleWordActionPages))
311                     return WIKIAUTH_ANON; // ActionPage.
312                 global $WikiNameRegexp;
313                 if (preg_match("/$WikiNameRegexp\Z/A", $action))
314                     return WIKIAUTH_ANON; // ActionPage.
315                 else
316                     return WIKIAUTH_ADMIN;
317         }
318     }
319
320     function possiblyDeflowerVirginWiki () {
321         if ($this->getArg('action') != 'browse')
322             return;
323         if ($this->getArg('pagename') != HOME_PAGE)
324             return;
325
326         $page = $this->getPage();
327         $current = $page->getCurrentRevision();
328         if ($current->getVersion() > 0)
329             return;             // Homepage exists.
330
331         include('lib/loadsave.php');
332         SetupWiki($this);
333         $this->finish();        // NORETURN
334     }
335
336     function handleAction () {
337         $action = $this->getArg('action');
338         $method = "action_$action";
339         if (method_exists($this, $method)) {
340             $this->{$method}();
341         }
342         elseif ($this->isActionPage($action)) {
343             $this->actionpage($action);
344         }
345         else {
346             $this->finish(fmt("%s: Bad action", $action));
347         }
348     }
349
350
351     function finish ($errormsg = false) {
352         static $in_exit = 0;
353
354         if ($in_exit)
355             exit();        // just in case CloseDataBase calls us
356         $in_exit = true;
357
358         if (!empty($this->_dbi))
359             $this->_dbi->close();
360         unset($this->_dbi);
361
362
363         global $ErrorManager;
364         $ErrorManager->flushPostponedErrors();
365
366         if (!empty($errormsg)) {
367             PrintXML(HTML::br(),
368                      HTML::hr(),
369                      HTML::h2(_("Fatal PhpWiki Error")),
370                      $errormsg);
371             // HACK:
372             echo "\n</body></html>";
373         }
374
375         Request::finish();
376         exit;
377     }
378
379     function _deducePagename () {
380         if ($this->getArg('pagename'))
381             return $this->getArg('pagename');
382
383         if (USE_PATH_INFO) {
384             $pathinfo = $this->get('PATH_INFO');
385             $tail = substr($pathinfo, strlen(PATH_INFO_PREFIX));
386
387             if ($tail && $pathinfo == PATH_INFO_PREFIX . $tail) {
388                 return $tail;
389             }
390         }
391
392         $query_string = $this->get('QUERY_STRING');
393         if (preg_match('/^[^&=]+$/', $query_string)) {
394             return urldecode($query_string);
395         }
396
397         return HOME_PAGE;
398     }
399
400     function _deduceAction () {
401         if (!($action = $this->getArg('action')))
402             return 'browse';
403
404         if (method_exists($this, "action_$action"))
405             return $action;
406
407         // Allow for, e.g. action=LikePages
408         if ($this->isActionPage($action))
409             return $action;
410
411         // Check for _('PhpWikiAdministration').'/'._('Remove') actions
412         $pagename = $this->getArg('pagename');
413         if (strstr($pagename,_('PhpWikiAdministration')))
414             return $action;
415
416         trigger_error("$action: Unknown action", E_USER_NOTICE);
417         return 'browse';
418     }
419
420     function _deduceUsername () {
421         if ($userid = $this->getSessionVar('wiki_user')) {
422             if (!empty($this->_user))
423                 $this->_user->authhow = 'session';
424             return $userid;
425         }
426         if ($userid = $this->getCookieVar('WIKI_ID')) {
427             if (!empty($this->_user))
428                 $this->_user->authhow = 'cookie';
429             return $userid;
430         }
431         return false;
432     }
433     
434     function isActionPage ($pagename) {
435         if (isSubPage($pagename)) 
436             $subpagename = subPageSlice($pagename,-1); // last element
437         else 
438             $subpagename = $pagename;
439         // Temp workaround for french single-word action page 'Historique'
440         $singleWordActionPages = array("Historique", "Info", _('Preferences'));
441         if (! in_array($subpagename, $singleWordActionPages)) {
442             // Allow for, e.g. action=LikePages
443             global $WikiNameRegexp;
444             if (!preg_match("/$WikiNameRegexp\\Z/A", $subpagename))
445                 return false;
446         }
447         $dbi = $this->getDbh();
448         $page = $dbi->getPage($pagename);
449         $rev = $page->getCurrentRevision();
450         // FIXME: more restrictive check for sane plugin?
451         if (strstr($rev->getPackedContent(), '<?plugin'))
452             return true;
453         trigger_error("$pagename: Does not appear to be an 'action page'", E_USER_NOTICE);
454         return false;
455     }
456
457     function action_browse () {
458         $this->compress_output();
459         include_once("lib/display.php");
460         displayPage($this);
461     }
462
463     function action_verify () {
464         $this->action_browse();
465     }
466
467     function actionpage ($action) {
468         $this->compress_output();
469         include_once("lib/display.php");
470         actionPage($this, $action);
471     }
472
473     function action_diff () {
474         $this->compress_output();
475         include_once "lib/diff.php";
476         showDiff($this);
477     }
478
479     function action_search () {
480         // This is obsolete: reformulate URL and redirect.
481         // FIXME: this whole section should probably be deleted.
482         if ($this->getArg('searchtype') == 'full') {
483             $search_page = _("FullTextSearch");
484         }
485         else {
486             $search_page = _("TitleSearch");
487         }
488         $this->redirect(WikiURL($search_page,
489                                 array('s' => $this->getArg('searchterm')),
490                                 'absolute_url'));
491     }
492
493     function action_edit () {
494         $this->compress_output();
495         include "lib/editpage.php";
496         $e = new PageEditor ($this);
497         $e->editPage();
498     }
499
500     function action_viewsource () {
501         $this->compress_output();
502         include "lib/editpage.php";
503         $e = new PageEditor ($this);
504         $e->viewSource();
505     }
506
507     function action_lock () {
508         $page = $this->getPage();
509         $page->set('locked', true);
510         $this->action_browse();
511     }
512
513     function action_unlock () {
514         // FIXME: This check is redundant.
515         //$user->requireAuth(WIKIAUTH_ADMIN);
516         $page = $this->getPage();
517         $page->set('locked', false);
518         $this->action_browse();
519     }
520
521     function action_remove () {
522         // FIXME: This check is redundant.
523         //$user->requireAuth(WIKIAUTH_ADMIN);
524         $pagename = $this->getArg('pagename');
525         if (strstr($pagename,_('PhpWikiAdministration'))) {
526             $this->action_browse();
527         } else {
528             include('lib/removepage.php');
529             RemovePage($this);
530         }
531     }
532
533
534     function action_upload () {
535         include_once("lib/loadsave.php");
536         LoadPostFile($this);
537     }
538
539     function action_zip () {
540         include_once("lib/loadsave.php");
541         MakeWikiZip($this);
542         // I don't think it hurts to add cruft at the end of the zip file.
543         echo "\n========================================================\n";
544         echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
545     }
546
547     function action_ziphtml () {
548         include_once("lib/loadsave.php");
549         MakeWikiZipHtml($this);
550         // I don't think it hurts to add cruft at the end of the zip file.
551         echo "\n========================================================\n";
552         echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
553     }
554
555     function action_dumpserial () {
556         include_once("lib/loadsave.php");
557         DumpToDir($this);
558     }
559
560     function action_dumphtml () {
561         include_once("lib/loadsave.php");
562         DumpHtmlToDir($this);
563     }
564
565     function action_loadfile () {
566         include_once("lib/loadsave.php");
567         LoadFileOrDir($this);
568     }
569 }
570
571 //FIXME: deprecated
572 function is_safe_action ($action) {
573     return WikiRequest::requiredAuthority($action) < WIKIAUTH_ADMIN;
574 }
575
576
577 function main () {
578     global $request;
579
580     $request = new WikiRequest();
581     $request->updateAuthAndPrefs();
582
583     /* FIXME: is this needed anymore?
584         if (USE_PATH_INFO && ! $request->get('PATH_INFO')
585             && ! preg_match(',/$,', $request->get('REDIRECT_URL'))) {
586             $request->redirect(SERVER_URL
587                                . preg_replace('/(\?|$)/', '/\1',
588                                               $request->get('REQUEST_URI'),
589                                               1));
590             exit;
591         }
592     */
593
594     // Enable the output of most of the warning messages.
595     // The warnings will screw up zip files though.
596     global $ErrorManager;
597     if (substr($request->getArg('action'), 0, 3) != 'zip') {
598         $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE);
599         //$ErrorManager->setPostponedErrorMask(0);
600     }
601
602     //FIXME:
603     //if ($user->is_authenticated())
604     //  $LogEntry->user = $user->getId();
605
606     $request->possiblyDeflowerVirginWiki();
607 if(defined('WIKI_XMLRPC')) return;
608     $request->handleAction();
609 if (defined('DEBUG') and DEBUG>1) phpinfo(INFO_VARIABLES);
610     $request->finish();
611 }
612
613 // Used for debugging purposes
614 function getmicrotime(){
615     list($usec, $sec) = explode(" ", microtime());
616     return ((float)$usec + (float)$sec);
617 }
618 if (defined('DEBUG')) $GLOBALS['debugclock'] = getmicrotime();
619
620 main();
621
622
623 // Local Variables:
624 // mode: php
625 // tab-width: 8
626 // c-basic-offset: 4
627 // c-hanging-comment-ender-p: nil
628 // indent-tabs-mode: nil
629 // End:
630 ?>