xref: /webtrees/app/Services/CaptchaService.php (revision 5bfc689774bb9a6401271c4ed15a6d50652c991b)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2022 webtrees development team
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Services;
21
22use Fisharebest\Webtrees\Session;
23use Fisharebest\Webtrees\Validator;
24use Psr\Http\Message\ServerRequestInterface;
25use Ramsey\Uuid\Uuid;
26
27use function view;
28
29/**
30 * Completely Automated Public Turing test to tell Computers and Humans Apart.
31 */
32class CaptchaService
33{
34    // If the form is completed faster than this, then suspect a robot.
35    private const MINIMUM_FORM_TIME = 3.0;
36
37    /**
38     * Create the captcha
39     *
40     * @return string
41     */
42    public function createCaptcha(): string
43    {
44        $x = Uuid::uuid4()->toString();
45        $y = Uuid::uuid4()->toString();
46        $z = Uuid::uuid4()->toString();
47
48        Session::put('captcha-t', microtime(true));
49        Session::put('captcha-x', $x);
50        Session::put('captcha-y', $y);
51        Session::put('captcha-z', $z);
52
53        return view('captcha', [
54            'x' => $x,
55            'y' => $y,
56            'z' => $z,
57        ]);
58    }
59
60    /**
61     * Check the user's response.
62     *
63     * @param ServerRequestInterface $request
64     *
65     * @return bool
66     */
67    public function isRobot(ServerRequestInterface $request): bool
68    {
69        $t = Session::pull('captcha-t');
70        $x = Session::pull('captcha-x');
71        $y = Session::pull('captcha-y');
72        $z = Session::pull('captcha-z');
73
74        assert(is_int($t));
75        assert(is_string($x));
76        assert(is_string($y));
77        assert(is_string($z));
78
79        $value_x = Validator::parsedBody($request)->string($x, '');
80        $value_y = Validator::parsedBody($request)->string($y, '');
81
82        // The captcha uses javascript to copy value z from field y to field x.
83        // Expect it in both fields.
84        if ($value_x !== $z || $value_y !== $z) {
85            return true;
86        }
87
88        // If the form was returned too quickly, the probably a robot.
89        return microtime(true) < $t + self::MINIMUM_FORM_TIME;
90    }
91}
92