Commit 5f91cbb6 authored by Sara Arjona's avatar Sara Arjona
Browse files

MDL-71135 course: core_course_get_state external method

parent f7b0960d
<?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/>.
namespace core_course\external;
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->libdir . '/externallib.php');
use external_api;
use external_function_parameters;
use external_value;
/**
* Class for exporting a course state.
*
* @package core_course
* @copyright 2021 Ferran Recio <ferran@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 4.0
*/
class get_state extends external_api {
/**
* Webservice parameters.
*
* @return external_function_parameters
*/
public static function execute_parameters(): external_function_parameters {
return new external_function_parameters(
[
'courseid' => new external_value(PARAM_INT, 'course id', VALUE_REQUIRED),
]
);
}
/**
* This method will load all course, sections and cm states needed to initialize the frontend
* course editor module. The state data of every individual course, section and cm is
* build using the specifics "state" output components.
*
* By default, the states are generated by:
* - core_course\output\course_format\state
* - core_course\output\section_format\state
* - core_course\output\cm_format\state
*
* As the other main course outputs, format plugins can override those output components
* to send more information to the frontend course editor. These extended classes should
* be located in format_XXX\output\course_format\state, format_XXX\output\section_format\state
* or format_XXX\output\cm_format\state.
*
* @param int $courseid the course id
* @return string Course state in JSON
*/
public static function execute(int $courseid): string {
global $PAGE, $CFG;
require_once($CFG->dirroot.'/course/lib.php');
$params = external_api::validate_parameters(self::execute_parameters(), [
'courseid' => $courseid,
]);
$courseid = $params['courseid'];
self::validate_context(\context_course::instance($courseid));
$courseformat = course_get_format($courseid);
$modinfo = $courseformat->get_modinfo();
// Get the proper renderer.
$renderer = $courseformat->get_renderer($PAGE);
$result = (object)[
'course' => (object)[],
'section' => [],
'cm' => [],
];
// Load the output class names.
$courseclass = $courseformat->get_output_classname('course_format\state');
$sectionclass = $courseformat->get_output_classname('section_format\state');
$cmclass = $courseformat->get_output_classname('cm_format\state');
// General state.
$coursestate = new $courseclass($courseformat);
$result->course = $coursestate->export_for_template($renderer);
// Sections and course modules state.
$sections = $modinfo->get_section_info_all();
foreach ($sections as $section) {
if (!empty($section->uservisible)) {
// Only return this section data if it's visible by current user on the course page.
$sectionstate = new $sectionclass($courseformat, $section);
$result->section[] = $sectionstate->export_for_template($renderer);
}
}
foreach ($modinfo->cms as $cm) {
if ($cm->is_visible_on_course_page()) {
// Only return this course module data if it's visible by current user on the course page.
$section = $sections[$cm->sectionnum];
$cmstate = new $cmclass($courseformat, $section, $cm);
$result->cm[] = $cmstate->export_for_template($renderer);
}
}
return json_encode($result);
}
/**
* Webservice returns.
*
* @return external_value
*/
public static function execute_returns(): external_value {
return new external_value(PARAM_RAW, 'Encoded course state JSON');
}
}
<?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/>.
namespace core_course\output\cm_format;
use core_course\course_format;
use section_info;
use cm_info;
use renderable;
use stdClass;
/**
* Contains the ajax update course module structure.
*
* @package core_course
* @copyright 2021 Ferran Recio <ferran@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class state implements renderable {
/** @var course_format the course format class */
protected $format;
/** @var section_info the course section class */
protected $section;
/** @var bool if cmitem HTML content must be exported as well */
protected $exportcontent;
/** @var cm_info the course module to display */
protected $cm;
/**
* Constructor.
*
* @param course_format $format the course format
* @param section_info $section the section data
* @param cm_info $cm the course module data
* @param bool $exportcontent = false if pre-rendered cmitem must be exported.
*/
public function __construct(course_format $format, section_info $section, cm_info $cm, bool $exportcontent = false) {
$this->format = $format;
$this->section = $section;
$this->cm = $cm;
$this->exportcontent = $exportcontent;
}
/**
* Export this data so it can be used as state object in the course editor.
*
* @param renderer_base $output typically, the renderer that's calling this function
* @return stdClass data context for a mustache template
*/
public function export_for_template(\renderer_base $output): stdClass {
$format = $this->format;
$section = $this->section;
$cm = $this->cm;
$data = (object)[
'id' => $cm->id,
'name' => $cm->name,
'visible' => !empty($cm->visible),
];
if ($this->exportcontent) {
$data->content = $output->course_section_updated_cm_item($format, $section, $cm);
}
return $data;
}
}
<?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/>.
namespace core_course\output\course_format;
use core_course\course_format;
use renderable;
use stdClass;
/**
* Contains the ajax update course structure.
*
* @package core_course
* @copyright 2021 Ferran Recio <ferran@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class state implements renderable {
/** @var course_format the course format class */
protected $format;
/**
* Constructor.
*
* @param course_format $format the course format
*/
public function __construct(course_format $format) {
$this->format = $format;
}
/**
* Export this data so it can be used as state object in the course editor.
*
* @param renderer_base $output typically, the renderer that's calling this function
* @return stdClass data context for a mustache template
*/
public function export_for_template(\renderer_base $output): stdClass {
$format = $this->format;
$course = $format->get_course();
$modinfo = $this->format->get_modinfo();
$data = (object)[
'id' => $course->id,
'numsections' => $format->get_last_section_number(),
'sectionlist' => [],
'editmode' => $format->show_editor(),
];
$sections = $modinfo->get_section_info_all();
foreach ($sections as $section) {
if (!empty($section->uservisible)) {
$data->sectionlist[] = $section->id;
}
}
return $data;
}
}
<?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/>.
namespace core_course\output\section_format;
use core_course\course_format;
use section_info;
use renderable;
use stdClass;
/**
* Contains the ajax update section structure.
*
* @package core_course
* @copyright 2021 Ferran Recio <ferran@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class state implements renderable {
/** @var course_format the course format class */
protected $format;
/** @var section_info the course section class */
protected $section;
/**
* Constructor.
*
* @param course_format $format the course format
* @param section_info $section the section info
*/
public function __construct(course_format $format, section_info $section) {
$this->format = $format;
$this->section = $section;
}
/**
* Export this data so it can be used as state object in the course editor.
*
* @param renderer_base $output typically, the renderer that's calling this function
* @return array data context for a mustache template
*/
public function export_for_template(\renderer_base $output): stdClass {
$format = $this->format;
$section = $this->section;
$modinfo = $format->get_modinfo();
$data = (object)[
'id' => $section->id,
'section' => $section->section,
'title' => $format->get_section_name($section),
'cmlist' => [],
'visible' => !empty($section->visible),
];
if (empty($modinfo->sections[$section->section])) {
return $data;
}
foreach ($modinfo->sections[$section->section] as $modnumber) {
$mod = $modinfo->cms[$modnumber];
if ($mod->is_visible_on_course_page()) {
$data->cmlist[] = $mod->id;
}
}
return $data;
}
}
<?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/>.
namespace core_course\external;
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->dirroot . '/webservice/tests/helpers.php');
use external_api;
/**
* Tests for the get_state class.
*
* @package core_course
* @category test
* @copyright 2021 Sara Arjona (sara@moodle.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @coversDefaultClass \core_course\external\get_state
*/
class get_state_test extends \externallib_advanced_testcase {
/** @var array Sections in the testing course. */
private $sections;
/** @var array Activities in the testing course. */
private $activities;
/**
* Setup to ensure that fixtures are loaded.
*/
public static function setupBeforeClass(): void {
global $CFG;
require_once($CFG->dirroot . '/course/lib.php');
require_once($CFG->dirroot . '/course/tests/fixtures/format_theunittest.php');
require_once($CFG->dirroot . '/course/tests/fixtures/format_theunittest_output_course_format_state.php');
}
/**
* Setup testcase.
*/
public function setUp(): void {
$this->resetAfterTest();
$this->sections = [];
$this->activities = [];
}
/**
* Test tearDown.
*/
public function tearDown(): void {
unset($this->sections);
unset($this->activities);
}
/**
* Test the behaviour of get_state::execute().
*
* @dataProvider get_state_provider
* @covers ::execute
*
* @param string $role The role of the user that will execute the method.
* @param string $format The course format of the course where the method will be executed.
* @param string|null $expectedexception If this call will raise an exception, this is its name.
*/
public function test_get_state(string $role, string $format = 'topics', ?string $expectedexception = null): void {
$this->resetAfterTest();
// Create a course.
$numsections = 6;
$visiblesections = $numsections + 1; // Include topic 0.
$course = $this->getDataGenerator()->create_course(['numsections' => $numsections, 'format' => $format]);
$hiddensections = [4, 6];
foreach ($hiddensections as $section) {
set_section_visible($course->id, $section, 0);
}
// Create and enrol user.
$isadmin = ($role == 'admin');
$canedit = $isadmin || ($role == 'editingteacher');
if ($isadmin) {
$this->setAdminUser();
} else {
if (!$canedit) {
// User won't see the hidden sections. Remove them from the total.
$visiblesections = $visiblesections - count($hiddensections);
}
$user = $this->getDataGenerator()->create_user();
if ($role != 'unenroled') {
$this->getDataGenerator()->enrol_user($user->id, $course->id, $role);
}
$this->setUser($user);
}
// Add some activities to the course.
$this->create_activity($course->id, 'page', 1, true, $canedit);
$this->create_activity($course->id, 'forum', 1, true, $canedit);
$this->create_activity($course->id, 'book', 1, false, $canedit);
$this->create_activity($course->id, 'assign', 2, false, $canedit);
$this->create_activity($course->id, 'glossary', 4, true, $canedit);
$this->create_activity($course->id, 'label', 5, false, $canedit);
$this->create_activity($course->id, 'feedback', 5, true, $canedit);
if ($expectedexception) {
$this->expectException($expectedexception);
}
// Get course state.
$result = get_state::execute($course->id);
$result = external_api::clean_returnvalue(get_state::execute_returns(), $result);
$result = json_decode($result);
if ($format == 'social' || $format == 'theunittest') {
// These course format's hasn't the renderer file, so a debugging message will be displayed.
$this->assertDebuggingCalled();
}
// Check course information.
$this->assertEquals($numsections, $result->course->numsections);
$this->assertCount($visiblesections, $result->section);
$this->assertCount(count($this->activities), $result->cm);
$this->assertCount(count($result->course->sectionlist), $result->section);
if ($format == 'theunittest') {
$this->assertTrue(property_exists($result->course, 'newfancyelement'));
} else {
$this->assertFalse(property_exists($result->course, 'newfancyelement'));
}
// Check sections information.
foreach ($result->section as $section) {
if (in_array($section->section, $hiddensections)) {
$this->assertFalse($section->visible);
} else {
$this->assertTrue($section->visible);
}
// Check section is defined in course->sectionlist.
$this->assertContains($section->id, $result->course->sectionlist);
// Check course modules list for this section is the expected.
if (array_key_exists($section->section, $this->sections)) {
$this->assertEquals($this->sections[$section->section], $section->cmlist);
}
}
// Check course modules information.
foreach ($result->cm as $cm) {
$this->assertEquals($this->activities[$cm->id]->name, $cm->name);
$this->assertEquals((bool) $this->activities[$cm->id]->visible, $cm->visible);
}
}
/**
* Data provider for test_get_state().
*
* @return array
*/
public function get_state_provider(): array {
return [
// ROLES. Testing behaviour depending on the user role calling the method.
'Admin user should work' => [
'role' => 'admin',
],
'Editing teacher should work' => [
'role' => 'editingteacher',
],
'Student should work' => [
'role' => 'student',
],
'Unenroled user should raise an exception' => [
'role' => 'unenroled',
'format' => 'topics',
'expectedexception' => 'moodle_exception',
],
// COURSEFORMAT. Test behaviour depending on course formats.
'Single activity format should work (admin)' => [
'role' => 'admin',
'format' => 'singleactivity',
],
'Social format should work (admin)' => [
'role' => 'admin',
'format' => 'social',
],
'Weeks format should work (admin)' => [
'role' => 'admin',
'format' => 'weeks',
],
'The unit tests format should work (admin)' => [
'role' => 'admin',
'format' => 'theunittest',
],
'Single activity format should work (student)' => [
'role' => 'student',
'format' => 'singleactivity',
],
'Social format should work (student)' => [
'role' => 'student',
'format' => 'social',
],
'Weeks format should work (student)' => [
'role' => 'student',
'format' => 'weeks',
],
'The unit tests format should work (student)' => [
'role' => 'student',
'format' => 'theunittest',
],
'Single activity format should raise an exception (unenroled)' => [
'role' => 'unenroled',
'format' => 'singleactivity',
'expectedexception' => 'moodle_exception',
],
'Social format should raise an exception (unenroled)' => [
'role' => 'unenroled',
'format' => 'social',
'expectedexception' => 'moodle_exception',
],
'Weeks format should raise an exception (unenroled)' => [
'role' => 'unenroled',
'format' => 'weeks',
'expectedexception' => 'moodle_exception',
],
'The unit tests format should raise an exception (unenroled)' => [
'role' => 'unenroled',
'format' => 'theunittest',
'expectedexception' => 'moodle_exception',
],
];