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

Last change on this file since 25231 was 25231, checked in by rvelices, 11 years ago

private method becomes public (use in plugin)

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