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