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

Last change on this file since 7975 was 7975, checked in by rvelices, 13 years ago

new template features: combine_script, footer_script and get_combined_scripts
migrated public templates only; need more code doc

  • Property svn:eol-style set to LF
File size: 28.3 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based picture gallery                                  |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008-2010 Piwigo Team                  http://piwigo.org |
6// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
7// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
8// +-----------------------------------------------------------------------+
9// | This program is free software; you can redistribute it and/or modify  |
10// | it under the terms of the GNU General Public License as published by  |
11// | the Free Software Foundation                                          |
12// |                                                                       |
13// | This program is distributed in the hope that it will be useful, but   |
14// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
15// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
16// | General Public License for more details.                              |
17// |                                                                       |
18// | You should have received a copy of the GNU General Public License     |
19// | along with this program; if not, write to the Free Software           |
20// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
21// | USA.                                                                  |
22// +-----------------------------------------------------------------------+
23
24
25require_once(PHPWG_ROOT_PATH.'include/smarty/libs/Smarty.class.php');
26
27
28class Template {
29
30  var $smarty;
31
32  var $output = '';
33
34  // Hash of filenames for each template handle.
35  var $files = array();
36
37  // Template extents filenames for each template handle.
38  var $extents = array();
39
40  // Templates prefilter from external sources (plugins)
41  var $external_filters = array();
42
43  // used by html_head smarty block to add content before </head>
44  var $html_head_elements = array();
45
46  var $scriptLoader;
47  var $html_footer_raw_script = array();
48
49  function Template($root = ".", $theme= "", $path = "template")
50  {
51    global $conf, $lang_info;
52
53    $this->scriptLoader = new ScriptLoader;
54    $this->smarty = new Smarty;
55    $this->smarty->debugging = $conf['debug_template'];
56    $this->smarty->compile_check = $conf['template_compile_check'];
57    $this->smarty->force_compile = $conf['template_force_compile'];
58
59    if (!isset($conf['local_data_dir_checked']))
60    {
61      mkgetdir($conf['local_data_dir'], MKGETDIR_DEFAULT&~MKGETDIR_DIE_ON_ERROR);
62      if (!is_writable($conf['local_data_dir']))
63      {
64        load_language('admin.lang');
65        fatal_error(
66          sprintf(
67            l10n('Give write access (chmod 777) to "%s" directory at the root of your Piwigo installation'),
68            basename($conf['local_data_dir'])
69            ),
70          l10n('an error happened'),
71          false // show trace
72          );
73      }
74      if (function_exists('pwg_query')) {
75        conf_update_param('local_data_dir_checked', 'true');
76      }
77    }
78   
79    $compile_dir = $conf['local_data_dir'].'/templates_c';
80    mkgetdir( $compile_dir );
81
82    $this->smarty->compile_dir = $compile_dir;
83
84    $this->smarty->assign_by_ref( 'pwg', new PwgTemplateAdapter() );
85    $this->smarty->register_modifier( 'translate', array('Template', 'mod_translate') );
86    $this->smarty->register_modifier( 'explode', array('Template', 'mod_explode') );
87    $this->smarty->register_modifier( 'get_extent', array(&$this, 'get_extent') );
88    $this->smarty->register_block('html_head', array(&$this, 'block_html_head') );
89    $this->smarty->register_function('combine_script', array(&$this, 'func_combine_script') );
90    $this->smarty->register_function('get_combined_scripts', array(&$this, 'func_get_combined_scripts') );
91    $this->smarty->register_block('footer_script', array(&$this, 'block_footer_script') );
92    $this->smarty->register_function('known_script', array(&$this, 'func_known_script') );
93    $this->smarty->register_prefilter( array('Template', 'prefilter_white_space') );
94    if ( $conf['compiled_template_cache_language'] )
95    {
96      $this->smarty->register_prefilter( array('Template', 'prefilter_language') );
97    }
98
99    $this->smarty->template_dir = array();
100    if ( !empty($theme) )
101    {
102      $this->set_theme($root, $theme, $path);
103      $this->set_prefilter( 'header', array('Template', 'prefilter_local_css') );
104    }
105    else
106      $this->set_template_dir($root);
107
108    $this->smarty->assign('lang_info', $lang_info);
109
110    if (!defined('IN_ADMIN') and isset($conf['extents_for_templates']))
111    {
112      $tpl_extents = unserialize($conf['extents_for_templates']);
113      $this->set_extents($tpl_extents, './template-extension/', true, $theme);
114    }
115  }
116
117  /**
118   * Load theme's parameters.
119   */
120  function set_theme($root, $theme, $path, $load_css=true, $load_local_head=true)
121  {
122    $this->set_template_dir($root.'/'.$theme.'/'.$path);
123
124    $themeconf = $this->load_themeconf($root.'/'.$theme);
125
126    if (isset($themeconf['parent']) and $themeconf['parent'] != $theme)
127    {
128      $this->set_theme(
129        $root,
130        $themeconf['parent'],
131        $path,
132        isset($themeconf['load_parent_css']) ? $themeconf['load_parent_css'] : $load_css,
133        isset($themeconf['load_parent_local_head']) ? $themeconf['load_parent_local_head'] : $load_local_head
134      );
135    }
136
137    $tpl_var = array(
138      'id' => $theme,
139      'load_css' => $load_css,
140    );
141    if (!empty($themeconf['local_head']) and $load_local_head)
142    {
143      $tpl_var['local_head'] = realpath($root.'/'.$theme.'/'.$themeconf['local_head'] );
144    }
145    $themeconf['id'] = $theme;
146    $this->smarty->append('themes', $tpl_var);
147    $this->smarty->append('themeconf', $themeconf, true);
148  }
149
150  /**
151   * Add template directory for this Template object.
152   * Set compile id if not exists.
153   */
154  function set_template_dir($dir)
155  {
156    $this->smarty->template_dir[] = $dir;
157
158    if (!isset($this->smarty->compile_id))
159    {
160      $real_dir = realpath($dir);
161      $compile_id = crc32( $real_dir===false ? $dir : $real_dir);
162      $this->smarty->compile_id = base_convert($compile_id, 10, 36 );
163    }
164  }
165
166  /**
167   * Gets the template root directory for this Template object.
168   */
169  function get_template_dir()
170  {
171    return $this->smarty->template_dir;
172  }
173
174  /**
175   * Deletes all compiled templates.
176   */
177  function delete_compiled_templates()
178  {
179      $save_compile_id = $this->smarty->compile_id;
180      $this->smarty->compile_id = null;
181      $this->smarty->clear_compiled_tpl();
182      $this->smarty->compile_id = $save_compile_id;
183      file_put_contents($this->smarty->compile_dir.'/index.htm', 'Not allowed!');
184  }
185
186  function get_themeconf($val)
187  {
188    $tc = $this->smarty->get_template_vars('themeconf');
189    return isset($tc[$val]) ? $tc[$val] : '';
190  }
191
192  /**
193   * Sets the template filename for handle.
194   */
195  function set_filename($handle, $filename)
196  {
197    return $this->set_filenames( array($handle=>$filename) );
198  }
199
200  /**
201   * Sets the template filenames for handles. $filename_array should be a
202   * hash of handle => filename pairs.
203   */
204  function set_filenames($filename_array)
205  {
206    if (!is_array($filename_array))
207    {
208      return false;
209    }
210    reset($filename_array);
211    while(list($handle, $filename) = each($filename_array))
212    {
213      if (is_null($filename))
214      {
215        unset($this->files[$handle]);
216      }
217      else
218      {
219        $this->files[$handle] = $this->get_extent($filename, $handle);
220      }
221    }
222    return true;
223  }
224
225  /**
226   * Sets template extention filename for handles.
227   */
228  function set_extent($filename, $param, $dir='', $overwrite=true, $theme='N/A')
229  {
230    return $this->set_extents(array($filename => $param), $dir, $overwrite);
231  }
232
233  /**
234   * Sets template extentions filenames for handles.
235   * $filename_array should be an hash of filename => array( handle, param) or filename => handle
236   */
237  function set_extents($filename_array, $dir='', $overwrite=true, $theme='N/A')
238  {
239    if (!is_array($filename_array))
240    {
241      return false;
242    }
243    foreach ($filename_array as $filename => $value)
244    {
245      if (is_array($value))
246      {
247        $handle = $value[0];
248        $param = $value[1];
249        $thm = $value[2];
250      }
251      elseif (is_string($value))
252      {
253        $handle = $value;
254        $param = 'N/A';
255        $thm = 'N/A';
256      }
257      else
258      {
259        return false;
260      }
261
262      if ((stripos(implode('',array_keys($_GET)), '/'.$param) !== false or $param == 'N/A')
263        and ($thm == $theme or $thm == 'N/A')
264        and (!isset($this->extents[$handle]) or $overwrite)
265        and file_exists($dir . $filename))
266      {
267        $this->extents[$handle] = realpath($dir . $filename);
268      }
269    }
270    return true;
271  }
272
273  /** return template extension if exists  */
274  function get_extent($filename='', $handle='')
275  {
276    if (isset($this->extents[$handle]))
277    {
278      $filename = $this->extents[$handle];
279    }
280    return $filename;
281  }
282
283  /** see smarty assign http://www.smarty.net/manual/en/api.assign.php */
284  function assign($tpl_var, $value = null)
285  {
286    $this->smarty->assign( $tpl_var, $value );
287  }
288
289  /**
290   * Inserts the uncompiled code for $handle as the value of $varname in the
291   * root-level. This can be used to effectively include a template in the
292   * middle of another template.
293   * This is equivalent to assign($varname, $this->parse($handle, true))
294   */
295  function assign_var_from_handle($varname, $handle)
296  {
297    $this->assign($varname, $this->parse($handle, true));
298    return true;
299  }
300
301  /** see smarty append http://www.smarty.net/manual/en/api.append.php */
302  function append($tpl_var, $value=null, $merge=false)
303  {
304    $this->smarty->append( $tpl_var, $value, $merge );
305  }
306
307  /**
308   * Root-level variable concatenation. Appends a  string to an existing
309   * variable assignment with the same name.
310   */
311  function concat($tpl_var, $value)
312  {
313    $old_val = & $this->smarty->get_template_vars($tpl_var);
314    if ( isset($old_val) )
315    {
316      $old_val .= $value;
317    }
318    else
319    {
320      $this->assign($tpl_var, $value);
321    }
322  }
323
324  /** see smarty append http://www.smarty.net/manual/en/api.clear_assign.php */
325  function clear_assign($tpl_var)
326  {
327    $this->smarty->clear_assign( $tpl_var );
328  }
329
330  /** see smarty get_template_vars http://www.smarty.net/manual/en/api.get_template_vars.php */
331  function &get_template_vars($name=null)
332  {
333    return $this->smarty->get_template_vars( $name );
334  }
335
336
337  /**
338   * Load the file for the handle, eventually compile the file and run the compiled
339   * code. This will add the output to the results or return the result if $return
340   * is true.
341   */
342  function parse($handle, $return=false)
343  {
344    if ( !isset($this->files[$handle]) )
345    {
346      fatal_error("Template->parse(): Couldn't load template file for handle $handle");
347    }
348
349    $this->smarty->assign( 'ROOT_URL', get_root_url() );
350    $this->smarty->assign( 'TAG_INPUT_ENABLED',
351      ((is_adviser()) ? 'disabled="disabled" onclick="return false;"' : ''));
352
353    $save_compile_id = $this->smarty->compile_id;
354    $this->load_external_filters($handle);
355
356    global $conf, $lang_info;
357    if ( $conf['compiled_template_cache_language'] and isset($lang_info['code']) )
358    {
359      $this->smarty->compile_id .= '.'.$lang_info['code'];
360    }
361
362    $v = $this->smarty->fetch($this->files[$handle], null, null, false);
363
364    $this->smarty->compile_id = $save_compile_id;
365    $this->unload_external_filters($handle);
366
367    if ($return)
368    {
369      return $v;
370    }
371    $this->output .= $v;
372  }
373
374  /**
375   * Load the file for the handle, eventually compile the file and run the compiled
376   * code. This will print out the results of executing the template.
377   */
378  function pparse($handle)
379  {
380    $this->parse($handle, false);
381    $this->flush();
382  }
383
384  function flush()
385  {
386    if (!$this->scriptLoader->did_head())
387    {
388      $search = "\n</head>";
389      $pos = strpos( $this->output, $search );
390      if ($pos !== false)
391      {
392          $scripts = $this->scriptLoader->get_head_scripts();
393          $content = array();
394          foreach ($scripts as $id => $script)
395          {
396              $content[]=
397                  '<script type="text/javascript" src="'
398                  . Template::make_script_src($script)
399                  .'"></script>';
400          }
401
402          $this->output = substr_replace( $this->output, "\n".implode( "\n", $content ), $pos, 0 );
403      } //else maybe error or warning ?
404    }
405   
406    if ( count($this->html_head_elements) )
407    {
408      $search = "\n</head>";
409      $pos = strpos( $this->output, $search );
410      if ($pos !== false)
411      {
412        $this->output = substr_replace( $this->output, "\n".implode( "\n", $this->html_head_elements ), $pos, 0 );
413      } //else maybe error or warning ?
414      $this->html_head_elements = array();
415    }
416
417    echo $this->output;
418    $this->output='';
419  }
420
421  /** flushes the output */
422  function p()
423  {
424    $this->flush();
425
426    if ($this->smarty->debugging)
427    {
428      global $t2;
429      $this->smarty->assign(
430        array(
431        'AAAA_DEBUG_TOTAL_TIME__' => get_elapsed_time($t2, get_moment())
432        )
433        );
434      require_once(SMARTY_CORE_DIR . 'core.display_debug_console.php');
435      echo smarty_core_display_debug_console(null, $this->smarty);
436    }
437  }
438
439  /**
440   * translate variable modifier - translates a text to the currently loaded
441   * language
442   */
443  static function mod_translate($text)
444  {
445    return l10n($text);
446  }
447
448  /**
449   * explode variable modifier - similar to php explode
450   * 'Yes;No'|@explode:';' -> array('Yes', 'No')
451   */
452  static function mod_explode($text, $delimiter=',')
453  {
454    return explode($delimiter, $text);
455  }
456
457  /**
458   * This smarty "html_head" block allows to add content just before
459   * </head> element in the output after the head has been parsed. This is
460   * handy in order to respect strict standards when <style> and <link>
461   * html elements must appear in the <head> element
462   */
463  function block_html_head($params, $content, &$smarty, &$repeat)
464  {
465    $content = trim($content);
466    if ( !empty($content) )
467    { // second call
468      $this->html_head_elements[] = $content;
469    }
470  }
471
472 /**
473   * This smarty "known_script" functions allows to insert well known java scripts
474   * such as prototype, jquery, etc... only once. Examples:
475   * {known_script id="jquery" src="{$ROOT_URL}template-common/lib/jquery.packed.js"}
476   */
477  function func_known_script($params, &$smarty )
478  {
479    if (!isset($params['id']))
480    {
481        $smarty->trigger_error("known_script: missing 'id' parameter");
482        return;
483    }
484    $id = $params['id'];
485    if (! isset( $this->known_scripts[$id] ) )
486    {
487      if (!isset($params['src']))
488      {
489          $smarty->trigger_error("known_script: missing 'src' parameter");
490          return;
491      }
492      $this->known_scripts[$id] = $params['src'];
493      $content = '<script type="text/javascript" src="'.$params['src'].'"></script>';
494      if (isset($params['now']) and $params['now'] and empty($this->output) )
495      {
496        return $content;
497      }
498      $repeat = false;
499      $this->block_html_head(null, $content, $smarty, $repeat);
500    }
501  }
502 
503  function func_combine_script($params, &$smarty)
504  {
505    if (!isset($params['id']))
506    {
507      $smarty->trigger_error("combine_script: missing 'id' parameter", E_USER_ERROR);
508    }
509    $load = 0;
510    if (isset($params['load']))
511    {
512      switch ($params['load'])
513      {
514        case 'header': break;
515        case 'footer': $load=1; break;
516        case 'async': $load=2; break;
517        default: $smarty->trigger_error("combine_script: invalid 'load' parameter", E_USER_ERROR);
518      }
519    }
520    $this->scriptLoader->add( $params['id'], $load, 
521      empty($params['require']) ? array() : explode( ',', $params['require'] ), 
522      @$params['path'], 
523      isset($params['version']) ? $params['version'] : 0 );
524  }
525
526
527  function func_get_combined_scripts($params, &$smarty)
528  {
529    if (!isset($params['load']))
530    {
531      $smarty->trigger_error("get_combined_scripts: missing 'load' parameter", E_USER_ERROR);
532    }
533    $load = $params['load']=='header' ? 0 : 1;
534    $content = array();
535   
536    if ($load==0)
537    {
538      if ($this->scriptLoader->did_head())
539        fatal_error('get_combined_scripts several times header');
540       
541      $scripts = $this->scriptLoader->get_head_scripts();
542      foreach ($scripts as $id => $script)
543      {
544          $content[]=
545              '<script type="text/javascript" src="'
546              . Template::make_script_src($script)
547              .'"></script>';
548      }
549    }
550    else
551    {
552      if (!$this->scriptLoader->did_head())
553        fatal_error('get_combined_scripts didn\'t call header');
554      $scripts = $this->scriptLoader->get_footer_scripts();
555      foreach ($scripts[0] as $id => $script)
556      {
557        $content[]=
558          '<script type="text/javascript" src="'
559          . Template::make_script_src($script)
560          .'"></script>';
561      }
562      if (count($this->html_footer_raw_script))
563      {
564        $content[]= '<script type="text/javascript">';
565        $content = array_merge($content, $this->html_footer_raw_script);
566        $content[]= '</script>';
567      }
568
569      if (count($scripts[1]))
570      {
571        $content[]= '<script type="text/javascript">';
572        $content[]= '(function() {
573  var after = document.getElementsByTagName(\'script\')[document.getElementsByTagName(\'script\').length-1];
574  var s;';
575        foreach ($scripts[1] as $id => $script)
576        {
577          $content[]=
578            's=document.createElement(\'script\'); s.type = \'text/javascript\'; s.async = true; s.src = \''
579            . Template::make_script_src($script)
580            .'\';';
581          $content[]= 'after = after.parentNode.insertBefore(s, after);';
582        }
583        $content[]= '})();';
584        $content[]= '</script>';
585      }
586    }
587    return implode("\n", $content);
588  }
589
590
591  private static function make_script_src( $script )
592  {
593    $ret = '';
594    if ( url_is_remote($script->path) )
595      $ret = $script->path;
596    else
597    {
598      $ret = get_root_url().$script->path;
599      if ($script->version!==false)
600      {
601        $ret.= '?v'. ($script->version ? $script->version : PHPWG_VERSION);
602      }
603    }
604    return $ret;
605  }
606
607  function block_footer_script($params, $content, &$smarty, &$repeat)
608  {
609    $content = trim($content);
610    if ( !empty($content) )
611    { // second call
612      $this->html_footer_raw_script[] = $content;
613    }
614  }
615
616 /**
617   * This function allows to declare a Smarty prefilter from a plugin, thus allowing
618   * it to modify template source before compilation and without changing core files
619   * They will be processed by weight ascending.
620   * http://www.smarty.net/manual/en/advanced.features.prefilters.php
621   */
622  function set_prefilter($handle, $callback, $weight=50)
623  {
624    $this->external_filters[$handle][$weight][] = array('prefilter', $callback);
625    ksort($this->external_filters[$handle]);
626  }
627
628  function set_postfilter($handle, $callback, $weight=50)
629  {
630    $this->external_filters[$handle][$weight][] = array('postfilter', $callback);
631    ksort($this->external_filters[$handle]);
632  }
633
634  function set_outputfilter($handle, $callback, $weight=50)
635  {
636    $this->external_filters[$handle][$weight][] = array('outputfilter', $callback);
637    ksort($this->external_filters[$handle]);
638  }
639
640 /**
641   * This function actually triggers the filters on the tpl files.
642   * Called in the parse method.
643   * http://www.smarty.net/manual/en/advanced.features.prefilters.php
644   */
645  function load_external_filters($handle)
646  {
647    if (isset($this->external_filters[$handle]))
648    {
649      $compile_id = '';
650      foreach ($this->external_filters[$handle] as $filters)
651      {
652        foreach ($filters as $filter)
653        {
654          list($type, $callback) = $filter;
655          $compile_id .= $type.( is_array($callback) ? implode('', $callback) : $callback );
656          call_user_func(array($this->smarty, 'register_'.$type), $callback);
657        }
658      }
659      $this->smarty->compile_id .= '.'.base_convert(crc32($compile_id), 10, 36);
660    }
661  }
662
663  function unload_external_filters($handle)
664  {
665    if (isset($this->external_filters[$handle]))
666    {
667      foreach ($this->external_filters[$handle] as $filters)
668      {
669        foreach ($filters as $filter)
670        {
671          list($type, $callback) = $filter;
672          call_user_func(array($this->smarty, 'unregister_'.$type), $callback);
673        }
674      }
675    }
676  }
677
678  static function prefilter_white_space($source, &$smarty)
679  {
680    $ld = $smarty->left_delimiter;
681    $rd = $smarty->right_delimiter;
682    $ldq = preg_quote($ld, '#');
683    $rdq = preg_quote($rd, '#');
684
685    $regex = array();
686    $tags = array('if', 'foreach', 'section');
687    foreach($tags as $tag)
688    {
689      array_push($regex, "#^[ \t]+($ldq$tag"."[^$ld$rd]*$rdq)\s*$#m");
690      array_push($regex, "#^[ \t]+($ldq/$tag$rdq)\s*$#m");
691    }
692    $tags = array('include', 'else', 'html_head');
693    foreach($tags as $tag)
694    {
695      array_push($regex, "#^[ \t]+($ldq$tag"."[^$ld$rd]*$rdq)\s*$#m");
696    }
697    $source = preg_replace( $regex, "$1", $source);
698    return $source;
699  }
700
701  /**
702   * Smarty prefilter to allow caching (whenever possible) language strings
703   * from templates.
704   */
705  static function prefilter_language($source, &$smarty)
706  {
707    global $lang;
708    $ldq = preg_quote($smarty->left_delimiter, '~');
709    $rdq = preg_quote($smarty->right_delimiter, '~');
710
711    $regex = "~$ldq *\'([^'$]+)\'\|@translate *$rdq~";
712    $source = preg_replace( $regex.'e', 'isset($lang[\'$1\']) ? $lang[\'$1\'] : \'$0\'', $source);
713
714    $regex = "~$ldq *\'([^'$]+)\'\|@translate\|~";
715    $source = preg_replace( $regex.'e', 'isset($lang[\'$1\']) ? \'{\'.var_export($lang[\'$1\'],true).\'|\' : \'$0\'', $source);
716
717    $regex = "~($ldq *assign +var=.+ +value=)\'([^'$]+)\'\|@translate~e";
718    $source = preg_replace( $regex, 'isset($lang[\'$2\']) ? \'$1\'.var_export($lang[\'$2\'],true) : \'$0\'', $source);
719
720    return $source;
721  }
722
723  static function prefilter_local_css($source, &$smarty)
724  {
725    $css = array();
726
727    foreach ($smarty->get_template_vars('themes') as $theme)
728    {
729      if (file_exists(PHPWG_ROOT_PATH.'local/css/'.$theme['id'].'-rules.css'))
730      {
731        array_push($css, '<link rel="stylesheet" type="text/css" href="{$ROOT_URL}local/css/'.$theme['id'].'-rules.css">');
732      }
733    }
734    if (file_exists(PHPWG_ROOT_PATH.'local/css/rules.css'))
735    {
736      array_push($css, '<link rel="stylesheet" type="text/css" href="{$ROOT_URL}local/css/rules.css">');
737    }
738
739    if (!empty($css))
740    {
741      $source = str_replace("\n</head>", "\n".implode( "\n", $css )."\n</head>", $source);
742    }
743
744    return $source;
745  }
746
747  function load_themeconf($dir)
748  {
749    global $themeconfs, $conf;
750
751    $dir = realpath($dir);
752    if (!isset($themeconfs[$dir]))
753    {
754      $themeconf = array();
755      include($dir.'/themeconf.inc.php');
756      // Put themeconf in cache
757      $themeconfs[$dir] = $themeconf;
758    }
759    return $themeconfs[$dir];
760  }
761}
762
763
764/**
765 * This class contains basic functions that can be called directly from the
766 * templates in the form $pwg->l10n('edit')
767 */
768class PwgTemplateAdapter
769{
770  function l10n($text)
771  {
772    return l10n($text);
773  }
774
775  function l10n_dec($s, $p, $v)
776  {
777    return l10n_dec($s, $p, $v);
778  }
779
780  function sprintf()
781  {
782    $args = func_get_args();
783    return call_user_func_array('sprintf',  $args );
784  }
785}
786
787
788final class Script
789{
790  public $load_mode;
791  public $precedents = array();
792  public $path;
793  public $version;
794  public $extra = array();
795
796  function Script($load_mode, $precedents, $path, $version)
797  {
798    $this->load_mode = $load_mode;
799    $this->precedents = $precedents;
800    $this->path = $path;
801    $this->version = $version;
802  }
803
804  function set_path($path)
805  {
806    if (!empty($path))
807      $this->path = $path;
808  }
809}
810
811
812/** Manage a list of required scripts for a page, by optimizing their loading location (head, bottom, async)
813and later on by combining them in a unique file respecting at the same time dependencies.*/
814class ScriptLoader
815{
816  private $registered_scripts;
817  private $did_head;
818  private static $known_paths = array(
819      'core.scripts' => 'themes/default/js/scripts.js',
820      'jquery' => 'themes/default/js/jquery.min.js',
821      'jquery.ui' => 'themes/default/js/ui/packed/ui.core.packed.js'
822    );
823
824  function __construct()
825  {
826    $this->clear();
827  }
828
829  function clear()
830  {
831    $this->registered_scripts = array();
832    $this->did_head = false;
833  }
834
835  function add($id, $load_mode, $require, $path, $version=0)
836  {
837    if ($this->did_head && $load_mode==0 )
838    {
839      trigger_error("Attempt to add a new script $id but the head has been written", E_USER_WARNING);
840    }
841    if (! isset( $this->registered_scripts[$id] ) )
842    {
843      $script = new Script($load_mode, $require, $path, $version);
844      self::fill_well_known($id, $script);
845      $this->registered_scripts[$id] = $script;
846    }
847    else
848    {
849      $script = & $this->registered_scripts[$id];
850      if (count($require))
851      {
852        $script->precedents = array_unique( array_merge($script->precedents, $require) );
853      }
854      $script->set_path($path);
855      if ($version && version_compare($script->version, $version)<0 )
856        $script->version = $version;
857      if ($load_mode < $script->load_mode)
858        $script->load_mode = $load_mode;
859    }
860  }
861
862  function did_head()
863  {
864    return $this->did_head;
865  }
866
867  private static function fill_well_known($id, $script)
868  {
869    if ( empty($script->path) && isset(self::$known_paths[$id]))
870    {
871      $script->path = self::$known_paths[$id];
872    }
873    if ( strncmp($id, 'jquery.', 7)==0 )
874    {
875      if ( !in_array('jquery', $script->precedents ) )
876        $script->precedents[] = 'jquery';
877      if ( strncmp($id, 'jquery.ui.', 10)==0 && !in_array('jquery.ui', $script->precedents ) )
878        $script->precedents[] = 'jquery.ui';
879    }
880  }
881
882  function get_head_scripts()
883  {
884    do
885    {
886      $changed = false;
887      foreach( $this->registered_scripts as $id => $script)
888      {
889        $load = $script->load_mode;
890        if ($load==0)
891          continue;
892        if ($load==2)
893          $load=1; // we are async -> a predecessor cannot be async because the script execution order is not guaranteed
894        foreach( $script->precedents as $precedent)
895        {
896          if ( !isset($this->registered_scripts[$precedent] ) )
897          {
898            trigger_error("Script $id requires undefined script $precedent", E_USER_WARNING);
899            continue;
900          }
901          if ( $this->registered_scripts[$precedent]->load_mode > $load )
902          {
903            $this->registered_scripts[$precedent]->load_mode = $load;
904            $changed = true;
905          }
906        }
907      }
908    }
909    while ($changed);
910
911    foreach( array_keys($this->registered_scripts) as $id )
912    {
913      $this->compute_script_topological_order($id);
914    }
915
916    uasort($this->registered_scripts, array('ScriptLoader', 'cmp_by_mode_and_order'));
917
918    $result = array();
919    foreach( $this->registered_scripts as $id => $script)
920    {
921      if ($script->load_mode > 0)
922        break;
923      if ( !empty($script->path) )
924        $result[$id] = $script;
925      else
926        trigger_error("Script $id has an undefined path", E_USER_WARNING);
927    }
928    $this->did_head = true;
929    return $result;
930  }
931
932  function get_footer_scripts()
933  {
934    if (!$this->did_head)
935    {
936      trigger_error("Attempt to write footer scripts without header scripts", E_USER_WARNING);
937    }
938    $result = array( array(), array() );
939    foreach( $this->registered_scripts as $id => $script)
940    {
941      if ($script->load_mode > 0)
942      {
943        if ( !empty( $script->path ) )
944        {
945          $result[$script->load_mode-1][$id] = $script;
946        }
947        else
948          trigger_error("Script $id has an undefined path", E_USER_WARNING);
949      }
950    }
951    return $result;
952  }
953
954  private function compute_script_topological_order($script_id)
955  {
956    if (!isset($this->registered_scripts[$script_id]))
957    {
958      trigger_error("Undefined script $script_id is required by someone", E_USER_WARNING);
959      return 0;
960    }
961    $script = & $this->registered_scripts[$script_id];
962    if (isset($script->extra['order']))
963      return $script->extra['order'];
964    if (count($script->precedents) == 0)
965      return ($script->extra['order'] = 0);
966    $max = 0;
967    foreach( $script->precedents as $precedent)
968      $max = max($max, $this->compute_script_topological_order($precedent) );
969    $max++;
970    return ($script->extra['order'] = $max);
971  }
972
973  private static function cmp_by_mode_and_order($s1, $s2)
974  {
975    $ret = $s1->load_mode - $s2->load_mode;
976    if (!$ret)
977      $ret = $s1->extra['order'] - $s2->extra['order'];
978    return $ret;
979  }
980}
981
982?>
Note: See TracBrowser for help on using the repository browser.