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

Last change on this file since 2632 was 2632, checked in by rub, 16 years ago

Purpose of datepicker with jQuery.
I will open a french topic on forum to debate of implementation and possibles changes.

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