<?php
/**
 * 芋头CMS
 * ============================================================================
 * 版权所有 2016-2028 沅陵县乌托邦网络服务有限公司，并保留所有权利。
 * 网站地址: http://www.yutoucms.cn
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 芋头 <mxgsf@qq.com>
 * Date: 2026-5-20
 */


$action = isset($_GET['action']) ? $_GET['action'] : 'config';

if ($action === 'config') {
    // UEditor 初始化配置
    header('Content-Type:application/json');
    $config = [
        /* 上传配置 */
        "imageActionName" => "uploadimage",
        "imageFieldName" => "upfile",
        "imageMaxSize" => 2048000,
        "imageAllowFiles" => [".png", ".jpg", ".jpeg", ".gif", ".bmp"],
        "imageUrlPrefix" => "",
        "imagePathFormat" => "/uploads/{yyyy}{mm}{dd}/{time}{rand}",
        /* 涂鸦配置 */
        "scrawlActionName" => "uploadscrawl",
        "scrawlFieldName" => "upfile",
        "scrawlMaxSize" => 2048000,
        "scrawlUrlPrefix" => "",
        "scrawlPathFormat" => "/uploads/{yyyy}{mm}{dd}/{time}{rand}",
    ];
    echo json_encode($config);
    exit;
}

if ($action === 'uploadimage') {
    header('Content-Type:application/json');
    if (empty($_FILES['upfile'])) {
        echo json_encode(['state'=>'ERROR', 'msg'=>'没有上传文件']);
        exit;
    }
    $file = $_FILES['upfile'];
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    $allowed = ['png','jpg','jpeg','gif','bmp','webp'];
    if (!in_array($ext, $allowed)) {
        echo json_encode(['state'=>'ERROR', 'msg'=>'不支持的文件格式']);
        exit;
    }
    if ($file['size'] > 5*1024*1024) {
        echo json_encode(['state'=>'ERROR', 'msg'=>'文件大小超过5MB']);
        exit;
    }
    $dir = dirname(__DIR__, 2) . '/uploads/' . date('Ymd');
    if (!is_dir($dir)) mkdir($dir, 0755, true);
    $filename = uniqid() . '.' . $ext;
    $filepath = $dir . '/' . $filename;
    if (move_uploaded_file($file['tmp_name'], $filepath)) {
        $url = '/uploads/' . date('Ymd') . '/' . $filename;
        echo json_encode([
            'state'=>'SUCCESS',
            'url'=>$url,
            'title'=>$filename,
            'original'=>$file['name'],
        ]);
    } else {
        echo json_encode(['state'=>'ERROR', 'msg'=>'保存文件失败']);
    }
    exit;
}

echo json_encode(['state'=>'ERROR', 'msg'=>'未知操作']);
