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

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

feature 1502: Allow to have configuration page for each theme.css.
About string for theme has to be saved in language theme directory (about.html)

File size: 17.9 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    $compile_dir = $conf['local_data_dir'].'/templates_c';
56    mkgetdir( $compile_dir );
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') );
62    $this->smarty->register_modifier( 'explode', array('Template', 'mod_explode') );
63    $this->smarty->register_modifier( 'get_extent', array(&$this, 'get_extent') );
64    $this->smarty->register_block('html_head', array(&$this, 'block_html_head') );
65    $this->smarty->register_function('known_script', array(&$this, 'func_known_script') );
66    $this->smarty->register_prefilter( array('Template', 'prefilter_white_space') );
67    if ( $conf['compiled_template_cache_language'] )
68    {
69      $this->smarty->register_prefilter( array('Template', 'prefilter_language') );
70    }
71
72    $this->smarty->template_dir = array();
73    if ( !empty($theme) )
74    {
75      $this->set_theme($root, $theme, $path);
76      $this->set_prefilter( 'header', array('Template', 'prefilter_local_css') );
77    }
78    else
79      $this->set_template_dir($root);
80
81    $this->smarty->assign('lang_info', $lang_info);
82
83    if (!defined('IN_ADMIN') and isset($conf['extents_for_templates']))
84    {
85      $tpl_extents = unserialize($conf['extents_for_templates']);
86      $this->set_extents($tpl_extents, './template-extension/', true, $theme);
87    }
88  }
89
90  /**
91   * Load theme's parameters.
92   */
93  function set_theme($root, $theme, $path)
94  {
95    $this->set_template_dir($root.'/'.$theme.'/'.$path);
96
97    $themeconf = $this->load_themeconf($root.'/'.$theme);
98
99    if (isset($themeconf['parent']) and $themeconf['parent'] != $theme)
100    {
101      $this->set_theme($root, $themeconf['parent'], $path);
102    }
103
104    $tpl_var = array('id' => $theme);
105    if (!empty($themeconf['local_head']) )
106    {
107      $tpl_var['local_head'] = realpath($root.'/'.$theme.'/'.$themeconf['local_head'] );
108    }
109    $this->smarty->append('themes', $tpl_var);
110    $this->smarty->append('themeconf', $themeconf, true);
111  }
112
113  /**
114   * Add template directory for this Template object.
115   * Set compile id if not exists.
116   */
117  function set_template_dir($dir)
118  {
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    }
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;
146      file_put_contents($this->smarty->compile_dir.'/index.htm', 'Not allowed!');
147  }
148
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))
177      {
178        unset($this->files[$handle]);
179      }
180      else
181      {
182        $this->files[$handle] = $this->get_extent($filename, $handle);
183      }
184    }
185    return true;
186  }
187
188  /**
189   * Sets template extention filename for handles.
190   */
191  function set_extent($filename, $param, $dir='', $overwrite=true, $theme='N/A')
192  {
193    return $this->set_extents(array($filename => $param), $dir, $overwrite);
194  }
195
196  /**
197   * Sets template extentions filenames for handles.
198   * $filename_array should be an hash of filename => array( handle, param) or filename => handle
199   */
200  function set_extents($filename_array, $dir='', $overwrite=true, $theme='N/A')
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];
212        $thm = $value[2];
213      }
214      elseif (is_string($value))
215      {
216        $handle = $value;
217        $param = 'N/A';
218        $thm = 'N/A';
219      }
220      else
221      {
222        return false;
223      }
224
225      if ((stripos(implode('',array_keys($_GET)), '/'.$param) !== false or $param == 'N/A')
226        and ($thm == $theme or $thm == 'N/A')
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  }
235
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  }
245
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 );
250  }
251
252  /**
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  /**
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    {
309      fatal_error("Template->parse(): Couldn't load template file for handle $handle");
310    }
311
312    $this->smarty->assign( 'ROOT_URL', get_root_url() );
313    $this->smarty->assign( 'TAG_INPUT_ENABLED',
314      ((is_adviser()) ? 'disabled="disabled" onclick="return false;"' : ''));
315
316    $save_compile_id = $this->smarty->compile_id;
317    $this->load_external_filters($handle);
318
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    }
324
325    $v = $this->smarty->fetch($this->files[$handle], null, null, false);
326
327    $this->smarty->compile_id = $save_compile_id;
328    $this->unload_external_filters($handle);
329
330    if ($return)
331    {
332      return $v;
333    }
334    $this->output .= $v;
335  }
336
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);
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    }
359
360    echo $this->output;
361    $this->output='';
362  }
363
364  /** flushes the output */
365  function p()
366  {
367    $this->flush();
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    }
380  }
381
382  /**
383   * translate variable modifier - translates a text to the currently loaded
384   * language
385   */
386  static function mod_translate($text)
387  {
388    return l10n($text);
389  }
390
391  /**
392   * explode variable modifier - similar to php explode
393   * 'Yes;No'|@explode:';' -> array('Yes', 'No')
394   */
395  static function mod_explode($text, $delimiter=',')
396  {
397    return explode($delimiter, $text);
398  }
399
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>
404   * html elements must appear in the <head> element
405   */
406  function block_html_head($params, $content, &$smarty, &$repeat)
407  {
408    $content = trim($content);
409    if ( !empty($content) )
410    { // second call
411      $this->html_head_elements[] = $content;
412    }
413  }
414
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
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   */
452  function set_prefilter($handle, $callback, $weight=50)
453  {
454    $this->external_filters[$handle][$weight][] = array('prefilter', $callback);
455    ksort($this->external_filters[$handle]);
456  }
457
458  function set_postfilter($handle, $callback, $weight=50)
459  {
460    $this->external_filters[$handle][$weight][] = array('postfilter', $callback);
461    ksort($this->external_filters[$handle]);
462  }
463
464  function set_outputfilter($handle, $callback, $weight=50)
465  {
466    $this->external_filters[$handle][$weight][] = array('outputfilter', $callback);
467    ksort($this->external_filters[$handle]);
468  }
469
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   */
475  function load_external_filters($handle)
476  {
477    if (isset($this->external_filters[$handle]))
478    {
479      $compile_id = '';
480      foreach ($this->external_filters[$handle] as $filters)
481      {
482        foreach ($filters as $filter)
483        {
484          list($type, $callback) = $filter;
485          $compile_id .= $type.( is_array($callback) ? implode('', $callback) : $callback );
486          call_user_func(array($this->smarty, 'register_'.$type), $callback);
487        }
488      }
489      $this->smarty->compile_id .= '.'.base_convert(crc32($compile_id), 10, 36);
490    }
491  }
492
493  function unload_external_filters($handle)
494  {
495    if (isset($this->external_filters[$handle]))
496    {
497      foreach ($this->external_filters[$handle] as $filters)
498      {
499        foreach ($filters as $filter)
500        {
501          list($type, $callback) = $filter;
502          call_user_func(array($this->smarty, 'unregister_'.$type), $callback);
503        }
504      }
505    }
506  }
507
508  static function prefilter_white_space($source, &$smarty)
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    {
519      array_push($regex, "#^[ \t]+($ldq$tag"."[^$ld$rd]*$rdq)\s*$#m");
520      array_push($regex, "#^[ \t]+($ldq/$tag$rdq)\s*$#m");
521    }
522    $tags = array('include', 'else', 'html_head');
523    foreach($tags as $tag)
524    {
525      array_push($regex, "#^[ \t]+($ldq$tag"."[^$ld$rd]*$rdq)\s*$#m");
526    }
527    $source = preg_replace( $regex, "$1", $source);
528    return $source;
529  }
530
531  /**
532   * Smarty prefilter to allow caching (whenever possible) language strings
533   * from templates.
534   */
535  static function prefilter_language($source, &$smarty)
536  {
537    global $lang;
538    $ldq = preg_quote($smarty->left_delimiter, '~');
539    $rdq = preg_quote($smarty->right_delimiter, '~');
540
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
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
550    return $source;
551  }
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  }
576
577  function load_themeconf($dir)
578  {
579    global $themeconfs, $conf, $page;
580
581    $dir = realpath($dir);
582    if (!isset($themeconfs[$dir]))
583    {
584      $themeconf = array();
585      include($dir.'/themeconf.inc.php');
586      // Put themeconf in cache
587      $themeconfs[$dir] = $themeconf;
588    }
589    return $themeconfs[$dir];
590  }
591}
592
593
594/**
595 * This class contains basic functions that can be called directly from the
596 * templates in the form $pwg->l10n('edit')
597 */
598class PwgTemplateAdapter
599{
600  function l10n($text)
601  {
602    return l10n($text);
603  }
604
605  function l10n_dec($s, $p, $v)
606  {
607    return l10n_dec($s, $p, $v);
608  }
609
610  function sprintf()
611  {
612    $args = func_get_args();
613    return call_user_func_array('sprintf',  $args );
614  }
615}
616
617?>
Note: See TracBrowser for help on using the repository browser.