<?php
/*
'软件名称：苹果CMS 源码库：https://github.com/magicblack
'--------------------------------------------------------
'Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
'遵循Apache2开源协议发布，并提供免费使用。
'--------------------------------------------------------
*/
header('Content-Type:text/html;charset=utf-8');

// === 关键：使用回调型输出缓冲，在真正发送前计算哈希并设置响应头 ===
ob_start(function ($buffer) {
    
    // 可选：只在前台页面启用（跳过后台）
    $uri = $_SERVER['REQUEST_URI'] ?? '';
    if (stripos($uri, '/admin.php') !== false||stripos($uri, '/api.php') !== false) {
        return $buffer;
    }

    // 识别 HTML 被 JSON 字符串化（最典型问题）
    if (
        strlen($buffer) > 10 &&
        $buffer[0] === '"' &&
        substr($buffer, -1) === '"' &&
        strpos($buffer, '<!DOCTYPE') !== false
    ) {
        // // 去掉首尾引号
        // $buffer = substr($buffer, 1, -1);

        // // 还原 json_encode 的转义
        // $buffer = str_replace('\"', '"', $buffer);
        // $buffer = str_replace('\\/', '/', $buffer);

        // // 如果有多重转义，继续解一次
        // $buffer = preg_replace('/\\\\+\"/', '"', $buffer);
        
        $decoded = json_decode($buffer, true);
        // 只有解码成功才替换
        if (json_last_error() === JSON_ERROR_NONE && is_string($decoded)) {
            $buffer = $decoded;
        }
    }
    
    // 非 HEAD、且有内容时再处理
    if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'HEAD' || $buffer === '') {
        return $buffer;
    }

    // 读取 Content-Type（如果业务层改过，就以业务层为准）
    $ctype = 'text/html';
    foreach (headers_list() as $h) {
        if (stripos($h, 'Content-Type:') === 0) {
            $ctype = trim(substr($h, strlen('Content-Type:')));
            break;
        }
    }

    // 仅对文本/JSON/JS 这类内容加哈希，避免二进制大文件占内存
    if (preg_match('#^(text/|application/(json|javascript))#i', $ctype)) {
        $raw = hash('sha256', $buffer, true);
        $b64 = base64_encode($raw);
        header('X-Content-Hash256: ' . $b64, true);
    }

    return $buffer; // 一定要返回内容
});

// 检测PHP环境
if (version_compare(PHP_VERSION, '5.5.0', '<')) die('PHP版本需要>=5.5，请升级【PHP version requires > = 5.5，please upgrade】');
// 超时时间
@ini_set('max_execution_time', '0');
// 内存限制 取消内存限制
@ini_set("memory_limit", '-1');

// 定义应用目录
define('ROOT_PATH', __DIR__ . '/');
define('APP_PATH', __DIR__ . '/application/');
define('MAC_COMM', __DIR__ . '/application/common/common/');
define('MAC_HOME_COMM', __DIR__ . '/application/index/common/');
define('MAC_ADMIN_COMM', __DIR__ . '/application/admin/common/');
define('MAC_START_TIME', microtime(true));
define('BIND_MODULE', 'index');
define('ENTRANCE', 'index');
$in_file = rtrim($_SERVER['SCRIPT_NAME'], '/');
if (substr($in_file, strlen($in_file) - 4) !== '.php') {
    $in_file = substr($in_file, 0, strpos($in_file, '.php')) . '.php';
}
define('IN_FILE', $in_file);

if (!is_file('./application/data/install/install.lock')) {
    header("Location: ./install.php");
    // 回调缓冲会在这里统一处理/发送，无需手动 ob_end_clean
    exit;
}

if (!@mb_check_encoding($_SERVER['PATH_INFO'] ?? '', 'utf-8')) {
    $_SERVER['PATH_INFO'] = @mb_convert_encoding($_SERVER['PATH_INFO'], 'UTF-8', 'GBK');
}

// 加载框架引导文件（此过程产生的所有输出都会先进入缓冲回调）
require __DIR__ . '/thinkphp/start.php';

// 让缓冲回调运行并把内容送给客户端
// （也可以省略这行让 PHP 在请求结束时自动 flush）
ob_end_flush();
