Solução Gráfica Design SGD
[ class tree: SGD ] [ index: SGD ] [ all elements ]

Source for file class_crushJsCss.php

Documentation is available at class_crushJsCss.php

  1. <?php
  2. // It initializes session to capture $_SESSION['PRODUCTION'] var
  3. /**
  4.  * PHP Version of the Dean Edwards 's Packer  de Dean Edwards, a JavaScript Compressor/Obfuscator.
  5.  * @link http://joliclic.free.fr/php/javascript-packer/en/
  6.  */
  7. require_once('phpclasses/packer/class.JavaScriptPacker.php');
  8. /**
  9.  * CSSTidy is an opensource CSS parser and optimiser. It is available as executeable
  10.  * file (available for Windows, Linux and OSX) which can be controlled per command
  11.  * line and as PHP script (both with almost the same functionality).
  12.  * @link http://csstidy.sourceforge.net/index.php
  13.  */
  14. require_once('phpclasses/csstidy/class.csstidy.php');
  15.  
  16. //This verifies if the class already was declared.
  17. if(!class_exists('crushJsCss')){
  18.     /**
  19.      * Merge, compact, scramble and cache  Javascript and CSS files
  20.      * 
  21.      * This compact class and  scrambles JavaScript files through Dean Edwards's
  22.      * algorithm implemented in a class PHP by Nicolas Martin. Also, it compacts and
  23.      * optimize files CSS through the class CSSTidy. Finally, it compacts everything
  24.      * through gzip. And to save bandwidth, it creates files cache.
  25.      * 
  26.      * @author   Antonio Jozzolino <info@sgd.com.br>
  27.      * @since    Fri Aug 01 2008 08:25:51 GMT-0300
  28.      * @changed  Wed Aug 06 2008 13:04:32 GMT-0300
  29.      * @version  0.01
  30.      * @link     http://www.sgd.com.br
  31.      * @link     http://dean.edwards.name/packer/
  32.      * @link     http://joliclic.free.fr/php/javascript-packer/en/
  33.      * @link     http://csstidy.sourceforge.net/index.php
  34.      * @link     http://rakaz.nl/item/make_your_pages_load_faster_by_combining_and_compressing_javascript_and_css_files
  35.      * @link     http://www.sgd.com.br/content/view/42/88888891/
  36.      * @link     http://www.phpclasses.org/browse/package/4754.html
  37.      * @link     http://www.sgd.com.br/component/option,com_docman/task,doc_download/gid,10/Itemid,34/
  38.      * @example  examples/index.php Html
  39.      * @example  examples/javascript.php Javascript
  40.      * @example  examples/css.php CSS
  41.      */
  42.     class crushJsCss{    
  43.         /**
  44.           * @access public
  45.           * @var bolean Define to false for test phase
  46.           */
  47.         var $production      = true;
  48.         /**
  49.           * @access public
  50.           * @var string key [ "file"]  absolute script path. Use $_SERVER["DOCUMENT_ROOT"] if your server permit it.
  51.                        * @var bolean key[ "pack"]  optional. True to scramble script, false to no modification.
  52.           */        
  53.         var $scripts;
  54.         /**
  55.           * @access public
  56.           * @var string  Define scramble level . Values: 'None', 'Numeric', 'Normal', 'High ASCII'.  'Normal' is default value.
  57.           * @see http://dean.edwards.name/packer/usage/
  58.           */
  59.         var $js_encoding     = 'Normal';
  60.         /**
  61.           * @access public
  62.           * @var bolean True is default value.
  63.           * @see http://dean.edwards.name/packer/usage/
  64.           */        
  65.         var $js_fastDecode   = true;
  66.         /**
  67.           * @access public
  68.           * @var bolean False is default value.
  69.           * @see http://dean.edwards.name/packer/usage/
  70.           */
  71.         var $js_specialChars = false;
  72.         /**
  73.           * @access public
  74.           * @var string absolute script path to cache directory. $_SERVER["DOCUMENT_ROOT"] ."/cache" is default value. This directory should have writing permission (chmod -c 775)
  75.           */
  76.         var $cachedir;
  77.         /**
  78.           * @access public
  79.           * @var string "javascript" or "css". "javascript " is default value.
  80.           */        
  81.         var $type            = 'javascript';
  82.         /**
  83.           * @access private
  84.           * @var string  define which compact method browser client suports, gzip, deflare or none.
  85.           */    
  86.         var $encoding        = 'none';
  87.         /**
  88.           * @access private
  89.           * @var string  name of cache file.
  90.           */        
  91.         var $cachefile;
  92.         /**
  93.           * @access private
  94.           * @var string  compact method
  95.           */        
  96.         var $gzip;
  97.         /**
  98.           * @access private
  99.           * @var string  compact method
  100.           */        
  101.         var $deflate
  102.         /**
  103.           * @access public
  104.           * @var bolean  If true, Remove unnecessary backslashes ("\"). False is default value.
  105.           * @see http://csstidy.sourceforge.net/usage.php
  106.           */
  107.         var $tidy_cfg_remove_bslash              = false;
  108.         /**
  109.           * @access public
  110.           * @var bolean  If true, compat "#000000" to "#000". True is default value.
  111.           * @see http://csstidy.sourceforge.net/usage.php
  112.           */
  113.         var $tidy_cfg_compress_colors            = true;
  114.         /**
  115.           * @access public
  116.           * @var bolean  if true,  change "bold" to "700". True is default value.
  117.           * @see http://csstidy.sourceforge.net/usage.php
  118.           */
  119.         var $tidy_cfg_compress_font_weight       = true;
  120.         /**
  121.           * @access public
  122.           * @var bolean  if true,  change all selector to lower case. Default is false.
  123.           * @see http://csstidy.sourceforge.net/usage.php
  124.           */
  125.         var $tidy_cfg_lowercase_s                = false;
  126.         /**
  127.           * @access public
  128.           * @var numeric 0 = Dont't Optimise, 1 = Safe Optimisations, 2 = All Optisiations. Default is 1.
  129.           * @see http://csstidy.sourceforge.net/usage.php
  130.           * @see http://www.dustindiaz.com/css-shorthand/
  131.           */
  132.         var $tidy_cfg_optimise_shorthands        = 1;
  133.         /**
  134.           * @access public
  135.           * @var bolean if true, Remove last ";" . False is default.
  136.           * @see http://csstidy.sourceforge.net/usage.php
  137.           */
  138.         var $tidy_cfg_remove_last_semicolon      = false;
  139.         /**
  140.           * @access public
  141.           * @var numeric case for properties. 0 = no change, 1 = lowercase, 2 = uppercase. 0 is default.
  142.           * @see http://csstidy.sourceforge.net/usage.php
  143.           */
  144.         var $tidy_cfg_case_properties            = 0;
  145.         /**
  146.           * @access public
  147.           * @var bolean sort properties in ascendant order. False is default.
  148.           * @see http://csstidy.sourceforge.net/usage.php
  149.           */
  150.         var $tidy_cfg_sort_properties            = false;
  151.         /**
  152.           * @access public
  153.           * @var bolean sort selectors in ascendant order. False is default.
  154.           * @see http://csstidy.sourceforge.net/usage.php
  155.           */
  156.         var $tidy_cfg_sort_selectors             = false;
  157.         /**
  158.           * @access public
  159.           * @var numeric 0 = Do not change anything, 1 = Only separate selectors (split at .), 2 = Merge selectors with same properties (fast). 2 is default.
  160.           * @see http://csstidy.sourceforge.net/usage.php
  161.           */
  162.         var $tidy_cfg_merge_selectors            = 2;
  163.         /**
  164.           * @access public
  165.           * @var bolean Discard invalid properties based at $tidy_cfg_discard_invalid_properties value. False is default.
  166.           * @see http://csstidy.sourceforge.net/usage.php
  167.           */
  168.         var $tidy_cfg_discard_invalid_properties = false;
  169.         /**
  170.           * @access public
  171.           * @var string  Possible values are 'CSS1.0', 'CSS2.0', 'CSS2.1'. Default is 'CSS2.1'
  172.           * @see http://csstidy.sourceforge.net/usage.php
  173.           */
  174.         var $tidy_cfg_css_level                  = 'CSS2.1';
  175.         /**
  176.           * @access public
  177.           * @var bolean. Save comments, hacks, etc. Most optimisations can *not* be applied if this is enabled. Default is false.
  178.           * @see http://csstidy.sourceforge.net/usage.php
  179.           */
  180.         var $tidy_cfg_preserve_css               = false;
  181.         /**
  182.           * @access public
  183.           * @var bolean. Insert a first line with a comment like this: "CSSTidy 1.3dev: Tue, 05 Aug 2008 14:56:53 +0200" . Default is false.
  184.           * @see http://csstidy.sourceforge.net/usage.php
  185.           */
  186.         var $tidy_cfg_timestamp                  = false;    
  187.         /**
  188.           *  Construtor function
  189.           *
  190.           *  This function set defaults values and determine client browser capabilities.
  191.           *  @access public
  192.           */
  193.         function crushJsCss()
  194.         {
  195.             $this->production = (isset($_SESSION['PRODUCTION'])) $_SESSION['PRODUCTION'$this->production;
  196.             $this->cachedir  = (!$this->cachedir)$_SERVER["DOCUMENT_ROOT"].'/cache' $this->cachedir;
  197.             
  198.             // Determine supported compression method
  199.             $this->gzip    = strstr($_SERVER['HTTP_ACCEPT_ENCODING']'gzip');
  200.             $this->deflate = strstr($_SERVER['HTTP_ACCEPT_ENCODING']'deflate');
  201.             // Determine used compression method
  202.             $this->encoding = $this->gzip ? 'gzip' ($this->deflate ? 'deflate' 'none');
  203.             // Check for buggy versions of Internet Explorer
  204.             if (!strstr($_SERVER['HTTP_USER_AGENT']'Opera'&& 
  205.                 preg_match('/^Mozilla\/4\.0 \(compatible; MSIE ([0-9]\.[0-9])/i'$_SERVER['HTTP_USER_AGENT']$matches)) {
  206.                 $version floatval($matches[1]);
  207.                 
  208.                 if ($version 6)
  209.                     $this->encoding = 'none';
  210.                     
  211.                 if ($version == && !strstr($_SERVER['HTTP_USER_AGENT']'EV1')) 
  212.                     $this->encoding = 'none';
  213.             }            
  214.         }
  215.         /**
  216.           *  Merge, compact and scramble javascript and css files
  217.           *  
  218.           *  This function first checks whether the file needs new version or the version stored in cache can be used.
  219.           *  If a new file should be created, the function checks the variable $type to determine if a file is javascript or css.
  220.           *  The function also check the $production  and $scripts["pack"], to determine whether the file should be compressed.
  221.           *  All css  or javascripts files are merged into a single file and submitted to function gzipIt, which compact and return the content according to the client browser´s capabilities.
  222.           *  @access public
  223.           *  @return string string or binary content
  224.           */
  225.         function jscss()
  226.         {
  227.             $this->cache();
  228.             $str '';
  229.             foreach ($this->scripts as $file){
  230.                 $src file_get_contents($file['file']);
  231.                 if($this->production && !isset($file['pack'])){
  232.                     if($this->type == 'javascript'){
  233.                         $packer new JavaScriptPacker($src$this->js_encoding$this->js_fastDecode$this->js_specialChars);
  234.                         $str   .=  "\n" .(preg_replace('/[\n\r]/'";\n"$packer->pack()));
  235.                     }else{
  236.                         $css new csstidy();
  237.                         $css->set_cfg('remove_bslash'              $this->tidy_cfg_remove_bslash);
  238.                         $css->set_cfg('compress_colors'            $this->tidy_cfg_compress_colors);
  239.                         $css->set_cfg('compress_font-weight'       $this->tidy_cfg_compress_font_weight);
  240.                         $css->set_cfg('lowercase_s'                $this->tidy_cfg_lowercase_s);
  241.                         $css->set_cfg('optimise_shorthands'        $this->tidy_cfg_optimise_shorthands);
  242.                         $css->set_cfg('remove_last_;'              $this->tidy_cfg_remove_last_semicolon);
  243.                         $css->set_cfg('case_properties'            $this->tidy_cfg_case_properties);
  244.                         $css->set_cfg('sort_properties'            $this->tidy_cfg_sort_properties);
  245.                         $css->set_cfg('sort_selectors'             $this->tidy_cfg_sort_selectors);
  246.                         $css->set_cfg('merge_selectors'            $this->tidy_cfg_merge_selectors);
  247.                         $css->set_cfg('discard_invalid_properties' $this->tidy_cfg_discard_invalid_properties);
  248.                         $css->set_cfg('css_level'                  $this->tidy_cfg_css_level);
  249.                         $css->set_cfg('preserve_css'               $this->tidy_cfg_preserve_css);
  250.                         $css->set_cfg('timestamp'                  $this->tidy_cfg_timestamp);                    
  251.                         $css->parse($src);        
  252.                         $str .= "\n" $css->print->plain();                    
  253.                     }
  254.                 }else{
  255.                     $str .=  "\n" $src;
  256.                 }
  257.             }
  258.             $this->gzipIt($str);
  259.         }
  260.         /**
  261.           *  It verifies cache´s contents
  262.           *  
  263.           *  It verifies that cache is valid. If yes, the version of the cache is sent. If the client's browser already has the file, nothing is sent.
  264.           *  @access private
  265.           *  @return string or binary content
  266.           */        
  267.         function cache()
  268.         {
  269.             $size 0;
  270.             foreach ($this->scripts as $file){
  271.                 $chaged[filemtime($file['file']);
  272.                 $size     += strlen($file['file']);
  273.             }
  274.             sort($chagedSORT_NUMERIC);
  275.             // Try the cache first to see if the combined files were already generated
  276.             $hash md5($chaged[count($chaged)-1]);
  277.             $this->cachefile = 'cache-' $hash '_S'.$size.'.' $this->type . ($this->encoding != 'none' '.' $this->encoding : '');        
  278.             if (file_exists($this->cachedir . '/' $this->cachefile)) {
  279.                 // Send Etag hash
  280.                 header ("Etag: \"" $hash "\"");            
  281.                 if (isset($_SERVER['HTTP_IF_NONE_MATCH']&& 
  282.                     stripslashes($_SERVER['HTTP_IF_NONE_MATCH']== '"' $this->cachefile . '"'){
  283.                         // Return visit and no modifications, so do not send anything
  284.                         header ("HTTP/1.0 304 Not Modified");
  285.                         header ('Content-Length: 0');
  286.                         exit;
  287.                 }
  288.                 if ($fp fopen($this->cachedir . '/' $this->cachefile'rb')) {
  289.                     header ('Vary: Accept-Encoding');
  290.                     if ($this->encoding != 'none'{
  291.                         header ("Content-Encoding: " $this->encoding);
  292.                     }        
  293.                     header ("Content-Type: text/" $this->type);
  294.                     header ("Content-Length: " filesize($this->cachedir . '/' $this->cachefile));
  295.                     fpassthru($fp);
  296.                     fclose($fp);
  297.                     exit;
  298.                 }
  299.             }
  300.         }
  301.         /**
  302.           *  Compact javascript and css files and save in cache directory
  303.           *  
  304.           *  It ensures the client's browser accepts compressed files. If yes, return the file to accept compaction.
  305.           *  If not, return the file without compress. Save the file in the cache for later use.
  306.           *  @access private
  307.           *  @param string $contents 
  308.           *  @return string string or binary content
  309.           */        
  310.         function gzipIt($contents)
  311.         {
  312.             // Send Content-Type
  313.             header ("Content-Type: text/" $this->type);
  314.             if (isset($this->encoding&& $this->encoding != 'none'){
  315.                 // Send compressed contents
  316.                 $contents gzencode($contents9$this->gzip ? FORCE_GZIP FORCE_DEFLATE);
  317.                 header ('Vary: Accept-Encoding');
  318.                 header ("Content-Encoding: " $this->encoding);
  319.                 header ('Content-Length: ' strlen($contents));
  320.                 print $contents;
  321.             }else{
  322.                 // Send regular contents
  323.                 header ('Content-Length: ' strlen($contents));
  324.                 echo $contents;
  325.             }
  326.             // Store cache
  327.             if ($fp fopen($this->cachedir . '/' $this->cachefile'wb')){
  328.                 fwrite($fp$contents);
  329.                 fclose($fp);
  330.             }    
  331.         }        
  332.     }
  333. }
  334. ?>

Documentation generated on Wed, 06 Aug 2008 13:04:43 -0300 by phpDocumentor 1.4.1