first commit

This commit is contained in:
CHIEFSOFT\ameye
2024-09-30 18:11:26 -04:00
commit e592ca6823
27270 changed files with 5002257 additions and 0 deletions
+372
View File
@@ -0,0 +1,372 @@
<?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/>.
/**
* Class communication
*
* @package core
* @copyright 2017 Marina Glancy
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core\hub;
defined('MOODLE_INTERNAL') || die();
use moodle_exception;
use curl;
use stdClass;
use coding_exception;
use moodle_url;
/**
* Provides methods to communicate with the hub (sites directory) web services.
*
* @package core
* @copyright 2017 Marina Glancy
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class api {
/** @var File type: Course screenshot */
const HUB_SCREENSHOT_FILE_TYPE = 'screenshot';
/** @var File type: Hub screenshot */
const HUB_HUBSCREENSHOT_FILE_TYPE = 'hubscreenshot';
/** @var File type: Backup */
const HUB_BACKUP_FILE_TYPE = 'backup';
/**
* Calls a remote function exposed via web services on the hub.
*
* @param string $function name of WS function
* @param array $data parameters of WS function
* @param bool $allowpublic allow request without registration on the hub
* @return mixed depends on the function
* @throws moodle_exception
*/
protected static function call($function, array $data = [], $allowpublic = false) {
$token = registration::get_token() ?: 'publichub';
if (!$allowpublic && $token === 'publichub') {
// This will throw an exception.
registration::require_registration();
}
return self::call_rest($token, $function, $data);
}
/**
* Performs a REST request to the hub site (using the GET method).
*
* @param string $token
* @param string $function
* @param array $data
* @return mixed
* @throws moodle_exception
*/
protected static function call_rest($token, $function, array $data) {
$params = [
'wstoken' => $token,
'wsfunction' => $function,
'moodlewsrestformat' => 'json'
] + $data;
$curl = new curl();
$serverurl = HUB_MOODLEORGHUBURL . "/local/hub/webservice/webservices.php";
$query = http_build_query($params, '', '&');
$curloutput = @json_decode($curl->post($serverurl, $query), true);
$info = $curl->get_info();
if ($curl->get_errno()) {
// Connection error.
throw new moodle_exception('errorconnect', 'hub', '', $curl->error);
} else if (isset($curloutput['exception'])) {
// Exception occurred on the remote side.
self::process_curl_exception($token, $curloutput);
} else if ($info['http_code'] != 200) {
throw new moodle_exception('errorconnect', 'hub', '', $info['http_code']);
} else {
return $curloutput;
}
}
/**
* Analyses exception received from the hub server.
*
* @param string $token token used for CURL request
* @param array $curloutput output from CURL request
* @throws moodle_exception
*/
protected static function process_curl_exception($token, $curloutput) {
if (!isset($curloutput['exception'])) {
return;
}
if ($token === registration::get_token()) {
// Check if registration token was rejected or there are other problems with registration.
if (($curloutput['exception'] === 'moodle_exception' && $curloutput['errorcode'] === 'invalidtoken')
|| $curloutput['exception'] === 'registration_exception') {
// Force admin to repeat site registration process.
registration::reset_token();
throw new moodle_exception('errorwstokenreset', 'hub', '', $curloutput['message']);
}
}
throw new moodle_exception('errorws', 'hub', '', $curloutput['message']);
}
/**
* Update site registration on the hub.
*
* @param array $siteinfo
* @throws moodle_exception
*/
public static function update_registration(array $siteinfo) {
$params = array('siteinfo' => $siteinfo, 'validateurl' => 1);
self::call('hub_update_site_info', $params);
}
/**
* Returns information about the hub.
*
* Example of the return array:
* {
* "courses": 384,
* "description": "Official Moodle sites directory.",
* "downloadablecourses": 0,
* "enrollablecourses": 0,
* "hublogo": 1,
* "language": "en",
* "name": "moodle",
* "sites": 274175,
* "url": "https://stats.moodle.org",
* "imgurl": "https://stats.moodle.org/local/hub/webservice/download.php?filetype=hubscreenshot"
* }
*
* @return array
* @throws moodle_exception
*/
public static function get_hub_info() {
$info = self::call('hub_get_info', [], true);
$info['imgurl'] = new moodle_url(HUB_MOODLEORGHUBURL . '/local/hub/webservice/download.php',
['filetype' => self::HUB_HUBSCREENSHOT_FILE_TYPE]);
return $info;
}
/**
* Calls WS function hub_get_courses
*
* @deprecated since Moodle 3.8. Moodle.net has been sunsetted making this function useless.
*
* Parameter $options may have any of these fields:
* [
* 'ids' => new external_multiple_structure(new external_value(PARAM_INT, 'id of a course in the hub course
* directory'), 'ids of course', VALUE_OPTIONAL),
* 'sitecourseids' => new external_multiple_structure(new external_value(PARAM_INT, 'id of a course in the
* site'), 'ids of course in the site', VALUE_OPTIONAL),
* 'coverage' => new external_value(PARAM_TEXT, 'coverage', VALUE_OPTIONAL),
* 'licenceshortname' => new external_value(PARAM_ALPHANUMEXT, 'licence short name', VALUE_OPTIONAL),
* 'subject' => new external_value(PARAM_ALPHANUM, 'subject', VALUE_OPTIONAL),
* 'audience' => new external_value(PARAM_ALPHA, 'audience', VALUE_OPTIONAL),
* 'educationallevel' => new external_value(PARAM_ALPHA, 'educational level', VALUE_OPTIONAL),
* 'language' => new external_value(PARAM_ALPHANUMEXT, 'language', VALUE_OPTIONAL),
* 'orderby' => new external_value(PARAM_ALPHA, 'orderby method: newest, eldest, publisher, fullname,
* ratingaverage', VALUE_OPTIONAL),
* 'givememore' => new external_value(PARAM_INT, 'next range of result - range size being set by the hub
* server ', VALUE_OPTIONAL),
* 'allsitecourses' => new external_value(PARAM_INT,
* 'if 1 return all not visible and visible courses whose siteid is the site
* matching token. Only courses of this site are returned.
* givememore parameter is ignored if this param = 1.
* In case of public token access, this param option is ignored', VALUE_DEFAULT, 0),
* ]
*
* Each course in the returned array of courses will have fields:
* [
* 'id' => new external_value(PARAM_INT, 'id'),
* 'fullname' => new external_value(PARAM_TEXT, 'course name'),
* 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
* 'description' => new external_value(PARAM_TEXT, 'course description'),
* 'language' => new external_value(PARAM_ALPHANUMEXT, 'course language'),
* 'publishername' => new external_value(PARAM_TEXT, 'publisher name'),
* 'publisheremail' => new external_value(PARAM_EMAIL, 'publisher email', VALUE_OPTIONAL),
* 'privacy' => new external_value(PARAM_INT, 'privacy: published or not', VALUE_OPTIONAL),
* 'sitecourseid' => new external_value(PARAM_INT, 'course id on the site', VALUE_OPTIONAL),
* 'contributornames' => new external_value(PARAM_TEXT, 'contributor names', VALUE_OPTIONAL),
* 'coverage' => new external_value(PARAM_TEXT, 'coverage', VALUE_OPTIONAL),
* 'creatorname' => new external_value(PARAM_TEXT, 'creator name'),
* 'licenceshortname' => new external_value(PARAM_ALPHANUMEXT, 'licence short name'),
* 'subject' => new external_value(PARAM_ALPHANUM, 'subject'),
* 'audience' => new external_value(PARAM_ALPHA, 'audience'),
* 'educationallevel' => new external_value(PARAM_ALPHA, 'educational level'),
* 'creatornotes' => new external_value(PARAM_RAW, 'creator notes'),
* 'creatornotesformat' => new external_value(PARAM_INT, 'notes format'),
* 'demourl' => new external_value(PARAM_URL, 'demo URL', VALUE_OPTIONAL),
* 'courseurl' => new external_value(PARAM_URL, 'course URL', VALUE_OPTIONAL),
* 'backupsize' => new external_value(PARAM_INT, 'course backup size in bytes', VALUE_OPTIONAL),
* 'enrollable' => new external_value(PARAM_BOOL, 'is the course enrollable'),
* 'screenshots' => new external_value(PARAM_INT, 'total number of screenshots'),
* 'timemodified' => new external_value(PARAM_INT, 'time of last modification - timestamp'),
* 'contents' => new external_multiple_structure(new external_single_structure(
* array(
* 'moduletype' => new external_value(PARAM_ALPHA, 'the type of module (activity/block)'),
* 'modulename' => new external_value(PARAM_TEXT, 'the name of the module (forum, resource etc)'),
* 'contentcount' => new external_value(PARAM_INT, 'how many time the module is used in the course'),
* )), 'contents', VALUE_OPTIONAL),
* 'rating' => new external_single_structure (
* array(
* 'aggregate' => new external_value(PARAM_FLOAT, 'Rating average', VALUE_OPTIONAL),
* 'scaleid' => new external_value(PARAM_INT, 'Rating scale'),
* 'count' => new external_value(PARAM_INT, 'Rating count'),
* ), 'rating', VALUE_OPTIONAL),
* 'comments' => new external_multiple_structure(new external_single_structure (
* array(
* 'comment' => new external_value(PARAM_TEXT, 'the comment'),
* 'commentator' => new external_value(PARAM_TEXT, 'the name of commentator'),
* 'date' => new external_value(PARAM_INT, 'date of the comment'),
* )), 'contents', VALUE_OPTIONAL),
* 'outcomes' => new external_multiple_structure(new external_single_structure(
* array(
* 'fullname' => new external_value(PARAM_TEXT, 'the outcome fullname')
* )), 'outcomes', VALUE_OPTIONAL)
* ]
*
* Additional fields for each course:
* 'screenshotbaseurl' (moodle_url) URL of the first screenshot, only set if $course['screenshots']>0
* 'commenturl' (moodle_url) URL for comments
*
* @param string $search search string
* @param bool $downloadable return downloadable courses
* @param bool $enrollable return enrollable courses
* @param array|\stdClass $options other options from the list of allowed options:
* 'ids', 'sitecourseids', 'coverage', 'licenceshortname', 'subject', 'audience',
* 'educationallevel', 'language', 'orderby', 'givememore', 'allsitecourses'
* @return array of two elements: [$courses, $coursetotal]
* @throws \coding_exception
* @throws moodle_exception
*/
public static function get_courses($search, $downloadable, $enrollable, $options) {
debugging("This function has been deprecated as part of the Moodle.net sunsetting process.");
return [[], 0];
}
/**
* Unregister the site
*
* @throws moodle_exception
*/
public static function unregister_site() {
global $CFG;
self::call('hub_unregister_site', ['url' => [$CFG->wwwroot]]);
}
/**
* Unpublish courses
*
* @deprecated since Moodle 3.8. Moodle.net has been sunsetted making this function useless.
*
* @param int[]|int $courseids
* @throws moodle_exception
*/
public static function unregister_courses($courseids) {
debugging("This function has been deprecated as part of the Moodle.net sunsetting process.");
}
/**
* Publish one course
*
* @deprecated since Moodle 3.8. Moodle.net has been sunsetted making this function useless.
*
* Expected contents of $courseinfo:
* [
* 'sitecourseid' => new external_value(PARAM_INT, 'the id of the course on the publishing site'),
* 'fullname' => new external_value(PARAM_TEXT, 'course name'),
* 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
* 'description' => new external_value(PARAM_TEXT, 'course description'),
* 'language' => new external_value(PARAM_ALPHANUMEXT, 'course language'),
* 'publishername' => new external_value(PARAM_TEXT, 'publisher name'),
* 'publisheremail' => new external_value(PARAM_EMAIL, 'publisher email'),
* 'contributornames' => new external_value(PARAM_TEXT, 'contributor names'),
* 'coverage' => new external_value(PARAM_TEXT, 'coverage'),
* 'creatorname' => new external_value(PARAM_TEXT, 'creator name'),
* 'licenceshortname' => new external_value(PARAM_ALPHANUMEXT, 'licence short name'),
* 'subject' => new external_value(PARAM_ALPHANUM, 'subject'),
* 'audience' => new external_value(PARAM_ALPHA, 'audience'),
* 'educationallevel' => new external_value(PARAM_ALPHA, 'educational level'),
* 'creatornotes' => new external_value(PARAM_RAW, 'creator notes'),
* 'creatornotesformat' => new external_value(PARAM_INT, 'notes format'),
* 'demourl' => new external_value(PARAM_URL, 'demo URL', VALUE_OPTIONAL),
* 'courseurl' => new external_value(PARAM_URL, 'course URL', VALUE_OPTIONAL),
* 'enrollable' => new external_value(PARAM_BOOL, 'is the course enrollable', VALUE_DEFAULT, 0),
* 'screenshots' => new external_value(PARAM_INT, 'the number of screenhots', VALUE_OPTIONAL),
* 'deletescreenshots' => new external_value(PARAM_INT, 'ask to delete all the existing screenshot files
* (it does not reset the screenshot number)', VALUE_DEFAULT, 0),
* 'contents' => new external_multiple_structure(new external_single_structure(
* array(
* 'moduletype' => new external_value(PARAM_ALPHA, 'the type of module (activity/block)'),
* 'modulename' => new external_value(PARAM_TEXT, 'the name of the module (forum, resource etc)'),
* 'contentcount' => new external_value(PARAM_INT, 'how many time the module is used in the course'),
* )), 'contents', VALUE_OPTIONAL),
* 'outcomes' => new external_multiple_structure(new external_single_structure(
* array(
* 'fullname' => new external_value(PARAM_TEXT, 'the outcome fullname')
* )), 'outcomes', VALUE_OPTIONAL)
* ]
*
* @param array|\stdClass $courseinfo
* @return int id of the published course on the hub
* @throws moodle_exception if the communication with the hub failed or the course could not be published
*/
public static function register_course($courseinfo) {
debugging("This function has been deprecated as part of the Moodle.net sunsetting process.");
throw new moodle_exception('errorcoursewronglypublished', 'hub');
}
/**
* Uploads a screenshot for the published course
*
* @deprecated since Moodle 3.8. Moodle.net has been sunsetted making this function useless.
*
* @param int $hubcourseid id of the published course on the hub, it must be published from this site
* @param \stored_file $file
* @param int $screenshotnumber ordinal number of the screenshot
*/
public static function add_screenshot($hubcourseid, \stored_file $file, $screenshotnumber) {
debugging("This function has been deprecated as part of the Moodle.net sunsetting process.");
}
/**
* Downloads course backup
*
* @deprecated since Moodle 3.8. Moodle.net has been sunsetted making this function useless.
*
* @param int $hubcourseid id of the course on the hub
* @param string $path local path (in tempdir) to save the downloaded backup to.
*/
public static function download_course_backup($hubcourseid, $path) {
debugging("This function has been deprecated as part of the Moodle.net sunsetting process.");
}
/**
* Uploads a course backup
*
* @deprecated since Moodle 3.8. Moodle.net has been sunsetted making this function useless.
*
* @param int $hubcourseid id of the published course on the hub, it must be published from this site
* @param \stored_file $backupfile
*/
public static function upload_course_backup($hubcourseid, \stored_file $backupfile) {
debugging("This function has been deprecated as part of the Moodle.net sunsetting process.");
}
}
+611
View File
@@ -0,0 +1,611 @@
<?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/>.
/**
* Class registration
*
* @package core
* @copyright 2017 Marina Glancy
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core\hub;
defined('MOODLE_INTERNAL') || die();
use moodle_exception;
use moodle_url;
use context_system;
use stdClass;
use html_writer;
/**
* Methods to use when registering the site at the moodle sites directory.
*
* @package core
* @copyright 2017 Marina Glancy
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class registration {
/** @var array Fields used in a site registration form.
* IMPORTANT: any new fields with non-empty defaults have to be added to CONFIRM_NEW_FIELDS */
const FORM_FIELDS = ['policyagreed', 'language', 'countrycode', 'privacy',
'contactemail', 'contactable', 'emailalert', 'emailalertemail', 'commnews', 'commnewsemail',
'contactname', 'name', 'description', 'imageurl', 'contactphone', 'regioncode', 'geolocation', 'street'];
/** @var array List of new FORM_FIELDS or siteinfo fields added indexed by the version when they were added.
* If site was already registered, admin will be promted to confirm new registration data manually. Until registration is manually confirmed,
* the scheduled task updating registration will be paused.
* Keys of this array are not important as long as they increment, use current date to avoid confusions.
*/
const CONFIRM_NEW_FIELDS = [
2017092200 => [
'commnews', // Receive communication news. This was added in 3.4 and is "On" by default. Admin must confirm or opt-out.
'mobileservicesenabled', 'mobilenotificationsenabled', 'registereduserdevices', 'registeredactiveuserdevices' // Mobile stats added in 3.4.
],
// Analytics stats added in Moodle 3.7.
2019022200 => ['analyticsenabledmodels', 'analyticspredictions', 'analyticsactions', 'analyticsactionsnotuseful'],
// Active users stats added in Moodle 3.9.
2020022600 => ['activeusers', 'activeparticipantnumberaverage'],
// Database type, course date info, site theme, primary auth type added in Moodle 4.2.
2023021700 => ['dbtype', 'coursesnodates', 'sitetheme', 'primaryauthtype'],
];
/** @var string Site privacy: not displayed */
const HUB_SITENOTPUBLISHED = 'notdisplayed';
/** @var string Site privacy: public */
const HUB_SITENAMEPUBLISHED = 'named';
/** @var string Site privacy: public and global */
const HUB_SITELINKPUBLISHED = 'linked';
/** @var stdClass cached site registration information */
protected static $registration = null;
/**
* Get site registration
*
* @param bool $confirmed
* @return stdClass|null
*/
protected static function get_registration($confirmed = true) {
global $DB;
if (self::$registration === null) {
self::$registration = $DB->get_record('registration_hubs', ['huburl' => HUB_MOODLEORGHUBURL]) ?: null;
}
if (self::$registration && (bool)self::$registration->confirmed == (bool)$confirmed) {
return self::$registration;
}
return null;
}
/**
* Same as get_registration except it throws exception if site not registered
*
* @return stdClass
* @throws \moodle_exception
*/
public static function require_registration() {
if ($registration = self::get_registration()) {
return $registration;
}
if (has_capability('moodle/site:config', context_system::instance())) {
throw new moodle_exception('registrationwarning', 'admin', new moodle_url('/admin/registration/index.php'));
} else {
throw new moodle_exception('registrationwarningcontactadmin', 'admin');
}
}
/**
* Checks if site is registered
*
* @return bool
*/
public static function is_registered() {
return self::get_registration() ? true : false;
}
/**
* Returns registration token
*
* @param int $strictness if set to MUST_EXIST and site is not registered will throw an exception
* @return null
* @throws moodle_exception
*/
public static function get_token($strictness = IGNORE_MISSING) {
if ($strictness == MUST_EXIST) {
$registration = self::require_registration();
} else if (!$registration = self::get_registration()) {
return null;
}
return $registration->token;
}
/**
* When was the registration last updated
*
* @return int|null timestamp or null if site is not registered
*/
public static function get_last_updated() {
if ($registration = self::get_registration()) {
return $registration->timemodified;
}
return null;
}
/**
* Calculates and prepares site information to send to the sites directory as a part of registration.
*
* @param array $defaults default values for inputs in the registration form (if site was never registered before)
* @return array site info
*/
public static function get_site_info($defaults = []) {
global $CFG, $DB;
require_once($CFG->libdir . '/badgeslib.php');
require_once($CFG->dirroot . "/course/lib.php");
$siteinfo = array();
foreach (self::FORM_FIELDS as $field) {
$siteinfo[$field] = get_config('hub', 'site_'.$field);
if ($siteinfo[$field] === false) {
$siteinfo[$field] = array_key_exists($field, $defaults) ? $defaults[$field] : null;
}
}
// Statistical data.
$siteinfo['courses'] = $DB->count_records('course') - 1;
$siteinfo['users'] = $DB->count_records('user', array('deleted' => 0));
$siteinfo['activeusers'] = $DB->count_records_select('user', 'deleted = ? AND lastlogin > ?', [0, time() - DAYSECS * 30]);
$siteinfo['enrolments'] = $DB->count_records('role_assignments');
$siteinfo['posts'] = $DB->count_records('forum_posts');
$siteinfo['questions'] = $DB->count_records('question');
$siteinfo['resources'] = $DB->count_records('resource');
$siteinfo['badges'] = $DB->count_records_select('badge', 'status <> ' . BADGE_STATUS_ARCHIVED);
$siteinfo['issuedbadges'] = $DB->count_records('badge_issued');
$siteinfo['participantnumberaverage'] = average_number_of_participants();
$siteinfo['activeparticipantnumberaverage'] = average_number_of_participants(true, time() - DAYSECS * 30);
$siteinfo['modulenumberaverage'] = average_number_of_courses_modules();
$siteinfo['dbtype'] = $CFG->dbtype;
$siteinfo['coursesnodates'] = $DB->count_records_select('course', 'enddate = ?', [0]) - 1;
$siteinfo['sitetheme'] = get_config('core', 'theme');
// Primary auth type.
$primaryauthsql = 'SELECT auth, count(auth) as tc FROM {user} GROUP BY auth ORDER BY tc DESC';
$siteinfo['primaryauthtype'] = $DB->get_field_sql($primaryauthsql, null, IGNORE_MULTIPLE);
// Version and url.
$siteinfo['moodlerelease'] = $CFG->release;
$siteinfo['url'] = $CFG->wwwroot;
// Mobile related information.
$siteinfo['mobileservicesenabled'] = 0;
$siteinfo['mobilenotificationsenabled'] = 0;
$siteinfo['registereduserdevices'] = 0;
$siteinfo['registeredactiveuserdevices'] = 0;
if (!empty($CFG->enablewebservices) && !empty($CFG->enablemobilewebservice)) {
$siteinfo['mobileservicesenabled'] = 1;
$siteinfo['registereduserdevices'] = $DB->count_records('user_devices');
$airnotifierextpath = $CFG->dirroot . '/message/output/airnotifier/externallib.php';
if (file_exists($airnotifierextpath)) { // Maybe some one uninstalled the plugin.
require_once($airnotifierextpath);
$siteinfo['mobilenotificationsenabled'] = \message_airnotifier_external::is_system_configured();
$siteinfo['registeredactiveuserdevices'] = $DB->count_records('message_airnotifier_devices', array('enable' => 1));
}
}
// Analytics related data follow.
$siteinfo['analyticsenabledmodels'] = \core_analytics\stats::enabled_models();
$siteinfo['analyticspredictions'] = \core_analytics\stats::predictions();
$siteinfo['analyticsactions'] = \core_analytics\stats::actions();
$siteinfo['analyticsactionsnotuseful'] = \core_analytics\stats::actions_not_useful();
// IMPORTANT: any new fields in siteinfo have to be added to the constant CONFIRM_NEW_FIELDS.
return $siteinfo;
}
/**
* Human-readable summary of data that will be sent to the sites directory.
*
* @param array $siteinfo result of get_site_info()
* @return string
*/
public static function get_stats_summary($siteinfo) {
$fieldsneedconfirm = self::get_new_registration_fields();
$summary = html_writer::tag('p', get_string('sendfollowinginfo_help', 'hub')) .
html_writer::start_tag('ul');
$mobileservicesenabled = $siteinfo['mobileservicesenabled'] ? get_string('yes') : get_string('no');
$mobilenotificationsenabled = $siteinfo['mobilenotificationsenabled'] ? get_string('yes') : get_string('no');
$moodlerelease = $siteinfo['moodlerelease'];
if (preg_match('/^(\d+\.\d.*?)[\. ]/', $moodlerelease, $matches)) {
$moodlerelease = $matches[1];
}
$senddata = [
'moodlerelease' => get_string('sitereleasenum', 'hub', $moodlerelease),
'courses' => get_string('coursesnumber', 'hub', $siteinfo['courses']),
'users' => get_string('usersnumber', 'hub', $siteinfo['users']),
'activeusers' => get_string('activeusersnumber', 'hub', $siteinfo['activeusers']),
'enrolments' => get_string('roleassignmentsnumber', 'hub', $siteinfo['enrolments']),
'posts' => get_string('postsnumber', 'hub', $siteinfo['posts']),
'questions' => get_string('questionsnumber', 'hub', $siteinfo['questions']),
'resources' => get_string('resourcesnumber', 'hub', $siteinfo['resources']),
'badges' => get_string('badgesnumber', 'hub', $siteinfo['badges']),
'issuedbadges' => get_string('issuedbadgesnumber', 'hub', $siteinfo['issuedbadges']),
'participantnumberaverage' => get_string('participantnumberaverage', 'hub',
format_float($siteinfo['participantnumberaverage'], 2)),
'activeparticipantnumberaverage' => get_string('activeparticipantnumberaverage', 'hub',
format_float($siteinfo['activeparticipantnumberaverage'], 2)),
'modulenumberaverage' => get_string('modulenumberaverage', 'hub',
format_float($siteinfo['modulenumberaverage'], 2)),
'mobileservicesenabled' => get_string('mobileservicesenabled', 'hub', $mobileservicesenabled),
'mobilenotificationsenabled' => get_string('mobilenotificationsenabled', 'hub', $mobilenotificationsenabled),
'registereduserdevices' => get_string('registereduserdevices', 'hub', $siteinfo['registereduserdevices']),
'registeredactiveuserdevices' => get_string('registeredactiveuserdevices', 'hub', $siteinfo['registeredactiveuserdevices']),
'analyticsenabledmodels' => get_string('analyticsenabledmodels', 'hub', $siteinfo['analyticsenabledmodels']),
'analyticspredictions' => get_string('analyticspredictions', 'hub', $siteinfo['analyticspredictions']),
'analyticsactions' => get_string('analyticsactions', 'hub', $siteinfo['analyticsactions']),
'analyticsactionsnotuseful' => get_string('analyticsactionsnotuseful', 'hub', $siteinfo['analyticsactionsnotuseful']),
'dbtype' => get_string('dbtype', 'hub', $siteinfo['dbtype']),
'coursesnodates' => get_string('coursesnodates', 'hub', $siteinfo['coursesnodates']),
'sitetheme' => get_string('sitetheme', 'hub', $siteinfo['sitetheme']),
'primaryauthtype' => get_string('primaryauthtype', 'hub', $siteinfo['primaryauthtype']),
];
foreach ($senddata as $key => $str) {
$class = in_array($key, $fieldsneedconfirm) ? ' needsconfirmation mark' : '';
$summary .= html_writer::tag('li', $str, ['class' => 'site' . $key . $class]);
}
$summary .= html_writer::end_tag('ul');
return $summary;
}
/**
* Save registration info locally so it can be retrieved when registration needs to be updated
*
* @param stdClass $formdata data from {@link site_registration_form}
*/
public static function save_site_info($formdata) {
foreach (self::FORM_FIELDS as $field) {
set_config('site_' . $field, $formdata->$field, 'hub');
}
// Even if the connection with the sites directory fails, admin has manually submitted the form which means they don't need
// to be redirected to the site registration page any more.
set_config('site_regupdateversion', max(array_keys(self::CONFIRM_NEW_FIELDS)), 'hub');
}
/**
* Updates site registration when "Update reigstration" button is clicked by admin
*/
public static function update_manual() {
global $DB;
if (!$registration = self::get_registration()) {
return false;
}
$siteinfo = self::get_site_info();
try {
api::update_registration($siteinfo);
} catch (moodle_exception $e) {
if (!self::is_registered()) {
// Token was rejected during registration update and site and locally stored token was reset,
// proceed to site registration. This method will redirect away.
self::register('');
}
\core\notification::add(get_string('errorregistrationupdate', 'hub', $e->getMessage()),
\core\output\notification::NOTIFY_ERROR);
return false;
}
$DB->update_record('registration_hubs', ['id' => $registration->id, 'timemodified' => time()]);
\core\notification::add(get_string('siteregistrationupdated', 'hub'),
\core\output\notification::NOTIFY_SUCCESS);
self::$registration = null;
return true;
}
/**
* Updates site registration via cron
*
* @throws moodle_exception
*/
public static function update_cron() {
global $DB;
if (!$registration = self::get_registration()) {
mtrace(get_string('registrationwarning', 'admin'));
return;
}
if (self::get_new_registration_fields()) {
mtrace(get_string('pleaserefreshregistrationnewdata', 'admin'));
return;
}
$siteinfo = self::get_site_info();
api::update_registration($siteinfo);
$DB->update_record('registration_hubs', ['id' => $registration->id, 'timemodified' => time()]);
mtrace(get_string('siteregistrationupdated', 'hub'));
self::$registration = null;
}
/**
* Confirms registration by the sites directory.
*
* @param string $token
* @param string $newtoken
* @param string $hubname
* @throws moodle_exception
*/
public static function confirm_registration($token, $newtoken, $hubname) {
global $DB;
$registration = self::get_registration(false);
if (!$registration || $registration->token !== $token) {
throw new moodle_exception('wrongtoken', 'hub', new moodle_url('/admin/registration/index.php'));
}
$record = ['id' => $registration->id];
$record['token'] = $newtoken;
$record['confirmed'] = 1;
$record['hubname'] = $hubname;
$record['timemodified'] = time();
$DB->update_record('registration_hubs', $record);
self::$registration = null;
$siteinfo = self::get_site_info();
if (strlen(http_build_query($siteinfo)) > 1800) {
// Update registration again because the initial request was too long and could have been truncated.
api::update_registration($siteinfo);
self::$registration = null;
}
// Finally, allow other plugins to perform actions once a site is registered for first time.
$pluginsfunction = get_plugins_with_function('post_site_registration_confirmed');
foreach ($pluginsfunction as $plugins) {
foreach ($plugins as $pluginfunction) {
$pluginfunction($registration->id);
}
}
}
/**
* Retrieve the options for site privacy form element to use in registration form
* @return array
*/
public static function site_privacy_options() {
return [
self::HUB_SITENOTPUBLISHED => get_string('siteprivacynotpublished', 'hub'),
self::HUB_SITENAMEPUBLISHED => get_string('siteprivacypublished', 'hub'),
self::HUB_SITELINKPUBLISHED => get_string('siteprivacylinked', 'hub')
];
}
/**
* Registers a site
*
* This method will make sure that unconfirmed registration record is created and then redirect to
* registration script on the sites directory.
* The sites directory will check that the site is accessible, register it and redirect back
* to /admin/registration/confirmregistration.php
*
* @param string $returnurl
* @throws \coding_exception
*/
public static function register($returnurl) {
global $DB, $SESSION;
if (self::is_registered()) {
// Caller of this method must make sure that site is not registered.
throw new \coding_exception('Site already registered');
}
$hub = self::get_registration(false);
if (empty($hub)) {
// Create a new record in 'registration_hubs'.
$hub = new stdClass();
$hub->token = get_site_identifier();
$hub->secret = $hub->token;
$hub->huburl = HUB_MOODLEORGHUBURL;
$hub->hubname = 'moodle';
$hub->confirmed = 0;
$hub->timemodified = time();
$hub->id = $DB->insert_record('registration_hubs', $hub);
self::$registration = null;
}
$params = self::get_site_info();
// The most conservative limit for the redirect URL length is 2000 characters. Only pass parameters before
// we reach this limit. The next registration update will update all fields.
// We will also update registration after we receive confirmation from moodle.net.
$url = new moodle_url(HUB_MOODLEORGHUBURL . '/local/hub/siteregistration.php',
['token' => $hub->token, 'url' => $params['url']]);
foreach ($params as $key => $value) {
if (strlen($url->out(false, [$key => $value])) > 2000) {
break;
}
$url->param($key, $value);
}
$SESSION->registrationredirect = $returnurl;
redirect($url);
}
/**
* Unregister site
*
* @param bool $unpublishalladvertisedcourses
* @param bool $unpublishalluploadedcourses
* @return bool
*/
public static function unregister($unpublishalladvertisedcourses, $unpublishalluploadedcourses) {
global $DB;
if (!$hub = self::get_registration()) {
return true;
}
// Course unpublish went ok, unregister the site now.
try {
api::unregister_site();
} catch (moodle_exception $e) {
\core\notification::add(get_string('unregistrationerror', 'hub', $e->getMessage()),
\core\output\notification::NOTIFY_ERROR);
return false;
}
$DB->delete_records('registration_hubs', array('id' => $hub->id));
self::$registration = null;
return true;
}
/**
* Resets the registration token without changing site identifier so site can be re-registered
*
* @return bool
*/
public static function reset_token() {
global $DB;
if (!$hub = self::get_registration()) {
return true;
}
$DB->delete_records('registration_hubs', array('id' => $hub->id));
self::$registration = null;
}
/**
* Generate a new token for the site that is not registered
*
* @param string $token
* @throws moodle_exception
*/
public static function reset_site_identifier($token) {
global $DB, $CFG;
$registration = self::get_registration(false);
if (!$registration || $registration->token != $token) {
throw new moodle_exception('wrongtoken', 'hub',
new moodle_url('/admin/registration/index.php'));
}
$DB->delete_records('registration_hubs', array('id' => $registration->id));
self::$registration = null;
$CFG->siteidentifier = null;
get_site_identifier();
}
/**
* Returns information about the sites directory.
*
* Example of the return array:
* {
* "courses": 384,
* "description": "Official moodle sites directory",
* "downloadablecourses": 0,
* "enrollablecourses": 0,
* "hublogo": 1,
* "language": "en",
* "name": "moodle",
* "sites": 274175,
* "url": "https://stats.moodle.org",
* "imgurl": "https://stats.moodle.org/local/hub/webservice/download.php?filetype=hubscreenshot"
* }
*
* @return array|null
*/
public static function get_moodlenet_info() {
try {
return api::get_hub_info();
} catch (moodle_exception $e) {
// Ignore error, we only need it for displaying information about the sites directory.
// If this request fails, it's not a big deal.
return null;
}
}
/**
* Does admin need to be redirected to the registration page after install?
*
* @param bool|null $markasviewed if set to true will mark the registration form as viewed and admin will not be redirected
* to the registration form again (regardless of whether the site was registered or not).
* @return bool
*/
public static function show_after_install($markasviewed = null) {
global $CFG;
if (self::is_registered()) {
$showregistration = false;
$markasviewed = true;
} else {
$showregistration = !empty($CFG->registrationpending);
if ($showregistration && !site_is_public()) {
// If it's not a public site, don't redirect to registration, it won't work anyway.
$showregistration = false;
$markasviewed = true;
}
}
if ($markasviewed !== null) {
set_config('registrationpending', !$markasviewed);
}
return $showregistration;
}
/**
* Returns the list of the fields in the registration form that were added since registration or last manual update
*
* If this list is not empty the scheduled task will be paused and admin will be reminded to update registration manually.
*
* @return array
*/
public static function get_new_registration_fields() {
$fieldsneedconfirm = [];
if (!self::is_registered()) {
// Nothing to update if site is not registered.
return $fieldsneedconfirm;
}
$lastupdated = (int)get_config('hub', 'site_regupdateversion');
foreach (self::CONFIRM_NEW_FIELDS as $version => $fields) {
if ($version > $lastupdated) {
$fieldsneedconfirm = array_merge($fieldsneedconfirm, $fields);
}
}
return $fieldsneedconfirm;
}
/**
* Redirect to the site registration form if it's a new install, upgrade or registration needs updating.
*
* @param string|moodle_url $url
*/
public static function registration_reminder($url) {
if (defined('BEHAT_SITE_RUNNING') && BEHAT_SITE_RUNNING) {
// No redirection during behat runs.
return;
}
if (!has_capability('moodle/site:config', context_system::instance())) {
return;
}
if (self::show_after_install() || self::get_new_registration_fields()) {
$returnurl = new moodle_url($url);
redirect(new moodle_url('/admin/registration/index.php', ['returnurl' => $returnurl->out_as_local_url(false)]));
}
}
}
+322
View File
@@ -0,0 +1,322 @@
<?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/>.
/**
* Class site_registration_form
*
* @package core
* @copyright 2017 Marina Glancy
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core\hub;
defined('MOODLE_INTERNAL') || die();
use context_course;
use stdClass;
global $CFG;
require_once($CFG->libdir . '/formslib.php');
/**
* The site registration form. Information will be sent to the sites directory.
*
* @author Jerome Mouneyrac <jerome@mouneyrac.com>
* @package core
* @copyright 2017 Marina Glancy
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class site_registration_form extends \moodleform {
/**
* Form definition
*/
public function definition() {
global $CFG;
$strrequired = get_string('required');
$mform = & $this->_form;
$admin = get_admin();
$site = get_site();
$siteinfo = registration::get_site_info([
'name' => format_string($site->fullname, true, array('context' => context_course::instance(SITEID))),
'description' => $site->summary,
'contactname' => fullname($admin, true),
'contactemail' => $admin->email,
'contactphone' => $admin->phone1,
'street' => '',
'countrycode' => $admin->country ?: $CFG->country,
'regioncode' => '-', // Not supported yet.
'language' => explode('_', current_language())[0],
'geolocation' => '',
'emailalert' => 0,
'commnews' => 0,
'policyagreed' => 0
]);
// Fields that need to be highlighted.
$highlightfields = registration::get_new_registration_fields();
$mform->addElement('header', 'moodle', get_string('registrationinfo', 'hub'));
$mform->addElement('text', 'name', get_string('sitename', 'hub'),
array('class' => 'registration_textfield', 'maxlength' => 255));
$mform->setType('name', PARAM_TEXT);
$mform->addHelpButton('name', 'sitename', 'hub');
$mform->addElement('select', 'privacy', get_string('siteprivacy', 'hub'), registration::site_privacy_options());
$mform->setType('privacy', PARAM_ALPHA);
$mform->addHelpButton('privacy', 'siteprivacy', 'hub');
unset($options);
$mform->addElement('textarea', 'description', get_string('sitedesc', 'hub'),
array('rows' => 3, 'cols' => 41));
$mform->setType('description', PARAM_TEXT);
$mform->addHelpButton('description', 'sitedesc', 'hub');
$languages = get_string_manager()->get_list_of_languages();
\core_collator::asort($languages);
$mform->addElement('select', 'language', get_string('sitelang', 'hub'), $languages);
$mform->setType('language', PARAM_ALPHANUMEXT);
$mform->addHelpButton('language', 'sitelang', 'hub');
// Postal address was part of this form before but not any more.
$mform->addElement('hidden', 'street');
$mform->setType('street', PARAM_TEXT);
$mform->addHelpButton('street', 'postaladdress', 'hub');
$mform->addElement('hidden', 'regioncode', '-');
$mform->setType('regioncode', PARAM_ALPHANUMEXT);
$countries = ['' => ''] + get_string_manager()->get_list_of_countries();
$mform->addElement('select', 'countrycode', get_string('sitecountry', 'hub'), $countries);
$mform->setType('countrycode', PARAM_ALPHANUMEXT);
$mform->addHelpButton('countrycode', 'sitecountry', 'hub');
$mform->addRule('countrycode', $strrequired, 'required', null, 'client');
// Geolocation was part of this form before but not any more.
$mform->addElement('hidden', 'geolocation');
$mform->setType('geolocation', PARAM_RAW);
$mform->addHelpButton('geolocation', 'sitegeolocation', 'hub');
// Admin name was part of this form before but not any more.
$mform->addElement('hidden', 'contactname');
$mform->setType('contactname', PARAM_TEXT);
$mform->addHelpButton('contactname', 'siteadmin', 'hub');
$mform->addElement('hidden', 'contactphone');
$mform->setType('contactphone', PARAM_TEXT);
$mform->addHelpButton('contactphone', 'sitephone', 'hub');
$mform->addElement('text', 'contactemail', get_string('siteemail', 'hub'),
array('class' => 'registration_textfield'));
$mform->addRule('contactemail', $strrequired, 'required', null, 'client');
$mform->setType('contactemail', PARAM_EMAIL);
$mform->addHelpButton('contactemail', 'siteemail', 'hub');
$options = array();
$options[0] = get_string("registrationcontactno");
$options[1] = get_string("registrationcontactyes");
$mform->addElement('select', 'contactable', get_string('siteregistrationcontact', 'hub'), $options);
$mform->setType('contactable', PARAM_INT);
$mform->addHelpButton('contactable', 'siteregistrationcontact', 'hub');
$mform->hideIf('contactable', 'privacy', 'eq', registration::HUB_SITENOTPUBLISHED);
unset($options);
$this->add_checkbox_with_email('emailalert', 'siteregistrationemail', false, get_string('registrationyes'));
$this->add_checkbox_with_email(
'commnews',
'sitecommnews',
in_array('commnews', $highlightfields),
get_string('sitecommnewsyes', 'hub')
);
// TODO site logo.
$mform->addElement('hidden', 'imageurl', ''); // TODO: temporary.
$mform->setType('imageurl', PARAM_URL);
$mform->addElement('checkbox', 'policyagreed', get_string('policyagreed', 'hub'),
get_string('policyagreeddesc', 'hub', HUB_MOODLEORGHUBURL . '/privacy'));
$mform->addRule('policyagreed', $strrequired, 'required', null, 'client');
$mform->addElement('header', 'sitestats', get_string('sendfollowinginfo', 'hub'));
$mform->setExpanded('sitestats', !empty($highlightfields));
$mform->addElement('static', 'urlstring', get_string('siteurl', 'hub'), $siteinfo['url']);
$mform->addHelpButton('urlstring', 'siteurl', 'hub');
// Display statistic that are going to be retrieve by the sites directory.
$mform->addElement('static', 'siteinfosummary', get_string('sendfollowinginfo', 'hub'), registration::get_stats_summary($siteinfo));
// Check if it's a first registration or update.
if (registration::is_registered()) {
$buttonlabel = get_string('updatesiteregistration', 'core_hub');
$mform->addElement('hidden', 'update', true);
$mform->setType('update', PARAM_BOOL);
} else {
$buttonlabel = get_string('register', 'core_admin');
}
$this->add_action_buttons(false, $buttonlabel);
$mform->addElement('hidden', 'returnurl');
$mform->setType('returnurl', PARAM_LOCALURL);
// Prepare and set data.
$siteinfo['emailalertnewemail'] = !empty($siteinfo['emailalert']) && !empty($siteinfo['emailalertemail']);
if (empty($siteinfo['emailalertnewemail'])) {
$siteinfo['emailalertemail'] = '';
}
$siteinfo['commnewsnewemail'] = !empty($siteinfo['commnews']) && !empty($siteinfo['commnewsemail']);
if (empty($siteinfo['commnewsnewemail'])) {
$siteinfo['commnewsemail'] = '';
}
// Set data. Always require to check policyagreed even if it was checked earlier.
$this->set_data(['policyagreed' => 0] + $siteinfo);
}
/**
* Add yes/no select with additional checkbox allowing to specify another email
*
* @deprecated since Moodle 3.11 - MDL-71460 The form elements using this have been converted to checkboxes
* @todo MDL-71472 - Will be deleted in 4.3
* @see \core\hub\site_registration_form::add_checkbox_with_email()
* @param string $elementname
* @param string $stridentifier
* @param array|null $options options for the select element
* @param bool $highlight highlight as a new field
*/
protected function add_select_with_email($elementname, $stridentifier, $options = null, $highlight = false) {
debugging('add_select_with_email() is deprecated. Please use add_checkbox_with_email() instead.', DEBUG_DEVELOPER);
$mform = $this->_form;
if ($options === null) {
$options = [0 => get_string('no'), 1 => get_string('yes')];
}
$group = [
$mform->createElement('select', $elementname, get_string($stridentifier, 'hub'), $options),
$mform->createElement('static', $elementname . 'sep', '', '<br/>'),
$mform->createElement('advcheckbox', $elementname . 'newemail', '', get_string('usedifferentemail', 'hub'),
['onchange' => "this.form.elements['{$elementname}email'].focus();"]),
$mform->createElement('text', $elementname . 'email', get_string('email'))
];
$element = $mform->addElement('group', $elementname . 'group', get_string($stridentifier, 'hub'), $group, '', false);
if ($highlight) {
$element->setAttributes(['class' => $element->getAttribute('class') . ' needsconfirmation mark']);
}
$mform->hideIf($elementname . 'email', $elementname, 'eq', 0);
$mform->hideIf($elementname . 'newemail', $elementname, 'eq', 0);
$mform->hideIf($elementname . 'email', $elementname . 'newemail', 'notchecked');
$mform->setType($elementname, PARAM_INT);
$mform->setType($elementname . 'email', PARAM_RAW_TRIMMED); // E-mail will be validated in validation().
$mform->addHelpButton($elementname . 'group', $stridentifier, 'hub');
}
/**
* Add yes/no checkbox with additional checkbox allowing to specify another email
*
* @param string $elementname
* @param string $stridentifier
* @param bool $highlight highlight as a new field
* @param string $checkboxtext The text to show after the text.
*/
protected function add_checkbox_with_email($elementname, $stridentifier, $highlight = false, string $checkboxtext = '') {
$mform = $this->_form;
$group = [
$mform->createElement('advcheckbox', $elementname, '', $checkboxtext, ['class' => 'pt-2']),
$mform->createElement('static', $elementname . 'sep', '', '<br/>'),
$mform->createElement('advcheckbox', $elementname . 'newemail', '', get_string('usedifferentemail', 'hub'),
['onchange' => "this.form.elements['{$elementname}email'].focus();"]),
$mform->createElement('text', $elementname . 'email', get_string('email'))
];
$element = $mform->addElement('group', $elementname . 'group', get_string($stridentifier, 'hub'), $group, '', false);
if ($highlight) {
$element->setAttributes(['class' => $element->getAttribute('class') . ' needsconfirmation mark']);
}
$mform->hideif($elementname . 'email', $elementname, 'eq', 0);
$mform->hideif($elementname . 'newemail', $elementname, 'eq', 0);
$mform->hideif($elementname . 'email', $elementname . 'newemail', 'notchecked');
$mform->setType($elementname, PARAM_INT);
$mform->setType($elementname . 'email', PARAM_RAW_TRIMMED); // E-mail will be validated in validation().
$mform->addHelpButton($elementname . 'group', $stridentifier, 'hub');
}
/**
* Validation of the form data
*
* @param array $data array of ("fieldname"=>value) of submitted data
* @param array $files array of uploaded files "element_name"=>tmp_file_path
* @return array of "element_name"=>"error_description" if there are errors,
* or an empty array if everything is OK
*/
public function validation($data, $files) {
$errors = parent::validation($data, $files);
// Validate optional emails. We do not use PARAM_EMAIL because it blindly clears the field if it is not a valid email.
if (!empty($data['emailalert']) && !empty($data['emailalertnewemail']) && !validate_email($data['emailalertemail'])) {
$errors['emailalertgroup'] = get_string('invalidemail');
}
if (!empty($data['commnews']) && !empty($data['commnewsnewemail']) && !validate_email($data['commnewsemail'])) {
$errors['commnewsgroup'] = get_string('invalidemail');
}
return $errors;
}
/**
* Returns the form data
*
* @return stdClass
*/
public function get_data() {
if ($data = parent::get_data()) {
// Never return '*newemail' checkboxes, always return 'emailalertemail' and 'commnewsemail' even if not applicable.
if (empty($data->emailalert) || empty($data->emailalertnewemail)) {
$data->emailalertemail = null;
}
unset($data->emailalertnewemail);
if (empty($data->commnews) || empty($data->commnewsnewemail)) {
$data->commnewsemail = null;
}
unset($data->commnewsnewemail);
// Always return 'contactable'.
$data->contactable = empty($data->contactable) ? 0 : 1;
if (debugging('', DEBUG_DEVELOPER)) {
// Display debugging message for developers who added fields to the form and forgot to add them to registration::FORM_FIELDS.
$keys = array_diff(array_keys((array)$data),
['returnurl', 'mform_isexpanded_id_sitestats', 'submitbutton', 'update']);
if ($extrafields = array_diff($keys, registration::FORM_FIELDS)) {
debugging('Found extra fields in the form results: ' . join(', ', $extrafields), DEBUG_DEVELOPER);
}
if ($missingfields = array_diff(registration::FORM_FIELDS, $keys)) {
debugging('Some fields are missing in the form results: ' . join(', ', $missingfields), DEBUG_DEVELOPER);
}
}
}
return $data;
}
}