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

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

FileCombiner does not try to change url of images embedded in base64

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