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