.
/**
* @package mod_data
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
use mod_data\manager;
use mod_data\preset;
defined('MOODLE_INTERNAL') || die();
// Some constants
define ('DATA_MAX_ENTRIES', 50);
define ('DATA_PERPAGE_SINGLE', 1);
define ('DATA_FIRSTNAME', -1);
define ('DATA_LASTNAME', -2);
define ('DATA_APPROVED', -3);
define ('DATA_TIMEADDED', 0);
define ('DATA_TIMEMODIFIED', -4);
define ('DATA_TAGS', -5);
define ('DATA_CAP_EXPORT', 'mod/data:viewalluserpresets');
// Users having assigned the default role "Non-editing teacher" can export database records
// Using the mod/data capability "viewalluserpresets" existing in Moodle 1.9.x.
// In Moodle >= 2, new roles may be introduced and used instead.
define('DATA_PRESET_COMPONENT', 'mod_data');
define('DATA_PRESET_FILEAREA', 'site_presets');
define('DATA_PRESET_CONTEXT', SYSCONTEXTID);
define('DATA_EVENT_TYPE_OPEN', 'open');
define('DATA_EVENT_TYPE_CLOSE', 'close');
require_once(__DIR__ . '/deprecatedlib.php');
/**
* @package mod_data
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class data_field_base { // Base class for Database Field Types (see field/*/field.class.php)
/** @var string Subclasses must override the type with their name */
var $type = 'unknown';
/** @var object The database object that this field belongs to */
var $data = NULL;
/** @var object The field object itself, if we know it */
var $field = NULL;
/** @var int Width of the icon for this fieldtype */
var $iconwidth = 16;
/** @var int Width of the icon for this fieldtype */
var $iconheight = 16;
/** @var object course module or cmifno */
var $cm;
/** @var object activity context */
var $context;
/** @var priority for globalsearch indexing */
protected static $priority = self::NO_PRIORITY;
/** priority value for invalid fields regarding indexing */
const NO_PRIORITY = 0;
/** priority value for minimum priority */
const MIN_PRIORITY = 1;
/** priority value for low priority */
const LOW_PRIORITY = 2;
/** priority value for high priority */
const HIGH_PRIORITY = 3;
/** priority value for maximum priority */
const MAX_PRIORITY = 4;
/** @var bool whether the field is used in preview mode. */
protected $preview = false;
/**
* Constructor function
*
* @global object
* @uses CONTEXT_MODULE
* @param int $field
* @param int $data
* @param int $cm
*/
function __construct($field=0, $data=0, $cm=0) { // Field or data or both, each can be id or object
global $DB;
if (empty($field) && empty($data)) {
throw new \moodle_exception('missingfield', 'data');
}
if (!empty($field)) {
if (is_object($field)) {
$this->field = $field; // Programmer knows what they are doing, we hope
} else if (!$this->field = $DB->get_record('data_fields', array('id'=>$field))) {
throw new \moodle_exception('invalidfieldid', 'data');
}
if (empty($data)) {
if (!$this->data = $DB->get_record('data', array('id'=>$this->field->dataid))) {
throw new \moodle_exception('invalidid', 'data');
}
}
}
if (empty($this->data)) { // We need to define this properly
if (!empty($data)) {
if (is_object($data)) {
$this->data = $data; // Programmer knows what they are doing, we hope
} else if (!$this->data = $DB->get_record('data', array('id'=>$data))) {
throw new \moodle_exception('invalidid', 'data');
}
} else { // No way to define it!
throw new \moodle_exception('missingdata', 'data');
}
}
if ($cm) {
$this->cm = $cm;
} else {
$this->cm = get_coursemodule_from_instance('data', $this->data->id);
}
if (empty($this->field)) { // We need to define some default values
$this->define_default_field();
}
$this->context = context_module::instance($this->cm->id);
}
/**
* Return the field type name.
*
* @return string the filed type.
*/
public function get_name(): string {
return $this->field->name;
}
/**
* Return if the field type supports preview.
*
* Fields without a preview cannot be displayed in the preset preview.
*
* @return bool if the plugin supports preview.
*/
public function supports_preview(): bool {
return false;
}
/**
* Generate a fake data_content for this field to be used in preset previews.
*
* Data plugins must override this method and support_preview in order to enable
* preset preview for this field.
*
* @param int $recordid the fake record id
* @return stdClass the fake record
*/
public function get_data_content_preview(int $recordid): stdClass {
$message = get_string('nopreviewavailable', 'mod_data', $this->field->name);
return (object)[
'id' => 0,
'fieldid' => $this->field->id,
'recordid' => $recordid,
'content' => "$message",
'content1' => null,
'content2' => null,
'content3' => null,
'content4' => null,
];
}
/**
* Set the field to preview mode.
*
* @param bool $preview the new preview value
*/
public function set_preview(bool $preview) {
$this->preview = $preview;
}
/**
* Get the field preview value.
*
* @return bool
*/
public function get_preview(): bool {
return $this->preview;
}
/**
* This field just sets up a default field object
*
* @return bool
*/
function define_default_field() {
global $OUTPUT;
if (empty($this->data->id)) {
echo $OUTPUT->notification('Programmer error: dataid not defined in field class');
}
$this->field = new stdClass();
$this->field->id = 0;
$this->field->dataid = $this->data->id;
$this->field->type = $this->type;
$this->field->param1 = '';
$this->field->param2 = '';
$this->field->param3 = '';
$this->field->name = '';
$this->field->description = '';
$this->field->required = false;
return true;
}
/**
* Set up the field object according to data in an object. Now is the time to clean it!
*
* @return bool
*/
function define_field($data) {
$this->field->type = $this->type;
$this->field->dataid = $this->data->id;
$this->field->name = trim($data->name);
$this->field->description = trim($data->description);
$this->field->required = !empty($data->required) ? 1 : 0;
if (isset($data->param1)) {
$this->field->param1 = trim($data->param1);
}
if (isset($data->param2)) {
$this->field->param2 = trim($data->param2);
}
if (isset($data->param3)) {
$this->field->param3 = trim($data->param3);
}
if (isset($data->param4)) {
$this->field->param4 = trim($data->param4);
}
if (isset($data->param5)) {
$this->field->param5 = trim($data->param5);
}
return true;
}
/**
* Insert a new field in the database
* We assume the field object is already defined as $this->field
*
* @global object
* @return bool
*/
function insert_field() {
global $DB, $OUTPUT;
if (empty($this->field)) {
echo $OUTPUT->notification('Programmer error: Field has not been defined yet! See define_field()');
return false;
}
$this->field->id = $DB->insert_record('data_fields',$this->field);
// Trigger an event for creating this field.
$event = \mod_data\event\field_created::create(array(
'objectid' => $this->field->id,
'context' => $this->context,
'other' => array(
'fieldname' => $this->field->name,
'dataid' => $this->data->id
)
));
$event->trigger();
return true;
}
/**
* Update a field in the database
*
* @global object
* @return bool
*/
function update_field() {
global $DB;
$DB->update_record('data_fields', $this->field);
// Trigger an event for updating this field.
$event = \mod_data\event\field_updated::create(array(
'objectid' => $this->field->id,
'context' => $this->context,
'other' => array(
'fieldname' => $this->field->name,
'dataid' => $this->data->id
)
));
$event->trigger();
return true;
}
/**
* Delete a field completely
*
* @global object
* @return bool
*/
function delete_field() {
global $DB;
if (!empty($this->field->id)) {
$manager = manager::create_from_instance($this->data);
// Get the field before we delete it.
$field = $DB->get_record('data_fields', array('id' => $this->field->id));
$this->delete_content();
$DB->delete_records('data_fields', array('id'=>$this->field->id));
// Trigger an event for deleting this field.
$event = \mod_data\event\field_deleted::create(array(
'objectid' => $this->field->id,
'context' => $this->context,
'other' => array(
'fieldname' => $this->field->name,
'dataid' => $this->data->id
)
));
if (!$manager->has_fields() && $manager->has_records()) {
$DB->delete_records('data_records', ['dataid' => $this->data->id]);
}
$event->add_record_snapshot('data_fields', $field);
$event->trigger();
}
return true;
}
/**
* Print the relevant form element in the ADD template for this field
*
* @global object
* @param int $recordid
* @return string
*/
function display_add_field($recordid=0, $formdata=null) {
global $DB, $OUTPUT;
if ($formdata) {
$fieldname = 'field_' . $this->field->id;
$content = $formdata->$fieldname;
} else if ($recordid) {
$content = $DB->get_field('data_content', 'content', array('fieldid'=>$this->field->id, 'recordid'=>$recordid));
} else {
$content = '';
}
// beware get_field returns false for new, empty records MDL-18567
if ($content===false) {
$content='';
}
$str = '
';
return $str;
}
/**
* Print the relevant form element to define the attributes for this field
* viewable by teachers only.
*
* @global object
* @global object
* @return void Output is echo'd
*/
function display_edit_field() {
global $CFG, $DB, $OUTPUT;
if (empty($this->field)) { // No field has been defined yet, try and make one
$this->define_default_field();
}
// Throw an exception if field type doen't exist. Anyway user should never access to edit a field with an unknown fieldtype.
if ($this->type === 'unknown') {
throw new \moodle_exception(get_string('missingfieldtype', 'data', (object)['name' => $this->field->name]));
}
echo $OUTPUT->box_start('generalbox boxaligncenter boxwidthwide');
echo '';
echo $OUTPUT->box_end();
}
/**
* Validates params of fieldinput data. Overwrite to validate fieldtype specific data.
*
* You are expected to return an array like ['paramname' => 'Error message for paramname param'] if there is an error,
* return an empty array if everything is fine.
*
* @param stdClass $fieldinput The field input data to check
* @return array $errors if empty validation was fine, otherwise contains one or more error messages
*/
public function validate(stdClass $fieldinput): array {
return [];
}
/**
* Return the data_content of the field, or generate it if it is in preview mode.
*
* @param int $recordid the record id
* @return stdClass|bool the record data or false if none
*/
protected function get_data_content(int $recordid) {
global $DB;
if ($this->preview) {
return $this->get_data_content_preview($recordid);
}
return $DB->get_record(
'data_content',
['fieldid' => $this->field->id, 'recordid' => $recordid]
);
}
/**
* Display the content of the field in browse mode
*
* @global object
* @param int $recordid
* @param object $template
* @return bool|string
*/
function display_browse_field($recordid, $template) {
global $DB;
$content = $this->get_data_content($recordid);
if (!$content || !isset($content->content)) {
return '';
}
$options = new stdClass();
if ($this->field->param1 == '1') {
// We are autolinking this field, so disable linking within us.
$options->filter = false;
}
$options->para = false;
$str = format_text($content->content, $content->content1, $options);
return $str;
}
/**
* Update the content of one data field in the data_content table
* @global object
* @param int $recordid
* @param mixed $value
* @param string $name
* @return bool
*/
function update_content($recordid, $value, $name=''){
global $DB;
$content = new stdClass();
$content->fieldid = $this->field->id;
$content->recordid = $recordid;
$content->content = clean_param($value, PARAM_NOTAGS);
if ($oldcontent = $DB->get_record('data_content', array('fieldid'=>$this->field->id, 'recordid'=>$recordid))) {
$content->id = $oldcontent->id;
return $DB->update_record('data_content', $content);
} else {
return $DB->insert_record('data_content', $content);
}
}
/**
* Delete all content associated with the field
*
* @global object
* @param int $recordid
* @return bool
*/
function delete_content($recordid=0) {
global $DB;
if ($recordid) {
$conditions = array('fieldid'=>$this->field->id, 'recordid'=>$recordid);
} else {
$conditions = array('fieldid'=>$this->field->id);
}
$rs = $DB->get_recordset('data_content', $conditions);
if ($rs->valid()) {
$fs = get_file_storage();
foreach ($rs as $content) {
$fs->delete_area_files($this->context->id, 'mod_data', 'content', $content->id);
}
}
$rs->close();
return $DB->delete_records('data_content', $conditions);
}
/**
* Check if a field from an add form is empty
*
* @param mixed $value
* @param mixed $name
* @return bool
*/
function notemptyfield($value, $name) {
return !empty($value);
}
/**
* Just in case a field needs to print something before the whole form
*/
function print_before_form() {
}
/**
* Just in case a field needs to print something after the whole form
*/
function print_after_form() {
}
/**
* Returns the sortable field for the content. By default, it's just content
* but for some plugins, it could be content 1 - content4
*
* @return string
*/
function get_sort_field() {
return 'content';
}
/**
* Returns the SQL needed to refer to the column. Some fields may need to CAST() etc.
*
* @param string $fieldname
* @return string $fieldname
*/
function get_sort_sql($fieldname) {
return $fieldname;
}
/**
* Returns the name/type of the field
*
* @return string
*/
function name() {
return get_string('fieldtypelabel', "datafield_$this->type");
}
/**
* Prints the respective type icon
*
* @global object
* @return string
*/
function image() {
global $OUTPUT;
return $OUTPUT->pix_icon('field/' . $this->type, $this->type, 'data');
}
/**
* Per default, it is assumed that fields support text exporting.
* Override this (return false) on fields not supporting text exporting.
*
* @return bool true
*/
function text_export_supported() {
return true;
}
/**
* Per default, it is assumed that fields do not support file exporting. Override this (return true)
* on fields supporting file export. You will also have to implement export_file_value().
*
* @return bool true if field will export a file, false otherwise
*/
public function file_export_supported(): bool {
return false;
}
/**
* Per default, does not return a file (just null).
* Override this in fields class, if you want your field to export a file content.
* In case you are exporting a file value, export_text_value() should return the corresponding file name.
*
* @param stdClass $record
* @return null|string the file content as string or null, if no file content is being provided
*/
public function export_file_value(stdClass $record): null|string {
return null;
}
/**
* Per default, a field does not support the import of files.
*
* A field type can overwrite this function and return true. In this case it also has to implement the function
* import_file_value().
*
* @return false means file imports are not supported
*/
public function file_import_supported(): bool {
return false;
}
/**
* Returns a stored_file object for exporting a file of a given record.
*
* @param int $contentid content id
* @param string $filecontent the content of the file as string
* @param string $filename the filename the file should have
*/
public function import_file_value(int $contentid, string $filecontent, string $filename): void {
return;
}
/**
* Per default, return the record's text value only from the "content" field.
* Override this in fields class if necessary.
*
* @param stdClass $record
* @return string
*/
public function export_text_value(stdClass $record) {
if ($this->text_export_supported()) {
return $record->content;
}
return '';
}
/**
* @param string $relativepath
* @return bool false
*/
function file_ok($relativepath) {
return false;
}
/**
* Returns the priority for being indexed by globalsearch
*
* @return int
*/
public static function get_priority() {
return static::$priority;
}
/**
* Returns the presentable string value for a field content.
*
* The returned string should be plain text.
*
* @param stdClass $content
* @return string
*/
public static function get_content_value($content) {
return trim($content->content, "\r\n ");
}
/**
* Return the plugin configs for external functions,
* in some cases the configs will need formatting or be returned only if the current user has some capabilities enabled.
*
* @return array the list of config parameters
* @since Moodle 3.3
*/
public function get_config_for_external() {
// Return all the field configs to null (maybe there is a private key for a service or something similar there).
$configs = [];
for ($i = 1; $i <= 10; $i++) {
$configs["param$i"] = null;
}
return $configs;
}
/**
* Function to let field define their parameters.
*
* This method that should be overridden by the datafield plugins
* when they need to define their data.
*
* @return array
*/
protected function get_field_params(): array {
// Name and description of the field.
$data = [
'name' => $this->field->name,
'description' => $this->field->description,
];
// Whether the field is required.
if (isset($this->field->required)) {
$data['required'] = $this->field->required;
}
// Add all the field parameters.
for ($i = 1; $i <= 10; $i++) {
if (isset($this->field->{"param$i"})) {
$data["param$i"] = $this->field->{"param$i"};
}
}
return $data;
}
}
/**
* Given a template and a dataid, generate a default case template
*
* @param stdClass $data the mod_data record.
* @param string $template the template name
* @param int $recordid the entry record
* @param bool $form print a form instead of data
* @param bool $update if the function update the $data object or not
* @return string the template content or an empty string if no content is available (for instance, when database has no fields).
*/
function data_generate_default_template(&$data, $template, $recordid = 0, $form = false, $update = true) {
global $DB;
if (!$data || !$template) {
return '';
}
// These templates are empty by default (they have no content).
$emptytemplates = [
'csstemplate',
'jstemplate',
'listtemplateheader',
'listtemplatefooter',
'rsstitletemplate',
];
if (in_array($template, $emptytemplates)) {
return '';
}
$manager = manager::create_from_instance($data);
if (empty($manager->get_fields())) {
// No template will be returned if there are no fields.
return '';
}
$templateclass = \mod_data\template::create_default_template($manager, $template, $form);
$templatecontent = $templateclass->get_template_content();
if ($update) {
// Update the database instance.
$newdata = new stdClass();
$newdata->id = $data->id;
$newdata->{$template} = $templatecontent;
$DB->update_record('data', $newdata);
$data->{$template} = $templatecontent;
}
return $templatecontent;
}
/**
* Build the form elements to manage tags for a record.
*
* @param int|bool $recordid
* @param string[] $selected raw tag names
* @return string
*/
function data_generate_tag_form($recordid = false, $selected = []) {
global $CFG, $DB, $OUTPUT, $PAGE;
$tagtypestoshow = \core_tag_area::get_showstandard('mod_data', 'data_records');
$showstandard = ($tagtypestoshow != core_tag_tag::HIDE_STANDARD);
$typenewtags = ($tagtypestoshow != core_tag_tag::STANDARD_ONLY);
$str = html_writer::start_tag('div', array('class' => 'datatagcontrol'));
$namefield = empty($CFG->keeptagnamecase) ? 'name' : 'rawname';
$tagcollid = \core_tag_area::get_collection('mod_data', 'data_records');
$tags = [];
$selectedtags = [];
if ($showstandard) {
$tags += $DB->get_records_menu('tag', array('isstandard' => 1, 'tagcollid' => $tagcollid),
$namefield, 'id,' . $namefield . ' as fieldname');
}
if ($recordid) {
$selectedtags += core_tag_tag::get_item_tags_array('mod_data', 'data_records', $recordid);
}
if (!empty($selected)) {
list($sql, $params) = $DB->get_in_or_equal($selected, SQL_PARAMS_NAMED);
$params['tagcollid'] = $tagcollid;
$sql = "SELECT id, $namefield FROM {tag} WHERE tagcollid = :tagcollid AND rawname $sql";
$selectedtags += $DB->get_records_sql_menu($sql, $params);
}
$tags += $selectedtags;
$str .= '';
if (has_capability('moodle/tag:manage', context_system::instance()) && $showstandard) {
$url = new moodle_url('/tag/manage.php', array('tc' => core_tag_area::get_collection('mod_data',
'data_records')));
$str .= ' ' . $OUTPUT->action_link($url, get_string('managestandardtags', 'tag'));
}
$PAGE->requires->js_call_amd('core/form-autocomplete', 'enhance', $params = array(
'#tags',
$typenewtags,
'',
get_string('entertags', 'tag'),
false,
$showstandard,
get_string('noselection', 'form')
)
);
$str .= html_writer::end_tag('div');
return $str;
}
/**
* Search for a field name and replaces it with another one in all the
* form templates. Set $newfieldname as '' if you want to delete the
* field from the form.
*
* @global object
* @param object $data
* @param string $searchfieldname
* @param string $newfieldname
* @return bool
*/
function data_replace_field_in_templates($data, $searchfieldname, $newfieldname) {
global $DB;
$newdata = (object)['id' => $data->id];
$update = false;
$templates = ['listtemplate', 'singletemplate', 'asearchtemplate', 'addtemplate', 'rsstemplate'];
foreach ($templates as $templatename) {
if (empty($data->$templatename)) {
continue;
}
$search = [
'[[' . $searchfieldname . ']]',
'[[' . $searchfieldname . '#id]]',
'[[' . $searchfieldname . '#name]]',
'[[' . $searchfieldname . '#description]]',
];
if (empty($newfieldname)) {
$replace = ['', '', '', ''];
} else {
$replace = [
'[[' . $newfieldname . ']]',
'[[' . $newfieldname . '#id]]',
'[[' . $newfieldname . '#name]]',
'[[' . $newfieldname . '#description]]',
];
}
$newdata->{$templatename} = str_ireplace($search, $replace, $data->{$templatename} ?? '');
$update = true;
}
if (!$update) {
return true;
}
return $DB->update_record('data', $newdata);
}
/**
* Appends a new field at the end of the form template.
*
* @global object
* @param object $data
* @param string $newfieldname
* @return bool if the field has been added or not
*/
function data_append_new_field_to_templates($data, $newfieldname): bool {
global $DB, $OUTPUT;
$newdata = (object)['id' => $data->id];
$update = false;
$templates = ['singletemplate', 'addtemplate', 'rsstemplate'];
foreach ($templates as $templatename) {
if (empty($data->$templatename)
|| strpos($data->$templatename, "[[$newfieldname]]") !== false
|| strpos($data->$templatename, "##otherfields##") !== false
) {
continue;
}
$newdata->$templatename = $data->$templatename;
$fields = [[
'fieldname' => '[[' . $newfieldname . '#name]]',
'fieldcontent' => '[[' . $newfieldname . ']]',
]];
$newdata->$templatename .= $OUTPUT->render_from_template(
'mod_data/fields_otherfields',
['fields' => $fields, 'classes' => 'added_field']
);
$update = true;
}
if (!$update) {
return false;
}
return $DB->update_record('data', $newdata);
}
/**
* given a field name
* this function creates an instance of the particular subfield class
*
* @global object
* @param string $name
* @param object $data
* @return object|bool
*/
function data_get_field_from_name($name, $data){
global $DB;
$field = $DB->get_record('data_fields', array('name'=>$name, 'dataid'=>$data->id));
if ($field) {
return data_get_field($field, $data);
} else {
return false;
}
}
/**
* given a field id
* this function creates an instance of the particular subfield class
*
* @global object
* @param int $fieldid
* @param object $data
* @return bool|object
*/
function data_get_field_from_id($fieldid, $data){
global $DB;
$field = $DB->get_record('data_fields', array('id'=>$fieldid, 'dataid'=>$data->id));
if ($field) {
return data_get_field($field, $data);
} else {
return false;
}
}
/**
* given a field id
* this function creates an instance of the particular subfield class
*
* @global object
* @param string $type
* @param object $data
* @return object
*/
function data_get_field_new($type, $data) {
global $CFG;
$type = clean_param($type, PARAM_ALPHA);
$filepath = $CFG->dirroot.'/mod/data/field/'.$type.'/field.class.php';
// It should never access this method if the subfield class doesn't exist.
if (!file_exists($filepath)) {
throw new \moodle_exception('invalidfieldtype', 'data');
}
require_once($filepath);
$newfield = 'data_field_'.$type;
$newfield = new $newfield(0, $data);
return $newfield;
}
/**
* returns a subclass field object given a record of the field, used to
* invoke plugin methods
* input: $param $field - record from db
*
* @global object
* @param stdClass $field the field record
* @param stdClass $data the data instance
* @param stdClass|null $cm optional course module data
* @return data_field_base the field object instance or data_field_base if unkown type
*/
function data_get_field(stdClass $field, stdClass $data, ?stdClass $cm=null): data_field_base {
global $CFG;
if (!isset($field->type)) {
return new data_field_base($field);
}
$field->type = clean_param($field->type, PARAM_ALPHA);
$filepath = $CFG->dirroot.'/mod/data/field/'.$field->type.'/field.class.php';
if (!file_exists($filepath)) {
return new data_field_base($field);
}
require_once($filepath);
$newfield = 'data_field_'.$field->type;
$newfield = new $newfield($field, $data, $cm);
return $newfield;
}
/**
* Given record object (or id), returns true if the record belongs to the current user
*
* @global object
* @global object
* @param mixed $record record object or id
* @return bool
*/
function data_isowner($record) {
global $USER, $DB;
if (!isloggedin()) { // perf shortcut
return false;
}
if (!is_object($record)) {
if (!$record = $DB->get_record('data_records', array('id'=>$record))) {
return false;
}
}
return ($record->userid == $USER->id);
}
/**
* has a user reached the max number of entries?
*
* @param object $data
* @return bool
*/
function data_atmaxentries($data){
if (!$data->maxentries){
return false;
} else {
return (data_numentries($data) >= $data->maxentries);
}
}
/**
* returns the number of entries already made by this user
*
* @global object
* @global object
* @param object $data
* @return int
*/
function data_numentries($data, $userid=null) {
global $USER, $DB;
if ($userid === null) {
$userid = $USER->id;
}
$sql = 'SELECT COUNT(*) FROM {data_records} WHERE dataid=? AND userid=?';
return $DB->count_records_sql($sql, array($data->id, $userid));
}
/**
* function that takes in a dataid and adds a record
* this is used everytime an add template is submitted
*
* @global object
* @global object
* @param object $data
* @param int $groupid
* @param int $userid
* @param bool $approved If specified, and the user has the capability to approve entries, then this value
* will be used as the approved status of the new record
* @return bool
*/
function data_add_record($data, $groupid = 0, $userid = null, bool $approved = true) {
global $USER, $DB;
$cm = get_coursemodule_from_instance('data', $data->id);
$context = context_module::instance($cm->id);
$record = new stdClass();
$record->userid = $userid ?? $USER->id;
$record->dataid = $data->id;
$record->groupid = $groupid;
$record->timecreated = $record->timemodified = time();
if (has_capability('mod/data:approve', $context)) {
$record->approved = $approved;
} else {
$record->approved = 0;
}
$record->id = $DB->insert_record('data_records', $record);
// Trigger an event for creating this record.
$event = \mod_data\event\record_created::create(array(
'objectid' => $record->id,
'context' => $context,
'other' => array(
'dataid' => $data->id
)
));
$event->trigger();
$course = get_course($cm->course);
data_update_completion_state($data, $course, $cm);
return $record->id;
}
/**
* check the multple existence any tag in a template
*
* check to see if there are 2 or more of the same tag being used.
*
* @global object
* @param int $dataid,
* @param string $template
* @return bool
*/
function data_tags_check($dataid, $template) {
global $DB, $OUTPUT;
// first get all the possible tags
$fields = $DB->get_records('data_fields', array('dataid'=>$dataid));
// then we generate strings to replace
$tagsok = true; // let's be optimistic
foreach ($fields as $field){
$pattern="/\[\[" . preg_quote($field->name, '/') . "\]\]/i";
if (preg_match_all($pattern, $template, $dummy)>1){
$tagsok = false;
echo $OUTPUT->notification('[['.$field->name.']] - '.get_string('multipletags','data'));
}
}
// else return true
return $tagsok;
}
/**
* Adds an instance of a data
*
* @param stdClass $data
* @param mod_data_mod_form $mform
* @return int intance id
*/
function data_add_instance($data, $mform = null) {
global $DB, $CFG;
require_once($CFG->dirroot.'/mod/data/locallib.php');
if (empty($data->assessed)) {
$data->assessed = 0;
}
if (empty($data->ratingtime) || empty($data->assessed)) {
$data->assesstimestart = 0;
$data->assesstimefinish = 0;
}
$data->timemodified = time();
$data->id = $DB->insert_record('data', $data);
// Add calendar events if necessary.
data_set_events($data);
if (!empty($data->completionexpected)) {
\core_completion\api::update_completion_date_event($data->coursemodule, 'data', $data->id, $data->completionexpected);
}
data_grade_item_update($data);
return $data->id;
}
/**
* updates an instance of a data
*
* @global object
* @param object $data
* @return bool
*/
function data_update_instance($data) {
global $DB, $CFG;
require_once($CFG->dirroot.'/mod/data/locallib.php');
$data->timemodified = time();
if (!empty($data->instance)) {
$data->id = $data->instance;
}
if (empty($data->assessed)) {
$data->assessed = 0;
}
if (empty($data->ratingtime) or empty($data->assessed)) {
$data->assesstimestart = 0;
$data->assesstimefinish = 0;
}
if (empty($data->notification)) {
$data->notification = 0;
}
$DB->update_record('data', $data);
// Add calendar events if necessary.
data_set_events($data);
$completionexpected = (!empty($data->completionexpected)) ? $data->completionexpected : null;
\core_completion\api::update_completion_date_event($data->coursemodule, 'data', $data->id, $completionexpected);
data_grade_item_update($data);
return true;
}
/**
* deletes an instance of a data
*
* @global object
* @param int $id
* @return bool
*/
function data_delete_instance($id) { // takes the dataid
global $DB, $CFG;
if (!$data = $DB->get_record('data', array('id'=>$id))) {
return false;
}
$cm = get_coursemodule_from_instance('data', $data->id);
$context = context_module::instance($cm->id);
// Delete all information related to fields.
$fields = $DB->get_records('data_fields', ['dataid' => $id]);
foreach ($fields as $field) {
$todelete = data_get_field($field, $data, $cm);
$todelete->delete_field();
}
// Remove old calendar events.
$events = $DB->get_records('event', array('modulename' => 'data', 'instance' => $id));
foreach ($events as $event) {
$event = calendar_event::load($event);
$event->delete();
}
// cleanup gradebook
data_grade_item_delete($data);
// Delete the instance itself
// We must delete the module record after we delete the grade item.
$result = $DB->delete_records('data', array('id'=>$id));
return $result;
}
/**
* returns a summary of data activity of this user
*
* @global object
* @param object $course
* @param object $user
* @param object $mod
* @param object $data
* @return object|null
*/
function data_user_outline($course, $user, $mod, $data) {
global $DB, $CFG;
require_once("$CFG->libdir/gradelib.php");
$grades = grade_get_grades($course->id, 'mod', 'data', $data->id, $user->id);
if (empty($grades->items[0]->grades)) {
$grade = false;
} else {
$grade = reset($grades->items[0]->grades);
}
if ($countrecords = $DB->count_records('data_records', array('dataid'=>$data->id, 'userid'=>$user->id))) {
$result = new stdClass();
$result->info = get_string('numrecords', 'data', $countrecords);
$lastrecord = $DB->get_record_sql('SELECT id,timemodified FROM {data_records}
WHERE dataid = ? AND userid = ?
ORDER BY timemodified DESC', array($data->id, $user->id), true);
$result->time = $lastrecord->timemodified;
if ($grade) {
if (!$grade->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
$result->info .= ', ' . get_string('gradenoun') . ': ' . $grade->str_long_grade;
} else {
$result->info = get_string('gradenoun') . ': ' . get_string('hidden', 'grades');
}
}
return $result;
} else if ($grade) {
$result = (object) [
'time' => grade_get_date_for_user_grade($grade, $user),
];
if (!$grade->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
$result->info = get_string('gradenoun') . ': ' . $grade->str_long_grade;
} else {
$result->info = get_string('gradenoun') . ': ' . get_string('hidden', 'grades');
}
return $result;
}
return NULL;
}
/**
* Prints all the records uploaded by this user
*
* @global object
* @param object $course
* @param object $user
* @param object $mod
* @param object $data
*/
function data_user_complete($course, $user, $mod, $data) {
global $DB, $CFG, $OUTPUT;
require_once("$CFG->libdir/gradelib.php");
$grades = grade_get_grades($course->id, 'mod', 'data', $data->id, $user->id);
if (!empty($grades->items[0]->grades)) {
$grade = reset($grades->items[0]->grades);
if (!$grade->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
echo $OUTPUT->container(get_string('gradenoun') . ': ' . $grade->str_long_grade);
if ($grade->str_feedback) {
echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
}
} else {
echo $OUTPUT->container(get_string('gradenoun') . ': ' . get_string('hidden', 'grades'));
}
}
$records = $DB->get_records(
'data_records',
['dataid' => $data->id, 'userid' => $user->id],
'timemodified DESC'
);
if ($records) {
$manager = manager::create_from_instance($data);
$parser = $manager->get_template('singletemplate');
echo $parser->parse_entries($records);
}
}
/**
* Return grade for given user or all users.
*
* @global object
* @param object $data
* @param int $userid optional user id, 0 means all users
* @return array array of grades, false if none
*/
function data_get_user_grades($data, $userid=0) {
global $CFG;
require_once($CFG->dirroot.'/rating/lib.php');
$ratingoptions = new stdClass;
$ratingoptions->component = 'mod_data';
$ratingoptions->ratingarea = 'entry';
$ratingoptions->modulename = 'data';
$ratingoptions->moduleid = $data->id;
$ratingoptions->userid = $userid;
$ratingoptions->aggregationmethod = $data->assessed;
$ratingoptions->scaleid = $data->scale;
$ratingoptions->itemtable = 'data_records';
$ratingoptions->itemtableusercolumn = 'userid';
$rm = new rating_manager();
return $rm->get_user_grades($ratingoptions);
}
/**
* Update activity grades
*
* @category grade
* @param object $data
* @param int $userid specific user only, 0 means all
* @param bool $nullifnone
*/
function data_update_grades($data, $userid=0, $nullifnone=true) {
global $CFG, $DB;
require_once($CFG->libdir.'/gradelib.php');
if (!$data->assessed) {
data_grade_item_update($data);
} else if ($grades = data_get_user_grades($data, $userid)) {
data_grade_item_update($data, $grades);
} else if ($userid and $nullifnone) {
$grade = new stdClass();
$grade->userid = $userid;
$grade->rawgrade = NULL;
data_grade_item_update($data, $grade);
} else {
data_grade_item_update($data);
}
}
/**
* Update/create grade item for given data
*
* @category grade
* @param stdClass $data A database instance with extra cmidnumber property
* @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
* @return object grade_item
*/
function data_grade_item_update($data, $grades=NULL) {
global $CFG;
require_once($CFG->libdir.'/gradelib.php');
$params = array('itemname'=>$data->name, 'idnumber'=>$data->cmidnumber);
if (!$data->assessed or $data->scale == 0) {
$params['gradetype'] = GRADE_TYPE_NONE;
} else if ($data->scale > 0) {
$params['gradetype'] = GRADE_TYPE_VALUE;
$params['grademax'] = $data->scale;
$params['grademin'] = 0;
} else if ($data->scale < 0) {
$params['gradetype'] = GRADE_TYPE_SCALE;
$params['scaleid'] = -$data->scale;
}
if ($grades === 'reset') {
$params['reset'] = true;
$grades = NULL;
}
return grade_update('mod/data', $data->course, 'mod', 'data', $data->id, 0, $grades, $params);
}
/**
* Delete grade item for given data
*
* @category grade
* @param object $data object
* @return object grade_item
*/
function data_grade_item_delete($data) {
global $CFG;
require_once($CFG->libdir.'/gradelib.php');
return grade_update('mod/data', $data->course, 'mod', 'data', $data->id, 0, NULL, array('deleted'=>1));
}
// junk functions
/**
* takes a list of records, the current data, a search string,
* and mode to display prints the translated template
*
* @deprecated since Moodle 4.1 MDL-75146 - please do not use this function any more.
* @todo MDL-75189 Final deprecation in Moodle 4.5.
* @param string $templatename the template name
* @param array $records the entries records
* @param stdClass $data the database instance object
* @param string $search the current search term
* @param int $page page number for pagination
* @param bool $return if the result should be returned (true) or printed (false)
* @param moodle_url|null $jumpurl a moodle_url by which to jump back to the record list (can be null)
* @return mixed string with all parsed entries or nothing if $return is false
*/
function data_print_template($templatename, $records, $data, $search='', $page=0, $return=false, ?moodle_url $jumpurl=null) {
debugging(
'data_print_template is deprecated. Use mod_data\\manager::get_template and mod_data\\template::parse_entries instead',
DEBUG_DEVELOPER
);
$options = [
'search' => $search,
'page' => $page,
];
if ($jumpurl) {
$options['baseurl'] = $jumpurl;
}
$manager = manager::create_from_instance($data);
$parser = $manager->get_template($templatename, $options);
$content = $parser->parse_entries($records);
if ($return) {
return $content;
}
echo $content;
}
/**
* Return rating related permissions
*
* @param string $contextid the context id
* @param string $component the component to get rating permissions for
* @param string $ratingarea the rating area to get permissions for
* @return array an associative array of the user's rating permissions
*/
function data_rating_permissions($contextid, $component, $ratingarea) {
$context = context::instance_by_id($contextid, MUST_EXIST);
if ($component != 'mod_data' || $ratingarea != 'entry') {
return null;
}
return array(
'view' => has_capability('mod/data:viewrating',$context),
'viewany' => has_capability('mod/data:viewanyrating',$context),
'viewall' => has_capability('mod/data:viewallratings',$context),
'rate' => has_capability('mod/data:rate',$context)
);
}
/**
* Validates a submitted rating
* @param array $params submitted data
* context => object the context in which the rated items exists [required]
* itemid => int the ID of the object being rated
* scaleid => int the scale from which the user can select a rating. Used for bounds checking. [required]
* rating => int the submitted rating
* rateduserid => int the id of the user whose items have been rated. NOT the user who submitted the ratings. 0 to update all. [required]
* aggregation => int the aggregation method to apply when calculating grades ie RATING_AGGREGATE_AVERAGE [required]
* @return boolean true if the rating is valid. Will throw rating_exception if not
*/
function data_rating_validate($params) {
global $DB, $USER;
// Check the component is mod_data
if ($params['component'] != 'mod_data') {
throw new rating_exception('invalidcomponent');
}
// Check the ratingarea is entry (the only rating area in data module)
if ($params['ratingarea'] != 'entry') {
throw new rating_exception('invalidratingarea');
}
// Check the rateduserid is not the current user .. you can't rate your own entries
if ($params['rateduserid'] == $USER->id) {
throw new rating_exception('nopermissiontorate');
}
$datasql = "SELECT d.id as dataid, d.scale, d.course, r.userid as userid, d.approval, r.approved, r.timecreated, d.assesstimestart, d.assesstimefinish, r.groupid
FROM {data_records} r
JOIN {data} d ON r.dataid = d.id
WHERE r.id = :itemid";
$dataparams = array('itemid'=>$params['itemid']);
if (!$info = $DB->get_record_sql($datasql, $dataparams)) {
//item doesn't exist
throw new rating_exception('invaliditemid');
}
if ($info->scale != $params['scaleid']) {
//the scale being submitted doesnt match the one in the database
throw new rating_exception('invalidscaleid');
}
//check that the submitted rating is valid for the scale
// lower limit
if ($params['rating'] < 0 && $params['rating'] != RATING_UNSET_RATING) {
throw new rating_exception('invalidnum');
}
// upper limit
if ($info->scale < 0) {
//its a custom scale
$scalerecord = $DB->get_record('scale', array('id' => -$info->scale));
if ($scalerecord) {
$scalearray = explode(',', $scalerecord->scale);
if ($params['rating'] > count($scalearray)) {
throw new rating_exception('invalidnum');
}
} else {
throw new rating_exception('invalidscaleid');
}
} else if ($params['rating'] > $info->scale) {
//if its numeric and submitted rating is above maximum
throw new rating_exception('invalidnum');
}
if ($info->approval && !$info->approved) {
//database requires approval but this item isnt approved
throw new rating_exception('nopermissiontorate');
}
// check the item we're rating was created in the assessable time window
if (!empty($info->assesstimestart) && !empty($info->assesstimefinish)) {
if ($info->timecreated < $info->assesstimestart || $info->timecreated > $info->assesstimefinish) {
throw new rating_exception('notavailable');
}
}
$course = $DB->get_record('course', array('id'=>$info->course), '*', MUST_EXIST);
$cm = get_coursemodule_from_instance('data', $info->dataid, $course->id, false, MUST_EXIST);
$context = context_module::instance($cm->id);
// if the supplied context doesnt match the item's context
if ($context->id != $params['context']->id) {
throw new rating_exception('invalidcontext');
}
// Make sure groups allow this user to see the item they're rating
$groupid = $info->groupid;
if ($groupid > 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) { // Groups are being used
if (!groups_group_exists($groupid)) { // Can't find group
throw new rating_exception('cannotfindgroup');//something is wrong
}
if (!groups_is_member($groupid) and !has_capability('moodle/site:accessallgroups', $context)) {
// do not allow rating of posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS
throw new rating_exception('notmemberofgroup');
}
}
return true;
}
/**
* Can the current user see ratings for a given itemid?
*
* @param array $params submitted data
* contextid => int contextid [required]
* component => The component for this module - should always be mod_data [required]
* ratingarea => object the context in which the rated items exists [required]
* itemid => int the ID of the object being rated [required]
* scaleid => int scale id [optional]
* @return bool
* @throws coding_exception
* @throws rating_exception
*/
function mod_data_rating_can_see_item_ratings($params) {
global $DB;
// Check the component is mod_data.
if (!isset($params['component']) || $params['component'] != 'mod_data') {
throw new rating_exception('invalidcomponent');
}
// Check the ratingarea is entry (the only rating area in data).
if (!isset($params['ratingarea']) || $params['ratingarea'] != 'entry') {
throw new rating_exception('invalidratingarea');
}
if (!isset($params['itemid'])) {
throw new rating_exception('invaliditemid');
}
$datasql = "SELECT d.id as dataid, d.course, r.groupid
FROM {data_records} r
JOIN {data} d ON r.dataid = d.id
WHERE r.id = :itemid";
$dataparams = array('itemid' => $params['itemid']);
if (!$info = $DB->get_record_sql($datasql, $dataparams)) {
// Item doesn't exist.
throw new rating_exception('invaliditemid');
}
// User can see ratings of all participants.
if ($info->groupid == 0) {
return true;
}
$course = $DB->get_record('course', array('id' => $info->course), '*', MUST_EXIST);
$cm = get_coursemodule_from_instance('data', $info->dataid, $course->id, false, MUST_EXIST);
// Make sure groups allow this user to see the item they're rating.
return groups_group_visible($info->groupid, $course, $cm);
}
/**
* function that takes in the current data, number of items per page,
* a search string and prints a preference box in view.php
*
* This preference box prints a searchable advanced search template if
* a) A template is defined
* b) The advanced search checkbox is checked.
*
* @global object
* @global object
* @param object $data
* @param int $perpage
* @param string $search
* @param string $sort
* @param string $order
* @param array $search_array
* @param int $advanced
* @param string $mode
* @return void
*/
function data_print_preference_form($data, $perpage, $search, $sort='', $order='ASC', $search_array = '', $advanced = 0, $mode= ''){
global $DB, $PAGE, $OUTPUT;
$cm = get_coursemodule_from_instance('data', $data->id);
$context = context_module::instance($cm->id);
echo '