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

Last change on this file since 5230 was 5208, checked in by patdenice, 14 years ago

feature 1522: Move local css local files and local language files to local directory.
Add $conftemplate_force_compile to help developpers.

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