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