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

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

feature 2999: documentation of Template class, other classes of template.class.php pending

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