From 9a48fc60d1cce8a344ec7e09293e3d958099486d Mon Sep 17 00:00:00 2001 From: robocoder Date: Fri, 25 Dec 2009 23:12:58 +0000 Subject: Serve up compressed piwik.js if possible. This can be used if user's web server (e.g., Apache) doesn't have mod_deflate or mod_gzip when serving up piwik.js directly. git-svn-id: http://dev.piwik.org/svn/trunk@1732 59fd770c-687e-43c8-a1e3-f5a4ff64c105 --- js/index.php | 46 +++++++++++++++++++++++++++++++++++++++------- 1 file changed, 39 insertions(+), 7 deletions(-) (limited to 'js/index.php') diff --git a/js/index.php b/js/index.php index 60786f2849..483e5fbabe 100644 --- a/js/index.php +++ b/js/index.php @@ -7,18 +7,46 @@ * @version $Id$ */ -$file = "../piwik.js"; +$file = '../piwik.js'; -/* - * Conditional GET - */ if (file_exists($file)) { + // conditional GET $modifiedSince = ''; if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) { $modifiedSince = $_SERVER['HTTP_IF_MODIFIED_SINCE']; } $lastModified = gmdate('D, d M Y H:i:s', filemtime($file)) . ' GMT'; + // optional compression + $compressed = false; + $encoding = ''; + if (extension_loaded('zlib') && function_exists('file_get_contents') && function_exists('file_put_contents') && isset($_SERVER['HTTP_ACCEPT_ENCODING'])) { + $acceptEncoding = $_SERVER['HTTP_ACCEPT_ENCODING']; + if (preg_match('/(?:^|, ?)(deflate)(?:,|$)/', $acceptEncoding, $matches)) { + $encoding = $matches[1]; + } else if (preg_match('/(?:^|, ?)((x-)?gzip)(?:,|$)/', $acceptEncoding, $matches)) { + $encoding = $matches[1]; + } + + if (!empty($encoding)) { + $filegz = '../piwik.js.' . $encoding; + + if(!file_exists($filegz) || (filemtime($file) > filemtime($filegz))) { + $data = file_get_contents($file); + + if ($encoding == 'deflate') { + $data = gzcompress($data, 9); + } else if ($encoding == 'gzip' || $encoding == 'x-gzip') { + $data = gzencode($data, 9); + } + + file_put_contents($filegz, $data); + $compressed = true; + $file = $filegz; + } + } + } + // strip any trailing data appended to header if (false !== ($semicolon = strpos($modifiedSince, ';'))) { $modifiedSince = substr($modifiedSince, 0, $semicolon); @@ -29,13 +57,17 @@ if (file_exists($file)) { } else { header('Last-Modified: ' . $lastModified); header('Content-Length: ' . filesize($file)); - header('Content-Type: application/x-javascript'); + header('Content-Type: application/x-javascript; charset=UTF-8'); + + if ($compressed) { + header('Content-Encoding: ' . $encoding); + } if (!readfile($file)) { - header ("HTTP/1.0 505 Internal server error"); + header ('HTTP/1.0 505 Internal server error'); } } } else { - header ("HTTP/1.0 404 Not Found"); + header ('HTTP/1.0 404 Not Found'); } exit; -- cgit v1.2.3