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