<?php
function imagecache_render_cron()
{
    // Load the view
    $view = \Drupal\views\Views::getView('people_directory');

    if ($view) {
        // Select /people view
        $view->setDisplay('page_1');

        // Clear the view's cache
        $view->storage->invalidateCaches();

        // Execute the view and build the render
        $view->execute();
        $view_build = $view->buildRenderable('page_1', []);

        // Render the output
        \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 - (30 * 60)) {
            \Drupal::logger('imagecache_external')->notice('@filepath older than 24 hours, refreshing', [
                '@filepath' => $filepath,
            ]);
            $needs_refresh = TRUE;
        }
    }
}