]> git.mxchange.org Git - friendica.git/blob - mod/proxy.php
80a84a165fc3cf84a38d7849a45b432bf0fe72cb
[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
14 define('PROXY_DEFAULT_TIME', 86400); // 1 Day
15
16 define('PROXY_SIZE_MICRO', 'micro');
17 define('PROXY_SIZE_THUMB', 'thumb');
18 define('PROXY_SIZE_SMALL', 'small');
19 define('PROXY_SIZE_MEDIUM', 'medium');
20 define('PROXY_SIZE_LARGE', 'large');
21
22 require_once 'include/security.php';
23
24 function proxy_init(App $a) {
25         // Pictures are stored in one of the following ways:
26         // 1. If a folder "proxy" exists and is writeable, then use this for caching
27         // 2. If a cache path is defined, use this
28         // 3. If everything else failed, cache into the database
29         //
30         // Question: Do we really need these three methods?
31
32         if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
33                 header('HTTP/1.1 304 Not Modified');
34                 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
35                 header('Etag: ' . $_SERVER['HTTP_IF_NONE_MATCH']);
36                 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
37                 header('Cache-Control: max-age=31536000');
38
39                 if (function_exists('header_remove')) {
40                         header_remove('Last-Modified');
41                         header_remove('Expires');
42                         header_remove('Cache-Control');
43                 }
44                 exit;
45         }
46
47         if (function_exists('header_remove')) {
48                 header_remove('Pragma');
49                 header_remove('pragma');
50         }
51
52         $thumb = false;
53         $size = 1024;
54         $sizetype = '';
55         $basepath = $a->get_basepath();
56
57         // If the cache path isn't there, try to create it
58         if (!is_dir($basepath . '/proxy') && is_writable($basepath)) {
59                 mkdir($basepath . '/proxy');
60         }
61
62         // Checking if caching into a folder in the webroot is activated and working
63         $direct_cache = (is_dir($basepath . '/proxy') && is_writable($basepath . '/proxy'));
64
65         // Look for filename in the arguments
66         if ((isset($a->argv[1]) || isset($a->argv[2]) || isset($a->argv[3])) && !isset($_REQUEST['url'])) {
67                 if (isset($a->argv[3])) {
68                         $url = $a->argv[3];
69                 } elseif (isset($a->argv[2])) {
70                         $url = $a->argv[2];
71                 } else {
72                         $url = $a->argv[1];
73                 }
74
75                 if (isset($a->argv[3]) && ($a->argv[3] == 'thumb')) {
76                         $size = 200;
77                 }
78
79                 // thumb, small, medium and large.
80                 if (substr($url, -6) == ':micro') {
81                         $size = 48;
82                         $sizetype = ':micro';
83                         $url = substr($url, 0, -6);
84                 } elseif (substr($url, -6) == ':thumb') {
85                         $size = 80;
86                         $sizetype = ':thumb';
87                         $url = substr($url, 0, -6);
88                 } elseif (substr($url, -6) == ':small') {
89                         $size = 175;
90                         $url = substr($url, 0, -6);
91                         $sizetype = ':small';
92                 } elseif (substr($url, -7) == ':medium') {
93                         $size = 600;
94                         $url = substr($url, 0, -7);
95                         $sizetype = ':medium';
96                 } elseif (substr($url, -6) == ':large') {
97                         $size = 1024;
98                         $url = substr($url, 0, -6);
99                         $sizetype = ':large';
100                 }
101
102                 $pos = strrpos($url, '=.');
103                 if ($pos) {
104                         $url = substr($url, 0, $pos + 1);
105                 }
106
107                 $url = str_replace(array('.jpg', '.jpeg', '.gif', '.png'), array('','','',''), $url);
108
109                 $url = base64_decode(strtr($url, '-_', '+/'), true);
110
111                 if ($url) {
112                         $_REQUEST['url'] = $url;
113                 }
114         } else {
115                 $direct_cache = false;
116         }
117
118         if (!$direct_cache) {
119                 $urlhash = 'pic:' . sha1($_REQUEST['url']);
120
121                 $cachefile = get_cachefile(hash('md5', $_REQUEST['url']));
122                 if ($cachefile != '' && file_exists($cachefile)) {
123                         $img_str = file_get_contents($cachefile);
124                         $mime = image_type_to_mime_type(exif_imagetype($cachefile));
125
126                         header('Content-type: ' . $mime);
127                         header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
128                         header('Etag: "' . md5($img_str) . '"');
129                         header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
130                         header('Cache-Control: max-age=31536000');
131
132                         // reduce quality - if it isn't a GIF
133                         if ($mime != 'image/gif') {
134                                 $Image = new Image($img_str, $mime);
135                                 if ($Image->isValid()) {
136                                         $img_str = $Image->asString();
137                                 }
138                         }
139
140                         echo $img_str;
141                         killme();
142                 }
143         } else {
144                 $cachefile = '';
145         }
146
147         $valid = true;
148         $r = array();
149
150         if (!$direct_cache && ($cachefile == '')) {
151                 $r = dba::selectFirst('photo', ['data', 'desc'], ['resource-id' => $urlhash]);
152                 if (DBM::is_result($r)) {
153                         $img_str = $r['data'];
154                         $mime = $r['desc'];
155                         if ($mime == '') {
156                                 $mime = 'image/jpeg';
157                         }
158                 }
159         }
160
161         if (!DBM::is_result($r)) {
162                 // It shouldn't happen but it does - spaces in URL
163                 $_REQUEST['url'] = str_replace(' ', '+', $_REQUEST['url']);
164                 $redirects = 0;
165                 $img_str = fetch_url($_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 = array('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 = array('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 = array();
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 }