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

require_once dirname(__DIR__) . '/main.php';header('Content-Type: application/json');$allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];$maxSize = 5 * 1024 * 1024; // 5MBif ($_SERVER['REQUEST_METHOD'] !== 'POST') {    echo json_encode(['code' => 405, 'msg' => '鍙敮鎸丳OST璇锋眰']);    exit;}if (empty($_FILES['file'])) {    echo json_encode(['code' => 400, 'msg' => '娌℃湁涓婁紶鏂囦欢']);    exit;}$file = $_FILES['file'];if ($file['error'] !== UPLOAD_ERR_OK) {    $errors = [        UPLOAD_ERR_INI_SIZE => '鏂囦欢澶у皬瓒呰繃鏈嶅姟鍣ㄩ檺鍒?,        UPLOAD_ERR_FORM_SIZE => '鏂囦欢澶у皬瓒呰繃琛ㄥ崟闄愬埗',        UPLOAD_ERR_PARTIAL => '鏂囦欢鍙湁閮ㄥ垎涓婁紶',        UPLOAD_ERR_NO_FILE => '娌℃湁鏂囦欢琚笂浼?,        UPLOAD_ERR_NO_TMP_DIR => '鏈嶅姟鍣ㄧ己灏戜复鏃剁洰褰?,        UPLOAD_ERR_CANT_WRITE => '鏃犳硶鍐欏叆纾佺洏',        UPLOAD_ERR_EXTENSION => '鏂囦欢涓婁紶琚墿灞曢樆姝?,    ];    echo json_encode(['code' => 400, 'msg' => $errors[$file['error']] ?? '鏈煡閿欒']);    exit;}if ($file['size'] > $maxSize) {    echo json_encode(['code' => 400, 'msg' => '鏂囦欢澶у皬涓嶈兘瓒呰繃5MB']);    exit;}$finfo = finfo_open(FILEINFO_MIME_TYPE);$mimeType = finfo_file($finfo, $file['tmp_name']);finfo_close($finfo);if (!in_array($mimeType, $allowedTypes)) {    echo json_encode(['code' => 400, 'msg' => '鍙敮鎸?JPG/PNG/GIF/WebP 鏍煎紡']);    exit;}$uploadDir = dirname(__DIR__) . '/../uploads/' . date('Ymd') . '/';if (!is_dir($uploadDir)) {    mkdir($uploadDir, 0755, true);}$ext = pathinfo($file['name'], PATHINFO_EXTENSION);$newName = uniqid() . '_' . time() . '.' . $ext;$destPath = $uploadDir . $newName;if (move_uploaded_file($file['tmp_name'], $destPath)) {    $siteUrl = rtrim(getSiteConfig('site_url', 'http://' . $_SERVER['HTTP_HOST']), '/');    $relativePath = '/uploads/' . date('Ymd') . '/' . $newName;    echo json_encode([        'code' => 200,        'msg' => '涓婁紶鎴愬姛',        'data' => [            'url' => $siteUrl . $relativePath,            'path' => $relativePath        ]    ]);} else {    echo json_encode(['code' => 500, 'msg' => '鏂囦欢淇濆瓨澶辫触']);}