diff --git a/php/utils/room-icons.php b/php/utils/room-icons.php index 66479fa..eef02b4 100644 --- a/php/utils/room-icons.php +++ b/php/utils/room-icons.php @@ -37,7 +37,6 @@ * @return string Relative path or null if icon is absent. */ function room_icon(\CommunityRoom $room, string $size): ?string { - global $ICON_ALLOWLIST; list($width, $height) = explode("x", $size); $width = intval($width); $height = intval($height); @@ -48,13 +47,10 @@ $room_id = $room->get_room_identifier(); $icon_cached = room_icon_path($room_id); $icon_resized = room_icon_path_resized($room_id, $size); - if (file_exists($icon_resized)) { - if (empty(file_get_contents($icon_resized))) { - return ""; - } - return room_icon_path_relative($room_id, $size); - } - if (!file_exists($icon_cached)) { + $icon_expired = file_exists($icon_cached) && filemtime($icon_cached) < strtotime("-1 hour"); + + // Re-fetch icons periodically. + if (!file_exists($icon_cached) || $icon_expired) { $icon_url = $room->get_icon_url(); if (empty($icon_url)) { return null; @@ -64,19 +60,26 @@ if (empty($icon)) { log_info("$room_id returned empty icon."); } - // Cache result, no matter if empty - file_put_contents($icon_cached, $icon); + // Never overwrite with an empty file. + if (!(file_exists($icon_cached) && empty($icon))) { + file_put_contents($icon_cached, $icon); + } } - $icon_cached_contents = file_get_contents($icon_cached); - if (empty($icon_cached_contents)) { - file_put_contents($icon_resized, ""); - return ""; + if (!file_exists($icon_resized) || $icon_expired) { + $icon_cached_contents = file_get_contents($icon_cached); + if (empty($icon_cached_contents)) { + file_put_contents($icon_resized, ""); + return ""; + } + // Resize image + $gd_image = imagecreatefromstring($icon_cached_contents); + $gd_resized = imagescale($gd_image, $width, $height); + if (!imagewebp($gd_resized, $icon_resized)) { + log_info("Converting image for $room_id to $size failed"); + } } - // Resize image - $gd_image = imagecreatefromstring($icon_cached_contents); - $gd_resized = imagescale($gd_image, $width, $height); - if (!imagewebp($gd_resized, $icon_resized)) { - log_info("Converting image for $room_id to $size failed"); + if (filesize($icon_resized) == 0) { + return ""; } return room_icon_path_relative($room_id, $size); }