]> git.mxchange.org Git - friendica.git/blob - mod/proxy.php
App::get_baseurl is now replaced with System::baseUrl
[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 = qu("SELECT * FROM `photo` WHERE `resource-id` = '%s' LIMIT 1", $urlhash);
146                 if (dbm::is_result($r)) {
147                         $img_str = $r[0]['data'];
148                         $mime = $r[0]['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                         q("INSERT INTO `photo`
185                         ( `uid`, `contact-id`, `guid`, `resource-id`, `created`, `edited`, `filename`, `album`, `height`, `width`, `desc`, `data`, `scale`, `profile`, `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid` )
186                         VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, %d, '%s', '%s', '%s', '%s' )",
187                                 0, 0, get_guid(), dbesc($urlhash),
188                                 dbesc(datetime_convert()),
189                                 dbesc(datetime_convert()),
190                                 dbesc(basename(dbesc($_REQUEST['url']))),
191                                 dbesc(''),
192                                 intval(imagesy($image)),
193                                 intval(imagesx($image)),
194                                 $mime,
195                                 dbesc($img_str),
196                                 100,
197                                 intval(0),
198                                 dbesc(''), dbesc(''), dbesc(''), dbesc('')
199                         );
200
201                 } else {
202                         $img = new Photo($img_str, $mime);
203                         if ($img->is_valid() && !$direct_cache && ($cachefile == '')) {
204                                 $img->store(0, 0, $urlhash, $_REQUEST['url'], '', 100);
205                         }
206                 }
207         }
208
209         $img_str_orig = $img_str;
210
211         // reduce quality - if it isn't a GIF
212         if ($mime != 'image/gif') {
213                 $img = new Photo($img_str, $mime);
214                 if ($img->is_valid()) {
215                         $img->scaleImage($size);
216                         $img_str = $img->imageString();
217                 }
218         }
219
220         // If there is a real existing directory then put the cache file there
221         // advantage: real file access is really fast
222         // Otherwise write in cachefile
223         if ($valid && $direct_cache) {
224                 file_put_contents($basepath . '/proxy/' . proxy_url($_REQUEST['url'], true), $img_str_orig);
225                 if ($sizetype != '') {
226                         file_put_contents($basepath . '/proxy/' . proxy_url($_REQUEST['url'], true) . $sizetype, $img_str);
227                 }
228         } elseif ($cachefile != '') {
229                 file_put_contents($cachefile, $img_str_orig);
230         }
231
232         header('Content-type: ' . $mime);
233
234         // Only output the cache headers when the file is valid
235         if ($valid) {
236                 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
237                 header('Etag: "' . md5($img_str) . '"');
238                 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
239                 header('Cache-Control: max-age=31536000');
240         }
241
242         echo $img_str;
243
244         killme();
245 }
246
247 /**
248  * @brief Transform a remote URL into a local one
249  *
250  * This function only performs the URL replacement on http URL and if the
251  * provided URL isn't local, "the isn't deactivated" (sic) and if the config
252  * system.proxy_disabled is set to false.
253  *
254  * @param string $url       The URL to proxyfy
255  * @param bool   $writemode Returns a local path the remote URL should be saved to
256  * @param string $size      One of the PROXY_SIZE_* constants
257  *
258  * @return string The proxyfied URL or relative path
259  */
260 function proxy_url($url, $writemode = false, $size = '') {
261         $a = get_app();
262
263         if (substr($url, 0, strlen('http')) !== 'http') {
264                 return $url;
265         }
266
267         // Only continue if it isn't a local image and the isn't deactivated
268         if (proxy_is_local_image($url)) {
269                 $url = str_replace(normalise_link(System::baseUrl()) . '/', System::baseUrl() . '/', $url);
270                 return $url;
271         }
272
273         if (get_config('system', 'proxy_disabled')) {
274                 return $url;
275         }
276
277         // Image URL may have encoded ampersands for display which aren't desirable for proxy
278         $url = html_entity_decode($url, ENT_NOQUOTES, 'utf-8');
279
280         // Creating a sub directory to reduce the amount of files in the cache directory
281         $basepath = $a->get_basepath() . '/proxy';
282
283         $shortpath = hash('md5', $url);
284         $longpath = substr($shortpath, 0, 2);
285
286         if (is_dir($basepath) && $writemode && !is_dir($basepath . '/' . $longpath)) {
287                 mkdir($basepath . '/' . $longpath);
288                 chmod($basepath . '/' . $longpath, 0777);
289         }
290
291         $longpath .= '/' . strtr(base64_encode($url), '+/', '-_');
292
293         // Extract the URL extension
294         $extension = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION);
295
296         $extensions = array('jpg', 'jpeg', 'gif', 'png');
297         if (in_array($extension, $extensions)) {
298                 $shortpath .= '.' . $extension;
299                 $longpath .= '.' . $extension;
300         }
301
302         $proxypath = System::baseUrl() . '/proxy/' . $longpath;
303
304         if ($size != '') {
305                 $size = ':' . $size;
306         }
307
308         // Too long files aren't supported by Apache
309         // Writemode in combination with long files shouldn't be possible
310         if ((strlen($proxypath) > 250) && $writemode) {
311                 return $shortpath;
312         } elseif (strlen($proxypath) > 250) {
313                 return System::baseUrl() . '/proxy/' . $shortpath . '?url=' . urlencode($url);
314         } elseif ($writemode) {
315                 return $longpath;
316         } else {
317                 return $proxypath . $size;
318         }
319 }
320
321 /**
322  * @param $url string
323  * @return boolean
324  */
325 function proxy_is_local_image($url) {
326         if ($url[0] == '/') {
327                 return true;
328         }
329
330         if (strtolower(substr($url, 0, 5)) == 'data:') {
331                 return true;
332         }
333
334         // links normalised - bug #431
335         $baseurl = normalise_link(System::baseUrl());
336         $url = normalise_link($url);
337         return (substr($url, 0, strlen($baseurl)) == $baseurl);
338 }
339
340 /**
341  * @brief Return the array of query string parameters from a URL
342  *
343  * @param string $url
344  * @return array Associative array of query string parameters
345  */
346 function proxy_parse_query($url) {
347         $query = parse_url($url, PHP_URL_QUERY);
348         $query = html_entity_decode($query);
349         $query_list = explode('&', $query);
350         $arr = array();
351
352         foreach ($query_list as $key_value) {
353                 $key_value_list = explode('=', $key_value);
354                 $arr[$key_value_list[0]] = $key_value_list[1];
355         }
356
357         unset($url, $query_list, $url);
358         return $arr;
359 }
360
361 function proxy_img_cb($matches) {
362         // if the picture seems to be from another picture cache then take the original source
363         $queryvar = proxy_parse_query($matches[2]);
364         if (($queryvar['url'] != '') && (substr($queryvar['url'], 0, 4) == 'http')) {
365                 $matches[2] = urldecode($queryvar['url']);
366         }
367
368         // following line changed per bug #431
369         if (proxy_is_local_image($matches[2])) {
370                 return $matches[1] . $matches[2] . $matches[3];
371         }
372
373         return $matches[1] . proxy_url(htmlspecialchars_decode($matches[2])) . $matches[3];
374 }
375
376 function proxy_parse_html($html) {
377         $html = str_replace(normalise_link(System::baseUrl()) . '/', System::baseUrl() . '/', $html);
378
379         return preg_replace_callback('/(<img [^>]*src *= *["\'])([^"\']+)(["\'][^>]*>)/siU', 'proxy_img_cb', $html);
380 }