+ // Webserver already tried direct cache...
+
+ // Try to use filecache;
+ $cachefile = self::responseFromCache($request);
+
+ // Try to use photo from db
+ self::responseFromDB($request);
+
+ //
+ // If script is here, the requested url has never cached before.
+ // Let's fetch it, scale it if required, then save it in cache.
+ //
+
+ // It shouldn't happen but it does - spaces in URL
+ $request['url'] = str_replace(' ', '+', $request['url']);
+ $fetchResult = HTTPSignature::fetchRaw($request['url'], local_user(), true, ['timeout' => 10]);
+ $img_str = $fetchResult->getBody();
+
+ // If there is an error then return a blank image
+ if ((substr($fetchResult->getReturnCode(), 0, 1) == '4') || empty($img_str)) {
+ Logger::info('Error fetching image', ['image' => $request['url'], 'return' => $fetchResult->getReturnCode(), 'empty' => empty($img_str)]);
+ self::responseError();
+ // stop.
+ }
+
+ $tempfile = tempnam(get_temppath(), 'cache');
+ file_put_contents($tempfile, $img_str);
+ $mime = mime_content_type($tempfile);
+ unlink($tempfile);
+
+ $image = new Image($img_str, $mime);
+ if (!$image->isValid()) {
+ Logger::info('The image is invalid', ['image' => $request['url'], 'mime' => $mime]);
+ self::responseError();
+ // stop.
+ }
+
+ $basepath = $a->getBasePath();
+
+ // Store original image
+ if ($direct_cache) {
+ // direct cache , store under ./proxy/
+ file_put_contents($basepath . '/proxy/' . ProxyUtils::proxifyUrl($request['url'], true), $image->asString());
+ } elseif($cachefile !== '') {
+ // cache file
+ file_put_contents($cachefile, $image->asString());
+ } else {
+ // database
+ Photo::store($image, 0, 0, $request['urlhash'], $request['url'], '', 100);
+ }
+
+
+ // reduce quality - if it isn't a GIF
+ if ($image->getType() != 'image/gif') {
+ $image->scaleDown($request['size']);
+ }
+
+
+ // Store scaled image
+ if ($direct_cache && $request['sizetype'] != '') {
+ file_put_contents($basepath . '/proxy/' . ProxyUtils::proxifyUrl($request['url'], true) . $request['sizetype'], $image->asString());
+ }
+
+ self::responseImageHttpCache($image);
+ // stop.
+ }
+
+
+ /**
+ * Build info about requested image to be proxied
+ *
+ * @return array
+ * [
+ * 'url' => requested url,
+ * 'urlhash' => sha1 has of the url prefixed with 'pic:',
+ * 'size' => requested image size (int)
+ * 'sizetype' => requested image size (string): ':micro', ':thumb', ':small', ':medium', ':large'
+ * ]
+ * @throws \Exception
+ */
+ private static function getRequestInfo()
+ {
+ $a = DI::app();
+ $size = 1024;
+ $sizetype = '';