source: trunk/include/template.class.php @ 5123

Last change on this file since 5123 was 5123, checked in by plg, 14 years ago

feature 1502: based on Dotclear model, P@t has reorganized the way Piwigo
manages template/theme in a simpler "theme only level" architecture. It
supports multiple level inheritance.

File size: 17.0 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based picture gallery                                  |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008-2009 Piwigo Team                  http://piwigo.org |
6// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
7// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
8// +-----------------------------------------------------------------------+
9// | This program is free software; you can redistribute it and/or modify  |
10// | it under the terms of the GNU General Public License as published by  |
11// | the Free Software Foundation                                          |
12// |                                                                       |
13// | This program is distributed in the hope that it will be useful, but   |
14// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
15// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
16// | General Public License for more details.                              |
17// |                                                                       |
18// | You should have received a copy of the GNU General Public License     |
19// | along with this program; if not, write to the Free Software           |
20// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
21// | USA.                                                                  |
22// +-----------------------------------------------------------------------+
23
24
25require_once(PHPWG_ROOT_PATH.'include/smarty/libs/Smarty.class.php');
26
27// migrate lang:XXX
28//    sed "s/{lang:\([^}]\+\)}/{\'\1\'|@translate}/g" my_template.tpl
29// migrate change root level vars {XXX}
30//    sed "s/{pwg_root}/{ROOT_URL}/g" my_template.tpl
31// migrate change root level vars {XXX}
32//    sed "s/{\([a-zA-Z_]\+\)}/{$\1}/g" my_template.tpl
33// migrate all
34//    cat my_template.tpl | sed "s/{lang:\([^}]\+\)}/{\'\1\'|@translate}/g" | sed "s/{pwg_root}/{ROOT_URL}/g" | sed "s/{\([a-zA-Z_]\+\)}/{$\1}/g"
35
36
37class Template {
38
39  var $smarty;
40
41  var $output = '';
42
43  // Hash of filenames for each template handle.
44  var $files = array();
45
46  // Template extents filenames for each template handle.
47  var $extents = array();
48
49  // Templates prefilter from external sources (plugins)
50  var $external_filters = array();
51 
52  // used by html_head smarty block to add content before </head>
53  var $html_head_elements = array();
54
55  function Template($root = ".", $theme= "", $path = "template")
56  {
57    global $conf, $lang_info;
58
59    $this->smarty = new Smarty;
60    $this->smarty->debugging = $conf['debug_template'];
61    $this->smarty->compile_check=$conf['template_compile_check'];
62
63    $compile_dir = $conf['local_data_dir'].'/templates_c';
64    mkgetdir( $compile_dir );
65
66    $this->smarty->compile_dir = $compile_dir;
67
68    $this->smarty->assign_by_ref( 'pwg', new PwgTemplateAdapter() );
69    $this->smarty->register_modifier( 'translate', array('Template', 'mod_translate') );
70    $this->smarty->register_modifier( 'explode', array('Template', 'mod_explode') );
71    $this->smarty->register_modifier( 'get_extent', array(&$this, 'get_extent') );
72    $this->smarty->register_block('html_head', array(&$this, 'block_html_head') );
73    $this->smarty->register_function('known_script', array(&$this, 'func_known_script') );
74    $this->smarty->register_prefilter( array('Template', 'prefilter_white_space') );
75    if ( $conf['compiled_template_cache_language'] )
76    {
77      $this->smarty->register_prefilter( array('Template', 'prefilter_language') );
78    }
79
80    $this->smarty->template_dir = array();
81    if ( !empty($theme) )
82    {
83      $this->set_theme($root, $theme, $path);
84    }
85
86    $this->smarty->assign('lang_info', $lang_info);
87
88    if (!defined('IN_ADMIN') and isset($conf['extents_for_templates']))
89    {
90      $tpl_extents = unserialize($conf['extents_for_templates']);
91      $this->set_extents($tpl_extents, './template-extension/', true);
92    }
93  }
94
95  /**
96   * Load theme's parameters.
97   */
98  function set_theme($root, $theme, $path)
99  {
100    $this->set_template_dir($root.'/'.$theme.'/'.$path);
101
102    include($root.'/'.$theme.'/themeconf.inc.php');
103
104    if (isset($themeconf['parent']))
105    {
106      $this->set_theme($root, $themeconf['parent'], $path);
107    }
108
109    $tpl_var = array('name' => $themeconf['theme']);
110    if (file_exists($root.'/'.$theme.'/local_head.tpl'))
111    {
112      $tpl_var['local_head'] = realpath($root.'/'.$theme.'/local_head.tpl');
113    }
114    $this->smarty->append('themes', $tpl_var);
115    $this->smarty->append('themeconf', $themeconf, true);
116  }
117
118  function set_template_dir($dir)
119  {
120    $this->smarty->template_dir[] = $dir;
121
122    if (!isset($this->smarty->compile_id))
123    {
124      $real_dir = realpath($dir);
125      $compile_id = crc32( $real_dir===false ? $dir : $real_dir);
126      $this->smarty->compile_id = base_convert($compile_id, 10, 36 );
127    }
128  }
129
130  /**
131   * Gets the template root directory for this Template object.
132   */
133  function get_template_dir()
134  {
135    return $this->smarty->template_dir;
136  }
137
138  /**
139   * Deletes all compiled templates.
140   */
141  function delete_compiled_templates()
142  {
143      $save_compile_id = $this->smarty->compile_id;
144      $this->smarty->compile_id = null;
145      $this->smarty->clear_compiled_tpl();
146      $this->smarty->compile_id = $save_compile_id;
147      file_put_contents($this->smarty->compile_dir.'/index.htm', 'Not allowed!');
148  }
149
150  function get_themeconf($val)
151  {
152    $tc = $this->smarty->get_template_vars('themeconf');
153    return isset($tc[$val]) ? $tc[$val] : '';
154  }
155
156  /**
157   * Sets the template filename for handle.
158   */
159  function set_filename($handle, $filename)
160  {
161    return $this->set_filenames( array($handle=>$filename) );
162  }
163
164  /**
165   * Sets the template filenames for handles. $filename_array should be a
166   * hash of handle => filename pairs.
167   */
168  function set_filenames($filename_array)
169  {
170    if (!is_array($filename_array))
171    {
172      return false;
173    }
174    reset($filename_array);
175    while(list($handle, $filename) = each($filename_array))
176    {
177      if (is_null($filename))
178      {
179        unset($this->files[$handle]);
180      }
181      else
182      {
183        $this->files[$handle] = $this->get_extent($filename, $handle);
184      }
185    }
186    return true;
187  }
188
189  /**
190   * Sets template extention filename for handles.
191   */
192  function set_extent($filename, $param, $dir='', $overwrite=true)
193  {
194    return $this->set_extents(array($filename => $param), $dir, $overwrite);
195  }
196
197  /**
198   * Sets template extentions filenames for handles.
199   * $filename_array should be an hash of filename => array( handle, param) or filename => handle
200   */
201  function set_extents($filename_array, $dir='', $overwrite=true)
202  {
203    global $user;
204
205    if (!is_array($filename_array))
206    {
207      return false;
208    }
209    foreach ($filename_array as $filename => $value)
210    {
211      if (is_array($value))
212      {
213        $handle = $value[0];
214        $param = $value[1];
215        $tpl = $value[2];
216      }
217      elseif (is_string($value))
218      {
219        $handle = $value;
220        $param = 'N/A';
221        $tpl = 'N/A';
222      }
223      else
224      {
225        return false;
226      }
227
228      if ((stripos(implode('',array_keys($_GET)), '/'.$param) !== false or $param == 'N/A')
229        and ($tpl == $user['theme'] or $tpl == 'N/A')
230        and (!isset($this->extents[$handle]) or $overwrite)
231        and file_exists($dir . $filename))
232      {
233        $this->extents[$handle] = realpath($dir . $filename);
234      }
235    }
236    return true;
237  }
238
239  /** return template extension if exists  */
240  function get_extent($filename='', $handle='')
241  {
242    if (isset($this->extents[$handle]))
243    {
244      $filename = $this->extents[$handle];
245    }
246    return $filename;
247  }
248
249  /** see smarty assign http://www.smarty.net/manual/en/api.assign.php */
250  function assign($tpl_var, $value = null)
251  {
252    $this->smarty->assign( $tpl_var, $value );
253  }
254
255  /**
256   * Inserts the uncompiled code for $handle as the value of $varname in the
257   * root-level. This can be used to effectively include a template in the
258   * middle of another template.
259   * This is equivalent to assign($varname, $this->parse($handle, true))
260   */
261  function assign_var_from_handle($varname, $handle)
262  {
263    $this->assign($varname, $this->parse($handle, true));
264    return true;
265  }
266
267  /** see smarty append http://www.smarty.net/manual/en/api.append.php */
268  function append($tpl_var, $value=null, $merge=false)
269  {
270    $this->smarty->append( $tpl_var, $value, $merge );
271  }
272
273  /**
274   * Root-level variable concatenation. Appends a  string to an existing
275   * variable assignment with the same name.
276   */
277  function concat($tpl_var, $value)
278  {
279    $old_val = & $this->smarty->get_template_vars($tpl_var);
280    if ( isset($old_val) )
281    {
282      $old_val .= $value;
283    }
284    else
285    {
286      $this->assign($tpl_var, $value);
287    }
288  }
289
290  /** see smarty append http://www.smarty.net/manual/en/api.clear_assign.php */
291  function clear_assign($tpl_var)
292  {
293    $this->smarty->clear_assign( $tpl_var );
294  }
295
296  /** see smarty get_template_vars http://www.smarty.net/manual/en/api.get_template_vars.php */
297  function &get_template_vars($name=null)
298  {
299    return $this->smarty->get_template_vars( $name );
300  }
301
302
303  /**
304   * Load the file for the handle, eventually compile the file and run the compiled
305   * code. This will add the output to the results or return the result if $return
306   * is true.
307   */
308  function parse($handle, $return=false)
309  {
310    if ( !isset($this->files[$handle]) )
311    {
312      fatal_error("Template->parse(): Couldn't load template file for handle $handle");
313    }
314
315    $this->smarty->assign( 'ROOT_URL', get_root_url() );
316    $this->smarty->assign( 'TAG_INPUT_ENABLED',
317      ((is_adviser()) ? 'disabled="disabled" onclick="return false;"' : ''));
318
319    $save_compile_id = $this->smarty->compile_id;
320    $this->load_external_filters($handle);
321
322    global $conf, $lang_info;
323    if ( $conf['compiled_template_cache_language'] and isset($lang_info['code']) )
324    {
325      $this->smarty->compile_id .= '.'.$lang_info['code'];
326    }
327
328    $v = $this->smarty->fetch($this->files[$handle], null, null, false);
329
330    $this->smarty->compile_id = $save_compile_id;
331    $this->unload_external_filters($handle);
332
333    if ($return)
334    {
335      return $v;
336    }
337    $this->output .= $v;
338  }
339
340  /**
341   * Load the file for the handle, eventually compile the file and run the compiled
342   * code. This will print out the results of executing the template.
343   */
344  function pparse($handle)
345  {
346    $this->parse($handle, false);
347    $this->flush();
348  }
349
350  function flush()
351  {
352    if ( count($this->html_head_elements) )
353    {
354      $search = "\n</head>";
355      $pos = strpos( $this->output, $search );
356      if ($pos !== false)
357      {
358        $this->output = substr_replace( $this->output, "\n".implode( "\n", $this->html_head_elements ), $pos, 0 );
359      } //else maybe error or warning ?
360      $this->html_head_elements = array();
361    }
362
363    echo $this->output;
364    $this->output='';
365  }
366
367  /** flushes the output */
368  function p()
369  {
370    $this->flush();
371
372    if ($this->smarty->debugging)
373    {
374      global $t2;
375      $this->smarty->assign(
376        array(
377        'AAAA_DEBUG_TOTAL_TIME__' => get_elapsed_time($t2, get_moment())
378        )
379        );
380      require_once(SMARTY_CORE_DIR . 'core.display_debug_console.php');
381      echo smarty_core_display_debug_console(null, $this->smarty);
382    }
383  }
384
385  /**
386   * translate variable modifier - translates a text to the currently loaded
387   * language
388   */
389  static function mod_translate($text)
390  {
391    return l10n($text);
392  }
393
394  /**
395   * explode variable modifier - similar to php explode
396   * 'Yes;No'|@explode:';' -> array('Yes', 'No')
397   */
398  static function mod_explode($text, $delimiter=',')
399  {
400    return explode($delimiter, $text);
401  }
402
403  /**
404   * This smarty "html_head" block allows to add content just before
405   * </head> element in the output after the head has been parsed. This is
406   * handy in order to respect strict standards when <style> and <link>
407   * html elements must appear in the <head> element
408   */
409  function block_html_head($params, $content, &$smarty, &$repeat)
410  {
411    $content = trim($content);
412    if ( !empty($content) )
413    { // second call
414      $this->html_head_elements[] = $content;
415    }
416  }
417
418 /**
419   * This smarty "known_script" functions allows to insert well known java scripts
420   * such as prototype, jquery, etc... only once. Examples:
421   * {known_script id="jquery" src="{$ROOT_URL}template-common/lib/jquery.packed.js"}
422   */
423  function func_known_script($params, &$smarty )
424  {
425    if (!isset($params['id']))
426    {
427        $smarty->trigger_error("known_script: missing 'id' parameter");
428        return;
429    }
430    $id = $params['id'];
431    if (! isset( $this->known_scripts[$id] ) )
432    {
433      if (!isset($params['src']))
434      {
435          $smarty->trigger_error("known_script: missing 'src' parameter");
436          return;
437      }
438      $this->known_scripts[$id] = $params['src'];
439      $content = '<script type="text/javascript" src="'.$params['src'].'"></script>';
440      if (isset($params['now']) and $params['now'] and empty($this->output) )
441      {
442        return $content;
443      }
444      $repeat = false;
445      $this->block_html_head(null, $content, $smarty, $repeat);
446    }
447  }
448
449 /**
450   * This function allows to declare a Smarty prefilter from a plugin, thus allowing
451   * it to modify template source before compilation and without changing core files
452   * They will be processed by weight ascending.
453   * http://www.smarty.net/manual/en/advanced.features.prefilters.php
454   */
455  function set_prefilter($handle, $callback, $weight=50)
456  {
457    $this->external_filters[$handle][$weight][] = array('prefilter', $callback);
458    ksort($this->external_filters[$handle]);
459  }
460
461  function set_postfilter($handle, $callback, $weight=50)
462  {
463    $this->external_filters[$handle][$weight][] = array('postfilter', $callback);
464    ksort($this->external_filters[$handle]);
465  }
466
467  function set_outputfilter($handle, $callback, $weight=50)
468  {
469    $this->external_filters[$handle][$weight][] = array('outputfilter', $callback);
470    ksort($this->external_filters[$handle]);
471  }
472 
473 /**
474   * This function actually triggers the filters on the tpl files.
475   * Called in the parse method.
476   * http://www.smarty.net/manual/en/advanced.features.prefilters.php
477   */
478  function load_external_filters($handle)
479  {
480    if (isset($this->external_filters[$handle]))
481    {
482      $compile_id = '';
483      foreach ($this->external_filters[$handle] as $filters) 
484      {
485        foreach ($filters as $filter) 
486        {
487          list($type, $callback) = $filter;
488          $compile_id .= $type.( is_array($callback) ? implode('', $callback) : $callback );
489          call_user_func(array($this->smarty, 'register_'.$type), $callback);
490        }
491      }
492      $this->smarty->compile_id .= '.'.base_convert(crc32($compile_id), 10, 36);
493    }
494  }
495
496  function unload_external_filters($handle)
497  {
498    if (isset($this->external_filters[$handle]))
499    {
500      foreach ($this->external_filters[$handle] as $filters) 
501      {
502        foreach ($filters as $filter) 
503        {
504          list($type, $callback) = $filter;
505          call_user_func(array($this->smarty, 'unregister_'.$type), $callback);
506        }
507      }
508    }
509  }
510
511  static function prefilter_white_space($source, &$smarty)
512  {
513    $ld = $smarty->left_delimiter;
514    $rd = $smarty->right_delimiter;
515    $ldq = preg_quote($ld, '#');
516    $rdq = preg_quote($rd, '#');
517
518    $regex = array();
519    $tags = array('if', 'foreach', 'section');
520    foreach($tags as $tag)
521    {
522      array_push($regex, "#^[ \t]+($ldq$tag"."[^$ld$rd]*$rdq)\s*$#m");
523      array_push($regex, "#^[ \t]+($ldq/$tag$rdq)\s*$#m");
524    }
525    $tags = array('include', 'else', 'html_head');
526    foreach($tags as $tag)
527    {
528      array_push($regex, "#^[ \t]+($ldq$tag"."[^$ld$rd]*$rdq)\s*$#m");
529    }
530    $source = preg_replace( $regex, "$1", $source);
531    return $source;
532  }
533
534  /**
535   * Smarty prefilter to allow caching (whenever possible) language strings
536   * from templates.
537   */
538  static function prefilter_language($source, &$smarty)
539  {
540    global $lang;
541    $ldq = preg_quote($smarty->left_delimiter, '~');
542    $rdq = preg_quote($smarty->right_delimiter, '~');
543
544    $regex = "~$ldq *\'([^'$]+)\'\|@translate *$rdq~";
545    $source = preg_replace( $regex.'e', 'isset($lang[\'$1\']) ? $lang[\'$1\'] : \'$0\'', $source);
546
547    $regex = "~$ldq *\'([^'$]+)\'\|@translate\|~";
548    $source = preg_replace( $regex.'e', 'isset($lang[\'$1\']) ? \'{\'.var_export($lang[\'$1\'],true).\'|\' : \'$0\'', $source);
549
550    $regex = "~($ldq *assign +var=.+ +value=)\'([^'$]+)\'\|@translate~e";
551    $source = preg_replace( $regex, 'isset($lang[\'$2\']) ? \'$1\'.var_export($lang[\'$2\'],true) : \'$0\'', $source);
552
553    return $source;
554  }
555}
556
557
558/**
559 * This class contains basic functions that can be called directly from the
560 * templates in the form $pwg->l10n('edit')
561 */
562class PwgTemplateAdapter
563{
564  function l10n($text)
565  {
566    return l10n($text);
567  }
568
569  function l10n_dec($s, $p, $v)
570  {
571    return l10n_dec($s, $p, $v);
572  }
573
574  function sprintf()
575  {
576    $args = func_get_args();
577    return call_user_func_array('sprintf',  $args );
578  }
579}
580
581?>
Note: See TracBrowser for help on using the repository browser.