source: branches/2.4/include/template.class.php @ 19794

Last change on this file since 19794 was 19794, checked in by flop25, 11 years ago

bug:2797 merge r19696 in 2.4 branche
added !defined('IN_ADMIN') to prefilter_local_css to exlude the local css files from the administration part

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