2 /***************************************************************************
3 * Copyright (C) 2003-2010 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 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.
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).
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
125 class PlTokenHook
extends PlHook
130 public function __construct($callback, $auth = AUTH_PUBLIC
, $perms = 'user', $type = NO_AUTH
)
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;
142 protected function run(PlPage
&$page, array $args)
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
)) {
149 $user = Platal
::session()->tokenAuth(@$args[1], @$args[2]);
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
)) {
159 // Replace the first three remaining elements of the path with the
160 // PlPage and PlUser objects.
164 return call_user_func_array($this->callback
, $args);
168 /** A specialized plat/al hook for serving wiki pages.
170 class PlWikiHook
extends PlHook
172 public function __construct($auth = AUTH_PUBLIC
, $perms = 'user', $type = DO_AUTH
)
174 parent
::__construct($auth, $perms, $type);
177 protected function run(PlPage
&$page, array $args)
186 public $aliased = null
;
187 public $children = array();
189 public function addChild(array $path, PlHook
$hook)
192 $next = array_shift($path);
194 if ($next && $next{0} == '%') {
196 $next = $platal->hook_map(substr($next, 1));
201 @$child =& $this->children
[$next];
203 $child = new PlHookTree();
204 $this->children
[$next] =& $child;
205 $child->aliased
= $alias;
208 $child->hook
= $hook;
210 $child->addChild($path, $hook);
214 private function findChildAux(array $remain, array $matched, array $aliased)
217 if ($this->aliased
) {
221 $child = @$this->children
[$next];
223 array_shift($remain);
225 return $child->findChildAux($remain, $matched, $aliased);
228 return array($this->hook
, $matched, $remain, $aliased);
231 public function findChild(array $path)
233 return $this->findChildAux($path, array(), array());
236 private function findNearestChildAux(array $remain, array $matched, array $aliased)
239 if ($this->aliased
) {
243 $child = @$this->children
[$next];
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) {
265 array_shift($remain);
267 return $child->findNearestChildAux($remain, $matched, $aliased);
269 if (($pos = strpos($next, '.php')) !== false
) {
270 $remain[0] = substr($next, 0, $pos);
271 return $this->findNearestChildAux($remain, $matched, $aliased);
274 return array($this->hook
, $matched, $remain, $aliased);
277 public function findNearestChild(array $path)
279 return $this->findNearestChildAux($path, array(), array());
283 abstract class Platal
292 public $argv = array();
294 static private $_page = null
;
296 public function __construct()
298 global $platal, $session, $globals;
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.
305 $globals = $this->buildGlobals();
308 /* Get the current session: assign first, then activate the session.
310 $session = $this->buildSession();
311 if (!$session->startAvailableAuth()) {
312 Platal
::page()->trigError("Données d'authentification invalides.");
315 $modules = func_get_args();
316 if (isset($modules[0]) && is_array($modules[0])) {
317 $modules = $modules[0];
319 $this->path
= trim(Get
::_get('n', null
), '/');
321 $this->mods
= array();
322 $this->hooks
= new PlHookTree();
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);
334 if ($globals->mode
== '') {
335 pl_redirect('index.html');
339 public function pl_self($n = null
)
345 return join('/', array_slice($this->argv
, 0, $n +
1));
347 if ($n <= -count($this->argv
))
348 return $this->argv
[0];
350 return join('/', array_slice($this->argv
, 0, $n));
353 public static function wiki_hook($auth = AUTH_PUBLIC
, $perms = 'user', $type = DO_AUTH
)
355 return new PlWikiHook($auth, $perms, $type);
358 public function hook_map($name)
363 protected function find_hook()
365 $p = explode('/', $this->path
);
366 list($hook, $matched, $remain, $aliased) = $this->hooks
->findChild($p);
370 $this->argv
= $remain;
371 array_unshift($this->argv
, implode('/', $matched));
372 if (!empty($aliased)) {
373 $this->ns
= implode('/', $aliased) . '/';
375 $this->https
= !$hook->hasType(NO_HTTPS
);
379 public function near_hook()
381 $p = explode('/', $this->path
);
382 list($hook, $matched, $remain, $aliased) = $this->hooks
->findNearestChild($p);
386 $url = implode('/', $matched);
387 if (!empty($remain)) {
388 $url .= '/' . implode('/', $remain);
390 if ($url == $this->path ||
levenshtein($url, $this->path
) > strlen($url) / 3
391 ||
!$hook->checkPerms()) {
397 private function call_hook(PlPage
&$page)
399 $hook = $this->find_hook();
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']);
408 return $hook->call($page, $this->argv
);
411 /** Show the authentication form.
413 abstract public function force_login(PlPage
& $page);
415 public function run()
417 $page =& self
::page();
419 if (empty($this->path
)) {
420 $this->path
= 'index';
424 $page->assign('platal', $this);
425 $res = $this->call_hook($page);
428 $this->mods
['core']->handler_400($page);
432 $this->mods
['core']->handler_403($page);
436 $this->mods
['core']->handler_404($page);
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>');
449 $page->kill(pl_entities($e->getMessage()));
453 $page->assign('platal', $this);
454 if ($res == PL_JSON
) {
461 public function error403()
463 $page =& self
::page();
465 $this->mods
['core']->handler_403($page);
466 $page->assign('platal', $this);
470 public function error404()
472 $page =& self
::page();
474 $this->mods
['core']->handler_404($page);
475 $page->assign('platal', $this);
479 public static function notAllowed()
482 self
::page()->trigWarning('Tu accèdes à cette page car tu es administrateur du site.');
489 public static function load($modname, $include = null
)
492 $modname = strtolower($modname);
493 if (isset($platal->mods
[$modname])) {
494 if (is_null($include)) {
497 $platal->mods
[$modname]->load($include);
499 if (is_null($include)) {
500 require_once PLModule
::path($modname) . '.php';
502 require_once PLModule
::path($modname) . '/' . $include;
507 public static function assert($cond, $error, $userfriendly = null
)
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é.";
515 throw new PlException($userfriendly, $error);
519 public function &buildLogger($uid, $suid = 0)
521 if (defined('PL_LOGGER_CLASS')) {
522 $class = PL_LOGGER_CLASS
;
523 $logger = new $class($uid, $suid);
526 return PlLogger
::dummy($uid, $suid);
530 protected function &buildPage()
532 $pageclass = PL_PAGE_CLASS
;
533 $page = new $pageclass();
537 static public function &page()
539 if (is_null(self
::$_page)) {
541 self
::$_page = $platal->buildPage();
546 protected function &buildSession()
548 $sessionclass = PL_SESSION_CLASS
;
549 $session = new $sessionclass();
553 static public function &session()
559 protected function &buildGlobals()
561 $globalclass = PL_GLOBALS_CLASS
;
562 $globals = new $globalclass();
566 static public function &globals()
573 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: