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

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