1<?php
2require_once('SecureLinkDecorator.php');
3
4class NginxSecureLinkMd5Decorator implements SecureLinkDecorator
5{
6	protected $url = null;
7	protected $prefs = array();
8
9	public static $SUPPORTED_VARIABLES = array(
10		'$secure_link_expires',
11		'$uri',
12		'$remote_addr',
13		'$host',
14	);
15
16	static function supported_variables() {
17		return self::$SUPPORTED_VARIABLES;
18	}
19
20	function __construct($url, $preferences)
21	{
22		$this->url = $url;
23		$this->prefs = $preferences;
24	}
25
26	public function decorate()
27	{
28		$prefs = $this->prefs;
29		$url = $this->url;
30		$expiry = intval($prefs['download_security_link_expiry']);
31		if ($expiry <= 0)
32			$expiry = PHP_INT_MAX;
33		else
34			$expiry = time() + $expiry;
35		$url_parts = parse_url($url);
36		$evaluation = str_replace(
37			self::supported_variables(),
38			array(
39				$expiry,
40				$url_parts['path'],
41				$_SERVER['REMOTE_ADDR'],
42				$url_parts['host'],
43			),
44			$prefs['download_security_expression']
45		);
46		$query_string = $url_parts['query'];
47		parse_str($query_string, $query_args);
48		$query_args['md5'] = str_replace(array('+', '/', '='), array('-', '_', ''), base64_encode(md5($evaluation, true)));
49		if (strpos($prefs['download_security_expression'], '$secure_link_expires') !== false)
50			$query_args['expires'] = $expiry;
51		require_once(__DIR__ . '/../vendor/shim_http_build_url.php');
52		return http_build_url($url_parts, array('query' => http_build_query($query_args)));
53	}
54}