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

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

bug 2858: Smarty3 fix php warnings, concat, used modifier on array

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