3 * @file src/Module/Proxy.php
4 * @brief Based upon "Privacy Image Cache" by Tobias Hößl <https://github.com/CatoTH/>
6 namespace Friendica\Module;
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;
23 class Proxy extends BaseModule
27 * @brief Initializer method for this class.
29 * Sets application instance and checks if /proxy/ path is writable.
31 * @param \Friendica\App $app Application instance
33 public static function init()
35 // Set application instance here
39 * Pictures are stored in one of the following ways:
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
45 * Question: Do we really need these three methods?
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');
54 if (function_exists('header_remove')) {
55 header_remove('Last-Modified');
56 header_remove('Expires');
57 header_remove('Cache-Control');
64 if (function_exists('header_remove')) {
65 header_remove('Pragma');
66 header_remove('pragma');
72 $basepath = $a->getBasePath();
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');
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'));
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])) {
86 } elseif (isset($a->argv[2])) {
92 if (isset($a->argv[3]) && ($a->argv[3] == 'thumb')) {
96 // thumb, small, medium and large.
97 if (substr($url, -6) == ':micro') {
100 $url = substr($url, 0, -6);
101 } elseif (substr($url, -6) == ':thumb') {
103 $sizetype = ':thumb';
104 $url = substr($url, 0, -6);
105 } elseif (substr($url, -6) == ':small') {
107 $url = substr($url, 0, -6);
108 $sizetype = ':small';
109 } elseif (substr($url, -7) == ':medium') {
111 $url = substr($url, 0, -7);
112 $sizetype = ':medium';
113 } elseif (substr($url, -6) == ':large') {
115 $url = substr($url, 0, -6);
116 $sizetype = ':large';
119 $pos = strrpos($url, '=.');
121 $url = substr($url, 0, $pos + 1);
124 $url = str_replace(['.jpg', '.jpeg', '.gif', '.png'], ['','','',''], $url);
126 $url = base64_decode(strtr($url, '-_', '+/'), true);
129 $_REQUEST['url'] = $url;
132 $direct_cache = false;
135 if (empty($_REQUEST['url'])) {
136 System::httpExit(400, ["title" => L10n::t('Bad Request.')]);
139 if (!$direct_cache) {
140 $urlhash = 'pic:' . sha1($_REQUEST['url']);
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);
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');
153 // reduce quality - if it isn't a GIF
154 if ($mime != 'image/gif') {
155 $image = new Image($img_str, $mime);
157 if ($image->isValid()) {
158 $img_str = $image->asString();
172 if (!$direct_cache && ($cachefile == '')) {
173 $photo = DBA::selectFirst('photo', ['data', 'desc'], ['resource-id' => $urlhash]);
175 if (DBA::isResult($photo)) {
176 $img_str = $photo['data'];
177 $mime = $photo['desc'];
180 $mime = 'image/jpeg';
185 if (!DBA::isResult($photo)) {
186 // It shouldn't happen but it does - spaces in URL
187 $_REQUEST['url'] = str_replace(' ', '+', $_REQUEST['url']);
189 $fetchResult = Network::fetchUrlFull($_REQUEST['url'], true, $redirects, 10);
190 $img_str = $fetchResult->getBody();
192 $tempfile = tempnam(get_temppath(), 'cache');
193 file_put_contents($tempfile, $img_str);
194 $mime = mime_content_type($tempfile);
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');
201 $cachefile = ''; // Clear the cachefile so that the dummy isn't stored
203 $image = new Image($img_str, 'image/png');
205 if ($image->isValid()) {
206 $image->scaleDown(10);
207 $img_str = $image->asString();
209 } elseif ($mime != 'image/jpeg' && !$direct_cache && $cachefile == '') {
210 $image = @imagecreatefromstring($img_str);
212 if ($image === FALSE) {
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);
222 $image = new Image($img_str, $mime);
224 if ($image->isValid() && !$direct_cache && ($cachefile == '')) {
225 Photo::store($image, 0, 0, $urlhash, $_REQUEST['url'], '', 100);
230 $img_str_orig = $img_str;
232 // reduce quality - if it isn't a GIF
233 if ($mime != 'image/gif') {
234 $image = new Image($img_str, $mime);
236 if ($image->isValid()) {
237 $image->scaleDown($size);
238 $img_str = $image->asString();
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
247 if ($valid && $direct_cache) {
248 file_put_contents($basepath . '/proxy/' . ProxyUtils::proxifyUrl($_REQUEST['url'], true), $img_str_orig);
250 if ($sizetype != '') {
251 file_put_contents($basepath . '/proxy/' . ProxyUtils::proxifyUrl($_REQUEST['url'], true) . $sizetype, $img_str);
253 } elseif ($cachefile != '') {
254 file_put_contents($cachefile, $img_str_orig);
257 header('Content-type: ' . $mime);
259 // Only output the cache headers when the file is 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');