<?php

/**
 * 文件管理类
 * Date: 2026-07-24
 * Author: 小新
 * SystemName: XiaoPHP
 */

namespace XiaoPHP\System;

class File
{
    private $storageRoot;
    private $maxSize = 2 * 1024 * 1024; // 默认2MB

    public function __construct()
    {
        $this->storageRoot = SYS_PATH . '/../Resources/PHPFile';
    }

    public function upload($allowedTypes = [], $subdir = '', $randomName = true)
    {

        if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
            return $this->res(1, '上传失败：未收到文件或上传出错');
        }
        $file = $_FILES['file'];
        if ($file['size'] > $this->maxSize) {
            return $this->res(1, '文件过大（最大' . ($this->maxSize/1024/1024) . 'MB）');
        }


        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mime = finfo_file($finfo, $file['tmp_name']);
        finfo_close($finfo);
        if ($allowedTypes && !in_array($mime, $allowedTypes, true)) {
            return $this->res(1, '不允许的文件类型：' . $mime);
        }


        if (!$this->scanPhp($file['tmp_name'])) {
            return $this->res(1, '文件含有恶意PHP代码');
        }


        $subdir = trim($subdir, '/');
        $targetDir = $this->storageRoot . ($subdir ? '/' . $subdir : '');
        if (!is_dir($targetDir) && !mkdir($targetDir, 0755, true)) {
            return $this->res(1, '无法创建目录：' . $targetDir);
        }


        $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
        if ($randomName) {
            $newName = bin2hex(random_bytes(16)) . ($ext ? '.' . $ext : '');
        } else {
            $newName = preg_replace('/[^a-zA-Z0-9_\-.]/', '', basename($file['name']));
            if (!$newName) $newName = 'file';
        }
        $targetPath = $targetDir . '/' . $newName;


        if (!move_uploaded_file($file['tmp_name'], $targetPath)) {
            return $this->res(1, '文件移动失败');
        }

        $metaFile = '';
        if ($randomName) {
            $meta = ['filename' => $newName, 'md5' => md5_file($targetPath)];
            $metaName = preg_replace('/[^a-zA-Z0-9_\-.]/', '', $file['name']) ?: 'file';
            $metaFile = $targetDir . '/' . $metaName . '.json';
            file_put_contents($metaFile, json_encode($meta, JSON_PRETTY_PRINT));
        }

        return $this->res(0, '上传成功', ['filename' => $newName, 'metadata' => $metaFile]);
    }


    public function getInfo($path)
    {
        $real = $this->resolvePath($path);
        if (!$real) {
            return $this->res(1, '文件不存在');
        }
        $info = [
            'size' => filesize($real),
            'mtime' => filemtime($real),
            'mime' => mime_content_type($real),
            'md5' => md5_file($real),
        ];
        
        $dir = dirname($real);
        $base = basename($real);
        foreach (glob($dir . '/*.json') as $f) {
            $data = json_decode(file_get_contents($f), true);
            if (isset($data['filename']) && $data['filename'] === $base) {
                $info['metadata'] = $data;
                break;
            }
        }
        return $this->res(0, '获取成功', ['info' => $info]);
    }


    public function read($path)
    {
        $real = $this->resolvePath($path);
        if (!$real) {
            return $this->res(1, '文件不存在');
        }
        return $this->res(0, '读取成功', ['content' => file_get_contents($real)]);
    }


    public function delete($path)
    {
        $real = $this->resolvePath($path);
        if (!$real) {
            return $this->res(1, '文件不存在');
        }
        
        $dir = dirname($real);
        $base = basename($real);
        foreach (glob($dir . '/*.json') as $f) {
            $data = json_decode(file_get_contents($f), true);
            if (isset($data['filename']) && $data['filename'] === $base) {
                unlink($f);
                break;
            }
        }
        if (unlink($real)) {
            return $this->res(0, '删除成功');
        } else {
            return $this->res(1, '删除失败');
        }
    }

   

    private function resolvePath($path)
    {
        $full = $this->storageRoot . '/' . ltrim($path, '/');
        $real = realpath($full);
        if ($real && strpos($real, $this->storageRoot) === 0) {
            return $real;
        }
        return false;
    }

    private function scanPhp($tmp)
    {
        if (!is_readable($tmp)) return false;
        $h = fopen($tmp, 'rb');
        if (!$h) return false;
        $content = fread($h, 4096);
        fclose($h);
        return !preg_match('/<\?(?:php|=)?/i', $content) 
            && !preg_match('/<script\s+language\s*=\s*["\']?php["\']?/i', $content);
    }

    private function res($code, $msg, $extra = [])
    {
        return array_merge(['code' => $code, 'msg' => $msg], $extra);
    }
}