<?php
/**
 * CMS 域名授权校验模块
 * 使用方法：在需要校验的页面开头 require_once 'includes/license.php';
 */

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

define('LICENSE_API_URL', 'https://cms.barju.cn/api/license_check.php');
define('LICENSE_APPLY_URL', 'https://cms.barju.cn/license-apply.html');
define('LICENSE_FILE', __DIR__ . '/../license.dat');
define('LICENSE_AES_KEY', 'BarJuCMS2026LicenseKey!'); // 16/24/32 字节 AES 密钥

/**
 * AES 加密
 */
function license_encrypt($data) {
    $key = LICENSE_AES_KEY;
    $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('AES-128-CBC'));
    $encrypted = openssl_encrypt(json_encode($data), 'AES-128-CBC', $key, 0, $iv);
    return base64_encode($iv . $encrypted);
}

/**
 * AES 解密
 */
function license_decrypt($data) {
    $key = LICENSE_AES_KEY;
    $data = base64_decode($data);
    $iv_length = openssl_cipher_iv_length('AES-128-CBC');
    $iv = substr($data, 0, $iv_length);
    $encrypted = substr($data, $iv_length);
    $decrypted = openssl_decrypt($encrypted, 'AES-128-CBC', $key, 0, $iv);
    return json_decode($decrypted, true);
}

/**
 * 获取当前域名
 */
function license_get_domain() {
    $domain = $_SERVER['HTTP_HOST'] ?? '';
    return strtolower($domain);
}

/**
 * 读取本地授权文件
 */
function license_read_local() {
    if (!file_exists(LICENSE_FILE)) {
        return null;
    }
    $content = file_get_contents(LICENSE_FILE);
    if (empty($content)) {
        return null;
    }
    $data = license_decrypt($content);
    return $data;
}

/**
 * 保存授权文件到本地
 */
function license_save_local($data) {
    $content = license_encrypt($data);
    return file_put_contents(LICENSE_FILE, $content) !== false;
}

/**
 * 远程校验授权
 */
function license_check_remote($domain = '') {
    if (empty($domain)) {
        $domain = license_get_domain();
    }
    
    $url = LICENSE_API_URL . '?domain=' . urlencode($domain);
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $response = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);
    
    if ($error) {
        // 网络错误，使用本地缓存
        return license_read_local();
    }
    
    $data = json_decode($response, true);
    if ($data && $data['success']) {
        // 远程校验通过，更新本地文件
        license_save_local($data['data']);
        return $data['data'];
    }
    
    return null;
}

/**
 * 申请授权（调用远程接口）
 */
function license_apply($domain = '') {
    if (empty($domain)) {
        $domain = license_get_domain();
    }
    
    $url = 'https://cms.barju.cn/api/license_apply.php';
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['domain' => $domain]));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $response = curl_exec($ch);
    curl_close($ch);
    
    $data = json_decode($response, true);
    if ($data && $data['success']) {
        license_save_local($data['data']);
        return $data;
    }
    
    return $data; // 返回错误信息
}

/**
 * 全局授权校验（在所有 admin 页面调用）
 * 返回值：true=已授权，false=未授权
 */
function license_check() {
    // 公开页面不校验
    $script = basename($_SERVER['PHP_SELF']);
    $public_pages = ['login.php', 'license.php'];
    if (in_array($script, $public_pages)) {
        return true;
    }
    
    // 先读本地授权
    $local = license_read_local();
    $domain = license_get_domain();
    
    if ($local && isset($local['domain']) && $local['domain'] === $domain) {
        // 本地有授权，检查是否过期
        $expires_at = strtotime($local['expires_at']);
        if ($expires_at > time()) {
            // 未过期，定时同步远程状态（每6小时同步一次）
            $last_check = $local['last_check'] ?? 0;
            if (time() - $last_check > 21600) { // 6小时
                $remote = license_check_remote($domain);
                if ($remote) {
                    $remote['last_check'] = time();
                    license_save_local($remote);
                }
            }
            return true;
        }
    }
    
    // 本地无授权或已过期，尝试远程校验
    $remote = license_check_remote($domain);
    if ($remote) {
        $remote['last_check'] = time();
        license_save_local($remote);
        return true;
    }
    
    // 未授权，跳转授权页面
    if (strpos($_SERVER['PHP_SELF'], '/admin/') !== false) {
        header('Location: /admin/license.php');
        exit;
    }
    
    return false;
}
