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

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

feature 2978: l10n() and {translate} with additional arguments
TODO: apply in core

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