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

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

feature 1502: $themeconfload_css_parent apply recursively

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