]> git.mxchange.org Git - friendica.git/blob - src/Module/Proxy.php
29e0f4f52f4903c151419133d661a8a4335f9507
[friendica.git] / src / Module / Proxy.php
1 <?php
2 /**
3  * @file src/Module/Proxy.php
4  * @brief Based upon "Privacy Image Cache" by Tobias Hößl <https://github.com/CatoTH/>
5  */
6 namespace Friendica\Module;
7
8 use Friendica\App;
9 use Friendica\BaseModule;
10 use Friendica\Core\Config;
11 use Friendica\Core\L10n;
12 use Friendica\Core\System;
13 use Friendica\Database\DBA;
14 use Friendica\Model\Photo;
15 use Friendica\Object\Image;
16 use Friendica\Util\DateTimeFormat;
17 use Friendica\Util\Network;
18 use Friendica\Util\Proxy as ProxyUtils;
19
20 /**
21  * @brief Module Proxy
22  */
23 class Proxy extends BaseModule
24 {
25
26         /**
27          * @brief Initializer method for this class.
28          *
29          * Sets application instance and checks if /proxy/ path is writable.
30          *
31          * @param \Friendica\App $app Application instance
32          */
33         public static function init()
34         {
35                 // Set application instance here
36                 $a = self::getApp();
37
38                 /*
39                  * Pictures are stored in one of the following ways:
40                  *
41                  * 1. If a folder "proxy" exists and is writeable, then use this for caching
42                  * 2. If a cache path is defined, use this
43                  * 3. If everything else failed, cache into the database
44                  *
45                  * Question: Do we really need these three methods?
46                  */
47                 if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
48                         header('HTTP/1.1 304 Not Modified');
49                         header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
50                         header('Etag: ' . $_SERVER['HTTP_IF_NONE_MATCH']);
51                         header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
52                         header('Cache-Control: max-age=31536000');
53
54                         if (function_exists('header_remove')) {
55                                 header_remove('Last-Modified');
56                                 header_remove('Expires');
57                                 header_remove('Cache-Control');
58                         }
59
60                         /// @TODO Stop here?
61                         exit();
62                 }
63
64                 if (function_exists('header_remove')) {
65                         header_remove('Pragma');
66                         header_remove('pragma');
67                 }
68
69                 $thumb = false;
70                 $size = 1024;
71                 $sizetype = '';
72                 $basepath = $a->getBasePath();
73
74                 // If the cache path isn't there, try to create it
75                 if (!is_dir($basepath . '/proxy') && is_writable($basepath)) {
76                         mkdir($basepath . '/proxy');
77                 }
78
79                 // Checking if caching into a folder in the webroot is activated and working
80                 $direct_cache = (is_dir($basepath . '/proxy') && is_writable($basepath . '/proxy'));
81
82                 // Look for filename in the arguments
83                 if ((isset($a->argv[1]) || isset($a->argv[2]) || isset($a->argv[3])) && !isset($_REQUEST['url'])) {
84                         if (isset($a->argv[3])) {
85                                 $url = $a->argv[3];
86                         } elseif (isset($a->argv[2])) {
87                                 $url = $a->argv[2];
88                         } else {
89                                 $url = $a->argv[1];
90                         }
91
92                         if (isset($a->argv[3]) && ($a->argv[3] == 'thumb')) {
93                                 $size = 200;
94                         }
95
96                         // thumb, small, medium and large.
97                         if (substr($url, -6) == ':micro') {
98                                 $size = 48;
99                                 $sizetype = ':micro';
100                                 $url = substr($url, 0, -6);
101                         } elseif (substr($url, -6) == ':thumb') {
102                                 $size = 80;
103                                 $sizetype = ':thumb';
104                                 $url = substr($url, 0, -6);
105                         } elseif (substr($url, -6) == ':small') {
106                                 $size = 300;
107                                 $url = substr($url, 0, -6);
108                                 $sizetype = ':small';
109                         } elseif (substr($url, -7) == ':medium') {
110                                 $size = 600;
111                                 $url = substr($url, 0, -7);
112                                 $sizetype = ':medium';
113                         } elseif (substr($url, -6) == ':large') {
114                                 $size = 1024;
115                                 $url = substr($url, 0, -6);
116                                 $sizetype = ':large';
117                         }
118
119                         $pos = strrpos($url, '=.');
120                         if ($pos) {
121                                 $url = substr($url, 0, $pos + 1);
122                         }
123
124                         $url = str_replace(['.jpg', '.jpeg', '.gif', '.png'], ['','','',''], $url);
125
126                         $url = base64_decode(strtr($url, '-_', '+/'), true);
127
128                         if ($url) {
129                                 $_REQUEST['url'] = $url;
130                         }
131                 } else {
132                         $direct_cache = false;
133                 }
134
135                 if (empty($_REQUEST['url'])) {
136                         System::httpExit(400, ["title" => L10n::t('Bad Request.')]);
137                 }
138
139                 if (!$direct_cache) {
140                         $urlhash = 'pic:' . sha1($_REQUEST['url']);
141
142                         $cachefile = get_cachefile(hash('md5', $_REQUEST['url']));
143                         if ($cachefile != '' && file_exists($cachefile)) {
144                                 $img_str = file_get_contents($cachefile);
145                                 $mime = mime_content_type($cachefile);
146
147                                 header('Content-type: ' . $mime);
148                                 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
149                                 header('Etag: "' . md5($img_str) . '"');
150                                 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
151                                 header('Cache-Control: max-age=31536000');
152
153                                 // reduce quality - if it isn't a GIF
154                                 if ($mime != 'image/gif') {
155                                         $image = new Image($img_str, $mime);
156
157                                         if ($image->isValid()) {
158                                                 $img_str = $image->asString();
159                                         }
160                                 }
161
162                                 echo $img_str;
163                                 exit();
164                         }
165                 } else {
166                         $cachefile = '';
167                 }
168
169                 $valid = true;
170                 $photo = null;
171
172                 if (!$direct_cache && ($cachefile == '')) {
173                         $photo = DBA::selectFirst('photo', ['data', 'desc'], ['resource-id' => $urlhash]);
174
175                         if (DBA::isResult($photo)) {
176                                 $img_str = $photo['data'];
177                                 $mime = $photo['desc'];
178
179                                 if ($mime == '') {
180                                         $mime = 'image/jpeg';
181                                 }
182                         }
183                 }
184
185                 if (!DBA::isResult($photo)) {
186                         // It shouldn't happen but it does - spaces in URL
187                         $_REQUEST['url'] = str_replace(' ', '+', $_REQUEST['url']);
188                         $redirects = 0;
189                         $fetchResult = Network::fetchUrlFull($_REQUEST['url'], true, $redirects, 10);
190                         $img_str = $fetchResult->getBody();
191
192                         $tempfile = tempnam(get_temppath(), 'cache');
193                         file_put_contents($tempfile, $img_str);
194                         $mime = mime_content_type($tempfile);
195                         unlink($tempfile);
196
197                         // If there is an error then return a blank image
198                         if ((substr($fetchResult->getReturnCode(), 0, 1) == '4') || (!$img_str)) {
199                                 $img_str = file_get_contents('images/blank.png');
200                                 $mime = 'image/png';
201                                 $cachefile = ''; // Clear the cachefile so that the dummy isn't stored
202                                 $valid = false;
203                                 $image = new Image($img_str, 'image/png');
204
205                                 if ($image->isValid()) {
206                                         $image->scaleDown(10);
207                                         $img_str = $image->asString();
208                                 }
209                         } elseif ($mime != 'image/jpeg' && !$direct_cache && $cachefile == '') {
210                                 $image = @imagecreatefromstring($img_str);
211
212                                 if ($image === FALSE) {
213                                         die();
214                                 }
215
216                                 $fields = ['uid' => 0, 'contact-id' => 0, 'guid' => System::createGUID(), 'resource-id' => $urlhash, 'created' => DateTimeFormat::utcNow(), 'edited' => DateTimeFormat::utcNow(),
217                                         'filename' => basename($_REQUEST['url']), 'type' => '', 'album' => '', 'height' => imagesy($image), 'width' => imagesx($image),
218                                         'datasize' => 0, 'data' => $img_str, 'scale' => 100, 'profile' => 0,
219                                         'allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '', 'desc' => $mime];
220                                 DBA::insert('photo', $fields);
221                         } else {
222                                 $image = new Image($img_str, $mime);
223
224                                 if ($image->isValid() && !$direct_cache && ($cachefile == '')) {
225                                         Photo::store($image, 0, 0, $urlhash, $_REQUEST['url'], '', 100);
226                                 }
227                         }
228                 }
229
230                 $img_str_orig = $img_str;
231
232                 // reduce quality - if it isn't a GIF
233                 if ($mime != 'image/gif') {
234                         $image = new Image($img_str, $mime);
235
236                         if ($image->isValid()) {
237                                 $image->scaleDown($size);
238                                 $img_str = $image->asString();
239                         }
240                 }
241
242                 /*
243                  * If there is a real existing directory then put the cache file there
244                  * advantage: real file access is really fast
245                  * Otherwise write in cachefile
246                  */
247                 if ($valid && $direct_cache) {
248                         file_put_contents($basepath . '/proxy/' . ProxyUtils::proxifyUrl($_REQUEST['url'], true), $img_str_orig);
249
250                         if ($sizetype != '') {
251                                 file_put_contents($basepath . '/proxy/' . ProxyUtils::proxifyUrl($_REQUEST['url'], true) . $sizetype, $img_str);
252                         }
253                 } elseif ($cachefile != '') {
254                         file_put_contents($cachefile, $img_str_orig);
255                 }
256
257                 header('Content-type: ' . $mime);
258
259                 // Only output the cache headers when the file is valid
260                 if ($valid) {
261                         header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
262                         header('Etag: "' . md5($img_str) . '"');
263                         header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
264                         header('Cache-Control: max-age=31536000');
265                 }
266
267                 echo $img_str;
268
269                 exit();
270         }
271
272 }