Creates a new plat/al error code for invalid request. This is intended
[platal.git] / classes / platal.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2010 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
5 * *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. *
10 * *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program; if not, write to the Free Software *
18 * Foundation, Inc., *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
21
22 // Return values for handlers and hooks. This defines the behavior of both the
23 // plat/al engine, and the invidivual hooks.
24 define('PL_DO_AUTH', 300); // User should be redirected to the login page.
25 define('PL_BAD_REQUEST', 400); // Request is not valid, and could not be interpreted.
26 define('PL_FORBIDDEN', 403); // User is not allowed to view page (auth or permission error).
27 define('PL_NOT_FOUND', 404); // Page doesn't not exist. Engine will try to offer suggestions.
28 define('PL_WIKI', 500); // Page is a wiki page, plat/al engine should yield to the wiki engine.
29 define('PL_JSON', 501); // Page is valid, but result should be JSON-encoded, not HTML-encoded.
30
31 abstract class PlHook
32 {
33 protected $auth;
34 protected $perms;
35 protected $type;
36
37 protected function __construct($auth = AUTH_PUBLIC, $perms = 'user', $type = DO_AUTH)
38 {
39 $this->auth = $auth;
40 $this->perms = $perms;
41 $this->type = $type;
42 }
43
44 public function checkPerms()
45 {
46 // Don't check permissions if there are no permission requirement
47 // (either no requested group membership, or public auth is allowed).
48 return !$this->perms || $this->auth == AUTH_PUBLIC ||
49 Platal::session()->checkPerms($this->perms);
50 }
51
52 public function hasType($type)
53 {
54 return ($this->type & $type) == $type;
55 }
56
57 abstract protected function run(PlPage &$page, array $args);
58
59 public function call(PlPage &$page, array $args)
60 {
61 global $globals, $session, $platal;
62 if (!$session->checkAuth($this->auth)) {
63 if ($this->hasType(DO_AUTH)) {
64 if (!$session->start($this->auth)) {
65 $platal->force_login($page);
66 return PL_FORBIDDEN;
67 }
68 } else {
69 return PL_FORBIDDEN;
70 }
71 }
72 if (!$this->checkPerms()) {
73 if (Platal::notAllowed()) {
74 return PL_FORBIDDEN;
75 }
76 }
77 return $this->run($page, $args);
78 }
79 }
80
81 /** The standard plat/al hook, for interactive requests.
82 * It optionally does active authentication (DO_AUTH). The handler is invoked
83 * with the PlPage object, and with each of the remaining path components.
84 */
85 class PlStdHook extends PlHook
86 {
87 private $callback;
88
89 public function __construct($callback, $auth = AUTH_PUBLIC, $perms = 'user', $type = DO_AUTH)
90 {
91 parent::__construct($auth, $perms, $type);
92 $this->callback = $callback;
93 }
94
95 protected function run(PlPage &$page, array $args)
96 {
97 global $session, $platal;
98
99 $args[0] = $page;
100 $val = call_user_func_array($this->callback, $args);
101 if ($val == PL_DO_AUTH) {
102 if (!$session->start($session->loggedLevel())) {
103 $platal->force_login($page);
104 }
105 $val = call_user_func_array($this->callback, $args);
106 }
107 return $val;
108 }
109 }
110
111 /** A specialized hook for token-based requests.
112 * It is intended for purely passive requests (typically for serving CSV or RSS
113 * content outside the browser), and can fallback to regular session-based
114 * authentication when the token is not valid/available.
115 *
116 * Note that $auth is only applied for session-backed authentication; it is
117 * assumed that token-based auth is always enough for the hook (otherwise, just
118 * use PlStdHook above).
119 *
120 * Also, this hook requires that the first two unmatched path components are the
121 * user and token (for instance /<matched path>/<user>/<token>/....). They will
122 * be popped before being passed to the handler, and replaced by the request's
123 * PlUser object.
124 */
125 class PlTokenHook extends PlHook
126 {
127 private $actualAuth;
128 private $callback;
129
130 public function __construct($callback, $auth = AUTH_PUBLIC, $perms = 'user', $type = NO_AUTH)
131 {
132 // As mentioned above, $auth is only applied for session-based auth
133 // (as opposed to token-based). PlHook is initialized to AUTH_PUBLIC to
134 // avoid it refusing to approve requests; this is important as the user
135 // is not yet authenticated at that point (see below for the actual
136 // permissions check).
137 parent::__construct(AUTH_PUBLIC, $perms, $type);
138 $this->actualAuth = $auth;
139 $this->callback = $callback;
140 }
141
142 protected function run(PlPage &$page, array $args)
143 {
144 // Retrieve the user, either from the session (less expensive, as it is
145 // already there), or from the in-path (user, token) pair.
146 if (S::logged() && Platal::session()->checkAuth($this->actualAuth)) {
147 $user = S::user();
148 } else {
149 $user = Platal::session()->tokenAuth(@$args[1], @$args[2]);
150 }
151
152 // Check the permissions, unless the handler is fully public.
153 if ($this->actualAuth > AUTH_PUBLIC) {
154 if (is_null($user) || !$user->checkPerms($this->perms)) {
155 return PL_FORBIDDEN;
156 }
157 }
158
159 // Replace the first three remaining elements of the path with the
160 // PlPage and PlUser objects.
161 array_shift($args);
162 $args[0] = $page;
163 $args[1] = $user;
164 return call_user_func_array($this->callback, $args);
165 }
166 }
167
168 /** A specialized plat/al hook for serving wiki pages.
169 */
170 class PlWikiHook extends PlHook
171 {
172 public function __construct($auth = AUTH_PUBLIC, $perms = 'user', $type = DO_AUTH)
173 {
174 parent::__construct($auth, $perms, $type);
175 }
176
177 protected function run(PlPage &$page, array $args)
178 {
179 return PL_WIKI;
180 }
181 }
182
183 class PlHookTree
184 {
185 public $hook = null;
186 public $aliased = null;
187 public $children = array();
188
189 public function addChild(array $path, PlHook $hook)
190 {
191 global $platal;
192 $next = array_shift($path);
193 $alias = null;
194 if ($next && $next{0} == '%') {
195 $alias = $next;
196 $next = $platal->hook_map(substr($next, 1));
197 }
198 if (!$next) {
199 return;
200 }
201 @$child =& $this->children[$next];
202 if (!$child) {
203 $child = new PlHookTree();
204 $this->children[$next] =& $child;
205 $child->aliased = $alias;
206 }
207 if (empty($path)) {
208 $child->hook = $hook;
209 } else {
210 $child->addChild($path, $hook);
211 }
212 }
213
214 private function findChildAux(array $remain, array $matched, array $aliased)
215 {
216 $next = @$remain[0];
217 if ($this->aliased) {
218 $aliased = $matched;
219 }
220 if (!empty($next)) {
221 $child = @$this->children[$next];
222 if ($child) {
223 array_shift($remain);
224 $matched[] = $next;
225 return $child->findChildAux($remain, $matched, $aliased);
226 }
227 }
228 return array($this->hook, $matched, $remain, $aliased);
229 }
230
231 public function findChild(array $path)
232 {
233 return $this->findChildAux($path, array(), array());
234 }
235
236 private function findNearestChildAux(array $remain, array $matched, array $aliased)
237 {
238 $next = @$remain[0];
239 if ($this->aliased) {
240 $aliased = $matched;
241 }
242 if (!empty($next)) {
243 $child = @$this->children[$next];
244 if (!$child) {
245 $nearest_lev = 50;
246 $nearest_sdx = 50;
247 $match = null;
248 foreach ($this->children as $path=>$hook) {
249 $lev = levenshtein($next, $path);
250 if ($lev <= $nearest_lev
251 && ($lev < strlen($next) / 2 || strpos($next, $path) !== false
252 || strpos($path, $next) !== false)) {
253 $sdx = levenshtein(soundex($next), soundex($path));
254 if ($lev == $nearest_lev || $sdx < $nearest_sdx) {
255 $child = $hook;
256 $nearest_lev = $lev;
257 $nearest_sdx = $sdx;
258 $match = $path;
259 }
260 }
261 }
262 $next = $match;
263 }
264 if ($child) {
265 array_shift($remain);
266 $matched[] = $next;
267 return $child->findNearestChildAux($remain, $matched, $aliased);
268 }
269 if (($pos = strpos($next, '.php')) !== false) {
270 $remain[0] = substr($next, 0, $pos);
271 return $this->findNearestChildAux($remain, $matched, $aliased);
272 }
273 }
274 return array($this->hook, $matched, $remain, $aliased);
275 }
276
277 public function findNearestChild(array $path)
278 {
279 return $this->findNearestChildAux($path, array(), array());
280 }
281 }
282
283 abstract class Platal
284 {
285 private $mods;
286 private $hooks;
287
288 protected $https;
289
290 public $ns;
291 public $path;
292 public $argv = array();
293
294 static private $_page = null;
295
296 public function __construct()
297 {
298 global $platal, $session, $globals;
299 $platal = $this;
300
301 /* Assign globals first, then call init: init must be used for operations
302 * that requires access to the content of $globals (e.g. XDB requires
303 * $globals to be assigned.
304 */
305 $globals = $this->buildGlobals();
306 $globals->init();
307
308 /* Get the current session: assign first, then activate the session.
309 */
310 $session = $this->buildSession();
311 if (!$session->startAvailableAuth()) {
312 Platal::page()->trigError("Données d'authentification invalides.");
313 }
314
315 $modules = func_get_args();
316 if (isset($modules[0]) && is_array($modules[0])) {
317 $modules = $modules[0];
318 }
319 $this->path = trim(Get::_get('n', null), '/');
320
321 $this->mods = array();
322 $this->hooks = new PlHookTree();
323
324 array_unshift($modules, 'core');
325 foreach ($modules as $module) {
326 $module = strtolower($module);
327 $this->mods[$module] = $m = PLModule::factory($module);
328 $hooks = $m->handlers();
329 foreach ($hooks as $path=>$hook) {
330 $this->hooks->addChild(explode('/', $path), $hook);
331 }
332 }
333
334 if ($globals->mode == '') {
335 pl_redirect('index.html');
336 }
337 }
338
339 public function pl_self($n = null)
340 {
341 if (is_null($n))
342 return $this->path;
343
344 if ($n >= 0)
345 return join('/', array_slice($this->argv, 0, $n + 1));
346
347 if ($n <= -count($this->argv))
348 return $this->argv[0];
349
350 return join('/', array_slice($this->argv, 0, $n));
351 }
352
353 public static function wiki_hook($auth = AUTH_PUBLIC, $perms = 'user', $type = DO_AUTH)
354 {
355 return new PlWikiHook($auth, $perms, $type);
356 }
357
358 public function hook_map($name)
359 {
360 return null;
361 }
362
363 protected function find_hook()
364 {
365 $p = explode('/', $this->path);
366 list($hook, $matched, $remain, $aliased) = $this->hooks->findChild($p);
367 if (empty($hook)) {
368 return null;
369 }
370 $this->argv = $remain;
371 array_unshift($this->argv, implode('/', $matched));
372 if (!empty($aliased)) {
373 $this->ns = implode('/', $aliased) . '/';
374 }
375 $this->https = !$hook->hasType(NO_HTTPS);
376 return $hook;
377 }
378
379 public function near_hook()
380 {
381 $p = explode('/', $this->path);
382 list($hook, $matched, $remain, $aliased) = $this->hooks->findNearestChild($p);
383 if (empty($hook)) {
384 return null;
385 }
386 $url = implode('/', $matched);
387 if (!empty($remain)) {
388 $url .= '/' . implode('/', $remain);
389 }
390 if ($url == $this->path || levenshtein($url, $this->path) > strlen($url) / 3
391 || !$hook->checkPerms()) {
392 return null;
393 }
394 return $url;
395 }
396
397 private function call_hook(PlPage &$page)
398 {
399 $hook = $this->find_hook();
400 if (empty($hook)) {
401 return PL_NOT_FOUND;
402 }
403 global $globals, $session;
404 if ($this->https && !@$_SERVER['HTTPS'] && $globals->core->secure_domain) {
405 http_redirect('https://' . $globals->core->secure_domain . $_SERVER['REQUEST_URI']);
406 }
407
408 return $hook->call($page, $this->argv);
409 }
410
411 /** Show the authentication form.
412 */
413 abstract public function force_login(PlPage& $page);
414
415 public function run()
416 {
417 $page =& self::page();
418
419 if (empty($this->path)) {
420 $this->path = 'index';
421 }
422
423 try {
424 $page->assign('platal', $this);
425 $res = $this->call_hook($page);
426 switch ($res) {
427 case PL_BAD_REQUEST:
428 $this->mods['core']->handler_400($page);
429 break;
430
431 case PL_FORBIDDEN:
432 $this->mods['core']->handler_403($page);
433 break;
434
435 case PL_NOT_FOUND:
436 $this->mods['core']->handler_404($page);
437 break;
438
439 case PL_WIKI:
440 return PL_WIKI;
441 }
442 } catch (Exception $e) {
443 header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');
444 PlErrorReport::report($e);
445 if (self::globals()->debug) {
446 $page->kill(pl_entities($e->getMessage())
447 . '<pre>' . pl_entities("" . $e) . '</pre>');
448 } else {
449 $page->kill(pl_entities($e->getMessage()));
450 }
451 }
452
453 $page->assign('platal', $this);
454 if ($res == PL_JSON) {
455 $page->runJSon();
456 } else {
457 $page->run();
458 }
459 }
460
461 public function error403()
462 {
463 $page =& self::page();
464
465 $this->mods['core']->handler_403($page);
466 $page->assign('platal', $this);
467 $page->run();
468 }
469
470 public function error404()
471 {
472 $page =& self::page();
473
474 $this->mods['core']->handler_404($page);
475 $page->assign('platal', $this);
476 $page->run();
477 }
478
479 public static function notAllowed()
480 {
481 if (S::admin()) {
482 self::page()->trigWarning('Tu accèdes à cette page car tu es administrateur du site.');
483 return false;
484 } else {
485 return true;
486 }
487 }
488
489 public static function load($modname, $include = null)
490 {
491 global $platal;
492 $modname = strtolower($modname);
493 if (isset($platal->mods[$modname])) {
494 if (is_null($include)) {
495 return;
496 }
497 $platal->mods[$modname]->load($include);
498 } else {
499 if (is_null($include)) {
500 require_once PLModule::path($modname) . '.php';
501 } else {
502 require_once PLModule::path($modname) . '/' . $include;
503 }
504 }
505 }
506
507 public static function assert($cond, $error, $userfriendly = null)
508 {
509 if ($cond === false) {
510 if ($userfriendly == null) {
511 $userfriendly = "Une erreur interne s'est produite.
512 Merci de réessayer la manipulation qui a déclenché l'erreur ;
513 si cela ne fonctionne toujours pas, merci de nous signaler le problème rencontré.";
514 }
515 throw new PlException($userfriendly, $error);
516 }
517 }
518
519 public function &buildLogger($uid, $suid = 0)
520 {
521 if (defined('PL_LOGGER_CLASS')) {
522 $class = PL_LOGGER_CLASS;
523 $logger = new $class($uid, $suid);
524 return $logger;
525 } else {
526 return PlLogger::dummy($uid, $suid);
527 }
528 }
529
530 protected function &buildPage()
531 {
532 $pageclass = PL_PAGE_CLASS;
533 $page = new $pageclass();
534 return $page;
535 }
536
537 static public function &page()
538 {
539 if (is_null(self::$_page)) {
540 global $platal;
541 self::$_page = $platal->buildPage();
542 }
543 return self::$_page;
544 }
545
546 protected function &buildSession()
547 {
548 $sessionclass = PL_SESSION_CLASS;
549 $session = new $sessionclass();
550 return $session;
551 }
552
553 static public function &session()
554 {
555 global $session;
556 return $session;
557 }
558
559 protected function &buildGlobals()
560 {
561 $globalclass = PL_GLOBALS_CLASS;
562 $globals = new $globalclass();
563 return $globals;
564 }
565
566 static public function &globals()
567 {
568 global $globals;
569 return $globals;
570 }
571 }
572
573 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
574 ?>