stage_file_proxy.module in Stage File Proxy 6
File
stage_file_proxy.module
View source
<?php
function stage_file_proxy_init() {
$file_dir = file_directory_path();
if (strpos($_GET['q'], $file_dir) !== 0) {
return;
}
$relative_path = substr($_GET['q'], strlen($file_dir) + 1);
$server = variable_get('stage_file_proxy_origin', NULL);
if ($server) {
if (variable_get('stage_file_proxy_use_imagecache_root', TRUE) && strpos($relative_path, 'imagecache') === 0) {
$relative_path = preg_replace('/imagecache\\/.*\\/(.*)/U', '$1', $relative_path);
if (file_exists($file_dir . '/' . $relative_path) || file_exists($relative_path)) {
return;
}
}
if (variable_get('stage_file_proxy_hotlink', FALSE)) {
header("Location: {$server}/{$_GET['q']}");
exit;
}
elseif (_stage_file_proxy_fetch($server, $relative_path)) {
header("Location: /{$_GET['q']}");
exit;
}
else {
die('Stage File Proxy encountered an unknown error');
}
}
}
function _stage_file_proxy_fetch($server, $relative_path) {
$dirs = explode('/', $relative_path);
$filename = array_pop($dirs);
$tree = array();
$file_dir = file_directory_path();
$dir_path = $file_dir;
$dir_checks = array();
foreach ($dirs as $dir) {
$tree[] = $dir;
$dir_path = $file_dir . '/' . implode('/', $tree);
$dir_checks[] = $dir_path;
}
$url = $server . '/' . $dir_path . '/' . rawurlencode($filename);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.15) Gecko/20080623 Firefox/2.0.0.15');
$res = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) < 300) {
if (!file_check_directory($dir_path, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
foreach ($dir_checks as $dir) {
if (!file_check_directory($dir, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
return FALSE;
}
}
}
file_put_contents($file_dir . '/' . $relative_path, $res);
return TRUE;
}
return FALSE;
}