<?php
/**
* File caching functions
*
* @package Core
* @author Andreas Goetz <hide@address.com>
* @version $Id: cache.php,v 1.2 2007/12/03 20:04:40 andig2 Exp $
*/
// define cache folder
if (!defined('CACHE')) define('CACHE', 'cache');
function cache_get_filename($url, $cache_folder, $ext = '')
{
global $config;
if ($cache_folder) $cache_folder = "$cache_folder/";
if ($ext) $ext = ".$ext";
// construct cache file name
$md5 = md5($url);
$subdir = ($config['hierarchical']) ? substr($md5, 0, 1).'/' : '';
$cache_file = CACHE.'/'.$cache_folder.$subdir.$md5.$ext;
return $cache_file;
}
/**
* Verify existance of cached file for given url/ extension
*
* @author Andreas Goetz <hide@address.com>
* @param string url of the image
* @param string ext file extension of the image
* @param string file result: URL to the cached image if exists
* @return bool result of check
*/
function cache_file_exists($url, &$cache_file, $cache_folder, $ext = '')
{
$cache_file = cache_get_filename($url, $cache_folder, $ext);
$result = file_exists($cache_file) && filesize($cache_file);
return($result);
}
function cache_get($url, $cache_folder, $cache_max_age, $serialize = false)
{
$data = false;
if ($cache_max_age > 0)
{
if (cache_file_exists($url, $cache_file, $cache_folder) &&
(time()-filemtime($cache_file) < $cache_max_age))
{
$data = file_get_contents($cache_file);
if (($data !== false) && $serialize) $data = unserialize($data);
}
}
return $data;
}
function cache_put($url, $data, $cache_folder, $cache_max_age, $serialize = false)
{
// only put file to cache if caching is enabled
if ($cache_max_age > 0)
{
// get the cache file name
$cache_file = cache_get_filename($url, $cache_folder);
// commit to disk
if ($serialize) $data = serialize($data);
file_put_contents($cache_file, $data);
}
}
?>