source: tags/release-2_0_0RC4/include/template.class.php @ 8528

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