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