<?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 get relative file path
function get_relative_path( $current_path, $file_path ) {
	// Prepare file path
	if ( strpos( $file_path, '?' ) !== false ) {
		list( $file_path, $query_string ) = explode( '?', $file_path, 2 );
	}

	$current_path = str_replace( '\\', '/', $current_path );
	$real_path    = realpath( $current_path . '/' . $file_path );
	$root_path    = realpath( str_replace( '\\', '/', getenv( 'DOCUMENT_ROOT' ) ) );

	return substr( $real_path, strlen( $root_path ) ) . ( isset( $query_string ) ? "?{$query_string}" : '' );
}

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

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

	if ( ! ( $source = @file_get_contents( $path ) ) ) {
		return '';
	}

	// Rewrite all relative URLs
	if ( preg_match_all( '/(@import\s+|[^:,;\}\r\n]*)([^,;\}\r\n]*)url\s*\(\s*([^\)]+)\s*\)([^,;\}\r\n]*[,;\}])/i', $source, $matches, PREG_SET_ORDER ) ) {
		foreach ( $matches as $match ) {
			$file_url = get_relative_path( dirname( $path ), trim( $match[3], '"\'' ) );

			if ( '@import' != trim( $match[1] ) ) {
				if ( strpos( $match[3], '://' ) === false && strpos( $match[3], '//' ) !== 0 && ! empty( $file_url ) ) {
					$file_url = ltrim( str_replace( '\\', '/', $file_url ), '/' );
					$source   = str_replace( $match[0], $match[1] . $match[2] . 'url(/' . $file_url . ')' . $match[4], $source );
				}
			} elseif ( ! preg_match( '#^https?://#', $match[3] ) ) {
				// Get file path
				$file_path = getenv( 'DOCUMENT_ROOT' ) . $file_url;

				// Compress file being imported
				if ( $import = get_file( $file_path ) ) {
					$source = str_replace( $match[0], $import, $source );
				}
			}
		}
	}

	return $source;
}

// Get global variables containing styles need to be loaded
global $it_styles;

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

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

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

	foreach ( $it_styles as $style ) {
		$style = substr( $style, 0, strpos( $style, '?' ) );

		if ( strpos( $style, '..' ) !== false || '.css' != substr( $style, -4 ) ) {
			// Might be hacking attemp
			continue;
		}

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

	// Set necessary headers
	header( 'Content-Type: text/css'                                                    );
	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 );
}
