<?php
/**
 * UNIVERSAL WORDPRESS CACHE PURGER
 * Standalone PHP
 *
 * PHP 7.4+ / PHP 8.x
 *
 * Membersihkan:
 * - PHP OPcache
 * - APCu
 * - WordPress object cache (jika WP dapat dimuat)
 * - LiteSpeed Cache
 * - WP Rocket
 * - W3 Total Cache
 * - WP Super Cache
 * - WP Fastest Cache
 * - Autoptimize
 * - Hummingbird
 * - SG Optimizer / SiteGround
 * - Breeze
 * - Cache Enabler
 * - Comet Cache
 * - Swift Performance
 * - FlyingPress
 * - Powered Cache
 * - Borlabs Cache
 * - SpeedyCache
 * - Seraphinite Accelerator
 * - NitroPack local cache
 * - Elementor generated CSS
 * - Divi generated/static cache
 * - Beaver Builder cache
 * - Oxygen cache
 * - Bricks generated CSS
 * - Redis object cache via WordPress
 * - Transients WordPress
 * - Generic wp-content/cache
 * - Generic cache directories detected automatically
 *
 * TIDAK membutuhkan secret key.
 *
 * Setelah selesai digunakan, sebaiknya hapus file ini dari server.
 */

@set_time_limit(0);
@ignore_user_abort(true);
@ini_set('memory_limit', '512M');

if (!headers_sent()) {
    header('Content-Type: text/plain; charset=UTF-8');
    header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
    header('Pragma: no-cache');
    header('Expires: Thu, 01 Jan 1970 00:00:00 GMT');
    header('Surrogate-Control: no-store');
}

/* =========================================================
 * CONFIG
 * ========================================================= */

$BASE = realpath(__DIR__);

$stats = [
    'files'   => 0,
    'dirs'    => 0,
    'bytes'   => 0,
    'errors'  => [],
    'purged'  => [],
];


/* =========================================================
 * HELPERS
 * ========================================================= */

function humanSize($bytes)
{
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];

    $bytes = max(0, (float)$bytes);
    $pow = $bytes > 0
        ? floor(log($bytes, 1024))
        : 0;

    $pow = min($pow, count($units) - 1);

    $bytes /= (1 << (10 * $pow));

    return round($bytes, 2) . ' ' . $units[$pow];
}


function normalizePath($path)
{
    return rtrim(
        str_replace('\\', '/', $path),
        '/'
    );
}


function pathInside($path, $root)
{
    $root = normalizePath($root);

    $real = realpath($path);

    if ($real !== false) {
        $path = normalizePath($real);
    } else {
        $parent = realpath(dirname($path));

        if ($parent === false) {
            return false;
        }

        $path = normalizePath($parent)
            . '/'
            . basename($path);
    }

    return (
        $path === $root ||
        strpos($path . '/', $root . '/') === 0
    );
}


function deleteFileHard($file, &$stats)
{
    if (!file_exists($file) && !is_link($file)) {
        return true;
    }

    $size = 0;

    if (is_file($file)) {
        $size = @filesize($file);

        if ($size === false) {
            $size = 0;
        }
    }

    @chmod($file, 0666);

    for ($i = 0; $i < 3; $i++) {

        if (@unlink($file)) {
            $stats['files']++;
            $stats['bytes'] += $size;

            return true;
        }

        clearstatcache(true, $file);
        usleep(30000);
    }

    if (!file_exists($file) && !is_link($file)) {
        return true;
    }

    $stats['errors'][] =
        'Gagal menghapus file: ' . $file;

    return false;
}


function purgeDirectory($directory, &$stats, $deleteRoot = false)
{
    if (!is_dir($directory)) {
        return;
    }

    @chmod($directory, 0777);

    try {

        $iterator = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator(
                $directory,
                FilesystemIterator::SKIP_DOTS
            ),
            RecursiveIteratorIterator::CHILD_FIRST
        );

        foreach ($iterator as $item) {

            $path = $item->getPathname();

            if ($item->isLink()) {

                deleteFileHard(
                    $path,
                    $stats
                );

                continue;
            }

            if ($item->isDir()) {

                @chmod($path, 0777);

                if (@rmdir($path)) {
                    $stats['dirs']++;
                }

                continue;
            }

            deleteFileHard(
                $path,
                $stats
            );
        }

    } catch (Throwable $e) {

        $stats['errors'][] =
            $directory . ': ' . $e->getMessage();
    }

    if ($deleteRoot) {

        @chmod($directory, 0777);

        if (@rmdir($directory)) {
            $stats['dirs']++;
        }
    }

    $stats['purged'][] = $directory;
}


function purgeIfExists($directory, &$stats, $root)
{
    if (!is_dir($directory)) {
        return false;
    }

    if (!pathInside($directory, $root)) {
        return false;
    }

    echo "[PURGE] {$directory}\n";

    purgeDirectory(
        $directory,
        $stats,
        false
    );

    return true;
}


/* =========================================================
 * HEADER
 * ========================================================= */

echo "============================================================\n";
echo " UNIVERSAL WORDPRESS CACHE PURGER\n";
echo "============================================================\n\n";

echo "Root        : {$BASE}\n";
echo "PHP         : " . PHP_VERSION . "\n";
echo "SAPI        : " . PHP_SAPI . "\n";
echo "Time        : " . date('Y-m-d H:i:s') . "\n\n";


/* =========================================================
 * PHP OUTPUT BUFFER
 * ========================================================= */

echo "------------------------------------------------------------\n";
echo "[PHP] OUTPUT BUFFER\n";
echo "------------------------------------------------------------\n";

while (ob_get_level() > 0) {
    @ob_end_flush();
}

echo "DONE\n\n";


/* =========================================================
 * PHP STAT CACHE
 * ========================================================= */

echo "------------------------------------------------------------\n";
echo "[PHP] STAT CACHE\n";
echo "------------------------------------------------------------\n";

clearstatcache(true);

echo "DONE\n\n";


/* =========================================================
 * OPCACHE
 * ========================================================= */

echo "------------------------------------------------------------\n";
echo "[PHP] OPCACHE\n";
echo "------------------------------------------------------------\n";

if (function_exists('opcache_reset')) {

    $result = @opcache_reset();

    echo $result
        ? "OPcache reset: SUCCESS\n"
        : "OPcache reset: FAILED / DISABLED\n";

} else {

    echo "OPcache: NOT AVAILABLE\n";
}

echo "\n";


/* =========================================================
 * APCU
 * ========================================================= */

echo "------------------------------------------------------------\n";
echo "[PHP] APCU\n";
echo "------------------------------------------------------------\n";

if (function_exists('apcu_clear_cache')) {

    try {

        $result = @apcu_clear_cache();

        echo $result
            ? "APCu reset: SUCCESS\n"
            : "APCu reset: FAILED\n";

    } catch (Throwable $e) {

        echo "APCu error: "
            . $e->getMessage()
            . "\n";
    }

} else {

    echo "APCu: NOT AVAILABLE\n";
}

echo "\n";


/* =========================================================
 * CACHE DIRECTORY LIST
 * ========================================================= */

echo "------------------------------------------------------------\n";
echo "[FILESYSTEM] KNOWN CACHE LOCATIONS\n";
echo "------------------------------------------------------------\n";

$cacheDirectories = [

    /*
     * Generic WordPress
     */
    'wp-content/cache',
    'wp-content/tmp',
    'wp-content/temp',

    /*
     * LiteSpeed Cache
     */
    'wp-content/litespeed',
    'wp-content/cache/litespeed',

    /*
     * WP Rocket
     */
    'wp-content/cache/wp-rocket',
    'wp-content/cache/min',
    'wp-content/cache/busting',

    /*
     * W3 Total Cache
     */
    'wp-content/cache/page_enhanced',
    'wp-content/cache/minify',
    'wp-content/cache/object',
    'wp-content/cache/db',
    'wp-content/cache/tmp',
    'wp-content/w3tc-cache',

    /*
     * WP Super Cache
     */
    'wp-content/cache/supercache',
    'wp-content/cache/meta',

    /*
     * WP Fastest Cache
     */
    'wp-content/cache/all',
    'wp-content/cache/wpfc-minified',
    'wp-content/cache/wpfc-mobile-cache',

    /*
     * Autoptimize
     */
    'wp-content/cache/autoptimize',
    'wp-content/cache/autoptimize/css',
    'wp-content/cache/autoptimize/js',

    /*
     * Hummingbird
     */
    'wp-content/wphb-cache',
    'wp-content/cache/wphb',

    /*
     * SiteGround / SG Optimizer
     */
    'wp-content/cache/sg-cachepress',
    'wp-content/cache/sg-optimizer',

    /*
     * Breeze
     */
    'wp-content/cache/breeze',

    /*
     * Cache Enabler
     */
    'wp-content/cache/cache-enabler',

    /*
     * Comet Cache
     */
    'wp-content/cache/comet-cache',

    /*
     * Swift Performance
     */
    'wp-content/cache/swift-performance',
    'wp-content/cache/swift-performance-lite',

    /*
     * FlyingPress
     */
    'wp-content/cache/flying-press',
    'wp-content/cache/flyingpress',

    /*
     * Powered Cache
     */
    'wp-content/cache/powered-cache',

    /*
     * Borlabs Cache
     */
    'wp-content/cache/borlabs-cache',

    /*
     * SpeedyCache
     */
    'wp-content/cache/speedycache',

    /*
     * Seraphinite Accelerator
     */
    'wp-content/cache/seraphinite-accelerator',
    'wp-content/cache/seraphinite',

    /*
     * NitroPack local files
     */
    'wp-content/cache/nitropack',
    'wp-content/nitropack',

    /*
     * WP Optimize
     */
    'wp-content/cache/wpo-cache',
    'wp-content/cache/wpo-minify',
    'wp-content/cache/wpo-minify/header',
    'wp-content/cache/wpo-minify/footer',

    /*
     * Asset CleanUp
     */
    'wp-content/cache/wpacu',

    /*
     * Fast Velocity Minify
     */
    'wp-content/cache/fvm',

    /*
     * Async JavaScript
     */
    'wp-content/cache/async-javascript',

    /*
     * Clearfy
     */
    'wp-content/cache/clearfy',

    /*
     * Hyper Cache
     */
    'wp-content/cache/hyper-cache',

    /*
     * Cachify
     */
    'wp-content/cache/cachify',

    /*
     * Simple Cache
     */
    'wp-content/cache/simple-cache',

    /*
     * Nginx Helper local data
     */
    'wp-content/cache/nginx-helper',

    /*
     * Endurance Cache
     */
    'wp-content/cache/endurance',

    /*
     * Bluehost / Newfold
     */
    'wp-content/cache/newfold',
    'wp-content/cache/bluehost',

    /*
     * Pantheon Advanced Page Cache
     */
    'wp-content/cache/pantheon',

    /*
     * Kinsta local generated cache
     */
    'wp-content/cache/kinsta',

    /*
     * Cloudways
     */
    'wp-content/cache/cloudways',

    /*
     * Varnish helper/cache plugins
     */
    'wp-content/cache/varnish',

    /*
     * WP Cloudflare Super Page Cache
     */
    'wp-content/cache/wp-cloudflare-super-page-cache',

    /*
     * Elementor
     */
    'wp-content/uploads/elementor/css',
    'wp-content/uploads/elementor/tmp',
    'wp-content/uploads/elementor/google-fonts',

    /*
     * Elementor Pro
     */
    'wp-content/uploads/elementor-pro',

    /*
     * Divi
     */
    'wp-content/et-cache',
    'wp-content/cache/et',
    'wp-content/cache/divi',

    /*
     * Beaver Builder
     */
    'wp-content/uploads/bb-plugin/cache',
    'wp-content/uploads/bb-theme/cache',

    /*
     * Oxygen Builder
     */
    'wp-content/uploads/oxygen/css',
    'wp-content/uploads/oxygen/cache',

    /*
     * Bricks
     */
    'wp-content/uploads/bricks/css',
    'wp-content/uploads/bricks/cache',

    /*
     * Breakdance
     */
    'wp-content/uploads/breakdance/css',
    'wp-content/uploads/breakdance/cache',

    /*
     * GeneratePress
     */
    'wp-content/uploads/generatepress',

    /*
     * Kadence
     */
    'wp-content/uploads/kadence',
    'wp-content/cache/kadence',

    /*
     * Astra
     */
    'wp-content/uploads/ast-css',
    'wp-content/cache/astra',

    /*
     * Avada
     */
    'wp-content/uploads/fusion-styles',
    'wp-content/cache/fusion',

    /*
     * Thrive
     */
    'wp-content/uploads/thrive',
    'wp-content/cache/thrive',

    /*
     * Visual Composer
     */
    'wp-content/uploads/visualcomposer-assets',
    'wp-content/cache/visualcomposer',

    /*
     * WPBakery generated cache
     */
    'wp-content/cache/js_composer',

    /*
     * Revolution Slider
     */
    'wp-content/cache/revslider',

    /*
     * WooCommerce transients/cache files
     */
    'wp-content/cache/woocommerce',

    /*
     * EWWW
     */
    'wp-content/cache/ewww',

    /*
     * ShortPixel
     */
    'wp-content/cache/shortpixel',

    /*
     * Imagify
     */
    'wp-content/cache/imagify',

    /*
     * WebP Express
     */
    'wp-content/cache/webp-express',

    /*
     * Optimole
     */
    'wp-content/cache/optimole',

    /*
     * Jetpack
     */
    'wp-content/cache/jetpack',

    /*
     * Jetpack Boost
     */
    'wp-content/cache/jetpack-boost',
];


$seen = [];

foreach ($cacheDirectories as $relative) {

    $directory =
        $BASE . DIRECTORY_SEPARATOR . $relative;

    $key = normalizePath($directory);

    if (isset($seen[$key])) {
        continue;
    }

    $seen[$key] = true;

    purgeIfExists(
        $directory,
        $stats,
        $BASE
    );
}

echo "\n";


/* =========================================================
 * AUTO DETECT CACHE DIRECTORIES
 * ========================================================= */

echo "------------------------------------------------------------\n";
echo "[FILESYSTEM] AUTO DETECTION\n";
echo "------------------------------------------------------------\n";

$wpContent = $BASE . '/wp-content';

$cacheNamePatterns = [
    'cache',
    'caches',
    'cached',
    'litespeed',
    'autoptimize',
    'wphb-cache',
    'et-cache',
    'nitropack',
    'breeze',
    'flying-press',
    'flyingpress',
    'swift-performance',
    'speedycache',
    'wpo-cache',
    'wpo-minify',
    'wp-rocket',
    'supercache',
    'comet-cache',
    'hyper-cache',
    'cachify',
];


if (is_dir($wpContent)) {

    try {

        $iterator = new DirectoryIterator($wpContent);

        foreach ($iterator as $item) {

            if (
                $item->isDot() ||
                !$item->isDir()
            ) {
                continue;
            }

            $name = strtolower(
                $item->getFilename()
            );

            foreach ($cacheNamePatterns as $pattern) {

                if (
                    $name === $pattern ||
                    strpos($name, $pattern) !== false
                ) {

                    $directory =
                        $item->getPathname();

                    $key =
                        normalizePath($directory);

                    if (!isset($seen[$key])) {

                        purgeIfExists(
                            $directory,
                            $stats,
                            $BASE
                        );

                        $seen[$key] = true;
                    }

                    break;
                }
            }
        }

    } catch (Throwable $e) {

        $stats['errors'][] =
            'Auto detection: '
            . $e->getMessage();
    }
}

echo "\n";


/* =========================================================
 * LOAD WORDPRESS
 * ========================================================= */

echo "------------------------------------------------------------\n";
echo "[WORDPRESS] LOAD CORE\n";
echo "------------------------------------------------------------\n";

$wpLoaded = false;

$wpLoadCandidates = [
    $BASE . '/wp-load.php',
    dirname($BASE) . '/wp-load.php',
];


foreach ($wpLoadCandidates as $wpLoad) {

    if (file_exists($wpLoad)) {

        try {

            if (!defined('WP_USE_THEMES')) {
                define('WP_USE_THEMES', false);
            }

            require_once $wpLoad;

            $wpLoaded = true;

            echo "WordPress loaded: {$wpLoad}\n";

            break;

        } catch (Throwable $e) {

            echo "WordPress load error: "
                . $e->getMessage()
                . "\n";
        }
    }
}


if (!$wpLoaded) {
    echo "WordPress core tidak ditemukan.\n";
}

echo "\n";


/* =========================================================
 * WORDPRESS OBJECT CACHE
 * ========================================================= */

if ($wpLoaded) {

    echo "------------------------------------------------------------\n";
    echo "[WORDPRESS] OBJECT CACHE\n";
    echo "------------------------------------------------------------\n";

    if (function_exists('wp_cache_flush')) {

        try {

            $result = wp_cache_flush();

            echo "wp_cache_flush(): "
                . ($result ? 'SUCCESS' : 'DONE')
                . "\n";

        } catch (Throwable $e) {

            echo "wp_cache_flush error: "
                . $e->getMessage()
                . "\n";
        }
    }

    echo "\n";


    /* =====================================================
     * TRANSIENTS
     * ===================================================== */

    echo "------------------------------------------------------------\n";
    echo "[WORDPRESS] TRANSIENTS\n";
    echo "------------------------------------------------------------\n";

    global $wpdb;

    if (
        isset($wpdb) &&
        is_object($wpdb)
    ) {

        try {

            $optionsTable =
                $wpdb->options;

            $deleted1 = $wpdb->query(
                "DELETE FROM {$optionsTable}
                 WHERE option_name LIKE '\\_transient\\_%'"
            );

            $deleted2 = $wpdb->query(
                "DELETE FROM {$optionsTable}
                 WHERE option_name LIKE '\\_site\\_transient\\_%'"
            );

            echo "Transients deleted      : "
                . (int)$deleted1
                . "\n";

            echo "Site transients deleted : "
                . (int)$deleted2
                . "\n";

        } catch (Throwable $e) {

            echo "Transient error: "
                . $e->getMessage()
                . "\n";
        }
    }

    echo "\n";


    /* =====================================================
     * LITESPEED
     * ===================================================== */

    echo "------------------------------------------------------------\n";
    echo "[PLUGIN] LITESPEED\n";
    echo "------------------------------------------------------------\n";

    try {

        if (has_action('litespeed_purge_all')) {

            do_action('litespeed_purge_all');

            echo "LiteSpeed purge hook: SUCCESS\n";

        } elseif (
            class_exists('LiteSpeed\Purge')
        ) {

            do_action('litespeed_purge_all');

            echo "LiteSpeed purge: REQUESTED\n";

        } else {

            echo "LiteSpeed hook unavailable.\n";
        }

    } catch (Throwable $e) {

        echo "LiteSpeed error: "
            . $e->getMessage()
            . "\n";
    }

    echo "\n";


    /* =====================================================
     * WP ROCKET
     * ===================================================== */

    echo "------------------------------------------------------------\n";
    echo "[PLUGIN] WP ROCKET\n";
    echo "------------------------------------------------------------\n";

    try {

        if (function_exists('rocket_clean_domain')) {

            rocket_clean_domain();

            echo "rocket_clean_domain(): SUCCESS\n";
        }

        if (function_exists('rocket_clean_minify')) {

            rocket_clean_minify();

            echo "rocket_clean_minify(): SUCCESS\n";
        }

    } catch (Throwable $e) {

        echo "WP Rocket error: "
            . $e->getMessage()
            . "\n";
    }

    echo "\n";


    /* =====================================================
     * W3 TOTAL CACHE
     * ===================================================== */

    echo "------------------------------------------------------------\n";
    echo "[PLUGIN] W3 TOTAL CACHE\n";
    echo "------------------------------------------------------------\n";

    try {

        if (function_exists('w3tc_flush_all')) {

            w3tc_flush_all();

            echo "w3tc_flush_all(): SUCCESS\n";
        }

    } catch (Throwable $e) {

        echo "W3TC error: "
            . $e->getMessage()
            . "\n";
    }

    echo "\n";


    /* =====================================================
     * WP SUPER CACHE
     * ===================================================== */

    echo "------------------------------------------------------------\n";
    echo "[PLUGIN] WP SUPER CACHE\n";
    echo "------------------------------------------------------------\n";

    try {

        if (function_exists('wp_cache_clear_cache')) {

            wp_cache_clear_cache();

            echo "wp_cache_clear_cache(): SUCCESS\n";
        }

    } catch (Throwable $e) {

        echo "WP Super Cache error: "
            . $e->getMessage()
            . "\n";
    }

    echo "\n";


    /* =====================================================
     * WP FASTEST CACHE
     * ===================================================== */

    echo "------------------------------------------------------------\n";
    echo "[PLUGIN] WP FASTEST CACHE\n";
    echo "------------------------------------------------------------\n";

    try {

        if (function_exists('wpfc_clear_all_cache')) {

            wpfc_clear_all_cache(true);

            echo "WP Fastest Cache: SUCCESS\n";
        }

    } catch (Throwable $e) {

        echo "WP Fastest Cache error: "
            . $e->getMessage()
            . "\n";
    }

    echo "\n";


    /* =====================================================
     * AUTOPTIMIZE
     * ===================================================== */

    echo "------------------------------------------------------------\n";
    echo "[PLUGIN] AUTOPTIMIZE\n";
    echo "------------------------------------------------------------\n";

    try {

        if (
            class_exists(
                'autoptimizeCache'
            )
        ) {

            autoptimizeCache::clearall();

            echo "Autoptimize: SUCCESS\n";
        }

    } catch (Throwable $e) {

        echo "Autoptimize error: "
            . $e->getMessage()
            . "\n";
    }

    echo "\n";


    /* =====================================================
     * SG OPTIMIZER
     * ===================================================== */

    echo "------------------------------------------------------------\n";
    echo "[PLUGIN] SITEGROUND / SG OPTIMIZER\n";
    echo "------------------------------------------------------------\n";

    try {

        if (
            function_exists(
                'sg_cachepress_purge_cache'
            )
        ) {

            sg_cachepress_purge_cache();

            echo "SG Optimizer: SUCCESS\n";
        }

        if (
            function_exists(
                'sg_cachepress_purge_everything'
            )
        ) {

            sg_cachepress_purge_everything();

            echo "SG CachePress: SUCCESS\n";
        }

    } catch (Throwable $e) {

        echo "SG Optimizer error: "
            . $e->getMessage()
            . "\n";
    }

    echo "\n";


    /* =====================================================
     * FLYINGPRESS
     * ===================================================== */

    echo "------------------------------------------------------------\n";
    echo "[PLUGIN] FLYINGPRESS\n";
    echo "------------------------------------------------------------\n";

    try {

        do_action(
            'flying_press_purge_everything'
        );

        echo "FlyingPress purge hook: REQUESTED\n";

    } catch (Throwable $e) {

        echo "FlyingPress error: "
            . $e->getMessage()
            . "\n";
    }

    echo "\n";


    /* =====================================================
     * Hummingbird
     * ===================================================== */

    echo "------------------------------------------------------------\n";
    echo "[PLUGIN] HUMMINGBIRD\n";
    echo "------------------------------------------------------------\n";

    try {

        do_action(
            'wphb_clear_page_cache'
        );

        do_action(
            'wphb_clear_minify_cache'
        );

        echo "Hummingbird hooks: REQUESTED\n";

    } catch (Throwable $e) {

        echo "Hummingbird error: "
            . $e->getMessage()
            . "\n";
    }

    echo "\n";


    /* =====================================================
     * BREEZE
     * ===================================================== */

    echo "------------------------------------------------------------\n";
    echo "[PLUGIN] BREEZE\n";
    echo "------------------------------------------------------------\n";

    try {

        do_action(
            'breeze_clear_all_cache'
        );

        echo "Breeze hook: REQUESTED\n";

    } catch (Throwable $e) {

        echo "Breeze error: "
            . $e->getMessage()
            . "\n";
    }

    echo "\n";


    /* =====================================================
     * ELEMENTOR
     * ===================================================== */

    echo "------------------------------------------------------------\n";
    echo "[PLUGIN] ELEMENTOR\n";
    echo "------------------------------------------------------------\n";

    try {

        if (
            class_exists('\Elementor\Plugin')
        ) {

            \Elementor\Plugin::$instance
                ->files_manager
                ->clear_cache();

            echo "Elementor CSS cache: SUCCESS\n";
        }

    } catch (Throwable $e) {

        echo "Elementor error: "
            . $e->getMessage()
            . "\n";
    }

    echo "\n";


    /* =====================================================
     * REDIS OBJECT CACHE
     * ===================================================== */

    echo "------------------------------------------------------------\n";
    echo "[OBJECT CACHE] REDIS\n";
    echo "------------------------------------------------------------\n";

    try {

        if (
            function_exists('wp_cache_flush')
        ) {

            wp_cache_flush();

            echo "Redis/Object cache flush requested through WordPress.\n";
        }

    } catch (Throwable $e) {

        echo "Redis error: "
            . $e->getMessage()
            . "\n";
    }

    echo "\n";
}


/* =========================================================
 * PHP GARBAGE COLLECTION
 * ========================================================= */

echo "------------------------------------------------------------\n";
echo "[PHP] GARBAGE COLLECTION\n";
echo "------------------------------------------------------------\n";

if (function_exists('gc_collect_cycles')) {

    $cycles =
        gc_collect_cycles();

    echo "Cycles collected: {$cycles}\n";
}

clearstatcache(true);

echo "\n";


/* =========================================================
 * RESULTS
 * ========================================================= */

echo "============================================================\n";
echo " CACHE PURGE RESULT\n";
echo "============================================================\n";

echo "Files deleted : "
    . $stats['files']
    . "\n";

echo "Dirs deleted  : "
    . $stats['dirs']
    . "\n";

echo "Data removed  : "
    . humanSize($stats['bytes'])
    . "\n";

echo "Locations     : "
    . count(array_unique($stats['purged']))
    . "\n";

echo "Errors        : "
    . count($stats['errors'])
    . "\n";


if (!empty($stats['errors'])) {

    echo "\n";
    echo "ERROR DETAILS\n";
    echo "------------------------------------------------------------\n";

    foreach (
        array_unique($stats['errors'])
        as $error
    ) {

        echo "- {$error}\n";
    }
}


echo "\n";
echo "============================================================\n";
echo " CACHE PURGE FINISHED\n";
echo "============================================================\n";