<?php
/**
 * 芋头CMS UEditor 控制器
 * ============================================================================
 * 版权所有 2016-2028 沅陵县乌托邦网络服务有限公司，并保留所有权利。
 * 网站地址: http://www.yutoucms.cn
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷。
 * ============================================================================
 * Author: 芋头 <mxgsf@qq.com>
 * Date: 2026-6-4
 */
header('Content-Type: application/json; charset=utf-8');

$action = isset($_GET['action']) ? trim($_GET['action']) : 'config';
$configPath = __DIR__ . '/config.json';
$configRaw = file_exists($configPath) ? file_get_contents($configPath) : '{}';
$configRaw = preg_replace('!\/\*.*?\*\/!s', '', $configRaw);
$config = json_decode($configRaw, true);
if (!is_array($config)) $config = [];

function ue_out($arr) {
    echo json_encode($arr, JSON_UNESCAPED_UNICODE);
    exit;
}

if ($action === 'config') {
    ue_out($config);
}

$map = [
    'uploadimage' => ['field' => $config['imageFieldName'] ?? 'upfile', 'dir' => '/uploads/' . date('Ymd') . '/', 'types' => ['png','jpg','jpeg','gif','bmp','webp','ico','svg'], 'max' => 20 * 1024 * 1024],
    'uploadscrawl' => ['field' => $config['scrawlFieldName'] ?? 'upfile', 'dir' => '/uploads/' . date('Ymd') . '/', 'types' => ['png'], 'max' => 20 * 1024 * 1024],
    'uploadvideo' => ['field' => $config['videoFieldName'] ?? 'upfile', 'dir' => '/uploads/video/' . date('Ym') . '/', 'types' => ['flv','swf','mkv','avi','rm','rmvb','mpeg','mpg','ogg','ogv','mov','wmv','mp4','webm','mp3','wav','mid'], 'max' => 525000000],
    'uploadfile'  => ['field' => $config['fileFieldName'] ?? 'upfile',  'dir' => '/uploads/file/' . date('Ym') . '/', 'types' => ['png','jpg','jpeg','gif','bmp','ico','webp','flv','swf','mkv','avi','rm','rmvb','mpeg','mpg','ogg','ogv','mov','wmv','mp4','webm','mp3','wav','mid','rar','zip','tar','gz','7z','bz2','cab','iso','svg','doc','docx','xls','xlsx','ppt','pptx','pdf','txt','md','xml'], 'max' => 525000000],
];

if ($action === 'listimage' || $action === 'listfile') {
    $isImage = $action === 'listimage';
    $baseRel = $isImage ? '/uploads/' : '/uploads/file/';
    $baseAbs = dirname(dirname(dirname(__DIR__))) . $baseRel;
    $allow = $isImage ? ['png','jpg','jpeg','gif','bmp','ico','webp','svg'] : ['png','jpg','jpeg','gif','bmp','ico','webp','flv','swf','mkv','avi','rm','rmvb','mpeg','mpg','ogg','ogv','mov','wmv','mp4','webm','mp3','wav','mid','rar','zip','tar','gz','7z','bz2','cab','iso','svg','doc','docx','xls','xlsx','ppt','pptx','pdf','txt','md','xml'];
    $files = [];
    if (is_dir($baseAbs)) {
        $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($baseAbs, FilesystemIterator::SKIP_DOTS));
        foreach ($it as $f) {
            if (!$f->isFile()) continue;
            $ext = strtolower(pathinfo($f->getFilename(), PATHINFO_EXTENSION));
            if (!in_array($ext, $allow)) continue;
            $full = str_replace('\\', '/', $f->getPathname());
            $root = str_replace('\\', '/', dirname(dirname(dirname(__DIR__))));
            $url = str_replace($root, '', $full);
            $files[] = ['url' => $url, 'mtime' => $f->getMTime()];
        }
    }
    usort($files, function($a,$b){ return $b['mtime'] - $a['mtime']; });
    ue_out(['state' => 'SUCCESS', 'list' => $files, 'start' => 0, 'total' => count($files)]);
}

if (!isset($map[$action])) {
    ue_out(['state' => '请求地址出错']);
}

$rule = $map[$action];
$field = $rule['field'];

if ($action === 'uploadscrawl' && !empty($_POST[$field])) {
    $img = $_POST[$field];
    $img = preg_replace('#^data:image/\w+;base64,#i', '', $img);
    $binary = base64_decode($img);
    if (!$binary) ue_out(['state' => '涂鸦内容为空']);
    $dirRel = $rule['dir'];
    $dirAbs = dirname(dirname(dirname(__DIR__))) . $dirRel;
    if (!is_dir($dirAbs)) mkdir($dirAbs, 0755, true);
    $name = uniqid() . '_' . time() . '.png';
    $path = $dirAbs . $name;
    file_put_contents($path, $binary);
    ue_out(['state' => 'SUCCESS', 'url' => $dirRel . $name, 'title' => $name, 'original' => 'scrawl.png']);
}

if (empty($_FILES[$field])) {
    ue_out(['state' => '没有上传文件']);
}
$file = $_FILES[$field];
if ($file['error'] !== UPLOAD_ERR_OK) {
    ue_out(['state' => '上传失败']);
}
if ($file['size'] > $rule['max']) {
    ue_out(['state' => '文件大小超限']);
}
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if (!in_array($ext, $rule['types'])) {
    ue_out(['state' => '文件格式不允许']);
}
$dirRel = $rule['dir'];
$dirAbs = dirname(dirname(dirname(__DIR__))) . $dirRel;
if (!is_dir($dirAbs)) mkdir($dirAbs, 0755, true);
$name = uniqid() . '_' . time() . '.' . $ext;
$dest = $dirAbs . $name;
if (!move_uploaded_file($file['tmp_name'], $dest)) {
    ue_out(['state' => '保存文件失败']);
}
ue_out(['state' => 'SUCCESS', 'url' => $dirRel . $name, 'title' => $name, 'original' => $file['name']]);
