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