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

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

fix define_derivative (matter of smarty3 variable scope)

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