source: branches/2.0/include/template.class.php @ 3998

Last change on this file since 3998 was 3998, checked in by patdenice, 15 years ago

merge r3927, r3928, r3951, r3953 from trunk to branch 2.0
r3927: Add Smarty's prefilter capability. see topic:16219 (FR).
r3928: Improve template prefilter functions
r3951: Allow to add prefilters, postfilters and output filters to templates.
r3953: Simplification of commit 3951.

  • Property svn:eol-style set to LF
  • Property svn:keywords set to Author Date Id Revision
File size: 16.5 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= "")
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    if ( !empty($theme) )
81    {
82      include($root.'/theme/'.$theme.'/themeconf.inc.php');
83      $this->smarty->assign('themeconf', $themeconf);
84    }
85
86    $this->smarty->assign('lang_info', $lang_info);
87
88    $this->set_template_dir($root);
89
90    if (!defined('IN_ADMIN') and isset($conf['extents_for_templates']))
91    {
92      $tpl_extents = unserialize($conf['extents_for_templates']);
93      $this->set_extents($tpl_extents, './template-extension/', true);
94    }
95  }
96
97  /**
98   * Sets the template root directory for this Template object.
99   */
100  function set_template_dir($dir)
101  {
102    $this->smarty->template_dir = $dir;
103
104    $real_dir = realpath($dir);
105    $compile_id = crc32( $real_dir===false ? $dir : $real_dir);
106    $this->smarty->compile_id = base_convert($compile_id, 10, 36 );
107  }
108
109  /**
110   * Gets the template root directory for this Template object.
111   */
112  function get_template_dir()
113  {
114    return $this->smarty->template_dir;
115  }
116
117  /**
118   * Deletes all compiled templates.
119   */
120  function delete_compiled_templates()
121  {
122      $save_compile_id = $this->smarty->compile_id;
123      $this->smarty->compile_id = null;
124      $this->smarty->clear_compiled_tpl();
125      $this->smarty->compile_id = $save_compile_id;
126      file_put_contents($this->smarty->compile_dir.'/index.htm', 'Not allowed!');
127  }
128
129  function get_themeconf($val)
130  {
131    $tc = $this->smarty->get_template_vars('themeconf');
132    return isset($tc[$val]) ? $tc[$val] : '';
133  }
134
135  /**
136   * Sets the template filename for handle.
137   */
138  function set_filename($handle, $filename)
139  {
140    return $this->set_filenames( array($handle=>$filename) );
141  }
142
143  /**
144   * Sets the template filenames for handles. $filename_array should be a
145   * hash of handle => filename pairs.
146   */
147  function set_filenames($filename_array)
148  {
149    if (!is_array($filename_array))
150    {
151      return false;
152    }
153    reset($filename_array);
154    while(list($handle, $filename) = each($filename_array))
155    {
156      if (is_null($filename))
157      {
158        unset($this->files[$handle]);
159      }
160      else
161      {
162        $this->files[$handle] = $this->get_extent($filename, $handle);
163      }
164    }
165    return true;
166  }
167
168  /**
169   * Sets template extention filename for handles.
170   */
171  function set_extent($filename, $param, $dir='', $overwrite=true)
172  {
173    return $this->set_extents(array($filename => $param), $dir, $overwrite);
174  }
175
176  /**
177   * Sets template extentions filenames for handles.
178   * $filename_array should be an hash of filename => array( handle, param) or filename => handle
179   */
180  function set_extents($filename_array, $dir='', $overwrite=true)
181  {
182    if (!is_array($filename_array))
183    {
184      return false;
185    }
186    foreach ($filename_array as $filename => $value)
187    {
188      if (is_array($value))
189      {
190        $handle = $value[0];
191        $param = $value[1];
192        $tpl = $value[2];
193      }
194      elseif (is_string($value))
195      {
196        $handle = $value;
197        $param = 'N/A';
198        $tpl = 'N/A';
199      }
200      else
201      {
202        return false;
203      }
204
205      if ((stripos(implode('',array_keys($_GET)), '/'.$param) !== false or $param == 'N/A')
206        and (preg_match('/'.preg_quote($tpl,'/').'$/', $this->get_template_dir()) or $tpl == 'N/A')
207        and (!isset($this->extents[$handle]) or $overwrite)
208        and file_exists($dir . $filename))
209      {
210        $this->extents[$handle] = realpath($dir . $filename);
211      }
212    }
213    return true;
214  }
215
216  /** return template extension if exists  */
217  function get_extent($filename='', $handle='')
218  {
219    if (isset($this->extents[$handle]))
220    {
221      $filename = $this->extents[$handle];
222    }
223    return $filename;
224  }
225
226  /** see smarty assign http://www.smarty.net/manual/en/api.assign.php */
227  function assign($tpl_var, $value = null)
228  {
229    $this->smarty->assign( $tpl_var, $value );
230  }
231
232  /**
233   * Inserts the uncompiled code for $handle as the value of $varname in the
234   * root-level. This can be used to effectively include a template in the
235   * middle of another template.
236   * This is equivalent to assign($varname, $this->parse($handle, true))
237   */
238  function assign_var_from_handle($varname, $handle)
239  {
240    $this->assign($varname, $this->parse($handle, true));
241    return true;
242  }
243
244  /** see smarty append http://www.smarty.net/manual/en/api.append.php */
245  function append($tpl_var, $value=null, $merge=false)
246  {
247    $this->smarty->append( $tpl_var, $value, $merge );
248  }
249
250  /**
251   * Root-level variable concatenation. Appends a  string to an existing
252   * variable assignment with the same name.
253   */
254  function concat($tpl_var, $value)
255  {
256    $old_val = & $this->smarty->get_template_vars($tpl_var);
257    if ( isset($old_val) )
258    {
259      $old_val .= $value;
260    }
261    else
262    {
263      $this->assign($tpl_var, $value);
264    }
265  }
266
267  /** see smarty append http://www.smarty.net/manual/en/api.clear_assign.php */
268  function clear_assign($tpl_var)
269  {
270    $this->smarty->clear_assign( $tpl_var );
271  }
272
273  /** see smarty get_template_vars http://www.smarty.net/manual/en/api.get_template_vars.php */
274  function &get_template_vars($name=null)
275  {
276    return $this->smarty->get_template_vars( $name );
277  }
278
279
280  /**
281   * Load the file for the handle, eventually compile the file and run the compiled
282   * code. This will add the output to the results or return the result if $return
283   * is true.
284   */
285  function parse($handle, $return=false)
286  {
287    if ( !isset($this->files[$handle]) )
288    {
289      fatal_error("Template->parse(): Couldn't load template file for handle $handle");
290    }
291
292    $this->smarty->assign( 'ROOT_URL', get_root_url() );
293    $this->smarty->assign( 'TAG_INPUT_ENABLED',
294      ((is_adviser()) ? 'disabled="disabled" onclick="return false;"' : ''));
295
296    $save_compile_id = $this->smarty->compile_id;
297    $this->load_external_filters($handle);
298
299    global $conf, $lang_info;
300    if ( $conf['compiled_template_cache_language'] and isset($lang_info['code']) )
301    {
302      $this->smarty->compile_id .= '.'.$lang_info['code'];
303    }
304
305    $v = $this->smarty->fetch($this->files[$handle], null, null, false);
306
307    $this->smarty->compile_id = $save_compile_id;
308    $this->unload_external_filters($handle);
309
310    if ($return)
311    {
312      return $v;
313    }
314    $this->output .= $v;
315  }
316
317  /**
318   * Load the file for the handle, eventually compile the file and run the compiled
319   * code. This will print out the results of executing the template.
320   */
321  function pparse($handle)
322  {
323    $this->parse($handle, false);
324    $this->flush();
325  }
326
327  function flush()
328  {
329    if ( count($this->html_head_elements) )
330    {
331      $search = "\n</head>";
332      $pos = strpos( $this->output, $search );
333      if ($pos !== false)
334      {
335        $this->output = substr_replace( $this->output, "\n".implode( "\n", $this->html_head_elements ), $pos, 0 );
336      } //else maybe error or warning ?
337      $this->html_head_elements = array();
338    }
339
340    echo $this->output;
341    $this->output='';
342  }
343
344  /** flushes the output */
345  function p()
346  {
347    $this->flush();
348
349    if ($this->smarty->debugging)
350    {
351      global $t2;
352      $this->smarty->assign(
353        array(
354        'AAAA_DEBUG_TOTAL_TIME__' => get_elapsed_time($t2, get_moment())
355        )
356        );
357      require_once(SMARTY_CORE_DIR . 'core.display_debug_console.php');
358      echo smarty_core_display_debug_console(null, $this->smarty);
359    }
360  }
361
362  /**
363   * translate variable modifier - translates a text to the currently loaded
364   * language
365   */
366  static function mod_translate($text)
367  {
368    return l10n($text);
369  }
370
371  /**
372   * explode variable modifier - similar to php explode
373   * 'Yes;No'|@explode:';' -> array('Yes', 'No')
374   */
375  static function mod_explode($text, $delimiter=',')
376  {
377    return explode($delimiter, $text);
378  }
379
380  /**
381   * This smarty "html_head" block allows to add content just before
382   * </head> element in the output after the head has been parsed. This is
383   * handy in order to respect strict standards when <style> and <link>
384   * html elements must appear in the <head> element
385   */
386  function block_html_head($params, $content, &$smarty, &$repeat)
387  {
388    $content = trim($content);
389    if ( !empty($content) )
390    { // second call
391      $this->html_head_elements[] = $content;
392    }
393  }
394
395 /**
396   * This smarty "known_script" functions allows to insert well known java scripts
397   * such as prototype, jquery, etc... only once. Examples:
398   * {known_script id="jquery" src="{$ROOT_URL}template-common/lib/jquery.packed.js"}
399   */
400  function func_known_script($params, &$smarty )
401  {
402    if (!isset($params['id']))
403    {
404        $smarty->trigger_error("known_script: missing 'id' parameter");
405        return;
406    }
407    $id = $params['id'];
408    if (! isset( $this->known_scripts[$id] ) )
409    {
410      if (!isset($params['src']))
411      {
412          $smarty->trigger_error("known_script: missing 'src' parameter");
413          return;
414      }
415      $this->known_scripts[$id] = $params['src'];
416      $content = '<script type="text/javascript" src="'.$params['src'].'"></script>';
417      if (isset($params['now']) and $params['now'] and empty($this->output) )
418      {
419        return $content;
420      }
421      $repeat = false;
422      $this->block_html_head(null, $content, $smarty, $repeat);
423    }
424  }
425
426 /**
427   * This function allows to declare a Smarty prefilter from a plugin, thus allowing
428   * it to modify template source before compilation and without changing core files
429   * They will be processed by weight ascending.
430   * http://www.smarty.net/manual/en/advanced.features.prefilters.php
431   */
432  function set_prefilter($handle, $callback, $weight=50)
433  {
434    $this->external_filters[$handle][$weight][] = array('prefilter', $callback);
435    ksort($this->external_filters[$handle]);
436  }
437
438  function set_postfilter($handle, $callback, $weight=50)
439  {
440    $this->external_filters[$handle][$weight][] = array('postfilter', $callback);
441    ksort($this->external_filters[$handle]);
442  }
443
444  function set_outputfilter($handle, $callback, $weight=50)
445  {
446    $this->external_filters[$handle][$weight][] = array('outputfilter', $callback);
447    ksort($this->external_filters[$handle]);
448  }
449 
450 /**
451   * This function actually triggers the filters on the tpl files.
452   * Called in the parse method.
453   * http://www.smarty.net/manual/en/advanced.features.prefilters.php
454   */
455  function load_external_filters($handle)
456  {
457    if (isset($this->external_filters[$handle]))
458    {
459      $compile_id = '';
460      foreach ($this->external_filters[$handle] as $filters) 
461      {
462        foreach ($filters as $filter) 
463        {
464          list($type, $callback) = $filter;
465          $compile_id .= $type.( is_array($callback) ? implode('', $callback) : $callback );
466          call_user_func(array($this->smarty, 'register_'.$type), $callback);
467        }
468      }
469      $this->smarty->compile_id .= '.'.base_convert(crc32($compile_id), 10, 36);
470    }
471  }
472
473  function unload_external_filters($handle)
474  {
475    if (isset($this->external_filters[$handle]))
476    {
477      foreach ($this->external_filters[$handle] as $filters) 
478      {
479        foreach ($filters as $filter) 
480        {
481          list($type, $callback) = $filter;
482          call_user_func(array($this->smarty, 'unregister_'.$type), $callback);
483        }
484      }
485    }
486  }
487
488  static function prefilter_white_space($source, &$smarty)
489  {
490    $ld = $smarty->left_delimiter;
491    $rd = $smarty->right_delimiter;
492    $ldq = preg_quote($ld, '#');
493    $rdq = preg_quote($rd, '#');
494
495    $regex = array();
496    $tags = array('if', 'foreach', 'section');
497    foreach($tags as $tag)
498    {
499      array_push($regex, "#^[ \t]+($ldq$tag"."[^$ld$rd]*$rdq)\s*$#m");
500      array_push($regex, "#^[ \t]+($ldq/$tag$rdq)\s*$#m");
501    }
502    $tags = array('include', 'else', 'html_head');
503    foreach($tags as $tag)
504    {
505      array_push($regex, "#^[ \t]+($ldq$tag"."[^$ld$rd]*$rdq)\s*$#m");
506    }
507    $source = preg_replace( $regex, "$1", $source);
508    return $source;
509  }
510
511  /**
512   * Smarty prefilter to allow caching (whenever possible) language strings
513   * from templates.
514   */
515  static function prefilter_language($source, &$smarty)
516  {
517    global $lang;
518    $ldq = preg_quote($smarty->left_delimiter, '~');
519    $rdq = preg_quote($smarty->right_delimiter, '~');
520
521    $regex = "~$ldq *\'([^'$]+)\'\|@translate *$rdq~";
522    $source = preg_replace( $regex.'e', 'isset($lang[\'$1\']) ? $lang[\'$1\'] : \'$0\'', $source);
523
524    $regex = "~$ldq *\'([^'$]+)\'\|@translate\|~";
525    $source = preg_replace( $regex.'e', 'isset($lang[\'$1\']) ? \'{\'.var_export($lang[\'$1\'],true).\'|\' : \'$0\'', $source);
526
527    $regex = "~($ldq *assign +var=.+ +value=)\'([^'$]+)\'\|@translate~e";
528    $source = preg_replace( $regex, 'isset($lang[\'$2\']) ? \'$1\'.var_export($lang[\'$2\'],true) : \'$0\'', $source);
529
530    return $source;
531  }
532}
533
534
535/**
536 * This class contains basic functions that can be called directly from the
537 * templates in the form $pwg->l10n('edit')
538 */
539class PwgTemplateAdapter
540{
541  function l10n($text)
542  {
543    return l10n($text);
544  }
545
546  function l10n_dec($s, $p, $v)
547  {
548    return l10n_dec($s, $p, $v);
549  }
550
551  function sprintf()
552  {
553    $args = func_get_args();
554    return call_user_func_array('sprintf',  $args );
555  }
556}
557
558?>
Note: See TracBrowser for help on using the repository browser.