<?php

/**
 * 以统一安全参数启动会话。
 */
function cmsStartSession()
{
    if (session_status() === PHP_SESSION_ACTIVE) {
        return;
    }

    $https = !empty($_SERVER['HTTPS']) && strtolower((string) $_SERVER['HTTPS']) !== 'off';
    session_set_cookie_params([
        'lifetime' => 0,
        'path' => '/',
        'secure' => $https,
        'httponly' => true,
        'samesite' => 'Lax',
    ]);
    session_start();
}

/**
 * 校验后台会话空闲时间，默认两小时。
 */
function cmsValidateAdminSession($timeout = 7200)
{
    if (empty($_SESSION['admin_id'])) {
        return true;
    }

    $now = time();
    if (!empty($_SESSION['last_activity']) && $now - intval($_SESSION['last_activity']) > $timeout) {
        $_SESSION = [];
        if (ini_get('session.use_cookies')) {
            $params = session_get_cookie_params();
            setcookie(session_name(), '', $now - 42000, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
        }
        session_destroy();
        return false;
    }

    $_SESSION['last_activity'] = $now;
    return true;
}

