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