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