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