Add smarty prefilter to allow access to const field of classes (Closes #1204).
[platal.git] / classes / plpage.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2011 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 if (!@include_once 'smarty/libs/Smarty.class.php') {
23 require_once 'smarty/Smarty.class.php';
24 }
25
26 abstract class PlPage extends Smarty
27 {
28 private $_page_type;
29 private $_tpl;
30 private $_errors;
31 private $_failure;
32 private $_jsonVars;
33
34 // {{{ function PlPage()
35
36 public function __construct()
37 {
38 parent::Smarty();
39
40 global $globals;
41
42 $this->caching = false;
43 $this->config_overwrite = false;
44 $this->use_sub_dirs = false;
45 $this->template_dir = $globals->spoolroot . '/templates/';
46 $this->compile_dir = $globals->spoolroot . '/spool/templates_c/';
47 array_unshift($this->plugins_dir,
48 $globals->spoolroot . '/core/plugins/',
49 $globals->spoolroot . '/plugins/');
50 $this->config_dir = $globals->spoolroot . '/configs/';
51
52 $this->compile_check = !empty($globals->debug) || $globals->smarty_autocompile;
53
54 $this->_errors = array('errors' => array());
55 $this->_jsonVars = array();
56 $this->_failure = false;
57
58 if ($globals->mode != 'rw') {
59 $this->trigError("En raison d'une maintenance, une partie des fonctionnalités du site est"
60 . " actuellement désactivée, en particulier aucune donnée ne sera sauvegardée");
61 }
62 $this->register_prefilter('at_to_globals');
63 $this->register_prefilter('get_class_constants');
64 }
65
66 // }}}
67 // {{{ function changeTpl()
68
69 public function changeTpl($tpl, $type = SKINNED)
70 {
71 $this->_tpl = $tpl;
72 $this->_page_type = $type;
73 $this->assign('pl_tpl', $tpl);
74 }
75
76 // }}}
77 // {{{ function getCoreTpl()
78
79 public static function getCoreTpl($tpl)
80 {
81 global $globals;
82 return $globals->spoolroot . '/core/templates/' . $tpl;
83 }
84
85 // }}}
86 // {{{ function coreTpl()
87
88 /** Use a template from the core.
89 */
90 public function coreTpl($tpl, $type = SKINNED)
91 {
92 global $globals;
93 $this->changeTpl(self::getCoreTpl($tpl), $type);
94 }
95
96 // }}}
97 // {{{ function raw()
98
99 public function raw()
100 {
101 global $globals;
102 $this->assign('globals', $globals);
103 return $this->fetch($this->_tpl);
104 }
105
106 // }}}
107 // {{{ function _run()
108
109 protected function _run($skin)
110 {
111 global $globals, $platal, $TIME_BEGIN;
112
113 Platal::session()->close();
114
115 $this->register_prefilter('trimwhitespace');
116 $this->register_prefilter('form_force_encodings');
117 $this->register_prefilter('wiki_include');
118 $this->register_prefilter('core_include');
119 $this->register_prefilter('if_rewrites');
120 $this->assign('pl_triggers', $this->_errors);
121 $this->assign('pl_errors', $this->nb_errs());
122 $this->assign('pl_failure', $this->_failure);
123 $this->assign_by_ref('platal', $platal);
124 $this->assign_by_ref('globals', $globals);
125
126 if (Env::has('json') && count($this->_jsonVars)) {
127 return $this->jsonDisplay();
128 }
129
130 $display = Env::s('display');
131 if ($display == 'light' && $this->_page_type == SKINNED) {
132 $this->_page_type = SIMPLE;
133 } elseif ($display == 'raw') {
134 $this->_page_type = NO_SKIN;
135 } elseif ($display == 'full') {
136 $this->_page_type = SKINNED;
137 }
138
139 if ($this->_page_type == SIMPLE) {
140 $this->assign('simple', true);
141 } else {
142 $this->assign('simple', false);
143 }
144
145 switch ($this->_page_type) {
146 case NO_SKIN:
147 if (!($globals->debug & DEBUG_SMARTY)) {
148 error_reporting(0);
149 }
150 $this->display($this->_tpl);
151 exit;
152
153 case SIMPLE:
154 case SKINNED:
155 $this->register_modifier('escape_html', 'escape_html');
156 $this->default_modifiers = Array('@escape_html');
157 }
158 if (S::i('auth') <= AUTH_PUBLIC) {
159 $this->register_outputfilter('hide_emails');
160 }
161 header("Accept-Charset: utf-8");
162 if (Env::v('forceXml')) {
163 pl_content_headers("text/xml");
164 }
165
166 if (!$globals->debug) {
167 error_reporting(0);
168 $this->display($skin);
169 pl_print_errors(true);
170 exit;
171 }
172
173 $this->assign('validate', true);
174 if (!($globals->debug & DEBUG_SMARTY)) {
175 error_reporting(0);
176 }
177 $START_SMARTY = microtime(true);
178 $result = $this->fetch($skin);
179 $ttime = sprintf('Temps total: %.02fs (Smarty %.02fs) - Mémoire totale : %dKo<br />',
180 microtime(true) - $TIME_BEGIN, microtime(true) - $START_SMARTY,
181 memory_get_peak_usage(true) / 1024);
182 if ($globals->debug & DEBUG_BT) {
183 PlBacktrace::clean();
184 $this->assign_by_ref('backtraces', PlBacktrace::$bt);
185 $result = str_replace('@@BACKTRACE@@',
186 $this->fetch(self::getCoreTpl('backtrace.tpl')),
187 $result);
188 } else {
189 $result = str_replace('@@BACKTRACE@@', '', $result);
190 }
191
192 $replc = "<span class='erreur'>VALIDATION HTML INACTIVE</span><br />";
193 if ($globals->debug & DEBUG_VALID) {
194 global $platal;
195 $fd = fopen($this->compile_dir."/valid.html","w");
196 fwrite($fd, $result);
197 fclose($fd);
198
199 $replc = '<span id="html_valid"><span style="color: #860">VALIDATION HTML EN COURS</span></span>'
200 . '<script type="text/javascript">$("#html_valid").updateHtml("validator");</script>'
201 . '<br />';
202 }
203
204 echo str_replace("@HOOK@", $ttime.$replc, $result);
205 exit;
206 }
207
208 abstract public function run();
209
210 // }}}
211 // {{{ function nb_errs()
212
213 public function nb_errs()
214 {
215 return count($this->_errors['errors']);
216 }
217
218 // }}}
219 // {{{ function trig()
220
221 private function trig($msg, $type = 'errors')
222 {
223 if (!isset($this->_errors[$type])) {
224 $this->_errors[$type] = array();
225 }
226 $this->_errors[$type][] = $msg;
227 }
228
229 public function trigError($msg)
230 {
231 $this->trig($msg, 'errors');
232 }
233
234 public function trigWarning($msg)
235 {
236 $this->trig($msg, 'warnings');
237 }
238
239 public function trigSuccess($msg)
240 {
241 $this->trig($msg, 'success');
242 }
243
244 // }}}
245 // {{{ function trigRedirect
246
247 // Acts as trig(), but replaces the template with a simple one displaying
248 // the error messages and a "continue" link.
249 private function trigRedirect($msg, $continue, $type = 'errors')
250 {
251 $this->trig($msg, $type);
252 $this->coreTpl('msgredirect.tpl');
253 $this->assign('continue', $continue);
254 $this->run();
255 }
256
257 public function trigErrorRedirect($msg, $continue)
258 {
259 $this->trigRedirect($msg, $continue, 'errors');
260 }
261
262 public function trigWarningRedirect($msg, $continue)
263 {
264 $this->trigRedirect($msg, $continue, 'warnings');
265 }
266
267 public function trigSuccessRedirect($msg, $continue)
268 {
269 $this->trigRedirect($msg, $continue, 'success');
270 }
271
272 // }}}
273 // {{{ function kill()
274
275 public function kill($msg, $type = 'errors')
276 {
277 // PHP is used on command line... do not run the whole page stuff.
278 if (php_sapi_name() == 'cli') {
279 echo $msg . "\n";
280 exit(-1);
281 }
282
283 global $platal;
284
285 $this->trig($msg, $type);
286 $this->_failure = true;
287 $this->run();
288 }
289
290 public function killError($msg)
291 {
292 $this->kill($msg, 'errors');
293 }
294
295 public function killWarning($msg)
296 {
297 $this->kill($msg, 'warnings');
298 }
299
300 public function killSuccess($msg)
301 {
302 $this->kill($msg, 'success');
303 }
304
305 // }}}
306 // {{{ function setTitle
307
308 public function setTitle($title)
309 {
310 global $globals;
311 if (isset($globals->core->sitename)) {
312 $title = $globals->core->sitename . ' :: ' . $title;
313 }
314 $this->assign('pl_title', $title);
315 }
316
317 // }}}
318 // {{{ function addJsLink
319
320 public function addJsLink($filename, $static_content = true)
321 {
322 if ($static_content) {
323 $this->append('pl_js', pl_static_content_path("javascript/", $filename));
324 } else {
325 $this->append('pl_js', "javascript/$filename");
326 }
327 }
328
329 // }}}
330 // {{{ function addCssLink
331
332 public function addCssLink($path)
333 {
334 $this->append('pl_css', $path);
335 }
336
337 // }}}
338 // {{{ function addLink
339
340 public function addLink($rel, $path)
341 {
342 $this->append('pl_link', array('rel' => $rel, 'href' => $path));
343 }
344
345
346 // }}}
347 // {{{ function addCssInline
348
349 public function addCssInline($css)
350 {
351 if (!empty($css)) {
352 $this->append('pl_inline_css', $css);
353 }
354 }
355
356 // }}}
357 // {{{ function setRssLink
358
359 public function setRssLink($title, $path)
360 {
361 $this->assign('pl_rss', array('title' => $title, 'href' => $path));
362 }
363
364 // }}}
365 // {{{ function jsonDisplay
366 protected function jsonDisplay()
367 {
368 pl_content_headers("text/javascript");
369 if (!empty(PlBacktrace::$bt)) {
370 $this->jsonAssign('pl_backtraces', PlBacktrace::$bt);
371 }
372 array_walk_recursive($this->_jsonVars, "escape_XDB");
373 $jsonbegin = Env::v('jsonBegin');
374 $jsonend = Env::v('jsonEnd');
375 if (Env::has('jsonVar')) {
376 $jsonbegin = Env::v('jsonVar').' = ';
377 $jsonend = ';';
378 } elseif (Env::has('jsonFunc')) {
379 $jsonbegin = Env::v('jsonFunc').'(';
380 $jsonend = ');';
381 }
382 echo $jsonbegin, json_encode($this->_jsonVars), $jsonend;
383 exit;
384 }
385 // }}}
386
387 public function runJSon()
388 {
389 pl_content_headers("text/javascript");
390 if (!empty(PlBacktrace::$bt)) {
391 $this->jsonAssign('pl_backtraces', PlBacktrace::$bt);
392 }
393 echo json_encode($this->_jsonVars);
394 exit;
395 }
396
397 // {{{ function jsonAssign
398 public function jsonAssign($var, $value)
399 {
400 $this->_jsonVars[$var] = $value;
401 }
402
403 // }}}
404 }
405
406 function escape_XDB(&$item, $key)
407 {
408 if ($item instanceof XDBIterator) {
409 $expanded = array();
410 while ($a = $item->next()) {
411 $expanded[] = $a;
412 }
413 $item = $expanded;
414 }
415 }
416
417 // {{{ function escape_html ()
418
419 /**
420 * default smarty plugin, used to auto-escape dangerous html.
421 *
422 * < --> &lt;
423 * > --> &gt;
424 * " --> &quot;
425 * & not followed by some entity --> &amp;
426 */
427 function escape_html($string)
428 {
429 if (is_string($string)) {
430 return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
431 } else {
432 return $string;
433 }
434 }
435
436 // }}}
437 // {{{ function at_to_globals()
438
439 /**
440 * helper
441 */
442
443 function _to_globals($s) {
444 global $globals;
445 $t = explode('.',$s);
446 if (count($t) == 1) {
447 return var_export($globals->$t[0],true);
448 } else {
449 return var_export($globals->$t[0]->$t[1],true);
450 }
451 }
452
453 /**
454 * compilation plugin used to import $globals confing through #globals.foo.bar# directives
455 */
456
457 function at_to_globals($tpl_source, $smarty)
458 {
459 return preg_replace('/#globals\.([a-zA-Z0-9_.]+?)#/e', '_to_globals(\'\\1\')', $tpl_source);
460 }
461
462 // }}}
463 // {{{ function get_class_constants()
464
465 /**
466 * helper
467 */
468
469 function _get_class_const($class, $const)
470 {
471 return var_export(constant($class . '::' . $const), true);
472 }
473
474 /**
475 * Compilation plugin used to import class constants through calls to #Class::CONSTANT#
476 */
477
478 function get_class_constants($tpl_source, $smarty)
479 {
480 return preg_replace('/#([a-zA-Z0-9_]+)::([A-Z0-9_]+)#/e', '_get_class_const(\'\\1\',\'\\2\')', $tpl_source);
481 }
482
483 // }}}
484 // {{{ function trimwhitespace
485
486 function trimwhitespace($source, $smarty)
487 {
488 $tags = '(script|pre|textarea)';
489 preg_match_all("!<$tags.*?>.*?</(\\1)>!ius", $source, $tagsmatches);
490 $source = preg_replace("!<$tags.*?>.*?</(\\1)>!ius", "&&&tags&&&", $source);
491
492 // remove all leading spaces, tabs and carriage returns NOT
493 // preceeded by a php close tag.
494 $source = preg_replace('/((?<!\?>)\n)[\s]+/m', '\1', $source);
495 $source = preg_replace("!&&&tags&&&!e", 'array_shift($tagsmatches[0])', $source);
496
497 return $source;
498 }
499
500 // }}}
501 // {{{ function wiki_include
502
503 function wiki_include($source, $smarty)
504 {
505 global $globals;
506 return preg_replace('/\{include( [^}]*)? wiki=([^} ]+)(.*?)\}/ui',
507 '{include\1 file="' . $globals->spoolroot . '/spool/wiki.d/cache_\2.tpl"\3 included=1}',
508 $source);
509 }
510
511 function core_include($source, $smarty)
512 {
513 global $globals;
514 return preg_replace('/\{include( [^}]*)? core=([^} ]+)(.*?)\}/ui',
515 '{include\1 file="' . $globals->spoolroot . '/core/templates/\2"\3}',
516 $source);
517 }
518
519 // }}}
520 //{{{ function hasPerm
521
522 function if_rewrites($source, $smarty)
523 {
524 $perms = 'isset($smarty.session.user|smarty:nodefaults) && $smarty.session.user';
525 return preg_replace(array('/\{(else)?if([^}]*) (\!?)hasPerms?\(([^)]+)\)([^}]*)\}/',
526 '/\{(else)?if([^}]*) (\!?)t\(([^)]+)\)([^}]*)\}/'),
527 array('{\1if\2 \3(' . $perms . '->checkPerms(\4))\5}',
528 '{\1if\2 \3(isset(\4|smarty:nodefaults) && (\4|smarty:nodefaults))\5}'),
529 $source);
530 }
531
532 // }}}
533 // {{{
534
535 function form_force_encodings($source, $smarty)
536 {
537 return preg_replace('/<form[^\w]/',
538 '\0 accept-charset="utf-8" ',
539 $source);
540 }
541
542 // }}}
543 // {{{ function hide_emails
544
545 function _hide_email($source)
546 {
547 $source = str_replace("\n", '', $source);
548 return '<script type="text/javascript">//<![CDATA[' . "\n" .
549 'Nix.decode("' . addslashes(str_rot13($source)) . '");' . "\n" .
550 '//]]></script>';
551 }
552
553 function hide_emails($source, $smarty)
554 {
555 if (!strpos($source, '@')) {
556 return $source;
557 }
558
559 //prevent email replacement in <script> and <textarea>
560 $tags = '(script|textarea|select)';
561 preg_match_all("!<$tags.*?>.*?</(\\1)>!ius", $source, $tagsmatches);
562 $source = preg_replace("!<$tags.*?>.*?</(\\1)>!ius", "&&&tags&&&", $source);
563
564 //catch all emails in <a href="mailto:...">
565 preg_match_all("!<a[^>]+href=[\"'][^\"']*[-a-z0-9+_.]+@[-a-z0-9_.]+[^\"']*[\"'].*?>.*?</a>!ius", $source, $ahref);
566 $source = preg_replace("!<a[^>]+href=[\"'][^\"']*[-a-z0-9+_.]+@[-a-z0-9_.]+[^\"']*[\"'].*?>.*?</a>!ius", '&&&ahref&&&', $source);
567
568 //prevant replacement in tag attributes
569 preg_match_all("!<[^>]+[-a-z0-9_+.]+@[-a-z0-9_.]+.+?>!ius", $source, $misc);
570 $source = preg_replace("!<[^>]+[-a-z0-9_+.]+@[-a-z0-9_.]+.+?>!ius", '&&&misc&&&', $source);
571
572 //catch !
573 $source = preg_replace('!([-a-z0-9_+.]+@[-a-z0-9_.]+)!iue', '_hide_email("\1")', $source);
574 $source = preg_replace('!&&&ahref&&&!e', '_hide_email(array_shift($ahref[0]))', $source);
575
576 // restore data
577 $source = preg_replace('!&&&misc&&&!e', 'array_shift($misc[0])', $source);
578 $source = preg_replace("!&&&tags&&&!e", 'array_shift($tagsmatches[0])', $source);
579
580 return $source;
581 }
582
583 // }}}
584
585 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
586 ?>