aboutsummaryrefslogtreecommitdiff
path: root/cdn/originpull.php
blob: 00f9a03e6b8318c34c1e1191dddd49272b317879 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<?php
exit; // REMOVE THIS LINE IN PRODUCTION ENVIRONMENT!!!

if ( ! isset($_GET['url']) || $_GET['url'] == "" ){
	header($_SERVER['SERVER_PROTOCOL'] . " 404 Not Found");
	header('X-Cache: Miss');
	exit;
}
header('X-Cache: Hit');

define('ABSP', dirname(__FILE__) . '/');

# directory on origin website
define('URI', '/');

# origin website
define('ORIGIN', 'https://jungegemeinde.iamfabulous.de' . URI);

# local directory
define('LOCAL', '/');

$basepath = array('js', 'static', 'img', 'static/img');
$path_parts = pathinfo($_GET['url']);

function getMime($file){
	$finfo = new finfo(FILEINFO_MIME_TYPE);
	$mime = $finfo->file($file);

	# hack to get correct mime type for .css and .js
	$ext = pathinfo($file,PATHINFO_EXTENSION);
	switch($ext){
		case 'css': 
			$mime = "text/css";
			break;
		case'js':
			$mime = "text/javascript";
			break;
		default:
			break;
	}

	return $mime;
}

foreach($basepath as $dir){
	
	if ( URI . $dir . "/" == $path_parts['dirname'] . '/' ){

		if ( !is_dir(ABSP . $dir) ){
			mkdir(ABSP . $dir, 0744, true);
		}

		$request = str_replace(URI . $dir . "/", "",$_GET['url'] );
		$scan = array_diff( scandir($dir), array('.', '..') );

		if ( in_array($request, $scan) ){
			header("Content-type: " . getMime($dir . '/' . $request));
			header("X-Accel-Redirect: " . LOCAL . $dir . '/' . $request);
			exit;
		} else {
			$ch = curl_init(ORIGIN . $dir . "/" . $request);
			curl_setopt($ch, CURLOPT_NOBODY, true);
			curl_setopt($ch, CURLOPT_USERAGENT, 'Origin Pull/v0.1');
			curl_exec($ch);
			$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
			curl_close($ch);

			if ( $httpcode == 200 || $httpcode == 302 ) {
				file_put_contents($dir . '/' . $request,  file_get_contents(ORIGIN . $dir . "/" . $request) );
				header("Content-type: " . getMime($dir . '/' . $request));
				header("X-Accel-Redirect: " . LOCAL . $dir . '/' . $request);
				exit;
			} else {
				continue;
			}
		}
	}

}

header($_SERVER['SERVER_PROTOCOL'] . " 404 Not Found");
header('X-Cache: Miss');