summaryrefslogtreecommitdiff
path: root/captcha.php
blob: 3629cd0db5b7c7dea40443ae9363a27889cbe822 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?php
include_once "{$_SERVER['DOCUMENT_ROOT']}/lib/config.php";
include_once "{$_SERVER['DOCUMENT_ROOT']}/lib/alert.php";
include_once "{$_SERVER['DOCUMENT_ROOT']}/lib/captcha.php";
include_once "{$_SERVER['DOCUMENT_ROOT']}/lib/utils.php";

session_start();

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["answer"])) {
    if ($_POST["answer"] == ($_SESSION["captcha_word"] ?? "")) {
        $_SESSION["captcha_solved"] = true;
        echo json_response([
            "status_code" => 200,
            "message" => "Solved!",
            "data" => null
        ]);
    } else {
        echo json_response([
            "status_code" => 400,
            "message" => "Wrong answer!",
            "data" => null
        ], 400);
    }
    exit;
}

$file_folder = $_SERVER["DOCUMENT_ROOT"] . '/static/img/captcha';

if (!CONFIG['captcha']['enable'] || ($_SESSION["captcha_solved"] ?? false) || !is_dir($file_folder)) {
    $_SESSION["captcha_solved"] = true;
    echo json_response([
        "status_code" => 200,
        "message" => "No need to solve captcha",
        "data" => null
    ]);
    exit;
}

$files = scandir($file_folder);
array_splice($files, 0, 2);

$filename = $files[random_int(0, count($files) - 1)];
$filename = basename($filename, ".png");

$_SESSION["captcha_word"] = $filename;

$image = generate_image_captcha(
    CONFIG['captcha']['x'],
    CONFIG['captcha']['y'],
    random_int(1, 3),
    $filename,
    $file_folder
);

echo json_response([
    "status_code" => 200,
    "message" => null,
    "data" => $image
]);