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