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

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

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

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