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

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

smarty 3 - first pass for tests

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