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