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 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);
34 protected function __construct($auth = AUTH_PUBLIC
, $perms = 'user', $type = DO_AUTH
)
37 $this->perms
= $perms;
41 public function checkPerms()
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
);
49 public function hasType($type)
51 return ($this->type
& $type) == $type;
54 abstract protected function run(PlPage
&$page, array $args);
56 public function call(PlPage
&$page, array $args)
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);
69 if (!$this->checkPerms()) {
70 if (Platal
::notAllowed()) {
74 return $this->run($page, $args);
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.
82 class PlStdHook
extends PlHook
86 public function __construct($callback, $auth = AUTH_PUBLIC
, $perms = 'user', $type = DO_AUTH
)
88 parent
::__construct($auth, $perms, $type);
89 $this->callback
= $callback;
92 protected function run(PlPage
&$page, array $args)
94 global $session, $platal;
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);
102 $val = call_user_func_array($this->callback
, $args);
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.
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).
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
122 class PlTokenHook
extends PlHook
127 public function __construct($callback, $auth = AUTH_PUBLIC
, $perms = 'user', $type = NO_AUTH
)
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;
139 protected function run(PlPage
&$page, array $args)
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
)) {
146 $user = Platal
::session()->tokenAuth(@$args[1], @$args[2]);
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
)) {
156 // Replace the first three remaining elements of the path with the
157 // PlPage and PlUser objects.
161 return call_user_func_array($this->callback
, $args);
165 /** A specialized plat/al hook for serving wiki pages.
167 class PlWikiHook
extends PlHook
169 public function __construct($auth = AUTH_PUBLIC
, $perms = 'user', $type = DO_AUTH
)
171 parent
::__construct($auth, $perms, $type);
174 protected function run(PlPage
&$page, array $args)
183 public $aliased = null
;
184 public $children = array();
186 public function addChild(array $path, PlHook
$hook)
189 $next = array_shift($path);
191 if ($next && $next{0} == '%') {
193 $next = $platal->hook_map(substr($next, 1));
198 @$child =& $this->children
[$next];
200 $child = new PlHookTree();
201 $this->children
[$next] =& $child;
202 $child->aliased
= $alias;
205 $child->hook
= $hook;
207 $child->addChild($path, $hook);
211 private function findChildAux(array $remain, array $matched, array $aliased)
214 if ($this->aliased
) {
218 $child = @$this->children
[$next];
220 array_shift($remain);
222 return $child->findChildAux($remain, $matched, $aliased);
225 return array($this->hook
, $matched, $remain, $aliased);
228 public function findChild(array $path)
230 return $this->findChildAux($path, array(), array());
233 private function findNearestChildAux(array $remain, array $matched, array $aliased)
236 if ($this->aliased
) {
240 $child = @$this->children
[$next];
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) {
262 array_shift($remain);
264 return $child->findNearestChildAux($remain, $matched, $aliased);
266 if (($pos = strpos($next, '.php')) !== false
) {
267 $remain[0] = substr($next, 0, $pos);
268 return $this->findNearestChildAux($remain, $matched, $aliased);
271 return array($this->hook
, $matched, $remain, $aliased);
274 public function findNearestChild(array $path)
276 return $this->findNearestChildAux($path, array(), array());
280 abstract class Platal
289 public $argv = array();
291 static private $_page = null
;
293 public function __construct()
295 global $platal, $session, $globals;
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.
302 $globals = $this->buildGlobals();
305 /* Get the current session: assign first, then activate the session.
307 $session = $this->buildSession();
308 if (!$session->startAvailableAuth()) {
309 Platal
::page()->trigError("Données d'authentification invalides.");
312 $modules = func_get_args();
313 if (isset($modules[0]) && is_array($modules[0])) {
314 $modules = $modules[0];
316 $this->path
= trim(Get
::_get('n', null
), '/');
318 $this->mods
= array();
319 $this->hooks
= new PlHookTree();
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);
331 if ($globals->mode
== '') {
332 pl_redirect('index.html');
336 public function pl_self($n = null
)
342 return join('/', array_slice($this->argv
, 0, $n +
1));
344 if ($n <= -count($this->argv
))
345 return $this->argv
[0];
347 return join('/', array_slice($this->argv
, 0, $n));
350 public static function wiki_hook($auth = AUTH_PUBLIC
, $perms = 'user', $type = DO_AUTH
)
352 return new PlWikiHook($auth, $perms, $type);
355 public function hook_map($name)
360 protected function find_hook()
362 $p = explode('/', $this->path
);
363 list($hook, $matched, $remain, $aliased) = $this->hooks
->findChild($p);
367 $this->argv
= $remain;
368 array_unshift($this->argv
, implode('/', $matched));
369 if (!empty($aliased)) {
370 $this->ns
= implode('/', $aliased) . '/';
372 $this->https
= !$hook->hasType(NO_HTTPS
);
376 public function near_hook()
378 $p = explode('/', $this->path
);
379 list($hook, $matched, $remain, $aliased) = $this->hooks
->findNearestChild($p);
383 $url = implode('/', $matched);
384 if (!empty($remain)) {
385 $url .= '/' . implode('/', $remain);
387 if ($url == $this->path ||
levenshtein($url, $this->path
) > strlen($url) / 3
388 ||
!$hook->checkPerms()) {
394 private function call_hook(PlPage
&$page)
396 $hook = $this->find_hook();
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']);
405 return $hook->call($page, $this->argv
);
408 /** Show the authentication form.
410 abstract public function force_login(PlPage
& $page);
412 public function run()
414 $page =& self
::page();
416 if (empty($this->path
)) {
417 $this->path
= 'index';
421 $page->assign('platal', $this);
422 $res = $this->call_hook($page);
425 $this->mods
['core']->handler_403($page);
429 $this->mods
['core']->handler_404($page);
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>');
442 $page->kill(pl_entities($e->getMessage()));
446 $page->assign('platal', $this);
447 if ($res == PL_JSON
) {
454 public function error403()
456 $page =& self
::page();
458 $this->mods
['core']->handler_403($page);
459 $page->assign('platal', $this);
463 public function error404()
465 $page =& self
::page();
467 $this->mods
['core']->handler_404($page);
468 $page->assign('platal', $this);
472 public static function notAllowed()
475 self
::page()->trigWarning('Tu accèdes à cette page car tu es administrateur du site.');
482 public static function load($modname, $include = null
)
485 $modname = strtolower($modname);
486 if (isset($platal->mods
[$modname])) {
487 if (is_null($include)) {
490 $platal->mods
[$modname]->load($include);
492 if (is_null($include)) {
493 require_once PLModule
::path($modname) . '.php';
495 require_once PLModule
::path($modname) . '/' . $include;
500 public static function assert($cond, $error, $userfriendly = null
)
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é.";
508 throw new PlException($userfriendly, $error);
512 public function &buildLogger($uid, $suid = 0)
514 if (defined('PL_LOGGER_CLASS')) {
515 $class = PL_LOGGER_CLASS
;
516 $logger = new $class($uid, $suid);
519 return PlLogger
::dummy($uid, $suid);
523 protected function &buildPage()
525 $pageclass = PL_PAGE_CLASS
;
526 $page = new $pageclass();
530 static public function &page()
532 if (is_null(self
::$_page)) {
534 self
::$_page = $platal->buildPage();
539 protected function &buildSession()
541 $sessionclass = PL_SESSION_CLASS
;
542 $session = new $sessionclass();
546 static public function &session()
552 protected function &buildGlobals()
554 $globalclass = PL_GLOBALS_CLASS
;
555 $globals = new $globalclass();
559 static public function &globals()
566 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: