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

Last change on this file since 17675 was 17675, checked in by rvelices, 12 years ago

bug 2725: Piwigo isn't compatible with suPHP + better handling of watermark upload errors

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