]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/main.php
Fixed bugs so now page deletion works again. Also added some minor
[SourceForge/phpwiki.git] / lib / main.php
1 <?php
2 rcs_id('$Id: main.php,v 1.39 2002-01-28 01:57:13 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         // Handle preference updates, an authentication requests, if any.
106         if ($new_prefs = $this->getArg('pref')) {
107             $this->setArg('pref', false);
108             foreach ($new_prefs as $key => $val)
109                 $this->_prefs->set($key, $val);
110         }
111
112         // Handle authentication request, if any.
113         if ($auth_args = $this->getArg('auth')) {
114             $this->setArg('auth', false);
115             $this->_handleAuthRequest($auth_args); // possible NORETURN
116         }
117         elseif ( ! $this->_user->isSignedIn() ) {
118             // If not auth request, try to sign in as saved user.
119             if (($saved_user = $this->getPref('userid')) != false)
120                 $this->_signIn($saved_user);
121         }
122
123         // Save preferences
124         $this->setSessionVar('wiki_prefs', $this->_prefs);
125         $this->setCookieVar('WIKI_PREFS2', $this->_prefs, 365);
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             // If no password was submitted, it's not really
182             // a failure --- just need to prompt for password...
183             if (!isset($auth_args['password']))
184                 $fail_message = false;
185             WikiUser::PrintLoginForm($this, $auth_args, $fail_message);
186             $this->finish();    //NORETURN
187         }
188         else {
189             // Login request cancelled.
190         }
191     }
192
193     /**
194      * Attempt to sign in (bogo-login).
195      *
196      * Fails silently.
197      *
198      * @param $userid string Userid to attempt to sign in as.
199      * @access private
200      */
201     function _signIn ($userid) {
202         $user = WikiUser::AuthCheck(array('userid' => $userid));
203         if (isa($user, 'WikiUser'))
204             $this->_setUser($user); // success!
205     }
206
207     function _setUser ($user) {
208         $this->_user = $user;
209         $this->setSessionVar('wiki_user', $user);
210
211         // Save userid to prefs..
212         $this->_prefs->set('userid',
213                            $user->isSignedIn() ? $user->getId() : '');
214     }
215
216     function _notAuthorized ($require_level) {
217         // User does not have required authority.  Prompt for login.
218         $what = HTML::em($this->getArg('action'));
219
220         if ($require_level >= WIKIAUTH_FORBIDDEN) {
221             $this->finish(fmt("Action %s is disallowed on this wiki", $what));
222         }
223         elseif ($require_level == WIKIAUTH_BOGO)
224             $msg = fmt("You must sign in to %s this wiki", $what);
225         elseif ($require_level == WIKIAUTH_USER)
226             $msg = fmt("You must log in to %s this wiki", $what);
227         else
228             $msg = fmt("You must be an administrator to %s this wiki", $what);
229         
230         WikiUser::PrintLoginForm($this, compact('require_level'), $msg);
231         $this->finish();    // NORETURN
232     }
233     
234     function requiredAuthority ($action) {
235         // FIXME: clean up.
236         switch ($action) {
237         case 'browse':
238         case 'diff':
239         case 'actionpage':
240             return WIKIAUTH_ANON;
241
242         case 'zip':
243             if (defined('ZIPDUMP_AUTH') && ZIPDUMP_AUTH)
244                 return WIKIAUTH_ADMIN;
245             return WIKIAUTH_ANON;
246             
247         case 'edit':
248         case 'save':            // FIXME delete
249             if (defined('REQUIRE_SIGNIN_BEFORE_EDIT') && REQUIRE_SIGNIN_BEFORE_EDIT)
250                 return WIKIAUTH_BOGO;
251             return WIKIAUTH_ANON;
252             // return WIKIAUTH_BOGO;
253
254         case 'upload':
255         case 'dumpserial':
256         case 'loadfile':
257         case 'remove':
258         case 'lock':
259         case 'unlock':
260             return WIKIAUTH_ADMIN;
261         default:
262             global $WikiNameRegexp;
263             if (preg_match("/$WikiNameRegexp\Z/A", $action))
264                 return WIKIAUTH_ANON; // ActionPage.
265             else
266                 return WIKIAUTH_ADMIN;
267         }
268     }
269         
270     function deflowerDatabase () {
271         if ($this->getArg('action') != 'browse')
272             return;
273         if ($this->getArg('pagename') != HomePage)
274             return;
275
276         $page = $this->getPage();
277         $current = $page->getCurrentRevision();
278         if ($current->getVersion() > 0)
279             return;             // Homepage exists.
280
281         include('lib/loadsave.php');
282         SetupWiki($this);
283         $this->finish();        // NORETURN
284     }
285
286     function handleAction () {
287         $action = $this->getArg('action');
288         $method = "action_$action";
289         if (! method_exists($this, $method)) {
290             $this->finish(fmt("%s: Bad action", $action));
291         }
292         $this->{$method}();
293     }
294         
295         
296     function finish ($errormsg = false) {
297         static $in_exit = 0;
298
299         if ($in_exit)
300             exit();             // just in case CloseDataBase calls us
301         $in_exit = true;
302
303         if (!empty($this->_dbi))
304             $this->_dbi->close();
305         unset($this->_dbi);
306         
307
308         global $ErrorManager;
309         $ErrorManager->flushPostponedErrors();
310    
311         if (!empty($errormsg)) {
312             PrintXML(array(HTML::br(),
313                            HTML::hr(),
314                            HTML::h2(_("Fatal PhpWiki Error")),
315                            $errormsg));
316             // HACK:
317             echo "\n</body></html>";
318         }
319
320         Request::finish();
321         exit;
322     }
323         
324     function _deducePagename () {
325         if ($this->getArg('pagename'))
326             return $this->getArg('pagename');
327
328         if (USE_PATH_INFO) {
329             $pathinfo = $this->get('PATH_INFO');
330             $tail = substr($pathinfo, strlen(PATH_INFO_PREFIX));
331             
332             if ($tail && $pathinfo == PATH_INFO_PREFIX . $tail) {
333                 return $tail;
334             }
335         }
336
337         $query_string = $this->get('QUERY_STRING');
338         if (preg_match('/^[^&=]+$/', $query_string)) {
339             return urldecode($query_string);
340         }
341         
342     
343         return HomePage;
344     }
345
346     
347     function _deduceAction () {
348         if (!($action = $this->getArg('action')))
349             return 'browse';
350
351         if ($action != 'actionpage' && method_exists($this, "action_$action"))
352             return $action;
353
354         // Allow for, e.g. action=LikePages
355         global $WikiNameRegexp;
356         if (preg_match("/$WikiNameRegexp\\Z/A", $action)) {
357             $dbi = $this->getDbh();
358             $actionpage = $dbi->getPage($action);
359             $rev = $actionpage->getCurrentRevision();
360             // FIXME: more restrictive check for sane plugin?
361             if (strstr($rev->getPackedContent(), '<?plugin')) {
362                 $this->_actionpage = $actionpage;
363                 return 'actionpage';
364             }
365             trigger_error("$action: Does not appera to be an 'action page'", E_USER_NOTICE);
366             return 'browse';
367         }
368                 
369         trigger_error("$action: Unknown action", E_USER_NOTICE);
370         return 'browse';
371     }
372
373     function action_browse () {
374         $this->compress_output();
375         include_once("lib/display.php");
376         displayPage($this);
377     }
378
379     function action_actionpage () {
380         $this->compress_output();
381         include_once("lib/display.php");
382         actionPage($this, $this->_actionpage);
383     }
384     
385     function action_diff () {
386         $this->compress_output();
387         include_once "lib/diff.php";
388         showDiff($this);
389     }
390
391     function action_search () {
392         // This is obsolete: reformulate URL and redirect.
393         // FIXME: this whole section should probably be deleted.
394         if ($this->getArg('searchtype') == 'full') {
395             $search_page = _("FullTextSearch");
396         }
397         else {
398             $search_page = _("TitleSearch");
399         }
400         $this->redirect(WikiURL($search_page,
401                                 array('s' => $this->getArg('searchterm')),
402                                 'absolute_url'));
403     }
404
405     function action_edit () {
406         $this->compress_output();
407         include "lib/editpage.php";
408         editPage($this);
409     }
410
411     // FIXME: combine this with edit
412     function action_save () {
413         $this->compress_output();
414         include "lib/savepage.php";
415         savePage($this);
416     }
417
418     function action_lock () {
419         $page = $this->getPage();
420         $page->set('locked', true);
421         $this->action_browse();
422     }
423
424     function action_unlock () {
425         // FIXME: This check is redundant.
426         //$user->requireAuth(WIKIAUTH_ADMIN);
427         $page = $this->getPage();
428         $page->set('locked', false);
429         $this->action_browse();
430     }
431
432     function action_remove () {
433         // FIXME: This check is redundant.
434         //$user->requireAuth(WIKIAUTH_ADMIN);
435         include('lib/removepage.php');
436         RemovePage($this);
437     }
438
439     
440     function action_upload () {
441         include_once("lib/loadsave.php");
442         LoadPostFile($this);
443     }
444     
445     function action_zip () {
446         include_once("lib/loadsave.php");
447         MakeWikiZip($this);
448         // I don't think it hurts to add cruft at the end of the zip file.
449         echo "\n========================================================\n";
450         echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
451     }
452         
453     function action_dumpserial () {
454         include_once("lib/loadsave.php");
455         DumpToDir($this);
456     }
457
458     function action_loadfile () {
459         include_once("lib/loadsave.php");
460         LoadFileOrDir($this);
461     }
462 }
463
464 //FIXME: deprecated
465 function is_safe_action ($action) {
466     return WikiRequest::requiredAuthority($action) < WIKIAUTH_ADMIN;
467 }
468
469
470 function main () {
471     global $request;
472
473     $request = new WikiRequest();
474     
475     /* FIXME: is this needed anymore?
476     if (USE_PATH_INFO && ! $request->get('PATH_INFO')
477         && ! preg_match(',/$,', $request->get('REDIRECT_URL'))) {
478         $request->redirect(SERVER_URL
479                            . preg_replace('/(\?|$)/', '/\1',
480                                           $request->get('REQUEST_URI'),
481                                           1));
482         exit;
483     }
484     */
485
486     // Enable the output of most of the warning messages.
487     // The warnings will screw up zip files and setpref though.
488     global $ErrorManager;
489     if ($request->getArg('action') != 'zip') {
490         $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE);
491         //$ErrorManager->setPostponedErrorMask(0);
492     }
493
494     
495     //FIXME:
496     //if ($user->is_authenticated())
497     //  $LogEntry->user = $user->getId();
498
499     $request->deflowerDatabase();
500
501     $request->handleAction();
502     $request->finish();
503 }
504
505 main();
506
507
508 // Local Variables:
509 // mode: php
510 // tab-width: 8
511 // c-basic-offset: 4
512 // c-hanging-comment-ender-p: nil
513 // indent-tabs-mode: nil
514 // End:   
515 ?>