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

Last change on this file since 5196 was 5196, checked in by plg, 14 years ago

increase copyright year to 2010

File size: 16.7 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based picture gallery                                  |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008-2010 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
28class Template {
29
30  var $smarty;
31
32  var $output = '';
33
34  // Hash of filenames for each template handle.
35  var $files = array();
36
37  // Template extents filenames for each template handle.
38  var $extents = array();
39
40  // Templates prefilter from external sources (plugins)
41  var $external_filters = array();
42
43  // used by html_head smarty block to add content before </head>
44  var $html_head_elements = array();
45
46  function Template($root = ".", $theme= "", $path = "template")
47  {
48    global $conf, $lang_info;
49
50    $this->smarty = new Smarty;
51    $this->smarty->debugging = $conf['debug_template'];
52    $this->smarty->compile_check=$conf['template_compile_check'];
53
54    $compile_dir = $conf['local_data_dir'].'/templates_c';
55    mkgetdir( $compile_dir );
56
57    $this->smarty->compile_dir = $compile_dir;
58
59    $this->smarty->assign_by_ref( 'pwg', new PwgTemplateAdapter() );
60    $this->smarty->register_modifier( 'translate', array('Template', 'mod_translate') );
61    $this->smarty->register_modifier( 'explode', array('Template', 'mod_explode') );
62    $this->smarty->register_modifier( 'get_extent', array(&$this, 'get_extent') );
63    $this->smarty->register_block('html_head', array(&$this, 'block_html_head') );
64    $this->smarty->register_function('known_script', array(&$this, 'func_known_script') );
65    $this->smarty->register_prefilter( array('Template', 'prefilter_white_space') );
66    if ( $conf['compiled_template_cache_language'] )
67    {
68      $this->smarty->register_prefilter( array('Template', 'prefilter_language') );
69    }
70
71    $this->smarty->template_dir = array();
72    if ( !empty($theme) )
73      $this->set_theme($root, $theme, $path);
74    else
75      $this->set_template_dir($root);
76
77    $this->smarty->assign('lang_info', $lang_info);
78
79    if (!defined('IN_ADMIN') and isset($conf['extents_for_templates']))
80    {
81      $tpl_extents = unserialize($conf['extents_for_templates']);
82      $this->set_extents($tpl_extents, './template-extension/', true, $theme);
83    }
84  }
85
86  /**
87   * Load theme's parameters.
88   */
89  function set_theme($root, $theme, $path)
90  {
91    $this->set_template_dir($root.'/'.$theme.'/'.$path);
92
93    include($root.'/'.$theme.'/themeconf.inc.php');
94
95    if (isset($themeconf['parent']) and $themeconf['parent'] != $theme)
96    {
97      $this->set_theme($root, $themeconf['parent'], $path);
98    }
99
100    $tpl_var = array('id' => $theme);
101    if (!empty($themeconf['local_head']) )
102    {
103      $tpl_var['local_head'] = realpath($root.'/'.$theme.'/'.$themeconf['local_head'] );
104    }
105    $this->smarty->append('themes', $tpl_var);
106    $this->smarty->append('themeconf', $themeconf, true);
107  }
108
109  /**
110   * Add template directory for this Template object.
111   * Set compile id if not exists.
112   */
113  function set_template_dir($dir)
114  {
115    $this->smarty->template_dir[] = $dir;
116
117    if (!isset($this->smarty->compile_id))
118    {
119      $real_dir = realpath($dir);
120      $compile_id = crc32( $real_dir===false ? $dir : $real_dir);
121      $this->smarty->compile_id = base_convert($compile_id, 10, 36 );
122    }
123  }
124
125  /**
126   * Gets the template root directory for this Template object.
127   */
128  function get_template_dir()
129  {
130    return $this->smarty->template_dir;
131  }
132
133  /**
134   * Deletes all compiled templates.
135   */
136  function delete_compiled_templates()
137  {
138      $save_compile_id = $this->smarty->compile_id;
139      $this->smarty->compile_id = null;
140      $this->smarty->clear_compiled_tpl();
141      $this->smarty->compile_id = $save_compile_id;
142      file_put_contents($this->smarty->compile_dir.'/index.htm', 'Not allowed!');
143  }
144
145  function get_themeconf($val)
146  {
147    $tc = $this->smarty->get_template_vars('themeconf');
148    return isset($tc[$val]) ? $tc[$val] : '';
149  }
150
151  /**
152   * Sets the template filename for handle.
153   */
154  function set_filename($handle, $filename)
155  {
156    return $this->set_filenames( array($handle=>$filename) );
157  }
158
159  /**
160   * Sets the template filenames for handles. $filename_array should be a
161   * hash of handle => filename pairs.
162   */
163  function set_filenames($filename_array)
164  {
165    if (!is_array($filename_array))
166    {
167      return false;
168    }
169    reset($filename_array);
170    while(list($handle, $filename) = each($filename_array))
171    {
172      if (is_null($filename))
173      {
174        unset($this->files[$handle]);
175      }
176      else
177      {
178        $this->files[$handle] = $this->get_extent($filename, $handle);
179      }
180    }
181    return true;
182  }
183
184  /**
185   * Sets template extention filename for handles.
186   */
187  function set_extent($filename, $param, $dir='', $overwrite=true, $theme='N/A')
188  {
189    return $this->set_extents(array($filename => $param), $dir, $overwrite);
190  }
191
192  /**
193   * Sets template extentions filenames for handles.
194   * $filename_array should be an hash of filename => array( handle, param) or filename => handle
195   */
196  function set_extents($filename_array, $dir='', $overwrite=true, $theme='N/A')
197  {
198    if (!is_array($filename_array))
199    {
200      return false;
201    }
202    foreach ($filename_array as $filename => $value)
203    {
204      if (is_array($value))
205      {
206        $handle = $value[0];
207        $param = $value[1];
208        $thm = $value[2];
209      }
210      elseif (is_string($value))
211      {
212        $handle = $value;
213        $param = 'N/A';
214        $thm = 'N/A';
215      }
216      else
217      {
218        return false;
219      }
220
221      if ((stripos(implode('',array_keys($_GET)), '/'.$param) !== false or $param == 'N/A')
222        and ($thm == $theme)
223        and (!isset($this->extents[$handle]) or $overwrite)
224        and file_exists($dir . $filename))
225      {
226        $this->extents[$handle] = realpath($dir . $filename);
227      }
228    }
229    return true;
230  }
231
232  /** return template extension if exists  */
233  function get_extent($filename='', $handle='')
234  {
235    if (isset($this->extents[$handle]))
236    {
237      $filename = $this->extents[$handle];
238    }
239    return $filename;
240  }
241
242  /** see smarty assign http://www.smarty.net/manual/en/api.assign.php */
243  function assign($tpl_var, $value = null)
244  {
245    $this->smarty->assign( $tpl_var, $value );
246  }
247
248  /**
249   * Inserts the uncompiled code for $handle as the value of $varname in the
250   * root-level. This can be used to effectively include a template in the
251   * middle of another template.
252   * This is equivalent to assign($varname, $this->parse($handle, true))
253   */
254  function assign_var_from_handle($varname, $handle)
255  {
256    $this->assign($varname, $this->parse($handle, true));
257    return true;
258  }
259
260  /** see smarty append http://www.smarty.net/manual/en/api.append.php */
261  function append($tpl_var, $value=null, $merge=false)
262  {
263    $this->smarty->append( $tpl_var, $value, $merge );
264  }
265
266  /**
267   * Root-level variable concatenation. Appends a  string to an existing
268   * variable assignment with the same name.
269   */
270  function concat($tpl_var, $value)
271  {
272    $old_val = & $this->smarty->get_template_vars($tpl_var);
273    if ( isset($old_val) )
274    {
275      $old_val .= $value;
276    }
277    else
278    {
279      $this->assign($tpl_var, $value);
280    }
281  }
282
283  /** see smarty append http://www.smarty.net/manual/en/api.clear_assign.php */
284  function clear_assign($tpl_var)
285  {
286    $this->smarty->clear_assign( $tpl_var );
287  }
288
289  /** see smarty get_template_vars http://www.smarty.net/manual/en/api.get_template_vars.php */
290  function &get_template_vars($name=null)
291  {
292    return $this->smarty->get_template_vars( $name );
293  }
294
295
296  /**
297   * Load the file for the handle, eventually compile the file and run the compiled
298   * code. This will add the output to the results or return the result if $return
299   * is true.
300   */
301  function parse($handle, $return=false)
302  {
303    if ( !isset($this->files[$handle]) )
304    {
305      fatal_error("Template->parse(): Couldn't load template file for handle $handle");
306    }
307
308    $this->smarty->assign( 'ROOT_URL', get_root_url() );
309    $this->smarty->assign( 'TAG_INPUT_ENABLED',
310      ((is_adviser()) ? 'disabled="disabled" onclick="return false;"' : ''));
311
312    $save_compile_id = $this->smarty->compile_id;
313    $this->load_external_filters($handle);
314
315    global $conf, $lang_info;
316    if ( $conf['compiled_template_cache_language'] and isset($lang_info['code']) )
317    {
318      $this->smarty->compile_id .= '.'.$lang_info['code'];
319    }
320
321    $v = $this->smarty->fetch($this->files[$handle], null, null, false);
322
323    $this->smarty->compile_id = $save_compile_id;
324    $this->unload_external_filters($handle);
325
326    if ($return)
327    {
328      return $v;
329    }
330    $this->output .= $v;
331  }
332
333  /**
334   * Load the file for the handle, eventually compile the file and run the compiled
335   * code. This will print out the results of executing the template.
336   */
337  function pparse($handle)
338  {
339    $this->parse($handle, false);
340    $this->flush();
341  }
342
343  function flush()
344  {
345    if ( count($this->html_head_elements) )
346    {
347      $search = "\n</head>";
348      $pos = strpos( $this->output, $search );
349      if ($pos !== false)
350      {
351        $this->output = substr_replace( $this->output, "\n".implode( "\n", $this->html_head_elements ), $pos, 0 );
352      } //else maybe error or warning ?
353      $this->html_head_elements = array();
354    }
355
356    echo $this->output;
357    $this->output='';
358  }
359
360  /** flushes the output */
361  function p()
362  {
363    $this->flush();
364
365    if ($this->smarty->debugging)
366    {
367      global $t2;
368      $this->smarty->assign(
369        array(
370        'AAAA_DEBUG_TOTAL_TIME__' => get_elapsed_time($t2, get_moment())
371        )
372        );
373      require_once(SMARTY_CORE_DIR . 'core.display_debug_console.php');
374      echo smarty_core_display_debug_console(null, $this->smarty);
375    }
376  }
377
378  /**
379   * translate variable modifier - translates a text to the currently loaded
380   * language
381   */
382  static function mod_translate($text)
383  {
384    return l10n($text);
385  }
386
387  /**
388   * explode variable modifier - similar to php explode
389   * 'Yes;No'|@explode:';' -> array('Yes', 'No')
390   */
391  static function mod_explode($text, $delimiter=',')
392  {
393    return explode($delimiter, $text);
394  }
395
396  /**
397   * This smarty "html_head" block allows to add content just before
398   * </head> element in the output after the head has been parsed. This is
399   * handy in order to respect strict standards when <style> and <link>
400   * html elements must appear in the <head> element
401   */
402  function block_html_head($params, $content, &$smarty, &$repeat)
403  {
404    $content = trim($content);
405    if ( !empty($content) )
406    { // second call
407      $this->html_head_elements[] = $content;
408    }
409  }
410
411 /**
412   * This smarty "known_script" functions allows to insert well known java scripts
413   * such as prototype, jquery, etc... only once. Examples:
414   * {known_script id="jquery" src="{$ROOT_URL}template-common/lib/jquery.packed.js"}
415   */
416  function func_known_script($params, &$smarty )
417  {
418    if (!isset($params['id']))
419    {
420        $smarty->trigger_error("known_script: missing 'id' parameter");
421        return;
422    }
423    $id = $params['id'];
424    if (! isset( $this->known_scripts[$id] ) )
425    {
426      if (!isset($params['src']))
427      {
428          $smarty->trigger_error("known_script: missing 'src' parameter");
429          return;
430      }
431      $this->known_scripts[$id] = $params['src'];
432      $content = '<script type="text/javascript" src="'.$params['src'].'"></script>';
433      if (isset($params['now']) and $params['now'] and empty($this->output) )
434      {
435        return $content;
436      }
437      $repeat = false;
438      $this->block_html_head(null, $content, $smarty, $repeat);
439    }
440  }
441
442 /**
443   * This function allows to declare a Smarty prefilter from a plugin, thus allowing
444   * it to modify template source before compilation and without changing core files
445   * They will be processed by weight ascending.
446   * http://www.smarty.net/manual/en/advanced.features.prefilters.php
447   */
448  function set_prefilter($handle, $callback, $weight=50)
449  {
450    $this->external_filters[$handle][$weight][] = array('prefilter', $callback);
451    ksort($this->external_filters[$handle]);
452  }
453
454  function set_postfilter($handle, $callback, $weight=50)
455  {
456    $this->external_filters[$handle][$weight][] = array('postfilter', $callback);
457    ksort($this->external_filters[$handle]);
458  }
459
460  function set_outputfilter($handle, $callback, $weight=50)
461  {
462    $this->external_filters[$handle][$weight][] = array('outputfilter', $callback);
463    ksort($this->external_filters[$handle]);
464  }
465
466 /**
467   * This function actually triggers the filters on the tpl files.
468   * Called in the parse method.
469   * http://www.smarty.net/manual/en/advanced.features.prefilters.php
470   */
471  function load_external_filters($handle)
472  {
473    if (isset($this->external_filters[$handle]))
474    {
475      $compile_id = '';
476      foreach ($this->external_filters[$handle] as $filters)
477      {
478        foreach ($filters as $filter)
479        {
480          list($type, $callback) = $filter;
481          $compile_id .= $type.( is_array($callback) ? implode('', $callback) : $callback );
482          call_user_func(array($this->smarty, 'register_'.$type), $callback);
483        }
484      }
485      $this->smarty->compile_id .= '.'.base_convert(crc32($compile_id), 10, 36);
486    }
487  }
488
489  function unload_external_filters($handle)
490  {
491    if (isset($this->external_filters[$handle]))
492    {
493      foreach ($this->external_filters[$handle] as $filters)
494      {
495        foreach ($filters as $filter)
496        {
497          list($type, $callback) = $filter;
498          call_user_func(array($this->smarty, 'unregister_'.$type), $callback);
499        }
500      }
501    }
502  }
503
504  static function prefilter_white_space($source, &$smarty)
505  {
506    $ld = $smarty->left_delimiter;
507    $rd = $smarty->right_delimiter;
508    $ldq = preg_quote($ld, '#');
509    $rdq = preg_quote($rd, '#');
510
511    $regex = array();
512    $tags = array('if', 'foreach', 'section');
513    foreach($tags as $tag)
514    {
515      array_push($regex, "#^[ \t]+($ldq$tag"."[^$ld$rd]*$rdq)\s*$#m");
516      array_push($regex, "#^[ \t]+($ldq/$tag$rdq)\s*$#m");
517    }
518    $tags = array('include', 'else', 'html_head');
519    foreach($tags as $tag)
520    {
521      array_push($regex, "#^[ \t]+($ldq$tag"."[^$ld$rd]*$rdq)\s*$#m");
522    }
523    $source = preg_replace( $regex, "$1", $source);
524    return $source;
525  }
526
527  /**
528   * Smarty prefilter to allow caching (whenever possible) language strings
529   * from templates.
530   */
531  static function prefilter_language($source, &$smarty)
532  {
533    global $lang;
534    $ldq = preg_quote($smarty->left_delimiter, '~');
535    $rdq = preg_quote($smarty->right_delimiter, '~');
536
537    $regex = "~$ldq *\'([^'$]+)\'\|@translate *$rdq~";
538    $source = preg_replace( $regex.'e', 'isset($lang[\'$1\']) ? $lang[\'$1\'] : \'$0\'', $source);
539
540    $regex = "~$ldq *\'([^'$]+)\'\|@translate\|~";
541    $source = preg_replace( $regex.'e', 'isset($lang[\'$1\']) ? \'{\'.var_export($lang[\'$1\'],true).\'|\' : \'$0\'', $source);
542
543    $regex = "~($ldq *assign +var=.+ +value=)\'([^'$]+)\'\|@translate~e";
544    $source = preg_replace( $regex, 'isset($lang[\'$2\']) ? \'$1\'.var_export($lang[\'$2\'],true) : \'$0\'', $source);
545
546    return $source;
547  }
548}
549
550
551/**
552 * This class contains basic functions that can be called directly from the
553 * templates in the form $pwg->l10n('edit')
554 */
555class PwgTemplateAdapter
556{
557  function l10n($text)
558  {
559    return l10n($text);
560  }
561
562  function l10n_dec($s, $p, $v)
563  {
564    return l10n_dec($s, $p, $v);
565  }
566
567  function sprintf()
568  {
569    $args = func_get_args();
570    return call_user_func_array('sprintf',  $args );
571  }
572}
573
574?>
Note: See TracBrowser for help on using the repository browser.