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

Last change on this file since 19576 was 19576, checked in by mistic100, 11 years ago

bug:2663 replace JSmin by JShrink

  • Property svn:eol-style set to LF
File size: 42.0 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  var $picture_buttons = array();
51  var $index_buttons = array();
52
53  function Template($root = ".", $theme= "", $path = "template")
54  {
55    global $conf, $lang_info;
56
57    $this->scriptLoader = new ScriptLoader;
58    $this->smarty = new Smarty;
59    $this->smarty->debugging = $conf['debug_template'];
60    $this->smarty->compile_check = $conf['template_compile_check'];
61    $this->smarty->force_compile = $conf['template_force_compile'];
62
63    if (!isset($conf['data_dir_checked']))
64    {
65      $dir = PHPWG_ROOT_PATH.$conf['data_location'];
66      mkgetdir($dir, MKGETDIR_DEFAULT&~MKGETDIR_DIE_ON_ERROR);
67      if (!is_writable($dir))
68      {
69        load_language('admin.lang');
70        fatal_error(
71          sprintf(
72            l10n('Give write access (chmod 777) to "%s" directory at the root of your Piwigo installation'),
73            $conf['data_location']
74            ),
75          l10n('an error happened'),
76          false // show trace
77          );
78      }
79      if (function_exists('pwg_query')) {
80        conf_update_param('data_dir_checked', 1);
81      }
82    }
83
84    $compile_dir = PHPWG_ROOT_PATH.$conf['data_location'].'templates_c';
85    mkgetdir( $compile_dir );
86
87    $this->smarty->compile_dir = $compile_dir;
88
89    $this->smarty->assign_by_ref( 'pwg', new PwgTemplateAdapter() );
90    $this->smarty->register_modifier( 'translate', array('Template', 'mod_translate') );
91    $this->smarty->register_modifier( 'explode', array('Template', 'mod_explode') );
92    $this->smarty->register_modifier( 'get_extent', array(&$this, 'get_extent') );
93    $this->smarty->register_block('html_head', array(&$this, 'block_html_head') );
94    $this->smarty->register_block('html_style', array(&$this, 'block_html_style') );
95    $this->smarty->register_function('combine_script', array(&$this, 'func_combine_script') );
96    $this->smarty->register_function('get_combined_scripts', array(&$this, 'func_get_combined_scripts') );
97    $this->smarty->register_function('combine_css', array(&$this, 'func_combine_css') );
98    $this->smarty->register_function('define_derivative', array(&$this, 'func_define_derivative') );
99    $this->smarty->register_compiler_function('get_combined_css', array(&$this, 'func_get_combined_css') );
100    $this->smarty->register_block('footer_script', array(&$this, 'block_footer_script') );
101    $this->smarty->register_prefilter( array('Template', 'prefilter_white_space') );
102    if ( $conf['compiled_template_cache_language'] )
103    {
104      $this->smarty->register_prefilter( array('Template', 'prefilter_language') );
105    }
106
107    $this->smarty->template_dir = array();
108    if ( !empty($theme) )
109    {
110      $this->set_theme($root, $theme, $path);
111      $this->set_prefilter( 'header', array('Template', 'prefilter_local_css') );
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
602    // TEMP in 2.5 for backward compatibility
603    if(!empty($params['require']))
604    {
605      $params['require'] = str_replace('jquery.effects.', 'jquery.ui.effect-', $params['require'] );
606      $params['require'] = str_replace('jquery.effects', 'jquery.ui.effect', $params['require'] );
607    }
608
609    $this->scriptLoader->add( $params['id'], $load,
610      empty($params['require']) ? array() : explode( ',', $params['require'] ),
611      @$params['path'],
612      isset($params['version']) ? $params['version'] : 0 );
613  }
614
615
616  function func_get_combined_scripts($params)
617  {
618    if (!isset($params['load']))
619    {
620      $this->smarty->trigger_error("get_combined_scripts: missing 'load' parameter", E_USER_ERROR);
621    }
622    $load = $params['load']=='header' ? 0 : 1;
623    $content = array();
624
625    if ($load==0)
626    {
627      return self::COMBINED_SCRIPTS_TAG;
628    }
629    else
630    {
631      $scripts = $this->scriptLoader->get_footer_scripts();
632      foreach ($scripts[0] as $script)
633      {
634        $content[]=
635          '<script type="text/javascript" src="'
636          . self::make_script_src($script)
637          .'"></script>';
638      }
639      if (count($this->scriptLoader->inline_scripts))
640      {
641        $content[]= '<script type="text/javascript">//<![CDATA[
642';
643        $content = array_merge($content, $this->scriptLoader->inline_scripts);
644        $content[]= '//]]></script>';
645      }
646
647      if (count($scripts[1]))
648      {
649        $content[]= '<script type="text/javascript">';
650        $content[]= '(function() {
651var s,after = document.getElementsByTagName(\'script\')[document.getElementsByTagName(\'script\').length-1];';
652        foreach ($scripts[1] as $id => $script)
653        {
654          $content[]=
655            's=document.createElement(\'script\'); s.type=\'text/javascript\'; s.async=true; s.src=\''
656            . self::make_script_src($script)
657            .'\';';
658          $content[]= 'after = after.parentNode.insertBefore(s, after);';
659        }
660        $content[]= '})();';
661        $content[]= '</script>';
662      }
663    }
664    return implode("\n", $content);
665  }
666
667
668  private static function make_script_src( $script )
669  {
670    $ret = '';
671    if ( $script->is_remote() )
672      $ret = $script->path;
673    else
674    {
675      $ret = get_root_url().$script->path;
676      if ($script->version!==false)
677      {
678        $ret.= '?v'. ($script->version ? $script->version : PHPWG_VERSION);
679      }
680    }
681    // trigger the event for eventual use of a cdn
682    $ret = trigger_event('combined_script', $ret, $script);
683    return embellish_url($ret);
684  }
685
686  function block_footer_script($params, $content)
687  {
688    $content = trim($content);
689    if ( !empty($content) )
690    { // second call
691
692      // TEMP in 2.5 for backward compatibility
693      if(!empty($params['require']))
694      {
695        $params['require'] = str_replace('jquery.effects.', 'jquery.ui.effect-', $params['require'] );
696        $params['require'] = str_replace('jquery.effects', 'jquery.ui.effect', $params['require'] );
697      }
698
699      $this->scriptLoader->add_inline(
700        $content,
701        empty($params['require']) ? array() : explode(',', $params['require'])
702      );
703    }
704  }
705
706  /**
707    * combine_css smarty function allows inclusion of a css stylesheet file in the current page.
708    * The engine will combine several css files into a single one in order to reduce the number of
709    * required http requests.
710    * param path - required - the path to css file RELATIVE to piwigo root dir
711    * param version - optional - plugins could use this and change it in order to force a
712        browser refresh
713    */
714  function func_combine_css($params)
715  {
716    !empty($params['path']) || fatal_error('combine_css missing path');
717    $order = (int)@$params['order'];
718    $version = isset($params['version']) ? $params['version'] : 0;
719    $this->css_by_priority[$order][] = array( $params['path'], $version);
720  }
721
722  function func_get_combined_css($params)
723  {
724    return 'echo '.var_export(self::COMBINED_CSS_TAG,true);
725  }
726
727
728 /**
729   * This function allows to declare a Smarty prefilter from a plugin, thus allowing
730   * it to modify template source before compilation and without changing core files
731   * They will be processed by weight ascending.
732   * http://www.smarty.net/manual/en/advanced.features.prefilters.php
733   */
734  function set_prefilter($handle, $callback, $weight=50)
735  {
736    $this->external_filters[$handle][$weight][] = array('prefilter', $callback);
737    ksort($this->external_filters[$handle]);
738  }
739
740  function set_postfilter($handle, $callback, $weight=50)
741  {
742    $this->external_filters[$handle][$weight][] = array('postfilter', $callback);
743    ksort($this->external_filters[$handle]);
744  }
745
746  function set_outputfilter($handle, $callback, $weight=50)
747  {
748    $this->external_filters[$handle][$weight][] = array('outputfilter', $callback);
749    ksort($this->external_filters[$handle]);
750  }
751
752 /**
753   * This function actually triggers the filters on the tpl files.
754   * Called in the parse method.
755   * http://www.smarty.net/manual/en/advanced.features.prefilters.php
756   */
757  function load_external_filters($handle)
758  {
759    if (isset($this->external_filters[$handle]))
760    {
761      $compile_id = '';
762      foreach ($this->external_filters[$handle] as $filters)
763      {
764        foreach ($filters as $filter)
765        {
766          list($type, $callback) = $filter;
767          $compile_id .= $type.( is_array($callback) ? implode('', $callback) : $callback );
768          call_user_func(array($this->smarty, 'register_'.$type), $callback);
769        }
770      }
771      $this->smarty->compile_id .= '.'.base_convert(crc32($compile_id), 10, 36);
772    }
773  }
774
775  function unload_external_filters($handle)
776  {
777    if (isset($this->external_filters[$handle]))
778    {
779      foreach ($this->external_filters[$handle] as $filters)
780      {
781        foreach ($filters as $filter)
782        {
783          list($type, $callback) = $filter;
784          call_user_func(array($this->smarty, 'unregister_'.$type), $callback);
785        }
786      }
787    }
788  }
789
790  static function prefilter_white_space($source, &$smarty)
791  {
792    $ld = $smarty->left_delimiter;
793    $rd = $smarty->right_delimiter;
794    $ldq = preg_quote($ld, '#');
795    $rdq = preg_quote($rd, '#');
796
797    $regex = array();
798    $tags = array('if','foreach','section','footer_script');
799    foreach($tags as $tag)
800    {
801      array_push($regex, "#^[ \t]+($ldq$tag"."[^$ld$rd]*$rdq)\s*$#m");
802      array_push($regex, "#^[ \t]+($ldq/$tag$rdq)\s*$#m");
803    }
804    $tags = array('include','else','combine_script','html_head');
805    foreach($tags as $tag)
806    {
807      array_push($regex, "#^[ \t]+($ldq$tag"."[^$ld$rd]*$rdq)\s*$#m");
808    }
809    $source = preg_replace( $regex, "$1", $source);
810    return $source;
811  }
812
813  /**
814   * Smarty prefilter to allow caching (whenever possible) language strings
815   * from templates.
816   */
817  static function prefilter_language($source, &$smarty)
818  {
819    global $lang;
820    $ldq = preg_quote($smarty->left_delimiter, '~');
821    $rdq = preg_quote($smarty->right_delimiter, '~');
822
823    $regex = "~$ldq *\'([^'$]+)\'\|@translate *$rdq~";
824    $source = preg_replace_callback( $regex, create_function('$m', 'global $lang; return isset($lang[$m[1]]) ? $lang[$m[1]] : $m[0];'), $source);
825
826    $regex = "~$ldq *\'([^'$]+)\'\|@translate\|~";
827    $source = preg_replace_callback( $regex, create_function('$m', 'global $lang; return isset($lang[$m[1]]) ? \'{\'.var_export($lang[$m[1]],true).\'|\' : $m[0];'), $source);
828
829    $regex = "~($ldq *assign +var=.+ +value=)\'([^'$]+)\'\|@translate~";
830    $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);
831
832    return $source;
833  }
834
835  static function prefilter_local_css($source, &$smarty)
836  {
837    $css = array();
838    foreach ($smarty->get_template_vars('themes') as $theme)
839    {
840      $f = PWG_LOCAL_DIR.'css/'.$theme['id'].'-rules.css';
841      if (file_exists(PHPWG_ROOT_PATH.$f))
842      {
843        array_push($css, "{combine_css path='$f' order=10}");
844      }
845    }
846    $f = PWG_LOCAL_DIR.'css/rules.css';
847    if (file_exists(PHPWG_ROOT_PATH.$f))
848    {
849      array_push($css, "{combine_css path='$f' order=10}");
850    }
851
852    if (!empty($css))
853    {
854      $source = str_replace("\n{get_combined_css}", "\n".implode( "\n", $css )."\n{get_combined_css}", $source);
855    }
856
857    return $source;
858  }
859
860  function load_themeconf($dir)
861  {
862    global $themeconfs, $conf;
863
864    $dir = realpath($dir);
865    if (!isset($themeconfs[$dir]))
866    {
867      $themeconf = array();
868      include($dir.'/themeconf.inc.php');
869      // Put themeconf in cache
870      $themeconfs[$dir] = $themeconf;
871    }
872    return $themeconfs[$dir];
873  }
874 
875  function add_picture_button($content, $rank)
876  {
877    $this->picture_buttons[$rank][] = $content;
878  }
879 
880  function add_index_button($content, $rank)
881  {
882    $this->index_buttons[$rank][] = $content;
883  }
884 
885  function parse_picture_buttons()
886  {
887    if (!empty($this->picture_buttons))
888    {
889      ksort($this->picture_buttons);
890      foreach ($this->picture_buttons as $ranked)
891        foreach ($ranked as $content)
892          $this->concat('PLUGIN_PICTURE_ACTIONS', $content);
893    }
894  }
895   
896  function parse_index_buttons()
897  {
898    if (!empty($this->index_buttons))
899    {
900      ksort($this->index_buttons);
901      foreach ($this->index_buttons as $ranked)
902        foreach ($ranked as $content)
903          $this->concat('PLUGIN_INDEX_ACTIONS', $content);
904    }
905  }
906   
907}
908
909
910/**
911 * This class contains basic functions that can be called directly from the
912 * templates in the form $pwg->l10n('edit')
913 */
914class PwgTemplateAdapter
915{
916  function l10n($text)
917  {
918    return l10n($text);
919  }
920
921  function l10n_dec($s, $p, $v)
922  {
923    return l10n_dec($s, $p, $v);
924  }
925
926  function sprintf()
927  {
928    $args = func_get_args();
929    return call_user_func_array('sprintf',  $args );
930  }
931
932  function derivative($type, $img)
933  {
934    return new DerivativeImage($type, $img);
935  }
936
937  function derivative_url($type, $img)
938  {
939    return DerivativeImage::url($type, $img);
940  }
941}
942
943
944final class Script
945{
946  public $id;
947  public $load_mode;
948  public $precedents = array();
949  public $path;
950  public $version;
951  public $extra = array();
952
953  function Script($load_mode, $id, $path, $version, $precedents)
954  {
955    $this->id = $id;
956    $this->load_mode = $load_mode;
957    $this->id = $id;
958    $this->set_path($path);
959    $this->version = $version;
960    $this->precedents = $precedents;
961  }
962
963  function set_path($path)
964  {
965    if (!empty($path))
966      $this->path = $path;
967  }
968
969  function is_remote()
970  {
971    return url_is_remote( $this->path );
972  }
973}
974
975
976/** Manage a list of required scripts for a page, by optimizing their loading location (head, bottom, async)
977and later on by combining them in a unique file respecting at the same time dependencies.*/
978class ScriptLoader
979{
980  private $registered_scripts;
981  public $inline_scripts;
982
983  private $did_head;
984  private $head_done_scripts;
985  private $did_footer;
986
987  private static $known_paths = array(
988      'core.scripts' => 'themes/default/js/scripts.js',
989      'jquery' => 'themes/default/js/jquery.min.js',
990      'jquery.ui' => 'themes/default/js/ui/minified/jquery.ui.core.min.js',
991      'jquery.ui.effect' => 'themes/default/js/ui/minified/jquery.ui.effect.min.js',
992    );
993
994  private static $ui_core_dependencies = array(
995      'jquery.ui.widget' => array('jquery'),
996      'jquery.ui.position' => array('jquery'),
997      'jquery.ui.mouse' => array('jquery', 'jquery.ui', 'jquery.ui.widget'),
998    );
999
1000  function __construct()
1001  {
1002    $this->clear();
1003  }
1004
1005  function clear()
1006  {
1007    $this->registered_scripts = array();
1008    $this->inline_scripts = array();
1009    $this->head_done_scripts = array();
1010    $this->did_head = $this->did_footer = false;
1011  }
1012
1013  function get_all()
1014  {
1015    return $this->registered_scripts;
1016  }
1017
1018  function add_inline($code, $require)
1019  {
1020    !$this->did_footer || trigger_error("Attempt to add inline script but the footer has been written", E_USER_WARNING);
1021    if(!empty($require))
1022    {
1023      foreach ($require as $id)
1024      {
1025        if(!isset($this->registered_scripts[$id]))
1026          $this->load_known_required_script($id, 1) or fatal_error("inline script not found require $id");
1027        $s = $this->registered_scripts[$id];
1028        if($s->load_mode==2)
1029          $s->load_mode=1; // until now the implementation does not allow executing inline script depending on another async script
1030      }
1031    }
1032    $this->inline_scripts[] = $code;
1033  }
1034
1035  function add($id, $load_mode, $require, $path, $version=0)
1036  {
1037    if ($this->did_head && $load_mode==0)
1038    {
1039      trigger_error("Attempt to add script $id but the head has been written", E_USER_WARNING);
1040    }
1041    elseif ($this->did_footer)
1042    {
1043      trigger_error("Attempt to add script $id but the footer has been written", E_USER_WARNING);
1044    }
1045    if (! isset( $this->registered_scripts[$id] ) )
1046    {
1047      $script = new Script($load_mode, $id, $path, $version, $require);
1048      self::fill_well_known($id, $script);
1049      $this->registered_scripts[$id] = $script;
1050
1051      // Load or modify all UI core files
1052      if ($id == 'jquery.ui' and $script->path == self::$known_paths['jquery.ui'])
1053      {
1054        foreach (self::$ui_core_dependencies as $script_id => $required_ids)
1055          $this->add($script_id, $load_mode, $required_ids, null, $version);
1056      }
1057
1058      // Try to load undefined required script
1059      foreach ($script->precedents as $script_id)
1060      {
1061        if (! isset( $this->registered_scripts[$script_id] ) )
1062          $this->load_known_required_script($script_id, $load_mode);
1063      }
1064    }
1065    else
1066    {
1067      $script = $this->registered_scripts[$id];
1068      if (count($require))
1069      {
1070        $script->precedents = array_unique( array_merge($script->precedents, $require) );
1071      }
1072      $script->set_path($path);
1073      if ($version && version_compare($script->version, $version)<0 )
1074        $script->version = $version;
1075      if ($load_mode < $script->load_mode)
1076        $script->load_mode = $load_mode;
1077    }
1078
1079  }
1080
1081  function did_head()
1082  {
1083    return $this->did_head;
1084  }
1085
1086  function get_head_scripts()
1087  {
1088    self::check_load_dep($this->registered_scripts);
1089    foreach( array_keys($this->registered_scripts) as $id )
1090    {
1091      $this->compute_script_topological_order($id);
1092    }
1093
1094    uasort($this->registered_scripts, array('ScriptLoader', 'cmp_by_mode_and_order'));
1095
1096    foreach( $this->registered_scripts as $id => $script)
1097    {
1098      if ($script->load_mode > 0)
1099        break;
1100      if ( !empty($script->path) )
1101        $this->head_done_scripts[$id] = $script;
1102      else
1103        trigger_error("Script $id has an undefined path", E_USER_WARNING);
1104    }
1105    $this->did_head = true;
1106    return self::do_combine($this->head_done_scripts, 0);
1107  }
1108
1109  function get_footer_scripts()
1110  {
1111    if (!$this->did_head)
1112    {
1113      self::check_load_dep($this->registered_scripts);
1114    }
1115    $this->did_footer = true;
1116    $todo = array();
1117    foreach( $this->registered_scripts as $id => $script)
1118    {
1119      if (!isset($this->head_done_scripts[$id]))
1120      {
1121        $todo[$id] = $script;
1122      }
1123    }
1124
1125    foreach( array_keys($todo) as $id )
1126    {
1127      $this->compute_script_topological_order($id);
1128    }
1129
1130    uasort($todo, array('ScriptLoader', 'cmp_by_mode_and_order'));
1131
1132    $result = array( array(), array() );
1133    foreach( $todo as $id => $script)
1134    {
1135      $result[$script->load_mode-1][$id] = $script;
1136    }
1137    return array( self::do_combine($result[0],1), self::do_combine($result[1],2) );
1138  }
1139
1140  private static function do_combine($scripts, $load_mode)
1141  {
1142    global $conf;
1143    if (count($scripts)<2 or !$conf['template_combine_files'])
1144      return $scripts;
1145    $combiner = new FileCombiner('js');
1146    $result = array();
1147    foreach ($scripts as $script)
1148    {
1149      if ($script->is_remote())
1150      {
1151        if ( $combiner->combine( $out_file, $out_version) )
1152        {
1153          $results[] = new Script($load_mode, 'combi', $out_file, $out_version, array() );
1154        }
1155        $results[] = $script;
1156      }
1157      else
1158        $combiner->add( $script->path, $script->version );
1159    }
1160    if ( $combiner->combine( $out_file, $out_version) )
1161    {
1162      $results[] = new Script($load_mode, 'combi', $out_file, $out_version, array() );
1163    }
1164    return $results;
1165  }
1166
1167  // checks that if B depends on A, then B->load_mode >= A->load_mode in order to respect execution order
1168  private static function check_load_dep($scripts)
1169  {
1170    global $conf;
1171    do
1172    {
1173      $changed = false;
1174      foreach( $scripts as $id => $script)
1175      {
1176        $load = $script->load_mode;
1177        foreach( $script->precedents as $precedent)
1178        {
1179          if ( !isset($scripts[$precedent] ) )
1180            continue;
1181          if ( $scripts[$precedent]->load_mode > $load )
1182          {
1183            $scripts[$precedent]->load_mode = $load;
1184            $changed = true;
1185          }
1186          if ($load==2 && $scripts[$precedent]->load_mode==2 && ($scripts[$precedent]->is_remote() or !$conf['template_combine_files']) )
1187          {// we are async -> a predecessor cannot be async unlesss it can be merged; otherwise script execution order is not guaranteed
1188            $scripts[$precedent]->load_mode = 1;
1189            $changed = true;
1190          }
1191        }
1192      }
1193    }
1194    while ($changed);
1195  }
1196
1197
1198  private static function fill_well_known($id, $script)
1199  {
1200    if ( empty($script->path) && isset(self::$known_paths[$id]))
1201    {
1202      $script->path = self::$known_paths[$id];
1203    }
1204    if ( strncmp($id, 'jquery.', 7)==0 )
1205    {
1206      $required_ids = array('jquery');
1207
1208      if ( strncmp($id, 'jquery.ui.effect-', 17)==0 )
1209      {
1210        $required_ids = array('jquery', 'jquery.ui.effect');
1211
1212        if ( empty($script->path) )
1213          $script->path = dirname(self::$known_paths['jquery.ui.effect'])."/$id.min.js";
1214      }
1215      elseif ( strncmp($id, 'jquery.ui.', 10)==0 )
1216      {
1217        if ( !isset(self::$ui_core_dependencies[$id]) )
1218          $required_ids = array_merge(array('jquery', 'jquery.ui'), array_keys(self::$ui_core_dependencies));
1219
1220        if ( empty($script->path) )
1221          $script->path = dirname(self::$known_paths['jquery.ui'])."/$id.min.js";
1222      }
1223
1224      foreach ($required_ids as $required_id)
1225      {
1226        if ( !in_array($required_id, $script->precedents ) )
1227          $script->precedents[] = $required_id;
1228      }
1229    }
1230  }
1231
1232  private function load_known_required_script($id, $load_mode)
1233  {
1234    if ( isset(self::$known_paths[$id]) or strncmp($id, 'jquery.ui.', 10)==0  )
1235    {
1236      $this->add($id, $load_mode, array(), null);
1237      return true;
1238    }
1239    return false;
1240  }
1241
1242  private function compute_script_topological_order($script_id, $recursion_limiter=0)
1243  {
1244    if (!isset($this->registered_scripts[$script_id]))
1245    {
1246      trigger_error("Undefined script $script_id is required by someone", E_USER_WARNING);
1247      return 0;
1248    }
1249    $recursion_limiter<5 or fatal_error("combined script circular dependency");
1250    $script = $this->registered_scripts[$script_id];
1251    if (isset($script->extra['order']))
1252      return $script->extra['order'];
1253    if (count($script->precedents) == 0)
1254      return ($script->extra['order'] = 0);
1255    $max = 0;
1256    foreach( $script->precedents as $precedent)
1257      $max = max($max, $this->compute_script_topological_order($precedent, $recursion_limiter+1) );
1258    $max++;
1259    return ($script->extra['order'] = $max);
1260  }
1261
1262  private static function cmp_by_mode_and_order($s1, $s2)
1263  {
1264    $ret = $s1->load_mode - $s2->load_mode;
1265    if ($ret) return $ret;
1266
1267    $ret = $s1->extra['order'] - $s2->extra['order'];
1268    if ($ret) return $ret;
1269
1270    if ($s1->extra['order']==0 and ($s1->is_remote() xor $s2->is_remote()) )
1271    {
1272      return $s1->is_remote() ? -1 : 1;
1273    }
1274    return strcmp($s1->id,$s2->id);
1275  }
1276}
1277
1278
1279/*Allows merging of javascript and css files into a single one.*/
1280final class FileCombiner
1281{
1282  private $type; // js or css
1283  private $files = array();
1284  private $versions = array();
1285
1286  function FileCombiner($type)
1287  {
1288    $this->type = $type;
1289  }
1290
1291  static function clear_combined_files()
1292  {
1293    $dir = opendir(PHPWG_ROOT_PATH.PWG_COMBINED_DIR);
1294    while ($file = readdir($dir))
1295    {
1296      if ( get_extension($file)=='js' || get_extension($file)=='css')
1297        unlink(PHPWG_ROOT_PATH.PWG_COMBINED_DIR.$file);
1298    }
1299    closedir($dir);
1300  }
1301
1302  function add($file, $version)
1303  {
1304    $this->files[] = $file;
1305    $this->versions[] = $version;
1306  }
1307
1308  function clear()
1309  {
1310    $this->files = array();
1311    $this->versions = array();
1312  }
1313
1314  function combine(&$out_file, &$out_version)
1315  {
1316    if (count($this->files) == 0)
1317    {
1318      return false;
1319    }
1320    if (count($this->files) == 1)
1321    {
1322      $out_file = $this->files[0];
1323      $out_version = $this->versions[0];
1324      $this->clear();
1325      return 1;
1326    }
1327
1328    $is_css = $this->type == "css";
1329    global $conf;
1330    $key = array();
1331    if ($is_css)
1332      $key[] = get_absolute_root_url(false);//because we modify bg url
1333    for ($i=0; $i<count($this->files); $i++)
1334    {
1335      $key[] = $this->files[$i];
1336      $key[] = $this->versions[$i];
1337      if ($conf['template_compile_check']) $key[] = filemtime( PHPWG_ROOT_PATH . $this->files[$i] );
1338    }
1339    $key = join('>', $key);
1340
1341    $file = base_convert(crc32($key),10,36);
1342    $file = PWG_COMBINED_DIR . $file . '.' . $this->type;
1343
1344    $exists = file_exists( PHPWG_ROOT_PATH . $file );
1345    if ($exists)
1346    {
1347      $is_reload =
1348        (isset($_SERVER['HTTP_CACHE_CONTROL']) && strpos($_SERVER['HTTP_CACHE_CONTROL'], 'max-age=0') !== false)
1349        || (isset($_SERVER['HTTP_PRAGMA']) && strpos($_SERVER['HTTP_PRAGMA'], 'no-cache'));
1350      if (is_admin() && $is_reload)
1351      {// the user pressed F5 in the browser
1352        if ($is_css || $conf['template_compile_check']==false)
1353          $exists = false; // we foce regeneration of css because @import sub-files are never checked for modification
1354      }
1355    }
1356
1357    if ($exists)
1358    {
1359      $out_file = $file;
1360      $out_version = false;
1361      $this->clear();
1362      return 2;
1363    }
1364
1365    $output = '';
1366    foreach ($this->files as $input_file)
1367    {
1368      $output .= "/*BEGIN $input_file */\n";
1369      if ($is_css)
1370        $output .= self::process_css($input_file);
1371      else
1372        $output .= self::process_js($input_file);
1373      $output .= "\n";
1374    }
1375
1376    mkgetdir( dirname(PHPWG_ROOT_PATH.$file) );
1377    file_put_contents( PHPWG_ROOT_PATH.$file,  $output );
1378    @chmod(PHPWG_ROOT_PATH.$file, 0644);
1379    $out_file = $file;
1380    $out_version = false;
1381    $this->clear();
1382    return 2;
1383  }
1384
1385  private static function process_js($file)
1386  {
1387    $js = file_get_contents(PHPWG_ROOT_PATH . $file);
1388    if (strpos($file, '.min')===false and strpos($file, '.packed')===false )
1389    {
1390      require_once(PHPWG_ROOT_PATH.'include/jshrink.class.php');
1391      try { $js = JShrink_Minifier::minify($js); } catch(Exception $e) {}
1392    }
1393    return trim($js, " \t\r\n;").";\n";
1394  }
1395
1396  private static function process_css($file)
1397  {
1398    $css = self::process_css_rec($file);
1399    if (version_compare(PHP_VERSION, '5.2.4', '>='))
1400    {
1401      require_once(PHPWG_ROOT_PATH.'include/cssmin.class.php');
1402      $css = CssMin::minify($css, array('Variables'=>false));
1403    }
1404    $css = trigger_event('combined_css_postfilter', $css);
1405    return $css;
1406  }
1407
1408  private static function process_css_rec($file)
1409  {
1410    static $PATTERN = "#url\(\s*['|\"]{0,1}(.*?)['|\"]{0,1}\s*\)#";
1411    $css = file_get_contents(PHPWG_ROOT_PATH . $file);
1412    if (preg_match_all($PATTERN, $css, $matches, PREG_SET_ORDER))
1413    {
1414      $search = $replace = array();
1415      foreach ($matches as $match)
1416      {
1417        if ( !url_is_remote($match[1]) && $match[1][0] != '/')
1418        {
1419          $relative = dirname($file) . "/$match[1]";
1420          $search[] = $match[0];
1421          $replace[] = 'url('.embellish_url(get_absolute_root_url(false).$relative).')';
1422        }
1423      }
1424      $css = str_replace($search, $replace, $css);
1425    }
1426
1427    $imports = preg_match_all("#@import\s*['|\"]{0,1}(.*?)['|\"]{0,1};#", $css, $matches, PREG_SET_ORDER);
1428    if ($imports)
1429    {
1430      $search = $replace = array();
1431      foreach ($matches as $match)
1432      {
1433        $search[] = $match[0];
1434        $replace[] = self::process_css_rec(dirname($file) . "/$match[1]");
1435      }
1436      $css = str_replace($search, $replace, $css);
1437    }
1438    return $css;
1439  }
1440}
1441
1442?>
Note: See TracBrowser for help on using the repository browser.