MDL-66874 mod_data: Explicitly add btn-secondary class to select all
[moodle.git] / mod / data / lib.php
CommitLineData
4636bf83 1<?php
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
3d4b223a 17
4636bf83 18/**
002a2a44 19 * @package mod_data
4636bf83 20 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
21 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
22 */
23
c4b70cfc
SB
24defined('MOODLE_INTERNAL') || die();
25
b8b554ac 26// Some constants
0997e51a 27define ('DATA_MAX_ENTRIES', 50);
28define ('DATA_PERPAGE_SINGLE', 1);
b572ce19 29
714bec74 30define ('DATA_FIRSTNAME', -1);
31define ('DATA_LASTNAME', -2);
bb5740f4 32define ('DATA_APPROVED', -3);
3239b010 33define ('DATA_TIMEADDED', 0);
34define ('DATA_TIMEMODIFIED', -4);
d45c7a68 35define ('DATA_TAGS', -5);
714bec74 36
a7e35395 37define ('DATA_CAP_EXPORT', 'mod/data:viewalluserpresets');
8aff1574
SH
38
39define('DATA_PRESET_COMPONENT', 'mod_data');
40define('DATA_PRESET_FILEAREA', 'site_presets');
41define('DATA_PRESET_CONTEXT', SYSCONTEXTID);
42
7c6f961b
MN
43define('DATA_EVENT_TYPE_OPEN', 'open');
44define('DATA_EVENT_TYPE_CLOSE', 'close');
45
a7e35395 46// Users having assigned the default role "Non-editing teacher" can export database records
47// Using the mod/data capability "viewalluserpresets" existing in Moodle 1.9.x.
8429163d 48// In Moodle >= 2, new roles may be introduced and used instead.
a7e35395 49
4636bf83 50/**
002a2a44 51 * @package mod_data
4636bf83 52 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
53 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
54 */
668fc89a 55class data_field_base { // Base class for Database Field Types (see field/*/field.class.php)
3d4b223a 56
4636bf83 57 /** @var string Subclasses must override the type with their name */
58 var $type = 'unknown';
59 /** @var object The database object that this field belongs to */
60 var $data = NULL;
61 /** @var object The field object itself, if we know it */
56c1ca88 62 var $field = NULL;
4636bf83 63 /** @var int Width of the icon for this fieldtype */
64 var $iconwidth = 16;
65 /** @var int Width of the icon for this fieldtype */
66 var $iconheight = 16;
67 /** @var object course module or cmifno */
68 var $cm;
69 /** @var object activity context */
70 var $context;
2af9ad7d
DG
71 /** @var priority for globalsearch indexing */
72 protected static $priority = self::NO_PRIORITY;
73 /** priority value for invalid fields regarding indexing */
74 const NO_PRIORITY = 0;
75 /** priority value for minimum priority */
76 const MIN_PRIORITY = 1;
77 /** priority value for low priority */
78 const LOW_PRIORITY = 2;
79 /** priority value for high priority */
80 const HIGH_PRIORITY = 3;
81 /** priority value for maximum priority */
82 const MAX_PRIORITY = 4;
4636bf83 83
84 /**
85 * Constructor function
86 *
87 * @global object
88 * @uses CONTEXT_MODULE
89 * @param int $field
90 * @param int $data
91 * @param int $cm
92 */
8429163d 93 function __construct($field=0, $data=0, $cm=0) { // Field or data or both, each can be id or object
9c00b5d7 94 global $DB;
0997e51a 95
96 if (empty($field) && empty($data)) {
29c1bb15 97 print_error('missingfield', 'data');
0997e51a 98 }
b572ce19 99
0997e51a 100 if (!empty($field)) {
101 if (is_object($field)) {
102 $this->field = $field; // Programmer knows what they are doing, we hope
9c00b5d7 103 } else if (!$this->field = $DB->get_record('data_fields', array('id'=>$field))) {
29c1bb15 104 print_error('invalidfieldid', 'data');
0997e51a 105 }
106 if (empty($data)) {
9c00b5d7 107 if (!$this->data = $DB->get_record('data', array('id'=>$this->field->dataid))) {
29c1bb15 108 print_error('invalidid', 'data');
0997e51a 109 }
110 }
111 }
b572ce19 112
0997e51a 113 if (empty($this->data)) { // We need to define this properly
114 if (!empty($data)) {
115 if (is_object($data)) {
116 $this->data = $data; // Programmer knows what they are doing, we hope
9c00b5d7 117 } else if (!$this->data = $DB->get_record('data', array('id'=>$data))) {
29c1bb15 118 print_error('invalidid', 'data');
0997e51a 119 }
120 } else { // No way to define it!
29c1bb15 121 print_error('missingdata', 'data');
0997e51a 122 }
123 }
b572ce19 124
8429163d 125 if ($cm) {
126 $this->cm = $cm;
127 } else {
128 $this->cm = get_coursemodule_from_instance('data', $this->data->id);
129 }
130
0997e51a 131 if (empty($this->field)) { // We need to define some default values
132 $this->define_default_field();
133 }
8429163d 134
0b3b8c30 135 $this->context = context_module::instance($this->cm->id);
3d4b223a 136 }
0997e51a 137
6403e679 138
4636bf83 139 /**
140 * This field just sets up a default field object
141 *
142 * @return bool
143 */
0997e51a 144 function define_default_field() {
4102b449 145 global $OUTPUT;
0997e51a 146 if (empty($this->data->id)) {
4102b449 147 echo $OUTPUT->notification('Programmer error: dataid not defined in field class');
0997e51a 148 }
39790bd8 149 $this->field = new stdClass();
0997e51a 150 $this->field->id = 0;
151 $this->field->dataid = $this->data->id;
152 $this->field->type = $this->type;
153 $this->field->param1 = '';
154 $this->field->param2 = '';
155 $this->field->param3 = '';
156 $this->field->name = '';
157 $this->field->description = '';
b89cca19 158 $this->field->required = false;
b572ce19 159
0997e51a 160 return true;
3d4b223a 161 }
0997e51a 162
4636bf83 163 /**
164 * Set up the field object according to data in an object. Now is the time to clean it!
165 *
166 * @return bool
167 */
0997e51a 168 function define_field($data) {
169 $this->field->type = $this->type;
170 $this->field->dataid = $this->data->id;
171
172 $this->field->name = trim($data->name);
173 $this->field->description = trim($data->description);
1c3b2058 174 $this->field->required = !empty($data->required) ? 1 : 0;
0997e51a 175
176 if (isset($data->param1)) {
177 $this->field->param1 = trim($data->param1);
178 }
179 if (isset($data->param2)) {
8921fdb7 180 $this->field->param2 = trim($data->param2);
0997e51a 181 }
182 if (isset($data->param3)) {
183 $this->field->param3 = trim($data->param3);
184 }
185 if (isset($data->param4)) {
186 $this->field->param4 = trim($data->param4);
187 }
188 if (isset($data->param5)) {
189 $this->field->param5 = trim($data->param5);
190 }
191
192 return true;
3d4b223a 193 }
6403e679 194
4636bf83 195 /**
196 * Insert a new field in the database
197 * We assume the field object is already defined as $this->field
198 *
199 * @global object
200 * @return bool
201 */
0997e51a 202 function insert_field() {
4102b449 203 global $DB, $OUTPUT;
9c00b5d7 204
0997e51a 205 if (empty($this->field)) {
4102b449 206 echo $OUTPUT->notification('Programmer error: Field has not been defined yet! See define_field()');
0997e51a 207 return false;
208 }
209
a8f3a651 210 $this->field->id = $DB->insert_record('data_fields',$this->field);
e0d7ed6d
MN
211
212 // Trigger an event for creating this field.
213 $event = \mod_data\event\field_created::create(array(
214 'objectid' => $this->field->id,
215 'context' => $this->context,
216 'other' => array(
217 'fieldname' => $this->field->name,
218 'dataid' => $this->data->id
219 )
220 ));
221 $event->trigger();
222
0997e51a 223 return true;
3d4b223a 224 }
225
0997e51a 226
4636bf83 227 /**
228 * Update a field in the database
229 *
230 * @global object
231 * @return bool
232 */
0997e51a 233 function update_field() {
9c00b5d7 234 global $DB;
235
9d749339 236 $DB->update_record('data_fields', $this->field);
d1ec5557
MN
237
238 // Trigger an event for updating this field.
239 $event = \mod_data\event\field_updated::create(array(
240 'objectid' => $this->field->id,
241 'context' => $this->context,
242 'other' => array(
243 'fieldname' => $this->field->name,
244 'dataid' => $this->data->id
245 )
246 ));
247 $event->trigger();
248
0997e51a 249 return true;
250 }
3d4b223a 251
4636bf83 252 /**
253 * Delete a field completely
254 *
255 * @global object
256 * @return bool
257 */
0997e51a 258 function delete_field() {
9c00b5d7 259 global $DB;
260
0997e51a 261 if (!empty($this->field->id)) {
e37c413e
MN
262 // Get the field before we delete it.
263 $field = $DB->get_record('data_fields', array('id' => $this->field->id));
264
0997e51a 265 $this->delete_content();
8429163d 266 $DB->delete_records('data_fields', array('id'=>$this->field->id));
e37c413e
MN
267
268 // Trigger an event for deleting this field.
269 $event = \mod_data\event\field_deleted::create(array(
270 'objectid' => $this->field->id,
271 'context' => $this->context,
272 'other' => array(
273 'fieldname' => $this->field->name,
274 'dataid' => $this->data->id
275 )
276 ));
277 $event->add_record_snapshot('data_fields', $field);
278 $event->trigger();
3d4b223a 279 }
e37c413e 280
0997e51a 281 return true;
282 }
283
4636bf83 284 /**
285 * Print the relevant form element in the ADD template for this field
286 *
287 * @global object
288 * @param int $recordid
289 * @return string
290 */
1c3b2058
JO
291 function display_add_field($recordid=0, $formdata=null) {
292 global $DB, $OUTPUT;
9c00b5d7 293
b89cca19
DW
294 if ($formdata) {
295 $fieldname = 'field_' . $this->field->id;
296 $content = $formdata->$fieldname;
1c3b2058 297 } else if ($recordid) {
9c00b5d7 298 $content = $DB->get_field('data_content', 'content', array('fieldid'=>$this->field->id, 'recordid'=>$recordid));
0997e51a 299 } else {
3d4b223a 300 $content = '';
301 }
6403e679 302
344e15e6 303 // beware get_field returns false for new, empty records MDL-18567
304 if ($content===false) {
305 $content='';
306 }
307
1c3b2058
JO
308 $str = '<div title="' . s($this->field->description) . '">';
309 $str .= '<label for="field_'.$this->field->id.'"><span class="accesshide">'.$this->field->name.'</span>';
b89cca19 310 if ($this->field->required) {
663640f5 311 $image = $OUTPUT->pix_icon('req', get_string('requiredelement', 'form'));
c07c5e7b 312 $str .= html_writer::div($image, 'inline-req');
b89cca19 313 }
398be7c8
DW
314 $str .= '</label><input class="basefieldinput form-control d-inline mod-data-input" ' .
315 'type="text" name="field_' . $this->field->id . '" ' .
316 'id="field_' . $this->field->id . '" value="' . s($content) . '" />';
bbe39b6c 317 $str .= '</div>';
0997e51a 318
3d4b223a 319 return $str;
320 }
321
4636bf83 322 /**
323 * Print the relevant form element to define the attributes for this field
324 * viewable by teachers only.
325 *
326 * @global object
327 * @global object
328 * @return void Output is echo'd
329 */
0997e51a 330 function display_edit_field() {
b2dc6880 331 global $CFG, $DB, $OUTPUT;
0997e51a 332
333 if (empty($this->field)) { // No field has been defined yet, try and make one
334 $this->define_default_field();
3d4b223a 335 }
4102b449 336 echo $OUTPUT->box_start('generalbox boxaligncenter boxwidthwide');
0997e51a 337
b7dc2256 338 echo '<form id="editfield" action="'.$CFG->wwwroot.'/mod/data/field.php" method="post">'."\n";
0997e51a 339 echo '<input type="hidden" name="d" value="'.$this->data->id.'" />'."\n";
340 if (empty($this->field->id)) {
341 echo '<input type="hidden" name="mode" value="add" />'."\n";
342 $savebutton = get_string('add');
343 } else {
344 echo '<input type="hidden" name="fid" value="'.$this->field->id.'" />'."\n";
345 echo '<input type="hidden" name="mode" value="update" />'."\n";
346 $savebutton = get_string('savechanges');
347 }
348 echo '<input type="hidden" name="type" value="'.$this->type.'" />'."\n";
349 echo '<input name="sesskey" value="'.sesskey().'" type="hidden" />'."\n";
6403e679 350
66e2b9f8 351 echo $OUTPUT->heading($this->name(), 3);
0997e51a 352
3d4b223a 353 require_once($CFG->dirroot.'/mod/data/field/'.$this->type.'/mod.html');
0997e51a 354
85db96c5 355 echo '<div class="mdl-align">';
e85fda95
DW
356 echo '<input type="submit" class="btn btn-primary" value="'.$savebutton.'" />'."\n";
357 echo '<input type="submit" class="btn btn-secondary" name="cancel" value="'.get_string('cancel').'" />'."\n";
e357c206 358 echo '</div>';
0997e51a 359
360 echo '</form>';
361
4102b449 362 echo $OUTPUT->box_end();
3d4b223a 363 }
6403e679 364
4636bf83 365 /**
366 * Display the content of the field in browse mode
367 *
368 * @global object
369 * @param int $recordid
370 * @param object $template
371 * @return bool|string
372 */
0997e51a 373 function display_browse_field($recordid, $template) {
9c00b5d7 374 global $DB;
375
376 if ($content = $DB->get_record('data_content', array('fieldid'=>$this->field->id, 'recordid'=>$recordid))) {
6403e679 377 if (isset($content->content)) {
39790bd8 378 $options = new stdClass();
c8505cac 379 if ($this->field->param1 == '1') { // We are autolinking this field, so disable linking within us
380 //$content->content = '<span class="nolink">'.$content->content.'</span>';
381 //$content->content1 = FORMAT_HTML;
382 $options->filter=false;
383 }
1f697b99 384 $options->para = false;
385 $str = format_text($content->content, $content->content1, $options);
3d4b223a 386 } else {
387 $str = '';
388 }
389 return $str;
390 }
391 return false;
392 }
6403e679 393
4636bf83 394 /**
395 * Update the content of one data field in the data_content table
396 * @global object
397 * @param int $recordid
398 * @param mixed $value
399 * @param string $name
400 * @return bool
401 */
0997e51a 402 function update_content($recordid, $value, $name=''){
9c00b5d7 403 global $DB;
404
39790bd8 405 $content = new stdClass();
0997e51a 406 $content->fieldid = $this->field->id;
c87fbb27 407 $content->recordid = $recordid;
408 $content->content = clean_param($value, PARAM_NOTAGS);
0997e51a 409
9c00b5d7 410 if ($oldcontent = $DB->get_record('data_content', array('fieldid'=>$this->field->id, 'recordid'=>$recordid))) {
3d4b223a 411 $content->id = $oldcontent->id;
9c00b5d7 412 return $DB->update_record('data_content', $content);
0997e51a 413 } else {
9c00b5d7 414 return $DB->insert_record('data_content', $content);
3d4b223a 415 }
0997e51a 416 }
6403e679 417
4636bf83 418 /**
419 * Delete all content associated with the field
420 *
421 * @global object
422 * @param int $recordid
423 * @return bool
424 */
0997e51a 425 function delete_content($recordid=0) {
9c00b5d7 426 global $DB;
0997e51a 427
0997e51a 428 if ($recordid) {
8429163d 429 $conditions = array('fieldid'=>$this->field->id, 'recordid'=>$recordid);
0997e51a 430 } else {
8429163d 431 $conditions = array('fieldid'=>$this->field->id);
3d4b223a 432 }
0997e51a 433
6b1b1d03
EL
434 $rs = $DB->get_recordset('data_content', $conditions);
435 if ($rs->valid()) {
8429163d 436 $fs = get_file_storage();
437 foreach ($rs as $content) {
64f93798 438 $fs->delete_area_files($this->context->id, 'mod_data', 'content', $content->id);
8429163d 439 }
0997e51a 440 }
6b1b1d03 441 $rs->close();
0997e51a 442
8429163d 443 return $DB->delete_records('data_content', $conditions);
0997e51a 444 }
6403e679 445
4636bf83 446 /**
447 * Check if a field from an add form is empty
448 *
449 * @param mixed $value
450 * @param mixed $name
451 * @return bool
452 */
f9eab7b0 453 function notemptyfield($value, $name) {
3d4b223a 454 return !empty($value);
455 }
6403e679 456
4636bf83 457 /**
458 * Just in case a field needs to print something before the whole form
459 */
0997e51a 460 function print_before_form() {
3d4b223a 461 }
0997e51a 462
4636bf83 463 /**
464 * Just in case a field needs to print something after the whole form
465 */
5f5bcda8 466 function print_after_form() {
5f5bcda8 467 }
6403e679 468
469
4636bf83 470 /**
471 * Returns the sortable field for the content. By default, it's just content
472 * but for some plugins, it could be content 1 - content4
473 *
474 * @return string
475 */
cf3e199b 476 function get_sort_field() {
477 return 'content';
478 }
0997e51a 479
4636bf83 480 /**
481 * Returns the SQL needed to refer to the column. Some fields may need to CAST() etc.
482 *
483 * @param string $fieldname
484 * @return string $fieldname
485 */
64452eb4 486 function get_sort_sql($fieldname) {
487 return $fieldname;
488 }
489
4636bf83 490 /**
491 * Returns the name/type of the field
492 *
493 * @return string
494 */
b8b554ac 495 function name() {
421b2d44 496 return get_string('fieldtypelabel', "datafield_$this->type");
0997e51a 497 }
6403e679 498
4636bf83 499 /**
500 * Prints the respective type icon
501 *
502 * @global object
503 * @return string
504 */
0997e51a 505 function image() {
5ef44400 506 global $OUTPUT;
0997e51a 507
a7d4cb67
DC
508 $params = array('d'=>$this->data->id, 'fid'=>$this->field->id, 'mode'=>'display', 'sesskey'=>sesskey());
509 $link = new moodle_url('/mod/data/field.php', $params);
510 $str = '<a href="'.$link->out().'">';
b9b409cf 511 $str .= $OUTPUT->pix_icon('field/' . $this->type, $this->type, 'data');
663640f5 512 $str .= '</a>';
0997e51a 513 return $str;
514 }
515
4636bf83 516 /**
517 * Per default, it is assumed that fields support text exporting.
518 * Override this (return false) on fields not supporting text exporting.
519 *
520 * @return bool true
521 */
b8b554ac 522 function text_export_supported() {
523 return true;
524 }
6403e679 525
4636bf83 526 /**
527 * Per default, return the record's text value only from the "content" field.
528 * Override this in fields class if necesarry.
529 *
530 * @param string $record
531 * @return string
532 */
b8b554ac 533 function export_text_value($record) {
534 if ($this->text_export_supported()) {
535 return $record->content;
536 }
537 }
0997e51a 538
4636bf83 539 /**
540 * @param string $relativepath
541 * @return bool false
542 */
8429163d 543 function file_ok($relativepath) {
544 return false;
545 }
2af9ad7d
DG
546
547 /**
548 * Returns the priority for being indexed by globalsearch
549 *
550 * @return int
551 */
552 public static function get_priority() {
553 return static::$priority;
554 }
555
556 /**
557 * Returns the presentable string value for a field content.
fa90f529
DM
558 *
559 * The returned string should be plain text.
560 *
561 * @param stdClass $content
2af9ad7d
DG
562 * @return string
563 */
fa90f529
DM
564 public static function get_content_value($content) {
565 return trim($content->content, "\r\n ");
2af9ad7d 566 }
aefe9c5f
JL
567
568 /**
569 * Return the plugin configs for external functions,
570 * in some cases the configs will need formatting or be returned only if the current user has some capabilities enabled.
571 *
572 * @return array the list of config parameters
573 * @since Moodle 3.3
574 */
575 public function get_config_for_external() {
576 // Return all the field configs to null (maybe there is a private key for a service or something similar there).
577 $configs = [];
578 for ($i = 1; $i <= 10; $i++) {
579 $configs["param$i"] = null;
580 }
581 return $configs;
582 }
b8b554ac 583}
3d4b223a 584
585
4636bf83 586/**
587 * Given a template and a dataid, generate a default case template
588 *
589 * @global object
590 * @param object $data
591 * @param string template [addtemplate, singletemplate, listtempalte, rsstemplate]
592 * @param int $recordid
593 * @param bool $form
594 * @param bool $update
595 * @return bool|string
596 */
a44e7081 597function data_generate_default_template(&$data, $template, $recordid=0, $form=false, $update=true) {
9c00b5d7 598 global $DB;
d118d06a 599
edaa546a 600 if (!$data && !$template) {
3d4b223a 601 return false;
602 }
5cd07964 603 if ($template == 'csstemplate' or $template == 'jstemplate' ) {
f24eb261 604 return '';
605 }
6403e679 606
b8b554ac 607 // get all the fields for that database
9c00b5d7 608 if ($fields = $DB->get_records('data_fields', array('dataid'=>$data->id), 'id')) {
6403e679 609
b41fc49c 610 $table = new html_table();
2ddd7605 611 $table->attributes['class'] = 'mod-data-default-template ##approvalstatusclass##';
b41fc49c
NK
612 $table->colclasses = array('template-field', 'template-token');
613 $table->data = array();
f41cadeb 614 foreach ($fields as $field) {
b8b554ac 615 if ($form) { // Print forms instead of data
d118d06a 616 $fieldobj = data_get_field($field, $data);
b89cca19 617 $token = $fieldobj->display_add_field($recordid, null);
b8b554ac 618 } else { // Just print the tag
b41fc49c 619 $token = '[['.$field->name.']]';
d118d06a 620 }
b41fc49c
NK
621 $table->data[] = array(
622 $field->name.': ',
623 $token
624 );
3d4b223a 625 }
ca5f3e0a
AH
626
627 if (core_tag_tag::is_enabled('mod_data', 'data_records')) {
628 $label = new html_table_cell(get_string('tags') . ':');
629 if ($form) {
630 $cell = data_generate_tag_form();
631 } else {
632 $cell = new html_table_cell('##tags##');
633 }
634 $table->data[] = new html_table_row(array($label, $cell));
635 }
636
bb828644 637 if ($template == 'listtemplate') {
d0372ed6 638 $cell = new html_table_cell('##edit## ##more## ##delete## ##approve## ##disapprove## ##export##');
b41fc49c
NK
639 $cell->colspan = 2;
640 $cell->attributes['class'] = 'controls';
641 $table->data[] = new html_table_row(array($cell));
bb828644 642 } else if ($template == 'singletemplate') {
d0372ed6 643 $cell = new html_table_cell('##edit## ##delete## ##approve## ##disapprove## ##export##');
b41fc49c
NK
644 $cell->colspan = 2;
645 $cell->attributes['class'] = 'controls';
646 $table->data[] = new html_table_row(array($cell));
714bec74 647 } else if ($template == 'asearchtemplate') {
2b04c41c 648 $row = new html_table_row(array(get_string('authorfirstname', 'data').': ', '##firstname##'));
b41fc49c
NK
649 $row->attributes['class'] = 'searchcontrols';
650 $table->data[] = $row;
2b04c41c 651 $row = new html_table_row(array(get_string('authorlastname', 'data').': ', '##lastname##'));
b41fc49c
NK
652 $row->attributes['class'] = 'searchcontrols';
653 $table->data[] = $row;
3d4b223a 654 }
655
cf9ecfda
AG
656 $str = '';
657 if ($template == 'listtemplate'){
658 $str .= '##delcheck##';
659 $str .= html_writer::empty_tag('br');
660 }
661
662 $str .= html_writer::start_tag('div', array('class' => 'defaulttemplate'));
b41fc49c
NK
663 $str .= html_writer::table($table);
664 $str .= html_writer::end_tag('div');
d118d06a 665 if ($template == 'listtemplate'){
b41fc49c 666 $str .= html_writer::empty_tag('hr');
3d4b223a 667 }
f9eab7b0 668
d118d06a 669 if ($update) {
39790bd8 670 $newdata = new stdClass();
d118d06a 671 $newdata->id = $data->id;
f41cadeb 672 $newdata->{$template} = $str;
9d749339 673 $DB->update_record('data', $newdata);
674 $data->{$template} = $str;
3d4b223a 675 }
d118d06a 676
677 return $str;
3d4b223a 678 }
679}
680
ca5f3e0a
AH
681/**
682 * Build the form elements to manage tags for a record.
683 *
d45c7a68
AH
684 * @param int|bool $recordid
685 * @param string[] $selected raw tag names
ca5f3e0a
AH
686 * @return string
687 */
d45c7a68 688function data_generate_tag_form($recordid = false, $selected = []) {
822b3346 689 global $CFG, $DB, $OUTPUT, $PAGE;
ca5f3e0a
AH
690
691 $tagtypestoshow = \core_tag_area::get_showstandard('mod_data', 'data_records');
692 $showstandard = ($tagtypestoshow != core_tag_tag::HIDE_STANDARD);
693 $typenewtags = ($tagtypestoshow != core_tag_tag::STANDARD_ONLY);
694
695 $str = html_writer::start_tag('div', array('class' => 'datatagcontrol'));
696
697 $namefield = empty($CFG->keeptagnamecase) ? 'name' : 'rawname';
698
d45c7a68
AH
699 $tagcollid = \core_tag_area::get_collection('mod_data', 'data_records');
700 $tags = [];
701 $selectedtags = [];
ca5f3e0a
AH
702
703 if ($showstandard) {
d45c7a68
AH
704 $tags += $DB->get_records_menu('tag', array('isstandard' => 1, 'tagcollid' => $tagcollid),
705 $namefield, 'id,' . $namefield . ' as fieldname');
706 }
ca5f3e0a 707
d45c7a68
AH
708 if ($recordid) {
709 $selectedtags += core_tag_tag::get_item_tags_array('mod_data', 'data_records', $recordid);
710 }
711
712 if (!empty($selected)) {
713 list($sql, $params) = $DB->get_in_or_equal($selected, SQL_PARAMS_NAMED);
714 $params['tagcollid'] = $tagcollid;
715 $sql = "SELECT id, $namefield FROM {tag} WHERE tagcollid = :tagcollid AND rawname $sql";
716 $selectedtags += $DB->get_records_sql_menu($sql, $params);
ca5f3e0a
AH
717 }
718
d45c7a68
AH
719 $tags += $selectedtags;
720
ca5f3e0a
AH
721 $str .= '<select class="custom-select" name="tags[]" id="tags" multiple>';
722 foreach ($tags as $tagid => $tag) {
d45c7a68 723 $selected = key_exists($tagid, $selectedtags) ? 'selected' : '';
ca5f3e0a
AH
724 $str .= "<option value='$tag' $selected>$tag</option>";
725 }
726 $str .= '</select>';
727
822b3346
MN
728 if (has_capability('moodle/tag:manage', context_system::instance()) && $showstandard) {
729 $url = new moodle_url('/tag/manage.php', array('tc' => core_tag_area::get_collection('mod_data',
730 'data_records')));
731 $str .= ' ' . $OUTPUT->action_link($url, get_string('managestandardtags', 'tag'));
732 }
733
ca5f3e0a
AH
734 $PAGE->requires->js_call_amd('core/form-autocomplete', 'enhance', $params = array(
735 '#tags',
736 $typenewtags,
737 '',
738 get_string('entertags', 'tag'),
739 false,
740 $showstandard,
741 get_string('noselection', 'form')
742 )
743 );
744
745 $str .= html_writer::end_tag('div');
746
747 return $str;
748}
749
3d4b223a 750
4636bf83 751/**
56c1ca88 752 * Search for a field name and replaces it with another one in all the
753 * form templates. Set $newfieldname as '' if you want to delete the
4636bf83 754 * field from the form.
755 *
756 * @global object
757 * @param object $data
758 * @param string $searchfieldname
759 * @param string $newfieldname
760 * @return bool
761 */
0997e51a 762function data_replace_field_in_templates($data, $searchfieldname, $newfieldname) {
9c00b5d7 763 global $DB;
764
f9eab7b0 765 if (!empty($newfieldname)) {
766 $prestring = '[[';
767 $poststring = ']]';
9706fa56 768 $idpart = '#id';
735a7952 769
770 } else {
f9eab7b0 771 $prestring = '';
772 $poststring = '';
9706fa56 773 $idpart = '';
f9eab7b0 774 }
6403e679 775
39790bd8 776 $newdata = new stdClass();
735a7952 777 $newdata->id = $data->id;
9c00b5d7 778 $newdata->singletemplate = str_ireplace('[['.$searchfieldname.']]',
779 $prestring.$newfieldname.$poststring, $data->singletemplate);
6403e679 780
9c00b5d7 781 $newdata->listtemplate = str_ireplace('[['.$searchfieldname.']]',
782 $prestring.$newfieldname.$poststring, $data->listtemplate);
6403e679 783
9c00b5d7 784 $newdata->addtemplate = str_ireplace('[['.$searchfieldname.']]',
785 $prestring.$newfieldname.$poststring, $data->addtemplate);
6403e679 786
9c00b5d7 787 $newdata->addtemplate = str_ireplace('[['.$searchfieldname.'#id]]',
788 $prestring.$newfieldname.$idpart.$poststring, $data->addtemplate);
9706fa56 789
9c00b5d7 790 $newdata->rsstemplate = str_ireplace('[['.$searchfieldname.']]',
791 $prestring.$newfieldname.$poststring, $data->rsstemplate);
6403e679 792
9c00b5d7 793 return $DB->update_record('data', $newdata);
f9eab7b0 794}
795
796
4636bf83 797/**
798 * Appends a new field at the end of the form template.
799 *
800 * @global object
801 * @param object $data
802 * @param string $newfieldname
803 */
0997e51a 804function data_append_new_field_to_templates($data, $newfieldname) {
9c00b5d7 805 global $DB;
0997e51a 806
39790bd8 807 $newdata = new stdClass();
0997e51a 808 $newdata->id = $data->id;
ed69c723 809 $change = false;
0997e51a 810
f9eab7b0 811 if (!empty($data->singletemplate)) {
9c00b5d7 812 $newdata->singletemplate = $data->singletemplate.' [[' . $newfieldname .']]';
ed69c723 813 $change = true;
0997e51a 814 }
815 if (!empty($data->addtemplate)) {
9c00b5d7 816 $newdata->addtemplate = $data->addtemplate.' [[' . $newfieldname . ']]';
ed69c723 817 $change = true;
f9eab7b0 818 }
819 if (!empty($data->rsstemplate)) {
9c00b5d7 820 $newdata->rsstemplate = $data->singletemplate.' [[' . $newfieldname . ']]';
ed69c723 821 $change = true;
822 }
823 if ($change) {
9c00b5d7 824 $DB->update_record('data', $newdata);
f9eab7b0 825 }
f9eab7b0 826}
827
828
4636bf83 829/**
830 * given a field name
831 * this function creates an instance of the particular subfield class
832 *
833 * @global object
834 * @param string $name
835 * @param object $data
836 * @return object|bool
837 */
0997e51a 838function data_get_field_from_name($name, $data){
9c00b5d7 839 global $DB;
840
1e123f47 841 $field = $DB->get_record('data_fields', array('name'=>$name, 'dataid'=>$data->id));
0997e51a 842
843 if ($field) {
844 return data_get_field($field, $data);
845 } else {
846 return false;
847 }
848}
849
4636bf83 850/**
851 * given a field id
852 * this function creates an instance of the particular subfield class
853 *
854 * @global object
855 * @param int $fieldid
856 * @param object $data
857 * @return bool|object
858 */
0997e51a 859function data_get_field_from_id($fieldid, $data){
9c00b5d7 860 global $DB;
861
1e123f47 862 $field = $DB->get_record('data_fields', array('id'=>$fieldid, 'dataid'=>$data->id));
3d4b223a 863
0997e51a 864 if ($field) {
865 return data_get_field($field, $data);
5782be6b 866 } else {
d6f0e247 867 return false;
3d4b223a 868 }
3d4b223a 869}
870
4636bf83 871/**
872 * given a field id
873 * this function creates an instance of the particular subfield class
874 *
875 * @global object
876 * @param string $type
877 * @param object $data
878 * @return object
879 */
0997e51a 880function data_get_field_new($type, $data) {
881 global $CFG;
b572ce19 882
0997e51a 883 require_once($CFG->dirroot.'/mod/data/field/'.$type.'/field.class.php');
884 $newfield = 'data_field_'.$type;
885 $newfield = new $newfield(0, $data);
886 return $newfield;
887}
888
4636bf83 889/**
890 * returns a subclass field object given a record of the field, used to
891 * invoke plugin methods
892 * input: $param $field - record from db
893 *
894 * @global object
895 * @param object $field
896 * @param object $data
897 * @param object $cm
898 * @return object
899 */
8429163d 900function data_get_field($field, $data, $cm=null) {
0997e51a 901 global $CFG;
b572ce19 902
0997e51a 903 if ($field) {
3d4b223a 904 require_once('field/'.$field->type.'/field.class.php');
905 $newfield = 'data_field_'.$field->type;
8429163d 906 $newfield = new $newfield($field, $data, $cm);
3d4b223a 907 return $newfield;
908 }
909}
910
911
8429163d 912/**
913 * Given record object (or id), returns true if the record belongs to the current user
4636bf83 914 *
915 * @global object
916 * @global object
917 * @param mixed $record record object or id
8429163d 918 * @return bool
919 */
920function data_isowner($record) {
9c00b5d7 921 global $USER, $DB;
3d4b223a 922
4f0c2d00 923 if (!isloggedin()) { // perf shortcut
3d4b223a 924 return false;
925 }
926
8429163d 927 if (!is_object($record)) {
928 if (!$record = $DB->get_record('data_records', array('id'=>$record))) {
929 return false;
930 }
3d4b223a 931 }
932
8429163d 933 return ($record->userid == $USER->id);
3d4b223a 934}
935
4636bf83 936/**
937 * has a user reached the max number of entries?
938 *
939 * @param object $data
940 * @return bool
941 */
b572ce19 942function data_atmaxentries($data){
943 if (!$data->maxentries){
3d4b223a 944 return false;
b572ce19 945
3d4b223a 946 } else {
947 return (data_numentries($data) >= $data->maxentries);
948 }
949}
950
4636bf83 951/**
952 * returns the number of entries already made by this user
56c1ca88 953 *
4636bf83 954 * @global object
955 * @global object
56c1ca88 956 * @param object $data
4636bf83 957 * @return int
958 */
f9729dcf 959function data_numentries($data, $userid=null) {
8429163d 960 global $USER, $DB;
f9729dcf
MG
961 if ($userid === null) {
962 $userid = $USER->id;
963 }
9c00b5d7 964 $sql = 'SELECT COUNT(*) FROM {data_records} WHERE dataid=? AND userid=?';
f9729dcf 965 return $DB->count_records_sql($sql, array($data->id, $userid));
3d4b223a 966}
967
4636bf83 968/**
56c1ca88 969 * function that takes in a dataid and adds a record
4636bf83 970 * this is used everytime an add template is submitted
971 *
972 * @global object
973 * @global object
974 * @param object $data
975 * @param int $groupid
976 * @return bool
977 */
0997e51a 978function data_add_record($data, $groupid=0){
9c00b5d7 979 global $USER, $DB;
6403e679 980
c088d603 981 $cm = get_coursemodule_from_instance('data', $data->id);
0b3b8c30 982 $context = context_module::instance($cm->id);
b572ce19 983
39790bd8 984 $record = new stdClass();
3d4b223a 985 $record->userid = $USER->id;
0997e51a 986 $record->dataid = $data->id;
3d4b223a 987 $record->groupid = $groupid;
0997e51a 988 $record->timecreated = $record->timemodified = time();
0468976c 989 if (has_capability('mod/data:approve', $context)) {
6e0119dd 990 $record->approved = 1;
991 } else {
992 $record->approved = 0;
993 }
76ca452c
MN
994 $record->id = $DB->insert_record('data_records', $record);
995
996 // Trigger an event for creating this record.
997 $event = \mod_data\event\record_created::create(array(
998 'objectid' => $record->id,
999 'context' => $context,
1000 'other' => array(
1001 'dataid' => $data->id
1002 )
1003 ));
1004 $event->trigger();
1005
f9729dcf 1006 $course = get_course($cm->course);
cf873ada 1007 data_update_completion_state($data, $course, $cm);
f9729dcf 1008
76ca452c 1009 return $record->id;
3d4b223a 1010}
1011
4636bf83 1012/**
1013 * check the multple existence any tag in a template
1014 *
1015 * check to see if there are 2 or more of the same tag being used.
1016 *
1017 * @global object
1018 * @param int $dataid,
56c1ca88 1019 * @param string $template
4636bf83 1020 * @return bool
1021 */
9c00b5d7 1022function data_tags_check($dataid, $template) {
4102b449 1023 global $DB, $OUTPUT;
9c00b5d7 1024
b8b554ac 1025 // first get all the possible tags
9c00b5d7 1026 $fields = $DB->get_records('data_fields', array('dataid'=>$dataid));
b8b554ac 1027 // then we generate strings to replace
1028 $tagsok = true; // let's be optimistic
b572ce19 1029 foreach ($fields as $field){
546a58bc 1030 $pattern="/\[\[" . preg_quote($field->name, '/') . "\]\]/i";
b572ce19 1031 if (preg_match_all($pattern, $template, $dummy)>1){
3d4b223a 1032 $tagsok = false;
4102b449 1033 echo $OUTPUT->notification('[['.$field->name.']] - '.get_string('multipletags','data'));
3d4b223a 1034 }
1035 }
b8b554ac 1036 // else return true
3d4b223a 1037 return $tagsok;
1038}
1039
4636bf83 1040/**
1041 * Adds an instance of a data
1042 *
6b04fdc0
PS
1043 * @param stdClass $data
1044 * @param mod_data_mod_form $mform
1045 * @return int intance id
4636bf83 1046 */
6b04fdc0 1047function data_add_instance($data, $mform = null) {
87d6e85a
SB
1048 global $DB, $CFG;
1049 require_once($CFG->dirroot.'/mod/data/locallib.php');
3d4b223a 1050
57244db3 1051 if (empty($data->assessed)) {
1052 $data->assessed = 0;
d6af3cfa 1053 }
1054
f3013ba6
AG
1055 if (empty($data->ratingtime) || empty($data->assessed)) {
1056 $data->assesstimestart = 0;
1057 $data->assesstimefinish = 0;
1058 }
1059
3d4b223a 1060 $data->timemodified = time();
1061
a8f3a651 1062 $data->id = $DB->insert_record('data', $data);
3d4b223a 1063
87d6e85a
SB
1064 // Add calendar events if necessary.
1065 data_set_events($data);
9ffbdafc
AG
1066 if (!empty($data->completionexpected)) {
1067 \core_completion\api::update_completion_date_event($data->coursemodule, 'data', $data->id, $data->completionexpected);
1068 }
87d6e85a 1069
612607bd 1070 data_grade_item_update($data);
b572ce19 1071
3d4b223a 1072 return $data->id;
1073}
1074
4636bf83 1075/**
1076 * updates an instance of a data
1077 *
1078 * @global object
1079 * @param object $data
1080 * @return bool
1081 */
3d4b223a 1082function data_update_instance($data) {
87d6e85a
SB
1083 global $DB, $CFG;
1084 require_once($CFG->dirroot.'/mod/data/locallib.php');
6403e679 1085
04366d79 1086 $data->timemodified = time();
b572ce19 1087 $data->id = $data->instance;
6403e679 1088
57244db3 1089 if (empty($data->assessed)) {
1090 $data->assessed = 0;
17e5f3fc 1091 }
b572ce19 1092
d251b259
AD
1093 if (empty($data->ratingtime) or empty($data->assessed)) {
1094 $data->assesstimestart = 0;
1095 $data->assesstimefinish = 0;
1096 }
1097
05ac14ca 1098 if (empty($data->notification)) {
1099 $data->notification = 0;
1100 }
1101
0bcf8b6f 1102 $DB->update_record('data', $data);
04366d79 1103
87d6e85a
SB
1104 // Add calendar events if necessary.
1105 data_set_events($data);
9ffbdafc
AG
1106 $completionexpected = (!empty($data->completionexpected)) ? $data->completionexpected : null;
1107 \core_completion\api::update_completion_date_event($data->coursemodule, 'data', $data->id, $completionexpected);
87d6e85a 1108
04366d79 1109 data_grade_item_update($data);
b572ce19 1110
04366d79 1111 return true;
b572ce19 1112
3d4b223a 1113}
1114
4636bf83 1115/**
1116 * deletes an instance of a data
1117 *
1118 * @global object
1119 * @param int $id
1120 * @return bool
1121 */
b8b554ac 1122function data_delete_instance($id) { // takes the dataid
650a0c0a 1123 global $DB, $CFG;
3d4b223a 1124
8429163d 1125 if (!$data = $DB->get_record('data', array('id'=>$id))) {
3d4b223a 1126 return false;
1127 }
1128
8429163d 1129 $cm = get_coursemodule_from_instance('data', $data->id);
0b3b8c30 1130 $context = context_module::instance($cm->id);
b572ce19 1131
8429163d 1132/// Delete all the associated information
6403e679 1133
8429163d 1134 // files
1135 $fs = get_file_storage();
64f93798 1136 $fs->delete_area_files($context->id, 'mod_data');
3d4b223a 1137
8429163d 1138 // get all the records in this data
1139 $sql = "SELECT r.id
1140 FROM {data_records} r
1141 WHERE r.dataid = ?";
6403e679 1142
8429163d 1143 $DB->delete_records_select('data_content', "recordid IN ($sql)", array($id));
3d4b223a 1144
1145 // delete all the records and fields
c18269c7 1146 $DB->delete_records('data_records', array('dataid'=>$id));
1147 $DB->delete_records('data_fields', array('dataid'=>$id));
3d4b223a 1148
87d6e85a
SB
1149 // Remove old calendar events.
1150 $events = $DB->get_records('event', array('modulename' => 'data', 'instance' => $id));
1151 foreach ($events as $event) {
1152 $event = calendar_event::load($event);
1153 $event->delete();
1154 }
1155
8429163d 1156 // cleanup gradebook
b82cacea 1157 data_grade_item_delete($data);
b572ce19 1158
40fe1538
DW
1159 // Delete the instance itself
1160 // We must delete the module record after we delete the grade item.
1161 $result = $DB->delete_records('data', array('id'=>$id));
1162
04366d79 1163 return $result;
3d4b223a 1164}
1165
4636bf83 1166/**
1167 * returns a summary of data activity of this user
1168 *
1169 * @global object
1170 * @param object $course
1171 * @param object $user
1172 * @param object $mod
1173 * @param object $data
1174 * @return object|null
1175 */
3d4b223a 1176function data_user_outline($course, $user, $mod, $data) {
1a96363a
NC
1177 global $DB, $CFG;
1178 require_once("$CFG->libdir/gradelib.php");
1179
1180 $grades = grade_get_grades($course->id, 'mod', 'data', $data->id, $user->id);
1181 if (empty($grades->items[0]->grades)) {
1182 $grade = false;
1183 } else {
1184 $grade = reset($grades->items[0]->grades);
1185 }
1186
9c00b5d7 1187
1188 if ($countrecords = $DB->count_records('data_records', array('dataid'=>$data->id, 'userid'=>$user->id))) {
39790bd8 1189 $result = new stdClass();
63701c78 1190 $result->info = get_string('numrecords', 'data', $countrecords);
9c00b5d7 1191 $lastrecord = $DB->get_record_sql('SELECT id,timemodified FROM {data_records}
1192 WHERE dataid = ? AND userid = ?
1193 ORDER BY timemodified DESC', array($data->id, $user->id), true);
3d4b223a 1194 $result->time = $lastrecord->timemodified;
1a96363a 1195 if ($grade) {
f5d1dbb3
MF
1196 if (!$grade->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
1197 $result->info .= ', ' . get_string('grade') . ': ' . $grade->str_long_grade;
1198 } else {
1199 $result->info = get_string('grade') . ': ' . get_string('hidden', 'grades');
1200 }
1a96363a
NC
1201 }
1202 return $result;
1203 } else if ($grade) {
4bb39eab
AN
1204 $result = (object) [
1205 'time' => grade_get_date_for_user_grade($grade, $user),
1206 ];
f5d1dbb3
MF
1207 if (!$grade->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
1208 $result->info = get_string('grade') . ': ' . $grade->str_long_grade;
1209 } else {
1210 $result->info = get_string('grade') . ': ' . get_string('hidden', 'grades');
1211 }
4433f871 1212
3d4b223a 1213 return $result;
1214 }
1215 return NULL;
3d4b223a 1216}
1217
4636bf83 1218/**
1219 * Prints all the records uploaded by this user
1220 *
1221 * @global object
1222 * @param object $course
1223 * @param object $user
1224 * @param object $mod
1225 * @param object $data
1226 */
3d4b223a 1227function data_user_complete($course, $user, $mod, $data) {
1a96363a
NC
1228 global $DB, $CFG, $OUTPUT;
1229 require_once("$CFG->libdir/gradelib.php");
1230
1231 $grades = grade_get_grades($course->id, 'mod', 'data', $data->id, $user->id);
1232 if (!empty($grades->items[0]->grades)) {
1233 $grade = reset($grades->items[0]->grades);
f5d1dbb3
MF
1234 if (!$grade->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
1235 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
1236 if ($grade->str_feedback) {
1237 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
1238 }
1239 } else {
1240 echo $OUTPUT->container(get_string('grade') . ': ' . get_string('hidden', 'grades'));
1a96363a
NC
1241 }
1242 }
9c00b5d7 1243
1244 if ($records = $DB->get_records('data_records', array('dataid'=>$data->id,'userid'=>$user->id), 'timemodified DESC')) {
3d45b8e5 1245 data_print_template('singletemplate', $records, $data);
3d4b223a 1246 }
1247}
1248
04366d79 1249/**
1250 * Return grade for given user or all users.
1251 *
4636bf83 1252 * @global object
1253 * @param object $data
04366d79 1254 * @param int $userid optional user id, 0 means all users
1255 * @return array array of grades, false if none
1256 */
612607bd 1257function data_get_user_grades($data, $userid=0) {
d251b259
AD
1258 global $CFG;
1259
1260 require_once($CFG->dirroot.'/rating/lib.php');
04366d79 1261
2b04c41c
SH
1262 $ratingoptions = new stdClass;
1263 $ratingoptions->component = 'mod_data';
1264 $ratingoptions->ratingarea = 'entry';
d251b259
AD
1265 $ratingoptions->modulename = 'data';
1266 $ratingoptions->moduleid = $data->id;
04366d79 1267
d251b259
AD
1268 $ratingoptions->userid = $userid;
1269 $ratingoptions->aggregationmethod = $data->assessed;
1270 $ratingoptions->scaleid = $data->scale;
1271 $ratingoptions->itemtable = 'data_records';
1272 $ratingoptions->itemtableusercolumn = 'userid';
04366d79 1273
2b04c41c 1274 $rm = new rating_manager();
d251b259 1275 return $rm->get_user_grades($ratingoptions);
04366d79 1276}
1277
1278/**
775f811a 1279 * Update activity grades
04366d79 1280 *
a153c9f2 1281 * @category grade
775f811a 1282 * @param object $data
1283 * @param int $userid specific user only, 0 means all
4636bf83 1284 * @param bool $nullifnone
04366d79 1285 */
775f811a 1286function data_update_grades($data, $userid=0, $nullifnone=true) {
9c00b5d7 1287 global $CFG, $DB;
1288 require_once($CFG->libdir.'/gradelib.php');
04366d79 1289
775f811a 1290 if (!$data->assessed) {
1291 data_grade_item_update($data);
b572ce19 1292
775f811a 1293 } else if ($grades = data_get_user_grades($data, $userid)) {
1294 data_grade_item_update($data, $grades);
b572ce19 1295
775f811a 1296 } else if ($userid and $nullifnone) {
39790bd8 1297 $grade = new stdClass();
775f811a 1298 $grade->userid = $userid;
1299 $grade->rawgrade = NULL;
1300 data_grade_item_update($data, $grade);
b572ce19 1301
04366d79 1302 } else {
775f811a 1303 data_grade_item_update($data);
1304 }
1305}
1306
04366d79 1307/**
612607bd 1308 * Update/create grade item for given data
04366d79 1309 *
a153c9f2
AD
1310 * @category grade
1311 * @param stdClass $data A database instance with extra cmidnumber property
1312 * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
04366d79 1313 * @return object grade_item
1314 */
0b5a80a1 1315function data_grade_item_update($data, $grades=NULL) {
612607bd 1316 global $CFG;
9c00b5d7 1317 require_once($CFG->libdir.'/gradelib.php');
04366d79 1318
13534ef7 1319 $params = array('itemname'=>$data->name, 'idnumber'=>$data->cmidnumber);
b572ce19 1320
04366d79 1321 if (!$data->assessed or $data->scale == 0) {
612607bd 1322 $params['gradetype'] = GRADE_TYPE_NONE;
b572ce19 1323
04366d79 1324 } else if ($data->scale > 0) {
1325 $params['gradetype'] = GRADE_TYPE_VALUE;
1326 $params['grademax'] = $data->scale;
1327 $params['grademin'] = 0;
b572ce19 1328
04366d79 1329 } else if ($data->scale < 0) {
1330 $params['gradetype'] = GRADE_TYPE_SCALE;
1331 $params['scaleid'] = -$data->scale;
1332 }
b572ce19 1333
0b5a80a1 1334 if ($grades === 'reset') {
1335 $params['reset'] = true;
1336 $grades = NULL;
1337 }
1338
1339 return grade_update('mod/data', $data->course, 'mod', 'data', $data->id, 0, $grades, $params);
04366d79 1340}
1341
1342/**
1343 * Delete grade item for given data
1344 *
a153c9f2 1345 * @category grade
04366d79 1346 * @param object $data object
1347 * @return object grade_item
1348 */
1349function data_grade_item_delete($data) {
612607bd 1350 global $CFG;
1351 require_once($CFG->libdir.'/gradelib.php');
b572ce19 1352
b67ec72f 1353 return grade_update('mod/data', $data->course, 'mod', 'data', $data->id, 0, NULL, array('deleted'=>1));
04366d79 1354}
1355
b8b554ac 1356// junk functions
4636bf83 1357/**
56c1ca88 1358 * takes a list of records, the current data, a search string,
4636bf83 1359 * and mode to display prints the translated template
1360 *
1361 * @global object
1362 * @global object
1363 * @param string $template
56c1ca88 1364 * @param array $records
4636bf83 1365 * @param object $data
56c1ca88 1366 * @param string $search
4636bf83 1367 * @param int $page
1368 * @param bool $return
f09040d7 1369 * @param object $jumpurl a moodle_url by which to jump back to the record list (can be null)
4636bf83 1370 * @return mixed
1371 */
f09040d7 1372function data_print_template($template, $records, $data, $search='', $page=0, $return=false, moodle_url $jumpurl=null) {
f2a1963c 1373 global $CFG, $DB, $OUTPUT;
cf9ecfda 1374
c088d603 1375 $cm = get_coursemodule_from_instance('data', $data->id);
0b3b8c30 1376 $context = context_module::instance($cm->id);
b572ce19 1377
2c216a6c
MN
1378 static $fields = array();
1379 static $dataid = null;
b572ce19 1380
63701c78 1381 if (empty($dataid)) {
1382 $dataid = $data->id;
1383 } else if ($dataid != $data->id) {
2c216a6c 1384 $fields = array();
63701c78 1385 }
b572ce19 1386
3d45b8e5 1387 if (empty($fields)) {
9c00b5d7 1388 $fieldrecords = $DB->get_records('data_fields', array('dataid'=>$data->id));
3d45b8e5 1389 foreach ($fieldrecords as $fieldrecord) {
1390 $fields[]= data_get_field($fieldrecord, $data);
1391 }
3d45b8e5 1392 }
b572ce19 1393
64452eb4 1394 if (empty($records)) {
1395 return;
1396 }
b572ce19 1397
f09040d7
HB
1398 if (!$jumpurl) {
1399 $jumpurl = new moodle_url('/mod/data/view.php', array('d' => $data->id));
1400 }
1401 $jumpurl = new moodle_url($jumpurl, array('page' => $page, 'sesskey' => sesskey()));
1402
668fc89a 1403 foreach ($records as $record) { // Might be just one for the single template
b572ce19 1404
b8b554ac 1405 // Replacing tags
3d4b223a 1406 $patterns = array();
1407 $replacement = array();
b572ce19 1408
b8b554ac 1409 // Then we generate strings to replace for normal tags
3d45b8e5 1410 foreach ($fields as $field) {
f2584d0e 1411 $patterns[]='[['.$field->field->name.']]';
d118d06a 1412 $replacement[] = highlight($search, $field->display_browse_field($record->id, $template));
3d4b223a 1413 }
b572ce19 1414
cf9ecfda
AG
1415 $canmanageentries = has_capability('mod/data:manageentries', $context);
1416
b8b554ac 1417 // Replacing special tags (##Edit##, ##Delete##, ##More##)
e357c206 1418 $patterns[]='##edit##';
1419 $patterns[]='##delete##';
97fe80ad 1420 if (data_user_can_manage_entry($record, $data, $context)) {
64452eb4 1421 $replacement[] = '<a href="'.$CFG->wwwroot.'/mod/data/edit.php?d='
663640f5
DW
1422 .$data->id.'&amp;rid='.$record->id.'&amp;sesskey='.sesskey().'">' .
1423 $OUTPUT->pix_icon('t/edit', get_string('edit')) . '</a>';
3d4b223a 1424 $replacement[] = '<a href="'.$CFG->wwwroot.'/mod/data/view.php?d='
663640f5
DW
1425 .$data->id.'&amp;delete='.$record->id.'&amp;sesskey='.sesskey().'">' .
1426 $OUTPUT->pix_icon('t/delete', get_string('delete')) . '</a>';
046dd7dc 1427 } else {
3d4b223a 1428 $replacement[] = '';
eeeb4f2a 1429 $replacement[] = '';
3d4b223a 1430 }
d53e5129 1431
1432 $moreurl = $CFG->wwwroot . '/mod/data/view.php?d=' . $data->id . '&amp;rid=' . $record->id;
32d799c6 1433 if ($search) {
1434 $moreurl .= '&amp;filter=1';
1435 }
e357c206 1436 $patterns[]='##more##';
663640f5 1437 $replacement[] = '<a href="'.$moreurl.'">' . $OUTPUT->pix_icon('t/preview', get_string('more', 'data')) . '</a>';
d53e5129 1438
e357c206 1439 $patterns[]='##moreurl##';
d53e5129 1440 $replacement[] = $moreurl;
473dd288 1441
cf9ecfda
AG
1442 $patterns[]='##delcheck##';
1443 if ($canmanageentries) {
e274f1b2
JP
1444 $checkbox = new \core\output\checkbox_toggleall('listview-entries', false, [
1445 'id' => "entry_{$record->id}",
1446 'name' => 'delcheck[]',
4f71255e 1447 'classes' => 'recordcheckbox',
e274f1b2
JP
1448 'value' => $record->id,
1449 ]);
1450 $replacement[] = $OUTPUT->render($checkbox);
cf9ecfda
AG
1451 } else {
1452 $replacement[] = '';
1453 }
1454
e357c206 1455 $patterns[]='##user##';
64452eb4 1456 $replacement[] = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$record->userid.
1457 '&amp;course='.$data->course.'">'.fullname($record).'</a>';
8185aeb6 1458
560237b4 1459 $patterns[] = '##userpicture##';
c910cf30 1460 $ruser = user_picture::unalias($record, null, 'userid');
80771075
JL
1461 // If the record didn't come with user data, retrieve the user from database.
1462 if (!isset($ruser->picture)) {
1463 $ruser = core_user::get_user($record->userid);
1464 }
c910cf30 1465 $replacement[] = $OUTPUT->user_picture($ruser, array('courseid' => $data->course));
560237b4 1466
8185aeb6 1467 $patterns[]='##export##';
1468
6708a1f5 1469 if (!empty($CFG->enableportfolios) && ($template == 'singletemplate' || $template == 'listtemplate')
8185aeb6 1470 && ((has_capability('mod/data:exportentry', $context)
1471 || (data_isowner($record->id) && has_capability('mod/data:exportownentry', $context))))) {
24ba58ee 1472 require_once($CFG->libdir . '/portfoliolib.php');
0d06b6fd 1473 $button = new portfolio_add_button();
37743241 1474 $button->set_callback_options('data_portfolio_caller', array('id' => $cm->id, 'recordid' => $record->id), 'mod_data');
6be1dcae 1475 list($formats, $files) = data_portfolio_caller::formats($fields, $record);
276378e6 1476 $button->set_formats($formats);
0d06b6fd 1477 $replacement[] = $button->to_html(PORTFOLIO_ADD_ICON_LINK);
8185aeb6 1478 } else {
1479 $replacement[] = '';
1480 }
8429163d 1481
c95034f2 1482 $patterns[] = '##timeadded##';
8429163d 1483 $replacement[] = userdate($record->timecreated);
c95034f2 1484
1485 $patterns[] = '##timemodified##';
35e129c1 1486 $replacement [] = userdate($record->timemodified);
473dd288 1487
e357c206 1488 $patterns[]='##approve##';
851d3b7a 1489 if (has_capability('mod/data:approve', $context) && ($data->approval) && (!$record->approved)) {
f09040d7 1490 $approveurl = new moodle_url($jumpurl, array('approve' => $record->id));
d0372ed6 1491 $approveicon = new pix_icon('t/approve', get_string('approve', 'data'), '', array('class' => 'iconsmall'));
851d3b7a
FM
1492 $replacement[] = html_writer::tag('span', $OUTPUT->action_icon($approveurl, $approveicon),
1493 array('class' => 'approve'));
473dd288 1494 } else {
6e0119dd 1495 $replacement[] = '';
1496 }
6403e679 1497
d0372ed6
HB
1498 $patterns[]='##disapprove##';
1499 if (has_capability('mod/data:approve', $context) && ($data->approval) && ($record->approved)) {
f09040d7 1500 $disapproveurl = new moodle_url($jumpurl, array('disapprove' => $record->id));
d0372ed6
HB
1501 $disapproveicon = new pix_icon('t/block', get_string('disapprove', 'data'), '', array('class' => 'iconsmall'));
1502 $replacement[] = html_writer::tag('span', $OUTPUT->action_icon($disapproveurl, $disapproveicon),
1503 array('class' => 'disapprove'));
1504 } else {
1505 $replacement[] = '';
1506 }
1507
0bec64c6 1508 $patterns[] = '##approvalstatus##';
2ddd7605 1509 $patterns[] = '##approvalstatusclass##';
0bec64c6
HB
1510 if (!$data->approval) {
1511 $replacement[] = '';
2ddd7605 1512 $replacement[] = '';
0bec64c6 1513 } else if ($record->approved) {
d58f3a4d 1514 $replacement[] = get_string('approved', 'data');
2ddd7605 1515 $replacement[] = 'approved';
0bec64c6 1516 } else {
d58f3a4d 1517 $replacement[] = get_string('notapproved', 'data');
2ddd7605 1518 $replacement[] = 'notapproved';
0bec64c6
HB
1519 }
1520
e357c206 1521 $patterns[]='##comments##';
4d3d87f0 1522 if (($template == 'listtemplate') && ($data->comments)) {
e998effa
DC
1523
1524 if (!empty($CFG->usecomments)) {
36051c9e 1525 require_once($CFG->dirroot . '/comment/lib.php');
866354a9 1526 list($context, $course, $cm) = get_context_info_array($context->id);
6bdfef5d 1527 $cmt = new stdClass();
e998effa 1528 $cmt->context = $context;
866354a9
DC
1529 $cmt->course = $course;
1530 $cmt->cm = $cm;
1531 $cmt->area = 'database_entry';
e998effa
DC
1532 $cmt->itemid = $record->id;
1533 $cmt->showcount = true;
d846488e 1534 $cmt->component = 'mod_data';
e998effa 1535 $comment = new comment($cmt);
36051c9e 1536 $replacement[] = $comment->output(true);
e998effa 1537 }
4d3d87f0 1538 } else {
1539 $replacement[] = '';
1540 }
6e0119dd 1541
ca5f3e0a
AH
1542 if (core_tag_tag::is_enabled('mod_data', 'data_records')) {
1543 $patterns[] = "##tags##";
1544 $replacement[] = $OUTPUT->tag_list(
1545 core_tag_tag::get_item_tags('mod_data', 'data_records', $record->id), '', 'data-tags');
1546 }
1547
b8b554ac 1548 // actual replacement of the tags
f2584d0e 1549 $newtext = str_ireplace($patterns, $replacement, $data->{$template});
5023c3ab 1550
b8b554ac 1551 // no more html formatting and filtering - see MDL-6635
aa3b20e9 1552 if ($return) {
1553 return $newtext;
1554 } else {
1555 echo $newtext;
b572ce19 1556
aa3b20e9 1557 // hack alert - return is always false in singletemplate anyway ;-)
1558 /**********************************
1559 * Printing Ratings Form *
1560 *********************************/
1561 if ($template == 'singletemplate') { //prints ratings options
1562 data_print_ratings($data, $record);
1563 }
b572ce19 1564
aa3b20e9 1565 /**********************************
d251b259 1566 * Printing Comments Form *
aa3b20e9 1567 *********************************/
d251b259 1568 if (($template == 'singletemplate') && ($data->comments)) {
e998effa 1569 if (!empty($CFG->usecomments)) {
36051c9e 1570 require_once($CFG->dirroot . '/comment/lib.php');
866354a9 1571 list($context, $course, $cm) = get_context_info_array($context->id);
6bdfef5d 1572 $cmt = new stdClass();
e998effa 1573 $cmt->context = $context;
866354a9
DC
1574 $cmt->course = $course;
1575 $cmt->cm = $cm;
1576 $cmt->area = 'database_entry';
e998effa
DC
1577 $cmt->itemid = $record->id;
1578 $cmt->showcount = true;
d846488e 1579 $cmt->component = 'mod_data';
e998effa 1580 $comment = new comment($cmt);
36051c9e 1581 $comment->output(false);
e998effa 1582 }
aa3b20e9 1583 }
4d3d87f0 1584 }
3d4b223a 1585 }
1586}
1587
d251b259
AD
1588/**
1589 * Return rating related permissions
2b04c41c
SH
1590 *
1591 * @param string $contextid the context id
1592 * @param string $component the component to get rating permissions for
1593 * @param string $ratingarea the rating area to get permissions for
d251b259
AD
1594 * @return array an associative array of the user's rating permissions
1595 */
2b04c41c 1596function data_rating_permissions($contextid, $component, $ratingarea) {
d197ea43 1597 $context = context::instance_by_id($contextid, MUST_EXIST);
2b04c41c 1598 if ($component != 'mod_data' || $ratingarea != 'entry') {
d251b259 1599 return null;
d251b259 1600 }
2b04c41c
SH
1601 return array(
1602 'view' => has_capability('mod/data:viewrating',$context),
1603 'viewany' => has_capability('mod/data:viewanyrating',$context),
1604 'viewall' => has_capability('mod/data:viewallratings',$context),
1605 'rate' => has_capability('mod/data:rate',$context)
1606 );
d251b259
AD
1607}
1608
aeafd436 1609/**
2c2ff8d5
AD
1610 * Validates a submitted rating
1611 * @param array $params submitted data
1612 * context => object the context in which the rated items exists [required]
1613 * itemid => int the ID of the object being rated
1614 * scaleid => int the scale from which the user can select a rating. Used for bounds checking. [required]
1615 * rating => int the submitted rating
1616 * rateduserid => int the id of the user whose items have been rated. NOT the user who submitted the ratings. 0 to update all. [required]
1617 * aggregation => int the aggregation method to apply when calculating grades ie RATING_AGGREGATE_AVERAGE [required]
778361c3 1618 * @return boolean true if the rating is valid. Will throw rating_exception if not
aeafd436 1619 */
778361c3 1620function data_rating_validate($params) {
2c2ff8d5
AD
1621 global $DB, $USER;
1622
2b04c41c
SH
1623 // Check the component is mod_data
1624 if ($params['component'] != 'mod_data') {
1625 throw new rating_exception('invalidcomponent');
2c2ff8d5
AD
1626 }
1627
2b04c41c
SH
1628 // Check the ratingarea is entry (the only rating area in data module)
1629 if ($params['ratingarea'] != 'entry') {
1630 throw new rating_exception('invalidratingarea');
1631 }
1632
1633 // Check the rateduserid is not the current user .. you can't rate your own entries
1634 if ($params['rateduserid'] == $USER->id) {
1635 throw new rating_exception('nopermissiontorate');
1636 }
1637
1638 $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
2c2ff8d5
AD
1639 FROM {data_records} r
1640 JOIN {data} d ON r.dataid = d.id
1641 WHERE r.id = :itemid";
1642 $dataparams = array('itemid'=>$params['itemid']);
1643 if (!$info = $DB->get_record_sql($datasql, $dataparams)) {
778361c3
AD
1644 //item doesn't exist
1645 throw new rating_exception('invaliditemid');
2c2ff8d5
AD
1646 }
1647
6ac149dc
AD
1648 if ($info->scale != $params['scaleid']) {
1649 //the scale being submitted doesnt match the one in the database
1650 throw new rating_exception('invalidscaleid');
1651 }
1652
6ac149dc 1653 //check that the submitted rating is valid for the scale
5693d56c
EL
1654
1655 // lower limit
1656 if ($params['rating'] < 0 && $params['rating'] != RATING_UNSET_RATING) {
6ac149dc 1657 throw new rating_exception('invalidnum');
5693d56c
EL
1658 }
1659
1660 // upper limit
1661 if ($info->scale < 0) {
6ac149dc 1662 //its a custom scale
2b04c41c 1663 $scalerecord = $DB->get_record('scale', array('id' => -$info->scale));
6ac149dc
AD
1664 if ($scalerecord) {
1665 $scalearray = explode(',', $scalerecord->scale);
1666 if ($params['rating'] > count($scalearray)) {
1667 throw new rating_exception('invalidnum');
1668 }
1669 } else {
1670 throw new rating_exception('invalidscaleid');
1671 }
1672 } else if ($params['rating'] > $info->scale) {
1673 //if its numeric and submitted rating is above maximum
1674 throw new rating_exception('invalidnum');
1675 }
1676
2c2ff8d5
AD
1677 if ($info->approval && !$info->approved) {
1678 //database requires approval but this item isnt approved
778361c3 1679 throw new rating_exception('nopermissiontorate');
2c2ff8d5
AD
1680 }
1681
2b04c41c 1682 // check the item we're rating was created in the assessable time window
2c2ff8d5
AD
1683 if (!empty($info->assesstimestart) && !empty($info->assesstimefinish)) {
1684 if ($info->timecreated < $info->assesstimestart || $info->timecreated > $info->assesstimefinish) {
778361c3 1685 throw new rating_exception('notavailable');
2c2ff8d5
AD
1686 }
1687 }
1688
74df2951 1689 $course = $DB->get_record('course', array('id'=>$info->course), '*', MUST_EXIST);
2b04c41c 1690 $cm = get_coursemodule_from_instance('data', $info->dataid, $course->id, false, MUST_EXIST);
0b3b8c30 1691 $context = context_module::instance($cm->id);
2c2ff8d5 1692
2b04c41c
SH
1693 // if the supplied context doesnt match the item's context
1694 if ($context->id != $params['context']->id) {
778361c3 1695 throw new rating_exception('invalidcontext');
2c2ff8d5
AD
1696 }
1697
1698 // Make sure groups allow this user to see the item they're rating
2b04c41c 1699 $groupid = $info->groupid;
2c2ff8d5
AD
1700 if ($groupid > 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) { // Groups are being used
1701 if (!groups_group_exists($groupid)) { // Can't find group
778361c3 1702 throw new rating_exception('cannotfindgroup');//something is wrong
2c2ff8d5
AD
1703 }
1704
1705 if (!groups_is_member($groupid) and !has_capability('moodle/site:accessallgroups', $context)) {
1706 // do not allow rating of posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS
778361c3 1707 throw new rating_exception('notmemberofgroup');
2c2ff8d5
AD
1708 }
1709 }
1710
1711 return true;
aeafd436
AD
1712}
1713
731c2712
AA
1714/**
1715 * Can the current user see ratings for a given itemid?
1716 *
1717 * @param array $params submitted data
1718 * contextid => int contextid [required]
1719 * component => The component for this module - should always be mod_data [required]
1720 * ratingarea => object the context in which the rated items exists [required]
1721 * itemid => int the ID of the object being rated [required]
1722 * scaleid => int scale id [optional]
1723 * @return bool
1724 * @throws coding_exception
1725 * @throws rating_exception
1726 */
1727function mod_data_rating_can_see_item_ratings($params) {
1728 global $DB;
1729
1730 // Check the component is mod_data.
1731 if (!isset($params['component']) || $params['component'] != 'mod_data') {
1732 throw new rating_exception('invalidcomponent');
1733 }
1734
1735 // Check the ratingarea is entry (the only rating area in data).
1736 if (!isset($params['ratingarea']) || $params['ratingarea'] != 'entry') {
1737 throw new rating_exception('invalidratingarea');
1738 }
1739
1740 if (!isset($params['itemid'])) {
1741 throw new rating_exception('invaliditemid');
1742 }
1743
1744 $datasql = "SELECT d.id as dataid, d.course, r.groupid
1745 FROM {data_records} r
1746 JOIN {data} d ON r.dataid = d.id
1747 WHERE r.id = :itemid";
1748 $dataparams = array('itemid' => $params['itemid']);
1749 if (!$info = $DB->get_record_sql($datasql, $dataparams)) {
1750 // Item doesn't exist.
1751 throw new rating_exception('invaliditemid');
1752 }
1753
ca3e8022
AG
1754 // User can see ratings of all participants.
1755 if ($info->groupid == 0) {
1756 return true;
1757 }
1758
731c2712
AA
1759 $course = $DB->get_record('course', array('id' => $info->course), '*', MUST_EXIST);
1760 $cm = get_coursemodule_from_instance('data', $info->dataid, $course->id, false, MUST_EXIST);
1761
1762 // Make sure groups allow this user to see the item they're rating.
1763 return groups_group_visible($info->groupid, $course, $cm);
1764}
1765
a593aeee 1766
4636bf83 1767/**
56c1ca88 1768 * function that takes in the current data, number of items per page,
1769 * a search string and prints a preference box in view.php
1770 *
1771 * This preference box prints a searchable advanced search template if
1772 * a) A template is defined
1773 * b) The advanced search checkbox is checked.
4636bf83 1774 *
1775 * @global object
1776 * @global object
56c1ca88 1777 * @param object $data
1778 * @param int $perpage
4636bf83 1779 * @param string $search
1780 * @param string $sort
1781 * @param string $order
1782 * @param array $search_array
1783 * @param int $advanced
1784 * @param string $mode
1785 * @return void
1786 */
7900ecb0 1787function data_print_preference_form($data, $perpage, $search, $sort='', $order='ASC', $search_array = '', $advanced = 0, $mode= ''){
601104f2 1788 global $CFG, $DB, $PAGE, $OUTPUT;
8429163d 1789
7900ecb0 1790 $cm = get_coursemodule_from_instance('data', $data->id);
0b3b8c30 1791 $context = context_module::instance($cm->id);
7900ecb0 1792 echo '<br /><div class="datapreferences">';
b7dc2256 1793 echo '<form id="options" action="view.php" method="get">';
7900ecb0 1794 echo '<div>';
473dd288 1795 echo '<input type="hidden" name="d" value="'.$data->id.'" />';
7900ecb0 1796 if ($mode =='asearch') {
1797 $advanced = 1;
1798 echo '<input type="hidden" name="mode" value="list" />';
1799 }
a032a460 1800 echo '<label for="pref_perpage">'.get_string('pagesize','data').'</label> ';
76a2fd82 1801 $pagesizes = array(2=>2,3=>3,4=>4,5=>5,6=>6,7=>7,8=>8,9=>9,10=>10,15=>15,
6e0119dd 1802 20=>20,30=>30,40=>40,50=>50,100=>100,200=>200,300=>300,400=>400,500=>500,1000=>1000);
398be7c8 1803 echo html_writer::select($pagesizes, 'perpage', $perpage, false, array('id' => 'pref_perpage', 'class' => 'custom-select'));
0d284a8b 1804
7900ecb0 1805 if ($advanced) {
0d284a8b
DM
1806 $regsearchclass = 'search_none';
1807 $advancedsearchclass = 'search_inline';
1808 } else {
1809 $regsearchclass = 'search_inline';
1810 $advancedsearchclass = 'search_none';
7900ecb0 1811 }
e85fda95 1812 echo '<div id="reg_search" class="' . $regsearchclass . ' form-inline" >&nbsp;&nbsp;&nbsp;';
398be7c8
DW
1813 echo '<label for="pref_search">' . get_string('search') . '</label> <input type="text" ' .
1814 'class="form-control" size="16" name="search" id= "pref_search" value="' . s($search) . '" /></div>';
a032a460 1815 echo '&nbsp;&nbsp;&nbsp;<label for="pref_sortby">'.get_string('sortby').'</label> ';
b8b554ac 1816 // foreach field, print the option
5cac5fa4 1817 echo '<select name="sort" id="pref_sortby" class="custom-select mr-1">';
9c00b5d7 1818 if ($fields = $DB->get_records('data_fields', array('dataid'=>$data->id), 'name')) {
3239b010 1819 echo '<optgroup label="'.get_string('fields', 'data').'">';
1820 foreach ($fields as $field) {
1821 if ($field->id == $sort) {
1822 echo '<option value="'.$field->id.'" selected="selected">'.$field->name.'</option>';
1823 } else {
1824 echo '<option value="'.$field->id.'">'.$field->name.'</option>';
1825 }
1826 }
1827 echo '</optgroup>';
714bec74 1828 }
3239b010 1829 $options = array();
1830 $options[DATA_TIMEADDED] = get_string('timeadded', 'data');
1831 $options[DATA_TIMEMODIFIED] = get_string('timemodified', 'data');
1832 $options[DATA_FIRSTNAME] = get_string('authorfirstname', 'data');
1833 $options[DATA_LASTNAME] = get_string('authorlastname', 'data');
bb5740f4 1834 if ($data->approval and has_capability('mod/data:approve', $context)) {
1835 $options[DATA_APPROVED] = get_string('approved', 'data');
1836 }
3239b010 1837 echo '<optgroup label="'.get_string('other', 'data').'">';
714bec74 1838 foreach ($options as $key => $name) {
1839 if ($key == $sort) {
1840 echo '<option value="'.$key.'" selected="selected">'.$name.'</option>';
cf3e199b 1841 } else {
714bec74 1842 echo '<option value="'.$key.'">'.$name.'</option>';
cf3e199b 1843 }
1844 }
3239b010 1845 echo '</optgroup>';
cf3e199b 1846 echo '</select>';
a032a460 1847 echo '<label for="pref_order" class="accesshide">'.get_string('order').'</label>';
5cac5fa4 1848 echo '<select id="pref_order" name="order" class="custom-select mr-1">';
c8505cac 1849 if ($order == 'ASC') {
af25f45e 1850 echo '<option value="ASC" selected="selected">'.get_string('ascending','data').'</option>';
cf3e199b 1851 } else {
1852 echo '<option value="ASC">'.get_string('ascending','data').'</option>';
1853 }
c8505cac 1854 if ($order == 'DESC') {
af25f45e 1855 echo '<option value="DESC" selected="selected">'.get_string('descending','data').'</option>';
cf3e199b 1856 } else {
1857 echo '<option value="DESC">'.get_string('descending','data').'</option>';
1858 }
af25f45e 1859 echo '</select>';
86638489 1860
7900ecb0 1861 if ($advanced) {
1862 $checked = ' checked="checked" ';
1863 }
1864 else {
1865 $checked = '';
1866 }
9dec75db 1867 $PAGE->requires->js('/mod/data/data.js');
de8ff581 1868 echo '&nbsp;<input type="hidden" name="advanced" value="0" />';
d53e5129 1869 echo '&nbsp;<input type="hidden" name="filter" value="1" />';
398be7c8 1870 echo '&nbsp;<input type="checkbox" id="advancedcheckbox" name="advanced" value="1" ' . $checked . ' ' .
5cac5fa4 1871 'onchange="showHideAdvSearch(this.checked);" class="mx-1" />' .
398be7c8
DW
1872 '<label for="advancedcheckbox">' . get_string('advancedsearch', 'data') . '</label>';
1873 echo '&nbsp;<input type="submit" class="btn btn-secondary" value="' . get_string('savesettings', 'data') . '" />';
8429163d 1874
7900ecb0 1875 echo '<br />';
0d284a8b 1876 echo '<div class="' . $advancedsearchclass . '" id="data_adv_form">';
7900ecb0 1877 echo '<table class="boxaligncenter">';
8429163d 1878
7900ecb0 1879 // print ASC or DESC
1880 echo '<tr><td colspan="2">&nbsp;</td></tr>';
1881 $i = 0;
1882
1883 // Determine if we are printing all fields for advanced search, or the template for advanced search
1884 // If a template is not defined, use the deafault template and display all fields.
1885 if(empty($data->asearchtemplate)) {
1886 data_generate_default_template($data, 'asearchtemplate');
1887 }
1888
2c216a6c
MN
1889 static $fields = array();
1890 static $dataid = null;
b572ce19 1891
7900ecb0 1892 if (empty($dataid)) {
1893 $dataid = $data->id;
1894 } else if ($dataid != $data->id) {
2c216a6c 1895 $fields = array();
7900ecb0 1896 }
1897
1898 if (empty($fields)) {
9c00b5d7 1899 $fieldrecords = $DB->get_records('data_fields', array('dataid'=>$data->id));
7900ecb0 1900 foreach ($fieldrecords as $fieldrecord) {
1901 $fields[]= data_get_field($fieldrecord, $data);
1902 }
7900ecb0 1903 }
1904
b8b554ac 1905 // Replacing tags
7900ecb0 1906 $patterns = array();
1907 $replacement = array();
1908
b8b554ac 1909 // Then we generate strings to replace for normal tags
7900ecb0 1910 foreach ($fields as $field) {
98f67312 1911 $fieldname = $field->field->name;
1912 $fieldname = preg_quote($fieldname, '/');
1913 $patterns[] = "/\[\[$fieldname\]\]/i";
714bec74 1914 $searchfield = data_get_field_from_id($field->field->id, $data);
7900ecb0 1915 if (!empty($search_array[$field->field->id]->data)) {
1916 $replacement[] = $searchfield->display_search_field($search_array[$field->field->id]->data);
1917 } else {
1918 $replacement[] = $searchfield->display_search_field();
1919 }
1920 }
714bec74 1921 $fn = !empty($search_array[DATA_FIRSTNAME]->data) ? $search_array[DATA_FIRSTNAME]->data : '';
1922 $ln = !empty($search_array[DATA_LASTNAME]->data) ? $search_array[DATA_LASTNAME]->data : '';
1923 $patterns[] = '/##firstname##/';
398be7c8
DW
1924 $replacement[] = '<label class="accesshide" for="u_fn">' . get_string('authorfirstname', 'data') . '</label>' .
1925 '<input type="text" class="form-control" size="16" id="u_fn" name="u_fn" value="' . s($fn) . '" />';
714bec74 1926 $patterns[] = '/##lastname##/';
398be7c8
DW
1927 $replacement[] = '<label class="accesshide" for="u_ln">' . get_string('authorlastname', 'data') . '</label>' .
1928 '<input type="text" class="form-control" size="16" id="u_ln" name="u_ln" value="' . s($ln) . '" />';
714bec74 1929
d45c7a68
AH
1930 if (core_tag_tag::is_enabled('mod_data', 'data_records')) {
1931 $patterns[] = "/##tags##/";
1932 $selectedtags = isset($search_array[DATA_TAGS]->rawtagnames) ? $search_array[DATA_TAGS]->rawtagnames : [];
1933 $replacement[] = data_generate_tag_form(false, $selectedtags);
1934 }
1935
668fc89a 1936 // actual replacement of the tags
b572ce19 1937
39790bd8 1938 $options = new stdClass();
7900ecb0 1939 $options->para=false;
1940 $options->noclean=true;
1941 echo '<tr><td>';
b03c67e9 1942 echo preg_replace($patterns, $replacement, format_text($data->asearchtemplate, FORMAT_HTML, $options));
7900ecb0 1943 echo '</td></tr>';
b572ce19 1944
398be7c8 1945 echo '<tr><td colspan="4"><br/>' .
5cac5fa4 1946 '<input type="submit" class="btn btn-primary mr-1" value="' . get_string('savesettings', 'data') . '" />' .
398be7c8
DW
1947 '<input type="submit" class="btn btn-secondary" name="resetadv" value="' . get_string('resetsettings', 'data') . '" />' .
1948 '</td></tr>';
7900ecb0 1949 echo '</table>';
c8505cac 1950 echo '</div>';
7900ecb0 1951 echo '</div>';
1952 echo '</form>';
b8b554ac 1953 echo '</div>';
3d4b223a 1954}
5f5bcda8 1955
4636bf83 1956/**
1957 * @global object
1958 * @global object
1959 * @param object $data
1960 * @param object $record
1961 * @return void Output echo'd
1962 */
4d3d87f0 1963function data_print_ratings($data, $record) {
56c1ca88 1964 global $OUTPUT;
2b04c41c 1965 if (!empty($record->rating)){
d251b259 1966 echo $OUTPUT->render($record->rating);
4d3d87f0 1967 }
4d3d87f0 1968}
1969
4636bf83 1970/**
b2b4ec30
RT
1971 * List the actions that correspond to a view of this module.
1972 * This is used by the participation report.
1973 *
1974 * Note: This is not used by new logging system. Event with
1975 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
1976 * be considered as view action.
4636bf83 1977 *
1978 * @return array
1979 */
4c03f920 1980function data_get_view_actions() {
1981 return array('view');
1982}
1983
4636bf83 1984/**
b2b4ec30
RT
1985 * List the actions that correspond to a post of this module.
1986 * This is used by the participation report.
1987 *
1988 * Note: This is not used by new logging system. Event with
1989 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
1990 * will be considered as post action.
1991 *
4636bf83 1992 * @return array
1993 */
4c03f920 1994function data_get_post_actions() {
1995 return array('add','update','record delete');
1996}
1997
4636bf83 1998/**
4636bf83 1999 * @param string $name
2000 * @param int $dataid
2001 * @param int $fieldid
2002 * @return bool
2003 */
e9da9f5b
PS
2004function data_fieldname_exists($name, $dataid, $fieldid = 0) {
2005 global $DB;
0997e51a 2006
e9da9f5b
PS
2007 if (!is_numeric($name)) {
2008 $like = $DB->sql_like('df.name', ':name', false);
fdeb3e1f 2009 } else {
e9da9f5b 2010 $like = "df.name = :name";
fdeb3e1f 2011 }
e9da9f5b 2012 $params = array('name'=>$name);
6403e679 2013 if ($fieldid) {
e9da9f5b
PS
2014 $params['dataid'] = $dataid;
2015 $params['fieldid1'] = $fieldid;
2016 $params['fieldid2'] = $fieldid;
9c00b5d7 2017 return $DB->record_exists_sql("SELECT * FROM {data_fields} df
e9da9f5b
PS
2018 WHERE $like AND df.dataid = :dataid
2019 AND ((df.id < :fieldid1) OR (df.id > :fieldid2))", $params);
0997e51a 2020 } else {
e9da9f5b 2021 $params['dataid'] = $dataid;
9c00b5d7 2022 return $DB->record_exists_sql("SELECT * FROM {data_fields} df
e9da9f5b 2023 WHERE $like AND df.dataid = :dataid", $params);
0997e51a 2024 }
2025}
2026
4636bf83 2027/**
2028 * @param array $fieldinput
2029 */
0997e51a 2030function data_convert_arrays_to_strings(&$fieldinput) {
2031 foreach ($fieldinput as $key => $val) {
2032 if (is_array($val)) {
2033 $str = '';
2034 foreach ($val as $inner) {
2035 $str .= $inner . ',';
2036 }
2037 $str = substr($str, 0, -1);
b572ce19 2038
0997e51a 2039 $fieldinput->$key = $str;
2040 }
2041 }
2042}
2043
901dd2fb 2044
7f258664 2045/**
2046 * Converts a database (module instance) to use the Roles System
4636bf83 2047 *
2048 * @global object
2049 * @global object
2050 * @uses CONTEXT_MODULE
2051 * @uses CAP_PREVENT
2052 * @uses CAP_ALLOW
2053 * @param object $data a data object with the same attributes as a record
2054 * from the data database table
2055 * @param int $datamodid the id of the data module, from the modules table
4f0c2d00
PS
2056 * @param array $teacherroles array of roles that have archetype teacher
2057 * @param array $studentroles array of roles that have archetype student
2058 * @param array $guestroles array of roles that have archetype guest
4636bf83 2059 * @param int $cmid the course_module id for this data instance
2060 * @return boolean data module was converted or not
7f258664 2061 */
2062function data_convert_to_roles($data, $teacherroles=array(), $studentroles=array(), $cmid=NULL) {
4102b449 2063 global $CFG, $DB, $OUTPUT;
6403e679 2064
7f258664 2065 if (!isset($data->participants) && !isset($data->assesspublic)
2066 && !isset($data->groupmode)) {
2067 // We assume that this database has already been converted to use the
2068 // Roles System. above fields get dropped the data module has been
2069 // upgraded to use Roles.
2070 return false;
2071 }
b572ce19 2072
7f258664 2073 if (empty($cmid)) {
2074 // We were not given the course_module id. Try to find it.
741c4d0b 2075 if (!$cm = get_coursemodule_from_instance('data', $data->id)) {
4102b449 2076 echo $OUTPUT->notification('Could not get the course module for the data');
7f258664 2077 return false;
2078 } else {
2079 $cmid = $cm->id;
2080 }
2081 }
0b3b8c30 2082 $context = context_module::instance($cmid);
6403e679 2083
b572ce19 2084
7f258664 2085 // $data->participants:
2086 // 1 - Only teachers can add entries
2087 // 3 - Teachers and students can add entries
2088 switch ($data->participants) {
2089 case 1:
2090 foreach ($studentroles as $studentrole) {
2091 assign_capability('mod/data:writeentry', CAP_PREVENT, $studentrole->id, $context->id);
2092 }
2093 foreach ($teacherroles as $teacherrole) {
2094 assign_capability('mod/data:writeentry', CAP_ALLOW, $teacherrole->id, $context->id);
2095 }
2096 break;
2097 case 3:
2098 foreach ($studentroles as $studentrole) {
2099 assign_capability('mod/data:writeentry', CAP_ALLOW, $studentrole->id, $context->id);
2100 }
2101 foreach ($teacherroles as $teacherrole) {
2102 assign_capability('mod/data:writeentry', CAP_ALLOW, $teacherrole->id, $context->id);
2103 }
2104 break;
2105 }
6403e679 2106
7f258664 2107 // $data->assessed:
2108 // 2 - Only teachers can rate posts
2109 // 1 - Everyone can rate posts
2110 // 0 - No one can rate posts
2111 switch ($data->assessed) {
2112 case 0:
2113 foreach ($studentroles as $studentrole) {
2114 assign_capability('mod/data:rate', CAP_PREVENT, $studentrole->id, $context->id);
2115 }
2116 foreach ($teacherroles as $teacherrole) {
2117 assign_capability('mod/data:rate', CAP_PREVENT, $teacherrole->id, $context->id);
2118 }
2119 break;
2120 case 1:
2121 foreach ($studentroles as $studentrole) {
2122 assign_capability('mod/data:rate', CAP_ALLOW, $studentrole->id, $context->id);
2123 }
2124 foreach ($teacherroles as $teacherrole) {
2125 assign_capability('mod/data:rate', CAP_ALLOW, $teacherrole->id, $context->id);
2126 }
2127 break;
2128 case 2:
2129 foreach ($studentroles as $studentrole) {
2130 assign_capability('mod/data:rate', CAP_PREVENT, $studentrole->id, $context->id);
2131 }
2132 foreach ($teacherroles as $teacherrole) {
2133 assign_capability('mod/data:rate', CAP_ALLOW, $teacherrole->id, $context->id);
2134 }
2135 break;
2136 }
6403e679 2137
7f258664 2138 // $data->assesspublic:
2139 // 0 - Students can only see their own ratings
2140 // 1 - Students can see everyone's ratings
2141 switch ($data->assesspublic) {
2142 case 0:
2143 foreach ($studentroles as $studentrole) {
2144 assign_capability('mod/data:viewrating', CAP_PREVENT, $studentrole->id, $context->id);
2145 }
2146 foreach ($teacherroles as $teacherrole) {
2147 assign_capability('mod/data:viewrating', CAP_ALLOW, $teacherrole->id, $context->id);
2148 }
2149 break;
2150 case 1:
2151 foreach ($studentroles as $studentrole) {
2152 assign_capability('mod/data:viewrating', CAP_ALLOW, $studentrole->id, $context->id);
2153 }
2154 foreach ($teacherroles as $teacherrole) {
2155 assign_capability('mod/data:viewrating', CAP_ALLOW, $teacherrole->id, $context->id);
2156 }
2157 break;
2158 }
2159
2160 if (empty($cm)) {
9c00b5d7 2161 $cm = $DB->get_record('course_modules', array('id'=>$cmid));
7f258664 2162 }
6403e679 2163
7f258664 2164 switch ($cm->groupmode) {
055f2185 2165 case NOGROUPS:
7f258664 2166 break;
055f2185 2167 case SEPARATEGROUPS:
7f258664 2168 foreach ($studentroles as $studentrole) {
2169 assign_capability('moodle/site:accessallgroups', CAP_PREVENT, $studentrole->id, $context->id);
2170 }
2171 foreach ($teacherroles as $teacherrole) {
2172 assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $teacherrole->id, $context->id);
2173 }
2174 break;
055f2185 2175 case VISIBLEGROUPS:
7f258664 2176 foreach ($studentroles as $studentrole) {
2177 assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $studentrole->id, $context->id);
2178 }
2179 foreach ($teacherroles as $teacherrole) {
2180 assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $teacherrole->id, $context->id);
2181 }
2182 break;
2183 }
2184 return true;
2185}
2186
4636bf83 2187/**
8303eb84 2188 * Returns the best name to show for a preset
4636bf83 2189 *
2190 * @param string $shortname
2191 * @param string $path
2192 * @return string
8303eb84 2193 */
2194function data_preset_name($shortname, $path) {
2195
668fc89a 2196 // We are looking inside the preset itself as a first choice, but also in normal data directory
30d76014 2197 $string = get_string('modulename', 'datapreset_'.$shortname);
8303eb84 2198
2199 if (substr($string, 0, 1) == '[') {
2200 return $shortname;
2201 } else {
2202 return $string;
2203 }
2204}
2205
4636bf83 2206/**
8aff1574 2207 * Returns an array of all the available presets.
4636bf83 2208 *
4636bf83 2209 * @return array
8303eb84 2210 */
2211function data_get_available_presets($context) {
2212 global $CFG, $USER;
b572ce19 2213
8303eb84 2214 $presets = array();
b572ce19 2215
8aff1574 2216 // First load the ratings sub plugins that exist within the modules preset dir
bd3b3bba 2217 if ($dirs = core_component::get_plugin_list('datapreset')) {
a9cda870 2218 foreach ($dirs as $dir=>$fulldir) {
8303eb84 2219 if (is_directory_a_preset($fulldir)) {
39790bd8 2220 $preset = new stdClass();
8303eb84 2221 $preset->path = $fulldir;
2222 $preset->userid = 0;
2223 $preset->shortname = $dir;
2224 $preset->name = data_preset_name($dir, $fulldir);
2225 if (file_exists($fulldir.'/screenshot.jpg')) {
2226 $preset->screenshot = $CFG->wwwroot.'/mod/data/preset/'.$dir.'/screenshot.jpg';
2227 } else if (file_exists($fulldir.'/screenshot.png')) {
2228 $preset->screenshot = $CFG->wwwroot.'/mod/data/preset/'.$dir.'/screenshot.png';
2229 } else if (file_exists($fulldir.'/screenshot.gif')) {
2230 $preset->screenshot = $CFG->wwwroot.'/mod/data/preset/'.$dir.'/screenshot.gif';
2231 }
2232 $presets[] = $preset;
2233 }
2234 }
2235 }
8aff1574
SH
2236 // Now add to that the site presets that people have saved
2237 $presets = data_get_available_site_presets($context, $presets);
2238 return $presets;
2239}
8303eb84 2240
8aff1574
SH
2241/**
2242 * Gets an array of all of the presets that users have saved to the site.
2243 *
2244 * @param stdClass $context The context that we are looking from.
2245 * @param array $presets
2246 * @return array An array of presets
2247 */
2248function data_get_available_site_presets($context, array $presets=array()) {
810860d2
PS
2249 global $USER;
2250
8aff1574
SH
2251 $fs = get_file_storage();
2252 $files = $fs->get_area_files(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA);
2253 $canviewall = has_capability('mod/data:viewalluserpresets', $context);
2254 if (empty($files)) {
2255 return $presets;
2256 }
2257 foreach ($files as $file) {
2258 if (($file->is_directory() && $file->get_filepath()=='/') || !$file->is_directory() || (!$canviewall && $file->get_userid() != $USER->id)) {
2259 continue;
2260 }
2261 $preset = new stdClass;
2262 $preset->path = $file->get_filepath();
2263 $preset->name = trim($preset->path, '/');
2264 $preset->shortname = $preset->name;
2265 $preset->userid = $file->get_userid();
2266 $preset->id = $file->get_id();
2267 $preset->storedfile = $file;
2268 $presets[] = $preset;
2269 }
2270 return $presets;
2271}
2272
2273/**
2274 * Deletes a saved preset.
2275 *
2276 * @param string $name
2277 * @return bool
2278 */
2279function data_delete_site_preset($name) {
2280 $fs = get_file_storage();
2281
2282 $files = $fs->get_directory_files(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, '/'.$name.'/');
2283 if (!empty($files)) {
2284 foreach ($files as $file) {
2285 $file->delete();
8303eb84 2286 }
2287 }
b572ce19 2288
8aff1574
SH
2289 $dir = $fs->get_file(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, '/'.$name.'/', '.');
2290 if (!empty($dir)) {
2291 $dir->delete();
2292 }
2293 return true;
8303eb84 2294}
2295
4636bf83 2296/**
8aff1574
SH
2297 * Prints the heads for a page
2298 *
2299 * @param stdClass $course
2300 * @param stdClass $cm
2301 * @param stdClass $data
4636bf83 2302 * @param string $currenttab
2303 */
8303eb84 2304function data_print_header($course, $cm, $data, $currenttab='') {
b572ce19 2305
b0ff558c 2306 global $CFG, $displaynoticegood, $displaynoticebad, $OUTPUT, $PAGE;
b572ce19 2307
b0ff558c 2308 $PAGE->set_title($data->name);
b0ff558c 2309 echo $OUTPUT->header();
66e2b9f8
AD
2310 echo $OUTPUT->heading(format_string($data->name), 2);
2311 echo $OUTPUT->box(format_module_intro('data', $data, $cm->id), 'generalbox', 'intro');
8303eb84 2312
66e2b9f8 2313 // Groups needed for Add entry tab
055f2185 2314 $currentgroup = groups_get_activity_group($cm);
5d59cbe9 2315 $groupmode = groups_get_activity_groupmode($cm);
b572ce19 2316
668fc89a 2317 // Print the tabs
b572ce19 2318
8303eb84 2319 if ($currenttab) {
138e480e 2320 include('tabs.php');
8303eb84 2321 }
b572ce19 2322
b8b554ac 2323 // Print any notices
b572ce19 2324
8303eb84 2325 if (!empty($displaynoticegood)) {
4102b449 2326 echo $OUTPUT->notification($displaynoticegood, 'notifysuccess'); // good (usually green)
8303eb84 2327 } else if (!empty($displaynoticebad)) {
4102b449 2328 echo $OUTPUT->notification($displaynoticebad); // bad (usuually red)
8303eb84 2329 }
2330}
7f258664 2331
4636bf83 2332/**
0393a8b7
PS
2333 * Can user add more entries?
2334 *
4636bf83 2335 * @param object $data
2336 * @param mixed $currentgroup
2337 * @param int $groupmode
0393a8b7 2338 * @param stdClass $context
4636bf83 2339 * @return bool
2340 */
e4e96115 2341function data_user_can_add_entry($data, $currentgroup, $groupmode, $context = null) {
cca1547e 2342 global $USER;
b572ce19 2343
e4e96115 2344 if (empty($context)) {
0393a8b7 2345 $cm = get_coursemodule_from_instance('data', $data->id, 0, false, MUST_EXIST);
0b3b8c30 2346 $context = context_module::instance($cm->id);
e4e96115
RW
2347 }
2348
0393a8b7
PS
2349 if (has_capability('mod/data:manageentries', $context)) {
2350 // no entry limits apply if user can manage
e4e96115 2351
0393a8b7 2352 } else if (!has_capability('mod/data:writeentry', $context)) {
e4e96115 2353 return false;
b572ce19 2354
0393a8b7 2355 } else if (data_atmaxentries($data)) {
cca1547e 2356 return false;
e8027a40
ARN
2357 } else if (data_in_readonly_period($data)) {
2358 // Check whether we're in a read-only period
2742ffe7
AD
2359 return false;
2360 }
2361
04366d79 2362 if (!$groupmode or has_capability('moodle/site:accessallgroups', $context)) {
2363 return true;
2364 }
2365
cca1547e 2366 if ($currentgroup) {
2c386f82 2367 return groups_is_member($currentgroup);
cca1547e 2368 } else {
2369 //else it might be group 0 in visible mode
2370 if ($groupmode == VISIBLEGROUPS){
cca1547e 2371 return true;
04366d79 2372 } else {
2373 return false;
cca1547e 2374 }
2375 }
2376}
2377
97fe80ad
JB
2378/**
2379 * Check whether the current user is allowed to manage the given record considering manageentries capability,
2380 * data_in_readonly_period() result, ownership (determined by data_isowner()) and manageapproved setting.
2381 * @param mixed $record record object or id
2382 * @param object $data data object
2383 * @param object $context context object
2384 * @return bool returns true if the user is allowd to edit the entry, false otherwise
2385 */
2386function data_user_can_manage_entry($record, $data, $context) {
2387 global $DB;
2388
2389 if (has_capability('mod/data:manageentries', $context)) {
2390 return true;
2391 }
2392
2393 // Check whether this activity is read-only at present.
2394 $readonly = data_in_readonly_period($data);
2395
2396 if (!$readonly) {
2397 // Get record object from db if just id given like in data_isowner.
2398 // ...done before calling data_isowner() to avoid querying db twice.
2399 if (!is_object($record)) {
2400 if (!$record = $DB->get_record('data_records', array('id' => $record))) {
2401 return false;
2402 }
2403 }
2404 if (data_isowner($record)) {
2405 if ($data->approval && $record->approved) {
2406 return $data->manageapproved == 1;
2407 } else {
2408 return true;
2409 }
2410 }
2411 }
2412
2413 return false;
2414}
2415
e8027a40
ARN
2416/**
2417 * Check whether the specified database activity is currently in a read-only period
2418 *
2419 * @param object $data
2420 * @return bool returns true if the time fields in $data indicate a read-only period; false otherwise
2421 */
2422function data_in_readonly_period($data) {
2423 $now = time();
2424 if (!$data->timeviewfrom && !$data->timeviewto) {
2425 return false;
2426 } else if (($data->timeviewfrom && $now < $data->timeviewfrom) || ($data->timeviewto && $now > $data->timeviewto)) {
2427 return false;
2428 }
2429 return true;
2430}
50194545 2431
4636bf83 2432/**
2433 * @return bool
2434 */
50194545 2435function is_directory_a_preset($directory) {
2436 $directory = rtrim($directory, '/\\') . '/';
2dc6be3f 2437 $status = file_exists($directory.'singletemplate.html') &&
2438 file_exists($directory.'listtemplate.html') &&
2439 file_exists($directory.'listtemplateheader.html') &&
2440 file_exists($directory.'listtemplatefooter.html') &&
2441 file_exists($directory.'addtemplate.html') &&
2442 file_exists($directory.'rsstemplate.html') &&
2443 file_exists($directory.'rsstitletemplate.html') &&
2444 file_exists($directory.'csstemplate.css') &&
2445 file_exists($directory.'jstemplate.js') &&
2446 file_exists($directory.'preset.xml');
b572ce19 2447
2dc6be3f 2448 return $status;
50194545 2449}
2450
4636bf83 2451/**
cba87c36 2452 * Abstract class used for data preset importers
4636bf83 2453 */
cba87c36 2454abstract class data_preset_importer {
b572ce19 2455
cba87c36
SH
2456 protected $course;
2457 protected $cm;
2458 protected $module;
2459 protected $directory;
50194545 2460
4636bf83 2461 /**
cba87c36
SH
2462 * Constructor
2463 *
2464 * @param stdClass $course
2465 * @param stdClass $cm
2466 * @param stdClass $module
2467 * @param string $directory
4636bf83 2468 */
cba87c36 2469 public function __construct($course, $cm, $module, $directory) {
50194545 2470 $this->course = $course;
2471 $this->cm = $cm;
cba87c36
SH
2472 $this->module = $module;
2473 $this->directory = $directory;
2474 }
2475
2476 /**
2477 * Returns the name of the directory the preset is located in
2478 * @return string
2479 */
2480 public function get_directory() {
2481 return basename($this->directory);
50194545 2482 }
263819c8
AD
2483
2484 /**
2485 * Retreive the contents of a file. That file may either be in a conventional directory of the Moodle file storage
2486 * @param file_storage $filestorage. should be null if using a conventional directory
2487 * @param stored_file $fileobj the directory to look in. null if using a conventional directory
2488 * @param string $dir the directory to look in. null if using the Moodle file storage
2489 * @param string $filename the name of the file we want
c600a85c 2490 * @return string the contents of the file or null if the file doesn't exist.
263819c8
AD
2491 */
2492 public function data_preset_get_file_contents(&$filestorage, &$fileobj, $dir, $filename) {
2493 if(empty($filestorage) || empty($fileobj)) {
2494 if (substr($dir, -1)!='/') {
2495 $dir .= '/';
2496 }
c600a85c
AG
2497 if (file_exists($dir.$filename)) {
2498 return file_get_contents($dir.$filename);
2499 } else {
2500 return null;
2501 }
263819c8 2502 } else {
c600a85c
AG
2503 if ($filestorage->file_exists(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, $fileobj->get_filepath(), $filename)) {
2504 $file = $filestorage->get_file(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, $fileobj->get_filepath(), $filename);
2505 return $file->get_content();
2506 } else {
2507 return null;
2508 }
263819c8
AD
2509 }
2510
2511 }
4636bf83 2512 /**
cba87c36
SH
2513 * Gets the preset settings
2514 * @global moodle_database $DB
2515 * @return stdClass
4636bf83 2516 */
cba87c36
SH
2517 public function get_preset_settings() {
2518 global $DB;
50194545 2519
263819c8 2520 $fs = $fileobj = null;
cba87c36 2521 if (!is_directory_a_preset($this->directory)) {
263819c8 2522 //maybe the user requested a preset stored in the Moodle file storage
375053ed 2523
263819c8
AD
2524 $fs = get_file_storage();
2525 $files = $fs->get_area_files(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA);
2526
720f37fd 2527 //preset name to find will be the final element of the directory
c600a85c
AG
2528 $explodeddirectory = explode('/', $this->directory);
2529 $presettofind = end($explodeddirectory);
720f37fd
AD
2530
2531 //now go through the available files available and see if we can find it
263819c8
AD
2532 foreach ($files as $file) {
2533 if (($file->is_directory() && $file->get_filepath()=='/') || !$file->is_directory()) {
2534 continue;
2535 }
2536 $presetname = trim($file->get_filepath(), '/');
720f37fd 2537 if ($presetname==$presettofind) {
263819c8
AD
2538 $this->directory = $presetname;
2539 $fileobj = $file;
2540 }
2541 }
2542
2543 if (empty($fileobj)) {
2544 print_error('invalidpreset', 'data', '', $this->directory);
2545 }
50194545 2546 }
2547
cba87c36
SH
2548 $allowed_settings = array(
2549 'intro',
2550 'comments',
2551 'requiredentries',
2552 'requiredentriestoview',
2553 'maxentries',
2554 'rssarticles',
2555 'approval',
2556 'defaultsortdir',
2557 'defaultsort');
2558
2559 $result = new stdClass;
2560 $result->settings = new stdClass;
2561 $result->importfields = array();
2562 $result->currentfields = $DB->get_records('data_fields', array('dataid'=>$this->module->id));
2563 if (!$result->currentfields) {
2564 $result->currentfields = array();
2565 }
2566
2567
50194545 2568 /* Grab XML */
263819c8 2569 $presetxml = $this->data_preset_get_file_contents($fs, $fileobj, $this->directory,'preset.xml');
143c1eb9 2570 $parsedxml = xmlize($presetxml, 0);
50194545 2571
2572 /* First, do settings. Put in user friendly array. */
2573 $settingsarray = $parsedxml['preset']['#']['settings'][0]['#'];
cba87c36 2574 $result->settings = new StdClass();
50194545 2575 foreach ($settingsarray as $setting => $value) {
cba87c36 2576 if (!is_array($value) || !in_array($setting, $allowed_settings)) {
eaa30818 2577 // unsupported setting
2578 continue;
2579 }
cba87c36 2580 $result->settings->$setting = $value[0]['#'];
50194545 2581 }
2582
2583 /* Now work out fields to user friendly array */
2584 $fieldsarray = $parsedxml['preset']['#']['field'];
50194545 2585 foreach ($fieldsarray as $field) {
02007b01 2586 if (!is_array($field)) {
2587 continue;
2588 }
50194545 2589 $f = new StdClass();
2590 foreach ($field['#'] as $param => $value) {
02007b01 2591 if (!is_array($value)) {
2592 continue;
2593 }
9c00b5d7 2594 $f->$param = $value[0]['#'];
50194545 2595 }
cba87c36 2596 $f->dataid = $this->module->id;
50194545 2597 $f->type = clean_param($f->type, PARAM_ALPHA);
cba87c36 2598 $result->importfields[] = $f;
50194545 2599 }
50194545 2600 /* Now add the HTML templates to the settings array so we can update d */
263819c8
AD
2601 $result->settings->singletemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"singletemplate.html");
2602 $result->settings->listtemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"listtemplate.html");
2603 $result->settings->listtemplateheader = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"listtemplateheader.html");
2604 $result->settings->listtemplatefooter = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"listtemplatefooter.html");
2605 $result->settings->addtemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"addtemplate.html");
2606 $result->settings->rsstemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"rsstemplate.html");
2607 $result->settings->rsstitletemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"rsstitletemplate.html");
2608 $result->settings->csstemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"csstemplate.css");
2609 $result->settings->jstemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"jstemplate.js");
c600a85c 2610 $result->settings->asearchtemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"asearchtemplate.html");
50194545 2611
cba87c36 2612 $result->settings->instance = $this->module->id;
cba87c36 2613 return $result;
50194545 2614 }
2615
4636bf83 2616 /**
cba87c36 2617 * Import the preset into the given database module
4636bf83 2618 * @return bool
2619 */
cba87c36 2620 function import($overwritesettings) {
fe9d5f7e 2621 global $DB, $CFG;
50194545 2622
cba87c36
SH
2623 $params = $this->get_preset_settings();
2624 $settings = $params->settings;
2625 $newfields = $params->importfields;
2626 $currentfields = $params->currentfields;
50194545 2627 $preservedfields = array();
b572ce19 2628
50194545 2629 /* Maps fields and makes new ones */
2630 if (!empty($newfields)) {
2631 /* We require an injective mapping, and need to know what to protect */
2632 foreach ($newfields as $nid => $newfield) {
2633 $cid = optional_param("field_$nid", -1, PARAM_INT);
cba87c36
SH
2634 if ($cid == -1) {
2635 continue;
2636 }
29c1bb15 2637 if (array_key_exists($cid, $preservedfields)){
2638 print_error('notinjectivemap', 'data');
8429163d 2639 }
50194545 2640 else $preservedfields[$cid] = true;
2641 }
b572ce19 2642
50194545 2643 foreach ($newfields as $nid => $newfield) {
2644 $cid = optional_param("field_$nid", -1, PARAM_INT);
b572ce19 2645
50194545 2646 /* A mapping. Just need to change field params. Data kept. */
2647 if ($cid != -1 and isset($currentfields[$cid])) {
cba87c36 2648 $fieldobject = data_get_field_from_id($currentfields[$cid]->id, $this->module);
50194545 2649 foreach ($newfield as $param => $value) {
2650 if ($param != "id") {
2651 $fieldobject->field->$param = $value;
2652 }
2653 }
2654 unset($fieldobject->field->similarfield);
2655 $fieldobject->update_field();
2656 unset($fieldobject);
cba87c36
SH
2657 } else {
2658 /* Make a new field */
50194545 2659 include_once("field/$newfield->type/field.class.php");
b572ce19 2660
50194545 2661 if (!isset($newfield->description)) {
2662 $newfield->description = '';
2663 }
2664 $classname = 'data_field_'.$newfield->type;
cba87c36 2665 $fieldclass = new $classname($newfield, $this->module);
50194545 2666 $fieldclass->insert_field();
2667 unset($fieldclass);
2668 }
2669 }
2670 }
2671
2672 /* Get rid of all old unused data */
2673 if (!empty($preservedfields)) {
2674 foreach ($currentfields as $cid => $currentfield) {
2675 if (!array_key_exists($cid, $preservedfields)) {
2676 /* Data not used anymore so wipe! */
2677 print "Deleting field $currentfield->name<br />";
b572ce19 2678
50194545 2679 $id = $currentfield->id;
2680 //Why delete existing data records and related comments/ratings??
9c00b5d7 2681 $DB->delete_records('data_content', array('fieldid'=>$id));
2682 $DB->delete_records('data_fields', array('id'=>$id));
50194545 2683 }
2684 }
2685 }
2686
cba87c36 2687 // handle special settings here
eaa30818 2688 if (!empty($settings->defaultsort)) {
2689 if (is_numeric($settings->defaultsort)) {
668fc89a 2690 // old broken value
eaa30818 2691 $settings->defaultsort = 0;
2692 } else {
cba87c36 2693 $settings->defaultsort = (int)$DB->get_field('data_fields', 'id', array('dataid'=>$this->module->id, 'name'=>$settings->defaultsort));
eaa30818 2694 }
2695 } else {
2696 $settings->defaultsort = 0;
2697 }
2698
2699 // do we want to overwrite all current database settings?
8528bf26 2700 if ($overwritesettings) {
eaa30818 2701 // all supported settings
8528bf26 2702 $overwrite = array_keys((array)$settings);
2703 } else {
eaa30818 2704 // only templates and sorting
8528bf26 2705 $overwrite = array('singletemplate', 'listtemplate', 'listtemplateheader', 'listtemplatefooter',
2706 'addtemplate', 'rsstemplate', 'rsstitletemplate', 'csstemplate', 'jstemplate',
eaa30818 2707 'asearchtemplate', 'defaultsortdir', 'defaultsort');
8528bf26 2708 }
2709
eaa30818 2710 // now overwrite current data settings
cba87c36 2711 foreach ($this->module as $prop=>$unused) {
8528bf26 2712 if (in_array($prop, $overwrite)) {
cba87c36 2713 $this->module->$prop = $settings->$prop;
13534ef7
ML
2714 }
2715 }
db0f2a44 2716
cba87c36 2717 data_update_instance($this->module);
50194545 2718
cba87c36
SH
2719 return $this->cleanup();
2720 }
b572ce19 2721
cba87c36
SH
2722 /**
2723 * Any clean up routines should go here
2724 * @return bool
2725 */
2726 public function cleanup() {
50194545 2727 return true;
2728 }
2729}
2730
cba87c36
SH
2731/**
2732 * Data preset importer for uploaded presets
2733 */
2734class data_preset_upload_importer extends data_preset_importer {
2735 public function __construct($course, $cm, $module, $filepath) {
2736 global $USER;
2737 if (is_file($filepath)) {
2738 $fp = get_file_packer();
2739 if ($fp->extract_to_pathname($filepath, $filepath.'_extracted')) {
2740 fulldelete($filepath);
2741 }
2742 $filepath .= '_extracted';
2743 }
2744 parent::__construct($course, $cm, $module, $filepath);
2745 }
2746 public function cleanup() {
2747 return fulldelete($this->directory);
2748 }
2749}
2750
2751/**
2752 * Data preset importer for existing presets
2753 */
2754class data_preset_existing_importer extends data_preset_importer {
2755 protected $userid;
2756 public function __construct($course, $cm, $module, $fullname) {
2757 global $USER;
2758 list($userid, $shortname) = explode('/', $fullname, 2);
0b3b8c30 2759 $context = context_module::instance($cm->id);
cba87c36
SH
2760 if ($userid && ($userid != $USER->id) && !has_capability('mod/data:manageuserpresets', $context) && !has_capability('mod/data:viewalluserpresets', $context)) {
2761 throw new coding_exception('Invalid preset provided');
2762 }
2763
2764 $this->userid = $userid;
2765 $filepath = data_preset_path($course, $userid, $shortname);
2766 parent::__construct($course, $cm, $module, $filepath);
2767 }
2768 public function get_userid() {
2769 return $this->userid;
2770 }
2771}
2772
4636bf83 2773/**
2774 * @global object
2775 * @global object
2776 * @param object $course
2777 * @param int $userid
2778 * @param string $shortname
2779 * @return string
2780 */
50194545 2781function data_preset_path($course, $userid, $shortname) {
2782 global $USER, $CFG;
b572ce19 2783
0b3b8c30 2784 $context = context_course::instance($course->id);
b572ce19 2785
50194545 2786 $userid = (int)$userid;
b572ce19 2787
263819c8 2788 $path = null;
50194545 2789 if ($userid > 0 && ($userid == $USER->id || has_capability('mod/data:viewalluserpresets', $context))) {
263819c8 2790 $path = $CFG->dataroot.'/data/preset/'.$userid.'/'.$shortname;
50194545 2791 } else if ($userid == 0) {
263819c8 2792 $path = $CFG->dirroot.'/mod/data/preset/'.$shortname;
50194545 2793 } else if ($userid < 0) {
7aa06e6d 2794 $path = $CFG->tempdir.'/data/'.-$userid.'/'.$shortname;
50194545 2795 }
b572ce19 2796
263819c8 2797 return $path;
50194545 2798}
0b5a80a1 2799
2800/**
2801 * Implementation of the function for printing the form elements that control
2802 * whether the course reset functionality affects the data.
4636bf83 2803 *
0b5a80a1 2804 * @param $mform form passed by reference
2805 */
2806function data_reset_course_form_definition(&$mform) {
2807 $mform->addElement('header', 'dataheader', get_string('modulenameplural', 'data'));
2808 $mform->addElement('checkbox', 'reset_data', get_string('deleteallentries','data'));
2809
2810 $mform->addElement('checkbox', 'reset_data_notenrolled', get_string('deletenotenrolled', 'data'));
2811 $mform->disabledIf('reset_data_notenrolled', 'reset_data', 'checked');
2812
2813 $mform->addElement('checkbox', 'reset_data_ratings', get_string('deleteallratings'));
2814 $mform->disabledIf('reset_data_ratings', 'reset_data', 'checked');
2815
2816 $mform->addElement('checkbox', 'reset_data_comments', get_string('deleteallcomments'));
2817 $mform->disabledIf('reset_data_comments', 'reset_data', 'checked');
80effa0f
MN
2818
2819 $mform->addElement('checkbox', 'reset_data_tags', get_string('removealldatatags', 'data'));
2820 $mform->disabledIf('reset_data_tags', 'reset_data', 'checked');
0b5a80a1 2821}
2822
2823/**
2824 * Course reset form defaults.
4636bf83 2825 * @return array
0b5a80a1 2826 */
2827function data_reset_course_form_defaults($course) {
2828 return array('reset_data'=>0, 'reset_data_ratings'=>1, 'reset_data_comments'=>1, 'reset_data_notenrolled'=>0);
2829}
2830
2831/**
2832 * Removes all grades from gradebook
4636bf83 2833 *
2834 * @global object
2835 * @global object
0b5a80a1 2836 * @param int $courseid
4636bf83 2837 * @param string $type optional type
0b5a80a1 2838 */
2839function data_reset_gradebook($courseid, $type='') {
9c00b5d7 2840 global $CFG, $DB;
0b5a80a1 2841
2842 $sql = "SELECT d.*, cm.idnumber as cmidnumber, d.course as courseid
9c00b5d7 2843 FROM {data} d, {course_modules} cm, {modules} m
2844 WHERE m.name='data' AND m.id=cm.module AND cm.instance=d.id AND d.course=?";
0b5a80a1 2845
9c00b5d7 2846 if ($datas = $DB->get_records_sql($sql, array($courseid))) {
0b5a80a1 2847 foreach ($datas as $data) {
2848 data_grade_item_update($data, 'reset');
2849 }
2850 }
2851}
2852
2853/**
72d2982e 2854 * Actual implementation of the reset course functionality, delete all the
0b5a80a1 2855 * data responses for course $data->courseid.
4636bf83 2856 *
2857 * @global object
2858 * @global object
2859 * @param object $data the data submitted from the reset course.
0b5a80a1 2860 * @return array status array
2861 */
2862function data_reset_userdata($data) {
9c00b5d7 2863 global $CFG, $DB;
0b5a80a1 2864 require_once($CFG->libdir.'/filelib.php');
d251b259 2865 require_once($CFG->dirroot.'/rating/lib.php');
b572ce19 2866
0b5a80a1 2867 $componentstr = get_string('modulenameplural', 'data');
2868 $status = array();
b572ce19 2869
0b5a80a1 2870 $allrecordssql = "SELECT r.id
9c00b5d7 2871 FROM {data_records} r
2872 INNER JOIN {data} d ON r.dataid = d.id
2873 WHERE d.course = ?";
0b5a80a1 2874
2875 $alldatassql = "SELECT d.id
9c00b5d7 2876 FROM {data} d
2877 WHERE d.course=?";
0b5a80a1 2878
d251b259 2879 $rm = new rating_manager();
2b04c41c
SH
2880 $ratingdeloptions = new stdClass;
2881 $ratingdeloptions->component = 'mod_data';
2882 $ratingdeloptions->ratingarea = 'entry';
d251b259 2883
4e457296
MN
2884 // Set the file storage - may need it to remove files later.
2885 $fs = get_file_storage();
2886
0b5a80a1 2887 // delete entries if requested
2888 if (!empty($data->reset_data)) {
e998effa 2889 $DB->delete_records_select('comments', "itemid IN ($allrecordssql) AND commentarea='database_entry'", array($data->courseid));
9c00b5d7 2890 $DB->delete_records_select('data_content', "recordid IN ($allrecordssql)", array($data->courseid));
2891 $DB->delete_records_select('data_records', "dataid IN ($alldatassql)", array($data->courseid));
0b5a80a1 2892
9c00b5d7 2893 if ($datas = $DB->get_records_sql($alldatassql, array($data->courseid))) {
0b5a80a1 2894 foreach ($datas as $dataid=>$unused) {
d251b259
AD
2895 if (!$cm = get_coursemodule_from_instance('data', $dataid)) {
2896 continue;
2897 }
0b3b8c30 2898 $datacontext = context_module::instance($cm->id);
d251b259 2899
4e457296
MN
2900 // Delete any files that may exist.
2901 $fs->delete_area_files($datacontext->id, 'mod_data', 'content');
2902
d251b259
AD
2903 $ratingdeloptions->contextid = $datacontext->id;
2904 $rm->delete_ratings($ratingdeloptions);
80effa0f
MN
2905
2906 core_tag_tag::delete_instances('mod_data', null, $datacontext->id);
0b5a80a1 2907 }
2908 }
b572ce19 2909
0b5a80a1 2910 if (empty($data->reset_gradebook_grades)) {
2911 // remove all grades from gradebook
2912 data_reset_gradebook($data->courseid);
2913 }
2914 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallentries', 'data'), 'error'=>false);
2915 }
2916
2917 // remove entries by users not enrolled into course
2918 if (!empty($data->reset_data_notenrolled)) {
2919 $recordssql = "SELECT r.id, r.userid, r.dataid, u.id AS userexists, u.deleted AS userdeleted
9c00b5d7 2920 FROM {data_records} r
2921 JOIN {data} d ON r.dataid = d.id
2922 LEFT JOIN {user} u ON r.userid = u.id
2923 WHERE d.course = ? AND r.userid > 0";
0b5a80a1 2924
0b3b8c30 2925 $course_context = context_course::instance($data->courseid);
0b5a80a1 2926 $notenrolled = array();
2927 $fields = array();
6b1b1d03
EL
2928 $rs = $DB->get_recordset_sql($recordssql, array($data->courseid));
2929 foreach ($rs as $record) {
2930 if (array_key_exists($record->userid, $notenrolled) or !$record->userexists or $record->userdeleted
2931 or !is_enrolled($course_context, $record->userid)) {
2932 //delete ratings
2933 if (!$cm = get_coursemodule_from_instance('data', $record->dataid)) {
2934 continue;
2935 }
0b3b8c30 2936 $datacontext = context_module::instance($cm->id);
6b1b1d03
EL
2937 $ratingdeloptions->contextid = $datacontext->id;
2938 $ratingdeloptions->itemid = $record->id;
2939 $rm->delete_ratings($ratingdeloptions);
2940
4e457296
MN
2941 // Delete any files that may exist.
2942 if ($contents = $DB->get_records('data_content', array('recordid' => $record->id), '', 'id')) {
2943 foreach ($contents as $content) {
2944 $fs->delete_area_files($datacontext->id, 'mod_data', 'content', $content->id);
0b5a80a1 2945 }
0b5a80a1 2946 }
6b1b1d03 2947 $notenrolled[$record->userid] = true;
4e457296 2948
80effa0f
MN
2949 core_tag_tag::remove_all_item_tags('mod_data', 'data_records', $record->id);
2950
4e457296
MN
2951 $DB->delete_records('comments', array('itemid' => $record->id, 'commentarea' => 'database_entry'));
2952 $DB->delete_records('data_content', array('recordid' => $record->id));
2953 $DB->delete_records('data_records', array('id' => $record->id));
0b5a80a1 2954 }
0b5a80a1 2955 }
6b1b1d03
EL
2956 $rs->close();
2957 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletenotenrolled', 'data'), 'error'=>false);
0b5a80a1 2958 }
2959
2960 // remove all ratings
2961 if (!empty($data->reset_data_ratings)) {
d251b259
AD
2962 if ($datas = $DB->get_records_sql($alldatassql, array($data->courseid))) {
2963 foreach ($datas as $dataid=>$unused) {
2964 if (!$cm = get_coursemodule_from_instance('data', $dataid)) {
2965 continue;
2966 }
0b3b8c30 2967 $datacontext = context_module::instance($cm->id);
d251b259
AD
2968
2969 $ratingdeloptions->contextid = $datacontext->id;
2970 $rm->delete_ratings($ratingdeloptions);
2971 }
2972 }
0b5a80a1 2973
2974 if (empty($data->reset_gradebook_grades)) {
2975 // remove all grades from gradebook
2976 data_reset_gradebook($data->courseid);
2977 }
b572ce19 2978
0b5a80a1 2979 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallratings'), 'error'=>false);
2980 }
2981
2982 // remove all comments
2983 if (!empty($data->reset_data_comments)) {
e998effa 2984 $DB->delete_records_select('comments', "itemid IN ($allrecordssql) AND commentarea='database_entry'", array($data->courseid));
0b5a80a1 2985 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallcomments'), 'error'=>false);
2986 }
2987
80effa0f
MN
2988 // Remove all the tags.
2989 if (!empty($data->reset_data_tags)) {
2990 if ($datas = $DB->get_records_sql($alldatassql, array($data->courseid))) {
2991 foreach ($datas as $dataid => $unused) {
2992 if (!$cm = get_coursemodule_from_instance('data', $dataid)) {
2993 continue;
2994 }
2995
2996 $context = context_module::instance($cm->id);
2997 core_tag_tag::delete_instances('mod_data', null, $context->id);
2998
2999 }
3000 }
3001 $status[] = array('component' => $componentstr, 'item' => get_string('tagsdeleted', 'data'), 'error' => false);
3002 }
3003
b8b554ac 3004 // updating dates - shift may be negative too
0b5a80a1 3005 if ($data->timeshift) {
0d14fcbc
AA
3006 // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
3007 // See MDL-9367.
3008 shift_course_mod_dates('data', array('timeavailablefrom', 'timeavailableto',
3009 'timeviewfrom', 'timeviewto', 'assesstimestart', 'assesstimefinish'), $data->timeshift, $data->courseid);
0b5a80a1 3010 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
3011 }
b572ce19 3012
0b5a80a1 3013 return $status;
3014}
f432bebf 3015
3016/**
3017 * Returns all other caps used in module
4636bf83 3018 *
3019 * @return array
f432bebf 3020 */
3021function data_get_extra_capabilities() {
939218c2
TH
3022 return ['moodle/rating:view', 'moodle/rating:viewany', 'moodle/rating:viewall', 'moodle/rating:rate',
3023 'moodle/comment:view', 'moodle/comment:post', 'moodle/comment:delete'];
f432bebf 3024}
3025
18a2a0cb 3026/**
3027 * @param string $feature FEATURE_xx constant for requested feature
3028 * @return mixed True if module supports feature, null if doesn't know
3029 */
3030function data_supports($feature) {
3031 switch($feature) {
42f103be 3032 case FEATURE_GROUPS: return true;
3033 case FEATURE_GROUPINGS: return true;
dc5c2bd9 3034 case FEATURE_MOD_INTRO: return true;
18a2a0cb 3035 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
cf873ada 3036 case FEATURE_COMPLETION_HAS_RULES: return true;
42f103be 3037 case FEATURE_GRADE_HAS_GRADE: return true;
3038 case FEATURE_GRADE_OUTCOMES: return true;
d251b259 3039 case FEATURE_RATE: return true;
fd3f6bf9 3040 case FEATURE_BACKUP_MOODLE2: return true;
3e4c2435 3041 case FEATURE_SHOW_DESCRIPTION: return true;
6492401d 3042 case FEATURE_COMMENT: return true;
42f103be 3043
18a2a0cb 3044 default: return null;
17da2e6f 3045 }
18a2a0cb 3046}
4636bf83 3047/**
3048 * @global object
3049 * @param array $export
3050 * @param string $delimiter_name
3051 * @param object $database
3052 * @param int $count
3053 * @param bool $return
3054 * @return string|void
3055 */
9a5abd1b 3056function data_export_csv($export, $delimiter_name, $database, $count, $return=false) {
ecd06483 3057 global $CFG;
3058 require_once($CFG->libdir . '/csvlib.class.php');
9a5abd1b
AG
3059
3060 $filename = $database . '-' . $count . '-record';
20988152 3061 if ($count > 1) {
3062 $filename .= 's';
3063 }
9a5abd1b
AG
3064 if ($return) {
3065 return csv_export_writer::print_array($export, $delimiter_name, '"', true);
3066 } else {
3067 csv_export_writer::download_array($filename, $export, $delimiter_name);
20988152 3068 }
3069}
3070
4636bf83 3071/**
3072 * @global object
3073 * @param array $export
3074 * @param string $dataname
3075 * @param int $count
3076 * @return string
3077 */
1bf8c6b2 3078function data_export_xls($export, $dataname, $count) {
20988152 3079 global $CFG;
3080 require_once("$CFG->libdir/excellib.class.php");
fa7f82be 3081 $filename = clean_filename("{$dataname}-{$count}_record");
20988152 3082 if ($count > 1) {
3083 $filename .= 's';
3084 }
3085 $filename .= clean_filename('-' . gmdate("Ymd_Hi"));
3086 $filename .= '.xls';
ecd06483 3087
3088 $filearg = '-';
ecd06483 3089 $workbook = new MoodleExcelWorkbook($filearg);
1bf8c6b2 3090 $workbook->send($filename);
20988152 3091 $worksheet = array();
75427a82 3092 $worksheet[0] = $workbook->add_worksheet('');
20988152 3093 $rowno = 0;
3094 foreach ($export as $row) {
3095 $colno = 0;
3096 foreach($row as $col) {
3097 $worksheet[0]->write($rowno, $colno, $col);
3098 $colno++;
3099 }
3100 $rowno++;
3101 }
3102 $workbook->close();
ecd06483 3103 return $filename;
20988152 3104}
3105
4636bf83 3106/**
3107 * @global object
3108 * @param array $export
3109 * @param string $dataname
3110 * @param int $count
3111 * @param string
3112 */
1bf8c6b2 3113function data_export_ods($export, $dataname, $count) {
20988152 3114 global $CFG;
3115 require_once("$CFG->libdir/odslib.class.php");
fa7f82be 3116 $filename = clean_filename("{$dataname}-{$count}_record");
20988152 3117 if ($count > 1) {
3118 $filename .= 's';
3119 }
3120 $filename .= clean_filename('-' . gmdate("Ymd_Hi"));
3121 $filename .= '.ods';
ecd06483 3122 $filearg = '-';
1bf8c6b2 3123 $workbook = new MoodleODSWorkbook($filearg);
3124 $workbook->send($filename);
20988152 3125 $worksheet = array();
75427a82 3126 $worksheet[0] = $workbook->add_worksheet('');
20988152 3127 $rowno = 0;
3128 foreach ($export as $row) {
3129 $colno = 0;
3130 foreach($row as $col) {
3131 $worksheet[0]->write($rowno, $colno, $col);
3132 $colno++;
3133 }
3134 $rowno++;
3135 }
3136 $workbook->close();
ecd06483 3137 return $filename;
3138}
3139
4636bf83 3140/**
3141 * @global object
3142 * @param int $dataid
3143 * @param array $fields
3144 * @param array $selectedfields
83468603
AG
3145 * @param int $currentgroup group ID of the current group. This is used for
3146 * exporting data while maintaining group divisions.
6e12c215
AB
3147 * @param object $context the context in which the operation is performed (for capability checks)
3148 * @param bool $userdetails whether to include the details of the record author
3149 * @param bool $time whether to include time created/modified
3150 * @param bool $approval whether to include approval status
04f7b079 3151 * @param bool $tags whether to include tags
4636bf83 3152 * @return array
3153 */
4f304eeb 3154function data_get_exportdata($dataid, $fields, $selectedfields, $currentgroup=0, $context=null,
04f7b079 3155 $userdetails=false, $time=false, $approval=false, $tags = false) {
ecd06483 3156 global $DB;
3157
4f304eeb
HB
3158 if (is_null($context)) {
3159 $context = context_system::instance();
3160 }
3161 // exporting user data needs special permission
3162 $userdetails = $userdetails && has_capability('mod/data:exportuserinfo', $context);
3163
ecd06483 3164 $exportdata = array();
3165
3166 // populate the header in first row of export
3167 foreach($fields as $key => $field) {
3168 if (!in_array($field->field->id, $selectedfields)) {
3169 // ignore values we aren't exporting
3170 unset($fields[$key]);
3171 } else {
3172 $exportdata[0][] = $field->field->name;
3173 }
3174 }
3dfd48ba
MN
3175 if ($tags) {
3176 $exportdata[0][] = get_string('tags', 'data');
3177 }
4f304eeb
HB
3178 if ($userdetails) {
3179 $exportdata[0][] = get_string('user');
3180 $exportdata[0][] = get_string('username');
3181 $exportdata[0][] = get_string('email');
3182 }
3183 if ($time) {
3184 $exportdata[0][] = get_string('timeadded', 'data');
3185 $exportdata[0][] = get_string('timemodified', 'data');
3186 }
3187 if ($approval) {
3188 $exportdata[0][] = get_string('approved', 'data');
3189 }
ecd06483 3190
3191 $datarecords = $DB->get_records('data_records', array('dataid'=>$dataid));
3192 ksort($datarecords);
3193 $line = 1;
3194 foreach($datarecords as $record) {
3195 // get content indexed by fieldid
83468603
AG
3196 if ($currentgroup) {
3197 $select = 'SELECT c.fieldid, c.content, c.content1, c.content2, c.content3, c.content4 FROM {data_content} c, {data_records} r WHERE c.recordid = ? AND r.id = c.recordid AND r.groupid = ?';
3198 $where = array($record->id, $currentgroup);
3199 } else {
3200 $select = 'SELECT fieldid, content, content1, content2, content3, content4 FROM {data_content} WHERE recordid = ?';
3201 $where = array($record->id);
3202 }
3203
3204 if( $content = $DB->get_records_sql($select, $where) ) {
ecd06483 3205 foreach($fields as $field) {
3206 $contents = '';
3207 if(isset($content[$field->field->id])) {
3208 $contents = $field->export_text_value($content[$field->field->id]);
3209 }
3210 $exportdata[$line][] = $contents;
3211 }
3dfd48ba
MN
3212 if ($tags) {