quiz editing MDL-24750 The Add random button should also let you add questions from...
authorTim Hunt <T.J.Hunt@open.ac.uk>
Mon, 22 Nov 2010 09:52:42 +0000 (09:52 +0000)
committerTim Hunt <T.J.Hunt@open.ac.uk>
Mon, 22 Nov 2010 09:52:42 +0000 (09:52 +0000)
Also includes a fix for MDL-24749 by Sam Hemelryk. Thanks Sam.

This commit also includes a certain amount of code cleaning up.

23 files changed:
mod/quiz/addrandom.php
mod/quiz/addrandomform.php [new file with mode: 0644]
mod/quiz/edit.js
mod/quiz/edit.php
mod/quiz/editlib.php
mod/quiz/lang/en/quiz.php
question/category_class.php
question/category_form_randomquestion.php [deleted file]
question/question.php
question/type/calculated/questiontype.php
question/type/calculatedmulti/questiontype.php
question/type/calculatedsimple/questiontype.php
question/type/description/questiontype.php
question/type/essay/questiontype.php
question/type/match/questiontype.php
question/type/multianswer/questiontype.php
question/type/multichoice/questiontype.php
question/type/numerical/questiontype.php
question/type/questiontype.php
question/type/random/edit_random_form.php
question/type/random/questiontype.php
question/type/shortanswer/questiontype.php
question/type/truefalse/questiontype.php

index cb4e7c2..36d603f 100644 (file)
  */
 require_once('../../config.php');
 require_once($CFG->dirroot . '/mod/quiz/editlib.php');
+require_once($CFG->dirroot . '/mod/quiz/addrandomform.php');
 require_once($CFG->dirroot . '/question/category_class.php');
 
 list($thispageurl, $contexts, $cmid, $cm, $quiz, $pagevars) =
         question_edit_setup('editq', '/mod/quiz/addrandom.php', true);
 
+// These params are only passed from page request to request while we stay on
+// this page otherwise they would go in question_edit_setup
+$returnurl = optional_param('returnurl', '', PARAM_LOCALURL);
+$addonpage = optional_param('addonpage', 0, PARAM_INT);
+$category = optional_param('category', 0, PARAM_INT);
+
+// Get the course object and related bits.
+if (!$course = $DB->get_record('course', array('id' => $quiz->course))) {
+    print_error('invalidcourseid');
+}
+//you need mod/quiz:manage in addition to question capabilities to access this page.
+require_capability('mod/quiz:manage', $contexts->lowest());
+
+$PAGE->set_url($thispageurl);
+
+if ($returnurl) {
+    $returnurl = new moodle_url($returnurl);
+} else {
+    $returnurl = new moodle_url('/mod/quiz/edit.php', array('cmid' => $cmid));
+}
+
 $defaultcategoryobj = question_make_default_categories($contexts->all());
-$defaultcategoryid = $defaultcategoryobj->id;
-$defaultcategorycontext = $defaultcategoryobj->contextid;
-$defaultcategory = "$defaultcategoryid, $defaultcategorycontext";
+$defaultcategory = $defaultcategoryobj->id . ',' . $defaultcategoryobj->contextid;
 
 $qcobject = new question_category_object(
     $pagevars['cpage'],
     $thispageurl,
     $contexts->having_one_edit_tab_cap('categories'),
-    $defaultcategoryid,
+    $defaultcategoryobj->id,
     $defaultcategory,
     null,
     $contexts->having_cap('moodle/question:add'));
 
-//setting the second parameter of process_randomquestion_formdata to true causes it to redirect on success
-$newquestioninfo = quiz_process_randomquestion_formdata($qcobject);
-if ($newquestioninfo == 'cancelled') {
-    $returnurl = optional_param('returnurl', 0, PARAM_LOCALURL);
-    if ($returnurl) {
-        redirect($CFG->wwwroot . $returnurl);
-    } else {
-        redirect($CFG->wwwroot . '/mod/quiz/edit.php?cmid=' . $cmid);
-    }
-}
-if ($newquestioninfo) {
-    $newrandomcategory = $newquestioninfo->newrandomcategory;
-    if (!$newrandomcategory) {
-        print_error('cannotcreatecategory');
-    } else {
-        add_to_log($quiz->course, 'quiz', 'addcategory',
-                "view.php?id = $cm->id", "$newrandomcategory", $cm->id);
-        redirect($CFG->wwwroot . "/mod/quiz/edit.php?cmid=$cmid&addonpage=$newquestioninfo->addonpage&addrandom=1&categoryid=$newquestioninfo->newrandomcategory&randomcount=1&sesskey=" . sesskey());
-    }
+$mform = new quiz_add_random_form(new moodle_url('/mod/quiz/addrandom.php'), $contexts);
+
+if ($mform->is_cancelled()) {
+    redirect($returnurl);
 }
 
-//these params are only passed from page request to request while we stay on this page
-//otherwise they would go in question_edit_setup
-$quiz_page = optional_param('quiz_page', 0, PARAM_SEQUENCE);
-$returnurl = optional_param('returnurl', 0, PARAM_LOCALURL);
+if ($data = $mform->get_data()) {
+    if (!empty($data->existingcategory)) {
+        list($categoryid) = explode(',', $data->category);
+        $includesubcategories = !empty($data->includesubcategories);
+        $returnurl->param('cat', $data->category);
 
-$url = new moodle_url('/mod/quiz/addrandom.php');
-if ($quiz_page != 0) {
-    $url->param('quiz_page', $quiz_page);
-}
-if ($returnurl != 0) {
-    $url->param('returnurl', $returnurl);
-}
-$PAGE->set_url($url);
+    } else if (!empty($data->newcategory)) {
+        list($parentid, $contextid) = explode(',', $data->parent);
+        $categoryid = $qcobject->add_category($data->parent, $data->name, '', true);
+        $includesubcategories = 0;
+        add_to_log($quiz->course, 'quiz', 'addcategory',
+                'view.php?id=' . $cm->id, $categoryid, $cm->id);
+        $returnurl->param('cat', $categoryid . ',' . $contextid);
 
-$strquizzes = get_string('modulenameplural', 'quiz');
-$strquiz = get_string('modulename', 'quiz');
-$streditingquestions = get_string('editquestions', 'quiz');
-$streditingquiz = get_string('editinga', 'moodle', $strquiz);
+    } else {
+        throw new coding_exception('It seems a form was submitted without any button being pressed???');
+    }
 
-// Get the course object and related bits.
-if (! $course = $DB->get_record('course', array('id' => $quiz->course))) {
-    print_error('invalidcourseid');
+    quiz_add_random_questions($quiz, $addonpage, $categoryid, 1, $includesubcategories);
+    redirect($returnurl);
 }
-//you need mod/quiz:manage in addition to question capabilities to access this page.
-require_capability('mod/quiz:manage', $contexts->lowest());
 
-// Print basic page layout.
+$mform->set_data(array(
+    'addonpage' => $addonpage,
+    'returnurl' => $returnurl,
+    'cmid' => $cm->id,
+    'category' => $category,
+));
+
+// Setup $PAGE.
+$streditingquiz = get_string('editinga', 'moodle', get_string('modulename', 'quiz'));
 $PAGE->navbar->add($streditingquiz);
 $PAGE->set_title($streditingquiz);
 $PAGE->set_heading($course->fullname);
@@ -87,9 +96,6 @@ if (!$quizname = $DB->get_field($cm->modname, 'name', array('id' => $cm->instanc
 }
 
 echo $OUTPUT->heading(get_string('addrandomquestiontoquiz', 'quiz', $quizname), 2, 'mdl-left');
-
-$addonpage = optional_param('addonpage_form', 0, PARAM_SEQUENCE);
-$qcobject->display_randomquestion_user_interface($addonpage);
-
+$mform->display();
 echo $OUTPUT->footer();
 
diff --git a/mod/quiz/addrandomform.php b/mod/quiz/addrandomform.php
new file mode 100644 (file)
index 0000000..2db19f3
--- /dev/null
@@ -0,0 +1,57 @@
+<?php
+
+require_once($CFG->libdir.'/formslib.php');
+
+class quiz_add_random_form extends moodleform {
+
+    function definition() {
+        global $CFG, $DB;
+        $mform =& $this->_form;
+
+        $contexts = $this->_customdata;
+
+//--------------------------------------------------------------------------------
+        $mform->addElement('header', 'categoryheader', get_string('randomfromexistingcategory', 'quiz'));
+
+        $mform->addElement('questioncategory', 'category', get_string('category'),
+                array('contexts' => $contexts->all(), 'top' => false));
+
+        $mform->addElement('checkbox', 'includesubcategories', '', get_string('recurse', 'quiz'));
+
+        $mform->addElement('submit', 'existingcategory', get_string('addrandomquestion', 'quiz'));
+
+//--------------------------------------------------------------------------------
+        $mform->addElement('header', 'categoryheader', get_string('randomquestionusinganewcategory', 'quiz'));
+
+        $mform->addElement('text', 'name', get_string('name'), 'maxlength="254" size="50"');
+        $mform->setType('name', PARAM_MULTILANG);
+
+        $mform->addElement('questioncategory', 'parent', get_string('parentcategory', 'question'),
+                array('contexts' => $contexts->all(), 'top' => true));
+        $mform->addHelpButton('parent', 'parentcategory', 'question');
+
+        $mform->addElement('submit', 'newcategory', get_string('createcategoryandaddrandomquestion', 'quiz'));
+
+//--------------------------------------------------------------------------------
+        $mform->addElement('cancel');
+        $mform->closeHeaderBefore('cancel');
+
+        $mform->addElement('hidden', 'addonpage', 0, 'id="rform_qpage"');
+        $mform->setType('addonpage', PARAM_SEQUENCE);
+        $mform->addElement('hidden', 'cmid', 0);
+        $mform->setType('cmid', PARAM_INT);
+        $mform->addElement('hidden', 'returnurl', 0);
+        $mform->setType('returnurl', PARAM_LOCALURL);
+    }
+
+    function validation($fromform, $files) {
+        $errors = parent::validation($fromform, $files);
+
+        if (!empty($fromform['newcategory']) && trim($fromform['name']) == '') {
+            $errors['name'] = get_string('categorynamecantbeblank', 'quiz');
+        }
+
+        return $errors;
+    }
+}
+
index 659282c..d96842f 100644 (file)
@@ -6,6 +6,9 @@ function quiz_edit_init() {
 
     // Add random question dialogue --------------------------------------------
 
+    var randomquestiondialog = YAHOO.util.Dom.get('randomquestiondialog');
+    YAHOO.util.Dom.get(document.body).appendChild(randomquestiondialog);
+
     quiz_edit.randomquestiondialog = new YAHOO.widget.Dialog('randomquestiondialog', {
             modal: true,
             width: '100%',
@@ -28,7 +31,7 @@ function quiz_edit_init() {
         // Transfer the page number from the button form to the pop-up form.
         var addrandombutton = YAHOO.util.Event.getTarget(e);
         var addpagehidden = YAHOO.util.Dom.getElementsByClassName('addonpage_formelement', 'input', addrandombutton.form);
-        document.getElementById('rform_qpage').value = addpagehidden.value;
+        document.getElementById('rform_qpage').value = addpagehidden[0].value;
 
         // Show the dialogue and stop the default action.
         quiz_edit.randomquestiondialog.show();
@@ -46,6 +49,10 @@ function quiz_edit_init() {
         YAHOO.util.Event.preventDefault(e);
     });
 
+    YAHOO.util.Event.addListener('id_existingcategory', 'click', quiz_yui_workaround);
+
+    YAHOO.util.Event.addListener('id_newcategory', 'click', quiz_yui_workaround);
+
     // Repaginate dialogue -----------------------------------------------------
     quiz_edit.repaginatedialog = new YAHOO.widget.Dialog('repaginatedialog', {
             modal: true,
@@ -88,6 +95,17 @@ function quiz_edit_init() {
     }
 }
 
+function quiz_yui_workaround(e) {
+    // YUI does not send the button pressed with the form submission, so copy
+    // the button name to a hidden input.
+    var submitbutton = YAHOO.util.Event.getTarget(e);
+    var input = document.createElement('input');
+    input.type = 'hidden';
+    input.name = submitbutton.name;
+    input.value = 1;
+    submitbutton.form.appendChild(input);
+}
+
 // Initialise everything on the quiz settings form.
 function quiz_settings_init() {
     var repaginatecheckbox = document.getElementById('id_repaginatenow');
index 002e7f6..691bfbe 100644 (file)
@@ -49,6 +49,7 @@
 
 require_once('../../config.php');
 require_once($CFG->dirroot . '/mod/quiz/editlib.php');
+require_once($CFG->dirroot . '/mod/quiz/addrandomform.php');
 require_once($CFG->dirroot . '/question/category_class.php');
 
 /**
@@ -63,8 +64,7 @@ function module_specific_buttons($cmid, $cmoptions) {
     } else {
         $disabled = '';
     }
-    $straddtoquiz = get_string('addtoquiz', 'quiz');
-    $out = '<input type="submit" name="add" value="' . $OUTPUT->larrow() . ' ' . $straddtoquiz .
+    $out = '<input type="submit" name="add" value="' . $OUTPUT->larrow() . ' ' . get_string('addtoquiz', 'quiz') .
             '" ' . $disabled . "/>\n";
     return $out;
 }
@@ -79,7 +79,7 @@ function module_specific_controls($totalnumber, $recurse, $category, $cmid, $cmo
     $catcontext = get_context_instance_by_id($category->contextid);
     if (has_capability('moodle/question:useall', $catcontext)) {
         if ($cmoptions->hasattempts) {
-            $disabled = 'disabled="disabled"';
+            $disabled = ' disabled="disabled"';
         } else {
             $disabled = '';
         }
@@ -93,19 +93,22 @@ function module_specific_controls($totalnumber, $recurse, $category, $cmid, $cmo
             for ($i = 20; $i <= min(100, $maxrand); $i += 10) {
                 $randomcount[$i] = $i;
             }
-            $straddtoquiz = get_string('addtoquiz', 'quiz');
-            $out = '<strong><label for="menurandomcount">'.get_string('addrandomfromcategory', 'quiz').
-                    '</label></strong><br />';
-            $attributes = array();
-            $attributes['disabled'] = $cmoptions->hasattempts ? 'disabled' : null;
-            $select = html_writer::select($randomcount, 'randomcount', '1', null, $attributes);
-            $out .= get_string('addrandom', 'quiz', $select);
-            $out .= '<input type="hidden" name="recurse" value="'.$recurse.'" />';
-            $out .= '<input type="hidden" name="categoryid" value="' . $category->id . '" />';
-            $out .= ' <input type="submit" name="addrandom" value="'.
-                    $straddtoquiz.'" '.$disabled.' />';
-            $out .= $OUTPUT->help_icon('addarandomquestion', 'quiz');
+        } else {
+            $randomcount[0] = 0;
+            $disabled = ' disabled="disabled"';
         }
+
+        $out = '<strong><label for="menurandomcount">'.get_string('addrandomfromcategory', 'quiz').
+                '</label></strong><br />';
+        $attributes = array();
+        $attributes['disabled'] = $disabled ? 'disabled' : null;
+        $select = html_writer::select($randomcount, 'randomcount', '1', null, $attributes);
+        $out .= get_string('addrandom', 'quiz', $select);
+        $out .= '<input type="hidden" name="recurse" value="'.$recurse.'" />';
+        $out .= '<input type="hidden" name="categoryid" value="' . $category->id . '" />';
+        $out .= ' <input type="submit" name="addrandom" value="'.
+                get_string('addtoquiz', 'quiz').'"' . $disabled . ' />';
+        $out .= $OUTPUT->help_icon('addarandomquestion', 'quiz');
     }
     return $out;
 }
@@ -119,9 +122,7 @@ list($thispageurl, $contexts, $cmid, $cm, $quiz, $pagevars) =
         question_edit_setup('editq', '/mod/quiz/edit.php', true);
 
 $defaultcategoryobj = question_make_default_categories($contexts->all());
-$defaultcategoryid = $defaultcategoryobj->id;
-$defaultcategorycontext = $defaultcategoryobj->contextid;
-$defaultcategory = $defaultcategoryid . ',' . $defaultcategorycontext;
+$defaultcategory = $defaultcategoryobj->id . ',' . $defaultcategoryobj->contextid;
 
 if ($quiz_qbanktool > -1) {
     $thispageurl->param('qbanktool', $quiz_qbanktool);
@@ -227,80 +228,16 @@ if (optional_param('add', false, PARAM_BOOL) && confirm_sesskey()) {
 }
 
 $qcobject = new question_category_object($pagevars['cpage'], $thispageurl,
-        $contexts->having_one_edit_tab_cap('categories'), $defaultcategoryid,
+        $contexts->having_one_edit_tab_cap('categories'), $defaultcategoryobj->id,
         $defaultcategory, null, $contexts->having_cap('moodle/question:add'));
 
-$newrandomcategory = false;
-$newquestioninfo = quiz_process_randomquestion_formdata($qcobject);
-if ($newquestioninfo && $newquestioninfo != 'cancelled') {
-    $newrandomcategory = $newquestioninfo->newrandomcategory;
-    if (!$newrandomcategory) {
-        print_error('cannotcreatecategory');
-    } else {
-        add_to_log($quiz->course, 'quiz', 'addcategory',
-                "view.php?id=$cm->id", $newrandomcategory, $cm->id);
-    }
-}
-
-if ((optional_param('addrandom', false, PARAM_BOOL) || $newrandomcategory) && confirm_sesskey()) {
-
-    /// Add random questions to the quiz
+if ((optional_param('addrandom', false, PARAM_BOOL)) && confirm_sesskey()) {
+    // Add random questions to the quiz
     $recurse = optional_param('recurse', 0, PARAM_BOOL);
     $addonpage = optional_param('addonpage', 0, PARAM_INT);
-    if ($newrandomcategory) {
-        $categoryid = $newrandomcategory;
-        $randomcount = optional_param('randomcount', 1, PARAM_INT);
-    } else {
-        $categoryid = required_param('categoryid', PARAM_INT);
-        $randomcount = required_param('randomcount', PARAM_INT);
-    }
-    // load category
-    $category = $DB->get_record('question_categories', array('id' => $categoryid));
-    if (!$category) {
-        print_error('invalidcategoryid', 'error');
-    }
-    $catcontext = get_context_instance_by_id($category->contextid);
-    require_capability('moodle/question:useall', $catcontext);
-    $category->name = $category->name;
-    // Find existing random questions in this category that are
-    // not used by any quiz.
-    if ($existingquestions = $DB->get_records_sql(
-            "SELECT q.id,q.qtype FROM {question} q
-            WHERE qtype = '" . RANDOM . "'
-                AND category = ?
-                AND " . $DB->sql_compare_text('questiontext') . " = ?
-                AND NOT EXISTS (SELECT * FROM {quiz_question_instances} WHERE question = q.id)
-            ORDER BY id", array($category->id, $recurse))) {
-        // Take as many of these as needed.
-        while (($existingquestion = array_shift($existingquestions)) && $randomcount > 0) {
-            quiz_add_quiz_question($existingquestion->id, $quiz, $addonpage);
-            $randomcount--;
-        }
-    }
-
-    // If more are needed, create them.
-    if ($randomcount > 0) {
-        $form->questiontext = $recurse; // we use the questiontext field
-                // to store the info on whether to include
-                // questions in subcategories
-        $form->questiontextformat = 0;
-        $form->image = '';
-        $form->defaultgrade = 1;
-        $form->hidden = 1;
-        for ($i = 0; $i < $randomcount; $i++) {
-            $form->category = $category->id . ',' . $category->contextid;
-            $form->stamp = make_unique_id_code(); // Set the unique
-                    //code (not to be changed)
-            $question = new stdClass;
-            $question->qtype = RANDOM;
-            $question = $QTYPES[RANDOM]->save_question($question, $form,
-                    $course);
-            if(!isset($question->id)) {
-                print_error('cannotinsertrandomquestion', 'quiz');
-            }
-            quiz_add_quiz_question($question->id, $quiz, $addonpage);
-        }
-    }
+    $categoryid = required_param('categoryid', PARAM_INT);
+    $randomcount = required_param('randomcount', PARAM_INT);
+    quiz_add_random_questions($quiz, $addonpage, $categoryid, $randomcount, $recurse);
 
     quiz_update_sumgrades($quiz);
     quiz_delete_previews($quiz);
@@ -546,7 +483,7 @@ if (!empty($notifystrings)) {
 }
 
 if ($quiz_reordertool) {
-    $perpage= array();
+    $perpage = array();
     $perpage[0] = get_string('allinone', 'quiz');
     for ($i = 1; $i <= 50; ++$i) {
         $perpage[$i] = $i;
@@ -585,7 +522,12 @@ echo '</div>';
 echo '</div>';
 
 if (!$quiz_reordertool) {
-    // display category adding UI
+    $randomform = new quiz_add_random_form(new moodle_url('/mod/quiz/addrandom.php'), $contexts);
+    $randomform->set_data(array(
+        'category' => $pagevars['cat'],
+        'returnurl' => str_replace($CFG->wwwroot, '', $thispageurl->out(false)),
+        'cmid' => $cm->id,
+    ));
     ?>
 <div id="randomquestiondialog">
 <div class="hd"><?php print_string('addrandomquestiontoquiz', 'quiz', $quiz->name); ?>
@@ -593,7 +535,7 @@ if (!$quiz_reordertool) {
 </span>
 </div>
 <div class="bd"><?php
-$qcobject->display_randomquestion_user_interface();
+$randomform->display();
 ?></div>
 </div>
     <?php
index 66e8d5d..925a679 100644 (file)
@@ -82,13 +82,13 @@ function quiz_delete_empty_page($layout, $index) {
  * Adds a question to a quiz by updating $quiz as well as the
  * quiz and quiz_question_instances tables. It also adds a page break
  * if required.
- * @return boolean         false if the question was already in the quiz
- * @param int $id          The id of the question to be added
- * @param object $quiz  The extended quiz object as used by edit.php
- *                         This is updated by this function
- * @param int $page  Which page in quiz to add the question on; if 0 (default), add at the end
+ * @param int $id The id of the question to be added
+ * @param object $quiz The extended quiz object as used by edit.php
+ *      This is updated by this function
+ * @param int $page Which page in quiz to add the question on. If 0 (default), add at the end
+ * @return boolean false if the question was already in the quiz
  */
-function quiz_add_quiz_question($id, &$quiz, $page = 0) {
+function quiz_add_quiz_question($id, $quiz, $page = 0) {
     global $DB;
     $questions = explode(',', quiz_clean_layout($quiz->questions));
     if (in_array($id, $questions)) {
@@ -148,6 +148,54 @@ function quiz_add_quiz_question($id, &$quiz, $page = 0) {
     return true;
 }
 
+function quiz_add_random_questions($quiz, $addonpage, $categoryid, $number, $includesubcategories) {
+    global $DB, $QTYPES;
+
+    $category = $DB->get_record('question_categories', array('id' => $categoryid));
+    if (!$category) {
+        print_error('invalidcategoryid', 'error');
+    }
+
+    $catcontext = get_context_instance_by_id($category->contextid);
+    require_capability('moodle/question:useall', $catcontext);
+
+    // Find existing random questions in this category that are
+    // not used by any quiz.
+    if ($existingquestions = $DB->get_records_sql(
+            "SELECT q.id,q.qtype FROM {question} q
+            WHERE qtype = '" . RANDOM . "'
+                AND category = ?
+                AND " . $DB->sql_compare_text('questiontext') . " = ?
+                AND NOT EXISTS (SELECT * FROM {quiz_question_instances} WHERE question = q.id)
+            ORDER BY id", array($category->id, $includesubcategories))) {
+        // Take as many of these as needed.
+        while (($existingquestion = array_shift($existingquestions)) && $number > 0) {
+            quiz_add_quiz_question($existingquestion->id, $quiz, $addonpage);
+            $number -= 1;
+        }
+    }
+
+    if ($number <= 0) {
+        return;
+    }
+
+    // More random questions are needed, create them.
+    $form->questiontext = array('text' => $includesubcategories, 'format' => 0);
+    $form->defaultgrade = 1;
+    $form->hidden = 1;
+    for ($i = 0; $i < $number; $i += 1) {
+        $form->category = $category->id . ',' . $category->contextid;
+        $form->stamp = make_unique_id_code(); // Set the unique code (not to be changed)
+        $question = new stdClass;
+        $question->qtype = RANDOM;
+        $question = $QTYPES[RANDOM]->save_question($question, $form);
+        if (!isset($question->id)) {
+            print_error('cannotinsertrandomquestion', 'quiz');
+        }
+        quiz_add_quiz_question($question->id, $quiz, $addonpage);
+    }
+}
+
 /**
  * Add a page break after at particular position$.
  * @param string $layout the existinng layout, $quiz->questions.
@@ -551,8 +599,6 @@ function quiz_print_question_list($quiz, $pageurl, $allowdelete = true,
                              '" tabindex="' . ($lastindex + $qno) .
                              '" />';
         ?>
-<!--         <input type="submit" class="pointssubmitbutton" value="<?php
-        echo $strsave; ?>" /> -->
 </div>
 <?php
                 }
@@ -640,7 +686,7 @@ function quiz_print_pagecontrols($quiz, $pageurl, $page, $hasattempts) {
     $contexts = new question_edit_contexts($thiscontext);
 
     // Get the default category.
-    $defaultcategory = question_make_default_categories($contexts->all());
+    list($defaultcategoryid) = explode(',', $pageurl->param('cat'));
 
     // Create the url the question page will return to
     $returnurladdtoquiz = new moodle_url($pageurl, array('addonpage' => $page));
@@ -649,7 +695,7 @@ function quiz_print_pagecontrols($quiz, $pageurl, $page, $hasattempts) {
     $returnurladdtoquiz = str_replace($CFG->wwwroot, '', $returnurladdtoquiz->out(false));
     $newquestionparams = array('returnurl' => $returnurladdtoquiz,
             'cmid' => $quiz->cmid, 'appendqnumstring' => 'addquestion');
-    create_new_question_button($defaultcategory->id, $newquestionparams, get_string('addaquestion', 'quiz'),
+    create_new_question_button($defaultcategoryid, $newquestionparams, get_string('addaquestion', 'quiz'),
             get_string('createquestionandadd', 'quiz'), $hasattempts);
 
     if ($hasattempts) {
@@ -661,10 +707,11 @@ function quiz_print_pagecontrols($quiz, $pageurl, $page, $hasattempts) {
     <div class="singlebutton">
         <form class="randomquestionform" action="<?php echo $CFG->wwwroot; ?>/mod/quiz/addrandom.php" method="get">
             <div>
-                <input type="hidden" class="addonpage_formelement" name="addonpage_form" value="<?php echo $page; ?>" />
+                <input type="hidden" class="addonpage_formelement" name="addonpage" value="<?php echo $page; ?>" />
                 <input type="hidden" name="cmid" value="<?php echo $quiz->cmid; ?>" />
                 <input type="hidden" name="courseid" value="<?php echo $quiz->course; ?>" />
-                <input type="hidden" name="returnurl" value="<?php echo s($pageurl->out(false)); ?>" />
+                <input type="hidden" name="category" value="<?php echo $pageurl->param('cat'); ?>" />
+                <input type="hidden" name="returnurl" value="<?php echo s(str_replace($CFG->wwwroot, '', $pageurl->out(false))); ?>" />
                 <input type="submit" id="addrandomdialoglaunch_<?php echo $randombuttoncount; ?>" value="<?php echo get_string('addarandomquestion', 'quiz'); ?>" <?php echo " $disabled"; ?> />
             </div>
         </form>
@@ -673,44 +720,6 @@ function quiz_print_pagecontrols($quiz, $pageurl, $page, $hasattempts) {
     <?php
     echo "\n</div>";
 }
-/**
- * Process submitted form data to create a new category for a random question
- * This is used by edit.php and addrandom.php
- * cmid
- *
- * @param object $qcobject
- * @return object an object with properties newrandomcategory and addonpage if operation successful.
- *      if operation failed, returns false.
- */
-function quiz_process_randomquestion_formdata(&$qcobject) {
-    global $CFG, $DB;
-    $newrandomcategory = 0;
-    $addonpage = 0;
-    $newquestioninfo = false;
-    if ($qcobject->catform_rand->is_cancelled()) {
-        return 'cancelled';
-    } else if ($catformdata = $qcobject->catform_rand->get_data()) {
-        $newquestioninfo = new stdClass;
-        $addonpage = $catformdata->addonpage;
-        $newquestioninfo->addonpage = $catformdata->addonpage;
-        if (!$catformdata->id) {//new category
-            $newrandomcategory = $qcobject->add_category($catformdata->parent,
-                    $catformdata->name, $catformdata->info, true);
-            if (!is_null($newrandomcategory)) {
-                $newquestioninfo->newrandomcategory = $newrandomcategory;
-                if (! $newcategory = $DB->get_record('question_categories',
-                        array('id' => $newrandomcategory))) {
-                    $newquestioninfo->newrandomcategory = false;
-                }
-            } else {
-                $newquestioninfo->newrandomcategory = false;
-            }
-        } else {
-            $newquestioninfo->newrandomcategory = false;
-        }
-    }
-    return $newquestioninfo;
-}
 
 /**
  * Print a given single question in quiz for the edit tab of edit.php.
index d9d6814..783871d 100644 (file)
@@ -215,7 +215,7 @@ $string['countdown'] = 'Countdown';
 $string['countdownfinished'] = 'The quiz is closing, you should submit your answers now.';
 $string['countdowntenminutes'] = 'The quiz will be closing in ten minutes.';
 $string['coursetestmanager'] = 'Course Test Manager format';
-$string['createcategoryfornewrandomquestion'] = 'Create a new question category for the new random question';
+$string['createcategoryandaddrandomquestion'] = 'Create category and add random question';
 $string['createfirst'] = 'You must create some short-answer questions first.';
 $string['createmultiple'] = 'Add several random questions to quiz';
 $string['createnewquestion'] = 'Create new question';
@@ -663,7 +663,9 @@ $string['quizwillopen'] = 'This quiz will open {$a}';
 $string['random'] = 'Random question';
 $string['randomcreate'] = 'Create Random Questions';
 $string['randomfromcategory'] = 'Random question from category:';
+$string['randomfromexistingcategory'] = 'Random question from an existing category';
 $string['randomnosubcat'] = 'Questions from this category only, not its subcategories.';
+$string['randomquestionusinganewcategory'] = 'Random question using a new category';
 $string['randomsamatch'] = 'Random Short-Answer Matching';
 $string['randomsamatchcreate'] = 'Create Random Short-Answer Matching questions';
 $string['randomsamatchintro'] = 'For each of the following questions, select the matching answer from the menu.';
@@ -672,7 +674,7 @@ $string['randomwithsubcat'] = 'Questions from this category and its subcategorie
 $string['readytosend'] = 'You are about to send your whole quiz to be graded.  Are you sure you want to continue?';
 $string['reattemptquiz'] = 'Re-attempt quiz';
 $string['recentlyaddedquestion'] = 'Recently added question!';
-$string['recurse'] = 'Display questions from sub-categories too';
+$string['recurse'] = 'Include questions from sub-categories too';
 $string['regrade'] = 'Regrade all attempts';
 $string['regradecomplete'] = 'All attempts have been regraded';
 $string['regradecount'] = '{$a->changed} out of {$a->attempt} grades were changed';
index 46842d4..195e29c 100644 (file)
@@ -10,9 +10,8 @@
 // number of categories to display on page
 define("QUESTION_PAGE_LENGTH", 25);
 
-require_once("$CFG->libdir/listlib.php");
-require_once("$CFG->dirroot/question/category_form.php");
-require_once("$CFG->dirroot/question/category_form_randomquestion.php");
+require_once($CFG->libdir . '/listlib.php');
+require_once($CFG->dirroot . '/question/category_form.php');
 require_once('move_form.php');
 
 class question_category_list extends moodle_list {
@@ -111,10 +110,6 @@ class question_category_object {
      * @var question_category_edit_form Object representing form for adding / editing categories.
      */
     var $catform;
-    /**
-     * @var question_category_edit_form_randomquestion Object representing simplified form for adding a category in order to add it into a quiz as a random question.
-     */
-    var $catform_rand;
 
     /**
      * Constructor
@@ -176,10 +171,8 @@ class question_category_object {
             list($paged, $count) = $this->editlists[$key]->list_from_records($paged, $count);
         }
         $this->catform = new question_category_edit_form($this->pageurl, compact('contexts', 'currentcat'));
-        $this->catform_rand = new question_category_edit_form_randomquestion($this->pageurl, compact('contexts', 'currentcat'));
         if (!$currentcat){
             $this->catform->set_data(array('parent'=>$defaultcategory));
-            $this->catform_rand->set_data(array('parent'=>$defaultcategory));
         }
     }
     /**
@@ -197,16 +190,6 @@ class question_category_object {
         $this->output_new_table();
         echo '<br />';
 
-    }
-    /**
-     * Displays the user interface
-     *
-     */
-    function display_randomquestion_user_interface($addonpage=0) {
-        $this->catform_rand->set_data(array('addonpage'=>$addonpage));
-        /// Interface for adding a new category:
-        $this->output_new_randomquestion_table();
-
     }
 
     /**
@@ -216,14 +199,6 @@ class question_category_object {
         $this->catform->display();
     }
 
-    /**
-     * Outputs a table to allow entry of a new category
-     */
-    function output_new_randomquestion_table() {
-        $this->catform_rand->display();
-    }
-
-
     /**
      * Outputs a list to allow editing/rearranging of existing categories
      *
@@ -365,7 +340,7 @@ class question_category_object {
     /**
      * Creates a new category with given params
      */
-    public function add_category($newparent, $newcategory, $newinfo, $return=false) {
+    public function add_category($newparent, $newcategory, $newinfo, $return = false) {
         global $DB;
         if (empty($newcategory)) {
             print_error('categorynamecantbeblank', 'quiz');
diff --git a/question/category_form_randomquestion.php b/question/category_form_randomquestion.php
deleted file mode 100644 (file)
index bdf08b6..0000000
+++ /dev/null
@@ -1,38 +0,0 @@
-<?php
-
-require_once($CFG->libdir.'/formslib.php');
-
-class question_category_edit_form_randomquestion extends moodleform {
-
-    function definition() {
-        global $CFG, $DB;
-        $mform =& $this->_form;
-
-        $contexts = $this->_customdata['contexts'];
-        $currentcat = $this->_customdata['currentcat'];
-//--------------------------------------------------------------------------------
-        $mform->addElement('header', 'categoryheader', get_string('createcategoryfornewrandomquestion', 'quiz'));
-
-        $questioncategoryel = $mform->addElement('questioncategory', 'parent', get_string('parentcategory', 'question'),
-                array('contexts'=>$contexts, 'top'=>true, 'currentcat'=>$currentcat, 'nochildrenof'=>$currentcat));
-        $mform->setType('parent', PARAM_SEQUENCE);
-        $mform->addHelpButton('parent', 'parentcategory', 'question');
-
-        $mform->addElement('text','name', get_string('name'),'maxlength="254" size="50"');
-        $mform->setDefault('name', '');
-        $mform->addRule('name', get_string('categorynamecantbeblank', 'quiz'), 'required', null, 'client');
-        $mform->setType('name', PARAM_MULTILANG);
-
-        $mform->addElement('hidden', 'info', '');
-        $mform->setType('info', PARAM_MULTILANG);
-
-//--------------------------------------------------------------------------------
-        $this->add_action_buttons(true, get_string('addrandomquestion', 'quiz'));
-//--------------------------------------------------------------------------------
-        $mform->addElement('hidden', 'id', 0);
-        $mform->setType('id', PARAM_INT);
-        $mform->addElement('hidden', 'addonpage', 0, 'id="rform_qpage"');
-        $mform->setType('addonpage', PARAM_SEQUENCE);
-    }
-}
-
index efdb1f6..0041413 100644 (file)
@@ -248,7 +248,7 @@ if ($mform->is_cancelled()){
 
     } else {
         // We are acutally saving the question.
-        $question = $QTYPES[$question->qtype]->save_question($question, $fromform, $COURSE, $wizardnow, true);
+        $question = $QTYPES[$question->qtype]->save_question($question, $fromform);
         if (!empty($CFG->usetags) && isset($fromform->tags)) {
             // A wizardpage from multipe pages questiontype like calculated may not
             // allow editing the question tags, hence the isset($fromform->tags) test.
index 6b04d83..eed7933 100644 (file)
@@ -667,10 +667,10 @@ class question_calculated_qtype extends default_questiontype {
      * @param int $course
      * @param PARAM_ALPHA $wizardnow should be added as we are coming from question2.php
      */
-    function save_question($question, $form, $course) {
+    function save_question($question, $form) {
         global $DB;
         if ($this->wizard_pages_number() == 1 ){
-                $question = parent::save_question($question, $form, $course);
+                $question = parent::save_question($question, $form);
             return $question ;
         }
 
@@ -689,7 +689,7 @@ class question_calculated_qtype extends default_questiontype {
         case '' :
         case 'question': // coming from the first page, creating the second
             if (empty($form->id)) { // for a new question $form->id is empty
-                $question = parent::save_question($question, $form, $course);
+                $question = parent::save_question($question, $form);
                 //prepare the datasets using default $questionfromid
                 $this->preparedatasets($form);
                 $form->id = $question->id;
@@ -699,7 +699,7 @@ class question_calculated_qtype extends default_questiontype {
                 }
             } else if (!empty($form->makecopy)){
                 $questionfromid =  $form->id ;
-                $question = parent::save_question($question, $form, $course);
+                $question = parent::save_question($question, $form);
                 //prepare the datasets
                 $this->preparedatasets($form,$questionfromid);
                 $form->id = $question->id;
@@ -708,7 +708,7 @@ class question_calculated_qtype extends default_questiontype {
                     $this->addnamecategory($question);
                 }
             }  else {// editing a question
-                $question = parent::save_question($question, $form, $course);
+                $question = parent::save_question($question, $form);
                 //prepare the datasets
                 $this->preparedatasets($form,$question->id);
                 $form->id = $question->id;
@@ -2087,7 +2087,7 @@ class question_calculated_qtype extends default_questiontype {
             $course = $DB->get_record('course', array('id'=> $courseid));
         }
 
-        $new_question = $this->save_question($question, $form, $course);
+        $new_question = $this->save_question($question, $form);
 
         $dataset_form = new stdClass();
         $dataset_form->nextpageparam["forceregeneration"]= 1;
index 3a2be46..ff66469 100644 (file)
@@ -526,7 +526,7 @@ class question_calculatedmulti_qtype extends question_calculated_qtype {
             $course = $DB->get_record('course', array('id'=> $courseid));
         }
 
-        $new_question = $this->save_question($question, $form, $course);
+        $new_question = $this->save_question($question, $form);
 
         $dataset_form = new stdClass();
         $dataset_form->nextpageparam["forceregeneration"]= 1;
index 419cdf4..f205a3b 100644 (file)
@@ -321,7 +321,7 @@ class question_calculatedsimple_qtype extends question_calculated_qtype {
             $course = $DB->get_record('course', array('id'=> $courseid));
         }
 
-        $new_question = $this->save_question($question, $form, $course);
+        $new_question = $this->save_question($question, $form);
 
         $dataset_form = new stdClass();
         $dataset_form->nextpageparam["forceregeneration"]= 1;
index ecb3b38..a0ae412 100644 (file)
@@ -45,11 +45,11 @@ class description_qtype extends default_questiontype {
         return false;
     }
 
-    function save_question($question, $form, $course) {
+    function save_question($question, $form) {
         // Make very sure that descriptions can'e be created with a grade of
         // anything other than 0.
         $form->defaultgrade = 0;
-        return parent::save_question($question, $form, $course);
+        return parent::save_question($question, $form);
     }
 
     function get_question_options(&$question) {
index 1a29b9e..102b26f 100644 (file)
@@ -144,7 +144,7 @@ class question_essay_qtype extends default_questiontype {
             $course = $DB->get_record('course', array('id' => $courseid));
         }
 
-        return $this->save_question($question, $form, $course);
+        return $this->save_question($question, $form);
     }
 
     function move_files($questionid, $oldcontextid, $newcontextid) {
index 96bb660..0284021 100644 (file)
@@ -493,7 +493,7 @@ class question_match_qtype extends default_questiontype {
             $course = $DB->get_record('course', array('id' => $courseid));
         }
 
-        return $this->save_question($question, $form, $course);
+        return $this->save_question($question, $form);
     }
 
     function move_files($questionid, $oldcontextid, $newcontextid) {
index 4519cba..1c713f2 100644 (file)
@@ -130,8 +130,7 @@ class embedded_cloze_qtype extends default_questiontype {
             $wrapped->parent = $question->id;
             $previousid = $wrapped->id ;
             $wrapped->category = $question->category . ',1'; // save_question strips this extra bit off again.
-            $wrapped = $QTYPES[$wrapped->qtype]->save_question($wrapped,
-                    clone($wrapped), $question->course);
+            $wrapped = $QTYPES[$wrapped->qtype]->save_question($wrapped, clone($wrapped));
             $sequence[] = $wrapped->id;
             if ($previousid != 0 && $previousid != $wrapped->id ) {
                 // for some reasons a new question has been created
@@ -160,7 +159,7 @@ class embedded_cloze_qtype extends default_questiontype {
         }
     }
 
-    function save_question($authorizedquestion, $form, $course) {
+    function save_question($authorizedquestion, $form) {
         $question = qtype_multianswer_extract_question($form->questiontext);
         if (isset($authorizedquestion->id)) {
             $question->id = $authorizedquestion->id;
@@ -176,7 +175,7 @@ class embedded_cloze_qtype extends default_questiontype {
         $form->questiontextformat = 0;
         $form->options = clone($question->options);
         unset($question->options);
-        return parent::save_question($question, $form, $course);
+        return parent::save_question($question, $form);
     }
 
     function create_session_and_responses(&$question, &$state, $cmoptions, $attempt) {
@@ -694,7 +693,7 @@ Good luck!
             $course = $DB->get_record('course', array('id' => $courseid));
         }
 
-        return $this->save_question($question, $form, $course);
+        return $this->save_question($question, $form);
     }
 
 }
index ed133dc..02f8087 100644 (file)
@@ -488,7 +488,7 @@ class question_multichoice_qtype extends default_questiontype {
             $course = $DB->get_record('course', array('id' => $courseid));
         }
 
-        return $this->save_question($question, $form, $course);
+        return $this->save_question($question, $form);
     }
 
     function move_files($questionid, $oldcontextid, $newcontextid) {
index 0828eb6..c22b15e 100644 (file)
@@ -1318,7 +1318,7 @@ class question_numerical_qtype extends question_shortanswer_qtype {
             $course = $DB->get_record('course', array('id' => $courseid));
         }
 
-        return $this->save_question($question, $form, $course);
+        return $this->save_question($question, $form);
     }
 
     function move_files($questionid, $oldcontextid, $newcontextid) {
index 76986b5..5aaf4d3 100644 (file)
@@ -305,7 +305,7 @@ class default_questiontype {
     *       redisplayed with validation errors, from validation_errors field, which
     *       is itself an object, shown next to the form fields. (I don't think this is accurate any more.)
     */
-    function save_question($question, $form, $course) {
+    function save_question($question, $form) {
         global $USER, $DB, $OUTPUT;
 
         list($question->category) = explode(',', $form->category);
@@ -364,10 +364,10 @@ class default_questiontype {
         $question->modifiedby = $USER->id;
         $question->timemodified = time();
 
-        if (!empty($question->questiontext)) {
+        if (!empty($question->questiontext) && !empty($form->questiontext['itemid'])) {
             $question->questiontext = file_save_draft_area_files($form->questiontext['itemid'], $context->id, 'question', 'questiontext', (int)$question->id, $this->fileoptions, $question->questiontext);
         }
-        if (!empty($question->generalfeedback)) {
+        if (!empty($question->generalfeedback) && !empty($form->generalfeedback['itemid'])) {
             $question->generalfeedback = file_save_draft_area_files($form->generalfeedback['itemid'], $context->id, 'question', 'generalfeedback', (int)$question->id, $this->fileoptions, $question->generalfeedback);
         }
         $DB->update_record('question', $question);
@@ -392,10 +392,7 @@ class default_questiontype {
         }
 
         if (!empty($result->noticeyesno)) {
-            echo $OUTPUT->confirm($result->noticeyesno, "question.php?id=$question->id&courseid={$course->id}",
-                    "edit.php?courseid={$course->id}");
-            echo $OUTPUT->footer();
-            exit;
+            throw new coding_exception('$result->noticeyesno no longer supported in save_question.');
         }
 
         // Give the question a unique version stamp determined by question_hash()
index 0572d14..a4b419f 100644 (file)
@@ -34,7 +34,7 @@ class question_edit_random_form extends question_edit_form {
         $mform->addElement('questioncategory', 'category', get_string('category', 'quiz'),
                 array('contexts' => $this->contexts->having_cap('moodle/question:useall')));
 
-        $mform->addElement('advcheckbox', 'questiontext', get_string("recurse", "quiz"), null, null, array(0, 1));
+        $mform->addElement('advcheckbox', 'questiontext[text]', get_string('recurse', 'quiz'), null, null, array(0, 1));
 
         $mform->addElement('hidden', 'name');
         $mform->setType('name', PARAM_ALPHA);
@@ -73,13 +73,18 @@ class question_edit_random_form extends question_edit_form {
         $mform->setDefault('returnurl', 0);
 
         $buttonarray = array();
-        $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
-
-        $buttonarray[] = &$mform->createElement('cancel');
+        $buttonarray[] = $mform->createElement('submit', 'submitbutton', get_string('savechanges'));
+        $buttonarray[] = $mform->createElement('cancel');
         $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
         $mform->closeHeaderBefore('buttonar');
     }
 
+    function set_data($question) {
+        $question->questiontext = array('text' => $question->questiontext);
+        // We don't want the complex stuff in the base class to run.
+        moodleform::set_data($question);
+    }
+
     function validation($fromform, $files) {
         //validation of category
         //is not relevant for this question type
index 84bcba7..6d99083 100644 (file)
@@ -117,11 +117,11 @@ class random_qtype extends default_questiontype {
         return get_string($string, 'qtype_random', $category->name);
     }
 
-    function save_question($question, $form, $course) {
+    function save_question($question, $form) {
         $form->name = '';
         // Name is not a required field for random questions, but parent::save_question
         // Assumes that it is.
-        return parent::save_question($question, $form, $course);
+        return parent::save_question($question, $form);
     }
 
     function save_question_options($question) {
index 2ef7e13..1388f5e 100644 (file)
@@ -372,7 +372,7 @@ class question_shortanswer_qtype extends default_questiontype {
             $course = $DB->get_record('course', array('id' => $courseid));
         }
 
-        return $this->save_question($question, $form, $course);
+        return $this->save_question($question, $form);
     }
 
     function check_file_access($question, $state, $options, $contextid, $component,
index d9620e3..1dc2cc1 100644 (file)
@@ -306,7 +306,7 @@ class question_truefalse_qtype extends default_questiontype {
             $course = $DB->get_record('course', array('id' => $courseid));
         }
 
-        return $this->save_question($question, $form, $course);
+        return $this->save_question($question, $form);
     }
 }
 //// END OF CLASS ////