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

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

remove all svn:mergeinfo properties

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