]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/main.php
Refactoring continues:
[SourceForge/phpwiki.git] / lib / main.php
1 <?php
2 rcs_id('$Id: main.php,v 1.29 2002-01-23 19:21:43 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
94     // FIXME: make $request an argument of WikiTemplate,
95     // then subsume _init into WikiRequest().
96     function _init () {
97         // Normalize args...
98         $this->setArg('pagename', $this->_deducePagename());
99         $this->setArg('action', $this->_deduceAction());
100
101         // Restore auth state
102         $this->_user = new WikiUser($this->getSessionVar('auth_state'));
103
104         // Restore saved preferences
105         if (!($prefs = $this->getCookieVar('WIKI_PREFS')))
106             $prefs = $this->getSessionVar('user_prefs');
107         $this->_prefs = new UserPreferences($prefs);
108
109         // Handle preference updates, an authentication requests, if any.
110         if ($new_prefs = $this->getArg('pref')) {
111             $this->setArg('pref', false);
112             $this->_setPreferences($new_prefs);
113         }
114
115         // Handle authentication request, if any.
116         if ($auth_args = $this->getArg('auth')) {
117             $this->setArg('auth', false);
118             $this->_handleAuthRequest($auth_args); // possible NORETURN
119         }
120         
121         if (!$auth_args && !$this->_user->isSignedIn()) {
122             // Try to sign in as saved user.
123             if (($saved_user = $this->getPref('userid')) != false)
124                 $this->_signIn($saved_user);
125         }
126
127         // Ensure user has permissions for action
128         $require_level = $this->requiredAuthority($this->getArg('action'));
129         if (! $this->_user->hasAuthority($require_level))
130             $this->_notAuthorized($require_level); // NORETURN
131     }
132
133     function getUser () {
134         return $this->_user;
135     }
136
137     function getPrefs () {
138         return $this->_prefs;
139     }
140
141     // Convenience function:
142     function getPref ($key) {
143         return $this->_prefs->get($key);
144     }
145
146     function getDbh () {
147         if (!isset($this->_dbi)) {
148             $this->_dbi = WikiDB::open($GLOBALS['DBParams']);
149         }
150         return $this->_dbi;
151     }
152
153     /**
154      * Get requested page from the page database.
155      *
156      * This is a convenience function.
157      */
158     function getPage () {
159         if (!isset($this->_dbi))
160             $this->getDbh();
161         return $this->_dbi->getPage($this->getArg('pagename'));
162     }
163
164     function _handleAuthRequest ($auth_args) {
165         if (!is_array($auth_args))
166             return;
167
168         // Ignore password unless POSTed.
169         if (!$this->isPost())
170             unset($auth_args['password']);
171
172         $user = WikiUser::AuthCheck($auth_args);
173
174         if (isa($user, 'WikiUser')) {
175             // Successful login (or logout.)
176             $this->_setUser($user);
177         }
178         elseif ($user) {
179             // Login attempt failed.
180             $fail_message = $user;
181             WikiUser::PrintLoginForm($auth_args, $fail_message);
182             $this->finish();    //NORETURN
183         }
184         else {
185             // Login request cancelled.
186         }
187     }
188
189     /**
190      * Attempt to sign in (bogo-login).
191      *
192      * Fails silently.
193      *
194      * @param $userid string Userid to attempt to sign in as.
195      * @access private
196      */
197     function _signIn ($userid) {
198         $user = WikiUser::AuthCheck(array('userid' => $userid));
199         if (isa($user, 'WikiUser'))
200             $this->_setUser($user); // success!
201     }
202
203     function _setUser ($user) {
204         $this->_user = $user;
205         $this->setSessionVar('auth_state', $user);
206         // Save userid to prefs..
207         if ($user->isSignedIn())
208             $this->_setPreferences(array('userid' => $user->getId()));
209         else
210             $this->_setPreferences(array('userid' => false));
211     }
212
213     function _notAuthorized ($require_level) {
214         // User does not have required authority.  Prompt for login.
215         $what = HTML::em($this->getArg('action'));
216
217         if ($require_level >= WIKIAUTH_FORBIDDEN) {
218             $this->finish(fmt("Action %s is disallowed on this wiki", $what));
219         }
220         elseif ($require_level == WIKIAUTH_BOGO)
221             $msg = fmt("You must sign in to %s this wiki", $what);
222         elseif ($require_level == WIKIAUTH_USER)
223             $msg = fmt("You must log in to %s this wiki", $what);
224         else
225             $msg = fmt("You must be an administrator to %s this wiki", $what);
226         
227         WikiUser::PrintLoginForm(compact('require_level'), $msg);
228         $this->finish();    // NORETURN
229     }
230     
231     function requiredAuthority ($action) {
232         // FIXME: clean up.
233         switch ($action) {
234         case 'browse':
235         case 'diff':
236         // case ActionPage:   
237         // case 'search':
238             return WIKIAUTH_ANON;
239
240         case 'zip':
241             return WIKIAUTH_ANON;
242             
243         case 'edit':
244         case 'save':            // FIXME delete
245             return WIKIAUTH_ANON;
246             // return WIKIAUTH_BOGO;
247
248         case 'upload':
249         case 'dumpserial':
250         case 'loadfile':
251         case 'remove':
252         case 'lock':
253         case 'unlock':
254         default:
255             return WIKIAUTH_ADMIN;
256         }
257     }
258         
259     function _setPreferences ($new_prefs) {
260         if (!is_array($new_prefs))
261             return;
262
263         // Update and save preferences.
264         foreach ($new_prefs as $name => $value)
265             $this->_prefs->set($name, $value);
266         
267         $this->setSessionVar('user_prefs', $this->_prefs);
268         $this->setCookieVar('WIKI_PREFS', $this->_prefs, 365);
269     }
270
271     function deflowerDatabase () {
272         if ($this->getArg('action') != 'browse')
273             return;
274         if ($this->getArg('pagename') != _("HomePage"))
275             return;
276
277         $page = $this->getPage();
278         $current = $page->getCurrentRevision();
279         if ($current->getVersion() > 0)
280             return;             // Homepage exists.
281
282         include('lib/loadsave.php');
283         SetupWiki($this);
284         $this->finish();        // NORETURN
285     }
286
287     function handleAction () {
288         $action = $this->getArg('action');
289         $method = "action_$action";
290         if (! method_exists($this, $method)) {
291             $this->finish(fmt("%s: Bad action", $action));
292         }
293         $this->{$method}();
294     }
295         
296         
297     function finish ($errormsg = false) {
298         static $in_exit = 0;
299
300         if ($in_exit)
301             exit();             // just in case CloseDataBase calls us
302         $in_exit = true;
303
304         if (!empty($this->_dbi))
305             $this->_dbi->close();
306         unset($this->_dbi);
307         
308
309         global $ErrorManager;
310         $ErrorManager->flushPostponedErrors();
311    
312         if (!empty($errormsg)) {
313             PrintXML(array(HTML::br(),
314                            HTML::hr(),
315                            HTML::h2(_("Fatal PhpWiki Error")),
316                            $errormsg));
317             // HACK:
318             echo "\n</body></html>";
319         }
320
321         Request::finish();
322         exit;
323     }
324         
325     function _deducePagename () {
326         if ($this->getArg('pagename'))
327             return $this->getArg('pagename');
328
329         if (USE_PATH_INFO) {
330             $pathinfo = $this->get('PATH_INFO');
331             $tail = substr($pathinfo, strlen(PATH_INFO_PREFIX));
332             
333             if ($tail && $pathinfo == PATH_INFO_PREFIX . $tail) {
334                 return $tail;
335             }
336         }
337
338         $query_string = $this->get('QUERY_STRING');
339         if (preg_match('/^[^&=]+$/', $query_string)) {
340             return urldecode($query_string);
341         }
342         
343     
344         return _("HomePage");
345     }
346
347     
348     function _deduceAction () {
349         if (!($action = $this->getArg('action')))
350             return 'browse';
351
352         if (! method_exists($this, "action_$action")) {
353             // unknown action.
354             trigger_error("$action: Unknown action", E_USER_NOTICE);
355             return 'browse';
356         }
357         return $action;
358     }
359
360     function action_browse () {
361         $this->compress_output();
362         include_once("lib/display.php");
363         displayPage($this);
364     }
365     
366     function action_diff () {
367         $this->compress_output();
368         include_once "lib/diff.php";
369         showDiff($this);
370     }
371
372     function action_search () {
373         // This is obsolete: reformulate URL and redirect.
374         // FIXME: this whole section should probably be deleted.
375         if ($this->getArg('searchtype') == 'full') {
376             $search_page = _("FullTextSearch");
377         }
378         else {
379             $search_page = _("TitleSearch");
380         }
381         $this->redirect(WikiURL($search_page,
382                                 array('s' => $this->getArg('searchterm')),
383                                 'absolute_url'));
384     }
385
386     function action_edit () {
387         $this->compress_output();
388         include "lib/editpage.php";
389         editPage($this);
390     }
391
392     // FIXME: combine this with edit
393     function action_save () {
394         $this->compress_output();
395         include "lib/savepage.php";
396         savePage($this);
397     }
398
399     function action_lock () {
400         $page = $this->getPage();
401         $page->set('locked', true);
402         $this->action_browse();
403     }
404
405     function action_unlock () {
406         // FIXME: This check is redundant.
407         //$user->requireAuth(WIKIAUTH_ADMIN);
408         $page = $this->getPage();
409         $page->set('locked', false);
410         $this->action_browse();
411     }
412
413     function action_remove () {
414         // FIXME: This check is redundant.
415         //$user->requireAuth(WIKIAUTH_ADMIN);
416         include('lib/removepage.php');
417     }
418
419     
420     function action_upload () {
421         include_once("lib/loadsave.php");
422         LoadPostFile($this);
423     }
424     
425     function action_zip () {
426         include_once("lib/loadsave.php");
427         MakeWikiZip($this);
428         // I don't think it hurts to add cruft at the end of the zip file.
429         echo "\n========================================================\n";
430         echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
431     }
432         
433     function action_dumpserial () {
434         include_once("lib/loadsave.php");
435         DumpToDir($this);
436     }
437
438     function action_loadfile () {
439         include_once("lib/loadsave.php");
440         LoadFileOrDir($this);
441     }
442 }
443
444 //FIXME: deprecated
445 function is_safe_action ($action) {
446     return WikiRequest::requiredAuthority($action) < WIKIAUTH_ADMIN;
447 }
448
449
450 function main () {
451     global $request;
452
453     $request = new WikiRequest();
454     $request->_init();
455     
456     /* FIXME: is this needed anymore?
457     if (USE_PATH_INFO && ! $request->get('PATH_INFO')
458         && ! preg_match(',/$,', $request->get('REDIRECT_URL'))) {
459         $request->redirect(SERVER_URL
460                            . preg_replace('/(\?|$)/', '/\1',
461                                           $request->get('REQUEST_URI'),
462                                           1));
463         exit;
464     }
465     */
466
467     // Enable the output of most of the warning messages.
468     // The warnings will screw up zip files and setpref though.
469     global $ErrorManager;
470     if ($request->getArg('action') != 'zip') {
471         //$ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE);
472         $ErrorManager->setPostponedErrorMask(0);
473     }
474
475     
476     //FIXME:
477     //if ($user->is_authenticated())
478     //  $LogEntry->user = $user->getId();
479
480     $request->deflowerDatabase();
481
482     $request->handleAction();
483     $request->finish();
484 }
485
486 main();
487
488
489 // Local Variables:
490 // mode: php
491 // tab-width: 8
492 // c-basic-offset: 4
493 // c-hanging-comment-ender-p: nil
494 // indent-tabs-mode: nil
495 // End:   
496 ?>