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