2 // Based upon "Privacy Image Cache" by Tobias Hößl <https://github.com/CatoTH/>
5 use Friendica\Core\Config;
6 use Friendica\Core\System;
8 define('PROXY_DEFAULT_TIME', 86400); // 1 Day
10 define('PROXY_SIZE_MICRO', 'micro');
11 define('PROXY_SIZE_THUMB', 'thumb');
12 define('PROXY_SIZE_SMALL', 'small');
13 define('PROXY_SIZE_MEDIUM', 'medium');
14 define('PROXY_SIZE_LARGE', 'large');
16 require_once 'include/security.php';
17 require_once 'include/Photo.php';
19 function proxy_init(App $a) {
20 // Pictures are stored in one of the following ways:
21 // 1. If a folder "proxy" exists and is writeable, then use this for caching
22 // 2. If a cache path is defined, use this
23 // 3. If everything else failed, cache into the database
25 // Question: Do we really need these three methods?
27 if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
28 header('HTTP/1.1 304 Not Modified');
29 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
30 header('Etag: ' . $_SERVER['HTTP_IF_NONE_MATCH']);
31 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
32 header('Cache-Control: max-age=31536000');
34 if (function_exists('header_remove')) {
35 header_remove('Last-Modified');
36 header_remove('Expires');
37 header_remove('Cache-Control');
42 if (function_exists('header_remove')) {
43 header_remove('Pragma');
44 header_remove('pragma');
50 $basepath = $a->get_basepath();
52 // If the cache path isn't there, try to create it
53 if (!is_dir($basepath . '/proxy') && is_writable($basepath)) {
54 mkdir($basepath . '/proxy');
57 // Checking if caching into a folder in the webroot is activated and working
58 $direct_cache = (is_dir($basepath . '/proxy') && is_writable($basepath . '/proxy'));
60 // Look for filename in the arguments
61 if ((isset($a->argv[1]) || isset($a->argv[2]) || isset($a->argv[3])) && !isset($_REQUEST['url'])) {
62 if (isset($a->argv[3])) {
64 } elseif (isset($a->argv[2])) {
70 if (isset($a->argv[3]) && ($a->argv[3] == 'thumb')) {
74 // thumb, small, medium and large.
75 if (substr($url, -6) == ':micro') {
78 $url = substr($url, 0, -6);
79 } elseif (substr($url, -6) == ':thumb') {
82 $url = substr($url, 0, -6);
83 } elseif (substr($url, -6) == ':small') {
85 $url = substr($url, 0, -6);
87 } elseif (substr($url, -7) == ':medium') {
89 $url = substr($url, 0, -7);
90 $sizetype = ':medium';
91 } elseif (substr($url, -6) == ':large') {
93 $url = substr($url, 0, -6);
97 $pos = strrpos($url, '=.');
99 $url = substr($url, 0, $pos + 1);
102 $url = str_replace(array('.jpg', '.jpeg', '.gif', '.png'), array('','','',''), $url);
104 $url = base64_decode(strtr($url, '-_', '+/'), true);
107 $_REQUEST['url'] = $url;
110 $direct_cache = false;
113 if (!$direct_cache) {
114 $urlhash = 'pic:' . sha1($_REQUEST['url']);
116 $cachefile = get_cachefile(hash('md5', $_REQUEST['url']));
117 if ($cachefile != '' && file_exists($cachefile)) {
118 $img_str = file_get_contents($cachefile);
119 $mime = image_type_to_mime_type(exif_imagetype($cachefile));
121 header('Content-type: ' . $mime);
122 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
123 header('Etag: "' . md5($img_str) . '"');
124 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
125 header('Cache-Control: max-age=31536000');
127 // reduce quality - if it isn't a GIF
128 if ($mime != 'image/gif') {
129 $img = new Photo($img_str, $mime);
130 if ($img->is_valid()) {
131 $img_str = $img->imageString();
145 if (!$direct_cache && ($cachefile == '')) {
146 $r = dba::select('photo', array('data', 'desc'), array('resource-id' => $urlhash), array('limit' => 1));
147 if (dbm::is_result($r)) {
148 $img_str = $r['data'];
151 $mime = 'image/jpeg';
156 if (!dbm::is_result($r)) {
157 // It shouldn't happen but it does - spaces in URL
158 $_REQUEST['url'] = str_replace(' ', '+', $_REQUEST['url']);
160 $img_str = fetch_url($_REQUEST['url'], true, $redirects, 10);
162 $tempfile = tempnam(get_temppath(), 'cache');
163 file_put_contents($tempfile, $img_str);
164 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
167 // If there is an error then return a blank image
168 if ((substr($a->get_curl_code(), 0, 1) == '4') || (!$img_str)) {
169 $img_str = file_get_contents('images/blank.png');
171 $cachefile = ''; // Clear the cachefile so that the dummy isn't stored
173 $img = new Photo($img_str, 'image/png');
174 if ($img->is_valid()) {
175 $img->scaleImage(10);
176 $img_str = $img->imageString();
178 } elseif ($mime != 'image/jpeg' && !$direct_cache && $cachefile == '') {
179 $image = @imagecreatefromstring($img_str);
181 if ($image === FALSE) {
185 $fields = array('uid' => 0, 'contact-id' => 0, 'guid' => get_guid(), 'resource-id' => $urlhash, 'created' => datetime_convert(), 'edited' => datetime_convert(),
186 'filename' => basename($_REQUEST['url']), 'type' => '', 'album' => '', 'height' => imagesy($image), 'width' => imagesx($image),
187 'datasize' => 0, 'data' => $img_str, 'scale' => 100, 'profile' => 0,
188 'allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '', 'desc' => $mime);
189 dba::insert('photo', $fields);
191 $img = new Photo($img_str, $mime);
192 if ($img->is_valid() && !$direct_cache && ($cachefile == '')) {
193 $img->store(0, 0, $urlhash, $_REQUEST['url'], '', 100);
198 $img_str_orig = $img_str;
200 // reduce quality - if it isn't a GIF
201 if ($mime != 'image/gif') {
202 $img = new Photo($img_str, $mime);
203 if ($img->is_valid()) {
204 $img->scaleImage($size);
205 $img_str = $img->imageString();
209 // If there is a real existing directory then put the cache file there
210 // advantage: real file access is really fast
211 // Otherwise write in cachefile
212 if ($valid && $direct_cache) {
213 file_put_contents($basepath . '/proxy/' . proxy_url($_REQUEST['url'], true), $img_str_orig);
214 if ($sizetype != '') {
215 file_put_contents($basepath . '/proxy/' . proxy_url($_REQUEST['url'], true) . $sizetype, $img_str);
217 } elseif ($cachefile != '') {
218 file_put_contents($cachefile, $img_str_orig);
221 header('Content-type: ' . $mime);
223 // Only output the cache headers when the file is valid
225 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
226 header('Etag: "' . md5($img_str) . '"');
227 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
228 header('Cache-Control: max-age=31536000');
237 * @brief Transform a remote URL into a local one
239 * This function only performs the URL replacement on http URL and if the
240 * provided URL isn't local, "the isn't deactivated" (sic) and if the config
241 * system.proxy_disabled is set to false.
243 * @param string $url The URL to proxyfy
244 * @param bool $writemode Returns a local path the remote URL should be saved to
245 * @param string $size One of the PROXY_SIZE_* constants
247 * @return string The proxyfied URL or relative path
249 function proxy_url($url, $writemode = false, $size = '') {
252 if (substr($url, 0, strlen('http')) !== 'http') {
256 // Only continue if it isn't a local image and the isn't deactivated
257 if (proxy_is_local_image($url)) {
258 $url = str_replace(normalise_link(System::baseUrl()) . '/', System::baseUrl() . '/', $url);
262 if (Config::get('system', 'proxy_disabled')) {
266 // Image URL may have encoded ampersands for display which aren't desirable for proxy
267 $url = html_entity_decode($url, ENT_NOQUOTES, 'utf-8');
269 // Creating a sub directory to reduce the amount of files in the cache directory
270 $basepath = $a->get_basepath() . '/proxy';
272 $shortpath = hash('md5', $url);
273 $longpath = substr($shortpath, 0, 2);
275 if (is_dir($basepath) && $writemode && !is_dir($basepath . '/' . $longpath)) {
276 mkdir($basepath . '/' . $longpath);
277 chmod($basepath . '/' . $longpath, 0777);
280 $longpath .= '/' . strtr(base64_encode($url), '+/', '-_');
282 // Extract the URL extension
283 $extension = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION);
285 $extensions = array('jpg', 'jpeg', 'gif', 'png');
286 if (in_array($extension, $extensions)) {
287 $shortpath .= '.' . $extension;
288 $longpath .= '.' . $extension;
291 $proxypath = System::baseUrl() . '/proxy/' . $longpath;
297 // Too long files aren't supported by Apache
298 // Writemode in combination with long files shouldn't be possible
299 if ((strlen($proxypath) > 250) && $writemode) {
301 } elseif (strlen($proxypath) > 250) {
302 return System::baseUrl() . '/proxy/' . $shortpath . '?url=' . urlencode($url);
303 } elseif ($writemode) {
306 return $proxypath . $size;
314 function proxy_is_local_image($url) {
315 if ($url[0] == '/') {
319 if (strtolower(substr($url, 0, 5)) == 'data:') {
323 // links normalised - bug #431
324 $baseurl = normalise_link(System::baseUrl());
325 $url = normalise_link($url);
326 return (substr($url, 0, strlen($baseurl)) == $baseurl);
330 * @brief Return the array of query string parameters from a URL
333 * @return array Associative array of query string parameters
335 function proxy_parse_query($url) {
336 $query = parse_url($url, PHP_URL_QUERY);
337 $query = html_entity_decode($query);
338 $query_list = explode('&', $query);
341 foreach ($query_list as $key_value) {
342 $key_value_list = explode('=', $key_value);
343 $arr[$key_value_list[0]] = $key_value_list[1];
346 unset($url, $query_list, $url);
350 function proxy_img_cb($matches) {
351 // if the picture seems to be from another picture cache then take the original source
352 $queryvar = proxy_parse_query($matches[2]);
353 if (($queryvar['url'] != '') && (substr($queryvar['url'], 0, 4) == 'http')) {
354 $matches[2] = urldecode($queryvar['url']);
357 // following line changed per bug #431
358 if (proxy_is_local_image($matches[2])) {
359 return $matches[1] . $matches[2] . $matches[3];
362 return $matches[1] . proxy_url(htmlspecialchars_decode($matches[2])) . $matches[3];
365 function proxy_parse_html($html) {
366 $html = str_replace(normalise_link(System::baseUrl()) . '/', System::baseUrl() . '/', $html);
368 return preg_replace_callback('/(<img [^>]*src *= *["\'])([^"\']+)(["\'][^>]*>)/siU', 'proxy_img_cb', $html);