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

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

feature 2548 multisize - ability to choose displayed size on index page
-added some logs on i.php (configurable) to measure the perf

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