]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/main.php
Another refactor of the OOP HTML/XML generation code. (Sorry.)
[SourceForge/phpwiki.git] / lib / main.php
1 <?php
2 rcs_id('$Id: main.php,v 1.41 2002-01-28 18:49:08 dairiki Exp $');
3
4
5 include "lib/config.php";
6 include "lib/stdlib.php";
7 require_once('lib/Request.php');
8 require_once("lib/WikiUser.php");
9 require_once('lib/WikiDB.php');
10
11 // FIXME: move to config?
12 if (defined('THEME')) {
13     include("themes/" . THEME . "/themeinfo.php");
14 }
15 if (empty($Theme)) {
16     include("themes/default/themeinfo.php");
17 }
18 assert(!empty($Theme));
19
20 class _UserPreference
21 {
22     function _UserPreference ($default_value) {
23         $this->default_value = $default_value;
24     }
25
26     function sanify ($value) {
27         return (string) $value;
28     }
29 }
30
31 class _UserPreference_int extends _UserPreference 
32 {
33     function _UserPreference_int ($default, $minval = false, $maxval = false) {
34         $this->_UserPreference((int) $default);
35         $this->_minval = (int) $minval;
36         $this->_maxval = (int) $maxval;
37     }
38     
39     function sanify ($value) {
40         $value = (int) $value;
41         if ($this->_minval !== false && $value < $this->_minval)
42             $value = $this->_minval;
43         if ($this->_maxval !== false && $value > $this->_maxval)
44             $value = $this->_maxval;
45         return $value;
46     }
47 }
48
49 $UserPreferences = array('editWidth' => new _UserPreference_int(80, 30, 150),
50                          'editHeight' => new _UserPreference_int(22, 5, 80),
51                          'userid' => new _UserPreference(''));
52
53 class UserPreferences {
54     function UserPreferences ($saved_prefs = false) {
55         $this->_prefs = array();
56
57         if (isa($saved_prefs, 'UserPreferences')) {
58             foreach ($saved_prefs->_prefs as $name => $value)
59                 $this->set($name, $value);
60         }
61     }
62
63     function _getPref ($name) {
64         global $UserPreferences;
65         if (!isset($UserPreferences[$name])) {
66             trigger_error("$key: unknown preference", E_USER_NOTICE);
67             return false;
68         }
69         return $UserPreferences[$name];
70     }
71     
72     function get ($name) {
73         if (isset($this->_prefs[$name]))
74             return $this->_prefs[$name];
75         if (!($pref = $this->_getPref($name)))
76             return false;
77         return $pref->default_value;
78     }
79
80     function set ($name, $value) {
81         if (!($pref = $this->_getPref($name)))
82             return false;
83         $this->_prefs[$name] = $pref->sanify($value);
84     }
85 }
86
87
88 class WikiRequest extends Request {
89
90     function WikiRequest () {
91         $this->Request();
92         
93         // Normalize args...
94         $this->setArg('pagename', $this->_deducePagename());
95         $this->setArg('action', $this->_deduceAction());
96
97         // Restore auth state
98         $this->_user = new WikiUser($this->getSessionVar('wiki_user'));
99
100         // Restore saved preferences
101         if (!($prefs = $this->getCookieVar('WIKI_PREFS2')))
102             $prefs = $this->getSessionVar('wiki_prefs');
103         $this->_prefs = new UserPreferences($prefs);
104     }
105
106     // This really maybe should be part of the constructor, but since it
107     // may involve HTML/template output, the global $request really needs
108     // to be initialized before we do this stuff.
109     function updateAuthAndPrefs () {
110         // Handle preference updates, an authentication requests, if any.
111         if ($new_prefs = $this->getArg('pref')) {
112             $this->setArg('pref', false);
113             foreach ($new_prefs as $key => $val)
114                 $this->_prefs->set($key, $val);
115         }
116
117         // Handle authentication request, if any.
118         if ($auth_args = $this->getArg('auth')) {
119             $this->setArg('auth', false);
120             $this->_handleAuthRequest($auth_args); // possible NORETURN
121         }
122         elseif ( ! $this->_user->isSignedIn() ) {
123             // If not auth request, try to sign in as saved user.
124             if (($saved_user = $this->getPref('userid')) != false)
125                 $this->_signIn($saved_user);
126         }
127
128         // Save preferences
129         $this->setSessionVar('wiki_prefs', $this->_prefs);
130         $this->setCookieVar('WIKI_PREFS2', $this->_prefs, 365);
131
132         // Ensure user has permissions for action
133         $require_level = $this->requiredAuthority($this->getArg('action'));
134         if (! $this->_user->hasAuthority($require_level))
135             $this->_notAuthorized($require_level); // NORETURN
136     }
137
138     function getUser () {
139         return $this->_user;
140     }
141
142     function getPrefs () {
143         return $this->_prefs;
144     }
145
146     // Convenience function:
147     function getPref ($key) {
148         return $this->_prefs->get($key);
149     }
150
151     function getDbh () {
152         if (!isset($this->_dbi)) {
153             $this->_dbi = WikiDB::open($GLOBALS['DBParams']);
154         }
155         return $this->_dbi;
156     }
157
158     /**
159      * Get requested page from the page database.
160      *
161      * This is a convenience function.
162      */
163     function getPage () {
164         if (!isset($this->_dbi))
165             $this->getDbh();
166         return $this->_dbi->getPage($this->getArg('pagename'));
167     }
168
169     function _handleAuthRequest ($auth_args) {
170         if (!is_array($auth_args))
171             return;
172
173         // Ignore password unless POSTed.
174         if (!$this->isPost())
175             unset($auth_args['password']);
176
177         $user = WikiUser::AuthCheck($auth_args);
178
179         if (isa($user, 'WikiUser')) {
180             // Successful login (or logout.)
181             $this->_setUser($user);
182         }
183         elseif ($user) {
184             // Login attempt failed.
185             $fail_message = $user;
186             // If no password was submitted, it's not really
187             // a failure --- just need to prompt for password...
188             if (!isset($auth_args['password']))
189                 $fail_message = false;
190             WikiUser::PrintLoginForm($this, $auth_args, $fail_message);
191             $this->finish();    //NORETURN
192         }
193         else {
194             // Login request cancelled.
195         }
196     }
197
198     /**
199      * Attempt to sign in (bogo-login).
200      *
201      * Fails silently.
202      *
203      * @param $userid string Userid to attempt to sign in as.
204      * @access private
205      */
206     function _signIn ($userid) {
207         $user = WikiUser::AuthCheck(array('userid' => $userid));
208         if (isa($user, 'WikiUser'))
209             $this->_setUser($user); // success!
210     }
211
212     function _setUser ($user) {
213         $this->_user = $user;
214         $this->setSessionVar('wiki_user', $user);
215
216         // Save userid to prefs..
217         $this->_prefs->set('userid',
218                            $user->isSignedIn() ? $user->getId() : '');
219     }
220
221     function _notAuthorized ($require_level) {
222         // User does not have required authority.  Prompt for login.
223         $what = HTML::em($this->getArg('action'));
224
225         if ($require_level >= WIKIAUTH_FORBIDDEN) {
226             $this->finish(fmt("Action %s is disallowed on this wiki", $what));
227         }
228         elseif ($require_level == WIKIAUTH_BOGO)
229             $msg = fmt("You must sign in to %s this wiki", $what);
230         elseif ($require_level == WIKIAUTH_USER)
231             $msg = fmt("You must log in to %s this wiki", $what);
232         else
233             $msg = fmt("You must be an administrator to %s this wiki", $what);
234         
235         WikiUser::PrintLoginForm($this, compact('require_level'), $msg);
236         $this->finish();    // NORETURN
237     }
238     
239     function requiredAuthority ($action) {
240         // FIXME: clean up.
241         switch ($action) {
242         case 'browse':
243         case 'diff':
244         case 'actionpage':
245             return WIKIAUTH_ANON;
246
247         case 'zip':
248             if (defined('ZIPDUMP_AUTH') && ZIPDUMP_AUTH)
249                 return WIKIAUTH_ADMIN;
250             return WIKIAUTH_ANON;
251             
252         case 'edit':
253         case 'save':            // FIXME delete
254             if (defined('REQUIRE_SIGNIN_BEFORE_EDIT') && REQUIRE_SIGNIN_BEFORE_EDIT)
255                 return WIKIAUTH_BOGO;
256             return WIKIAUTH_ANON;
257             // return WIKIAUTH_BOGO;
258
259         case 'upload':
260         case 'dumpserial':
261         case 'loadfile':
262         case 'remove':
263         case 'lock':
264         case 'unlock':
265             return WIKIAUTH_ADMIN;
266         default:
267             global $WikiNameRegexp;
268             if (preg_match("/$WikiNameRegexp\Z/A", $action))
269                 return WIKIAUTH_ANON; // ActionPage.
270             else
271                 return WIKIAUTH_ADMIN;
272         }
273     }
274         
275     function possiblyDeflowerVirginWiki () {
276         if ($this->getArg('action') != 'browse')
277             return;
278         if ($this->getArg('pagename') != HomePage)
279             return;
280
281         $page = $this->getPage();
282         $current = $page->getCurrentRevision();
283         if ($current->getVersion() > 0)
284             return;             // Homepage exists.
285
286         include('lib/loadsave.php');
287         SetupWiki($this);
288         $this->finish();        // NORETURN
289     }
290
291     function handleAction () {
292         $action = $this->getArg('action');
293         $method = "action_$action";
294         if (! method_exists($this, $method)) {
295             $this->finish(fmt("%s: Bad action", $action));
296         }
297         $this->{$method}();
298     }
299         
300         
301     function finish ($errormsg = false) {
302         static $in_exit = 0;
303
304         if ($in_exit)
305             exit();             // just in case CloseDataBase calls us
306         $in_exit = true;
307
308         if (!empty($this->_dbi))
309             $this->_dbi->close();
310         unset($this->_dbi);
311         
312
313         global $ErrorManager;
314         $ErrorManager->flushPostponedErrors();
315    
316         if (!empty($errormsg)) {
317             PrintXML(HTML::br(),
318                      HTML::hr(),
319                      HTML::h2(_("Fatal PhpWiki Error")),
320                      $errormsg);
321             // HACK:
322             echo "\n</body></html>";
323         }
324
325         Request::finish();
326         exit;
327     }
328         
329     function _deducePagename () {
330         if ($this->getArg('pagename'))
331             return $this->getArg('pagename');
332
333         if (USE_PATH_INFO) {
334             $pathinfo = $this->get('PATH_INFO');
335             $tail = substr($pathinfo, strlen(PATH_INFO_PREFIX));
336             
337             if ($tail && $pathinfo == PATH_INFO_PREFIX . $tail) {
338                 return $tail;
339             }
340         }
341
342         $query_string = $this->get('QUERY_STRING');
343         if (preg_match('/^[^&=]+$/', $query_string)) {
344             return urldecode($query_string);
345         }
346     
347         return HomePage;
348     }
349
350     
351     function _deduceAction () {
352         if (!($action = $this->getArg('action')))
353             return 'browse';
354
355         if ($action != 'actionpage' && method_exists($this, "action_$action"))
356             return $action;
357
358         // Allow for, e.g. action=LikePages
359         global $WikiNameRegexp;
360         if (preg_match("/$WikiNameRegexp\\Z/A", $action)) {
361             $dbi = $this->getDbh();
362             $actionpage = $dbi->getPage($action);
363             $rev = $actionpage->getCurrentRevision();
364             // FIXME: more restrictive check for sane plugin?
365             if (strstr($rev->getPackedContent(), '<?plugin')) {
366                 $this->_actionpage = $actionpage;
367                 return 'actionpage';
368             }
369             trigger_error("$action: Does not appera to be an 'action page'", E_USER_NOTICE);
370             return 'browse';
371         }
372                 
373         trigger_error("$action: Unknown action", E_USER_NOTICE);
374         return 'browse';
375     }
376
377     function action_browse () {
378         $this->compress_output();
379         include_once("lib/display.php");
380         displayPage($this);
381     }
382
383     function action_actionpage () {
384         $this->compress_output();
385         include_once("lib/display.php");
386         actionPage($this, $this->_actionpage);
387     }
388     
389     function action_diff () {
390         $this->compress_output();
391         include_once "lib/diff.php";
392         showDiff($this);
393     }
394
395     function action_search () {
396         // This is obsolete: reformulate URL and redirect.
397         // FIXME: this whole section should probably be deleted.
398         if ($this->getArg('searchtype') == 'full') {
399             $search_page = _("FullTextSearch");
400         }
401         else {
402             $search_page = _("TitleSearch");
403         }
404         $this->redirect(WikiURL($search_page,
405                                 array('s' => $this->getArg('searchterm')),
406                                 'absolute_url'));
407     }
408
409     function action_edit () {
410         $this->compress_output();
411         include "lib/editpage.php";
412         editPage($this);
413     }
414
415     // FIXME: combine this with edit
416     function action_save () {
417         $this->compress_output();
418         include "lib/savepage.php";
419         savePage($this);
420     }
421
422     function action_lock () {
423         $page = $this->getPage();
424         $page->set('locked', true);
425         $this->action_browse();
426     }
427
428     function action_unlock () {
429         // FIXME: This check is redundant.
430         //$user->requireAuth(WIKIAUTH_ADMIN);
431         $page = $this->getPage();
432         $page->set('locked', false);
433         $this->action_browse();
434     }
435
436     function action_remove () {
437         // FIXME: This check is redundant.
438         //$user->requireAuth(WIKIAUTH_ADMIN);
439         include('lib/removepage.php');
440         RemovePage($this);
441     }
442
443     
444     function action_upload () {
445         include_once("lib/loadsave.php");
446         LoadPostFile($this);
447     }
448     
449     function action_zip () {
450         include_once("lib/loadsave.php");
451         MakeWikiZip($this);
452         // I don't think it hurts to add cruft at the end of the zip file.
453         echo "\n========================================================\n";
454         echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
455     }
456         
457     function action_dumpserial () {
458         include_once("lib/loadsave.php");
459         DumpToDir($this);
460     }
461
462     function action_loadfile () {
463         include_once("lib/loadsave.php");
464         LoadFileOrDir($this);
465     }
466 }
467
468 //FIXME: deprecated
469 function is_safe_action ($action) {
470     return WikiRequest::requiredAuthority($action) < WIKIAUTH_ADMIN;
471 }
472
473
474 function main () {
475     global $request;
476
477     $request = new WikiRequest();
478     $request->updateAuthAndPrefs();
479     
480     /* FIXME: is this needed anymore?
481     if (USE_PATH_INFO && ! $request->get('PATH_INFO')
482         && ! preg_match(',/$,', $request->get('REDIRECT_URL'))) {
483         $request->redirect(SERVER_URL
484                            . preg_replace('/(\?|$)/', '/\1',
485                                           $request->get('REQUEST_URI'),
486                                           1));
487         exit;
488     }
489     */
490
491     // Enable the output of most of the warning messages.
492     // The warnings will screw up zip files though.
493     global $ErrorManager;
494     if ($request->getArg('action') != 'zip') {
495         $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE);
496         //$ErrorManager->setPostponedErrorMask(0);
497     }
498     
499     //FIXME:
500     //if ($user->is_authenticated())
501     //  $LogEntry->user = $user->getId();
502
503     $request->possiblyDeflowerVirginWiki();
504
505     $request->handleAction();
506     $request->finish();
507 }
508
509 main();
510
511
512 // Local Variables:
513 // mode: php
514 // tab-width: 8
515 // c-basic-offset: 4
516 // c-hanging-comment-ender-p: nil
517 // indent-tabs-mode: nil
518 // End:   
519 ?>