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

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

new template feature: combine_css

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