See Release Notes
Long Term Support Release
Differences Between: [Versions 310 and 401] [Versions 311 and 401] [Versions 39 and 401] [Versions 400 and 401] [Versions 401 and 402] [Versions 401 and 403]
1 <?php 2 // This file is part of Moodle - http://moodle.org/ 3 // 4 // Moodle is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // Moodle is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU General Public License for more details. 13 // 14 // You should have received a copy of the GNU General Public License 15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>. 16 17 /** 18 * The default questiontype class. 19 * 20 * @package moodlecore 21 * @subpackage questiontypes 22 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} 23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 24 */ 25 26 27 defined('MOODLE_INTERNAL') || die(); 28 29 require_once($CFG->dirroot . '/question/engine/lib.php'); 30 require_once($CFG->libdir . '/questionlib.php'); 31 32 33 /** 34 * This is the base class for Moodle question types. 35 * 36 * There are detailed comments on each method, explaining what the method is 37 * for, and the circumstances under which you might need to override it. 38 * 39 * Note: the questiontype API should NOT be considered stable yet. Very few 40 * question types have been produced yet, so we do not yet know all the places 41 * where the current API is insufficient. I would rather learn from the 42 * experiences of the first few question type implementors, and improve the 43 * interface to meet their needs, rather the freeze the API prematurely and 44 * condem everyone to working round a clunky interface for ever afterwards. 45 * 46 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} 47 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 48 */ 49 class question_type { 50 protected $fileoptions = array( 51 'subdirs' => true, 52 'maxfiles' => -1, 53 'maxbytes' => 0, 54 ); 55 56 public function __construct() { 57 } 58 59 /** 60 * @return string the name of this question type. 61 */ 62 public function name() { 63 return substr(get_class($this), 6); 64 } 65 66 /** 67 * @return string the full frankenstyle name for this plugin. 68 */ 69 public function plugin_name() { 70 return get_class($this); 71 } 72 73 /** 74 * @return string the name of this question type in the user's language. 75 * You should not need to override this method, the default behaviour should be fine. 76 */ 77 public function local_name() { 78 return get_string('pluginname', $this->plugin_name()); 79 } 80 81 /** 82 * The name this question should appear as in the create new question 83 * dropdown. Override this method to return false if you don't want your 84 * question type to be createable, for example if it is an abstract base type, 85 * otherwise, you should not need to override this method. 86 * 87 * @return mixed the desired string, or false to hide this question type in the menu. 88 */ 89 public function menu_name() { 90 return $this->local_name(); 91 } 92 93 /** 94 * @return bool override this to return false if this is not really a 95 * question type, for example the description question type is not 96 * really a question type. 97 */ 98 public function is_real_question_type() { 99 return true; 100 } 101 102 /** 103 * @return bool true if this question type sometimes requires manual grading. 104 */ 105 public function is_manual_graded() { 106 return false; 107 } 108 109 /** 110 * @param object $question a question of this type. 111 * @param string $otherquestionsinuse comma-separate list of other question ids in this attempt. 112 * @return bool true if a particular instance of this question requires manual grading. 113 */ 114 public function is_question_manual_graded($question, $otherquestionsinuse) { 115 return $this->is_manual_graded(); 116 } 117 118 /** 119 * @return bool true if this question type can be used by the random question type. 120 */ 121 public function is_usable_by_random() { 122 return true; 123 } 124 125 /** 126 * Whether this question type can perform a frequency analysis of student 127 * responses. 128 * 129 * If this method returns true, you must implement the get_possible_responses 130 * method, and the question_definition class must implement the 131 * classify_response method. 132 * 133 * @return bool whether this report can analyse all the student responses 134 * for things like the quiz statistics report. 135 */ 136 public function can_analyse_responses() { 137 // This works in most cases. 138 return !$this->is_manual_graded(); 139 } 140 141 /** 142 * @return whether the question_answers.answer field needs to have 143 * restore_decode_content_links_worker called on it. 144 */ 145 public function has_html_answers() { 146 return false; 147 } 148 149 /** 150 * If your question type has a table that extends the question table, and 151 * you want the base class to automatically save, backup and restore the extra fields, 152 * override this method to return an array wherer the first element is the table name, 153 * and the subsequent entries are the column names (apart from id and questionid). 154 * 155 * @return mixed array as above, or null to tell the base class to do nothing. 156 */ 157 public function extra_question_fields() { 158 return null; 159 } 160 161 /** 162 * If you use extra_question_fields, overload this function to return question id field name 163 * in case you table use another name for this column 164 */ 165 public function questionid_column_name() { 166 return 'questionid'; 167 } 168 169 /** 170 * If your question type has a table that extends the question_answers table, 171 * make this method return an array wherer the first element is the table name, 172 * and the subsequent entries are the column names (apart from id and answerid). 173 * 174 * @return mixed array as above, or null to tell the base class to do nothing. 175 */ 176 public function extra_answer_fields() { 177 return null; 178 } 179 180 /** 181 * If the quetsion type uses files in responses, then this method should 182 * return an array of all the response variables that might have corresponding 183 * files. For example, the essay qtype returns array('attachments', 'answers'). 184 * 185 * @return array response variable names that may have associated files. 186 */ 187 public function response_file_areas() { 188 return array(); 189 } 190 191 /** 192 * Return an instance of the question editing form definition. This looks for a 193 * class called edit_{$this->name()}_question_form in the file 194 * question/type/{$this->name()}/edit_{$this->name()}_question_form.php 195 * and if it exists returns an instance of it. 196 * 197 * @param string $submiturl passed on to the constructor call. 198 * @return object an instance of the form definition, or null if one could not be found. 199 */ 200 public function create_editing_form($submiturl, $question, $category, 201 $contexts, $formeditable) { 202 global $CFG; 203 require_once($CFG->dirroot . '/question/type/edit_question_form.php'); 204 $definitionfile = $CFG->dirroot . '/question/type/' . $this->name() . 205 '/edit_' . $this->name() . '_form.php'; 206 if (!is_readable($definitionfile) || !is_file($definitionfile)) { 207 throw new coding_exception($this->plugin_name() . 208 ' is missing the definition of its editing formin file ' . 209 $definitionfile . '.'); 210 } 211 require_once($definitionfile); 212 $classname = $this->plugin_name() . '_edit_form'; 213 if (!class_exists($classname)) { 214 throw new coding_exception($this->plugin_name() . 215 ' does not define the class ' . $this->plugin_name() . 216 '_edit_form.'); 217 } 218 return new $classname($submiturl, $question, $category, $contexts, $formeditable); 219 } 220 221 /** 222 * @return string the full path of the folder this plugin's files live in. 223 */ 224 public function plugin_dir() { 225 global $CFG; 226 return $CFG->dirroot . '/question/type/' . $this->name(); 227 } 228 229 /** 230 * @return string the URL of the folder this plugin's files live in. 231 */ 232 public function plugin_baseurl() { 233 global $CFG; 234 return $CFG->wwwroot . '/question/type/' . $this->name(); 235 } 236 237 /** 238 * Get extra actions for a question of this type to add to the question bank edit menu. 239 * 240 * This method is called if the {@link edit_menu_column} is being used in the 241 * question bank, which it is by default since Moodle 3.8. If applicable for 242 * your question type, you can return arn array of {@link action_menu_link}s. 243 * These will be added at the end of the Edit menu for this question. 244 * 245 * The $question object passed in will have a hard-to-predict set of fields, 246 * because the fields present depend on which columns are included in the 247 * question bank view. However, you can rely on 'id', 'createdby', 248 * 'contextid', 'hidden' and 'category' (id) being present, and so you 249 * can call question_has_capability_on without causing performance problems. 250 * 251 * @param stdClass $question the available information about the particular question the action is for. 252 * @return action_menu_link[] any actions you want to add to the Edit menu for this question. 253 */ 254 public function get_extra_question_bank_actions(stdClass $question): array { 255 return []; 256 } 257 258 /** 259 * This method should be overriden if you want to include a special heading or some other 260 * html on a question editing page besides the question editing form. 261 * 262 * @param question_edit_form $mform a child of question_edit_form 263 * @param object $question 264 * @param string $wizardnow is '' for first page. 265 */ 266 public function display_question_editing_page($mform, $question, $wizardnow) { 267 global $OUTPUT; 268 $heading = $this->get_heading(empty($question->id)); 269 echo $OUTPUT->heading_with_help($heading, 'pluginname', $this->plugin_name()); 270 $mform->display(); 271 } 272 273 /** 274 * Method called by display_question_editing_page and by question.php to get 275 * heading for breadcrumbs. 276 * 277 * @return string the heading 278 */ 279 public function get_heading($adding = false) { 280 if ($adding) { 281 $string = 'pluginnameadding'; 282 } else { 283 $string = 'pluginnameediting'; 284 } 285 return get_string($string, $this->plugin_name()); 286 } 287 288 /** 289 * Set any missing settings for this question to the default values. This is 290 * called before displaying the question editing form. 291 * 292 * @param object $questiondata the question data, loaded from the databsae, 293 * or more likely a newly created question object that is only partially 294 * initialised. 295 */ 296 public function set_default_options($questiondata) { 297 } 298 299 /** 300 * Return default value for a given form element either from user_preferences table or $default. 301 * 302 * @param string $name the name of the form element. 303 * @param mixed $default default value. 304 * @return string|null default value for a given form element. 305 */ 306 public function get_default_value(string $name, $default): ?string { 307 return get_user_preferences($this->plugin_name() . '_' . $name, $default ?? '0'); 308 } 309 310 /** 311 * Save the default value for a given form element in user_preferences table. 312 * 313 * @param string $name the name of the value to set. 314 * @param string $value the setting value. 315 */ 316 public function set_default_value(string $name, string $value): void { 317 set_user_preference($this->plugin_name() . '_' . $name, $value); 318 } 319 320 /** 321 * Save question defaults when creating new questions. 322 * 323 * @param stdClass $fromform data from the form. 324 */ 325 public function save_defaults_for_new_questions(stdClass $fromform): void { 326 // Some question types may not make use of the certain form elements, so 327 // we need to do a check on the following generic form elements. For instance, 328 // 'defaultmark' is not use in qtype_multianswer and 'penalty' in not used in 329 // qtype_essay and qtype_recordrtc. 330 if (isset($fromform->defaultmark)) { 331 $this->set_default_value('defaultmark', $fromform->defaultmark); 332 } 333 if (isset($fromform->penalty)) { 334 $this->set_default_value('penalty', $fromform->penalty); 335 } 336 } 337 338 /** 339 * Saves (creates or updates) a question. 340 * 341 * Given some question info and some data about the answers 342 * this function parses, organises and saves the question 343 * It is used by {@link question.php} when saving new data from 344 * a form, and also by {@link import.php} when importing questions 345 * This function in turn calls {@link save_question_options} 346 * to save question-type specific data. 347 * 348 * Whether we are saving a new question or updating an existing one can be 349 * determined by testing !empty($question->id). If it is not empty, we are updating. 350 * 351 * The question will be saved in category $form->category. 352 * 353 * @param object $question the question object which should be updated. For a 354 * new question will be mostly empty. 355 * @param object $form the object containing the information to save, as if 356 * from the question editing form. 357 * @param object $course not really used any more. 358 * @return object On success, return the new question object. On failure, 359 * return an object as follows. If the error object has an errors field, 360 * display that as an error message. Otherwise, the editing form will be 361 * redisplayed with validation errors, from validation_errors field, which 362 * is itself an object, shown next to the form fields. (I don't think this 363 * is accurate any more.) 364 */ 365 public function save_question($question, $form) { 366 global $USER, $DB; 367 368 // The actual update/insert done with multiple DB access, so we do it in a transaction. 369 $transaction = $DB->start_delegated_transaction (); 370 371 list($form->category) = explode(',', $form->category); 372 $context = $this->get_context_by_category_id($form->category); 373 $question->category = $form->category; 374 375 // This default implementation is suitable for most 376 // question types. 377 378 // First, save the basic question itself. 379 $question->name = trim($form->name); 380 $question->parent = isset($form->parent) ? $form->parent : 0; 381 $question->length = $this->actual_number_of_questions($question); 382 $question->penalty = isset($form->penalty) ? $form->penalty : 0; 383 384 // The trim call below has the effect of casting any strange values received, 385 // like null or false, to an appropriate string, so we only need to test for 386 // missing values. Be careful not to break the value '0' here. 387 if (!isset($form->questiontext['text'])) { 388 $question->questiontext = ''; 389 } else { 390 $question->questiontext = trim($form->questiontext['text']); 391 } 392 $question->questiontextformat = !empty($form->questiontext['format']) ? 393 $form->questiontext['format'] : 0; 394 395 if (empty($form->generalfeedback['text'])) { 396 $question->generalfeedback = ''; 397 } else { 398 $question->generalfeedback = trim($form->generalfeedback['text']); 399 } 400 $question->generalfeedbackformat = !empty($form->generalfeedback['format']) ? 401 $form->generalfeedback['format'] : 0; 402 403 if ($question->name === '') { 404 $question->name = shorten_text(strip_tags($form->questiontext['text']), 15); 405 if ($question->name === '') { 406 $question->name = '-'; 407 } 408 } 409 410 if ($question->penalty > 1 or $question->penalty < 0) { 411 $question->errors['penalty'] = get_string('invalidpenalty', 'question'); 412 } 413 414 if (isset($form->defaultmark)) { 415 $question->defaultmark = $form->defaultmark; 416 } 417 418 // Only create a new bank entry if the question is not a new version (New question or duplicating a question). 419 $questionbankentry = null; 420 if (isset($question->id)) { 421 $oldparent = $question->id; 422 if (!empty($question->id)) { 423 // Get the bank entry record where the question is referenced. 424 $questionbankentry = get_question_bank_entry($question->id); 425 } 426 } 427 428 // Get the bank entry old id (this is when there are questions related with a parent, e.g.: qtype_multianswers). 429 if (isset($question->oldid)) { 430 if (!empty($question->oldid)) { 431 $questionbankentry = get_question_bank_entry($question->oldid); 432 } 433 } 434 435 // Always creates a new question and version record. 436 // Set the unique code. 437 $question->stamp = make_unique_id_code(); 438 $question->createdby = $USER->id; 439 $question->timecreated = time(); 440 441 // Idnumber validation. 442 $question->idnumber = null; 443 if (isset($form->idnumber)) { 444 if ((string) $form->idnumber === '') { 445 $question->idnumber = null; 446 } else { 447 // While this check already exists in the form validation, 448 // this is a backstop preventing unnecessary errors. 449 // Only set the idnumber if it has changed and will not cause a unique index violation. 450 if (strpos($form->category, ',') !== false) { 451 list($category, $categorycontextid) = explode(',', $form->category); 452 } else { 453 $category = $form->category; 454 } 455 $params = ['idnumber' => $form->idnumber, 'categoryid' => $category]; 456 $andcondition = ''; 457 if (isset($question->id) && isset($questionbankentry->id)) { 458 $andcondition = 'AND qbe.id != :notid'; 459 $params['notid'] = $questionbankentry->id; 460 } 461 $sql = "SELECT qbe.id 462 FROM {question_bank_entries} qbe 463 WHERE qbe.idnumber = :idnumber 464 AND qbe.questioncategoryid = :categoryid 465 $andcondition"; 466 if (!$DB->record_exists_sql($sql, $params)) { 467 $question->idnumber = $form->idnumber; 468 } 469 } 470 } 471 472 // Create the question. 473 $question->id = $DB->insert_record('question', $question); 474 if (!$questionbankentry) { 475 // Create a record for question_bank_entries, question_versions and question_references. 476 $questionbankentry = new \stdClass(); 477 $questionbankentry->questioncategoryid = $form->category; 478 $questionbankentry->idnumber = $question->idnumber; 479 $questionbankentry->ownerid = $question->createdby; 480 $questionbankentry->id = $DB->insert_record('question_bank_entries', $questionbankentry); 481 } else { 482 $questionbankentryold = new \stdClass(); 483 $questionbankentryold->id = $questionbankentry->id; 484 $questionbankentryold->idnumber = $question->idnumber; 485 $DB->update_record('question_bank_entries', $questionbankentryold); 486 } 487 488 // Create question_versions records. 489 $questionversion = new \stdClass(); 490 $questionversion->questionbankentryid = $questionbankentry->id; 491 $questionversion->questionid = $question->id; 492 // Get the version and status from the parent question if parent is set. 493 if (!$question->parent) { 494 // Get the status field. It comes from the form, but for testing we can. 495 $status = $form->status ?? $question->status ?? 496 \core_question\local\bank\question_version_status::QUESTION_STATUS_READY; 497 $questionversion->version = get_next_version($questionbankentry->id); 498 $questionversion->status = $status; 499 } else { 500 $parentversion = get_question_version($form->parent); 501 $questionversion->version = $parentversion[array_key_first($parentversion)]->version; 502 $questionversion->status = $parentversion[array_key_first($parentversion)]->status; 503 } 504 $questionversion->id = $DB->insert_record('question_versions', $questionversion); 505 506 // Now, whether we are updating a existing question, or creating a new 507 // one, we have to do the files processing and update the record. 508 // Question already exists, update. 509 $question->modifiedby = $USER->id; 510 $question->timemodified = time(); 511 512 if (!empty($question->questiontext) && !empty($form->questiontext['itemid'])) { 513 $question->questiontext = file_save_draft_area_files($form->questiontext['itemid'], 514 $context->id, 'question', 'questiontext', (int)$question->id, 515 $this->fileoptions, $question->questiontext); 516 } 517 if (!empty($question->generalfeedback) && !empty($form->generalfeedback['itemid'])) { 518 $question->generalfeedback = file_save_draft_area_files( 519 $form->generalfeedback['itemid'], $context->id, 520 'question', 'generalfeedback', (int)$question->id, 521 $this->fileoptions, $question->generalfeedback); 522 } 523 $DB->update_record('question', $question); 524 525 // Now to save all the answers and type-specific options. 526 $form->id = $question->id; 527 $form->qtype = $question->qtype; 528 $form->questiontext = $question->questiontext; 529 $form->questiontextformat = $question->questiontextformat; 530 // Current context. 531 $form->context = $context; 532 // Old parent question id is used when there are questions related with a parent, e.g.: qtype_multianswers). 533 if (isset($oldparent)) { 534 $form->oldparent = $oldparent; 535 } else { 536 $form->oldparent = $question->parent; 537 } 538 $result = $this->save_question_options($form); 539 540 if (!empty($result->error)) { 541 throw new \moodle_exception($result->error); 542 } 543 544 if (!empty($result->notice)) { 545 notice($result->notice, "question.php?id={$question->id}"); 546 } 547 548 if (!empty($result->noticeyesno)) { 549 throw new coding_exception( 550 '$result->noticeyesno no longer supported in save_question.'); 551 } 552 553 // Log the creation of this question. 554 $event = \core\event\question_created::create_from_question_instance($question, $context); 555 $event->trigger(); 556 557 $transaction->allow_commit(); 558 559 return $question; 560 } 561 562 /** 563 * Saves question-type specific options 564 * 565 * This is called by {@link save_question()} to save the question-type specific data 566 * @return object $result->error or $result->notice 567 * @param object $question This holds the information from the editing form, 568 * it is not a standard question object. 569 */ 570 public function save_question_options($question) { 571 global $DB; 572 $extraquestionfields = $this->extra_question_fields(); 573 574 if (is_array($extraquestionfields)) { 575 $question_extension_table = array_shift($extraquestionfields); 576 577 $function = 'update_record'; 578 $questionidcolname = $this->questionid_column_name(); 579 $options = $DB->get_record($question_extension_table, 580 array($questionidcolname => $question->id)); 581 if (!$options) { 582 $function = 'insert_record'; 583 $options = new stdClass(); 584 $options->$questionidcolname = $question->id; 585 } 586 foreach ($extraquestionfields as $field) { 587 if (property_exists($question, $field)) { 588 $options->$field = $question->$field; 589 } 590 } 591 592 $DB->{$function}($question_extension_table, $options); 593 } 594 } 595 596 /** 597 * Save the answers, with any extra data. 598 * 599 * Questions that use answers will call it from {@link save_question_options()}. 600 * @param object $question This holds the information from the editing form, 601 * it is not a standard question object. 602 * @return object $result->error or $result->notice 603 */ 604 public function save_question_answers($question) { 605 global $DB; 606 607 $context = $question->context; 608 $oldanswers = $DB->get_records('question_answers', 609 array('question' => $question->id), 'id ASC'); 610 611 // We need separate arrays for answers and extra answer data, so no JOINS there. 612 $extraanswerfields = $this->extra_answer_fields(); 613 $isextraanswerfields = is_array($extraanswerfields); 614 $extraanswertable = ''; 615 $oldanswerextras = array(); 616 if ($isextraanswerfields) { 617 $extraanswertable = array_shift($extraanswerfields); 618 if (!empty($oldanswers)) { 619 $oldanswerextras = $DB->get_records_sql("SELECT * FROM {{$extraanswertable}} WHERE " . 620 'answerid IN (SELECT id FROM {question_answers} WHERE question = ' . $question->id . ')' ); 621 } 622 } 623 624 // Insert all the new answers. 625 foreach ($question->answer as $key => $answerdata) { 626 // Check for, and ignore, completely blank answer from the form. 627 if ($this->is_answer_empty($question, $key)) { 628 continue; 629 } 630 631 // Update an existing answer if possible. 632 $answer = array_shift($oldanswers); 633 if (!$answer) { 634 $answer = new stdClass(); 635 $answer->question = $question->id; 636 $answer->answer = ''; 637 $answer->feedback = ''; 638 $answer->id = $DB->insert_record('question_answers', $answer); 639 } 640 641 $answer = $this->fill_answer_fields($answer, $question, $key, $context); 642 $DB->update_record('question_answers', $answer); 643 644 if ($isextraanswerfields) { 645 // Check, if this answer contains some extra field data. 646 if ($this->is_extra_answer_fields_empty($question, $key)) { 647 continue; 648 } 649 650 $answerextra = array_shift($oldanswerextras); 651 if (!$answerextra) { 652 $answerextra = new stdClass(); 653 $answerextra->answerid = $answer->id; 654 // Avoid looking for correct default for any possible DB field type 655 // by setting real values. 656 $answerextra = $this->fill_extra_answer_fields($answerextra, $question, $key, $context, $extraanswerfields); 657 $answerextra->id = $DB->insert_record($extraanswertable, $answerextra); 658 } else { 659 // Update answerid, as record may be reused from another answer. 660 $answerextra->answerid = $answer->id; 661 $answerextra = $this->fill_extra_answer_fields($answerextra, $question, $key, $context, $extraanswerfields); 662 $DB->update_record($extraanswertable, $answerextra); 663 } 664 } 665 } 666 667 if ($isextraanswerfields) { 668 // Delete any left over extra answer fields records. 669 $oldanswerextraids = array(); 670 foreach ($oldanswerextras as $oldextra) { 671 $oldanswerextraids[] = $oldextra->id; 672 } 673 $DB->delete_records_list($extraanswertable, 'id', $oldanswerextraids); 674 } 675 676 // Delete any left over old answer records. 677 $fs = get_file_storage(); 678 foreach ($oldanswers as $oldanswer) { 679 $fs->delete_area_files($context->id, 'question', 'answerfeedback', $oldanswer->id); 680 $DB->delete_records('question_answers', array('id' => $oldanswer->id)); 681 } 682 } 683 684 /** 685 * Returns true is answer with the $key is empty in the question data and should not be saved in DB. 686 * 687 * The questions using question_answers table may want to overload this. Default code will work 688 * for shortanswer and similar question types. 689 * @param object $questiondata This holds the information from the question editing form or import. 690 * @param int $key A key of the answer in question. 691 * @return bool True if answer shouldn't be saved in DB. 692 */ 693 protected function is_answer_empty($questiondata, $key) { 694 return trim($questiondata->answer[$key]) == '' && $questiondata->fraction[$key] == 0 && 695 html_is_blank($questiondata->feedback[$key]['text']); 696 } 697 698 /** 699 * Return $answer, filling necessary fields for the question_answers table. 700 * 701 * The questions using question_answers table may want to overload this. Default code will work 702 * for shortanswer and similar question types. 703 * @param stdClass $answer Object to save data. 704 * @param object $questiondata This holds the information from the question editing form or import. 705 * @param int $key A key of the answer in question. 706 * @param object $context needed for working with files. 707 * @return $answer answer with filled data. 708 */ 709 protected function fill_answer_fields($answer, $questiondata, $key, $context) { 710 $answer->answer = $questiondata->answer[$key]; 711 $answer->fraction = $questiondata->fraction[$key]; 712 $answer->feedback = $this->import_or_save_files($questiondata->feedback[$key], 713 $context, 'question', 'answerfeedback', $answer->id); 714 $answer->feedbackformat = $questiondata->feedback[$key]['format']; 715 return $answer; 716 } 717 718 /** 719 * Returns true if extra answer fields for answer with the $key is empty 720 * in the question data and should not be saved in DB. 721 * 722 * Questions where extra answer fields are optional will want to overload this. 723 * @param object $questiondata This holds the information from the question editing form or import. 724 * @param int $key A key of the answer in question. 725 * @return bool True if extra answer data shouldn't be saved in DB. 726 */ 727 protected function is_extra_answer_fields_empty($questiondata, $key) { 728 // No extra answer data in base class. 729 return true; 730 } 731 732 /** 733 * Return $answerextra, filling necessary fields for the extra answer fields table. 734 * 735 * The questions may want to overload it to save files or do other data processing. 736 * @param stdClass $answerextra Object to save data. 737 * @param object $questiondata This holds the information from the question editing form or import. 738 * @param int $key A key of the answer in question. 739 * @param object $context needed for working with files. 740 * @param array $extraanswerfields extra answer fields (without table name). 741 * @return $answer answerextra with filled data. 742 */ 743 protected function fill_extra_answer_fields($answerextra, $questiondata, $key, $context, $extraanswerfields) { 744 foreach ($extraanswerfields as $field) { 745 // The $questiondata->$field[$key] won't work in PHP, break it down to two strings of code. 746 $fieldarray = $questiondata->$field; 747 $answerextra->$field = $fieldarray[$key]; 748 } 749 return $answerextra; 750 } 751 752 public function save_hints($formdata, $withparts = false) { 753 global $DB; 754 $context = $formdata->context; 755 756 $oldhints = $DB->get_records('question_hints', 757 array('questionid' => $formdata->id), 'id ASC'); 758 759 760 $numhints = $this->count_hints_on_form($formdata, $withparts); 761 762 for ($i = 0; $i < $numhints; $i += 1) { 763 if (html_is_blank($formdata->hint[$i]['text'])) { 764 $formdata->hint[$i]['text'] = ''; 765 } 766 767 if ($withparts) { 768 $clearwrong = !empty($formdata->hintclearwrong[$i]); 769 $shownumcorrect = !empty($formdata->hintshownumcorrect[$i]); 770 } 771 772 if ($this->is_hint_empty_in_form_data($formdata, $i, $withparts)) { 773 continue; 774 } 775 776 // Update an existing hint if possible. 777 $hint = array_shift($oldhints); 778 if (!$hint) { 779 $hint = new stdClass(); 780 $hint->questionid = $formdata->id; 781 $hint->hint = ''; 782 $hint->id = $DB->insert_record('question_hints', $hint); 783 } 784 785 $hint->hint = $this->import_or_save_files($formdata->hint[$i], 786 $context, 'question', 'hint', $hint->id); 787 $hint->hintformat = $formdata->hint[$i]['format']; 788 if ($withparts) { 789 $hint->clearwrong = $clearwrong; 790 $hint->shownumcorrect = $shownumcorrect; 791 } 792 $hint->options = $this->save_hint_options($formdata, $i, $withparts); 793 $DB->update_record('question_hints', $hint); 794 } 795 796 // Delete any remaining old hints. 797 $fs = get_file_storage(); 798 foreach ($oldhints as $oldhint) { 799 $fs->delete_area_files($context->id, 'question', 'hint', $oldhint->id); 800 $DB->delete_records('question_hints', array('id' => $oldhint->id)); 801 } 802 } 803 804 /** 805 * Count number of hints on the form. 806 * Overload if you use custom hint controls. 807 * @param object $formdata the data from the form. 808 * @param bool $withparts whether to take into account clearwrong and shownumcorrect options. 809 * @return int count of hints on the form. 810 */ 811 protected function count_hints_on_form($formdata, $withparts) { 812 if (!empty($formdata->hint)) { 813 $numhints = max(array_keys($formdata->hint)) + 1; 814 } else { 815 $numhints = 0; 816 } 817 818 if ($withparts) { 819 if (!empty($formdata->hintclearwrong)) { 820 $numclears = max(array_keys($formdata->hintclearwrong)) + 1; 821 } else { 822 $numclears = 0; 823 } 824 if (!empty($formdata->hintshownumcorrect)) { 825 $numshows = max(array_keys($formdata->hintshownumcorrect)) + 1; 826 } else { 827 $numshows = 0; 828 } 829 $numhints = max($numhints, $numclears, $numshows); 830 } 831 return $numhints; 832 } 833 834 /** 835 * Determine if the hint with specified number is not empty and should be saved. 836 * Overload if you use custom hint controls. 837 * @param object $formdata the data from the form. 838 * @param int $number number of hint under question. 839 * @param bool $withparts whether to take into account clearwrong and shownumcorrect options. 840 * @return bool is this particular hint data empty. 841 */ 842 protected function is_hint_empty_in_form_data($formdata, $number, $withparts) { 843 if ($withparts) { 844 return empty($formdata->hint[$number]['text']) && empty($formdata->hintclearwrong[$number]) && 845 empty($formdata->hintshownumcorrect[$number]); 846 } else { 847 return empty($formdata->hint[$number]['text']); 848 } 849 } 850 851 /** 852 * Save additional question type data into the hint optional field. 853 * Overload if you use custom hint information. 854 * @param object $formdata the data from the form. 855 * @param int $number number of hint to get options from. 856 * @param bool $withparts whether question have parts. 857 * @return string value to save into the options field of question_hints table. 858 */ 859 protected function save_hint_options($formdata, $number, $withparts) { 860 return null; // By default, options field is unused. 861 } 862 863 /** 864 * Can be used to {@link save_question_options()} to transfer the combined 865 * feedback fields from $formdata to $options. 866 * @param object $options the $question->options object being built. 867 * @param object $formdata the data from the form. 868 * @param object $context the context the quetsion is being saved into. 869 * @param bool $withparts whether $options->shownumcorrect should be set. 870 */ 871 protected function save_combined_feedback_helper($options, $formdata, 872 $context, $withparts = false) { 873 $options->correctfeedback = $this->import_or_save_files($formdata->correctfeedback, 874 $context, 'question', 'correctfeedback', $formdata->id); 875 $options->correctfeedbackformat = $formdata->correctfeedback['format']; 876 877 $options->partiallycorrectfeedback = $this->import_or_save_files( 878 $formdata->partiallycorrectfeedback, 879 $context, 'question', 'partiallycorrectfeedback', $formdata->id); 880 $options->partiallycorrectfeedbackformat = $formdata->partiallycorrectfeedback['format']; 881 882 $options->incorrectfeedback = $this->import_or_save_files($formdata->incorrectfeedback, 883 $context, 'question', 'incorrectfeedback', $formdata->id); 884 $options->incorrectfeedbackformat = $formdata->incorrectfeedback['format']; 885 886 if ($withparts) { 887 $options->shownumcorrect = !empty($formdata->shownumcorrect); 888 } 889 890 return $options; 891 } 892 893 /** 894 * Loads the question type specific options for the question. 895 * 896 * This function loads any question type specific options for the 897 * question from the database into the question object. This information 898 * is placed in the $question->options field. A question type is 899 * free, however, to decide on a internal structure of the options field. 900 * @return bool Indicates success or failure. 901 * @param object $question The question object for the question. This object 902 * should be updated to include the question type 903 * specific information (it is passed by reference). 904 */ 905 public function get_question_options($question) { 906 global $DB, $OUTPUT; 907 908 if (!isset($question->options)) { 909 $question->options = new stdClass(); 910 } 911 912 $extraquestionfields = $this->extra_question_fields(); 913 if (is_array($extraquestionfields)) { 914 $question_extension_table = array_shift($extraquestionfields); 915 $extra_data = $DB->get_record($question_extension_table, 916 array($this->questionid_column_name() => $question->id), 917 implode(', ', $extraquestionfields)); 918 if ($extra_data) { 919 foreach ($extraquestionfields as $field) { 920 $question->options->$field = $extra_data->$field; 921 } 922 } else { 923 echo $OUTPUT->notification('Failed to load question options from the table ' . 924 $question_extension_table . ' for questionid ' . $question->id); 925 return false; 926 } 927 } 928 929 $extraanswerfields = $this->extra_answer_fields(); 930 if (is_array($extraanswerfields)) { 931 $answerextensiontable = array_shift($extraanswerfields); 932 // Use LEFT JOIN in case not every answer has extra data. 933 $question->options->answers = $DB->get_records_sql(" 934 SELECT qa.*, qax." . implode(', qax.', $extraanswerfields) . ' 935 FROM {question_answers} qa ' . " 936 LEFT JOIN {{$answerextensiontable}} qax ON qa.id = qax.answerid 937 WHERE qa.question = ? 938 ORDER BY qa.id", array($question->id)); 939 if (!$question->options->answers) { 940 echo $OUTPUT->notification('Failed to load question answers from the table ' . 941 $answerextensiontable . 'for questionid ' . $question->id); 942 return false; 943 } 944 } else { 945 // Don't check for success or failure because some question types do 946 // not use the answers table. 947 $question->options->answers = $DB->get_records('question_answers', 948 array('question' => $question->id), 'id ASC'); 949 } 950 951 $question->hints = $DB->get_records('question_hints', 952 array('questionid' => $question->id), 'id ASC'); 953 954 return true; 955 } 956 957 /** 958 * Create an appropriate question_definition for the question of this type 959 * using data loaded from the database. 960 * @param object $questiondata the question data loaded from the database. 961 * @return question_definition the corresponding question_definition. 962 */ 963 public function make_question($questiondata) { 964 $question = $this->make_question_instance($questiondata); 965 $this->initialise_question_instance($question, $questiondata); 966 return $question; 967 } 968 969 /** 970 * Create an appropriate question_definition for the question of this type 971 * using data loaded from the database. 972 * @param object $questiondata the question data loaded from the database. 973 * @return question_definition an instance of the appropriate question_definition subclass. 974 * Still needs to be initialised. 975 */ 976 protected function make_question_instance($questiondata) { 977 question_bank::load_question_definition_classes($this->name()); 978 $class = 'qtype_' . $this->name() . '_question'; 979 return new $class(); 980 } 981 982 /** 983 * Initialise the common question_definition fields. 984 * @param question_definition $question the question_definition we are creating. 985 * @param object $questiondata the question data loaded from the database. 986 */ 987 protected function initialise_question_instance(question_definition $question, $questiondata) { 988 $question->id = $questiondata->id; 989 $question->category = $questiondata->category; 990 $question->contextid = $questiondata->contextid; 991 $question->parent = $questiondata->parent; 992 $question->qtype = $this; 993 $question->name = $questiondata->name; 994 $question->questiontext = $questiondata->questiontext; 995 $question->questiontextformat = $questiondata->questiontextformat; 996 $question->generalfeedback = $questiondata->generalfeedback; 997 $question->generalfeedbackformat = $questiondata->generalfeedbackformat; 998 $question->defaultmark = $questiondata->defaultmark + 0; 999 $question->length = $questiondata->length; 1000 $question->penalty = $questiondata->penalty; 1001 $question->stamp = $questiondata->stamp; 1002 $question->timecreated = $questiondata->timecreated; 1003 $question->timemodified = $questiondata->timemodified; 1004 $question->createdby = $questiondata->createdby; 1005 $question->modifiedby = $questiondata->modifiedby; 1006 1007 $this->initialise_core_question_metadata($question, $questiondata); 1008 1009 // Fill extra question fields values. 1010 $extraquestionfields = $this->extra_question_fields(); 1011 if (is_array($extraquestionfields)) { 1012 // Omit table name. 1013 array_shift($extraquestionfields); 1014 foreach ($extraquestionfields as $field) { 1015 $question->$field = $questiondata->options->$field; 1016 } 1017 } 1018 1019 $this->initialise_question_hints($question, $questiondata); 1020 1021 // Add the custom fields. 1022 $this->initialise_custom_fields($question, $questiondata); 1023 } 1024 1025 /** 1026 * Initialise the question metadata. 1027 * 1028 * @param question_definition $question the question_definition we are creating. 1029 * @param object $questiondata the question data loaded from the database. 1030 */ 1031 protected function initialise_core_question_metadata(question_definition $question, $questiondata) { 1032 $fields = 1033 [ 1034 'status', 1035 'versionid', 1036 'version', 1037 'questionbankentryid', 1038 'idnumber', 1039 ]; 1040 1041 foreach ($fields as $field) { 1042 if (isset($questiondata->{$field})) { 1043 $question->{$field} = $questiondata->{$field}; 1044 } 1045 } 1046 } 1047 1048 /** 1049 * Initialise question_definition::hints field. 1050 * @param question_definition $question the question_definition we are creating. 1051 * @param object $questiondata the question data loaded from the database. 1052 */ 1053 protected function initialise_question_hints(question_definition $question, $questiondata) { 1054 if (empty($questiondata->hints)) { 1055 return; 1056 } 1057 foreach ($questiondata->hints as $hint) { 1058 $question->hints[] = $this->make_hint($hint); 1059 } 1060 } 1061 1062 /** 1063 * Create a question_hint, or an appropriate subclass for this question, 1064 * from a row loaded from the database. 1065 * @param object $hint the DB row from the question hints table. 1066 * @return question_hint 1067 */ 1068 protected function make_hint($hint) { 1069 return question_hint::load_from_record($hint); 1070 } 1071 1072 /** 1073 * Initialise question custom fields. 1074 * @param question_definition $question the question_definition we are creating. 1075 * @param object $questiondata the question data loaded from the database. 1076 */ 1077 protected function initialise_custom_fields(question_definition $question, $questiondata) { 1078 if (!empty($questiondata->customfields)) { 1079 $question->customfields = $questiondata->customfields; 1080 } 1081 } 1082 1083 /** 1084 * Initialise the combined feedback fields. 1085 * @param question_definition $question the question_definition we are creating. 1086 * @param object $questiondata the question data loaded from the database. 1087 * @param bool $withparts whether to set the shownumcorrect field. 1088 */ 1089 protected function initialise_combined_feedback(question_definition $question, 1090 $questiondata, $withparts = false) { 1091 $question->correctfeedback = $questiondata->options->correctfeedback; 1092 $question->correctfeedbackformat = $questiondata->options->correctfeedbackformat; 1093 $question->partiallycorrectfeedback = $questiondata->options->partiallycorrectfeedback; 1094 $question->partiallycorrectfeedbackformat = 1095 $questiondata->options->partiallycorrectfeedbackformat; 1096 $question->incorrectfeedback = $questiondata->options->incorrectfeedback; 1097 $question->incorrectfeedbackformat = $questiondata->options->incorrectfeedbackformat; 1098 if ($withparts) { 1099 $question->shownumcorrect = $questiondata->options->shownumcorrect; 1100 } 1101 } 1102 1103 /** 1104 * Initialise question_definition::answers field. 1105 * @param question_definition $question the question_definition we are creating. 1106 * @param object $questiondata the question data loaded from the database. 1107 * @param bool $forceplaintextanswers most qtypes assume that answers are 1108 * FORMAT_PLAIN, and dont use the answerformat DB column (it contains 1109 * the default 0 = FORMAT_MOODLE). Therefore, by default this method 1110 * ingores answerformat. Pass false here to use answerformat. For example 1111 * multichoice does this. 1112 */ 1113 protected function initialise_question_answers(question_definition $question, 1114 $questiondata, $forceplaintextanswers = true) { 1115 $question->answers = array(); 1116 if (empty($questiondata->options->answers)) { 1117 return; 1118 } 1119 foreach ($questiondata->options->answers as $a) { 1120 $question->answers[$a->id] = $this->make_answer($a); 1121 if (!$forceplaintextanswers) { 1122 $question->answers[$a->id]->answerformat = $a->answerformat; 1123 } 1124 } 1125 } 1126 1127 /** 1128 * Create a question_answer, or an appropriate subclass for this question, 1129 * from a row loaded from the database. 1130 * @param object $answer the DB row from the question_answers table plus extra answer fields. 1131 * @return question_answer 1132 */ 1133 protected function make_answer($answer) { 1134 return new question_answer($answer->id, $answer->answer, 1135 $answer->fraction, $answer->feedback, $answer->feedbackformat); 1136 } 1137 1138 /** 1139 * Deletes the question-type specific data when a question is deleted. 1140 * @param int $question the question being deleted. 1141 * @param int $contextid the context this quesiotn belongs to. 1142 */ 1143 public function delete_question($questionid, $contextid) { 1144 global $DB; 1145 1146 $this->delete_files($questionid, $contextid); 1147 1148 $extraquestionfields = $this->extra_question_fields(); 1149 if (is_array($extraquestionfields)) { 1150 $question_extension_table = array_shift($extraquestionfields); 1151 $DB->delete_records($question_extension_table, 1152 array($this->questionid_column_name() => $questionid)); 1153 } 1154 1155 $extraanswerfields = $this->extra_answer_fields(); 1156 if (is_array($extraanswerfields)) { 1157 $answer_extension_table = array_shift($extraanswerfields); 1158 $DB->delete_records_select($answer_extension_table, 1159 'answerid IN (SELECT qa.id FROM {question_answers} qa WHERE qa.question = ?)', 1160 array($questionid)); 1161 } 1162 1163 $DB->delete_records('question_answers', array('question' => $questionid)); 1164 1165 $DB->delete_records('question_hints', array('questionid' => $questionid)); 1166 } 1167 1168 /** 1169 * Returns the number of question numbers which are used by the question 1170 * 1171 * This function returns the number of question numbers to be assigned 1172 * to the question. Most question types will have length one; they will be 1173 * assigned one number. The 'description' type, however does not use up a 1174 * number and so has a length of zero. Other question types may wish to 1175 * handle a bundle of questions and hence return a number greater than one. 1176 * @return int The number of question numbers which should be 1177 * assigned to the question. 1178 * @param object $question The question whose length is to be determined. 1179 * Question type specific information is included. 1180 */ 1181 public function actual_number_of_questions($question) { 1182 // By default, each question is given one number. 1183 return 1; 1184 } 1185 1186 /** 1187 * Calculate the score a monkey would get on a question by clicking randomly. 1188 * 1189 * Some question types have significant non-zero average expected score 1190 * of the response is just selected randomly. For example 50% for a 1191 * true-false question. It is useful to know what this is. For example 1192 * it gets shown in the quiz statistics report. 1193 * 1194 * For almost any open-ended question type (E.g. shortanswer or numerical) 1195 * this should be 0. 1196 * 1197 * For selective response question types (e.g. multiple choice), you can probably compute this. 1198 * 1199 * For particularly complicated question types the may be impossible or very 1200 * difficult to compute. In this case return null. (Or, if the expected score 1201 * is very tiny even though the exact value is unknown, it may appropriate 1202 * to return 0.) 1203 * 1204 * @param stdClass $questiondata data defining a question, as returned by 1205 * question_bank::load_question_data(). 1206 * @return number|null either a fraction estimating what the student would 1207 * score by guessing, or null, if it is not possible to estimate. 1208 */ 1209 public function get_random_guess_score($questiondata) { 1210 return 0; 1211 } 1212 1213 /** 1214 * Whether or not to break down question stats and response analysis, for a question defined by $questiondata. 1215 * 1216 * @param object $questiondata The full question definition data. 1217 * @return bool 1218 */ 1219 public function break_down_stats_and_response_analysis_by_variant($questiondata) { 1220 return true; 1221 } 1222 1223 /** 1224 * This method should return all the possible types of response that are 1225 * recognised for this question. 1226 * 1227 * The question is modelled as comprising one or more subparts. For each 1228 * subpart, there are one or more classes that that students response 1229 * might fall into, each of those classes earning a certain score. 1230 * 1231 * For example, in a shortanswer question, there is only one subpart, the 1232 * text entry field. The response the student gave will be classified according 1233 * to which of the possible $question->options->answers it matches. 1234 * 1235 * For the matching question type, there will be one subpart for each 1236 * question stem, and for each stem, each of the possible choices is a class 1237 * of student's response. 1238 * 1239 * A response is an object with two fields, ->responseclass is a string 1240 * presentation of that response, and ->fraction, the credit for a response 1241 * in that class. 1242 * 1243 * Array keys have no specific meaning, but must be unique, and must be 1244 * the same if this function is called repeatedly. 1245 * 1246 * @param object $question the question definition data. 1247 * @return array keys are subquestionid, values are arrays of possible 1248 * responses to that subquestion. 1249 */ 1250 public function get_possible_responses($questiondata) { 1251 return array(); 1252 } 1253 1254 /** 1255 * Utility method used by {@link qtype_renderer::head_code()}. It looks 1256 * for any of the files script.js or script.php that exist in the plugin 1257 * folder and ensures they get included. 1258 */ 1259 public function find_standard_scripts() { 1260 global $PAGE; 1261 1262 $plugindir = $this->plugin_dir(); 1263 $plugindirrel = 'question/type/' . $this->name(); 1264 1265 if (file_exists($plugindir . '/script.js')) { 1266 $PAGE->requires->js('/' . $plugindirrel . '/script.js'); 1267 } 1268 if (file_exists($plugindir . '/script.php')) { 1269 $PAGE->requires->js('/' . $plugindirrel . '/script.php'); 1270 } 1271 } 1272 1273 /** 1274 * Returns true if the editing wizard is finished, false otherwise. 1275 * 1276 * The default implementation returns true, which is suitable for all question- 1277 * types that only use one editing form. This function is used in 1278 * question.php to decide whether we can regrade any states of the edited 1279 * question and redirect to edit.php. 1280 * 1281 * The dataset dependent question-type, which is extended by the calculated 1282 * question-type, overwrites this method because it uses multiple pages (i.e. 1283 * a wizard) to set up the question and associated datasets. 1284 * 1285 * @param object $form The data submitted by the previous page. 1286 * 1287 * @return bool Whether the wizard's last page was submitted or not. 1288 */ 1289 public function finished_edit_wizard($form) { 1290 // In the default case there is only one edit page. 1291 return true; 1292 } 1293 1294 // IMPORT/EXPORT FUNCTIONS --------------------------------- . 1295 1296 /* 1297 * Imports question from the Moodle XML format 1298 * 1299 * Imports question using information from extra_question_fields function 1300 * If some of you fields contains id's you'll need to reimplement this 1301 */ 1302 public function import_from_xml($data, $question, qformat_xml $format, $extra=null) { 1303 $question_type = $data['@']['type']; 1304 if ($question_type != $this->name()) { 1305 return false; 1306 } 1307 1308 $extraquestionfields = $this->extra_question_fields(); 1309 if (!is_array($extraquestionfields)) { 1310 return false; 1311 } 1312 1313 // Omit table name. 1314 array_shift($extraquestionfields); 1315 $qo = $format->import_headers($data); 1316 $qo->qtype = $question_type; 1317 1318 foreach ($extraquestionfields as $field) { 1319 $qo->$field = $format->getpath($data, array('#', $field, 0, '#'), ''); 1320 } 1321 1322 // Run through the answers. 1323 $answers = $data['#']['answer']; 1324 $a_count = 0; 1325 $extraanswersfields = $this->extra_answer_fields(); 1326 if (is_array($extraanswersfields)) { 1327 array_shift($extraanswersfields); 1328 } 1329 foreach ($answers as $answer) { 1330 $ans = $format->import_answer($answer); 1331 if (!$this->has_html_answers()) { 1332 $qo->answer[$a_count] = $ans->answer['text']; 1333 } else { 1334 $qo->answer[$a_count] = $ans->answer; 1335 } 1336 $qo->fraction[$a_count] = $ans->fraction; 1337 $qo->feedback[$a_count] = $ans->feedback; 1338 if (is_array($extraanswersfields)) { 1339 foreach ($extraanswersfields as $field) { 1340 $qo->{$field}[$a_count] = 1341 $format->getpath($answer, array('#', $field, 0, '#'), ''); 1342 } 1343 } 1344 ++$a_count; 1345 } 1346 return $qo; 1347 } 1348 1349 /* 1350 * Export question to the Moodle XML format 1351 * 1352 * Export question using information from extra_question_fields function 1353 * If some of you fields contains id's you'll need to reimplement this 1354 */ 1355 public function export_to_xml($question, qformat_xml $format, $extra=null) { 1356 $extraquestionfields = $this->extra_question_fields(); 1357 if (!is_array($extraquestionfields)) { 1358 return false; 1359 } 1360 1361 // Omit table name. 1362 array_shift($extraquestionfields); 1363 $expout=''; 1364 foreach ($extraquestionfields as $field) { 1365 $exportedvalue = $format->xml_escape($question->options->$field); 1366 $expout .= " <{$field}>{$exportedvalue}</{$field}>\n"; 1367 } 1368 1369 $extraanswersfields = $this->extra_answer_fields(); 1370 if (is_array($extraanswersfields)) { 1371 array_shift($extraanswersfields); 1372 } 1373 foreach ($question->options->answers as $answer) { 1374 $extra = ''; 1375 if (is_array($extraanswersfields)) { 1376 foreach ($extraanswersfields as $field) { 1377 $exportedvalue = $format->xml_escape($answer->$field); 1378 $extra .= " <{$field}>{$exportedvalue}</{$field}>\n"; 1379 } 1380 } 1381 1382 $expout .= $format->write_answer($answer, $extra); 1383 } 1384 return $expout; 1385 } 1386 1387 /** 1388 * Abstract function implemented by each question type. It runs all the code 1389 * required to set up and save a question of any type for testing purposes. 1390 * Alternate DB table prefix may be used to facilitate data deletion. 1391 */ 1392 public function generate_test($name, $courseid=null) { 1393 $form = new stdClass(); 1394 $form->name = $name; 1395 $form->questiontextformat = 1; 1396 $form->questiontext = 'test question, generated by script'; 1397 $form->defaultmark = 1; 1398 $form->penalty = 0.3333333; 1399 $form->status = \core_question\local\bank\question_version_status::QUESTION_STATUS_READY; 1400 $form->generalfeedback = "Well done"; 1401 1402 $context = context_course::instance($courseid); 1403 $newcategory = question_make_default_categories(array($context)); 1404 $form->category = $newcategory->id . ',1'; 1405 1406 $question = new stdClass(); 1407 $question->courseid = $courseid; 1408 $question->qtype = $this->qtype; 1409 return array($form, $question); 1410 } 1411 1412 /** 1413 * Get question context by category id 1414 * @param int $category 1415 * @return object $context 1416 */ 1417 protected function get_context_by_category_id($category) { 1418 global $DB; 1419 $contextid = $DB->get_field('question_categories', 'contextid', array('id'=>$category)); 1420 $context = context::instance_by_id($contextid, IGNORE_MISSING); 1421 return $context; 1422 } 1423 1424 /** 1425 * Save the file belonging to one text field. 1426 * 1427 * @param array $field the data from the form (or from import). This will 1428 * normally have come from the formslib editor element, so it will be an 1429 * array with keys 'text', 'format' and 'itemid'. However, when we are 1430 * importing, it will be an array with keys 'text', 'format' and 'files' 1431 * @param object $context the context the question is in. 1432 * @param string $component indentifies the file area question. 1433 * @param string $filearea indentifies the file area questiontext, 1434 * generalfeedback, answerfeedback, etc. 1435 * @param int $itemid identifies the file area. 1436 * 1437 * @return string the text for this field, after files have been processed. 1438 */ 1439 protected function import_or_save_files($field, $context, $component, $filearea, $itemid) { 1440 if (!empty($field['itemid'])) { 1441 // This is the normal case. We are safing the questions editing form. 1442 return file_save_draft_area_files($field['itemid'], $context->id, $component, 1443 $filearea, $itemid, $this->fileoptions, trim($field['text'])); 1444 1445 } else if (!empty($field['files'])) { 1446 // This is the case when we are doing an import. 1447 foreach ($field['files'] as $file) { 1448 $this->import_file($context, $component, $filearea, $itemid, $file); 1449 } 1450 } 1451 return trim($field['text']); 1452 } 1453 1454 /** 1455 * Move all the files belonging to this question from one context to another. 1456 * @param int $questionid the question being moved. 1457 * @param int $oldcontextid the context it is moving from. 1458 * @param int $newcontextid the context it is moving to. 1459 */ 1460 public function move_files($questionid, $oldcontextid, $newcontextid) { 1461 $fs = get_file_storage(); 1462 $fs->move_area_files_to_new_context($oldcontextid, 1463 $newcontextid, 'question', 'questiontext', $questionid); 1464 $fs->move_area_files_to_new_context($oldcontextid, 1465 $newcontextid, 'question', 'generalfeedback', $questionid); 1466 } 1467 1468 /** 1469 * Move all the files belonging to this question's answers when the question 1470 * is moved from one context to another. 1471 * @param int $questionid the question being moved. 1472 * @param int $oldcontextid the context it is moving from. 1473 * @param int $newcontextid the context it is moving to. 1474 * @param bool $answerstoo whether there is an 'answer' question area, 1475 * as well as an 'answerfeedback' one. Default false. 1476 */ 1477 protected function move_files_in_answers($questionid, $oldcontextid, 1478 $newcontextid, $answerstoo = false) { 1479 global $DB; 1480 $fs = get_file_storage(); 1481 1482 $answerids = $DB->get_records_menu('question_answers', 1483 array('question' => $questionid), 'id', 'id,1'); 1484 foreach ($answerids as $answerid => $notused) { 1485 if ($answerstoo) { 1486 $fs->move_area_files_to_new_context($oldcontextid, 1487 $newcontextid, 'question', 'answer', $answerid); 1488 } 1489 $fs->move_area_files_to_new_context($oldcontextid, 1490 $newcontextid, 'question', 'answerfeedback', $answerid); 1491 } 1492 } 1493 1494 /** 1495 * Move all the files belonging to this question's hints when the question 1496 * is moved from one context to another. 1497 * @param int $questionid the question being moved. 1498 * @param int $oldcontextid the context it is moving from. 1499 * @param int $newcontextid the context it is moving to. 1500 * @param bool $answerstoo whether there is an 'answer' question area, 1501 * as well as an 'answerfeedback' one. Default false. 1502 */ 1503 protected function move_files_in_hints($questionid, $oldcontextid, $newcontextid) { 1504 global $DB; 1505 $fs = get_file_storage(); 1506 1507 $hintids = $DB->get_records_menu('question_hints', 1508 array('questionid' => $questionid), 'id', 'id,1'); 1509 foreach ($hintids as $hintid => $notused) { 1510 $fs->move_area_files_to_new_context($oldcontextid, 1511 $newcontextid, 'question', 'hint', $hintid); 1512 } 1513 } 1514 1515 /** 1516 * Move all the files belonging to this question's answers when the question 1517 * is moved from one context to another. 1518 * @param int $questionid the question being moved. 1519 * @param int $oldcontextid the context it is moving from. 1520 * @param int $newcontextid the context it is moving to. 1521 * @param bool $answerstoo whether there is an 'answer' question area, 1522 * as well as an 'answerfeedback' one. Default false. 1523 */ 1524 protected function move_files_in_combined_feedback($questionid, $oldcontextid, 1525 $newcontextid) { 1526 global $DB; 1527 $fs = get_file_storage(); 1528 1529 $fs->move_area_files_to_new_context($oldcontextid, 1530 $newcontextid, 'question', 'correctfeedback', $questionid); 1531 $fs->move_area_files_to_new_context($oldcontextid, 1532 $newcontextid, 'question', 'partiallycorrectfeedback', $questionid); 1533 $fs->move_area_files_to_new_context($oldcontextid, 1534 $newcontextid, 'question', 'incorrectfeedback', $questionid); 1535 } 1536 1537 /** 1538 * Delete all the files belonging to this question. 1539 * @param int $questionid the question being deleted. 1540 * @param int $contextid the context the question is in. 1541 */ 1542 protected function delete_files($questionid, $contextid) { 1543 $fs = get_file_storage(); 1544 $fs->delete_area_files($contextid, 'question', 'questiontext', $questionid); 1545 $fs->delete_area_files($contextid, 'question', 'generalfeedback', $questionid); 1546 } 1547 1548 /** 1549 * Delete all the files belonging to this question's answers. 1550 * @param int $questionid the question being deleted. 1551 * @param int $contextid the context the question is in. 1552 * @param bool $answerstoo whether there is an 'answer' question area, 1553 * as well as an 'answerfeedback' one. Default false. 1554 */ 1555 protected function delete_files_in_answers($questionid, $contextid, $answerstoo = false) { 1556 global $DB; 1557 $fs = get_file_storage(); 1558 1559 $answerids = $DB->get_records_menu('question_answers', 1560 array('question' => $questionid), 'id', 'id,1'); 1561 foreach ($answerids as $answerid => $notused) { 1562 if ($answerstoo) { 1563 $fs->delete_area_files($contextid, 'question', 'answer', $answerid); 1564 } 1565 $fs->delete_area_files($contextid, 'question', 'answerfeedback', $answerid); 1566 } 1567 } 1568 1569 /** 1570 * Delete all the files belonging to this question's hints. 1571 * @param int $questionid the question being deleted. 1572 * @param int $contextid the context the question is in. 1573 */ 1574 protected function delete_files_in_hints($questionid, $contextid) { 1575 global $DB; 1576 $fs = get_file_storage(); 1577 1578 $hintids = $DB->get_records_menu('question_hints', 1579 array('questionid' => $questionid), 'id', 'id,1'); 1580 foreach ($hintids as $hintid => $notused) { 1581 $fs->delete_area_files($contextid, 'question', 'hint', $hintid); 1582 } 1583 } 1584 1585 /** 1586 * Delete all the files belonging to this question's answers. 1587 * @param int $questionid the question being deleted. 1588 * @param int $contextid the context the question is in. 1589 * @param bool $answerstoo whether there is an 'answer' question area, 1590 * as well as an 'answerfeedback' one. Default false. 1591 */ 1592 protected function delete_files_in_combined_feedback($questionid, $contextid) { 1593 global $DB; 1594 $fs = get_file_storage(); 1595 1596 $fs->delete_area_files($contextid, 1597 'question', 'correctfeedback', $questionid); 1598 $fs->delete_area_files($contextid, 1599 'question', 'partiallycorrectfeedback', $questionid); 1600 $fs->delete_area_files($contextid, 1601 'question', 'incorrectfeedback', $questionid); 1602 } 1603 1604 public function import_file($context, $component, $filearea, $itemid, $file) { 1605 $fs = get_file_storage(); 1606 $record = new stdClass(); 1607 if (is_object($context)) { 1608 $record->contextid = $context->id; 1609 } else { 1610 $record->contextid = $context; 1611 } 1612 $record->component = $component; 1613 $record->filearea = $filearea; 1614 $record->itemid = $itemid; 1615 $record->filename = $file->name; 1616 $record->filepath = '/'; 1617 return $fs->create_file_from_string($record, $this->decode_file($file)); 1618 } 1619 1620 protected function decode_file($file) { 1621 switch ($file->encoding) { 1622 case 'base64': 1623 default: 1624 return base64_decode($file->content); 1625 } 1626 } 1627 } 1628 1629 1630 /** 1631 * This class is used in the return value from 1632 * {@link question_type::get_possible_responses()}. 1633 * 1634 * @copyright 2010 The Open University 1635 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 1636 */ 1637 class question_possible_response { 1638 /** 1639 * @var string the classification of this response the student gave to this 1640 * part of the question. Must match one of the responseclasses returned by 1641 * {@link question_type::get_possible_responses()}. 1642 */ 1643 public $responseclass; 1644 1645 /** @var string the (partial) credit awarded for this responses. */ 1646 public $fraction; 1647 1648 /** 1649 * Constructor, just an easy way to set the fields. 1650 * @param string $responseclassid see the field descriptions above. 1651 * @param string $response see the field descriptions above. 1652 * @param number $fraction see the field descriptions above. 1653 */ 1654 public function __construct($responseclass, $fraction) { 1655 $this->responseclass = $responseclass; 1656 $this->fraction = $fraction; 1657 } 1658 1659 public static function no_response() { 1660 return new question_possible_response(get_string('noresponse', 'question'), 0); 1661 } 1662 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body