<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2019 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------

// [ 应用入口文件 ]
namespace think;

$server = isset($_REQUEST['server']) || isset($_SERVER['HTTP_SERVER']) || substr($_SERVER['REQUEST_URI'], 1, 9) == 'index.php' || $_SERVER['REQUEST_METHOD'] == 'OPTIONS';
if (!$server) {
    /*
     * 用户访问前端
     * 不在tp加载后判断，为了安全的使用 exit()（常驻内存运行时不走本文件）
     */
    $rootPath = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR;

    // 安装检测-s
    if (!is_file($rootPath . 'install.lock') && is_file($rootPath . 'install' . DIRECTORY_SEPARATOR . 'index.html')) {
        header("location:" . DIRECTORY_SEPARATOR . 'install' . DIRECTORY_SEPARATOR);
        exit();
    }
    // 安装检测-e

    // 检测是否已编译前端（如果存在 index.html，则访问）-s
    if (is_file($rootPath . 'index.html')) {
        header("location:" . DIRECTORY_SEPARATOR . 'index.html');
        exit();
    }
    // 检测是否已编译前端-e
}

/*
 * 本地上传文件 URL 形如 /storage/delivery/... ，须在此直接读盘输出。
 * 否则未配置 Nginx 静态别名时，请求会落入路由被当成「Storage 控制器」而 404。
 */
$__reqUri = $_SERVER['REQUEST_URI'] ?? '/';
$__path  = parse_url($__reqUri, PHP_URL_PATH);
if (is_string($__path) && str_starts_with($__path, '/storage/')) {
    $__base = realpath(__DIR__ . DIRECTORY_SEPARATOR . 'storage');
    if ($__base !== false) {
        $__sub = str_replace("\0", '', substr($__path, strlen('/storage')));
        $__sub = str_replace('\\', '/', ltrim($__sub, '/'));
        if ($__sub === '' || str_contains($__sub, '..')) {
            http_response_code(404);
            header('Content-Type: text/plain; charset=utf-8');
            exit('File not found');
        }
        $__file = realpath($__base . '/' . $__sub);
        if ($__file !== false && str_starts_with($__file, $__base) && is_file($__file) && is_readable($__file)) {
            $__mime = function_exists('mime_content_type') ? @mime_content_type($__file) : '';
            if (!$__mime) {
                $__mime = 'application/octet-stream';
            }
            header('Content-Type: ' . $__mime);
            header('Content-Length: ' . (string) filesize($__file));
            readfile($__file);
            exit;
        }
    }
    http_response_code(404);
    header('Content-Type: text/plain; charset=utf-8');
    exit('File not found');
}

require __DIR__ . '/../vendor/autoload.php';

// 执行HTTP应用并响应
$http = (new App())->http;

$response = $http->run();

$response->send();

$http->end($response);
