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