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

Last change on this file since 28988 was 28917, checked in by plg, 10 years ago

i18n for the new HTML5 upload (use i18n files from plupload)

optional specific $lang_info[jquery_code] and $lang_info[plupload_code] to load the right i18n file

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