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

Last change on this file since 23688 was 23688, checked in by rvelices, 11 years ago

replace the language_prefilter with a postfilter (now that smarty has modifiercompiler feature, there is no need for prefilter)

  • Property svn:eol-style set to LF
File size: 42.3 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based photo gallery                                    |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008-2013 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
24define('BUTTONS_RANK_NEUTRAL', 50);
25
26class Template {
27
28  var $smarty;
29
30  var $output = '';
31
32  // Hash of filenames for each template handle.
33  var $files = array();
34
35  // Template extents filenames for each template handle.
36  var $extents = array();
37
38  // Templates prefilter from external sources (plugins)
39  var $external_filters = array();
40
41  // used by html_head smarty block to add content before </head>
42  var $html_head_elements = array();
43  private $html_style = '';
44
45  const COMBINED_SCRIPTS_TAG = '<!-- COMBINED_SCRIPTS -->';
46  var $scriptLoader;
47
48  const COMBINED_CSS_TAG = '<!-- COMBINED_CSS -->';
49  var $css_by_priority = array();
50
51  var $picture_buttons = array();
52  var $index_buttons = array();
53
54  function Template($root = ".", $theme= "", $path = "template")
55  {
56    global $conf, $lang_info;
57
58    SmartyException::$escape = false;
59
60    $this->scriptLoader = new ScriptLoader;
61    $this->smarty = new SmartyBC;
62    $this->smarty->debugging = $conf['debug_template'];
63    if (!$this->smarty->debugging)
64      $this->smarty->error_reporting = error_reporting() & ~E_NOTICE;
65    $this->smarty->compile_check = $conf['template_compile_check'];
66    $this->smarty->force_compile = $conf['template_force_compile'];
67
68    if (!isset($conf['data_dir_checked']))
69    {
70      $dir = PHPWG_ROOT_PATH.$conf['data_location'];
71      mkgetdir($dir, MKGETDIR_DEFAULT&~MKGETDIR_DIE_ON_ERROR);
72      if (!is_writable($dir))
73      {
74        load_language('admin.lang');
75        fatal_error(
76          sprintf(
77            l10n('Give write access (chmod 777) to "%s" directory at the root of your Piwigo installation'),
78            $conf['data_location']
79            ),
80          l10n('an error happened'),
81          false // show trace
82          );
83      }
84      if (function_exists('pwg_query')) {
85        conf_update_param('data_dir_checked', 1);
86      }
87    }
88
89    $compile_dir = PHPWG_ROOT_PATH.$conf['data_location'].'templates_c';
90    mkgetdir( $compile_dir );
91
92    $this->smarty->setCompileDir($compile_dir);
93
94    $this->smarty->assign( 'pwg', new PwgTemplateAdapter() );
95    $this->smarty->registerPlugin('modifiercompiler', 'translate', array('Template', 'modcompiler_translate') );
96    $this->smarty->registerPlugin('modifiercompiler', 'translate_dec', array('Template', 'modcompiler_translate_dec') );
97    $this->smarty->registerPlugin('modifier', 'explode', array('Template', 'mod_explode') );
98    $this->smarty->registerPlugin( 'modifier', 'get_extent', array($this, 'get_extent') );
99    $this->smarty->registerPlugin('block', 'html_head', array($this, 'block_html_head') );
100    $this->smarty->registerPlugin('block', 'html_style', array($this, 'block_html_style') );
101    $this->smarty->registerPlugin('function', 'combine_script', array($this, 'func_combine_script') );
102    $this->smarty->registerPlugin('function', 'get_combined_scripts', array($this, 'func_get_combined_scripts') );
103    $this->smarty->registerPlugin('function', 'combine_css', array($this, 'func_combine_css') );
104    $this->smarty->registerPlugin('function', 'define_derivative', array($this, 'func_define_derivative') );
105    $this->smarty->registerPlugin('compiler', 'get_combined_css', array($this, 'func_get_combined_css') );
106    $this->smarty->registerPlugin('block', 'footer_script', array($this, 'block_footer_script') );
107    $this->smarty->registerFilter('pre', array('Template', 'prefilter_white_space') );
108    if ( $conf['compiled_template_cache_language'] )
109    {
110      $this->smarty->registerFilter('post', array('Template', 'postfilter_language') );
111    }
112
113    $this->smarty->setTemplateDir(array());
114    if ( !empty($theme) )
115    {
116      $this->set_theme($root, $theme, $path);
117      if (!defined('IN_ADMIN'))
118      {
119        $this->set_prefilter( 'header', array('Template', 'prefilter_local_css') );
120      }
121    }
122    else
123      $this->set_template_dir($root);
124
125    $this->smarty->assign('lang_info', $lang_info);
126
127    if (!defined('IN_ADMIN') and isset($conf['extents_for_templates']))
128    {
129      $tpl_extents = unserialize($conf['extents_for_templates']);
130      $this->set_extents($tpl_extents, './template-extension/', true, $theme);
131    }
132  }
133
134  /**
135   * Load theme's parameters.
136   */
137  function set_theme($root, $theme, $path, $load_css=true, $load_local_head=true)
138  {
139    $this->set_template_dir($root.'/'.$theme.'/'.$path);
140
141    $themeconf = $this->load_themeconf($root.'/'.$theme);
142
143    if (isset($themeconf['parent']) and $themeconf['parent'] != $theme)
144    {
145      $this->set_theme(
146        $root,
147        $themeconf['parent'],
148        $path,
149        isset($themeconf['load_parent_css']) ? $themeconf['load_parent_css'] : $load_css,
150        isset($themeconf['load_parent_local_head']) ? $themeconf['load_parent_local_head'] : $load_local_head
151      );
152    }
153
154    $tpl_var = array(
155      'id' => $theme,
156      'load_css' => $load_css,
157    );
158    if (!empty($themeconf['local_head']) and $load_local_head)
159    {
160      $tpl_var['local_head'] = realpath($root.'/'.$theme.'/'.$themeconf['local_head'] );
161    }
162    $themeconf['id'] = $theme;
163    $this->smarty->append('themes', $tpl_var);
164    $this->smarty->append('themeconf', $themeconf, true);
165  }
166
167  /**
168   * Add template directory for this Template object.
169   * Set compile id if not exists.
170   */
171  function set_template_dir($dir)
172  {
173    $this->smarty->addTemplateDir($dir);
174
175    if (!isset($this->smarty->compile_id))
176    {
177      $compile_id = "1";
178      $compile_id .= ($real_dir = realpath($dir))===false ? $dir : $real_dir;
179      $this->smarty->compile_id = base_convert(crc32($compile_id), 10, 36 );
180    }
181  }
182
183  /**
184   * Gets the template root directory for this Template object.
185   */
186  function get_template_dir()
187  {
188    return $this->smarty->getTemplateDir();
189  }
190
191  /**
192   * Deletes all compiled templates.
193   */
194  function delete_compiled_templates()
195  {
196      $save_compile_id = $this->smarty->compile_id;
197      $this->smarty->compile_id = null;
198      $this->smarty->clearCompiledTemplate();
199      $this->smarty->compile_id = $save_compile_id;
200      file_put_contents($this->smarty->getCompileDir().'/index.htm', 'Not allowed!');
201  }
202
203  function get_themeconf($val)
204  {
205    $tc = $this->smarty->getTemplateVars('themeconf');
206    return isset($tc[$val]) ? $tc[$val] : '';
207  }
208
209  /**
210   * Sets the template filename for handle.
211   */
212  function set_filename($handle, $filename)
213  {
214    return $this->set_filenames( array($handle=>$filename) );
215  }
216
217  /**
218   * Sets the template filenames for handles. $filename_array should be a
219   * hash of handle => filename pairs.
220   */
221  function set_filenames($filename_array)
222  {
223    if (!is_array($filename_array))
224    {
225      return false;
226    }
227    reset($filename_array);
228    while(list($handle, $filename) = each($filename_array))
229    {
230      if (is_null($filename))
231      {
232        unset($this->files[$handle]);
233      }
234      else
235      {
236        $this->files[$handle] = $this->get_extent($filename, $handle);
237      }
238    }
239    return true;
240  }
241
242  /**
243   * Sets template extention filename for handles.
244   */
245  function set_extent($filename, $param, $dir='', $overwrite=true, $theme='N/A')
246  {
247    return $this->set_extents(array($filename => $param), $dir, $overwrite);
248  }
249
250  /**
251   * Sets template extentions filenames for handles.
252   * $filename_array should be an hash of filename => array( handle, param) or filename => handle
253   */
254  function set_extents($filename_array, $dir='', $overwrite=true, $theme='N/A')
255  {
256    if (!is_array($filename_array))
257    {
258      return false;
259    }
260    foreach ($filename_array as $filename => $value)
261    {
262      if (is_array($value))
263      {
264        $handle = $value[0];
265        $param = $value[1];
266        $thm = $value[2];
267      }
268      elseif (is_string($value))
269      {
270        $handle = $value;
271        $param = 'N/A';
272        $thm = 'N/A';
273      }
274      else
275      {
276        return false;
277      }
278
279      if ((stripos(implode('',array_keys($_GET)), '/'.$param) !== false or $param == 'N/A')
280        and ($thm == $theme or $thm == 'N/A')
281        and (!isset($this->extents[$handle]) or $overwrite)
282        and file_exists($dir . $filename))
283      {
284        $this->extents[$handle] = realpath($dir . $filename);
285      }
286    }
287    return true;
288  }
289
290  /** return template extension if exists  */
291  function get_extent($filename='', $handle='')
292  {
293    if (isset($this->extents[$handle]))
294    {
295      $filename = $this->extents[$handle];
296    }
297    return $filename;
298  }
299
300  /** see smarty assign http://www.smarty.net/manual/en/api.assign.php */
301  function assign($tpl_var, $value = null)
302  {
303    $this->smarty->assign( $tpl_var, $value );
304  }
305
306  /**
307   * Inserts the uncompiled code for $handle as the value of $varname in the
308   * root-level. This can be used to effectively include a template in the
309   * middle of another template.
310   * This is equivalent to assign($varname, $this->parse($handle, true))
311   */
312  function assign_var_from_handle($varname, $handle)
313  {
314    $this->assign($varname, $this->parse($handle, true));
315    return true;
316  }
317
318  /** see smarty append http://www.smarty.net/manual/en/api.append.php */
319  function append($tpl_var, $value=null, $merge=false)
320  {
321    $this->smarty->append( $tpl_var, $value, $merge );
322  }
323
324  /**
325   * Root-level variable concatenation. Appends a  string to an existing
326   * variable assignment with the same name.
327   */
328  function concat($tpl_var, $value)
329  {
330    $this->assign($tpl_var,
331      $this->smarty->getTemplateVars($tpl_var) . $value);
332  }
333
334  /** see smarty append http://www.smarty.net/manual/en/api.clear_assign.php */
335  function clear_assign($tpl_var)
336  {
337    $this->smarty->clearAssign( $tpl_var );
338  }
339
340  /** see smarty get_template_vars http://www.smarty.net/manual/en/api.get_template_vars.php */
341  function get_template_vars($name=null)
342  {
343    return $this->smarty->getTemplateVars( $name );
344  }
345
346
347  /**
348   * Load the file for the handle, eventually compile the file and run the compiled
349   * code. This will add the output to the results or return the result if $return
350   * is true.
351   */
352  function parse($handle, $return=false)
353  {
354    if ( !isset($this->files[$handle]) )
355    {
356      fatal_error("Template->parse(): Couldn't load template file for handle $handle");
357    }
358
359    $this->smarty->assign( 'ROOT_URL', get_root_url() );
360
361    $save_compile_id = $this->smarty->compile_id;
362    $this->load_external_filters($handle);
363
364    global $conf, $lang_info;
365    if ( $conf['compiled_template_cache_language'] and isset($lang_info['code']) )
366    {
367      $this->smarty->compile_id .= '_'.$lang_info['code'];
368    }
369
370    $v = $this->smarty->fetch($this->files[$handle]);
371
372    $this->smarty->compile_id = $save_compile_id;
373    $this->unload_external_filters($handle);
374
375    if ($return)
376    {
377      return $v;
378    }
379    $this->output .= $v;
380  }
381
382  /**
383   * Load the file for the handle, eventually compile the file and run the compiled
384   * code. This will print out the results of executing the template.
385   */
386  function pparse($handle)
387  {
388    $this->parse($handle, false);
389    $this->flush();
390  }
391
392  function flush()
393  {
394    if (!$this->scriptLoader->did_head())
395    {
396      $pos = strpos( $this->output, self::COMBINED_SCRIPTS_TAG );
397      if ($pos !== false)
398      {
399          $scripts = $this->scriptLoader->get_head_scripts();
400          $content = array();
401          foreach ($scripts as $script)
402          {
403              $content[]=
404                  '<script type="text/javascript" src="'
405                  . self::make_script_src($script)
406                  .'"></script>';
407          }
408
409          $this->output = substr_replace( $this->output, implode( "\n", $content ), $pos, strlen(self::COMBINED_SCRIPTS_TAG) );
410      } //else maybe error or warning ?
411    }
412
413    if(!empty($this->css_by_priority))
414    {
415      ksort($this->css_by_priority);
416
417      global $conf;
418      $css = array();
419      if ($conf['template_combine_files'])
420      {
421        $combiner = new FileCombiner('css');
422        foreach ($this->css_by_priority as $files)
423        {
424          foreach ($files as $file_ver)
425            $combiner->add( $file_ver[0], $file_ver[1] );
426        }
427        if ( $combiner->combine( $out_file, $out_version) )
428          $css[] = array($out_file, $out_version);
429      }
430      else
431      {
432        foreach ($this->css_by_priority as $files)
433          $css = array_merge($css, $files);
434      }
435
436      $content = array();
437      foreach( $css as $file_ver )
438      {
439        $href = embellish_url(get_root_url().$file_ver[0]);
440        if ($file_ver[1] !== false)
441          $href .= '?v' . ($file_ver[1] ? $file_ver[1] : PHPWG_VERSION);
442        // trigger the event for eventual use of a cdn
443        $href = trigger_event('combined_css', $href, $file_ver[0], $file_ver[1]);
444        $content[] = '<link rel="stylesheet" type="text/css" href="'.$href.'">';
445      }
446      $this->output = str_replace(self::COMBINED_CSS_TAG,
447          implode( "\n", $content ),
448          $this->output );
449                        $this->css_by_priority = array();
450    }
451
452    if ( count($this->html_head_elements) || strlen($this->html_style) )
453    {
454      $search = "\n</head>";
455      $pos = strpos( $this->output, $search );
456      if ($pos !== false)
457      {
458        $rep = "\n".implode( "\n", $this->html_head_elements );
459        if (strlen($this->html_style))
460        {
461          $rep.='<style type="text/css">'.$this->html_style.'</style>';
462        }
463        $this->output = substr_replace( $this->output, $rep, $pos, 0 );
464      } //else maybe error or warning ?
465      $this->html_head_elements = array();
466      $this->html_style = '';
467    }
468
469    echo $this->output;
470    $this->output='';
471  }
472
473  /** flushes the output */
474  function p()
475  {
476    $this->flush();
477
478    if ($this->smarty->debugging)
479    {
480      global $t2;
481      $this->smarty->assign(
482        array(
483        'AAAA_DEBUG_TOTAL_TIME__' => get_elapsed_time($t2, get_moment())
484        )
485        );
486      Smarty_Internal_Debug::display_debug($this->smarty);
487    }
488  }
489
490  static function get_php_str_val($str)
491  {
492    if (is_string($str) && strlen($str)>1)
493    {
494      if ( ($str[0]=='\'' && $str[strlen($str)-1]=='\'')
495        || ($str[0]=='"' && $str[strlen($str)-1]=='"'))
496      {
497        eval('$tmp='.$str.';');
498        return $tmp;
499      }
500    }
501    return null;
502  }
503
504  /**
505   * translate variable modifier - translates a text to the currently loaded language
506   */
507  static function modcompiler_translate($params)
508  {
509    global $conf, $lang;
510    if ( $conf['compiled_template_cache_language']
511      && ($key=self::get_php_str_val($params[0])) !== null)
512    {
513      if (isset($lang[$key]))
514        return var_export($lang[$key], true);
515    }
516    return 'l10n('.$params[0].')';
517  }
518
519  static function modcompiler_translate_dec($params)
520  {
521    global $conf, $lang, $lang_info;
522    if ( $conf['compiled_template_cache_language'])
523    {
524      $ret = 'sprintf(';
525      if ($lang_info['zero_plural'])
526      {
527        $ret .= '($tmp=('.$params[0].'))>1||$tmp==0';
528      }
529      else
530      {
531        $ret .= '($tmp=('.$params[0].'))>1';
532      }
533      $ret .= '?';
534      $ret .= self::modcompiler_translate( array($params[2]) );
535      $ret .= ':';
536      $ret .= self::modcompiler_translate( array($params[1]) );
537      $ret .= ',$tmp';
538      $ret .= ')';
539      return $ret;
540    }
541    return 'l10n_dec('.$params[1].','.$params[2].','.$params[0].')';
542  }
543
544  /**
545   * explode variable modifier - similar to php explode
546   * 'Yes;No'|@explode:';' -> array('Yes', 'No')
547   */
548  static function mod_explode($text, $delimiter=',')
549  {
550    return explode($delimiter, $text);
551  }
552
553  /**
554   * This smarty "html_head" block allows to add content just before
555   * </head> element in the output after the head has been parsed. This is
556   * handy in order to respect strict standards when <style> and <link>
557   * html elements must appear in the <head> element
558   */
559  function block_html_head($params, $content)
560  {
561    $content = trim($content);
562    if ( !empty($content) )
563    { // second call
564      $this->html_head_elements[] = $content;
565    }
566  }
567
568  function block_html_style($params, $content)
569  {
570    $content = trim($content);
571    if ( !empty($content) )
572    { // second call
573      $this->html_style .= "\n".$content;
574    }
575  }
576
577  function func_define_derivative($params, $smarty)
578  {
579    !empty($params['name']) or fatal_error('define_derivative missing name');
580    if (isset($params['type']))
581    {
582      $derivative = ImageStdParams::get_by_type($params['type']);
583      $smarty->assign( $params['name'], $derivative);
584      return;
585    }
586    !empty($params['width']) or fatal_error('define_derivative missing width');
587    !empty($params['height']) or fatal_error('define_derivative missing height');
588
589    $w = intval($params['width']);
590    $h = intval($params['height']);
591    $crop = 0;
592    $minw=null;
593    $minh=null;
594
595    if (isset($params['crop']))
596    {
597      if (is_bool($params['crop']))
598      {
599        $crop = $params['crop'] ? 1:0;
600      }
601      else
602      {
603        $crop = round($params['crop']/100, 2);
604      }
605
606      if ($crop)
607      {
608        $minw = empty($params['min_width']) ? $w : intval($params['min_width']);
609        $minw <= $w or fatal_error('define_derivative invalid min_width');
610        $minh = empty($params['min_height']) ? $h : intval($params['min_height']);
611        $minh <= $h or fatal_error('define_derivative invalid min_height');
612      }
613    }
614
615    $smarty->assign( $params['name'], ImageStdParams::get_custom($w, $h, $crop, $minw, $minh) );
616  }
617
618   /**
619    * combine_script smarty function allows inclusion of a javascript file in the current page.
620    * The engine will combine several js files into a single one in order to reduce the number of
621    * required http requests.
622    * param id - required
623    * param path - required - the path to js file RELATIVE to piwigo root dir
624    * param load - optional - header|footer|async, default header
625    * param require - optional - comma separated list of script ids required to be loaded and executed
626        before this one
627    * param version - optional - plugins could use this and change it in order to force a
628        browser refresh
629    */
630  function func_combine_script($params)
631  {
632    if (!isset($params['id']))
633    {
634      trigger_error("combine_script: missing 'id' parameter", E_USER_ERROR);
635    }
636    $load = 0;
637    if (isset($params['load']))
638    {
639      switch ($params['load'])
640      {
641        case 'header': break;
642        case 'footer': $load=1; break;
643        case 'async': $load=2; break;
644        default: trigger_error("combine_script: invalid 'load' parameter", E_USER_ERROR);
645      }
646    }
647
648    $this->scriptLoader->add( $params['id'], $load,
649      empty($params['require']) ? array() : explode( ',', $params['require'] ),
650      @$params['path'],
651      isset($params['version']) ? $params['version'] : 0 );
652  }
653
654
655  function func_get_combined_scripts($params)
656  {
657    if (!isset($params['load']))
658    {
659      trigger_error("get_combined_scripts: missing 'load' parameter", E_USER_ERROR);
660    }
661    $load = $params['load']=='header' ? 0 : 1;
662    $content = array();
663
664    if ($load==0)
665    {
666      return self::COMBINED_SCRIPTS_TAG;
667    }
668    else
669    {
670      $scripts = $this->scriptLoader->get_footer_scripts();
671      foreach ($scripts[0] as $script)
672      {
673        $content[]=
674          '<script type="text/javascript" src="'
675          . self::make_script_src($script)
676          .'"></script>';
677      }
678      if (count($this->scriptLoader->inline_scripts))
679      {
680        $content[]= '<script type="text/javascript">//<![CDATA[
681';
682        $content = array_merge($content, $this->scriptLoader->inline_scripts);
683        $content[]= '//]]></script>';
684      }
685
686      if (count($scripts[1]))
687      {
688        $content[]= '<script type="text/javascript">';
689        $content[]= '(function() {
690var s,after = document.getElementsByTagName(\'script\')[document.getElementsByTagName(\'script\').length-1];';
691        foreach ($scripts[1] as $id => $script)
692        {
693          $content[]=
694            's=document.createElement(\'script\'); s.type=\'text/javascript\'; s.async=true; s.src=\''
695            . self::make_script_src($script)
696            .'\';';
697          $content[]= 'after = after.parentNode.insertBefore(s, after);';
698        }
699        $content[]= '})();';
700        $content[]= '</script>';
701      }
702    }
703    return implode("\n", $content);
704  }
705
706
707  private static function make_script_src( $script )
708  {
709    $ret = '';
710    if ( $script->is_remote() )
711      $ret = $script->path;
712    else
713    {
714      $ret = get_root_url().$script->path;
715      if ($script->version!==false)
716      {
717        $ret.= '?v'. ($script->version ? $script->version : PHPWG_VERSION);
718      }
719    }
720    // trigger the event for eventual use of a cdn
721    $ret = trigger_event('combined_script', $ret, $script);
722    return embellish_url($ret);
723  }
724
725  function block_footer_script($params, $content)
726  {
727    $content = trim($content);
728    if ( !empty($content) )
729    { // second call
730
731      $this->scriptLoader->add_inline(
732        $content,
733        empty($params['require']) ? array() : explode(',', $params['require'])
734      );
735    }
736  }
737
738  /**
739    * combine_css smarty function allows inclusion of a css stylesheet file in the current page.
740    * The engine will combine several css files into a single one in order to reduce the number of
741    * required http requests.
742    * param path - required - the path to css file RELATIVE to piwigo root dir
743    * param version - optional - plugins could use this and change it in order to force a
744        browser refresh
745    */
746  function func_combine_css($params)
747  {
748    !empty($params['path']) || fatal_error('combine_css missing path');
749    $order = (int)@$params['order'];
750    $version = isset($params['version']) ? $params['version'] : 0;
751    $this->css_by_priority[$order][] = array( $params['path'], $version);
752  }
753
754  function func_get_combined_css($params)
755  {
756    return self::COMBINED_CSS_TAG;
757  }
758
759
760 /**
761   * This function allows to declare a Smarty prefilter from a plugin, thus allowing
762   * it to modify template source before compilation and without changing core files
763   * They will be processed by weight ascending.
764   * http://www.smarty.net/manual/en/advanced.features.prefilters.php
765   */
766  function set_prefilter($handle, $callback, $weight=50)
767  {
768    $this->external_filters[$handle][$weight][] = array('pre', $callback);
769    ksort($this->external_filters[$handle]);
770  }
771
772  function set_postfilter($handle, $callback, $weight=50)
773  {
774    $this->external_filters[$handle][$weight][] = array('post', $callback);
775    ksort($this->external_filters[$handle]);
776  }
777
778  function set_outputfilter($handle, $callback, $weight=50)
779  {
780    $this->external_filters[$handle][$weight][] = array('output', $callback);
781    ksort($this->external_filters[$handle]);
782  }
783
784 /**
785   * This function actually triggers the filters on the tpl files.
786   * Called in the parse method.
787   * http://www.smarty.net/manual/en/advanced.features.prefilters.php
788   */
789  function load_external_filters($handle)
790  {
791    if (isset($this->external_filters[$handle]))
792    {
793      $compile_id = '';
794      foreach ($this->external_filters[$handle] as $filters)
795      {
796        foreach ($filters as $filter)
797        {
798          list($type, $callback) = $filter;
799          $compile_id .= $type.( is_array($callback) ? implode('', $callback) : $callback );
800          $this->smarty->registerFilter($type, $callback);
801        }
802      }
803      $this->smarty->compile_id .= '.'.base_convert(crc32($compile_id), 10, 36);
804    }
805  }
806
807  function unload_external_filters($handle)
808  {
809    if (isset($this->external_filters[$handle]))
810    {
811      foreach ($this->external_filters[$handle] as $filters)
812      {
813        foreach ($filters as $filter)
814        {
815          list($type, $callback) = $filter;
816          $this->smarty->unregisterFilter($type, $callback);
817        }
818      }
819    }
820  }
821
822  static function prefilter_white_space($source, $smarty)
823  {
824    $ld = $smarty->left_delimiter;
825    $rd = $smarty->right_delimiter;
826    $ldq = preg_quote($ld, '#');
827    $rdq = preg_quote($rd, '#');
828
829    $regex = array();
830    $tags = array('if','foreach','section','footer_script');
831    foreach($tags as $tag)
832    {
833      $regex[] = "#^[ \t]+($ldq$tag"."[^$ld$rd]*$rdq)\s*$#m";
834      $regex[] = "#^[ \t]+($ldq/$tag$rdq)\s*$#m";
835    }
836    $tags = array('include','else','combine_script','html_head');
837    foreach($tags as $tag)
838    {
839      $regex[] = "#^[ \t]+($ldq$tag"."[^$ld$rd]*$rdq)\s*$#m";
840    }
841    $source = preg_replace( $regex, "$1", $source);
842    return $source;
843  }
844
845  /**
846   * Smarty postfilter
847   */
848  static function postfilter_language($source, $smarty)
849  {
850    // replaces echo PHP_STRING_LITERAL; with the string literal value
851    $source = preg_replace_callback(
852      '/\\<\\?php echo ((?:\'(?:(?:\\\\.)|[^\'])*\')|(?:"(?:(?:\\\\.)|[^"])*"));\\?\\>\\n/',
853      create_function('$matches', 'eval(\'$tmp=\'.$matches[1].\';\');return $tmp;'),
854      $source);
855    return $source;
856  }
857
858  static function prefilter_local_css($source, $smarty)
859  {
860    $css = array();
861    foreach ($smarty->getTemplateVars('themes') as $theme)
862    {
863      $f = PWG_LOCAL_DIR.'css/'.$theme['id'].'-rules.css';
864      if (file_exists(PHPWG_ROOT_PATH.$f))
865      {
866        $css[] = "{combine_css path='$f' order=10}";
867      }
868    }
869    $f = PWG_LOCAL_DIR.'css/rules.css';
870    if (file_exists(PHPWG_ROOT_PATH.$f))
871    {
872      $css[] = "{combine_css path='$f' order=10}";
873    }
874
875    if (!empty($css))
876    {
877      $source = str_replace("\n{get_combined_css}", "\n".implode( "\n", $css )."\n{get_combined_css}", $source);
878    }
879
880    return $source;
881  }
882
883  function load_themeconf($dir)
884  {
885    global $themeconfs, $conf;
886
887    $dir = realpath($dir);
888    if (!isset($themeconfs[$dir]))
889    {
890      $themeconf = array();
891      include($dir.'/themeconf.inc.php');
892      // Put themeconf in cache
893      $themeconfs[$dir] = $themeconf;
894    }
895    return $themeconfs[$dir];
896  }
897
898  function add_picture_button($content, $rank=BUTTONS_RANK_NEUTRAL)
899  {
900    $this->picture_buttons[$rank][] = $content;
901  }
902
903  function add_index_button($content, $rank=BUTTONS_RANK_NEUTRAL)
904  {
905    $this->index_buttons[$rank][] = $content;
906  }
907
908  function parse_picture_buttons()
909  {
910    if (!empty($this->picture_buttons))
911    {
912      ksort($this->picture_buttons);
913      $this->assign('PLUGIN_PICTURE_BUTTONS',
914          array_reduce(
915            $this->picture_buttons,
916            create_function('$v,$w', 'return array_merge($v, $w);'),
917            array()
918          ));
919    }
920  }
921
922  function parse_index_buttons()
923  {
924    if (!empty($this->index_buttons))
925    {
926      ksort($this->index_buttons);
927      $this->assign('PLUGIN_INDEX_BUTTONS',
928          array_reduce(
929            $this->index_buttons,
930            create_function('$v,$w', 'return array_merge($v, $w);'),
931            array()
932          ));
933    }
934  }
935
936}
937
938
939/**
940 * This class contains basic functions that can be called directly from the
941 * templates in the form $pwg->l10n('edit')
942 */
943class PwgTemplateAdapter
944{
945  function l10n($text)
946  {
947    return l10n($text);
948  }
949
950  function l10n_dec($s, $p, $v)
951  {
952    return l10n_dec($s, $p, $v);
953  }
954
955  function sprintf()
956  {
957    $args = func_get_args();
958    return call_user_func_array('sprintf',  $args );
959  }
960
961  function derivative($type, $img)
962  {
963    return new DerivativeImage($type, $img);
964  }
965
966  function derivative_url($type, $img)
967  {
968    return DerivativeImage::url($type, $img);
969  }
970}
971
972
973final class Script
974{
975  public $id;
976  public $load_mode;
977  public $precedents = array();
978  public $path;
979  public $version;
980  public $extra = array();
981
982  function Script($load_mode, $id, $path, $version, $precedents)
983  {
984    $this->id = $id;
985    $this->load_mode = $load_mode;
986    $this->id = $id;
987    $this->set_path($path);
988    $this->version = $version;
989    $this->precedents = $precedents;
990  }
991
992  function set_path($path)
993  {
994    if (!empty($path))
995      $this->path = $path;
996  }
997
998  function is_remote()
999  {
1000    return url_is_remote( $this->path ) || strncmp($this->path, '//', 2)==0;
1001  }
1002}
1003
1004
1005/** Manage a list of required scripts for a page, by optimizing their loading location (head, bottom, async)
1006and later on by combining them in a unique file respecting at the same time dependencies.*/
1007class ScriptLoader
1008{
1009  private $registered_scripts;
1010  public $inline_scripts;
1011
1012  private $did_head;
1013  private $head_done_scripts;
1014  private $did_footer;
1015
1016  private static $known_paths = array(
1017      'core.scripts' => 'themes/default/js/scripts.js',
1018      'jquery' => 'themes/default/js/jquery.min.js',
1019      'jquery.ui' => 'themes/default/js/ui/minified/jquery.ui.core.min.js',
1020      'jquery.ui.effect' => 'themes/default/js/ui/minified/jquery.ui.effect.min.js',
1021    );
1022
1023  private static $ui_core_dependencies = array(
1024      'jquery.ui.widget' => array('jquery'),
1025      'jquery.ui.position' => array('jquery'),
1026      'jquery.ui.mouse' => array('jquery', 'jquery.ui', 'jquery.ui.widget'),
1027    );
1028
1029  function __construct()
1030  {
1031    $this->clear();
1032  }
1033
1034  function clear()
1035  {
1036    $this->registered_scripts = array();
1037    $this->inline_scripts = array();
1038    $this->head_done_scripts = array();
1039    $this->did_head = $this->did_footer = false;
1040  }
1041
1042  function get_all()
1043  {
1044    return $this->registered_scripts;
1045  }
1046
1047  function add_inline($code, $require)
1048  {
1049    !$this->did_footer || trigger_error("Attempt to add inline script but the footer has been written", E_USER_WARNING);
1050    if(!empty($require))
1051    {
1052      foreach ($require as $id)
1053      {
1054        if(!isset($this->registered_scripts[$id]))
1055          $this->load_known_required_script($id, 1) or fatal_error("inline script not found require $id");
1056        $s = $this->registered_scripts[$id];
1057        if($s->load_mode==2)
1058          $s->load_mode=1; // until now the implementation does not allow executing inline script depending on another async script
1059      }
1060    }
1061    $this->inline_scripts[] = $code;
1062  }
1063
1064  function add($id, $load_mode, $require, $path, $version=0)
1065  {
1066    if ($this->did_head && $load_mode==0)
1067    {
1068      trigger_error("Attempt to add script $id but the head has been written", E_USER_WARNING);
1069    }
1070    elseif ($this->did_footer)
1071    {
1072      trigger_error("Attempt to add script $id but the footer has been written", E_USER_WARNING);
1073    }
1074    if (! isset( $this->registered_scripts[$id] ) )
1075    {
1076      $script = new Script($load_mode, $id, $path, $version, $require);
1077      self::fill_well_known($id, $script);
1078      $this->registered_scripts[$id] = $script;
1079
1080      // Load or modify all UI core files
1081      if ($id == 'jquery.ui' and $script->path == self::$known_paths['jquery.ui'])
1082      {
1083        foreach (self::$ui_core_dependencies as $script_id => $required_ids)
1084          $this->add($script_id, $load_mode, $required_ids, null, $version);
1085      }
1086
1087      // Try to load undefined required script
1088      foreach ($script->precedents as $script_id)
1089      {
1090        if (! isset( $this->registered_scripts[$script_id] ) )
1091          $this->load_known_required_script($script_id, $load_mode);
1092      }
1093    }
1094    else
1095    {
1096      $script = $this->registered_scripts[$id];
1097      if (count($require))
1098      {
1099        $script->precedents = array_unique( array_merge($script->precedents, $require) );
1100      }
1101      $script->set_path($path);
1102      if ($version && version_compare($script->version, $version)<0 )
1103        $script->version = $version;
1104      if ($load_mode < $script->load_mode)
1105        $script->load_mode = $load_mode;
1106    }
1107
1108  }
1109
1110  function did_head()
1111  {
1112    return $this->did_head;
1113  }
1114
1115  function get_head_scripts()
1116  {
1117    self::check_load_dep($this->registered_scripts);
1118    foreach( array_keys($this->registered_scripts) as $id )
1119    {
1120      $this->compute_script_topological_order($id);
1121    }
1122
1123    uasort($this->registered_scripts, array('ScriptLoader', 'cmp_by_mode_and_order'));
1124
1125    foreach( $this->registered_scripts as $id => $script)
1126    {
1127      if ($script->load_mode > 0)
1128        break;
1129      if ( !empty($script->path) )
1130        $this->head_done_scripts[$id] = $script;
1131      else
1132        trigger_error("Script $id has an undefined path", E_USER_WARNING);
1133    }
1134    $this->did_head = true;
1135    return self::do_combine($this->head_done_scripts, 0);
1136  }
1137
1138  function get_footer_scripts()
1139  {
1140    if (!$this->did_head)
1141    {
1142      self::check_load_dep($this->registered_scripts);
1143    }
1144    $this->did_footer = true;
1145    $todo = array();
1146    foreach( $this->registered_scripts as $id => $script)
1147    {
1148      if (!isset($this->head_done_scripts[$id]))
1149      {
1150        $todo[$id] = $script;
1151      }
1152    }
1153
1154    foreach( array_keys($todo) as $id )
1155    {
1156      $this->compute_script_topological_order($id);
1157    }
1158
1159    uasort($todo, array('ScriptLoader', 'cmp_by_mode_and_order'));
1160
1161    $result = array( array(), array() );
1162    foreach( $todo as $id => $script)
1163    {
1164      $result[$script->load_mode-1][$id] = $script;
1165    }
1166    return array( self::do_combine($result[0],1), self::do_combine($result[1],2) );
1167  }
1168
1169  private static function do_combine($scripts, $load_mode)
1170  {
1171    global $conf;
1172    if (count($scripts)<2 or !$conf['template_combine_files'])
1173      return $scripts;
1174    $combiner = new FileCombiner('js');
1175    $result = array();
1176    foreach ($scripts as $script)
1177    {
1178      if ($script->is_remote())
1179      {
1180        if ( $combiner->combine( $out_file, $out_version) )
1181        {
1182          $results[] = new Script($load_mode, 'combi', $out_file, $out_version, array() );
1183        }
1184        $results[] = $script;
1185      }
1186      else
1187        $combiner->add( $script->path, $script->version );
1188    }
1189    if ( $combiner->combine( $out_file, $out_version) )
1190    {
1191      $results[] = new Script($load_mode, 'combi', $out_file, $out_version, array() );
1192    }
1193    return $results;
1194  }
1195
1196  // checks that if B depends on A, then B->load_mode >= A->load_mode in order to respect execution order
1197  private static function check_load_dep($scripts)
1198  {
1199    global $conf;
1200    do
1201    {
1202      $changed = false;
1203      foreach( $scripts as $id => $script)
1204      {
1205        $load = $script->load_mode;
1206        foreach( $script->precedents as $precedent)
1207        {
1208          if ( !isset($scripts[$precedent] ) )
1209            continue;
1210          if ( $scripts[$precedent]->load_mode > $load )
1211          {
1212            $scripts[$precedent]->load_mode = $load;
1213            $changed = true;
1214          }
1215          if ($load==2 && $scripts[$precedent]->load_mode==2 && ($scripts[$precedent]->is_remote() or !$conf['template_combine_files']) )
1216          {// we are async -> a predecessor cannot be async unlesss it can be merged; otherwise script execution order is not guaranteed
1217            $scripts[$precedent]->load_mode = 1;
1218            $changed = true;
1219          }
1220        }
1221      }
1222    }
1223    while ($changed);
1224  }
1225
1226
1227  private static function fill_well_known($id, $script)
1228  {
1229    if ( empty($script->path) && isset(self::$known_paths[$id]))
1230    {
1231      $script->path = self::$known_paths[$id];
1232    }
1233    if ( strncmp($id, 'jquery.', 7)==0 )
1234    {
1235      $required_ids = array('jquery');
1236
1237      if ( strncmp($id, 'jquery.ui.effect-', 17)==0 )
1238      {
1239        $required_ids = array('jquery', 'jquery.ui.effect');
1240
1241        if ( empty($script->path) )
1242          $script->path = dirname(self::$known_paths['jquery.ui.effect'])."/$id.min.js";
1243      }
1244      elseif ( strncmp($id, 'jquery.ui.', 10)==0 )
1245      {
1246        if ( !isset(self::$ui_core_dependencies[$id]) )
1247          $required_ids = array_merge(array('jquery', 'jquery.ui'), array_keys(self::$ui_core_dependencies));
1248
1249        if ( empty($script->path) )
1250          $script->path = dirname(self::$known_paths['jquery.ui'])."/$id.min.js";
1251      }
1252
1253      foreach ($required_ids as $required_id)
1254      {
1255        if ( !in_array($required_id, $script->precedents ) )
1256          $script->precedents[] = $required_id;
1257      }
1258    }
1259  }
1260
1261  private function load_known_required_script($id, $load_mode)
1262  {
1263    if ( isset(self::$known_paths[$id]) or strncmp($id, 'jquery.ui.', 10)==0  )
1264    {
1265      $this->add($id, $load_mode, array(), null);
1266      return true;
1267    }
1268    return false;
1269  }
1270
1271  private function compute_script_topological_order($script_id, $recursion_limiter=0)
1272  {
1273    if (!isset($this->registered_scripts[$script_id]))
1274    {
1275      trigger_error("Undefined script $script_id is required by someone", E_USER_WARNING);
1276      return 0;
1277    }
1278    $recursion_limiter<5 or fatal_error("combined script circular dependency");
1279    $script = $this->registered_scripts[$script_id];
1280    if (isset($script->extra['order']))
1281      return $script->extra['order'];
1282    if (count($script->precedents) == 0)
1283      return ($script->extra['order'] = 0);
1284    $max = 0;
1285    foreach( $script->precedents as $precedent)
1286      $max = max($max, $this->compute_script_topological_order($precedent, $recursion_limiter+1) );
1287    $max++;
1288    return ($script->extra['order'] = $max);
1289  }
1290
1291  private static function cmp_by_mode_and_order($s1, $s2)
1292  {
1293    $ret = $s1->load_mode - $s2->load_mode;
1294    if ($ret) return $ret;
1295
1296    $ret = $s1->extra['order'] - $s2->extra['order'];
1297    if ($ret) return $ret;
1298
1299    if ($s1->extra['order']==0 and ($s1->is_remote() xor $s2->is_remote()) )
1300    {
1301      return $s1->is_remote() ? -1 : 1;
1302    }
1303    return strcmp($s1->id,$s2->id);
1304  }
1305}
1306
1307
1308/*Allows merging of javascript and css files into a single one.*/
1309final class FileCombiner
1310{
1311  private $type; // js or css
1312  private $files = array();
1313  private $versions = array();
1314
1315  function FileCombiner($type)
1316  {
1317    $this->type = $type;
1318  }
1319
1320  static function clear_combined_files()
1321  {
1322    $dir = opendir(PHPWG_ROOT_PATH.PWG_COMBINED_DIR);
1323    while ($file = readdir($dir))
1324    {
1325      if ( get_extension($file)=='js' || get_extension($file)=='css')
1326        unlink(PHPWG_ROOT_PATH.PWG_COMBINED_DIR.$file);
1327    }
1328    closedir($dir);
1329  }
1330
1331  function add($file, $version)
1332  {
1333    $this->files[] = $file;
1334    $this->versions[] = $version;
1335  }
1336
1337  function clear()
1338  {
1339    $this->files = array();
1340    $this->versions = array();
1341  }
1342
1343  function combine(&$out_file, &$out_version)
1344  {
1345    if (count($this->files) == 0)
1346    {
1347      return false;
1348    }
1349    if (count($this->files) == 1)
1350    {
1351      $out_file = $this->files[0];
1352      $out_version = $this->versions[0];
1353      $this->clear();
1354      return 1;
1355    }
1356
1357    $is_css = $this->type == "css";
1358    global $conf;
1359    $key = array();
1360    if ($is_css)
1361      $key[] = get_absolute_root_url(false);//because we modify bg url
1362    for ($i=0; $i<count($this->files); $i++)
1363    {
1364      $key[] = $this->files[$i];
1365      $key[] = $this->versions[$i];
1366      if ($conf['template_compile_check']) $key[] = filemtime( PHPWG_ROOT_PATH . $this->files[$i] );
1367    }
1368    $key = join('>', $key);
1369
1370    $file = base_convert(crc32($key),10,36);
1371    $file = PWG_COMBINED_DIR . $file . '.' . $this->type;
1372
1373    $exists = file_exists( PHPWG_ROOT_PATH . $file );
1374    if ($exists)
1375    {
1376      $is_reload =
1377        (isset($_SERVER['HTTP_CACHE_CONTROL']) && strpos($_SERVER['HTTP_CACHE_CONTROL'], 'max-age=0') !== false)
1378        || (isset($_SERVER['HTTP_PRAGMA']) && strpos($_SERVER['HTTP_PRAGMA'], 'no-cache'));
1379      if (is_admin() && $is_reload)
1380      {// the user pressed F5 in the browser
1381        if ($is_css || $conf['template_compile_check']==false)
1382          $exists = false; // we foce regeneration of css because @import sub-files are never checked for modification
1383      }
1384    }
1385
1386    if ($exists)
1387    {
1388      $out_file = $file;
1389      $out_version = false;
1390      $this->clear();
1391      return 2;
1392    }
1393
1394    $output = '';
1395    foreach ($this->files as $input_file)
1396    {
1397      $output .= "/*BEGIN $input_file */\n";
1398      if ($is_css)
1399        $output .= self::process_css($input_file);
1400      else
1401        $output .= self::process_js($input_file);
1402      $output .= "\n";
1403    }
1404
1405    mkgetdir( dirname(PHPWG_ROOT_PATH.$file) );
1406    file_put_contents( PHPWG_ROOT_PATH.$file,  $output );
1407    @chmod(PHPWG_ROOT_PATH.$file, 0644);
1408    $out_file = $file;
1409    $out_version = false;
1410    $this->clear();
1411    return 2;
1412  }
1413
1414  private static function process_js($file)
1415  {
1416    $js = file_get_contents(PHPWG_ROOT_PATH . $file);
1417    if (strpos($file, '.min')===false and strpos($file, '.packed')===false )
1418    {
1419      require_once(PHPWG_ROOT_PATH.'include/jshrink.class.php');
1420      try { $js = JShrink_Minifier::minify($js); } catch(Exception $e) {}
1421    }
1422    return trim($js, " \t\r\n;").";\n";
1423  }
1424
1425  private static function process_css($file)
1426  {
1427    $css = self::process_css_rec($file);
1428    if (version_compare(PHP_VERSION, '5.2.4', '>='))
1429    {
1430      require_once(PHPWG_ROOT_PATH.'include/cssmin.class.php');
1431      $css = CssMin::minify($css, array('Variables'=>false));
1432    }
1433    $css = trigger_event('combined_css_postfilter', $css);
1434    return $css;
1435  }
1436
1437  private static function process_css_rec($file)
1438  {
1439    static $PATTERN = "#url\(\s*['|\"]{0,1}(.*?)['|\"]{0,1}\s*\)#";
1440    $css = file_get_contents(PHPWG_ROOT_PATH . $file);
1441    if (preg_match_all($PATTERN, $css, $matches, PREG_SET_ORDER))
1442    {
1443      $search = $replace = array();
1444      foreach ($matches as $match)
1445      {
1446        if ( !url_is_remote($match[1]) && $match[1][0] != '/')
1447        {
1448          $relative = dirname($file) . "/$match[1]";
1449          $search[] = $match[0];
1450          $replace[] = 'url('.embellish_url(get_absolute_root_url(false).$relative).')';
1451        }
1452      }
1453      $css = str_replace($search, $replace, $css);
1454    }
1455
1456    $imports = preg_match_all("#@import\s*['|\"]{0,1}(.*?)['|\"]{0,1};#", $css, $matches, PREG_SET_ORDER);
1457    if ($imports)
1458    {
1459      $search = $replace = array();
1460      foreach ($matches as $match)
1461      {
1462        $search[] = $match[0];
1463        $replace[] = self::process_css_rec(dirname($file) . "/$match[1]");
1464      }
1465      $css = str_replace($search, $replace, $css);
1466    }
1467    return $css;
1468  }
1469}
1470
1471?>
Note: See TracBrowser for help on using the repository browser.