Merge branch 'MDL-68749-310-2' of git://github.com/mickhawkins/moodle into MOODLE_310...
[moodle.git] / question / type / numerical / questiontype.php
CommitLineData
aeb15530 1<?php
fe6ce234
DC
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
f77f47ec 17
1fe641f7 18/**
f77f47ec
TH
19 * Question type class for the numerical question type.
20 *
7764183a
TH
21 * @package qtype
22 * @subpackage numerical
23 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
fe6ce234 25 */
516cf3eb 26
7764183a 27
a17b297d
TH
28defined('MOODLE_INTERNAL') || die();
29
603bd001 30require_once($CFG->libdir . '/questionlib.php');
1da821bb
TH
31require_once($CFG->dirroot . '/question/type/numerical/question.php');
32
f77f47ec 33
1fe641f7 34/**
f77f47ec 35 * The numerical question type class.
1fe641f7 36 *
37 * This class contains some special features in order to make the
38 * question type embeddable within a multianswer (cloze) question
39 *
7764183a
TH
40 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
41 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1fe641f7 42 */
f77f47ec 43class qtype_numerical extends question_type {
1fa39364 44 const UNITINPUT = 0;
8566369f
TH
45 const UNITRADIO = 1;
46 const UNITSELECT = 2;
1fa39364
TH
47
48 const UNITNONE = 3;
1fa39364
TH
49 const UNITGRADED = 1;
50 const UNITOPTIONAL = 0;
51
52 const UNITGRADEDOUTOFMARK = 1;
53 const UNITGRADEDOUTOFMAX = 2;
54
48aad79a
JMV
55 /**
56 * Validate that a string is a number formatted correctly for the current locale.
57 * @param string $x a string
58 * @return bool whether $x is a number that the numerical question type can interpret.
59 */
60 public static function is_valid_number(string $x) : bool {
61 $ap = new qtype_numerical_answer_processor(array());
62 list($value, $unit) = $ap->apply_units($x);
63 return !is_null($value) && !$unit;
64 }
65
f77f47ec
TH
66 public function get_question_options($question) {
67 global $CFG, $DB, $OUTPUT;
397bd295 68 parent::get_question_options($question);
516cf3eb 69 // Get the question answers and their respective tolerances
32a189d6 70 // Note: question_numerical is an extension of the answer table rather than
4f48fb42 71 // the question table as is usually the case for qtype
516cf3eb 72 // specific tables.
f34488b2 73 if (!$question->options->answers = $DB->get_records_sql(
516cf3eb 74 "SELECT a.*, n.tolerance " .
f34488b2 75 "FROM {question_answers} a, " .
76 " {question_numerical} n " .
77 "WHERE a.question = ? " .
026bec73 78 " AND a.id = n.answer " .
f34488b2 79 "ORDER BY a.id ASC", array($question->id))) {
fdd015b7
TH
80 echo $OUTPUT->notification('Error: Missing question answer for numerical question ' .
81 $question->id . '!');
516cf3eb 82 return false;
83 }
f77f47ec 84
fdd015b7
TH
85 $question->hints = $DB->get_records('question_hints',
86 array('questionid' => $question->id), 'id ASC');
f77f47ec 87
516cf3eb 88 $this->get_numerical_units($question);
3d9645ae 89 // Get_numerical_options() need to know if there are units
90 // to set correctly default values.
cf146692 91 $this->get_numerical_options($question);
516cf3eb 92
5a14d563 93 // If units are defined we strip off the default unit from the answer, if
516cf3eb 94 // it is present. (Required for compatibility with the old code and DB).
95 if ($defaultunit = $this->get_default_numerical_unit($question)) {
fdd015b7 96 foreach ($question->options->answers as $key => $val) {
516cf3eb 97 $answer = trim($val->answer);
98 $length = strlen($defaultunit->unit);
1fe641f7 99 if ($length && substr($answer, -$length) == $defaultunit->unit) {
516cf3eb 100 $question->options->answers[$key]->answer =
1fe641f7 101 substr($answer, 0, strlen($answer)-$length);
516cf3eb 102 }
103 }
104 }
c5da9906 105
106 return true;
107 }
f77f47ec
TH
108
109 public function get_numerical_units(&$question) {
92b36005 110 global $DB;
f77f47ec
TH
111
112 if ($units = $DB->get_records('question_numerical_units',
113 array('question' => $question->id), 'id ASC')) {
114 $units = array_values($units);
92b36005
PP
115 } else {
116 $units = array();
117 }
118 foreach ($units as $key => $unit) {
61cca0b7 119 $units[$key]->multiplier = clean_param($unit->multiplier, PARAM_FLOAT);
92b36005
PP
120 }
121 $question->options->units = $units;
122 return true;
123 }
124
fdd015b7 125 public function get_default_numerical_unit($question) {
92b36005
PP
126 if (isset($question->options->units[0])) {
127 foreach ($question->options->units as $unit) {
128 if (abs($unit->multiplier - 1.0) < '1.0e-' . ini_get('precision')) {
129 return $unit;
130 }
131 }
132 }
133 return false;
134 }
135
fdd015b7 136 public function get_numerical_options($question) {
c5da9906 137 global $DB;
fdd015b7
TH
138 if (!$options = $DB->get_record('question_numerical_options',
139 array('question' => $question->id))) {
52ad7e0c
TH
140 // Old question, set defaults.
141 $question->options->unitgradingtype = 0;
142 $question->options->unitpenalty = 0.1;
cf146692 143 if ($defaultunit = $this->get_default_numerical_unit($question)) {
52ad7e0c 144 $question->options->showunits = self::UNITINPUT;
fdd015b7 145 } else {
e0736817 146 $question->options->showunits = self::UNITNONE;
cf146692 147 }
52ad7e0c 148 $question->options->unitsleft = 0;
52ad7e0c 149
c5da9906 150 } else {
cf146692
PP
151 $question->options->unitgradingtype = $options->unitgradingtype;
152 $question->options->unitpenalty = $options->unitpenalty;
fe6ce234
DC
153 $question->options->showunits = $options->showunits;
154 $question->options->unitsleft = $options->unitsleft;
c5da9906 155 }
aeb15530 156
516cf3eb 157 return true;
158 }
fe6ce234 159
1fe641f7 160 /**
161 * Save the units and the answers associated with this question.
162 */
f77f47ec 163 public function save_question_options($question) {
f34488b2 164 global $DB;
fe6ce234
DC
165 $context = $question->context;
166
3d9645ae 167 // Get old versions of the objects.
69988ed4
TH
168 $oldanswers = $DB->get_records('question_answers',
169 array('question' => $question->id), 'id ASC');
170 $oldoptions = $DB->get_records('question_numerical',
171 array('question' => $question->id), 'answer ASC');
516cf3eb 172
1fe641f7 173 // Save the units.
fdd015b7 174 $result = $this->save_units($question);
516cf3eb 175 if (isset($result->error)) {
176 return $result;
177 } else {
69988ed4 178 $units = $result->units;
516cf3eb 179 }
180
3d9645ae 181 // Insert all the new answers.
69988ed4 182 foreach ($question->answer as $key => $answerdata) {
94a6d656 183 // Check for, and ingore, completely blank answer from the form.
69988ed4 184 if (trim($answerdata) == '' && $question->fraction[$key] == 0 &&
fe6ce234 185 html_is_blank($question->feedback[$key]['text'])) {
94a6d656 186 continue;
187 }
516cf3eb 188
69988ed4
TH
189 // Update an existing answer if possible.
190 $answer = array_shift($oldanswers);
191 if (!$answer) {
192 $answer = new stdClass();
193 $answer->question = $question->id;
194 $answer->answer = '';
195 $answer->feedback = '';
196 $answer->id = $DB->insert_record('question_answers', $answer);
197 }
198
199 if (trim($answerdata) === '*') {
94a6d656 200 $answer->answer = '*';
201 } else {
52ad7e0c
TH
202 $answer->answer = $this->apply_unit($answerdata, $units,
203 !empty($question->unitsleft));
94a6d656 204 if ($answer->answer === false) {
8766d198 205 $result->notice = get_string('invalidnumericanswer', 'qtype_numerical');
516cf3eb 206 }
94a6d656 207 }
208 $answer->fraction = $question->fraction[$key];
69988ed4
TH
209 $answer->feedback = $this->import_or_save_files($question->feedback[$key],
210 $context, 'question', 'answerfeedback', $answer->id);
fe6ce234 211 $answer->feedbackformat = $question->feedback[$key]['format'];
69988ed4 212 $DB->update_record('question_answers', $answer);
f34488b2 213
3d9645ae 214 // Set up the options object.
94a6d656 215 if (!$options = array_shift($oldoptions)) {
69988ed4 216 $options = new stdClass();
94a6d656 217 }
69988ed4
TH
218 $options->question = $question->id;
219 $options->answer = $answer->id;
94a6d656 220 if (trim($question->tolerance[$key]) == '') {
221 $options->tolerance = '';
222 } else {
52ad7e0c
TH
223 $options->tolerance = $this->apply_unit($question->tolerance[$key],
224 $units, !empty($question->unitsleft));
94a6d656 225 if ($options->tolerance === false) {
8766d198 226 $result->notice = get_string('invalidnumerictolerance', 'qtype_numerical');
94a6d656 227 }
6d1eb004 228 $options->tolerance = (string)$options->tolerance;
94a6d656 229 }
69988ed4 230 if (isset($options->id)) {
0bcf8b6f 231 $DB->update_record('question_numerical', $options);
69988ed4 232 } else {
0bcf8b6f 233 $DB->insert_record('question_numerical', $options);
1fe641f7 234 }
235 }
516cf3eb 236
69988ed4
TH
237 // Delete any left over old answer records.
238 $fs = get_file_storage();
fdd015b7 239 foreach ($oldanswers as $oldanswer) {
69988ed4
TH
240 $fs->delete_area_files($context->id, 'question', 'answerfeedback', $oldanswer->id);
241 $DB->delete_records('question_answers', array('id' => $oldanswer->id));
516cf3eb 242 }
fdd015b7 243 foreach ($oldoptions as $oldoption) {
69988ed4 244 $DB->delete_records('question_numerical', array('id' => $oldoption->id));
c5da9906 245 }
69988ed4 246
fdd015b7 247 $result = $this->save_unit_options($question);
69988ed4 248 if (!empty($result->error) || !empty($result->notice)) {
1fe641f7 249 return $result;
250 }
69988ed4 251
1fa39364
TH
252 $this->save_hints($question);
253
1fe641f7 254 return true;
516cf3eb 255 }
256
92b36005 257 /**
41dcc2a5 258 * The numerical options control the display and the grading of the unit
92b36005 259 * part of the numerical question and related types (calculateds)
fdd015b7
TH
260 * Questions previous to 2.0 do not have this table as multianswer questions
261 * in all versions including 2.0. The default values are set to give the same grade
92b36005 262 * as old question.
41dcc2a5 263 *
92b36005 264 */
e0736817 265 public function save_unit_options($question) {
c5da9906 266 global $DB;
0ff4bd08 267 $result = new stdClass();
69988ed4 268
e0736817
TH
269 $update = true;
270 $options = $DB->get_record('question_numerical_options',
271 array('question' => $question->id));
c5da9906 272 if (!$options) {
0ff4bd08 273 $options = new stdClass();
c5da9906 274 $options->question = $question->id;
69988ed4 275 $options->id = $DB->insert_record('question_numerical_options', $options);
c5da9906 276 }
69988ed4 277
1fa39364 278 if (isset($question->unitpenalty)) {
c5da9906 279 $options->unitpenalty = $question->unitpenalty;
1fa39364
TH
280 } else {
281 // Either an old question or a close question type.
e0736817 282 $options->unitpenalty = 1;
c5da9906 283 }
1fa39364
TH
284
285 $options->unitgradingtype = 0;
286 if (isset($question->unitrole)) {
287 // Saving the editing form.
288 $options->showunits = $question->unitrole;
289 if ($question->unitrole == self::UNITGRADED) {
290 $options->unitgradingtype = $question->unitgradingtypes;
fdd015b7 291 $options->showunits = $question->multichoicedisplay;
cf146692 292 }
1fa39364
TH
293
294 } else if (isset($question->showunits)) {
295 // Updated import, e.g. Moodle XML.
296 $options->showunits = $question->showunits;
57239949 297 if (isset($question->unitgradingtype)) {
298 $options->unitgradingtype = $question->unitgradingtype;
299 }
92b36005 300 } else {
1fa39364
TH
301 // Legacy import.
302 if ($defaultunit = $this->get_default_numerical_unit($question)) {
303 $options->showunits = self::UNITINPUT;
69988ed4 304 } else {
1fa39364 305 $options->showunits = self::UNITNONE;
cf146692 306 }
c5da9906 307 }
69988ed4 308
1fa39364 309 $options->unitsleft = !empty($question->unitsleft);
22f17bca 310
69988ed4 311 $DB->update_record('question_numerical_options', $options);
fe6ce234 312
f77f47ec
TH
313 // Report any problems.
314 if (!empty($result->notice)) {
315 return $result;
316 }
317
318 return true;
c5da9906 319 }
320
fdd015b7 321 public function save_units($question) {
f34488b2 322 global $DB;
0ff4bd08 323 $result = new stdClass();
516cf3eb 324
ed0ba6da 325 // Delete the units previously saved for this question.
f34488b2 326 $DB->delete_records('question_numerical_units', array('question' => $question->id));
ed0ba6da 327
26b26662 328 // Nothing to do.
329 if (!isset($question->multiplier)) {
330 $result->units = array();
331 return $result;
332 }
333
ed0ba6da 334 // Save the new units.
516cf3eb 335 $units = array();
cf146692 336 $unitalreadyinsert = array();
ed0ba6da 337 foreach ($question->multiplier as $i => $multiplier) {
3d9645ae 338 // Discard any unit which doesn't specify the unit or the multiplier.
fdd015b7
TH
339 if (!empty($question->multiplier[$i]) && !empty($question->unit[$i]) &&
340 !array_key_exists($question->unit[$i], $unitalreadyinsert)) {
341 $unitalreadyinsert[$question->unit[$i]] = 1;
0ff4bd08 342 $units[$i] = new stdClass();
516cf3eb 343 $units[$i]->question = $question->id;
52ad7e0c
TH
344 $units[$i]->multiplier = $this->apply_unit($question->multiplier[$i],
345 array(), false);
516cf3eb 346 $units[$i]->unit = $question->unit[$i];
979425b5 347 $DB->insert_record('question_numerical_units', $units[$i]);
516cf3eb 348 }
349 }
350 unset($question->multiplier, $question->unit);
351
516cf3eb 352 $result->units = &$units;
353 return $result;
354 }
355
f77f47ec
TH
356 protected function initialise_question_instance(question_definition $question, $questiondata) {
357 parent::initialise_question_instance($question, $questiondata);
358 $this->initialise_numerical_answers($question, $questiondata);
544de1c0
TH
359 $question->unitdisplay = $questiondata->options->showunits;
360 $question->unitgradingtype = $questiondata->options->unitgradingtype;
361 $question->unitpenalty = $questiondata->options->unitpenalty;
52ad7e0c
TH
362 $question->ap = $this->make_answer_processor($questiondata->options->units,
363 $questiondata->options->unitsleft);
c5da9906 364 }
365
18f9b2d2 366 public function initialise_numerical_answers(question_definition $question, $questiondata) {
f77f47ec
TH
367 $question->answers = array();
368 if (empty($questiondata->options->answers)) {
369 return;
370 }
371 foreach ($questiondata->options->answers as $a) {
544de1c0
TH
372 $question->answers[$a->id] = new qtype_numerical_answer($a->id, $a->answer,
373 $a->fraction, $a->feedback, $a->feedbackformat, $a->tolerance);
f77f47ec
TH
374 }
375 }
c5da9906 376
18f9b2d2 377 public function make_answer_processor($units, $unitsleft) {
ae3e2e6e 378 if (empty($units)) {
52ad7e0c 379 return new qtype_numerical_answer_processor(array());
c5da9906 380 }
52ad7e0c 381
ae3e2e6e
TH
382 $cleanedunits = array();
383 foreach ($units as $unit) {
384 $cleanedunits[$unit->unit] = $unit->multiplier;
f77f47ec 385 }
52ad7e0c 386
ae3e2e6e 387 return new qtype_numerical_answer_processor($cleanedunits, $unitsleft);
c5da9906 388 }
389
e0736817 390 public function delete_question($questionid, $contextid) {
f34488b2 391 global $DB;
9203b705
TH
392 $DB->delete_records('question_numerical', array('question' => $questionid));
393 $DB->delete_records('question_numerical_options', array('question' => $questionid));
394 $DB->delete_records('question_numerical_units', array('question' => $questionid));
395
396 parent::delete_question($questionid, $contextid);
516cf3eb 397 }
9203b705 398
0ff173d3
TH
399 public function get_random_guess_score($questiondata) {
400 foreach ($questiondata->options->answers as $aid => $answer) {
401 if ('*' == trim($answer->answer)) {
52ad7e0c 402 return max($answer->fraction - $questiondata->options->unitpenalty, 0);
0ff173d3
TH
403 }
404 }
405 return 0;
406 }
407
544de1c0 408 /**
52ad7e0c 409 * Add a unit to a response for display.
544de1c0
TH
410 * @param object $questiondata the data defining the quetsion.
411 * @param string $answer a response.
412 * @param object $unit a unit. If null, {@link get_default_numerical_unit()}
413 * is used.
414 */
415 public function add_unit($questiondata, $answer, $unit = null) {
416 if (is_null($unit)) {
417 $unit = $this->get_default_numerical_unit($questiondata);
418 }
419
420 if (!$unit) {
421 return $answer;
422 }
423
424 if (!empty($questiondata->options->unitsleft)) {
425 return $unit->unit . ' ' . $answer;
426 } else {
427 return $answer . ' ' . $unit->unit;
428 }
429 }
430
0ff173d3
TH
431 public function get_possible_responses($questiondata) {
432 $responses = array();
433
434 $unit = $this->get_default_numerical_unit($questiondata);
435
24400682 436 $starfound = false;
0ff173d3
TH
437 foreach ($questiondata->options->answers as $aid => $answer) {
438 $responseclass = $answer->answer;
439
24400682
TH
440 if ($responseclass === '*') {
441 $starfound = true;
442 } else {
544de1c0 443 $responseclass = $this->add_unit($questiondata, $responseclass, $unit);
0ff173d3
TH
444
445 $ans = new qtype_numerical_answer($answer->id, $answer->answer, $answer->fraction,
446 $answer->feedback, $answer->feedbackformat, $answer->tolerance);
447 list($min, $max) = $ans->get_tolerance_interval();
f4fe3968 448 $responseclass .= " ({$min}..{$max})";
0ff173d3
TH
449 }
450
451 $responses[$aid] = new question_possible_response($responseclass,
452 $answer->fraction);
453 }
24400682
TH
454
455 if (!$starfound) {
456 $responses[0] = new question_possible_response(
457 get_string('didnotmatchanyanswer', 'question'), 0);
458 }
459
0ff173d3
TH
460 $responses[null] = question_possible_response::no_response();
461
462 return array($questiondata->id => $responses);
463 }
464
516cf3eb 465 /**
1fe641f7 466 * Checks if the $rawresponse has a unit and applys it if appropriate.
467 *
468 * @param string $rawresponse The response string to be converted to a float.
469 * @param array $units An array with the defined units, where the
470 * unit is the key and the multiplier the value.
471 * @return float The rawresponse with the unit taken into
472 * account as a float.
473 */
e0736817 474 public function apply_unit($rawresponse, $units, $unitsleft) {
52ad7e0c 475 $ap = $this->make_answer_processor($units, $unitsleft);
3a6eb8ef
TH
476 list($value, $unit, $multiplier) = $ap->apply_units($rawresponse);
477 if (!is_null($multiplier)) {
478 $value *= $multiplier;
479 }
52ad7e0c 480 return $value;
b9bd6da4 481 }
fe6ce234 482
e0736817 483 public function move_files($questionid, $oldcontextid, $newcontextid) {
fe6ce234 484 $fs = get_file_storage();
5d548d3e
TH
485
486 parent::move_files($questionid, $oldcontextid, $newcontextid);
487 $this->move_files_in_answers($questionid, $oldcontextid, $newcontextid);
d44480f6 488 $this->move_files_in_hints($questionid, $oldcontextid, $newcontextid);
fe6ce234
DC
489 }
490
9203b705
TH
491 protected function delete_files($questionid, $contextid) {
492 $fs = get_file_storage();
493
494 parent::delete_files($questionid, $contextid);
495 $this->delete_files_in_answers($questionid, $contextid);
d44480f6 496 $this->delete_files_in_hints($questionid, $contextid);
9203b705 497 }
516cf3eb 498}
0ff173d3 499
52ad7e0c 500
0ff173d3
TH
501/**
502 * This class processes numbers with units.
503 *
504 * @copyright 2010 The Open University
505 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
506 */
507class qtype_numerical_answer_processor {
508 /** @var array unit name => multiplier. */
509 protected $units;
510 /** @var string character used as decimal point. */
511 protected $decsep;
512 /** @var string character used as thousands separator. */
513 protected $thousandssep;
544de1c0
TH
514 /** @var boolean whether the units come before or after the number. */
515 protected $unitsbefore;
0ff173d3
TH
516
517 protected $regex = null;
518
e0736817
TH
519 public function __construct($units, $unitsbefore = false, $decsep = null,
520 $thousandssep = null) {
0ff173d3
TH
521 if (is_null($decsep)) {
522 $decsep = get_string('decsep', 'langconfig');
523 }
524 $this->decsep = $decsep;
525
526 if (is_null($thousandssep)) {
527 $thousandssep = get_string('thousandssep', 'langconfig');
528 }
529 $this->thousandssep = $thousandssep;
530
531 $this->units = $units;
544de1c0 532 $this->unitsbefore = $unitsbefore;
0ff173d3
TH
533 }
534
535 /**
536 * Set the decimal point and thousands separator character that should be used.
537 * @param string $decsep
538 * @param string $thousandssep
539 */
540 public function set_characters($decsep, $thousandssep) {
541 $this->decsep = $decsep;
542 $this->thousandssep = $thousandssep;
543 $this->regex = null;
544 }
545
546 /** @return string the decimal point character used. */
547 public function get_point() {
548 return $this->decsep;
549 }
550
551 /** @return string the thousands separator character used. */
552 public function get_separator() {
553 return $this->thousandssep;
554 }
555
f040d4b0 556 /**
326bb547 557 * @return bool If the student's response contains a '.' or a ',' that
f040d4b0
TH
558 * matches the thousands separator in the current locale. In this case, the
559 * parsing in apply_unit can give a result that the student did not expect.
560 */
561 public function contains_thousands_seaparator($value) {
562 if (!in_array($this->thousandssep, array('.', ','))) {
563 return false;
564 }
565
566 return strpos($value, $this->thousandssep) !== false;
567 }
568
0ff173d3
TH
569 /**
570 * Create the regular expression that {@link parse_response()} requires.
571 * @return string
572 */
573 protected function build_regex() {
574 if (!is_null($this->regex)) {
575 return $this->regex;
576 }
577
544de1c0
TH
578 $decsep = preg_quote($this->decsep, '/');
579 $thousandssep = preg_quote($this->thousandssep, '/');
580 $beforepointre = '([+-]?[' . $thousandssep . '\d]*)';
581 $decimalsre = $decsep . '(\d*)';
0ff173d3
TH
582 $exponentre = '(?:e|E|(?:x|\*|×)10(?:\^|\*\*))([+-]?\d+)';
583
f4fe3968 584 $numberbit = "{$beforepointre}(?:{$decimalsre})?(?:{$exponentre})?";
b3c9da2f 585
544de1c0 586 if ($this->unitsbefore) {
f4fe3968 587 $this->regex = "/{$numberbit}$/";
544de1c0 588 } else {
f4fe3968 589 $this->regex = "/^{$numberbit}/";
0ff173d3 590 }
0ff173d3
TH
591 return $this->regex;
592 }
593
594 /**
1a1353a5
TH
595 * This method can be used for more locale-strict parsing of repsonses. At the
596 * moment we don't use it, and instead use the more lax parsing in apply_units.
597 * This is just a note that this funciton was used in the past, so if you are
598 * intersted, look through version control history.
599 *
0ff173d3
TH
600 * Take a string which is a number with or without a decimal point and exponent,
601 * and possibly followed by one of the units, and split it into bits.
602 * @param string $response a value, optionally with a unit.
603 * @return array four strings (some of which may be blank) the digits before
604 * and after the decimal point, the exponent, and the unit. All four will be
605 * null if the response cannot be parsed.
606 */
607 protected function parse_response($response) {
608 if (!preg_match($this->build_regex(), $response, $matches)) {
609 return array(null, null, null, null);
610 }
611
b3c9da2f
TH
612 $matches += array('', '', '', ''); // Fill in any missing matches.
613 list($matchedpart, $beforepoint, $decimals, $exponent) = $matches;
0ff173d3
TH
614
615 // Strip out thousands separators.
616 $beforepoint = str_replace($this->thousandssep, '', $beforepoint);
617
618 // Must be either something before, or something after the decimal point.
619 // (The only way to do this in the regex would make it much more complicated.)
620 if ($beforepoint === '' && $decimals === '') {
621 return array(null, null, null, null);
622 }
623
b3c9da2f
TH
624 if ($this->unitsbefore) {
625 $unit = substr($response, 0, -strlen($matchedpart));
626 } else {
627 $unit = substr($response, strlen($matchedpart));
628 }
544de1c0 629 $unit = trim($unit);
544de1c0 630
0ff173d3
TH
631 return array($beforepoint, $decimals, $exponent, $unit);
632 }
633
634 /**
1a1353a5
TH
635 * Takes a number in almost any localised form, and possibly with a unit
636 * after it. It separates off the unit, if present, and converts to the
637 * default unit, by using the given unit multiplier.
0ff173d3
TH
638 *
639 * @param string $response a value, optionally with a unit.
640 * @return array(numeric, sting) the value with the unit stripped, and normalised
641 * by the unit multiplier, if any, and the unit string, for reference.
642 */
5073fb74 643 public function apply_units($response, $separateunit = null) {
1a1353a5
TH
644 // Strip spaces (which may be thousands separators) and change other forms
645 // of writing e to e.
646 $response = str_replace(' ', '', $response);
647 $response = preg_replace('~(?:e|E|(?:x|\*|×)10(?:\^|\*\*))([+-]?\d+)~', 'e$1', $response);
e64e28d7
DP
648
649 // If a . is present or there are multiple , (i.e. 2,456,789 ) assume ,
650 // is a thouseands separator, and strip it, else assume it is a decimal
651 // separator, and change it to ..
652 if (strpos($response, '.') !== false || substr_count($response, ',') > 1) {
653 $response = str_replace(',', '', $response);
654 } else {
326bb547 655 $response = str_replace([$this->thousandssep, $this->decsep, ','], ['', '.', '.'], $response);
1a1353a5 656 }
e64e28d7 657
1a1353a5
TH
658 $regex = '[+-]?(?:\d+(?:\\.\d*)?|\\.\d+)(?:e[-+]?\d+)?';
659 if ($this->unitsbefore) {
f4fe3968 660 $regex = "/{$regex}$/";
1a1353a5 661 } else {
f4fe3968 662 $regex = "/^{$regex}/";
1a1353a5
TH
663 }
664 if (!preg_match($regex, $response, $matches)) {
3a6eb8ef 665 return array(null, null, null);
0ff173d3
TH
666 }
667
1a1353a5
TH
668 $numberstring = $matches[0];
669 if ($this->unitsbefore) {
3d9645ae 670 // Substr returns false when it means '', so cast back to string.
6c314a36 671 $unit = (string) substr($response, 0, -strlen($numberstring));
1a1353a5 672 } else {
6c314a36 673 $unit = (string) substr($response, strlen($numberstring));
0ff173d3
TH
674 }
675
5073fb74
TH
676 if (!is_null($separateunit)) {
677 $unit = $separateunit;
678 }
679
6c314a36 680 if ($this->is_known_unit($unit)) {
3a6eb8ef 681 $multiplier = 1 / $this->units[$unit];
0ff173d3 682 } else {
3a6eb8ef 683 $multiplier = null;
0ff173d3
TH
684 }
685
3d9645ae 686 return array($numberstring + 0, $unit, $multiplier); // The + 0 is to convert to number.
0ff173d3 687 }
544de1c0 688
5073fb74
TH
689 /**
690 * @return string the default unit.
691 */
692 public function get_default_unit() {
693 reset($this->units);
694 return key($this->units);
695 }
696
544de1c0
TH
697 /**
698 * @param string $answer a response.
699 * @param string $unit a unit.
700 */
d7d8cee2
TH
701 public function add_unit($answer, $unit = null) {
702 if (is_null($unit)) {
5073fb74 703 $unit = $this->get_default_unit();
d7d8cee2
TH
704 }
705
544de1c0
TH
706 if (!$unit) {
707 return $answer;
708 }
709
710 if ($this->unitsbefore) {
711 return $unit . ' ' . $answer;
712 } else {
713 return $answer . ' ' . $unit;
714 }
715 }
5d2465c3
TH
716
717 /**
718 * Is this unit recognised.
719 * @param string $unit the unit
720 * @return bool whether this is a unit we recognise.
721 */
722 public function is_known_unit($unit) {
723 return array_key_exists($unit, $this->units);
724 }
5073fb74
TH
725
726 /**
727 * Whether the units go before or after the number.
728 * @return true = before, false = after.
729 */
730 public function are_units_before() {
731 return $this->unitsbefore;
732 }
733
734 /**
735 * Get the units as an array suitably for passing to html_writer::select.
736 * @return array of unit choices.
737 */
738 public function get_unit_options() {
739 $options = array();
740 foreach ($this->units as $unit => $notused) {
741 $options[$unit] = $unit;
742 }
743 return $options;
744 }
0ff173d3 745}