1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
|
<?php // $Id: questiontype.php,v 1.3 2006/04/05 05:53:23 gustav_delius Exp $
/////////////////
/// CALCULATED ///
/////////////////
/// QUESTION TYPE CLASS //////////////////
require_once("$CFG->dirroot/question/type/datasetdependent/abstractqtype.php");
class question_calculated_qtype extends question_dataset_dependent_questiontype {
// Used by the function custom_generator_tools:
var $calcgenerateidhasbeenadded = false;
function name() {
return 'calculated';
}
function get_question_options(&$question) {
// First get the datasets and default options
if(false === parent::get_question_options($question)) {
return false;
}
if (!$options = get_record('question_calculated', 'question', $question->id)) {
notify("No options were found for calculated question
#{$question->id}! Proceeding with defaults.");
$options = new stdClass;
$options->tolerance = 0.01;
$options->tolerancetype = 1; // relative
$options->correctanswerlength = 2;
$options->correctanswerformat = 1; // decimals
}
// For historic reasons we also need these fields in the answer objects.
// This should eventually be removed and related code changed to use
// the values in $question->options instead.
foreach ($question->options->answers as $key => $answer) {
$answer = &$question->options->answers[$key]; // for PHP 4.x
$answer->calcid = $options->id;
$answer->tolerance = $options->tolerance;
$answer->tolerancetype = $options->tolerancetype;
$answer->correctanswerlength = $options->correctanswerlength;
$answer->correctanswerformat = $options->correctanswerformat;
}
$virtualqtype = $this->get_virtual_qtype();
$virtualqtype->get_numerical_units($question);
return true;
}
function save_question_options($question) {
//$options = $question->subtypeoptions;
// Get old answers:
global $CFG;
if (!$oldanswers = get_records_sql(
"SELECT a.*, c.tolerance, c.tolerancetype,
c.correctanswerlength, c.id AS calcid
FROM {$CFG->prefix}question_answers a,
{$CFG->prefix}question_calculated c
WHERE c.question = $question->id AND a.id = c.answer")) {
$oldanswers = array();
}
// Update with new answers
$answerrec->question = $calcrec->question = $question->id;
$n = count($question->answers);
for ($i = 0; $i < $n; $i++) {
$answerrec->answer = $question->answers[$i];
$answerrec->fraction = isset($question->fraction[$i])
? $question->fraction[$i] : 1.0;
$answerrec->feedback = isset($question->feedback[$i])
? $question->feedback[$i] : '';
$calcrec->tolerance = isset($question->tolerance[$i])
? $question->tolerance[$i]
: $question->tolerance[0];
$calcrec->tolerancetype = isset($question->tolerancetype[$i])
? $question->tolerancetype[$i]
: $question->tolerancetype[0];
$calcrec->correctanswerlength = isset($question->correctanswerlength[$i])
? $question->correctanswerlength[$i]
: $question->correctanswerlength[0];
$calcrec->correctanswerformat = isset($question->correctanswerformat[$i])
? $question->correctanswerformat[$i]
: $question->correctanswerformat[0];
if ($oldanswer = array_shift($oldanswers)) {
// Reuse old records:
$calcrec->answer = $answerrec->id = $oldanswer->id;
$calcrec->id = $oldanswer->calcid;
if (!update_record('question_answers', $answerrec)) {
error("Unable to update answer for calculated question #{$question->id}!");
} else {
// notify("Answer updated successfully for calculated question $question->name");
}
if (!update_record('question_calculated', $calcrec)) {
error("Unable to update options for calculated question #{$question->id}!");
} else {
// notify("Options updated successfully for calculated question $question->name");
}
} else {
unset($answerrec->id);
unset($calcrec->id);
if (!($calcrec->answer = insert_record('question_answers',
$answerrec))) {
error("Unable to insert answer for calculated question $question->id");
} else {
// notify("Answer inserted successfully for calculated question $question->id");
}
if (!insert_record('question_calculated', $calcrec)) {
error("Unable to insert options calculared question $question->id");
} else {
// notify("Options inserted successfully for calculated question $question->id");
}
}
}
// Delete excessive records:
foreach ($oldanswers as $oldanswer) {
if (!delete_records('question_answers', 'id', $oldanswer->id)) {
error("Unable to delete old answers for calculated question $question->id");
} else {
// notify("Old answers deleted successfully for calculated question $question->id");
}
if (!delete_records('question_calculated', 'id', $oldanswer->calcid)) {
error("Unable to delete old options for calculated question $question->id");
} else {
// notify("Old options deleted successfully for calculated question $question->id");
}
}
// Save units
$virtualqtype = $this->get_virtual_qtype();
$virtualqtype->save_numerical_units($question);
return true;
}
function create_runtime_question($question, $form) {
$question = parent::create_runtime_question($question, $form);
$question->options->answers = array();
foreach ($form->answers as $key => $answer) {
$a->answer = trim($form->answer[$key]);
$a->tolerance = $form->tolerance[$key];
$a->tolerancetype = $form->tolerancetype[$key];
$a->correctanswerlength = $form->correctanswerlength[$key];
$a->correctanswerformat = $form->correctanswerformat[$key];
$question->options->answers[] = clone($a);
}
return $question;
}
function validate_form($form) {
switch($form->wizardpage) {
case 'question':
$calculatedmessages = array();
if (empty($form->name)) {
$calculatedmessages[] = get_string('missingname', 'quiz');
}
if (empty($form->questiontext)) {
$calculatedmessages[] = get_string('missingquestiontext', 'quiz');
}
// Verify formulas
foreach ($form->answers as $key => $answer) {
if ('' === trim($answer)) {
$calculatedmessages[] =
get_string('missingformula', 'quiz');
}
if ($formulaerrors =
qtype_calculated_find_formula_errors($answer)) {
$calculatedmessages[] = $formulaerrors;
}
if (! isset($form->tolerance[$key])) {
$form->tolerance[$key] = 0.0;
}
if (! is_numeric($form->tolerance[$key])) {
$calculatedmessages[] =
get_string('tolerancemustbenumeric', 'quiz');
}
}
if (!empty($calculatedmessages)) {
$errorstring = "The following errors were found:<br />";
foreach ($calculatedmessages as $msg) {
$errorstring .= $msg . '<br />';
}
error($errorstring);
}
break;
default:
return parent::validate_form($form);
break;
}
return true;
}
/**
* Deletes question from the question-type specific tables
*
* @return boolean Success/Failure
* @param object $question The question being deleted
*/
function delete_question($questionid) {
delete_records("question_calculated", "question", $questionid);
delete_records("question_numerical_units", "question", $questionid);
if ($datasets = get_records('question_datasets', 'question', $questionid)) {
foreach ($datasets as $dataset) {
delete_records('question_dataset_definitions', 'id', $dataset->datasetdefinition);
delete_records('question_dataset_items', 'definition', $dataset->datasetdefinition);
}
}
delete_records("question_datasets", "question", $questionid);
return true;
}
function print_question_formulation_and_controls(&$question, &$state, $cmoptions,
$options) {
// Substitute variables in questiontext before giving the data to the
// virtual type for printing
$virtualqtype = $this->get_virtual_qtype();
$unit = $virtualqtype->get_default_numerical_unit($question);
// We modify the question to look like a numerical question
$numericalquestion = clone($question);
$numericalquestion->options = clone($question->options);
foreach ($question->options->answers as $key => $answer) {
$numericalquestion->options->answers[$key] = clone($answer);
}
foreach ($numericalquestion->options->answers as $key => $answer) {
$answer = &$numericalquestion->options->answers[$key]; // for PHP 4.x
$correctanswer = qtype_calculated_calculate_answer(
$answer->answer, $state->options->dataset, $answer->tolerance,
$answer->tolerancetype, $answer->correctanswerlength,
$answer->correctanswerformat, $unit->unit);
$answer->answer = $correctanswer->answer;
}
$numericalquestion->questiontext = parent::substitute_variables(
$numericalquestion->questiontext, $state->options->dataset);
$virtualqtype->print_question_formulation_and_controls($numericalquestion,
$state, $cmoptions, $options);
}
function grade_responses(&$question, &$state, $cmoptions) {
// Forward the grading to the virtual qtype
// We modify the question to look like a numerical question
$numericalquestion = clone($question);
$numericalquestion->options = clone($question->options);
foreach ($question->options->answers as $key => $answer) {
$numericalquestion->options->answers[$key] = clone($answer);
}
foreach ($numericalquestion->options->answers as $key => $answer) {
$answer = &$numericalquestion->options->answers[$key]; // for PHP 4.x
$answer->answer = $this->substitute_variables($answer->answer,
$state->options->dataset);
}
return parent::grade_responses($numericalquestion, $state, $cmoptions);
}
function response_summary($question, $state, $length=80) {
// The actual response is the bit after the hyphen
return substr($state->answer, strpos($state->answer, '-')+1, $length);
}
// ULPGC ecastro
function check_response(&$question, &$state) {
// Forward the checking to the virtual qtype
// We modify the question to look like a numerical question
$numericalquestion = clone($question);
$numericalquestion->options = clone($question->options);
foreach ($question->options->answers as $key => $answer) {
$numericalquestion->options->answers[$key] = clone($answer);
}
foreach ($numericalquestion->options->answers as $key => $answer) {
$answer = &$numericalquestion->options->answers[$key]; // for PHP 4.x
$answer->answer = $this->substitute_variables($answer->answer,
$state->options->dataset);
}
return parent::check_response($numericalquestion, $state);
}
// ULPGC ecastro
function get_actual_response(&$question, &$state) {
// Substitute variables in questiontext before giving the data to the
// virtual type
$virtualqtype = $this->get_virtual_qtype();
$unit = $virtualqtype->get_default_numerical_unit($question);
// We modify the question to look like a numerical question
$numericalquestion = clone($question);
$numericalquestion->options = clone($question->options);
foreach ($question->options->answers as $key => $answer) {
$numericalquestion->options->answers[$key] = clone($answer);
}
foreach ($numericalquestion->options->answers as $key => $answer) {
$answer = &$numericalquestion->options->answers[$key]; // for PHP 4.x
$answer->answer = $this->substitute_variables($answer->answer,
$state->options->dataset);
// apply_unit
}
$numericalquestion->questiontext = parent::substitute_variables(
$numericalquestion->questiontext, $state->options->dataset);
$responses = $virtualqtype->get_all_responses($numericalquestion, $state);
$response = reset($responses->responses);
$correct = $response->answer.' : ';
$responses = $virtualqtype->get_actual_response($numericalquestion, $state);
foreach ($responses as $key=>$response){
$responses[$key] = $correct.$response;
}
return $responses;
}
function create_virtual_qtype() {
global $CFG;
require_once("$CFG->dirroot/question/type/numerical/questiontype.php");
return new question_numerical_qtype();
}
function supports_dataset_item_generation() {
// Calcualted support generation of randomly distributed number data
return true;
}
function custom_generator_tools($datasetdef) {
if (ereg('^(uniform|loguniform):([^:]*):([^:]*):([0-9]*)$',
$datasetdef->options, $regs)) {
$defid = "$datasetdef->type-$datasetdef->category-$datasetdef->name";
for ($i = 0 ; $i<10 ; ++$i) {
$lengthoptions[$i] = get_string(($regs[1] == 'uniform'
? 'decimals'
: 'significantfigures'), 'quiz', $i);
}
return '<input type="submit" onClick="'
. "document.addform.regenerateddefid.value='$defid'; return true;"
.'" value="'. get_string('generatevalue', 'quiz') . '"/><br/>'
. '<input type="text" size="3" name="calcmin[]" '
. " value=\"$regs[2]\"/> & <input name=\"calcmax[]\" "
. ' type="text" size="3" value="' . $regs[3] .'"/> '
. choose_from_menu($lengthoptions, 'calclength[]',
$regs[4], // Selected
'', '', '', true) . '<br/>'
. choose_from_menu(array('uniform' => get_string('uniform', 'quiz'),
'loguniform' => get_string('loguniform', 'quiz')),
'calcdistribution[]',
$regs[1], // Selected
'', '', '', true);
} else {
return '';
}
}
function update_dataset_options($datasetdefs, $form) {
// Do we have informatin about new options???
if (empty($form->definition) || empty($form->calcmin)
|| empty($form->calcmax) || empty($form->calclength)
|| empty($form->calcdistribution)) {
// I gues not:
} else {
// Looks like we just could have some new information here
foreach ($form->definition as $key => $defid) {
if (isset($datasetdefs[$defid])
&& is_numeric($form->calcmin[$key])
&& is_numeric($form->calcmax[$key])
&& is_numeric($form->calclength[$key])) {
switch ($form->calcdistribution[$key]) {
case 'uniform': case 'loguniform':
$datasetdefs[$defid]->options =
$form->calcdistribution[$key] . ':'
. $form->calcmin[$key] . ':'
. $form->calcmax[$key] . ':'
. $form->calclength[$key];
break;
default:
notify("Unexpected distribution $form->calcdistribution[$key]");
}
}
}
}
// Look for empty options, on which we set default values
foreach ($datasetdefs as $defid => $def) {
if (empty($def->options)) {
$datasetdefs[$defid]->options = 'uniform:1.0:10.0:1';
}
}
return $datasetdefs;
}
function generate_dataset_item($options) {
if (!ereg('^(uniform|loguniform):([^:]*):([^:]*):([0-9]*)$',
$options, $regs)) {
// Unknown options...
return false;
}
if ($regs[1] == 'uniform') {
$nbr = $regs[2] + ($regs[3]-$regs[2])*mt_rand()/mt_getrandmax();
return round($nbr, $regs[4]);
} else if ($regs[1] == 'loguniform') {
$log0 = log(abs($regs[2])); // It would have worked the other way to
$nbr = exp($log0 + (log(abs($regs[3])) - $log0)*mt_rand()/mt_getrandmax());
// Reformat according to the precision $regs[4]:
// Determine the format 0.[1-9][0-9]* for the nbr...
$p10 = 0;
while ($nbr < 1) {
--$p10;
$nbr *= 10;
}
while ($nbr >= 1) {
++$p10;
$nbr /= 10;
}
// ... and have the nbr rounded off to the correct length
$nbr = round($nbr, $regs[4]);
// Have the nbr written on a suitable format,
// Either scientific or plain numeric
if (-2 > $p10 || 4 < $p10) {
// Use scientific format:
$eX = 'e'.--$p10;
$nbr *= 10;
if (1 == $regs[4]) {
$nbr = $nbr.$eX;
} else {
// Attach additional zeros at the end of $nbr,
$nbr .= (1==strlen($nbr) ? '.' : '')
. '00000000000000000000000000000000000000000x';
$nbr = substr($nbr, 0, $regs[4] +1).$eX;
}
} else {
// Stick to plain numeric format
$nbr *= "1e$p10";
if (0.1 <= $nbr / "1e$regs[4]") {
$nbr = $nbr;
} else {
// Could be an idea to add some zeros here
$nbr .= (ereg('^[0-9]*$', $nbr) ? '.' : '')
. '00000000000000000000000000000000000000000x';
$oklen = $regs[4] + ($p10 < 1 ? 2-$p10 : 1);
$nbr = substr($nbr, 0, $oklen);
}
}
// The larger of the values decide the sign in case the
// have equal different signs (which they really must not have)
if ($regs[2] + $regs[3] > 0) {
return $nbr;
} else {
return -$nbr;
}
} else {
error("The distribution $regs[1] caused problems");
}
return '';
}
function comment_header($question) {
//$this->get_question_options($question);
global $SESSION;
$strheader = '';
$delimiter = '';
if (empty($question->id)) {
$answers = $SESSION->datasetdependent->questionform->answers;
} else {
$answers = $question->options->answers;
}
foreach ($answers as $answer) {
if (is_string($answer)) {
$strheader .= $delimiter.$answer;
} else {
$strheader .= $delimiter.$answer->answer;
}
$delimiter = ',';
}
return $strheader;
}
function comment_on_datasetitems($question, $data, $number) {
/// Find a default unit:
if (!empty($question->id) && $unit = get_record('question_numerical_units',
'question', $question->id, 'multiplier', 1.0)) {
$unit = $unit->unit;
} else {
$unit = '';
}
$answers = $question->options->answers;
$stranswers = get_string('answer', 'quiz');
$strmin = get_string('min', 'quiz');
$strmax = get_string('max', 'quiz');
$errors = '';
$delimiter = ': ';
$virtualqtype = $this->get_virtual_qtype();
foreach ($answers as $answer) {
$calculated = qtype_calculated_calculate_answer(
$answer->answer, $data, $answer->tolerance,
$answer->tolerancetype, $answer->correctanswerlength,
$answer->correctanswerformat, $unit);
$calculated->tolerance = $answer->tolerance;
$calculated->tolerancetype = $answer->tolerancetype;
$calculated->correctanswerlength = $answer->correctanswerlength;
$calculated->correctanswerformat = $answer->correctanswerformat;
$virtualqtype->get_tolerance_interval($calculated);
if ($calculated->min === '') {
// This should mean that something is wrong
$errors .= " -$calculated->answer";
$stranswers .= $delimiter;
} else {
$stranswers .= $delimiter.$calculated->answer;
$strmin .= $delimiter.$calculated->min;
$strmax .= $delimiter.$calculated->max;
}
}
return "$stranswers<br/>$strmin<br/>$strmax<br/>$errors";
}
function tolerance_types() {
return array('1' => get_string('relative', 'quiz'),
'2' => get_string('nominal', 'quiz'),
'3' => get_string('geometric', 'quiz'));
}
function dataset_options($form, $name, $renameabledatasets=false) {
// Takes datasets from the parent implementation but
// filters options that are currently not accepted by calculated
// It also determines a default selection...
list($options, $selected) = parent::dataset_options($form, $name);
foreach ($options as $key => $whatever) {
if (!ereg('^'.LITERAL.'-', $key) && $key != '0') {
unset($options[$key]);
}
}
if (!$selected) {
$selected = LITERAL . "-0-$name"; // Default
}
return array($options, $selected);
}
function construct_dataset_menus($form, $mandatorydatasets,
$optionaldatasets) {
$datasetmenus = array();
foreach ($mandatorydatasets as $datasetname) {
if (!isset($datasetmenus[$datasetname])) {
list($options, $selected) =
$this->dataset_options($form, $datasetname);
unset($options['0']); // Mandatory...
$datasetmenus[$datasetname] = choose_from_menu ($options,
'dataset[]', $selected, '', '', "0", true);
}
}
foreach ($optionaldatasets as $datasetname) {
if (!isset($datasetmenus[$datasetname])) {
list($options, $selected) =
$this->dataset_options($form, $datasetname);
$datasetmenus[$datasetname] = choose_from_menu ($options,
'dataset[]', $selected, '', '', "0", true);
}
}
return $datasetmenus;
}
function get_correct_responses(&$question, &$state) {
$virtualqtype = $this->get_virtual_qtype();
$unit = $virtualqtype->get_default_numerical_unit($question);
foreach ($question->options->answers as $answer) {
if (((int) $answer->fraction) === 1) {
$answernumerical = qtype_calculated_calculate_answer(
$answer->answer, $state->options->dataset, $answer->tolerance,
$answer->tolerancetype, $answer->correctanswerlength,
$answer->correctanswerformat, $unit->unit);
return array('' => $answernumerical->answer);
}
}
return null;
}
function substitute_variables($str, $dataset) {
$formula = parent::substitute_variables($str, $dataset);
if ($error = qtype_calculated_find_formula_errors($formula)) {
return $error;
}
/// Calculate the correct answer
if (empty($formula)) {
$str = '';
} else {
eval('$str = '.$formula.';');
}
return $str;
}
/// BACKUP FUNCTIONS ////////////////////////////
/*
* Backup the data in the question
*
* This is used in question/backuplib.php
*/
function backup($bf,$preferences,$question,$level=6) {
$status = true;
$calculateds = get_records("question_calculated","question",$question,"id");
//If there are calculated-s
if ($calculateds) {
//Iterate over each calculateds
foreach ($calculateds as $calculated) {
$status = $status &&fwrite ($bf,start_tag("CALCULATED",$level,true));
//Print calculated contents
fwrite ($bf,full_tag("ANSWER",$level+1,false,$calculated->answer));
fwrite ($bf,full_tag("TOLERANCE",$level+1,false,$calculated->tolerance));
fwrite ($bf,full_tag("TOLERANCETYPE",$level+1,false,$calculated->tolerancetype));
fwrite ($bf,full_tag("CORRECTANSWERLENGTH",$level+1,false,$calculated->correctanswerlength));
fwrite ($bf,full_tag("CORRECTANSWERFORMAT",$level+1,false,$calculated->correctanswerformat));
//Now backup numerical_units
$status = question_backup_numerical_units($bf,$preferences,$question,7);
//Now backup required dataset definitions and items...
$status = question_backup_datasets($bf,$preferences,$question,7);
//End calculated data
$status = $status &&fwrite ($bf,end_tag("CALCULATED",$level,true));
}
//Now print question_answers
$status = question_backup_answers($bf,$preferences,$question);
}
return $status;
}
/// RESTORE FUNCTIONS /////////////////
/*
* Restores the data in the question
*
* This is used in question/restorelib.php
*/
function restore($old_question_id,$new_question_id,$info,$restore) {
$status = true;
//Get the calculated-s array
$calculateds = $info['#']['CALCULATED'];
//Iterate over calculateds
for($i = 0; $i < sizeof($calculateds); $i++) {
$cal_info = $calculateds[$i];
//traverse_xmlize($cal_info); //Debug
//print_object ($GLOBALS['traverse_array']); //Debug
//$GLOBALS['traverse_array']=""; //Debug
//Now, build the question_calculated record structure
$calculated->question = $new_question_id;
$calculated->answer = backup_todb($cal_info['#']['ANSWER']['0']['#']);
$calculated->tolerance = backup_todb($cal_info['#']['TOLERANCE']['0']['#']);
$calculated->tolerancetype = backup_todb($cal_info['#']['TOLERANCETYPE']['0']['#']);
$calculated->correctanswerlength = backup_todb($cal_info['#']['CORRECTANSWERLENGTH']['0']['#']);
$calculated->correctanswerformat = backup_todb($cal_info['#']['CORRECTANSWERFORMAT']['0']['#']);
////We have to recode the answer field
$answer = backup_getid($restore->backup_unique_code,"question_answers",$calculated->answer);
if ($answer) {
$calculated->answer = $answer->new_id;
}
//The structure is equal to the db, so insert the question_calculated
$newid = insert_record ("question_calculated",$calculated);
//Do some output
if (($i+1) % 50 == 0) {
if (!defined('RESTORE_SILENTLY')) {
echo ".";
if (($i+1) % 1000 == 0) {
echo "<br />";
}
}
backup_flush(300);
}
//Now restore numerical_units
$status = question_restore_numerical_units ($old_question_id,$new_question_id,$cal_info,$restore);
//Now restore dataset_definitions
if ($status && $newid) {
$status = question_restore_dataset_definitions ($old_question_id,$new_question_id,$cal_info,$restore);
}
if (!$newid) {
$status = false;
}
}
return $status;
}
}
//// END OF CLASS ////
//////////////////////////////////////////////////////////////////////////
//// INITIATION - Without this line the question type is not in use... ///
//////////////////////////////////////////////////////////////////////////
$QTYPES['calculated']= new question_calculated_qtype();
// The following adds the questiontype to the menu of types shown to teachers
$QTYPE_MENU['calculated'] = get_string("calculated", "quiz");
function qtype_calculated_calculate_answer($formula, $individualdata,
$tolerance, $tolerancetype, $answerlength, $answerformat='1', $unit='') {
/// The return value has these properties:
/// ->answer the correct answer
/// ->min the lower bound for an acceptable response
/// ->max the upper bound for an accetpable response
/// Exchange formula variables with the correct values...
global $QTYPES;
$answer = $QTYPES['calculated']->substitute_variables($formula, $individualdata);
if ('1' == $answerformat) { /* Answer is to have $answerlength decimals */
/*** Adjust to the correct number of decimals ***/
$calculated->answer = round($answer, $answerlength);
if ($answerlength) {
/* Try to include missing zeros at the end */
if (ereg('^(.*\\.)(.*)$', $calculated->answer, $regs)) {
$calculated->answer = $regs[1] . substr(
$regs[2] . '00000000000000000000000000000000000000000x',
0, $answerlength)
. $unit;
} else {
$calculated->answer .=
substr('.00000000000000000000000000000000000000000x',
0, $answerlength + 1) . $unit;
}
} else {
/* Attach unit */
$calculated->answer .= $unit;
}
} else if ($answer) { // Significant figures does only apply if the result is non-zero
// Convert to positive answer...
if ($answer < 0) {
$answer = -$answer;
$sign = '-';
} else {
$sign = '';
}
// Determine the format 0.[1-9][0-9]* for the answer...
$p10 = 0;
while ($answer < 1) {
--$p10;
$answer *= 10;
}
while ($answer >= 1) {
++$p10;
$answer /= 10;
}
// ... and have the answer rounded of to the correct length
$answer = round($answer, $answerlength);
// Have the answer written on a suitable format,
// Either scientific or plain numeric
if (-2 > $p10 || 4 < $p10) {
// Use scientific format:
$eX = 'e'.--$p10;
$answer *= 10;
if (1 == $answerlength) {
$calculated->answer = $sign.$answer.$eX.$unit;
} else {
// Attach additional zeros at the end of $answer,
$answer .= (1==strlen($answer) ? '.' : '')
. '00000000000000000000000000000000000000000x';
$calculated->answer = $sign
.substr($answer, 0, $answerlength +1).$eX.$unit;
}
} else {
// Stick to plain numeric format
$answer *= "1e$p10";
if (0.1 <= $answer / "1e$answerlength") {
$calculated->answer = $sign.$answer.$unit;
} else {
// Could be an idea to add some zeros here
$answer .= (ereg('^[0-9]*$', $answer) ? '.' : '')
. '00000000000000000000000000000000000000000x';
$oklen = $answerlength + ($p10 < 1 ? 2-$p10 : 1);
$calculated->answer = $sign.substr($answer, 0, $oklen).$unit;
}
}
} else {
$calculated->answer = 0.0;
}
/// Return the result
return $calculated;
}
function qtype_calculated_find_formula_errors($formula) {
/// Validates the formula submitted from the question edit page.
/// Returns false if everything is alright.
/// Otherwise it constructs an error message
// Strip away dataset names
while (ereg('\\{[[:alpha:]][^>} <{"\']*\\}', $formula, $regs)) {
$formula = str_replace($regs[0], '1', $formula);
}
// Strip away empty space and lowercase it
$formula = strtolower(str_replace(' ', '', $formula));
$safeoperatorchar = '-+/*%>:^~<?=&|!'; /* */
$operatorornumber = "[$safeoperatorchar.0-9eE]";
while (ereg("(^|[$safeoperatorchar,(])([a-z0-9_]*)\\(($operatorornumber+(,$operatorornumber+((,$operatorornumber+)+)?)?)?\\)",
$formula, $regs)) {
switch ($regs[2]) {
// Simple parenthesis
case '':
if ($regs[4] || strlen($regs[3])==0) {
return get_string('illegalformulasyntax', 'quiz', $regs[0]);
}
break;
// Zero argument functions
case 'pi':
if ($regs[3]) {
return get_string('functiontakesnoargs', 'quiz', $regs[2]);
}
break;
// Single argument functions (the most common case)
case 'abs': case 'acos': case 'acosh': case 'asin': case 'asinh':
case 'atan': case 'atanh': case 'bindec': case 'ceil': case 'cos':
case 'cosh': case 'decbin': case 'decoct': case 'deg2rad':
case 'exp': case 'expm1': case 'floor': case 'is_finite':
case 'is_infinite': case 'is_nan': case 'log10': case 'log1p':
case 'octdec': case 'rad2deg': case 'sin': case 'sinh': case 'sqrt':
case 'tan': case 'tanh':
if ($regs[4] || empty($regs[3])) {
return get_string('functiontakesonearg','quiz',$regs[2]);
}
break;
// Functions that take one or two arguments
case 'log': case 'round':
if ($regs[5] || empty($regs[3])) {
return get_string('functiontakesoneortwoargs','quiz',$regs[2]);
}
break;
// Functions that must have two arguments
case 'atan2': case 'fmod': case 'pow':
if ($regs[5] || empty($regs[4])) {
return get_string('functiontakestwoargs', 'quiz', $regs[2]);
}
break;
// Functions that take two or more arguments
case 'min': case 'max':
if (empty($regs[4])) {
return get_string('functiontakesatleasttwo','quiz',$regs[2]);
}
break;
default:
return get_string('unsupportedformulafunction','quiz',$regs[2]);
}
// Exchange the function call with '1' and then chack for
// another function call...
if ($regs[1]) {
// The function call is proceeded by an operator
$formula = str_replace($regs[0], $regs[1] . '1', $formula);
} else {
// The function call starts the formula
$formula = ereg_replace("^$regs[2]\\([^)]*\\)", '1', $formula);
}
}
if (ereg("[^$safeoperatorchar.0-9eE]+", $formula, $regs)) {
return get_string('illegalformulasyntax', 'quiz', $regs[0]);
} else {
// Formula just might be valid
return false;
}
}
function dump($obj) {
echo "<pre>\n";
var_dump($obj);
echo "</pre><br />\n";
}
?>
|