<?php
/**
 * 炎酷CMS - 后台登录验证码
 * 优先 GD 图片验证码；无 GD 扩展时回退算术题（文本输出），答案均存 session
 */
define('YKCMS', 1);
session_start();

if (function_exists('imagecreatetruecolor')) {
    // GD 图片验证码：4 位数字字母
    $chars = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789';
    $code = '';
    for ($i = 0; $i < 4; $i++) {
        $code .= $chars[mt_rand(0, strlen($chars) - 1)];
    }
    $_SESSION['yk_captcha'] = strtolower($code);

    $w = 120; $h = 42;
    $img = imagecreatetruecolor($w, $h);
    $bg = imagecolorallocate($img, 245, 247, 250);
    imagefill($img, 0, 0, $bg);
    // 干扰线
    for ($i = 0; $i < 5; $i++) {
        $c = imagecolorallocate($img, mt_rand(150, 220), mt_rand(150, 220), mt_rand(150, 220));
        imageline($img, mt_rand(0, $w), mt_rand(0, $h), mt_rand(0, $w), mt_rand(0, $h), $c);
    }
    // 字符
    for ($i = 0; $i < 4; $i++) {
        $c = imagecolorallocate($img, mt_rand(30, 120), mt_rand(30, 120), mt_rand(30, 160));
        imagestring($img, 5, 12 + $i * 26, mt_rand(8, 18), $code[$i], $c);
    }
    // 干扰点
    for ($i = 0; $i < 60; $i++) {
        $c = imagecolorallocate($img, mt_rand(120, 220), mt_rand(120, 220), mt_rand(120, 220));
        imagesetpixel($img, mt_rand(0, $w - 1), mt_rand(0, $h - 1), $c);
    }
    header('Content-Type: image/png');
    header('Cache-Control: no-store, no-cache');
    imagepng($img);
    imagedestroy($img);
    exit;
}

// 无 GD：算术题回退，答案存 session，输出纯文本
$a = mt_rand(1, 9);
$b = mt_rand(1, 9);
$_SESSION['yk_captcha'] = (string)($a + $b);
header('Content-Type: text/plain; charset=utf-8');
header('Cache-Control: no-store, no-cache');
echo $a . ' + ' . $b . ' = ?';
