MDL-51569 mod_choice: Validate the submitted optionid
authorDamyon Wiese <damyon@moodle.com>
Thu, 5 Nov 2015 08:26:46 +0000 (16:26 +0800)
committerDan Poltawski <dan@moodle.com>
Thu, 5 Nov 2015 10:48:40 +0000 (10:48 +0000)
Make sure any submitted choice options actually belong to the current choice
module.

mod/choice/lib.php
mod/choice/tests/lib_test.php

index 7a62bc3..79f83a3 100644 (file)
@@ -269,6 +269,12 @@ function choice_user_submit_response($formanswer, $choice, $userid, $course, $cm
         $formanswers = array($formanswer);
     }
 
         $formanswers = array($formanswer);
     }
 
+    $options = $DB->get_records('choice_options', array('choiceid' => $choice->id), '', 'id');
+    foreach ($formanswers as $key => $val) {
+        if (!isset($options[$val])) {
+            print_error('cannotsubmit', 'choice', $continueurl);
+        }
+    }
     // Start lock to prevent synchronous access to the same data
     // before it's updated, if using limits.
     if ($choice->limitanswers) {
     // Start lock to prevent synchronous access to the same data
     // before it's updated, if using limits.
     if ($choice->limitanswers) {
index 341886e..faaa434 100644 (file)
@@ -131,6 +131,28 @@ class mod_choice_lib_testcase extends externallib_advanced_testcase {
 
     }
 
 
     }
 
+    public function test_choice_user_submit_response_validation() {
+        global $USER;
+
+        $this->resetAfterTest();
+
+        $this->setAdminUser();
+        // Setup test data.
+        $course = $this->getDataGenerator()->create_course();
+        $choice1 = $this->getDataGenerator()->create_module('choice', array('course' => $course->id));
+        $choice2 = $this->getDataGenerator()->create_module('choice', array('course' => $course->id));
+        $cm = get_coursemodule_from_instance('choice', $choice1->id);
+
+        $choicewithoptions1 = choice_get_choice($choice1->id);
+        $choicewithoptions2 = choice_get_choice($choice2->id);
+        $optionids1 = array_keys($choicewithoptions1->option);
+        $optionids2 = array_keys($choicewithoptions2->option);
+
+        // Make sure we cannot submit options from a different choice instance.
+        $this->setExpectedException('moodle_exception');
+        choice_user_submit_response($optionids2[0], $choice1, $USER->id, $course, $cm);
+    }
+
     /**
      * Test choice_get_my_response
      * @return void
     /**
      * Test choice_get_my_response
      * @return void