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

Last change on this file since 2464 was 2464, checked in by vdigital, 16 years ago

Feature:837 "Extend for templates" could have dedicated .css files by a simple technical {html_head} inclusion.

  • Property svn:eol-style set to LF
  • Property svn:keywords set to Author Date Id Revision
File size: 11.8 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    global $conf; 
149    if (!is_array($filename_array))
150    {
151      return false;
152    }
153    reset($filename_array);
154    $tpl_extension = isset($conf['extents_for_templates']) ?
155      unserialize($conf['extents_for_templates']) : array();
156    while(list($handle, $filename) = each($filename_array))
157    {
158      if (is_null($filename))
159        unset( $this->files[$handle] );
160      else
161      {
162        if (!isset($this->files[$handle])) $this->files[$handle] = $filename;
163        foreach ($tpl_extension as $file => $conditions)
164        {
165          $localtpl = './template-extension/' . $file;
166          if ($handle == $conditions[0] and 
167             (stripos(implode('/',array_flip($_GET)),$conditions[1])>0 
168              or $conditions[1] == 'N/A')
169              and file_exists($localtpl))
170          { /* examples: Are best_rated, created-monthly-calendar, list, ... set? */
171              $this->files[$handle] = '../.' . $localtpl; 
172              /* assign their tpl-extension */
173          }
174        }
175      }
176    }
177    return true;
178  }
179  function on_extension($key, $tlpname)
180  {
181    return $tplname;
182  }
183  /** see smarty assign http://www.smarty.net/manual/en/api.assign.php */
184  function assign($tpl_var, $value = null)
185  {
186    $this->smarty->assign( $tpl_var, $value );
187  }
188
189  /**
190   * Inserts the uncompiled code for $handle as the value of $varname in the
191   * root-level. This can be used to effectively include a template in the
192   * middle of another template.
193   * This is equivalent to assign($varname, $this->parse($handle, true))
194   */
195  function assign_var_from_handle($varname, $handle)
196  {
197    $this->assign($varname, $this->parse($handle, true));
198    return true;
199  }
200
201  /** see smarty append http://www.smarty.net/manual/en/api.append.php */
202  function append($tpl_var, $value=null, $merge=false)
203  {
204    $this->smarty->append( $tpl_var, $value, $merge );
205  }
206
207  /**
208   * Root-level variable concatenation. Appends a  string to an existing
209   * variable assignment with the same name.
210   */
211  function concat($tpl_var, $value)
212  {
213    $old_val = & $this->smarty->get_template_vars($tpl_var);
214    if ( isset($old_val) )
215    {
216      $old_val .= $value;
217    }
218    else
219    {
220      $this->assign($tpl_var, $value);
221    }
222  }
223
224  /** see smarty append http://www.smarty.net/manual/en/api.clear_assign.php */
225  function clear_assign($tpl_var)
226  {
227    $this->smarty->clear_assign( $tpl_var );
228  }
229
230  /** see smarty get_template_vars http://www.smarty.net/manual/en/api.get_template_vars.php */
231  function &get_template_vars($name=null)
232  {
233    return $this->smarty->get_template_vars( $name );
234  }
235
236
237  /**
238   * Load the file for the handle, eventually compile the file and run the compiled
239   * code. This will add the output to the results or return the result if $return
240   * is true.
241   */
242  function parse($handle, $return=false)
243  {
244    if ( !isset($this->files[$handle]) )
245    {
246      die("Template->parse(): Couldn't load template file for handle $handle");
247    }
248
249    $this->smarty->assign( 'ROOT_URL', get_root_url() );
250    $this->smarty->assign( 'TAG_INPUT_ENABLED',
251      ((is_adviser()) ? 'disabled="disabled" onclick="return false;"' : ''));
252
253    global $conf, $lang_info;
254    if ( $conf['compiled_template_cache_language'] and isset($lang_info['code']) )
255    {
256      $save_compile_id = $this->smarty->compile_id;
257      $this->smarty->compile_id .= '.'.$lang_info['code'];
258    }
259   
260    $v = $this->smarty->fetch($this->files[$handle], null, null, false);
261   
262    if (isset ($save_compile_id) )
263    {
264      $this->smarty->compile_id = $save_compile_id;
265    }
266     
267    if ($return)
268    {
269      return $v;
270    }
271    $this->output .= $v;
272  }
273
274  /**
275   * Load the file for the handle, eventually compile the file and run the compiled
276   * code. This will print out the results of executing the template.
277   */
278  function pparse($handle)
279  {
280    $this->parse($handle, false);
281    $this->flush();
282  }
283
284  function flush()
285  {
286    if ( count($this->html_head_elements) )
287    {
288      $search = "\n</head>";
289      $pos = strpos( $this->output, $search );
290      if ($pos !== false)
291      {
292        $this->output = substr_replace( $this->output, "\n".implode( "\n", $this->html_head_elements ), $pos, 0 );
293      } //else maybe error or warning ?
294      $this->html_head_elements = array();
295    }
296    echo $this->output;
297    $this->output='';
298  }
299
300  /** flushes the output */
301  function p()
302  {
303    $start = get_moment();
304
305    $this->flush();
306
307    if ($this->smarty->debugging)
308    {
309      global $t2;
310      $this->smarty->assign(
311        array(
312        'AAAA_DEBUG_OUTPUT_TIME__' => get_elapsed_time($start, get_moment()),
313        'AAAA_DEBUG_TOTAL_TIME__' => get_elapsed_time($t2, get_moment())
314        )
315        );
316      require_once(SMARTY_CORE_DIR . 'core.display_debug_console.php');
317      echo smarty_core_display_debug_console(null, $this->smarty);
318    }
319  }
320
321  /**
322   * translate variable modifier - translates a text to the currently loaded
323   * language
324   */
325  /*static*/ function mod_translate($text)
326  {
327    return l10n($text);
328  }
329
330  /**
331   * explode variable modifier - similar to php explode
332   * 'Yes;No'|@explode:';' -> array('Yes', 'No')
333   */
334  /*static*/ function mod_explode($text, $delimiter=',')
335  {
336    return explode($delimiter, $text);
337  }
338 
339  /**
340   * This smarty "html_head" block allows to add content just before
341   * </head> element in the output after the head has been parsed. This is
342   * handy in order to respect strict standards when <style> and <link>
343   * html elements must appear in the <head> element           
344   */
345  function block_html_head($params, $content, &$smarty, &$repeat)
346  {
347    $content = trim($content);
348    if ( !empty($content) )
349    { // second call
350      if ( empty($this->output) )
351      {//page header not parsed yet
352        $this->append('head_elements', $content);
353      }
354      else
355      {
356        $this->html_head_elements[] = $content;
357      }
358    }
359  }
360 
361  /**
362   * Smarty prefilter to allow caching (whenever possible) language strings
363   * from templates.
364   */
365  function prefilter_language($source, &$smarty)
366  {
367    global $lang;
368    $ldq = preg_quote($this->smarty->left_delimiter, '~');
369    $rdq = preg_quote($this->smarty->right_delimiter, '~');
370   
371    $regex = "~$ldq *\'([^'$]+)\'\|@translate *$rdq~";
372    $source = preg_replace( $regex.'e', 'isset($lang[\'$1\']) ? $lang[\'$1\'] : \'$0\'', $source);
373
374    $regex = "~$ldq *\'([^'$]+)\'\|@translate\|~";
375    $source = preg_replace( $regex.'e', 'isset($lang[\'$1\']) ? \'{\'.var_export($lang[\'$1\'],true).\'|\' : \'$0\'', $source);
376
377    return $source;
378  }
379}
380
381/**
382 * This class contains basic functions that can be called directly from the
383 * templates in the form $pwg->l10n('edit')
384 */
385class PwgTemplateAdapter
386{
387  function l10n($text)
388  {
389    return l10n($text);
390  }
391
392  function l10n_dec($s, $p, $v)
393  {
394    return l10n_dec($s, $p, $v);
395  }
396
397  function sprintf()
398  {
399    $args = func_get_args();
400    return call_user_func_array('sprintf',  $args );
401  }
402}
403
404?>
Note: See TracBrowser for help on using the repository browser.