Subversion Repositories oidplus

Rev

Rev 1116 | Rev 1149 | 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 - 2023 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. // phpcs:disable PSR1.Files.SideEffects
  23. \defined('INSIDE_OIDPLUS') or die;
  24. // phpcs:enable PSR1.Files.SideEffects
  25.  
  26. class OIDplusCaptchaPluginRecaptcha extends OIDplusCaptchaPlugin {
  27.  
  28.         /**
  29.          *
  30.          */
  31.         /*public*/ const RECAPTCHA_V2_CHECKBOX  = 1;
  32.  
  33.         /**
  34.          *
  35.          */
  36.         /*public*/ const RECAPTCHA_V2_INVISIBLE = 2;
  37.  
  38.         /**
  39.          *
  40.          */
  41.         /*public*/ const RECAPTCHA_V3           = 3;
  42.  
  43.         /**
  44.          * @return string
  45.          */
  46.         public static function id(): string {
  47.                 return 'reCAPTCHA'; // TODO: Now it is called "reCAPTCHA"
  48.         }
  49.  
  50.         /**
  51.          * @return bool
  52.          * @throws OIDplusException
  53.          */
  54.         public function isVisible(): bool {
  55.                 return OIDplus::baseConfig()->getValue('RECAPTCHA_VERSION', self::RECAPTCHA_V2_CHECKBOX) == self::RECAPTCHA_V2_CHECKBOX;
  56.         }
  57.  
  58.         /**
  59.          * @param string|null $header_text
  60.          * @param string|null $footer_text
  61.          * @return string
  62.          * @throws OIDplusException
  63.          */
  64.         public function captchaGenerate(string $header_text=null, string $footer_text=null): string {
  65.                 return '<noscript>'.
  66.                        '<p><font color="red">'._L('You need to enable JavaScript to solve the CAPTCHA.').'</font></p>'.
  67.                        '</noscript>'.
  68.                        (!$this->isVisible() || !$header_text ? '' : '<p>'.$header_text.'</p>').
  69.                        '<div id="recaptcha"></div>'.
  70.                        '<input type="hidden" id="oidplus-recaptcha-response" name="oidplus-recaptcha-response">'.
  71.                        '<script>'.
  72. //                     '    $("form").submit(function(e){'.
  73. //                     // TODO: The form must not be submitted before recaptchaFinished() is called!
  74. //                     '         event.preventDefault();'.
  75. //                     '    });'.
  76.                        '    var recaptchaLoaded = function() {'.
  77.                        '        console.log("reCAPTCHA ready");'.
  78.                        '        grecaptcha.render("recaptcha", {'.
  79.                        '            "sitekey": "'.OIDplus::baseConfig()->getValue('RECAPTCHA_PUBLIC', '').'",'.
  80.                        ($this->isVisible() ? '' :
  81.                        '            "size": "invisible",').
  82.                        '            "callback": function (token) {'. // TODO: also 'expired-callback' and 'error-callback'
  83.                        '                console.log("reCAPTCHA solved");'.
  84.                        '                document.getElementById("oidplus-recaptcha-response").value = token;'.
  85.                        '            }'.
  86.                        '        });'.
  87.                        ($this->isVisible() ? '' :
  88.                        '        grecaptcha.execute();').
  89.                        '    };'.
  90.                        '    var oidplus_captcha_response = function() {'.
  91.                        '        return document.getElementById("oidplus-recaptcha-response").value;'.
  92.                        '    };'.
  93.                        '    var oidplus_captcha_reset = function() {'.
  94.                        '        grecaptcha.reset();'.
  95.                        ($this->isVisible() ? '' :
  96.                        '        grecaptcha.execute();').
  97.                        '    };'.
  98.                        '</script>'.
  99.                        '<script src="https://www.google.com/recaptcha/api.js?onload=recaptchaLoaded&render=explicit" async defer></script>'.
  100.                        (!$this->isVisible() || !$footer_text ? '' : '<p>'.$footer_text.'</p>');
  101.         }
  102.  
  103.         /**
  104.          * @param array $params
  105.          * @param string|null $fieldname
  106.          * @return void
  107.          * @throws OIDplusException
  108.          */
  109.         public function captchaVerify(array $params, string $fieldname=null) {
  110.                 $secret=OIDplus::baseConfig()->getValue('RECAPTCHA_PRIVATE', '');
  111.  
  112.                 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)
  113.                 _CheckParamExists($params, $fieldname);
  114.                 $response=$params[$fieldname];
  115.  
  116.                 $verify=url_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.urlencode($secret).'&response='.urlencode($response).'&remoteip='.urlencode($_SERVER['REMOTE_ADDR']));
  117.                 if (!$verify) {
  118.                         throw new OIDplusException(_L('CAPTCHA not successfully verified').' (Web request failed)');
  119.                 }
  120.                 $captcha_success=@json_decode($verify);
  121.                 $SCORE_THRESHOLD = 0.5; // TODO: Make Score configurable (only V3)
  122.                 if (!$captcha_success) {
  123.                         throw new OIDplusException(_L('CAPTCHA not successfully verified').' ('._L('JSON Decode failed').')');
  124.                 }
  125.                 if ($captcha_success->success==false) {
  126.                         throw new OIDplusException(_L('CAPTCHA not successfully verified').' ('._L('Failed').')');
  127.                 }
  128.                 if (isset($captcha_success->score) && ($captcha_success->score < $SCORE_THRESHOLD)) {
  129.                         throw new OIDplusException(_L('CAPTCHA not successfully verified').' ('._L('Score %1 too low', $captcha_success->score).')');
  130.                 }
  131.         }
  132.  
  133.         /**
  134.          * @return string
  135.          */
  136.         public static function setupHTML(): string {
  137.                 return '<div id="CAPTCHAPLUGIN_PARAMS_RECAPTCHA">'.
  138.                        '<p>(<a href="https://developers.google.com/recaptcha/intro" target="_blank">'._L('more information and obtain key').'</a>)</p>'.
  139.                        '<p>'._L('reCAPTCHA Version').'<br><select id="recaptcha_version">'.
  140.                        // Note: JavaScript will add "\ViaThinkSoft\OIDplus\OIDplusCaptchaPluginRecaptcha::" in front of the name
  141.                        '    <option name="RECAPTCHA_V2_CHECKBOX">reCAPTCHA V2 Checkbox</option>'.
  142.                        '    <option name="RECAPTCHA_V2_INVISIBLE">reCAPTCHA V2 Invisible</option>'.
  143.                        '    <option name="RECAPTCHA_V3">reCAPTCHA V3</option>'.
  144.                        '</select></p>'.
  145.                        '<p>'._L('reCAPTCHA Public key').'<br><input id="recaptcha_public" type="text" onkeypress="rebuild()" onkeyup="rebuild()"> <span id="recaptcha_public_warn"></span></p>'.
  146.                        '<p>'._L('reCAPTCHA Private key').'<br><input id="recaptcha_private" type="text" onkeypress="rebuild()" onkeyup="rebuild()"> <span id="recaptcha_private_warn"></span></p>'.
  147.                        '</div>';
  148.         }
  149.  
  150.         /**
  151.          * @param array $http_headers
  152.          * @return void
  153.          */
  154.         function httpHeaderCheck(array &$http_headers) {
  155.                 $http_headers["Content-Security-Policy"]["script-src"][] = "https://www.google.com/";
  156.                 $http_headers["Content-Security-Policy"]["script-src"][] = "https://www.gstatic.com/";
  157.                 $http_headers["Content-Security-Policy"]["img-src"][]    = "https://www.google.com/";
  158.                 $http_headers["Content-Security-Policy"]["img-src"][]    = "https://www.gstatic.com/";
  159.                 $http_headers["Content-Security-Policy"]["frame-src"][]  = "https://www.google.com/";
  160.                 $http_headers["Content-Security-Policy"]["frame-src"][]  = "https://www.gstatic.com/";
  161.         }
  162.  
  163. }
  164.