MDL-51629 mod_survey: New WS mod_survey_get_surveys_by_courses
authorJuan Leyva <juanleyvadelgado@gmail.com>
Thu, 1 Oct 2015 10:01:47 +0000 (12:01 +0200)
committerJuan Leyva <juanleyvadelgado@gmail.com>
Thu, 15 Oct 2015 14:05:05 +0000 (16:05 +0200)
lib/db/services.php
mod/survey/classes/external.php [new file with mode: 0644]
mod/survey/db/services.php [new file with mode: 0644]
mod/survey/tests/externallib_test.php [new file with mode: 0644]
mod/survey/version.php
version.php

index effb656..4903401 100644 (file)
@@ -1231,6 +1231,7 @@ $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_page_view_page',
             'mod_resource_view_resource',
             'mod_folder_view_folder',
diff --git a/mod/survey/classes/external.php b/mod/survey/classes/external.php
new file mode 100644 (file)
index 0000000..d7f4547
--- /dev/null
@@ -0,0 +1,167 @@
+<?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 <juan@moodle.com>
+ * @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");
+
+/**
+ * Survey external functions
+ *
+ * @package    mod_survey
+ * @category   external
+ * @copyright  2015 Juan Leyva <juan@moodle.com>
+ * @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(),
+            )
+        );
+    }
+
+}
diff --git a/mod/survey/db/services.php b/mod/survey/db/services.php
new file mode 100644 (file)
index 0000000..4ab9a66
--- /dev/null
@@ -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/>.
+
+/**
+ * Survey external functions and service definitions.
+ *
+ * @package    mod_survey
+ * @category   external
+ * @copyright  2015 Juan Leyva <juan@moodle.com>
+ * @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'  => ''
+    )
+);
diff --git a/mod/survey/tests/externallib_test.php b/mod/survey/tests/externallib_test.php
new file mode 100644 (file)
index 0000000..884ef45
--- /dev/null
@@ -0,0 +1,194 @@
+<?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 <juan@moodle.com>
+ * @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 <juan@moodle.com>
+ * @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']));
+    }
+
+}
index f185838..d953293 100644 (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;
index bacaea3..4a29a81 100644 (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.