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

Last change on this file since 23263 was 23263, checked in by mistic100, 11 years ago

feature:2785 Improve template method to sort actions buttons
+ add default rank = 50

  • 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;
[2216]59    $this->smarty = new Smarty;
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
88    $this->smarty->compile_dir = $compile_dir;
89
90    $this->smarty->assign_by_ref( 'pwg', new PwgTemplateAdapter() );
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
[5123]108    $this->smarty->template_dir = 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  {
[5123]168    $this->smarty->template_dir[] = $dir;
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  {
183    return $this->smarty->template_dir;
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;
193      $this->smarty->clear_compiled_tpl();
194      $this->smarty->compile_id = $save_compile_id;
[2497]195      file_put_contents($this->smarty->compile_dir.'/index.htm', 'Not allowed!');
[2278]196  }
197
[2216]198  function get_themeconf($val)
199  {
200    $tc = $this->smarty->get_template_vars('themeconf');
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 */
343  function &get_template_vars($name=null)
344  {
345    return $this->smarty->get_template_vars( $name );
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
[2290]372    $v = $this->smarty->fetch($this->files[$handle], null, null, false);
[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        );
488      require_once(SMARTY_CORE_DIR . 'core.display_debug_console.php');
489      echo smarty_core_display_debug_console(null, $this->smarty);
490    }
[2216]491  }
492
493  /**
[2286]494   * translate variable modifier - translates a text to the currently loaded
495   * language
[2216]496   */
[2536]497  static function mod_translate($text)
[2216]498  {
[2286]499    return l10n($text);
[2216]500  }
501
502  /**
[2286]503   * explode variable modifier - similar to php explode
[2290]504   * 'Yes;No'|@explode:';' -> array('Yes', 'No')
[2216]505   */
[2536]506  static function mod_explode($text, $delimiter=',')
[2216]507  {
[2286]508    return explode($delimiter, $text);
[2216]509  }
[2476]510
[2334]511  /**
512   * This smarty "html_head" block allows to add content just before
513   * </head> element in the output after the head has been parsed. This is
514   * handy in order to respect strict standards when <style> and <link>
[2476]515   * html elements must appear in the <head> element
[2334]516   */
[17021]517  function block_html_head($params, $content)
[2334]518  {
519    $content = trim($content);
520    if ( !empty($content) )
521    { // second call
[2627]522      $this->html_head_elements[] = $content;
[2334]523    }
524  }
[2476]525
[17021]526  function block_html_style($params, $content)
[12920]527  {
528    $content = trim($content);
529    if ( !empty($content) )
530    { // second call
[20370]531      $this->html_style .= "\n".$content;
[12920]532    }
533  }
534
[17021]535  function func_define_derivative($params)
[12954]536  {
[13871]537    !empty($params['name']) or fatal_error('define_derivative missing name');
[12954]538    if (isset($params['type']))
539    {
540      $derivative = ImageStdParams::get_by_type($params['type']);
[17021]541      $this->smarty->assign( $params['name'], $derivative);
[12954]542      return;
543    }
[13871]544    !empty($params['width']) or fatal_error('define_derivative missing width');
545    !empty($params['height']) or fatal_error('define_derivative missing height');
[12954]546
[13021]547    $w = intval($params['width']);
548    $h = intval($params['height']);
549    $crop = 0;
550    $minw=null;
551    $minh=null;
[18630]552
[12954]553    if (isset($params['crop']))
554    {
555      if (is_bool($params['crop']))
556      {
[13021]557        $crop = $params['crop'] ? 1:0;
[12954]558      }
559      else
560      {
[13021]561        $crop = round($params['crop']/100, 2);
[12954]562      }
563
[13021]564      if ($crop)
[12954]565      {
[13021]566        $minw = empty($params['min_width']) ? $w : intval($params['min_width']);
[13871]567        $minw <= $w or fatal_error('define_derivative invalid min_width');
[13021]568        $minh = empty($params['min_height']) ? $h : intval($params['min_height']);
[13871]569        $minh <= $h or fatal_error('define_derivative invalid min_height');
[12954]570      }
571    }
572
[17021]573    $this->smarty->assign( $params['name'], ImageStdParams::get_custom($w, $h, $crop, $minw, $minh) );
[12954]574  }
575
[11753]576   /**
[8506]577    * combine_script smarty function allows inclusion of a javascript file in the current page.
578    * The engine will combine several js files into a single one in order to reduce the number of
579    * required http requests.
580    * param id - required
581    * param path - required - the path to js file RELATIVE to piwigo root dir
582    * param load - optional - header|footer|async, default header
583    * param require - optional - comma separated list of script ids required to be loaded and executed
584        before this one
585    * param version - optional - plugins could use this and change it in order to force a
586        browser refresh
587    */
[17021]588  function func_combine_script($params)
[7975]589  {
590    if (!isset($params['id']))
591    {
[17021]592      $this->smarty->trigger_error("combine_script: missing 'id' parameter", E_USER_ERROR);
[7975]593    }
594    $load = 0;
595    if (isset($params['load']))
596    {
597      switch ($params['load'])
598      {
599        case 'header': break;
600        case 'footer': $load=1; break;
601        case 'async': $load=2; break;
[17021]602        default: $this->smarty->trigger_error("combine_script: invalid 'load' parameter", E_USER_ERROR);
[7975]603      }
604    }
[18775]605
[7995]606    $this->scriptLoader->add( $params['id'], $load,
607      empty($params['require']) ? array() : explode( ',', $params['require'] ),
608      @$params['path'],
[7975]609      isset($params['version']) ? $params['version'] : 0 );
610  }
[2513]611
[7975]612
[17021]613  function func_get_combined_scripts($params)
[7975]614  {
615    if (!isset($params['load']))
616    {
[17021]617      $this->smarty->trigger_error("get_combined_scripts: missing 'load' parameter", E_USER_ERROR);
[7975]618    }
619    $load = $params['load']=='header' ? 0 : 1;
620    $content = array();
[7995]621
[7975]622    if ($load==0)
623    {
[7987]624      return self::COMBINED_SCRIPTS_TAG;
[7975]625    }
626    else
627    {
628      $scripts = $this->scriptLoader->get_footer_scripts();
[8012]629      foreach ($scripts[0] as $script)
[7975]630      {
631        $content[]=
632          '<script type="text/javascript" src="'
[8012]633          . self::make_script_src($script)
[7975]634          .'"></script>';
635      }
[7995]636      if (count($this->scriptLoader->inline_scripts))
[7975]637      {
[8401]638        $content[]= '<script type="text/javascript">//<![CDATA[
[8299]639';
[7995]640        $content = array_merge($content, $this->scriptLoader->inline_scripts);
[8299]641        $content[]= '//]]></script>';
[7975]642      }
643
644      if (count($scripts[1]))
645      {
646        $content[]= '<script type="text/javascript">';
647        $content[]= '(function() {
[8725]648var s,after = document.getElementsByTagName(\'script\')[document.getElementsByTagName(\'script\').length-1];';
[7975]649        foreach ($scripts[1] as $id => $script)
650        {
651          $content[]=
[8378]652            's=document.createElement(\'script\'); s.type=\'text/javascript\'; s.async=true; s.src=\''
[8012]653            . self::make_script_src($script)
[7975]654            .'\';';
655          $content[]= 'after = after.parentNode.insertBefore(s, after);';
656        }
657        $content[]= '})();';
658        $content[]= '</script>';
659      }
660    }
661    return implode("\n", $content);
662  }
663
664
665  private static function make_script_src( $script )
666  {
667    $ret = '';
[8012]668    if ( $script->is_remote() )
[7975]669      $ret = $script->path;
670    else
671    {
[13240]672      $ret = get_root_url().$script->path;
[7975]673      if ($script->version!==false)
674      {
675        $ret.= '?v'. ($script->version ? $script->version : PHPWG_VERSION);
676      }
677    }
[8012]678    // trigger the event for eventual use of a cdn
679    $ret = trigger_event('combined_script', $ret, $script);
[13240]680    return embellish_url($ret);
[7975]681  }
682
[17021]683  function block_footer_script($params, $content)
[7975]684  {
685    $content = trim($content);
686    if ( !empty($content) )
687    { // second call
[18775]688
[9580]689      $this->scriptLoader->add_inline(
690        $content,
691        empty($params['require']) ? array() : explode(',', $params['require'])
692      );
[7975]693    }
694  }
[7995]695
[8506]696  /**
697    * combine_css smarty function allows inclusion of a css stylesheet file in the current page.
698    * The engine will combine several css files into a single one in order to reduce the number of
699    * required http requests.
700    * param path - required - the path to css file RELATIVE to piwigo root dir
701    * param version - optional - plugins could use this and change it in order to force a
702        browser refresh
703    */
[17021]704  function func_combine_css($params)
[7987]705  {
706    !empty($params['path']) || fatal_error('combine_css missing path');
707    $order = (int)@$params['order'];
708    $version = isset($params['version']) ? $params['version'] : 0;
709    $this->css_by_priority[$order][] = array( $params['path'], $version);
710  }
[7975]711
[17021]712  function func_get_combined_css($params)
[7987]713  {
[8378]714    return 'echo '.var_export(self::COMBINED_CSS_TAG,true);
[7987]715  }
716
717
[3927]718 /**
719   * This function allows to declare a Smarty prefilter from a plugin, thus allowing
720   * it to modify template source before compilation and without changing core files
721   * They will be processed by weight ascending.
722   * http://www.smarty.net/manual/en/advanced.features.prefilters.php
723   */
[3951]724  function set_prefilter($handle, $callback, $weight=50)
[3927]725  {
[3953]726    $this->external_filters[$handle][$weight][] = array('prefilter', $callback);
[3928]727    ksort($this->external_filters[$handle]);
[3927]728  }
[3951]729
730  function set_postfilter($handle, $callback, $weight=50)
731  {
[3953]732    $this->external_filters[$handle][$weight][] = array('postfilter', $callback);
[3951]733    ksort($this->external_filters[$handle]);
734  }
735
736  function set_outputfilter($handle, $callback, $weight=50)
737  {
[3953]738    $this->external_filters[$handle][$weight][] = array('outputfilter', $callback);
[3951]739    ksort($this->external_filters[$handle]);
740  }
[5177]741
[3927]742 /**
743   * This function actually triggers the filters on the tpl files.
744   * Called in the parse method.
745   * http://www.smarty.net/manual/en/advanced.features.prefilters.php
746   */
[3928]747  function load_external_filters($handle)
[3927]748  {
[3928]749    if (isset($this->external_filters[$handle]))
[3927]750    {
[3951]751      $compile_id = '';
[5177]752      foreach ($this->external_filters[$handle] as $filters)
[3928]753      {
[5177]754        foreach ($filters as $filter)
[3928]755        {
[3951]756          list($type, $callback) = $filter;
757          $compile_id .= $type.( is_array($callback) ? implode('', $callback) : $callback );
[3953]758          call_user_func(array($this->smarty, 'register_'.$type), $callback);
[3928]759        }
760      }
[3951]761      $this->smarty->compile_id .= '.'.base_convert(crc32($compile_id), 10, 36);
[3927]762    }
763  }
[3928]764
765  function unload_external_filters($handle)
766  {
767    if (isset($this->external_filters[$handle]))
768    {
[5177]769      foreach ($this->external_filters[$handle] as $filters)
[3928]770      {
[5177]771        foreach ($filters as $filter)
[3928]772        {
[3951]773          list($type, $callback) = $filter;
[3953]774          call_user_func(array($this->smarty, 'unregister_'.$type), $callback);
[3928]775        }
776      }
777    }
778  }
779
[2536]780  static function prefilter_white_space($source, &$smarty)
[2481]781  {
782    $ld = $smarty->left_delimiter;
783    $rd = $smarty->right_delimiter;
784    $ldq = preg_quote($ld, '#');
785    $rdq = preg_quote($rd, '#');
786
787    $regex = array();
[8378]788    $tags = array('if','foreach','section','footer_script');
[2481]789    foreach($tags as $tag)
790    {
[2489]791      array_push($regex, "#^[ \t]+($ldq$tag"."[^$ld$rd]*$rdq)\s*$#m");
792      array_push($regex, "#^[ \t]+($ldq/$tag$rdq)\s*$#m");
[2481]793    }
[8378]794    $tags = array('include','else','combine_script','html_head');
[2481]795    foreach($tags as $tag)
796    {
[2489]797      array_push($regex, "#^[ \t]+($ldq$tag"."[^$ld$rd]*$rdq)\s*$#m");
[2481]798    }
799    $source = preg_replace( $regex, "$1", $source);
800    return $source;
801  }
802
[2334]803  /**
[2476]804   * Smarty prefilter to allow caching (whenever possible) language strings
[2334]805   * from templates.
806   */
[2536]807  static function prefilter_language($source, &$smarty)
[2334]808  {
809    global $lang;
[2481]810    $ldq = preg_quote($smarty->left_delimiter, '~');
811    $rdq = preg_quote($smarty->right_delimiter, '~');
[2476]812
[2334]813    $regex = "~$ldq *\'([^'$]+)\'\|@translate *$rdq~";
[12427]814    $source = preg_replace_callback( $regex, create_function('$m', 'global $lang; return isset($lang[$m[1]]) ? $lang[$m[1]] : $m[0];'), $source);
[2334]815
816    $regex = "~$ldq *\'([^'$]+)\'\|@translate\|~";
[12656]817    $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]818
[12429]819    $regex = "~($ldq *assign +var=.+ +value=)\'([^'$]+)\'\|@translate~";
[12656]820    $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]821
[2334]822    return $source;
823  }
[5208]824
825  static function prefilter_local_css($source, &$smarty)
826  {
827    $css = array();
828    foreach ($smarty->get_template_vars('themes') as $theme)
829    {
[8722]830      $f = PWG_LOCAL_DIR.'css/'.$theme['id'].'-rules.css';
[7987]831      if (file_exists(PHPWG_ROOT_PATH.$f))
[5208]832      {
[7987]833        array_push($css, "{combine_css path='$f' order=10}");
[5208]834      }
835    }
[8722]836    $f = PWG_LOCAL_DIR.'css/rules.css';
[7987]837    if (file_exists(PHPWG_ROOT_PATH.$f))
[5208]838    {
[7987]839      array_push($css, "{combine_css path='$f' order=10}");
[5208]840    }
841
842    if (!empty($css))
843    {
[7987]844      $source = str_replace("\n{get_combined_css}", "\n".implode( "\n", $css )."\n{get_combined_css}", $source);
[5208]845    }
846
847    return $source;
848  }
[5446]849
850  function load_themeconf($dir)
851  {
[5448]852    global $themeconfs, $conf;
[5446]853
854    $dir = realpath($dir);
855    if (!isset($themeconfs[$dir]))
856    {
857      $themeconf = array();
858      include($dir.'/themeconf.inc.php');
859      // Put themeconf in cache
860      $themeconfs[$dir] = $themeconf;
861    }
862    return $themeconfs[$dir];
863  }
[21818]864
[23263]865  function add_picture_button($content, $rank=BUTTONS_RANK_NEUTRAL)
[18760]866  {
867    $this->picture_buttons[$rank][] = $content;
868  }
[21818]869
[23263]870  function add_index_button($content, $rank=BUTTONS_RANK_NEUTRAL)
[18760]871  {
872    $this->index_buttons[$rank][] = $content;
873  }
[21818]874
[18760]875  function parse_picture_buttons()
876  {
877    if (!empty($this->picture_buttons))
878    {
879      ksort($this->picture_buttons);
[23263]880      $this->assign('PLUGIN_PICTURE_BUTTONS', 
881          array_reduce(
882            $this->picture_buttons, 
883            create_function('$v,$w', 'return array_merge($v, $w);'), 
884            array()
885          ));
[18760]886    }
887  }
[21818]888
[18760]889  function parse_index_buttons()
890  {
891    if (!empty($this->index_buttons))
892    {
893      ksort($this->index_buttons);
[23263]894      $this->assign('PLUGIN_INDEX_BUTTONS', 
895          array_reduce(
896            $this->index_buttons, 
897            create_function('$v,$w', 'return array_merge($v, $w);'), 
898            array()
899          ));
[18760]900    }
901  }
[21818]902
[2216]903}
904
[3927]905
[2216]906/**
907 * This class contains basic functions that can be called directly from the
908 * templates in the form $pwg->l10n('edit')
909 */
910class PwgTemplateAdapter
911{
912  function l10n($text)
913  {
914    return l10n($text);
915  }
916
917  function l10n_dec($s, $p, $v)
918  {
919    return l10n_dec($s, $p, $v);
920  }
921
922  function sprintf()
923  {
924    $args = func_get_args();
925    return call_user_func_array('sprintf',  $args );
926  }
[12920]927
[13170]928  function derivative($type, $img)
929  {
930    return new DerivativeImage($type, $img);
931  }
932
[12908]933  function derivative_url($type, $img)
934  {
935    return DerivativeImage::url($type, $img);
936  }
[2216]937}
938
[7975]939
940final class Script
941{
[8008]942  public $id;
[7975]943  public $load_mode;
944  public $precedents = array();
945  public $path;
946  public $version;
947  public $extra = array();
948
[8012]949  function Script($load_mode, $id, $path, $version, $precedents)
[7975]950  {
[8008]951    $this->id = $id;
[7975]952    $this->load_mode = $load_mode;
[8012]953    $this->id = $id;
954    $this->set_path($path);
955    $this->version = $version;
[7975]956    $this->precedents = $precedents;
957  }
958
959  function set_path($path)
960  {
961    if (!empty($path))
962      $this->path = $path;
963  }
[8012]964
[7995]965  function is_remote()
966  {
[23184]967    return url_is_remote( $this->path ) || strncmp($this->path, '//', 2)==0;
[7995]968  }
[7975]969}
970
971
972/** Manage a list of required scripts for a page, by optimizing their loading location (head, bottom, async)
973and later on by combining them in a unique file respecting at the same time dependencies.*/
974class ScriptLoader
975{
976  private $registered_scripts;
[7995]977  public $inline_scripts;
978
[7975]979  private $did_head;
[7995]980  private $head_done_scripts;
[10616]981  private $did_footer;
[7995]982
[7975]983  private static $known_paths = array(
984      'core.scripts' => 'themes/default/js/scripts.js',
985      'jquery' => 'themes/default/js/jquery.min.js',
[9559]986      'jquery.ui' => 'themes/default/js/ui/minified/jquery.ui.core.min.js',
[18630]987      'jquery.ui.effect' => 'themes/default/js/ui/minified/jquery.ui.effect.min.js',
[7975]988    );
989
[9559]990  private static $ui_core_dependencies = array(
991      'jquery.ui.widget' => array('jquery'),
992      'jquery.ui.position' => array('jquery'),
993      'jquery.ui.mouse' => array('jquery', 'jquery.ui', 'jquery.ui.widget'),
994    );
995
[7975]996  function __construct()
997  {
998    $this->clear();
999  }
1000
1001  function clear()
1002  {
1003    $this->registered_scripts = array();
[7995]1004    $this->inline_scripts = array();
1005    $this->head_done_scripts = array();
[10616]1006    $this->did_head = $this->did_footer = false;
[7975]1007  }
1008
[8506]1009  function get_all()
1010  {
1011    return $this->registered_scripts;
1012  }
1013
[7995]1014  function add_inline($code, $require)
1015  {
[10616]1016    !$this->did_footer || trigger_error("Attempt to add inline script but the footer has been written", E_USER_WARNING);
[7995]1017    if(!empty($require))
1018    {
[9580]1019      foreach ($require as $id)
1020      {
1021        if(!isset($this->registered_scripts[$id]))
1022          $this->load_known_required_script($id, 1) or fatal_error("inline script not found require $id");
1023        $s = $this->registered_scripts[$id];
1024        if($s->load_mode==2)
1025          $s->load_mode=1; // until now the implementation does not allow executing inline script depending on another async script
1026      }
[7995]1027    }
1028    $this->inline_scripts[] = $code;
1029  }
1030
[7975]1031  function add($id, $load_mode, $require, $path, $version=0)
1032  {
[10616]1033    if ($this->did_head && $load_mode==0)
[7975]1034    {
[10616]1035      trigger_error("Attempt to add script $id but the head has been written", E_USER_WARNING);
[7975]1036    }
[10616]1037    elseif ($this->did_footer)
1038    {
1039      trigger_error("Attempt to add script $id but the footer has been written", E_USER_WARNING);
1040    }
[7975]1041    if (! isset( $this->registered_scripts[$id] ) )
1042    {
[8012]1043      $script = new Script($load_mode, $id, $path, $version, $require);
[7975]1044      self::fill_well_known($id, $script);
1045      $this->registered_scripts[$id] = $script;
[10616]1046
1047      // Load or modify all UI core files
1048      if ($id == 'jquery.ui' and $script->path == self::$known_paths['jquery.ui'])
1049      {
1050        foreach (self::$ui_core_dependencies as $script_id => $required_ids)
1051          $this->add($script_id, $load_mode, $required_ids, null, $version);
1052      }
1053
1054      // Try to load undefined required script
1055      foreach ($script->precedents as $script_id)
1056      {
1057        if (! isset( $this->registered_scripts[$script_id] ) )
1058          $this->load_known_required_script($script_id, $load_mode);
1059      }
[7975]1060    }
1061    else
1062    {
[10616]1063      $script = $this->registered_scripts[$id];
[7975]1064      if (count($require))
1065      {
1066        $script->precedents = array_unique( array_merge($script->precedents, $require) );
1067      }
1068      $script->set_path($path);
1069      if ($version && version_compare($script->version, $version)<0 )
1070        $script->version = $version;
1071      if ($load_mode < $script->load_mode)
1072        $script->load_mode = $load_mode;
1073    }
[9580]1074
[7975]1075  }
1076
1077  function did_head()
1078  {
1079    return $this->did_head;
1080  }
1081
1082  function get_head_scripts()
1083  {
[7995]1084    self::check_load_dep($this->registered_scripts);
[7975]1085    foreach( array_keys($this->registered_scripts) as $id )
1086    {
1087      $this->compute_script_topological_order($id);
1088    }
1089
1090    uasort($this->registered_scripts, array('ScriptLoader', 'cmp_by_mode_and_order'));
1091
1092    foreach( $this->registered_scripts as $id => $script)
1093    {
1094      if ($script->load_mode > 0)
1095        break;
1096      if ( !empty($script->path) )
[7995]1097        $this->head_done_scripts[$id] = $script;
[7975]1098      else
1099        trigger_error("Script $id has an undefined path", E_USER_WARNING);
1100    }
1101    $this->did_head = true;
[8012]1102    return self::do_combine($this->head_done_scripts, 0);
[7975]1103  }
1104
1105  function get_footer_scripts()
1106  {
[10656]1107    if (!$this->did_head)
1108    {
1109      self::check_load_dep($this->registered_scripts);
1110    }
[10616]1111    $this->did_footer = true;
[7995]1112    $todo = array();
[7975]1113    foreach( $this->registered_scripts as $id => $script)
1114    {
[7995]1115      if (!isset($this->head_done_scripts[$id]))
[7975]1116      {
[7995]1117        $todo[$id] = $script;
1118      }
1119    }
[8401]1120
[7995]1121    foreach( array_keys($todo) as $id )
1122    {
1123      $this->compute_script_topological_order($id);
1124    }
1125
1126    uasort($todo, array('ScriptLoader', 'cmp_by_mode_and_order'));
1127
1128    $result = array( array(), array() );
1129    foreach( $todo as $id => $script)
1130    {
1131      $result[$script->load_mode-1][$id] = $script;
1132    }
[8012]1133    return array( self::do_combine($result[0],1), self::do_combine($result[1],2) );
[7995]1134  }
1135
[8170]1136  private static function do_combine($scripts, $load_mode)
1137  {
1138    global $conf;
1139    if (count($scripts)<2 or !$conf['template_combine_files'])
1140      return $scripts;
1141    $combiner = new FileCombiner('js');
[8305]1142    $result = array();
[8170]1143    foreach ($scripts as $script)
1144    {
[8305]1145      if ($script->is_remote())
1146      {
1147        if ( $combiner->combine( $out_file, $out_version) )
1148        {
1149          $results[] = new Script($load_mode, 'combi', $out_file, $out_version, array() );
1150        }
1151        $results[] = $script;
1152      }
1153      else
1154        $combiner->add( $script->path, $script->version );
[8170]1155    }
1156    if ( $combiner->combine( $out_file, $out_version) )
1157    {
[8305]1158      $results[] = new Script($load_mode, 'combi', $out_file, $out_version, array() );
[8170]1159    }
[8305]1160    return $results;
[8170]1161  }
[8401]1162
[8170]1163  // checks that if B depends on A, then B->load_mode >= A->load_mode in order to respect execution order
[7995]1164  private static function check_load_dep($scripts)
1165  {
[8170]1166    global $conf;
[7995]1167    do
1168    {
1169      $changed = false;
1170      foreach( $scripts as $id => $script)
1171      {
1172        $load = $script->load_mode;
1173        foreach( $script->precedents as $precedent)
[7975]1174        {
[7995]1175          if ( !isset($scripts[$precedent] ) )
1176            continue;
1177          if ( $scripts[$precedent]->load_mode > $load )
1178          {
1179            $scripts[$precedent]->load_mode = $load;
1180            $changed = true;
1181          }
[8401]1182          if ($load==2 && $scripts[$precedent]->load_mode==2 && ($scripts[$precedent]->is_remote() or !$conf['template_combine_files']) )
[7995]1183          {// we are async -> a predecessor cannot be async unlesss it can be merged; otherwise script execution order is not guaranteed
1184            $scripts[$precedent]->load_mode = 1;
1185            $changed = true;
1186          }
[7975]1187        }
1188      }
1189    }
[7995]1190    while ($changed);
[7975]1191  }
[8012]1192
1193
[7995]1194  private static function fill_well_known($id, $script)
1195  {
1196    if ( empty($script->path) && isset(self::$known_paths[$id]))
1197    {
1198      $script->path = self::$known_paths[$id];
1199    }
1200    if ( strncmp($id, 'jquery.', 7)==0 )
1201    {
[9559]1202      $required_ids = array('jquery');
1203
[18630]1204      if ( strncmp($id, 'jquery.ui.effect-', 17)==0 )
[9559]1205      {
[18630]1206        $required_ids = array('jquery', 'jquery.ui.effect');
[9559]1207
1208        if ( empty($script->path) )
[18630]1209          $script->path = dirname(self::$known_paths['jquery.ui.effect'])."/$id.min.js";
[9559]1210      }
[18630]1211      elseif ( strncmp($id, 'jquery.ui.', 10)==0 )
[9559]1212      {
[18630]1213        if ( !isset(self::$ui_core_dependencies[$id]) )
1214          $required_ids = array_merge(array('jquery', 'jquery.ui'), array_keys(self::$ui_core_dependencies));
[9559]1215
1216        if ( empty($script->path) )
[18630]1217          $script->path = dirname(self::$known_paths['jquery.ui'])."/$id.min.js";
[9559]1218      }
1219
1220      foreach ($required_ids as $required_id)
1221      {
1222        if ( !in_array($required_id, $script->precedents ) )
1223          $script->precedents[] = $required_id;
1224      }
[7995]1225    }
1226  }
[7975]1227
[9580]1228  private function load_known_required_script($id, $load_mode)
1229  {
[18630]1230    if ( isset(self::$known_paths[$id]) or strncmp($id, 'jquery.ui.', 10)==0  )
[9580]1231    {
1232      $this->add($id, $load_mode, array(), null);
1233      return true;
1234    }
1235    return false;
1236  }
1237
[8170]1238  private function compute_script_topological_order($script_id, $recursion_limiter=0)
[7975]1239  {
1240    if (!isset($this->registered_scripts[$script_id]))
1241    {
1242      trigger_error("Undefined script $script_id is required by someone", E_USER_WARNING);
1243      return 0;
1244    }
[8170]1245    $recursion_limiter<5 or fatal_error("combined script circular dependency");
[10616]1246    $script = $this->registered_scripts[$script_id];
[7975]1247    if (isset($script->extra['order']))
1248      return $script->extra['order'];
1249    if (count($script->precedents) == 0)
1250      return ($script->extra['order'] = 0);
1251    $max = 0;
1252    foreach( $script->precedents as $precedent)
[8170]1253      $max = max($max, $this->compute_script_topological_order($precedent, $recursion_limiter+1) );
[7975]1254    $max++;
1255    return ($script->extra['order'] = $max);
1256  }
1257
1258  private static function cmp_by_mode_and_order($s1, $s2)
1259  {
1260    $ret = $s1->load_mode - $s2->load_mode;
[7995]1261    if ($ret) return $ret;
[8012]1262
[7995]1263    $ret = $s1->extra['order'] - $s2->extra['order'];
1264    if ($ret) return $ret;
[8012]1265
[7995]1266    if ($s1->extra['order']==0 and ($s1->is_remote() xor $s2->is_remote()) )
1267    {
1268      return $s1->is_remote() ? -1 : 1;
1269    }
1270    return strcmp($s1->id,$s2->id);
[7975]1271  }
1272}
1273
[7987]1274
1275/*Allows merging of javascript and css files into a single one.*/
1276final class FileCombiner
1277{
1278  private $type; // js or css
1279  private $files = array();
1280  private $versions = array();
1281
1282  function FileCombiner($type)
1283  {
1284    $this->type = $type;
1285  }
[8012]1286
[7995]1287  static function clear_combined_files()
1288  {
[12802]1289    $dir = opendir(PHPWG_ROOT_PATH.PWG_COMBINED_DIR);
[7995]1290    while ($file = readdir($dir))
1291    {
1292      if ( get_extension($file)=='js' || get_extension($file)=='css')
[12802]1293        unlink(PHPWG_ROOT_PATH.PWG_COMBINED_DIR.$file);
[7995]1294    }
1295    closedir($dir);
1296  }
[7987]1297
1298  function add($file, $version)
1299  {
1300    $this->files[] = $file;
1301    $this->versions[] = $version;
1302  }
1303
1304  function clear()
1305  {
1306    $this->files = array();
1307    $this->versions = array();
1308  }
1309
1310  function combine(&$out_file, &$out_version)
1311  {
1312    if (count($this->files) == 0)
1313    {
1314      return false;
1315    }
1316    if (count($this->files) == 1)
1317    {
1318      $out_file = $this->files[0];
1319      $out_version = $this->versions[0];
1320      $this->clear();
1321      return 1;
1322    }
1323
[8075]1324    $is_css = $this->type == "css";
[7987]1325    global $conf;
1326    $key = array();
[8401]1327    if ($is_css)
[8075]1328      $key[] = get_absolute_root_url(false);//because we modify bg url
[7987]1329    for ($i=0; $i<count($this->files); $i++)
1330    {
1331      $key[] = $this->files[$i];
1332      $key[] = $this->versions[$i];
1333      if ($conf['template_compile_check']) $key[] = filemtime( PHPWG_ROOT_PATH . $this->files[$i] );
1334    }
1335    $key = join('>', $key);
1336
1337    $file = base_convert(crc32($key),10,36);
[12802]1338    $file = PWG_COMBINED_DIR . $file . '.' . $this->type;
[8401]1339
[8075]1340    $exists = file_exists( PHPWG_ROOT_PATH . $file );
1341    if ($exists)
[7987]1342    {
[8075]1343      $is_reload =
1344        (isset($_SERVER['HTTP_CACHE_CONTROL']) && strpos($_SERVER['HTTP_CACHE_CONTROL'], 'max-age=0') !== false)
1345        || (isset($_SERVER['HTTP_PRAGMA']) && strpos($_SERVER['HTTP_PRAGMA'], 'no-cache'));
[8299]1346      if (is_admin() && $is_reload)
[8075]1347      {// the user pressed F5 in the browser
1348        if ($is_css || $conf['template_compile_check']==false)
1349          $exists = false; // we foce regeneration of css because @import sub-files are never checked for modification
1350      }
1351    }
1352
1353    if ($exists)
1354    {
[7987]1355      $out_file = $file;
1356      $out_version = false;
1357      $this->clear();
1358      return 2;
1359    }
1360
[8506]1361    $output = '';
[7987]1362    foreach ($this->files as $input_file)
1363    {
[8506]1364      $output .= "/*BEGIN $input_file */\n";
[8075]1365      if ($is_css)
[8012]1366        $output .= self::process_css($input_file);
[7987]1367      else
[8075]1368        $output .= self::process_js($input_file);
[7987]1369      $output .= "\n";
1370    }
1371
[17675]1372    mkgetdir( dirname(PHPWG_ROOT_PATH.$file) );
1373    file_put_contents( PHPWG_ROOT_PATH.$file,  $output );
1374    @chmod(PHPWG_ROOT_PATH.$file, 0644);
[7987]1375    $out_file = $file;
1376    $out_version = false;
1377    $this->clear();
1378    return 2;
1379  }
1380
[8075]1381  private static function process_js($file)
1382  {
1383    $js = file_get_contents(PHPWG_ROOT_PATH . $file);
1384    if (strpos($file, '.min')===false and strpos($file, '.packed')===false )
1385    {
[19576]1386      require_once(PHPWG_ROOT_PATH.'include/jshrink.class.php');
1387      try { $js = JShrink_Minifier::minify($js); } catch(Exception $e) {}
[8075]1388    }
[9606]1389    return trim($js, " \t\r\n;").";\n";
[8075]1390  }
[8401]1391
[8012]1392  private static function process_css($file)
[7987]1393  {
[8170]1394    $css = self::process_css_rec($file);
[16278]1395    if (version_compare(PHP_VERSION, '5.2.4', '>='))
1396    {
1397      require_once(PHPWG_ROOT_PATH.'include/cssmin.class.php');
1398      $css = CssMin::minify($css, array('Variables'=>false));
1399    }
[8401]1400    $css = trigger_event('combined_css_postfilter', $css);
[8170]1401    return $css;
1402  }
[8401]1403
[8170]1404  private static function process_css_rec($file)
1405  {
[7987]1406    static $PATTERN = "#url\(\s*['|\"]{0,1}(.*?)['|\"]{0,1}\s*\)#";
1407    $css = file_get_contents(PHPWG_ROOT_PATH . $file);
1408    if (preg_match_all($PATTERN, $css, $matches, PREG_SET_ORDER))
1409    {
1410      $search = $replace = array();
1411      foreach ($matches as $match)
1412      {
[11122]1413        if ( !url_is_remote($match[1]) && $match[1][0] != '/')
[7987]1414        {
1415          $relative = dirname($file) . "/$match[1]";
1416          $search[] = $match[0];
[8401]1417          $replace[] = 'url('.embellish_url(get_absolute_root_url(false).$relative).')';
[7987]1418        }
1419      }
1420      $css = str_replace($search, $replace, $css);
1421    }
1422
1423    $imports = preg_match_all("#@import\s*['|\"]{0,1}(.*?)['|\"]{0,1};#", $css, $matches, PREG_SET_ORDER);
1424    if ($imports)
1425    {
1426      $search = $replace = array();
1427      foreach ($matches as $match)
1428      {
1429        $search[] = $match[0];
[8170]1430        $replace[] = self::process_css_rec(dirname($file) . "/$match[1]");
[7987]1431      }
1432      $css = str_replace($search, $replace, $css);
1433    }
1434    return $css;
1435  }
1436}
1437
[7995]1438?>
Note: See TracBrowser for help on using the repository browser.