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
+560
View File
@@ -0,0 +1,560 @@
<?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/>.
/**
* This file contains the profile_define_base class.
*
* @package core_user
* @copyright 2007 onwards Shane Elliot {@link http://pukunui.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/**
* Class profile_define_base
*
* @copyright 2007 onwards Shane Elliot {@link http://pukunui.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class profile_define_base {
/**
* Prints out the form snippet for creating or editing a profile field
* @param MoodleQuickForm $form instance of the moodleform class
*/
public function define_form(&$form) {
$form->addElement('header', '_commonsettings', get_string('profilecommonsettings', 'admin'));
$this->define_form_common($form);
$form->addElement('header', '_specificsettings', get_string('profilespecificsettings', 'admin'));
$this->define_form_specific($form);
}
/**
* Prints out the form snippet for the part of creating or editing a profile field common to all data types.
*
* @param MoodleQuickForm $form instance of the moodleform class
*/
public function define_form_common(&$form) {
$strrequired = get_string('required');
// Accepted values for 'shortname' would follow [a-zA-Z0-9_] pattern,
// but we are accepting any PARAM_TEXT value here,
// and checking [a-zA-Z0-9_] pattern in define_validate_common() function to throw an error when needed.
$form->addElement('text', 'shortname', get_string('profileshortname', 'admin'), 'maxlength="100" size="25"');
$form->addRule('shortname', $strrequired, 'required', null, 'client');
$form->setType('shortname', PARAM_TEXT);
$form->addElement('text', 'name', get_string('profilename', 'admin'), 'size="50"');
$form->addRule('name', $strrequired, 'required', null, 'client');
$form->setType('name', PARAM_TEXT);
$form->addElement('editor', 'description', get_string('profiledescription', 'admin'), null, null);
$form->addElement('selectyesno', 'required', get_string('profilerequired', 'admin'));
$form->addElement('selectyesno', 'locked', get_string('profilelocked', 'admin'));
$form->addElement('selectyesno', 'forceunique', get_string('profileforceunique', 'admin'));
$form->addElement('selectyesno', 'signup', get_string('profilesignup', 'admin'));
$choices = array();
$choices[PROFILE_VISIBLE_NONE] = get_string('profilevisiblenone', 'admin');
$choices[PROFILE_VISIBLE_PRIVATE] = get_string('profilevisibleprivate', 'admin');
$choices[PROFILE_VISIBLE_TEACHERS] = get_string('profilevisibleteachers', 'admin');
$choices[PROFILE_VISIBLE_ALL] = get_string('profilevisibleall', 'admin');
$form->addElement('select', 'visible', get_string('profilevisible', 'admin'), $choices);
$form->addHelpButton('visible', 'profilevisible', 'admin');
$form->setDefault('visible', PROFILE_VISIBLE_ALL);
$choices = profile_list_categories();
$form->addElement('select', 'categoryid', get_string('profilecategory', 'admin'), $choices);
}
/**
* Prints out the form snippet for the part of creating or editing a profile field specific to the current data type.
* @param MoodleQuickForm $form instance of the moodleform class
*/
public function define_form_specific($form) {
// Do nothing - overwrite if necessary.
}
/**
* Validate the data from the add/edit profile field form.
*
* Generally this method should not be overwritten by child classes.
*
* @param stdClass|array $data from the add/edit profile field form
* @param array $files
* @return array associative array of error messages
*/
public function define_validate($data, $files) {
$data = (object)$data;
$err = array();
$err += $this->define_validate_common($data, $files);
$err += $this->define_validate_specific($data, $files);
return $err;
}
/**
* Validate the data from the add/edit profile field form that is common to all data types.
*
* Generally this method should not be overwritten by child classes.
*
* @param stdClass|array $data from the add/edit profile field form
* @param array $files
* @return array associative array of error messages
*/
public function define_validate_common($data, $files) {
global $DB;
$err = array();
// Check the shortname was not truncated by cleaning.
if (empty($data->shortname)) {
$err['shortname'] = get_string('required');
} else {
// Check allowed pattern (numbers, letters and underscore).
if (!preg_match('/^[a-zA-Z0-9_]+$/', $data->shortname)) {
$err['shortname'] = get_string('profileshortnameinvalid', 'admin');
} else {
// Fetch field-record from DB.
$field = profile_get_custom_field_data_by_shortname($data->shortname);
// Check the shortname is unique.
if ($field and $field->id <> $data->id) {
$err['shortname'] = get_string('profileshortnamenotunique', 'admin');
}
// NOTE: since 2.0 the shortname may collide with existing fields in $USER because we load these fields into
// $USER->profile array instead.
}
}
// No further checks necessary as the form class will take care of it.
return $err;
}
/**
* Validate the data from the add/edit profile field form
* that is specific to the current data type
* @param array $data
* @param array $files
* @return array associative array of error messages
*/
public function define_validate_specific($data, $files) {
// Do nothing - overwrite if necessary.
return array();
}
/**
* Alter form based on submitted or existing data
* @param MoodleQuickForm $mform
*/
public function define_after_data(&$mform) {
// Do nothing - overwrite if necessary.
}
/**
* Add a new profile field or save changes to current field
* @param array|stdClass $data from the add/edit profile field form
*/
public function define_save($data) {
global $DB;
$data = $this->define_save_preprocess($data); // Hook for child classes.
$old = false;
if (!empty($data->id)) {
$old = $DB->get_record('user_info_field', array('id' => (int)$data->id));
}
// Check to see if the category has changed.
if (!$old or $old->categoryid != $data->categoryid) {
$data->sortorder = $DB->count_records('user_info_field', array('categoryid' => $data->categoryid)) + 1;
}
if (empty($data->id)) {
unset($data->id);
$data->id = $DB->insert_record('user_info_field', $data);
} else {
$DB->update_record('user_info_field', $data);
}
$field = $DB->get_record('user_info_field', array('id' => $data->id));
if ($old) {
\core\event\user_info_field_updated::create_from_field($field)->trigger();
} else {
\core\event\user_info_field_created::create_from_field($field)->trigger();
}
profile_purge_user_fields_cache();
}
/**
* Preprocess data from the add/edit profile field form before it is saved.
*
* This method is a hook for the child classes to overwrite.
*
* @param array|stdClass $data from the add/edit profile field form
* @return array|stdClass processed data object
*/
public function define_save_preprocess($data) {
// Do nothing - overwrite if necessary.
return $data;
}
/**
* Provides a method by which we can allow the default data in profile_define_* to use an editor
*
* This should return an array of editor names (which will need to be formatted/cleaned)
*
* @return array
*/
public function define_editors() {
return array();
}
}
/**
* Reorder the profile fields within a given category starting at the field at the given startorder.
*/
function profile_reorder_fields() {
global $DB;
if ($categories = $DB->get_records('user_info_category')) {
foreach ($categories as $category) {
$i = 1;
if ($fields = $DB->get_records('user_info_field', array('categoryid' => $category->id), 'sortorder ASC')) {
foreach ($fields as $field) {
$f = new stdClass();
$f->id = $field->id;
$f->sortorder = $i++;
$DB->update_record('user_info_field', $f);
}
}
}
profile_purge_user_fields_cache();
}
}
/**
* Reorder the profile categoriess starting at the category at the given startorder.
*/
function profile_reorder_categories() {
global $DB;
$i = 1;
if ($categories = $DB->get_records('user_info_category', null, 'sortorder ASC')) {
foreach ($categories as $cat) {
$c = new stdClass();
$c->id = $cat->id;
$c->sortorder = $i++;
$DB->update_record('user_info_category', $c);
}
profile_purge_user_fields_cache();
}
}
/**
* Delete a profile category
* @param int $id of the category to be deleted
* @return bool success of operation
*/
function profile_delete_category($id) {
global $DB;
// Retrieve the category.
if (!$category = $DB->get_record('user_info_category', array('id' => $id))) {
throw new \moodle_exception('invalidcategoryid');
}
if (!$categories = $DB->get_records('user_info_category', null, 'sortorder ASC')) {
throw new \moodle_exception('nocate', 'debug');
}
unset($categories[$category->id]);
if (!count($categories)) {
return false; // We can not delete the last category.
}
// Does the category contain any fields.
if ($DB->count_records('user_info_field', array('categoryid' => $category->id))) {
if (array_key_exists($category->sortorder - 1, $categories)) {
$newcategory = $categories[$category->sortorder - 1];
} else if (array_key_exists($category->sortorder + 1, $categories)) {
$newcategory = $categories[$category->sortorder + 1];
} else {
$newcategory = reset($categories); // Get first category if sortorder broken.
}
$sortorder = $DB->count_records('user_info_field', array('categoryid' => $newcategory->id)) + 1;
if ($fields = $DB->get_records('user_info_field', array('categoryid' => $category->id), 'sortorder ASC')) {
foreach ($fields as $field) {
$f = new stdClass();
$f->id = $field->id;
$f->sortorder = $sortorder++;
$f->categoryid = $newcategory->id;
if ($DB->update_record('user_info_field', $f)) {
$field->sortorder = $f->sortorder;
$field->categoryid = $f->categoryid;
\core\event\user_info_field_updated::create_from_field($field)->trigger();
}
}
}
}
// Finally we get to delete the category.
$DB->delete_records('user_info_category', array('id' => $category->id));
profile_reorder_categories();
\core\event\user_info_category_deleted::create_from_category($category)->trigger();
profile_purge_user_fields_cache();
return true;
}
/**
* Deletes a profile field.
* @param int $id
*/
function profile_delete_field($id) {
global $DB;
// Remove any user data associated with this field.
if (!$DB->delete_records('user_info_data', array('fieldid' => $id))) {
throw new \moodle_exception('cannotdeletecustomfield');
}
// Note: Any availability conditions that depend on this field will remain,
// but show the field as missing until manually corrected to something else.
// Need to rebuild course cache to update the info.
rebuild_course_cache(0, true);
// Prior to the delete, pull the record for the event.
$field = $DB->get_record('user_info_field', array('id' => $id));
// Try to remove the record from the database.
$DB->delete_records('user_info_field', array('id' => $id));
\core\event\user_info_field_deleted::create_from_field($field)->trigger();
profile_purge_user_fields_cache();
// Reorder the remaining fields in the same category.
profile_reorder_fields();
}
/**
* Change the sort order of a field
*
* @param int $id of the field
* @param string $move direction of move
* @return bool success of operation
*/
function profile_move_field($id, $move) {
global $DB;
// Get the field object.
if (!$field = $DB->get_record('user_info_field', array('id' => $id))) {
return false;
}
// Count the number of fields in this category.
$fieldcount = $DB->count_records('user_info_field', array('categoryid' => $field->categoryid));
// Calculate the new sortorder.
if ( ($move == 'up') and ($field->sortorder > 1)) {
$neworder = $field->sortorder - 1;
} else if (($move == 'down') and ($field->sortorder < $fieldcount)) {
$neworder = $field->sortorder + 1;
} else {
return false;
}
// Retrieve the field object that is currently residing in the new position.
$params = array('categoryid' => $field->categoryid, 'sortorder' => $neworder);
if ($swapfield = $DB->get_record('user_info_field', $params)) {
// Swap the sortorders.
$swapfield->sortorder = $field->sortorder;
$field->sortorder = $neworder;
// Update the field records.
$DB->update_record('user_info_field', $field);
$DB->update_record('user_info_field', $swapfield);
\core\event\user_info_field_updated::create_from_field($field)->trigger();
\core\event\user_info_field_updated::create_from_field($swapfield)->trigger();
}
profile_reorder_fields();
return true;
}
/**
* Change the sort order of a category.
*
* @param int $id of the category
* @param string $move direction of move
* @return bool success of operation
*/
function profile_move_category($id, $move) {
global $DB;
// Get the category object.
if (!($category = $DB->get_record('user_info_category', array('id' => $id)))) {
return false;
}
// Count the number of categories.
$categorycount = $DB->count_records('user_info_category');
// Calculate the new sortorder.
if (($move == 'up') and ($category->sortorder > 1)) {
$neworder = $category->sortorder - 1;
} else if (($move == 'down') and ($category->sortorder < $categorycount)) {
$neworder = $category->sortorder + 1;
} else {
return false;
}
// Retrieve the category object that is currently residing in the new position.
if ($swapcategory = $DB->get_record('user_info_category', array('sortorder' => $neworder))) {
// Swap the sortorders.
$swapcategory->sortorder = $category->sortorder;
$category->sortorder = $neworder;
// Update the category records.
$DB->update_record('user_info_category', $category);
$DB->update_record('user_info_category', $swapcategory);
\core\event\user_info_category_updated::create_from_category($category)->trigger();
\core\event\user_info_category_updated::create_from_category($swapcategory)->trigger();
profile_purge_user_fields_cache();
return true;
}
return false;
}
/**
* Retrieve a list of all the available data types
* @return array a list of the datatypes suitable to use in a select statement
*/
function profile_list_datatypes() {
$datatypes = array();
$plugins = core_component::get_plugin_list('profilefield');
foreach ($plugins as $type => $unused) {
$datatypes[$type] = get_string('pluginname', 'profilefield_'.$type);
}
asort($datatypes);
return $datatypes;
}
/**
* Retrieve a list of categories and ids suitable for use in a form
* @return array
*/
function profile_list_categories() {
global $DB;
$categories = $DB->get_records_menu('user_info_category', null, 'sortorder ASC', 'id, name');
return array_map('format_string', $categories);
}
/**
* Create or update a profile category
*
* @param stdClass $data
*/
function profile_save_category(stdClass $data): void {
global $DB;
if (empty($data->id)) {
unset($data->id);
$data->sortorder = $DB->count_records('user_info_category') + 1;
$data->id = $DB->insert_record('user_info_category', $data, true);
$createdcategory = $DB->get_record('user_info_category', array('id' => $data->id));
\core\event\user_info_category_created::create_from_category($createdcategory)->trigger();
} else {
$DB->update_record('user_info_category', $data);
$updatedcateogry = $DB->get_record('user_info_category', array('id' => $data->id));
\core\event\user_info_category_updated::create_from_category($updatedcateogry)->trigger();
}
profile_reorder_categories();
profile_purge_user_fields_cache();
}
/**
* Save updated field definition or create a new field
*
* @param stdClass $data data from the form profile_field_form
* @param array $editors editors for this form field type
*/
function profile_save_field(stdClass $data, array $editors): void {
global $CFG;
require_once($CFG->dirroot.'/user/profile/field/'.$data->datatype.'/define.class.php');
$newfield = 'profile_define_'.$data->datatype;
/** @var profile_define_base $formfield */
$formfield = new $newfield();
// Collect the description and format back into the proper data structure from the editor.
// Note: This field will ALWAYS be an editor.
$data->descriptionformat = $data->description['format'];
$data->description = $data->description['text'];
// Check whether the default data is an editor, this is (currently) only the textarea field type.
if (is_array($data->defaultdata) && array_key_exists('text', $data->defaultdata)) {
// Collect the default data and format back into the proper data structure from the editor.
$data->defaultdataformat = $data->defaultdata['format'];
$data->defaultdata = $data->defaultdata['text'];
}
// Convert the data format for.
if (is_array($editors)) {
foreach ($editors as $editor) {
if (isset($field->$editor)) {
$field->{$editor.'format'} = $field->{$editor}['format'];
$field->$editor = $field->{$editor}['text'];
}
}
}
$formfield->define_save($data);
profile_reorder_fields();
profile_reorder_categories();
}
/**
* Purge the cache for the user profile fields
*/
function profile_purge_user_fields_cache() {
$cache = \cache::make_from_params(cache_store::MODE_REQUEST, 'core_profile', 'customfields',
[], ['simplekeys' => true, 'simpledata' => true]);
$cache->purge();
}
@@ -0,0 +1,216 @@
<?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/>.
/**
* Privacy class for requesting user data.
*
* @package profilefield_checkbox
* @copyright 2018 Mihail Geshoski <mihail@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace profilefield_checkbox\privacy;
defined('MOODLE_INTERNAL') || die();
use \core_privacy\local\metadata\collection;
use \core_privacy\local\request\contextlist;
use \core_privacy\local\request\approved_contextlist;
use core_privacy\local\request\userlist;
use core_privacy\local\request\approved_userlist;
/**
* Privacy class for requesting user data.
*
* @copyright 2018 Mihail Geshoski <mihail@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider implements
\core_privacy\local\metadata\provider,
\core_privacy\local\request\core_userlist_provider,
\core_privacy\local\request\plugin\provider {
/**
* Returns meta data about this system.
*
* @param collection $collection The initialised collection to add items to.
* @return collection A listing of user data stored through this system.
*/
public static function get_metadata(collection $collection): collection {
return $collection->add_database_table('user_info_data', [
'userid' => 'privacy:metadata:profilefield_checkbox:userid',
'fieldid' => 'privacy:metadata:profilefield_checkbox:fieldid',
'data' => 'privacy:metadata:profilefield_checkbox:data',
'dataformat' => 'privacy:metadata:profilefield_checkbox:dataformat'
], 'privacy:metadata:profilefield_checkbox:tableexplanation');
}
/**
* Get the list of contexts that contain user information for the specified user.
*
* @param int $userid The user to search.
* @return contextlist $contextlist The contextlist containing the list of contexts used in this plugin.
*/
public static function get_contexts_for_userid(int $userid): contextlist {
$sql = "SELECT ctx.id
FROM {user_info_data} uda
JOIN {user_info_field} uif ON uda.fieldid = uif.id
JOIN {context} ctx ON ctx.instanceid = uda.userid
AND ctx.contextlevel = :contextlevel
WHERE uda.userid = :userid
AND uif.datatype = :datatype";
$params = [
'userid' => $userid,
'contextlevel' => CONTEXT_USER,
'datatype' => 'checkbox'
];
$contextlist = new contextlist();
$contextlist->add_from_sql($sql, $params);
return $contextlist;
}
/**
* Get the list of users within a specific context.
*
* @param userlist $userlist The userlist containing the list of users who have data in this context/plugin combination.
*/
public static function get_users_in_context(userlist $userlist) {
$context = $userlist->get_context();
if (!$context instanceof \context_user) {
return;
}
$sql = "SELECT uda.userid
FROM {user_info_data} uda
JOIN {user_info_field} uif
ON uda.fieldid = uif.id
WHERE uda.userid = :userid
AND uif.datatype = :datatype";
$params = [
'userid' => $context->instanceid,
'datatype' => 'checkbox'
];
$userlist->add_from_sql('userid', $sql, $params);
}
/**
* Export all user data for the specified user, in the specified contexts.
*
* @param approved_contextlist $contextlist The approved contexts to export information for.
*/
public static function export_user_data(approved_contextlist $contextlist) {
$user = $contextlist->get_user();
foreach ($contextlist->get_contexts() as $context) {
// Check if the context is a user context.
if ($context->contextlevel == CONTEXT_USER && $context->instanceid == $user->id) {
$results = static::get_records($user->id);
foreach ($results as $result) {
$data = (object) [
'name' => $result->name,
'description' => $result->description,
'data' => $result->data
];
\core_privacy\local\request\writer::with_context($context)->export_data([
get_string('pluginname', 'profilefield_checkbox')], $data);
}
}
}
}
/**
* Delete all user data which matches the specified context.
*
* @param context $context A user context.
*/
public static function delete_data_for_all_users_in_context(\context $context) {
// Delete data only for user context.
if ($context->contextlevel == CONTEXT_USER) {
static::delete_data($context->instanceid);
}
}
/**
* Delete multiple users within a single context.
*
* @param approved_userlist $userlist The approved context and user information to delete information for.
*/
public static function delete_data_for_users(approved_userlist $userlist) {
$context = $userlist->get_context();
if ($context instanceof \context_user) {
static::delete_data($context->instanceid);
}
}
/**
* Delete all user data for the specified user, in the specified contexts.
*
* @param approved_contextlist $contextlist The approved contexts and user information to delete information for.
*/
public static function delete_data_for_user(approved_contextlist $contextlist) {
$user = $contextlist->get_user();
foreach ($contextlist->get_contexts() as $context) {
// Check if the context is a user context.
if ($context->contextlevel == CONTEXT_USER && $context->instanceid == $user->id) {
static::delete_data($context->instanceid);
}
}
}
/**
* Delete data related to a userid.
*
* @param int $userid The user ID
*/
protected static function delete_data($userid) {
global $DB;
$params = [
'userid' => $userid,
'datatype' => 'checkbox'
];
$DB->delete_records_select('user_info_data', "fieldid IN (
SELECT id FROM {user_info_field} WHERE datatype = :datatype)
AND userid = :userid", $params);
}
/**
* Get records related to this plugin and user.
*
* @param int $userid The user ID
* @return array An array of records.
*/
protected static function get_records($userid) {
global $DB;
$sql = "SELECT *
FROM {user_info_data} uda
JOIN {user_info_field} uif ON uda.fieldid = uif.id
WHERE uda.userid = :userid
AND uif.datatype = :datatype";
$params = [
'userid' => $userid,
'datatype' => 'checkbox'
];
return $DB->get_records_sql($sql, $params);
}
}
@@ -0,0 +1,45 @@
<?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/>.
/**
* Checkbox profile field
*
* @package profilefield_checkbox
* @copyright 2008 onwards Shane Elliot {@link http://pukunui.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/**
* Class profile_define_checkbox
* @copyright 2008 onwards Shane Elliot {@link http://pukunui.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class profile_define_checkbox extends profile_define_base {
/**
* Add elements for creating/editing a checkbox profile field.
*
* @param moodleform $form
*/
public function define_form_specific($form) {
// Select whether or not this should be checked by default.
$form->addElement('selectyesno', 'defaultdata', get_string('profiledefaultchecked', 'admin'));
$form->setDefault('defaultdata', 0); // Defaults to 'no'.
$form->setType('defaultdata', PARAM_BOOL);
}
}
@@ -0,0 +1,88 @@
<?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 profile_field_checkbox
*
* @package profilefield_checkbox
* @copyright 2008 onwards Shane Elliot {@link http://pukunui.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class profile_field_checkbox extends profile_field_base {
/**
* Add elements for editing the profile field value.
* @param moodleform $mform
*/
public function edit_field_add($mform) {
// Create the form field.
$checkbox = $mform->addElement('advcheckbox', $this->inputname, format_string($this->field->name));
if ($this->data == '1') {
$checkbox->setChecked(true);
}
$mform->setType($this->inputname, PARAM_BOOL);
if ($this->is_required() and !has_capability('moodle/user:update', context_system::instance())) {
$mform->addRule($this->inputname, get_string('required'), 'nonzero', null, 'client');
}
}
/**
* Override parent {@see profile_field_base::is_empty} check
*
* We can't check the "data" property, because if not set by the user then it's populated by "defaultdata" of the field,
* which can also be 0 (false) therefore ensuring the parent class check could never return true for this comparison
*
* @return bool
*/
public function is_empty() {
return ($this->userid && !$this->field->hasuserdata);
}
/**
* Override parent {@see profile_field_base::show_field_content} check
*
* We only need to determine whether the field is visible, because we also want to show the "defaultdata" of the field,
* even if the user hasn't explicitly filled it in
*
* @param context|null $context
* @return bool
*/
public function show_field_content(?context $context = null): bool {
return $this->is_visible($context);
}
/**
* Display the data for this field
*
* @return string HTML.
*/
public function display_data() {
return $this->data ? get_string('yes') : get_string('no');
}
/**
* Return the field type and null properties.
* This will be used for validating the data submitted by a user.
*
* @return array the param type and null property
* @since Moodle 3.2
*/
public function get_field_properties() {
return array(PARAM_BOOL, NULL_NOT_ALLOWED);
}
}
@@ -0,0 +1,30 @@
<?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/>.
/**
* Strings for component 'profilefield_checkbox', language 'en', branch 'MOODLE_20_STABLE'
*
* @package profilefield_checkbox
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$string['pluginname'] = 'Checkbox';
$string['privacy:metadata:profilefield_checkbox:userid'] = 'The ID of the user whose data is stored by the Checkbox user profile field';
$string['privacy:metadata:profilefield_checkbox:fieldid'] = 'The ID of the profile field';
$string['privacy:metadata:profilefield_checkbox:data'] = 'The checkbox user profile field user data';
$string['privacy:metadata:profilefield_checkbox:dataformat'] = 'The format of Checkbox user profile field user data';
$string['privacy:metadata:profilefield_checkbox:tableexplanation'] = 'Additional profile data';
@@ -0,0 +1,301 @@
<?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/>.
/**
* Base class for unit tests for profilefield_checkbox.
*
* @package profilefield_checkbox
* @copyright 2018 Mihail Geshoski <mihail@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace profilefield_checkbox\privacy;
defined('MOODLE_INTERNAL') || die();
use core_privacy\tests\provider_testcase;
use profilefield_checkbox\privacy\provider;
use core_privacy\local\request\approved_userlist;
/**
* Unit tests for user\profile\field\checkbox\classes\privacy\provider.php
*
* @copyright 2018 Mihail Geshoski <mihail@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider_test extends provider_testcase {
/**
* Basic setup for these tests.
*/
public function setUp(): void {
$this->resetAfterTest(true);
}
/**
* Test getting the context for the user ID related to this plugin.
*/
public function test_get_contexts_for_userid(): void {
global $DB;
// Create profile category.
$categoryid = $this->add_profile_category();
// Create profile field.
$profilefieldid = $this->add_profile_field($categoryid, 'checkbox');
// Create a user.
$user = $this->getDataGenerator()->create_user();
$this->add_user_info_data($user->id, $profilefieldid, 'test data');
// Get the field that was created.
$userfielddata = $DB->get_records('user_info_data', array('userid' => $user->id));
// Confirm we got the right number of user field data.
$this->assertCount(1, $userfielddata);
$context = \context_user::instance($user->id);
$contextlist = provider::get_contexts_for_userid($user->id);
$this->assertEquals($context, $contextlist->current());
}
/**
* Test that data is exported correctly for this plugin.
*/
public function test_export_user_data(): void {
// Create profile category.
$categoryid = $this->add_profile_category();
// Create checkbox profile field.
$checkboxprofilefieldid = $this->add_profile_field($categoryid, 'checkbox');
// Create datetime profile field.
$datetimeprofilefieldid = $this->add_profile_field($categoryid, 'datetime');
// Create a user.
$user = $this->getDataGenerator()->create_user();
$context = \context_user::instance($user->id);
// Add checkbox user info data.
$this->add_user_info_data($user->id, $checkboxprofilefieldid, 'test data');
// Add datetime user info data.
$this->add_user_info_data($user->id, $datetimeprofilefieldid, '1524067200');
$writer = \core_privacy\local\request\writer::with_context($context);
$this->assertFalse($writer->has_any_data());
$this->export_context_data_for_user($user->id, $context, 'profilefield_checkbox');
$data = $writer->get_data([get_string('pluginname', 'profilefield_checkbox')]);
$this->assertCount(3, (array) $data);
$this->assertEquals('Test field', $data->name);
$this->assertEquals('This is a test.', $data->description);
$this->assertEquals('test data', $data->data);
}
/**
* Test that user data is deleted using the context.
*/
public function test_delete_data_for_all_users_in_context(): void {
global $DB;
// Create profile category.
$categoryid = $this->add_profile_category();
// Create checkbox profile field.
$checkboxprofilefieldid = $this->add_profile_field($categoryid, 'checkbox');
// Create datetime profile field.
$datetimeprofilefieldid = $this->add_profile_field($categoryid, 'datetime');
// Create a user.
$user = $this->getDataGenerator()->create_user();
$context = \context_user::instance($user->id);
// Add checkbox user info data.
$this->add_user_info_data($user->id, $checkboxprofilefieldid, 'test data');
// Add datetime user info data.
$this->add_user_info_data($user->id, $datetimeprofilefieldid, '1524067200');
// Check that we have two entries.
$userinfodata = $DB->get_records('user_info_data', ['userid' => $user->id]);
$this->assertCount(2, $userinfodata);
provider::delete_data_for_all_users_in_context($context);
// Check that the correct profile field has been deleted.
$userinfodata = $DB->get_records('user_info_data', ['userid' => $user->id]);
$this->assertCount(1, $userinfodata);
$this->assertNotEquals('test data', reset($userinfodata)->data);
}
/**
* Test that user data is deleted for this user.
*/
public function test_delete_data_for_user(): void {
global $DB;
// Create profile category.
$categoryid = $this->add_profile_category();
// Create checkbox profile field.
$checkboxprofilefieldid = $this->add_profile_field($categoryid, 'checkbox');
// Create datetime profile field.
$datetimeprofilefieldid = $this->add_profile_field($categoryid, 'datetime');
// Create a user.
$user = $this->getDataGenerator()->create_user();
$context = \context_user::instance($user->id);
// Add checkbox user info data.
$this->add_user_info_data($user->id, $checkboxprofilefieldid, 'test data');
// Add datetime user info data.
$this->add_user_info_data($user->id, $datetimeprofilefieldid, '1524067200');
// Check that we have two entries.
$userinfodata = $DB->get_records('user_info_data', ['userid' => $user->id]);
$this->assertCount(2, $userinfodata);
$approvedlist = new \core_privacy\local\request\approved_contextlist($user, 'profilefield_checkbox',
[$context->id]);
provider::delete_data_for_user($approvedlist);
// Check that the correct profile field has been deleted.
$userinfodata = $DB->get_records('user_info_data', ['userid' => $user->id]);
$this->assertCount(1, $userinfodata);
$this->assertNotEquals('test data', reset($userinfodata)->data);
}
/**
* Test that only users with a user context are fetched.
*/
public function test_get_users_in_context(): void {
$this->resetAfterTest();
$component = 'profilefield_checkbox';
// Create profile category.
$categoryid = $this->add_profile_category();
// Create profile field.
$profilefieldid = $this->add_profile_field($categoryid, 'checkbox');
// Create a user.
$user = $this->getDataGenerator()->create_user();
$usercontext = \context_user::instance($user->id);
// The list of users should not return anything yet (related data still haven't been created).
$userlist = new \core_privacy\local\request\userlist($usercontext, $component);
provider::get_users_in_context($userlist);
$this->assertCount(0, $userlist);
$this->add_user_info_data($user->id, $profilefieldid, 'test data');
// The list of users for user context should return the user.
provider::get_users_in_context($userlist);
$this->assertCount(1, $userlist);
$expected = [$user->id];
$actual = $userlist->get_userids();
$this->assertEquals($expected, $actual);
// The list of users for system context should not return any users.
$systemcontext = \context_system::instance();
$userlist = new \core_privacy\local\request\userlist($systemcontext, $component);
provider::get_users_in_context($userlist);
$this->assertCount(0, $userlist);
}
/**
* Test that data for users in approved userlist is deleted.
*/
public function test_delete_data_for_users(): void {
$this->resetAfterTest();
$component = 'profilefield_checkbox';
// Create profile category.
$categoryid = $this->add_profile_category();
// Create profile field.
$profilefieldid = $this->add_profile_field($categoryid, 'checkbox');
// Create user1.
$user1 = $this->getDataGenerator()->create_user();
$usercontext1 = \context_user::instance($user1->id);
// Create user2.
$user2 = $this->getDataGenerator()->create_user();
$usercontext2 = \context_user::instance($user2->id);
$this->add_user_info_data($user1->id, $profilefieldid, 'test data');
$this->add_user_info_data($user2->id, $profilefieldid, 'test data');
// The list of users for usercontext1 should return user1.
$userlist1 = new \core_privacy\local\request\userlist($usercontext1, $component);
provider::get_users_in_context($userlist1);
$this->assertCount(1, $userlist1);
$expected = [$user1->id];
$actual = $userlist1->get_userids();
$this->assertEquals($expected, $actual);
// The list of users for usercontext2 should return user2.
$userlist2 = new \core_privacy\local\request\userlist($usercontext2, $component);
provider::get_users_in_context($userlist2);
$this->assertCount(1, $userlist2);
$expected = [$user2->id];
$actual = $userlist2->get_userids();
$this->assertEquals($expected, $actual);
// Add userlist1 to the approved user list.
$approvedlist = new approved_userlist($usercontext1, $component, $userlist1->get_userids());
// Delete user data using delete_data_for_user for usercontext1.
provider::delete_data_for_users($approvedlist);
// Re-fetch users in usercontext1 - The user list should now be empty.
$userlist1 = new \core_privacy\local\request\userlist($usercontext1, $component);
provider::get_users_in_context($userlist1);
$this->assertCount(0, $userlist1);
// Re-fetch users in usercontext2 - The user list should not be empty (user2).
$userlist2 = new \core_privacy\local\request\userlist($usercontext2, $component);
provider::get_users_in_context($userlist2);
$this->assertCount(1, $userlist2);
// User data should be only removed in the user context.
$systemcontext = \context_system::instance();
// Add userlist2 to the approved user list in the system context.
$approvedlist = new approved_userlist($systemcontext, $component, $userlist2->get_userids());
// Delete user1 data using delete_data_for_user.
provider::delete_data_for_users($approvedlist);
// Re-fetch users in usercontext2 - The user list should not be empty (user2).
$userlist1 = new \core_privacy\local\request\userlist($usercontext2, $component);
provider::get_users_in_context($userlist1);
$this->assertCount(1, $userlist1);
}
/**
* Add dummy user info data.
*
* @param int $userid The ID of the user
* @param int $fieldid The ID of the field
* @param string $data The data
*/
private function add_user_info_data($userid, $fieldid, $data) {
global $DB;
$userinfodata = array(
'userid' => $userid,
'fieldid' => $fieldid,
'data' => $data,
'dataformat' => 0
);
$DB->insert_record('user_info_data', $userinfodata);
}
/**
* Add dummy profile category.
*
* @return int The ID of the profile category
*/
private function add_profile_category() {
$cat = $this->getDataGenerator()->create_custom_profile_field_category(['name' => 'Test category']);
return $cat->id;
}
/**
* Add dummy profile field.
*
* @param int $categoryid The ID of the profile category
* @param string $datatype The datatype of the profile field
* @return int The ID of the profile field
*/
private function add_profile_field($categoryid, $datatype) {
$data = $this->getDataGenerator()->create_custom_profile_field([
'datatype' => $datatype,
'shortname' => 'tstField',
'name' => 'Test field',
'description' => 'This is a test.',
'categoryid' => $categoryid,
]);
return $data->id;
}
}
@@ -0,0 +1,122 @@
<?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/>.
namespace profilefield_checkbox;
use advanced_testcase;
use profile_field_checkbox;
/**
* Unit tests for the field class
*
* @package profilefield_checkbox
* @covers \profile_field_checkbox
* @copyright 2024 Paul Holden <paulh@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class profile_field_checkbox_test extends advanced_testcase {
/**
* Load required test libraries
*/
public static function setUpBeforeClass(): void {
global $CFG;
require_once("{$CFG->dirroot}/user/profile/lib.php");
}
/**
* Data provider for {@see test_is_empty}
*
* @return array[]
*/
public static function is_empty_provider(): array {
return [
'No value' => [
[],
true,
],
'Value equals 0' => [
['profile_field_check' => 0],
false,
],
'Value equals 1' => [
['profile_field_check' => 1],
false,
],
];
}
/**
* Test field empty state
*
* @param array $userrecord
* @param bool $expected
*
* @dataProvider is_empty_provider
*/
public function test_is_empty(array $userrecord, bool $expected): void {
$this->resetAfterTest();
$this->getDataGenerator()->create_custom_profile_field([
'datatype' => 'checkbox',
'name' => 'My check',
'shortname' => 'check',
]);
$user = $this->getDataGenerator()->create_user($userrecord);
/** @var profile_field_checkbox[] $fields */
$fields = profile_get_user_fields_with_data($user->id);
$fieldinstance = reset($fields);
$this->assertEquals($expected, $fieldinstance->is_empty());
}
/**
* Test whether to show field content
*/
public function test_show_field_content(): void {
$this->resetAfterTest();
$this->getDataGenerator()->create_custom_profile_field([
'datatype' => 'checkbox',
'name' => 'My check',
'shortname' => 'check',
'visible' => PROFILE_VISIBLE_PRIVATE,
]);
// User can view their own value.
$userwith = $this->getDataGenerator()->create_user(['profile_field_check' => 1]);
$this->setUser($userwith);
/** @var profile_field_checkbox[] $fields */
$fields = profile_get_user_fields_with_data($userwith->id);
$fieldinstance = reset($fields);
$this->assertTrue($fieldinstance->show_field_content());
// Another user cannot view the value.
$userview = $this->getDataGenerator()->create_user();
$this->setUser($userview);
$this->assertFalse($fieldinstance->show_field_content());
// Another user with appropriate access can view the value.
$this->setAdminUser();
$this->assertTrue($fieldinstance->show_field_content());
}
}
+29
View File
@@ -0,0 +1,29 @@
<?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/>.
/**
* Version information for the checkbox profile field type.
*
* @package profilefield_checkbox
* @copyright 2008 onwards Shane Elliot {@link http://pukunui.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$plugin->version = 2024042200; // The current plugin version (Date: YYYYMMDDXX).
$plugin->requires = 2024041600; // Requires this Moodle version.
$plugin->component = 'profilefield_checkbox'; // Full name of the plugin (used for diagnostics)
@@ -0,0 +1,217 @@
<?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/>.
/**
* Privacy class for requesting user data.
*
* @package profilefield_datetime
* @copyright 2018 Mihail Geshoski <mihail@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace profilefield_datetime\privacy;
defined('MOODLE_INTERNAL') || die();
use \core_privacy\local\metadata\collection;
use \core_privacy\local\request\contextlist;
use \core_privacy\local\request\approved_contextlist;
use \core_privacy\local\request\transform;
use core_privacy\local\request\userlist;
use core_privacy\local\request\approved_userlist;
/**
* Privacy class for requesting user data.
*
* @copyright 2018 Mihail Geshoski <mihail@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider implements
\core_privacy\local\metadata\provider,
\core_privacy\local\request\core_userlist_provider,
\core_privacy\local\request\plugin\provider {
/**
* Returns meta data about this system.
*
* @param collection $collection The initialised collection to add items to.
* @return collection A listing of user data stored through this system.
*/
public static function get_metadata(collection $collection): collection {
return $collection->add_database_table('user_info_data', [
'userid' => 'privacy:metadata:profilefield_datetime:userid',
'fieldid' => 'privacy:metadata:profilefield_datetime:fieldid',
'data' => 'privacy:metadata:profilefield_datetime:data',
'dataformat' => 'privacy:metadata:profilefield_datetime:dataformat'
], 'privacy:metadata:profilefield_datetime:tableexplanation');
}
/**
* Get the list of contexts that contain user information for the specified user.
*
* @param int $userid The user to search.
* @return contextlist $contextlist The contextlist containing the list of contexts used in this plugin.
*/
public static function get_contexts_for_userid(int $userid): contextlist {
$sql = "SELECT ctx.id
FROM {user_info_data} uda
JOIN {user_info_field} uif ON uda.fieldid = uif.id
JOIN {context} ctx ON ctx.instanceid = uda.userid
AND ctx.contextlevel = :contextlevel
WHERE uda.userid = :userid
AND uif.datatype = :datatype";
$params = [
'userid' => $userid,
'contextlevel' => CONTEXT_USER,
'datatype' => 'datetime'
];
$contextlist = new contextlist();
$contextlist->add_from_sql($sql, $params);
return $contextlist;
}
/**
* Get the list of users within a specific context.
*
* @param userlist $userlist The userlist containing the list of users who have data in this context/plugin combination.
*/
public static function get_users_in_context(userlist $userlist) {
$context = $userlist->get_context();
if (!$context instanceof \context_user) {
return;
}
$sql = "SELECT uda.userid
FROM {user_info_data} uda
JOIN {user_info_field} uif
ON uda.fieldid = uif.id
WHERE uda.userid = :userid
AND uif.datatype = :datatype";
$params = [
'userid' => $context->instanceid,
'datatype' => 'datetime'
];
$userlist->add_from_sql('userid', $sql, $params);
}
/**
* Export all user data for the specified user, in the specified contexts.
*
* @param approved_contextlist $contextlist The approved contexts to export information for.
*/
public static function export_user_data(approved_contextlist $contextlist) {
$user = $contextlist->get_user();
foreach ($contextlist->get_contexts() as $context) {
// Check if the context is a user context.
if ($context->contextlevel == CONTEXT_USER && $context->instanceid == $user->id) {
$results = static::get_records($user->id);
foreach ($results as $result) {
$data = (object) [
'name' => $result->name,
'description' => $result->description,
'data' => transform::date($result->data)
];
\core_privacy\local\request\writer::with_context($context)->export_data([
get_string('pluginname', 'profilefield_datetime')], $data);
}
}
}
}
/**
* Delete all user data which matches the specified context.
*
* @param context $context A user context.
*/
public static function delete_data_for_all_users_in_context(\context $context) {
// Delete data only for user context.
if ($context->contextlevel == CONTEXT_USER) {
static::delete_data($context->instanceid);
}
}
/**
* Delete multiple users within a single context.
*
* @param approved_userlist $userlist The approved context and user information to delete information for.
*/
public static function delete_data_for_users(approved_userlist $userlist) {
$context = $userlist->get_context();
if ($context instanceof \context_user) {
static::delete_data($context->instanceid);
}
}
/**
* Delete all user data for the specified user, in the specified contexts.
*
* @param approved_contextlist $contextlist The approved contexts and user information to delete information for.
*/
public static function delete_data_for_user(approved_contextlist $contextlist) {
$user = $contextlist->get_user();
foreach ($contextlist->get_contexts() as $context) {
// Check if the context is a user context.
if ($context->contextlevel == CONTEXT_USER && $context->instanceid == $user->id) {
static::delete_data($context->instanceid);
}
}
}
/**
* Delete data related to a userid.
*
* @param int $userid The user ID
*/
protected static function delete_data($userid) {
global $DB;
$params = [
'userid' => $userid,
'datatype' => 'datetime'
];
$DB->delete_records_select('user_info_data', "fieldid IN (
SELECT id FROM {user_info_field} WHERE datatype = :datatype)
AND userid = :userid", $params);
}
/**
* Get records related to this plugin and user.
*
* @param int $userid The user ID
* @return array An array of records.
*/
protected static function get_records($userid) {
global $DB;
$sql = "SELECT *
FROM {user_info_data} uda
JOIN {user_info_field} uif ON uda.fieldid = uif.id
WHERE uda.userid = :userid
AND uif.datatype = :datatype";
$params = [
'userid' => $userid,
'datatype' => 'datetime'
];
return $DB->get_records_sql($sql, $params);
}
}
@@ -0,0 +1,179 @@
<?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/>.
/**
* This file contains the datetime profile field definition class.
*
* @package profilefield_datetime
* @copyright 2010 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License
*/
/**
* Define datetime fields.
*
* @copyright 2010 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License
*/
class profile_define_datetime extends profile_define_base {
/**
* Define the setting for a datetime custom field.
*
* @param moodleform $form the user form
*/
public function define_form_specific($form) {
// Get the current calendar in use - see MDL-18375.
$calendartype = \core_calendar\type_factory::get_calendar_instance();
// Create variables to store start and end.
list($year, $month, $day) = explode('_', date('Y_m_d'));
$currentdate = $calendartype->convert_from_gregorian($year, $month, $day);
$currentyear = $currentdate['year'];
$arryears = $calendartype->get_years();
// Add elements.
$form->addElement('select', 'param1', get_string('startyear', 'profilefield_datetime'), $arryears);
$form->setType('param1', PARAM_INT);
$form->setDefault('param1', $currentyear);
$form->addElement('select', 'param2', get_string('endyear', 'profilefield_datetime'), $arryears);
$form->setType('param2', PARAM_INT);
$form->setDefault('param2', $currentyear);
$form->addElement('checkbox', 'param3', get_string('wanttime', 'profilefield_datetime'));
$form->setType('param3', PARAM_INT);
$form->addElement('hidden', 'startday', '1');
$form->setType('startday', PARAM_INT);
$form->addElement('hidden', 'startmonth', '1');
$form->setType('startmonth', PARAM_INT);
$form->addElement('hidden', 'startyear', '1');
$form->setType('startyear', PARAM_INT);
$form->addElement('hidden', 'endday', '1');
$form->setType('endday', PARAM_INT);
$form->addElement('hidden', 'endmonth', '1');
$form->setType('endmonth', PARAM_INT);
$form->addElement('hidden', 'endyear', '1');
$form->setType('endyear', PARAM_INT);
$form->addElement('hidden', 'defaultdata', '0');
$form->setType('defaultdata', PARAM_INT);
}
/**
* Validate the data from the profile field form.
*
* @param stdClass $data from the add/edit profile field form
* @param array $files
* @return array associative array of error messages
*/
public function define_validate_specific($data, $files) {
$errors = array();
// Make sure the start year is not greater than the end year.
if ($data->param1 > $data->param2) {
$errors['param1'] = get_string('startyearafterend', 'profilefield_datetime');
}
return $errors;
}
/**
* Alter form based on submitted or existing data.
*
* @param moodleform $mform
*/
public function define_after_data(&$mform) {
global $DB;
// If we are adding a new profile field then the dates have already been set
// by setDefault to the correct dates in the used calendar system. We only want
// to execute the rest of the code when we have the years in the DB saved in
// Gregorian that need converting to the date for this user.
$id = optional_param('id', 0, PARAM_INT);
if ($id === 0) {
return;
}
// Get the field data from the DB.
$field = $DB->get_record('user_info_field', array('id' => $id), 'param1, param2', MUST_EXIST);
// Get the current calendar in use - see MDL-18375.
$calendartype = \core_calendar\type_factory::get_calendar_instance();
// An array to store form values.
$values = array();
// The start and end year will be set as a Gregorian year in the DB. We want
// convert these to the equivalent year in the current calendar type being used.
$startdate = $calendartype->convert_from_gregorian($field->param1, 1, 1);
$values['startday'] = $startdate['day'];
$values['startmonth'] = $startdate['month'];
$values['startyear'] = $startdate['year'];
$values['param1'] = $startdate['year'];
$stopdate = $calendartype->convert_from_gregorian($field->param2, 1, 1);
$values['endday'] = $stopdate['day'];
$values['endmonth'] = $stopdate['month'];
$values['endyear'] = $stopdate['year'];
$values['param2'] = $stopdate['year'];
// Set the values.
foreach ($values as $key => $value) {
$param = $mform->getElement($key);
$param->setValue($value);
}
}
/**
* Preprocess data from the profile field form before
* it is saved.
*
* @param stdClass $data from the add/edit profile field form
* @return stdClass processed data object
*/
public function define_save_preprocess($data) {
// Get the current calendar in use - see MDL-18375.
$calendartype = \core_calendar\type_factory::get_calendar_instance();
// Check if the start year was changed, if it was then convert from the start of that year.
if ($data->param1 != $data->startyear) {
$startdate = $calendartype->convert_to_gregorian($data->param1, 1, 1);
} else {
$startdate = $calendartype->convert_to_gregorian($data->param1, $data->startmonth, $data->startday);
}
// Check if the end year was changed, if it was then convert from the start of that year.
if ($data->param2 != $data->endyear) {
$stopdate = $calendartype->convert_to_gregorian($data->param2, 1, 1);
} else {
$stopdate = $calendartype->convert_to_gregorian($data->param2, $data->endmonth, $data->endday);
}
$data->param1 = $startdate['year'];
$data->param2 = $stopdate['year'];
if (empty($data->param3)) {
$data->param3 = null;
}
// No valid value in the default data column needed.
$data->defaultdata = '0';
return $data;
}
}
+146
View File
@@ -0,0 +1,146 @@
<?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/>.
/**
* This file contains the datetime profile field class.
*
* @package profilefield_datetime
* @copyright 2010 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License
*/
/**
* Handles displaying and editing the datetime field.
*
* @copyright 2010 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License
*/
class profile_field_datetime extends profile_field_base {
/**
* Handles editing datetime fields.
*
* @param moodleform $mform
*/
public function edit_field_add($mform) {
// Get the current calendar in use - see MDL-18375.
$calendartype = \core_calendar\type_factory::get_calendar_instance();
// Check if the field is required.
if ($this->field->required) {
$optional = false;
} else {
$optional = true;
}
// Convert the year stored in the DB as gregorian to that used by the calendar type.
$startdate = $calendartype->convert_from_gregorian($this->field->param1, 1, 1);
$stopdate = $calendartype->convert_from_gregorian($this->field->param2, 1, 1);
$attributes = array(
'startyear' => $startdate['year'],
'stopyear' => $stopdate['year'],
'optional' => $optional
);
// Check if they wanted to include time as well.
if (!empty($this->field->param3)) {
$mform->addElement('date_time_selector', $this->inputname, format_string($this->field->name), $attributes);
} else {
$mform->addElement('date_selector', $this->inputname, format_string($this->field->name), $attributes);
}
$mform->setType($this->inputname, PARAM_INT);
$mform->setDefault($this->inputname, time());
}
/**
* If timestamp is in YYYY-MM-DD or YYYY-MM-DD-HH-MM-SS format, then convert it to timestamp.
*
* @param string|int $datetime datetime to be converted.
* @param stdClass $datarecord The object that will be used to save the record
* @return int timestamp
* @since Moodle 2.5
*/
public function edit_save_data_preprocess($datetime, $datarecord) {
if (!$datetime) {
return 0;
}
if (is_numeric($datetime)) {
$gregoriancalendar = \core_calendar\type_factory::get_calendar_instance('gregorian');
$datetime = $gregoriancalendar->timestamp_to_date_string($datetime, '%Y-%m-%d-%H-%M-%S', 99, true, true);
}
$datetime = explode('-', $datetime);
// Bound year with start and end year.
$datetime[0] = min(max($datetime[0], $this->field->param1), $this->field->param2);
if (!empty($this->field->param3) && count($datetime) == 6) {
return make_timestamp($datetime[0], $datetime[1], $datetime[2], $datetime[3], $datetime[4], $datetime[5]);
} else {
return make_timestamp($datetime[0], $datetime[1], $datetime[2]);
}
}
/**
* Display the data for this field.
*/
public function display_data() {
// Check if time was specified.
if (!empty($this->field->param3)) {
$format = get_string('strftimedaydatetime', 'langconfig');
} else {
$format = get_string('strftimedate', 'langconfig');
}
// Check if a date has been specified.
if (empty($this->data)) {
return get_string('notset', 'profilefield_datetime');
} else {
return userdate($this->data, $format);
}
}
/**
* Check if the field data is considered empty
*
* @return boolean
*/
public function is_empty() {
return empty($this->data);
}
/**
* Return the field type and null properties.
* This will be used for validating the data submitted by a user.
*
* @return array the param type and null property
* @since Moodle 3.2
*/
public function get_field_properties() {
return array(PARAM_INT, NULL_NOT_ALLOWED);
}
/**
* Check if the field should convert the raw data into user-friendly data when exporting
*
* @return bool
*/
public function is_transform_supported(): bool {
return true;
}
}
@@ -0,0 +1,38 @@
<?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/>.
/**
* The english language pack used in this profile field type.
*
* @package profilefield_datetime
* @copyright 2010 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License
*/
$string['currentdatedefault'] = 'Check to use current date as default';
$string['defaultdate'] = 'Default date';
$string['endyear'] = 'End year';
$string['notset'] = 'Not set';
$string['pluginname'] = 'Date/Time';
$string['privacy:metadata:profilefield_datetime:userid'] = 'The ID of the user whose data is stored by the Date/time user profile field';
$string['privacy:metadata:profilefield_datetime:fieldid'] = 'The ID of the profile field';
$string['privacy:metadata:profilefield_datetime:data'] = 'Date/time user profile field user data';
$string['privacy:metadata:profilefield_datetime:dataformat'] = 'The format of Date/time user profile field user data';
$string['privacy:metadata:profilefield_datetime:tableexplanation'] = 'Additional profile data';
$string['specifydatedefault'] = 'or specify a date';
$string['startyearafterend'] = 'The start year can\'t occur after the end year';
$string['startyear'] = 'Start year';
$string['wanttime'] = 'Include time?';
@@ -0,0 +1,305 @@
<?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/>.
/**
* Base class for unit tests for profilefield_datetime.
*
* @package profilefield_datetime
* @copyright 2018 Mihail Geshoski <mihail@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace profilefield_datetime\privacy;
defined('MOODLE_INTERNAL') || die();
use core_privacy\tests\provider_testcase;
use profilefield_datetime\privacy\provider;
use core_privacy\local\request\approved_userlist;
/**
* Unit tests for user\profile\field\datetime\classes\privacy\provider.php
*
* @copyright 2018 Mihail Geshoski <mihail@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider_test extends provider_testcase {
/**
* Basic setup for these tests.
*/
public function setUp(): void {
$this->resetAfterTest(true);
}
/**
* Test getting the context for the user ID related to this plugin.
*/
public function test_get_contexts_for_userid(): void {
global $DB;
// Create profile category.
$categoryid = $this->add_profile_category();
// Create profile field.
$profilefieldid = $this->add_profile_field($categoryid, 'datetime');
// Create a user.
$user = $this->getDataGenerator()->create_user();
$this->add_user_info_data($user->id, $profilefieldid, 'test data');
// Get the field that was created.
$userfielddata = $DB->get_records('user_info_data', array('userid' => $user->id));
// Confirm we got the right number of user field data.
$this->assertCount(1, $userfielddata);
$context = \context_user::instance($user->id);
$contextlist = provider::get_contexts_for_userid($user->id);
$this->assertEquals($context, $contextlist->current());
}
/**
* Test that data is exported correctly for this plugin.
*/
public function test_export_user_data(): void {
// Create profile category.
$categoryid = $this->add_profile_category();
// Create datetime profile field.
$datetimeprofilefieldid = $this->add_profile_field($categoryid, 'datetime');
// Create checkbox profile field.
$checkboxprofilefieldid = $this->add_profile_field($categoryid, 'checkbox');
// Create a user.
$user = $this->getDataGenerator()->create_user();
$context = \context_user::instance($user->id);
// Add datetime user info data.
$this->add_user_info_data($user->id, $datetimeprofilefieldid, '1524067200');
// Add checkbox user info data.
$this->add_user_info_data($user->id, $checkboxprofilefieldid, 'test data');
$writer = \core_privacy\local\request\writer::with_context($context);
$this->assertFalse($writer->has_any_data());
$this->export_context_data_for_user($user->id, $context, 'profilefield_datetime');
$data = $writer->get_data([get_string('pluginname', 'profilefield_datetime')]);
$this->assertCount(3, (array) $data);
$this->assertEquals('Test field', $data->name);
$this->assertEquals('This is a test.', $data->description);
$this->assertEquals('19 April 2018', $data->data);
}
/**
* Test that user data is deleted using the context.
*/
public function test_delete_data_for_all_users_in_context(): void {
global $DB;
// Create profile category.
$categoryid = $this->add_profile_category();
// Create datetime profile field.
$datetimeprofilefieldid = $this->add_profile_field($categoryid, 'datetime');
// Create checkbox profile field.
$checkboxprofilefieldid = $this->add_profile_field($categoryid, 'checkbox');
// Create a user.
$user = $this->getDataGenerator()->create_user();
$context = \context_user::instance($user->id);
// Add datetime user info data.
$this->add_user_info_data($user->id, $datetimeprofilefieldid, '1524067200');
// Add checkbox user info data.
$this->add_user_info_data($user->id, $checkboxprofilefieldid, 'test data');
// Check that we have two entries.
$userinfodata = $DB->get_records('user_info_data', ['userid' => $user->id]);
$this->assertCount(2, $userinfodata);
provider::delete_data_for_all_users_in_context($context);
// Check that the correct profile field has been deleted.
$userinfodata = $DB->get_records('user_info_data', ['userid' => $user->id]);
$this->assertCount(1, $userinfodata);
$this->assertNotEquals('1524067200', reset($userinfodata)->data);
}
/**
* Test that user data is deleted for this user.
*/
public function test_delete_data_for_user(): void {
global $DB;
// Create profile category.
$categoryid = $this->add_profile_category();
// Create datetime profile field.
$datetimeprofilefieldid = $this->add_profile_field($categoryid, 'datetime');
// Create checkbox profile field.
$checkboxprofilefieldid = $this->add_profile_field($categoryid, 'checkbox');
// Create a user.
$user = $this->getDataGenerator()->create_user();
$context = \context_user::instance($user->id);
// Add datetime user info data.
$this->add_user_info_data($user->id, $datetimeprofilefieldid, '1524067200');
// Add checkbox user info data.
$this->add_user_info_data($user->id, $checkboxprofilefieldid, 'test data');
// Check that we have two entries.
$userinfodata = $DB->get_records('user_info_data', ['userid' => $user->id]);
$this->assertCount(2, $userinfodata);
$approvedlist = new \core_privacy\local\request\approved_contextlist($user, 'profilefield_datetime',
[$context->id]);
provider::delete_data_for_user($approvedlist);
// Check that the correct profile field has been deleted.
$userinfodata = $DB->get_records('user_info_data', ['userid' => $user->id]);
$this->assertCount(1, $userinfodata);
$this->assertNotEquals('1524067200', reset($userinfodata)->data);
}
/**
* Test that only users with a user context are fetched.
*/
public function test_get_users_in_context(): void {
$this->resetAfterTest();
$component = 'profilefield_datetime';
// Create profile category.
$categoryid = $this->add_profile_category();
// Create profile field.
$profilefieldid = $this->add_profile_field($categoryid, 'datetime');
// Create a user.
$user = $this->getDataGenerator()->create_user();
$usercontext = \context_user::instance($user->id);
// The list of users should not return anything yet (related data still haven't been created).
$userlist = new \core_privacy\local\request\userlist($usercontext, $component);
provider::get_users_in_context($userlist);
$this->assertCount(0, $userlist);
$this->add_user_info_data($user->id, $profilefieldid, 'test data');
// The list of users for user context should return the user.
provider::get_users_in_context($userlist);
$this->assertCount(1, $userlist);
$expected = [$user->id];
$actual = $userlist->get_userids();
$this->assertEquals($expected, $actual);
// The list of users for system context should not return any users.
$systemcontext = \context_system::instance();
$userlist = new \core_privacy\local\request\userlist($systemcontext, $component);
provider::get_users_in_context($userlist);
$this->assertCount(0, $userlist);
}
/**
* Test that data for users in approved userlist is deleted.
*/
public function test_delete_data_for_users(): void {
$this->resetAfterTest();
$component = 'profilefield_datetime';
// Create profile category.
$categoryid = $this->add_profile_category();
// Create profile field.
$profilefieldid = $this->add_profile_field($categoryid, 'datetime');
// Create user1.
$user1 = $this->getDataGenerator()->create_user();
$usercontext1 = \context_user::instance($user1->id);
// Create user2.
$user2 = $this->getDataGenerator()->create_user();
$usercontext2 = \context_user::instance($user2->id);
$this->add_user_info_data($user1->id, $profilefieldid, 'test data');
$this->add_user_info_data($user2->id, $profilefieldid, 'test data');
// The list of users for usercontext1 should return user1.
$userlist1 = new \core_privacy\local\request\userlist($usercontext1, $component);
provider::get_users_in_context($userlist1);
$this->assertCount(1, $userlist1);
$expected = [$user1->id];
$actual = $userlist1->get_userids();
$this->assertEquals($expected, $actual);
// The list of users for usercontext2 should return user2.
$userlist2 = new \core_privacy\local\request\userlist($usercontext2, $component);
provider::get_users_in_context($userlist2);
$this->assertCount(1, $userlist2);
$expected = [$user2->id];
$actual = $userlist2->get_userids();
$this->assertEquals($expected, $actual);
// Add userlist1 to the approved user list.
$approvedlist = new approved_userlist($usercontext1, $component, $userlist1->get_userids());
// Delete user data using delete_data_for_user for usercontext1.
provider::delete_data_for_users($approvedlist);
// Re-fetch users in usercontext1 - The user list should now be empty.
$userlist1 = new \core_privacy\local\request\userlist($usercontext1, $component);
provider::get_users_in_context($userlist1);
$this->assertCount(0, $userlist1);
// Re-fetch users in usercontext2 - The user list should not be empty (user2).
$userlist2 = new \core_privacy\local\request\userlist($usercontext2, $component);
provider::get_users_in_context($userlist2);
$this->assertCount(1, $userlist2);
// User data should be only removed in the user context.
$systemcontext = \context_system::instance();
// Add userlist2 to the approved user list in the system context.
$approvedlist = new approved_userlist($systemcontext, $component, $userlist2->get_userids());
// Delete user1 data using delete_data_for_user.
provider::delete_data_for_users($approvedlist);
// Re-fetch users in usercontext2 - The user list should not be empty (user2).
$userlist1 = new \core_privacy\local\request\userlist($usercontext2, $component);
provider::get_users_in_context($userlist1);
$this->assertCount(1, $userlist1);
}
/**
* Add dummy user info data.
*
* @param int $userid The ID of the user
* @param int $fieldid The ID of the field
* @param string $data The data
*/
private function add_user_info_data($userid, $fieldid, $data) {
global $DB;
$userinfodata = array(
'userid' => $userid,
'fieldid' => $fieldid,
'data' => $data,
'dataformat' => 0
);
$DB->insert_record('user_info_data', $userinfodata);
}
/**
* Add dummy profile category.
*
* @return int The ID of the profile category
*/
private function add_profile_category() {
$cat = $this->getDataGenerator()->create_custom_profile_field_category(['name' => 'Test category']);
return $cat->id;
}
/**
* Add dummy profile field.
*
* @param int $categoryid The ID of the profile category
* @param string $datatype The datatype of the profile field
* @return int The ID of the profile field
*/
private function add_profile_field($categoryid, $datatype) {
$data = $this->getDataGenerator()->create_custom_profile_field([
'datatype' => $datatype,
'shortname' => 'tstField',
'name' => 'Test field',
'description' => 'This is a test.',
'categoryid' => $categoryid,
]);
return $data->id;
}
}
+29
View File
@@ -0,0 +1,29 @@
<?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/>.
/**
* Version information for the datetime field.
*
* @package profilefield_datetime
* @copyright 2010 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License
*/
defined('MOODLE_INTERNAL') || die();
$plugin->version = 2024042200; // The current plugin version (Date: YYYYMMDDXX).
$plugin->requires = 2024041600; // Requires this Moodle version.
$plugin->component = 'profilefield_datetime'; // Full name of the plugin (used for diagnostics)
@@ -0,0 +1,216 @@
<?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/>.
/**
* Privacy class for requesting user data.
*
* @package profilefield_menu
* @copyright 2018 Mihail Geshoski <mihail@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace profilefield_menu\privacy;
defined('MOODLE_INTERNAL') || die();
use \core_privacy\local\metadata\collection;
use \core_privacy\local\request\contextlist;
use \core_privacy\local\request\approved_contextlist;
use core_privacy\local\request\userlist;
use core_privacy\local\request\approved_userlist;
/**
* Privacy class for requesting user data.
*
* @copyright 2018 Mihail Geshoski <mihail@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider implements
\core_privacy\local\metadata\provider,
\core_privacy\local\request\core_userlist_provider,
\core_privacy\local\request\plugin\provider {
/**
* Returns meta data about this system.
*
* @param collection $collection The initialised collection to add items to.
* @return collection A listing of user data stored through this system.
*/
public static function get_metadata(collection $collection): collection {
return $collection->add_database_table('user_info_data', [
'userid' => 'privacy:metadata:profilefield_menu:userid',
'fieldid' => 'privacy:metadata:profilefield_menu:fieldid',
'data' => 'privacy:metadata:profilefield_menu:data',
'dataformat' => 'privacy:metadata:profilefield_menu:dataformat'
], 'privacy:metadata:profilefield_menu:tableexplanation');
}
/**
* Get the list of contexts that contain user information for the specified user.
*
* @param int $userid The user to search.
* @return contextlist $contextlist The contextlist containing the list of contexts used in this plugin.
*/
public static function get_contexts_for_userid(int $userid): contextlist {
$sql = "SELECT ctx.id
FROM {user_info_data} uda
JOIN {user_info_field} uif ON uda.fieldid = uif.id
JOIN {context} ctx ON ctx.instanceid = uda.userid
AND ctx.contextlevel = :contextlevel
WHERE uda.userid = :userid
AND uif.datatype = :datatype";
$params = [
'userid' => $userid,
'contextlevel' => CONTEXT_USER,
'datatype' => 'menu'
];
$contextlist = new contextlist();
$contextlist->add_from_sql($sql, $params);
return $contextlist;
}
/**
* Get the list of users within a specific context.
*
* @param userlist $userlist The userlist containing the list of users who have data in this context/plugin combination.
*/
public static function get_users_in_context(userlist $userlist) {
$context = $userlist->get_context();
if (!$context instanceof \context_user) {
return;
}
$sql = "SELECT uda.userid
FROM {user_info_data} uda
JOIN {user_info_field} uif
ON uda.fieldid = uif.id
WHERE uda.userid = :userid
AND uif.datatype = :datatype";
$params = [
'userid' => $context->instanceid,
'datatype' => 'menu'
];
$userlist->add_from_sql('userid', $sql, $params);
}
/**
* Export all user data for the specified user, in the specified contexts.
*
* @param approved_contextlist $contextlist The approved contexts to export information for.
*/
public static function export_user_data(approved_contextlist $contextlist) {
$user = $contextlist->get_user();
foreach ($contextlist->get_contexts() as $context) {
// Check if the context is a user context.
if ($context->contextlevel == CONTEXT_USER && $context->instanceid == $user->id) {
$results = static::get_records($user->id);
foreach ($results as $result) {
$data = (object) [
'name' => $result->name,
'description' => $result->description,
'data' => $result->data
];
\core_privacy\local\request\writer::with_context($context)->export_data([
get_string('pluginname', 'profilefield_menu')], $data);
}
}
}
}
/**
* Delete all user data which matches the specified context.
*
* @param context $context A user context.
*/
public static function delete_data_for_all_users_in_context(\context $context) {
// Delete data only for user context.
if ($context->contextlevel == CONTEXT_USER) {
static::delete_data($context->instanceid);
}
}
/**
* Delete multiple users within a single context.
*
* @param approved_userlist $userlist The approved context and user information to delete information for.
*/
public static function delete_data_for_users(approved_userlist $userlist) {
$context = $userlist->get_context();
if ($context instanceof \context_user) {
static::delete_data($context->instanceid);
}
}
/**
* Delete all user data for the specified user, in the specified contexts.
*
* @param approved_contextlist $contextlist The approved contexts and user information to delete information for.
*/
public static function delete_data_for_user(approved_contextlist $contextlist) {
$user = $contextlist->get_user();
foreach ($contextlist->get_contexts() as $context) {
// Check if the context is a user context.
if ($context->contextlevel == CONTEXT_USER && $context->instanceid == $user->id) {
static::delete_data($context->instanceid);
}
}
}
/**
* Delete data related to a userid.
*
* @param int $userid The user ID
*/
protected static function delete_data($userid) {
global $DB;
$params = [
'userid' => $userid,
'datatype' => 'menu'
];
$DB->delete_records_select('user_info_data', "fieldid IN (
SELECT id FROM {user_info_field} WHERE datatype = :datatype)
AND userid = :userid", $params);
}
/**
* Get records related to this plugin and user.
*
* @param int $userid The user ID
* @return array An array of records.
*/
protected static function get_records($userid) {
global $DB;
$sql = "SELECT *
FROM {user_info_data} uda
JOIN {user_info_field} uif ON uda.fieldid = uif.id
WHERE uda.userid = :userid
AND uif.datatype = :datatype";
$params = [
'userid' => $userid,
'datatype' => 'menu'
];
return $DB->get_records_sql($sql, $params);
}
}
+84
View File
@@ -0,0 +1,84 @@
<?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/>.
/**
* Menu profile field definition.
*
* @package profilefield_menu
* @copyright 2007 onwards Shane Elliot {@link http://pukunui.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/**
* Class profile_define_menu
*
* @copyright 2007 onwards Shane Elliot {@link http://pukunui.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class profile_define_menu extends profile_define_base {
/**
* Adds elements to the form for creating/editing this type of profile field.
* @param moodleform $form
*/
public function define_form_specific($form) {
// Param 1 for menu type contains the options.
$form->addElement('textarea', 'param1', get_string('profilemenuoptions', 'admin'), array('rows' => 6, 'cols' => 40));
$form->setType('param1', PARAM_TEXT);
// Default data.
$form->addElement('text', 'defaultdata', get_string('profiledefaultdata', 'admin'), 'size="50"');
$form->setType('defaultdata', PARAM_TEXT);
}
/**
* Validates data for the profile field.
*
* @param array $data
* @param array $files
* @return array
*/
public function define_validate_specific($data, $files) {
$err = array();
$data->param1 = str_replace("\r", '', $data->param1);
// Check that we have at least 2 options.
if (($options = explode("\n", $data->param1)) === false) {
$err['param1'] = get_string('profilemenunooptions', 'admin');
} else if (count($options) < 2) {
$err['param1'] = get_string('profilemenutoofewoptions', 'admin');
} else if (!empty($data->defaultdata) and !in_array($data->defaultdata, $options)) {
// Check the default data exists in the options.
$err['defaultdata'] = get_string('profilemenudefaultnotinoptions', 'admin');
}
return $err;
}
/**
* Processes data before it is saved.
* @param array|stdClass $data
* @return array|stdClass
*/
public function define_save_preprocess($data) {
$data->param1 = str_replace("\r", '', $data->param1);
return $data;
}
}
+191
View File
@@ -0,0 +1,191 @@
<?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/>.
/**
* Menu profile field.
*
* @package profilefield_menu
* @copyright 2007 onwards Shane Elliot {@link http://pukunui.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/**
* Class profile_field_menu
*
* @copyright 2007 onwards Shane Elliot {@link http://pukunui.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class profile_field_menu extends profile_field_base {
/** @var array $options */
public $options;
/** @var int $datakey */
public $datakey;
/**
* Constructor method.
*
* Pulls out the options for the menu from the database and sets the the corresponding key for the data if it exists.
*
* @param int $fieldid
* @param int $userid
* @param object $fielddata
*/
public function __construct($fieldid = 0, $userid = 0, $fielddata = null) {
// First call parent constructor.
parent::__construct($fieldid, $userid, $fielddata);
// Param 1 for menu type is the options.
if (isset($this->field->param1)) {
$options = explode("\n", $this->field->param1);
} else {
$options = array();
}
$this->options = array();
if (!empty($this->field->required)) {
$this->options[''] = get_string('choose').'...';
}
foreach ($options as $key => $option) {
// Multilang formatting with filters.
$this->options[$option] = format_string($option, true, ['context' => context_system::instance()]);
}
// Set the data key.
if ($this->data !== null) {
$key = $this->data;
if (isset($this->options[$key]) || ($key = array_search($key, $this->options)) !== false) {
$this->data = $key;
$this->datakey = $key;
}
}
}
/**
* Create the code snippet for this field instance
* Overwrites the base class method
* @param moodleform $mform Moodle form instance
*/
public function edit_field_add($mform) {
$mform->addElement('select', $this->inputname, format_string($this->field->name), $this->options);
}
/**
* Set the default value for this field instance
* Overwrites the base class method.
* @param moodleform $mform Moodle form instance
*/
public function edit_field_set_default($mform) {
$key = $this->field->defaultdata;
if (isset($this->options[$key]) || ($key = array_search($key, $this->options)) !== false){
$defaultkey = $key;
} else {
$defaultkey = '';
}
$mform->setDefault($this->inputname, $defaultkey);
}
/**
* The data from the form returns the key.
*
* This should be converted to the respective option string to be saved in database
* Overwrites base class accessor method.
*
* @param mixed $data The key returned from the select input in the form
* @param stdClass $datarecord The object that will be used to save the record
* @return mixed Data or null
*/
public function edit_save_data_preprocess($data, $datarecord) {
return isset($this->options[$data]) ? $data : null;
}
/**
* When passing the user object to the form class for the edit profile page
* we should load the key for the saved data
*
* Overwrites the base class method.
*
* @param stdClass $user User object.
*/
public function edit_load_user_data($user) {
$user->{$this->inputname} = $this->datakey;
}
/**
* HardFreeze the field if locked.
* @param moodleform $mform instance of the moodleform class
*/
public function edit_field_set_locked($mform) {
if (!$mform->elementExists($this->inputname)) {
return;
}
if ($this->is_locked() and !has_capability('moodle/user:update', context_system::instance())) {
$mform->hardFreeze($this->inputname);
$mform->setConstant($this->inputname, format_string($this->datakey));
}
}
/**
* Convert external data (csv file) from value to key for processing later by edit_save_data_preprocess
*
* @param string $value one of the values in menu options.
* @return int options key for the menu
*/
public function convert_external_data($value) {
if (isset($this->options[$value])) {
$retval = $value;
} else {
$retval = array_search($value, $this->options);
}
// If value is not found in options then return null, so that it can be handled
// later by edit_save_data_preprocess.
if ($retval === false) {
$retval = null;
}
return $retval;
}
/**
* Return the field type and null properties.
* This will be used for validating the data submitted by a user.
*
* @return array the param type and null property
* @since Moodle 3.2
*/
public function get_field_properties() {
return array(PARAM_TEXT, NULL_NOT_ALLOWED);
}
/**
* Return the field settings suitable to be exported via an external function.
*
* @return array all the settings
*/
public function get_field_config_for_external() {
if (isset($this->field->param1) && !empty($this->options)) {
// Remove "Choose" option to make it consisten with the rest of the data.
if (!empty($this->field->required)) {
unset($this->options['']);
}
$this->field->param2 = implode("\n", array_values($this->options));
}
return (array) $this->field;
}
}
@@ -0,0 +1,30 @@
<?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/>.
/**
* Strings for component 'profilefield_menu', language 'en', branch 'MOODLE_20_STABLE'
*
* @package profilefield_menu
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$string['pluginname'] = 'Drop-down menu';
$string['privacy:metadata:profilefield_menu:userid'] = 'The ID of the user whose data is stored by the drop-down menu user profile field';
$string['privacy:metadata:profilefield_menu:fieldid'] = 'The ID of the profile field';
$string['privacy:metadata:profilefield_menu:data'] = 'Drop-down menu user profile field user data';
$string['privacy:metadata:profilefield_menu:dataformat'] = 'The format of the drop-down menu user profile field user data';
$string['privacy:metadata:profilefield_menu:tableexplanation'] = 'Additional profile data';
@@ -0,0 +1,302 @@
<?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/>.
/**
* Base class for unit tests for profilefield_menu.
*
* @package profilefield_menu
* @copyright 2018 Mihail Geshoski <mihail@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace profilefield_menu\privacy;
defined('MOODLE_INTERNAL') || die();
use core_privacy\tests\provider_testcase;
use profilefield_menu\privacy\provider;
use core_privacy\local\request\approved_userlist;
/**
* Unit tests for user\profile\field\menu\classes\privacy\provider.php
*
* @copyright 2018 Mihail Geshoski <mihail@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider_test extends provider_testcase {
/**
* Basic setup for these tests.
*/
public function setUp(): void {
$this->resetAfterTest(true);
}
/**
* Test getting the context for the user ID related to this plugin.
*/
public function test_get_contexts_for_userid(): void {
global $DB;
// Create profile category.
$categoryid = $this->add_profile_category();
// Create profile field.
$profilefieldid = $this->add_profile_field($categoryid, 'menu');
// Create a user.
$user = $this->getDataGenerator()->create_user();
$this->add_user_info_data($user->id, $profilefieldid, 'test data');
// Get the field that was created.
$userfielddata = $DB->get_records('user_info_data', array('userid' => $user->id));
// Confirm we got the right number of user field data.
$this->assertCount(1, $userfielddata);
$context = \context_user::instance($user->id);
$contextlist = provider::get_contexts_for_userid($user->id);
$this->assertEquals($context, $contextlist->current());
}
/**
* Test that data is exported correctly for this plugin.
*/
public function test_export_user_data(): void {
// Create profile category.
$categoryid = $this->add_profile_category();
// Create menu profile field.
$menuprofilefieldid = $this->add_profile_field($categoryid, 'menu');
// Create checkbox profile field.
$checkboxprofilefieldid = $this->add_profile_field($categoryid, 'checkbox');
// Create a user.
$user = $this->getDataGenerator()->create_user();
$context = \context_user::instance($user->id);
// Add menu user info data.
$this->add_user_info_data($user->id, $menuprofilefieldid, 'test menu');
// Add checkbox user info data.
$this->add_user_info_data($user->id, $checkboxprofilefieldid, 'test data');
$writer = \core_privacy\local\request\writer::with_context($context);
$this->assertFalse($writer->has_any_data());
$this->export_context_data_for_user($user->id, $context, 'profilefield_menu');
$data = $writer->get_data([get_string('pluginname', 'profilefield_menu')]);
$this->assertCount(3, (array) $data);
$this->assertEquals('Test field', $data->name);
$this->assertEquals('This is a test.', $data->description);
$this->assertEquals('test menu', $data->data);
}
/**
* Test that user data is deleted using the context.
*/
public function test_delete_data_for_all_users_in_context(): void {
global $DB;
// Create profile category.
$categoryid = $this->add_profile_category();
// Create menu profile field.
$menuprofilefieldid = $this->add_profile_field($categoryid, 'menu');
// Create checkbox profile field.
$checkboxprofilefieldid = $this->add_profile_field($categoryid, 'checkbox');
// Create a user.
$user = $this->getDataGenerator()->create_user();
$context = \context_user::instance($user->id);
// Add menu user info data.
$this->add_user_info_data($user->id, $menuprofilefieldid, 'test menu');
// Add checkbox user info data.
$this->add_user_info_data($user->id, $checkboxprofilefieldid, 'test data');
// Check that we have two entries.
$userinfodata = $DB->get_records('user_info_data', ['userid' => $user->id]);
$this->assertCount(2, $userinfodata);
provider::delete_data_for_all_users_in_context($context);
// Check that the correct profile field has been deleted.
$userinfodata = $DB->get_records('user_info_data', ['userid' => $user->id]);
$this->assertCount(1, $userinfodata);
$this->assertNotEquals('test menu', reset($userinfodata)->data);
}
/**
* Test that user data is deleted for this user.
*/
public function test_delete_data_for_user(): void {
global $DB;
// Create profile category.
$categoryid = $this->add_profile_category();
// Create menu profile field.
$menuprofilefieldid = $this->add_profile_field($categoryid, 'menu');
// Create checkbox profile field.
$checkboxprofilefieldid = $this->add_profile_field($categoryid, 'checkbox');
// Create a user.
$user = $this->getDataGenerator()->create_user();
$context = \context_user::instance($user->id);
// Add menu user info data.
$this->add_user_info_data($user->id, $menuprofilefieldid, 'test menu');
// Add checkbox user info data.
$this->add_user_info_data($user->id, $checkboxprofilefieldid, 'test data');
// Check that we have two entries.
$userinfodata = $DB->get_records('user_info_data', ['userid' => $user->id]);
$this->assertCount(2, $userinfodata);
$approvedlist = new \core_privacy\local\request\approved_contextlist($user, 'profilefield_menu',
[$context->id]);
provider::delete_data_for_user($approvedlist);
// Check that the correct profile field has been deleted.
$userinfodata = $DB->get_records('user_info_data', ['userid' => $user->id]);
$this->assertCount(1, $userinfodata);
$this->assertNotEquals('test menu', reset($userinfodata)->data);
}
/**
* Test that only users with a user context are fetched.
*/
public function test_get_users_in_context(): void {
$this->resetAfterTest();
$component = 'profilefield_menu';
// Create profile category.
$categoryid = $this->add_profile_category();
// Create menu profile field.
$profilefieldid = $this->add_profile_field($categoryid, 'menu');
// Create a user.
$user = $this->getDataGenerator()->create_user();
$usercontext = \context_user::instance($user->id);
// The list of users should not return anything yet (related data still haven't been created).
$userlist = new \core_privacy\local\request\userlist($usercontext, $component);
provider::get_users_in_context($userlist);
$this->assertCount(0, $userlist);
$this->add_user_info_data($user->id, $profilefieldid, 'test data');
// The list of users for user context should return the user.
provider::get_users_in_context($userlist);
$this->assertCount(1, $userlist);
$expected = [$user->id];
$actual = $userlist->get_userids();
$this->assertEquals($expected, $actual);
// The list of users for system context should not return any users.
$systemcontext = \context_system::instance();
$userlist = new \core_privacy\local\request\userlist($systemcontext, $component);
provider::get_users_in_context($userlist);
$this->assertCount(0, $userlist);
}
/**
* Test that data for users in approved userlist is deleted.
*/
public function test_delete_data_for_users(): void {
$this->resetAfterTest();
$component = 'profilefield_menu';
// Create profile category.
$categoryid = $this->add_profile_category();
// Create menu profile field.
$profilefieldid = $this->add_profile_field($categoryid, 'menu');
// Create user1.
$user1 = $this->getDataGenerator()->create_user();
$usercontext1 = \context_user::instance($user1->id);
// Create user2.
$user2 = $this->getDataGenerator()->create_user();
$usercontext2 = \context_user::instance($user2->id);
$this->add_user_info_data($user1->id, $profilefieldid, 'test data');
$this->add_user_info_data($user2->id, $profilefieldid, 'test data');
// The list of users for usercontext1 should return user1.
$userlist1 = new \core_privacy\local\request\userlist($usercontext1, $component);
provider::get_users_in_context($userlist1);
$this->assertCount(1, $userlist1);
$expected = [$user1->id];
$actual = $userlist1->get_userids();
$this->assertEquals($expected, $actual);
// The list of users for usercontext2 should return user2.
$userlist2 = new \core_privacy\local\request\userlist($usercontext2, $component);
provider::get_users_in_context($userlist2);
$this->assertCount(1, $userlist2);
$expected = [$user2->id];
$actual = $userlist2->get_userids();
$this->assertEquals($expected, $actual);
// Add userlist1 to the approved user list.
$approvedlist = new approved_userlist($usercontext1, $component, $userlist1->get_userids());
// Delete user data using delete_data_for_user for usercontext1.
provider::delete_data_for_users($approvedlist);
// Re-fetch users in usercontext1 - The user list should now be empty.
$userlist1 = new \core_privacy\local\request\userlist($usercontext1, $component);
provider::get_users_in_context($userlist1);
$this->assertCount(0, $userlist1);
// Re-fetch users in usercontext2 - The user list should not be empty (user2).
$userlist2 = new \core_privacy\local\request\userlist($usercontext2, $component);
provider::get_users_in_context($userlist2);
$this->assertCount(1, $userlist2);
// User data should be only removed in the user context.
$systemcontext = \context_system::instance();
// Add userlist2 to the approved user list in the system context.
$approvedlist = new approved_userlist($systemcontext, $component, $userlist2->get_userids());
// Delete user1 data using delete_data_for_user.
provider::delete_data_for_users($approvedlist);
// Re-fetch users in usercontext2 - The user list should not be empty (user2).
$userlist1 = new \core_privacy\local\request\userlist($usercontext2, $component);
provider::get_users_in_context($userlist1);
$this->assertCount(1, $userlist1);
}
/**
* Add dummy user info data.
*
* @param int $userid The ID of the user
* @param int $fieldid The ID of the field
* @param string $data The data
*/
private function add_user_info_data($userid, $fieldid, $data) {
global $DB;
$userinfodata = array(
'userid' => $userid,
'fieldid' => $fieldid,
'data' => $data,
'dataformat' => 0
);
$DB->insert_record('user_info_data', $userinfodata);
}
/**
* Add dummy profile category.
*
* @return int The ID of the profile category
*/
private function add_profile_category() {
$cat = $this->getDataGenerator()->create_custom_profile_field_category(['name' => 'Test category']);
return $cat->id;
}
/**
* Add dummy profile field.
*
* @param int $categoryid The ID of the profile category
* @param string $datatype The datatype of the profile field
* @return int The ID of the profile field
*/
private function add_profile_field($categoryid, $datatype) {
$data = $this->getDataGenerator()->create_custom_profile_field([
'datatype' => $datatype,
'shortname' => 'tstField',
'name' => 'Test field',
'description' => 'This is a test.',
'categoryid' => $categoryid,
]);
return $data->id;
}
}
+29
View File
@@ -0,0 +1,29 @@
<?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/>.
/**
* Menu profile field version information.
*
* @package profilefield_menu
* @copyright 2007 onwards Shane Elliot {@link http://pukunui.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$plugin->version = 2024042200; // The current plugin version (Date: YYYYMMDDXX).
$plugin->requires = 2024041600; // Requires this Moodle version.
$plugin->component = 'profilefield_menu'; // Full name of the plugin (used for diagnostics)
@@ -0,0 +1,74 @@
<?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/>.
/**
* Contains class profilefield_social\networks
*
* @package profilefield_social
* @copyright 2020 Bas Brands
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace profilefield_social;
/**
* helper class for social profile fields.
*
* @copyright 2020 Bas Brands <bas@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class helper {
/**
* Get the available social networks
*
* @return array list of social networks.
*/
public static function get_networks(): array {
return [
'icq' => get_string('icqnumber', 'profilefield_social'),
'msn' => get_string('msnid', 'profilefield_social'),
'aim' => get_string('aimid', 'profilefield_social'),
'yahoo' => get_string('yahooid', 'profilefield_social'),
'skype' => get_string('skypeid', 'profilefield_social'),
'url' => get_string('webpage', 'profilefield_social'),
];
}
/**
* Get the translated fieldname string for a network.
*
* @param string $fieldname Network short name.
* @return string network name.
*/
public static function get_fieldname(string $fieldname): string {
$networks = self::get_networks();
return $networks[$fieldname];
}
/**
* Get the available network url formats.
*
* @return array list network url strings.
*/
public static function get_network_urls(): array {
return [
'skype' => '<a href="skype:%%ENCODED%%?call">%%PLAIN%%</a>',
'icq' => '<a href="http://www.icq.com/whitepages/cmd.php?uin=%%ENCODED%%&action=message">%%PLAIN%%</a>',
'url' => '<a href="%%PLAIN%%">%%PLAIN%%</a>'
];
}
}
@@ -0,0 +1,214 @@
<?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/>.
/**
* Privacy class for requesting user data.
*
* @package profilefield_social
* @copyright 2020 Bas Brands
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace profilefield_social\privacy;
defined('MOODLE_INTERNAL') || die();
use \core_privacy\local\metadata\collection;
use \core_privacy\local\request\contextlist;
use \core_privacy\local\request\approved_contextlist;
use core_privacy\local\request\userlist;
use core_privacy\local\request\approved_userlist;
/**
* Privacy class for requesting user data.
*
* @copyright 2018 Mihail Geshoski <mihail@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider implements
\core_privacy\local\metadata\provider,
\core_privacy\local\request\core_userlist_provider,
\core_privacy\local\request\plugin\provider {
/**
* Returns meta data about this system.
*
* @param collection $collection The initialised collection to add items to.
* @return collection A listing of user data stored through this system.
*/
public static function get_metadata(collection $collection): collection {
return $collection->add_database_table('user_info_data', [
'userid' => 'privacy:metadata:profile_field_social:userid',
'fieldid' => 'privacy:metadata:profile_field_social:fieldid',
'data' => 'privacy:metadata:profile_field_social:data',
'dataformat' => 'privacy:metadata:profile_field_social:dataformat'
], 'privacy:metadata:profile_field_social:tableexplanation');
}
/**
* Get the list of contexts that contain user information for the specified user.
*
* @param int $userid The user to search.
* @return contextlist $contextlist The contextlist containing the list of contexts used in this plugin.
*/
public static function get_contexts_for_userid(int $userid): contextlist {
$sql = "SELECT ctx.id
FROM {user_info_data} uda
JOIN {user_info_field} uif ON uda.fieldid = uif.id
JOIN {context} ctx ON ctx.instanceid = uda.userid
AND ctx.contextlevel = :contextlevel
WHERE uda.userid = :userid
AND uif.datatype = :datatype";
$params = [
'userid' => $userid,
'contextlevel' => CONTEXT_USER,
'datatype' => 'social'
];
$contextlist = new contextlist();
$contextlist->add_from_sql($sql, $params);
return $contextlist;
}
/**
* Get the list of users within a specific context.
*
* @param userlist $userlist The userlist containing the list of users who have data in this context/plugin combination.
*/
public static function get_users_in_context(userlist $userlist) {
$context = $userlist->get_context();
if (!$context instanceof \context_user) {
return;
}
$sql = "SELECT uda.userid
FROM {user_info_data} uda
JOIN {user_info_field} uif
ON uda.fieldid = uif.id
WHERE uda.userid = :userid
AND uif.datatype = :datatype";
$params = [
'userid' => $context->instanceid,
'datatype' => 'social'
];
$userlist->add_from_sql('userid', $sql, $params);
}
/**
* Export all user data for the specified user, in the specified contexts.
*
* @param approved_contextlist $contextlist The approved contexts to export information for.
*/
public static function export_user_data(approved_contextlist $contextlist) {
$user = $contextlist->get_user();
foreach ($contextlist->get_contexts() as $context) {
// Check if the context is a user context.
if ($context->contextlevel == CONTEXT_USER && $context->instanceid == $user->id) {
$results = static::get_records($user->id);
foreach ($results as $result) {
$data = (object) [
'name' => $result->name,
'description' => $result->description,
'data' => $result->data
];
\core_privacy\local\request\writer::with_context($context)->export_data([
get_string('pluginname', 'profilefield_social')], $data);
}
}
}
}
/**
* Delete all user data which matches the specified context.
*
* @param context $context A user context.
*/
public static function delete_data_for_all_users_in_context(\context $context) {
// Delete data only for user context.
if ($context->contextlevel == CONTEXT_USER) {
static::delete_data($context->instanceid);
}
}
/**
* Delete multiple users within a single context.
*
* @param approved_userlist $userlist The approved context and user information to delete information for.
*/
public static function delete_data_for_users(approved_userlist $userlist) {
$context = $userlist->get_context();
if ($context instanceof \context_user) {
static::delete_data($context->instanceid);
}
}
/**
* Delete all user data for the specified user, in the specified contexts.
*
* @param approved_contextlist $contextlist The approved contexts and user information to delete information for.
*/
public static function delete_data_for_user(approved_contextlist $contextlist) {
$user = $contextlist->get_user();
foreach ($contextlist->get_contexts() as $context) {
// Check if the context is a user context.
if ($context->contextlevel == CONTEXT_USER && $context->instanceid == $user->id) {
static::delete_data($context->instanceid);
}
}
}
/**
* Delete data related to a userid.
*
* @param int $userid The user ID
*/
protected static function delete_data($userid) {
global $DB;
$params = [
'userid' => $userid,
'datatype' => 'social'
];
$DB->delete_records_select('user_info_data', "fieldid IN (
SELECT id FROM {user_info_field} WHERE datatype = :datatype)
AND userid = :userid", $params);
}
/**
* Get records related to this plugin and user.
*
* @param int $userid The user ID
* @return array An array of records.
*/
protected static function get_records($userid) {
global $DB;
$sql = "SELECT *
FROM {user_info_data} uda
JOIN {user_info_field} uif ON uda.fieldid = uif.id
WHERE uda.userid = :userid
AND uif.datatype = :datatype";
$params = [
'userid' => $userid,
'datatype' => 'social'
];
return $DB->get_records_sql($sql, $params);
}
}
@@ -0,0 +1,95 @@
<?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/>.
/**
* Textarea profile field define.
*
* @package profilefield_social
* @copyright 2020 Bas Brands <bas@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/**
* Class profile_define_social.
*
* @copyright 2020 Bas Brands <bas@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class profile_define_social extends profile_define_base {
/**
* Prints out the form snippet for the part of creating or editing a profile field common to all data types.
*
* @param MoodleQuickForm $form instance of the moodleform class
*/
public function define_form_common(&$form) {
$availablenetworks = profilefield_social\helper::get_networks();
$networks = array_merge(['0' => get_string('select')], $availablenetworks);
$form->addElement('hidden', 'defaultdata', '');
$form->setType('defaultdata', PARAM_TEXT);
$form->addElement('select', 'param1', get_string('networktype', 'profilefield_social'), $networks);
$form->addRule('param1', get_string('required'), 'required', null, 'client');
$form->setType('param1', PARAM_TEXT);
parent::define_form_common($form);
$form->removeElement('name');
}
/**
* Alter form based on submitted or existing data.
*
* @param MoodleQuickForm $form
*/
public function define_after_data(&$form) {
if (isset($form->_defaultValues['name'])) {
$form->setDefault('param1', $form->_defaultValues['name']);
}
}
/**
* Validate the data from the add/edit profile field form that is common to all data types.
*
* Generally this method should not be overwritten by child classes.
*
* @param stdClass|array $data from the add/edit profile field form
* @param array $files
* @return array associative array of error messages
*/
public function define_validate_common($data, $files) {
$err = parent::define_validate_common($data, $files);
$networks = profilefield_social\helper::get_networks();
if (empty($data->param1) || !array_key_exists($data->param1, $networks)) {
$err['param1'] = get_string('invalidnetwork', 'profilefield_social');
}
return $err;
}
/**
* Preprocess data from the add/edit profile field form before it is saved.
*
* This method is a hook for the child classes to overwrite.
*
* @param array|stdClass $data from the add/edit profile field form
* @return array|stdClass processed data object
*/
public function define_save_preprocess($data) {
$data->name = $data->param1;
return $data;
}
}
+86
View File
@@ -0,0 +1,86 @@
<?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/>.
/**
* Social profile field define.
*
* @package profilefield_social
* @copyright 2020 Bas Brands <bas@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/**
* Class profile_field_social.
*
* @copyright 2020 Bas Brands <bas@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class profile_field_social extends profile_field_base {
/**
* Adds elements for this field type to the edit form.
* @param moodleform $mform
*/
public function edit_field_add($mform) {
$mform->addElement('text', $this->inputname, $this->field->name, null, null);
if ($this->field->param1 === 'url') {
$mform->setType($this->inputname, PARAM_URL);
} else {
$mform->setType($this->inputname, PARAM_NOTAGS);
}
}
/**
* alter the fieldname to be fetched from the language file.
*
* @param stdClass $field
*/
public function set_field($field) {
$networks = profilefield_social\helper::get_networks();
$field->name = $networks[$field->name];
parent::set_field($field);
}
/**
* Display the data for this field
* @return string
*/
public function display_data() {
$network = $this->field->param1;
$networkurls = profilefield_social\helper::get_network_urls();
if (array_key_exists($network, $networkurls)) {
$pattern = ['%%ENCODED%%', '%%PLAIN%%'];
$data = [rawurlencode($this->data), $this->data];
return str_replace($pattern, $data, $networkurls[$network]);
}
return $this->data;
}
/**
* Return the field type and null properties.
* This will be used for validating the data submitted by a user.
*
* @return array the param type and null property
* @since Moodle 3.2
*/
public function get_field_properties() {
return array(PARAM_TEXT, NULL_NOT_ALLOWED);
}
}
@@ -0,0 +1,39 @@
<?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/>.
/**
* Strings for component 'profilefield_social'
*
* @package profilefield_social
* @copyright 2020 Bas Brands <bas@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$string['invalidnetwork'] = 'Invalid social network';
$string['networkinuse'] = 'Social network has already been added';
$string['pluginname'] = 'Social';
$string['networktype'] = 'Network type';
$string['privacy:metadata:profile_field_social:data'] = 'Text area user profile field user data';
$string['privacy:metadata:profile_field_social:dataformat'] = 'The format of Text area user profile field user data';
$string['privacy:metadata:profile_field_social:fieldid'] = 'The ID of the profile field';
$string['privacy:metadata:profile_field_social:tableexplanation'] = 'Additional profile data';
$string['privacy:metadata:profile_field_social:userid'] = 'The ID of the user whose data is stored by the social user profile field';
$string['aimid'] = 'AIM ID';
$string['yahooid'] = 'Yahoo ID';
$string['skypeid'] = 'Skype ID';
$string['icqnumber'] = 'ICQ number';
$string['msnid'] = 'MSN ID';
$string['webpage'] = 'Web page';
@@ -0,0 +1,23 @@
@core @core_user
Feature: Social profile fields can not have a duplicate shortname.
In order edit social profile fields properly
As an admin
I should not be able to create duplicate shortnames for social profile fields.
@javascript
Scenario: Verify you can edit social profile fields.
Given I log in as "admin"
When I navigate to "Users > Accounts > User profile fields" in site administration
And I click on "Create a new profile field" "link"
And I click on "Social" "link"
And I set the following fields to these values:
| Network type | Yahoo ID |
| Short name | yahoo |
And I click on "Save changes" "button"
And I click on "Create a new profile field" "link"
And I click on "Social" "link"
And I set the following fields to these values:
| Network type | Yahoo ID |
| Short name | yahoo |
And I click on "Save changes" "button"
Then I should see "This short name is already in use"
@@ -0,0 +1,301 @@
<?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/>.
/**
* Base class for unit tests for profilefield_social.
*
* @package profilefield_social
* @copyright 2020 Bas Brands <bas@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace profilefield_social\privacy;
defined('MOODLE_INTERNAL') || die();
use core_privacy\tests\provider_testcase;
use profilefield_social\privacy\provider;
use core_privacy\local\request\approved_userlist;
/**
* Unit tests for user\profile\field\social\classes\privacy\provider.php
*
* @copyright 2020 Bas Brands <bas@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider_test extends provider_testcase {
/**
* Basic setup for these tests.
*/
public function setUp(): void {
$this->resetAfterTest(true);
}
/**
* Test getting the context for the user ID related to this plugin.
*/
public function test_get_contexts_for_userid(): void {
global $DB;
// Create profile category.
$categoryid = $this->add_profile_category();
// Create profile field.
$profilefieldid = $this->add_profile_field($categoryid, 'social');
// Create a user.
$user = $this->getDataGenerator()->create_user();
$this->add_user_info_data($user->id, $profilefieldid, 'test data');
// Get the field that was created.
$userfielddata = $DB->get_records('user_info_data', array('userid' => $user->id));
// Confirm we got the right number of user field data.
$this->assertCount(1, $userfielddata);
$context = \context_user::instance($user->id);
$contextlist = provider::get_contexts_for_userid($user->id);
$this->assertEquals($context, $contextlist->current());
}
/**
* Test that data is exported correctly for this plugin.
*/
public function test_export_user_data(): void {
// Create profile category.
$categoryid = $this->add_profile_category();
// Create social profile field.
$socialprofilefieldid = $this->add_profile_field($categoryid, 'social');
// Create checkbox profile field.
$checkboxprofilefieldid = $this->add_profile_field($categoryid, 'checkbox');
// Create a user.
$user = $this->getDataGenerator()->create_user();
$context = \context_user::instance($user->id);
// Add social user info data.
$this->add_user_info_data($user->id, $socialprofilefieldid, '#icq-1294923');
// Add checkbox user info data.
$this->add_user_info_data($user->id, $checkboxprofilefieldid, 'test data');
$writer = \core_privacy\local\request\writer::with_context($context);
$this->assertFalse($writer->has_any_data());
$this->export_context_data_for_user($user->id, $context, 'profilefield_social');
$data = $writer->get_data([get_string('pluginname', 'profilefield_social')]);
$this->assertCount(3, (array) $data);
$this->assertEquals('icq', $data->name);
$this->assertEquals('', $data->description);
$this->assertEquals('#icq-1294923', $data->data);
}
/**
* Test that user data is deleted using the context.
*/
public function test_delete_data_for_all_users_in_context(): void {
global $DB;
// Create profile category.
$categoryid = $this->add_profile_category();
// Create social profile field.
$socialprofilefieldid = $this->add_profile_field($categoryid, 'social');
// Create checkbox profile field.
$checkboxprofilefieldid = $this->add_profile_field($categoryid, 'checkbox');
// Create a user.
$user = $this->getDataGenerator()->create_user();
$context = \context_user::instance($user->id);
// Add social user info data.
$this->add_user_info_data($user->id, $socialprofilefieldid, '#icq-1294923');
// Add checkbox user info data.
$this->add_user_info_data($user->id, $checkboxprofilefieldid, 'test data');
// Check that we have two entries.
$userinfodata = $DB->get_records('user_info_data', ['userid' => $user->id]);
$this->assertCount(2, $userinfodata);
provider::delete_data_for_all_users_in_context($context);
// Check that the correct profile field has been deleted.
$userinfodata = $DB->get_records('user_info_data', ['userid' => $user->id]);
$this->assertCount(1, $userinfodata);
$this->assertNotEquals('#icq-1294923', reset($userinfodata)->data);
}
/**
* Test that user data is deleted for this user.
*/
public function test_delete_data_for_user(): void {
global $DB;
// Create profile category.
$categoryid = $this->add_profile_category();
// Create social profile field.
$socialprofilefieldid = $this->add_profile_field($categoryid, 'social');
// Create checkbox profile field.
$checkboxprofilefieldid = $this->add_profile_field($categoryid, 'checkbox');
// Create a user.
$user = $this->getDataGenerator()->create_user();
$context = \context_user::instance($user->id);
// Add social user info data.
$this->add_user_info_data($user->id, $socialprofilefieldid, '#icq-1294923');
// Add checkbox user info data.
$this->add_user_info_data($user->id, $checkboxprofilefieldid, 'test data');
// Check that we have two entries.
$userinfodata = $DB->get_records('user_info_data', ['userid' => $user->id]);
$this->assertCount(2, $userinfodata);
$approvedlist = new \core_privacy\local\request\approved_contextlist($user, 'profilefield_social',
[$context->id]);
provider::delete_data_for_user($approvedlist);
// Check that the correct profile field has been deleted.
$userinfodata = $DB->get_records('user_info_data', ['userid' => $user->id]);
$this->assertCount(1, $userinfodata);
$this->assertNotEquals('#icq-1294923', reset($userinfodata)->data);
}
/**
* Test that only users with a user context are fetched.
*/
public function test_get_users_in_context(): void {
$this->resetAfterTest();
$component = 'profilefield_social';
// Create profile category.
$categoryid = $this->add_profile_category();
// Create profile field.
$profilefieldid = $this->add_profile_field($categoryid, 'social');
// Create a user.
$user = $this->getDataGenerator()->create_user();
$usercontext = \context_user::instance($user->id);
// The list of users should not return anything yet (related data still haven't been created).
$userlist = new \core_privacy\local\request\userlist($usercontext, $component);
provider::get_users_in_context($userlist);
$this->assertCount(0, $userlist);
$this->add_user_info_data($user->id, $profilefieldid, 'test data');
// The list of users for user context should return the user.
provider::get_users_in_context($userlist);
$this->assertCount(1, $userlist);
$expected = [$user->id];
$actual = $userlist->get_userids();
$this->assertEquals($expected, $actual);
// The list of users for system context should not return any users.
$systemcontext = \context_system::instance();
$userlist = new \core_privacy\local\request\userlist($systemcontext, $component);
provider::get_users_in_context($userlist);
$this->assertCount(0, $userlist);
}
/**
* Test that data for users in approved userlist is deleted.
*/
public function test_delete_data_for_users(): void {
$this->resetAfterTest();
$component = 'profilefield_social';
// Create profile category.
$categoryid = $this->add_profile_category();
// Create profile field.
$profilefieldid = $this->add_profile_field($categoryid, 'social');
// Create user1.
$user1 = $this->getDataGenerator()->create_user();
$usercontext1 = \context_user::instance($user1->id);
// Create user2.
$user2 = $this->getDataGenerator()->create_user();
$usercontext2 = \context_user::instance($user2->id);
$this->add_user_info_data($user1->id, $profilefieldid, 'test data');
$this->add_user_info_data($user2->id, $profilefieldid, 'test data');
// The list of users for usercontext1 should return user1.
$userlist1 = new \core_privacy\local\request\userlist($usercontext1, $component);
provider::get_users_in_context($userlist1);
$this->assertCount(1, $userlist1);
$expected = [$user1->id];
$actual = $userlist1->get_userids();
$this->assertEquals($expected, $actual);
// The list of users for usercontext2 should return user2.
$userlist2 = new \core_privacy\local\request\userlist($usercontext2, $component);
provider::get_users_in_context($userlist2);
$this->assertCount(1, $userlist2);
$expected = [$user2->id];
$actual = $userlist2->get_userids();
$this->assertEquals($expected, $actual);
// Add userlist1 to the approved user list.
$approvedlist = new approved_userlist($usercontext1, $component, $userlist1->get_userids());
// Delete user data using delete_data_for_user for usercontext1.
provider::delete_data_for_users($approvedlist);
// Re-fetch users in usercontext1 - The user list should now be empty.
$userlist1 = new \core_privacy\local\request\userlist($usercontext1, $component);
provider::get_users_in_context($userlist1);
$this->assertCount(0, $userlist1);
// Re-fetch users in usercontext2 - The user list should not be empty (user2).
$userlist2 = new \core_privacy\local\request\userlist($usercontext2, $component);
provider::get_users_in_context($userlist2);
$this->assertCount(1, $userlist2);
// User data should be only removed in the user context.
$systemcontext = \context_system::instance();
// Add userlist2 to the approved user list in the system context.
$approvedlist = new approved_userlist($systemcontext, $component, $userlist2->get_userids());
// Delete user1 data using delete_data_for_user.
provider::delete_data_for_users($approvedlist);
// Re-fetch users in usercontext2 - The user list should not be empty (user2).
$userlist1 = new \core_privacy\local\request\userlist($usercontext2, $component);
provider::get_users_in_context($userlist1);
$this->assertCount(1, $userlist1);
}
/**
* Add dummy user info data.
*
* @param int $userid The ID of the user
* @param int $fieldid The ID of the field
* @param string $data The data
*/
private function add_user_info_data($userid, $fieldid, $data) {
global $DB;
$userinfodata = array(
'userid' => $userid,
'fieldid' => $fieldid,
'data' => $data,
'dataformat' => 0
);
$DB->insert_record('user_info_data', $userinfodata);
}
/**
* Add dummy profile category.
*
* @return int The ID of the profile category
*/
private function add_profile_category() {
$cat = $this->getDataGenerator()->create_custom_profile_field_category(['name' => 'Test category']);
return $cat->id;
}
/**
* Add dummy profile field.
*
* @param int $categoryid The ID of the profile category
* @param string $datatype The datatype of the profile field
* @return int The ID of the profile field
*/
private function add_profile_field($categoryid, $datatype) {
$data = $this->getDataGenerator()->create_custom_profile_field([
'datatype' => $datatype,
'shortname' => 'icq',
'name' => 'icq',
'description' => '',
'categoryid' => $categoryid,
]);
return $data->id;
}
}
+196
View File
@@ -0,0 +1,196 @@
<?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/>.
/**
* Contains upgrade and install functions for the social profile fields.
*
* @package profilefield_social
* @copyright 2020 Bas Brands <bas@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once("$CFG->dirroot/user/profile/definelib.php");
/**
* Create the default category for custom profile fields if it does not exist yet.
*
* @return int Category ID for social user profile category.
*/
function user_profile_social_create_info_category(): int {
global $DB;
$categories = $DB->get_records('user_info_category', null, 'sortorder ASC');
// Check that we have at least one category defined.
if (empty($categories)) {
$defaultcategory = (object) [
'name' => get_string('profiledefaultcategory', 'admin'),
'sortorder' => 1
];
return $DB->insert_record('user_info_category', $defaultcategory);
} else {
return (int)$DB->get_field_sql('SELECT min(id) from {user_info_category}');
}
}
/**
* Called on upgrade to create new profile fields based on the old user table columns
* for icq, msn, aim, skype and url.
*
* @param string $social Social profile field.
*/
function user_profile_social_moveto_profilefield($social) {
global $DB;
$users = $DB->get_records_select('user', "$social IS NOT NULL AND $social != ''");
if (count($users)) {
$profilefield = user_profile_social_create_profilefield($social);
foreach ($users as $user) {
$userinfodata = [
'userid' => $user->id,
'fieldid' => $profilefield->id,
'data' => $user->$social,
'dataformat' => 0
];
$user->$social = '';
$DB->update_record('user', $user);
$DB->insert_record('user_info_data', $userinfodata);
}
}
}
/**
* Create an new custom social profile field if it does not exist
*
* @param string $social Social profile field.
* @return object DB record or social profield field.
*/
function user_profile_social_create_profilefield($social) {
global $DB, $CFG;
$hiddenfields = explode(',', $CFG->hiddenuserfields);
$confignames = [
'url' => 'webpage',
'icq' => 'icqnumber',
'skype' => 'skypeid',
'yahoo' => 'yahooid',
'aim' => 'aimid',
'msn' => 'msnid',
];
$visible = (in_array($confignames[$social], $hiddenfields)) ? 3 : 2;
$categoryid = user_profile_social_create_info_category();
$newfield = (object)[
'shortname' => $social,
'name' => $social,
'datatype' => 'social',
'description' => '',
'descriptionformat' => 1,
'categoryid' => $categoryid,
'required' => 0,
'locked' => 0,
'visible' => $visible,
'forceunique' => 0,
'signup' => 0,
'defaultdata' => '',
'defaultdataformat' => 0,
'param1' => $social
];
$profilefield = $DB->get_record_sql(
'SELECT * FROM {user_info_field} WHERE datatype = :datatype AND ' .
$DB->sql_compare_text('param1') . ' = ' . $DB->sql_compare_text(':social', 40),
['datatype' => 'social', 'social' => $social]);
if (!$profilefield) {
// Find a new unique shortname.
$count = 0;
$shortname = $newfield->shortname;
while ($field = $DB->get_record('user_info_field', array('shortname' => $shortname))) {
$count++;
$shortname = $newfield->shortname . '_' . $count;
}
$newfield->shortname = $shortname;
$profileclass = new profile_define_base();
$profileclass->define_save($newfield);
profile_reorder_fields();
$profilefield = $DB->get_record_sql(
'SELECT * FROM {user_info_field} WHERE datatype = :datatype AND ' .
$DB->sql_compare_text('param1') . ' = ' . $DB->sql_compare_text(':social', 40),
['datatype' => 'social', 'social' => $social]);
}
if (!$profilefield) {
throw new moodle_exception('upgradeerror', 'admin', 'could not create new social profile field');
}
return $profilefield;
}
/**
* Update the module availability configuration for all course modules
*
*/
function user_profile_social_update_module_availability() {
global $DB;
// Use transaction to improve performance if there are many individual database updates.
$transaction = $DB->start_delegated_transaction();
// Query all the course_modules entries that have availability set.
$rs = $DB->get_recordset_select('course_modules', 'availability IS NOT NULL', [], '', 'id, availability');
foreach ($rs as $mod) {
if (isset($mod->availability)) {
$availability = json_decode($mod->availability);
if (!is_null($availability)) {
user_profile_social_update_availability_structure($availability);
$newavailability = json_encode($availability);
if ($newavailability !== $mod->availability) {
$mod->availability = json_encode($availability);
$DB->update_record('course_modules', $mod);
}
}
}
}
$rs->close();
$transaction->allow_commit();
}
/**
* Loop through the availability info and change all move standard profile
* fields for icq, skype, aim, yahoo, msn and url to be custom profile fields.
* @param mixed $structure The availability object.
*/
function user_profile_social_update_availability_structure(&$structure) {
if (is_array($structure)) {
foreach ($structure as $st) {
user_profile_social_update_availability_structure($st);
}
}
foreach ($structure as $key => $value) {
if ($key === 'c' && is_array($value)) {
user_profile_social_update_availability_structure($value);
}
if ($key === 'type' && $value === 'profile') {
if (isset($structure->sf) && in_array($structure->sf,
['icq', 'skype', 'aim', 'yahoo', 'msn', 'url'])) {
$structure->cf = $structure->sf;
unset($structure->sf);
}
}
}
}
+29
View File
@@ -0,0 +1,29 @@
<?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/>.
/**
* Version information for the social profile field.
*
* @package profilefield_social
* @copyright 2020 Bas Brands <bas@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$plugin->version = 2024042200;
$plugin->requires = 2024041600;
$plugin->component = 'profilefield_social';
@@ -0,0 +1,214 @@
<?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/>.
/**
* Privacy class for requesting user data.
*
* @package profilefield_text
* @copyright 2018 Mihail Geshoski <mihail@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace profilefield_text\privacy;
use \core_privacy\local\metadata\collection;
use \core_privacy\local\request\contextlist;
use \core_privacy\local\request\approved_contextlist;
use core_privacy\local\request\userlist;
use core_privacy\local\request\approved_userlist;
/**
* Privacy class for requesting user data.
*
* @copyright 2018 Mihail Geshoski <mihail@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider implements
\core_privacy\local\metadata\provider,
\core_privacy\local\request\core_userlist_provider,
\core_privacy\local\request\plugin\provider {
/**
* Returns meta data about this system.
*
* @param collection $collection The initialised collection to add items to.
* @return collection A listing of user data stored through this system.
*/
public static function get_metadata(collection $collection): collection {
return $collection->add_database_table('user_info_data', [
'userid' => 'privacy:metadata:profilefield_text:userid',
'fieldid' => 'privacy:metadata:profilefield_text:fieldid',
'data' => 'privacy:metadata:profilefield_text:data',
'dataformat' => 'privacy:metadata:profilefield_text:dataformat'
], 'privacy:metadata:profilefield_text:tableexplanation');
}
/**
* Get the list of contexts that contain user information for the specified user.
*
* @param int $userid The user to search.
* @return contextlist $contextlist The contextlist containing the list of contexts used in this plugin.
*/
public static function get_contexts_for_userid(int $userid): contextlist {
$sql = "SELECT ctx.id
FROM {user_info_data} uda
JOIN {user_info_field} uif ON uda.fieldid = uif.id
JOIN {context} ctx ON ctx.instanceid = uda.userid
AND ctx.contextlevel = :contextlevel
WHERE uda.userid = :userid
AND uif.datatype = :datatype";
$params = [
'userid' => $userid,
'contextlevel' => CONTEXT_USER,
'datatype' => 'text'
];
$contextlist = new contextlist();
$contextlist->add_from_sql($sql, $params);
return $contextlist;
}
/**
* Get the list of users within a specific context.
*
* @param userlist $userlist The userlist containing the list of users who have data in this context/plugin combination.
*/
public static function get_users_in_context(userlist $userlist) {
$context = $userlist->get_context();
if (!$context instanceof \context_user) {
return;
}
$sql = "SELECT uda.userid
FROM {user_info_data} uda
JOIN {user_info_field} uif
ON uda.fieldid = uif.id
WHERE uda.userid = :userid
AND uif.datatype = :datatype";
$params = [
'userid' => $context->instanceid,
'datatype' => 'text'
];
$userlist->add_from_sql('userid', $sql, $params);
}
/**
* Export all user data for the specified user, in the specified contexts.
*
* @param approved_contextlist $contextlist The approved contexts to export information for.
*/
public static function export_user_data(approved_contextlist $contextlist) {
$user = $contextlist->get_user();
foreach ($contextlist->get_contexts() as $context) {
// Check if the context is a user context.
if ($context->contextlevel == CONTEXT_USER && $context->instanceid == $user->id) {
$results = static::get_records($user->id);
foreach ($results as $result) {
$data = (object) [
'name' => $result->name,
'description' => $result->description,
'data' => $result->data
];
\core_privacy\local\request\writer::with_context($context)->export_data([
get_string('pluginname', 'profilefield_text')], $data);
}
}
}
}
/**
* Delete all user data which matches the specified context.
*
* @param context $context A user context.
*/
public static function delete_data_for_all_users_in_context(\context $context) {
// Delete data only for user context.
if ($context->contextlevel == CONTEXT_USER) {
static::delete_data($context->instanceid);
}
}
/**
* Delete multiple users within a single context.
*
* @param approved_userlist $userlist The approved context and user information to delete information for.
*/
public static function delete_data_for_users(approved_userlist $userlist) {
$context = $userlist->get_context();
if ($context instanceof \context_user) {
static::delete_data($context->instanceid);
}
}
/**
* Delete all user data for the specified user, in the specified contexts.
*
* @param approved_contextlist $contextlist The approved contexts and user information to delete information for.
*/
public static function delete_data_for_user(approved_contextlist $contextlist) {
$user = $contextlist->get_user();
foreach ($contextlist->get_contexts() as $context) {
// Check if the context is a user context.
if ($context->contextlevel == CONTEXT_USER && $context->instanceid == $user->id) {
static::delete_data($context->instanceid);
}
}
}
/**
* Delete data related to a userid.
*
* @param int $userid The user ID
*/
protected static function delete_data($userid) {
global $DB;
$params = [
'userid' => $userid,
'datatype' => 'text'
];
$DB->delete_records_select('user_info_data', "fieldid IN (
SELECT id FROM {user_info_field} WHERE datatype = :datatype)
AND userid = :userid", $params);
}
/**
* Get records related to this plugin and user.
*
* @param int $userid The user ID
* @return array An array of records.
*/
protected static function get_records($userid) {
global $DB;
$sql = "SELECT *
FROM {user_info_data} uda
JOIN {user_info_field} uif ON uda.fieldid = uif.id
WHERE uda.userid = :userid
AND uif.datatype = :datatype";
$params = [
'userid' => $userid,
'datatype' => 'text'
];
return $DB->get_records_sql($sql, $params);
}
}
+73
View File
@@ -0,0 +1,73 @@
<?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/>.
/**
* Text profile field definition.
*
* @package profilefield_text
* @copyright 2007 onwards Shane Elliot {@link http://pukunui.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/**
* Class profile_define_text
*
* @copyright 2007 onwards Shane Elliot {@link http://pukunui.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class profile_define_text extends profile_define_base {
/**
* Add elements for creating/editing a text profile field.
*
* @param MoodleQuickForm $form
*/
public function define_form_specific($form) {
// Default data.
$form->addElement('text', 'defaultdata', get_string('profiledefaultdata', 'admin'), 'size="50"');
$form->setType('defaultdata', PARAM_TEXT);
// Param 1 for text type is the size of the field.
$form->addElement('text', 'param1', get_string('profilefieldsize', 'admin'), 'size="6"');
$form->setDefault('param1', 30);
$form->setType('param1', PARAM_INT);
// Param 2 for text type is the maxlength of the field.
$form->addElement('text', 'param2', get_string('profilefieldmaxlength', 'admin'), 'size="6"');
$form->setDefault('param2', 2048);
$form->setType('param2', PARAM_INT);
$form->addHelpButton('param2', 'profilefieldmaxlength', 'admin');
// Param 3 for text type detemines if this is a password field or not.
$form->addElement('selectyesno', 'param3', get_string('profilefieldispassword', 'admin'));
$form->setDefault('param3', 0); // Defaults to 'no'.
$form->setType('param3', PARAM_INT);
// Param 4 for text type contains a link.
$form->addElement('text', 'param4', get_string('profilefieldlink', 'admin'));
$form->setType('param4', PARAM_URL);
$form->addHelpButton('param4', 'profilefieldlink', 'admin');
// Param 5 for text type contains link target.
$targetoptions = array( '' => get_string('linktargetnone', 'editor'),
'_blank' => get_string('linktargetblank', 'editor'),
'_self' => get_string('linktargetself', 'editor'),
'_top' => get_string('linktargettop', 'editor')
);
$form->addElement('select', 'param5', get_string('profilefieldlinktarget', 'admin'), $targetoptions);
$form->setType('param5', PARAM_RAW);
}
}
+112
View File
@@ -0,0 +1,112 @@
<?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/>.
/**
* Text profile field.
*
* @package profilefield_text
* @copyright 2007 onwards Shane Elliot {@link http://pukunui.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/**
* Class profile_field_text
*
* @copyright 2007 onwards Shane Elliot {@link http://pukunui.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class profile_field_text extends profile_field_base {
/**
* Overwrite the base class to display the data for this field
*/
public function display_data() {
// Default formatting.
$data = format_string($this->data);
// Are we creating a link?
if (!empty($this->field->param4) && !empty($data)) {
// Define the target.
if (! empty($this->field->param5)) {
$target = 'target="'.$this->field->param5.'"';
} else {
$target = '';
}
// Create the link.
$data = '<a href="'.str_replace('$$', urlencode($data),
$this->field->param4).'" '.$target.'>'.htmlspecialchars($data, ENT_COMPAT).'</a>';
}
return $data;
}
/**
* Add fields for editing a text profile field.
* @param moodleform $mform
*/
public function edit_field_add($mform) {
$size = $this->field->param1;
$maxlength = $this->field->param2;
$fieldtype = ($this->field->param3 == 1 ? 'password' : 'text');
// Create the form field.
$mform->addElement($fieldtype, $this->inputname, format_string($this->field->name),
'maxlength="'.$maxlength.'" size="'.$size.'" ');
$mform->setType($this->inputname, PARAM_TEXT);
}
/**
* Process the data before it gets saved in database
*
* @param string|null $data
* @param stdClass $datarecord
* @return string|null
*/
public function edit_save_data_preprocess($data, $datarecord) {
if ($data === null) {
return null;
}
return core_text::substr($data, 0, $this->field->param2);
}
/**
* Convert external data (csv file) from value to key for processing later by edit_save_data_preprocess
*
* @param string $data
* @return string|null
*/
public function convert_external_data($data) {
if (core_text::strlen($data) > $this->field->param2) {
return null;
}
return $data;
}
/**
* Return the field type and null properties.
* This will be used for validating the data submitted by a user.
*
* @return array the param type and null property
* @since Moodle 3.2
*/
public function get_field_properties() {
return array(PARAM_TEXT, NULL_NOT_ALLOWED);
}
}
@@ -0,0 +1,30 @@
<?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/>.
/**
* Strings for component 'profilefield_text', language 'en', branch 'MOODLE_20_STABLE'
*
* @package profilefield_text
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$string['pluginname'] = 'Text input';
$string['privacy:metadata:profilefield_text:userid'] = 'The ID of the user whose data is stored by the Text input user profile field';
$string['privacy:metadata:profilefield_text:fieldid'] = 'The ID of the profile field';
$string['privacy:metadata:profilefield_text:data'] = 'Text input user profile field user data';
$string['privacy:metadata:profilefield_text:dataformat'] = 'The format of Text input user profile field user data';
$string['privacy:metadata:profilefield_text:tableexplanation'] = 'Additional profile data';
@@ -0,0 +1,117 @@
<?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/>.
namespace profilefield_text;
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->dirroot.'/user/profile/lib.php');
require_once($CFG->dirroot.'/user/profile/field/text/field.class.php');
use profile_field_text;
/**
* Unit tests for the profilefield_text.
*
* @package profilefield_text
* @copyright 2022 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @covers \profilefield_text\profile_field_text
*/
class field_class_test extends \advanced_testcase {
/**
* Test that the profile text data is formatted and required filters applied
*
* @covers \profile_field_text::display_data
* @dataProvider filter_profile_field_text_provider
* @param string $input
* @param string $expected
*/
public function test_filter_display_data(string $input, string $expected): void {
$this->resetAfterTest();
$field = new profile_field_text();
$field->data = $input;
filter_set_global_state('multilang', TEXTFILTER_ON);
filter_set_global_state('emoticon', TEXTFILTER_ON);
filter_set_applies_to_strings('multilang', true);
$actual = $field->display_data();
$this->assertEquals($expected, $actual);
}
/**
* Data provider for {@see test_filter_display_data}
*
* @return string[]
*/
public function filter_profile_field_text_provider(): array {
return [
'simple_string' => ['Simple string', 'Simple string'],
'format_string' => ['HTML & is escaped', 'HTML &amp; is escaped'],
'multilang_filter' =>
['<span class="multilang" lang="en">English</span><span class="multilang" lang="fr">French</span>', 'English'],
'emoticons_filter' => ['No emoticons filter :-(', 'No emoticons filter :-(']
];
}
/**
* Test preprocess data validation
*/
public function test_edit_save_data_preprocess(): void {
$this->resetAfterTest();
$fielddata = $this->getDataGenerator()->create_custom_profile_field([
'datatype' => 'text',
'name' => 'Test',
'shortname' => 'test',
'param2' => 5, // Max length.
]);
$field = new profile_field_text(0, 0, $fielddata);
$value = $field->edit_save_data_preprocess('ABCDE', new \stdClass());
$this->assertEquals('ABCDE', $value);
// Exceed max length.
$value = $field->edit_save_data_preprocess('ABCDEF', new \stdClass());
$this->assertEquals('ABCDE', $value);
}
/**
* Test external data validation
*/
public function test_convert_external_data(): void {
$this->resetAfterTest();
$fielddata = $this->getDataGenerator()->create_custom_profile_field([
'datatype' => 'text',
'name' => 'Test',
'shortname' => 'test',
'param2' => 5, // Max length.
]);
$field = new profile_field_text(0, 0, $fielddata);
$value = $field->convert_external_data('ABCDE');
$this->assertEquals('ABCDE', $value);
// Exceed max length.
$value = $field->convert_external_data('ABCDEF');
$this->assertNull($value);
}
}
@@ -0,0 +1,300 @@
<?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/>.
/**
* Base class for unit tests for profilefield_text.
*
* @package profilefield_text
* @copyright 2018 Mihail Geshoski <mihail@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace profilefield_text\privacy;
use core_privacy\tests\provider_testcase;
use profilefield_text\privacy\provider;
use core_privacy\local\request\approved_userlist;
/**
* Unit tests for user\profile\field\text\classes\privacy\provider.php
*
* @copyright 2018 Mihail Geshoski <mihail@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider_test extends provider_testcase {
/**
* Basic setup for these tests.
*/
public function setUp(): void {
$this->resetAfterTest(true);
}
/**
* Test getting the context for the user ID related to this plugin.
*/
public function test_get_contexts_for_userid(): void {
global $DB;
// Create profile category.
$categoryid = $this->add_profile_category();
// Create profile field.
$profilefieldid = $this->add_profile_field($categoryid, 'text');
// Create a user.
$user = $this->getDataGenerator()->create_user();
$this->add_user_info_data($user->id, $profilefieldid, 'test data');
// Get the field that was created.
$userfielddata = $DB->get_records('user_info_data', array('userid' => $user->id));
// Confirm we got the right number of user field data.
$this->assertCount(1, $userfielddata);
$context = \context_user::instance($user->id);
$contextlist = provider::get_contexts_for_userid($user->id);
$this->assertEquals($context, $contextlist->current());
}
/**
* Test that data is exported correctly for this plugin.
*/
public function test_export_user_data(): void {
// Create profile category.
$categoryid = $this->add_profile_category();
// Create text profile field.
$textprofilefieldid = $this->add_profile_field($categoryid, 'text');
// Create checkbox profile field.
$checkboxprofilefieldid = $this->add_profile_field($categoryid, 'checkbox');
// Create a user.
$user = $this->getDataGenerator()->create_user();
$context = \context_user::instance($user->id);
// Add text user info data.
$this->add_user_info_data($user->id, $textprofilefieldid, 'test text');
// Add checkbox user info data.
$this->add_user_info_data($user->id, $checkboxprofilefieldid, 'test data');
$writer = \core_privacy\local\request\writer::with_context($context);
$this->assertFalse($writer->has_any_data());
$this->export_context_data_for_user($user->id, $context, 'profilefield_text');
$data = $writer->get_data([get_string('pluginname', 'profilefield_text')]);
$this->assertCount(3, (array) $data);
$this->assertEquals('Test field', $data->name);
$this->assertEquals('This is a test.', $data->description);
$this->assertEquals('test text', $data->data);
}
/**
* Test that user data is deleted using the context.
*/
public function test_delete_data_for_all_users_in_context(): void {
global $DB;
// Create profile category.
$categoryid = $this->add_profile_category();
// Create text profile field.
$textprofilefieldid = $this->add_profile_field($categoryid, 'text');
// Create checkbox profile field.
$checkboxprofilefieldid = $this->add_profile_field($categoryid, 'checkbox');
// Create a user.
$user = $this->getDataGenerator()->create_user();
$context = \context_user::instance($user->id);
// Add text user info data.
$this->add_user_info_data($user->id, $textprofilefieldid, 'test text');
// Add checkbox user info data.
$this->add_user_info_data($user->id, $checkboxprofilefieldid, 'test data');
// Check that we have two entries.
$userinfodata = $DB->get_records('user_info_data', ['userid' => $user->id]);
$this->assertCount(2, $userinfodata);
provider::delete_data_for_all_users_in_context($context);
// Check that the correct profile field has been deleted.
$userinfodata = $DB->get_records('user_info_data', ['userid' => $user->id]);
$this->assertCount(1, $userinfodata);
$this->assertNotEquals('test text', reset($userinfodata)->data);
}
/**
* Test that user data is deleted for this user.
*/
public function test_delete_data_for_user(): void {
global $DB;
// Create profile category.
$categoryid = $this->add_profile_category();
// Create text profile field.
$textprofilefieldid = $this->add_profile_field($categoryid, 'text');
// Create checkbox profile field.
$checkboxprofilefieldid = $this->add_profile_field($categoryid, 'checkbox');
// Create a user.
$user = $this->getDataGenerator()->create_user();
$context = \context_user::instance($user->id);
// Add text user info data.
$this->add_user_info_data($user->id, $textprofilefieldid, 'test text');
// Add checkbox user info data.
$this->add_user_info_data($user->id, $checkboxprofilefieldid, 'test data');
// Check that we have two entries.
$userinfodata = $DB->get_records('user_info_data', ['userid' => $user->id]);
$this->assertCount(2, $userinfodata);
$approvedlist = new \core_privacy\local\request\approved_contextlist($user, 'profilefield_text',
[$context->id]);
provider::delete_data_for_user($approvedlist);
// Check that the correct profile field has been deleted.
$userinfodata = $DB->get_records('user_info_data', ['userid' => $user->id]);
$this->assertCount(1, $userinfodata);
$this->assertNotEquals('test text', reset($userinfodata)->data);
}
/**
* Test that only users with a user context are fetched.
*/
public function test_get_users_in_context(): void {
$this->resetAfterTest();
$component = 'profilefield_text';
// Create profile category.
$categoryid = $this->add_profile_category();
// Create text profile field.
$profilefieldid = $this->add_profile_field($categoryid, 'text');
// Create a user.
$user = $this->getDataGenerator()->create_user();
$usercontext = \context_user::instance($user->id);
// The list of users should not return anything yet (related data still haven't been created).
$userlist = new \core_privacy\local\request\userlist($usercontext, $component);
provider::get_users_in_context($userlist);
$this->assertCount(0, $userlist);
$this->add_user_info_data($user->id, $profilefieldid, 'test data');
// The list of users for user context should return the user.
provider::get_users_in_context($userlist);
$this->assertCount(1, $userlist);
$expected = [$user->id];
$actual = $userlist->get_userids();
$this->assertEquals($expected, $actual);
// The list of users for system context should not return any users.
$systemcontext = \context_system::instance();
$userlist = new \core_privacy\local\request\userlist($systemcontext, $component);
provider::get_users_in_context($userlist);
$this->assertCount(0, $userlist);
}
/**
* Test that data for users in approved userlist is deleted.
*/
public function test_delete_data_for_users(): void {
$this->resetAfterTest();
$component = 'profilefield_text';
// Create profile category.
$categoryid = $this->add_profile_category();
// Create text profile field.
$profilefieldid = $this->add_profile_field($categoryid, 'text');
// Create user1.
$user1 = $this->getDataGenerator()->create_user();
$usercontext1 = \context_user::instance($user1->id);
// Create user2.
$user2 = $this->getDataGenerator()->create_user();
$usercontext2 = \context_user::instance($user2->id);
$this->add_user_info_data($user1->id, $profilefieldid, 'test data');
$this->add_user_info_data($user2->id, $profilefieldid, 'test data');
// The list of users for usercontext1 should return user1.
$userlist1 = new \core_privacy\local\request\userlist($usercontext1, $component);
provider::get_users_in_context($userlist1);
$this->assertCount(1, $userlist1);
$expected = [$user1->id];
$actual = $userlist1->get_userids();
$this->assertEquals($expected, $actual);
// The list of users for usercontext2 should return user2.
$userlist2 = new \core_privacy\local\request\userlist($usercontext2, $component);
provider::get_users_in_context($userlist2);
$this->assertCount(1, $userlist2);
$expected = [$user2->id];
$actual = $userlist2->get_userids();
$this->assertEquals($expected, $actual);
// Add userlist1 to the approved user list.
$approvedlist = new approved_userlist($usercontext1, $component, $userlist1->get_userids());
// Delete user data using delete_data_for_user for usercontext1.
provider::delete_data_for_users($approvedlist);
// Re-fetch users in usercontext1 - The user list should now be empty.
$userlist1 = new \core_privacy\local\request\userlist($usercontext1, $component);
provider::get_users_in_context($userlist1);
$this->assertCount(0, $userlist1);
// Re-fetch users in usercontext2 - The user list should not be empty (user2).
$userlist2 = new \core_privacy\local\request\userlist($usercontext2, $component);
provider::get_users_in_context($userlist2);
$this->assertCount(1, $userlist2);
// User data should be only removed in the user context.
$systemcontext = \context_system::instance();
// Add userlist2 to the approved user list in the system context.
$approvedlist = new approved_userlist($systemcontext, $component, $userlist2->get_userids());
// Delete user1 data using delete_data_for_user.
provider::delete_data_for_users($approvedlist);
// Re-fetch users in usercontext2 - The user list should not be empty (user2).
$userlist1 = new \core_privacy\local\request\userlist($usercontext2, $component);
provider::get_users_in_context($userlist1);
$this->assertCount(1, $userlist1);
}
/**
* Add dummy user info data.
*
* @param int $userid The ID of the user
* @param int $fieldid The ID of the field
* @param string $data The data
*/
private function add_user_info_data($userid, $fieldid, $data) {
global $DB;
$userinfodata = array(
'userid' => $userid,
'fieldid' => $fieldid,
'data' => $data,
'dataformat' => 0
);
$DB->insert_record('user_info_data', $userinfodata);
}
/**
* Add dummy profile category.
*
* @return int The ID of the profile category
*/
private function add_profile_category() {
$cat = $this->getDataGenerator()->create_custom_profile_field_category(['name' => 'Test category']);
return $cat->id;
}
/**
* Add dummy profile field.
*
* @param int $categoryid The ID of the profile category
* @param string $datatype The datatype of the profile field
* @return int The ID of the profile field
*/
private function add_profile_field($categoryid, $datatype) {
$data = $this->getDataGenerator()->create_custom_profile_field([
'datatype' => $datatype,
'shortname' => 'tstField',
'name' => 'Test field',
'description' => 'This is a test.',
'categoryid' => $categoryid,
]);
return $data->id;
}
}
+29
View File
@@ -0,0 +1,29 @@
<?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/>.
/**
* Text profile field version information.
*
* @package profilefield_text
* @copyright 2007 onwards Shane Elliot {@link http://pukunui.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$plugin->version = 2024042200; // The current plugin version (Date: YYYYMMDDXX).
$plugin->requires = 2024041600; // Requires this Moodle version.
$plugin->component = 'profilefield_text'; // Full name of the plugin (used for diagnostics).
@@ -0,0 +1,214 @@
<?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/>.
/**
* Privacy class for requesting user data.
*
* @package profilefield_textarea
* @copyright 2018 Mihail Geshoski <mihail@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace profilefield_textarea\privacy;
defined('MOODLE_INTERNAL') || die();
use \core_privacy\local\metadata\collection;
use \core_privacy\local\request\contextlist;
use \core_privacy\local\request\approved_contextlist;
use core_privacy\local\request\userlist;
use core_privacy\local\request\approved_userlist;
/**
* Privacy class for requesting user data.
*
* @copyright 2018 Mihail Geshoski <mihail@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider implements
\core_privacy\local\metadata\provider,
\core_privacy\local\request\core_userlist_provider,
\core_privacy\local\request\plugin\provider {
/**
* Returns meta data about this system.
*
* @param collection $collection The initialised collection to add items to.
* @return collection A listing of user data stored through this system.
*/
public static function get_metadata(collection $collection): collection {
return $collection->add_database_table('user_info_data', [
'userid' => 'privacy:metadata:profile_field_textarea:userid',
'fieldid' => 'privacy:metadata:profile_field_textarea:fieldid',
'data' => 'privacy:metadata:profile_field_textarea:data',
'dataformat' => 'privacy:metadata:profile_field_textarea:dataformat'
], 'privacy:metadata:profile_field_textarea:tableexplanation');
}
/**
* Get the list of contexts that contain user information for the specified user.
*
* @param int $userid The user to search.
* @return contextlist $contextlist The contextlist containing the list of contexts used in this plugin.
*/
public static function get_contexts_for_userid(int $userid): contextlist {
$sql = "SELECT ctx.id
FROM {user_info_data} uda
JOIN {user_info_field} uif ON uda.fieldid = uif.id
JOIN {context} ctx ON ctx.instanceid = uda.userid
AND ctx.contextlevel = :contextlevel
WHERE uda.userid = :userid
AND uif.datatype = :datatype";
$params = [
'userid' => $userid,
'contextlevel' => CONTEXT_USER,
'datatype' => 'textarea'
];
$contextlist = new contextlist();
$contextlist->add_from_sql($sql, $params);
return $contextlist;
}
/**
* Get the list of users within a specific context.
*
* @param userlist $userlist The userlist containing the list of users who have data in this context/plugin combination.
*/
public static function get_users_in_context(userlist $userlist) {
$context = $userlist->get_context();
if (!$context instanceof \context_user) {
return;
}
$sql = "SELECT uda.userid
FROM {user_info_data} uda
JOIN {user_info_field} uif
ON uda.fieldid = uif.id
WHERE uda.userid = :userid
AND uif.datatype = :datatype";
$params = [
'userid' => $context->instanceid,
'datatype' => 'textarea'
];
$userlist->add_from_sql('userid', $sql, $params);
}
/**
* Export all user data for the specified user, in the specified contexts.
*
* @param approved_contextlist $contextlist The approved contexts to export information for.
*/
public static function export_user_data(approved_contextlist $contextlist) {
$user = $contextlist->get_user();
foreach ($contextlist->get_contexts() as $context) {
// Check if the context is a user context.
if ($context->contextlevel == CONTEXT_USER && $context->instanceid == $user->id) {
$results = static::get_records($user->id);
foreach ($results as $result) {
$data = (object) [
'name' => $result->name,
'description' => $result->description,
'data' => $result->data
];
\core_privacy\local\request\writer::with_context($context)->export_data([
get_string('pluginname', 'profilefield_textarea')], $data);
}
}
}
}
/**
* Delete all user data which matches the specified context.
*
* @param context $context A user context.
*/
public static function delete_data_for_all_users_in_context(\context $context) {
// Delete data only for user context.
if ($context->contextlevel == CONTEXT_USER) {
static::delete_data($context->instanceid);
}
}
/**
* Delete multiple users within a single context.
*
* @param approved_userlist $userlist The approved context and user information to delete information for.
*/
public static function delete_data_for_users(approved_userlist $userlist) {
$context = $userlist->get_context();
if ($context instanceof \context_user) {
static::delete_data($context->instanceid);
}
}
/**
* Delete all user data for the specified user, in the specified contexts.
*
* @param approved_contextlist $contextlist The approved contexts and user information to delete information for.
*/
public static function delete_data_for_user(approved_contextlist $contextlist) {
$user = $contextlist->get_user();
foreach ($contextlist->get_contexts() as $context) {
// Check if the context is a user context.
if ($context->contextlevel == CONTEXT_USER && $context->instanceid == $user->id) {
static::delete_data($context->instanceid);
}
}
}
/**
* Delete data related to a userid.
*
* @param int $userid The user ID
*/
protected static function delete_data($userid) {
global $DB;
$params = [
'userid' => $userid,
'datatype' => 'textarea'
];
$DB->delete_records_select('user_info_data', "fieldid IN (
SELECT id FROM {user_info_field} WHERE datatype = :datatype)
AND userid = :userid", $params);
}
/**
* Get records related to this plugin and user.
*
* @param int $userid The user ID
* @return array An array of records.
*/
protected static function get_records($userid) {
global $DB;
$sql = "SELECT *
FROM {user_info_data} uda
JOIN {user_info_field} uif ON uda.fieldid = uif.id
WHERE uda.userid = :userid
AND uif.datatype = :datatype";
$params = [
'userid' => $userid,
'datatype' => 'textarea'
];
return $DB->get_records_sql($sql, $params);
}
}
@@ -0,0 +1,50 @@
<?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/>.
/**
* Textarea profile field define.
*
* @package profilefield_textarea
* @copyright 2007 onwards Shane Elliot {@link http://pukunui.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/**
* Class profile_define_textarea.
*
* @copyright 2007 onwards Shane Elliot {@link http://pukunui.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class profile_define_textarea extends profile_define_base {
/**
* Add elements for creating/editing a textarea profile field.
* @param moodleform $form
*/
public function define_form_specific($form) {
// Default data.
$form->addElement('editor', 'defaultdata', get_string('profiledefaultdata', 'admin'));
$form->setType('defaultdata', PARAM_RAW); // We have to trust person with capability to edit this default description.
}
/**
* Returns an array of editors used when defining this type of profile field.
* @return array
*/
public function define_editors() {
return array('defaultdata');
}
}
@@ -0,0 +1,96 @@
<?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/>.
/**
* Textarea profile field define.
*
* @package profilefield_textarea
* @copyright 2007 onwards Shane Elliot {@link http://pukunui.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/**
* Class profile_field_textarea.
*
* @copyright 2007 onwards Shane Elliot {@link http://pukunui.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class profile_field_textarea extends profile_field_base {
/**
* Adds elements for this field type to the edit form.
* @param moodleform $mform
*/
public function edit_field_add($mform) {
// Create the form field.
$mform->addElement('editor', $this->inputname, format_string($this->field->name), null, null);
$mform->setType($this->inputname, PARAM_RAW); // We MUST clean this before display!
}
/**
* Overwrite base class method, data in this field type is potentially too large to be included in the user object.
* @return bool
*/
public function is_user_object_data() {
return false;
}
/**
* Process incoming data for the field.
* @param stdClass $data
* @param stdClass $datarecord
* @return mixed|stdClass
*/
public function edit_save_data_preprocess($data, $datarecord) {
if (is_array($data)) {
$datarecord->dataformat = $data['format'];
$data = $data['text'];
}
return $data;
}
/**
* Load user data for this profile field, ready for editing.
* @param stdClass $user
*/
public function edit_load_user_data($user) {
if ($this->data !== null) {
$this->data = clean_text($this->data, $this->dataformat);
$user->{$this->inputname} = array('text' => $this->data, 'format' => $this->dataformat);
}
}
/**
* Display the data for this field
* @return string
*/
public function display_data() {
return format_text($this->data, $this->dataformat, array('overflowdiv' => true));
}
/**
* Return the field type and null properties.
* This will be used for validating the data submitted by a user.
*
* @return array the param type and null property
* @since Moodle 3.2
*/
public function get_field_properties() {
return array(PARAM_RAW, NULL_NOT_ALLOWED);
}
}
@@ -0,0 +1,30 @@
<?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/>.
/**
* Strings for component 'profilefield_textarea', language 'en', branch 'MOODLE_20_STABLE'
*
* @package profilefield_textarea
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$string['pluginname'] = 'Text area';
$string['privacy:metadata:profile_field_textarea:userid'] = 'The ID of the user whose data is stored by the Text area user profile field';
$string['privacy:metadata:profile_field_textarea:fieldid'] = 'The ID of the profile field';
$string['privacy:metadata:profile_field_textarea:data'] = 'Text area user profile field user data';
$string['privacy:metadata:profile_field_textarea:dataformat'] = 'The format of Text area user profile field user data';
$string['privacy:metadata:profile_field_textarea:tableexplanation'] = 'Additional profile data';
@@ -0,0 +1,301 @@
<?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/>.
/**
* Base class for unit tests for profilefield_textarea.
*
* @package profilefield_textarea
* @copyright 2018 Mihail Geshoski <mihail@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace profilefield_textarea\privacy;
defined('MOODLE_INTERNAL') || die();
use core_privacy\tests\provider_testcase;
use profilefield_textarea\privacy\provider;
use core_privacy\local\request\approved_userlist;
/**
* Unit tests for user\profile\field\textarea\classes\privacy\provider.php
*
* @copyright 2018 Mihail Geshoski <mihail@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider_test extends provider_testcase {
/**
* Basic setup for these tests.
*/
public function setUp(): void {
$this->resetAfterTest(true);
}
/**
* Test getting the context for the user ID related to this plugin.
*/
public function test_get_contexts_for_userid(): void {
global $DB;
// Create profile category.
$categoryid = $this->add_profile_category();
// Create profile field.
$profilefieldid = $this->add_profile_field($categoryid, 'textarea');
// Create a user.
$user = $this->getDataGenerator()->create_user();
$this->add_user_info_data($user->id, $profilefieldid, 'test data');
// Get the field that was created.
$userfielddata = $DB->get_records('user_info_data', array('userid' => $user->id));
// Confirm we got the right number of user field data.
$this->assertCount(1, $userfielddata);
$context = \context_user::instance($user->id);
$contextlist = provider::get_contexts_for_userid($user->id);
$this->assertEquals($context, $contextlist->current());
}
/**
* Test that data is exported correctly for this plugin.
*/
public function test_export_user_data(): void {
// Create profile category.
$categoryid = $this->add_profile_category();
// Create textarea profile field.
$textareaprofilefieldid = $this->add_profile_field($categoryid, 'textarea');
// Create checkbox profile field.
$checkboxprofilefieldid = $this->add_profile_field($categoryid, 'checkbox');
// Create a user.
$user = $this->getDataGenerator()->create_user();
$context = \context_user::instance($user->id);
// Add textarea user info data.
$this->add_user_info_data($user->id, $textareaprofilefieldid, 'test textarea');
// Add checkbox user info data.
$this->add_user_info_data($user->id, $checkboxprofilefieldid, 'test data');
$writer = \core_privacy\local\request\writer::with_context($context);
$this->assertFalse($writer->has_any_data());
$this->export_context_data_for_user($user->id, $context, 'profilefield_textarea');
$data = $writer->get_data([get_string('pluginname', 'profilefield_textarea')]);
$this->assertCount(3, (array) $data);
$this->assertEquals('Test field', $data->name);
$this->assertEquals('This is a test.', $data->description);
$this->assertEquals('test textarea', $data->data);
}
/**
* Test that user data is deleted using the context.
*/
public function test_delete_data_for_all_users_in_context(): void {
global $DB;
// Create profile category.
$categoryid = $this->add_profile_category();
// Create textarea profile field.
$textareaprofilefieldid = $this->add_profile_field($categoryid, 'textarea');
// Create checkbox profile field.
$checkboxprofilefieldid = $this->add_profile_field($categoryid, 'checkbox');
// Create a user.
$user = $this->getDataGenerator()->create_user();
$context = \context_user::instance($user->id);
// Add textarea user info data.
$this->add_user_info_data($user->id, $textareaprofilefieldid, 'test textarea');
// Add checkbox user info data.
$this->add_user_info_data($user->id, $checkboxprofilefieldid, 'test data');
// Check that we have two entries.
$userinfodata = $DB->get_records('user_info_data', ['userid' => $user->id]);
$this->assertCount(2, $userinfodata);
provider::delete_data_for_all_users_in_context($context);
// Check that the correct profile field has been deleted.
$userinfodata = $DB->get_records('user_info_data', ['userid' => $user->id]);
$this->assertCount(1, $userinfodata);
$this->assertNotEquals('test textarea', reset($userinfodata)->data);
}
/**
* Test that user data is deleted for this user.
*/
public function test_delete_data_for_user(): void {
global $DB;
// Create profile category.
$categoryid = $this->add_profile_category();
// Create textarea profile field.
$textareaprofilefieldid = $this->add_profile_field($categoryid, 'textarea');
// Create checkbox profile field.
$checkboxprofilefieldid = $this->add_profile_field($categoryid, 'checkbox');
// Create a user.
$user = $this->getDataGenerator()->create_user();
$context = \context_user::instance($user->id);
// Add textarea user info data.
$this->add_user_info_data($user->id, $textareaprofilefieldid, 'test textarea');
// Add checkbox user info data.
$this->add_user_info_data($user->id, $checkboxprofilefieldid, 'test data');
// Check that we have two entries.
$userinfodata = $DB->get_records('user_info_data', ['userid' => $user->id]);
$this->assertCount(2, $userinfodata);
$approvedlist = new \core_privacy\local\request\approved_contextlist($user, 'profilefield_textarea',
[$context->id]);
provider::delete_data_for_user($approvedlist);
// Check that the correct profile field has been deleted.
$userinfodata = $DB->get_records('user_info_data', ['userid' => $user->id]);
$this->assertCount(1, $userinfodata);
$this->assertNotEquals('test textarea', reset($userinfodata)->data);
}
/**
* Test that only users with a user context are fetched.
*/
public function test_get_users_in_context(): void {
$this->resetAfterTest();
$component = 'profilefield_textarea';
// Create profile category.
$categoryid = $this->add_profile_category();
// Create profile field.
$profilefieldid = $this->add_profile_field($categoryid, 'textarea');
// Create a user.
$user = $this->getDataGenerator()->create_user();
$usercontext = \context_user::instance($user->id);
// The list of users should not return anything yet (related data still haven't been created).
$userlist = new \core_privacy\local\request\userlist($usercontext, $component);
provider::get_users_in_context($userlist);
$this->assertCount(0, $userlist);
$this->add_user_info_data($user->id, $profilefieldid, 'test data');
// The list of users for user context should return the user.
provider::get_users_in_context($userlist);
$this->assertCount(1, $userlist);
$expected = [$user->id];
$actual = $userlist->get_userids();
$this->assertEquals($expected, $actual);
// The list of users for system context should not return any users.
$systemcontext = \context_system::instance();
$userlist = new \core_privacy\local\request\userlist($systemcontext, $component);
provider::get_users_in_context($userlist);
$this->assertCount(0, $userlist);
}
/**
* Test that data for users in approved userlist is deleted.
*/
public function test_delete_data_for_users(): void {
$this->resetAfterTest();
$component = 'profilefield_textarea';
// Create profile category.
$categoryid = $this->add_profile_category();
// Create profile field.
$profilefieldid = $this->add_profile_field($categoryid, 'textarea');
// Create user1.
$user1 = $this->getDataGenerator()->create_user();
$usercontext1 = \context_user::instance($user1->id);
// Create user2.
$user2 = $this->getDataGenerator()->create_user();
$usercontext2 = \context_user::instance($user2->id);
$this->add_user_info_data($user1->id, $profilefieldid, 'test data');
$this->add_user_info_data($user2->id, $profilefieldid, 'test data');
// The list of users for usercontext1 should return user1.
$userlist1 = new \core_privacy\local\request\userlist($usercontext1, $component);
provider::get_users_in_context($userlist1);
$this->assertCount(1, $userlist1);
$expected = [$user1->id];
$actual = $userlist1->get_userids();
$this->assertEquals($expected, $actual);
// The list of users for usercontext2 should return user2.
$userlist2 = new \core_privacy\local\request\userlist($usercontext2, $component);
provider::get_users_in_context($userlist2);
$this->assertCount(1, $userlist2);
$expected = [$user2->id];
$actual = $userlist2->get_userids();
$this->assertEquals($expected, $actual);
// Add userlist1 to the approved user list.
$approvedlist = new approved_userlist($usercontext1, $component, $userlist1->get_userids());
// Delete user data using delete_data_for_user for usercontext1.
provider::delete_data_for_users($approvedlist);
// Re-fetch users in usercontext1 - The user list should now be empty.
$userlist1 = new \core_privacy\local\request\userlist($usercontext1, $component);
provider::get_users_in_context($userlist1);
$this->assertCount(0, $userlist1);
// Re-fetch users in usercontext2 - The user list should not be empty (user2).
$userlist2 = new \core_privacy\local\request\userlist($usercontext2, $component);
provider::get_users_in_context($userlist2);
$this->assertCount(1, $userlist2);
// User data should be only removed in the user context.
$systemcontext = \context_system::instance();
// Add userlist2 to the approved user list in the system context.
$approvedlist = new approved_userlist($systemcontext, $component, $userlist2->get_userids());
// Delete user1 data using delete_data_for_user.
provider::delete_data_for_users($approvedlist);
// Re-fetch users in usercontext2 - The user list should not be empty (user2).
$userlist1 = new \core_privacy\local\request\userlist($usercontext2, $component);
provider::get_users_in_context($userlist1);
$this->assertCount(1, $userlist1);
}
/**
* Add dummy user info data.
*
* @param int $userid The ID of the user
* @param int $fieldid The ID of the field
* @param string $data The data
*/
private function add_user_info_data($userid, $fieldid, $data) {
global $DB;
$userinfodata = array(
'userid' => $userid,
'fieldid' => $fieldid,
'data' => $data,
'dataformat' => 0
);
$DB->insert_record('user_info_data', $userinfodata);
}
/**
* Add dummy profile category.
*
* @return int The ID of the profile category
*/
private function add_profile_category() {
$cat = $this->getDataGenerator()->create_custom_profile_field_category(['name' => 'Test category']);
return $cat->id;
}
/**
* Add dummy profile field.
*
* @param int $categoryid The ID of the profile category
* @param string $datatype The datatype of the profile field
* @return int The ID of the profile field
*/
private function add_profile_field($categoryid, $datatype) {
$data = $this->getDataGenerator()->create_custom_profile_field([
'datatype' => $datatype,
'shortname' => 'tstField',
'name' => 'Test field',
'description' => 'This is a test.',
'categoryid' => $categoryid,
]);
return $data->id;
}
}
+29
View File
@@ -0,0 +1,29 @@
<?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/>.
/**
* Version information for the textarea profile field.
*
* @package profilefield_textarea
* @copyright 2007 onwards Shane Elliot {@link http://pukunui.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$plugin->version = 2024042200; // The current plugin version (Date: YYYYMMDDXX).
$plugin->requires = 2024041600; // Requires this Moodle version.
$plugin->component = 'profilefield_textarea'; // Full name of the plugin (used for diagnostics)
+6
View File
@@ -0,0 +1,6 @@
This files describes API changes in /user/profile/field/* - user profile fields,
information provided here is intended especially for developers.
=== 3.4 ===
* profile_field_base::__construct() now takes three arguments instead of two. Update your plugins if required.
+166
View File
@@ -0,0 +1,166 @@
<?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/>.
/**
* Manage user profile fields.
* @package core_user
* @copyright 2007 onwards Shane Elliot {@link http://pukunui.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require('../../config.php');
require_once($CFG->libdir.'/adminlib.php');
require_once($CFG->dirroot.'/user/profile/lib.php');
require_once($CFG->dirroot.'/user/profile/definelib.php');
admin_externalpage_setup('profilefields');
$action = optional_param('action', '', PARAM_ALPHA);
$redirect = $CFG->wwwroot.'/user/profile/index.php';
$strdefaultcategory = get_string('profiledefaultcategory', 'admin');
$strcreatefield = get_string('profilecreatefield', 'admin');
// Do we have any actions to perform before printing the header.
switch ($action) {
case 'movecategory':
$id = required_param('id', PARAM_INT);
$dir = required_param('dir', PARAM_ALPHA);
if (confirm_sesskey()) {
profile_move_category($id, $dir);
}
redirect($redirect);
break;
case 'movefield':
$id = required_param('id', PARAM_INT);
$dir = required_param('dir', PARAM_ALPHA);
if (confirm_sesskey()) {
profile_move_field($id, $dir);
}
redirect($redirect);
break;
case 'deletecategory':
$id = required_param('id', PARAM_INT);
if (confirm_sesskey()) {
profile_delete_category($id);
}
redirect($redirect, get_string('deleted'));
break;
case 'deletefield':
$id = required_param('id', PARAM_INT);
$confirm = optional_param('confirm', 0, PARAM_BOOL);
// If no userdata for profile than don't show confirmation.
$datacount = $DB->count_records('user_info_data', array('fieldid' => $id));
if (((data_submitted() and $confirm) or ($datacount === 0)) and confirm_sesskey()) {
profile_delete_field($id);
redirect($redirect, get_string('deleted'));
}
// Ask for confirmation, as there is user data available for field.
$fieldname = $DB->get_field('user_info_field', 'name', array('id' => $id));
$optionsyes = array ('id' => $id, 'confirm' => 1, 'action' => 'deletefield', 'sesskey' => sesskey());
$strheading = get_string('profiledeletefield', 'admin', format_string($fieldname));
$PAGE->navbar->add($strheading);
echo $OUTPUT->header();
echo $OUTPUT->heading($strheading);
$formcontinue = new single_button(new moodle_url($redirect, $optionsyes), get_string('yes'), 'post');
$formcancel = new single_button(new moodle_url($redirect), get_string('no'), 'get');
echo $OUTPUT->confirm(get_string('profileconfirmfielddeletion', 'admin', $datacount), $formcontinue, $formcancel);
echo $OUTPUT->footer();
die;
break;
default:
// Normal form.
}
// Show all categories.
$categories = $DB->get_records('user_info_category', null, 'sortorder ASC');
// Check that we have at least one category defined.
if (empty($categories)) {
$defaultcategory = new stdClass();
$defaultcategory->name = $strdefaultcategory;
$defaultcategory->sortorder = 1;
$DB->insert_record('user_info_category', $defaultcategory);
redirect($redirect);
}
// Print the header.
echo $OUTPUT->header();
echo $OUTPUT->heading(get_string('profilefields', 'admin'));
$outputcategories = [];
$options = profile_list_datatypes();
foreach ($categories as $category) {
// Category fields.
$outputfields = [];
if ($fields = $DB->get_records('user_info_field', array('categoryid' => $category->id), 'sortorder ASC')) {
foreach ($fields as $field) {
$fieldname = format_string($field->name);
$component = 'profilefield_' . $field->datatype;
$classname = "\\$component\\helper";
if (class_exists($classname) && method_exists($classname, 'get_fieldname')) {
$fieldname = $classname::get_fieldname($field->name);
}
$outputfields[] = [
'id' => $field->id,
'shortname' => $field->shortname,
'datatype' => $field->datatype,
'name' => $fieldname,
'isfirst' => !count($outputfields),
'islast' => count($outputfields) == count($fields) - 1,
];
}
}
// Add new field menu.
$menu = new \action_menu();
$menu->set_menu_trigger($strcreatefield);
foreach ($options as $type => $fieldname) {
$action = new \action_menu_link_secondary(new \moodle_url('#'), null, $fieldname,
['data-action' => 'createfield', 'data-categoryid' => $category->id, 'data-datatype' => $type,
'data-datatypename' => $fieldname]);
$menu->add($action);
}
$menu->attributes['class'] .= ' float-left mr-1';
// Add category information to the template.
$outputcategories[] = [
'id' => $category->id,
'name' => format_string($category->name),
'fields' => $outputfields,
'hasfields' => count($outputfields),
'isfirst' => !count($outputcategories),
'islast' => count($outputcategories) == count($categories) - 1,
'candelete' => count($categories) > 1,
'addfieldmenu' => $menu->export_for_template($OUTPUT),
];
}
echo $OUTPUT->render_from_template('core_user/edit_profile_fields', [
'categories' => $outputcategories,
'sesskey' => sesskey(),
'baseurl' => (new moodle_url('/user/profile/index.php'))->out(false)
]);
echo $OUTPUT->footer();
+1017
View File
File diff suppressed because it is too large Load Diff