MDL-57455 mod_data: Import and export tags
[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();
0bec64c6 611 $table->attributes['class'] = 'mod-data-default-template ##approvalstatus##';
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 = []) {
ca5f3e0a
AH
689 global $CFG, $DB, $PAGE;
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
728 $PAGE->requires->js_call_amd('core/form-autocomplete', 'enhance', $params = array(
729 '#tags',
730 $typenewtags,
731 '',
732 get_string('entertags', 'tag'),
733 false,
734 $showstandard,
735 get_string('noselection', 'form')
736 )
737 );
738
739 $str .= html_writer::end_tag('div');
740
741 return $str;
742}
743
3d4b223a 744
4636bf83 745/**
56c1ca88 746 * Search for a field name and replaces it with another one in all the
747 * form templates. Set $newfieldname as '' if you want to delete the
4636bf83 748 * field from the form.
749 *
750 * @global object
751 * @param object $data
752 * @param string $searchfieldname
753 * @param string $newfieldname
754 * @return bool
755 */
0997e51a 756function data_replace_field_in_templates($data, $searchfieldname, $newfieldname) {
9c00b5d7 757 global $DB;
758
f9eab7b0 759 if (!empty($newfieldname)) {
760 $prestring = '[[';
761 $poststring = ']]';
9706fa56 762 $idpart = '#id';
735a7952 763
764 } else {
f9eab7b0 765 $prestring = '';
766 $poststring = '';
9706fa56 767 $idpart = '';
f9eab7b0 768 }
6403e679 769
39790bd8 770 $newdata = new stdClass();
735a7952 771 $newdata->id = $data->id;
9c00b5d7 772 $newdata->singletemplate = str_ireplace('[['.$searchfieldname.']]',
773 $prestring.$newfieldname.$poststring, $data->singletemplate);
6403e679 774
9c00b5d7 775 $newdata->listtemplate = str_ireplace('[['.$searchfieldname.']]',
776 $prestring.$newfieldname.$poststring, $data->listtemplate);
6403e679 777
9c00b5d7 778 $newdata->addtemplate = str_ireplace('[['.$searchfieldname.']]',
779 $prestring.$newfieldname.$poststring, $data->addtemplate);
6403e679 780
9c00b5d7 781 $newdata->addtemplate = str_ireplace('[['.$searchfieldname.'#id]]',
782 $prestring.$newfieldname.$idpart.$poststring, $data->addtemplate);
9706fa56 783
9c00b5d7 784 $newdata->rsstemplate = str_ireplace('[['.$searchfieldname.']]',
785 $prestring.$newfieldname.$poststring, $data->rsstemplate);
6403e679 786
9c00b5d7 787 return $DB->update_record('data', $newdata);
f9eab7b0 788}
789
790
4636bf83 791/**
792 * Appends a new field at the end of the form template.
793 *
794 * @global object
795 * @param object $data
796 * @param string $newfieldname
797 */
0997e51a 798function data_append_new_field_to_templates($data, $newfieldname) {
9c00b5d7 799 global $DB;
0997e51a 800
39790bd8 801 $newdata = new stdClass();
0997e51a 802 $newdata->id = $data->id;
ed69c723 803 $change = false;
0997e51a 804
f9eab7b0 805 if (!empty($data->singletemplate)) {
9c00b5d7 806 $newdata->singletemplate = $data->singletemplate.' [[' . $newfieldname .']]';
ed69c723 807 $change = true;
0997e51a 808 }
809 if (!empty($data->addtemplate)) {
9c00b5d7 810 $newdata->addtemplate = $data->addtemplate.' [[' . $newfieldname . ']]';
ed69c723 811 $change = true;
f9eab7b0 812 }
813 if (!empty($data->rsstemplate)) {
9c00b5d7 814 $newdata->rsstemplate = $data->singletemplate.' [[' . $newfieldname . ']]';
ed69c723 815 $change = true;
816 }
817 if ($change) {
9c00b5d7 818 $DB->update_record('data', $newdata);
f9eab7b0 819 }
f9eab7b0 820}
821
822
4636bf83 823/**
824 * given a field name
825 * this function creates an instance of the particular subfield class
826 *
827 * @global object
828 * @param string $name
829 * @param object $data
830 * @return object|bool
831 */
0997e51a 832function data_get_field_from_name($name, $data){
9c00b5d7 833 global $DB;
834
1e123f47 835 $field = $DB->get_record('data_fields', array('name'=>$name, 'dataid'=>$data->id));
0997e51a 836
837 if ($field) {
838 return data_get_field($field, $data);
839 } else {
840 return false;
841 }
842}
843
4636bf83 844/**
845 * given a field id
846 * this function creates an instance of the particular subfield class
847 *
848 * @global object
849 * @param int $fieldid
850 * @param object $data
851 * @return bool|object
852 */
0997e51a 853function data_get_field_from_id($fieldid, $data){
9c00b5d7 854 global $DB;
855
1e123f47 856 $field = $DB->get_record('data_fields', array('id'=>$fieldid, 'dataid'=>$data->id));
3d4b223a 857
0997e51a 858 if ($field) {
859 return data_get_field($field, $data);
5782be6b 860 } else {
d6f0e247 861 return false;
3d4b223a 862 }
3d4b223a 863}
864
4636bf83 865/**
866 * given a field id
867 * this function creates an instance of the particular subfield class
868 *
869 * @global object
870 * @param string $type
871 * @param object $data
872 * @return object
873 */
0997e51a 874function data_get_field_new($type, $data) {
875 global $CFG;
b572ce19 876
0997e51a 877 require_once($CFG->dirroot.'/mod/data/field/'.$type.'/field.class.php');
878 $newfield = 'data_field_'.$type;
879 $newfield = new $newfield(0, $data);
880 return $newfield;
881}
882
4636bf83 883/**
884 * returns a subclass field object given a record of the field, used to
885 * invoke plugin methods
886 * input: $param $field - record from db
887 *
888 * @global object
889 * @param object $field
890 * @param object $data
891 * @param object $cm
892 * @return object
893 */
8429163d 894function data_get_field($field, $data, $cm=null) {
0997e51a 895 global $CFG;
b572ce19 896
0997e51a 897 if ($field) {
3d4b223a 898 require_once('field/'.$field->type.'/field.class.php');
899 $newfield = 'data_field_'.$field->type;
8429163d 900 $newfield = new $newfield($field, $data, $cm);
3d4b223a 901 return $newfield;
902 }
903}
904
905
8429163d 906/**
907 * Given record object (or id), returns true if the record belongs to the current user
4636bf83 908 *
909 * @global object
910 * @global object
911 * @param mixed $record record object or id
8429163d 912 * @return bool
913 */
914function data_isowner($record) {
9c00b5d7 915 global $USER, $DB;
3d4b223a 916
4f0c2d00 917 if (!isloggedin()) { // perf shortcut
3d4b223a 918 return false;
919 }
920
8429163d 921 if (!is_object($record)) {
922 if (!$record = $DB->get_record('data_records', array('id'=>$record))) {
923 return false;
924 }
3d4b223a 925 }
926
8429163d 927 return ($record->userid == $USER->id);
3d4b223a 928}
929
4636bf83 930/**
931 * has a user reached the max number of entries?
932 *
933 * @param object $data
934 * @return bool
935 */
b572ce19 936function data_atmaxentries($data){
937 if (!$data->maxentries){
3d4b223a 938 return false;
b572ce19 939
3d4b223a 940 } else {
941 return (data_numentries($data) >= $data->maxentries);
942 }
943}
944
4636bf83 945/**
946 * returns the number of entries already made by this user
56c1ca88 947 *
4636bf83 948 * @global object
949 * @global object
56c1ca88 950 * @param object $data
4636bf83 951 * @return int
952 */
f9729dcf 953function data_numentries($data, $userid=null) {
8429163d 954 global $USER, $DB;
f9729dcf
MG
955 if ($userid === null) {
956 $userid = $USER->id;
957 }
9c00b5d7 958 $sql = 'SELECT COUNT(*) FROM {data_records} WHERE dataid=? AND userid=?';
f9729dcf 959 return $DB->count_records_sql($sql, array($data->id, $userid));
3d4b223a 960}
961
4636bf83 962/**
56c1ca88 963 * function that takes in a dataid and adds a record
4636bf83 964 * this is used everytime an add template is submitted
965 *
966 * @global object
967 * @global object
968 * @param object $data
969 * @param int $groupid
970 * @return bool
971 */
0997e51a 972function data_add_record($data, $groupid=0){
9c00b5d7 973 global $USER, $DB;
6403e679 974
c088d603 975 $cm = get_coursemodule_from_instance('data', $data->id);
0b3b8c30 976 $context = context_module::instance($cm->id);
b572ce19 977
39790bd8 978 $record = new stdClass();
3d4b223a 979 $record->userid = $USER->id;
0997e51a 980 $record->dataid = $data->id;
3d4b223a 981 $record->groupid = $groupid;
0997e51a 982 $record->timecreated = $record->timemodified = time();
0468976c 983 if (has_capability('mod/data:approve', $context)) {
6e0119dd 984 $record->approved = 1;
985 } else {
986 $record->approved = 0;
987 }
76ca452c
MN
988 $record->id = $DB->insert_record('data_records', $record);
989
990 // Trigger an event for creating this record.
991 $event = \mod_data\event\record_created::create(array(
992 'objectid' => $record->id,
993 'context' => $context,
994 'other' => array(
995 'dataid' => $data->id
996 )
997 ));
998 $event->trigger();
999
f9729dcf 1000 $course = get_course($cm->course);
cf873ada 1001 data_update_completion_state($data, $course, $cm);
f9729dcf 1002
76ca452c 1003 return $record->id;
3d4b223a 1004}
1005
4636bf83 1006/**
1007 * check the multple existence any tag in a template
1008 *
1009 * check to see if there are 2 or more of the same tag being used.
1010 *
1011 * @global object
1012 * @param int $dataid,
56c1ca88 1013 * @param string $template
4636bf83 1014 * @return bool
1015 */
9c00b5d7 1016function data_tags_check($dataid, $template) {
4102b449 1017 global $DB, $OUTPUT;
9c00b5d7 1018
b8b554ac 1019 // first get all the possible tags
9c00b5d7 1020 $fields = $DB->get_records('data_fields', array('dataid'=>$dataid));
b8b554ac 1021 // then we generate strings to replace
1022 $tagsok = true; // let's be optimistic
b572ce19 1023 foreach ($fields as $field){
546a58bc 1024 $pattern="/\[\[" . preg_quote($field->name, '/') . "\]\]/i";
b572ce19 1025 if (preg_match_all($pattern, $template, $dummy)>1){
3d4b223a 1026 $tagsok = false;
4102b449 1027 echo $OUTPUT->notification('[['.$field->name.']] - '.get_string('multipletags','data'));
3d4b223a 1028 }
1029 }
b8b554ac 1030 // else return true
3d4b223a 1031 return $tagsok;
1032}
1033
4636bf83 1034/**
1035 * Adds an instance of a data
1036 *
6b04fdc0
PS
1037 * @param stdClass $data
1038 * @param mod_data_mod_form $mform
1039 * @return int intance id
4636bf83 1040 */
6b04fdc0 1041function data_add_instance($data, $mform = null) {
87d6e85a
SB
1042 global $DB, $CFG;
1043 require_once($CFG->dirroot.'/mod/data/locallib.php');
3d4b223a 1044
57244db3 1045 if (empty($data->assessed)) {
1046 $data->assessed = 0;
d6af3cfa 1047 }
1048
f3013ba6
AG
1049 if (empty($data->ratingtime) || empty($data->assessed)) {
1050 $data->assesstimestart = 0;
1051 $data->assesstimefinish = 0;
1052 }
1053
3d4b223a 1054 $data->timemodified = time();
1055
a8f3a651 1056 $data->id = $DB->insert_record('data', $data);
3d4b223a 1057
87d6e85a
SB
1058 // Add calendar events if necessary.
1059 data_set_events($data);
9ffbdafc
AG
1060 if (!empty($data->completionexpected)) {
1061 \core_completion\api::update_completion_date_event($data->coursemodule, 'data', $data->id, $data->completionexpected);
1062 }
87d6e85a 1063
612607bd 1064 data_grade_item_update($data);
b572ce19 1065
3d4b223a 1066 return $data->id;
1067}
1068
4636bf83 1069/**
1070 * updates an instance of a data
1071 *
1072 * @global object
1073 * @param object $data
1074 * @return bool
1075 */
3d4b223a 1076function data_update_instance($data) {
87d6e85a
SB
1077 global $DB, $CFG;
1078 require_once($CFG->dirroot.'/mod/data/locallib.php');
6403e679 1079
04366d79 1080 $data->timemodified = time();
b572ce19 1081 $data->id = $data->instance;
6403e679 1082
57244db3 1083 if (empty($data->assessed)) {
1084 $data->assessed = 0;
17e5f3fc 1085 }
b572ce19 1086
d251b259
AD
1087 if (empty($data->ratingtime) or empty($data->assessed)) {
1088 $data->assesstimestart = 0;
1089 $data->assesstimefinish = 0;
1090 }
1091
05ac14ca 1092 if (empty($data->notification)) {
1093 $data->notification = 0;
1094 }
1095
0bcf8b6f 1096 $DB->update_record('data', $data);
04366d79 1097
87d6e85a
SB
1098 // Add calendar events if necessary.
1099 data_set_events($data);
9ffbdafc
AG
1100 $completionexpected = (!empty($data->completionexpected)) ? $data->completionexpected : null;
1101 \core_completion\api::update_completion_date_event($data->coursemodule, 'data', $data->id, $completionexpected);
87d6e85a 1102
04366d79 1103 data_grade_item_update($data);
b572ce19 1104
04366d79 1105 return true;
b572ce19 1106
3d4b223a 1107}
1108
4636bf83 1109/**
1110 * deletes an instance of a data
1111 *
1112 * @global object
1113 * @param int $id
1114 * @return bool
1115 */
b8b554ac 1116function data_delete_instance($id) { // takes the dataid
650a0c0a 1117 global $DB, $CFG;
3d4b223a 1118
8429163d 1119 if (!$data = $DB->get_record('data', array('id'=>$id))) {
3d4b223a 1120 return false;
1121 }
1122
8429163d 1123 $cm = get_coursemodule_from_instance('data', $data->id);
0b3b8c30 1124 $context = context_module::instance($cm->id);
b572ce19 1125
8429163d 1126/// Delete all the associated information
6403e679 1127
8429163d 1128 // files
1129 $fs = get_file_storage();
64f93798 1130 $fs->delete_area_files($context->id, 'mod_data');
3d4b223a 1131
8429163d 1132 // get all the records in this data
1133 $sql = "SELECT r.id
1134 FROM {data_records} r
1135 WHERE r.dataid = ?";
6403e679 1136
8429163d 1137 $DB->delete_records_select('data_content', "recordid IN ($sql)", array($id));
3d4b223a 1138
1139 // delete all the records and fields
c18269c7 1140 $DB->delete_records('data_records', array('dataid'=>$id));
1141 $DB->delete_records('data_fields', array('dataid'=>$id));
3d4b223a 1142
87d6e85a
SB
1143 // Remove old calendar events.
1144 $events = $DB->get_records('event', array('modulename' => 'data', 'instance' => $id));
1145 foreach ($events as $event) {
1146 $event = calendar_event::load($event);
1147 $event->delete();
1148 }
1149
3d4b223a 1150 // Delete the instance itself
c18269c7 1151 $result = $DB->delete_records('data', array('id'=>$id));
04366d79 1152
8429163d 1153 // cleanup gradebook
b82cacea 1154 data_grade_item_delete($data);
b572ce19 1155
04366d79 1156 return $result;
3d4b223a 1157}
1158
4636bf83 1159/**
1160 * returns a summary of data activity of this user
1161 *
1162 * @global object
1163 * @param object $course
1164 * @param object $user
1165 * @param object $mod
1166 * @param object $data
1167 * @return object|null
1168 */
3d4b223a 1169function data_user_outline($course, $user, $mod, $data) {
1a96363a
NC
1170 global $DB, $CFG;
1171 require_once("$CFG->libdir/gradelib.php");
1172
1173 $grades = grade_get_grades($course->id, 'mod', 'data', $data->id, $user->id);
1174 if (empty($grades->items[0]->grades)) {
1175 $grade = false;
1176 } else {
1177 $grade = reset($grades->items[0]->grades);
1178 }
1179
9c00b5d7 1180
1181 if ($countrecords = $DB->count_records('data_records', array('dataid'=>$data->id, 'userid'=>$user->id))) {
39790bd8 1182 $result = new stdClass();
63701c78 1183 $result->info = get_string('numrecords', 'data', $countrecords);
9c00b5d7 1184 $lastrecord = $DB->get_record_sql('SELECT id,timemodified FROM {data_records}
1185 WHERE dataid = ? AND userid = ?
1186 ORDER BY timemodified DESC', array($data->id, $user->id), true);
3d4b223a 1187 $result->time = $lastrecord->timemodified;
1a96363a
NC
1188 if ($grade) {
1189 $result->info .= ', ' . get_string('grade') . ': ' . $grade->str_long_grade;
1190 }
1191 return $result;
1192 } else if ($grade) {
39790bd8 1193 $result = new stdClass();
1a96363a 1194 $result->info = get_string('grade') . ': ' . $grade->str_long_grade;
4433f871
AD
1195
1196 //datesubmitted == time created. dategraded == time modified or time overridden
1197 //if grade was last modified by the user themselves use date graded. Otherwise use date submitted
94a74f54 1198 //TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704
4433f871
AD
1199 if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
1200 $result->time = $grade->dategraded;
1201 } else {
1202 $result->time = $grade->datesubmitted;
1203 }
1204
3d4b223a 1205 return $result;
1206 }
1207 return NULL;
3d4b223a 1208}
1209
4636bf83 1210/**
1211 * Prints all the records uploaded by this user
1212 *
1213 * @global object
1214 * @param object $course
1215 * @param object $user
1216 * @param object $mod
1217 * @param object $data
1218 */
3d4b223a 1219function data_user_complete($course, $user, $mod, $data) {
1a96363a
NC
1220 global $DB, $CFG, $OUTPUT;
1221 require_once("$CFG->libdir/gradelib.php");
1222
1223 $grades = grade_get_grades($course->id, 'mod', 'data', $data->id, $user->id);
1224 if (!empty($grades->items[0]->grades)) {
1225 $grade = reset($grades->items[0]->grades);
1226 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
1227 if ($grade->str_feedback) {
1228 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
1229 }
1230 }
9c00b5d7 1231
1232 if ($records = $DB->get_records('data_records', array('dataid'=>$data->id,'userid'=>$user->id), 'timemodified DESC')) {
3d45b8e5 1233 data_print_template('singletemplate', $records, $data);
3d4b223a 1234 }
1235}
1236
04366d79 1237/**
1238 * Return grade for given user or all users.
1239 *
4636bf83 1240 * @global object
1241 * @param object $data
04366d79 1242 * @param int $userid optional user id, 0 means all users
1243 * @return array array of grades, false if none
1244 */
612607bd 1245function data_get_user_grades($data, $userid=0) {
d251b259
AD
1246 global $CFG;
1247
1248 require_once($CFG->dirroot.'/rating/lib.php');
04366d79 1249
2b04c41c
SH
1250 $ratingoptions = new stdClass;
1251 $ratingoptions->component = 'mod_data';
1252 $ratingoptions->ratingarea = 'entry';
d251b259
AD
1253 $ratingoptions->modulename = 'data';
1254 $ratingoptions->moduleid = $data->id;
04366d79 1255
d251b259
AD
1256 $ratingoptions->userid = $userid;
1257 $ratingoptions->aggregationmethod = $data->assessed;
1258 $ratingoptions->scaleid = $data->scale;
1259 $ratingoptions->itemtable = 'data_records';
1260 $ratingoptions->itemtableusercolumn = 'userid';
04366d79 1261
2b04c41c 1262 $rm = new rating_manager();
d251b259 1263 return $rm->get_user_grades($ratingoptions);
04366d79 1264}
1265
1266/**
775f811a 1267 * Update activity grades
04366d79 1268 *
a153c9f2 1269 * @category grade
775f811a 1270 * @param object $data
1271 * @param int $userid specific user only, 0 means all
4636bf83 1272 * @param bool $nullifnone
04366d79 1273 */
775f811a 1274function data_update_grades($data, $userid=0, $nullifnone=true) {
9c00b5d7 1275 global $CFG, $DB;
1276 require_once($CFG->libdir.'/gradelib.php');
04366d79 1277
775f811a 1278 if (!$data->assessed) {
1279 data_grade_item_update($data);
b572ce19 1280
775f811a 1281 } else if ($grades = data_get_user_grades($data, $userid)) {
1282 data_grade_item_update($data, $grades);
b572ce19 1283
775f811a 1284 } else if ($userid and $nullifnone) {
39790bd8 1285 $grade = new stdClass();
775f811a 1286 $grade->userid = $userid;
1287 $grade->rawgrade = NULL;
1288 data_grade_item_update($data, $grade);
b572ce19 1289
04366d79 1290 } else {
775f811a 1291 data_grade_item_update($data);
1292 }
1293}
1294
04366d79 1295/**
612607bd 1296 * Update/create grade item for given data
04366d79 1297 *
a153c9f2
AD
1298 * @category grade
1299 * @param stdClass $data A database instance with extra cmidnumber property
1300 * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
04366d79 1301 * @return object grade_item
1302 */
0b5a80a1 1303function data_grade_item_update($data, $grades=NULL) {
612607bd 1304 global $CFG;
9c00b5d7 1305 require_once($CFG->libdir.'/gradelib.php');
04366d79 1306
13534ef7 1307 $params = array('itemname'=>$data->name, 'idnumber'=>$data->cmidnumber);
b572ce19 1308
04366d79 1309 if (!$data->assessed or $data->scale == 0) {
612607bd 1310 $params['gradetype'] = GRADE_TYPE_NONE;
b572ce19 1311
04366d79 1312 } else if ($data->scale > 0) {
1313 $params['gradetype'] = GRADE_TYPE_VALUE;
1314 $params['grademax'] = $data->scale;
1315 $params['grademin'] = 0;
b572ce19 1316
04366d79 1317 } else if ($data->scale < 0) {
1318 $params['gradetype'] = GRADE_TYPE_SCALE;
1319 $params['scaleid'] = -$data->scale;
1320 }
b572ce19 1321
0b5a80a1 1322 if ($grades === 'reset') {
1323 $params['reset'] = true;
1324 $grades = NULL;
1325 }
1326
1327 return grade_update('mod/data', $data->course, 'mod', 'data', $data->id, 0, $grades, $params);
04366d79 1328}
1329
1330/**
1331 * Delete grade item for given data
1332 *
a153c9f2 1333 * @category grade
04366d79 1334 * @param object $data object
1335 * @return object grade_item
1336 */
1337function data_grade_item_delete($data) {
612607bd 1338 global $CFG;
1339 require_once($CFG->libdir.'/gradelib.php');
b572ce19 1340
b67ec72f 1341 return grade_update('mod/data', $data->course, 'mod', 'data', $data->id, 0, NULL, array('deleted'=>1));
04366d79 1342}
1343
b8b554ac 1344// junk functions
4636bf83 1345/**
56c1ca88 1346 * takes a list of records, the current data, a search string,
4636bf83 1347 * and mode to display prints the translated template
1348 *
1349 * @global object
1350 * @global object
1351 * @param string $template
56c1ca88 1352 * @param array $records
4636bf83 1353 * @param object $data
56c1ca88 1354 * @param string $search
4636bf83 1355 * @param int $page
1356 * @param bool $return
f09040d7 1357 * @param object $jumpurl a moodle_url by which to jump back to the record list (can be null)
4636bf83 1358 * @return mixed
1359 */
f09040d7 1360function data_print_template($template, $records, $data, $search='', $page=0, $return=false, moodle_url $jumpurl=null) {
f2a1963c 1361 global $CFG, $DB, $OUTPUT;
cf9ecfda 1362
c088d603 1363 $cm = get_coursemodule_from_instance('data', $data->id);
0b3b8c30 1364 $context = context_module::instance($cm->id);
b572ce19 1365
2c216a6c
MN
1366 static $fields = array();
1367 static $dataid = null;
b572ce19 1368
63701c78 1369 if (empty($dataid)) {
1370 $dataid = $data->id;
1371 } else if ($dataid != $data->id) {
2c216a6c 1372 $fields = array();
63701c78 1373 }
b572ce19 1374
3d45b8e5 1375 if (empty($fields)) {
9c00b5d7 1376 $fieldrecords = $DB->get_records('data_fields', array('dataid'=>$data->id));
3d45b8e5 1377 foreach ($fieldrecords as $fieldrecord) {
1378 $fields[]= data_get_field($fieldrecord, $data);
1379 }
3d45b8e5 1380 }
b572ce19 1381
64452eb4 1382 if (empty($records)) {
1383 return;
1384 }
b572ce19 1385
f09040d7
HB
1386 if (!$jumpurl) {
1387 $jumpurl = new moodle_url('/mod/data/view.php', array('d' => $data->id));
1388 }
1389 $jumpurl = new moodle_url($jumpurl, array('page' => $page, 'sesskey' => sesskey()));
1390
668fc89a 1391 foreach ($records as $record) { // Might be just one for the single template
b572ce19 1392
b8b554ac 1393 // Replacing tags
3d4b223a 1394 $patterns = array();
1395 $replacement = array();
b572ce19 1396
b8b554ac 1397 // Then we generate strings to replace for normal tags
3d45b8e5 1398 foreach ($fields as $field) {
f2584d0e 1399 $patterns[]='[['.$field->field->name.']]';
d118d06a 1400 $replacement[] = highlight($search, $field->display_browse_field($record->id, $template));
3d4b223a 1401 }
b572ce19 1402
cf9ecfda
AG
1403 $canmanageentries = has_capability('mod/data:manageentries', $context);
1404
b8b554ac 1405 // Replacing special tags (##Edit##, ##Delete##, ##More##)
e357c206 1406 $patterns[]='##edit##';
1407 $patterns[]='##delete##';
97fe80ad 1408 if (data_user_can_manage_entry($record, $data, $context)) {
64452eb4 1409 $replacement[] = '<a href="'.$CFG->wwwroot.'/mod/data/edit.php?d='
663640f5
DW
1410 .$data->id.'&amp;rid='.$record->id.'&amp;sesskey='.sesskey().'">' .
1411 $OUTPUT->pix_icon('t/edit', get_string('edit')) . '</a>';
3d4b223a 1412 $replacement[] = '<a href="'.$CFG->wwwroot.'/mod/data/view.php?d='
663640f5
DW
1413 .$data->id.'&amp;delete='.$record->id.'&amp;sesskey='.sesskey().'">' .
1414 $OUTPUT->pix_icon('t/delete', get_string('delete')) . '</a>';
046dd7dc 1415 } else {
3d4b223a 1416 $replacement[] = '';
eeeb4f2a 1417 $replacement[] = '';
3d4b223a 1418 }
d53e5129 1419
1420 $moreurl = $CFG->wwwroot . '/mod/data/view.php?d=' . $data->id . '&amp;rid=' . $record->id;
32d799c6 1421 if ($search) {
1422 $moreurl .= '&amp;filter=1';
1423 }
e357c206 1424 $patterns[]='##more##';
663640f5 1425 $replacement[] = '<a href="'.$moreurl.'">' . $OUTPUT->pix_icon('t/preview', get_string('more', 'data')) . '</a>';
d53e5129 1426
e357c206 1427 $patterns[]='##moreurl##';
d53e5129 1428 $replacement[] = $moreurl;
473dd288 1429
cf9ecfda
AG
1430 $patterns[]='##delcheck##';
1431 if ($canmanageentries) {
1432 $replacement[] = html_writer::checkbox('delcheck[]', $record->id, false, '', array('class' => 'recordcheckbox'));
1433 } else {
1434 $replacement[] = '';
1435 }
1436
e357c206 1437 $patterns[]='##user##';
64452eb4 1438 $replacement[] = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$record->userid.
1439 '&amp;course='.$data->course.'">'.fullname($record).'</a>';
8185aeb6 1440
560237b4 1441 $patterns[] = '##userpicture##';
c910cf30 1442 $ruser = user_picture::unalias($record, null, 'userid');
80771075
JL
1443 // If the record didn't come with user data, retrieve the user from database.
1444 if (!isset($ruser->picture)) {
1445 $ruser = core_user::get_user($record->userid);
1446 }
c910cf30 1447 $replacement[] = $OUTPUT->user_picture($ruser, array('courseid' => $data->course));
560237b4 1448
8185aeb6 1449 $patterns[]='##export##';
1450
6708a1f5 1451 if (!empty($CFG->enableportfolios) && ($template == 'singletemplate' || $template == 'listtemplate')
8185aeb6 1452 && ((has_capability('mod/data:exportentry', $context)
1453 || (data_isowner($record->id) && has_capability('mod/data:exportownentry', $context))))) {
24ba58ee 1454 require_once($CFG->libdir . '/portfoliolib.php');
0d06b6fd 1455 $button = new portfolio_add_button();
37743241 1456 $button->set_callback_options('data_portfolio_caller', array('id' => $cm->id, 'recordid' => $record->id), 'mod_data');
6be1dcae 1457 list($formats, $files) = data_portfolio_caller::formats($fields, $record);
276378e6 1458 $button->set_formats($formats);
0d06b6fd 1459 $replacement[] = $button->to_html(PORTFOLIO_ADD_ICON_LINK);
8185aeb6 1460 } else {
1461 $replacement[] = '';
1462 }
8429163d 1463
c95034f2 1464 $patterns[] = '##timeadded##';
8429163d 1465 $replacement[] = userdate($record->timecreated);
c95034f2 1466
1467 $patterns[] = '##timemodified##';
35e129c1 1468 $replacement [] = userdate($record->timemodified);
473dd288 1469
e357c206 1470 $patterns[]='##approve##';
851d3b7a 1471 if (has_capability('mod/data:approve', $context) && ($data->approval) && (!$record->approved)) {
f09040d7 1472 $approveurl = new moodle_url($jumpurl, array('approve' => $record->id));
d0372ed6 1473 $approveicon = new pix_icon('t/approve', get_string('approve', 'data'), '', array('class' => 'iconsmall'));
851d3b7a
FM
1474 $replacement[] = html_writer::tag('span', $OUTPUT->action_icon($approveurl, $approveicon),
1475 array('class' => 'approve'));
473dd288 1476 } else {
6e0119dd 1477 $replacement[] = '';
1478 }
6403e679 1479
d0372ed6
HB
1480 $patterns[]='##disapprove##';
1481 if (has_capability('mod/data:approve', $context) && ($data->approval) && ($record->approved)) {
f09040d7 1482 $disapproveurl = new moodle_url($jumpurl, array('disapprove' => $record->id));
d0372ed6
HB
1483 $disapproveicon = new pix_icon('t/block', get_string('disapprove', 'data'), '', array('class' => 'iconsmall'));
1484 $replacement[] = html_writer::tag('span', $OUTPUT->action_icon($disapproveurl, $disapproveicon),
1485 array('class' => 'disapprove'));
1486 } else {
1487 $replacement[] = '';
1488 }
1489
0bec64c6
HB
1490 $patterns[] = '##approvalstatus##';
1491 if (!$data->approval) {
1492 $replacement[] = '';
1493 } else if ($record->approved) {
d58f3a4d 1494 $replacement[] = get_string('approved', 'data');
0bec64c6 1495 } else {
d58f3a4d 1496 $replacement[] = get_string('notapproved', 'data');
0bec64c6
HB
1497 }
1498
e357c206 1499 $patterns[]='##comments##';
4d3d87f0 1500 if (($template == 'listtemplate') && ($data->comments)) {
e998effa
DC
1501
1502 if (!empty($CFG->usecomments)) {
36051c9e 1503 require_once($CFG->dirroot . '/comment/lib.php');
866354a9 1504 list($context, $course, $cm) = get_context_info_array($context->id);
6bdfef5d 1505 $cmt = new stdClass();
e998effa 1506 $cmt->context = $context;
866354a9
DC
1507 $cmt->course = $course;
1508 $cmt->cm = $cm;
1509 $cmt->area = 'database_entry';
e998effa
DC
1510 $cmt->itemid = $record->id;
1511 $cmt->showcount = true;
d846488e 1512 $cmt->component = 'mod_data';
e998effa 1513 $comment = new comment($cmt);
36051c9e 1514 $replacement[] = $comment->output(true);
e998effa 1515 }
4d3d87f0 1516 } else {
1517 $replacement[] = '';
1518 }
6e0119dd 1519
ca5f3e0a
AH
1520 if (core_tag_tag::is_enabled('mod_data', 'data_records')) {
1521 $patterns[] = "##tags##";
1522 $replacement[] = $OUTPUT->tag_list(
1523 core_tag_tag::get_item_tags('mod_data', 'data_records', $record->id), '', 'data-tags');
1524 }
1525
b8b554ac 1526 // actual replacement of the tags
f2584d0e 1527 $newtext = str_ireplace($patterns, $replacement, $data->{$template});
5023c3ab 1528
b8b554ac 1529 // no more html formatting and filtering - see MDL-6635
aa3b20e9 1530 if ($return) {
1531 return $newtext;
1532 } else {
1533 echo $newtext;
b572ce19 1534
aa3b20e9 1535 // hack alert - return is always false in singletemplate anyway ;-)
1536 /**********************************
1537 * Printing Ratings Form *
1538 *********************************/
1539 if ($template == 'singletemplate') { //prints ratings options
1540 data_print_ratings($data, $record);
1541 }
b572ce19 1542
aa3b20e9 1543 /**********************************
d251b259 1544 * Printing Comments Form *
aa3b20e9 1545 *********************************/
d251b259 1546 if (($template == 'singletemplate') && ($data->comments)) {
e998effa 1547 if (!empty($CFG->usecomments)) {
36051c9e 1548 require_once($CFG->dirroot . '/comment/lib.php');
866354a9 1549 list($context, $course, $cm) = get_context_info_array($context->id);
6bdfef5d 1550 $cmt = new stdClass();
e998effa 1551 $cmt->context = $context;
866354a9
DC
1552 $cmt->course = $course;
1553 $cmt->cm = $cm;
1554 $cmt->area = 'database_entry';
e998effa
DC
1555 $cmt->itemid = $record->id;
1556 $cmt->showcount = true;
d846488e 1557 $cmt->component = 'mod_data';
e998effa 1558 $comment = new comment($cmt);
36051c9e 1559 $comment->output(false);
e998effa 1560 }
aa3b20e9 1561 }
4d3d87f0 1562 }
3d4b223a 1563 }
1564}
1565
d251b259
AD
1566/**
1567 * Return rating related permissions
2b04c41c
SH
1568 *
1569 * @param string $contextid the context id
1570 * @param string $component the component to get rating permissions for
1571 * @param string $ratingarea the rating area to get permissions for
d251b259
AD
1572 * @return array an associative array of the user's rating permissions
1573 */
2b04c41c 1574function data_rating_permissions($contextid, $component, $ratingarea) {
d197ea43 1575 $context = context::instance_by_id($contextid, MUST_EXIST);
2b04c41c 1576 if ($component != 'mod_data' || $ratingarea != 'entry') {
d251b259 1577 return null;
d251b259 1578 }
2b04c41c
SH
1579 return array(
1580 'view' => has_capability('mod/data:viewrating',$context),
1581 'viewany' => has_capability('mod/data:viewanyrating',$context),
1582 'viewall' => has_capability('mod/data:viewallratings',$context),
1583 'rate' => has_capability('mod/data:rate',$context)
1584 );
d251b259
AD
1585}
1586
aeafd436 1587/**
2c2ff8d5
AD
1588 * Validates a submitted rating
1589 * @param array $params submitted data
1590 * context => object the context in which the rated items exists [required]
1591 * itemid => int the ID of the object being rated
1592 * scaleid => int the scale from which the user can select a rating. Used for bounds checking. [required]
1593 * rating => int the submitted rating
1594 * rateduserid => int the id of the user whose items have been rated. NOT the user who submitted the ratings. 0 to update all. [required]
1595 * aggregation => int the aggregation method to apply when calculating grades ie RATING_AGGREGATE_AVERAGE [required]
778361c3 1596 * @return boolean true if the rating is valid. Will throw rating_exception if not
aeafd436 1597 */
778361c3 1598function data_rating_validate($params) {
2c2ff8d5
AD
1599 global $DB, $USER;
1600
2b04c41c
SH
1601 // Check the component is mod_data
1602 if ($params['component'] != 'mod_data') {
1603 throw new rating_exception('invalidcomponent');
2c2ff8d5
AD
1604 }
1605
2b04c41c
SH
1606 // Check the ratingarea is entry (the only rating area in data module)
1607 if ($params['ratingarea'] != 'entry') {
1608 throw new rating_exception('invalidratingarea');
1609 }
1610
1611 // Check the rateduserid is not the current user .. you can't rate your own entries
1612 if ($params['rateduserid'] == $USER->id) {
1613 throw new rating_exception('nopermissiontorate');
1614 }
1615
1616 $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
1617 FROM {data_records} r
1618 JOIN {data} d ON r.dataid = d.id
1619 WHERE r.id = :itemid";
1620 $dataparams = array('itemid'=>$params['itemid']);
1621 if (!$info = $DB->get_record_sql($datasql, $dataparams)) {
778361c3
AD
1622 //item doesn't exist
1623 throw new rating_exception('invaliditemid');
2c2ff8d5
AD
1624 }
1625
6ac149dc
AD
1626 if ($info->scale != $params['scaleid']) {
1627 //the scale being submitted doesnt match the one in the database
1628 throw new rating_exception('invalidscaleid');
1629 }
1630
6ac149dc 1631 //check that the submitted rating is valid for the scale
5693d56c
EL
1632
1633 // lower limit
1634 if ($params['rating'] < 0 && $params['rating'] != RATING_UNSET_RATING) {
6ac149dc 1635 throw new rating_exception('invalidnum');
5693d56c
EL
1636 }
1637
1638 // upper limit
1639 if ($info->scale < 0) {
6ac149dc 1640 //its a custom scale
2b04c41c 1641 $scalerecord = $DB->get_record('scale', array('id' => -$info->scale));
6ac149dc
AD
1642 if ($scalerecord) {
1643 $scalearray = explode(',', $scalerecord->scale);
1644 if ($params['rating'] > count($scalearray)) {
1645 throw new rating_exception('invalidnum');
1646 }
1647 } else {
1648 throw new rating_exception('invalidscaleid');
1649 }
1650 } else if ($params['rating'] > $info->scale) {
1651 //if its numeric and submitted rating is above maximum
1652 throw new rating_exception('invalidnum');
1653 }
1654
2c2ff8d5
AD
1655 if ($info->approval && !$info->approved) {
1656 //database requires approval but this item isnt approved
778361c3 1657 throw new rating_exception('nopermissiontorate');
2c2ff8d5
AD
1658 }
1659
2b04c41c 1660 // check the item we're rating was created in the assessable time window
2c2ff8d5
AD
1661 if (!empty($info->assesstimestart) && !empty($info->assesstimefinish)) {
1662 if ($info->timecreated < $info->assesstimestart || $info->timecreated > $info->assesstimefinish) {
778361c3 1663 throw new rating_exception('notavailable');
2c2ff8d5
AD
1664 }
1665 }
1666
74df2951 1667 $course = $DB->get_record('course', array('id'=>$info->course), '*', MUST_EXIST);
2b04c41c 1668 $cm = get_coursemodule_from_instance('data', $info->dataid, $course->id, false, MUST_EXIST);
0b3b8c30 1669 $context = context_module::instance($cm->id);
2c2ff8d5 1670
2b04c41c
SH
1671 // if the supplied context doesnt match the item's context
1672 if ($context->id != $params['context']->id) {
778361c3 1673 throw new rating_exception('invalidcontext');
2c2ff8d5
AD
1674 }
1675
1676 // Make sure groups allow this user to see the item they're rating
2b04c41c 1677 $groupid = $info->groupid;
2c2ff8d5
AD
1678 if ($groupid > 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) { // Groups are being used
1679 if (!groups_group_exists($groupid)) { // Can't find group
778361c3 1680 throw new rating_exception('cannotfindgroup');//something is wrong
2c2ff8d5
AD
1681 }
1682
1683 if (!groups_is_member($groupid) and !has_capability('moodle/site:accessallgroups', $context)) {
1684 // do not allow rating of posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS
778361c3 1685 throw new rating_exception('notmemberofgroup');
2c2ff8d5
AD
1686 }
1687 }
1688
1689 return true;
aeafd436
AD
1690}
1691
731c2712
AA
1692/**
1693 * Can the current user see ratings for a given itemid?
1694 *
1695 * @param array $params submitted data
1696 * contextid => int contextid [required]
1697 * component => The component for this module - should always be mod_data [required]
1698 * ratingarea => object the context in which the rated items exists [required]
1699 * itemid => int the ID of the object being rated [required]
1700 * scaleid => int scale id [optional]
1701 * @return bool
1702 * @throws coding_exception
1703 * @throws rating_exception
1704 */
1705function mod_data_rating_can_see_item_ratings($params) {
1706 global $DB;
1707
1708 // Check the component is mod_data.
1709 if (!isset($params['component']) || $params['component'] != 'mod_data') {
1710 throw new rating_exception('invalidcomponent');
1711 }
1712
1713 // Check the ratingarea is entry (the only rating area in data).
1714 if (!isset($params['ratingarea']) || $params['ratingarea'] != 'entry') {
1715 throw new rating_exception('invalidratingarea');
1716 }
1717
1718 if (!isset($params['itemid'])) {
1719 throw new rating_exception('invaliditemid');
1720 }
1721
1722 $datasql = "SELECT d.id as dataid, d.course, r.groupid
1723 FROM {data_records} r
1724 JOIN {data} d ON r.dataid = d.id
1725 WHERE r.id = :itemid";
1726 $dataparams = array('itemid' => $params['itemid']);
1727 if (!$info = $DB->get_record_sql($datasql, $dataparams)) {
1728 // Item doesn't exist.
1729 throw new rating_exception('invaliditemid');
1730 }
1731
ca3e8022
AG
1732 // User can see ratings of all participants.
1733 if ($info->groupid == 0) {
1734 return true;
1735 }
1736
731c2712
AA
1737 $course = $DB->get_record('course', array('id' => $info->course), '*', MUST_EXIST);
1738 $cm = get_coursemodule_from_instance('data', $info->dataid, $course->id, false, MUST_EXIST);
1739
1740 // Make sure groups allow this user to see the item they're rating.
1741 return groups_group_visible($info->groupid, $course, $cm);
1742}
1743
a593aeee 1744
4636bf83 1745/**
56c1ca88 1746 * function that takes in the current data, number of items per page,
1747 * a search string and prints a preference box in view.php
1748 *
1749 * This preference box prints a searchable advanced search template if
1750 * a) A template is defined
1751 * b) The advanced search checkbox is checked.
4636bf83 1752 *
1753 * @global object
1754 * @global object
56c1ca88 1755 * @param object $data
1756 * @param int $perpage
4636bf83 1757 * @param string $search
1758 * @param string $sort
1759 * @param string $order
1760 * @param array $search_array
1761 * @param int $advanced
1762 * @param string $mode
1763 * @return void
1764 */
7900ecb0 1765function data_print_preference_form($data, $perpage, $search, $sort='', $order='ASC', $search_array = '', $advanced = 0, $mode= ''){
601104f2 1766 global $CFG, $DB, $PAGE, $OUTPUT;
8429163d 1767
7900ecb0 1768 $cm = get_coursemodule_from_instance('data', $data->id);
0b3b8c30 1769 $context = context_module::instance($cm->id);
7900ecb0 1770 echo '<br /><div class="datapreferences">';
b7dc2256 1771 echo '<form id="options" action="view.php" method="get">';
7900ecb0 1772 echo '<div>';
473dd288 1773 echo '<input type="hidden" name="d" value="'.$data->id.'" />';
7900ecb0 1774 if ($mode =='asearch') {
1775 $advanced = 1;
1776 echo '<input type="hidden" name="mode" value="list" />';
1777 }
a032a460 1778 echo '<label for="pref_perpage">'.get_string('pagesize','data').'</label> ';
76a2fd82 1779 $pagesizes = array(2=>2,3=>3,4=>4,5=>5,6=>6,7=>7,8=>8,9=>9,10=>10,15=>15,
6e0119dd 1780 20=>20,30=>30,40=>40,50=>50,100=>100,200=>200,300=>300,400=>400,500=>500,1000=>1000);
398be7c8 1781 echo html_writer::select($pagesizes, 'perpage', $perpage, false, array('id' => 'pref_perpage', 'class' => 'custom-select'));
0d284a8b 1782
7900ecb0 1783 if ($advanced) {
0d284a8b
DM
1784 $regsearchclass = 'search_none';
1785 $advancedsearchclass = 'search_inline';
1786 } else {
1787 $regsearchclass = 'search_inline';
1788 $advancedsearchclass = 'search_none';
7900ecb0 1789 }
e85fda95 1790 echo '<div id="reg_search" class="' . $regsearchclass . ' form-inline" >&nbsp;&nbsp;&nbsp;';
398be7c8
DW
1791 echo '<label for="pref_search">' . get_string('search') . '</label> <input type="text" ' .
1792 'class="form-control" size="16" name="search" id= "pref_search" value="' . s($search) . '" /></div>';
a032a460 1793 echo '&nbsp;&nbsp;&nbsp;<label for="pref_sortby">'.get_string('sortby').'</label> ';
b8b554ac 1794 // foreach field, print the option
e85fda95 1795 echo '<select name="sort" id="pref_sortby" class="custom-select m-r-1">';
9c00b5d7 1796 if ($fields = $DB->get_records('data_fields', array('dataid'=>$data->id), 'name')) {
3239b010 1797 echo '<optgroup label="'.get_string('fields', 'data').'">';
1798 foreach ($fields as $field) {
1799 if ($field->id == $sort) {
1800 echo '<option value="'.$field->id.'" selected="selected">'.$field->name.'</option>';
1801 } else {
1802 echo '<option value="'.$field->id.'">'.$field->name.'</option>';
1803 }
1804 }
1805 echo '</optgroup>';
714bec74 1806 }
3239b010 1807 $options = array();
1808 $options[DATA_TIMEADDED] = get_string('timeadded', 'data');
1809 $options[DATA_TIMEMODIFIED] = get_string('timemodified', 'data');
1810 $options[DATA_FIRSTNAME] = get_string('authorfirstname', 'data');
1811 $options[DATA_LASTNAME] = get_string('authorlastname', 'data');
bb5740f4 1812 if ($data->approval and has_capability('mod/data:approve', $context)) {
1813 $options[DATA_APPROVED] = get_string('approved', 'data');
1814 }
3239b010 1815 echo '<optgroup label="'.get_string('other', 'data').'">';
714bec74 1816 foreach ($options as $key => $name) {
1817 if ($key == $sort) {
1818 echo '<option value="'.$key.'" selected="selected">'.$name.'</option>';
cf3e199b 1819 } else {
714bec74 1820 echo '<option value="'.$key.'">'.$name.'</option>';
cf3e199b 1821 }
1822 }
3239b010 1823 echo '</optgroup>';
cf3e199b 1824 echo '</select>';
a032a460 1825 echo '<label for="pref_order" class="accesshide">'.get_string('order').'</label>';
e85fda95 1826 echo '<select id="pref_order" name="order" class="custom-select m-r-1">';
c8505cac 1827 if ($order == 'ASC') {
af25f45e 1828 echo '<option value="ASC" selected="selected">'.get_string('ascending','data').'</option>';
cf3e199b 1829 } else {
1830 echo '<option value="ASC">'.get_string('ascending','data').'</option>';
1831 }
c8505cac 1832 if ($order == 'DESC') {
af25f45e 1833 echo '<option value="DESC" selected="selected">'.get_string('descending','data').'</option>';
cf3e199b 1834 } else {
1835 echo '<option value="DESC">'.get_string('descending','data').'</option>';
1836 }
af25f45e 1837 echo '</select>';
86638489 1838
7900ecb0 1839 if ($advanced) {
1840 $checked = ' checked="checked" ';
1841 }
1842 else {
1843 $checked = '';
1844 }
9dec75db 1845 $PAGE->requires->js('/mod/data/data.js');
de8ff581 1846 echo '&nbsp;<input type="hidden" name="advanced" value="0" />';
d53e5129 1847 echo '&nbsp;<input type="hidden" name="filter" value="1" />';
398be7c8
DW
1848 echo '&nbsp;<input type="checkbox" id="advancedcheckbox" name="advanced" value="1" ' . $checked . ' ' .
1849 'onchange="showHideAdvSearch(this.checked);" class="m-x-1" />' .
1850 '<label for="advancedcheckbox">' . get_string('advancedsearch', 'data') . '</label>';
1851 echo '&nbsp;<input type="submit" class="btn btn-secondary" value="' . get_string('savesettings', 'data') . '" />';
8429163d 1852
7900ecb0 1853 echo '<br />';
0d284a8b 1854 echo '<div class="' . $advancedsearchclass . '" id="data_adv_form">';
7900ecb0 1855 echo '<table class="boxaligncenter">';
8429163d 1856
7900ecb0 1857 // print ASC or DESC
1858 echo '<tr><td colspan="2">&nbsp;</td></tr>';
1859 $i = 0;
1860
1861 // Determine if we are printing all fields for advanced search, or the template for advanced search
1862 // If a template is not defined, use the deafault template and display all fields.
1863 if(empty($data->asearchtemplate)) {
1864 data_generate_default_template($data, 'asearchtemplate');
1865 }
1866
2c216a6c
MN
1867 static $fields = array();
1868 static $dataid = null;
b572ce19 1869
7900ecb0 1870 if (empty($dataid)) {
1871 $dataid = $data->id;
1872 } else if ($dataid != $data->id) {
2c216a6c 1873 $fields = array();
7900ecb0 1874 }
1875
1876 if (empty($fields)) {
9c00b5d7 1877 $fieldrecords = $DB->get_records('data_fields', array('dataid'=>$data->id));
7900ecb0 1878 foreach ($fieldrecords as $fieldrecord) {
1879 $fields[]= data_get_field($fieldrecord, $data);
1880 }
7900ecb0 1881 }
1882
b8b554ac 1883 // Replacing tags
7900ecb0 1884 $patterns = array();
1885 $replacement = array();
1886
b8b554ac 1887 // Then we generate strings to replace for normal tags
7900ecb0 1888 foreach ($fields as $field) {
98f67312 1889 $fieldname = $field->field->name;
1890 $fieldname = preg_quote($fieldname, '/');
1891 $patterns[] = "/\[\[$fieldname\]\]/i";
714bec74 1892 $searchfield = data_get_field_from_id($field->field->id, $data);
7900ecb0 1893 if (!empty($search_array[$field->field->id]->data)) {
1894 $replacement[] = $searchfield->display_search_field($search_array[$field->field->id]->data);
1895 } else {
1896 $replacement[] = $searchfield->display_search_field();
1897 }
1898 }
714bec74 1899 $fn = !empty($search_array[DATA_FIRSTNAME]->data) ? $search_array[DATA_FIRSTNAME]->data : '';
1900 $ln = !empty($search_array[DATA_LASTNAME]->data) ? $search_array[DATA_LASTNAME]->data : '';
1901 $patterns[] = '/##firstname##/';
398be7c8
DW
1902 $replacement[] = '<label class="accesshide" for="u_fn">' . get_string('authorfirstname', 'data') . '</label>' .
1903 '<input type="text" class="form-control" size="16" id="u_fn" name="u_fn" value="' . s($fn) . '" />';
714bec74 1904 $patterns[] = '/##lastname##/';
398be7c8
DW
1905 $replacement[] = '<label class="accesshide" for="u_ln">' . get_string('authorlastname', 'data') . '</label>' .
1906 '<input type="text" class="form-control" size="16" id="u_ln" name="u_ln" value="' . s($ln) . '" />';
714bec74 1907
d45c7a68
AH
1908 if (core_tag_tag::is_enabled('mod_data', 'data_records')) {
1909 $patterns[] = "/##tags##/";
1910 $selectedtags = isset($search_array[DATA_TAGS]->rawtagnames) ? $search_array[DATA_TAGS]->rawtagnames : [];
1911 $replacement[] = data_generate_tag_form(false, $selectedtags);
1912 }
1913
668fc89a 1914 // actual replacement of the tags
7900ecb0 1915 $newtext = preg_replace($patterns, $replacement, $data->asearchtemplate);
b572ce19 1916
39790bd8 1917 $options = new stdClass();
7900ecb0 1918 $options->para=false;
1919 $options->noclean=true;
1920 echo '<tr><td>';
1921 echo format_text($newtext, FORMAT_HTML, $options);
1922 echo '</td></tr>';
b572ce19 1923
398be7c8
DW
1924 echo '<tr><td colspan="4"><br/>' .
1925 '<input type="submit" class="btn btn-primary m-r-1" value="' . get_string('savesettings', 'data') . '" />' .
1926 '<input type="submit" class="btn btn-secondary" name="resetadv" value="' . get_string('resetsettings', 'data') . '" />' .
1927 '</td></tr>';
7900ecb0 1928 echo '</table>';
c8505cac 1929 echo '</div>';
7900ecb0 1930 echo '</div>';
1931 echo '</form>';
b8b554ac 1932 echo '</div>';
3d4b223a 1933}
5f5bcda8 1934
4636bf83 1935/**
1936 * @global object
1937 * @global object
1938 * @param object $data
1939 * @param object $record
1940 * @return void Output echo'd
1941 */
4d3d87f0 1942function data_print_ratings($data, $record) {
56c1ca88 1943 global $OUTPUT;
2b04c41c 1944 if (!empty($record->rating)){
d251b259 1945 echo $OUTPUT->render($record->rating);
4d3d87f0 1946 }
4d3d87f0 1947}
1948
4636bf83 1949/**
b2b4ec30
RT
1950 * List the actions that correspond to a view of this module.
1951 * This is used by the participation report.
1952 *
1953 * Note: This is not used by new logging system. Event with
1954 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
1955 * be considered as view action.
4636bf83 1956 *
1957 * @return array
1958 */
4c03f920 1959function data_get_view_actions() {
1960 return array('view');
1961}
1962
4636bf83 1963/**
b2b4ec30
RT
1964 * List the actions that correspond to a post of this module.
1965 * This is used by the participation report.
1966 *
1967 * Note: This is not used by new logging system. Event with
1968 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
1969 * will be considered as post action.
1970 *
4636bf83 1971 * @return array
1972 */
4c03f920 1973function data_get_post_actions() {
1974 return array('add','update','record delete');
1975}
1976
4636bf83 1977/**
4636bf83 1978 * @param string $name
1979 * @param int $dataid
1980 * @param int $fieldid
1981 * @return bool
1982 */
e9da9f5b
PS
1983function data_fieldname_exists($name, $dataid, $fieldid = 0) {
1984 global $DB;
0997e51a 1985
e9da9f5b
PS
1986 if (!is_numeric($name)) {
1987 $like = $DB->sql_like('df.name', ':name', false);
fdeb3e1f 1988 } else {
e9da9f5b 1989 $like = "df.name = :name";
fdeb3e1f 1990 }
e9da9f5b 1991 $params = array('name'=>$name);
6403e679 1992 if ($fieldid) {
e9da9f5b
PS
1993 $params['dataid'] = $dataid;
1994 $params['fieldid1'] = $fieldid;
1995 $params['fieldid2'] = $fieldid;
9c00b5d7 1996 return $DB->record_exists_sql("SELECT * FROM {data_fields} df
e9da9f5b
PS
1997 WHERE $like AND df.dataid = :dataid
1998 AND ((df.id < :fieldid1) OR (df.id > :fieldid2))", $params);
0997e51a 1999 } else {
e9da9f5b 2000 $params['dataid'] = $dataid;
9c00b5d7 2001 return $DB->record_exists_sql("SELECT * FROM {data_fields} df
e9da9f5b 2002 WHERE $like AND df.dataid = :dataid", $params);
0997e51a 2003 }
2004}
2005
4636bf83 2006/**
2007 * @param array $fieldinput
2008 */
0997e51a 2009function data_convert_arrays_to_strings(&$fieldinput) {
2010 foreach ($fieldinput as $key => $val) {
2011 if (is_array($val)) {
2012 $str = '';
2013 foreach ($val as $inner) {
2014 $str .= $inner . ',';
2015 }
2016 $str = substr($str, 0, -1);
b572ce19 2017
0997e51a 2018 $fieldinput->$key = $str;
2019 }
2020 }
2021}
2022
901dd2fb 2023
7f258664 2024/**
2025 * Converts a database (module instance) to use the Roles System
4636bf83 2026 *
2027 * @global object
2028 * @global object
2029 * @uses CONTEXT_MODULE
2030 * @uses CAP_PREVENT
2031 * @uses CAP_ALLOW
2032 * @param object $data a data object with the same attributes as a record
2033 * from the data database table
2034 * @param int $datamodid the id of the data module, from the modules table
4f0c2d00
PS
2035 * @param array $teacherroles array of roles that have archetype teacher
2036 * @param array $studentroles array of roles that have archetype student
2037 * @param array $guestroles array of roles that have archetype guest
4636bf83 2038 * @param int $cmid the course_module id for this data instance
2039 * @return boolean data module was converted or not
7f258664 2040 */
2041function data_convert_to_roles($data, $teacherroles=array(), $studentroles=array(), $cmid=NULL) {
4102b449 2042 global $CFG, $DB, $OUTPUT;
6403e679 2043
7f258664 2044 if (!isset($data->participants) && !isset($data->assesspublic)
2045 && !isset($data->groupmode)) {
2046 // We assume that this database has already been converted to use the
2047 // Roles System. above fields get dropped the data module has been
2048 // upgraded to use Roles.
2049 return false;
2050 }
b572ce19 2051
7f258664 2052 if (empty($cmid)) {
2053 // We were not given the course_module id. Try to find it.
741c4d0b 2054 if (!$cm = get_coursemodule_from_instance('data', $data->id)) {
4102b449 2055 echo $OUTPUT->notification('Could not get the course module for the data');
7f258664 2056 return false;
2057 } else {
2058 $cmid = $cm->id;
2059 }
2060 }
0b3b8c30 2061 $context = context_module::instance($cmid);
6403e679 2062
b572ce19 2063
7f258664 2064 // $data->participants:
2065 // 1 - Only teachers can add entries
2066 // 3 - Teachers and students can add entries
2067 switch ($data->participants) {
2068 case 1:
2069 foreach ($studentroles as $studentrole) {
2070 assign_capability('mod/data:writeentry', CAP_PREVENT, $studentrole->id, $context->id);
2071 }
2072 foreach ($teacherroles as $teacherrole) {
2073 assign_capability('mod/data:writeentry', CAP_ALLOW, $teacherrole->id, $context->id);
2074 }
2075 break;
2076 case 3:
2077 foreach ($studentroles as $studentrole) {
2078 assign_capability('mod/data:writeentry', CAP_ALLOW, $studentrole->id, $context->id);
2079 }
2080 foreach ($teacherroles as $teacherrole) {
2081 assign_capability('mod/data:writeentry', CAP_ALLOW, $teacherrole->id, $context->id);
2082 }
2083 break;
2084 }
6403e679 2085
7f258664 2086 // $data->assessed:
2087 // 2 - Only teachers can rate posts
2088 // 1 - Everyone can rate posts
2089 // 0 - No one can rate posts
2090 switch ($data->assessed) {
2091 case 0:
2092 foreach ($studentroles as $studentrole) {
2093 assign_capability('mod/data:rate', CAP_PREVENT, $studentrole->id, $context->id);
2094 }
2095 foreach ($teacherroles as $teacherrole) {
2096 assign_capability('mod/data:rate', CAP_PREVENT, $teacherrole->id, $context->id);
2097 }
2098 break;
2099 case 1:
2100 foreach ($studentroles as $studentrole) {
2101 assign_capability('mod/data:rate', CAP_ALLOW, $studentrole->id, $context->id);
2102 }
2103 foreach ($teacherroles as $teacherrole) {
2104 assign_capability('mod/data:rate', CAP_ALLOW, $teacherrole->id, $context->id);
2105 }
2106 break;
2107 case 2:
2108 foreach ($studentroles as $studentrole) {
2109 assign_capability('mod/data:rate', CAP_PREVENT, $studentrole->id, $context->id);
2110 }
2111 foreach ($teacherroles as $teacherrole) {
2112 assign_capability('mod/data:rate', CAP_ALLOW, $teacherrole->id, $context->id);
2113 }
2114 break;
2115 }
6403e679 2116
7f258664 2117 // $data->assesspublic:
2118 // 0 - Students can only see their own ratings
2119 // 1 - Students can see everyone's ratings
2120 switch ($data->assesspublic) {
2121 case 0:
2122 foreach ($studentroles as $studentrole) {
2123 assign_capability('mod/data:viewrating', CAP_PREVENT, $studentrole->id, $context->id);
2124 }
2125 foreach ($teacherroles as $teacherrole) {
2126 assign_capability('mod/data:viewrating', CAP_ALLOW, $teacherrole->id, $context->id);
2127 }
2128 break;
2129 case 1:
2130 foreach ($studentroles as $studentrole) {
2131 assign_capability('mod/data:viewrating', CAP_ALLOW, $studentrole->id, $context->id);
2132 }
2133 foreach ($teacherroles as $teacherrole) {
2134 assign_capability('mod/data:viewrating', CAP_ALLOW, $teacherrole->id, $context->id);
2135 }
2136 break;
2137 }
2138
2139 if (empty($cm)) {
9c00b5d7 2140 $cm = $DB->get_record('course_modules', array('id'=>$cmid));
7f258664 2141 }
6403e679 2142
7f258664 2143 switch ($cm->groupmode) {
055f2185 2144 case NOGROUPS:
7f258664 2145 break;
055f2185 2146 case SEPARATEGROUPS:
7f258664 2147 foreach ($studentroles as $studentrole) {
2148 assign_capability('moodle/site:accessallgroups', CAP_PREVENT, $studentrole->id, $context->id);
2149 }
2150 foreach ($teacherroles as $teacherrole) {
2151 assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $teacherrole->id, $context->id);
2152 }
2153 break;
055f2185 2154 case VISIBLEGROUPS:
7f258664 2155 foreach ($studentroles as $studentrole) {
2156 assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $studentrole->id, $context->id);
2157 }
2158 foreach ($teacherroles as $teacherrole) {
2159 assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $teacherrole->id, $context->id);
2160 }
2161 break;
2162 }
2163 return true;
2164}
2165
4636bf83 2166/**
8303eb84 2167 * Returns the best name to show for a preset
4636bf83 2168 *
2169 * @param string $shortname
2170 * @param string $path
2171 * @return string
8303eb84 2172 */
2173function data_preset_name($shortname, $path) {
2174
668fc89a 2175 // We are looking inside the preset itself as a first choice, but also in normal data directory
30d76014 2176 $string = get_string('modulename', 'datapreset_'.$shortname);
8303eb84 2177
2178 if (substr($string, 0, 1) == '[') {
2179 return $shortname;
2180 } else {
2181 return $string;
2182 }
2183}
2184
4636bf83 2185/**
8aff1574 2186 * Returns an array of all the available presets.
4636bf83 2187 *
4636bf83 2188 * @return array
8303eb84 2189 */
2190function data_get_available_presets($context) {
2191 global $CFG, $USER;
b572ce19 2192
8303eb84 2193 $presets = array();
b572ce19 2194
8aff1574 2195 // First load the ratings sub plugins that exist within the modules preset dir
bd3b3bba 2196 if ($dirs = core_component::get_plugin_list('datapreset')) {
a9cda870 2197 foreach ($dirs as $dir=>$fulldir) {
8303eb84 2198 if (is_directory_a_preset($fulldir)) {
39790bd8 2199 $preset = new stdClass();
8303eb84 2200 $preset->path = $fulldir;
2201 $preset->userid = 0;
2202 $preset->shortname = $dir;
2203 $preset->name = data_preset_name($dir, $fulldir);
2204 if (file_exists($fulldir.'/screenshot.jpg')) {
2205 $preset->screenshot = $CFG->wwwroot.'/mod/data/preset/'.$dir.'/screenshot.jpg';
2206 } else if (file_exists($fulldir.'/screenshot.png')) {
2207 $preset->screenshot = $CFG->wwwroot.'/mod/data/preset/'.$dir.'/screenshot.png';
2208 } else if (file_exists($fulldir.'/screenshot.gif')) {
2209 $preset->screenshot = $CFG->wwwroot.'/mod/data/preset/'.$dir.'/screenshot.gif';
2210 }
2211 $presets[] = $preset;
2212 }
2213 }
2214 }
8aff1574
SH
2215 // Now add to that the site presets that people have saved
2216 $presets = data_get_available_site_presets($context, $presets);
2217 return $presets;
2218}
8303eb84 2219
8aff1574
SH
2220/**
2221 * Gets an array of all of the presets that users have saved to the site.
2222 *
2223 * @param stdClass $context The context that we are looking from.
2224 * @param array $presets
2225 * @return array An array of presets
2226 */
2227function data_get_available_site_presets($context, array $presets=array()) {
810860d2
PS
2228 global $USER;
2229
8aff1574
SH
2230 $fs = get_file_storage();
2231 $files = $fs->get_area_files(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA);
2232 $canviewall = has_capability('mod/data:viewalluserpresets', $context);
2233 if (empty($files)) {
2234 return $presets;
2235 }
2236 foreach ($files as $file) {
2237 if (($file->is_directory() && $file->get_filepath()=='/') || !$file->is_directory() || (!$canviewall && $file->get_userid() != $USER->id)) {
2238 continue;
2239 }
2240 $preset = new stdClass;
2241 $preset->path = $file->get_filepath();
2242 $preset->name = trim($preset->path, '/');
2243 $preset->shortname = $preset->name;
2244 $preset->userid = $file->get_userid();
2245 $preset->id = $file->get_id();
2246 $preset->storedfile = $file;
2247 $presets[] = $preset;
2248 }
2249 return $presets;
2250}
2251
2252/**
2253 * Deletes a saved preset.
2254 *
2255 * @param string $name
2256 * @return bool
2257 */
2258function data_delete_site_preset($name) {
2259 $fs = get_file_storage();
2260
2261 $files = $fs->get_directory_files(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, '/'.$name.'/');
2262 if (!empty($files)) {
2263 foreach ($files as $file) {
2264 $file->delete();
8303eb84 2265 }
2266 }
b572ce19 2267
8aff1574
SH
2268 $dir = $fs->get_file(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, '/'.$name.'/', '.');
2269 if (!empty($dir)) {
2270 $dir->delete();
2271 }
2272 return true;
8303eb84 2273}
2274
4636bf83 2275/**
8aff1574
SH
2276 * Prints the heads for a page
2277 *
2278 * @param stdClass $course
2279 * @param stdClass $cm
2280 * @param stdClass $data
4636bf83 2281 * @param string $currenttab
2282 */
8303eb84 2283function data_print_header($course, $cm, $data, $currenttab='') {
b572ce19 2284
b0ff558c 2285 global $CFG, $displaynoticegood, $displaynoticebad, $OUTPUT, $PAGE;
b572ce19 2286
b0ff558c 2287 $PAGE->set_title($data->name);
b0ff558c 2288 echo $OUTPUT->header();
66e2b9f8
AD
2289 echo $OUTPUT->heading(format_string($data->name), 2);
2290 echo $OUTPUT->box(format_module_intro('data', $data, $cm->id), 'generalbox', 'intro');
8303eb84 2291
66e2b9f8 2292 // Groups needed for Add entry tab
055f2185 2293 $currentgroup = groups_get_activity_group($cm);
5d59cbe9 2294 $groupmode = groups_get_activity_groupmode($cm);
b572ce19 2295
668fc89a 2296 // Print the tabs
b572ce19 2297
8303eb84 2298 if ($currenttab) {
138e480e 2299 include('tabs.php');
8303eb84 2300 }
b572ce19 2301
b8b554ac 2302 // Print any notices
b572ce19 2303
8303eb84 2304 if (!empty($displaynoticegood)) {
4102b449 2305 echo $OUTPUT->notification($displaynoticegood, 'notifysuccess'); // good (usually green)
8303eb84 2306 } else if (!empty($displaynoticebad)) {
4102b449 2307 echo $OUTPUT->notification($displaynoticebad); // bad (usuually red)
8303eb84 2308 }
2309}
7f258664 2310
4636bf83 2311/**
0393a8b7
PS
2312 * Can user add more entries?
2313 *
4636bf83 2314 * @param object $data
2315 * @param mixed $currentgroup
2316 * @param int $groupmode
0393a8b7 2317 * @param stdClass $context
4636bf83 2318 * @return bool
2319 */
e4e96115 2320function data_user_can_add_entry($data, $currentgroup, $groupmode, $context = null) {
cca1547e 2321 global $USER;
b572ce19 2322
e4e96115 2323 if (empty($context)) {
0393a8b7 2324 $cm = get_coursemodule_from_instance('data', $data->id, 0, false, MUST_EXIST);
0b3b8c30 2325 $context = context_module::instance($cm->id);
e4e96115
RW
2326 }
2327
0393a8b7
PS
2328 if (has_capability('mod/data:manageentries', $context)) {
2329 // no entry limits apply if user can manage
e4e96115 2330
0393a8b7 2331 } else if (!has_capability('mod/data:writeentry', $context)) {
e4e96115 2332 return false;
b572ce19 2333
0393a8b7 2334 } else if (data_atmaxentries($data)) {
cca1547e 2335 return false;
e8027a40
ARN
2336 } else if (data_in_readonly_period($data)) {
2337 // Check whether we're in a read-only period
2742ffe7
AD
2338 return false;
2339 }
2340
04366d79 2341 if (!$groupmode or has_capability('moodle/site:accessallgroups', $context)) {
2342 return true;
2343 }
2344
cca1547e 2345 if ($currentgroup) {
2c386f82 2346 return groups_is_member($currentgroup);
cca1547e 2347 } else {
2348 //else it might be group 0 in visible mode
2349 if ($groupmode == VISIBLEGROUPS){
cca1547e 2350 return true;
04366d79 2351 } else {
2352 return false;
cca1547e 2353 }
2354 }
2355}
2356
97fe80ad
JB
2357/**
2358 * Check whether the current user is allowed to manage the given record considering manageentries capability,
2359 * data_in_readonly_period() result, ownership (determined by data_isowner()) and manageapproved setting.
2360 * @param mixed $record record object or id
2361 * @param object $data data object
2362 * @param object $context context object
2363 * @return bool returns true if the user is allowd to edit the entry, false otherwise
2364 */
2365function data_user_can_manage_entry($record, $data, $context) {
2366 global $DB;
2367
2368 if (has_capability('mod/data:manageentries', $context)) {
2369 return true;
2370 }
2371
2372 // Check whether this activity is read-only at present.
2373 $readonly = data_in_readonly_period($data);
2374
2375 if (!$readonly) {
2376 // Get record object from db if just id given like in data_isowner.
2377 // ...done before calling data_isowner() to avoid querying db twice.
2378 if (!is_object($record)) {
2379 if (!$record = $DB->get_record('data_records', array('id' => $record))) {
2380 return false;
2381 }
2382 }
2383 if (data_isowner($record)) {
2384 if ($data->approval && $record->approved) {
2385 return $data->manageapproved == 1;
2386 } else {
2387 return true;
2388 }
2389 }
2390 }
2391
2392 return false;
2393}
2394
e8027a40
ARN
2395/**
2396 * Check whether the specified database activity is currently in a read-only period
2397 *
2398 * @param object $data
2399 * @return bool returns true if the time fields in $data indicate a read-only period; false otherwise
2400 */
2401function data_in_readonly_period($data) {
2402 $now = time();
2403 if (!$data->timeviewfrom && !$data->timeviewto) {
2404 return false;
2405 } else if (($data->timeviewfrom && $now < $data->timeviewfrom) || ($data->timeviewto && $now > $data->timeviewto)) {
2406 return false;
2407 }
2408 return true;
2409}
50194545 2410
4636bf83 2411/**
2412 * @return bool
2413 */
50194545 2414function is_directory_a_preset($directory) {
2415 $directory = rtrim($directory, '/\\') . '/';
2dc6be3f 2416 $status = file_exists($directory.'singletemplate.html') &&
2417 file_exists($directory.'listtemplate.html') &&
2418 file_exists($directory.'listtemplateheader.html') &&
2419 file_exists($directory.'listtemplatefooter.html') &&
2420 file_exists($directory.'addtemplate.html') &&
2421 file_exists($directory.'rsstemplate.html') &&
2422 file_exists($directory.'rsstitletemplate.html') &&
2423 file_exists($directory.'csstemplate.css') &&
2424 file_exists($directory.'jstemplate.js') &&
2425 file_exists($directory.'preset.xml');
b572ce19 2426
2dc6be3f 2427 return $status;
50194545 2428}
2429
4636bf83 2430/**
cba87c36 2431 * Abstract class used for data preset importers
4636bf83 2432 */
cba87c36 2433abstract class data_preset_importer {
b572ce19 2434
cba87c36
SH
2435 protected $course;
2436 protected $cm;
2437 protected $module;
2438 protected $directory;
50194545 2439
4636bf83 2440 /**
cba87c36
SH
2441 * Constructor
2442 *
2443 * @param stdClass $course
2444 * @param stdClass $cm
2445 * @param stdClass $module
2446 * @param string $directory
4636bf83 2447 */
cba87c36 2448 public function __construct($course, $cm, $module, $directory) {
50194545 2449 $this->course = $course;
2450 $this->cm = $cm;
cba87c36
SH
2451 $this->module = $module;
2452 $this->directory = $directory;
2453 }
2454
2455 /**
2456 * Returns the name of the directory the preset is located in
2457 * @return string
2458 */
2459 public function get_directory() {
2460 return basename($this->directory);
50194545 2461 }
263819c8
AD
2462
2463 /**
2464 * Retreive the contents of a file. That file may either be in a conventional directory of the Moodle file storage
2465 * @param file_storage $filestorage. should be null if using a conventional directory
2466 * @param stored_file $fileobj the directory to look in. null if using a conventional directory
2467 * @param string $dir the directory to look in. null if using the Moodle file storage
2468 * @param string $filename the name of the file we want
c600a85c 2469 * @return string the contents of the file or null if the file doesn't exist.
263819c8
AD
2470 */
2471 public function data_preset_get_file_contents(&$filestorage, &$fileobj, $dir, $filename) {
2472 if(empty($filestorage) || empty($fileobj)) {
2473 if (substr($dir, -1)!='/') {
2474 $dir .= '/';
2475 }
c600a85c
AG
2476 if (file_exists($dir.$filename)) {
2477 return file_get_contents($dir.$filename);
2478 } else {
2479 return null;
2480 }
263819c8 2481 } else {
c600a85c
AG
2482 if ($filestorage->file_exists(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, $fileobj->get_filepath(), $filename)) {
2483 $file = $filestorage->get_file(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, $fileobj->get_filepath(), $filename);
2484 return $file->get_content();
2485 } else {
2486 return null;
2487 }
263819c8
AD
2488 }
2489
2490 }
4636bf83 2491 /**
cba87c36
SH
2492 * Gets the preset settings
2493 * @global moodle_database $DB
2494 * @return stdClass
4636bf83 2495 */
cba87c36
SH
2496 public function get_preset_settings() {
2497 global $DB;
50194545 2498
263819c8 2499 $fs = $fileobj = null;
cba87c36 2500 if (!is_directory_a_preset($this->directory)) {
263819c8 2501 //maybe the user requested a preset stored in the Moodle file storage
375053ed 2502
263819c8
AD
2503 $fs = get_file_storage();
2504 $files = $fs->get_area_files(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA);
2505
720f37fd 2506 //preset name to find will be the final element of the directory
c600a85c
AG
2507 $explodeddirectory = explode('/', $this->directory);
2508 $presettofind = end($explodeddirectory);
720f37fd
AD
2509
2510 //now go through the available files available and see if we can find it
263819c8
AD
2511 foreach ($files as $file) {
2512 if (($file->is_directory() && $file->get_filepath()=='/') || !$file->is_directory()) {
2513 continue;
2514 }
2515 $presetname = trim($file->get_filepath(), '/');
720f37fd 2516 if ($presetname==$presettofind) {
263819c8
AD
2517 $this->directory = $presetname;
2518 $fileobj = $file;
2519 }
2520 }
2521
2522 if (empty($fileobj)) {
2523 print_error('invalidpreset', 'data', '', $this->directory);
2524 }
50194545 2525 }
2526
cba87c36
SH
2527 $allowed_settings = array(
2528 'intro',
2529 'comments',
2530 'requiredentries',
2531 'requiredentriestoview',
2532 'maxentries',
2533 'rssarticles',
2534 'approval',
2535 'defaultsortdir',
2536 'defaultsort');
2537
2538 $result = new stdClass;
2539 $result->settings = new stdClass;
2540 $result->importfields = array();
2541 $result->currentfields = $DB->get_records('data_fields', array('dataid'=>$this->module->id));
2542 if (!$result->currentfields) {
2543 $result->currentfields = array();
2544 }
2545
2546
50194545 2547 /* Grab XML */
263819c8 2548 $presetxml = $this->data_preset_get_file_contents($fs, $fileobj, $this->directory,'preset.xml');
143c1eb9 2549 $parsedxml = xmlize($presetxml, 0);
50194545 2550
2551 /* First, do settings. Put in user friendly array. */
2552 $settingsarray = $parsedxml['preset']['#']['settings'][0]['#'];
cba87c36 2553 $result->settings = new StdClass();
50194545 2554 foreach ($settingsarray as $setting => $value) {
cba87c36 2555 if (!is_array($value) || !in_array($setting, $allowed_settings)) {
eaa30818 2556 // unsupported setting
2557 continue;
2558 }
cba87c36 2559 $result->settings->$setting = $value[0]['#'];
50194545 2560 }
2561
2562 /* Now work out fields to user friendly array */
2563 $fieldsarray = $parsedxml['preset']['#']['field'];
50194545 2564 foreach ($fieldsarray as $field) {
02007b01 2565 if (!is_array($field)) {
2566 continue;
2567 }
50194545 2568 $f = new StdClass();
2569 foreach ($field['#'] as $param => $value) {
02007b01 2570 if (!is_array($value)) {
2571 continue;
2572 }
9c00b5d7 2573 $f->$param = $value[0]['#'];
50194545 2574 }
cba87c36 2575 $f->dataid = $this->module->id;
50194545 2576 $f->type = clean_param($f->type, PARAM_ALPHA);
cba87c36 2577 $result->importfields[] = $f;
50194545 2578 }
50194545 2579 /* Now add the HTML templates to the settings array so we can update d */
263819c8
AD
2580 $result->settings->singletemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"singletemplate.html");
2581 $result->settings->listtemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"listtemplate.html");
2582 $result->settings->listtemplateheader = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"listtemplateheader.html");
2583 $result->settings->listtemplatefooter = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"listtemplatefooter.html");
2584 $result->settings->addtemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"addtemplate.html");
2585 $result->settings->rsstemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"rsstemplate.html");
2586 $result->settings->rsstitletemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"rsstitletemplate.html");
2587 $result->settings->csstemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"csstemplate.css");
2588 $result->settings->jstemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"jstemplate.js");
c600a85c 2589 $result->settings->asearchtemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"asearchtemplate.html");
50194545 2590
cba87c36 2591 $result->settings->instance = $this->module->id;
cba87c36 2592 return $result;
50194545 2593 }
2594
4636bf83 2595 /**
cba87c36 2596 * Import the preset into the given database module
4636bf83 2597 * @return bool
2598 */
cba87c36 2599 function import($overwritesettings) {
fe9d5f7e 2600 global $DB, $CFG;
50194545 2601
cba87c36
SH
2602 $params = $this->get_preset_settings();
2603 $settings = $params->settings;
2604 $newfields = $params->importfields;
2605 $currentfields = $params->currentfields;
50194545 2606 $preservedfields = array();
b572ce19 2607
50194545 2608 /* Maps fields and makes new ones */
2609 if (!empty($newfields)) {
2610 /* We require an injective mapping, and need to know what to protect */
2611 foreach ($newfields as $nid => $newfield) {
2612 $cid = optional_param("field_$nid", -1, PARAM_INT);
cba87c36
SH
2613 if ($cid == -1) {
2614 continue;
2615 }
29c1bb15 2616 if (array_key_exists($cid, $preservedfields)){
2617 print_error('notinjectivemap', 'data');
8429163d 2618 }
50194545 2619 else $preservedfields[$cid] = true;
2620 }
b572ce19 2621
50194545 2622 foreach ($newfields as $nid => $newfield) {
2623 $cid = optional_param("field_$nid", -1, PARAM_INT);
b572ce19 2624
50194545 2625 /* A mapping. Just need to change field params. Data kept. */
2626 if ($cid != -1 and isset($currentfields[$cid])) {
cba87c36 2627 $fieldobject = data_get_field_from_id($currentfields[$cid]->id, $this->module);
50194545 2628 foreach ($newfield as $param => $value) {
2629 if ($param != "id") {
2630 $fieldobject->field->$param = $value;
2631 }
2632 }
2633 unset($fieldobject->field->similarfield);
2634 $fieldobject->update_field();
2635 unset($fieldobject);
cba87c36
SH
2636 } else {
2637 /* Make a new field */
50194545 2638 include_once("field/$newfield->type/field.class.php");
b572ce19 2639
50194545 2640 if (!isset($newfield->description)) {
2641 $newfield->description = '';
2642 }
2643 $classname = 'data_field_'.$newfield->type;
cba87c36 2644 $fieldclass = new $classname($newfield, $this->module);
50194545 2645 $fieldclass->insert_field();
2646 unset($fieldclass);
2647 }
2648 }
2649 }
2650
2651 /* Get rid of all old unused data */
2652 if (!empty($preservedfields)) {
2653 foreach ($currentfields as $cid => $currentfield) {
2654 if (!array_key_exists($cid, $preservedfields)) {
2655 /* Data not used anymore so wipe! */
2656 print "Deleting field $currentfield->name<br />";
b572ce19 2657
50194545 2658 $id = $currentfield->id;
2659 //Why delete existing data records and related comments/ratings??
9c00b5d7 2660 $DB->delete_records('data_content', array('fieldid'=>$id));
2661 $DB->delete_records('data_fields', array('id'=>$id));
50194545 2662 }
2663 }
2664 }
2665
cba87c36 2666 // handle special settings here
eaa30818 2667 if (!empty($settings->defaultsort)) {
2668 if (is_numeric($settings->defaultsort)) {
668fc89a 2669 // old broken value
eaa30818 2670 $settings->defaultsort = 0;
2671 } else {
cba87c36 2672 $settings->defaultsort = (int)$DB->get_field('data_fields', 'id', array('dataid'=>$this->module->id, 'name'=>$settings->defaultsort));
eaa30818 2673 }
2674 } else {
2675 $settings->defaultsort = 0;
2676 }
2677
2678 // do we want to overwrite all current database settings?
8528bf26 2679 if ($overwritesettings) {
eaa30818 2680 // all supported settings
8528bf26 2681 $overwrite = array_keys((array)$settings);
2682 } else {
eaa30818 2683 // only templates and sorting
8528bf26 2684 $overwrite = array('singletemplate', 'listtemplate', 'listtemplateheader', 'listtemplatefooter',
2685 'addtemplate', 'rsstemplate', 'rsstitletemplate', 'csstemplate', 'jstemplate',
eaa30818 2686 'asearchtemplate', 'defaultsortdir', 'defaultsort');
8528bf26 2687 }
2688
eaa30818 2689 // now overwrite current data settings
cba87c36 2690 foreach ($this->module as $prop=>$unused) {
8528bf26 2691 if (in_array($prop, $overwrite)) {
cba87c36 2692 $this->module->$prop = $settings->$prop;
13534ef7
ML
2693 }
2694 }
db0f2a44 2695
cba87c36 2696 data_update_instance($this->module);
50194545 2697
cba87c36
SH
2698 return $this->cleanup();
2699 }
b572ce19 2700
cba87c36
SH
2701 /**
2702 * Any clean up routines should go here
2703 * @return bool
2704 */
2705 public function cleanup() {
50194545 2706 return true;
2707 }
2708}
2709
cba87c36
SH
2710/**
2711 * Data preset importer for uploaded presets
2712 */
2713class data_preset_upload_importer extends data_preset_importer {
2714 public function __construct($course, $cm, $module, $filepath) {
2715 global $USER;
2716 if (is_file($filepath)) {
2717 $fp = get_file_packer();
2718 if ($fp->extract_to_pathname($filepath, $filepath.'_extracted')) {
2719 fulldelete($filepath);
2720 }
2721 $filepath .= '_extracted';
2722 }
2723 parent::__construct($course, $cm, $module, $filepath);
2724 }
2725 public function cleanup() {
2726 return fulldelete($this->directory);
2727 }
2728}
2729
2730/**
2731 * Data preset importer for existing presets
2732 */
2733class data_preset_existing_importer extends data_preset_importer {
2734 protected $userid;
2735 public function __construct($course, $cm, $module, $fullname) {
2736 global $USER;
2737 list($userid, $shortname) = explode('/', $fullname, 2);
0b3b8c30 2738 $context = context_module::instance($cm->id);
cba87c36
SH
2739 if ($userid && ($userid != $USER->id) && !has_capability('mod/data:manageuserpresets', $context) && !has_capability('mod/data:viewalluserpresets', $context)) {
2740 throw new coding_exception('Invalid preset provided');
2741 }
2742
2743 $this->userid = $userid;
2744 $filepath = data_preset_path($course, $userid, $shortname);
2745 parent::__construct($course, $cm, $module, $filepath);
2746 }
2747 public function get_userid() {
2748 return $this->userid;
2749 }
2750}
2751
4636bf83 2752/**
2753 * @global object
2754 * @global object
2755 * @param object $course
2756 * @param int $userid
2757 * @param string $shortname
2758 * @return string
2759 */
50194545 2760function data_preset_path($course, $userid, $shortname) {
2761 global $USER, $CFG;
b572ce19 2762
0b3b8c30 2763 $context = context_course::instance($course->id);
b572ce19 2764
50194545 2765 $userid = (int)$userid;
b572ce19 2766
263819c8 2767 $path = null;
50194545 2768 if ($userid > 0 && ($userid == $USER->id || has_capability('mod/data:viewalluserpresets', $context))) {
263819c8 2769 $path = $CFG->dataroot.'/data/preset/'.$userid.'/'.$shortname;
50194545 2770 } else if ($userid == 0) {
263819c8 2771 $path = $CFG->dirroot.'/mod/data/preset/'.$shortname;
50194545 2772 } else if ($userid < 0) {
7aa06e6d 2773 $path = $CFG->tempdir.'/data/'.-$userid.'/'.$shortname;
50194545 2774 }
b572ce19 2775
263819c8 2776 return $path;
50194545 2777}
0b5a80a1 2778
2779/**
2780 * Implementation of the function for printing the form elements that control
2781 * whether the course reset functionality affects the data.
4636bf83 2782 *
0b5a80a1 2783 * @param $mform form passed by reference
2784 */
2785function data_reset_course_form_definition(&$mform) {
2786 $mform->addElement('header', 'dataheader', get_string('modulenameplural', 'data'));
2787 $mform->addElement('checkbox', 'reset_data', get_string('deleteallentries','data'));
2788
2789 $mform->addElement('checkbox', 'reset_data_notenrolled', get_string('deletenotenrolled', 'data'));
2790 $mform->disabledIf('reset_data_notenrolled', 'reset_data', 'checked');
2791
2792 $mform->addElement('checkbox', 'reset_data_ratings', get_string('deleteallratings'));
2793 $mform->disabledIf('reset_data_ratings', 'reset_data', 'checked');
2794
2795 $mform->addElement('checkbox', 'reset_data_comments', get_string('deleteallcomments'));
2796 $mform->disabledIf('reset_data_comments', 'reset_data', 'checked');
2797}
2798
2799/**
2800 * Course reset form defaults.
4636bf83 2801 * @return array
0b5a80a1 2802 */
2803function data_reset_course_form_defaults($course) {
2804 return array('reset_data'=>0, 'reset_data_ratings'=>1, 'reset_data_comments'=>1, 'reset_data_notenrolled'=>0);
2805}
2806
2807/**
2808 * Removes all grades from gradebook
4636bf83 2809 *
2810 * @global object
2811 * @global object
0b5a80a1 2812 * @param int $courseid
4636bf83 2813 * @param string $type optional type
0b5a80a1 2814 */
2815function data_reset_gradebook($courseid, $type='') {
9c00b5d7 2816 global $CFG, $DB;
0b5a80a1 2817
2818 $sql = "SELECT d.*, cm.idnumber as cmidnumber, d.course as courseid
9c00b5d7 2819 FROM {data} d, {course_modules} cm, {modules} m
2820 WHERE m.name='data' AND m.id=cm.module AND cm.instance=d.id AND d.course=?";
0b5a80a1 2821
9c00b5d7 2822 if ($datas = $DB->get_records_sql($sql, array($courseid))) {
0b5a80a1 2823 foreach ($datas as $data) {
2824 data_grade_item_update($data, 'reset');
2825 }
2826 }
2827}
2828
2829/**
72d2982e 2830 * Actual implementation of the reset course functionality, delete all the
0b5a80a1 2831 * data responses for course $data->courseid.
4636bf83 2832 *
2833 * @global object
2834 * @global object
2835 * @param object $data the data submitted from the reset course.
0b5a80a1 2836 * @return array status array
2837 */
2838function data_reset_userdata($data) {
9c00b5d7 2839 global $CFG, $DB;
0b5a80a1 2840 require_once($CFG->libdir.'/filelib.php');
d251b259 2841 require_once($CFG->dirroot.'/rating/lib.php');
b572ce19 2842
0b5a80a1 2843 $componentstr = get_string('modulenameplural', 'data');
2844 $status = array();
b572ce19 2845
0b5a80a1 2846 $allrecordssql = "SELECT r.id
9c00b5d7 2847 FROM {data_records} r
2848 INNER JOIN {data} d ON r.dataid = d.id
2849 WHERE d.course = ?";
0b5a80a1 2850
2851 $alldatassql = "SELECT d.id
9c00b5d7 2852 FROM {data} d
2853 WHERE d.course=?";
0b5a80a1 2854
d251b259 2855 $rm = new rating_manager();
2b04c41c
SH
2856 $ratingdeloptions = new stdClass;
2857 $ratingdeloptions->component = 'mod_data';
2858 $ratingdeloptions->ratingarea = 'entry';
d251b259 2859
4e457296
MN
2860 // Set the file storage - may need it to remove files later.
2861 $fs = get_file_storage();
2862
0b5a80a1 2863 // delete entries if requested
2864 if (!empty($data->reset_data)) {
e998effa 2865 $DB->delete_records_select('comments', "itemid IN ($allrecordssql) AND commentarea='database_entry'", array($data->courseid));
9c00b5d7 2866 $DB->delete_records_select('data_content', "recordid IN ($allrecordssql)", array($data->courseid));
2867 $DB->delete_records_select('data_records', "dataid IN ($alldatassql)", array($data->courseid));
0b5a80a1 2868
9c00b5d7 2869 if ($datas = $DB->get_records_sql($alldatassql, array($data->courseid))) {
0b5a80a1 2870 foreach ($datas as $dataid=>$unused) {
d251b259
AD
2871 if (!$cm = get_coursemodule_from_instance('data', $dataid)) {
2872 continue;
2873 }
0b3b8c30 2874 $datacontext = context_module::instance($cm->id);
d251b259 2875
4e457296
MN
2876 // Delete any files that may exist.
2877 $fs->delete_area_files($datacontext->id, 'mod_data', 'content');
2878
d251b259
AD
2879 $ratingdeloptions->contextid = $datacontext->id;
2880 $rm->delete_ratings($ratingdeloptions);
0b5a80a1 2881 }
2882 }
b572ce19 2883
0b5a80a1 2884 if (empty($data->reset_gradebook_grades)) {
2885 // remove all grades from gradebook
2886 data_reset_gradebook($data->courseid);
2887 }
2888 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallentries', 'data'), 'error'=>false);
2889 }
2890
2891 // remove entries by users not enrolled into course
2892 if (!empty($data->reset_data_notenrolled)) {
2893 $recordssql = "SELECT r.id, r.userid, r.dataid, u.id AS userexists, u.deleted AS userdeleted
9c00b5d7 2894 FROM {data_records} r
2895 JOIN {data} d ON r.dataid = d.id
2896 LEFT JOIN {user} u ON r.userid = u.id
2897 WHERE d.course = ? AND r.userid > 0";
0b5a80a1 2898
0b3b8c30 2899 $course_context = context_course::instance($data->courseid);
0b5a80a1 2900 $notenrolled = array();
2901 $fields = array();
6b1b1d03
EL
2902 $rs = $DB->get_recordset_sql($recordssql, array($data->courseid));
2903 foreach ($rs as $record) {
2904 if (array_key_exists($record->userid, $notenrolled) or !$record->userexists or $record->userdeleted
2905 or !is_enrolled($course_context, $record->userid)) {
2906 //delete ratings
2907 if (!$cm = get_coursemodule_from_instance('data', $record->dataid)) {
2908 continue;
2909 }
0b3b8c30 2910 $datacontext = context_module::instance($cm->id);
6b1b1d03
EL
2911 $ratingdeloptions->contextid = $datacontext->id;
2912 $ratingdeloptions->itemid = $record->id;
2913 $rm->delete_ratings($ratingdeloptions);
2914
4e457296
MN
2915 // Delete any files that may exist.
2916 if ($contents = $DB->get_records('data_content', array('recordid' => $record->id), '', 'id')) {
2917 foreach ($contents as $content) {
2918 $fs->delete_area_files($datacontext->id, 'mod_data', 'content', $content->id);
0b5a80a1 2919 }
0b5a80a1 2920 }
6b1b1d03 2921 $notenrolled[$record->userid] = true;
4e457296
MN
2922
2923 $DB->delete_records('comments', array('itemid' => $record->id, 'commentarea' => 'database_entry'));
2924 $DB->delete_records('data_content', array('recordid' => $record->id));
2925 $DB->delete_records('data_records', array('id' => $record->id));
0b5a80a1 2926 }
0b5a80a1 2927 }
6b1b1d03
EL
2928 $rs->close();
2929 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletenotenrolled', 'data'), 'error'=>false);
0b5a80a1 2930 }
2931
2932 // remove all ratings
2933 if (!empty($data->reset_data_ratings)) {
d251b259
AD
2934 if ($datas = $DB->get_records_sql($alldatassql, array($data->courseid))) {
2935 foreach ($datas as $dataid=>$unused) {
2936 if (!$cm = get_coursemodule_from_instance('data', $dataid)) {
2937 continue;
2938 }
0b3b8c30 2939 $datacontext = context_module::instance($cm->id);
d251b259
AD
2940
2941 $ratingdeloptions->contextid = $datacontext->id;
2942 $rm->delete_ratings($ratingdeloptions);
2943 }
2944 }
0b5a80a1 2945
2946 if (empty($data->reset_gradebook_grades)) {
2947 // remove all grades from gradebook
2948 data_reset_gradebook($data->courseid);
2949 }
b572ce19 2950
0b5a80a1 2951 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallratings'), 'error'=>false);
2952 }
2953
2954 // remove all comments
2955 if (!empty($data->reset_data_comments)) {
e998effa 2956 $DB->delete_records_select('comments', "itemid IN ($allrecordssql) AND commentarea='database_entry'", array($data->courseid));
0b5a80a1 2957 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallcomments'), 'error'=>false);
2958 }
2959
b8b554ac 2960 // updating dates - shift may be negative too
0b5a80a1 2961 if ($data->timeshift) {
0d14fcbc
AA
2962 // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
2963 // See MDL-9367.
2964 shift_course_mod_dates('data', array('timeavailablefrom', 'timeavailableto',
2965 'timeviewfrom', 'timeviewto', 'assesstimestart', 'assesstimefinish'), $data->timeshift, $data->courseid);
0b5a80a1 2966 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
2967 }
b572ce19 2968
0b5a80a1 2969 return $status;
2970}
f432bebf 2971
2972/**
2973 * Returns all other caps used in module
4636bf83 2974 *
2975 * @return array
f432bebf 2976 */
2977function data_get_extra_capabilities() {
16b86ae4 2978 return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames', 'moodle/rating:view', 'moodle/rating:viewany', 'moodle/rating:viewall', 'moodle/rating:rate', 'moodle/comment:view', 'moodle/comment:post', 'moodle/comment:delete');
f432bebf 2979}
2980
18a2a0cb 2981/**
2982 * @param string $feature FEATURE_xx constant for requested feature
2983 * @return mixed True if module supports feature, null if doesn't know
2984 */
2985function data_supports($feature) {
2986 switch($feature) {
42f103be 2987 case FEATURE_GROUPS: return true;
2988 case FEATURE_GROUPINGS: return true;
dc5c2bd9 2989 case FEATURE_MOD_INTRO: return true;
18a2a0cb 2990 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
cf873ada 2991 case FEATURE_COMPLETION_HAS_RULES: return true;
42f103be 2992 case FEATURE_GRADE_HAS_GRADE: return true;
2993 case FEATURE_GRADE_OUTCOMES: return true;
d251b259 2994 case FEATURE_RATE: return true;
fd3f6bf9 2995 case FEATURE_BACKUP_MOODLE2: return true;
3e4c2435 2996 case FEATURE_SHOW_DESCRIPTION: return true;
6492401d 2997 case FEATURE_COMMENT: return true;
42f103be 2998
18a2a0cb 2999 default: return null;
17da2e6f 3000 }
18a2a0cb 3001}
4636bf83 3002/**
3003 * @global object
3004 * @param array $export
3005 * @param string $delimiter_name
3006 * @param object $database
3007 * @param int $count
3008 * @param bool $return
3009 * @return string|void
3010 */
9a5abd1b 3011function data_export_csv($export, $delimiter_name, $database, $count, $return=false) {
ecd06483 3012 global $CFG;
3013 require_once($CFG->libdir . '/csvlib.class.php');
9a5abd1b
AG
3014
3015 $filename = $database . '-' . $count . '-record';
20988152 3016 if ($count > 1) {
3017 $filename .= 's';
3018 }
9a5abd1b
AG
3019 if ($return) {
3020 return csv_export_writer::print_array($export, $delimiter_name, '"', true);
3021 } else {
3022 csv_export_writer::download_array($filename, $export, $delimiter_name);
20988152 3023 }
3024}
3025
4636bf83 3026/**
3027 * @global object
3028 * @param array $export
3029 * @param string $dataname
3030 * @param int $count
3031 * @return string
3032 */
1bf8c6b2 3033function data_export_xls($export, $dataname, $count) {
20988152 3034 global $CFG;
3035 require_once("$CFG->libdir/excellib.class.php");
fa7f82be 3036 $filename = clean_filename("{$dataname}-{$count}_record");
20988152 3037 if ($count > 1) {
3038 $filename .= 's';
3039 }
3040 $filename .= clean_filename('-' . gmdate("Ymd_Hi"));
3041 $filename .= '.xls';
ecd06483 3042
3043 $filearg = '-';
ecd06483 3044 $workbook = new MoodleExcelWorkbook($filearg);
1bf8c6b2 3045 $workbook->send($filename);
20988152 3046 $worksheet = array();
75427a82 3047 $worksheet[0] = $workbook->add_worksheet('');
20988152 3048 $rowno = 0;
3049 foreach ($export as $row) {
3050 $colno = 0;
3051 foreach($row as $col) {
3052 $worksheet[0]->write($rowno, $colno, $col);
3053 $colno++;
3054 }
3055 $rowno++;
3056 }
3057 $workbook->close();
ecd06483 3058 return $filename;
20988152 3059}
3060
4636bf83 3061/**
3062 * @global object
3063 * @param array $export
3064 * @param string $dataname
3065 * @param int $count
3066 * @param string
3067 */
1bf8c6b2 3068function data_export_ods($export, $dataname, $count) {
20988152 3069 global $CFG;
3070 require_once("$CFG->libdir/odslib.class.php");
fa7f82be 3071 $filename = clean_filename("{$dataname}-{$count}_record");
20988152 3072 if ($count > 1) {
3073 $filename .= 's';
3074 }
3075 $filename .= clean_filename('-' . gmdate("Ymd_Hi"));
3076 $filename .= '.ods';
ecd06483 3077 $filearg = '-';
1bf8c6b2 3078 $workbook = new MoodleODSWorkbook($filearg);
3079 $workbook->send($filename);
20988152 3080 $worksheet = array();
75427a82 3081 $worksheet[0] = $workbook->add_worksheet('');
20988152 3082 $rowno = 0;
3083 foreach ($export as $row) {
3084 $colno = 0;
3085 foreach($row as $col) {
3086 $worksheet[0]->write($rowno, $colno, $col);
3087 $colno++;
3088 }
3089 $rowno++;
3090 }
3091 $workbook->close();
ecd06483 3092 return $filename;
3093}
3094
4636bf83 3095/**
3096 * @global object
3097 * @param int $dataid
3098 * @param array $fields
3099 * @param array $selectedfields
83468603
AG
3100 * @param int $currentgroup group ID of the current group. This is used for
3101 * exporting data while maintaining group divisions.
6e12c215
AB
3102 * @param object $context the context in which the operation is performed (for capability checks)
3103 * @param bool $userdetails whether to include the details of the record author
3104 * @param bool $time whether to include time created/modified
3105 * @param bool $approval whether to include approval status
04f7b079 3106 * @param bool $tags whether to include tags
4636bf83 3107 * @return array
3108 */
4f304eeb 3109function data_get_exportdata($dataid, $fields, $selectedfields, $currentgroup=0, $context=null,
04f7b079 3110 $userdetails=false, $time=false, $approval=false, $tags = false) {
ecd06483 3111 global $DB;
3112
4f304eeb
HB
3113 if (is_null($context)) {
3114 $context = context_system::instance();
3115 }
3116 // exporting user data needs special permission
3117 $userdetails = $userdetails && has_capability('mod/data:exportuserinfo', $context);
3118
ecd06483 3119 $exportdata = array();
3120
3121 // populate the header in first row of export
3122 foreach($fields as $key => $field) {
3123 if (!in_array($field->field->id, $selectedfields)) {
3124 // ignore values we aren't exporting
3125 unset($fields[$key]);
3126 } else {
3127 $exportdata[0][] = $field->field->name;
3128 }
3129 }
4f304eeb
HB
3130 if ($userdetails) {
3131 $exportdata[0][] = get_string('user');
3132 $exportdata[0][] = get_string('username');
3133 $exportdata[0][] = get_string('email');
3134 }
3135 if ($time) {
3136 $exportdata[0][] = get_string('timeadded', 'data');
3137 $exportdata[0][] = get_string('timemodified', 'data');
3138 }
3139 if ($approval) {
3140 $exportdata[0][] = get_string('approved', 'data');
3141 }
04f7b079
AH
3142 if ($tags) {
3143 $exportdata[0][] = get_string('tags', 'data');
3144 }
ecd06483 3145
3146 $datarecords = $DB->get_records('data_records', array('dataid'=>$dataid));
3147 ksort($datarecords);
3148 $line = 1;
3149 foreach($datarecords as $record) {
3150 // get content indexed by fieldid
83468603
AG
3151 if ($currentgroup) {
3152 $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 = ?';
3153 $where = array($record->id, $currentgroup);
3154 } else {
3155 $select = 'SELECT fieldid, content, content1, content2, content3, content4 FROM {data_content} WHERE recordid = ?';
3156 $where = array($record->id);
3157 }
3158
3159 if( $content = $DB->get_records_sql($select, $where) ) {
ecd06483 3160 foreach($fields as $field) {
3161 $contents = '';
3162 if(isset($content[$field->field->id])) {
3163 $contents = $field->export_text_value($content[$field->field->id]);
3164 }
3165 $exportdata[$line][] = $contents;
3166 }
4f304eeb
HB
3167 if ($userdetails) { // Add user details to the export data
3168 $userdata = get_complete_user_data('id', $record->userid);
3169 $exportdata[$line][] = fullname($userdata);
3170 $exportdata[$line][] = $userdata->username;
3171 $exportdata[$line][] = $userdata->email;
3172 }
3173 if ($time) { // Add time added / modified
3174 $exportdata[$line][] = userdate($record->timecreated);
3175 $exportdata[$line][] = userdate($record->timemodified);
3176 }
3177 if ($approval) { // Add approval status
3178 $exportdata[$line][] = (int) $record->approved;
3179 }
04f7b079
AH
3180 if ($tags) {
3181 $itemtags = \core_tag_tag::get_item_tags_array('mod_data', 'data_records', $record->id);
3182 $exportdata[$line][] = implode(', ', $itemtags);
3183 }
ecd06483 3184 }
3185 $line++;
3186 }
3187 $line--;
3188 return $exportdata;
3189}
3190
386b67d1
DM
3191////////////////////////////////////////////////////////////////////////////////
3192// File API //
3193////////////////////////////////////////////////////////////////////////////////
3194
8429163d 3195/**
3196 * Lists all browsable file areas
4636bf83 3197 *
d2b7803e
DC
3198 * @package mod_data
3199 * @category files
3200 * @param stdClass $course course object
3201 * @param stdClass $cm course module object
3202 * @param stdClass $context context object
4636bf83 3203 * @return array
8429163d 3204 */
3205function data_get_file_areas($course, $cm, $context) {
386b67d1 3206 return array('content' => get_string('areacontent', 'mod_data'));
8429163d 3207}
3208
00ecac72
MG
3209/**
3210 * File browsing support for data module.
3211 *
3212 * @param file_browser $browser
3213 * @param array $areas
3214 * @param stdClass $course
3215 * @param cm_info $cm
3216 * @param context $context
3217 * @param string $filearea
3218 * @param int $itemid
3219 * @param string $filepath
3220 * @param string $filename
3221 * @return file_info_stored file_info_stored instance or null if not found
3222 */
6b8b0b2e 3223function data_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
35ca63c1 3224 global $CFG, $DB, $USER;