2 // Based upon "Privacy Image Cache" by Tobias Hößl <https://github.com/CatoTH/>
5 use Friendica\Core\System;
7 define('PROXY_DEFAULT_TIME', 86400); // 1 Day
9 define('PROXY_SIZE_MICRO', 'micro');
10 define('PROXY_SIZE_THUMB', 'thumb');
11 define('PROXY_SIZE_SMALL', 'small');
12 define('PROXY_SIZE_MEDIUM', 'medium');
13 define('PROXY_SIZE_LARGE', 'large');
15 require_once 'include/security.php';
16 require_once 'include/Photo.php';
18 function proxy_init(App $a) {
19 // Pictures are stored in one of the following ways:
20 // 1. If a folder "proxy" exists and is writeable, then use this for caching
21 // 2. If a cache path is defined, use this
22 // 3. If everything else failed, cache into the database
24 // Question: Do we really need these three methods?
26 if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
27 header('HTTP/1.1 304 Not Modified');
28 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
29 header('Etag: ' . $_SERVER['HTTP_IF_NONE_MATCH']);
30 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
31 header('Cache-Control: max-age=31536000');
33 if (function_exists('header_remove')) {
34 header_remove('Last-Modified');
35 header_remove('Expires');
36 header_remove('Cache-Control');
41 if (function_exists('header_remove')) {
42 header_remove('Pragma');
43 header_remove('pragma');
49 $basepath = $a->get_basepath();
51 // If the cache path isn't there, try to create it
52 if (!is_dir($basepath . '/proxy') && is_writable($basepath)) {
53 mkdir($basepath . '/proxy');
56 // Checking if caching into a folder in the webroot is activated and working
57 $direct_cache = (is_dir($basepath . '/proxy') && is_writable($basepath . '/proxy'));
59 // Look for filename in the arguments
60 if ((isset($a->argv[1]) || isset($a->argv[2]) || isset($a->argv[3])) && !isset($_REQUEST['url'])) {
61 if (isset($a->argv[3])) {
63 } elseif (isset($a->argv[2])) {
69 if (isset($a->argv[3]) && ($a->argv[3] == 'thumb')) {
73 // thumb, small, medium and large.
74 if (substr($url, -6) == ':micro') {
77 $url = substr($url, 0, -6);
78 } elseif (substr($url, -6) == ':thumb') {
81 $url = substr($url, 0, -6);
82 } elseif (substr($url, -6) == ':small') {
84 $url = substr($url, 0, -6);
86 } elseif (substr($url, -7) == ':medium') {
88 $url = substr($url, 0, -7);
89 $sizetype = ':medium';
90 } elseif (substr($url, -6) == ':large') {
92 $url = substr($url, 0, -6);
96 $pos = strrpos($url, '=.');
98 $url = substr($url, 0, $pos + 1);
101 $url = str_replace(array('.jpg', '.jpeg', '.gif', '.png'), array('','','',''), $url);
103 $url = base64_decode(strtr($url, '-_', '+/'), true);
106 $_REQUEST['url'] = $url;
109 $direct_cache = false;
112 if (!$direct_cache) {
113 $urlhash = 'pic:' . sha1($_REQUEST['url']);
115 $cachefile = get_cachefile(hash('md5', $_REQUEST['url']));
116 if ($cachefile != '' && file_exists($cachefile)) {
117 $img_str = file_get_contents($cachefile);
118 $mime = image_type_to_mime_type(exif_imagetype($cachefile));
120 header('Content-type: ' . $mime);
121 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
122 header('Etag: "' . md5($img_str) . '"');
123 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
124 header('Cache-Control: max-age=31536000');
126 // reduce quality - if it isn't a GIF
127 if ($mime != 'image/gif') {
128 $img = new Photo($img_str, $mime);
129 if ($img->is_valid()) {
130 $img_str = $img->imageString();
144 if (!$direct_cache && ($cachefile == '')) {
145 $r = dba::select('photo', array('data', 'desc'), array('resource-id' => $urlhash), array('limit' => 1));
146 if (dbm::is_result($r)) {
147 $img_str = $r['data'];
150 $mime = 'image/jpeg';
155 if (!dbm::is_result($r)) {
156 // It shouldn't happen but it does - spaces in URL
157 $_REQUEST['url'] = str_replace(' ', '+', $_REQUEST['url']);
159 $img_str = fetch_url($_REQUEST['url'], true, $redirects, 10);
161 $tempfile = tempnam(get_temppath(), 'cache');
162 file_put_contents($tempfile, $img_str);
163 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
166 // If there is an error then return a blank image
167 if ((substr($a->get_curl_code(), 0, 1) == '4') || (!$img_str)) {
168 $img_str = file_get_contents('images/blank.png');
170 $cachefile = ''; // Clear the cachefile so that the dummy isn't stored
172 $img = new Photo($img_str, 'image/png');
173 if ($img->is_valid()) {
174 $img->scaleImage(10);
175 $img_str = $img->imageString();
177 } elseif ($mime != 'image/jpeg' && !$direct_cache && $cachefile == '') {
178 $image = @imagecreatefromstring($img_str);
180 if ($image === FALSE) {
184 $fields = array('uid' => 0, 'contact-id' => 0, 'guid' => get_guid(), 'resource-id' => $urlhash, 'created' => datetime_convert(), 'edited' => datetime_convert(),
185 'filename' => basename($_REQUEST['url']), 'type' => '', 'album' => '', 'height' => imagesy($image), 'width' => imagesx($image),
186 'datasize' => 0, 'data' => $img_str, 'scale' => 100, 'profile' => 0,
187 'allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '', 'desc' => $mime);
188 dba::insert('photo', $fields);
190 $img = new Photo($img_str, $mime);
191 if ($img->is_valid() && !$direct_cache && ($cachefile == '')) {
192 $img->store(0, 0, $urlhash, $_REQUEST['url'], '', 100);
197 $img_str_orig = $img_str;
199 // reduce quality - if it isn't a GIF
200 if ($mime != 'image/gif') {
201 $img = new Photo($img_str, $mime);
202 if ($img->is_valid()) {
203 $img->scaleImage($size);
204 $img_str = $img->imageString();
208 // If there is a real existing directory then put the cache file there
209 // advantage: real file access is really fast
210 // Otherwise write in cachefile
211 if ($valid && $direct_cache) {
212 file_put_contents($basepath . '/proxy/' . proxy_url($_REQUEST['url'], true), $img_str_orig);
213 if ($sizetype != '') {
214 file_put_contents($basepath . '/proxy/' . proxy_url($_REQUEST['url'], true) . $sizetype, $img_str);
216 } elseif ($cachefile != '') {
217 file_put_contents($cachefile, $img_str_orig);
220 header('Content-type: ' . $mime);
222 // Only output the cache headers when the file is valid
224 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
225 header('Etag: "' . md5($img_str) . '"');
226 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
227 header('Cache-Control: max-age=31536000');
236 * @brief Transform a remote URL into a local one
238 * This function only performs the URL replacement on http URL and if the
239 * provided URL isn't local, "the isn't deactivated" (sic) and if the config
240 * system.proxy_disabled is set to false.
242 * @param string $url The URL to proxyfy
243 * @param bool $writemode Returns a local path the remote URL should be saved to
244 * @param string $size One of the PROXY_SIZE_* constants
246 * @return string The proxyfied URL or relative path
248 function proxy_url($url, $writemode = false, $size = '') {
251 if (substr($url, 0, strlen('http')) !== 'http') {
255 // Only continue if it isn't a local image and the isn't deactivated
256 if (proxy_is_local_image($url)) {
257 $url = str_replace(normalise_link(System::baseUrl()) . '/', System::baseUrl() . '/', $url);
261 if (get_config('system', 'proxy_disabled')) {
265 // Image URL may have encoded ampersands for display which aren't desirable for proxy
266 $url = html_entity_decode($url, ENT_NOQUOTES, 'utf-8');
268 // Creating a sub directory to reduce the amount of files in the cache directory
269 $basepath = $a->get_basepath() . '/proxy';
271 $shortpath = hash('md5', $url);
272 $longpath = substr($shortpath, 0, 2);
274 if (is_dir($basepath) && $writemode && !is_dir($basepath . '/' . $longpath)) {
275 mkdir($basepath . '/' . $longpath);
276 chmod($basepath . '/' . $longpath, 0777);
279 $longpath .= '/' . strtr(base64_encode($url), '+/', '-_');
281 // Extract the URL extension
282 $extension = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION);
284 $extensions = array('jpg', 'jpeg', 'gif', 'png');
285 if (in_array($extension, $extensions)) {
286 $shortpath .= '.' . $extension;
287 $longpath .= '.' . $extension;
290 $proxypath = System::baseUrl() . '/proxy/' . $longpath;
296 // Too long files aren't supported by Apache
297 // Writemode in combination with long files shouldn't be possible
298 if ((strlen($proxypath) > 250) && $writemode) {
300 } elseif (strlen($proxypath) > 250) {
301 return System::baseUrl() . '/proxy/' . $shortpath . '?url=' . urlencode($url);
302 } elseif ($writemode) {
305 return $proxypath . $size;
313 function proxy_is_local_image($url) {
314 if ($url[0] == '/') {
318 if (strtolower(substr($url, 0, 5)) == 'data:') {
322 // links normalised - bug #431
323 $baseurl = normalise_link(System::baseUrl());
324 $url = normalise_link($url);
325 return (substr($url, 0, strlen($baseurl)) == $baseurl);
329 * @brief Return the array of query string parameters from a URL
332 * @return array Associative array of query string parameters
334 function proxy_parse_query($url) {
335 $query = parse_url($url, PHP_URL_QUERY);
336 $query = html_entity_decode($query);
337 $query_list = explode('&', $query);
340 foreach ($query_list as $key_value) {
341 $key_value_list = explode('=', $key_value);
342 $arr[$key_value_list[0]] = $key_value_list[1];
345 unset($url, $query_list, $url);
349 function proxy_img_cb($matches) {
350 // if the picture seems to be from another picture cache then take the original source
351 $queryvar = proxy_parse_query($matches[2]);
352 if (($queryvar['url'] != '') && (substr($queryvar['url'], 0, 4) == 'http')) {
353 $matches[2] = urldecode($queryvar['url']);
356 // following line changed per bug #431
357 if (proxy_is_local_image($matches[2])) {
358 return $matches[1] . $matches[2] . $matches[3];
361 return $matches[1] . proxy_url(htmlspecialchars_decode($matches[2])) . $matches[3];
364 function proxy_parse_html($html) {
365 $html = str_replace(normalise_link(System::baseUrl()) . '/', System::baseUrl() . '/', $html);
367 return preg_replace_callback('/(<img [^>]*src *= *["\'])([^"\']+)(["\'][^>]*>)/siU', 'proxy_img_cb', $html);