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