Skip to content
Browse files

removed mistakenly committed regexp plugin

  • Loading branch information...
1 parent a0a1aeb commit 691d35efc29c1b8fd241fc2cd6e51bc64d5d8826 joseph_rezeau committed Oct 28, 2007
View
24 question/type/regexp/db/mysql.php
@@ -1,24 +0,0 @@
-<?php //$Id$
-
-// MySQL commands for upgrading this question type
-
-function qtype_regexp_upgrade($oldversion=0) {
- global $CFG;
-
- if ($oldversion == 0) { // First time install
- $result = modify_database("$CFG->dirroot/question/type/regexp/db/mysql.sql");
- return $result;
- }
-
- // Question type was installed before. Upgrades must be applied
-
- if ($oldversion < 2007012800) {
- $result = modify_database("$CFG->dirroot/question/type/regexp/db/mysql02.sql");
- return $result;
-
- }
-
- return true;
-}
-
-?>
View
15 question/type/regexp/db/mysql.sql
@@ -1,15 +0,0 @@
-
-
---
--- Table structure for table `prefix_question_regexp`
---
-
-CREATE TABLE prefix_question_regexp (
- id int(10) unsigned NOT NULL auto_increment,
- question int(10) unsigned NOT NULL default '0',
- answers varchar(255) NOT NULL default '',
- usehint tinyint(2) NULL default '0', PRIMARY KEY (id),
- KEY question (question)
-) TYPE=MyISAM COMMENT='Options for regexp questions';
-
--- --------------------------------------------------------
View
8 question/type/regexp/db/mysql02.sql
@@ -1,8 +0,0 @@
-
-
---
--- Add the usehint field to table `prefix_question_regexp`
---
-
-ALTER TABLE `prefix_question_regexp` ADD `usehint` TINYINT( 2 ) NULL DEFAULT '0';
--- --------------------------------------------------------
View
23 question/type/regexp/db/postgres7.php
@@ -1,23 +0,0 @@
-<?php //$Id$
-
-// PostgreSQL commands for upgrading this question type
-
-function qtype_regexp_upgrade($oldversion=0) {
- global $CFG;
-
-
- if ($oldversion == 0) { // First time install
- $result = modify_database("$CFG->dirroot/question/type/regexp/db/postgres7.sql");
- return $result;
- }
-
- // Question type was installed before. Upgrades must be applied
- if ($oldversion < 2007012800) {
- $result = modify_database("$CFG->dirroot/question/type/regexp/db/postgres7_02.sql");
- return $result;
-
- }
- return true;
-}
-
-?>
View
14 question/type/regexp/db/postgres7.sql
@@ -1,14 +0,0 @@
-
-# --------------------------------------------------------
-
-#
-# Table structure for table prefix_question_regexp
-#
-
-CREATE TABLE prefix_question_regexp (
- id SERIAL PRIMARY KEY,
- question integer NOT NULL default '0',
- answers varchar(255) NOT NULL default '',
- usehint integer NULL default '0'
-);
-CREATE INDEX prefix_question_regexp_question_idx ON prefix_question_regexp (question);
View
65 question/type/regexp/display.html
@@ -1,65 +0,0 @@
-<div class="qtext">
- <?php echo $questiontext; ?>
-</div>
-
-<?php if ($image) { ?>
- <img class="qimage" src="<?php echo $image; ?>" alt="" />
-<?php } ?>
-
-<div class="ablock clearfix">
- <div class="prompt">
- <?php echo get_string("answer", "quiz").': '; ?>
- </div>
-
- <div class="answer">
- <input type="text" <?php echo "$readonly $inputname $value"; ?> size="80"/>&nbsp;
- <?php
- // only print Hint button if all these conditions are met (readonly is set on Review page, where we do not want Hint button displayed)
- if ($question->options->usehint && ($cmoptions->optionflags == QUESTION_ADAPTIVE) && !$readonly ) {
- $p = get_string("hintpenalty", "qtype_regexp", $question->penalty);
- $q = 'resp'.$question->id.'_';
- $q2 = $q.'submit';
- $hint = get_string("hint", "qtype_regexp");
- echo('<input id ='.$q.' type="submit" name='.$q2.' value='.$hint.' title='.$p.' onclick="submittheform(this.id)" style="">');
- }
- ?>
-
- </div>
- <?php if ($feedback) { ?>
- <div class="feedback">
- <?php echo $feedback ?>
- </div>
- <?php } ?>
- </div>
- <?php $this->print_question_submit_buttons($question, $state, $cmoptions, $options); ?>
-<?php if ($correctanswer) { ?>
- <div class="correctness correct">
- <?php echo get_string('correctanswer', 'quiz').': '. $correctanswer; ?>
- </div>
-<?php } ?>
-<!--js script for showing / hiding regexp generated alternative sentences (for teacher only)-->
-<?php
-$show = get_string("showalternate", "qtype_regexp");
-$hide = get_string("hidealternate", "qtype_regexp");
-echo ("<script>
-function showdiv(id,thisbutton) {
-if (document.getElementById(id).style.display == 'none') {
- document.getElementById(id).style.display = 'block'
- thisbutton.value = '".$hide."'
- } else {
- document.getElementById(id).style.display = 'none'
- thisbutton.value = '".$show."'
- }
- return;
-}
-function submittheform (myid) {
- a = document.forms[0].action;
- if (a.indexOf('preview.php')!=-1) {
- document.forms[0].name = 'responseform';
- }
- a = document.getElementsByName(myid)[0].value;
- document.getElementsByName(myid)[0].value = a + '\t';
- this.document.forms.responseform.submit();
-}
-</script>");
- ?>
View
102 question/type/regexp/edit_regexp_form.php
@@ -1,102 +0,0 @@
-<?php
-/** by Joseph Rézeau 23:43 24/02/2007
- * Defines the editing form for the shortanswer question type.
- *
- * @copyright &copy; 2007 Jamie Pratt
- * @author Jamie Pratt me@jamiep.org
- * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
- * @package questions
- */
-
-/**
- * shortanswer editing form definition.
- */
-
-class question_edit_regexp_form extends question_edit_form {
- /**
- * Add question-type specific form fields.
- *
- * @param MoodleQuickForm $mform the form being built.
- */
-
- function definition_inner(&$mform) {
- $langfile = 'qtype_'.$this->qtype();
-
- $mform->removeElement('generalfeedback'); //JR
- $menu = array(get_string('no', 'moodle'), get_string('yes', 'moodle'));
- $mform->addElement('select', 'usehint', get_string('usehint', 'qtype_regexp'), $menu);
- $mform->setHelpButton('usehint', array('regexphint', get_string('usehint', 'qtype_regexp'), 'qtype_regexp'));
- $mform->addElement('static', 'answersinstruct', get_string('correctanswers', 'quiz'), get_string('filloutoneanswer', $langfile));
- $mform->closeHeaderBefore('answersinstruct');
- $creategrades = get_grade_options();
- $gradeoptions = $creategrades->gradeoptions;
- $repeated = array();
- $repeated[] =& $mform->createElement('header', 'answerhdr', get_string('answerno', $langfile, '{no}'));
- $repeated[] =& $mform->createElement('text', 'answer', get_string('answer', 'quiz'),array('size'=>100)); //JR
- $repeated[] =& $mform->createElement('select', 'fraction', get_string('grade'), $gradeoptions);
- $repeated[] =& $mform->createElement('textarea', 'feedback', get_string('feedback', 'quiz'),array('cols'=>60, 'rows'=>1));
-
- if (isset($this->question->options)){
- $countanswers = count($this->question->options->answers);
- } else {
- $countanswers = 0;
- }
- $repeatsatstart = (QUESTION_NUMANS_START > ($countanswers + QUESTION_NUMANS_ADD))?
- QUESTION_NUMANS_START : ($countanswers + QUESTION_NUMANS_ADD);
- $repeatedoptions = array();
- $mform->setType('answer', PARAM_NOTAGS);
- $repeatedoptions['fraction']['default'] = 0;
- $this->repeat_elements($repeated, $repeatsatstart, $repeatedoptions, 'noanswers', 'addanswers', QUESTION_NUMANS_ADD, get_string('addmoreanswerblanks', 'qtype_shortanswer'));
-
- }
-
- function set_data($question) {
- if (isset($question->options)){
- $answers = $question->options->answers;
- if (count($answers)) {
- $key = 0;
- foreach ($answers as $answer){
- $default_values['answer['.$key.']'] = $answer->answer;
- $default_values['fraction['.$key.']'] = $answer->fraction;
- $default_values['feedback['.$key.']'] = $answer->feedback;
- $key++;
- }
- }
- $default_values['image'] = "None";
- $default_values['usehint'] = $question->options->usehint;
- $question = (object)((array)$question + $default_values);
- } else {
- $key = 0;
- $default_values['fraction['.$key.']'] = 1;
- $question = (object)((array)$question + $default_values);
- }
- parent::set_data($question);
- }
- function validation($data){
- $langfile = 'qtype_'.$this->qtype();
- $errors = array();
- $answers = $data['answer'];
- $answercount = 0;
- foreach ($answers as $answer){
- $trimmedanswer = trim($answer);
- if (!empty($trimmedanswer)){
- $parenserror = check_my_parens($trimmedanswer);
- if ($parenserror) {
- $errors['answer['.$answercount.']'] = $parenserror;
- }
- $answercount++;
- }
- }
- if ($answercount==0){
- $errors['answer[0]'] = get_string('notenoughanswers', $langfile);
- }
- if ($data['fraction'][0] != 1) {
- $errors['fraction[0]'] = get_string('fractionsnomax', $langfile, 1);
- }
- return $errors;
- }
- function qtype() {
- return 'regexp';
- }
-}
-?>
View
489 question/type/regexp/expandregexp.php
@@ -1,489 +0,0 @@
-<?php // $Id$
-
-// JOSEPH REZEAU 23:57 24/02/2007
-
-function expand_regexp($myregexp) {
- global $regexporiginal;
- $regexporiginal=$myregexp;
- $parenserror = check_my_parens($myregexp);
- if ($parenserror) {
- return;
- }
-
-// DEV il faudra peut etre revoir cette liste
- $charlist = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
-
-// change [a-c] to [abc] NOTE: ^ metacharacter is not processed inside []
- $pattern = '/\\[\w-\w\\]/'; // find [a-c] in $myregexp
- while (preg_match($pattern, $myregexp, $matches, PREG_OFFSET_CAPTURE) ) {
- $result = $matches[0][0];
- $offset = $matches[0][1];
- $stringleft = substr($myregexp, 0, $offset +1);
- $stringright = substr($myregexp, $offset + strlen($result) -1);
- $c1 = $result[1];
- $c3 = $result[3];
- $rs = '';
- for ($c = strrpos($charlist, $c1); $c < strrpos($charlist, $c3) +1; $c++) {
- $rs.= $charlist[$c];
- }
- $myregexp = $stringleft.$rs.$stringright;
- }
-
-// change [abc] to (a|b|c)
- $pattern = '/\\[.*?\\]/'; // find [abc] in $myregexp
- while (preg_match($pattern, $myregexp, $matches, PREG_OFFSET_CAPTURE) ) {
- $result = $matches[0][0];
- $offset = $matches[0][1];
- $stringleft = substr($myregexp, 0, $offset);
- $stringright = substr($myregexp, $offset + strlen($result));
- $rs = substr($result, 1, strlen($result) -2);
- $r = '';
- for ($i=0; $i < strlen($rs); $i++) {
- $r .= $rs[$i].'|';
- }
- $rs = '('.substr($r, 0, strlen($r)-1).')';
- $myregexp = $stringleft.$rs.$stringright;
- }
-
-// process ? in regexp (zero or one occurrence of preceding char)
- while (strpos($myregexp, '?')) {
- $c1 = strpos($myregexp, '?');
- $c0 = $myregexp[$c1 - 1];
-
-// if \? -> escaped ?, treat as literal char (replace with ¬ char temporarily)
-// this ¬ char chosen because non-alphanumeric & rarely used...
- if ($c0 == '\\') {
- $myregexp = substr($myregexp, 0,$c1 -1 ) .'¬' .substr($myregexp ,$c1 + 1);
- continue;
- }
-// if )? -> meta ? action upon parens (), replace with ¤ char temporarily
-// this ¤ char chosen because non-alphanumeric & rarely used...
- if ($c0 == ')') {
- $myregexp = substr( $myregexp, 0, $c1 -1 ) .'¤' .substr($myregexp, $c1 + 1);
- continue;
- }
-// if ? metacharacter acts upon an escaped char, put it in $c2
- if ($myregexp[$c1 - 2] == '\\') {
- $c0 = '\\'.$c0;
- }
- $c2 = '('.$c0.'|)';
- $myregexp = str_replace($c0.'?', $c2, $myregexp);
- }
- // replaces possible temporary ¬ char with escaped question mark
- if (strpos( $myregexp, '¬') != -1) {
- $myregexp = str_replace('¬', '\?', $myregexp);
- }
-// replaces possible temporary ¤ char with escaped question mark
- if (strpos( $myregexp, '¤') != -1) {
- $myregexp = str_replace('¤', ')?', $myregexp);
- }
-
-// process ? metacharacter acting upon a set of parentheses \(.*?\)\?
- $myregexp = str_replace(')?', '|)', $myregexp);
-
-// replace escaped characters with their escape code
- while ($c = strpos($myregexp, '\\')) {
- $s1 = substr($myregexp, $c, 2);
- $s2 = $myregexp[$c + 1];
- $s2 = rawurlencode($s2);
-
-// alaphanumeric chars can't be escaped; escape codes useful here are:
-// . = %2e ; + = %2b ; * = %2a
-// add any others as needed & modify below accordingly
- switch ($s2) {
- case '.' : $s2 = '%2e'; break;
- case '+' : $s2 = '%2b'; break;
- case '*' : $s2 = '%2a'; break;
- }
- $myregexp = str_replace($s1, $s2, $myregexp);
- }
-
-// remove starting and trailing metacharacters; not used for generation but useful for testing regexp
- if (strpos($myregexp, '^')) {
- $myregexp = substr($myregexp, 1);
- }
- if (strpos($myregexp, '$') == strlen($myregexp) -1) {
- $myregexp = substr( $myregexp, 0, strlen($myregexp) -1);
- }
-
-// process metacharacters not accepted in sentence generation
- $illegalchars = array ('+','*','.','{','}');
- $illegalchar = false;
- foreach ($illegalchars as $i) {
- if (strpos($myregexp, $i)) {
- $illegalchar = true;
- }
- }
- if ($illegalchar == true) {
- echo ("<p>SORRY! Cannot generate sentences from a regExp containing one of these metacharacters: ".implode(' ', $illegalchars)."<br>If you need to use one of them in your regExp as a LITERAL character, you must \'escape\' it.<br>EXAMPLE: The [bc]at sat on the ma[pt]\\.<p>Wrong regExp = <b>$myregexp</b>");
- return ('$myregexp');
- }
-
- $mynewregexp = find_nested_ors($myregexp); // check $myregexp for nested parentheses
- if ($mynewregexp != null) {
- $myregexp = $mynewregexp;
- }
-
- $result = find_ors($myregexp); // expand parenthesis contents
- if ( is_array($result) ) {
- $results = implode('\n', $result);
- }
- return $result; // returns array of alternate strings
-}
-
-function check_my_parens($myregexp) {
- $openparen = 0;
- $closeparen = 0;
- $opensqbrack = 0;
- $closesqbrack = 0;
- $iserror = false;
- $message = '';
- for ($i = 0; $i<strlen($myregexp); $i++) {
- if ($myregexp[$i] != '\\') {
- switch ($myregexp[$i]) {
- case '(': $openparen++; break;
- case ')': $closeparen++; break;
- case '[': $opensqbrack++; break;
- case ']': $closesqbrack++; break;
- default: break;
- }
- }
- }
- if ( ($openparen != $closeparen) || ($opensqbrack != $closesqbrack) ) {
- $iserror = true;
- $message .= get_string ('regexperror', 'qtype_regexp', $myregexp).'<br>';
- }
- if ($openparen != $closeparen) {
- $message .= get_string ('regexperrorparen', 'qtype_regexp').' - '.get_string ('regexperroropen', 'qtype_regexp', $openparen)." # ".get_string ('regexperrorclose', 'qtype_regexp', $closeparen).'<br>';
- }
- if ($opensqbrack != $closesqbrack) {
- $message .= get_string ('regexperrorsqbrack', 'qtype_regexp').' - '.get_string ('regexperroropen', 'qtype_regexp', $opensqbrack)." # ".get_string ('regexperrorclose', 'qtype_regexp', $closesqbrack);
- }
- if ($iserror) {
- return $message;
- }
- return;
-}
-
-// find individual $nestedors expressions in $myregexp
-function is_nested_ors ($mystring) {//return false;
- $orsstart = 0; $orsend = 0; $isnested = false; $parens = 0; $result = '';
- for ($i = 0; $i < strlen($mystring); $i++) {
- switch ($mystring[$i]) {
- case '(':
- $parens++;
- if ($parens == 1) {
- $orsstart = $i;
- }
- if ($parens == 2) {
- $isnested = true;
- }
- break;
- case ')':
- $parens--;
- if ($parens == 0) {
- if ($isnested == true) {
- $orsend = $i + 1;
- $i = strlen($mystring);
- break;
- } //end if
- } //end case
- } //end switch
- } // end for
- if ($isnested == true) {
- $result = substr( $mystring, $orsstart, $orsend - $orsstart);
- return $result;
- }
- return false;
-}
-
-// find nested parentheses
-function is_parents ($myregexp) {
- $finalresult = null;
- $pattern = '/[^(|)]*\\(([^(|)]*\\|[^(|)]*)+\\)[^(|)]*/';
- if (preg_match_all($pattern, $myregexp, $matches, PREG_OFFSET_CAPTURE)) {
- $matches = $matches[0];
- for ($i=0; $i<sizeof($matches); $i++) {
- $thisresult = $matches[$i][0];
- $leftchar = $thisresult[0];
- $rightchar = $thisresult[strlen($thisresult) -1];
- $outerchars = $leftchar .$rightchar;
- if ($outerchars !== '()') {
- $finalresult = $thisresult;
- break;
- }
- } // end for
- } // end if
-
- return $finalresult;
-}
-
-// find ((a|b)c)
-function find_nested_ors ($myregexp) {
-// find next nested parentheses in $myregexp
- while ($nestedors = is_nested_ors ($myregexp)) {
- $nestedorsoriginal = $nestedors;
-
-// find what?
- while ($myparent = is_parents ($nestedors)) {
- $leftchar = $nestedors[strpos($nestedors, $myparent) - 1];
- $rightchar = $nestedors[strpos($nestedors, $myparent) + strlen($myparent)];
- $outerchars = $leftchar.$rightchar;
-// il ne faut sans doute pas faire de BREAK ici...
- if ($outerchars == ')(') {
-// break;
- }
- switch ($outerchars) {
- case '||':
- case '()':
- $leftpar = '';
- $rightpar = '';
- break;
- case '((':
- case '))':
- case '(|':
- case '|(':
- case ')|':
- case '|)':
- $leftpar = '('; $rightpar = ')';
- break;
- default:
- break;
- }
- $t1 = find_ors ($myparent);
- $t = implode('|', $t1);
- $myresult = $leftpar.$t.$rightpar;
- $nestedors = str_replace( $myparent, $myresult, $nestedors);
-
- }
-// detect sequence of ((*|*)|(*|*)) within parentheses or |) or (| and remove all INSIDE parentheses
- $pattern = '/(\\(|\\|)\\([^(|)]*\\|[^(|)]*\\)(\\|\\([^(|)]*\\|[^(|)]*\\))*(\\)|\\|)/';
- while (preg_match($pattern, $nestedors, $matches, PREG_OFFSET_CAPTURE)) {
- $plainors = $matches[0][0];
- $leftchar = $plainors[0];
- $rightchar = $plainors[strlen($plainors) -1];
- $plainors2 = substr($plainors, 1, strlen($plainors) -2); // remove leading & trailing chars
- $plainors2 = str_replace( '(', '', $plainors2);
- $plainors2 = str_replace( ')', '', $plainors2);
- $plainors2 = $leftchar .$plainors2 .$rightchar;
- $nestedors = str_replace( $plainors, $plainors2, $nestedors);
- if (is_parents($nestedors)) {
- $myregexp = str_replace( $nestedorsoriginal, $nestedors, $myregexp);
- continue;
- }
- }
-
-// any sequence of (|)(|) in $nestedors? process them all
- $pattern = '/(\\([^(]*?\\|*?\\)){2,99}/';
- while (preg_match($pattern, $nestedors, $matches, PREG_OFFSET_CAPTURE)) {
- $parensseq = $matches[0][0];
- $myresult = find_ors ($parensseq);
- $myresult = implode('|', $myresult);
- $nestedors = str_replace( $parensseq, $myresult, $nestedors);
- }
-// test if we have reached the singleOrs stage
- if (is_parents ($nestedors) != null) {
- $myregexp = str_replace( $nestedorsoriginal, $nestedors, $myregexp);
- continue;
- }
-// no parents left in $nestedors, ...
-// find all single (*|*|*|*) and remove parentheses
- $patternsingleors = '/\\([^()]*\\)/';
- $patternsingleorstotal = '/^\\([^()]*\\)$/';
-
- while ($p = preg_match($patternsingleors, $nestedors, $matches, PREG_OFFSET_CAPTURE)) {
- $r = preg_match($patternsingleorstotal, $nestedors, $matches, PREG_OFFSET_CAPTURE);
- if ($r) {
- if ($matches[0][0] == $nestedors) {
- break;
- } // we have reached top of $nestedors: keep ( )!
- }
- $r = preg_match($patternsingleors, $nestedors, $matches, PREG_OFFSET_CAPTURE);
- $singleparens = $matches[0][0];
- $myresult = substr($singleparens, 1, strlen($singleparens)-2);
- $nestedors = str_replace( $singleparens, $myresult, $nestedors);
- if (is_parents ($nestedors) != null) {
- $myregexp = str_replace( $nestedorsoriginal, $nestedors, $myregexp);
- continue;
- }
-
- }
- $myregexp = str_replace( $nestedorsoriginal, $nestedors, $myregexp);
-
- } // end while ($nestedors = is_nested_ors ($myregexp))
- return $myregexp;
-}
-
-function find_ors ($mystring) {
-global $regexporiginal;
-
-// add extra space between consecutive parentheses (that extra space will be removed later on)
- $pattern = '/\\(.*?\\|.*?\\)/';
- while (strpos($mystring, ')(')) {
- $mystring = str_replace( ')(', ')µ(', $mystring);
- }
- if (strpos($mystring, ')(')) {
- $mystring = str_replace( ')(', ')£(', $mystring);
- }
-// in $mystring, find the parts outside of parentheses ($plainparts)
- $plainparts = preg_split($pattern, $mystring);
- if ($plainparts) {
- $plainparts = index_plain_parts ($mystring, $plainparts);
- }
- $a = preg_match_all($pattern, $mystring, $matches, PREG_OFFSET_CAPTURE);
- if(!$a) {
- $regexporiginal = stripslashes($regexporiginal);
- return $regexporiginal;
- }
- $plainors = index_ors($mystring, $matches);
-// send $list of $plainparts and $plainors to expand_ors () function
- return(expand_ors ($plainparts, $plainors));
-}
-
-function expand_ors ($plainparts, $plainors) {//return;
-
-// this function expands a chunk of words containing a single set of parenthesized alternatives
-// of the type: <(aaa|bbb)> OR <ccc (aaa|bbb)> OR <ccc (aaa|bbb) ddd> etc.
-// into a LIST of possible alternatives,
-// e.g. <ccc (aaa|bbb|)> -> <ccc aaa>, <ccc bbb>, <ccc>
- $expandedors = array();
- $expandedors[] = '';
- $slen = sizeof($expandedors);
- $expandedors[$slen-1] = '';
- if ($plainparts[0] == 0) { // if chunk begins with $plainparts
- $expandedors[$slen-1] = $plainparts[1];
- array_splice($plainparts, 0,2);
- }
- while ((sizeof($plainparts) !=0) || (sizeof($plainors) !=0)) { // go through sentence $plainparts
- $l = sizeof($expandedors);
- for ($k=0; $k<$l; $k++) {
- for ($m=0; $m < sizeof($plainors[1]); $m++) {
- $expandedors[] = '';
- $slen = sizeof($expandedors) -1;
- $expandedors[$slen] = $expandedors[0].$plainors[1][$m];
- if (sizeof($plainparts)) {
- if ($plainparts[1]) {
- $expandedors[$slen] .=$plainparts[1];
- }
- }
- $expandedors[$slen] = rawurldecode($expandedors[$slen]);
- }
- array_splice($expandedors, 0, 1);// remove current "model" sentence from Sentences
- }
- array_splice($plainors,0,2); // remove current $plainors
- array_splice($plainparts,0,2); // remove current $plainparts
-
- }
-// eliminate all extra µ signs which have been placed to replace consecutive parentheses by )µ(
- $n = count ($expandedors);
- for ($i = 0; $i < $n; $i++) {
- if (is_int(strpos($expandedors[$i], 'µ') ) ) { //corrects strpos for 1st char of a string found!
- $expandedors[$i] = str_replace('µ', '', $expandedors[$i]);
- }
- }
- return ($expandedors);
-}
-
-function index_plain_parts($mystring, $plainparts) {
- $indexedplainparts = array();
- if (is_array($plainparts) ) {
- foreach($plainparts as $parts) {
- if ($parts) {
- $index = strpos($mystring, $parts) ;
- $indexedplainparts[] = $index;
- $indexedplainparts[] = $parts;
- }
- }
- }
- return ($indexedplainparts);
-}
-
-function index_ors($mystring, $plainors) {
- $indexedplainors = array();
- foreach ($plainors as $ors) {
- foreach ($ors as $or) {
- $indexedplainors[] = $or[1];
- $o = substr($or[0], 1, strlen($or[0]) -2);
- $o = explode('|', $o);
- $indexedplainors[] = $o;
- }
- }
- return ($indexedplainors);
-}
-
-// functions adapted from Hot Potatoes
-function check_beginning( $guess, $answer, $ignorecase){
- if (substr($answer,0,8) == '<strong>'){ // this answer is in fact the regexp itself, do not process it
- return;
- }
- $guess = utf8_decode($guess);
- $answer = utf8_decode($answer);
- $outstring = '';
- if ($ignorecase) {
- $guessoriginal = $guess;
- $guess = strtoupper($guess);
- $answer = strtoupper($answer);
- }
- for ($i=0; ( $i<strlen($guess) && $i<strlen($answer) ) ; $i++) {
- if (strlen($answer) < $i ) {
- break;
- }
- if ($guess[$i] == $answer[$i]) {
- $outstring .= $guess[$i];
- } else {
- break;
- }
- }
- if ($ignorecase) {
- $outstring = substr($guessoriginal,0,strlen($outstring));
- }
- return $outstring;
-}
-
-function get_closest( $guess, $answers, $ignorecase){
-$ss = substr($guess, strlen($guess)-2);
- $closest[0] = ''; // closest answer
- $closest[1] = false; // closestcomplete false
- $closesta = '';
- $ishint = 0;
- $l = strlen($guess);
- if ( substr($guess, strlen($guess)-2) == '' ) {
- $ishint = 1;
- $guess = substr($guess, 0, $l -2);
- }
- $rightbits = array();
- foreach ( $answers as $answer) {
- $rightbits[0][] = $answer;
- $rightbits[1][] = check_beginning($guess, $answer, $ignorecase);
- }
- $s = sizeof($rightbits);
- $longest = 0;
- if ($s) {
- $a = $rightbits[0];
- $s = sizeof($a);
- for ($i=0; $i<$s ;$i++) {
- $a = $rightbits[0][$i];
- $g = $rightbits[1][$i];
- if (strlen($g) > $longest) {
- $longest = strlen($g);
- $closesta = $g;
- if ($ishint) {
- $a = utf8_decode($a); // for accents etc.
- $c = substr($a, $longest, 1);
- $closesta .= substr($a,$longest, 1);
- if (substr($a,$longest, 1) == ' ') { // if hint letter is a space, add next one
- $closesta .= substr($a,$longest + 1, 1);
- }
- if ($a == $closesta) {
- $closest[1] = true;
- }
-
- }
- }
- }
- }
- $closest[0] = utf8_encode($closesta);
- return $closest;
-}
-// end functions adapted from Hot Potatoes
-?>
View
BIN question/type/regexp/icon.gif
Deleted file not rendered
View
102 question/type/regexp/lang/en_utf8/help/regexp/regexp.html
@@ -1,102 +0,0 @@
-<h2 align="center">RegExp Short Answer Questions</h2>
-<p>Like the Short Answer question, the RegExp Short Answer question expects the respondent to answer an &quot;open&quot; question with a word or a short phrase. However, the RegExp system system gives you access to a more powerful system for
- analysing the student's answers. For a complete introduction to Regular Expressions,
- see these sites <a href="http://www.zend.com/zend/tut/tutorial-delin2.php" target="_blank">regular-expressions
-tutorial</a> or <a href="http://perso.wanadoo.fr/joseph.rezeau/eao/developpement/expandRegexpToString.htm#"
- target="_blank">rezeau.org</a>. </p>
-
-<h3>Correct answer matching a regular expression pattern </h3>
-<p>It is not possible to give complete examples of the vast possibilities offered
- by this system, and the following are just some possibilities. </p>
-<p><strong>Example 1.</strong> Suppose your question is &quot;What are the colors
- of the French flag?&quot;. In the Answer 1 box you would type the &quot;best&quot; answer, e.g. &quot;it's blue, white and red&quot;. For more details, see <a href="#firstcorrect">First&nbsp;correct&nbsp;answer</a> below. </p>
-<p>In the Answer 2 box you would type this regular
- expression: &quot;<span class="c_computeroutput">it&rsquo;s blue, white(,| and)
- red</span>/i&quot; (quotes should not be typed, of course) . This will match any of those 4 responses:</p>
-<ul>
- <li>it&rsquo;s blue, white, red</li>
- <li>it&rsquo;s blue, white and red</li>
- <li>It&rsquo;s blue, white, red</li>
- <li>It&rsquo;s blue, white and red </li>
-</ul>
-<p>Please note that by default a regular expression match is case sensitive; to
- make the match case insensitive you must add the <strong>/i</strong> parameter
- right at the end of your expression.</p>
-<p><strong>Example 2</strong>. Question: &quot;What is blue, or red, or yellow?&quot;.
- Answer: &quot;(|it's )a colou?r&quot;. This answer will match:</p>
-<ul>
- <li>a colour</li>
- <li> a color</li>
- <li>it's a colour</li>
- <li>it's a color</li>
-</ul>
-<p>Notes.- The beginning of this regular expression &quot;(|it's )&quot; will
- match either nothing or &quot;it's &quot; (i.e. &quot;it's&quot; followed by
- a space). The ? (question-mark) means: preceding character zero or one time;
- it is used here to match British English as well as US spelling.</p>
-<p><strong>Example 3.</strong> Question: &quot;Name an animal whose name is made
- of 3 letters and the middle letter is the vowel <em>a</em>&quot;. Anwer:
- &quot;[bcr]at&quot;. This will match: bat, cat and rat. </p>
-<h3>Detecting missing required words or character strings</h3>
-<p>Regular expressions alone cannot detect absent character strings, so you have to
- add a little code in your Answer to take care of this. Any Teacher Answer which
- begins with a double hyphen will analyse the student&rsquo;s response to find out
- whether the following string is present or absent. If present, the analysis
- continues to the next question; if absent, the analysis stops and the relevant
- Feedback message is displayed.</p>
-<p><strong>Example 4. </strong></p>
-<ul>
- <li>Answer 2: <span class="c_computeroutput">--.*blue.*</span>/i</li>
- <li>student answer: &quot;it's red and white&quot; </li>
- <li>Feedback 2: <span class="c_computeroutput">The color of the sky is missing!</span></li>
-</ul>
-<p>Here, the . (dot) stands for &ldquo;any character&rdquo; and the * (asterisk)
- means &ldquo;preceding special character repeated any number of times&rdquo;.
- The Answer2 regular expression above means: check whether the character string
- &quot;blue&quot;, preceded with anything and followed by anything is absent
- from the student's answer. Please note that the use of the asterisk is different
- in the normal Short Answer question type and in the RegExp question type.</p>
-<p><strong>Example 5.</strong> Question: &quot;Name an animal whose name is made of
- 3 letters and the middle letter is the vowel <em>a</em>&quot;. Teacher Answer: &quot;--[b|c|r]&quot;. Feedback: &quot;Your answer should start with one of these letters: b, c or r&quot; </p>
-<h3>Escaping special characters </h3>
-<p>If you need to use (in your Answers) characters which are part of the regular expressions set
- of <em>special characters</em> (or <em>meta</em> characters), you need to &quot;escape&quot; them (i.e. precede
- them with a backslash). E.g. if you want to accept the answer &quot;My computer
- cost 1000$&quot;, you must write the regular expression as &quot;My computer cost
- 1000\$&quot;. But please see <em>First correct answer</em> below. The special characters which must be escaped are the following <strong>.^$*()[]+?|{}</strong></p>
-<h3>Entering Answers in Edit Question mode (teacher)</h3>
-<p>[changes starting from February 2007 version of regexp question type] </p>
-<p>The Editing regular expression question interface screen has been slightly modified. </p>
-<h4>Display Hint Button</h4>
-<p>It is now possible for the teacher to tick a <strong>Display Hint Button</strong> box in order to allow the student to ask for a hint. This hint will add the next correct letter to the student's input response field and - if the penalty scheme has been enabled in the Quiz settings - will cost the student one penalty factor. When the student takes the quiz, mousing over the Hint button will display how much it will cost to &quot;buy&quot; a letter. By default Display Hint button value is set at No. Questions created prior to Feb. 2007 will have this No value. If you want to display the Hint button you'll have to edit those questions and select Yes and save. Please note that the Hint button will only be available to quizzes which have their Adaptive mode set to Yes, as it does not make sense to enable the Hint button for non-adaptive tests. </p>
-<p>Each time a student clicks the Hint button to buy a letter, an invisible paragraph character (&nbsp;&para;&nbsp;) is added to his response. When the teacher views the quiz results, that paragraph character is visible so the teacher knows that the Hint button was clicked for that response. </p>
-<h4><a name="firstcorrect" id="firstcorrect"></a>First correct answer</h4>
-<p>For a number of reasons, the way of entering the very first Answer (Answer 1) in your list of answers has been changed. For Answer 1 you must now enter an answer text which a) is the &quot;best&quot; possible answer; b) is <strong>not</strong> a regular expression or - more exactly - <em>will not be interpreted as a regular expression</em> but &quot;as is&quot; and c) has a Grade value of 100%. This means that you may have to edit regexp questions created prior to Feb. 2007 if they do not obey these rules. You will notice that when you create a new regexp question the Grade value for Answer 1 is already automatically set at 100%. You must not change this. If, however, you did, a warning message would be issued when you save your question, allowing you the opportunity to go back and set things right. In Moodle 1.8+ you won't be able to save your question if you have accidentally changed the 100% grade for Answer 1 for another value (this should not happen). </p>
-<p>Note.- There are two ways to enter an answer containing meta characters, according to whether this is Answer 1 or any of the subsequent Answers. Exemple question: how much did your computer cost?</p>
-<p>Answer 1: It cost $1,000.</p>
-<p>Answer 2: It cost ( me)?\$1,000\.</p>
-<p>In Anwer 1 you just type the expected answer &quot;as is&quot;. The text in Answer 2 will be interpreted as a regular expression, and thus you need to escape the two meta characters (the $ sign and the end-of-sentence full stop). Note that here I have added the optional pronoun &quot;me&quot;. </p>
-<h4>Other answers </h4>
-<p>Any answers with a Grade higher than 0% must be entered as valid regular expressions <em>which can yield acceptable alternative answers</em> (regardless of the Grade being less than 100%). </p>
-<p>This means that some regular expressions, which are perfectly valid and would correctly analyse the student's (correct) answer are not recommended. The only case where they would work is a) if your question's <strong>Display Hint Button</strong> is set at No and b) your quiz <strong>Adaptative Mode</strong> is set at No. This means that you must <em>not</em> enter as an answer with a grade higher than 0% a regular expression beginning with a double hyphen &quot;--&quot;, used for detecting missing character strings. </p>
-<h3>Previewing questions in popup window (teacher only) </h3>
-<p>[changes starting from February 2007 version of regexp question type] </p>
-<p>When the teacher previews a question in the popup preview question window it is now possible to display all of the acceptable alternative answers. Those alternative answers are automatically generated from the regular expressions you have entered when creating the question which carry a grade higher than 0%. The very first acceptable answer is printed as is at the top of the list. This is followed by all the other alternative acceptable answers, consisting of a) the Grade attributed; b) a reminder of the regular expression you entered and c) a list of all alternative answers.</p>
-<p>The only check done by the programme for the validity of your regular expressions consists in checking that opened parentheses and square brackets are correctly closed. If your parentheses and square brackets are not correctly closed, a warning message will be displayed showing the number of each. You should immediately edit the faulty question. </p>
-<p> However this does not totally protect you from other errors. If you made an error in one of your regular expressions, either of the following can happen: a) a PHP error notice or warning will be displayed, something like [<em><strong>Fatal error</strong>: Maximum execution time of 30 seconds exceeded etc.</em> ] or b) no error will be displayed but you will see by yourself that the alternative answers generated from your faulty regexp are in fact not acceptable. You should of course immediately edit the problem question, trying to find and correct the faulty regular expression. Hopefully a more robust and user-friendly checking mechanism will be available soon.</p>
-<p>It is highly recommended to use the preview popup window systematically immediately after having created or edited a regexp type question, and to click on the <strong>Show alternate answers</strong> button in order to check the validity of one's regular expressions. </p>
-<h3>Inserting regexp sub-questions in Cloze type questions</h3>
-<p>The syntax for inserting regexp sub-questions in Cloze type questions is as shown in the following examples.</p>
-<ul>
- <li>The colors
- of the French flag are {:REGEXP:=blue, white and red#Correct!~=<span class="c_computeroutput">it&rsquo;s blue, white(,| and)
- red</span>#Correct!~--.*blue.*#The color of the sky is missing.} </li>
- <li>The colors
- of the French flag are {:REGEXP:%100%blue, white and red#Correct!~%100%<span class="c_computeroutput">it&rsquo;s blue, white(,| and)
- red</span>#Correct!~--.*blue.*#The color of the sky is missing.} </li>
-</ul>
-<p>Please note that, as explained above, the very first answer must be Graded 100% (in Cloze type question syntax, all correct is either <strong>=</strong> or <strong>100%</strong>) and it must not be a regular expression. If you forget to give a 100% grade to the very first answer, a warning message will be displayed upon saving the question: &quot;<em>Answer 1 must be correct and its grade must be 100%. Do you want to go back and correct this?</em>&quot;. However, if you see this message, <em><strong>you must not click the </strong></em><strong>Yes</strong><em><strong> button</strong></em>, because it would not take you back to your Cloze type editing window. You must click <strong>No</strong> and immediately edit the faulty Cloze question and correct the problem.</p>
-<p>Please note that the syntax of the sub-questions inside a Cloze-type question must be followed exactly and that you must never ever copy and paste any question text from e.g. a word-processor into the Cloze-type question editing window. Quite often Cloze-type questions yield errors because extraneous blank spaces, new lines, or any odd formatting character has made its way into the question text.</p>
-<p>Unfortunately the Hint button will not be available to the student for a regexp question inserted into a Cloze-type question. Maybe this will be available later on, when I'm retired and have more time on my hands.</p>
-<hr />
-<p>Updated by JR 28-Mar-2007</p>
View
3 question/type/regexp/lang/en_utf8/help/regexp/regexphint.html
@@ -1,3 +0,0 @@
-<p align="center"><b>Hint button </b></p>
-
-<p>Selecting <strong>Display Hint Button</strong> -&gt; <strong>Yes</strong> will display a <strong>Hint</strong> button in order to allow the student to ask for a letter. This letter will be added to the student's actual response, possibly after extraneous wrong letters have been removed. If the penalty scheme has been enabled in the Quiz settings this hint will cost the student one penalty factor. When the student takes the quiz, moving the cursor over the Hint button will display a tooltip saying how much it will cost to &quot;buy&quot; a letter. By default Display Hint button value is set at No. Questions created prior to Feb. 2007 will have this value set at No. If you want to display the Hint button you'll have to edit those questions and select Yes and save. Please note that the Hint button will only be available to quizzes which have their Adaptive mode set to Yes, as it does not make sense to enable the Hint button for non-adaptive tests. </p>
View
20 question/type/regexp/lang/en_utf8/qtype_regexp.php
@@ -1,20 +0,0 @@
-<?php // $Id$
-$string['answerno'] = 'Answer $a';
-$string['addingregexp'] = 'Adding regular expression question';
-$string['editingregexp'] = 'Editing the regular expression question';
-$string['filloutoneanswer'] = '<em>Answer 1</em> must be a correct answer (grade = 100%%) and it must <strong>not</strong> be a regular expression.';
-$string['fractionsnomax'] = 'Answer $a must be correct and its grade must be 100%%.';
-$string['gradingdetailspenalty'] = 'Your submission(s) attracted a <strong>total</strong> penalty of $a. ';
-$string['hidealternate'] = 'Hide alternate answers';
-$string['hint'] = 'Hint';
-$string['hintpenalty'] = 'Hint&nbsp;cost&nbsp;for&nbsp;this&nbsp;question:&nbsp;$a&nbsp;penatly&nbsp;points';
-$string['notenoughanswers'] = 'This type of question requires at least one answer';
-$string['regexp'] = 'Regular expression short answer';
-$string['regexperror'] = 'Error in regular expression:<strong>$a</strong>';
-$string['regexperrorclose'] = 'close: <strong>$a</strong>';
-$string['regexperroropen'] = 'open: <strong>$a</strong>';
-$string['regexperrorparen'] = 'Parentheses';
-$string['regexperrorsqbrack'] = 'Square brackets';
-$string['showalternate'] = 'Show alternate answers';
-$string['usehint'] = 'Display Hint button';
-?>
View
67 question/type/regexp/lang/fr_utf8/help/regexp/regexp.html
@@ -1,67 +0,0 @@
-<h2 align="center">Questions à réponse courte avec expressions régulières </h2>
-<p>Tout comme la question à réponse courte, la question à réponse courte de type &quot;expression régulière&quot; attend de la part de l'élève une réponse à une question &quot;ouverte&quot;, consistant en un ou plusieurs mots ou une courte phrase. Cependant, l'utilisation des expressions régulières vous donne accès à un puissant système d'analyse de la réponse des élèves. Pour une introduction au système des expressions régulières, voir ces sites&nbsp;: <a href="http://www.zend.com/zend/tut/tutorial-delin2.php" target="_blank">regular-expressions
-tutorial</a> et <a href="http://perso.wanadoo.fr/joseph.rezeau/eao/developpement/expandRegexpToString.htm#"
- target="_blank">rezeau.org</a>. </p>
-<h3>Réponse correcte correspondant à une expression régulière </h3>
-<p>Il est impossible de fournir des exemples complets des vastes possibilités offertes par ce système, mais voici quelques possibilités. </p>
-<p><strong>Exemple 1</strong>. Supposons que votre question soit &quot;Donnes les couleurs du drapeau français&quot;. Dans le champ Solution 1 vous pourriez saisir cette expression régulière&nbsp;: &quot;(il est |)bleu, blanc(,| et) rouge/i&quot; (il ne faut pas taper les guillements, bien sûr ). Cette expression acceptera n'importe laquelle des réponses suivantes: </p>
-<ul>
- <li>il est bleu, blanc, rouge</li>
- <li>il est bleu, blanc et rouge</li>
- <li>Il est bleu, blanc, rouge</li>
- <li>Il est bleu, blanc et rouge</li>
- <li>bleu, blanc, rouge</li>
- <li>bleu, blanc et rouge </li>
-</ul>
-<p>Notez que par défaut une expression régulière est sensible à la casse (minuscules/majuscules). Pour rendre l'expression insensible à la casse, vous ajouterez le paramètre <strong>/i</strong> tout à la fin de l'expression.</p>
-<p><strong>Example 2</strong>. (en anglais) Question&nbsp;: &quot;What is blue, or red, or yellow?&quot;.
- Réponse&nbsp;: &quot;(|it's )a colou?r&quot;. Cette expression acceptera n'importe laquelle des réponses suivantes&nbsp;:</p>
-<ul>
- <li>a colour</li>
- <li> a color</li>
- <li>it's a colour</li>
- <li>it's a color</li>
-</ul>
-<p><strong>Note</strong>.- Le début de cette expression régulière &quot;<strong>(|it's )</strong>&quot; acceptera comme réponse soit rien soit &quot;<strong>it's</strong> &quot; (attention&nbsp;: <strong>it's</strong> suivi d'une espace). Le point d'interrogation signifie&nbsp;: le caractère qui précède, employé zéro ou une fois&nbsp;; nous l'utilisons ici pour accepter aussi bien l'orthographe anglaise (<strong>colour</strong>) qu'américaine (<strong>color</strong>). </p>
-<p><strong>Exemple 3.</strong> (en anglais encore) Question: &quot;Donnez en anglais le nom d'un animal qui fait 3 lettres et dont la lettreu du milieu ets la voyelle <em>a</em>&quot;. Réponse&nbsp;:
- &quot;[bcr]at&quot;. Ce qui acceptera les 3 réponses&nbsp;: <strong>bat</strong>, <strong>cat</strong> et <strong>rat</strong>. </p>
-<h3>Détection des mots ou chaînes de caractères manquants </h3>
-<p>Les expressions régulières seules ne permettent pas de détecter des mots ou groupes de lettres absents de la réponse d'un élève, il faudra donc ajouter un petit code pour y arriver. Toute réponse prévue par le professeur qui commencera par un double tiret analysera la réponse de l'élève pour voir si la chaîne de caractères qui suit est présente ou absente. Si cette chaîne est présente, l'analyse continuera jusqu'à la réponse prévue suivante&nbsp;; si la chaîne est absente, l'analyse s'arrêtera et le mesage de feedback prévu s'affichera. </p>
-<p><strong>Exemple 4. </strong>Question sur les couleurs du drapeau français. </p>
-<ul>
- <li>Réponse 2: <span class="c_computeroutput">--.*bleu.*</span>/i</li>
- <li>réponse de l'élève : &quot;il est blanc et rouge &quot; </li>
- <li>Feedback 2: <span class="c_computeroutput">Il manque la couleur du ciel !</span></li>
-</ul>
-<p>Ici, le point signifie &quot;n'importe quel caractère, et l'astérisque signifie &quot;le caractère qui précède, répété un nombre quelconque de fois&quot;. La réponse prévue n°&nbsp;2 ci-dessus signifie&nbsp;: vérifier si la chaîne de caractères &quot;bleu&quot;, précédée de n'importe quoi et suivie de n'importe quoi est absente de la réponse de l'élève. Notez que l'usage de l'astérisque est légèrement différent dans les questions de type Réponse Courte et dans les questions de type Réponse Courte avec expressions régulières. </p>
-<p><strong>Exemple 5.</strong> Question: &quot;Donnez en anglais le nom d'un animal qui fait 3 lettres et dont la lettreu du milieu ets la voyelle <em>a</em>&quot;. Réponse prévue&nbsp;: &quot;--[b|c|r]&quot;. Feedback: &quot;Votre réponse devrait commencer par l'une de ces 3 lettres : <strong>b</strong>, <strong>c</strong> ou <strong>r</strong>&quot;. </p>
-<h3>&Eacute;chapper les caractères spéciaux </h3>
-<p>Si vous avez besoin dans vos réponses prévues de caractères qui font partie de la liste des <strong>caractères spéciaux</strong> utilisés dans la syntaxe des expressions régulières, vous devrez les &quot;échapper&quot;, c-a-d les faire précéder d'une barre oblique inverse. Par exemple si vous voulez accepter la réponse &quot;Cet ordinateur vaut 1&nbsp;000$&quot;, vous écrirez ainsi l'expression régulière: &quot;Cet ordinateur vaut 1&nbsp;000\$&quot;. Voici la liste complète des caractères spéciaux qui doivent être échappés&nbsp;: <strong>^&nbsp;$&nbsp;*&nbsp;(&nbsp;)&nbsp;[&nbsp;]&nbsp;+&nbsp;?&nbsp;|&nbsp;{&nbsp;}</strong></p>
-<h3>Edition des Réponses en mode professeur </h3>
-<p>[modifications à dater de février 2007]</p>
-<p>L'écran d'édition des questions de type regexp a été légèrement modifié.</p>
-<h4>Affichage du bouton Indice</h4>
-<p>Il est désormais possible d'afficher un bouton <strong>Indice</strong> pour permettre à l'étudiant d'<em>acheter</em> une lettre. Le bouton Indice ne sera disponible pour l'étudiant que si dans le Test le paramètre <strong>Mode adaptatif </strong>a été réglé sur <strong>Oui</strong>. Si le paramètre Appliquer les pénalités a été activé dans les réglages du test, une pénalité correspondant au Facteur de pénalité sera appliquée à chaque &quot;achat&quot; de lettre par l'étudiant. Lorsque l'étudiant fait le test et qu'un bouton Indice est présent, en passant la souris sur ce bouton il verra s'afficher la pénalité que lui coûtera l'achat d'une lettre. </p>
-<p>Chaque fois que l'étudiant clique sur le bouton Indice pour acheter une lettre, un caractère paragraphe invisible (&nbsp;&para;&nbsp;) est ajouté au texte de sa réponse. Plus tard, lorsque le professeur visualise les résultats du test pour chaque étudiant, il peut voir ce caractère paragraphe à la fin de chaque réponse pour laquelle l'étudiant a demandé de l'aide. </p>
-<h4>Solution 1</h4>
-<p>Pour un certain nombre de raisons, la façon d'entrer les solutions dans Solution 1 a changé depuis la version de février 2007. Pour la Solution 1 vous devez maintenant entrer un texte qui a) est la &quot;meilleure&quot; réponse attendue possible; b) <strong>n'est pas</strong> une expression régulière ou - plus exactement - ne sera pas interprété comme telle mais comme du texte normal et c) à laquelle vous affectez une Note de 100%. Ceci veut dire que si vous avez créé des questions de type regexp avant Février 2007 vous devrez les modifier une par une pour vérifier qu'elles répondent bien à ces nouvelles règles. Vous remarquerez que lors de la création d'une nouvelle question de type regexp, la Note attribuée à la Solution 1 est automatiquement mise sur 100%. Vous ne devez pas modifier ceci. Si par hasard vous le faisiez, un message d'erreur vous le signalerait lors de l'enregistrement de votre question, et vous donnerait la possibilité de faire marche arrière pour corriger l'erreur. Message: &quot;La Solution 1 doit être correcte et avoir un score de 100%. Voulez-vous retourner modifier ceci ?&quot; </p>
-<p>Note.- Il y a maintenant deux manières d'entrer une solution contenant des méta caractères (<strong>^&nbsp;$&nbsp;*&nbsp;(&nbsp;)&nbsp;[&nbsp;]&nbsp;+&nbsp;?&nbsp;|&nbsp;{&nbsp;}</strong>), selon qu'il s'agit de la Solution 1 ou de l'une des solutions suivantes. Exemple: combien coûte cet ordinateur américain? </p>
-<p>Solution 1: Il vaut 1 000$.</p>
-<p>Solution 2: Il (m')?a couté 1 000\$\. </p>
-<p>Dans Solution 1 vous tapez la réponse attendue telle quelle. Dans la Solution 2 en revanche vous devez &quot;échapper&quot; les méta-caractères $ et point final.</p>
-<h4>Autres Solutions (Solution 2, 3, etc.) </h4>
-<p>Toute solution avec une Note supérieure à 0% doit être entrée sous forme d'une expression régulière qui peut générer des réponses alternatives acceptables (que la note soit de 100% ou inférieure). Ceci veut dire que vous ne pouvez pas entrer une solution ayant une Note supérieure à 0% et commençant par un double tiret --, syntaxe utilisée pour détecter l'absence de mots, comme expliqué plus haut.</p>
-<h3>Prévisualisation des questions dans une fenêtre popup (pour le professeur seulement)</h3>
-<p>[modifications à dater de février 2007]</p>
-<p>Lorsque le professeur prévisualise une question dans la fenêtre popup il peut désormais également voir la liste complète des solutions alternatives acceptables. Ces solutions alternatives sont automatiquement générées à partir des expressions régulières que vous avez entrées en créant la question et auxquelles vous avez attribué une note supérieure à 0%. La toute première solution (Solution 1) est affichée en tête de liste. Elle est suivie des autres solutions acceptables, sous la forme suivante: a) la note attribuée; b) un rappel de votre expression régulière et c) la liste des solutions générées par cette expression régulière.</p>
-<p>Actuellement le seul mécanisme de vérification de la validité des expressions régulières entrées par le professeur consiste à vérifier que les parenthèses ouvertes sont bien toutes refermées (ainsi que les crochets carrés, si vous les utilisez). Si le nombre de parenthèses (ou de crochets carrés) ouvertes ne correspond pas au nombre de parenthèses fermées, un message d'erreur vous en avertira, qui précisera l'expression régulière où l'erreur a été détectée ainsi que la nature de l'erreur (mais pas l'emplacement exact). Vous devrez immédiatement corriger l'expression régulière fautive dans la question en cours de prévisualisation. </p>
-<p>Toute autre erreur dans une expression régulière déclenchera l'un ou l'autre des comportements suivants lors de l'ouverture de la fenêtre popup de prévisualisation&nbsp;: a) une erreur de PHP du genre [<em><strong>Fatal error</strong>: Maximum execution time of 30 seconds exceeded etc.</em> ] ou bien b) pas de message d'erreur mais, en cliquant sur le bouton Afficher les réponses alternatives, vous pourrez constater que certaines des solutions générées par l'expression régulière fautive sont en fait inacceptables. Il vous faudra alors immédiatement revenir en mode édition pour essayer de repérer l'expression régulière fautive et la corriger. J'espère pouvoir bientôt proposer un système de détection des erreurs plus convivial...</p>
-<p>Insertion de sous-questions de type regexp dans une question de type Close</p>
-<p>Voici 2 exemples de syntaxe à utiliser pour ce type d'insertion:</p>
-<ul><li>Les couleurs du drapeau français sont&nbsp;: {:REGEXP:=bleu, blanc, rouge#Correct!~=<span class="c_computeroutput">le bleu, le blanc(,| et) le rouge </span>#Correct!~--.*bleu.*#Il manque la couleur du ciel.} </li>
-- <li>Les couleurs du drapeau français sont&nbsp;: {:REGEXP:%100%bleu, blanc, rouge#Correct!~%100%<span class="c_computeroutput">le bleu, le blanc(,| et) le rouge </span>#Correct!~%0%--.*bleu.*#Il manque la couleur du ciel.} </li>
--</ul>
-<p>Veuiller noter que, comme expliqué ci-dessus, la toute première solution doit avoir une note de 100% et ne doit pas être une expression régulière. Dans la syntaxe du type de question Cloze, une note de 100% s'écrit soit <strong>=</strong> soit <strong>%100%</strong>. Comme indiqué plus haut, si vous oubliez par hasard d'attribuer la note de 100% à la toute première solution de votre liste, au moment d'enregistrer votre question Cloze un message d'erreur vous en avertira. Toutefois, si vous voyez le message &quot;La Solution 1 doit être correcte et avoir un score de 100%. Voulez-vous retourner modifier ceci ?&quot; <em>vous ne devez pas cliquer sur le bouton Oui</em>, mais sur le bouton <strong>Non</strong>, puis retourner dans votre question Cloze et faire la correction nécessaire. </p>
-<p>Veuillez noter que la syntaxe des sous-questions insérées dans une question de type Cloze doit être suivie à la lettre et qu'il ne faut jamais copier-coller du texte depuis votre traitement de texte vers le texte d'une question de type Cloze sous peine d'en empêcher le bon fonctionnement.</p>
-<p>Malheureusement le bouton Indice n'est pas disponible pour une sous-question de type regexp insérée dans une question de type Cloze. Je ferai peut-être ça à la retraite... Un peu de patience! </p>
-
View
4 question/type/regexp/lang/fr_utf8/help/regexp/regexphint.html
@@ -1,4 +0,0 @@
-<p align="center"><strong>Le bouton Indice</strong></p>
-
-<p>Si <strong>Afficher le bouton Indice</strong> est sélectionné (<strong>Oui</strong>), un bouton <strong>Indice</strong> sera affiché au moment du Test pour permettre à l'étudiant d'<em>acheter</em> une lettre. Cette lettre sera ajoutée à la réponse de l'étudiant, après que d'éventuelles lettres superfétatoires et incorrectes aient été effacées. Si le paramètre <strong>Appliquer les pénalités</strong> a été réglé à <strong>Oui</strong> dans les paramètres généraux du Test, l'achat de cette lettre coûtera à l'étudiant la valeur indiquée dans la question à <strong>Facteur de pénalité</strong>. Lorsque l'étudiant fera le test, au survol du bouton Indice par la souris s'affichera une info-bulle indiquant le montant de la pénalité appliquée (<em>coût</em> de la lettre achetée). Par défaut l'affichage du bouton <strong>Indice</strong> est mis à Non. Pour les questions de type REGEXP créées avant la version REGEXP de février 2007, l'affichage du bouton <strong>Indice</strong> est également mis à <strong>Non</strong> par défaut. Si vous voulez le faire afficher il vous faudra ré-éditer vos questions.</p>
-<p>Enfin, notez que le bouton <strong>Indice</strong> s'affichera seulement dans les tests où le paramètre <strong>Mode adaptatif</strong> a été mis sur <strong>Oui</strong>. </p>
View
20 question/type/regexp/lang/fr_utf8/qtype_regexp.php
@@ -1,20 +0,0 @@
-<?php
-$string['answerno'] = 'Réponse $a';
-$string['addingregexp'] = 'Ajout d\'une question de type expression régulière.';
-$string['editingregexp'] = 'Modification d\'une question de type expression régulière';
-$string['filloutoneanswer'] = '<em>Solution 1</em> doit être correcte (Note = 100%%) et ne doit <strong>pas</strong> être une expression régulière.';
-$string['fractionsnomax'] = 'La Solution 1 doit être correcte et avoir un score de 100%%. Voulez-vous retourner modifier ceci&nbsp;?';
-$string['gradingdetailspenalty'] = 'Vous avez actuellement un total</strong> de $a points de pénalité. ';
-$string['hidealternate'] = 'Cacher les réponses alternatives';
-$string['hint'] = 'Indice';
-$string['hintpenalty'] = 'Coût&nbsp;de&nbsp;l\'indice&nbsp;pour&nbsp;cette&nbsp;question&nbsp;:&nbsp;$a&nbsp;points';
-$string['notenoughanswers'] = 'Ce type de question nécessite au moins une réponse!';
-$string['regexp'] = 'Réponse courte de type expression régulière';
-$string['regexperror'] = 'Erreur dans votre expression régulière&nbsp;: <strong>$a</strong>';
-$string['regexperrorclose'] = 'fermant(e)s: <strong>$a</strong>';
-$string['regexperroropen'] = 'ouvrant(e)s: <strong>$a</strong>';
-$string['regexperrorparen'] = 'Parenthèses';
-$string['regexperrorsqbrack'] = 'Crochets carrés';
-$string['showalternate'] = 'Afficher les réponses alternatives';
-$string['usehint'] = 'Afficher le bouton Indice';
-?>
View
649 question/type/regexp/questiontype.php
@@ -1,649 +0,0 @@
-<?php // $Id$
-
-///////////////////
-/// REGEXP ///
-///////////////////
-// Jean-Michel Vedrine & Joseph Rezeau - 23:36 26/03/2007
-// based on shortanswer/questiontype Moodle 1.6+
-// $Id$
-/// QUESTION TYPE CLASS //////////////////
-
-///
-/// This class contains some special features in order to make the
-/// question type embeddable within a multianswer (cloze) question
-///
-
-/// TODO
-// display whole set of alternative correct answers to student if correct answers is ON - maybe not a good idea?
-///
-
- include("expandregexp.php"); // to generate alternate correct answers from reg expressions in answers
- class question_regexp_qtype extends default_questiontype {
- function name() {
- return 'regexp';
- }
-
- function get_question_options(&$question) {
- // Get additional information from database
- // and attach it to the question object
- if (!$question->options = get_record('question_regexp', 'question', $question->id)) {
- notify('Error: Missing question options!');
- return false;
- }
-
- if (!$question->options->answers = get_records('question_answers', 'question',
- $question->id, 'id ASC')) {
- notify('Error: Missing question answers!');
- return false;
- }
- return true;
- }
-
- function save_question_options($question) {
- if (!$oldanswers = get_records("question_answers", "question", $question->id, "id ASC")) {
- $oldanswers = array();
- }
-
- $answers = array();
- $maxfraction = -1;
- $i = 0;
-
- // Insert all the new answers
- foreach ($question->answer as $key => $dataanswer) {
- $i++;
- $result = '';
- $answer = '';
- if ($dataanswer != "") {
- if ($oldanswer = array_shift($oldanswers)) { // Existing answer, so reuse it
- $answer = $oldanswer;
- $answer->answer = trim($dataanswer);
- $answer->fraction = $question->fraction[$key];
- $answer->feedback = $question->feedback[$key];
- if (!update_record("question_answers", $answer)) {
- $result->error = "Could not update quiz answer! (id=$answer->id)";
- return $result;
- }
- } else { // This is a completely new answer
- unset($answer);
- $answer->answer = trim($dataanswer);
- $answer->question = $question->id;
- $answer->fraction = $question->fraction[$key];
- $answer->feedback = $question->feedback[$key];
- if (!$answer->id = insert_record("question_answers", $answer)) {
- $result->error = "Could not insert quiz answer!";
- return $result;
- }
- }
- $answers[] = $answer->id;
- if ( ($i == 1) && ($question->fraction[$key] == 1) ) {
- $maxfraction = 1;
- }
- }
- }
- if (!$question->usehint) { // for instance the regexp has been authored as part of a CLOZE question, no usehint value has been provided
- $question->usehint = 0;
- }
-
- if ($options = get_record("question_regexp", "question", $question->id)) {
- $options->answers = implode(",",$answers);
- $options->usehint = $question->usehint;
- if (!update_record("question_regexp", $options)) {
- $result->error = "Could not update quiz regexp options! (id=$options->id)";
- return $result;
- }
- } else {
- unset($options);
- $options->question = $question->id;
- $options->answers = implode(",",$answers);
- $options->usehint = $question->usehint;
- if (!insert_record("question_regexp", $options)) {
- $result->error = "Could not insert quiz regexp options!";
- return $result;
- }
- }
-
- // delete old answer records
- if (!empty($oldanswers)) {
- foreach($oldanswers as $oa) {
- delete_records('question_answers', 'id', $oa->id);
- }
- }
-
- /// Perform sanity checks on fractional grades
- if ($maxfraction != 1) {
- $maxfraction = $maxfraction * 100;
- $result->noticeyesno = get_string("fractionsnomax", "qtype_regexp", $maxfraction);
- return $result;
- } else {
- 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_regexp", "question", $questionid);
- return true;
- }
- function print_question_formulation_and_controls(&$question, &$state, $cmoptions, $options) {
- global $CFG;
- global $firstcorrectanswer;
- global $closestcomplete;
- $firstcorrectanswer ='';
- $formatoptions = '';
- // get *first* correct answer for this question
- // rewrite this function if more answers are needed
- $correctanswers = $this->get_correct_responses($question, $state);
- $readonly = empty($options->readonly) ? '' : 'readonly="readonly"';
- $formatoptions->noclean = true;
- $formatoptions->para = false;
- $nameprefix = $question->name_prefix;
- $isadaptive = ($cmoptions->optionflags & QUESTION_ADAPTIVE);
- $ispreview = ($state->attempt == 0); // workaround to detect if question is displayed to teacher in preview popup window
- /// Print question text and media
-
- $questiontext = format_text($question->questiontext,
- $question->questiontextformat,
- $formatoptions, $cmoptions->course);
- $image = get_question_image($question, $cmoptions->course);
- /// Print input controls
- if (isset($state->responses[''])) {
- $r = $this->remove_blanks($state->responses['']); // $r = original full student response
- if ($closest = $this->find_closest(&$question, &$state, &$teststate, $isadaptive, $ispreview) ) {
- $response = $closest;
- } else {
- $response = $r;
- }
- $value = ' value="'.s($response, true).'" ';
- } else {
- $value = ' value="" ';
- }
- $inputname = ' name="'.$nameprefix.'" ';
- $r = stripslashes($r);
- $f = ''; // student's response with corrections to be displayed in feedback div
- $s = ''; // wrong part of student's response to be displayed in red crossed-out in feedback div
- $ishint = false;
- $l = strlen($r);
- if (substr($r, $l-2) == '' ) { // hint asked for; remove paragraph mark from student's response
- $r = substr($r, 0, $l - 2);
- $ishint = true;
- }
-
- if ( ($ispreview || $isadaptive) && $r ) {
-
- $s = $this->utf8_substr ($r, strlen (utf8_decode($response) ), 99);
- if ($ishint and $s) {
- $s = $this->utf8_substr ($r, strlen (utf8_decode($response) ) -1, 99);
- $response = $this->utf8_substr($response, 0, strlen (utf8_decode($response)) - 1);
- }
- if ($closest) {
- $f = '<span style="color:#0000FF;">'.$response.'</span><span style="text-decoration:line-through; color:#FF0000;">'.$s."</span><br>";
- } else {
- $f = '<span style="text-decoration:line-through; color:#FF0000;">'.stripslashes($response)."</span><br>";
- }
- }
- $feedback = '';
-
- if ($options->feedback) {
- if ($closestcomplete) { // hint has added to response one letter which makes response match one correct answer: submission is correct!
- // we must tell $state that everything is OK
- $state->responses[''] = $closest;
- $state->last_graded->responses[''] = $closest;
- $state->last_graded->grade = $question->maxgrade - $state->last_graded->sumpenalty;
- $state->raw_grade = $question->maxgrade;
- $state->last_graded->raw_grade = $question->maxgrade;
- }
-
- foreach($question->options->answers as $answer) {
- if($this->test_response($question, $state, $answer)) {
- if ($answer->feedback) {
- $feedback = format_text($answer->feedback, true, $formatoptions, $cmoptions->course);
- }
- break;
- }
- }
- }
- $feedback = $f .$feedback;
- $correctanswer = '';
- if ($options->readonly && $options->correct_responses) {
- $delimiter = '';
- if ($correctanswers) {
- foreach ($correctanswers as $ca) {
- $correctanswer .= $delimiter.$ca;
- $delimiter = ', ';
- }
- }
- }
- $correctanswer = stripslashes($correctanswer);
- include("$CFG->dirroot/question/type/regexp/display.html");
- }
-
-// remove extra blank spaces from student's response
- function remove_blanks($text) {
- $pattern = "/ /"; // finds 2 successive spaces (note: \s does not work with French 'à' character!
- while($w = preg_match($pattern, $text, $matches, PREG_OFFSET_CAPTURE) ) {
- $text = substr($text, 0, $matches[0][1]) .substr($text ,$matches[0][1] + 1);
- }
- return $text;
- }
-
- function utf8_substr($str, $from, $len){
- # utf8 substr
- # www.yeap.lv
- return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$from.'}'.
- '((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s',
- '$1',$str);
- }
-
- // ULPGC ecastro
- // this function is used by the Item analysis module!
- function check_response(&$question, &$state) {
- //JR uncomment return false if you want real student answers displayed
- //return false;
- $answers = &$question->options->answers;
- $testedstate = clone($state);
- $teststate = clone($state);
- $i = 0;
- foreach($answers as $aid => $answer) {
- $teststate->responses[''] = $answer->answer;
- if($this->compare_responses($question, $testedstate, $teststate) ) {
- return $aid;
- }
- }
- return false;
- }
-
- function grade_responses(&$question, &$state, $cmoptions) {
- $teststate = clone($state);
- $state->raw_grade = 0;
- // Compare the response with every teacher answer in turn
- // and return the first one that matches.
- foreach($question->options->answers as $answer) {
- // Now we use a bit of a hack: we put the answer into the response
- // of a teststate so that we can use the function compare_responses()
- $teststate->responses[''] = trim($answer->answer);
- if($this->compare_responses($question, $state, $teststate)) {
- $state->raw_grade = $answer->fraction;
- break;
- }
- }
-
- // Make sure we don't assign negative or too high marks
- $state->raw_grade = min(max((float) $state->raw_grade,
- 0.0), 1.0) * $question->maxgrade;
- $state->penalty = $question->penalty * $question->maxgrade;
- // mark the state as graded
- $state->event = ($state->event == QUESTION_EVENTCLOSE) ? QUESTION_EVENTCLOSEANDGRADE : QUESTION_EVENTGRADE;
- return true;
- }
-
-
- function compare_responses(&$question, &$state, &$teststate) {
- global $firstcorrectanswer;
- if (isset($state->responses[''])) {
- $response0 = $this->remove_blanks( stripslashes( $state->responses[''] ) );
- } else {
- $response0 = '';
- }
- if (!$response0) {
- return false;
- }
- if (!$firstcorrectanswer) {
- foreach ($question->options->answers as $answer) {
- $firstcorrectanswer = $answer->answer;
- break;
- }
- }
- $r = $this->remove_blanks($state->responses['']); // $r = original full student response
- if ($r && $question->options->usehint) {
- $c = $r[strlen($r)-1];
- $d = ord($c);
- if ($d == 9) { // hint button added \t char (code 9) at end of student response
- $r = substr($r,0,strlen($r)-1) .'';
- $state->responses[''] = $r;
- }
- }
- if (isset($teststate->responses[''])) {
- $response1 = trim($teststate->responses['']);
- } else {
- $response1 = '';
- }
-// testing for presence of final /i code meaning ignore case
- $ignorecase = "";
- if ( substr($response1,strlen($response1) - 2, 2) == '/i') {
- $response1 = substr($response1,0,strlen($response1) - 2);
- $ignorecase = 'i';
- }
-// testing for presence of (right or wrong) elements in student's answer
- if ($response1 == $firstcorrectanswer) { // we must escape potential metacharacters in $firstcorrectanswer
- $response1 = quotemeta($teststate->responses['']);
- }
- if ( (preg_match('/^'.$response1.'$/'.$ignorecase, $response0)) ) {
- return true;
- }
-// testing for absence of needed (right) elements in student's answer, through initial -- coding
- if (substr($response1,0,2) == '--') {
- $response1 = substr($response1,2);
- if (preg_match('/^'.$response1.'$/'.$ignorecase, $response0) == 0) {
- return true;
- }
- }
- return false;
- }
-
-
- // function to find whether student's response matches at least the beginning of one of the correct answers
- function find_closest(&$question, &$state, &$teststate, $isadaptive, $ispreview) {
- global $CFG;
- global $firstcorrectanswer;
- global $closestcomplete;
- $closestcomplete = false;
-
- if (isset($state->responses[''])) {
- $response0 = $this->remove_blanks(stripslashes($state->responses['']));
- } else {
- return null;
- }
- if ( (!$isadaptive) && (!$ispreview) ) {
- return null; // no need to generate alternate answers because no hint will be needed in non-adaptive mode
- }
-
- // generate alternative answers for answers with score > 0%
- // this means that TEACHER MUST write answers with a > 0% grade as regexp generating alternative answers
- $correctanswers = array();
- $i = 0;
- foreach ($question->options->answers as $answer) {
- if ($i == 0) {
- $i++;
- if ($answer->fraction != 1) {
- notify ("ATTENTION! first answer must be <b>correct</b> and its Grade must be <b>100%</b>");
- } else {
- $firstcorrectanswer = $answer->answer;
- $correctanswer['answer'] = $answer->answer;
- $correctanswer['fraction'] = $answer->fraction;
- $correctanswers[] = $correctanswer;
- }
- } else if ($answer->fraction != 0) {
- $correctanswer['answer'] = $answer->answer;
- $correctanswer['fraction'] = $answer->fraction;
- $correctanswers[] = $correctanswer;
- }
- }
- $alternateanswers = array();
- $alternateanswersic = array();
- $i=0;
- foreach ($correctanswers as $thecorrectanswer) {
- $i++;
- if ($i == 1) {
- $alternateanswers[] = $firstcorrectanswer;
- continue;
- }
- $correctanswer = $thecorrectanswer['answer'];
- $fraction = $thecorrectanswer['fraction']*100;
- $fraction = $fraction."%"; //JR 05-10-2007
- if ( substr($correctanswer,strlen($correctanswer) - 2, 2) == '/i') { // ignore case
- $correctanswer = substr($correctanswer, 0, strlen($correctanswer) - 2);
- $r = expand_regexp($correctanswer); // go to expand_regexp function to generate alternative answers
- if ($r) { // if error in regular expression, expand_regexp will return nothing
- if (is_array($r)) {
- $alternateanswersic[] = "$fraction <strong>$correctanswer</strong> (ignore case)"; // CAUTION: the <strong> tag is detected in get_closest function!
- $alternateanswersic = array_merge($alternateanswersic, $r); // ignorecase alternateanswers
- } else {
- $alternateanswersic[] = "$fraction <strong>$r</strong>";
- $alternateanswersic[] = "$r";
- }
- }
- } else { // do not ignorecase
- $r = expand_regexp($correctanswer);
- if ($r) { // if error in regular expression, expand_regexp will return nothing
- if (is_array($r)) {
- $alternateanswers[] = "$fraction <strong>$correctanswer</strong>";
- $alternateanswers = array_merge($alternateanswers, $r); // normal alternateanswers
- } else {
- $alternateanswers[] = "$fraction <strong>$r</strong>";
- $alternateanswers[] = "$r";
- }
- }
- }
- }
-
-// print display button for teacher only
- if (($ispreview) && ((sizeof($alternateanswersic) != 0) || (sizeof($alternateanswers) != 0))) {
- $show = get_string("showalternate", "qtype_regexp");
- echo("<input type=\"button\" value=\"$show\" onclick=\"showdiv('allanswers',this)\" >");
-
-// print alernate answers
- echo('<div id="allanswers" style="margin-bottom:0px; margin-top:0px; display:none;"><hr>');
- foreach ($alternateanswers as $answer) {
- echo("$answer<br>");
- }
- foreach ($alternateanswersic as $answer) {
- echo("$answer<br>");
- }
- echo("<hr></div>");
- }
-// if student response is null (nothing typed in) then no need to go get closest correct answer
- if (!$response0) {
- return false;
- }
-// find closest answer matching student response
- if (is_array ($alternateanswers) ) {
- $closestanswer = get_closest( $response0, $alternateanswers, false);
- }
- if (is_array ($alternateanswersic) ) {
- $closestansweric = get_closest( $response0, $alternateanswersic, true);
- }
- if ($closestanswer[1] == true) {
- $closestcomplete = true;
- return $closestanswer[0];
- } elseif ($closestansweric[1] == true) {
- $closestcomplete = true;
- return $closestansweric[0];
- }
- if (strlen($closestanswer[0]) > strlen($closestansweric[0]) ) { // find longest closest answer from ignore case and don't ignore case
- $closest = $closestanswer[0];
- } else {
- $closest = $closestansweric[0];
- }
-// if nothing correct, give first character of firstcorrectanswer to student (if ishint is true)
- $ishint = false;
- if (substr($response0, strlen($response0)-2) == '' ) { // hint asked for
- $ishint = true;
- }
- if ($closest == '' && $ishint) {
- $closest = $this->utf8_substr ($firstcorrectanswer, 0, 1);
- }
- return $closest;
- }
-
- function test_response(&$question, &$state, &$answer) {
- $teststate = clone($state);
- $teststate->responses[''] = trim($answer->answer);
- if($this->compare_responses($question, $state, $teststate)) {
- return true;
- }
- return false;
- }
-
- function get_actual_response($question, $state) {
- // change length to truncate responses here if you want
- $lmax = 255;
- if (!empty($state->responses)) {
- $responses[] = (strlen($state->responses['']) > $lmax) ?
- substr($state->responses[''], 0, $lmax).'...' : $state->responses[''];
- } else {
- $responses[] = '';
- }
- return $responses;
- }
- /**
- * Return a summary of the student response
- *
- * This function returns a short string of no more than a given length that
- * summarizes the student's response in the given $state. This is used for
- * example in the response history table
- * @return string The summary of the student response
- * @param object $question
- * @param object $state The state whose responses are to be summarized
- * @param int $length The maximum length of the returned string
- */
- function response_summary($question, $state, $length=255) {
- // This should almost certainly be overridden
- return substr(implode(',', $this->get_actual_response($question, $state)), 0, $length);
- }
-
- /// BACKUP FUNCTIONS ////////////////////////////
-
- /*
- * Backup the data in the question
- *
- * This is used in question/backuplib.php
- */
- function backup($bf,$preferences,$question,$level=6) {
-
- $status = true;
-
- $regexps = get_records("question_regexp","question",$question,"id");
- //If there are regexps
- if ($regexps) {
- //Iterate over each regexp
- foreach ($regexps as $regexp) {
- $status = fwrite ($bf,start_tag("REGEXP",$level,true));
- //Print regexp contents
- fwrite ($bf,full_tag("ANSWERS",$level+1,false,$regexp->answers));
- fwrite ($bf,full_tag("USEHINT",$level+1,false,$regexp->usehint));
- $status = fwrite ($bf,end_tag("REGEXP",$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;
- $regexp = '';
-
- //Get the regexps array
- $regexps = $info['#']['REGEXP'];
-
- //Iterate over regexps
- for($i = 0; $i < sizeof($regexps); $i++) {
- $sho_info = $regexps[$i];
-
- //Now, build the question_regexp record structure
- $regexp->question = $new_question_id;
- $regexp->answers = backup_todb($sho_info['#']['ANSWERS']['0']['#']);
- $regexp->usehint = backup_todb($sho_info['#']['USEHINT']['0']['#']);
-
- //We have to recode the answers field (a list of answers id)
- //Extracts answer id from sequence
- $answers_field = "";
- $in_first = true;
- $tok = strtok($regexp->answers,",");
- while ($tok) {
- //Get the answer from backup_ids
- $answer = backup_getid($restore->backup_unique_code,"question_answers",$tok);
- if ($answer) {
- if ($in_first) {
- $answers_field .= $answer->new_id;
- $in_first = false;
- } else {
- $answers_field .= ",".$answer->new_id;
- }
- }
- //check for next
- $tok = strtok(",");
- }
- //We have the answers field recoded to its new ids
- $regexp->answers = $answers_field;
-
- //The structure is equal to the db, so insert the question_regexp
- $newid = insert_record ("question_regexp",$regexp);
-
- //Do some output
- if (($i+1) % 50 == 0) {
- if (!defined('RESTORE_SILENTLY')) {
- echo ".";
- if (($i+1) % 1000 == 0) {
- echo "<br />";
- }
- }
- backup_flush(300);
- }
-
- if (!$newid) {
- $status = false;
- }
- }
-
- return $status;
- }
-
-
- /**
- * Provide export functionality for xml format
- * @param question object the question object
- * @param format object the format object so that helper methods can be used
- * @param extra mixed any additional format specific data that may be passed by the format (see format code for info)
- * @return string the data to append to the output buffer or false if error
- */
- function export_to_xml( $question, $format, $extra=null ) {
- $expout = " <usehint>{$question->options->usehint}</usehint>\n ";
- foreach($question->options->answers as $answer) {
- $percent = 100 * $answer->fraction;
- $expout .= " <answer fraction=\"$percent\">\n";
- $expout .= $format->writetext( $answer->answer,3,false );
- $expout .= " <feedback>\n";
- $expout .= $format->writetext( $answer->feedback,4,false );
- $expout .= " </feedback>\n";
- $expout .= " </answer>\n";
- }
- return $expout;
- }
-
- function import_from_xml($data, $question, $format, $extra=null) {
- // get common parts
- $question = $format->import_headers($data);
-
- // header parts particular to regexp
- $question->qtype = 'regexp';
-
- // get usehint
- $question->usehint = $data['#']['usehint'][0]['#'];
-
- // run through the answers
- $answers = $data['#']['answer'];
- $a_count = 0;
- foreach ($answers as $answer) {
- $ans = $format->import_answer( $answer );
- $question->answer[$a_count] = $ans->answer;
- $question->fraction[$a_count] = $ans->fraction;
- $question->feedback[$a_count] = $ans->feedback;
- ++$a_count;
- }
- return $question; }
-
-}
-//// END OF CLASS ////
-
-//////////////////////////////////////////////////////////////////////////
-//// INITIATION - Without this line the question type is not in use... ///
-//////////////////////////////////////////////////////////////////////////
-$QTYPES['regexp']= new question_regexp_qtype();
-// The following adds the questiontype to the menu of types shown to teachers
-$QTYPE_MENU['regexp'] = get_string("regexp", "qtype_regexp");
-
-?>
View
6 question/type/regexp/version.php
@@ -1,6 +0,0 @@
-<?PHP // $Id$
-
-$plugin->version = 2007012800;
-$plugin->requires = 2006032200;
-
-?>

0 comments on commit 691d35e

Please sign in to comment.
Something went wrong with that request. Please try again.