2 // Based upon "Privacy Image Cache" by Tobias Hößl <https://github.com/CatoTH/>
6 define('PROXY_DEFAULT_TIME', 86400); // 1 Day
8 define('PROXY_SIZE_MICRO', 'micro');
9 define('PROXY_SIZE_THUMB', 'thumb');
10 define('PROXY_SIZE_SMALL', 'small');
11 define('PROXY_SIZE_MEDIUM', 'medium');
12 define('PROXY_SIZE_LARGE', 'large');
14 require_once 'include/security.php';
15 require_once 'include/Photo.php';
17 function proxy_init(App $a) {
18 // Pictures are stored in one of the following ways:
19 // 1. If a folder "proxy" exists and is writeable, then use this for caching
20 // 2. If a cache path is defined, use this
21 // 3. If everything else failed, cache into the database
23 // Question: Do we really need these three methods?
25 if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
26 header('HTTP/1.1 304 Not Modified');
27 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
28 header('Etag: ' . $_SERVER['HTTP_IF_NONE_MATCH']);
29 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
30 header('Cache-Control: max-age=31536000');
32 if (function_exists('header_remove')) {
33 header_remove('Last-Modified');
34 header_remove('Expires');
35 header_remove('Cache-Control');
40 if (function_exists('header_remove')) {
41 header_remove('Pragma');
42 header_remove('pragma');
48 $basepath = $a->get_basepath();
50 // If the cache path isn't there, try to create it
51 if (!is_dir($basepath . '/proxy') AND is_writable($basepath)) {
52 mkdir($basepath . '/proxy');
55 // Checking if caching into a folder in the webroot is activated and working
56 $direct_cache = (is_dir($basepath . '/proxy') AND is_writable($basepath . '/proxy'));
58 // Look for filename in the arguments
59 if ((isset($a->argv[1]) OR isset($a->argv[2]) OR isset($a->argv[3])) AND !isset($_REQUEST['url'])) {
60 if (isset($a->argv[3])) {
62 } elseif (isset($a->argv[2])) {
68 if (isset($a->argv[3]) AND ($a->argv[3] == 'thumb')) {
72 // thumb, small, medium and large.
73 if (substr($url, -6) == ':micro') {
76 $url = substr($url, 0, -6);
77 } elseif (substr($url, -6) == ':thumb') {
80 $url = substr($url, 0, -6);
81 } elseif (substr($url, -6) == ':small') {
83 $url = substr($url, 0, -6);
85 } elseif (substr($url, -7) == ':medium') {
87 $url = substr($url, 0, -7);
88 $sizetype = ':medium';
89 } elseif (substr($url, -6) == ':large') {
91 $url = substr($url, 0, -6);
95 $pos = strrpos($url, '=.');
97 $url = substr($url, 0, $pos + 1);
100 $url = str_replace(array('.jpg', '.jpeg', '.gif', '.png'), array('','','',''), $url);
102 $url = base64_decode(strtr($url, '-_', '+/'), true);
105 $_REQUEST['url'] = $url;
108 $direct_cache = false;
111 if (!$direct_cache) {
112 $urlhash = 'pic:' . sha1($_REQUEST['url']);
114 $cachefile = get_cachefile(hash('md5', $_REQUEST['url']));
115 if ($cachefile != '' AND file_exists($cachefile)) {
116 $img_str = file_get_contents($cachefile);
117 $mime = image_type_to_mime_type(exif_imagetype($cachefile));
119 header('Content-type: ' . $mime);
120 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
121 header('Etag: "' . md5($img_str) . '"');
122 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
123 header('Cache-Control: max-age=31536000');
125 // reduce quality - if it isn't a GIF
126 if ($mime != 'image/gif') {
127 $img = new Photo($img_str, $mime);
128 if ($img->is_valid()) {
129 $img_str = $img->imageString();
143 if (!$direct_cache AND ($cachefile == '')) {
144 $r = qu("SELECT * FROM `photo` WHERE `resource-id` = '%s' LIMIT 1", $urlhash);
145 if (dbm::is_result($r)) {
146 $img_str = $r[0]['data'];
147 $mime = $r[0]['desc'];
149 $mime = 'image/jpeg';
154 if (!dbm::is_result($r)) {
155 // It shouldn't happen but it does - spaces in URL
156 $_REQUEST['url'] = str_replace(' ', '+', $_REQUEST['url']);
158 $img_str = fetch_url($_REQUEST['url'], true, $redirects, 10);
160 $tempfile = tempnam(get_temppath(), 'cache');
161 file_put_contents($tempfile, $img_str);
162 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
165 // If there is an error then return a blank image
166 if ((substr($a->get_curl_code(), 0, 1) == '4') OR (!$img_str)) {
167 $img_str = file_get_contents('images/blank.png');
169 $cachefile = ''; // Clear the cachefile so that the dummy isn't stored
171 $img = new Photo($img_str, 'image/png');
172 if ($img->is_valid()) {
173 $img->scaleImage(10);
174 $img_str = $img->imageString();
176 } elseif ($mime != 'image/jpeg' AND !$direct_cache AND $cachefile == '') {
177 $image = @imagecreatefromstring($img_str);
179 if ($image === FALSE) {
183 q("INSERT INTO `photo`
184 ( `uid`, `contact-id`, `guid`, `resource-id`, `created`, `edited`, `filename`, `album`, `height`, `width`, `desc`, `data`, `scale`, `profile`, `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid` )
185 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, %d, '%s', '%s', '%s', '%s' )",
186 0, 0, get_guid(), dbesc($urlhash),
187 dbesc(datetime_convert()),
188 dbesc(datetime_convert()),
189 dbesc(basename(dbesc($_REQUEST['url']))),
191 intval(imagesy($image)),
192 intval(imagesx($image)),
197 dbesc(''), dbesc(''), dbesc(''), dbesc('')
201 $img = new Photo($img_str, $mime);
202 if ($img->is_valid() AND !$direct_cache AND ($cachefile == '')) {
203 $img->store(0, 0, $urlhash, $_REQUEST['url'], '', 100);
208 $img_str_orig = $img_str;
210 // reduce quality - if it isn't a GIF
211 if ($mime != 'image/gif') {
212 $img = new Photo($img_str, $mime);
213 if ($img->is_valid()) {
214 $img->scaleImage($size);
215 $img_str = $img->imageString();
219 // If there is a real existing directory then put the cache file there
220 // advantage: real file access is really fast
221 // Otherwise write in cachefile
222 if ($valid AND $direct_cache) {
223 file_put_contents($basepath . '/proxy/' . proxy_url($_REQUEST['url'], true), $img_str_orig);
224 if ($sizetype != '') {
225 file_put_contents($basepath . '/proxy/' . proxy_url($_REQUEST['url'], true) . $sizetype, $img_str);
227 } elseif ($cachefile != '') {
228 file_put_contents($cachefile, $img_str_orig);
231 header('Content-type: ' . $mime);
233 // Only output the cache headers when the file is valid
235 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
236 header('Etag: "' . md5($img_str) . '"');
237 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
238 header('Cache-Control: max-age=31536000');
247 * @brief Transform a remote URL into a local one
249 * This function only performs the URL replacement on http URL and if the
250 * provided URL isn't local, "the isn't deactivated" (sic) and if the config
251 * system.proxy_disabled is set to false.
253 * @param string $url The URL to proxyfy
254 * @param bool $writemode Returns a local path the remote URL should be saved to
255 * @param string $size One of the PROXY_SIZE_* constants
257 * @return string The proxyfied URL or relative path
259 function proxy_url($url, $writemode = false, $size = '') {
262 if (substr($url, 0, strlen('http')) !== 'http') {
266 // Only continue if it isn't a local image and the isn't deactivated
267 if (proxy_is_local_image($url)) {
268 $url = str_replace(normalise_link(App::get_baseurl()) . '/', App::get_baseurl() . '/', $url);
272 if (get_config('system', 'proxy_disabled')) {
276 // Image URL may have encoded ampersands for display which aren't desirable for proxy
277 $url = html_entity_decode($url, ENT_NOQUOTES, 'utf-8');
279 // Creating a sub directory to reduce the amount of files in the cache directory
280 $basepath = $a->get_basepath() . '/proxy';
282 $shortpath = hash('md5', $url);
283 $longpath = substr($shortpath, 0, 2);
285 if (is_dir($basepath) AND $writemode AND !is_dir($basepath . '/' . $longpath)) {
286 mkdir($basepath . '/' . $longpath);
287 chmod($basepath . '/' . $longpath, 0777);
290 $longpath .= '/' . strtr(base64_encode($url), '+/', '-_');
292 // Extract the URL extension
293 $extension = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION);
295 $extensions = array('jpg', 'jpeg', 'gif', 'png');
296 if (in_array($extension, $extensions)) {
297 $shortpath .= '.' . $extension;
298 $longpath .= '.' . $extension;
301 $proxypath = App::get_baseurl() . '/proxy/' . $longpath;
307 // Too long files aren't supported by Apache
308 // Writemode in combination with long files shouldn't be possible
309 if ((strlen($proxypath) > 250) AND $writemode) {
311 } elseif (strlen($proxypath) > 250) {
312 return App::get_baseurl() . '/proxy/' . $shortpath . '?url=' . urlencode($url);
313 } elseif ($writemode) {
316 return $proxypath . $size;
324 function proxy_is_local_image($url) {
325 if ($url[0] == '/') {
329 if (strtolower(substr($url, 0, 5)) == 'data:') {
333 // links normalised - bug #431
334 $baseurl = normalise_link(App::get_baseurl());
335 $url = normalise_link($url);
336 return (substr($url, 0, strlen($baseurl)) == $baseurl);
340 * @brief Return the array of query string parameters from a URL
343 * @return array Associative array of query string parameters
345 function proxy_parse_query($url) {
346 $query = parse_url($url, PHP_URL_QUERY);
347 $query = html_entity_decode($query);
348 $query_list = explode('&', $query);
351 foreach ($query_list as $key_value) {
352 $key_value_list = explode('=', $key_value);
353 $arr[$key_value_list[0]] = $key_value_list[1];
356 unset($url, $query_list, $url);
360 function proxy_img_cb($matches) {
361 // if the picture seems to be from another picture cache then take the original source
362 $queryvar = proxy_parse_query($matches[2]);
363 if (($queryvar['url'] != '') AND (substr($queryvar['url'], 0, 4) == 'http')) {
364 $matches[2] = urldecode($queryvar['url']);
367 // following line changed per bug #431
368 if (proxy_is_local_image($matches[2])) {
369 return $matches[1] . $matches[2] . $matches[3];
372 return $matches[1] . proxy_url(htmlspecialchars_decode($matches[2])) . $matches[3];
375 function proxy_parse_html($html) {
376 $html = str_replace(normalise_link(App::get_baseurl()) . '/', App::get_baseurl() . '/', $html);
378 return preg_replace_callback('/(<img [^>]*src *= *["\'])([^"\']+)(["\'][^>]*>)/siU', 'proxy_img_cb', $html);