source: branches/2.1/include/template.class.php @ 6314

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

feature 1502: Add $themeconfload_parent_local_head parameter

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