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

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

bug 860: display a more readable error when the _data directory is not writable

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