4560f6ef5d3ea433bc0a7a81fd53075ab4b62d13
[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
27 abstract class PlHook
28 {
29 protected $auth;
30 protected $perms;
31 protected $type;
32
33 protected function __construct($auth = AUTH_PUBLIC, $perms = 'user', $type = DO_AUTH)
34 {
35 $this->auth = $auth;
36 $this->perms = $perms;
37 $this->type = $type;
38 }
39
40 public function needAuth()
41 {
42 return $this->auth > S::i('auth', AUTH_PUBLIC);
43 }
44
45 public function checkPerms()
46 {
47 if (!$this->perms || $this->auth == AUTH_PUBLIC) { // No perms, no check
48 return true;
49 }
50 $s_perms = S::v('perms');
51 return $s_perms->hasFlagCombination($this->perms);
52 }
53
54 public function hasType($type)
55 {
56 return ($this->type & $type) == $type;
57 }
58
59 abstract protected function run(PlPage &$page, array $args);
60
61 public function call(PlPage &$page, array $args)
62 {
63 global $globals, $session, $platal;
64 if ($this->needAuth()) {
65 if ($this->hasType(DO_AUTH)) {
66 if (!$session->start($this->auth)) {
67 $platal->force_login($page);
68 return PL_FORBIDDEN;
69 }
70 } else {
71 return PL_FORBIDDEN;
72 }
73 }
74 if (!$this->checkPerms()) {
75 if (Platal::notAllowed()) {
76 return PL_FORBIDDEN;
77 }
78 }
79 return $this->run($page, $args);
80 }
81 }
82
83 class PlStdHook extends PlHook
84 {
85 private $hook;
86
87 public function __construct($callback, $auth = AUTH_PUBLIC, $perms = 'user', $type = DO_AUTH)
88 {
89 parent::__construct($auth, $perms, $type);
90 $this->hook = $callback;
91 }
92
93 protected function run(PlPage &$page, array $args)
94 {
95 global $session, $platal;
96
97 $args[0] = $page;
98 $val = call_user_func_array($this->hook, $args);
99 if ($val == PL_DO_AUTH) {
100 if (!$session->start($session->loggedLevel())) {
101 $platal->force_login($page);
102 }
103 $val = call_user_func_array($this->hook, $args);
104 }
105 return $val;
106 }
107 }
108
109 class PlWikiHook extends PlHook
110 {
111 public function __construct($auth = AUTH_PUBLIC, $perms = 'user', $type = DO_AUTH)
112 {
113 parent::__construct($auth, $perms, $type);
114 }
115
116 protected function run(PlPage &$page, array $args)
117 {
118 return PL_WIKI;
119 }
120 }
121
122 class PlHookTree
123 {
124 public $hook = null;
125 public $aliased = null;
126 public $children = array();
127
128 public function addChild(array $path, PlHook $hook)
129 {
130 global $platal;
131 $next = array_shift($path);
132 $alias = null;
133 if ($next && $next{0} == '%') {
134 $alias = $next;
135 $next = $platal->hook_map(substr($next, 1));
136 }
137 if (!$next) {
138 return;
139 }
140 @$child =& $this->children[$next];
141 if (!$child) {
142 $child = new PlHookTree();
143 $this->children[$next] =& $child;
144 $child->aliased = $alias;
145 }
146 if (empty($path)) {
147 $child->hook = $hook;
148 } else {
149 $child->addChild($path, $hook);
150 }
151 }
152
153 private function findChildAux(array $remain, array $matched, array $aliased)
154 {
155 $next = @$remain[0];
156 if ($this->aliased) {
157 $aliased = $matched;
158 }
159 if (!empty($next)) {
160 $child = @$this->children[$next];
161 if ($child) {
162 array_shift($remain);
163 $matched[] = $next;
164 return $child->findChildAux($remain, $matched, $aliased);
165 }
166 }
167 return array($this->hook, $matched, $remain, $aliased);
168 }
169
170 public function findChild(array $path)
171 {
172 return $this->findChildAux($path, array(), array());
173 }
174
175 private function findNearestChildAux(array $remain, array $matched, array $aliased)
176 {
177 $next = @$remain[0];
178 if ($this->aliased) {
179 $aliased = $matched;
180 }
181 if (!empty($next)) {
182 $child = @$this->children[$next];
183 if (!$child) {
184 $nearest_lev = 50;
185 $nearest_sdx = 50;
186 $match = null;
187 foreach ($this->children as $path=>$hook) {
188 $lev = levenshtein($next, $path);
189 if ($lev <= $nearest_lev
190 && ($lev < strlen($next) / 2 || strpos($next, $path) !== false
191 || strpos($path, $next) !== false)) {
192 $sdx = levenshtein(soundex($next), soundex($path));
193 if ($lev == $nearest_lev || $sdx < $nearest_sdx) {
194 $child = $hook;
195 $nearest_lev = $lev;
196 $nearest_sdx = $sdx;
197 $match = $path;
198 }
199 }
200 }
201 $next = $match;
202 }
203 if ($child) {
204 array_shift($remain);
205 $matched[] = $next;
206 return $child->findNearestChildAux($remain, $matched, $aliased);
207 }
208 if (($pos = strpos($next, '.php')) !== false) {
209 $remain[0] = substr($next, 0, $pos);
210 return $this->findNearestChildAux($remain, $matched, $aliased);
211 }
212 }
213 return array($this->hook, $matched, $remain, $aliased);
214 }
215
216 public function findNearestChild(array $path)
217 {
218 return $this->findNearestChildAux($path, array(), array());
219 }
220 }
221
222 abstract class Platal
223 {
224 private $mods;
225 private $hooks;
226
227 protected $https;
228
229 public $ns;
230 public $path;
231 public $argv = array();
232
233 static private $_page = null;
234
235 public function __construct()
236 {
237 global $platal, $session, $globals;
238 $platal = $this;
239
240 /* Assign globals first, then call init: init must be used for operations
241 * that requires access to the content of $globals (e.g. XDB requires
242 * $globals to be assigned.
243 */
244 $globals = $this->buildGlobals();
245 $globals->init();
246
247 /* Get the current session: assign first, then activate the session.
248 */
249 $session = $this->buildSession();
250 if (!$session->startAvailableAuth()) {
251 Platal::page()->trigError("Données d'authentification invalides.");
252 }
253
254 $modules = func_get_args();
255 if (isset($modules[0]) && is_array($modules[0])) {
256 $modules = $modules[0];
257 }
258 $this->path = trim(Get::_get('n', null), '/');
259
260 $this->mods = array();
261 $this->hooks = new PlHookTree();
262
263 array_unshift($modules, 'core');
264 foreach ($modules as $module) {
265 $module = strtolower($module);
266 $this->mods[$module] = $m = PLModule::factory($module);
267 $hooks = $m->handlers();
268 foreach ($hooks as $path=>$hook) {
269 $this->hooks->addChild(explode('/', $path), $hook);
270 }
271 }
272
273 if ($globals->mode == '') {
274 pl_redirect('index.html');
275 }
276 }
277
278 public function pl_self($n = null)
279 {
280 if (is_null($n))
281 return $this->path;
282
283 if ($n >= 0)
284 return join('/', array_slice($this->argv, 0, $n + 1));
285
286 if ($n <= -count($this->argv))
287 return $this->argv[0];
288
289 return join('/', array_slice($this->argv, 0, $n));
290 }
291
292 public static function wiki_hook($auth = AUTH_PUBLIC, $perms = 'user', $type = DO_AUTH)
293 {
294 return new PlWikiHook($auth, $perms, $type);
295 }
296
297 public function hook_map($name)
298 {
299 return null;
300 }
301
302 protected function find_hook()
303 {
304 $p = explode('/', $this->path);
305 list($hook, $matched, $remain, $aliased) = $this->hooks->findChild($p);
306 if (empty($hook)) {
307 return null;
308 }
309 $this->argv = $remain;
310 array_unshift($this->argv, implode('/', $matched));
311 if (!empty($aliased)) {
312 $this->ns = implode('/', $aliased) . '/';
313 }
314 $this->https = !$hook->hasType(NO_HTTPS);
315 return $hook;
316 }
317
318 public function near_hook()
319 {
320 $p = explode('/', $this->path);
321 list($hook, $matched, $remain, $aliased) = $this->hooks->findNearestChild($p);
322 if (empty($hook)) {
323 return null;
324 }
325 $url = implode('/', $matched);
326 if (!empty($remain)) {
327 $url .= '/' . implode('/', $remain);
328 }
329 if ($url == $this->path || levenshtein($url, $this->path) > strlen($url) / 3
330 || !$hook->checkPerms()) {
331 return null;
332 }
333 return $url;
334 }
335
336 private function call_hook(PlPage &$page)
337 {
338 $hook = $this->find_hook();
339 if (empty($hook)) {
340 return PL_NOT_FOUND;
341 }
342 global $globals, $session;
343 if ($this->https && !@$_SERVER['HTTPS'] && $globals->core->secure_domain) {
344 http_redirect('https://' . $globals->core->secure_domain . $_SERVER['REQUEST_URI']);
345 }
346
347 return $hook->call($page, $this->argv);
348 }
349
350 /** Show the authentication form.
351 */
352 abstract public function force_login(PlPage& $page);
353
354 public function run()
355 {
356 $page =& self::page();
357
358 if (empty($this->path)) {
359 $this->path = 'index';
360 }
361
362 try {
363 $page->assign('platal', $this);
364 switch ($this->call_hook($page)) {
365 case PL_FORBIDDEN:
366 $this->mods['core']->handler_403($page);
367 break;
368
369 case PL_NOT_FOUND:
370 $this->mods['core']->handler_404($page);
371 break;
372
373 case PL_WIKI:
374 return PL_WIKI;
375 }
376 } catch (Exception $e) {
377 header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');
378 PlErrorReport::report($e);
379 if (self::globals()->debug) {
380 $page->kill(pl_entities($e->getMessage())
381 . '<pre>' . pl_entities("" . $e) . '</pre>');
382 } else {
383 $page->kill(pl_entities($e->getMessage()));
384 }
385 }
386
387 $page->assign('platal', $this);
388 $page->run();
389 }
390
391 public function error403()
392 {
393 $page =& self::page();
394
395 $this->mods['core']->handler_403($page);
396 $page->assign('platal', $this);
397 $page->run();
398 }
399
400 public function error404()
401 {
402 $page =& self::page();
403
404 $this->mods['core']->handler_404($page);
405 $page->assign('platal', $this);
406 $page->run();
407 }
408
409 public static function notAllowed()
410 {
411 if (S::admin()) {
412 self::page()->trigWarning('Tu accèdes à cette page car tu es administrateur du site.');
413 return false;
414 } else {
415 return true;
416 }
417 }
418
419 public static function load($modname, $include = null)
420 {
421 global $platal;
422 $modname = strtolower($modname);
423 if (isset($platal->mods[$modname])) {
424 if (is_null($include)) {
425 return;
426 }
427 $platal->mods[$modname]->load($include);
428 } else {
429 if (is_null($include)) {
430 require_once PLModule::path($modname) . '.php';
431 } else {
432 require_once PLModule::path($modname) . '/' . $include;
433 }
434 }
435 }
436
437 public static function assert($cond, $error, $userfriendly = null)
438 {
439 if ($cond === false) {
440 if ($userfriendly == null) {
441 $userfriendly = "Une erreur interne s'est produite.
442 Merci de réessayer la manipulation qui a déclenché l'erreur ;
443 si cela ne fonctionne toujours pas, merci de nous signaler le problème rencontré.";
444 }
445 throw new PlException($userfriendly, $error);
446 }
447 }
448
449 public function &buildLogger($uid, $suid = 0)
450 {
451 if (defined('PL_LOGGER_CLASS')) {
452 $class = PL_LOGGER_CLASS;
453 $logger = new $class($uid, $suid);
454 return $logger;
455 } else {
456 return PlLogger::dummy($uid, $suid);
457 }
458 }
459
460 protected function &buildPage()
461 {
462 $pageclass = PL_PAGE_CLASS;
463 $page = new $pageclass();
464 return $page;
465 }
466
467 static public function &page()
468 {
469 if (is_null(self::$_page)) {
470 global $platal;
471 self::$_page = $platal->buildPage();
472 }
473 return self::$_page;
474 }
475
476 protected function &buildSession()
477 {
478 $sessionclass = PL_SESSION_CLASS;
479 $session = new $sessionclass();
480 return $session;
481 }
482
483 static public function &session()
484 {
485 global $session;
486 return $session;
487 }
488
489 protected function &buildGlobals()
490 {
491 $globalclass = PL_GLOBALS_CLASS;
492 $globals = new $globalclass();
493 return $globals;
494 }
495
496 static public function &globals()
497 {
498 global $globals;
499 return $globals;
500 }
501 }
502
503 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
504 ?>