<?php

header('Content-type: text/css');
ob_start('ob_gzhandler');

if(!isset($_SERVER['HTTP_USER_AGENT']) || empty($_SERVER['HTTP_USER_AGENT'])){
	$_SERVER['HTTP_USER_AGENT'] = $_REQUEST['ua'];
};

if(!isset($_SERVER['HTTP_USER_AGENT']) || empty($_SERVER['HTTP_USER_AGENT'])) {
	die('No user agent');
};

if(!isset($_SERVER['QUERY_STRING']) || empty($_SERVER['QUERY_STRING'])) {
	die('No query string');
};

$cache_folder = $_SERVER['DOCUMENT_ROOT'] . '/assets/css/fonts/';
$fonts_cache_folder = $_SERVER['DOCUMENT_ROOT'] . '/assets/css/fonts/';
$fonts_client_cache_folder = '/assets/css/fonts/';
$file_extention = '.css';
$google_url = 'https://themes.googleusercontent.com/static/fonts/';
$query_stringMD5 = md5($_SERVER['QUERY_STRING']);
$user_agentMD5 = md5($_SERVER['HTTP_USER_AGENT']);
$file_name = $query_stringMD5 . '-' . $user_agentMD5;
$file_path = $cache_folder.$file_name.$file_extention;

if (file_exists($file_path)) {
    $font_css = file_get_contents($file_path);
    echo $font_css;
} else {
    $font_css = fetchFontsCss();
    $font_css_urls = extract_css_urls($font_css);
    foreach ($font_css_urls as &$css_url) {
        $parsed_url = parse_url($css_url);
        $path = $parsed_url['path'];
        $path_array = explode('/', $path); // Pull it apart
        array_shift($path_array); // Pop the first index off array
        array_shift($path_array); // Pop the second index off array
        array_shift($path_array); // Pop the second index off array
        $path = implode('/', $path_array); // Put it together again
        $path = implode('/', $path_array); // Put it together again
        $path = $fonts_cache_folder . $path; // Put it together again
        if (!file_exists($path)) {
            $path_dir = dirname($path);
            if (!file_exists($path_dir)) {
                mkdir($path_dir, 0755, true);
            }
            downloadFile($css_url, $path);
        }
    }
    
    $font_css_save = str_replace($google_url, $fonts_client_cache_folder, $font_css);
    echo $font_css_save;
    file_put_contents($file_path, $font_css_save, LOCK_EX);
}

function fetchFontsCss() {
	$opts = array('http' => array(
			'method'     => 'GET',
			'user_agent' => $_SERVER['HTTP_USER_AGENT']
		)
	);
	$context = stream_context_create($opts);
	$result = file_get_contents('https://fonts.googleapis.com/css?' . $_SERVER['QUERY_STRING'], false, $context);
	return $result;
};

function downloadFile($url, $path) {
	$newfname = $path;
	$file = fopen ($url, "rb");
	if ($file) {
		$newf = fopen ($newfname, "wb");
		if ($newf) {
			while(!feof($file)) {
				fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );
			};
			fclose($newf);
		};
		fclose($file);
	};
};

function extract_css_urls($text) { // From: http://nadeausoftware.com/articles/2008/01/php_tip_how_extract_urls_css_file
    $urls = array();
    $url_pattern     = '(([^\\\\\'", \(\)]*(\\\\.)?)+)';
    $urlfunc_pattern = 'url\(\s*[\'"]?' . $url_pattern . '[\'"]?\s*\)';
    $pattern         = '/(' .
         '(@import\s*[\'"]' . $url_pattern     . '[\'"])' .
        '|(@import\s*'      . $urlfunc_pattern . ')'      .
        '|('                . $urlfunc_pattern . ')'      .  ')/iu';
		
    if ( !preg_match_all( $pattern, $text, $matches ) )
        return $urls;
 
    // @import '...'
    // @import "..."
    foreach ( $matches[3] as $match )
        if ( !empty($match) )
            //$urls['import'][] = 
            $urls[] = 
                preg_replace( '/\\\\(.)/u', '\\1', $match );
 
    // @import url(...)
    // @import url('...')
    // @import url("...")
    foreach ( $matches[7] as $match )
        if ( !empty($match) )
            //$urls['import'][] = 
            $urls[] = 
                preg_replace( '/\\\\(.)/u', '\\1', $match );
 
    // url(...)
    // url('...')
    // url("...")
    foreach ( $matches[11] as $match )
        if ( !empty($match) )
            //$urls['property'][] = 
            $urls[] = 
                preg_replace( '/\\\\(.)/u', '\\1', $match );
 
    return $urls;
}

?>
