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

Last change on this file since 2536 was 2536, checked in by nikrou, 16 years ago

real static param

  • Property svn:eol-style set to LF
  • Property svn:keywords set to Author Date Id Revision
File size: 13.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    $compile_dir = $conf['local_data_dir'].'/templates_c';
57    mkgetdir( $compile_dir );
58
59    $this->smarty->compile_dir = $compile_dir;
60
61    $this->smarty->assign_by_ref( 'pwg', new PwgTemplateAdapter() );
62    $this->smarty->register_modifier( 'translate', array('Template', 'mod_translate') );
63    $this->smarty->register_modifier( 'explode', array('Template', 'mod_explode') );
64    $this->smarty->register_block('html_head', array(&$this, 'block_html_head') );
65    $this->smarty->register_function('known_script', array(&$this, 'func_known_script') );
66    $this->smarty->register_prefilter( array('Template', 'prefilter_white_space') );
67    if ( $conf['compiled_template_cache_language'] )
68    {
69      $this->smarty->register_prefilter( array('Template', 'prefilter_language') );
70    }
71
72    if ( !empty($theme) )
73    {
74      include($root.'/theme/'.$theme.'/themeconf.inc.php');
75      $this->smarty->assign('themeconf', $themeconf);
76    }
77
78    $this->set_template_dir($root);
79  }
80
81  /**
82   * Sets the template root directory for this Template object.
83   */
84  function set_template_dir($dir)
85  {
86    $this->smarty->template_dir = $dir;
87
88    $real_dir = realpath($dir);
89    $compile_id = crc32( $real_dir===false ? $dir : $real_dir);
90    $this->smarty->compile_id = base_convert($compile_id, 10, 36 );
91  }
92
93  /**
94   * Gets the template root directory for this Template object.
95   */
96  function get_template_dir()
97  {
98    return $this->smarty->template_dir;
99  }
100
101  /**
102   * Deletes all compiled templates.
103   */
104  function delete_compiled_templates()
105  {
106      $save_compile_id = $this->smarty->compile_id;
107      $this->smarty->compile_id = null;
108      $this->smarty->clear_compiled_tpl();
109      $this->smarty->compile_id = $save_compile_id;
110      file_put_contents($this->smarty->compile_dir.'/index.htm', 'Not allowed!');
111  }
112
113  function get_themeconf($val)
114  {
115    $tc = $this->smarty->get_template_vars('themeconf');
116    return isset($tc[$val]) ? $tc[$val] : '';
117  }
118
119  /**
120   * Sets the template filename for handle.
121   */
122  function set_filename($handle, $filename)
123  {
124    return $this->set_filenames( array($handle=>$filename) );
125  }
126
127  /**
128   * Sets the template filenames for handles. $filename_array should be a
129   * hash of handle => filename pairs.
130   */
131  function set_filenames($filename_array)
132  {
133    global $conf;
134    if (!is_array($filename_array))
135    {
136      return false;
137    }
138    reset($filename_array);
139    $tpl_extension = isset($conf['extents_for_templates']) ?
140      unserialize($conf['extents_for_templates']) : array();
141    while(list($handle, $filename) = each($filename_array))
142    {
143      if (is_null($filename))
144        unset( $this->files[$handle] );
145      else
146      {
147        $this->files[$handle] = $filename;
148        foreach ($tpl_extension as $file => $conditions)
149        {
150          $localtpl = './template-extension/' . $file;
151          if ($handle == $conditions[0] and
152             (stripos(implode('/',array_flip($_GET)),$conditions[1])>0
153              or $conditions[1] == 'N/A')
154              and file_exists($localtpl))
155          { /* examples: Are best_rated, created-monthly-calendar, list, ... set? */
156              $this->files[$handle] = '../.' . $localtpl;
157              /* assign their tpl-extension */
158          }
159        }
160      }
161    }
162    return true;
163  }
164
165  /** see smarty assign http://www.smarty.net/manual/en/api.assign.php */
166  function assign($tpl_var, $value = null)
167  {
168    $this->smarty->assign( $tpl_var, $value );
169  }
170
171  /**
172   * Inserts the uncompiled code for $handle as the value of $varname in the
173   * root-level. This can be used to effectively include a template in the
174   * middle of another template.
175   * This is equivalent to assign($varname, $this->parse($handle, true))
176   */
177  function assign_var_from_handle($varname, $handle)
178  {
179    $this->assign($varname, $this->parse($handle, true));
180    return true;
181  }
182
183  /** see smarty append http://www.smarty.net/manual/en/api.append.php */
184  function append($tpl_var, $value=null, $merge=false)
185  {
186    $this->smarty->append( $tpl_var, $value, $merge );
187  }
188
189  /**
190   * Root-level variable concatenation. Appends a  string to an existing
191   * variable assignment with the same name.
192   */
193  function concat($tpl_var, $value)
194  {
195    $old_val = & $this->smarty->get_template_vars($tpl_var);
196    if ( isset($old_val) )
197    {
198      $old_val .= $value;
199    }
200    else
201    {
202      $this->assign($tpl_var, $value);
203    }
204  }
205
206  /** see smarty append http://www.smarty.net/manual/en/api.clear_assign.php */
207  function clear_assign($tpl_var)
208  {
209    $this->smarty->clear_assign( $tpl_var );
210  }
211
212  /** see smarty get_template_vars http://www.smarty.net/manual/en/api.get_template_vars.php */
213  function &get_template_vars($name=null)
214  {
215    return $this->smarty->get_template_vars( $name );
216  }
217
218
219  /**
220   * Load the file for the handle, eventually compile the file and run the compiled
221   * code. This will add the output to the results or return the result if $return
222   * is true.
223   */
224  function parse($handle, $return=false)
225  {
226    if ( !isset($this->files[$handle]) )
227    {
228      fatal_error("Template->parse(): Couldn't load template file for handle $handle");
229    }
230
231    $this->smarty->assign( 'ROOT_URL', get_root_url() );
232    $this->smarty->assign( 'TAG_INPUT_ENABLED',
233      ((is_adviser()) ? 'disabled="disabled" onclick="return false;"' : ''));
234
235    global $conf, $lang_info;
236    if ( $conf['compiled_template_cache_language'] and isset($lang_info['code']) )
237    {
238      $save_compile_id = $this->smarty->compile_id;
239      $this->smarty->compile_id .= '.'.$lang_info['code'];
240    }
241
242    $v = $this->smarty->fetch($this->files[$handle], null, null, false);
243
244    if (isset ($save_compile_id) )
245    {
246      $this->smarty->compile_id = $save_compile_id;
247    }
248
249    if ($return)
250    {
251      return $v;
252    }
253    $this->output .= $v;
254  }
255
256  /**
257   * Load the file for the handle, eventually compile the file and run the compiled
258   * code. This will print out the results of executing the template.
259   */
260  function pparse($handle)
261  {
262    $this->parse($handle, false);
263    $this->flush();
264  }
265
266  function flush()
267  {
268    if ( count($this->html_head_elements) )
269    {
270      $search = "\n</head>";
271      $pos = strpos( $this->output, $search );
272      if ($pos !== false)
273      {
274        $this->output = substr_replace( $this->output, "\n".implode( "\n", $this->html_head_elements ), $pos, 0 );
275      } //else maybe error or warning ?
276      $this->html_head_elements = array();
277    }
278    echo $this->output;
279    $this->output='';
280  }
281
282  /** flushes the output */
283  function p()
284  {
285    $start = get_moment();
286
287    $this->flush();
288
289    if ($this->smarty->debugging)
290    {
291      global $t2;
292      $this->smarty->assign(
293        array(
294        'AAAA_DEBUG_OUTPUT_TIME__' => get_elapsed_time($start, get_moment()),
295        'AAAA_DEBUG_TOTAL_TIME__' => get_elapsed_time($t2, get_moment())
296        )
297        );
298      require_once(SMARTY_CORE_DIR . 'core.display_debug_console.php');
299      echo smarty_core_display_debug_console(null, $this->smarty);
300    }
301  }
302
303  /**
304   * translate variable modifier - translates a text to the currently loaded
305   * language
306   */
307  static function mod_translate($text)
308  {
309    return l10n($text);
310  }
311
312  /**
313   * explode variable modifier - similar to php explode
314   * 'Yes;No'|@explode:';' -> array('Yes', 'No')
315   */
316  static function mod_explode($text, $delimiter=',')
317  {
318    return explode($delimiter, $text);
319  }
320
321  /**
322   * This smarty "html_head" block allows to add content just before
323   * </head> element in the output after the head has been parsed. This is
324   * handy in order to respect strict standards when <style> and <link>
325   * html elements must appear in the <head> element
326   */
327  function block_html_head($params, $content, &$smarty, &$repeat)
328  {
329    $content = trim($content);
330    if ( !empty($content) )
331    { // second call
332      if ( empty($this->output) )
333      {//page header not parsed yet
334        $this->append('head_elements', $content);
335      }
336      else
337      {
338        $this->html_head_elements[] = $content;
339      }
340    }
341  }
342
343 /**
344   * This smarty "known_script" functions allows to insert well known java scripts
345   * such as prototype, jquery, etc... only once. Examples:
346   * {known_script id="jquery" src="{$ROOT_URL}template-common/lib/jquery.packed.js"}
347   */
348  function func_known_script($params, &$smarty )
349  {
350    if (!isset($params['id']))
351    {
352        $smarty->trigger_error("known_script: missing 'id' parameter");
353        return;
354    }
355    $id = $params['id'];
356    if (! isset( $this->known_scripts[$id] ) )
357    {
358      if (!isset($params['src']))
359      {
360          $smarty->trigger_error("known_script: missing 'src' parameter");
361          return;
362      }
363      $this->known_scripts[$id] = $params['src'];
364      $content = '<script type="text/javascript" src="'.$params['src'].'"></script>';
365      if (isset($params['now']) and $params['now'] and empty($this->output) )
366      {
367        return $content;
368      }
369      $repeat = false;
370      $this->block_html_head(null, $content, $smarty, $repeat);
371    }
372  }
373
374  static function prefilter_white_space($source, &$smarty)
375  {
376    $ld = $smarty->left_delimiter;
377    $rd = $smarty->right_delimiter;
378    $ldq = preg_quote($ld, '#');
379    $rdq = preg_quote($rd, '#');
380
381    $regex = array();
382    $tags = array('if', 'foreach', 'section');
383    foreach($tags as $tag)
384    {
385      array_push($regex, "#^[ \t]+($ldq$tag"."[^$ld$rd]*$rdq)\s*$#m");
386      array_push($regex, "#^[ \t]+($ldq/$tag$rdq)\s*$#m");
387    }
388    $tags = array('include', 'else', 'html_head');
389    foreach($tags as $tag)
390    {
391      array_push($regex, "#^[ \t]+($ldq$tag"."[^$ld$rd]*$rdq)\s*$#m");
392    }
393    $source = preg_replace( $regex, "$1", $source);
394    return $source;
395  }
396
397  /**
398   * Smarty prefilter to allow caching (whenever possible) language strings
399   * from templates.
400   */
401  static function prefilter_language($source, &$smarty)
402  {
403    global $lang;
404    $ldq = preg_quote($smarty->left_delimiter, '~');
405    $rdq = preg_quote($smarty->right_delimiter, '~');
406
407    $regex = "~$ldq *\'([^'$]+)\'\|@translate *$rdq~";
408    $source = preg_replace( $regex.'e', 'isset($lang[\'$1\']) ? $lang[\'$1\'] : \'$0\'', $source);
409
410    $regex = "~$ldq *\'([^'$]+)\'\|@translate\|~";
411    $source = preg_replace( $regex.'e', 'isset($lang[\'$1\']) ? \'{\'.var_export($lang[\'$1\'],true).\'|\' : \'$0\'', $source);
412
413    return $source;
414  }
415}
416
417/**
418 * This class contains basic functions that can be called directly from the
419 * templates in the form $pwg->l10n('edit')
420 */
421class PwgTemplateAdapter
422{
423  function l10n($text)
424  {
425    return l10n($text);
426  }
427
428  function l10n_dec($s, $p, $v)
429  {
430    return l10n_dec($s, $p, $v);
431  }
432
433  function sprintf()
434  {
435    $args = func_get_args();
436    return call_user_func_array('sprintf',  $args );
437  }
438}
439
440?>
Note: See TracBrowser for help on using the repository browser.