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