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

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

Simplification of commit 3951.

  • Property svn:eol-style set to LF
File size: 16.5 KB
RevLine 
[2216]1<?php
2// +-----------------------------------------------------------------------+
[2297]3// | Piwigo - a PHP based picture gallery                                  |
4// +-----------------------------------------------------------------------+
[3049]5// | Copyright(C) 2008-2009 Piwigo Team                  http://piwigo.org |
[2297]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// +-----------------------------------------------------------------------+
[2216]23
24
[2699]25require_once(PHPWG_ROOT_PATH.'include/smarty/libs/Smarty.class.php');
[2216]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
[2643]46  // Template extents filenames for each template handle.
47  var $extents = array();
48
[3927]49  // Templates prefilter from external sources (plugins)
50  var $external_filters = array();
51 
[2334]52  // used by html_head smarty block to add content before </head>
53  var $html_head_elements = array();
54
[2216]55  function Template($root = ".", $theme= "")
56  {
[2632]57    global $conf, $lang_info;
[2216]58
59    $this->smarty = new Smarty;
60    $this->smarty->debugging = $conf['debug_template'];
[2790]61    $this->smarty->compile_check=$conf['template_compile_check'];
[2216]62
[2497]63    $compile_dir = $conf['local_data_dir'].'/templates_c';
64    mkgetdir( $compile_dir );
[2216]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') );
[2286]70    $this->smarty->register_modifier( 'explode', array('Template', 'mod_explode') );
[2716]71    $this->smarty->register_modifier( 'get_extent', array(&$this, 'get_extent') );
[2334]72    $this->smarty->register_block('html_head', array(&$this, 'block_html_head') );
[2521]73    $this->smarty->register_function('known_script', array(&$this, 'func_known_script') );
[2481]74    $this->smarty->register_prefilter( array('Template', 'prefilter_white_space') );
[2334]75    if ( $conf['compiled_template_cache_language'] )
76    {
[2481]77      $this->smarty->register_prefilter( array('Template', 'prefilter_language') );
[2334]78    }
[2216]79
[2254]80    if ( !empty($theme) )
81    {
82      include($root.'/theme/'.$theme.'/themeconf.inc.php');
83      $this->smarty->assign('themeconf', $themeconf);
84    }
[2216]85
[2632]86    $this->smarty->assign('lang_info', $lang_info);
87
[2278]88    $this->set_template_dir($root);
[2643]89
[3169]90    if (!defined('IN_ADMIN') and isset($conf['extents_for_templates']))
[2643]91    {
92      $tpl_extents = unserialize($conf['extents_for_templates']);
93      $this->set_extents($tpl_extents, './template-extension/', true);
94    }
[2216]95  }
96
[2278]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);
[2334]106    $this->smarty->compile_id = base_convert($compile_id, 10, 36 );
[2278]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;
[2497]126      file_put_contents($this->smarty->compile_dir.'/index.htm', 'Not allowed!');
[2278]127  }
128
[2216]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))
[2643]157      {
158        unset($this->files[$handle]);
159      }
[2216]160      else
[2434]161      {
[2716]162        $this->files[$handle] = $this->get_extent($filename, $handle);
[2434]163      }
[2216]164    }
165    return true;
166  }
[2476]167
[2643]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  /**
[2699]177   * Sets template extentions filenames for handles.
[2643]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];
[2923]192        $tpl = $value[2];
[2643]193      }
194      elseif (is_string($value))
195      {
196        $handle = $value;
197        $param = 'N/A';
[2923]198        $tpl = 'N/A';
[2643]199      }
200      else
201      {
202        return false;
203      }
204
[3207]205      if ((stripos(implode('',array_keys($_GET)), '/'.$param) !== false or $param == 'N/A')
[2923]206        and (preg_match('/'.preg_quote($tpl,'/').'$/', $this->get_template_dir()) or $tpl == 'N/A')
[2643]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  }
[2790]215
[2716]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  }
[2643]225
[2286]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 );
[2290]230  }
[2286]231
[2216]232  /**
[2286]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  /**
[2216]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    {
[2502]289      fatal_error("Template->parse(): Couldn't load template file for handle $handle");
[2216]290    }
291
[2290]292    $this->smarty->assign( 'ROOT_URL', get_root_url() );
293    $this->smarty->assign( 'TAG_INPUT_ENABLED',
294      ((is_adviser()) ? 'disabled="disabled" onclick="return false;"' : ''));
[2334]295
[3928]296    $save_compile_id = $this->smarty->compile_id;
297    $this->load_external_filters($handle);
[3927]298
[2334]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    }
[2476]304
[2290]305    $v = $this->smarty->fetch($this->files[$handle], null, null, false);
[2476]306
[3928]307    $this->smarty->compile_id = $save_compile_id;
308    $this->unload_external_filters($handle);
[2476]309
[2231]310    if ($return)
[2216]311    {
[2231]312      return $v;
[2216]313    }
[2231]314    $this->output .= $v;
[2216]315  }
316
[2231]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);
[2334]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    }
[3927]339
[2231]340    echo $this->output;
341    $this->output='';
342  }
343
344  /** flushes the output */
[2216]345  function p()
346  {
[2334]347    $this->flush();
[2231]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    }
[2216]360  }
361
362  /**
[2286]363   * translate variable modifier - translates a text to the currently loaded
364   * language
[2216]365   */
[2536]366  static function mod_translate($text)
[2216]367  {
[2286]368    return l10n($text);
[2216]369  }
370
371  /**
[2286]372   * explode variable modifier - similar to php explode
[2290]373   * 'Yes;No'|@explode:';' -> array('Yes', 'No')
[2216]374   */
[2536]375  static function mod_explode($text, $delimiter=',')
[2216]376  {
[2286]377    return explode($delimiter, $text);
[2216]378  }
[2476]379
[2334]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>
[2476]384   * html elements must appear in the <head> element
[2334]385   */
386  function block_html_head($params, $content, &$smarty, &$repeat)
387  {
388    $content = trim($content);
389    if ( !empty($content) )
390    { // second call
[2627]391      $this->html_head_elements[] = $content;
[2334]392    }
393  }
[2476]394
[2513]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
[3927]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   */
[3951]432  function set_prefilter($handle, $callback, $weight=50)
[3927]433  {
[3953]434    $this->external_filters[$handle][$weight][] = array('prefilter', $callback);
[3928]435    ksort($this->external_filters[$handle]);
[3927]436  }
[3951]437
438  function set_postfilter($handle, $callback, $weight=50)
439  {
[3953]440    $this->external_filters[$handle][$weight][] = array('postfilter', $callback);
[3951]441    ksort($this->external_filters[$handle]);
442  }
443
444  function set_outputfilter($handle, $callback, $weight=50)
445  {
[3953]446    $this->external_filters[$handle][$weight][] = array('outputfilter', $callback);
[3951]447    ksort($this->external_filters[$handle]);
448  }
[3927]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   */
[3928]455  function load_external_filters($handle)
[3927]456  {
[3928]457    if (isset($this->external_filters[$handle]))
[3927]458    {
[3951]459      $compile_id = '';
460      foreach ($this->external_filters[$handle] as $filters) 
[3928]461      {
[3951]462        foreach ($filters as $filter) 
[3928]463        {
[3951]464          list($type, $callback) = $filter;
465          $compile_id .= $type.( is_array($callback) ? implode('', $callback) : $callback );
[3953]466          call_user_func(array($this->smarty, 'register_'.$type), $callback);
[3928]467        }
468      }
[3951]469      $this->smarty->compile_id .= '.'.base_convert(crc32($compile_id), 10, 36);
[3927]470    }
471  }
[3928]472
473  function unload_external_filters($handle)
474  {
475    if (isset($this->external_filters[$handle]))
476    {
[3951]477      foreach ($this->external_filters[$handle] as $filters) 
[3928]478      {
[3951]479        foreach ($filters as $filter) 
[3928]480        {
[3951]481          list($type, $callback) = $filter;
[3953]482          call_user_func(array($this->smarty, 'unregister_'.$type), $callback);
[3928]483        }
484      }
485    }
486  }
487
[2536]488  static function prefilter_white_space($source, &$smarty)
[2481]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    {
[2489]499      array_push($regex, "#^[ \t]+($ldq$tag"."[^$ld$rd]*$rdq)\s*$#m");
500      array_push($regex, "#^[ \t]+($ldq/$tag$rdq)\s*$#m");
[2481]501    }
502    $tags = array('include', 'else', 'html_head');
503    foreach($tags as $tag)
504    {
[2489]505      array_push($regex, "#^[ \t]+($ldq$tag"."[^$ld$rd]*$rdq)\s*$#m");
[2481]506    }
507    $source = preg_replace( $regex, "$1", $source);
508    return $source;
509  }
510
[2334]511  /**
[2476]512   * Smarty prefilter to allow caching (whenever possible) language strings
[2334]513   * from templates.
514   */
[2536]515  static function prefilter_language($source, &$smarty)
[2334]516  {
517    global $lang;
[2481]518    $ldq = preg_quote($smarty->left_delimiter, '~');
519    $rdq = preg_quote($smarty->right_delimiter, '~');
[2476]520
[2334]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
[2636]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
[2334]530    return $source;
531  }
[2216]532}
533
[3927]534
[2216]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.