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