]> git.mxchange.org Git - friendica.git/blob - mod/proxy.php
Issue-#3873
[friendica.git] / mod / proxy.php
1 <?php
2 // Based upon "Privacy Image Cache" by Tobias Hößl <https://github.com/CatoTH/>
3
4 use Friendica\App;
5 use Friendica\Core\Config;
6 use Friendica\Core\System;
7
8 define('PROXY_DEFAULT_TIME', 86400); // 1 Day
9
10 define('PROXY_SIZE_MICRO', 'micro');
11 define('PROXY_SIZE_THUMB', 'thumb');
12 define('PROXY_SIZE_SMALL', 'small');
13 define('PROXY_SIZE_MEDIUM', 'medium');
14 define('PROXY_SIZE_LARGE', 'large');
15
16 require_once 'include/security.php';
17 require_once 'include/Photo.php';
18
19 function proxy_init(App $a) {
20         // Pictures are stored in one of the following ways:
21         // 1. If a folder "proxy" exists and is writeable, then use this for caching
22         // 2. If a cache path is defined, use this
23         // 3. If everything else failed, cache into the database
24         //
25         // Question: Do we really need these three methods?
26
27         if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
28                 header('HTTP/1.1 304 Not Modified');
29                 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
30                 header('Etag: ' . $_SERVER['HTTP_IF_NONE_MATCH']);
31                 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
32                 header('Cache-Control: max-age=31536000');
33
34                 if (function_exists('header_remove')) {
35                         header_remove('Last-Modified');
36                         header_remove('Expires');
37                         header_remove('Cache-Control');
38                 }
39                 exit;
40         }
41
42         if (function_exists('header_remove')) {
43                 header_remove('Pragma');
44                 header_remove('pragma');
45         }
46
47         $thumb = false;
48         $size = 1024;
49         $sizetype = '';
50         $basepath = $a->get_basepath();
51
52         // If the cache path isn't there, try to create it
53         if (!is_dir($basepath . '/proxy') && is_writable($basepath)) {
54                 mkdir($basepath . '/proxy');
55         }
56
57         // Checking if caching into a folder in the webroot is activated and working
58         $direct_cache = (is_dir($basepath . '/proxy') && is_writable($basepath . '/proxy'));
59
60         // Look for filename in the arguments
61         if ((isset($a->argv[1]) || isset($a->argv[2]) || isset($a->argv[3])) && !isset($_REQUEST['url'])) {
62                 if (isset($a->argv[3])) {
63                         $url = $a->argv[3];
64                 } elseif (isset($a->argv[2])) {
65                         $url = $a->argv[2];
66                 } else {
67                         $url = $a->argv[1];
68                 }
69
70                 if (isset($a->argv[3]) && ($a->argv[3] == 'thumb')) {
71                         $size = 200;
72                 }
73
74                 // thumb, small, medium and large.
75                 if (substr($url, -6) == ':micro') {
76                         $size = 48;
77                         $sizetype = ':micro';
78                         $url = substr($url, 0, -6);
79                 } elseif (substr($url, -6) == ':thumb') {
80                         $size = 80;
81                         $sizetype = ':thumb';
82                         $url = substr($url, 0, -6);
83                 } elseif (substr($url, -6) == ':small') {
84                         $size = 175;
85                         $url = substr($url, 0, -6);
86                         $sizetype = ':small';
87                 } elseif (substr($url, -7) == ':medium') {
88                         $size = 600;
89                         $url = substr($url, 0, -7);
90                         $sizetype = ':medium';
91                 } elseif (substr($url, -6) == ':large') {
92                         $size = 1024;
93                         $url = substr($url, 0, -6);
94                         $sizetype = ':large';
95                 }
96
97                 $pos = strrpos($url, '=.');
98                 if ($pos) {
99                         $url = substr($url, 0, $pos + 1);
100                 }
101
102                 $url = str_replace(array('.jpg', '.jpeg', '.gif', '.png'), array('','','',''), $url);
103
104                 $url = base64_decode(strtr($url, '-_', '+/'), true);
105
106                 if ($url) {
107                         $_REQUEST['url'] = $url;
108                 }
109         } else {
110                 $direct_cache = false;
111         }
112
113         if (!$direct_cache) {
114                 $urlhash = 'pic:' . sha1($_REQUEST['url']);
115
116                 $cachefile = get_cachefile(hash('md5', $_REQUEST['url']));
117                 if ($cachefile != '' && file_exists($cachefile)) {
118                         $img_str = file_get_contents($cachefile);
119                         $mime = image_type_to_mime_type(exif_imagetype($cachefile));
120
121                         header('Content-type: ' . $mime);
122                         header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
123                         header('Etag: "' . md5($img_str) . '"');
124                         header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
125                         header('Cache-Control: max-age=31536000');
126
127                         // reduce quality - if it isn't a GIF
128                         if ($mime != 'image/gif') {
129                                 $img = new Photo($img_str, $mime);
130                                 if ($img->is_valid()) {
131                                         $img_str = $img->imageString();
132                                 }
133                         }
134
135                         echo $img_str;
136                         killme();
137                 }
138         } else {
139                 $cachefile = '';
140         }
141
142         $valid = true;
143         $r = array();
144
145         if (!$direct_cache && ($cachefile == '')) {
146                 $r = dba::select('photo', array('data', 'desc'), array('resource-id' => $urlhash), array('limit' => 1));
147                 if (dbm::is_result($r)) {
148                         $img_str = $r['data'];
149                         $mime = $r['desc'];
150                         if ($mime == '') {
151                                 $mime = 'image/jpeg';
152                         }
153                 }
154         }
155
156         if (!dbm::is_result($r)) {
157                 // It shouldn't happen but it does - spaces in URL
158                 $_REQUEST['url'] = str_replace(' ', '+', $_REQUEST['url']);
159                 $redirects = 0;
160                 $img_str = fetch_url($_REQUEST['url'], true, $redirects, 10);
161
162                 $tempfile = tempnam(get_temppath(), 'cache');
163                 file_put_contents($tempfile, $img_str);
164                 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
165                 unlink($tempfile);
166
167                 // If there is an error then return a blank image
168                 if ((substr($a->get_curl_code(), 0, 1) == '4') || (!$img_str)) {
169                         $img_str = file_get_contents('images/blank.png');
170                         $mime = 'image/png';
171                         $cachefile = ''; // Clear the cachefile so that the dummy isn't stored
172                         $valid = false;
173                         $img = new Photo($img_str, 'image/png');
174                         if ($img->is_valid()) {
175                                 $img->scaleImage(10);
176                                 $img_str = $img->imageString();
177                         }
178                 } elseif ($mime != 'image/jpeg' && !$direct_cache && $cachefile == '') {
179                         $image = @imagecreatefromstring($img_str);
180
181                         if ($image === FALSE) {
182                                 die();
183                         }
184
185                         $fields = array('uid' => 0, 'contact-id' => 0, 'guid' => get_guid(), 'resource-id' => $urlhash, 'created' => datetime_convert(), 'edited' => datetime_convert(),
186                                 'filename' => basename($_REQUEST['url']), 'type' => '', 'album' => '', 'height' => imagesy($image), 'width' => imagesx($image),
187                                 'datasize' => 0, 'data' => $img_str, 'scale' => 100, 'profile' => 0,
188                                 'allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '', 'desc' => $mime);
189                         dba::insert('photo', $fields);
190                 } else {
191                         $img = new Photo($img_str, $mime);
192                         if ($img->is_valid() && !$direct_cache && ($cachefile == '')) {
193                                 $img->store(0, 0, $urlhash, $_REQUEST['url'], '', 100);
194                         }
195                 }
196         }
197
198         $img_str_orig = $img_str;
199
200         // reduce quality - if it isn't a GIF
201         if ($mime != 'image/gif') {
202                 $img = new Photo($img_str, $mime);
203                 if ($img->is_valid()) {
204                         $img->scaleImage($size);
205                         $img_str = $img->imageString();
206                 }
207         }
208
209         // If there is a real existing directory then put the cache file there
210         // advantage: real file access is really fast
211         // Otherwise write in cachefile
212         if ($valid && $direct_cache) {
213                 file_put_contents($basepath . '/proxy/' . proxy_url($_REQUEST['url'], true), $img_str_orig);
214                 if ($sizetype != '') {
215                         file_put_contents($basepath . '/proxy/' . proxy_url($_REQUEST['url'], true) . $sizetype, $img_str);
216                 }
217         } elseif ($cachefile != '') {
218                 file_put_contents($cachefile, $img_str_orig);
219         }
220
221         header('Content-type: ' . $mime);
222
223         // Only output the cache headers when the file is valid
224         if ($valid) {
225                 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
226                 header('Etag: "' . md5($img_str) . '"');
227                 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
228                 header('Cache-Control: max-age=31536000');
229         }
230
231         echo $img_str;
232
233         killme();
234 }
235
236 /**
237  * @brief Transform a remote URL into a local one
238  *
239  * This function only performs the URL replacement on http URL and if the
240  * provided URL isn't local, "the isn't deactivated" (sic) and if the config
241  * system.proxy_disabled is set to false.
242  *
243  * @param string $url       The URL to proxyfy
244  * @param bool   $writemode Returns a local path the remote URL should be saved to
245  * @param string $size      One of the PROXY_SIZE_* constants
246  *
247  * @return string The proxyfied URL or relative path
248  */
249 function proxy_url($url, $writemode = false, $size = '') {
250         $a = get_app();
251
252         if (substr($url, 0, strlen('http')) !== 'http') {
253                 return $url;
254         }
255
256         // Only continue if it isn't a local image and the isn't deactivated
257         if (proxy_is_local_image($url)) {
258                 $url = str_replace(normalise_link(System::baseUrl()) . '/', System::baseUrl() . '/', $url);
259                 return $url;
260         }
261
262         if (Config::get('system', 'proxy_disabled')) {
263                 return $url;
264         }
265
266         // Image URL may have encoded ampersands for display which aren't desirable for proxy
267         $url = html_entity_decode($url, ENT_NOQUOTES, 'utf-8');
268
269         // Creating a sub directory to reduce the amount of files in the cache directory
270         $basepath = $a->get_basepath() . '/proxy';
271
272         $shortpath = hash('md5', $url);
273         $longpath = substr($shortpath, 0, 2);
274
275         if (is_dir($basepath) && $writemode && !is_dir($basepath . '/' . $longpath)) {
276                 mkdir($basepath . '/' . $longpath);
277                 chmod($basepath . '/' . $longpath, 0777);
278         }
279
280         $longpath .= '/' . strtr(base64_encode($url), '+/', '-_');
281
282         // Extract the URL extension
283         $extension = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION);
284
285         $extensions = array('jpg', 'jpeg', 'gif', 'png');
286         if (in_array($extension, $extensions)) {
287                 $shortpath .= '.' . $extension;
288                 $longpath .= '.' . $extension;
289         }
290
291         $proxypath = System::baseUrl() . '/proxy/' . $longpath;
292
293         if ($size != '') {
294                 $size = ':' . $size;
295         }
296
297         // Too long files aren't supported by Apache
298         // Writemode in combination with long files shouldn't be possible
299         if ((strlen($proxypath) > 250) && $writemode) {
300                 return $shortpath;
301         } elseif (strlen($proxypath) > 250) {
302                 return System::baseUrl() . '/proxy/' . $shortpath . '?url=' . urlencode($url);
303         } elseif ($writemode) {
304                 return $longpath;
305         } else {
306                 return $proxypath . $size;
307         }
308 }
309
310 /**
311  * @param $url string
312  * @return boolean
313  */
314 function proxy_is_local_image($url) {
315         if ($url[0] == '/') {
316                 return true;
317         }
318
319         if (strtolower(substr($url, 0, 5)) == 'data:') {
320                 return true;
321         }
322
323         // links normalised - bug #431
324         $baseurl = normalise_link(System::baseUrl());
325         $url = normalise_link($url);
326         return (substr($url, 0, strlen($baseurl)) == $baseurl);
327 }
328
329 /**
330  * @brief Return the array of query string parameters from a URL
331  *
332  * @param string $url
333  * @return array Associative array of query string parameters
334  */
335 function proxy_parse_query($url) {
336         $query = parse_url($url, PHP_URL_QUERY);
337         $query = html_entity_decode($query);
338         $query_list = explode('&', $query);
339         $arr = array();
340
341         foreach ($query_list as $key_value) {
342                 $key_value_list = explode('=', $key_value);
343                 $arr[$key_value_list[0]] = $key_value_list[1];
344         }
345
346         unset($url, $query_list, $url);
347         return $arr;
348 }
349
350 function proxy_img_cb($matches) {
351         // if the picture seems to be from another picture cache then take the original source
352         $queryvar = proxy_parse_query($matches[2]);
353         if (($queryvar['url'] != '') && (substr($queryvar['url'], 0, 4) == 'http')) {
354                 $matches[2] = urldecode($queryvar['url']);
355         }
356
357         // following line changed per bug #431
358         if (proxy_is_local_image($matches[2])) {
359                 return $matches[1] . $matches[2] . $matches[3];
360         }
361
362         return $matches[1] . proxy_url(htmlspecialchars_decode($matches[2])) . $matches[3];
363 }
364
365 function proxy_parse_html($html) {
366         $html = str_replace(normalise_link(System::baseUrl()) . '/', System::baseUrl() . '/', $html);
367
368         return preg_replace_callback('/(<img [^>]*src *= *["\'])([^"\']+)(["\'][^>]*>)/siU', 'proxy_img_cb', $html);
369 }