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

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