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

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