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

Last change on this file since 27455 was 27184, checked in by rvelices, 10 years ago

remove Smarty backward compatible class (pre Smarty3)

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