Система дистанционного обучения нашей школы работает на moodle 2.8
С недавнего времени Google отказался от reCAPTCHA V1, которая прекрасно работала с нашей версией moodle. А вот V2 с ней уже не работает.
В сети можно найти соответствующий трекер https://tracker.moodle.org/browse/MDL-48501
Надо изменить два файла на хостинге
/lib/form/recaptcha.php
/login/signup_form.php
Проще всего закинуть файл патча в нужное место хостинга и применить. Однако такое далеко не всегда возможно. Вручную вносить изменения задача тоже так себе.
Наиболее простой вариант – скачать данные файлы с сервера, применить к ним патч локально и загрузить обратно. Я сделал именно так и вот содержание файлов после применения патча:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* recaptcha type form element
*
* Contains HTML class for a recaptcha type element
*
* @package core_form
* @copyright 2008 Nicolas Connault <nicolasconnault@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once('HTML/QuickForm/input.php');
/**
* recaptcha type form element
*
* HTML class for a recaptcha type element
*
* @package core_form
* @category form
* @copyright 2008 Nicolas Connault <nicolasconnault@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class MoodleQuickForm_recaptcha extends HTML_QuickForm_input {
/** @var string html for help button, if empty then no help */
var $_helpbutton='';
/**
* constructor
*
* @param string $elementName (optional) name of the recaptcha element
* @param string $elementLabel (optional) label for recaptcha element
* @param mixed $attributes (optional) Either a typical HTML attribute string
* or an associative array
*/
function MoodleQuickForm_recaptcha($elementName = null, $elementLabel = null, $attributes = null) {
global $CFG, $PAGE;
$PAGE->requires->js(new moodle_url('https://www.google.com/recaptcha/api.js'), true);
parent::HTML_QuickForm_input($elementName, $elementLabel, $attributes);
$this->_type = 'recaptcha';
}
/**
* Returns the recaptcha element in HTML
*
* @return string
*/
function toHtml() {
global $CFG;
return html_writer::empty_tag('div', array('class'=>'g-recaptcha', 'data-sitekey'=> $CFG->recaptchapublickey));
}
/**
* get html for help button
*
* @return string html for help button
*/
function getHelpButton(){
return $this->_helpbutton;
}
/**
* Checks recaptcha response with google.
*
* @param string $responsestr
* @return bool
*/
function is_recaptcha_response_valid($responsestr) {
global $CFG;
require_once($CFG->libdir.'/filelib.php');
$remoteip = getremoteaddr();
$params = "secret={$CFG->recaptchaprivatekey}&response={$responsestr}&remoteip={$remoteip}";
$curl = new curl();
$url = 'https://www.google.com/recaptcha/api/siteverify';
$response = $curl->post($url, $params);
if ($curl->errno == 0) {
$data = json_decode($response);
if (isset($data->success) && $data->success == 'true') {
return true;
}
}
return false;
}
}
Второй:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* User sign-up form.
*
* @package core
* @subpackage auth
* @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once($CFG->libdir.'/formslib.php');
require_once($CFG->dirroot.'/user/profile/lib.php');
require_once($CFG->dirroot . '/user/editlib.php');
class login_signup_form extends moodleform {
function definition() {
global $USER, $CFG;
$mform = $this->_form;
$mform->addElement('header', 'createuserandpass', get_string('createuserandpass'), '');
$mform->addElement('text', 'username', get_string('username'), 'maxlength="100" size="12"');
$mform->setType('username', PARAM_NOTAGS);
$mform->addRule('username', get_string('missingusername'), 'required', null, 'server');
if (!empty($CFG->passwordpolicy)){
$mform->addElement('static', 'passwordpolicyinfo', '', print_password_policy());
}
$mform->addElement('passwordunmask', 'password', get_string('password'), 'maxlength="32" size="12"');
$mform->setType('password', PARAM_RAW);
$mform->addRule('password', get_string('missingpassword'), 'required', null, 'server');
$mform->addElement('header', 'supplyinfo', get_string('supplyinfo'),'');
$mform->addElement('text', 'email', get_string('email'), 'maxlength="100" size="25"');
$mform->setType('email', PARAM_RAW_TRIMMED);
$mform->addRule('email', get_string('missingemail'), 'required', null, 'server');
$mform->addElement('text', 'email2', get_string('emailagain'), 'maxlength="100" size="25"');
$mform->setType('email2', PARAM_RAW_TRIMMED);
$mform->addRule('email2', get_string('missingemail'), 'required', null, 'server');
$namefields = useredit_get_required_name_fields();
foreach ($namefields as $field) {
$mform->addElement('text', $field, get_string($field), 'maxlength="100" size="30"');
$mform->setType($field, PARAM_TEXT);
$stringid = 'missing' . $field;
if (!get_string_manager()->string_exists($stringid, 'moodle')) {
$stringid = 'required';
}
$mform->addRule($field, get_string($stringid), 'required', null, 'server');
}
$mform->addElement('text', 'city', get_string('city'), 'maxlength="120" size="20"');
$mform->setType('city', PARAM_TEXT);
if (!empty($CFG->defaultcity)) {
$mform->setDefault('city', $CFG->defaultcity);
}
$country = get_string_manager()->get_list_of_countries();
$default_country[''] = get_string('selectacountry');
$country = array_merge($default_country, $country);
$mform->addElement('select', 'country', get_string('country'), $country);
if( !empty($CFG->country) ){
$mform->setDefault('country', $CFG->country);
}else{
$mform->setDefault('country', '');
}
if ($this->signup_captcha_enabled()) {
$mform->addElement('recaptcha', 'recaptcha_element', get_string('recaptcha', 'auth'), array('https' => $CFG->loginhttps));
$mform->addHelpButton('recaptcha_element', 'recaptcha', 'auth');
}
profile_signup_fields($mform);
if (!empty($CFG->sitepolicy)) {
$mform->addElement('header', 'policyagreement', get_string('policyagreement'), '');
$mform->setExpanded('policyagreement');
$mform->addElement('static', 'policylink', '', '<a href="'.$CFG->sitepolicy.'" onclick="this.target=\'_blank\'">'.get_String('policyagreementclick').'</a>');
$mform->addElement('checkbox', 'policyagreed', get_string('policyaccept'));
$mform->addRule('policyagreed', get_string('policyagree'), 'required', null, 'server');
}
// buttons
$this->add_action_buttons(true, get_string('createaccount'));
}
function definition_after_data(){
$mform = $this->_form;
$mform->applyFilter('username', 'trim');
}
function validation($data, $files) {
global $CFG, $DB;
$errors = parent::validation($data, $files);
$authplugin = get_auth_plugin($CFG->registerauth);
if ($DB->record_exists('user', array('username'=>$data['username'], 'mnethostid'=>$CFG->mnet_localhost_id))) {
$errors['username'] = get_string('usernameexists');
} else {
//check allowed characters
if ($data['username'] !== core_text::strtolower($data['username'])) {
$errors['username'] = get_string('usernamelowercase');
} else {
if ($data['username'] !== clean_param($data['username'], PARAM_USERNAME)) {
$errors['username'] = get_string('invalidusername');
}
}
}
//check if user exists in external db
//TODO: maybe we should check all enabled plugins instead
if ($authplugin->user_exists($data['username'])) {
$errors['username'] = get_string('usernameexists');
}
if (! validate_email($data['email'])) {
$errors['email'] = get_string('invalidemail');
} else if ($DB->record_exists('user', array('email'=>$data['email']))) {
$errors['email'] = get_string('emailexists').' <a href="forgot_password.php">'.get_string('newpassword').'?</a>';
}
if (empty($data['email2'])) {
$errors['email2'] = get_string('missingemail');
} else if ($data['email2'] != $data['email']) {
$errors['email2'] = get_string('invalidemail');
}
if (!isset($errors['email'])) {
if ($err = email_is_not_allowed($data['email'])) {
$errors['email'] = $err;
}
}
$errmsg = '';
if (!check_password_policy($data['password'], $errmsg)) {
$errors['password'] = $errmsg;
}
// BEGIN moodle.org hack (MDLSITE-3878)
if ($this->signup_captcha_enabled()) {
$recaptcha_element = $this->_form->getElement('recaptcha_element');
if (!empty($this->_form->_submitValues['g-recaptcha-response'])) {
$response = $this->_form->_submitValues['g-recaptcha-response'];
if (!$recaptcha_element->is_recaptcha_response_valid($response)) {
$errors['recaptcha_element'] = get_string('invaliddata', 'error');
}
} else {
$errors['recaptcha_element'] = get_string('missingrecaptchachallengefield');
}
}
// END moodle.org hack (MDLSITE-3878)
// Validate customisable profile fields. (profile_validation expects an object as the parameter with userid set)
$dataobject = (object)$data;
$dataobject->id = 0;
$errors += profile_validation($dataobject, $files);
return $errors;
}
/**
* Returns whether or not the captcha element is enabled, and the admin settings fulfil its requirements.
* @return bool
*/
function signup_captcha_enabled() {
global $CFG;
return !empty($CFG->recaptchapublickey) && !empty($CFG->recaptchaprivatekey) && get_config('auth/email', 'recaptcha');
}
}
Можно просто скопировать это содержание в файлы хостинга через внутренний редактор без скачивания и загрузки обратно.
После этого reCAPTCHA v2 будет работать и дальше защищать сайт от нежелательный комментариев и регистраций.
