wordpress cache eklentisi custom cache

Genel Forum
Cevapla
muratca61
Site Admin
Mesajlar: 35964
Kayıt: Cmt Ara 21, 2024 7:56 am

wordpress cache eklentisi custom cache

Mesaj gönderen muratca61 »

Kod:Tümünü seç

<?php
/*
Plugin Name: Custom Cache
Description: Gelişmiş önbellek yönetimi (Her istek için benzersiz cache dosyası oluşturur + Boyut temelli temizleme + Profesyonel Admin Paneli).
Version: 3.0
Author: Sizin Adınız
*/

// Sabitler
if ( ! defined('WP_CONTENT_DIR') ) {
    define('WP_CONTENT_DIR', dirname(__FILE__));
}
define('CUSTOM_CACHE_DIR', WP_CONTENT_DIR . '/cache/');
define('MAX_CACHE_SIZE_MB', 100);       // Maksimum önbellek boyutu (MB)
define('CLEANUP_PERCENTAGE', 20);         // Temizlenecek dosya yüzdesi (%)
define('CACHE_EXPIRY', 3600);             // Cache geçerlilik süresi (saniye)

// Eklenti aktifleştirildiğinde cache klasörünü oluştur
register_activation_hook(__FILE__, 'custom_cache_activate');
function custom_cache_activate() {
    if ( ! file_exists(CUSTOM_CACHE_DIR) ) {
        if ( ! mkdir(CUSTOM_CACHE_DIR, 0755, true) ) {
            error_log('HATA: Cache klasörü oluşturulamadı: ' . CUSTOM_CACHE_DIR);
        } else {
            error_log('Cache klasörü oluşturuldu: ' . CUSTOM_CACHE_DIR);
        }
    }
}

// Eklenti pasifleştirildiğinde cache klasörünü sil
register_deactivation_hook(__FILE__, 'custom_cache_deactivate');
function custom_cache_deactivate() {
    if ( file_exists(CUSTOM_CACHE_DIR) ) {
        foreach ( glob(CUSTOM_CACHE_DIR . '*.html') as $file ) {
            if ( file_exists($file) && ! unlink($file) ) {
                error_log('HATA: Dosya silinemedi: ' . $file);
            }
        }
        rmdir(CUSTOM_CACHE_DIR);
    }
}

// Cache boyutunu hesapla (bayt cinsinden)
function custom_cache_get_size() {
    $total_size = 0;
    foreach ( glob(CUSTOM_CACHE_DIR . '*.html') as $file ) {
        if ( file_exists($file) ) {
            $total_size += filesize($file);
        }
    }
    return $total_size;
}

// Cache dosyalarını say
function custom_cache_get_file_count() {
    return count( glob(CUSTOM_CACHE_DIR . '*.html') );
}

// Mobil cihaz tespiti
function is_mobile_device() {
    return preg_match('/Mobile|Android|BlackBerry|iPhone|Windows Phone/i', $_SERVER['HTTP_USER_AGENT']);
}

// Her istek için benzersiz cache dosyası adı oluştur
function new_cache_file_name() {
    $mobile_suffix = is_mobile_device() ? '_mobile' : '_desktop';
    $cache_key = md5($_SERVER['REQUEST_URI']);
    return CUSTOM_CACHE_DIR . $cache_key . $mobile_suffix . '_' . microtime(true) . '.html';
}

// Aynı URL için oluşturulan cache dosyalarını bulmak üzere desen üretir
function get_cache_file_pattern() {
    $mobile_suffix = is_mobile_device() ? '_mobile' : '_desktop';
    $cache_key = md5($_SERVER['REQUEST_URI']);
    return CUSTOM_CACHE_DIR . $cache_key . $mobile_suffix . '_*.html';
}

// En güncel cache dosyasını getir (varsa)
function get_latest_cache_file() {
    $pattern = get_cache_file_pattern();
    $files = glob($pattern);
    if (!empty($files)) {
        usort($files, function($a, $b) {
            return filemtime($b) - filemtime($a);
        });
        $latest = $files[0];
        if ((time() - filemtime($latest)) <= CACHE_EXPIRY) {
            return $latest;
        }
    }
    return false;
}

// Boyut sınırını aştığında en eski dosyaları temizle
function custom_cache_cleanup_by_size() {
    $max_size     = MAX_CACHE_SIZE_MB * 1024 * 1024;
    $current_size = custom_cache_get_size();

    if ( $current_size > $max_size ) {
        $files = array();
        foreach ( glob(CUSTOM_CACHE_DIR . '*.html') as $file ) {
            $files[] = ['path' => $file, 'mtime' => filemtime($file)];
        }
        usort($files, function($a, $b) {
            return $a['mtime'] - $b['mtime'];
        });
        $delete_count = ceil(count($files) * (CLEANUP_PERCENTAGE / 100));
        for ( $i = 0; $i < $delete_count; $i++ ) {
            if ( isset($files[$i]['path']) && file_exists($files[$i]['path']) ) {
                if ( ! unlink($files[$i]['path']) ) {
                    error_log('HATA: Dosya silinemedi: ' . $files[$i]['path']);
                }
            }
        }
    }
}

// Cache'den içerik sun (Admin, AJAX veya giriş yapmış kullanıcılar hariç)
function custom_cache_serve() {
    if ( is_admin() || defined('DOING_AJAX') || is_user_logged_in() ) return;
    
    $cache_file = get_latest_cache_file();
    if ( $cache_file && file_exists($cache_file) ) {
        header("Content-Type: text/html; charset=UTF-8");
        readfile($cache_file);
        exit;
    }
}
add_action('template_redirect', 'custom_cache_serve', 0);

// Output Buffer'ı başlat (Admin, AJAX ve giriş yapmış kullanıcılar hariç)
function custom_cache_start() {
    if ( ! is_admin() && ! defined('DOING_AJAX') && ! is_user_logged_in() ) {
        ob_start();
    }
}
add_action('template_redirect', 'custom_cache_start', 1);

// Buffer'daki içeriği yeni benzersiz cache dosyasına kaydet
function custom_cache_end() {
    if ( ! is_admin() && ! defined('DOING_AJAX') && ! is_user_logged_in() ) {
        $content = ob_get_contents();
        ob_end_clean();

        if ( ! empty($content) ) {
            $cache_file = new_cache_file_name();
            if ( is_writable(CUSTOM_CACHE_DIR) ) {
                $write_result = file_put_contents($cache_file, $content);
                if ( $write_result === false ) {
                    error_log('HATA: Cache dosyası yazılamadı: ' . $cache_file);
                } else {
                    custom_cache_cleanup_by_size();
                }
            } else {
                error_log('HATA: Cache dizini yazılabilir değil: ' . CUSTOM_CACHE_DIR);
            }
        }
        echo $content;
    } else {
        if ( ob_get_length() ) {
            ob_end_flush();
        }
    }
}
add_action('shutdown', 'custom_cache_end', 999);

// Admin Paneli: Menü ekle
add_action('admin_menu', 'custom_cache_admin_menu');
function custom_cache_admin_menu() {
    add_menu_page(
        'Cache Yönetimi',
        'Cache',
        'manage_options',
        'custom-cache',
        'custom_cache_admin_page',
        'dashicons-performance'
    );
}

// Admin Paneli: Sayfa içeriği
function custom_cache_admin_page() {
    if ( isset($_POST['clear_cache']) ) {
        if ( isset($_POST['custom_cache_nonce']) && wp_verify_nonce($_POST['custom_cache_nonce'], 'custom_cache_clear') ) {
            foreach ( glob(CUSTOM_CACHE_DIR . '*.html') as $file ) {
                if ( file_exists($file) && ! unlink($file) ) {
                    error_log('HATA: Dosya silinemedi: ' . $file);
                }
            }
            echo '<div class="notice notice-success is-dismissible"><p>Önbellek temizlendi!</p></div>';
        } else {
            echo '<div class="notice notice-error is-dismissible"><p>Güvenlik doğrulaması başarısız!</p></div>';
        }
    }

    $current_size = round(custom_cache_get_size() / (1024 * 1024), 2);
    $max_size     = MAX_CACHE_SIZE_MB;
    $file_count   = custom_cache_get_file_count();
    ?>
    <div class="wrap">
        <h1>Cache Yönetimi</h1>
        <style>
            .cc-admin-container {
                background: #fff;
                padding: 20px;
                border: 1px solid #ddd;
                box-shadow: 0 1px 3px rgba(0,0,0,0.1);
                margin-top: 20px;
            }
            .cc-admin-table {
                width: 100%;
                border-collapse: collapse;
            }
            .cc-admin-table th, .cc-admin-table td {
                text-align: left;
                padding: 10px;
                border-bottom: 1px solid #eee;
            }
            .cc-admin-actions {
                margin-top: 20px;
            }
        </style>
        <div class="cc-admin-container">
            <table class="cc-admin-table">
                <tr>
                    <th>Mevcut Cache Boyutu</th>
                    <td><?php echo $current_size; ?> MB</td>
                </tr>
                <tr>
                    <th>Maksimum Cache Boyutu</th>
                    <td><?php echo $max_size; ?> MB</td>
                </tr>
                <tr>
                    <th>Önbellekteki Dosya Sayısı</th>
                    <td><?php echo $file_count; ?></td>
                </tr>
            </table>
            <div class="cc-admin-actions">
                <form method="post">
                    <?php wp_nonce_field('custom_cache_clear', 'custom_cache_nonce'); ?>
                    <?php submit_button('Önbelleği Temizle', 'primary', 'clear_cache'); ?>
                </form>
            </div>
        </div>
    </div>
    <?php
}
?>
muratca61
Site Admin
Mesajlar: 35964
Kayıt: Cmt Ara 21, 2024 7:56 am

Re: wordpress cache eklentisi custom cache

Mesaj gönderen muratca61 »

çalışıyormu bilinmiyor

Kod:Tümünü seç

<?php
/*
Plugin Name: Custom Cache
Description: Gelişmiş önbellek yönetimi (Her istek için benzersiz cache dosyası oluşturur + Boyut temelli temizleme + Profesyonel Admin Paneli + Aktif/Pasif ayarı).
Version: 3.1
Author: Sizin Adınız
*/

// Sabitler
if ( ! defined('WP_CONTENT_DIR') ) {
    define('WP_CONTENT_DIR', dirname(__FILE__));
}
define('CUSTOM_CACHE_DIR', WP_CONTENT_DIR . '/cache/');
define('MAX_CACHE_SIZE_MB', 100);       // Maksimum önbellek boyutu (MB)
define('CLEANUP_PERCENTAGE', 20);         // Temizlenecek dosya yüzdesi (%)
define('CACHE_EXPIRY', 3600);             // Cache geçerlilik süresi (saniye)

// Caching ayarını kontrol eden yardımcı fonksiyon (varsayılan: aktif)
function custom_cache_is_enabled() {
    return (bool) get_option('custom_cache_enabled', 1);
}

// Eklenti aktifleştirildiğinde cache klasörünü oluştur
register_activation_hook(__FILE__, 'custom_cache_activate');
function custom_cache_activate() {
    if ( ! file_exists(CUSTOM_CACHE_DIR) ) {
        if ( ! mkdir(CUSTOM_CACHE_DIR, 0755, true) ) {
            error_log('HATA: Cache klasörü oluşturulamadı: ' . CUSTOM_CACHE_DIR);
        } else {
            error_log('Cache klasörü oluşturuldu: ' . CUSTOM_CACHE_DIR);
        }
    }
    // Varsayılan olarak caching aktif olsun
    if ( get_option('custom_cache_enabled') === false ) {
        update_option('custom_cache_enabled', 1);
    }
}

// Eklenti pasifleştirildiğinde cache klasörünü sil
register_deactivation_hook(__FILE__, 'custom_cache_deactivate');
function custom_cache_deactivate() {
    if ( file_exists(CUSTOM_CACHE_DIR) ) {
        foreach ( glob(CUSTOM_CACHE_DIR . '*.html') as $file ) {
            if ( file_exists($file) && ! unlink($file) ) {
                error_log('HATA: Dosya silinemedi: ' . $file);
            }
        }
        rmdir(CUSTOM_CACHE_DIR);
    }
}

// Cache boyutunu hesapla (bayt cinsinden)
function custom_cache_get_size() {
    $total_size = 0;
    foreach ( glob(CUSTOM_CACHE_DIR . '*.html') as $file ) {
        if ( file_exists($file) ) {
            $total_size += filesize($file);
        }
    }
    return $total_size;
}

// Cache dosyalarını say
function custom_cache_get_file_count() {
    return count( glob(CUSTOM_CACHE_DIR . '*.html') );
}

// Mobil cihaz tespiti
function is_mobile_device() {
    return preg_match('/Mobile|Android|BlackBerry|iPhone|Windows Phone/i', $_SERVER['HTTP_USER_AGENT']);
}

// Her istek için benzersiz cache dosyası adı oluştur
function new_cache_file_name() {
    $mobile_suffix = is_mobile_device() ? '_mobile' : '_desktop';
    $cache_key = md5($_SERVER['REQUEST_URI']);
    return CUSTOM_CACHE_DIR . $cache_key . $mobile_suffix . '_' . microtime(true) . '.html';
}

// Aynı URL için oluşturulan cache dosyalarını bulmak üzere desen üretir
function get_cache_file_pattern() {
    $mobile_suffix = is_mobile_device() ? '_mobile' : '_desktop';
    $cache_key = md5($_SERVER['REQUEST_URI']);
    return CUSTOM_CACHE_DIR . $cache_key . $mobile_suffix . '_*.html';
}

// En güncel cache dosyasını getir (varsa ve geçerlilik süresi içerisinde)
function get_latest_cache_file() {
    $pattern = get_cache_file_pattern();
    $files = glob($pattern);
    if (!empty($files)) {
        usort($files, function($a, $b) {
            return filemtime($b) - filemtime($a);
        });
        $latest = $files[0];
        if ((time() - filemtime($latest)) <= CACHE_EXPIRY) {
            return $latest;
        }
    }
    return false;
}

// Boyut sınırını aştığında en eski dosyaları temizle
function custom_cache_cleanup_by_size() {
    $max_size     = MAX_CACHE_SIZE_MB * 1024 * 1024;
    $current_size = custom_cache_get_size();

    if ( $current_size > $max_size ) {
        $files = array();
        foreach ( glob(CUSTOM_CACHE_DIR . '*.html') as $file ) {
            $files[] = ['path' => $file, 'mtime' => filemtime($file)];
        }
        usort($files, function($a, $b) {
            return $a['mtime'] - $b['mtime'];
        });
        $delete_count = ceil(count($files) * (CLEANUP_PERCENTAGE / 100));
        for ( $i = 0; $i < $delete_count; $i++ ) {
            if ( isset($files[$i]['path']) && file_exists($files[$i]['path']) ) {
                if ( ! unlink($files[$i]['path']) ) {
                    error_log('HATA: Dosya silinemedi: ' . $files[$i]['path']);
                }
            }
        }
    }
}

// Cache'den içerik sun (Admin, AJAX veya giriş yapmış kullanıcılar hariç)
function custom_cache_serve() {
    if ( ! custom_cache_is_enabled() ) return;
    if ( is_admin() || defined('DOING_AJAX') || is_user_logged_in() ) return;
    
    $cache_file = get_latest_cache_file();
    if ( $cache_file && file_exists($cache_file) ) {
        header("Content-Type: text/html; charset=UTF-8");
        readfile($cache_file);
        exit;
    }
}
add_action('template_redirect', 'custom_cache_serve', 0);

// Output Buffer'ı başlat (Admin, AJAX ve giriş yapmış kullanıcılar hariç)
function custom_cache_start() {
    if ( ! custom_cache_is_enabled() ) return;
    if ( ! is_admin() && ! defined('DOING_AJAX') && ! is_user_logged_in() ) {
        ob_start();
    }
}
add_action('template_redirect', 'custom_cache_start', 1);

// Buffer'daki içeriği yeni benzersiz cache dosyasına kaydet
function custom_cache_end() {
    if ( ! custom_cache_is_enabled() ) {
        if ( ob_get_length() ) {
            ob_end_flush();
        }
        return;
    }
    if ( ! is_admin() && ! defined('DOING_AJAX') && ! is_user_logged_in() ) {
        $content = ob_get_contents();
        ob_end_clean();

        if ( ! empty($content) ) {
            $cache_file = new_cache_file_name();
            if ( is_writable(CUSTOM_CACHE_DIR) ) {
                $write_result = file_put_contents($cache_file, $content);
                if ( $write_result === false ) {
                    error_log('HATA: Cache dosyası yazılamadı: ' . $cache_file);
                } else {
                    custom_cache_cleanup_by_size();
                }
            } else {
                error_log('HATA: Cache dizini yazılabilir değil: ' . CUSTOM_CACHE_DIR);
            }
        }
        echo $content;
    } else {
        if ( ob_get_length() ) {
            ob_end_flush();
        }
    }
}
add_action('shutdown', 'custom_cache_end', 999);

// Admin Paneli: Menü ekle
add_action('admin_menu', 'custom_cache_admin_menu');
function custom_cache_admin_menu() {
    add_menu_page(
        'Cache Yönetimi',
        'Cache',
        'manage_options',
        'custom-cache',
        'custom_cache_admin_page',
        'dashicons-performance'
    );
}

// Admin Paneli: Sayfa içeriği
function custom_cache_admin_page() {
    // Önbellek temizleme işlemi
    if ( isset($_POST['clear_cache']) ) {
        if ( isset($_POST['custom_cache_nonce']) && wp_verify_nonce($_POST['custom_cache_nonce'], 'custom_cache_clear') ) {
            foreach ( glob(CUSTOM_CACHE_DIR . '*.html') as $file ) {
                if ( file_exists($file) && ! unlink($file) ) {
                    error_log('HATA: Dosya silinemedi: ' . $file);
                }
            }
            echo '<div class="notice notice-success is-dismissible"><p>Önbellek temizlendi!</p></div>';
        } else {
            echo '<div class="notice notice-error is-dismissible"><p>Güvenlik doğrulaması başarısız!</p></div>';
        }
    }
    
    // Ayar güncelleme işlemi
    if ( isset($_POST['update_cache_settings']) ) {
        if ( isset($_POST['custom_cache_settings_nonce']) && wp_verify_nonce($_POST['custom_cache_settings_nonce'], 'custom_cache_settings') ) {
            $enabled = isset($_POST['cache_enabled']) ? 1 : 0;
            update_option('custom_cache_enabled', $enabled);
            echo '<div class="notice notice-success is-dismissible"><p>Ayarlar kaydedildi!</p></div>';
        } else {
            echo '<div class="notice notice-error is-dismissible"><p>Güvenlik doğrulaması başarısız!</p></div>';
        }
    }
    
    $current_size = round(custom_cache_get_size() / (1024 * 1024), 2);
    $max_size     = MAX_CACHE_SIZE_MB;
    $file_count   = custom_cache_get_file_count();
    $cache_active = custom_cache_is_enabled();
    ?>
    <div class="wrap">
        <h1>Cache Yönetimi</h1>
        <style>
            .cc-admin-container {
                background: #fff;
                padding: 20px;
                border: 1px solid #ddd;
                box-shadow: 0 1px 3px rgba(0,0,0,0.1);
                margin-top: 20px;
            }
            .cc-admin-table {
                width: 100%;
                border-collapse: collapse;
            }
            .cc-admin-table th, .cc-admin-table td {
                text-align: left;
                padding: 10px;
                border-bottom: 1px solid #eee;
            }
            .cc-admin-actions {
                margin-top: 20px;
            }
            .cc-admin-form {
                margin-top: 20px;
            }
        </style>
        <div class="cc-admin-container">
            <table class="cc-admin-table">
                <tr>
                    <th>Mevcut Cache Boyutu</th>
                    <td><?php echo $current_size; ?> MB</td>
                </tr>
                <tr>
                    <th>Maksimum Cache Boyutu</th>
                    <td><?php echo $max_size; ?> MB</td>
                </tr>
                <tr>
                    <th>Önbellekteki Dosya Sayısı</th>
                    <td><?php echo $file_count; ?></td>
                </tr>
                <tr>
                    <th>Cache Durumu</th>
                    <td><?php echo ($cache_active ? 'Aktif' : 'Pasif'); ?></td>
                </tr>
            </table>
            <div class="cc-admin-actions">
                <!-- Önbelleği Temizle -->
                <form method="post">
                    <?php wp_nonce_field('custom_cache_clear', 'custom_cache_nonce'); ?>
                    <?php submit_button('Önbelleği Temizle', 'primary', 'clear_cache'); ?>
                </form>
            </div>
            <div class="cc-admin-form">
                <!-- Cache Ayarları -->
                <form method="post">
                    <?php wp_nonce_field('custom_cache_settings', 'custom_cache_settings_nonce'); ?>
                    <p>
                        <label for="cache_enabled"><strong>Cache Aktif:</strong></label>
                        <input type="checkbox" id="cache_enabled" name="cache_enabled" value="1" <?php checked($cache_active, 1); ?>>
                    </p>
                    <?php submit_button('Ayarları Kaydet', 'secondary', 'update_cache_settings'); ?>
                </form>
            </div>
        </div>
    </div>
    <?php
}
?>
muratca61
Site Admin
Mesajlar: 35964
Kayıt: Cmt Ara 21, 2024 7:56 am

Re: wordpress cache eklentisi custom cache

Mesaj gönderen muratca61 »

bilinmiyor

Kod:Tümünü seç

<?php
/*
Plugin Name: Custom Cache
Description: Gelişmiş önbellek yönetimi (Her istek için benzersiz cache dosyası oluşturur + Boyut temizleme + Admin Paneli + Aktif/Pasif ayarı).
Version: 3.1
Author: Sizin Adınız
*/

// Sabitler
if (!defined('WP_CONTENT_DIR')) {
    define('WP_CONTENT_DIR', dirname(__FILE__));
}
define('CUSTOM_CACHE_DIR', WP_CONTENT_DIR . '/cache/');
define('MAX_CACHE_SIZE_MB', 100);       // Maksimum önbellek boyutu (MB)
define('CLEANUP_PERCENTAGE', 20);       // Temizlenecek dosya yüzdesi (%)
define('CACHE_EXPIRY', 3600);           // Cache geçerlilik süresi (saniye)

// Caching ayarını kontrol eden yardımcı fonksiyon (varsayılan: aktif)
function custom_cache_is_enabled()
{
    return (bool) get_option('custom_cache_enabled', 1);
}

// Eklenti aktifleştirildiğinde cache klasörünü oluştur
register_activation_hook(__FILE__, 'custom_cache_activate');
function custom_cache_activate()
{
    if (!file_exists(CUSTOM_CACHE_DIR)) {
        if (!mkdir(CUSTOM_CACHE_DIR, 0755, true)) {
            error_log('HATA: Cache klasörü oluşturulamadı: ' . CUSTOM_CACHE_DIR);
        } else {
            error_log('Cache klasörü oluşturuldu: ' . CUSTOM_CACHE_DIR);
        }
    }
    // Varsayılan olarak caching aktif olsun
    if (get_option('custom_cache_enabled') === false) {
        update_option('custom_cache_enabled', 1);
    }
}

// Eklenti pasifleştirildiğinde cache klasörünü sil
register_deactivation_hook(__FILE__, 'custom_cache_deactivate');
function custom_cache_deactivate()
{
    if (file_exists(CUSTOM_CACHE_DIR)) {
        foreach (glob(CUSTOM_CACHE_DIR . '*.html') as $file) {
            if (file_exists($file) && !unlink($file)) {
                error_log('HATA: Dosya silinemedi: ' . $file);
            }
        }
        rmdir(CUSTOM_CACHE_DIR);
    }
}

// Cache boyutunu hesapla (bayt cinsinden)
function custom_cache_get_size()
{
    $total_size = 0;
    foreach (glob(CUSTOM_CACHE_DIR . '*.html') as $file) {
        if (file_exists($file)) {
            $total_size += filesize($file);
        }
    }
    return $total_size;
}

// Cache dosyalarını say
function custom_cache_get_file_count()
{
    return count(glob(CUSTOM_CACHE_DIR . '*.html'));
}

// Mobil cihaz tespiti
function is_mobile_device()
{
    return preg_match('/Mobile|Android|BlackBerry|iPhone|Windows Phone/i', $_SERVER['HTTP_USER_AGENT']);
}

// Her istek için benzersiz cache dosyası adı oluştur
function new_cache_file_name()
{
    $mobile_suffix = is_mobile_device() ? '_mobile' : '_desktop';
    $cache_key = md5($_SERVER['REQUEST_URI']);
    return CUSTOM_CACHE_DIR . $cache_key . $mobile_suffix . '_' . microtime(true) . '.html';
}

// Aynı URL için oluşturulan cache dosyalarını bulmak üzere desen üretir
function get_cache_file_pattern()
{
    $mobile_suffix = is_mobile_device() ? '_mobile' : '_desktop';
    $cache_key = md5($_SERVER['REQUEST_URI']);
    return CUSTOM_CACHE_DIR . $cache_key . $mobile_suffix . '_*.html';
}

// En güncel cache dosyasını getir (varsa ve geçerlilik süresi içerisinde)
function get_latest_cache_file()
{
    $pattern = get_cache_file_pattern();
    $files = glob($pattern);
    if (!empty($files)) {
        usort($files, function ($a, $b) {
            return filemtime($b) - filemtime($a);
        });
        $latest = $files[0];
        if ((time() - filemtime($latest)) <= CACHE_EXPIRY) {
            return $latest;
        }
    }
    return false;
}

// Boyut sınırını aştığında en eski dosyaları temizle
function custom_cache_cleanup_by_size()
{
    $max_size     = MAX_CACHE_SIZE_MB * 1024 * 1024;
    $current_size = custom_cache_get_size();

    if ($current_size > $max_size) {
        $files = array();
        foreach (glob(CUSTOM_CACHE_DIR . '*.html') as $file) {
            $files[] = ['path' => $file, 'mtime' => filemtime($file)];
        }
        usort($files, function ($a, $b) {
            return $a['mtime'] - $b['mtime'];
        });
        $delete_count = ceil(count($files) * (CLEANUP_PERCENTAGE / 100));
        for ($i = 0; $i < $delete_count; $i++) {
            if (isset($files[$i]['path']) && file_exists($files[$i]['path'])) {
                if (!unlink($files[$i]['path'])) {
                    error_log('HATA: Dosya silinemedi: ' . $files[$i]['path']);
                }
            }
        }
    }
}

// Cache'den içerik sun (TÜM KULLANICILAR İÇİN)
function custom_cache_serve()
{
    if (!custom_cache_is_enabled()) return;

    $cache_file = get_latest_cache_file();
    if ($cache_file && file_exists($cache_file)) {
        header("Content-Type: text/html; charset=UTF-8");
        readfile($cache_file);
        exit;
    }
}
add_action('template_redirect', 'custom_cache_serve', 0);

// Output Buffer'ı başlat (TÜM KULLANICILAR İÇİN)
function custom_cache_start()
{
    if (!custom_cache_is_enabled()) return;

    ob_start();
}
add_action('template_redirect', 'custom_cache_start', 1);

// Buffer'daki içeriği kaydet (TÜM KULLANICILAR İÇİN)
function custom_cache_end()
{
    if (!custom_cache_is_enabled()) {
        if (ob_get_length()) {
            ob_end_flush();
        }
        return;
    }

    $content = ob_get_contents();
    ob_end_clean();

    if (!empty($content)) {
        $cache_file = new_cache_file_name();
        if (is_writable(CUSTOM_CACHE_DIR)) {
            $write_result = file_put_contents($cache_file, $content);
            if ($write_result === false) {
                error_log('HATA: Cache dosyası yazılamadı: ' . $cache_file);
            } else {
                custom_cache_cleanup_by_size();
            }
        } else {
            error_log('HATA: Cache dizini yazılabilir değil: ' . CUSTOM_CACHE_DIR);
        }
    }
    echo $content;
}
add_action('shutdown', 'custom_cache_end', 999);

// Admin Paneli: Menü ekle
add_action('admin_menu', 'custom_cache_admin_menu');
function custom_cache_admin_menu()
{
    add_menu_page(
        'Cache Yönetimi',
        'Cache',
        'manage_options',
        'custom-cache',
        'custom_cache_admin_page',
        'dashicons-performance'
    );
}

// Admin Paneli: Sayfa içeriği
function custom_cache_admin_page()
{
    // Önbellek temizleme işlemi
    if (isset($_POST['clear_cache'])) {
        if (isset($_POST['custom_cache_nonce']) && wp_verify_nonce($_POST['custom_cache_nonce'], 'custom_cache_clear')) {
            foreach (glob(CUSTOM_CACHE_DIR . '*.html') as $file) {
                if (file_exists($file) && !unlink($file)) {
                    error_log('HATA: Dosya silinemedi: ' . $file);
                }
            }
            echo '<div class="notice notice-success is-dismissible"><p>Önbellek temizlendi!</p></div>';
        } else {
            echo '<div class="notice notice-error is-dismissible"><p>Güvenlik doğrulaması başarısız!</p></div>';
        }
    }

    // Ayar güncelleme işlemi
    if (isset($_POST['update_cache_settings'])) {
        if (isset($_POST['custom_cache_settings_nonce']) && wp_verify_nonce($_POST['custom_cache_settings_nonce'], 'custom_cache_settings')) {
            $enabled = isset($_POST['cache_enabled']) ? 1 : 0;
            update_option('custom_cache_enabled', $enabled);
            echo '<div class="notice notice-success is-dismissible"><p>Ayarlar kaydedildi!</p></div>';
        } else {
            echo '<div class="notice notice-error is-dismissible"><p>Güvenlik doğrulaması başarısız!</p></div>';
        }
    }

    $current_size = round(custom_cache_get_size() / (1024 * 1024), 2);
    $max_size     = MAX_CACHE_SIZE_MB;
    $file_count   = custom_cache_get_file_count();
    $cache_active = custom_cache_is_enabled();
?>
    <div class="wrap">
        <h1>Cache Yönetimi</h1>
        <style>
            .cc-admin-container {
                background: #fff;
                padding: 20px;
                border: 1px solid #ddd;
                box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
                margin-top: 20px;
            }

            .cc-admin-table {
                width: 100%;
                border-collapse: collapse;
            }

            .cc-admin-table th,
            .cc-admin-table td {
                text-align: left;
                padding: 10px;
                border-bottom: 1px solid #eee;
            }

            .cc-admin-actions {
                margin-top: 20px;
            }

            .cc-admin-form {
                margin-top: 20px;
            }
        </style>
        <div class="cc-admin-container">
            <table class="cc-admin-table">
                <tr>
                    <th>Mevcut Cache Boyutu</th>
                    <td><?php echo $current_size; ?> MB</td>
                </tr>
                <tr>
                    <th>Maksimum Cache Boyutu</th>
                    <td><?php echo $max_size; ?> MB</td>
                </tr>
                <tr>
                    <th>Önbellekteki Dosya Sayısı</th>
                    <td><?php echo $file_count; ?></td>
                </tr>
                <tr>
                    <th>Cache Durumu</th>
                    <td><?php echo ($cache_active ? 'Aktif' : 'Pasif'); ?></td>
                </tr>
            </table>
            <div class="cc-admin-actions">
                <!-- Önbelleği Temizle -->
                <form method="post">
                    <?php wp_nonce_field('custom_cache_clear', 'custom_cache_nonce'); ?>
                    <?php submit_button('Önbelleği Temizle', 'primary', 'clear_cache'); ?>
                </form>
            </div>
            <div class="cc-admin-form">
                <!-- Cache Ayarları -->
                <form method="post">
                    <?php wp_nonce_field('custom_cache_settings', 'custom_cache_settings_nonce'); ?>
                    <p>
                        <label for="cache_enabled"><strong>Cache Aktif:</strong></label>
                        <input type="checkbox" id="cache_enabled" name="cache_enabled" value="1" <?php checked($cache_active, 1); ?>>
                    </p>
                    <?php submit_button('Ayarları Kaydet', 'secondary', 'update_cache_settings'); ?>
                </form>
            </div>
        </div>
    </div>
<?php
}
?>
Cevapla