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

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

bug 860 related: don't try to update the configuration during install because
pwg_query is not available yet.

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