MDL-59241 mod_workshop: New WS mod_workshop_get_submissions
authorJuan Leyva <juanleyvadelgado@gmail.com>
Thu, 22 Jun 2017 10:00:43 +0000 (11:00 +0100)
committerJuan Leyva <juanleyvadelgado@gmail.com>
Mon, 2 Oct 2017 07:33:48 +0000 (09:33 +0200)
mod/workshop/classes/external.php
mod/workshop/classes/external/submission_exporter.php [new file with mode: 0644]
mod/workshop/db/services.php
mod/workshop/locallib.php
mod/workshop/tests/external_test.php
mod/workshop/version.php

index 841dc2e..bd24d27 100644 (file)
@@ -30,6 +30,7 @@ require_once("$CFG->libdir/externallib.php");
 require_once($CFG->dirroot . '/mod/workshop/locallib.php');
 
 use mod_workshop\external\workshop_summary_exporter;
+use mod_workshop\external\submission_exporter;
 
 /**
  * Workshop external functions
@@ -708,4 +709,168 @@ class mod_workshop_external extends external_api {
             'warnings' => new external_warnings()
         ));
     }
+
+    /**
+     * Helper method for returning the submission data according the current user capabilities and current phase.
+     *
+     * @param  stdClass $submission the submission data
+     * @param  workshop $workshop   the workshop class
+     * @param  bool $canviewauthorpublished whether the user has the capability mod/workshop:viewauthorpublished on
+     * @param  bool $canviewauthornames whether the user has the capability mod/workshop:vviewauthornames on
+     * @param  bool $canviewallsubmissions whether the user has the capability mod/workshop:viewallsubmissions on
+     * @return stdClass object with the submission data filtered
+     * @since Moodle 3.4
+     */
+    protected static function prepare_submission_for_external($submission, workshop $workshop, $canviewauthorpublished = null,
+            $canviewauthornames = null, $canviewallsubmissions = null) {
+        global $USER;
+
+        if (is_null($canviewauthorpublished)) {
+            $canviewauthorpublished = has_capability('mod/workshop:viewauthorpublished', $workshop->context);
+        }
+        if (is_null($canviewauthornames)) {
+            $canviewauthornames = has_capability('mod/workshop:viewauthornames', $workshop->context);
+        }
+        if (is_null($canviewallsubmissions)) {
+            $canviewallsubmissions = has_capability('mod/workshop:viewallsubmissions', $workshop->context);
+        }
+
+        $ownsubmission = $submission->authorid == $USER->id;
+        if (!$canviewauthornames && !$ownsubmission) {
+            $submission->authorid = 0;
+        }
+
+        $isworkshopclosed = $workshop->phase == workshop::PHASE_CLOSED;
+        $canviewsubmissiondetail = $ownsubmission || $canviewallsubmissions;
+        // If the workshop is not closed or the user can't see the submission detail: remove grading or feedback information.
+        if (!$isworkshopclosed || !$canviewsubmissiondetail) {
+            $properties = submission_exporter::properties_definition();
+            foreach ($properties as $attribute => $settings) {
+                if (!empty($settings['optional'])) {
+                    unset($submission->{$attribute});
+                }
+            }
+        }
+        return $submission;
+    }
+
+    /**
+     * Returns description of method parameters
+     *
+     * @return external_function_parameters
+     * @since Moodle 3.4
+     */
+    public static function get_submissions_parameters() {
+        return new external_function_parameters(
+            array(
+                'workshopid' => new external_value(PARAM_INT, 'Workshop instance id.'),
+                'userid' => new external_value(PARAM_INT, 'Get submissions done by this user. Use 0 or empty for the current user',
+                                                VALUE_DEFAULT, 0),
+                'groupid' => new external_value(PARAM_INT, 'Group id, 0 means that the function will determine the user group.
+                                                   It will return submissions done by users in the given group.',
+                                                   VALUE_DEFAULT, 0),
+                'page' => new external_value(PARAM_INT, 'The page of records to return.', VALUE_DEFAULT, 0),
+                'perpage' => new external_value(PARAM_INT, 'The number of records to return per page.', VALUE_DEFAULT, 0),
+            )
+        );
+    }
+
+    /**
+     * Retrieves all the workshop submissions visible by the current user or the one done by the given user.
+     *
+     * @param int $workshopid       the workshop instance id
+     * @param int $userid           get submissions done by this user
+     * @param int $groupid          (optional) group id, 0 means that the function will determine the user group
+     * @param int $page             page of records to return
+     * @param int $perpage          number of records to return per page
+     * @return array of warnings and the entries
+     * @since Moodle 3.4
+     * @throws moodle_exception
+     */
+    public static function get_submissions($workshopid, $userid = 0, $groupid = 0, $page = 0, $perpage = 0) {
+        global $PAGE, $USER;
+
+        $params = array('workshopid' => $workshopid, 'userid' => $userid, 'groupid' => $groupid,
+            'page' => $page, 'perpage' => $perpage);
+        $params = self::validate_parameters(self::get_submissions_parameters(), $params);
+        $submissions = $warnings = array();
+
+        list($workshop, $course, $cm, $context) = self::validate_workshop($params['workshopid']);
+
+        if (empty($params['groupid'])) {
+            // Check to see if groups are being used here.
+            if ($groupmode = groups_get_activity_groupmode($cm)) {
+                $groupid = groups_get_activity_group($cm);
+                // Determine is the group is visible to user (this is particullary for the group 0 -> all groups).
+                if (!groups_group_visible($groupid, $course, $cm)) {
+                    throw new moodle_exception('notingroup');
+                }
+            } else {
+                $groupid = 0;
+            }
+        }
+
+        if (!empty($params['userid']) && $params['userid'] != $USER->id) {
+            $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
+            core_user::require_active_user($user);
+            if (!$workshop->check_group_membership($user->id)) {
+                throw new moodle_exception('notingroup');
+            }
+        }
+
+        $totalfilesize = 0;
+        list($submissionsrecords, $totalcount) =
+            $workshop->get_visible_submissions($params['userid'], $groupid, $params['page'], $params['perpage']);
+
+        if ($totalcount) {
+
+            $canviewauthorpublished = has_capability('mod/workshop:viewauthorpublished', $context);
+            $canviewauthornames = has_capability('mod/workshop:viewauthornames', $context);
+            $canviewallsubmissions = has_capability('mod/workshop:viewallsubmissions', $context);
+
+            $related = array('context' => $context);
+            foreach ($submissionsrecords as $submission) {
+                $submission = self::prepare_submission_for_external($submission, $workshop, $canviewauthorpublished,
+                    $canviewauthornames, $canviewallsubmissions);
+
+                $exporter = new submission_exporter($submission, $related);
+                $submissions[] = $exporter->export($PAGE->get_renderer('core'));
+            }
+
+            // Retrieve total files size for the submissions (so external clients know how many data they'd need to download).
+            $fs = get_file_storage();
+            $files = $fs->get_area_files($context->id, 'mod_workshop', array('submission_content', 'submission_attachment'));
+            foreach ($files as $file) {
+                if ($file->is_directory() || !isset($submissionsrecords[$file->get_itemid()])) {
+                    continue;
+                }
+                $totalfilesize += $file->get_filesize();
+            }
+        }
+
+        return array(
+            'submissions' => $submissions,
+            'totalcount' => $totalcount,
+            'totalfilesize' => $totalfilesize,
+        );
+    }
+
+    /**
+     * Returns description of method result value
+     *
+     * @return external_description
+     * @since Moodle 3.4
+     */
+    public static function get_submissions_returns() {
+        return new external_single_structure(
+            array(
+                'submissions' => new external_multiple_structure(
+                    submission_exporter::get_read_structure()
+                ),
+                'totalcount' => new external_value(PARAM_INT, 'Total count of submissions.'),
+                'totalfilesize' => new external_value(PARAM_INT, 'Total size (bytes) of the files included in the submissions.'),
+                'warnings' => new external_warnings()
+            )
+        );
+    }
 }
diff --git a/mod/workshop/classes/external/submission_exporter.php b/mod/workshop/classes/external/submission_exporter.php
new file mode 100644 (file)
index 0000000..8bb4c45
--- /dev/null
@@ -0,0 +1,195 @@
+<?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/>.
+
+/**
+ * Class for exporting submission data.
+ *
+ * @package    mod_workshop
+ * @copyright  2017 Juan Leyva <juan@moodle.com>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+namespace mod_workshop\external;
+defined('MOODLE_INTERNAL') || die();
+
+use core\external\exporter;
+use renderer_base;
+use external_util;
+use external_files;
+
+/**
+ * Class for exporting submission data.
+ *
+ * @copyright  2017 Juan Leyva <juan@moodle.com>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class submission_exporter extends exporter {
+
+    protected static function define_properties() {
+
+        return array(
+            'id' => array(
+                'type' => PARAM_INT,
+                'description' => 'The primary key of the record.',
+            ),
+            'workshopid' => array(
+                'type' => PARAM_INT,
+                'description' => 'The id of the workshop instance.',
+            ),
+            'example' => array(
+                'type' => PARAM_BOOL,
+                'null' => NULL_ALLOWED,
+                'default' => false,
+                'description' => 'Is this submission an example from teacher.',
+            ),
+            'authorid' => array(
+                'type' => PARAM_INT,
+                'description' => 'The author of the submission.',
+            ),
+            'timecreated' => array(
+                'type' => PARAM_INT,
+                'description' => 'Timestamp when the work was submitted for the first time.',
+            ),
+            'timemodified' => array(
+                'type' => PARAM_INT,
+                'description' => 'Timestamp when the submission has been updated.',
+            ),
+            'title' => array(
+                'type' => PARAM_RAW,
+                'description' => 'The submission title.',
+            ),
+            'content' => array(
+                'type' => PARAM_RAW,
+                'null' => NULL_ALLOWED,
+                'description' => 'Submission text.',
+            ),
+            'contentformat' => array(
+                'choices' => array(FORMAT_HTML, FORMAT_MOODLE, FORMAT_PLAIN, FORMAT_MARKDOWN),
+                'type' => PARAM_INT,
+                'default' => FORMAT_MOODLE,
+                'description' => 'Submission text format.',
+            ),
+            'contenttrust' => array(
+                'type' => PARAM_INT,
+                'default' => 0,
+                'description' => 'The trust mode of the data.',
+            ),
+            'attachment' => array(
+                'type' => PARAM_INT,
+                'null' => NULL_ALLOWED,
+                'default' => 0,
+                'description' => 'Used by File API file_postupdate_standard_filemanager.',
+            ),
+            'grade' => array(
+                'type' => PARAM_FLOAT,
+                'null' => NULL_ALLOWED,
+                'description' => 'Aggregated grade for the submission. The grade is a decimal number from interval 0..100.
+                    If NULL then the grade for submission has not been aggregated yet.',
+                'optional' => true,
+            ),
+            'gradeover' => array(
+                'type' => PARAM_FLOAT,
+                'null' => NULL_ALLOWED,
+                'description' => 'Grade for the submission manually overridden by a teacher. Grade is always from interval 0..100.
+                    If NULL then the grade is not overriden.',
+                'optional' => true,
+            ),
+            'gradeoverby' => array(
+                'type' => PARAM_INT,
+                'null' => NULL_ALLOWED,
+                'description' => 'The id of the user who has overridden the grade for submission.',
+                'optional' => true,
+            ),
+            'feedbackauthor' => array(
+                'type' => PARAM_RAW,
+                'null' => NULL_ALLOWED,
+                'description' => 'Teacher comment/feedback for the author of the submission, for example describing the reasons
+                    for the grade overriding.',
+                'optional' => true,
+            ),
+            'feedbackauthorformat' => array(
+                'choices' => array(FORMAT_HTML, FORMAT_MOODLE, FORMAT_PLAIN, FORMAT_MARKDOWN),
+                'type' => PARAM_INT,
+                'default' => FORMAT_MOODLE,
+                'description' => 'Feedback text format.',
+            ),
+            'timegraded' => array(
+                'type' => PARAM_INT,
+                'null' => NULL_ALLOWED,
+                'description' => 'The timestamp when grade or gradeover was recently modified.',
+                'optional' => true,
+            ),
+            'published' => array(
+                'type' => PARAM_BOOL,
+                'null' => NULL_ALLOWED,
+                'default' => false,
+                'description' => 'Shall the submission be available to other when the workshop is closed.',
+            ),
+            'late' => array(
+                'type' => PARAM_INT,
+                'default' => 0,
+                'description' => 'Has this submission been submitted after the deadline or during the assessment phase?',
+            ),
+        );
+    }
+
+    protected static function define_related() {
+        return array(
+            'context' => 'context'
+        );
+    }
+
+    protected static function define_other_properties() {
+        return array(
+            'contentfiles' => array(
+                'type' => external_files::get_properties_for_exporter(),
+                'multiple' => true,
+                'optional' => true
+            ),
+            'attachmentfiles' => array(
+                'type' => external_files::get_properties_for_exporter(),
+                'multiple' => true,
+                'optional' => true
+            ),
+        );
+    }
+
+    protected function get_other_values(renderer_base $output) {
+        $context = $this->related['context'];
+
+        if (!empty($this->data->content)) {
+            $values['contentfiles'] =
+                external_util::get_area_files($context->id, 'mod_workshop', 'submission_content', $this->data->id);
+        }
+
+        $values['attachmentfiles'] =
+                external_util::get_area_files($context->id, 'mod_workshop', 'submission_attachment', $this->data->id);
+
+        return $values;
+    }
+
+    /**
+     * Get the formatting parameters for the content.
+     *
+     * @return array
+     */
+    protected function get_format_parameters_for_content() {
+        return [
+            'component' => 'mod_workshop',
+            'filearea' => 'submission_content',
+            'itemid' => $this->data->id,
+        ];
+    }
+}
index 416821a..6cdb621 100644 (file)
@@ -85,4 +85,11 @@ $functions = array(
         'capabilities'  => 'mod/workshop:submit',
         'services'      => array(MOODLE_OFFICIAL_MOBILE_SERVICE)
     ),
+    'mod_workshop_get_submissions' => array(
+        'classname'     => 'mod_workshop_external',
+        'methodname'    => 'get_submissions',
+        'description'   => 'Retrieves all the workshop submissions or the one done by the given user.',
+        'type'          => 'read',
+        'services'      => array(MOODLE_OFFICIAL_MOBILE_SERVICE)
+    ),
 );
index a79b623..4baddbe 100644 (file)
@@ -886,6 +886,69 @@ class workshop {
         return $DB->get_records_sql($sql, array_merge($params, $sortparams), $limitfrom, $limitnum);
     }
 
+    /**
+     * Returns submissions from this workshop that are viewable by the current user (except example submissions).
+     *
+     * @param mixed $authorid int|array If set to [array of] integer, return submission[s] of the given user[s] only
+     * @param int $groupid If non-zero, return only submissions by authors in the specified group. 0 for all groups.
+     * @param int $limitfrom Return a subset of records, starting at this point (optional)
+     * @param int $limitnum Return a subset containing this many records in total (optional, required if $limitfrom is set)
+     * @return array of records and the total submissions count
+     * @since  Moodle 3.4
+     */
+    public function get_visible_submissions($authorid = 0, $groupid = 0, $limitfrom = 0, $limitnum = 0) {
+        global $DB, $USER;
+
+        $submissions = array();
+        $select = "SELECT s.*";
+        $selectcount = "SELECT COUNT(s.id)";
+        $from = " FROM {workshop_submissions} s";
+        $params = array('workshopid' => $this->id);
+
+        // Check if the passed group (or all groups when groupid is 0) is visible by the current user.
+        if (!groups_group_visible($groupid, $this->course, $this->cm)) {
+            return array($submissions, 0);
+        }
+
+        if ($groupid) {
+            $from .= " JOIN {groups_members} gm ON (gm.userid = s.authorid AND gm.groupid = :groupid)";
+            $params['groupid'] = $groupid;
+        }
+        $where = " WHERE s.workshopid = :workshopid AND s.example = 0";
+
+        if (!has_capability('mod/workshop:viewallsubmissions', $this->context)) {
+            // Check published submissions.
+            $workshopclosed = $this->phase == self::PHASE_CLOSED;
+            $canviewpublished = has_capability('mod/workshop:viewpublishedsubmissions', $this->context);
+            if ($workshopclosed && $canviewpublished) {
+                $published = " OR s.published = 1";
+            } else {
+                $published = '';
+            }
+
+            // Always get submissions I did or I provided feedback to.
+            $where .= " AND (s.authorid = :authorid OR s.gradeoverby = :graderid $published)";
+            $params['authorid'] = $USER->id;
+            $params['graderid'] = $USER->id;
+        }
+
+        // Now, user filtering.
+        if (!empty($authorid)) {
+            list($usql, $uparams) = $DB->get_in_or_equal($authorid, SQL_PARAMS_NAMED);
+            $where .= " AND s.authorid $usql";
+            $params = array_merge($params, $uparams);
+        }
+
+        $order = " ORDER BY s.timecreated";
+
+        $totalcount = $DB->count_records_sql($selectcount.$from.$where, $params);
+        if ($totalcount) {
+            $submissions = $DB->get_records_sql($select.$from.$where.$order, $params, $limitfrom, $limitnum);
+        }
+        return array($submissions, $totalcount);
+    }
+
+
     /**
      * Returns a submission record with the author's data
      *
index 3647f96..903bebb 100644 (file)
@@ -32,6 +32,7 @@ require_once($CFG->dirroot . '/webservice/tests/helpers.php');
 require_once($CFG->dirroot . '/mod/workshop/lib.php');
 
 use mod_workshop\external\workshop_summary_exporter;
+use mod_workshop\external\submission_exporter;
 
 /**
  * Workshop module external functions tests
@@ -70,20 +71,33 @@ class mod_workshop_external_testcase extends externallib_advanced_testcase {
         $this->setAdminUser();
 
         // Setup test data.
-        $this->course = $this->getDataGenerator()->create_course();
+        $course = new stdClass();
+        $course->groupmode = SEPARATEGROUPS;
+        $course->groupmodeforce = true;
+        $this->course = $this->getDataGenerator()->create_course($course);
         $this->workshop = $this->getDataGenerator()->create_module('workshop', array('course' => $this->course->id));
         $this->context = context_module::instance($this->workshop->cmid);
         $this->cm = get_coursemodule_from_instance('workshop', $this->workshop->id);
 
         // Create users.
         $this->student = self::getDataGenerator()->create_user();
+        $this->anotherstudentg1 = self::getDataGenerator()->create_user();
+        $this->anotherstudentg2 = 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->anotherstudentg1->id, $this->course->id, $this->studentrole->id, 'manual');
+        $this->getDataGenerator()->enrol_user($this->anotherstudentg2->id, $this->course->id, $this->studentrole->id, 'manual');
         $this->getDataGenerator()->enrol_user($this->teacher->id, $this->course->id, $this->teacherrole->id, 'manual');
+
+        $this->group1 = $this->getDataGenerator()->create_group(array('courseid' => $this->course->id));
+        $this->group2 = $this->getDataGenerator()->create_group(array('courseid' => $this->course->id));
+        groups_add_member($this->group1, $this->student);
+        groups_add_member($this->group1, $this->anotherstudentg1);
+        groups_add_member($this->group2, $this->anotherstudentg2);
     }
 
     /**
@@ -790,4 +804,130 @@ class mod_workshop_external_testcase extends externallib_advanced_testcase {
         $this->expectException('moodle_exception');
         mod_workshop_external::delete_submission($submissionid);
     }
+
+    /**
+     * Test test_get_submissions_student.
+     */
+    public function test_get_submissions_student() {
+
+        // Create a couple of submissions with files.
+        $firstsubmissionid = $this->create_test_submission($this->student);  // Create submission with files.
+        $secondsubmissionid = $this->create_test_submission($this->anotherstudentg1->id);
+
+        $this->setUser($this->student);
+        $result = mod_workshop_external::get_submissions($this->workshop->id);
+        $result = external_api::clean_returnvalue(mod_workshop_external::get_submissions_returns(), $result);
+        // We should get just our submission.
+        $this->assertCount(1, $result['submissions']);
+        $this->assertEquals(1, $result['totalcount']);
+        $this->assertEquals($firstsubmissionid, $result['submissions'][0]['id']);
+        $this->assertCount(1, $result['submissions'][0]['contentfiles']); // Check we retrieve submission text files.
+        $this->assertCount(1, $result['submissions'][0]['attachmentfiles']); // Check we retrieve attachment files.
+        // We shoul not see the grade or feedback information.
+        $properties = submission_exporter::properties_definition();
+        foreach ($properties as $attribute => $settings) {
+            if (!empty($settings['optional'])) {
+                if (isset($result['submissions'][0][$attribute])) {
+                    echo "error $attribute";
+                }
+                $this->assertFalse(isset($result['submissions'][0][$attribute]));
+            }
+        }
+    }
+
+    /**
+     * Test test_get_submissions_published_student.
+     */
+    public function test_get_submissions_published_student() {
+        global $DB;
+
+        $DB->set_field('workshop', 'phase', workshop::PHASE_CLOSED, array('id' => $this->workshop->id));
+        // Create a couple of submissions with files.
+        $workshopgenerator = $this->getDataGenerator()->get_plugin_generator('mod_workshop');
+        $submission = array('published' => 1);
+        $submissionid = $workshopgenerator->create_submission($this->workshop->id, $this->anotherstudentg1->id, $submission);
+
+        $this->setUser($this->student);
+        $result = mod_workshop_external::get_submissions($this->workshop->id);
+        $result = external_api::clean_returnvalue(mod_workshop_external::get_submissions_returns(), $result);
+        // We should get just our submission.
+        $this->assertCount(1, $result['submissions']);
+        $this->assertEquals(1, $result['totalcount']);
+        $this->assertEquals($submissionid, $result['submissions'][0]['id']);
+
+        // Check with group restrictions.
+        $this->setUser($this->anotherstudentg2);
+        $result = mod_workshop_external::get_submissions($this->workshop->id);
+        $result = external_api::clean_returnvalue(mod_workshop_external::get_submissions_returns(), $result);
+        $this->assertCount(0, $result['submissions']);  // I can't see other users in separated groups.
+        $this->assertEquals(0, $result['totalcount']);
+    }
+
+    /**
+     * Test test_get_submissions_from_student_with_feedback_from_teacher.
+     */
+    public function test_get_submissions_from_student_with_feedback_from_teacher() {
+        global $DB;
+
+        // Create a couple of submissions with files.
+        $workshopgenerator = $this->getDataGenerator()->get_plugin_generator('mod_workshop');
+        $submissionid = $workshopgenerator->create_submission($this->workshop->id, $this->student->id);
+        // Create teacher feedback for submission.
+        $record = new stdclass();
+        $record->id = $submissionid;
+        $record->gradeover = 9;
+        $record->gradeoverby = $this->teacher->id;
+        $record->feedbackauthor = 'Hey';
+        $record->feedbackauthorformat = FORMAT_MOODLE;
+        $record->published = 1;
+        $DB->update_record('workshop_submissions', $record);
+
+        // Remove teacher caps.
+        assign_capability('mod/workshop:viewallsubmissions', CAP_PROHIBIT, $this->teacher->id, $this->context->id);
+        // Empty all the caches that may be affected  by this change.
+        accesslib_clear_all_caches_for_unit_testing();
+        course_modinfo::clear_instance_cache();
+
+        $this->setUser($this->teacher);
+        $result = mod_workshop_external::get_submissions($this->workshop->id, $this->student->id);
+        $result = external_api::clean_returnvalue(mod_workshop_external::get_submissions_returns(), $result);
+        // We should get just our submission.
+        $this->assertEquals(1, $result['totalcount']);
+        $this->assertEquals($submissionid, $result['submissions'][0]['id']);
+    }
+
+    /**
+     * Test test_get_submissions_from_students_as_teacher.
+     */
+    public function test_get_submissions_from_students_as_teacher() {
+        global $DB;
+
+        // Create a couple of submissions with files.
+        $workshopgenerator = $this->getDataGenerator()->get_plugin_generator('mod_workshop');
+        $submissionid1 = $workshopgenerator->create_submission($this->workshop->id, $this->student->id);
+        $submissionid2 = $workshopgenerator->create_submission($this->workshop->id, $this->anotherstudentg1->id);
+        $submissionid3 = $workshopgenerator->create_submission($this->workshop->id, $this->anotherstudentg2->id);
+
+        $this->setUser($this->teacher);
+        $result = mod_workshop_external::get_submissions($this->workshop->id); // Get all.
+        $result = external_api::clean_returnvalue(mod_workshop_external::get_submissions_returns(), $result);
+        $this->assertEquals(3, $result['totalcount']);
+        $this->assertCount(3, $result['submissions']);
+
+        $result = mod_workshop_external::get_submissions($this->workshop->id, 0, 0, 0, 2); // Check pagination.
+        $result = external_api::clean_returnvalue(mod_workshop_external::get_submissions_returns(), $result);
+        $this->assertEquals(3, $result['totalcount']);
+        $this->assertCount(2, $result['submissions']);
+
+        $result = mod_workshop_external::get_submissions($this->workshop->id, 0, $this->group2->id); // Get group 2.
+        $result = external_api::clean_returnvalue(mod_workshop_external::get_submissions_returns(), $result);
+        $this->assertEquals(1, $result['totalcount']);
+        $this->assertCount(1, $result['submissions']);
+        $this->assertEquals($submissionid3, $result['submissions'][0]['id']);
+
+        $result = mod_workshop_external::get_submissions($this->workshop->id, $this->anotherstudentg1->id); // Get one.
+        $result = external_api::clean_returnvalue(mod_workshop_external::get_submissions_returns(), $result);
+        $this->assertEquals(1, $result['totalcount']);
+        $this->assertEquals($submissionid2, $result['submissions'][0]['id']);
+    }
 }
index 937d9b4..43d1635 100644 (file)
@@ -24,7 +24,7 @@
 
 defined('MOODLE_INTERNAL') || die();
 
-$plugin->version   = 2017051507;        // The current module version (YYYYMMDDXX)
+$plugin->version   = 2017051508;        // The current module version (YYYYMMDDXX)
 $plugin->requires  = 2017050500;        // Requires this Moodle version.
 $plugin->component = 'mod_workshop';
 $plugin->cron      = 60;                // Give as a chance every minute.