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