<?php
// CI 3.1.4 Gadget Chain Test
// Looking for usable __destruct, __wakeup, __toString chains

// Simulate CI environment
define('BASEPATH', './system/');
define('APPPATH', './application/');

// Load necessary files
error_reporting(E_ALL);

echo "=== CI 3.1.4 Gadget Chain Analysis ===\n\n";

// Check Email class
$email_file = './system/libraries/Email.php';
if (file_exists($email_file)) {
    $content = file_get_contents($email_file);
    
    if (preg_match('/__destruct\s*\([^)]*\)\s*{([^}]+)}/', $content, $match)) {
        echo "Email __destruct:\n";
        echo trim($match[1]) . "\n\n";
    }
}

// Check Driver class
$driver_file = './system/libraries/Driver.php';
if (file_exists($driver_file)) {
    $content = file_get_contents($driver_file);
    
    if (preg_match('/__call\s*\([^)]*\)\s*{(.{0,500})}/s', $content, $match)) {
        echo "Driver __call:\n";
        echo trim($match[1]) . "\n\n";
    }
}

// Check all cache drivers
$cache_dir = './system/libraries/Cache/drivers/';
if (is_dir($cache_dir)) {
    $files = glob($cache_dir . '*.php');
    foreach ($files as $file) {
        $content = file_get_contents($file);
        $basename = basename($file);
        
        if (preg_match('/__destruct\s*\([^)]*\)\s*{([^}]+)}/', $content, $match)) {
            echo "$basename __destruct:\n";
            echo trim($match[1]) . "\n\n";
        }
    }
}

echo "=== Potential Chains ===\n";
echo "1. CI_Cache_redis->__destruct() calls \$this->_redis->close()\n";
echo "   If _redis is replaced with object having close() that executes code\n\n";

echo "2. CI_Driver->__call() calls call_user_func_array(\n";
echo "   array(\$this->_parent, \$method), \$args)\n";
echo "   If _parent and _methods are controlled, arbitrary method call possible\n\n";

