<?php

// Function to scan directory and its subdirectories
function scanDirectory($dir) {
    $files = [];
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));

    foreach ($iterator as $fileinfo) {
        if ($fileinfo->isFile()) {
            $extension = pathinfo($fileinfo->getFilename(), PATHINFO_EXTENSION);
            if (in_array($extension, ['js'])) {            
                $files[] = $fileinfo->getPathname();
            }
        }
    }

    return $files;
}

// Function to remove malicious script from a file
function cleanFile($file) {
    $content = file_get_contents($file);
    
     $maliciousScript = '';

    // $maliciousScript = '/function\s_0x3023\(_0x562006,_0x1334d6\).*?document\[_0x365b\[0x23\]\]\(_0x365b\[0x22\],_0x978889\);\}\(\);/s';
    
    // $maliciousScript = '/";

    if (preg_match($maliciousScript, $content)) {
        $cleanContent = preg_replace($maliciousScript, '', $content);
        file_put_contents($file, $cleanContent);
        echo "Cleaned it: $file\n"."<br/>";
    } else {
        echo "yehhh No malicious script found in: $file\n"."<br/>";
    }
 }


 function removeTextFromFile($file, $pattern, $idx1, $idx2) {
    $content = file_get_contents($file);

    $startIdx = strpos($content, $idx1);
    $endIdx = strpos($content, $idx2, $startIdx);

    if ($startIdx !== false && $endIdx !== false) {
        $textToRemove = substr($content, $startIdx, $endIdx - $startIdx + strlen($idx2));
        $cleanContent = str_replace($textToRemove, '', $content);
        
        file_put_contents($file, $cleanContent);
        return true; // Text successfully removed
    } else {
        return false; // Text not found
    }
}

// Pattern and indices to match
$pattern = '/function\s+_0x3023\([^)]*\)\s*\{[^}]*\}\s*_0x978889\(\);\s*/s';
$idx1 = 'function _0x3023';  // Example start index
$idx2 = ',_0x978889);}());'; // Example end index

// Directory to scan
$directoryToScan = './';

// Get all relevant files in the directory and subdirectories
$files = scanDirectory($directoryToScan);

// Clean each file
foreach ($files as $file) {
    //cleanFile($file);
    echo $file;
    echo "<br/>";
    if (removeTextFromFile($file, $pattern, $idx1, $idx2)) {
        echo "Removed text from: $file\n";        
    }
}
echo "Cleaning completed.\n";