MDL-50546 mod_quiz: New WS mod_quiz_get_quizzes_by_courses

This commit is contained in:
Juan Leyva
2016-02-26 15:42:11 +01:00
parent 03b8b55f10
commit 51e27aac2b
5 changed files with 525 additions and 1 deletions
+1
View File
@@ -1299,6 +1299,7 @@ $services = array(
'mod_lti_view_lti',
'mod_imscp_view_imscp',
'mod_imscp_get_imscps_by_courses',
'mod_quiz_get_quizzes_by_courses',
'mod_glossary_get_glossaries_by_courses',
'mod_wiki_get_wikis_by_courses',
'mod_wiki_view_wiki',
+275
View File
@@ -0,0 +1,275 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Quiz external API
*
* @package mod_quiz
* @category external
* @copyright 2016 Juan Leyva <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 3.1
*/
defined('MOODLE_INTERNAL') || die;
require_once($CFG->libdir . '/externallib.php');
require_once($CFG->dirroot . '/mod/quiz/locallib.php');
/**
* Quiz external functions
*
* @package mod_quiz
* @category external
* @copyright 2016 Juan Leyva <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 3.1
*/
class mod_quiz_external extends external_api {
/**
* Describes the parameters for get_quizzes_by_courses.
*
* @return external_external_function_parameters
* @since Moodle 3.1
*/
public static function get_quizzes_by_courses_parameters() {
return new external_function_parameters (
array(
'courseids' => new external_multiple_structure(
new external_value(PARAM_INT, 'course id'), 'Array of course ids', VALUE_DEFAULT, array()
),
)
);
}
/**
* Returns a list of quizzes in a provided list of courses,
* if no list is provided all quizzes that the user can view will be returned.
*
* @param array $courseids Array of course ids
* @return array of quizzes details
* @since Moodle 3.1
*/
public static function get_quizzes_by_courses($courseids = array()) {
global $USER;
$warnings = array();
$returnedquizzes = array();
$params = array(
'courseids' => $courseids,
);
$params = self::validate_parameters(self::get_quizzes_by_courses_parameters(), $params);
$mycourses = array();
if (empty($params['courseids'])) {
$mycourses = enrol_get_my_courses();
$params['courseids'] = array_keys($mycourses);
}
// Ensure there are courseids to loop through.
if (!empty($params['courseids'])) {
list($courses, $warnings) = external_util::validate_courses($params['courseids'], $mycourses);
// Get the quizzes in this course, this function checks users visibility permissions.
// We can avoid then additional validate_context calls.
$quizzes = get_all_instances_in_courses("quiz", $courses);
foreach ($quizzes as $quiz) {
$context = context_module::instance($quiz->coursemodule);
// Update quiz with override information.
$quiz = quiz_update_effective_access($quiz, $USER->id);
// Entry to return.
$quizdetails = array();
// First, we return information that any user can see in the web interface.
$quizdetails['id'] = $quiz->id;
$quizdetails['coursemodule'] = $quiz->coursemodule;
$quizdetails['course'] = $quiz->course;
$quizdetails['name'] = external_format_string($quiz->name, $context->id);
if (has_capability('mod/quiz:view', $context)) {
// Format intro.
list($quizdetails['intro'], $quizdetails['introformat']) = external_format_text($quiz->intro,
$quiz->introformat, $context->id, 'mod_quiz', 'intro', null);
$viewablefields = array('timeopen', 'timeclose', 'grademethod', 'section', 'visible', 'groupmode',
'groupingid');
$timenow = time();
$quizobj = quiz::create($quiz->id, $USER->id);
$accessmanager = new quiz_access_manager($quizobj, $timenow, has_capability('mod/quiz:ignoretimelimits',
$context, null, false));
// Fields the user could see if have access to the quiz.
if (!$accessmanager->prevent_access()) {
// Some times this function returns just empty.
$hasfeedback = quiz_has_feedback($quiz);
$quizdetails['hasfeedback'] = (!empty($hasfeedback)) ? 1 : 0;
$quizdetails['hasquestions'] = (int) $quizobj->has_questions();
$quizdetails['autosaveperiod'] = get_config('quiz', 'autosaveperiod');
$additionalfields = array('timelimit', 'attempts', 'attemptonlast', 'grademethod', 'decimalpoints',
'questiondecimalpoints', 'reviewattempt', 'reviewcorrectness', 'reviewmarks',
'reviewspecificfeedback', 'reviewgeneralfeedback', 'reviewrightanswer',
'reviewoverallfeedback', 'questionsperpage', 'navmethod', 'sumgrades', 'grade',
'browsersecurity', 'delay1', 'delay2', 'showuserpicture', 'showblocks',
'completionattemptsexhausted', 'completionpass', 'overduehandling',
'graceperiod', 'preferredbehaviour', 'canredoquestions');
$viewablefields = array_merge($viewablefields, $additionalfields);
}
// Fields only for managers.
if (has_capability('moodle/course:manageactivities', $context)) {
$additionalfields = array('shuffleanswers', 'timecreated', 'timemodified', 'password', 'subnet');
$viewablefields = array_merge($viewablefields, $additionalfields);
}
foreach ($viewablefields as $field) {
$quizdetails[$field] = $quiz->{$field};
}
}
$returnedquizzes[] = $quizdetails;
}
}
$result = array();
$result['quizzes'] = $returnedquizzes;
$result['warnings'] = $warnings;
return $result;
}
/**
* Describes the get_quizzes_by_courses return value.
*
* @return external_single_structure
* @since Moodle 3.1
*/
public static function get_quizzes_by_courses_returns() {
return new external_single_structure(
array(
'quizzes' => new external_multiple_structure(
new external_single_structure(
array(
'id' => new external_value(PARAM_INT, 'Standard Moodle primary key.'),
'course' => new external_value(PARAM_INT, 'Foreign key reference to the course this quiz is part of.'),
'coursemodule' => new external_value(PARAM_INT, 'Course module id.'),
'name' => new external_value(PARAM_RAW, 'Quiz name.'),
'intro' => new external_value(PARAM_RAW, 'Quiz introduction text.', VALUE_OPTIONAL),
'introformat' => new external_format_value('intro', VALUE_OPTIONAL),
'timeopen' => new external_value(PARAM_INT, 'The time when this quiz opens. (0 = no restriction.)',
VALUE_OPTIONAL),
'timeclose' => new external_value(PARAM_INT, 'The time when this quiz closes. (0 = no restriction.)',
VALUE_OPTIONAL),
'timelimit' => new external_value(PARAM_INT, 'The time limit for quiz attempts, in seconds.',
VALUE_OPTIONAL),
'overduehandling' => new external_value(PARAM_ALPHA, 'The method used to handle overdue attempts.
\'autosubmit\', \'graceperiod\' or \'autoabandon\'.',
VALUE_OPTIONAL),
'graceperiod' => new external_value(PARAM_INT, 'The amount of time (in seconds) after the time limit
runs out during which attempts can still be submitted,
if overduehandling is set to allow it.', VALUE_OPTIONAL),
'preferredbehaviour' => new external_value(PARAM_ALPHANUMEXT, 'The behaviour to ask questions to use.',
VALUE_OPTIONAL),
'canredoquestions' => new external_value(PARAM_INT, 'Allows students to redo any completed question
within a quiz attempt.', VALUE_OPTIONAL),
'attempts' => new external_value(PARAM_INT, 'The maximum number of attempts a student is allowed.',
VALUE_OPTIONAL),
'attemptonlast' => new external_value(PARAM_INT, 'Whether subsequent attempts start from teh answer
to the previous attempt (1) or start blank (0).',
VALUE_OPTIONAL),
'grademethod' => new external_value(PARAM_INT, 'One of the values QUIZ_GRADEHIGHEST, QUIZ_GRADEAVERAGE,
QUIZ_ATTEMPTFIRST or QUIZ_ATTEMPTLAST.', VALUE_OPTIONAL),
'decimalpoints' => new external_value(PARAM_INT, 'Number of decimal points to use when displaying
grades.', VALUE_OPTIONAL),
'questiondecimalpoints' => new external_value(PARAM_INT, 'Number of decimal points to use when
displaying question grades.
(-1 means use decimalpoints.)', VALUE_OPTIONAL),
'reviewattempt' => new external_value(PARAM_INT, 'Whether users are allowed to review their quiz
attempts at various times. This is a bit field, decoded by the
mod_quiz_display_options class. It is formed by ORing together
the constants defined there.', VALUE_OPTIONAL),
'reviewcorrectness' => new external_value(PARAM_INT, 'Whether users are allowed to review their quiz
attempts at various times.
A bit field, like reviewattempt.', VALUE_OPTIONAL),
'reviewmarks' => new external_value(PARAM_INT, 'Whether users are allowed to review their quiz attempts
at various times. A bit field, like reviewattempt.',
VALUE_OPTIONAL),
'reviewspecificfeedback' => new external_value(PARAM_INT, 'Whether users are allowed to review their
quiz attempts at various times. A bit field, like
reviewattempt.', VALUE_OPTIONAL),
'reviewgeneralfeedback' => new external_value(PARAM_INT, 'Whether users are allowed to review their
quiz attempts at various times. A bit field, like
reviewattempt.', VALUE_OPTIONAL),
'reviewrightanswer' => new external_value(PARAM_INT, 'Whether users are allowed to review their quiz
attempts at various times. A bit field, like
reviewattempt.', VALUE_OPTIONAL),
'reviewoverallfeedback' => new external_value(PARAM_INT, 'Whether users are allowed to review their quiz
attempts at various times. A bit field, like
reviewattempt.', VALUE_OPTIONAL),
'questionsperpage' => new external_value(PARAM_INT, 'How often to insert a page break when editing
the quiz, or when shuffling the question order.',
VALUE_OPTIONAL),
'navmethod' => new external_value(PARAM_ALPHA, 'Any constraints on how the user is allowed to navigate
around the quiz. Currently recognised values are
\'free\' and \'seq\'.', VALUE_OPTIONAL),
'shuffleanswers' => new external_value(PARAM_INT, 'Whether the parts of the question should be shuffled,
in those question types that support it.', VALUE_OPTIONAL),
'sumgrades' => new external_value(PARAM_FLOAT, 'The total of all the question instance maxmarks.',
VALUE_OPTIONAL),
'grade' => new external_value(PARAM_FLOAT, 'The total that the quiz overall grade is scaled to be
out of.', VALUE_OPTIONAL),
'timecreated' => new external_value(PARAM_INT, 'The time when the quiz was added to the course.',
VALUE_OPTIONAL),
'timemodified' => new external_value(PARAM_INT, 'Last modified time.',
VALUE_OPTIONAL),
'password' => new external_value(PARAM_RAW, 'A password that the student must enter before starting or
continuing a quiz attempt.', VALUE_OPTIONAL),
'subnet' => new external_value(PARAM_RAW, 'Used to restrict the IP addresses from which this quiz can
be attempted. The format is as requried by the address_in_subnet
function.', VALUE_OPTIONAL),
'browsersecurity' => new external_value(PARAM_ALPHANUMEXT, 'Restriciton on the browser the student must
use. E.g. \'securewindow\'.', VALUE_OPTIONAL),
'delay1' => new external_value(PARAM_INT, 'Delay that must be left between the first and second attempt,
in seconds.', VALUE_OPTIONAL),
'delay2' => new external_value(PARAM_INT, 'Delay that must be left between the second and subsequent
attempt, in seconds.', VALUE_OPTIONAL),
'showuserpicture' => new external_value(PARAM_INT, 'Option to show the user\'s picture during the
attempt and on the review page.', VALUE_OPTIONAL),
'showblocks' => new external_value(PARAM_INT, 'Whether blocks should be shown on the attempt.php and
review.php pages.', VALUE_OPTIONAL),
'completionattemptsexhausted' => new external_value(PARAM_INT, 'Mark quiz complete when the student has
exhausted the maximum number of attempts',
VALUE_OPTIONAL),
'completionpass' => new external_value(PARAM_INT, 'Wheter to require passing grade', VALUE_OPTIONAL),
'autosaveperiod' => new external_value(PARAM_INT, 'Auto-save delay', VALUE_OPTIONAL),
'hasfeedback' => new external_value(PARAM_INT, 'Whether the quiz has any non-blank feedback text',
VALUE_OPTIONAL),
'hasquestions' => new external_value(PARAM_INT, 'Whether the quiz has questions', VALUE_OPTIONAL),
'section' => new external_value(PARAM_INT, 'Course section id', VALUE_OPTIONAL),
'visible' => new external_value(PARAM_INT, 'Module visibility', VALUE_OPTIONAL),
'groupmode' => new external_value(PARAM_INT, 'Group mode', VALUE_OPTIONAL),
'groupingid' => new external_value(PARAM_INT, 'Grouping id', VALUE_OPTIONAL),
)
)
),
'warnings' => new external_warnings(),
)
);
}
}
+39
View File
@@ -0,0 +1,39 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Quiz external functions and service definitions.
*
* @package mod_quiz
* @category external
* @copyright 2016 Juan Leyva <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 3.1
*/
defined('MOODLE_INTERNAL') || die;
$functions = array(
'mod_quiz_get_quizzes_by_courses' => array(
'classname' => 'mod_quiz_external',
'methodname' => 'get_quizzes_by_courses',
'description' => 'Returns a list of quizzes in a provided list of courses,
if no list is provided all quizzes that the user can view will be returned.',
'type' => 'read',
'capabilities' => 'mod/quiz:view'
),
);
+209
View File
@@ -0,0 +1,209 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Quiz module external functions tests.
*
* @package mod_quiz
* @category external
* @copyright 2016 Juan Leyva <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 3.1
*/
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->dirroot . '/webservice/tests/helpers.php');
/**
* Quiz module external functions tests
*
* @package mod_quiz
* @category external
* @copyright 2016 Juan Leyva <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 3.1
*/
class mod_quiz_external_testcase extends externallib_advanced_testcase {
/**
* Set up for every test
*/
public function setUp() {
global $DB;
$this->resetAfterTest();
$this->setAdminUser();
// Setup test data.
$this->course = $this->getDataGenerator()->create_course();
$this->quiz = $this->getDataGenerator()->create_module('quiz', array('course' => $this->course->id));
$this->context = context_module::instance($this->quiz->cmid);
$this->cm = get_coursemodule_from_instance('quiz', $this->quiz->id);
// Create users.
$this->student = self::getDataGenerator()->create_user();
$this->teacher = self::getDataGenerator()->create_user();
// Users enrolments.
$this->studentrole = $DB->get_record('role', array('shortname' => 'student'));
$this->teacherrole = $DB->get_record('role', array('shortname' => 'editingteacher'));
$this->getDataGenerator()->enrol_user($this->student->id, $this->course->id, $this->studentrole->id, 'manual');
$this->getDataGenerator()->enrol_user($this->teacher->id, $this->course->id, $this->teacherrole->id, 'manual');
}
/*
* Test get quizzes by courses
*/
public function test_mod_quiz_get_quizzes_by_courses() {
global $DB;
// Create additional course.
$course2 = self::getDataGenerator()->create_course();
// Second quiz.
$record = new stdClass();
$record->course = $course2->id;
$quiz2 = self::getDataGenerator()->create_module('quiz', $record);
// Execute real Moodle enrolment as we'll call unenrol() method on the instance later.
$enrol = enrol_get_plugin('manual');
$enrolinstances = enrol_get_instances($course2->id, true);
foreach ($enrolinstances as $courseenrolinstance) {
if ($courseenrolinstance->enrol == "manual") {
$instance2 = $courseenrolinstance;
break;
}
}
$enrol->enrol_user($instance2, $this->student->id, $this->studentrole->id);
self::setUser($this->student);
$returndescription = mod_quiz_external::get_quizzes_by_courses_returns();
// Create what we expect to be returned when querying the two courses.
// First for the student user.
$allusersfields = array('id', 'coursemodule', 'course', 'name', 'intro', 'introformat', 'timeopen', 'timeclose',
'grademethod', 'section', 'visible', 'groupmode', 'groupingid');
$userswithaccessfields = array('timelimit', 'attempts', 'attemptonlast', 'grademethod', 'decimalpoints',
'questiondecimalpoints', 'reviewattempt', 'reviewcorrectness', 'reviewmarks',
'reviewspecificfeedback', 'reviewgeneralfeedback', 'reviewrightanswer',
'reviewoverallfeedback', 'questionsperpage', 'navmethod', 'sumgrades', 'grade',
'browsersecurity', 'delay1', 'delay2', 'showuserpicture', 'showblocks',
'completionattemptsexhausted', 'completionpass', 'autosaveperiod', 'hasquestions',
'hasfeedback', 'overduehandling', 'graceperiod', 'preferredbehaviour', 'canredoquestions');
$managerfields = array('shuffleanswers', 'timecreated', 'timemodified', 'password', 'subnet');
// Add expected coursemodule and other data.
$quiz1 = $this->quiz;
$quiz1->coursemodule = $quiz1->cmid;
$quiz1->introformat = 1;
$quiz1->section = 0;
$quiz1->visible = true;
$quiz1->groupmode = 0;
$quiz1->groupingid = 0;
$quiz1->hasquestions = 0;
$quiz1->hasfeedback = 0;
$quiz1->autosaveperiod = get_config('quiz', 'autosaveperiod');
$quiz2->coursemodule = $quiz2->cmid;
$quiz2->introformat = 1;
$quiz2->section = 0;
$quiz2->visible = true;
$quiz2->groupmode = 0;
$quiz2->groupingid = 0;
$quiz2->hasquestions = 0;
$quiz2->hasfeedback = 0;
$quiz2->autosaveperiod = get_config('quiz', 'autosaveperiod');
foreach (array_merge($allusersfields, $userswithaccessfields) as $field) {
$expected1[$field] = $quiz1->{$field};
$expected2[$field] = $quiz2->{$field};
}
$expectedquizzes = array($expected2, $expected1);
// Call the external function passing course ids.
$result = mod_quiz_external::get_quizzes_by_courses(array($course2->id, $this->course->id));
$result = external_api::clean_returnvalue($returndescription, $result);
$this->assertEquals($expectedquizzes, $result['quizzes']);
$this->assertCount(0, $result['warnings']);
// Call the external function without passing course id.
$result = mod_quiz_external::get_quizzes_by_courses();
$result = external_api::clean_returnvalue($returndescription, $result);
$this->assertEquals($expectedquizzes, $result['quizzes']);
$this->assertCount(0, $result['warnings']);
// Unenrol user from second course and alter expected quizzes.
$enrol->unenrol_user($instance2, $this->student->id);
array_shift($expectedquizzes);
// Call the external function without passing course id.
$result = mod_quiz_external::get_quizzes_by_courses();
$result = external_api::clean_returnvalue($returndescription, $result);
$this->assertEquals($expectedquizzes, $result['quizzes']);
// Call for the second course we unenrolled the user from, expected warning.
$result = mod_quiz_external::get_quizzes_by_courses(array($course2->id));
$this->assertCount(1, $result['warnings']);
$this->assertEquals('1', $result['warnings'][0]['warningcode']);
$this->assertEquals($course2->id, $result['warnings'][0]['itemid']);
// Now, try as a teacher for getting all the additional fields.
self::setUser($this->teacher);
foreach ($managerfields as $field) {
$expectedquizzes[0][$field] = $quiz1->{$field};
}
$result = mod_quiz_external::get_quizzes_by_courses();
$result = external_api::clean_returnvalue($returndescription, $result);
$this->assertEquals($expectedquizzes, $result['quizzes']);
// Admin also should get all the information.
self::setAdminUser();
$result = mod_quiz_external::get_quizzes_by_courses(array($this->course->id));
$result = external_api::clean_returnvalue($returndescription, $result);
$this->assertEquals($expectedquizzes, $result['quizzes']);
// Now, prevent access.
$enrol->enrol_user($instance2, $this->student->id);
self::setUser($this->student);
$quiz2->timeclose = time() - DAYSECS;
$DB->update_record('quiz', $quiz2);
$result = mod_quiz_external::get_quizzes_by_courses();
$result = external_api::clean_returnvalue($returndescription, $result);
$this->assertCount(2, $result['quizzes']);
// We only see a limited set of fields.
$this->assertCount(4, $result['quizzes'][0]);
$this->assertEquals($quiz2->id, $result['quizzes'][0]['id']);
$this->assertEquals($quiz2->coursemodule, $result['quizzes'][0]['coursemodule']);
$this->assertEquals($quiz2->course, $result['quizzes'][0]['course']);
$this->assertEquals($quiz2->name, $result['quizzes'][0]['name']);
$this->assertEquals($quiz2->course, $result['quizzes'][0]['course']);
$this->assertFalse(isset($result['quizzes'][0]['timelimit']));
}
}
+1 -1
View File
@@ -24,7 +24,7 @@
defined('MOODLE_INTERNAL') || die();
$plugin->version = 2015111600;
$plugin->version = 2015111601;
$plugin->requires = 2015111000;
$plugin->component = 'mod_quiz';
$plugin->cron = 60;