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

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

feature 2548 multisize - code cleanup + better usage in category_cats + i.php logs memory usage peak

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