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;
20 require_once 'include/security.php';
25 class Proxy extends BaseModule
29 * @brief Initializer method for this class.
31 * Sets application instance and checks if /proxy/ path is writable.
33 * @param \Friendica\App $app Application instance
35 public static function init()
37 // Set application instance here
41 * Pictures are stored in one of the following ways:
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
47 * Question: Do we really need these three methods?
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');
56 if (function_exists('header_remove')) {
57 header_remove('Last-Modified');
58 header_remove('Expires');
59 header_remove('Cache-Control');
66 if (function_exists('header_remove')) {
67 header_remove('Pragma');
68 header_remove('pragma');
74 $basepath = $a->getBasePath();
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');
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'));
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])) {
88 } elseif (isset($a->argv[2])) {
94 if (isset($a->argv[3]) && ($a->argv[3] == 'thumb')) {
98 // thumb, small, medium and large.
99 if (substr($url, -6) == ':micro') {
101 $sizetype = ':micro';
102 $url = substr($url, 0, -6);
103 } elseif (substr($url, -6) == ':thumb') {
105 $sizetype = ':thumb';
106 $url = substr($url, 0, -6);
107 } elseif (substr($url, -6) == ':small') {
109 $url = substr($url, 0, -6);
110 $sizetype = ':small';
111 } elseif (substr($url, -7) == ':medium') {
113 $url = substr($url, 0, -7);
114 $sizetype = ':medium';
115 } elseif (substr($url, -6) == ':large') {
117 $url = substr($url, 0, -6);
118 $sizetype = ':large';
121 $pos = strrpos($url, '=.');
123 $url = substr($url, 0, $pos + 1);
126 $url = str_replace(['.jpg', '.jpeg', '.gif', '.png'], ['','','',''], $url);
128 $url = base64_decode(strtr($url, '-_', '+/'), true);
131 $_REQUEST['url'] = $url;
134 $direct_cache = false;
137 if (empty($_REQUEST['url'])) {
138 System::httpExit(400, ["title" => L10n::t('Bad Request.')]);
141 if (!$direct_cache) {
142 $urlhash = 'pic:' . sha1($_REQUEST['url']);
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);
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');
155 // reduce quality - if it isn't a GIF
156 if ($mime != 'image/gif') {
157 $image = new Image($img_str, $mime);
159 if ($image->isValid()) {
160 $img_str = $image->asString();
174 if (!$direct_cache && ($cachefile == '')) {
175 $photo = DBA::selectFirst('photo', ['data', 'desc'], ['resource-id' => $urlhash]);
177 if (DBA::isResult($photo)) {
178 $img_str = $photo['data'];
179 $mime = $photo['desc'];
182 $mime = 'image/jpeg';
187 if (!DBA::isResult($photo)) {
188 // It shouldn't happen but it does - spaces in URL
189 $_REQUEST['url'] = str_replace(' ', '+', $_REQUEST['url']);
191 $fetchResult = Network::fetchUrlFull($_REQUEST['url'], true, $redirects, 10);
192 $img_str = $fetchResult->getBody();
194 $tempfile = tempnam(get_temppath(), 'cache');
195 file_put_contents($tempfile, $img_str);
196 $mime = mime_content_type($tempfile);
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');
203 $cachefile = ''; // Clear the cachefile so that the dummy isn't stored
205 $image = new Image($img_str, 'image/png');
207 if ($image->isValid()) {
208 $image->scaleDown(10);
209 $img_str = $image->asString();
211 } elseif ($mime != 'image/jpeg' && !$direct_cache && $cachefile == '') {
212 $image = @imagecreatefromstring($img_str);
214 if ($image === FALSE) {
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);
224 $image = new Image($img_str, $mime);
226 if ($image->isValid() && !$direct_cache && ($cachefile == '')) {
227 Photo::store($image, 0, 0, $urlhash, $_REQUEST['url'], '', 100);
232 $img_str_orig = $img_str;
234 // reduce quality - if it isn't a GIF
235 if ($mime != 'image/gif') {
236 $image = new Image($img_str, $mime);
238 if ($image->isValid()) {
239 $image->scaleDown($size);
240 $img_str = $image->asString();
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
249 if ($valid && $direct_cache) {
250 file_put_contents($basepath . '/proxy/' . ProxyUtils::proxifyUrl($_REQUEST['url'], true), $img_str_orig);
252 if ($sizetype != '') {
253 file_put_contents($basepath . '/proxy/' . ProxyUtils::proxifyUrl($_REQUEST['url'], true) . $sizetype, $img_str);
255 } elseif ($cachefile != '') {
256 file_put_contents($cachefile, $img_str_orig);
259 header('Content-type: ' . $mime);
261 // Only output the cache headers when the file is 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');