4 * @brief Based upon "Privacy Image Cache" by Tobias Hößl <https://github.com/CatoTH/>
8 use Friendica\Core\Config;
9 use Friendica\Core\System;
10 use Friendica\Database\DBM;
11 use Friendica\Model\Photo;
12 use Friendica\Object\Image;
13 use Friendica\Util\DateTimeFormat;
14 use Friendica\Util\Network;
16 define('PROXY_DEFAULT_TIME', 86400); // 1 Day
18 define('PROXY_SIZE_MICRO', 'micro');
19 define('PROXY_SIZE_THUMB', 'thumb');
20 define('PROXY_SIZE_SMALL', 'small');
21 define('PROXY_SIZE_MEDIUM', 'medium');
22 define('PROXY_SIZE_LARGE', 'large');
24 require_once 'include/security.php';
26 function proxy_init(App $a) {
27 // Pictures are stored in one of the following ways:
28 // 1. If a folder "proxy" exists and is writeable, then use this for caching
29 // 2. If a cache path is defined, use this
30 // 3. If everything else failed, cache into the database
32 // Question: Do we really need these three methods?
34 if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
35 header('HTTP/1.1 304 Not Modified');
36 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
37 header('Etag: ' . $_SERVER['HTTP_IF_NONE_MATCH']);
38 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
39 header('Cache-Control: max-age=31536000');
41 if (function_exists('header_remove')) {
42 header_remove('Last-Modified');
43 header_remove('Expires');
44 header_remove('Cache-Control');
49 if (function_exists('header_remove')) {
50 header_remove('Pragma');
51 header_remove('pragma');
57 $basepath = $a->get_basepath();
59 // If the cache path isn't there, try to create it
60 if (!is_dir($basepath . '/proxy') && is_writable($basepath)) {
61 mkdir($basepath . '/proxy');
64 // Checking if caching into a folder in the webroot is activated and working
65 $direct_cache = (is_dir($basepath . '/proxy') && is_writable($basepath . '/proxy'));
67 // Look for filename in the arguments
68 if ((isset($a->argv[1]) || isset($a->argv[2]) || isset($a->argv[3])) && !isset($_REQUEST['url'])) {
69 if (isset($a->argv[3])) {
71 } elseif (isset($a->argv[2])) {
77 if (isset($a->argv[3]) && ($a->argv[3] == 'thumb')) {
81 // thumb, small, medium and large.
82 if (substr($url, -6) == ':micro') {
85 $url = substr($url, 0, -6);
86 } elseif (substr($url, -6) == ':thumb') {
89 $url = substr($url, 0, -6);
90 } elseif (substr($url, -6) == ':small') {
92 $url = substr($url, 0, -6);
94 } elseif (substr($url, -7) == ':medium') {
96 $url = substr($url, 0, -7);
97 $sizetype = ':medium';
98 } elseif (substr($url, -6) == ':large') {
100 $url = substr($url, 0, -6);
101 $sizetype = ':large';
104 $pos = strrpos($url, '=.');
106 $url = substr($url, 0, $pos + 1);
109 $url = str_replace(['.jpg', '.jpeg', '.gif', '.png'], ['','','',''], $url);
111 $url = base64_decode(strtr($url, '-_', '+/'), true);
114 $_REQUEST['url'] = $url;
117 $direct_cache = false;
120 if (!$direct_cache) {
121 $urlhash = 'pic:' . sha1($_REQUEST['url']);
123 $cachefile = get_cachefile(hash('md5', $_REQUEST['url']));
124 if ($cachefile != '' && file_exists($cachefile)) {
125 $img_str = file_get_contents($cachefile);
126 $mime = image_type_to_mime_type(exif_imagetype($cachefile));
128 header('Content-type: ' . $mime);
129 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
130 header('Etag: "' . md5($img_str) . '"');
131 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
132 header('Cache-Control: max-age=31536000');
134 // reduce quality - if it isn't a GIF
135 if ($mime != 'image/gif') {
136 $Image = new Image($img_str, $mime);
137 if ($Image->isValid()) {
138 $img_str = $Image->asString();
151 if (!$direct_cache && ($cachefile == '')) {
152 $photo = dba::selectFirst('photo', ['data', 'desc'], ['resource-id' => $urlhash]);
153 if (DBM::is_result($photo)) {
154 $img_str = $photo['data'];
155 $mime = $photo['desc'];
157 $mime = 'image/jpeg';
162 if (!DBM::is_result($photo)) {
163 // It shouldn't happen but it does - spaces in URL
164 $_REQUEST['url'] = str_replace(' ', '+', $_REQUEST['url']);
166 $img_str = Network::fetchUrl($_REQUEST['url'], true, $redirects, 10);
168 $tempfile = tempnam(get_temppath(), 'cache');
169 file_put_contents($tempfile, $img_str);
170 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
173 // If there is an error then return a blank image
174 if ((substr($a->get_curl_code(), 0, 1) == '4') || (!$img_str)) {
175 $img_str = file_get_contents('images/blank.png');
177 $cachefile = ''; // Clear the cachefile so that the dummy isn't stored
179 $Image = new Image($img_str, 'image/png');
180 if ($Image->isValid()) {
181 $Image->scaleDown(10);
182 $img_str = $Image->asString();
184 } elseif ($mime != 'image/jpeg' && !$direct_cache && $cachefile == '') {
185 $image = @imagecreatefromstring($img_str);
187 if ($image === FALSE) {
191 $fields = ['uid' => 0, 'contact-id' => 0, 'guid' => get_guid(), 'resource-id' => $urlhash, 'created' => DateTimeFormat::utcNow(), 'edited' => DateTimeFormat::utcNow(),
192 'filename' => basename($_REQUEST['url']), 'type' => '', 'album' => '', 'height' => imagesy($image), 'width' => imagesx($image),
193 'datasize' => 0, 'data' => $img_str, 'scale' => 100, 'profile' => 0,
194 'allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '', 'desc' => $mime];
195 dba::insert('photo', $fields);
197 $Image = new Image($img_str, $mime);
198 if ($Image->isValid() && !$direct_cache && ($cachefile == '')) {
199 Photo::store($Image, 0, 0, $urlhash, $_REQUEST['url'], '', 100);
204 $img_str_orig = $img_str;
206 // reduce quality - if it isn't a GIF
207 if ($mime != 'image/gif') {
208 $Image = new Image($img_str, $mime);
209 if ($Image->isValid()) {
210 $Image->scaleDown($size);
211 $img_str = $Image->asString();
215 // If there is a real existing directory then put the cache file there
216 // advantage: real file access is really fast
217 // Otherwise write in cachefile
218 if ($valid && $direct_cache) {
219 file_put_contents($basepath . '/proxy/' . proxy_url($_REQUEST['url'], true), $img_str_orig);
220 if ($sizetype != '') {
221 file_put_contents($basepath . '/proxy/' . proxy_url($_REQUEST['url'], true) . $sizetype, $img_str);
223 } elseif ($cachefile != '') {
224 file_put_contents($cachefile, $img_str_orig);
227 header('Content-type: ' . $mime);
229 // Only output the cache headers when the file is valid
231 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
232 header('Etag: "' . md5($img_str) . '"');
233 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
234 header('Cache-Control: max-age=31536000');
243 * @brief Transform a remote URL into a local one
245 * This function only performs the URL replacement on http URL and if the
246 * provided URL isn't local, "the isn't deactivated" (sic) and if the config
247 * system.proxy_disabled is set to false.
249 * @param string $url The URL to proxyfy
250 * @param bool $writemode Returns a local path the remote URL should be saved to
251 * @param string $size One of the PROXY_SIZE_* constants
253 * @return string The proxyfied URL or relative path
255 function proxy_url($url, $writemode = false, $size = '') {
258 if (substr($url, 0, strlen('http')) !== 'http') {
262 // Only continue if it isn't a local image and the isn't deactivated
263 if (proxy_is_local_image($url)) {
264 $url = str_replace(normalise_link(System::baseUrl()) . '/', System::baseUrl() . '/', $url);
268 if (Config::get('system', 'proxy_disabled')) {
272 // Image URL may have encoded ampersands for display which aren't desirable for proxy
273 $url = html_entity_decode($url, ENT_NOQUOTES, 'utf-8');
275 // Creating a sub directory to reduce the amount of files in the cache directory
276 $basepath = $a->get_basepath() . '/proxy';
278 $shortpath = hash('md5', $url);
279 $longpath = substr($shortpath, 0, 2);
281 if (is_dir($basepath) && $writemode && !is_dir($basepath . '/' . $longpath)) {
282 mkdir($basepath . '/' . $longpath);
283 chmod($basepath . '/' . $longpath, 0777);
286 $longpath .= '/' . strtr(base64_encode($url), '+/', '-_');
288 // Extract the URL extension
289 $extension = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION);
291 $extensions = ['jpg', 'jpeg', 'gif', 'png'];
292 if (in_array($extension, $extensions)) {
293 $shortpath .= '.' . $extension;
294 $longpath .= '.' . $extension;
297 $proxypath = System::baseUrl() . '/proxy/' . $longpath;
303 // Too long files aren't supported by Apache
304 // Writemode in combination with long files shouldn't be possible
305 if ((strlen($proxypath) > 250) && $writemode) {
307 } elseif (strlen($proxypath) > 250) {
308 return System::baseUrl() . '/proxy/' . $shortpath . '?url=' . urlencode($url);
309 } elseif ($writemode) {
312 return $proxypath . $size;
320 function proxy_is_local_image($url) {
321 if ($url[0] == '/') {
325 if (strtolower(substr($url, 0, 5)) == 'data:') {
329 // links normalised - bug #431
330 $baseurl = normalise_link(System::baseUrl());
331 $url = normalise_link($url);
332 return (substr($url, 0, strlen($baseurl)) == $baseurl);
336 * @brief Return the array of query string parameters from a URL
339 * @return array Associative array of query string parameters
341 function proxy_parse_query($url) {
342 $query = parse_url($url, PHP_URL_QUERY);
343 $query = html_entity_decode($query);
344 $query_list = explode('&', $query);
347 foreach ($query_list as $key_value) {
348 $key_value_list = explode('=', $key_value);
349 $arr[$key_value_list[0]] = $key_value_list[1];
352 unset($url, $query_list, $url);
356 function proxy_img_cb($matches) {
357 // if the picture seems to be from another picture cache then take the original source
358 $queryvar = proxy_parse_query($matches[2]);
359 if (($queryvar['url'] != '') && (substr($queryvar['url'], 0, 4) == 'http')) {
360 $matches[2] = urldecode($queryvar['url']);
363 // following line changed per bug #431
364 if (proxy_is_local_image($matches[2])) {
365 return $matches[1] . $matches[2] . $matches[3];
368 return $matches[1] . proxy_url(htmlspecialchars_decode($matches[2])) . $matches[3];
371 function proxy_parse_html($html) {
372 $html = str_replace(normalise_link(System::baseUrl()) . '/', System::baseUrl() . '/', $html);
374 return preg_replace_callback('/(<img [^>]*src *= *["\'])([^"\']+)(["\'][^>]*>)/siU', 'proxy_img_cb', $html);