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

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