Subversion Repositories oidplus

Rev

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

  1. <?php
  2.  
  3. /*
  4.  * OIDplus 2.0
  5.  * Copyright 2019 - 2022 Daniel Marschall, ViaThinkSoft
  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.  
  20. namespace ViaThinkSoft\OIDplus;
  21.  
  22. class OIDplusCaptchaPluginRecaptcha extends OIDplusCaptchaPlugin {
  23.  
  24.         /*public*/ const RECAPTCHA_V2_CHECKBOX  = 1;
  25.         /*public*/ const RECAPTCHA_V2_INVISIBLE = 2;
  26.         /*public*/ const RECAPTCHA_V3           = 3;
  27.  
  28.         public static function id(): string {
  29.                 return 'reCAPTCHA'; // TODO: Now it is called "reCAPTCHA"
  30.         }
  31.  
  32.         public function isVisible(): bool {
  33.                 return OIDplus::baseConfig()->getValue('RECAPTCHA_VERSION', self::RECAPTCHA_V2_CHECKBOX) == self::RECAPTCHA_V2_CHECKBOX;
  34.         }
  35.  
  36.         public function captchaGenerate($header_text=null, $footer_text=null) {
  37.                 return '<noscript>'.
  38.                        '<p><font color="red">'._L('You need to enable JavaScript to solve the CAPTCHA.').'</font></p>'.
  39.                        '</noscript>'.
  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>');
  73.         }
  74.  
  75.         public function captchaVerify($params, $fieldname=null) {
  76.                 $secret=OIDplus::baseConfig()->getValue('RECAPTCHA_PRIVATE', '');
  77.  
  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)
  79.                 _CheckParamExists($params, $fieldname);
  80.                 $response=$params[$fieldname];
  81.  
  82.                 $verify=url_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.urlencode($secret).'&response='.urlencode($response).'&remoteip='.urlencode($_SERVER['REMOTE_ADDR']));
  83.                 if (!$verify) {
  84.                         throw new OIDplusException(_L('CAPTCHA not successfully verified').' (Web request failed)');
  85.                 }
  86.                 $captcha_success=@json_decode($verify);
  87.                 $SCORE_THRESHOLD = 0.5; // TODO: Make Score configurable (only V3)
  88.                 if (!$captcha_success) {
  89.                         throw new OIDplusException(_L('CAPTCHA not successfully verified').' ('._L('JSON Decode failed').')');
  90.                 }
  91.                 if ($captcha_success->success==false) {
  92.                         throw new OIDplusException(_L('CAPTCHA not successfully verified').' ('._L('Failed').')');
  93.                 }
  94.                 if (isset($captcha_success->score) && ($captcha_success->score < $SCORE_THRESHOLD)) {
  95.                         throw new OIDplusException(_L('CAPTCHA not successfully verified').' ('._L('Score %1 too low', $captcha_success->score).')');
  96.                 }
  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>'.
  102.                        '<p>'._L('reCAPTCHA Version').'<br><select id="recaptcha_version">'.
  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>'.
  107.                        '</select></p>'.
  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.  
  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/";
  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/";
  120.         }
  121.  
  122. }
  123.