<?php
/**
 * @version    $Id$
 * @package    IT_Theme_Framework
 * @author     InnoThemes Team <support@innothemes.com>
 * @copyright  Copyright (C) 2012 InnoThemes.com. All Rights Reserved.
 * @license    GNU/GPL v2 or later http://www.gnu.org/licenses/gpl-2.0.html
 *
 * Websites: http://www.innothemes.com
 */

// Define function to read script file
function get_file( $path ) {
	if ( function_exists( 'realpath' ) ) {
		$path = realpath( $path );
	}

	if ( ! $path || ! @is_file( $path ) ) {
		return '';
	}

	return @file_get_contents( $path );
}

// Get global variables containing scripts need to be loaded
global $it_scripts;

if ( isset( $it_scripts ) && is_array( $it_scripts ) && count( $it_scripts ) ) {
	$wp_root = dirname( dirname( dirname( dirname( dirname( dirname( dirname( __FILE__ ) ) ) ) ) ) );

	// Enable compression
	if ( ! isset( $_GET['c'] ) ) {
		$_GET['c'] = 'gzip';
	}

	// Start loading scripts
	$compress       = (boolean) $_GET['c'];
	$force_gzip     = ( $compress && 'gzip' == $_GET['c'] );
	$expires_offset = 31536000; // 1 year
	$out            = '';

	foreach ( $it_scripts as $script ) {
		$script = substr( $script, 0, strpos( $script, '?' ) );

		if ( strpos( $script, '..' ) !== false || '.js' != substr( $script, -3 ) ) {
			// Might be hacking attemp
			continue;
		}

		$path = $wp_root . $script;
		$out .= get_file( $path ) . "\n";
	}

	// Set necessary headers
	header( 'Content-Type: application/x-javascript; charset=UTF-8'                     );
	header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', time() + $expires_offset ) . ' GMT' );
	header( "Cache-Control: public, max-age=$expires_offset"                            );

	if ( $compress && ! ini_get( 'zlib.output_compression' ) && 'ob_gzhandler' != ini_get( 'output_handler' ) && isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
		header( 'Vary: Accept-Encoding' ); // Handle proxies

		if ( false !== stripos( $_SERVER['HTTP_ACCEPT_ENCODING'], 'deflate' ) && function_exists( 'gzdeflate' ) && ! $force_gzip ) {
			header( 'Content-Encoding: deflate' );

			$out = gzdeflate( $out, 3 );
		} elseif ( false !== stripos( $_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip' ) && function_exists( 'gzencode' ) ) {
			header( 'Content-Encoding: gzip' );

			$out = gzencode( $out, 3 );
		}
	}

	// Print output then exit
	exit( $out );
}
