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

Last change on this file since 2497 was 2497, checked in by rvelices, 16 years ago
  • bug 854: better checks of directory creations ( local_data_dir, templates_c, tmp etc...)
  • Property svn:eol-style set to LF
  • Property svn:keywords set to Author Date Id Revision
File size: 12.0 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based picture gallery                                  |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008      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 'smarty/libs/Smarty.class.php';
26
27// migrate lang:XXX
28//    sed "s/{lang:\([^}]\+\)}/{\'\1\'|@translate}/g" my_template.tpl
29// migrate change root level vars {XXX}
30//    sed "s/{pwg_root}/{ROOT_URL}/g" my_template.tpl
31// migrate change root level vars {XXX}
32//    sed "s/{\([a-zA-Z_]\+\)}/{$\1}/g" my_template.tpl
33// migrate all
34//    cat my_template.tpl | sed "s/{lang:\([^}]\+\)}/{\'\1\'|@translate}/g" | sed "s/{pwg_root}/{ROOT_URL}/g" | sed "s/{\([a-zA-Z_]\+\)}/{$\1}/g"
35
36
37class Template {
38
39  var $smarty;
40
41  var $output = '';
42
43  // Hash of filenames for each template handle.
44  var $files = array();
45
46  // used by html_head smarty block to add content before </head>
47  var $html_head_elements = array();
48
49  function Template($root = ".", $theme= "")
50  {
51    global $conf;
52
53    $this->smarty = new Smarty;
54    $this->smarty->debugging = $conf['debug_template'];
55
56    $compile_dir = $conf['local_data_dir'].'/templates_c';
57    mkgetdir( $compile_dir );
58
59    $this->smarty->compile_dir = $compile_dir;
60
61    $this->smarty->assign_by_ref( 'pwg', new PwgTemplateAdapter() );
62    $this->smarty->register_modifier( 'translate', array('Template', 'mod_translate') );
63    $this->smarty->register_modifier( 'explode', array('Template', 'mod_explode') );
64    $this->smarty->register_block('html_head', array(&$this, 'block_html_head') );
65    $this->smarty->register_prefilter( array('Template', 'prefilter_white_space') );
66    if ( $conf['compiled_template_cache_language'] )
67    {
68      $this->smarty->register_prefilter( array('Template', 'prefilter_language') );
69    }
70
71    if ( !empty($theme) )
72    {
73      include($root.'/theme/'.$theme.'/themeconf.inc.php');
74      $this->smarty->assign('themeconf', $themeconf);
75    }
76
77    $this->set_template_dir($root);
78  }
79
80  /**
81   * Sets the template root directory for this Template object.
82   */
83  function set_template_dir($dir)
84  {
85    $this->smarty->template_dir = $dir;
86
87    $real_dir = realpath($dir);
88    $compile_id = crc32( $real_dir===false ? $dir : $real_dir);
89    $this->smarty->compile_id = base_convert($compile_id, 10, 36 );
90  }
91
92  /**
93   * Gets the template root directory for this Template object.
94   */
95  function get_template_dir()
96  {
97    return $this->smarty->template_dir;
98  }
99
100  /**
101   * Deletes all compiled templates.
102   */
103  function delete_compiled_templates()
104  {
105      $save_compile_id = $this->smarty->compile_id;
106      $this->smarty->compile_id = null;
107      $this->smarty->clear_compiled_tpl();
108      $this->smarty->compile_id = $save_compile_id;
109      file_put_contents($this->smarty->compile_dir.'/index.htm', 'Not allowed!');
110  }
111
112  function get_themeconf($val)
113  {
114    $tc = $this->smarty->get_template_vars('themeconf');
115    return isset($tc[$val]) ? $tc[$val] : '';
116  }
117
118  /**
119   * Sets the template filename for handle.
120   */
121  function set_filename($handle, $filename)
122  {
123    return $this->set_filenames( array($handle=>$filename) );
124  }
125
126  /**
127   * Sets the template filenames for handles. $filename_array should be a
128   * hash of handle => filename pairs.
129   */
130  function set_filenames($filename_array)
131  {
132    global $conf;
133    if (!is_array($filename_array))
134    {
135      return false;
136    }
137    reset($filename_array);
138    $tpl_extension = isset($conf['extents_for_templates']) ?
139      unserialize($conf['extents_for_templates']) : array();
140    while(list($handle, $filename) = each($filename_array))
141    {
142      if (is_null($filename))
143        unset( $this->files[$handle] );
144      else
145      {
146        $this->files[$handle] = $filename;
147        foreach ($tpl_extension as $file => $conditions)
148        {
149          $localtpl = './template-extension/' . $file;
150          if ($handle == $conditions[0] and
151             (stripos(implode('/',array_flip($_GET)),$conditions[1])>0
152              or $conditions[1] == 'N/A')
153              and file_exists($localtpl))
154          { /* examples: Are best_rated, created-monthly-calendar, list, ... set? */
155              $this->files[$handle] = '../.' . $localtpl;
156              /* assign their tpl-extension */
157          }
158        }
159      }
160    }
161    return true;
162  }
163
164  /** see smarty assign http://www.smarty.net/manual/en/api.assign.php */
165  function assign($tpl_var, $value = null)
166  {
167    $this->smarty->assign( $tpl_var, $value );
168  }
169
170  /**
171   * Inserts the uncompiled code for $handle as the value of $varname in the
172   * root-level. This can be used to effectively include a template in the
173   * middle of another template.
174   * This is equivalent to assign($varname, $this->parse($handle, true))
175   */
176  function assign_var_from_handle($varname, $handle)
177  {
178    $this->assign($varname, $this->parse($handle, true));
179    return true;
180  }
181
182  /** see smarty append http://www.smarty.net/manual/en/api.append.php */
183  function append($tpl_var, $value=null, $merge=false)
184  {
185    $this->smarty->append( $tpl_var, $value, $merge );
186  }
187
188  /**
189   * Root-level variable concatenation. Appends a  string to an existing
190   * variable assignment with the same name.
191   */
192  function concat($tpl_var, $value)
193  {
194    $old_val = & $this->smarty->get_template_vars($tpl_var);
195    if ( isset($old_val) )
196    {
197      $old_val .= $value;
198    }
199    else
200    {
201      $this->assign($tpl_var, $value);
202    }
203  }
204
205  /** see smarty append http://www.smarty.net/manual/en/api.clear_assign.php */
206  function clear_assign($tpl_var)
207  {
208    $this->smarty->clear_assign( $tpl_var );
209  }
210
211  /** see smarty get_template_vars http://www.smarty.net/manual/en/api.get_template_vars.php */
212  function &get_template_vars($name=null)
213  {
214    return $this->smarty->get_template_vars( $name );
215  }
216
217
218  /**
219   * Load the file for the handle, eventually compile the file and run the compiled
220   * code. This will add the output to the results or return the result if $return
221   * is true.
222   */
223  function parse($handle, $return=false)
224  {
225    if ( !isset($this->files[$handle]) )
226    {
227      trigger_error("Template->parse(): Couldn't load template file for handle $handle", E_USER_ERROR);
228    }
229
230    $this->smarty->assign( 'ROOT_URL', get_root_url() );
231    $this->smarty->assign( 'TAG_INPUT_ENABLED',
232      ((is_adviser()) ? 'disabled="disabled" onclick="return false;"' : ''));
233
234    global $conf, $lang_info;
235    if ( $conf['compiled_template_cache_language'] and isset($lang_info['code']) )
236    {
237      $save_compile_id = $this->smarty->compile_id;
238      $this->smarty->compile_id .= '.'.$lang_info['code'];
239    }
240
241    $v = $this->smarty->fetch($this->files[$handle], null, null, false);
242
243    if (isset ($save_compile_id) )
244    {
245      $this->smarty->compile_id = $save_compile_id;
246    }
247
248    if ($return)
249    {
250      return $v;
251    }
252    $this->output .= $v;
253  }
254
255  /**
256   * Load the file for the handle, eventually compile the file and run the compiled
257   * code. This will print out the results of executing the template.
258   */
259  function pparse($handle)
260  {
261    $this->parse($handle, false);
262    $this->flush();
263  }
264
265  function flush()
266  {
267    if ( count($this->html_head_elements) )
268    {
269      $search = "\n</head>";
270      $pos = strpos( $this->output, $search );
271      if ($pos !== false)
272      {
273        $this->output = substr_replace( $this->output, "\n".implode( "\n", $this->html_head_elements ), $pos, 0 );
274      } //else maybe error or warning ?
275      $this->html_head_elements = array();
276    }
277    echo $this->output;
278    $this->output='';
279  }
280
281  /** flushes the output */
282  function p()
283  {
284    $start = get_moment();
285
286    $this->flush();
287
288    if ($this->smarty->debugging)
289    {
290      global $t2;
291      $this->smarty->assign(
292        array(
293        'AAAA_DEBUG_OUTPUT_TIME__' => get_elapsed_time($start, get_moment()),
294        'AAAA_DEBUG_TOTAL_TIME__' => get_elapsed_time($t2, get_moment())
295        )
296        );
297      require_once(SMARTY_CORE_DIR . 'core.display_debug_console.php');
298      echo smarty_core_display_debug_console(null, $this->smarty);
299    }
300  }
301
302  /**
303   * translate variable modifier - translates a text to the currently loaded
304   * language
305   */
306  /*static*/ function mod_translate($text)
307  {
308    return l10n($text);
309  }
310
311  /**
312   * explode variable modifier - similar to php explode
313   * 'Yes;No'|@explode:';' -> array('Yes', 'No')
314   */
315  /*static*/ function mod_explode($text, $delimiter=',')
316  {
317    return explode($delimiter, $text);
318  }
319
320  /**
321   * This smarty "html_head" block allows to add content just before
322   * </head> element in the output after the head has been parsed. This is
323   * handy in order to respect strict standards when <style> and <link>
324   * html elements must appear in the <head> element
325   */
326  function block_html_head($params, $content, &$smarty, &$repeat)
327  {
328    $content = trim($content);
329    if ( !empty($content) )
330    { // second call
331      if ( empty($this->output) )
332      {//page header not parsed yet
333        $this->append('head_elements', $content);
334      }
335      else
336      {
337        $this->html_head_elements[] = $content;
338      }
339    }
340  }
341
342  /*static */ function prefilter_white_space($source, &$smarty)
343  {
344    $ld = $smarty->left_delimiter;
345    $rd = $smarty->right_delimiter;
346    $ldq = preg_quote($ld, '#');
347    $rdq = preg_quote($rd, '#');
348
349    $regex = array();
350    $tags = array('if', 'foreach', 'section');
351    foreach($tags as $tag)
352    {
353      array_push($regex, "#^[ \t]+($ldq$tag"."[^$ld$rd]*$rdq)\s*$#m");
354      array_push($regex, "#^[ \t]+($ldq/$tag$rdq)\s*$#m");
355    }
356    $tags = array('include', 'else', 'html_head');
357    foreach($tags as $tag)
358    {
359      array_push($regex, "#^[ \t]+($ldq$tag"."[^$ld$rd]*$rdq)\s*$#m");
360    }
361    $source = preg_replace( $regex, "$1", $source);
362    return $source;
363  }
364
365  /**
366   * Smarty prefilter to allow caching (whenever possible) language strings
367   * from templates.
368   */
369  /*static */ function prefilter_language($source, &$smarty)
370  {
371    global $lang;
372    $ldq = preg_quote($smarty->left_delimiter, '~');
373    $rdq = preg_quote($smarty->right_delimiter, '~');
374
375    $regex = "~$ldq *\'([^'$]+)\'\|@translate *$rdq~";
376    $source = preg_replace( $regex.'e', 'isset($lang[\'$1\']) ? $lang[\'$1\'] : \'$0\'', $source);
377
378    $regex = "~$ldq *\'([^'$]+)\'\|@translate\|~";
379    $source = preg_replace( $regex.'e', 'isset($lang[\'$1\']) ? \'{\'.var_export($lang[\'$1\'],true).\'|\' : \'$0\'', $source);
380
381    return $source;
382  }
383}
384
385/**
386 * This class contains basic functions that can be called directly from the
387 * templates in the form $pwg->l10n('edit')
388 */
389class PwgTemplateAdapter
390{
391  function l10n($text)
392  {
393    return l10n($text);
394  }
395
396  function l10n_dec($s, $p, $v)
397  {
398    return l10n_dec($s, $p, $v);
399  }
400
401  function sprintf()
402  {
403    $args = func_get_args();
404    return call_user_func_array('sprintf',  $args );
405  }
406}
407
408?>
Note: See TracBrowser for help on using the repository browser.