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

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

bug 860 related: if the directory doesn't exist (SVN users) first try to
create it. To avoid useless checks on filesystem (rvelices should
appreciate) a configuration variable tells if we have to check or not.

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