ac34abad2e01598f2df08b98b33a378a47551912
[platal.git] / classes / plpage.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2008 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 require_once 'smarty/libs/Smarty.class.php';
23
24 abstract class PlPage extends Smarty
25 {
26 private $_page_type;
27 private $_tpl;
28 private $_errors;
29 private $_failure;
30 private $_jsonVars;
31
32 // {{{ function PlPage()
33
34 public function __construct()
35 {
36 parent::Smarty();
37
38 global $globals;
39
40 $this->caching = false;
41 $this->config_overwrite = false;
42 $this->use_sub_dirs = false;
43 $this->template_dir = $globals->spoolroot."/templates/";
44 $this->compile_dir = $globals->spoolroot."/spool/templates_c/";
45 array_unshift($this->plugins_dir, $globals->spoolroot."/plugins/");
46 $this->config_dir = $globals->spoolroot."/configs/";
47
48 $this->compile_check = !empty($globals->debug);
49
50 $this->_errors = array('errors' => array());
51 $this->_jsonVars = array();
52 $this->_failure = false;
53
54 if ($globals->mode != 'rw') {
55 $this->trigError("En raison d'une maintenance, une partie des fonctionnalités du site sont"
56 . " actuellement désactivée, en particuliers aucune donnée ne sera sauvegardée");
57 }
58 $this->register_prefilter('at_to_globals');
59 $this->addJsLink('xorg.js');
60 $this->addJsLink('jquery.js');
61 }
62
63 // }}}
64 // {{{ function changeTpl()
65
66 public function changeTpl($tpl, $type = SKINNED)
67 {
68 $this->_tpl = $tpl;
69 $this->_page_type = $type;
70 $this->assign('xorg_tpl', $tpl);
71 }
72
73 // }}}
74 // {{{ function raw()
75
76 public function raw()
77 {
78 global $globals;
79 $this->assign('globals', $globals);
80 return $this->fetch($this->_tpl);
81 }
82
83 // }}}
84 // {{{ function _run()
85
86 protected function _run($skin)
87 {
88 global $globals, $TIME_BEGIN;
89
90 session_write_close();
91
92 $this->register_prefilter('trimwhitespace');
93 $this->register_prefilter('form_force_encodings');
94 $this->register_prefilter('wiki_include');
95 $this->register_prefilter('if_has_perms');
96 $this->assign('xorg_triggers', $this->_errors);
97 $this->assign('xorg_errors', $this->nb_errs());
98 $this->assign('xorg_failure', $this->_failure);
99 $this->assign_by_ref('globals', $globals);
100
101 if (Env::has('json') && count($this->_jsonVars)) {
102 return $this->jsonDisplay();
103 }
104
105 if (Env::v('display') == 'light') {
106 $this->_page_type = SIMPLE;
107 } elseif (Env::v('display') == 'raw') {
108 $this->_page_type = NO_SKIN;
109 } elseif (Env::v('display') == 'full') {
110 $this->_page_typ = SKINNED;
111 }
112
113 switch ($this->_page_type) {
114 case NO_SKIN:
115 if (!($globals->debug & DEBUG_SMARTY)) {
116 error_reporting(0);
117 }
118 $this->display($this->_tpl);
119 exit;
120
121 case SIMPLE:
122 $this->assign('simple', true);
123
124 case SKINNED:
125 $this->register_modifier('escape_html', 'escape_html');
126 $this->default_modifiers = Array('@escape_html');
127 }
128 if (S::i('auth') <= AUTH_PUBLIC) {
129 $this->register_outputfilter('hide_emails');
130 }
131 $this->addJsLink('wiki.js');
132 header("Accept-Charset: utf-8");
133 if (Env::v('forceXml')) {
134 header("Content-Type: text/xml; charset=utf-8");
135 }
136
137 if (!$globals->debug) {
138 error_reporting(0);
139 $this->display($skin);
140 exit;
141 }
142
143 $this->assign('validate', true);
144 if (!($globals->debug & DEBUG_SMARTY)) {
145 error_reporting(0);
146 }
147 $START_SMARTY = microtime(true);
148 $result = $this->fetch($skin);
149 $ttime = sprintf('Temps total: %.02fs (Smarty %.02fs) - Mémoire totale : %dKo<br />',
150 microtime(true) - $TIME_BEGIN, microtime(true) - $START_SMARTY,
151 memory_get_peak_usage(true) / 1024);
152 if ($globals->debug & DEBUG_BT) {
153 PlBacktrace::clean();
154 $this->assign_by_ref('backtraces', PlBacktrace::$bt);
155 $result = str_replace('@@BACKTRACE@@', $this->fetch('skin/common.backtrace.tpl'), $result);
156 } else {
157 $result = str_replace('@@BACKTRACE@@', '', $result);
158 }
159
160 $replc = "<span class='erreur'>VALIDATION HTML INACTIVE</span><br />";
161 if ($globals->debug & DEBUG_VALID) {
162 $fd = fopen($this->compile_dir."/valid.html","w");
163 fwrite($fd, $result);
164 fclose($fd);
165
166 exec($globals->spoolroot."/bin/devel/xhtml.validate.pl ".$this->compile_dir."/valid.html", $val);
167 foreach ($val as $h) {
168 if (preg_match("/^X-W3C-Validator-Errors: (\d+)$/", $h, $m)) {
169 $replc = '<span style="color: #080;">HTML OK</span><br />';
170 if ($m[1]) {
171 $replc = "<span class='erreur'><a href='http://validator.w3.org/check?uri={$globals->baseurl}"
172 ."/valid.html&amp;ss=1#result'>{$m[1]} ERREUR(S) !!!</a></span><br />";
173 }
174 break;
175 }
176 }
177 }
178
179 echo str_replace("@HOOK@", $ttime.$replc, $result);
180 exit;
181 }
182
183 abstract public function run();
184
185 // }}}
186 // {{{ function nb_errs()
187
188 public function nb_errs()
189 {
190 return count($this->_errors['errors']);
191 }
192
193 // }}}
194 // {{{ function trig()
195
196 private function trig($msg, $type = 'errors')
197 {
198 if (!isset($this->_errors[$type])) {
199 $this->_errors[$type] = array();
200 }
201 $this->_errors[$type][] = $msg;
202 }
203
204 public function trigError($msg)
205 {
206 $this->trig($msg, 'errors');
207 }
208
209 public function trigWarning($msg)
210 {
211 $this->trig($msg, 'warnings');
212 }
213
214 public function trigSuccess($msg)
215 {
216 $this->trig($msg, 'success');
217 }
218
219 // }}}
220 // {{{ function kill()
221
222 public function kill($msg)
223 {
224 global $platal;
225
226 $this->assign('platal', $platal);
227 $this->trigError($msg);
228 $this->_failure = true;
229 $this->run();
230 }
231
232 // }}}
233 // {{{ function addJsLink
234
235 public function addJsLink($path)
236 {
237 $this->append('xorg_js', $path);
238 }
239
240 // }}}
241 // {{{ function addCssLink
242
243 public function addCssLink($path)
244 {
245 $this->append('xorg_css', $path);
246 }
247
248 // }}}
249 // {{{ function addCssInline
250
251 public function addCssInline($css)
252 {
253 if (!empty($css)) {
254 $this->append('xorg_inline_css', $css);
255 }
256 }
257
258 // }}}
259 // {{{ function setRssLink
260
261 public function setRssLink($title, $path)
262 {
263 $this->assign('xorg_rss', array('title' => $title, 'href' => $path));
264 }
265
266 // }}}
267 // {{{ function jsonDisplay
268 protected function jsonDisplay()
269 {
270 header("Content-type: text/javascript; charset=utf-8");
271 array_walk_recursive($this->_jsonVars, "escape_xorgDB");
272 $jsonbegin = Env::v('jsonBegin');
273 $jsonend = Env::v('jsonEnd');
274 if (Env::has('jsonVar')) {
275 $jsonbegin = Env::v('jsonVar').' = ';
276 $jsonend = ';';
277 } elseif (Env::has('jsonFunc')) {
278 $jsonbegin = Env::v('jsonFunc').'(';
279 $jsonend = ');';
280 }
281 echo $jsonbegin, json_encode($this->_jsonVars), $jsonend;
282 exit;
283 }
284 // }}}
285 // {{{ function jsonAssign
286 public function jsonAssign($var, $value)
287 {
288 $this->_jsonVars[$var] = $value;
289 }
290
291 // }}}
292 }
293
294 function escape_xorgDB(&$item, $key)
295 {
296 if (is_a($item, 'XOrgDBIterator')) {
297 $expanded = array();
298 while ($a = $item->next()) {
299 $expanded[] = $a;
300 }
301 $item = $expanded;
302 }
303 }
304
305 // {{{ function escape_html ()
306
307 /**
308 * default smarty plugin, used to auto-escape dangerous html.
309 *
310 * < --> &lt;
311 * > --> &gt;
312 * " --> &quot;
313 * & not followed by some entity --> &amp;
314 */
315 function escape_html($string)
316 {
317 if (is_string($string)) {
318 return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
319 } else {
320 return $string;
321 }
322 }
323
324 // }}}
325 // {{{ function at_to_globals()
326
327 /**
328 * helper
329 */
330
331 function _to_globals($s) {
332 global $globals;
333 $t = explode('.',$s);
334 if (count($t) == 1) {
335 return var_export($globals->$t[0],true);
336 } else {
337 return var_export($globals->$t[0]->$t[1],true);
338 }
339 }
340
341 /**
342 * compilation plugin used to import $globals confing through #globals.foo.bar# directives
343 */
344
345 function at_to_globals($tpl_source, &$smarty)
346 {
347 return preg_replace('/#globals\.([a-zA-Z0-9_.]+?)#/e', '_to_globals(\'\\1\')', $tpl_source);
348 }
349
350 // }}}
351 // {{{ function trimwhitespace
352
353 function trimwhitespace($source, &$smarty)
354 {
355 $tags = '(script|pre|textarea)';
356 preg_match_all("!<$tags.*?>.*?</(\\1)>!ius", $source, $tagsmatches);
357 $source = preg_replace("!<$tags.*?>.*?</(\\1)>!ius", "&&&tags&&&", $source);
358
359 // remove all leading spaces, tabs and carriage returns NOT
360 // preceeded by a php close tag.
361 $source = preg_replace('/((?<!\?>)\n)[\s]+/m', '\1', $source);
362 $source = preg_replace("!&&&tags&&&!e", 'array_shift($tagsmatches[0])', $source);
363
364 return $source;
365 }
366
367 // }}}
368 // {{{ function wiki_include
369
370 function wiki_include($source, &$smarty)
371 {
372 return preg_replace('/\{include( [^}]*)? wiki=([^} ]+)(.*?)\}/ui',
373 '{include\1 file="../spool/wiki.d/cache_\2.tpl"\3 included=1}',
374 $source);
375 }
376
377 // }}}
378 //{{{ function hasPerm
379
380 function if_has_perms($source, &$smarty)
381 {
382 $source = preg_replace('/\{if([^}]*) (\!?)hasPerms\(([^)]+)\)([^}]*)\}/',
383 '{if\1 \2$smarty.session.perms->hasFlagCombination(\3)\4}',
384 $source);
385 return preg_replace('/\{if([^}]*) (\!?)hasPerm\(([^)]+)\)([^}]*)\}/',
386 '{if\1 \2($smarty.session.perms && $smarty.session.perms->hasFlag(\3))\4}',
387 $source);
388 }
389
390 // }}}
391 // {{{
392
393 function form_force_encodings($source, &$smarty)
394 {
395 return preg_replace('/<form[^\w]/',
396 '\0 accept-charset="utf-8" ',
397 $source);
398 }
399
400 // }}}
401 // {{{ function hide_emails
402
403 function _hide_email($source)
404 {
405 $source = str_replace("\n", '', $source);
406 return '<script type="text/javascript">//<![CDATA[' . "\n" .
407 'Nix.decode("' . addslashes(str_rot13($source)) . '");' . "\n" .
408 '//]]></script>';
409 }
410
411 function hide_emails($source, &$smarty)
412 {
413 if (!strpos($source, '@')) {
414 return $source;
415 }
416
417 //prevent email replacement in <script> and <textarea>
418 $tags = '(script|textarea|select)';
419 preg_match_all("!<$tags.*?>.*?</(\\1)>!ius", $source, $tagsmatches);
420 $source = preg_replace("!<$tags.*?>.*?</(\\1)>!ius", "&&&tags&&&", $source);
421
422 //catch all emails in <a href="mailto:...">
423 preg_match_all("!<a[^>]+href=[\"'][^\"']*[-a-z0-9+_.]+@[-a-z0-9_.]+[^\"']*[\"'].*?>.*?</a>!ius", $source, $ahref);
424 $source = preg_replace("!<a[^>]+href=[\"'][^\"']*[-a-z0-9+_.]+@[-a-z0-9_.]+[^\"']*[\"'].*?>.*?</a>!ius", '&&&ahref&&&', $source);
425
426 //prevant replacement in tag attributes
427 preg_match_all("!<[^>]+[-a-z0-9_+.]+@[-a-z0-9_.]+.+?>!ius", $source, $misc);
428 $source = preg_replace("!<[^>]+[-a-z0-9_+.]+@[-a-z0-9_.]+.+?>!ius", '&&&misc&&&', $source);
429
430 //catch !
431 $source = preg_replace('!([-a-z0-9_+.]+@[-a-z0-9_.]+)!iue', '_hide_email("\1")', $source);
432 $source = preg_replace('!&&&ahref&&&!e', '_hide_email(array_shift($ahref[0]))', $source);
433
434 // restore data
435 $source = preg_replace('!&&&misc&&&!e', 'array_shift($misc[0])', $source);
436 $source = preg_replace("!&&&tags&&&!e", 'array_shift($tagsmatches[0])', $source);
437
438 return $source;
439 }
440
441 // }}}
442
443 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
444 ?>