+ $request = self::getRequestInfo();
+
+ if (empty($request['url'])) {
+ System::httpExit(400, ['title' => L10n::t('Bad Request.')]);
+ }
+
+ // 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']);
+ $redirects = 0;
+ $fetchResult = Network::fetchUrlFull($request['url'], true, $redirects, 10);
+ $img_str = $fetchResult->getBody();
+
+ $tempfile = tempnam(get_temppath(), 'cache');
+ file_put_contents($tempfile, $img_str);
+ $mime = mime_content_type($tempfile);
+ unlink($tempfile);
+
+ // If there is an error then return a blank image
+ if ((substr($fetchResult->getReturnCode(), 0, 1) == '4') || (!$img_str)) {
+ self::responseError();
+ // stop.
+ }
+
+ $image = new Image($img_str, $mime);
+ if (!$image->isValid()) {
+ 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']);