Subversion Repositories oidplus

Rev

Rev 1022 | Rev 1086 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
702 daniel-mar 1
<?php
2
 
3
/*
4
 * OIDplus 2.0
1016 daniel-mar 5
 * Copyright 2019 - 2022 Daniel Marschall, ViaThinkSoft
702 daniel-mar 6
 *
7
 * Licensed under the Apache License, Version 2.0 (the "License");
8
 * you may not use this file except in compliance with the License.
9
 * You may obtain a copy of the License at
10
 *
11
 *     http://www.apache.org/licenses/LICENSE-2.0
12
 *
13
 * Unless required by applicable law or agreed to in writing, software
14
 * distributed under the License is distributed on an "AS IS" BASIS,
15
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
 * See the License for the specific language governing permissions and
17
 * limitations under the License.
18
 */
19
 
1050 daniel-mar 20
namespace ViaThinkSoft\OIDplus;
702 daniel-mar 21
 
22
class OIDplusCaptchaPluginRecaptcha extends OIDplusCaptchaPlugin {
23
 
1016 daniel-mar 24
        /*public*/ const RECAPTCHA_V2_CHECKBOX  = 1;
25
        /*public*/ const RECAPTCHA_V2_INVISIBLE = 2;
26
        /*public*/ const RECAPTCHA_V3           = 3;
27
 
702 daniel-mar 28
        public static function id(): string {
1016 daniel-mar 29
                return 'reCAPTCHA'; // TODO: Now it is called "reCAPTCHA"
702 daniel-mar 30
        }
31
 
1016 daniel-mar 32
        public function isVisible(): bool {
33
                return OIDplus::baseConfig()->getValue('RECAPTCHA_VERSION', self::RECAPTCHA_V2_CHECKBOX) == self::RECAPTCHA_V2_CHECKBOX;
709 daniel-mar 34
        }
35
 
702 daniel-mar 36
        public function captchaGenerate($header_text=null, $footer_text=null) {
1016 daniel-mar 37
                return '<noscript>'.
702 daniel-mar 38
                       '<p><font color="red">'._L('You need to enable JavaScript to solve the CAPTCHA.').'</font></p>'.
39
                       '</noscript>'.
1016 daniel-mar 40
                       (!$this->isVisible() || !$header_text ? '' : '<p>'.$header_text.'</p>').
41
                       '<div id="recaptcha"></div>'.
42
                       '<input type="hidden" id="oidplus-recaptcha-response" name="oidplus-recaptcha-response">'.
43
                       '<script>'.
44
//                     '    $("form").submit(function(e){'.
45
//                     // TODO: The form must not be submitted before recaptchaFinished() is called!
46
//                     '         event.preventDefault();'.
47
//                     '    });'.
48
                       '    var recaptchaLoaded = function() {'.
49
                       '        console.log("reCAPTCHA ready");'.
50
                       '        grecaptcha.render("recaptcha", {'.
51
                       '            "sitekey": "'.OIDplus::baseConfig()->getValue('RECAPTCHA_PUBLIC', '').'",'.
52
                       ($this->isVisible() ? '' :
53
                       '            "size": "invisible",').
54
                       '            "callback": function (token) {'. // TODO: also 'expired-callback' and 'error-callback'
55
                       '                console.log("reCAPTCHA solved");'.
56
                       '                document.getElementById("oidplus-recaptcha-response").value = token;'.
57
                       '            }'.
58
                       '        });'.
59
                       ($this->isVisible() ? '' :
60
                       '        grecaptcha.execute();').
61
                       '    };'.
62
                       '    var oidplus_captcha_response = function() {'.
63
                       '        return document.getElementById("oidplus-recaptcha-response").value;'.
64
                       '    };'.
65
                       '    var oidplus_captcha_reset = function() {'.
66
                       '        grecaptcha.reset();'.
67
                       ($this->isVisible() ? '' :
68
                       '        grecaptcha.execute();').
69
                       '    };'.
70
                       '</script>'.
71
                       '<script src="https://www.google.com/recaptcha/api.js?onload=recaptchaLoaded&render=explicit" async defer></script>'.
72
                       (!$this->isVisible() || !$footer_text ? '' : '<p>'.$footer_text.'</p>');
702 daniel-mar 73
        }
74
 
75
        public function captchaVerify($params, $fieldname=null) {
1001 daniel-mar 76
                $secret=OIDplus::baseConfig()->getValue('RECAPTCHA_PRIVATE', '');
77
 
1016 daniel-mar 78
                if (is_null($fieldname)) $fieldname = 'oidplus-recaptcha-response'; // no individual AJAX field name (created by oidplus_captcha_response()) means that it is a plain POST event (e.g. by oobe.php)
702 daniel-mar 79
                _CheckParamExists($params, $fieldname);
80
                $response=$params[$fieldname];
1016 daniel-mar 81
 
82
                $verify=url_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.urlencode($secret).'&response='.urlencode($response).'&remoteip='.urlencode($_SERVER['REMOTE_ADDR']));
702 daniel-mar 83
                if (!$verify) {
1016 daniel-mar 84
                        throw new OIDplusException(_L('CAPTCHA not successfully verified').' (Web request failed)');
702 daniel-mar 85
                }
1001 daniel-mar 86
                $captcha_success=@json_decode($verify);
1016 daniel-mar 87
                $SCORE_THRESHOLD = 0.5; // TODO: Make Score configurable (only V3)
88
                if (!$captcha_success) {
1022 daniel-mar 89
                        throw new OIDplusException(_L('CAPTCHA not successfully verified').' ('._L('JSON Decode failed').')');
702 daniel-mar 90
                }
1016 daniel-mar 91
                if ($captcha_success->success==false) {
1022 daniel-mar 92
                        throw new OIDplusException(_L('CAPTCHA not successfully verified').' ('._L('Failed').')');
1016 daniel-mar 93
                }
94
                if (isset($captcha_success->score) && ($captcha_success->score < $SCORE_THRESHOLD)) {
1022 daniel-mar 95
                        throw new OIDplusException(_L('CAPTCHA not successfully verified').' ('._L('Score %1 too low', $captcha_success->score).')');
1016 daniel-mar 96
                }
702 daniel-mar 97
        }
98
 
99
        public static function setupHTML(): string {
100
                return '<div id="CAPTCHAPLUGIN_PARAMS_RECAPTCHA">'.
101
                       '<p>(<a href="https://developers.google.com/recaptcha/intro" target="_blank">'._L('more information and obtain key').'</a>)</p>'.
1016 daniel-mar 102
                       '<p>'._L('reCAPTCHA Version').'<br><select id="recaptcha_version">'.
1050 daniel-mar 103
                       // Note: JavaScript will add "\ViaThinkSoft\OIDplus\OIDplusCaptchaPluginRecaptcha::" in front of the name
104
                       '    <option name="RECAPTCHA_V2_CHECKBOX">reCAPTCHA V2 Checkbox</option>'.
105
                       '    <option name="RECAPTCHA_V2_INVISIBLE">reCAPTCHA V2 Invisible</option>'.
106
                       '    <option name="RECAPTCHA_V3">reCAPTCHA V3</option>'.
1016 daniel-mar 107
                       '</select></p>'.
702 daniel-mar 108
                       '<p>'._L('reCAPTCHA Public key').'<br><input id="recaptcha_public" type="text" onkeypress="rebuild()" onkeyup="rebuild()"> <span id="recaptcha_public_warn"></span></p>'.
109
                       '<p>'._L('reCAPTCHA Private key').'<br><input id="recaptcha_private" type="text" onkeypress="rebuild()" onkeyup="rebuild()"> <span id="recaptcha_private_warn"></span></p>'.
110
                       '</div>';
111
        }
112
 
1001 daniel-mar 113
        function httpHeaderCheck(&$http_headers) {
114
                $http_headers["Content-Security-Policy"]["script-src"][] = "https://www.google.com/";
115
                $http_headers["Content-Security-Policy"]["script-src"][] = "https://www.gstatic.com/";
1015 daniel-mar 116
                $http_headers["Content-Security-Policy"]["img-src"][]    = "https://www.google.com/";
117
                $http_headers["Content-Security-Policy"]["img-src"][]    = "https://www.gstatic.com/";
118
                $http_headers["Content-Security-Policy"]["frame-src"][]  = "https://www.google.com/";
119
                $http_headers["Content-Security-Policy"]["frame-src"][]  = "https://www.gstatic.com/";
1001 daniel-mar 120
        }
121
 
702 daniel-mar 122
}