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