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