PageRenderTime 537ms CodeModel.GetById 130ms app.highlight 87ms RepoModel.GetById 74ms app.codeStats 80ms

/components/com_virtuemart/fetchscript.php

https://bitbucket.org/dgough/annamaria-daneswood-25102012
PHP | 258 lines | 185 code | 31 blank | 42 comment | 43 complexity | 813f17d856b9d32cfd5468ebd87c58e7 MD5 | raw file
  1<?php
  2/**
  3* This file is used to send gzipped Javascripts and Stylesheets to the browser
  4* 
  5* It expects three parameters:
  6* 
  7* gzip (can be 1 or 0, for yes or no; default: 0)
  8* subdir[INDEX] (relative directory from /components/com_virtuemart/js)
  9* file[INDEX] (filename only)
 10* where INDEX is the actual number of the file to be included, so you can include multiple scripts at a time
 11* 
 12* @version $Id: fetchscript.php 1367 2008-04-10 19:30:20Z soeren_nb $
 13* @package VirtueMart
 14* @subpackage core
 15* @copyright Copyright (C) 2006-2007 soeren - All rights reserved.
 16* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
 17* VirtueMart is free software. This version may have been modified pursuant
 18* to the GNU General Public License, and as distributed it includes or
 19* is derivative of works licensed under the GNU General Public License or
 20* other free or open source software licenses.
 21* See /administrator/components/com_virtuemart/COPYRIGHT.php for copyright notices and details.
 22*
 23* http://virtuemart.net
 24*/
 25
 26/**
 27 * Initialise GZIP
 28 * @author Mambo / Joomla Project
 29 */
 30function initGzip() {
 31	global $do_gzip_compress;
 32	
 33	$gzip = isset( $_GET['gzip'] ) ? (boolean)$_GET['gzip'] : false;
 34	
 35	$do_gzip_compress = FALSE;
 36	if ($gzip) {
 37		$phpver 	= phpversion();
 38		$useragent 	= isset( $_SERVER['HTTP_USER_AGENT'] ) ? $_SERVER['HTTP_USER_AGENT'] : '';
 39		$canZip 	= isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ? $_SERVER['HTTP_ACCEPT_ENCODING'] : '';
 40		
 41		$gzip_check 	= 0;
 42		$zlib_check 	= 0;
 43		$gz_check		= 0;
 44		$zlibO_check	= 0;
 45		$sid_check		= 0;
 46		if ( strpos( $canZip, 'gzip' ) !== false) {
 47			$gzip_check = 1;
 48		}		
 49		if ( extension_loaded( 'zlib' ) ) {
 50			$zlib_check = 1;
 51		}		
 52		if ( function_exists('ob_gzhandler') ) {
 53			$gz_check = 1;
 54		}
 55		if ( ini_get('zlib.output_compression') ) {
 56			$zlibO_check = 1;
 57		}
 58
 59		if ( $phpver >= '4.0.4pl1' && ( strpos($useragent,'compatible') !== false || strpos($useragent,'Gecko')	!== false ) ) {
 60			// Check for gzip header or norton internet securities
 61			if ( ( $gzip_check || isset( $_SERVER['---------------']) ) && $zlib_check && $gz_check && !$zlibO_check ) {
 62				// You cannot specify additional output handlers if
 63				// zlib.output_compression is activated here
 64				ob_start( 'ob_gzhandler' );
 65				
 66				return;
 67			}
 68		} else if ( $phpver > '4.0' ) {
 69			if ( $gzip_check ) {
 70				
 71				if ( $zlib_check ) {
 72					$do_gzip_compress = TRUE;
 73					ob_start();
 74					ob_implicit_flush(0);
 75					
 76					header( 'Content-Encoding: gzip' );
 77					return;
 78				}
 79			}
 80		}
 81	}
 82	ob_start();
 83}
 84
 85/**
 86* Perform GZIP
 87* @author Mambo / Joomla! project
 88*/
 89function doGzip() {
 90	global $do_gzip_compress;
 91	if ( $do_gzip_compress ) {
 92		/**
 93		*Borrowed from php.net!
 94		*/
 95		$gzip_contents = ob_get_contents();
 96		ob_end_clean();
 97
 98		$gzip_size = strlen($gzip_contents);
 99		$gzip_crc = crc32($gzip_contents);
100
101		$gzip_contents = gzcompress($gzip_contents, 9);
102		$gzip_contents = substr($gzip_contents, 0, strlen($gzip_contents) - 4);
103
104		echo "\x1f\x8b\x08\x00\x00\x00\x00\x00";
105		echo $gzip_contents;
106		echo pack('V', $gzip_crc);
107		echo pack('V', $gzip_size);
108	} else {
109		ob_end_flush();
110	}
111}
112function cssUrl( $ref, $subdir ) {
113	$ref = str_replace( "'", '', stripslashes( trim($ref) ));
114	$ref = str_replace( '"', '', $ref);
115	if( $subdir[0] == '/' ) {
116		$subdir = substr( $subdir, 1 );
117	}
118	return 'url( "'. $subdir.'/'.$ref.'" )';
119}
120/**
121 * Checks and sets HTTP headers for conditional HTTP requests
122 * Borrowed from DokuWiki (/lib/exe/fetch.php)
123 * @author Simon Willison <swillison@gmail.com>
124 * @link   http://simon.incutio.com/archive/2003/04/23/conditionalGet
125 */
126function http_conditionalRequest($timestamp){
127    // A PHP implementation of conditional get, see 
128    //   http://fishbowl.pastiche.org/archives/001132.html
129    $last_modified = gmdate( 'D, d M Y H:i:s', $timestamp ) . ' GMT';
130    $etag = '"'.md5($last_modified).'"';
131    // Send the headers
132    header("Last-Modified: $last_modified");
133    header("ETag: $etag");
134    // See if the client has provided the required headers
135    $if_modified_since = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ?
136        stripslashes($_SERVER['HTTP_IF_MODIFIED_SINCE']) :
137        false;
138    $if_none_match = isset($_SERVER['HTTP_IF_NONE_MATCH']) ?
139        stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) : 
140        false;
141    if (!$if_modified_since && !$if_none_match) {
142        return;
143    }
144    // At least one of the headers is there - check them
145    if ($if_none_match && $if_none_match != $etag) {
146        return; // etag is there but doesn't match
147    }
148    if ($if_modified_since && $if_modified_since != $last_modified) {
149        return; // if-modified-since is there but doesn't match
150    }
151    // Nothing has changed since their last request - serve a 304 and exit
152    header('HTTP/1.0 304 Not Modified');
153    exit;
154}
155
156initGzip();
157
158$base_dir = dirname( __FILE__ );
159$subdirs = @$_GET['subdir'];
160if( !is_array( $subdirs ) && !empty( $subdirs )) {
161	$subdirs = array( $subdirs );
162}
163
164$files = @$_GET['file'];
165if( !is_array( $files ) && !empty( $files )) {
166	$files = array( $files );
167}
168if( empty( $files ) || sizeof($files) != sizeof( $subdirs )) {
169	header("HTTP/1.0 400 Bad Request");
170  	echo 'Bad request';
171  	exit;
172}
173$countFiles = sizeof($files);
174$newest_mdate = 0;
175
176for( $i = 0; $i < $countFiles; $i++ ) {
177	$file = $files[$i];
178	$subdir = $subdirs[$i];
179	
180	$dir = realpath( $base_dir . '/' .  $subdir );
181	$file = $dir . '/' . basename( $file );
182	
183	if( !file_exists( $file ) || !stristr( $dir, $base_dir )) {
184		if( $countFiles == 1 ) {
185		    header("HTTP/1.0 404 Not Found");
186		    echo 'Not Found';
187		    exit;
188		}
189		continue;
190	}
191	$newest_mdate = max( filemtime( $file ), $newest_mdate );
192}
193
194// This function quits the page load if the browser has a cached version of the requested script.
195// It then returns a 304 Not Modified header
196http_conditionalRequest( $newest_mdate );
197
198// here we need to send the script or stylesheet
199$processed_files = 0;
200for( $i = 0; $i < $countFiles; $i++ ) {
201	$file = $files[$i];
202	$subdir = $subdirs[$i];
203	
204	$dir = realpath( $base_dir . '/' .  $subdir );
205	$file = $dir . '/' . basename( $file );
206	if( !file_exists( $file ) || !stristr( $dir, $base_dir ) || !is_readable( $file )) {
207		continue;
208	}
209	$processed_files++;
210	$fileinfo = pathinfo( $file );
211	switch ( $fileinfo['extension']) {
212		case 'css': 
213			$mime_type = 'text/css'; 
214			header( 'Content-Type: '.$mime_type.';');
215			$css = implode( '', file( $file ));
216			
217			$str_css =   preg_replace("/url\((.+?)\)/ie","cssUrl('\\1', '$subdir')", $css);
218			echo $str_css;
219			
220			break;
221			
222		case 'js': 
223			$mime_type = 'text/javascript'; 
224			header( 'Content-Type: '.$mime_type.';');
225			
226			readfile( $file );
227			
228			break;
229			
230		default: 
231			continue;
232		
233	}
234}
235if( $processed_files == 0 ) {
236	if( !file_exists( $file ) ) {
237	    header("HTTP/1.0 404 Not Found");
238	    echo 'Not Found';
239	    exit;
240	}
241	if( !is_readable( $file ) ) {
242	    header("HTTP/1.0 500 Internal Server Error");
243	    echo "Could not read ".basename($file)." - bad permissions?";
244	  	exit;
245	}
246}
247// Tell the user agent to cache this script/stylesheet for a week
248$age = 604800;
249header( 'Expires: '.gmdate( 'D, d M Y H:i:s', time()+ $age ) . ' GMT' );
250header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s', @filemtime( $file ) ) . ' GMT' );
251header( 'Cache-Control: public, max-age='.$age.', must-revalidate, post-check=0, pre-check=0' );
252header( 'Pragma: public' );
253
254doGzip();
255
256exit;
257
258?>