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