2 /***************************************************************************
3 * Copyright (C) 2003-2011 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
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. *
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. *
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 *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
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.
37 protected function __construct($auth = AUTH_PUBLIC
, $perms = 'user', $type = DO_AUTH
)
40 $this->perms
= $perms;
44 public function checkPerms()
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
);
52 public function hasType($type)
54 return ($this->type
& $type) == $type;
57 abstract protected function run(PlPage
&$page, array $args);
59 public function call(PlPage
&$page, array $args)
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);
72 if (!$this->checkPerms()) {
73 if (Platal
::notAllowed()) {
77 return $this->run($page, $args);
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.
85 class PlStdHook
extends PlHook
89 public function __construct($callback, $auth = AUTH_PUBLIC
, $perms = 'user', $type = DO_AUTH
)
91 parent
::__construct($auth, $perms, $type);
92 $this->callback
= $callback;
95 protected function run(PlPage
&$page, array $args)
97 global $session, $platal;
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);
105 $val = call_user_func_array($this->callback
, $args);
111 /** A specialized hook for API requests.
112 * It is intended to be used for passive API requests, authenticated either by
113 * an existing session (with a valid XSRF token), or by an alternative single
114 * request auth mechanism implemented by PlSession::apiAuth.
116 * This hook is suitable for read-write requests against the website, provided
117 * $auth is set appropriately. Note that the auth level is only checked for
118 * session-authenticated users, as "apiAuth" users are assumed to always have
119 * the requested level (use another hook otherwise).
121 * The callback will be passed as arguments the PlPage, the authenticated
122 * PlUser, the JSON decoded payload, and the remaining path components, as with
125 * If the callback intends to JSON-encode its returned value, it is advised to
126 * use PlPage::jsonAssign, and return PL_JSON to enable automatic encoding.
128 class PlApiHook
extends PlHook
133 public function __construct($callback, $auth = AUTH_PUBLIC
, $perms = 'user', $type = NO_AUTH
)
135 // As mentioned above, $auth is only applied for session-based auth
136 // (as opposed to token-based). PlHook is initialized to AUTH_PUBLIC to
137 // avoid it refusing to approve requests; this is important as the user
138 // is not yet authenticated at that point (see below for the actual
139 // permissions check).
140 parent
::__construct(AUTH_PUBLIC
, $perms, $type);
141 $this->actualAuth
= $auth;
142 $this->callback
= $callback;
145 private function getEncodedPayload($method)
147 return $method == "GET" ?
"" : file_get_contents("php://input");
150 private function decodePayload($encodedPayload)
152 return empty($encodedPayload) ?
array() : json_decode($encodedPayload, true
);
155 protected function run(PlPage
&$page, array $args)
157 $method = $_SERVER['REQUEST_METHOD'];
158 $encodedPayload = $this->getEncodedPayload($method);
159 $jsonPayload = $this->decodePayload($encodedPayload);
160 $resource = '/' . implode('/', $args);
162 // If the payload wasn't a valid JSON encoded object, bail out early.
163 if (is_null($jsonPayload)) {
164 $page->trigError("Could not decode the JSON-encoded payload sent with the request.");
165 return PL_BAD_REQUEST
;
168 // Authenticate the request. Try first with the existing session (which
169 // is less expensive to check), by veryfing that the XSRF token is
170 // valid; otherwise fallbacks to API-type authentication from PlSession.
171 if (S
::logged() && S
::has_xsrf_token() && Platal
::session()->checkAuth($this->actualAuth
)) {
174 $user = Platal
::session()->apiAuth($method, $resource, $encodedPayload);
177 // Check the permissions, unless the handler is fully public.
178 if ($this->actualAuth
> AUTH_PUBLIC
) {
179 if (is_null($user) ||
!$user->checkPerms($this->perms
)) {
184 // Invoke the callback, whose signature is (PlPage, PlUser, jsonPayload).
186 array_unshift($args, $page, $user, $jsonPayload);
187 return call_user_func_array($this->callback
, $args);
191 /** A specialized hook for token-based requests.
192 * It is intended for purely passive requests (typically for serving CSV or RSS
193 * content outside the browser), and can fallback to regular session-based
194 * authentication when the token is not valid/available.
196 * Note that $auth is only applied for session-backed authentication; it is
197 * assumed that token-based auth is always enough for the hook (otherwise, just
198 * use PlStdHook above).
200 * Also, this hook requires that the first two unmatched path components are the
201 * user and token (for instance /<matched path>/<user>/<token>/....). They will
202 * be popped before being passed to the handler, and replaced by the request's
205 class PlTokenHook
extends PlHook
210 public function __construct($callback, $auth = AUTH_PUBLIC
, $perms = 'user', $type = NO_AUTH
)
212 // See PlApiHook::__construct.
213 parent
::__construct(AUTH_PUBLIC
, $perms, $type);
214 $this->actualAuth
= $auth;
215 $this->callback
= $callback;
218 protected function run(PlPage
&$page, array $args)
220 // Retrieve the user, either from the session (less expensive, as it is
221 // already there), or from the in-path (user, token) pair.
222 if (S
::logged() && Platal
::session()->checkAuth($this->actualAuth
)) {
225 $user = Platal
::session()->tokenAuth(@$args[1], @$args[2]);
228 // Check the permissions, unless the handler is fully public.
229 if ($this->actualAuth
> AUTH_PUBLIC
) {
230 if (is_null($user) ||
!$user->checkPerms($this->perms
)) {
235 // Replace the first three remaining elements of the path with the
236 // PlPage and PlUser objects.
240 return call_user_func_array($this->callback
, $args);
244 /** A specialized plat/al hook for serving wiki pages.
246 class PlWikiHook
extends PlHook
248 public function __construct($auth = AUTH_PUBLIC
, $perms = 'user', $type = DO_AUTH
)
250 parent
::__construct($auth, $perms, $type);
253 protected function run(PlPage
&$page, array $args)
262 public $aliased = null
;
263 public $children = array();
265 public function addChild(array $path, PlHook
$hook)
268 $next = array_shift($path);
270 if ($next && $next{0} == '%') {
272 $next = $platal->hook_map(substr($next, 1));
277 @$child =& $this->children
[$next];
279 $child = new PlHookTree();
280 $this->children
[$next] =& $child;
281 $child->aliased
= $alias;
284 $child->hook
= $hook;
286 $child->addChild($path, $hook);
290 private function findChildAux(array $remain, array $matched, array $aliased)
293 if ($this->aliased
) {
297 $child = @$this->children
[$next];
299 array_shift($remain);
301 return $child->findChildAux($remain, $matched, $aliased);
304 return array($this->hook
, $matched, $remain, $aliased);
307 public function findChild(array $path)
309 return $this->findChildAux($path, array(), array());
312 private function findNearestChildAux(array $remain, array $matched, array $aliased)
315 if ($this->aliased
) {
319 $child = @$this->children
[$next];
324 foreach ($this->children
as $path=>$hook) {
325 $lev = levenshtein($next, $path);
326 if ($lev <= $nearest_lev
327 && ($lev < strlen($next) / 2 ||
strpos($next, $path) !== false
328 ||
strpos($path, $next) !== false
)) {
329 $sdx = levenshtein(soundex($next), soundex($path));
330 if ($lev == $nearest_lev ||
$sdx < $nearest_sdx) {
341 array_shift($remain);
343 return $child->findNearestChildAux($remain, $matched, $aliased);
345 if (($pos = strpos($next, '.php')) !== false
) {
346 $remain[0] = substr($next, 0, $pos);
347 return $this->findNearestChildAux($remain, $matched, $aliased);
350 return array($this->hook
, $matched, $remain, $aliased);
353 public function findNearestChild(array $path)
355 return $this->findNearestChildAux($path, array(), array());
359 abstract class Platal
368 public $argv = array();
370 static private $_page = null
;
372 public function __construct()
374 global $platal, $session, $globals;
377 /* Assign globals first, then call init: init must be used for operations
378 * that requires access to the content of $globals (e.g. XDB requires
379 * $globals to be assigned.
381 $globals = $this->buildGlobals();
384 /* Get the current session: assign first, then activate the session.
386 $session = $this->buildSession();
387 if (!$session->startAvailableAuth()) {
388 Platal
::page()->trigError("Données d'authentification invalides.");
391 $modules = func_get_args();
392 if (isset($modules[0]) && is_array($modules[0])) {
393 $modules = $modules[0];
395 $this->path
= trim(Get
::_get('n', null
), '/');
397 $this->mods
= array();
398 $this->hooks
= new PlHookTree();
400 array_unshift($modules, 'core');
401 foreach ($modules as $module) {
402 $module = strtolower($module);
403 $this->mods
[$module] = $m = PLModule
::factory($module);
404 $hooks = $m->handlers();
405 foreach ($hooks as $path=>$hook) {
406 $this->hooks
->addChild(explode('/', $path), $hook);
410 if ($globals->mode
== '') {
411 pl_redirect('index.html');
415 public function pl_self($n = null
)
421 return join('/', array_slice($this->argv
, 0, $n +
1));
423 if ($n <= -count($this->argv
))
424 return $this->argv
[0];
426 return join('/', array_slice($this->argv
, 0, $n));
429 public static function wiki_hook($auth = AUTH_PUBLIC
, $perms = 'user', $type = DO_AUTH
)
431 return new PlWikiHook($auth, $perms, $type);
434 public function hook_map($name)
439 protected function find_hook()
441 $p = explode('/', $this->path
);
442 list($hook, $matched, $remain, $aliased) = $this->hooks
->findChild($p);
446 $this->argv
= $remain;
447 array_unshift($this->argv
, implode('/', $matched));
448 if (!empty($aliased)) {
449 $this->ns
= implode('/', $aliased) . '/';
451 $this->https
= !$hook->hasType(NO_HTTPS
);
455 public function near_hook()
457 $p = explode('/', $this->path
);
458 list($hook, $matched, $remain, $aliased) = $this->hooks
->findNearestChild($p);
462 $url = implode('/', $matched);
463 if (!empty($remain)) {
464 $url .= '/' . implode('/', $remain);
466 if ($url == $this->path ||
levenshtein($url, $this->path
) > strlen($url) / 3
467 ||
!$hook->checkPerms()) {
473 private function call_hook(PlPage
&$page)
475 $hook = $this->find_hook();
479 global $globals, $session;
480 if ($this->https
&& !@$_SERVER['HTTPS'] && $globals->core
->secure_domain
) {
481 http_redirect('https://' . $globals->core
->secure_domain
. $_SERVER['REQUEST_URI']);
484 return $hook->call($page, $this->argv
);
487 /** Show the authentication form.
489 abstract public function force_login(PlPage
& $page);
491 public function run()
493 $page =& self
::page();
495 if (empty($this->path
)) {
496 $this->path
= 'index';
500 $page->assign('platal', $this);
501 $res = $this->call_hook($page);
504 $this->mods
['core']->handler_400($page);
508 $this->mods
['core']->handler_403($page);
512 $this->mods
['core']->handler_404($page);
518 } catch (Exception
$e) {
519 header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');
520 PlErrorReport
::report($e);
521 if (self
::globals()->debug
) {
522 $page->kill(pl_entities($e->getMessage())
523 . '<pre>' . pl_entities("" . $e) . '</pre>');
525 $page->kill(pl_entities($e->getMessage()));
529 $page->assign('platal', $this);
530 if ($res == PL_JSON
) {
537 public function error403()
539 $page =& self
::page();
541 $this->mods
['core']->handler_403($page);
542 $page->assign('platal', $this);
546 public function error404()
548 $page =& self
::page();
550 $this->mods
['core']->handler_404($page);
551 $page->assign('platal', $this);
555 public static function notAllowed()
558 self
::page()->trigWarning('Tu accèdes à cette page car tu es administrateur du site.');
565 public static function load($modname, $include = null
)
568 $modname = strtolower($modname);
569 if (isset($platal->mods
[$modname])) {
570 if (is_null($include)) {
573 $platal->mods
[$modname]->load($include);
575 if (is_null($include)) {
576 require_once PLModule
::path($modname) . '.php';
578 require_once PLModule
::path($modname) . '/' . $include;
583 public static function assert($cond, $error, $userfriendly = null
)
585 if ($cond === false
) {
586 if ($userfriendly == null
) {
587 $userfriendly = "Une erreur interne s'est produite.
588 Merci de réessayer la manipulation qui a déclenché l'erreur ;
589 si cela ne fonctionne toujours pas, merci de nous signaler le problème rencontré.";
591 throw new PlException($userfriendly, $error);
595 public function &buildLogger($uid, $suid = 0)
597 if (defined('PL_LOGGER_CLASS')) {
598 $class = PL_LOGGER_CLASS
;
599 $logger = new $class($uid, $suid);
602 return PlLogger
::dummy($uid, $suid);
606 protected function &buildPage()
608 $pageclass = PL_PAGE_CLASS
;
609 $page = new $pageclass();
613 static public function &page()
615 if (is_null(self
::$_page)) {
617 self
::$_page = $platal->buildPage();
622 protected function &buildSession()
624 $sessionclass = PL_SESSION_CLASS
;
625 $session = new $sessionclass();
629 static public function &session()
635 protected function &buildGlobals()
637 $globalclass = PL_GLOBALS_CLASS
;
638 $globals = new $globalclass();
642 static public function &globals()
649 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: