Merge branch 'MDL-51629-master' of git://github.com/jleyva/moodle

This commit is contained in:
Andrew Nicols
2015-10-16 10:56:19 +08:00
11 changed files with 1231 additions and 108 deletions
+4
View File
@@ -1231,6 +1231,10 @@ $services = array(
'mod_scorm_get_scorm_sco_tracks',
'mod_scorm_get_scorm_attempt_count',
'mod_scorm_get_scorms_by_courses',
'mod_survey_get_surveys_by_courses',
'mod_survey_view_survey',
'mod_survey_get_questions',
'mod_survey_submit_answers',
'mod_page_view_page',
'mod_resource_view_resource',
'mod_folder_view_folder',
+408
View File
@@ -0,0 +1,408 @@
<?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/>.
/**
* Survey external API
*
* @package mod_survey
* @category external
* @copyright 2015 Juan Leyva <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 3.0
*/
defined('MOODLE_INTERNAL') || die;
require_once($CFG->libdir . '/externallib.php');
require_once($CFG->dirroot . '/mod/survey/lib.php');
/**
* Survey external functions
*
* @package mod_survey
* @category external
* @copyright 2015 Juan Leyva <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 3.0
*/
class mod_survey_external extends external_api {
/**
* Describes the parameters for get_surveys_by_courses.
*
* @return external_external_function_parameters
* @since Moodle 3.0
*/
public static function get_surveys_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 surveys in a provided list of courses,
* if no list is provided all surveys that the user can view will be returned.
*
* @param array $courseids the course ids
* @return array of surveys details
* @since Moodle 3.0
*/
public static function get_surveys_by_courses($courseids = array()) {
global $CFG, $USER, $DB;
$returnedsurveys = array();
$warnings = array();
$params = self::validate_parameters(self::get_surveys_by_courses_parameters(), array('courseids' => $courseids));
if (empty($params['courseids'])) {
$params['courseids'] = array_keys(enrol_get_my_courses());
}
// Ensure there are courseids to loop through.
if (!empty($params['courseids'])) {
list($courses, $warnings) = external_util::validate_courses($params['courseids']);
// Get the surveys in this course, this function checks users visibility permissions.
// We can avoid then additional validate_context calls.
$surveys = get_all_instances_in_courses("survey", $courses);
foreach ($surveys as $survey) {
$context = context_module::instance($survey->coursemodule);
// Entry to return.
$surveydetails = array();
// First, we return information that any user can see in the web interface.
$surveydetails['id'] = $survey->id;
$surveydetails['coursemodule'] = $survey->coursemodule;
$surveydetails['course'] = $survey->course;
$surveydetails['name'] = external_format_string($survey->name, $context->id);
if (has_capability('mod/survey:participate', $context)) {
$trimmedintro = trim($survey->intro);
if (empty($trimmedintro)) {
$tempo = $DB->get_field("survey", "intro", array("id" => $survey->template));
$survey->intro = get_string($tempo, "survey");
}
// Format intro.
list($surveydetails['intro'], $surveydetails['introformat']) =
external_format_text($survey->intro, $survey->introformat, $context->id, 'mod_survey', 'intro', null);
$surveydetails['template'] = $survey->template;
$surveydetails['days'] = $survey->days;
$surveydetails['questions'] = $survey->questions;
$surveydetails['surveydone'] = survey_already_done($survey->id, $USER->id) ? 1 : 0;
}
if (has_capability('moodle/course:manageactivities', $context)) {
$surveydetails['timecreated'] = $survey->timecreated;
$surveydetails['timemodified'] = $survey->timemodified;
$surveydetails['section'] = $survey->section;
$surveydetails['visible'] = $survey->visible;
$surveydetails['groupmode'] = $survey->groupmode;
$surveydetails['groupingid'] = $survey->groupingid;
}
$returnedsurveys[] = $surveydetails;
}
}
$result = array();
$result['surveys'] = $returnedsurveys;
$result['warnings'] = $warnings;
return $result;
}
/**
* Describes the get_surveys_by_courses return value.
*
* @return external_single_structure
* @since Moodle 3.0
*/
public static function get_surveys_by_courses_returns() {
return new external_single_structure(
array(
'surveys' => new external_multiple_structure(
new external_single_structure(
array(
'id' => new external_value(PARAM_INT, 'Survey id'),
'coursemodule' => new external_value(PARAM_INT, 'Course module id'),
'course' => new external_value(PARAM_INT, 'Course id'),
'name' => new external_value(PARAM_RAW, 'Survey name'),
'intro' => new external_value(PARAM_RAW, 'The Survey intro', VALUE_OPTIONAL),
'introformat' => new external_format_value('intro', VALUE_OPTIONAL),
'template' => new external_value(PARAM_INT, 'Survey type', VALUE_OPTIONAL),
'days' => new external_value(PARAM_INT, 'Days', VALUE_OPTIONAL),
'questions' => new external_value(PARAM_RAW, 'Question ids', VALUE_OPTIONAL),
'surveydone' => new external_value(PARAM_INT, 'Did I finish the survey?', VALUE_OPTIONAL),
'timecreated' => new external_value(PARAM_INT, 'Time of creation', VALUE_OPTIONAL),
'timemodified' => new external_value(PARAM_INT, 'Time of last modification', VALUE_OPTIONAL),
'section' => new external_value(PARAM_INT, 'Course section id', VALUE_OPTIONAL),
'visible' => new external_value(PARAM_INT, 'Visible', VALUE_OPTIONAL),
'groupmode' => new external_value(PARAM_INT, 'Group mode', VALUE_OPTIONAL),
'groupingid' => new external_value(PARAM_INT, 'Group id', VALUE_OPTIONAL),
), 'Surveys'
)
),
'warnings' => new external_warnings(),
)
);
}
/**
* Returns description of method parameters
*
* @return external_function_parameters
* @since Moodle 3.0
*/
public static function view_survey_parameters() {
return new external_function_parameters(
array(
'surveyid' => new external_value(PARAM_INT, 'survey instance id')
)
);
}
/**
* Trigger the course module viewed event and update the module completion status.
*
* @param int $surveyid the survey instance id
* @return array of warnings and status result
* @since Moodle 3.0
* @throws moodle_exception
*/
public static function view_survey($surveyid) {
global $DB, $USER;
$params = self::validate_parameters(self::view_survey_parameters(),
array(
'surveyid' => $surveyid
));
$warnings = array();
// Request and permission validation.
$survey = $DB->get_record('survey', array('id' => $params['surveyid']), '*', MUST_EXIST);
list($course, $cm) = get_course_and_cm_from_instance($survey, 'survey');
$context = context_module::instance($cm->id);
self::validate_context($context);
require_capability('mod/survey:participate', $context);
$viewed = survey_already_done($survey->id, $USER->id) ? 'graph' : 'form';
// Trigger course_module_viewed event and completion.
survey_view($survey, $course, $cm, $context, $viewed);
$result = array();
$result['status'] = true;
$result['warnings'] = $warnings;
return $result;
}
/**
* Returns description of method result value
*
* @return external_description
* @since Moodle 3.0
*/
public static function view_survey_returns() {
return new external_single_structure(
array(
'status' => new external_value(PARAM_BOOL, 'status: true if success'),
'warnings' => new external_warnings()
)
);
}
/**
* Returns description of method parameters
*
* @return external_function_parameters
* @since Moodle 3.0
*/
public static function get_questions_parameters() {
return new external_function_parameters(
array(
'surveyid' => new external_value(PARAM_INT, 'survey instance id')
)
);
}
/**
* Get the complete list of questions for the survey, including subquestions.
*
* @param int $surveyid the survey instance id
* @return array of warnings and the question list
* @since Moodle 3.0
* @throws moodle_exception
*/
public static function get_questions($surveyid) {
global $DB, $USER;
$params = self::validate_parameters(self::get_questions_parameters(),
array(
'surveyid' => $surveyid
));
$warnings = array();
// Request and permission validation.
$survey = $DB->get_record('survey', array('id' => $params['surveyid']), '*', MUST_EXIST);
list($course, $cm) = get_course_and_cm_from_instance($survey, 'survey');
$context = context_module::instance($cm->id);
self::validate_context($context);
require_capability('mod/survey:participate', $context);
$mainquestions = survey_get_questions($survey);
foreach ($mainquestions as $question) {
if ($question->type >= 0) {
// Parent is used in subquestions.
$question->parent = 0;
$questions[] = survey_translate_question($question);
// Check if the question has subquestions.
if ($question->multi) {
$subquestions = survey_get_subquestions($question);
foreach ($subquestions as $sq) {
$sq->parent = $question->id;
$questions[] = survey_translate_question($sq);
}
}
}
}
$result = array();
$result['questions'] = $questions;
$result['warnings'] = $warnings;
return $result;
}
/**
* Returns description of method result value
*
* @return external_description
* @since Moodle 3.0
*/
public static function get_questions_returns() {
return new external_single_structure(
array(
'questions' => new external_multiple_structure(
new external_single_structure(
array(
'id' => new external_value(PARAM_INT, 'Question id'),
'text' => new external_value(PARAM_RAW, 'Question text'),
'shorttext' => new external_value(PARAM_RAW, 'Question short text'),
'multi' => new external_value(PARAM_RAW, 'Subquestions ids'),
'intro' => new external_value(PARAM_RAW, 'The question intro'),
'type' => new external_value(PARAM_INT, 'Question type'),
'options' => new external_value(PARAM_RAW, 'Question options'),
'parent' => new external_value(PARAM_INT, 'Parent question (for subquestions)'),
), 'Questions'
)
),
'warnings' => new external_warnings()
)
);
}
/**
* Describes the parameters for submit_answers.
*
* @return external_function_parameters
* @since Moodle 3.0
*/
public static function submit_answers_parameters() {
return new external_function_parameters(
array(
'surveyid' => new external_value(PARAM_INT, 'Survey id'),
'answers' => new external_multiple_structure(
new external_single_structure(
array(
'key' => new external_value(PARAM_RAW, 'Answer key'),
'value' => new external_value(PARAM_RAW, 'Answer value')
)
)
),
)
);
}
/**
* Submit the answers for a given survey.
*
* @param int $surveyid the survey instance id
* @param array $answers the survey answers
* @return array of warnings and status result
* @since Moodle 3.0
* @throws moodle_exception
*/
public static function submit_answers($surveyid, $answers) {
global $DB, $USER;
$params = self::validate_parameters(self::submit_answers_parameters(),
array(
'surveyid' => $surveyid,
'answers' => $answers
));
$warnings = array();
// Request and permission validation.
$survey = $DB->get_record('survey', array('id' => $params['surveyid']), '*', MUST_EXIST);
list($course, $cm) = get_course_and_cm_from_instance($survey, 'survey');
$context = context_module::instance($cm->id);
self::validate_context($context);
require_capability('mod/survey:participate', $context);
if (survey_already_done($survey->id, $USER->id)) {
throw new moodle_exception("alreadysubmitted", "survey");
}
// Build the answers array. Data is cleaned inside the survey_save_answers function.
$answers = array();
foreach ($params['answers'] as $answer) {
$key = $answer['key'];
$answers[$key] = $answer['value'];
}
survey_save_answers($survey, $answers, $course, $context);
$result = array();
$result['status'] = true;
$result['warnings'] = $warnings;
return $result;
}
/**
* Returns description of method result value
*
* @return external_description
* @since Moodle 3.0
*/
public static function submit_answers_returns() {
return new external_single_structure(
array(
'status' => new external_value(PARAM_BOOL, 'status: true if success'),
'warnings' => new external_warnings()
)
);
}
}
+64
View File
@@ -0,0 +1,64 @@
<?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/>.
/**
* Survey external functions and service definitions.
*
* @package mod_survey
* @category external
* @copyright 2015 Juan Leyva <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 3.0
*/
defined('MOODLE_INTERNAL') || die;
$functions = array(
'mod_survey_get_surveys_by_courses' => array(
'classname' => 'mod_survey_external',
'methodname' => 'get_surveys_by_courses',
'description' => 'Returns a list of survey instances in a provided set of courses,
if no courses are provided then all the survey instances the user has access to will be returned.',
'type' => 'read',
'capabilities' => ''
),
'mod_survey_view_survey' => array(
'classname' => 'mod_survey_external',
'methodname' => 'view_survey',
'description' => 'Trigger the course module viewed event and update the module completion status.',
'type' => 'write',
'capabilities' => 'mod/survey:participate'
),
'mod_survey_get_questions' => array(
'classname' => 'mod_survey_external',
'methodname' => 'get_questions',
'description' => 'Get the complete list of questions for the survey, including subquestions.',
'type' => 'read',
'capabilities' => 'mod/survey:participate'
),
'mod_survey_submit_answers' => array(
'classname' => 'mod_survey_external',
'methodname' => 'submit_answers',
'description' => 'Submit the answers for a given survey.',
'type' => 'write',
'capabilities' => 'mod/survey:participate'
),
);
+179 -1
View File
@@ -535,7 +535,7 @@ function survey_print_multi($question) {
echo "<tr><th scope=\"col\" colspan=\"7\">$question->intro</th></tr>\n";
$subquestions = $DB->get_records_list("survey_questions", "id", explode(',', $question->multi));
$subquestions = survey_get_subquestions($question);
foreach ($subquestions as $q) {
$qnum++;
@@ -838,3 +838,181 @@ function survey_page_type_list($pagetype, $parentcontext, $currentcontext) {
$module_pagetype = array('mod-survey-*'=>get_string('page-mod-survey-x', 'survey'));
return $module_pagetype;
}
/**
* Mark the activity completed (if required) and trigger the course_module_viewed event.
*
* @param stdClass $survey survey object
* @param stdClass $course course object
* @param stdClass $cm course module object
* @param stdClass $context context object
* @param string $viewed which page viewed
* @since Moodle 3.0
*/
function survey_view($survey, $course, $cm, $context, $viewed) {
// Trigger course_module_viewed event.
$params = array(
'context' => $context,
'objectid' => $survey->id,
'courseid' => $course->id,
'other' => array('viewed' => $viewed)
);
$event = \mod_survey\event\course_module_viewed::create($params);
$event->add_record_snapshot('course_modules', $cm);
$event->add_record_snapshot('course', $course);
$event->add_record_snapshot('survey', $survey);
$event->trigger();
// Completion.
$completion = new completion_info($course);
$completion->set_module_viewed($cm);
}
/**
* Helper function for ordering a set of questions by the given ids.
*
* @param array $questions array of questions objects
* @param array $questionorder array of questions ids indicating the correct order
* @return array list of questions ordered
* @since Moodle 3.0
*/
function survey_order_questions($questions, $questionorder) {
$finalquestions = array();
foreach ($questionorder as $qid) {
$finalquestions[] = $questions[$qid];
}
return $finalquestions;
}
/**
* Translate the question texts and options.
*
* @param stdClass $question question object
* @return stdClass question object with all the text fields translated
* @since Moodle 3.0
*/
function survey_translate_question($question) {
if ($question->text) {
$question->text = get_string($question->text, "survey");
}
if ($question->shorttext) {
$question->shorttext = get_string($question->shorttext, "survey");
}
if ($question->intro) {
$question->intro = get_string($question->intro, "survey");
}
if ($question->options) {
$question->options = get_string($question->options, "survey");
}
return $question;
}
/**
* Returns the questions for a survey (ordered).
*
* @param stdClass $survey survey object
* @return array list of questions ordered
* @since Moodle 3.0
* @throws moodle_exception
*/
function survey_get_questions($survey) {
global $DB;
$questionids = explode(',', $survey->questions);
if (! $questions = $DB->get_records_list("survey_questions", "id", $questionids)) {
throw new moodle_exception('cannotfindquestion', 'survey');
}
return survey_order_questions($questions, $questionids);
}
/**
* Returns subquestions for a given question (ordered).
*
* @param stdClass $question questin object
* @return array list of subquestions ordered
* @since Moodle 3.0
*/
function survey_get_subquestions($question) {
global $DB;
$questionids = explode(',', $question->multi);
$questions = $DB->get_records_list("survey_questions", "id", $questionids);
return survey_order_questions($questions, $questionids);
}
/**
* Save the answer for the given survey
*
* @param stdClass $survey a survey object
* @param array $answersrawdata the answers to be saved
* @param stdClass $course a course object (required for trigger the submitted event)
* @param stdClass $context a context object (required for trigger the submitted event)
* @since Moodle 3.0
*/
function survey_save_answers($survey, $answersrawdata, $course, $context) {
global $DB, $USER;
$answers = array();
// Sort through the data and arrange it.
// This is necessary because some of the questions may have two answers, eg Question 1 -> 1 and P1.
foreach ($answersrawdata as $key => $val) {
if ($key <> "userid" && $key <> "id") {
if (substr($key, 0, 1) == "q") {
$key = clean_param(substr($key, 1), PARAM_ALPHANUM); // Keep everything but the 'q', number or P number.
}
if (substr($key, 0, 1) == "P") {
$realkey = (int) substr($key, 1);
$answers[$realkey][1] = $val;
} else {
$answers[$key][0] = $val;
}
}
}
// Now store the data.
$timenow = time();
$answerstoinsert = array();
foreach ($answers as $key => $val) {
if ($key != 'sesskey') {
$newdata = new stdClass();
$newdata->time = $timenow;
$newdata->userid = $USER->id;
$newdata->survey = $survey->id;
$newdata->question = $key;
if (!empty($val[0])) {
$newdata->answer1 = $val[0];
} else {
$newdata->answer1 = "";
}
if (!empty($val[1])) {
$newdata->answer2 = $val[1];
} else {
$newdata->answer2 = "";
}
$answerstoinsert[] = $newdata;
}
}
if (!empty($answerstoinsert)) {
$DB->insert_records("survey_answers", $answerstoinsert);
}
$params = array(
'context' => $context,
'courseid' => $course->id,
'other' => array('surveyid' => $survey->id)
);
$event = \mod_survey\event\response_submitted::create($params);
$event->trigger();
}
+2 -4
View File
@@ -275,10 +275,8 @@
if ($question->multi) {
echo $OUTPUT->heading($question->text . ':', 4);
$subquestions = $DB->get_records_list("survey_questions", "id", explode(',', $question->multi));
$subquestionorder = explode(",", $question->multi);
foreach ($subquestionorder as $key => $val) {
$subquestion = $subquestions[$val];
$subquestions = survey_get_subquestions($question);
foreach ($subquestions as $subquestion) {
if ($subquestion->type > 0) {
echo "<p class=\"centerpara\">";
echo "<a title=\"$strseemoredetail\" href=\"report.php?action=question&amp;id=$id&amp;qid=$subquestion->id\">";
+1 -46
View File
@@ -66,52 +66,7 @@
exit;
}
// Sort through the data and arrange it
// This is necessary because some of the questions
// may have two answers, eg Question 1 -> 1 and P1
$answers = array();
foreach ($formdata as $key => $val) {
if ($key <> "userid" && $key <> "id") {
if ( substr($key,0,1) == "q") {
$key = clean_param(substr($key,1), PARAM_ALPHANUM); // keep everything but the 'q', number or Pnumber
}
if ( substr($key,0,1) == "P") {
$realkey = (int) substr($key,1);
$answers[$realkey][1] = $val;
} else {
$answers[$key][0] = $val;
}
}
}
// Now store the data.
$timenow = time();
foreach ($answers as $key => $val) {
if ($key != 'sesskey') {
$newdata = new stdClass();
$newdata->time = $timenow;
$newdata->userid = $USER->id;
$newdata->survey = $survey->id;
$newdata->question = $key;
if (!empty($val[0])) {
$newdata->answer1 = $val[0];
} else {
$newdata->answer1 = "";
}
if (!empty($val[1])) {
$newdata->answer2 = $val[1];
} else {
$newdata->answer2 = "";
}
$DB->insert_record("survey_answers", $newdata);
}
}
survey_save_answers($survey, $formdata, $course, $context);
$params = array(
'context' => $context,
+385
View File
@@ -0,0 +1,385 @@
<?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/>.
/**
* Survey module external functions tests
*
* @package mod_survey
* @category external
* @copyright 2015 Juan Leyva <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 3.0
*/
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->dirroot . '/webservice/tests/helpers.php');
require_once($CFG->dirroot . '/mod/survey/lib.php');
/**
* Survey module external functions tests
*
* @package mod_survey
* @category external
* @copyright 2015 Juan Leyva <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 3.0
*/
class mod_survey_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->survey = $this->getDataGenerator()->create_module('survey', array('course' => $this->course->id));
$this->context = context_module::instance($this->survey->cmid);
$this->cm = get_coursemodule_from_instance('survey', $this->survey->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 surveys by courses
*/
public function test_mod_survey_get_surveys_by_courses() {
global $DB;
// Create additional course.
$course2 = self::getDataGenerator()->create_course();
// Second survey.
$record = new stdClass();
$record->course = $course2->id;
$survey2 = self::getDataGenerator()->create_module('survey', $record);
// Force empty intro.
$DB->set_field('survey', 'intro', '', array('id' => $survey2->id));
// 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_survey_external::get_surveys_by_courses_returns();
// Create what we expect to be returned when querying the two courses.
// First for the student user.
$expectedfields = array('id', 'coursemodule', 'course', 'name', 'intro', 'introformat', 'template', 'days', 'questions',
'surveydone');
// Add expected coursemodule and data.
$survey1 = $this->survey;
$survey1->coursemodule = $survey1->cmid;
$survey1->introformat = 1;
$survey1->surveydone = 0;
$survey1->section = 0;
$survey1->visible = true;
$survey1->groupmode = 0;
$survey1->groupingid = 0;
$survey2->coursemodule = $survey2->cmid;
$survey2->introformat = 1;
$survey2->surveydone = 0;
$survey2->section = 0;
$survey2->visible = true;
$survey2->groupmode = 0;
$survey2->groupingid = 0;
$tempo = $DB->get_field("survey", "intro", array("id" => $survey2->template));
$survey2->intro = nl2br(get_string($tempo, "survey"));
foreach ($expectedfields as $field) {
$expected1[$field] = $survey1->{$field};
$expected2[$field] = $survey2->{$field};
}
$expectedsurveys = array($expected2, $expected1);
// Call the external function passing course ids.
$result = mod_survey_external::get_surveys_by_courses(array($course2->id, $this->course->id));
$result = external_api::clean_returnvalue($returndescription, $result);
$this->assertEquals($expectedsurveys, $result['surveys']);
$this->assertCount(0, $result['warnings']);
// Call the external function without passing course id.
$result = mod_survey_external::get_surveys_by_courses();
$result = external_api::clean_returnvalue($returndescription, $result);
$this->assertEquals($expectedsurveys, $result['surveys']);
$this->assertCount(0, $result['warnings']);
// Unenrol user from second course and alter expected surveys.
$enrol->unenrol_user($instance2, $this->student->id);
array_shift($expectedsurveys);
// Call the external function without passing course id.
$result = mod_survey_external::get_surveys_by_courses();
$result = external_api::clean_returnvalue($returndescription, $result);
$this->assertEquals($expectedsurveys, $result['surveys']);
// Call for the second course we unenrolled the user from, expected warning.
$result = mod_survey_external::get_surveys_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);
$additionalfields = array('timecreated', 'timemodified', 'section', 'visible', 'groupmode', 'groupingid');
foreach ($additionalfields as $field) {
$expectedsurveys[0][$field] = $survey1->{$field};
}
$result = mod_survey_external::get_surveys_by_courses();
$result = external_api::clean_returnvalue($returndescription, $result);
$this->assertEquals($expectedsurveys, $result['surveys']);
// Admin also should get all the information.
self::setAdminUser();
$result = mod_survey_external::get_surveys_by_courses(array($this->course->id));
$result = external_api::clean_returnvalue($returndescription, $result);
$this->assertEquals($expectedsurveys, $result['surveys']);
// Now, prohibit capabilities.
$this->setUser($this->student);
$contextcourse1 = context_course::instance($this->course->id);
// Prohibit capability = mod/survey:participate on Course1 for students.
assign_capability('mod/survey:participate', CAP_PROHIBIT, $this->studentrole->id, $contextcourse1->id);
accesslib_clear_all_caches_for_unit_testing();
$surveys = mod_survey_external::get_surveys_by_courses(array($this->course->id));
$surveys = external_api::clean_returnvalue(mod_survey_external::get_surveys_by_courses_returns(), $surveys);
$this->assertFalse(isset($surveys['surveys'][0]['intro']));
}
/**
* Test view_survey
*/
public function test_view_survey() {
global $DB;
// Test invalid instance id.
try {
mod_survey_external::view_survey(0);
$this->fail('Exception expected due to invalid mod_survey instance id.');
} catch (moodle_exception $e) {
$this->assertEquals('invalidrecord', $e->errorcode);
}
// Test not-enrolled user.
$usernotenrolled = self::getDataGenerator()->create_user();
$this->setUser($usernotenrolled);
try {
mod_survey_external::view_survey($this->survey->id);
$this->fail('Exception expected due to not enrolled user.');
} catch (moodle_exception $e) {
$this->assertEquals('requireloginerror', $e->errorcode);
}
// Test user with full capabilities.
$this->setUser($this->student);
// Trigger and capture the event.
$sink = $this->redirectEvents();
$result = mod_survey_external::view_survey($this->survey->id);
$result = external_api::clean_returnvalue(mod_survey_external::view_survey_returns(), $result);
$this->assertTrue($result['status']);
$events = $sink->get_events();
$this->assertCount(1, $events);
$event = array_shift($events);
// Checking that the event contains the expected values.
$this->assertInstanceOf('\mod_survey\event\course_module_viewed', $event);
$this->assertEquals($this->context, $event->get_context());
$moodlesurvey = new \moodle_url('/mod/survey/view.php', array('id' => $this->cm->id));
$this->assertEquals($moodlesurvey, $event->get_url());
$this->assertEventContextNotUsed($event);
$this->assertNotEmpty($event->get_name());
// Test user with no capabilities.
// We need a explicit prohibit since this capability is only defined in authenticated user and guest roles.
assign_capability('mod/survey:participate', CAP_PROHIBIT, $this->studentrole->id, $this->context->id);
accesslib_clear_all_caches_for_unit_testing();
try {
mod_survey_external::view_survey($this->survey->id);
$this->fail('Exception expected due to missing capability.');
} catch (moodle_exception $e) {
$this->assertEquals('nopermissions', $e->errorcode);
}
}
/**
* Test get_questions
*/
public function test_get_questions() {
global $DB;
// Test user with full capabilities.
$this->setUser($this->student);
// Build our expectation array.
$expectedquestions = array();
$questions = survey_get_questions($this->survey);
foreach ($questions as $q) {
if ($q->type >= 0) {
$expectedquestions[$q->id] = $q;
if ($q->multi) {
$subquestions = survey_get_subquestions($q);
foreach ($subquestions as $sq) {
$expectedquestions[$sq->id] = $sq;
}
}
}
}
$result = mod_survey_external::get_questions($this->survey->id);
$result = external_api::clean_returnvalue(mod_survey_external::get_questions_returns(), $result);
// Check we receive the same questions.
$this->assertCount(0, $result['warnings']);
foreach ($result['questions'] as $q) {
$this->assertEquals(get_string($expectedquestions[$q['id']]->text, 'survey'), $q['text']);
$this->assertEquals(get_string($expectedquestions[$q['id']]->shorttext, 'survey'), $q['shorttext']);
$this->assertEquals($expectedquestions[$q['id']]->multi, $q['multi']);
$this->assertEquals($expectedquestions[$q['id']]->type, $q['type']);
// Parent questions must have parent eq to 0.
if ($q['multi']) {
$this->assertEquals(0, $q['parent']);
$this->assertEquals(get_string($expectedquestions[$q['id']]->options, 'survey'), $q['options']);
}
}
// Test user with no capabilities.
// We need a explicit prohibit since this capability is only defined in authenticated user and guest roles.
assign_capability('mod/survey:participate', CAP_PROHIBIT, $this->studentrole->id, $this->context->id);
accesslib_clear_all_caches_for_unit_testing();
try {
mod_survey_external::get_questions($this->survey->id);
$this->fail('Exception expected due to missing capability.');
} catch (moodle_exception $e) {
$this->assertEquals('nopermissions', $e->errorcode);
}
}
/**
* Test submit_answers
*/
public function test_submit_answers() {
global $DB;
// Test user with full capabilities.
$this->setUser($this->student);
// Build our questions and responses array.
$realquestions = array();
$questions = survey_get_questions($this->survey);
$i = 5;
foreach ($questions as $q) {
if ($q->type >= 0) {
if ($q->multi) {
$subquestions = survey_get_subquestions($q);
foreach ($subquestions as $sq) {
$realquestions[] = array(
'key' => 'q' . $sq->id,
'value' => $i % 5 + 1 // Values between 1 and 5.
);
$i++;
}
} else {
$realquestions[] = array(
'key' => 'q' . $q->id,
'value' => $i % 5 + 1
);
$i++;
}
}
}
$result = mod_survey_external::submit_answers($this->survey->id, $realquestions);
$result = external_api::clean_returnvalue(mod_survey_external::submit_answers_returns(), $result);
$this->assertTrue($result['status']);
$this->assertCount(0, $result['warnings']);
$dbanswers = $DB->get_records_menu('survey_answers', array('survey' => $this->survey->id), '', 'question, answer1');
foreach ($realquestions as $q) {
$id = str_replace('q', '', $q['key']);
$this->assertEquals($q['value'], $dbanswers[$id]);
}
// Submit again, we expect an error here.
try {
mod_survey_external::submit_answers($this->survey->id, $realquestions);
$this->fail('Exception expected due to answers already submitted.');
} catch (moodle_exception $e) {
$this->assertEquals('alreadysubmitted', $e->errorcode);
}
// Test user with no capabilities.
// We need a explicit prohibit since this capability is only defined in authenticated user and guest roles.
assign_capability('mod/survey:participate', CAP_PROHIBIT, $this->studentrole->id, $this->context->id);
accesslib_clear_all_caches_for_unit_testing();
try {
mod_survey_external::submit_answers($this->survey->id, $realquestions);
$this->fail('Exception expected due to missing capability.');
} catch (moodle_exception $e) {
$this->assertEquals('nopermissions', $e->errorcode);
}
// Test not-enrolled user.
$usernotenrolled = self::getDataGenerator()->create_user();
$this->setUser($usernotenrolled);
try {
mod_survey_external::submit_answers($this->survey->id, $realquestions);
$this->fail('Exception expected due to not enrolled user.');
} catch (moodle_exception $e) {
$this->assertEquals('requireloginerror', $e->errorcode);
}
}
}
+169
View File
@@ -0,0 +1,169 @@
<?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/>.
/**
* Unit tests for mod_survey lib
*
* @package mod_survey
* @category external
* @copyright 2015 Juan Leyva <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 3.0
*/
defined('MOODLE_INTERNAL') || die();
/**
* Unit tests for mod_survey lib
*
* @package mod_survey
* @category external
* @copyright 2015 Juan Leyva <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 3.0
*/
class mod_survey_lib_testcase extends advanced_testcase {
/**
* Prepares things before this test case is initialised
* @return void
*/
public static function setUpBeforeClass() {
global $CFG;
require_once($CFG->dirroot . '/mod/survey/lib.php');
}
/**
* Test survey_view
* @return void
*/
public function test_survey_view() {
global $CFG;
$CFG->enablecompletion = 1;
$this->resetAfterTest();
$this->setAdminUser();
// Setup test data.
$course = $this->getDataGenerator()->create_course(array('enablecompletion' => 1));
$survey = $this->getDataGenerator()->create_module('survey', array('course' => $course->id),
array('completion' => 2, 'completionview' => 1));
$context = context_module::instance($survey->cmid);
$cm = get_coursemodule_from_instance('survey', $survey->id);
// Trigger and capture the event.
$sink = $this->redirectEvents();
survey_view($survey, $course, $cm, $context, 'form');
$events = $sink->get_events();
// 2 additional events thanks to completion.
$this->assertCount(3, $events);
$event = array_shift($events);
// Checking that the event contains the expected values.
$this->assertInstanceOf('\mod_survey\event\course_module_viewed', $event);
$this->assertEquals($context, $event->get_context());
$moodleurl = new \moodle_url('/mod/survey/view.php', array('id' => $cm->id));
$this->assertEquals($moodleurl, $event->get_url());
$this->assertEquals('form', $event->other['viewed']);
$this->assertEventContextNotUsed($event);
$this->assertNotEmpty($event->get_name());
// Check completion status.
$completion = new completion_info($course);
$completiondata = $completion->get_data($cm);
$this->assertEquals(1, $completiondata->completionstate);
}
/**
* Test survey_order_questions
*/
public function test_survey_order_questions() {
global $DB;
$this->resetAfterTest();
$course = $this->getDataGenerator()->create_course();
$survey = $this->getDataGenerator()->create_module('survey', array('course' => $course->id));
$orderedquestionids = explode(',', $survey->questions);
$surveyquestions = $DB->get_records_list("survey_questions", "id", $orderedquestionids);
$questionsordered = survey_order_questions($surveyquestions, $orderedquestionids);
// Check one by one the correct order.
for ($i = 0; $i < count($orderedquestionids); $i++) {
$this->assertEquals($orderedquestionids[$i], $questionsordered[$i]->id);
}
}
/**
* Test survey_save_answers
*/
public function test_survey_save_answers() {
global $DB;
$this->resetAfterTest();
$this->setAdminUser();
// Setup test data.
$course = $this->getDataGenerator()->create_course();
$survey = $this->getDataGenerator()->create_module('survey', array('course' => $course->id));
$context = context_module::instance($survey->cmid);
// Build our questions and responses array.
$realquestions = array();
$questions = survey_get_questions($survey);
$i = 5;
foreach ($questions as $q) {
if ($q->type > 0) {
if ($q->multi) {
$subquestions = survey_get_subquestions($q);
foreach ($subquestions as $sq) {
$key = 'q' . $sq->id;
$realquestions[$key] = $i % 5 + 1;
$i++;
}
} else {
$key = 'q' . $q->id;
$realquestions[$key] = $i % 5 + 1;
$i++;
}
}
}
$sink = $this->redirectEvents();
survey_save_answers($survey, $realquestions, $course, $context);
// Check the stored answers, they must match.
$dbanswers = $DB->get_records_menu('survey_answers', array('survey' => $survey->id), '', 'question, answer1');
foreach ($realquestions as $key => $value) {
$id = str_replace('q', '', $key);
$this->assertEquals($value, $dbanswers[$id]);
}
// Check events.
$events = $sink->get_events();
$this->assertCount(1, $events);
$event = array_shift($events);
// Checking that the event contains the expected values.
$this->assertInstanceOf('\mod_survey\event\response_submitted', $event);
$this->assertEquals($context, $event->get_context());
$this->assertEquals($survey->id, $event->other['surveyid']);
}
}
+1 -1
View File
@@ -24,7 +24,7 @@
defined('MOODLE_INTERNAL') || die();
$plugin->version = 2015051100; // The current module version (Date: YYYYMMDDXX)
$plugin->version = 2015051101; // The current module version (Date: YYYYMMDDXX)
$plugin->requires = 2015050500; // Requires this Moodle version
$plugin->component = 'mod_survey'; // Full name of the plugin (used for diagnostics)
$plugin->cron = 0;
+17 -55
View File
@@ -54,13 +54,17 @@ if (! $template = $DB->get_record("survey", array("id" => $survey->template))) {
print_error('invalidtmptid', 'survey');
}
// Update 'viewed' state if required by completion system.
require_once($CFG->libdir . '/completionlib.php');
$completion = new completion_info($course);
$completion->set_module_viewed($cm);
$showscales = ($template->name != 'ciqname');
// Check the survey hasn't already been filled out.
$surveyalreadydone = survey_already_done($survey->id, $USER->id);
if ($surveyalreadydone) {
// Trigger course_module_viewed event and completion.
survey_view($survey, $course, $cm, $context, 'graph');
} else {
survey_view($survey, $course, $cm, $context, 'form');
}
$strsurvey = get_string("modulename", "survey");
$PAGE->set_title($survey->name);
$PAGE->set_heading($course->fullname);
@@ -91,18 +95,8 @@ if (!is_enrolled($context)) {
echo $OUTPUT->notification(get_string("guestsnotallowed", "survey"));
}
if ($surveyalreadydone) {
// Check the survey hasn't already been filled out.
if (survey_already_done($survey->id, $USER->id)) {
$params = array(
'objectid' => $survey->id,
'context' => $context,
'courseid' => $course->id,
'other' => array('viewed' => 'graph')
);
$event = \mod_survey\event\course_module_viewed::create($params);
$event->trigger();
$numusers = survey_count_responses($survey->id, $currentgroup, $groupingid);
if ($showscales) {
@@ -125,10 +119,9 @@ if (survey_already_done($survey->id, $USER->id)) {
echo $OUTPUT->box(format_module_intro('survey', $survey, $cm->id), 'generalbox', 'intro');
echo $OUTPUT->spacer(array('height' => 30, 'width' => 1), true); // Should be done with CSS instead.
$questions = $DB->get_records_list("survey_questions", "id", explode(',', $survey->questions));
$questionorder = explode(",", $survey->questions);
foreach ($questionorder as $key => $val) {
$question = $questions[$val];
$questions = survey_get_questions($survey);
foreach ($questions as $question) {
if ($question->type == 0 or $question->type == 1) {
if ($answer = survey_get_user_answer($survey->id, $question->id, $USER->id)) {
$table = new html_table();
@@ -146,16 +139,6 @@ if (survey_already_done($survey->id, $USER->id)) {
exit;
}
// Start the survey form.
$params = array(
'objectid' => $survey->id,
'context' => $context,
'courseid' => $course->id,
'other' => array('viewed' => 'form')
);
$event = \mod_survey\event\course_module_viewed::create($params);
$event->trigger();
echo "<form method=\"post\" action=\"save.php\" id=\"surveyform\">";
echo '<div>';
echo "<input type=\"hidden\" name=\"id\" value=\"$id\" />";
@@ -164,39 +147,18 @@ echo "<input type=\"hidden\" name=\"sesskey\" value=\"".sesskey()."\" />";
echo $OUTPUT->box(format_module_intro('survey', $survey, $cm->id), 'generalbox boxaligncenter bowidthnormal', 'intro');
echo '<div>'. get_string('allquestionrequireanswer', 'survey'). '</div>';
// Get all the major questions and their proper order.
if (! $questions = $DB->get_records_list("survey_questions", "id", explode(',', $survey->questions))) {
print_error('cannotfindquestion', 'survey');
}
$questionorder = explode( ",", $survey->questions);
// Cycle through all the questions in order and print them.
// Get all the major questions in order.
$questions = survey_get_questions($survey);
global $qnum; // TODO: ugly globals hack for survey_print_*().
global $checklist; // TODO: ugly globals hack for survey_print_*().
$qnum = 0;
$checklist = array();
foreach ($questionorder as $key => $val) {
$question = $questions["$val"];
$question->id = $val;
foreach ($questions as $question) {
if ($question->type >= 0) {
if ($question->text) {
$question->text = get_string($question->text, "survey");
}
if ($question->shorttext) {
$question->shorttext = get_string($question->shorttext, "survey");
}
if ($question->intro) {
$question->intro = get_string($question->intro, "survey");
}
if ($question->options) {
$question->options = get_string($question->options, "survey");
}
$question = survey_translate_question($question);
if ($question->multi) {
survey_print_multi($question);
+1 -1
View File
@@ -29,7 +29,7 @@
defined('MOODLE_INTERNAL') || die();
$version = 2015101400.00; // YYYYMMDD = weekly release date of this DEV branch.
$version = 2015101400.01; // YYYYMMDD = weekly release date of this DEV branch.
// RR = release increments - 00 in DEV branches.
// .XX = incremental changes.