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

Last change on this file since 2334 was 2334, checked in by rvelices, 16 years ago

2 template features:

  • added a {html_head} smarty block - allow any template file to add content just before </head> tag (handy for plugins and allows to move more presentation logic to tpls); the content is usually <style> or <link> which must appear inside html <head> tag
  • by config allow some language strings to be replaced during template compilation -> better performance. drawback: changes in the language file will not be propagated until template is recompiled.
  • Property svn:eol-style set to LF
  • Property svn:keywords set to Author Date Id Revision
File size: 11.0 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based picture gallery                                  |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008      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 '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  // used by html_head smarty block to add content before </head>
47  var $html_head_elements = array();
48
49  function Template($root = ".", $theme= "")
50  {
51    global $conf;
52
53    $this->smarty = new Smarty;
54    $this->smarty->debugging = $conf['debug_template'];
55
56    if ( isset($conf['compiled_template_dir'] ) )
57    {
58      $compile_dir = $conf['compiled_template_dir'];
59    }
60    else
61    {
62      $compile_dir = $conf['local_data_dir'];
63      if ( !is_dir($compile_dir) )
64      {
65        mkdir( $compile_dir, 0777);
66        file_put_contents($compile_dir.'/index.htm', '');
67      }
68      $compile_dir .= '/templates_c';
69    }
70    if ( !is_dir($compile_dir) )
71    {
72      mkdir( $compile_dir, 0777 );
73      file_put_contents($compile_dir.'/index.htm', '');
74    }
75
76    $this->smarty->compile_dir = $compile_dir;
77
78    $this->smarty->assign_by_ref( 'pwg', new PwgTemplateAdapter() );
79    $this->smarty->register_modifier( 'translate', array('Template', 'mod_translate') );
80    $this->smarty->register_modifier( 'explode', array('Template', 'mod_explode') );
81    $this->smarty->register_block('html_head', array(&$this, 'block_html_head') );
82    if ( $conf['compiled_template_cache_language'] )
83    {
84      $this->smarty->register_prefilter( array(&$this, 'prefilter_language') );
85    }
86
87    if ( !empty($theme) )
88    {
89      include($root.'/theme/'.$theme.'/themeconf.inc.php');
90      $this->smarty->assign('themeconf', $themeconf);
91    }
92
93    $this->set_template_dir($root);
94  }
95
96  /**
97   * Sets the template root directory for this Template object.
98   */
99  function set_template_dir($dir)
100  {
101    $this->smarty->template_dir = $dir;
102
103    $real_dir = realpath($dir);
104    $compile_id = crc32( $real_dir===false ? $dir : $real_dir);
105    $this->smarty->compile_id = base_convert($compile_id, 10, 36 );
106  }
107
108  /**
109   * Gets the template root directory for this Template object.
110   */
111  function get_template_dir()
112  {
113    return $this->smarty->template_dir;
114  }
115
116  /**
117   * Deletes all compiled templates.
118   */
119  function delete_compiled_templates()
120  {
121      $save_compile_id = $this->smarty->compile_id;
122      $this->smarty->compile_id = null;
123      $this->smarty->clear_compiled_tpl();
124      $this->smarty->compile_id = $save_compile_id;
125      file_put_contents($this->smarty->compile_dir.'/index.htm', '');
126  }
127
128  function get_themeconf($val)
129  {
130    $tc = $this->smarty->get_template_vars('themeconf');
131    return isset($tc[$val]) ? $tc[$val] : '';
132  }
133
134  /**
135   * Sets the template filename for handle.
136   */
137  function set_filename($handle, $filename)
138  {
139    return $this->set_filenames( array($handle=>$filename) );
140  }
141
142  /**
143   * Sets the template filenames for handles. $filename_array should be a
144   * hash of handle => filename pairs.
145   */
146  function set_filenames($filename_array)
147  {
148    if (!is_array($filename_array))
149    {
150      return false;
151    }
152
153    reset($filename_array);
154    while(list($handle, $filename) = each($filename_array))
155    {
156      if (is_null($filename))
157        unset( $this->files[$handle] );
158      else
159        $this->files[$handle] = $filename;
160    }
161    return true;
162  }
163
164  /** see smarty assign http://www.smarty.net/manual/en/api.assign.php */
165  function assign($tpl_var, $value = null)
166  {
167    $this->smarty->assign( $tpl_var, $value );
168  }
169
170  /**
171   * Inserts the uncompiled code for $handle as the value of $varname in the
172   * root-level. This can be used to effectively include a template in the
173   * middle of another template.
174   * This is equivalent to assign($varname, $this->parse($handle, true))
175   */
176  function assign_var_from_handle($varname, $handle)
177  {
178    $this->assign($varname, $this->parse($handle, true));
179    return true;
180  }
181
182  /** see smarty append http://www.smarty.net/manual/en/api.append.php */
183  function append($tpl_var, $value=null, $merge=false)
184  {
185    $this->smarty->append( $tpl_var, $value, $merge );
186  }
187
188  /**
189   * Root-level variable concatenation. Appends a  string to an existing
190   * variable assignment with the same name.
191   */
192  function concat($tpl_var, $value)
193  {
194    $old_val = & $this->smarty->get_template_vars($tpl_var);
195    if ( isset($old_val) )
196    {
197      $old_val .= $value;
198    }
199    else
200    {
201      $this->assign($tpl_var, $value);
202    }
203  }
204
205  /** see smarty append http://www.smarty.net/manual/en/api.clear_assign.php */
206  function clear_assign($tpl_var)
207  {
208    $this->smarty->clear_assign( $tpl_var );
209  }
210
211  /** see smarty get_template_vars http://www.smarty.net/manual/en/api.get_template_vars.php */
212  function &get_template_vars($name=null)
213  {
214    return $this->smarty->get_template_vars( $name );
215  }
216
217
218  /**
219   * Load the file for the handle, eventually compile the file and run the compiled
220   * code. This will add the output to the results or return the result if $return
221   * is true.
222   */
223  function parse($handle, $return=false)
224  {
225    if ( !isset($this->files[$handle]) )
226    {
227      die("Template->parse(): Couldn't load template file for handle $handle");
228    }
229
230    $this->smarty->assign( 'ROOT_URL', get_root_url() );
231    $this->smarty->assign( 'TAG_INPUT_ENABLED',
232      ((is_adviser()) ? 'disabled="disabled" onclick="return false;"' : ''));
233
234    global $conf, $lang_info;
235    if ( $conf['compiled_template_cache_language'] and isset($lang_info['code']) )
236    {
237      $save_compile_id = $this->smarty->compile_id;
238      $this->smarty->compile_id .= '.'.$lang_info['code'];
239    }
240   
241    $v = $this->smarty->fetch($this->files[$handle], null, null, false);
242   
243    if (isset ($save_compile_id) )
244    {
245      $this->smarty->compile_id = $save_compile_id;
246    }
247     
248    if ($return)
249    {
250      return $v;
251    }
252    $this->output .= $v;
253  }
254
255  /**
256   * Load the file for the handle, eventually compile the file and run the compiled
257   * code. This will print out the results of executing the template.
258   */
259  function pparse($handle)
260  {
261    $this->parse($handle, false);
262    $this->flush();
263  }
264
265  function flush()
266  {
267    if ( count($this->html_head_elements) )
268    {
269      $search = "\n</head>";
270      $pos = strpos( $this->output, $search );
271      if ($pos !== false)
272      {
273        $this->output = substr_replace( $this->output, "\n".implode( "\n", $this->html_head_elements ), $pos, 0 );
274      } //else maybe error or warning ?
275      $this->html_head_elements = array();
276    }
277    echo $this->output;
278    $this->output='';
279  }
280
281  /** flushes the output */
282  function p()
283  {
284    $start = get_moment();
285
286    $this->flush();
287
288    if ($this->smarty->debugging)
289    {
290      global $t2;
291      $this->smarty->assign(
292        array(
293        'AAAA_DEBUG_OUTPUT_TIME__' => get_elapsed_time($start, get_moment()),
294        'AAAA_DEBUG_TOTAL_TIME__' => get_elapsed_time($t2, get_moment())
295        )
296        );
297      require_once(SMARTY_CORE_DIR . 'core.display_debug_console.php');
298      echo smarty_core_display_debug_console(null, $this->smarty);
299    }
300  }
301
302  /**
303   * translate variable modifier - translates a text to the currently loaded
304   * language
305   */
306  /*static*/ function mod_translate($text)
307  {
308    return l10n($text);
309  }
310
311  /**
312   * explode variable modifier - similar to php explode
313   * 'Yes;No'|@explode:';' -> array('Yes', 'No')
314   */
315  /*static*/ function mod_explode($text, $delimiter=',')
316  {
317    return explode($delimiter, $text);
318  }
319 
320  /**
321   * This smarty "html_head" block allows to add content just before
322   * </head> element in the output after the head has been parsed. This is
323   * handy in order to respect strict standards when <style> and <link>
324   * html elements must appear in the <head> element           
325   */
326  function block_html_head($params, $content, &$smarty, &$repeat)
327  {
328    $content = trim($content);
329    if ( !empty($content) )
330    { // second call
331      if ( empty($this->output) )
332      {//page header not parsed yet
333        $this->append('head_elements', $content);
334      }
335      else
336      {
337        $this->html_head_elements[] = $content;
338      }
339    }
340  }
341 
342  /**
343   * Smarty prefilter to allow caching (whenever possible) language strings
344   * from templates.
345   */
346  function prefilter_language($source, &$smarty)
347  {
348    global $lang;
349    $ldq = preg_quote($this->smarty->left_delimiter, '~');
350    $rdq = preg_quote($this->smarty->right_delimiter, '~');
351   
352    $regex = "~$ldq *\'([^'$]+)\'\|@translate *$rdq~";
353    $source = preg_replace( $regex.'e', 'isset($lang[\'$1\']) ? $lang[\'$1\'] : \'$0\'', $source);
354
355    $regex = "~$ldq *\'([^'$]+)\'\|@translate\|~";
356    $source = preg_replace( $regex.'e', 'isset($lang[\'$1\']) ? \'{\'.var_export($lang[\'$1\'],true).\'|\' : \'$0\'', $source);
357
358    return $source;
359  }
360}
361
362/**
363 * This class contains basic functions that can be called directly from the
364 * templates in the form $pwg->l10n('edit')
365 */
366class PwgTemplateAdapter
367{
368  function l10n($text)
369  {
370    return l10n($text);
371  }
372
373  function l10n_dec($s, $p, $v)
374  {
375    return l10n_dec($s, $p, $v);
376  }
377
378  function sprintf()
379  {
380    $args = func_get_args();
381    return call_user_func_array('sprintf',  $args );
382  }
383}
384
385?>
Note: See TracBrowser for help on using the repository browser.