From ee441e7cba2a15b7a617f103b511545f4029a174 Mon Sep 17 00:00:00 2001
From: Arun Persaud <arun@nubati.net>
Date: Sun, 3 Jun 2012 09:24:23 -0700
Subject: add autoversioning of css and js files

automatically add the md5 hash to the filename and then use .htaccess to filter it out again.
This way we don't need to change the filename and the client can cache correctly
---
 htaccess_template |  5 ++++-
 index.php         | 23 +++++++++++++++++++----
 2 files changed, 23 insertions(+), 5 deletions(-)

diff --git a/htaccess_template b/htaccess_template
index aa6f5a7..d4ba12a 100644
--- a/htaccess_template
+++ b/htaccess_template
@@ -6,8 +6,11 @@ RewriteBase   /<insert web base url here>
 # hide git directory (and others)
 RedirectMatch 404 \.(git|cvs|svn|bzr|hg)(/.*|$)
 
+# use autoversioning of js and css files
+RewriteRule ^(.*)\.[[:xdigit:]]{32}\.(css|js)$ $1.$2 [L]
 
-# make the url nice and clean; the comments shows an url that should be matched
+
+### make the url nice and clean; the comments shows an url that should be matched
 
 # web_base/tag/me+berlin/pic/id
 RewriteRule tag/([-_\s,a-zA-Z0-9+]*)/pic/([0-9]*) index.php?tag=$1&pic=$2 [L]
diff --git a/index.php b/index.php
index 85610d9..a2de85a 100644
--- a/index.php
+++ b/index.php
@@ -25,14 +25,29 @@ else
   $pic = -1;
 /* end parse flags */
 
+/* autoversioning of js and css files */
+function autoversion($file)
+{
+  /* changes the file name of e.g. css/style.css to css/style.<md5>.css/js
+   * this way the browser can cache the file and will reload it if the file changed
+   * needs to have .htaccess set up correctly to link back to css/style.css */
+
+  /* only use it for file that have an absolut path */
+  if(!file_exists(dirname($_SERVER['SCRIPT_FILENAME']). '/' . $file))
+    return $file;
+
+  $md5 = md5_file(dirname($_SERVER['SCRIPT_FILENAME']). '/' . $file);
+  return preg_replace('{\\.([^./]+)$}', ".$md5.\$1", $file);
+}
+
 /* The basic layout */
 ?>
 
 <html>
 <title><?php echo htmlspecialchars($title) ?></title>
-<script src = "<?php echo $webbase?>/js/d3.min.js"></script>
-<link rel="stylesheet" type="text/css" href="<?php echo $webbase?>/css/normalize.css" />
-<link rel="stylesheet" type="text/css" href="<?php echo $webbase?>/css/style.css" />
+<script src = "<?php echo $webbase.autoversion("/js/d3.min.js")?>"></script>
+<link rel="stylesheet" type="text/css" href="<?php echo $webbase.autoversion("/css/normalize.css")?>" />
+<link rel="stylesheet" type="text/css" href="<?php echo $webbase.autoversion("/css/style.css")?>" />
 
 <body>
 
@@ -68,7 +83,7 @@ page <span class="index"></span>
 </footer>
 
 
-<script src = "<?php echo $webbase?>/js/photo-tags.js"></script>
+<script src = "<?php echo $webbase.autoversion("/js/photo-tags.js")?>"></script>
 <script type="text/javascript" >
 /*hand parameters over to javascript*/
 var page=<?php echo $page ?>;
-- 
cgit v1.2.3-18-g5258