Subversion Repositories oidplus

Rev

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