Last active
December 17, 2015 08:59
-
-
Save borgand/5584242 to your computer and use it in GitHub Desktop.
A SimpleSAMLphp Asset helper to produce MD5-fingerprinted URLs to assets. This allows long-term agressive caching by the browser while retaining instantaneous refreshing when the asset changes. Put this file in some SSP module's lib directory and rename the class name to match the module name (e.g. sspmod_mymodule_Asset).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Helper class for working with Assets | |
* | |
* @author Laas Toom, University of tartu | |
*/ | |
class sspmod_utmodule_Asset { | |
/** | |
* Get absolute URL to a specified asset. | |
* | |
* This function creates an absolute URL to a resource stored under ".../modules/<module>/www/". | |
* Additionally, when {@param $parameters}['fingerprint'] is set, the asset will be fingerprinted with MD5. e.g.: | |
* | |
* module/style.css -> module/style-c743acf9494efdcd97a17229f3fcd8f1.css | |
* | |
* Use following Apache RewriteRule to ditch this fingerprint on server: | |
* RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-d | |
* RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f | |
* RewriteRule ^(.+)-[0-9a-f]{32}\.(css|js)$ $1.$2 [PT] | |
* | |
* @param string $resource Resource path, on the form "<module name>/<resource>" | |
* @param array $parameters Extra parameters which should be added to the URL. Optional. | |
* @return string The absolute URL to the given resource. | |
*/ | |
public static function getAssetUrl($resource, array $parameters = array()) { | |
assert('is_string($resource)'); | |
assert('$resource[0] !== "/"'); | |
$fingerprint = false; | |
if (array_key_exists('fingerprint', $parameters)){ | |
$fingerprint = array_key_exists('fingerprint', $parameters); | |
# Remove it from parameters | |
unset($parameters['fingerprint']); | |
} | |
// apply fingerprint to resource name | |
if ($fingerprint) { | |
list($module_name, $asset_name) = explode("/", $resource); | |
$module_basedir = SimpleSAML_Module::getModuleDir($module_name); | |
$asset_file = $module_basedir . "/www/" . $asset_name; | |
// only try to hash existing files | |
if (file_exists($asset_file)) { | |
$asset_md5 = file_exists($asset_file) ? "-" . md5_file($asset_file) : ""; | |
$resource = preg_replace("/\.([^.]+)$/", "$asset_md5.$1", $resource); | |
} | |
} | |
$url = SimpleSAML_Module::getModuleUrl($resource, $parameters); | |
return $url; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment