Browse Source

Add SHA1 hashed thumbnail URLs when the base64 filename is too long

master
Skylar Ittner 3 years ago
parent
commit
603a294443
  1. 19
      cache/handle_404.php
  2. BIN
      database.mwb
  3. 26
      lib/Thumbnail.lib.php

19
cache/handle_404.php

@ -8,6 +8,8 @@
require_once __DIR__ . "/../required.php";
header("Content-Type: text/plain;utf-8");
$urlparts = explode("/", $_GET['file']);
$fileparts = explode(".", end($urlparts));
@ -21,12 +23,23 @@ if (!preg_match("/^[A-Za-z0-9\-!_]+$/", $fileparts[0])) {
die("Encoded image URL invalid, refusing to parse.");
}
$url = Base64::decode($fileparts[0]);
if (strpos($fileparts[0], "SHA1_") === 0) {
$hash = str_replace("SHA1_", "", $fileparts[0]);
if ($database->has("imagecache", ["hash" => $hash])) {
$url = $database->get("imagecache", 'url', ["hash" => $hash]);
echo $url;
} else {
http_response_code(404);
die("Not found.");
}
} else {
$url = Base64::decode($fileparts[0]);
}
if (!filter_var($url, FILTER_VALIDATE_URL)) {
http_response_code(403);
die("Invalid URL.");
}
//header("Content-Type: image/jpeg");
echo Thumbnail::addThumbnailToCache($url, (int) $fileparts[1]);
header("Content-Type: image/jpeg");
echo Thumbnail::addThumbnailToCache($url, (int) $fileparts[1]);

BIN
database.mwb

26
lib/Thumbnail.lib.php

@ -41,22 +41,44 @@ class Thumbnail {
}
/**
* Make a thumbnail, save it to the disk cache, and return a url relative to
* the app root.
* Return a thumbnail URL relative to the app root for the given image URL.
* @param string $url
* @param int $width
* @param int,bool $height
* @return string
*/
static function getThumbnailCacheURL(string $url, int $width = 150, $height = true): string {
global $database;
$encodedfilename = Base64::encode($url);
if (strlen("$encodedfilename.$width.jpg") > 250) {
// We're too long for common filesystems
$encodedfilename = "SHA1_" . sha1($url);
if (!$database->has("imagecache", ["url" => $url])) {
$database->insert("imagecache", ["url" => $url, "hash" => $encodedfilename, "created" => date("Y-m-d H:i:s")]);
}
}
$path = "cache/thumb/$encodedfilename.$width.jpg";
return $path;
}
/**
* Generate a thumbnail and save it to the cache
* @param string $url
* @param int $width
* @param type $height
* @return type
*/
static function addThumbnailToCache(string $url, int $width = 150, $height = true) {
global $database;
$encodedfilename = Base64::encode($url);
if (strlen("$encodedfilename.$width.jpg") > 250) {
// We're too long for common filesystems
$encodedfilename = "SHA1_" . sha1($url);
if (!$database->has("imagecache", ["url" => $url])) {
$database->insert("imagecache", ["url" => $url, "hash" => $encodedfilename, "created" => date("Y-m-d H:i:s")]);
}
}
$path = "cache/thumb/$encodedfilename.$width.jpg";
$image = self::getThumbnailFromUrl($url, $width, $height);
file_put_contents(__DIR__ . "/../$path", $image);

Loading…
Cancel
Save