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

Last change on this file since 28703 was 28703, checked in by mistic100, 10 years ago

add dark selectize theme + "ternary" template modifier

  • Property svn:eol-style set to LF
File size: 55.3 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based photo gallery                                    |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008-2013 Piwigo Team                  http://piwigo.org |
6// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
7// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
8// +-----------------------------------------------------------------------+
9// | This program is free software; you can redistribute it and/or modify  |
10// | it under the terms of the GNU General Public License as published by  |
11// | the Free Software Foundation                                          |
12// |                                                                       |
13// | This program is distributed in the hope that it will be useful, but   |
14// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
15// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
16// | General Public License for more details.                              |
17// |                                                                       |
18// | You should have received a copy of the GNU General Public License     |
19// | along with this program; if not, write to the Free Software           |
20// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
21// | USA.                                                                  |
22// +-----------------------------------------------------------------------+
23
24/**
25 * @package template
26 */
27
28require_once( PHPWG_ROOT_PATH .'include/smarty/libs/Smarty.class.php');
29
30
31/** default rank for buttons */
32define('BUTTONS_RANK_NEUTRAL', 50);
33
34/**
35 * This a wrapper arround Smarty classes proving various custom mechanisms for templates.
36 */
37class Template
38{
39  /** @var Smarty */
40  var $smarty;
41  /** @var string */
42  var $output = '';
43
44  /** @var string[] - Hash of filenames for each template handle. */
45  var $files = array();
46  /** @var string[] - Template extents filenames for each template handle. */
47  var $extents = array();
48  /** @var array - Templates prefilter from external sources (plugins) */
49  var $external_filters = array();
50
51  /** @var string - Content to add before </head> tag */
52  var $html_head_elements = array();
53  /** @var string - Runtime CSS rules */
54  private $html_style = '';
55
56  /** @const string */
57  const COMBINED_SCRIPTS_TAG = '<!-- COMBINED_SCRIPTS -->';
58  /** @var ScriptLoader */
59  var $scriptLoader;
60
61  /** @const string */
62  const COMBINED_CSS_TAG = '<!-- COMBINED_CSS -->';
63  /** @var CssLoader */
64  var $cssLoader;
65
66  /** @var array - Runtime buttons on picture page */
67  var $picture_buttons = array();
68  /** @var array - Runtime buttons on index page */
69  var $index_buttons = array();
70
71
72  /**
73   * @var string $root
74   * @var string $theme
75   * @var string $path
76   */
77  function __construct($root=".", $theme="", $path="template")
78  {
79    global $conf, $lang_info;
80
81    SmartyException::$escape = false;
82
83    $this->scriptLoader = new ScriptLoader;
84    $this->cssLoader = new CssLoader;
85    $this->smarty = new Smarty;
86    $this->smarty->debugging = $conf['debug_template'];
87    if (!$this->smarty->debugging)
88    {
89      $this->smarty->error_reporting = error_reporting() & ~E_NOTICE;
90    }
91    $this->smarty->compile_check = $conf['template_compile_check'];
92    $this->smarty->force_compile = $conf['template_force_compile'];
93
94    if (!isset($conf['data_dir_checked']))
95    {
96      $dir = PHPWG_ROOT_PATH.$conf['data_location'];
97      mkgetdir($dir, MKGETDIR_DEFAULT&~MKGETDIR_DIE_ON_ERROR);
98      if (!is_writable($dir))
99      {
100        load_language('admin.lang');
101        fatal_error(
102          l10n(
103            'Give write access (chmod 777) to "%s" directory at the root of your Piwigo installation',
104            $conf['data_location']
105            ),
106          l10n('an error happened'),
107          false // show trace
108          );
109      }
110      if (function_exists('pwg_query')) {
111        conf_update_param('data_dir_checked', 1);
112      }
113    }
114
115    $compile_dir = PHPWG_ROOT_PATH.$conf['data_location'].'templates_c';
116    mkgetdir( $compile_dir );
117
118    $this->smarty->setCompileDir($compile_dir);
119
120    $this->smarty->assign( 'pwg', new PwgTemplateAdapter() );
121    $this->smarty->registerPlugin('modifiercompiler', 'translate', array('Template', 'modcompiler_translate') );
122    $this->smarty->registerPlugin('modifiercompiler', 'translate_dec', array('Template', 'modcompiler_translate_dec') );
123    $this->smarty->registerPlugin('modifier', 'explode', array('Template', 'mod_explode') );
124    $this->smarty->registerPlugin('modifier', 'ternary', array('Template', 'mod_ternary') );
125    $this->smarty->registerPlugin('modifier', 'get_extent', array($this, 'get_extent') );
126    $this->smarty->registerPlugin('block', 'html_head', array($this, 'block_html_head') );
127    $this->smarty->registerPlugin('block', 'html_style', array($this, 'block_html_style') );
128    $this->smarty->registerPlugin('function', 'combine_script', array($this, 'func_combine_script') );
129    $this->smarty->registerPlugin('function', 'get_combined_scripts', array($this, 'func_get_combined_scripts') );
130    $this->smarty->registerPlugin('function', 'combine_css', array($this, 'func_combine_css') );
131    $this->smarty->registerPlugin('function', 'define_derivative', array($this, 'func_define_derivative') );
132    $this->smarty->registerPlugin('compiler', 'get_combined_css', array($this, 'func_get_combined_css') );
133    $this->smarty->registerPlugin('block', 'footer_script', array($this, 'block_footer_script') );
134    $this->smarty->registerFilter('pre', array('Template', 'prefilter_white_space') );
135    if ( $conf['compiled_template_cache_language'] )
136    {
137      $this->smarty->registerFilter('post', array('Template', 'postfilter_language') );
138    }
139
140    $this->smarty->setTemplateDir(array());
141    if ( !empty($theme) )
142    {
143      $this->set_theme($root, $theme, $path);
144      if (!defined('IN_ADMIN'))
145      {
146        $this->set_prefilter( 'header', array('Template', 'prefilter_local_css') );
147      }
148    }
149    else
150      $this->set_template_dir($root);
151
152    $this->smarty->assign('lang_info', $lang_info);
153
154    if (!defined('IN_ADMIN') and isset($conf['extents_for_templates']))
155    {
156      $tpl_extents = unserialize($conf['extents_for_templates']);
157      $this->set_extents($tpl_extents, './template-extension/', true, $theme);
158    }
159  }
160
161  /**
162   * Loads theme's parameters.
163   *
164   * @param string $root
165   * @param string $theme
166   * @param string $path
167   * @param bool $load_css
168   * @param bool $load_local_head
169   */
170  function set_theme($root, $theme, $path, $load_css=true, $load_local_head=true)
171  {
172    $this->set_template_dir($root.'/'.$theme.'/'.$path);
173
174    $themeconf = $this->load_themeconf($root.'/'.$theme);
175
176    if (isset($themeconf['parent']) and $themeconf['parent'] != $theme)
177    {
178      $this->set_theme(
179        $root,
180        $themeconf['parent'],
181        $path,
182        isset($themeconf['load_parent_css']) ? $themeconf['load_parent_css'] : $load_css,
183        isset($themeconf['load_parent_local_head']) ? $themeconf['load_parent_local_head'] : $load_local_head
184      );
185    }
186
187    $tpl_var = array(
188      'id' => $theme,
189      'load_css' => $load_css,
190    );
191    if (!empty($themeconf['local_head']) and $load_local_head)
192    {
193      $tpl_var['local_head'] = realpath($root.'/'.$theme.'/'.$themeconf['local_head'] );
194    }
195    $themeconf['id'] = $theme;
196    $this->smarty->append('themes', $tpl_var);
197    $this->smarty->append('themeconf', $themeconf, true);
198  }
199
200  /**
201   * Adds template directory for this Template object.
202   * Also set compile id if not exists.
203   *
204   * @param string $dir
205   */
206  function set_template_dir($dir)
207  {
208    $this->smarty->addTemplateDir($dir);
209
210    if (!isset($this->smarty->compile_id))
211    {
212      $compile_id = "1";
213      $compile_id .= ($real_dir = realpath($dir))===false ? $dir : $real_dir;
214      $this->smarty->compile_id = base_convert(crc32($compile_id), 10, 36 );
215    }
216  }
217
218  /**
219   * Gets the template root directory for this Template object.
220   *
221   * @return string
222   */
223  function get_template_dir()
224  {
225    return $this->smarty->getTemplateDir();
226  }
227
228  /**
229   * Deletes all compiled templates.
230   */
231  function delete_compiled_templates()
232  {
233      $save_compile_id = $this->smarty->compile_id;
234      $this->smarty->compile_id = null;
235      $this->smarty->clearCompiledTemplate();
236      $this->smarty->compile_id = $save_compile_id;
237      file_put_contents($this->smarty->getCompileDir().'/index.htm', 'Not allowed!');
238  }
239
240  /**
241   * Returns theme's parameter.
242   *
243   * @param string $val
244   * @return mixed
245   */
246  function get_themeconf($val)
247  {
248    $tc = $this->smarty->getTemplateVars('themeconf');
249    return isset($tc[$val]) ? $tc[$val] : '';
250  }
251
252  /**
253   * Sets the template filename for handle.
254   *
255   * @param string $handle
256   * @param string $filename
257   * @return bool
258   */
259  function set_filename($handle, $filename)
260  {
261    return $this->set_filenames( array($handle=>$filename) );
262  }
263
264  /**
265   * Sets the template filenames for handles.
266   *
267   * @param string[] $filename_array hashmap of handle=>filename
268   * @return true
269   */
270  function set_filenames($filename_array)
271  {
272    if (!is_array($filename_array))
273    {
274      return false;
275    }
276    reset($filename_array);
277    while(list($handle, $filename) = each($filename_array))
278    {
279      if (is_null($filename))
280      {
281        unset($this->files[$handle]);
282      }
283      else
284      {
285        $this->files[$handle] = $this->get_extent($filename, $handle);
286      }
287    }
288    return true;
289  }
290
291  /**
292   * Sets template extention filename for handles.
293   *
294   * @param string $filename
295   * @param mixed $param
296   * @param string $dir
297   * @param bool $overwrite
298   * @param string $theme
299   * @return bool
300   */
301  function set_extent($filename, $param, $dir='', $overwrite=true, $theme='N/A')
302  {
303    return $this->set_extents(array($filename => $param), $dir, $overwrite);
304  }
305
306  /**
307   * Sets template extentions filenames for handles.
308   *
309   * @param string[] $filename_array hashmap of handle=>filename
310   * @param string $dir
311   * @param bool $overwrite
312   * @param string $theme
313   * @return bool
314   */
315  function set_extents($filename_array, $dir='', $overwrite=true, $theme='N/A')
316  {
317    if (!is_array($filename_array))
318    {
319      return false;
320    }
321    foreach ($filename_array as $filename => $value)
322    {
323      if (is_array($value))
324      {
325        $handle = $value[0];
326        $param = $value[1];
327        $thm = $value[2];
328      }
329      elseif (is_string($value))
330      {
331        $handle = $value;
332        $param = 'N/A';
333        $thm = 'N/A';
334      }
335      else
336      {
337        return false;
338      }
339
340      if ((stripos(implode('',array_keys($_GET)), '/'.$param) !== false or $param == 'N/A')
341        and ($thm == $theme or $thm == 'N/A')
342        and (!isset($this->extents[$handle]) or $overwrite)
343        and file_exists($dir . $filename))
344      {
345        $this->extents[$handle] = realpath($dir . $filename);
346      }
347    }
348    return true;
349  }
350
351  /**
352   * Returns template extension if exists.
353   *
354   * @param string $filename should be empty!
355   * @param string $handle
356   * @return string
357   */
358  function get_extent($filename='', $handle='')
359  {
360    if (isset($this->extents[$handle]))
361    {
362      $filename = $this->extents[$handle];
363    }
364    return $filename;
365  }
366
367  /**
368   * Assigns a template variable.
369   * @see http://www.smarty.net/manual/en/api.assign.php
370   *
371   * @param string|array $tpl_var can be a var name or a hashmap of variables
372   *    (in this case, do not use the _$value_ parameter)
373   * @param mixed $value
374   */
375  function assign($tpl_var, $value=null)
376  {
377    $this->smarty->assign( $tpl_var, $value );
378  }
379
380  /**
381   * Defines _$varname_ as the compiled result of _$handle_.
382   * This can be used to effectively include a template in another template.
383   * This is equivalent to assign($varname, $this->parse($handle, true)).
384   *
385   * @param string $varname
386   * @param string $handle
387   * @return true
388   */
389  function assign_var_from_handle($varname, $handle)
390  {
391    $this->assign($varname, $this->parse($handle, true));
392    return true;
393  }
394
395  /**
396   * Appends a new value in a template array variable, the variable is created if needed.
397   * @see http://www.smarty.net/manual/en/api.append.php
398   *
399   * @param string $tpl_var
400   * @param mixed $value
401   * @param bool $merge
402   */
403  function append($tpl_var, $value=null, $merge=false)
404  {
405    $this->smarty->append( $tpl_var, $value, $merge );
406  }
407
408  /**
409   * Performs a string concatenation.
410   *
411   * @param string $tpl_var
412   * @param string $value
413   */
414  function concat($tpl_var, $value)
415  {
416    $this->assign($tpl_var,
417      $this->smarty->getTemplateVars($tpl_var) . $value);
418  }
419
420  /**
421   * Removes an assigned template variable.
422   * @see http://www.smarty.net/manual/en/api.clear_assign.php
423   *
424   * @param string $tpl_var
425   */
426  function clear_assign($tpl_var)
427  {
428    $this->smarty->clearAssign( $tpl_var );
429  }
430
431  /**
432   * Returns an assigned template variable.
433   * @see http://www.smarty.net/manual/en/api.get_template_vars.php
434   *
435   * @param string $tpl_var
436   */
437  function get_template_vars($tpl_var=null)
438  {
439    return $this->smarty->getTemplateVars( $tpl_var );
440  }
441
442  /**
443   * Loads the template file of the handle, compiles it and appends the result to the output
444   * (or returns it if _$return_ is true).
445   *
446   * @param string $handle
447   * @param bool $return
448   * @return null|string
449   */
450  function parse($handle, $return=false)
451  {
452    if ( !isset($this->files[$handle]) )
453    {
454      fatal_error("Template->parse(): Couldn't load template file for handle $handle");
455    }
456
457    $this->smarty->assign( 'ROOT_URL', get_root_url() );
458
459    $save_compile_id = $this->smarty->compile_id;
460    $this->load_external_filters($handle);
461
462    global $conf, $lang_info;
463    if ( $conf['compiled_template_cache_language'] and isset($lang_info['code']) )
464    {
465      $this->smarty->compile_id .= '_'.$lang_info['code'];
466    }
467
468    $v = $this->smarty->fetch($this->files[$handle]);
469
470    $this->smarty->compile_id = $save_compile_id;
471    $this->unload_external_filters($handle);
472
473    if ($return)
474    {
475      return $v;
476    }
477    $this->output .= $v;
478  }
479
480  /**
481   * Loads the template file of the handle, compiles it and appends the result to the output,
482   * then sends the output to the browser.
483   *
484   * @param string $handle
485   */
486  function pparse($handle)
487  {
488    $this->parse($handle, false);
489    $this->flush();
490  }
491
492  /**
493   * Load and compile JS & CSS into the template and sends the output to the browser.
494   */
495  function flush()
496  {
497    if (!$this->scriptLoader->did_head())
498    {
499      $pos = strpos( $this->output, self::COMBINED_SCRIPTS_TAG );
500      if ($pos !== false)
501      {
502          $scripts = $this->scriptLoader->get_head_scripts();
503          $content = array();
504          foreach ($scripts as $script)
505          {
506              $content[]=
507                  '<script type="text/javascript" src="'
508                  . self::make_script_src($script)
509                  .'"></script>';
510          }
511
512          $this->output = substr_replace( $this->output, implode( "\n", $content ), $pos, strlen(self::COMBINED_SCRIPTS_TAG) );
513      } //else maybe error or warning ?
514    }
515
516    $css = $this->cssLoader->get_css();
517
518    $content = array();
519    foreach( $css as $combi )
520    {
521      $href = embellish_url(get_root_url().$combi->path);
522      if ($combi->version !== false)
523        $href .= '?v' . ($combi->version ? $combi->version : PHPWG_VERSION);
524      // trigger the event for eventual use of a cdn
525      $href = trigger_change('combined_css', $href, $combi);
526      $content[] = '<link rel="stylesheet" type="text/css" href="'.$href.'">';
527    }
528    $this->output = str_replace(self::COMBINED_CSS_TAG,
529        implode( "\n", $content ),
530        $this->output );
531    $this->cssLoader->clear();
532
533    if ( count($this->html_head_elements) || strlen($this->html_style) )
534    {
535      $search = "\n</head>";
536      $pos = strpos( $this->output, $search );
537      if ($pos !== false)
538      {
539        $rep = "\n".implode( "\n", $this->html_head_elements );
540        if (strlen($this->html_style))
541        {
542          $rep.='<style type="text/css">'.$this->html_style.'</style>';
543        }
544        $this->output = substr_replace( $this->output, $rep, $pos, 0 );
545      } //else maybe error or warning ?
546      $this->html_head_elements = array();
547      $this->html_style = '';
548    }
549
550    echo $this->output;
551    $this->output='';
552  }
553
554  /**
555   * Same as flush() but with optional debugging.
556   * @see Template::flush()
557   */
558  function p()
559  {
560    $this->flush();
561
562    if ($this->smarty->debugging)
563    {
564      global $t2;
565      $this->smarty->assign(
566        array(
567        'AAAA_DEBUG_TOTAL_TIME__' => get_elapsed_time($t2, get_moment())
568        )
569        );
570      Smarty_Internal_Debug::display_debug($this->smarty);
571    }
572  }
573
574  /**
575   * Eval a temp string to retrieve the original PHP value.
576   *
577   * @param string $str
578   * @return mixed
579   */
580  static function get_php_str_val($str)
581  {
582    if (is_string($str) && strlen($str)>1)
583    {
584      if ( ($str[0]=='\'' && $str[strlen($str)-1]=='\'')
585        || ($str[0]=='"' && $str[strlen($str)-1]=='"'))
586      {
587        eval('$tmp='.$str.';');
588        return $tmp;
589      }
590    }
591    return null;
592  }
593
594  /**
595   * "translate" variable modifier.
596   * Usage :
597   *    - {'Comment'|translate}
598   *    - {'%d comments'|translate:$count}
599   * @see l10n()
600   *
601   * @param array $params
602   * @return string
603   */
604  static function modcompiler_translate($params)
605  {
606    global $conf, $lang;
607
608    switch (count($params))
609    {
610    case 1:
611      if ($conf['compiled_template_cache_language']
612        && ($key=self::get_php_str_val($params[0])) !== null
613        && isset($lang[$key])
614      ) {
615        return var_export($lang[$key], true);
616      }
617      return 'l10n('.$params[0].')';
618
619    default:
620      if ($conf['compiled_template_cache_language'])
621      {
622        $ret = 'sprintf(';
623        $ret .= self::modcompiler_translate( array($params[0]) );
624        $ret .= ','. implode(',', array_slice($params, 1));
625        $ret .= ')';
626        return $ret;
627      }
628      return 'l10n('.$params[0].','.implode(',', array_slice($params, 1)).')';
629    }
630  }
631
632  /**
633   * "translate_dec" variable modifier.
634   * Usage :
635   *    - {$count|translate_dec:'%d comment':'%d comments'}
636   * @see l10n_dec()
637   *
638   * @param array $params
639   * @return string
640   */
641  static function modcompiler_translate_dec($params)
642  {
643    global $conf, $lang, $lang_info;
644    if ($conf['compiled_template_cache_language'])
645    {
646      $ret = 'sprintf(';
647      if ($lang_info['zero_plural'])
648      {
649        $ret .= '($tmp=('.$params[0].'))>1||$tmp==0';
650      }
651      else
652      {
653        $ret .= '($tmp=('.$params[0].'))>1';
654      }
655      $ret .= '?';
656      $ret .= self::modcompiler_translate( array($params[2]) );
657      $ret .= ':';
658      $ret .= self::modcompiler_translate( array($params[1]) );
659      $ret .= ',$tmp';
660      $ret .= ')';
661      return $ret;
662    }
663    return 'l10n_dec('.$params[1].','.$params[2].','.$params[0].')';
664  }
665
666  /**
667   * "explode" variable modifier.
668   * Usage :
669   *    - {assign var=valueExploded value=$value|explode:','}
670   *
671   * @param string $text
672   * @param string $delimiter
673   * @return array
674   */
675  static function mod_explode($text, $delimiter=',')
676  {
677    return explode($delimiter, $text);
678  }
679 
680  /**
681   * ternary variable modifier.
682   * Usage :
683   *    - {$variable|ternary:'yes':'no'}
684   *
685   * @param mixed $param
686   * @param mixed $true
687   * @param mixed $false
688   * @return mixed
689   */
690  static function mod_ternary($param, $true, $false)
691  {
692    return $param ? $true : $false;
693  }
694
695  /**
696   * The "html_head" block allows to add content just before
697   * </head> element in the output after the head has been parsed.
698   *
699   * @param array $params (unused)
700   * @param string $content
701   */
702  function block_html_head($params, $content)
703  {
704    $content = trim($content);
705    if ( !empty($content) )
706    { // second call
707      $this->html_head_elements[] = $content;
708    }
709  }
710
711  /**
712   * The "html_style" block allows to add CSS juste before
713   * </head> element in the output after the head has been parsed.
714   *
715   * @param array $params (unused)
716   * @param string $content
717   */
718  function block_html_style($params, $content)
719  {
720    $content = trim($content);
721    if ( !empty($content) )
722    { // second call
723      $this->html_style .= "\n".$content;
724    }
725  }
726
727  /**
728   * The "define_derivative" function allows to define derivative from tpl file.
729   * It assigns a DerivativeParams object to _name_ template variable.
730   *
731   * @param array $params
732   *    - name (required)
733   *    - type (optional)
734   *    - width (required if type is empty)
735   *    - height (required if type is empty)
736   *    - crop (optional, used if type is empty)
737   *    - min_height (optional, used with crop)
738   *    - min_height (optional, used with crop)
739   * @param Smarty $smarty
740   */
741  function func_define_derivative($params, $smarty)
742  {
743    !empty($params['name']) or fatal_error('define_derivative missing name');
744    if (isset($params['type']))
745    {
746      $derivative = ImageStdParams::get_by_type($params['type']);
747      $smarty->assign( $params['name'], $derivative);
748      return;
749    }
750    !empty($params['width']) or fatal_error('define_derivative missing width');
751    !empty($params['height']) or fatal_error('define_derivative missing height');
752
753    $w = intval($params['width']);
754    $h = intval($params['height']);
755    $crop = 0;
756    $minw=null;
757    $minh=null;
758
759    if (isset($params['crop']))
760    {
761      if (is_bool($params['crop']))
762      {
763        $crop = $params['crop'] ? 1:0;
764      }
765      else
766      {
767        $crop = round($params['crop']/100, 2);
768      }
769
770      if ($crop)
771      {
772        $minw = empty($params['min_width']) ? $w : intval($params['min_width']);
773        $minw <= $w or fatal_error('define_derivative invalid min_width');
774        $minh = empty($params['min_height']) ? $h : intval($params['min_height']);
775        $minh <= $h or fatal_error('define_derivative invalid min_height');
776      }
777    }
778
779    $smarty->assign( $params['name'], ImageStdParams::get_custom($w, $h, $crop, $minw, $minh) );
780  }
781
782  /**
783   * The "combine_script" functions allows inclusion of a javascript file in the current page.
784   * The engine will combine several js files into a single one.
785   *
786   * @param array $params
787   *   - id (required)
788   *   - path (required)
789   *   - load (optional) 'header', 'footer' or 'async'
790   *   - require (optional) comma separated list of script ids required to be loaded
791   *     and executed before this one
792   *   - version (optional) used to force a browser refresh
793   */
794  function func_combine_script($params)
795  {
796    if (!isset($params['id']))
797    {
798      trigger_error("combine_script: missing 'id' parameter", E_USER_ERROR);
799    }
800    $load = 0;
801    if (isset($params['load']))
802    {
803      switch ($params['load'])
804      {
805        case 'header': break;
806        case 'footer': $load=1; break;
807        case 'async': $load=2; break;
808        default: trigger_error("combine_script: invalid 'load' parameter", E_USER_ERROR);
809      }
810    }
811
812    $this->scriptLoader->add( $params['id'], $load,
813      empty($params['require']) ? array() : explode( ',', $params['require'] ),
814      @$params['path'],
815      isset($params['version']) ? $params['version'] : 0,
816      @$params['template']);
817  }
818
819  /**
820   * The "get_combined_scripts" function returns HTML tag of combined scripts.
821   * It can returns a placeholder for delayed JS files combination and minification.
822   *
823   * @param array $params
824   *    - load (required)
825   */
826  function func_get_combined_scripts($params)
827  {
828    if (!isset($params['load']))
829    {
830      trigger_error("get_combined_scripts: missing 'load' parameter", E_USER_ERROR);
831    }
832    $load = $params['load']=='header' ? 0 : 1;
833    $content = array();
834
835    if ($load==0)
836    {
837      return self::COMBINED_SCRIPTS_TAG;
838    }
839    else
840    {
841      $scripts = $this->scriptLoader->get_footer_scripts();
842      foreach ($scripts[0] as $script)
843      {
844        $content[]=
845          '<script type="text/javascript" src="'
846          . self::make_script_src($script)
847          .'"></script>';
848      }
849      if (count($this->scriptLoader->inline_scripts))
850      {
851        $content[]= '<script type="text/javascript">//<![CDATA[
852';
853        $content = array_merge($content, $this->scriptLoader->inline_scripts);
854        $content[]= '//]]></script>';
855      }
856
857      if (count($scripts[1]))
858      {
859        $content[]= '<script type="text/javascript">';
860        $content[]= '(function() {
861var s,after = document.getElementsByTagName(\'script\')[document.getElementsByTagName(\'script\').length-1];';
862        foreach ($scripts[1] as $id => $script)
863        {
864          $content[]=
865            's=document.createElement(\'script\'); s.type=\'text/javascript\'; s.async=true; s.src=\''
866            . self::make_script_src($script)
867            .'\';';
868          $content[]= 'after = after.parentNode.insertBefore(s, after);';
869        }
870        $content[]= '})();';
871        $content[]= '</script>';
872      }
873    }
874    return implode("\n", $content);
875  }
876
877  /**
878   * Returns clean relative URL to script file.
879   *
880   * @param Combinable $script
881   * @return string
882   */
883  private static function make_script_src($script)
884  {
885    $ret = '';
886    if ( $script->is_remote() )
887      $ret = $script->path;
888    else
889    {
890      $ret = get_root_url().$script->path;
891      if ($script->version!==false)
892      {
893        $ret.= '?v'. ($script->version ? $script->version : PHPWG_VERSION);
894      }
895    }
896    // trigger the event for eventual use of a cdn
897    $ret = trigger_change('combined_script', $ret, $script);
898    return embellish_url($ret);
899  }
900
901  /**
902   * The "footer_script" block allows to add runtime script in the HTML page.
903   *
904   * @param array $params
905   *    - require (optional) comma separated list of script ids
906   * @param string $content
907   */
908  function block_footer_script($params, $content)
909  {
910    $content = trim($content);
911    if ( !empty($content) )
912    { // second call
913
914      $this->scriptLoader->add_inline(
915        $content,
916        empty($params['require']) ? array() : explode(',', $params['require'])
917      );
918    }
919  }
920
921  /**
922   * The "combine_css" function allows inclusion of a css file in the current page.
923   * The engine will combine several css files into a single one.
924   *
925   * @param array $params
926   *    - id (optional) used to deal with multiple inclusions from plugins
927   *    - path (required)
928   *    - version (optional) used to force a browser refresh
929   *    - order (optional)
930   *    - template (optional) set to true to allow smarty syntax in the css file
931   */
932  function func_combine_css($params)
933  {
934    if (empty($params['path']))
935    {
936      fatal_error('combine_css missing path');
937    }
938
939    if (!isset($params['id']))
940    {
941      $params['id'] = md5($params['path']);
942    }
943
944    $this->cssLoader->add($params['id'], $params['path'], isset($params['version']) ? $params['version'] : 0, (int)@$params['order'], (bool)@$params['template']);
945  }
946
947  /**
948   * The "get_combined_scripts" function returns a placeholder for delayed
949   * CSS files combination and minification.
950   *
951   * @param array $params (unused)
952   */
953  function func_get_combined_css($params)
954  {
955    return self::COMBINED_CSS_TAG;
956  }
957
958  /**
959   * Declares a Smarty prefilter from a plugin, allowing it to modify template
960   * source before compilation and without changing core files.
961   * They will be processed by weight ascending.
962   * @see http://www.smarty.net/manual/en/advanced.features.prefilters.php
963   *
964   * @param string $handle
965   * @param Callable $callback
966   * @param int $weight
967   */
968  function set_prefilter($handle, $callback, $weight=50)
969  {
970    $this->external_filters[$handle][$weight][] = array('pre', $callback);
971    ksort($this->external_filters[$handle]);
972  }
973
974  /**
975   * Declares a Smarty postfilter.
976   * They will be processed by weight ascending.
977   * @see http://www.smarty.net/manual/en/advanced.features.postfilters.php
978   *
979   * @param string $handle
980   * @param Callable $callback
981   * @param int $weight
982   */
983  function set_postfilter($handle, $callback, $weight=50)
984  {
985    $this->external_filters[$handle][$weight][] = array('post', $callback);
986    ksort($this->external_filters[$handle]);
987  }
988
989  /**
990   * Declares a Smarty outputfilter.
991   * They will be processed by weight ascending.
992   * @see http://www.smarty.net/manual/en/advanced.features.outputfilters.php
993   *
994   * @param string $handle
995   * @param Callable $callback
996   * @param int $weight
997   */
998  function set_outputfilter($handle, $callback, $weight=50)
999  {
1000    $this->external_filters[$handle][$weight][] = array('output', $callback);
1001    ksort($this->external_filters[$handle]);
1002  }
1003
1004  /**
1005   * Register the filters for the tpl file.
1006   *
1007   * @param string $handle
1008   */
1009  function load_external_filters($handle)
1010  {
1011    if (isset($this->external_filters[$handle]))
1012    {
1013      $compile_id = '';
1014      foreach ($this->external_filters[$handle] as $filters)
1015      {
1016        foreach ($filters as $filter)
1017        {
1018          list($type, $callback) = $filter;
1019          $compile_id .= $type.( is_array($callback) ? implode('', $callback) : $callback );
1020          $this->smarty->registerFilter($type, $callback);
1021        }
1022      }
1023      $this->smarty->compile_id .= '.'.base_convert(crc32($compile_id), 10, 36);
1024    }
1025  }
1026
1027  /**
1028   * Unregister the filters for the tpl file.
1029   *
1030   * @param string $handle
1031   */
1032  function unload_external_filters($handle)
1033  {
1034    if (isset($this->external_filters[$handle]))
1035    {
1036      foreach ($this->external_filters[$handle] as $filters)
1037      {
1038        foreach ($filters as $filter)
1039        {
1040          list($type, $callback) = $filter;
1041          $this->smarty->unregisterFilter($type, $callback);
1042        }
1043      }
1044    }
1045  }
1046
1047  /**
1048   * @toto : description of Template::prefilter_white_space
1049   *
1050   * @param string $source
1051   * @param Smarty $smarty
1052   * @param return string
1053   */
1054  static function prefilter_white_space($source, $smarty)
1055  {
1056    $ld = $smarty->left_delimiter;
1057    $rd = $smarty->right_delimiter;
1058    $ldq = preg_quote($ld, '#');
1059    $rdq = preg_quote($rd, '#');
1060
1061    $regex = array();
1062    $tags = array('if','foreach','section','footer_script');
1063    foreach($tags as $tag)
1064    {
1065      $regex[] = "#^[ \t]+($ldq$tag"."[^$ld$rd]*$rdq)\s*$#m";
1066      $regex[] = "#^[ \t]+($ldq/$tag$rdq)\s*$#m";
1067    }
1068    $tags = array('include','else','combine_script','html_head');
1069    foreach($tags as $tag)
1070    {
1071      $regex[] = "#^[ \t]+($ldq$tag"."[^$ld$rd]*$rdq)\s*$#m";
1072    }
1073    $source = preg_replace( $regex, "$1", $source);
1074    return $source;
1075  }
1076
1077  /**
1078   * Postfilter used when $conf['compiled_template_cache_language'] is true.
1079   *
1080   * @param string $source
1081   * @param Smarty $smarty
1082   * @param return string
1083   */
1084  static function postfilter_language($source, $smarty)
1085  {
1086    // replaces echo PHP_STRING_LITERAL; with the string literal value
1087    $source = preg_replace_callback(
1088      '/\\<\\?php echo ((?:\'(?:(?:\\\\.)|[^\'])*\')|(?:"(?:(?:\\\\.)|[^"])*"));\\?\\>\\n/',
1089      create_function('$matches', 'eval(\'$tmp=\'.$matches[1].\';\');return $tmp;'),
1090      $source);
1091    return $source;
1092  }
1093
1094  /**
1095   * Prefilter used to add theme local CSS files.
1096   *
1097   * @param string $source
1098   * @param Smarty $smarty
1099   * @param return string
1100   */
1101  static function prefilter_local_css($source, $smarty)
1102  {
1103    $css = array();
1104    foreach ($smarty->getTemplateVars('themes') as $theme)
1105    {
1106      $f = PWG_LOCAL_DIR.'css/'.$theme['id'].'-rules.css';
1107      if (file_exists(PHPWG_ROOT_PATH.$f))
1108      {
1109        $css[] = "{combine_css path='$f' order=10}";
1110      }
1111    }
1112    $f = PWG_LOCAL_DIR.'css/rules.css';
1113    if (file_exists(PHPWG_ROOT_PATH.$f))
1114    {
1115      $css[] = "{combine_css path='$f' order=10}";
1116    }
1117
1118    if (!empty($css))
1119    {
1120      $source = str_replace("{get_combined_css}", implode( "\n", $css )."\n{get_combined_css}", $source);
1121    }
1122
1123    return $source;
1124  }
1125
1126  /**
1127   * Loads the configuration file from a theme directory and returns it.
1128   *
1129   * @param string $dir
1130   * @return array
1131   */
1132  function load_themeconf($dir)
1133  {
1134    global $themeconfs, $conf;
1135
1136    $dir = realpath($dir);
1137    if (!isset($themeconfs[$dir]))
1138    {
1139      $themeconf = array();
1140      include($dir.'/themeconf.inc.php');
1141      // Put themeconf in cache
1142      $themeconfs[$dir] = $themeconf;
1143    }
1144    return $themeconfs[$dir];
1145  }
1146
1147  /**
1148   * Registers a button to be displayed on picture page.
1149   *
1150   * @param string $content
1151   * @param int $rank
1152   */
1153  function add_picture_button($content, $rank=BUTTONS_RANK_NEUTRAL)
1154  {
1155    $this->picture_buttons[$rank][] = $content;
1156  }
1157
1158  /**
1159   * Registers a button to be displayed on index pages.
1160   *
1161   * @param string $content
1162   * @param int $rank
1163   */
1164  function add_index_button($content, $rank=BUTTONS_RANK_NEUTRAL)
1165  {
1166    $this->index_buttons[$rank][] = $content;
1167  }
1168
1169  /**
1170   * Assigns PLUGIN_PICTURE_BUTTONS template variable with registered picture buttons.
1171   */
1172  function parse_picture_buttons()
1173  {
1174    if (!empty($this->picture_buttons))
1175    {
1176      ksort($this->picture_buttons);
1177      $buttons = array();
1178      foreach ($this->picture_buttons as $k => $row)
1179      {
1180        $buttons = array_merge($buttons, $row);
1181      }
1182      $this->assign('PLUGIN_PICTURE_BUTTONS', $buttons);
1183
1184      // only for PHP 5.3
1185      // $this->assign('PLUGIN_PICTURE_BUTTONS',
1186          // array_reduce(
1187            // $this->picture_buttons,
1188            // create_function('$v,$w', 'return array_merge($v, $w);'),
1189            // array()
1190          // ));
1191    }
1192  }
1193
1194  /**
1195   * Assigns PLUGIN_INDEX_BUTTONS template variable with registered index buttons.
1196   */
1197  function parse_index_buttons()
1198  {
1199    if (!empty($this->index_buttons))
1200    {
1201      ksort($this->index_buttons);
1202      $buttons = array();
1203      foreach ($this->index_buttons as $k => $row)
1204      {
1205        $buttons = array_merge($buttons, $row);
1206      }
1207      $this->assign('PLUGIN_INDEX_BUTTONS', $buttons);
1208
1209      // only for PHP 5.3
1210      // $this->assign('PLUGIN_INDEX_BUTTONS',
1211          // array_reduce(
1212            // $this->index_buttons,
1213            // create_function('$v,$w', 'return array_merge($v, $w);'),
1214            // array()
1215          // ));
1216    }
1217  }
1218}
1219
1220
1221/**
1222 * This class contains basic functions that can be called directly from the
1223 * templates in the form $pwg->l10n('edit')
1224 */
1225class PwgTemplateAdapter
1226{
1227  /**
1228   * @deprecated use "translate" modifier
1229   */
1230  function l10n($text)
1231  {
1232    return l10n($text);
1233  }
1234
1235  /**
1236   * @deprecated use "translate_dec" modifier
1237   */
1238  function l10n_dec($s, $p, $v)
1239  {
1240    return l10n_dec($s, $p, $v);
1241  }
1242
1243  /**
1244   * @deprecated use "translate" or "sprintf" modifier
1245   */
1246  function sprintf()
1247  {
1248    $args = func_get_args();
1249    return call_user_func_array('sprintf',  $args );
1250  }
1251
1252  /**
1253   * @param string $type
1254   * @param array $img
1255   * @return DerivativeImage
1256   */
1257  function derivative($type, $img)
1258  {
1259    return new DerivativeImage($type, $img);
1260  }
1261
1262  /**
1263   * @param string $type
1264   * @param array $img
1265   * @return string
1266   */
1267  function derivative_url($type, $img)
1268  {
1269    return DerivativeImage::url($type, $img);
1270  }
1271}
1272
1273
1274/**
1275 * A Combinable represents a JS or CSS file ready for cobination and minification.
1276 */
1277class Combinable
1278{
1279  /** @var string */
1280  public $id;
1281  /** @var string */
1282  public $path;
1283  /** @var string */
1284  public $version;
1285  /** @var bool */
1286  public $is_template;
1287
1288  /**
1289   * @param string $id
1290   * @param string $path
1291   * @param string $version
1292   */
1293  function __construct($id, $path, $version=0)
1294  {
1295    $this->id = $id;
1296    $this->set_path($path);
1297    $this->version = $version;
1298    $this->is_template = false;
1299  }
1300
1301  /**
1302   * @param string $path
1303   */
1304  function set_path($path)
1305  {
1306    if (!empty($path))
1307      $this->path = $path;
1308  }
1309
1310  /**
1311   * @return bool
1312   */
1313  function is_remote()
1314  {
1315    return url_is_remote($this->path) || strncmp($this->path, '//', 2)==0;
1316  }
1317}
1318
1319/**
1320 * Implementation of Combinable for JS files.
1321 */
1322final class Script extends Combinable
1323{
1324  /** @var int 0,1,2 */
1325  public $load_mode;
1326  /** @var array */
1327  public $precedents;
1328  /** @var array */
1329  public $extra;
1330
1331  /**
1332   * @param int 0,1,2
1333   * @param string $id
1334   * @param string $path
1335   * @param string $version
1336   * @param array $precedents
1337   */
1338  function __construct($load_mode, $id, $path, $version=0, $precedents=array())
1339  {
1340    parent::__construct($id, $path, $version);
1341    $this->load_mode = $load_mode;
1342    $this->precedents = $precedents;
1343    $this->extra = array();
1344  }
1345}
1346
1347/**
1348 * Implementation of Combinable for CSS files.
1349 */
1350final class Css extends Combinable
1351{
1352  /** @var int */
1353  public $order;
1354
1355  /**
1356   * @param string $id
1357   * @param string $path
1358   * @param string $version
1359   * @param int $order
1360   */
1361  function __construct($id, $path, $version=0, $order=0)
1362  {
1363    parent::__construct($id, $path, $version);
1364    $this->order = $order;
1365  }
1366}
1367
1368
1369/**
1370 * Manages a list of CSS files and combining them in a unique file.
1371 */
1372class CssLoader
1373{
1374  /** @param Css[] */
1375  private $registered_css;
1376  /** @param int used to keep declaration order */
1377  private $counter;
1378
1379  function __construct()
1380  {
1381    $this->clear();
1382  }
1383
1384  function clear()
1385  {
1386    $this->registered_css = array();
1387    $this->counter = 0;
1388  }
1389
1390  /**
1391   * @return Combinable[] array of combined CSS.
1392   */
1393  function get_css()
1394  {
1395    uasort($this->registered_css, array('CssLoader', 'cmp_by_order'));
1396    $combiner = new FileCombiner('css', $this->registered_css);
1397    return $combiner->combine();
1398  }
1399
1400  /**
1401   * Callback for CSS files sorting.
1402   */
1403  private static function cmp_by_order($a, $b)
1404  {
1405    return $a->order - $b->order;
1406  }
1407
1408  /**
1409   * Adds a new file, if a file with the same $id already exsists, the one with
1410   * the higher $order or higher $version is kept.
1411   *
1412   * @param string $id
1413   * @param string $path
1414   * @param string $version
1415   * @param int $order
1416   * @param bool $is_template
1417   */
1418  function add($id, $path, $version=0, $order=0, $is_template=false)
1419  {
1420    if (!isset($this->registered_css[$id]))
1421    {
1422      // costum order as an higher impact than declaration order
1423      $css = new Css($id, $path, $version, $order*1000+$this->counter);
1424      $css->is_template = $is_template;
1425      $this->registered_css[$id] = $css;
1426      $this->counter++;
1427    }
1428    else
1429    {
1430      $css = $this->registered_css[$id];
1431      if ($css->order<$order*1000 || version_compare($css->version, $version)<0)
1432      {
1433        unset($this->registered_css[$id]);
1434        $this->add($id, $path, $version, $order, $is_template);
1435      }
1436    }
1437  }
1438}
1439
1440
1441/**
1442 * Manage a list of required scripts for a page, by optimizing their loading location (head, footer, async)
1443 * and later on by combining them in a unique file respecting at the same time dependencies.
1444 */
1445class ScriptLoader
1446{
1447  /** @var Script[] */
1448  private $registered_scripts;
1449  /** @var string[] */
1450  public $inline_scripts;
1451
1452  /** @var bool */
1453  private $did_head;
1454  /** @var bool */
1455  private $head_done_scripts;
1456  /** @var bool */
1457  private $did_footer;
1458
1459  private static $known_paths = array(
1460      'core.scripts' => 'themes/default/js/scripts.js',
1461      'jquery' => 'themes/default/js/jquery.min.js',
1462      'jquery.ui' => 'themes/default/js/ui/minified/jquery.ui.core.min.js',
1463      'jquery.ui.effect' => 'themes/default/js/ui/minified/jquery.ui.effect.min.js',
1464    );
1465
1466  private static $ui_core_dependencies = array(
1467      'jquery.ui.widget' => array('jquery'),
1468      'jquery.ui.position' => array('jquery'),
1469      'jquery.ui.mouse' => array('jquery', 'jquery.ui', 'jquery.ui.widget'),
1470    );
1471
1472  function __construct()
1473  {
1474    $this->clear();
1475  }
1476
1477  function clear()
1478  {
1479    $this->registered_scripts = array();
1480    $this->inline_scripts = array();
1481    $this->head_done_scripts = array();
1482    $this->did_head = $this->did_footer = false;
1483  }
1484
1485  /**
1486   * @return bool
1487   */
1488  function did_head()
1489  {
1490    return $this->did_head;
1491  }
1492
1493  /**
1494   * @return Script[]
1495   */
1496  function get_all()
1497  {
1498    return $this->registered_scripts;
1499  }
1500
1501  /**
1502   * @param string $code
1503   * @param string[] $require
1504   */
1505  function add_inline($code, $require)
1506  {
1507    !$this->did_footer || trigger_error("Attempt to add inline script but the footer has been written", E_USER_WARNING);
1508    if(!empty($require))
1509    {
1510      foreach ($require as $id)
1511      {
1512        if(!isset($this->registered_scripts[$id]))
1513          $this->load_known_required_script($id, 1) or fatal_error("inline script not found require $id");
1514        $s = $this->registered_scripts[$id];
1515        if($s->load_mode==2)
1516          $s->load_mode=1; // until now the implementation does not allow executing inline script depending on another async script
1517      }
1518    }
1519    $this->inline_scripts[] = $code;
1520  }
1521
1522  /**
1523   * @param string $id
1524   * @param int $load_mode
1525   * @param string[] $require
1526   * @param string $path
1527   * @param string $version
1528   */
1529  function add($id, $load_mode, $require, $path, $version=0, $is_template=false)
1530  {
1531    if ($this->did_head && $load_mode==0)
1532    {
1533      trigger_error("Attempt to add script $id but the head has been written", E_USER_WARNING);
1534    }
1535    elseif ($this->did_footer)
1536    {
1537      trigger_error("Attempt to add script $id but the footer has been written", E_USER_WARNING);
1538    }
1539    if (! isset( $this->registered_scripts[$id] ) )
1540    {
1541      $script = new Script($load_mode, $id, $path, $version, $require);
1542      $script->is_template = $is_template;
1543      self::fill_well_known($id, $script);
1544      $this->registered_scripts[$id] = $script;
1545
1546      // Load or modify all UI core files
1547      if ($id == 'jquery.ui' and $script->path == self::$known_paths['jquery.ui'])
1548      {
1549        foreach (self::$ui_core_dependencies as $script_id => $required_ids)
1550          $this->add($script_id, $load_mode, $required_ids, null, $version);
1551      }
1552
1553      // Try to load undefined required script
1554      foreach ($script->precedents as $script_id)
1555      {
1556        if (! isset( $this->registered_scripts[$script_id] ) )
1557          $this->load_known_required_script($script_id, $load_mode);
1558      }
1559    }
1560    else
1561    {
1562      $script = $this->registered_scripts[$id];
1563      if (count($require))
1564      {
1565        $script->precedents = array_unique( array_merge($script->precedents, $require) );
1566      }
1567      $script->set_path($path);
1568      if ($version && version_compare($script->version, $version)<0 )
1569        $script->version = $version;
1570      if ($load_mode < $script->load_mode)
1571        $script->load_mode = $load_mode;
1572    }
1573  }
1574
1575  /**
1576   * Returns combined scripts loaded in header.
1577   *
1578   * @return Combinable[]
1579   */
1580  function get_head_scripts()
1581  {
1582    self::check_load_dep($this->registered_scripts);
1583    foreach( array_keys($this->registered_scripts) as $id )
1584    {
1585      $this->compute_script_topological_order($id);
1586    }
1587
1588    uasort($this->registered_scripts, array('ScriptLoader', 'cmp_by_mode_and_order'));
1589
1590    foreach( $this->registered_scripts as $id => $script)
1591    {
1592      if ($script->load_mode > 0)
1593        break;
1594      if ( !empty($script->path) )
1595        $this->head_done_scripts[$id] = $script;
1596      else
1597        trigger_error("Script $id has an undefined path", E_USER_WARNING);
1598    }
1599    $this->did_head = true;
1600    return self::do_combine($this->head_done_scripts, 0);
1601  }
1602
1603  /**
1604   * Returns combined scripts loaded in footer.
1605   *
1606   * @return Combinable[]
1607   */
1608  function get_footer_scripts()
1609  {
1610    if (!$this->did_head)
1611    {
1612      self::check_load_dep($this->registered_scripts);
1613    }
1614    $this->did_footer = true;
1615    $todo = array();
1616    foreach( $this->registered_scripts as $id => $script)
1617    {
1618      if (!isset($this->head_done_scripts[$id]))
1619      {
1620        $todo[$id] = $script;
1621      }
1622    }
1623
1624    foreach( array_keys($todo) as $id )
1625    {
1626      $this->compute_script_topological_order($id);
1627    }
1628
1629    uasort($todo, array('ScriptLoader', 'cmp_by_mode_and_order'));
1630
1631    $result = array( array(), array() );
1632    foreach( $todo as $id => $script)
1633    {
1634      $result[$script->load_mode-1][$id] = $script;
1635    }
1636    return array( self::do_combine($result[0],1), self::do_combine($result[1],2) );
1637  }
1638
1639  /**
1640   * @param Script[] $scripts
1641   * @param int $load_mode
1642   * @return Combinable[]
1643   */
1644  private static function do_combine($scripts, $load_mode)
1645  {
1646    $combiner = new FileCombiner('js', $scripts);
1647    return $combiner->combine();
1648  }
1649
1650  /**
1651   * Checks dependencies among Scripts.
1652   * Checks that if B depends on A, then B->load_mode >= A->load_mode in order to respect execution order.
1653   *
1654   * @param Script[] $scripts
1655   */
1656  private static function check_load_dep($scripts)
1657  {
1658    global $conf;
1659    do
1660    {
1661      $changed = false;
1662      foreach( $scripts as $id => $script)
1663      {
1664        $load = $script->load_mode;
1665        foreach( $script->precedents as $precedent)
1666        {
1667          if ( !isset($scripts[$precedent] ) )
1668            continue;
1669          if ( $scripts[$precedent]->load_mode > $load )
1670          {
1671            $scripts[$precedent]->load_mode = $load;
1672            $changed = true;
1673          }
1674          if ($load==2 && $scripts[$precedent]->load_mode==2 && ($scripts[$precedent]->is_remote() or !$conf['template_combine_files']) )
1675          {// we are async -> a predecessor cannot be async unlesss it can be merged; otherwise script execution order is not guaranteed
1676            $scripts[$precedent]->load_mode = 1;
1677            $changed = true;
1678          }
1679        }
1680      }
1681    }
1682    while ($changed);
1683  }
1684
1685  /**
1686   * Fill a script dependancies with the known jQuery UI scripts.
1687   *
1688   * @param string $id in FileCombiner::$known_paths
1689   * @param Script $script
1690   */
1691  private static function fill_well_known($id, $script)
1692  {
1693    if ( empty($script->path) && isset(self::$known_paths[$id]))
1694    {
1695      $script->path = self::$known_paths[$id];
1696    }
1697    if ( strncmp($id, 'jquery.', 7)==0 )
1698    {
1699      $required_ids = array('jquery');
1700
1701      if ( strncmp($id, 'jquery.ui.effect-', 17)==0 )
1702      {
1703        $required_ids = array('jquery', 'jquery.ui.effect');
1704
1705        if ( empty($script->path) )
1706          $script->path = dirname(self::$known_paths['jquery.ui.effect'])."/$id.min.js";
1707      }
1708      elseif ( strncmp($id, 'jquery.ui.', 10)==0 )
1709      {
1710        if ( !isset(self::$ui_core_dependencies[$id]) )
1711          $required_ids = array_merge(array('jquery', 'jquery.ui'), array_keys(self::$ui_core_dependencies));
1712
1713        if ( empty($script->path) )
1714          $script->path = dirname(self::$known_paths['jquery.ui'])."/$id.min.js";
1715      }
1716
1717      foreach ($required_ids as $required_id)
1718      {
1719        if ( !in_array($required_id, $script->precedents ) )
1720          $script->precedents[] = $required_id;
1721      }
1722    }
1723  }
1724
1725  /**
1726   * Add a known jQuery UI script to loaded scripts.
1727   *
1728   * @param string $id in FileCombiner::$known_paths
1729   * @param int $load_mode
1730   * @return bool
1731   */
1732  private function load_known_required_script($id, $load_mode)
1733  {
1734    if ( isset(self::$known_paths[$id]) or strncmp($id, 'jquery.ui.', 10)==0  )
1735    {
1736      $this->add($id, $load_mode, array(), null);
1737      return true;
1738    }
1739    return false;
1740  }
1741
1742  /**
1743   * Compute script order depending on dependencies.
1744   * Assigned to $script->extra['order'].
1745   *
1746   * @param string $script_id
1747   * @param int $recursion_limiter
1748   * @return int
1749   */
1750  private function compute_script_topological_order($script_id, $recursion_limiter=0)
1751  {
1752    if (!isset($this->registered_scripts[$script_id]))
1753    {
1754      trigger_error("Undefined script $script_id is required by someone", E_USER_WARNING);
1755      return 0;
1756    }
1757    $recursion_limiter<5 or fatal_error("combined script circular dependency");
1758    $script = $this->registered_scripts[$script_id];
1759    if (isset($script->extra['order']))
1760      return $script->extra['order'];
1761    if (count($script->precedents) == 0)
1762      return ($script->extra['order'] = 0);
1763    $max = 0;
1764    foreach( $script->precedents as $precedent)
1765      $max = max($max, $this->compute_script_topological_order($precedent, $recursion_limiter+1) );
1766    $max++;
1767    return ($script->extra['order'] = $max);
1768  }
1769
1770  /**
1771   * Callback for scripts sorter.
1772   */
1773  private static function cmp_by_mode_and_order($s1, $s2)
1774  {
1775    $ret = $s1->load_mode - $s2->load_mode;
1776    if ($ret) return $ret;
1777
1778    $ret = $s1->extra['order'] - $s2->extra['order'];
1779    if ($ret) return $ret;
1780
1781    if ($s1->extra['order']==0 and ($s1->is_remote() xor $s2->is_remote()) )
1782    {
1783      return $s1->is_remote() ? -1 : 1;
1784    }
1785    return strcmp($s1->id,$s2->id);
1786  }
1787}
1788
1789
1790/**
1791 * Allows merging of javascript and css files into a single one.
1792 */
1793final class FileCombiner
1794{
1795  /** @var string 'js' or 'css' */
1796  private $type;
1797  /** @var bool */
1798  private $is_css;
1799  /** @var Combinable[] */
1800  private $combinables;
1801
1802  /**
1803   * @param string $type 'js' or 'css'
1804   * @param Combinable[] $combinables
1805   */
1806  function __construct($type, $combinables=array())
1807  {
1808    $this->type = $type;
1809    $this->is_css = $type=='css';
1810    $this->combinables = $combinables;
1811  }
1812
1813  /**
1814   * Deletes all combined files from cache directory.
1815   */
1816  static function clear_combined_files()
1817  {
1818    $dir = opendir(PHPWG_ROOT_PATH.PWG_COMBINED_DIR);
1819    while ($file = readdir($dir))
1820    {
1821      if ( get_extension($file)=='js' || get_extension($file)=='css')
1822        unlink(PHPWG_ROOT_PATH.PWG_COMBINED_DIR.$file);
1823    }
1824    closedir($dir);
1825  }
1826
1827  /**
1828   * @param Combinable|Combinable[] $combinable
1829   */
1830  function add($combinable)
1831  {
1832    if (is_array($combinable))
1833    {
1834      $this->combinables = array_merge($this->combinables, $combinable);
1835    }
1836    else
1837    {
1838      $this->combinables[] = $combinable;
1839    }
1840  }
1841
1842  /**
1843   * @return Combinable[]
1844   */
1845  function combine()
1846  {
1847    global $conf;
1848    $force = false;
1849    if (is_admin() && ($this->is_css || !$conf['template_compile_check']) )
1850    {
1851      $force = (isset($_SERVER['HTTP_CACHE_CONTROL']) && strpos($_SERVER['HTTP_CACHE_CONTROL'], 'max-age=0') !== false)
1852        || (isset($_SERVER['HTTP_PRAGMA']) && strpos($_SERVER['HTTP_PRAGMA'], 'no-cache'));
1853    }
1854
1855    $result = array();
1856    $pending = array();
1857    $ini_key = $this->is_css ? array(get_absolute_root_url(false)): array(); //because for css we modify bg url;
1858    $key = $ini_key;
1859
1860    foreach ($this->combinables as $combinable)
1861    {
1862      if ($combinable->is_remote())
1863      {
1864        $this->flush_pending($result, $pending, $key, $force);
1865        $key = $ini_key;
1866        $result[] = $combinable;
1867        continue;
1868      }
1869      elseif (!$conf['template_combine_files'])
1870      {
1871        $this->flush_pending($result, $pending, $key, $force);
1872        $key = $ini_key;
1873      }
1874
1875      $key[] = $combinable->path;
1876      $key[] = $combinable->version;
1877      if ($conf['template_compile_check'])
1878        $key[] = filemtime( PHPWG_ROOT_PATH . $combinable->path );
1879      $pending[] = $combinable;
1880    }
1881    $this->flush_pending($result, $pending, $key, $force);
1882    return $result;
1883  }
1884
1885  /**
1886   * Process a set of pending files.
1887   *
1888   * @param array &$result
1889   * @param array &$pending
1890   * @param string[] $key
1891   * @param bool $force
1892   */
1893  private function flush_pending(&$result, &$pending, $key, $force)
1894  {
1895    if (count($pending)>1)
1896    {
1897      $key = join('>', $key);
1898      $file = PWG_COMBINED_DIR . base_convert(crc32($key),10,36) . '.' . $this->type;
1899      if ($force || !file_exists(PHPWG_ROOT_PATH.$file) )
1900      {
1901        $output = '';
1902        foreach ($pending as $combinable)
1903        {
1904          $output .= "/*BEGIN $combinable->path */\n";
1905          $output .= $this->process_combinable($combinable, true, $force);
1906          $output .= "\n";
1907        }
1908        mkgetdir( dirname(PHPWG_ROOT_PATH.$file) );
1909        file_put_contents( PHPWG_ROOT_PATH.$file, $output );
1910        @chmod(PHPWG_ROOT_PATH.$file, 0644);
1911      }
1912      $result[] = new Combinable("combi", $file, false);
1913    }
1914    elseif ( count($pending)==1)
1915    {
1916      $this->process_combinable($pending[0], false, $force);
1917      $result[] = $pending[0];
1918    }
1919    $key = array();
1920    $pending = array();
1921  }
1922
1923  /**
1924   * Process one combinable file.
1925   *
1926   * @param Combinable $combinable
1927   * @param bool $return_content
1928   * @param bool $force
1929   * @return null|string
1930   */
1931  private function process_combinable($combinable, $return_content, $force)
1932  {
1933    global $conf;
1934    if ($combinable->is_template)
1935    {
1936      if (!$return_content)
1937      {
1938        $key = array($combinable->path, $combinable->version);
1939        if ($conf['template_compile_check'])
1940          $key[] = filemtime( PHPWG_ROOT_PATH . $combinable->path );
1941        $file = PWG_COMBINED_DIR . 't' . base_convert(crc32(implode(',',$key)),10,36) . '.' . $this->type;
1942        if (!$force && file_exists(PHPWG_ROOT_PATH.$file) )
1943        {
1944          $combinable->path = $file;
1945          $combinable->version = false;
1946          return;
1947        }
1948      }
1949
1950      global $template;
1951      $handle = $this->type. '.' .$combinable->id;
1952      $template->set_filename($handle, realpath(PHPWG_ROOT_PATH.$combinable->path));
1953      trigger_notify( 'combinable_preparse', $template, $combinable, $this); //allow themes and plugins to set their own vars to template ...
1954      $content = $template->parse($handle, true);
1955
1956      if ($this->is_css)
1957        $content = self::process_css($content, $combinable->path );
1958      else
1959        $content = self::process_js($content, $combinable->path );
1960
1961      if ($return_content)
1962        return $content;
1963      file_put_contents( PHPWG_ROOT_PATH.$file, $content );
1964      $combinable->path = $file;
1965    }
1966    elseif ($return_content)
1967    {
1968      $content = file_get_contents(PHPWG_ROOT_PATH . $combinable->path);
1969      if ($this->is_css)
1970        $content = self::process_css($content, $combinable->path );
1971      else
1972        $content = self::process_js($content, $combinable->path );
1973      return $content;
1974    }
1975  }
1976
1977  /**
1978   * Process a JS file.
1979   *
1980   * @param string $js file content
1981   * @param string $file
1982   * @return string
1983   */
1984  private static function process_js($js, $file)
1985  {
1986    if (strpos($file, '.min')===false and strpos($file, '.packed')===false )
1987    {
1988      require_once(PHPWG_ROOT_PATH.'include/jshrink.class.php');
1989      try { $js = JShrink_Minifier::minify($js); } catch(Exception $e) {}
1990    }
1991    return trim($js, " \t\r\n;").";\n";
1992  }
1993
1994  /**
1995   * Process a CSS file.
1996   *
1997   * @param string $css file content
1998   * @param string $file
1999   * @return string
2000   */
2001  private static function process_css($css, $file)
2002  {
2003    $css = self::process_css_rec($css, dirname($file));
2004    if (strpos($file, '.min')===false and version_compare(PHP_VERSION, '5.2.4', '>='))
2005    {
2006      require_once(PHPWG_ROOT_PATH.'include/cssmin.class.php');
2007      $css = CssMin::minify($css, array('Variables'=>false));
2008    }
2009    $css = trigger_change('combined_css_postfilter', $css);
2010    return $css;
2011  }
2012
2013  /**
2014   * Resolves relative links in CSS file.
2015   *
2016   * @param string $css file content
2017   * @param string $dir
2018   * @return string
2019   */
2020  private static function process_css_rec($css, $dir)
2021  {
2022    static $PATTERN_URL = "#url\(\s*['|\"]{0,1}(.*?)['|\"]{0,1}\s*\)#";
2023    static $PATTERN_IMPORT = "#@import\s*['|\"]{0,1}(.*?)['|\"]{0,1};#";
2024
2025    if (preg_match_all($PATTERN_URL, $css, $matches, PREG_SET_ORDER))
2026    {
2027      $search = $replace = array();
2028      foreach ($matches as $match)
2029      {
2030        if ( !url_is_remote($match[1]) && $match[1][0] != '/' && strpos($match[1], 'data:image/')===false)
2031        {
2032          $relative = $dir . "/$match[1]";
2033          $search[] = $match[0];
2034          $replace[] = 'url('.embellish_url(get_absolute_root_url(false).$relative).')';
2035        }
2036      }
2037      $css = str_replace($search, $replace, $css);
2038    }
2039
2040    if (preg_match_all($PATTERN_IMPORT, $css, $matches, PREG_SET_ORDER))
2041    {
2042      $search = $replace = array();
2043      foreach ($matches as $match)
2044      {
2045        $search[] = $match[0];
2046        $sub_css = file_get_contents(PHPWG_ROOT_PATH . $dir . "/$match[1]");
2047        $replace[] = self::process_css_rec($sub_css, dirname($dir . "/$match[1]") );
2048      }
2049      $css = str_replace($search, $replace, $css);
2050    }
2051    return $css;
2052  }
2053}
2054
2055?>
Note: See TracBrowser for help on using the repository browser.