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->get_basepath();
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 $img_str = Network::fetchUrl($_REQUEST['url'], true, $redirects, 10);
193 $tempfile = tempnam(get_temppath(), 'cache');
194 file_put_contents($tempfile, $img_str);
195 $mime = mime_content_type($tempfile);
198 // If there is an error then return a blank image
199 if ((substr($a->get_curl_code(), 0, 1) == '4') || (!$img_str)) {
200 $img_str = file_get_contents('images/blank.png');
202 $cachefile = ''; // Clear the cachefile so that the dummy isn't stored
204 $image = new Image($img_str, 'image/png');
206 if ($image->isValid()) {
207 $image->scaleDown(10);
208 $img_str = $image->asString();
210 } elseif ($mime != 'image/jpeg' && !$direct_cache && $cachefile == '') {
211 $image = @imagecreatefromstring($img_str);
213 if ($image === FALSE) {
217 $fields = ['uid' => 0, 'contact-id' => 0, 'guid' => System::createGUID(), 'resource-id' => $urlhash, 'created' => DateTimeFormat::utcNow(), 'edited' => DateTimeFormat::utcNow(),
218 'filename' => basename($_REQUEST['url']), 'type' => '', 'album' => '', 'height' => imagesy($image), 'width' => imagesx($image),
219 'datasize' => 0, 'data' => $img_str, 'scale' => 100, 'profile' => 0,
220 'allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '', 'desc' => $mime];
221 DBA::insert('photo', $fields);
223 $image = new Image($img_str, $mime);
225 if ($image->isValid() && !$direct_cache && ($cachefile == '')) {
226 Photo::store($image, 0, 0, $urlhash, $_REQUEST['url'], '', 100);
231 $img_str_orig = $img_str;
233 // reduce quality - if it isn't a GIF
234 if ($mime != 'image/gif') {
235 $image = new Image($img_str, $mime);
237 if ($image->isValid()) {
238 $image->scaleDown($size);
239 $img_str = $image->asString();
244 * If there is a real existing directory then put the cache file there
245 * advantage: real file access is really fast
246 * Otherwise write in cachefile
248 if ($valid && $direct_cache) {
249 file_put_contents($basepath . '/proxy/' . ProxyUtils::proxifyUrl($_REQUEST['url'], true), $img_str_orig);
251 if ($sizetype != '') {
252 file_put_contents($basepath . '/proxy/' . ProxyUtils::proxifyUrl($_REQUEST['url'], true) . $sizetype, $img_str);
254 } elseif ($cachefile != '') {
255 file_put_contents($cachefile, $img_str_orig);
258 header('Content-type: ' . $mime);
260 // Only output the cache headers when the file is valid
262 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
263 header('Etag: "' . md5($img_str) . '"');
264 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
265 header('Cache-Control: max-age=31536000');