From ff593ceda2aa07cdfc1b6377007d335a39446f59 Mon Sep 17 00:00:00 2001 From: Michael Lee <lee.5151@osu.edu> Date: Wed, 17 Jul 2024 14:20:45 -0400 Subject: [PATCH] add hook to better handle file refreshes for cached OPIC images --- .../imagecache_render.module | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/web/modules/custom/imagecache_render/imagecache_render.module b/web/modules/custom/imagecache_render/imagecache_render.module index d327b01a43..0e3479d3b7 100644 --- a/web/modules/custom/imagecache_render/imagecache_render.module +++ b/web/modules/custom/imagecache_render/imagecache_render.module @@ -19,3 +19,58 @@ function imagecache_render_cron() \Drupal::service('renderer')->renderPlain($view_build); } } + +/** + * Add custom image refresh logic. + * + * Use this hook to add extra validation(s) whether to refresh images. + * + * @param $needs_refresh + * Whether to refresh or not + * @param $filepath + * The path is being checked. + */ +function imagecache_render_imagecache_external_needs_refresh_alter(&$needs_refresh, $filepath) +{ + // Check if OPIC is live + $domain = "opic.osu.edu"; + $port = 80; + $timeout = 5; + $connection = @fsockopen($domain, $port, $errno, $errstr, $timeout); + if (!$connection) { + \Drupal::logger('imagecache_external')->notice('Connection to @domain failed: @error. @filepath will not be refreshed.', [ + '@domain' => $domain, + '@error' => $errstr, + '@filepath' => $filepath, + ]); + fclose($connection); + return; + } + + // Check if the file exists. + // If images are flushed manually, this will force a refresh to prevent broken cached images. + if (!file_exists($filepath)) { + \Drupal::logger('imagecache_external')->notice('Image file @filepath does not exist. Refreshing.', [ + '@filepath' => $filepath, + ]); + $needs_refresh = TRUE; + return; + } + + // Only allow refresh on non-broken images between 3:00 AM and 5:00 AM Eastern + // Helps avoid refreshing a bunch of images when a user access the page (we run a cronjob at 4:00 AM to do this) + date_default_timezone_set('America/New_York'); + $current_hour = (int) date('G'); + if ($current_hour >= 3 && $current_hour < 5) { + if (filemtime($filepath) < \Drupal::time()->getRequestTime() - 60 * 60 * 24) { + \Drupal::logger('imagecache_external')->notice('@filepath older than 24 hours, refreshing', [ + '@filepath' => $filepath, + ]); + $needs_refresh = TRUE; + } else { + \Drupal::logger('imagecache_external')->notice('@filepath is less than 24 hours. Will not refresh.', [ + '@filepath' => $filepath, + ]); + } + } +} -- GitLab