2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
21 * @package core_course
23 * @copyright 2009 Petr Skodak
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') ||
die;
29 use core_course\external\course_summary_exporter
;
30 use core_external\external_api
;
31 use core_external\external_description
;
32 use core_external\external_files
;
33 use core_external\external_format_value
;
34 use core_external\external_function_parameters
;
35 use core_external\external_multiple_structure
;
36 use core_external\external_single_structure
;
37 use core_external\external_value
;
38 use core_external\external_warnings
;
39 use core_external\util
;
40 require_once(__DIR__
. "/lib.php");
43 * Course external functions
45 * @package core_course
47 * @copyright 2011 Jerome Mouneyrac
48 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
51 class core_course_external
extends external_api
{
54 * Returns description of method parameters
56 * @return external_function_parameters
57 * @since Moodle 2.9 Options available
60 public static function get_course_contents_parameters() {
61 return new external_function_parameters(
62 array('courseid' => new external_value(PARAM_INT
, 'course id'),
63 'options' => new external_multiple_structure (
64 new external_single_structure(
66 'name' => new external_value(PARAM_ALPHANUM
,
67 'The expected keys (value format) are:
68 excludemodules (bool) Do not return modules, return only the sections structure
69 excludecontents (bool) Do not return module contents (i.e: files inside a resource)
70 includestealthmodules (bool) Return stealth modules for students in a special
72 sectionid (int) Return only this section
73 sectionnumber (int) Return only this section with number (order)
74 cmid (int) Return only this module information (among the whole sections structure)
75 modname (string) Return only modules with this name "label, forum, etc..."
76 modid (int) Return only the module with this id (to be used with modname'),
77 'value' => new external_value(PARAM_RAW
, 'the value of the option,
78 this param is personaly validated in the external function.')
80 ), 'Options, used since Moodle 2.9', VALUE_DEFAULT
, array())
88 * @param int $courseid course id
89 * @param array $options Options for filtering the results, used since Moodle 2.9
91 * @since Moodle 2.9 Options available
94 public static function get_course_contents($courseid, $options = array()) {
95 global $CFG, $DB, $USER, $PAGE;
96 require_once($CFG->dirroot
. "/course/lib.php");
97 require_once($CFG->libdir
. '/completionlib.php');
100 $params = self
::validate_parameters(self
::get_course_contents_parameters(),
101 array('courseid' => $courseid, 'options' => $options));
104 if (!empty($params['options'])) {
106 foreach ($params['options'] as $option) {
107 $name = trim($option['name']);
108 // Avoid duplicated options.
109 if (!isset($filters[$name])) {
111 case 'excludemodules':
112 case 'excludecontents':
113 case 'includestealthmodules':
114 $value = clean_param($option['value'], PARAM_BOOL
);
115 $filters[$name] = $value;
118 case 'sectionnumber':
121 $value = clean_param($option['value'], PARAM_INT
);
122 if (is_numeric($value)) {
123 $filters[$name] = $value;
125 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
129 $value = clean_param($option['value'], PARAM_PLUGIN
);
131 $filters[$name] = $value;
133 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
137 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
143 //retrieve the course
144 $course = $DB->get_record('course', array('id' => $params['courseid']), '*', MUST_EXIST
);
146 // now security checks
147 $context = context_course
::instance($course->id
, IGNORE_MISSING
);
149 self
::validate_context($context);
150 } catch (Exception
$e) {
151 $exceptionparam = new stdClass();
152 $exceptionparam->message
= $e->getMessage();
153 $exceptionparam->courseid
= $course->id
;
154 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
157 $canupdatecourse = has_capability('moodle/course:update', $context);
159 //create return value
160 $coursecontents = array();
162 if ($canupdatecourse or $course->visible
163 or has_capability('moodle/course:viewhiddencourses', $context)) {
166 $modinfo = get_fast_modinfo($course);
167 $sections = $modinfo->get_section_info_all();
168 $courseformat = course_get_format($course);
169 $coursenumsections = $courseformat->get_last_section_number();
170 $stealthmodules = array(); // Array to keep all the modules available but not visible in a course section/topic.
172 $completioninfo = new completion_info($course);
174 //for each sections (first displayed to last displayed)
175 $modinfosections = $modinfo->get_sections();
176 foreach ($sections as $key => $section) {
178 // This becomes true when we are filtering and we found the value to filter with.
179 $sectionfound = false;
181 // Filter by section id.
182 if (!empty($filters['sectionid'])) {
183 if ($section->id
!= $filters['sectionid']) {
186 $sectionfound = true;
190 // Filter by section number. Note that 0 is a valid section number.
191 if (isset($filters['sectionnumber'])) {
192 if ($key != $filters['sectionnumber']) {
195 $sectionfound = true;
199 // reset $sectioncontents
200 $sectionvalues = array();
201 $sectionvalues['id'] = $section->id
;
202 $sectionvalues['name'] = get_section_name($course, $section);
203 $sectionvalues['visible'] = $section->visible
;
205 $options = (object) array('noclean' => true);
206 list($sectionvalues['summary'], $sectionvalues['summaryformat']) =
207 \core_external\util
::format_text($section->summary
, $section->summaryformat
,
208 $context, 'course', 'section', $section->id
, $options);
209 $sectionvalues['section'] = $section->section
;
210 $sectionvalues['hiddenbynumsections'] = $section->section
> $coursenumsections ?
1 : 0;
211 $sectionvalues['uservisible'] = $section->uservisible
;
212 if (!empty($section->availableinfo
)) {
213 $sectionvalues['availabilityinfo'] = \core_availability\info
::format_info($section->availableinfo
, $course);
216 $sectioncontents = array();
218 // For each module of the section.
219 if (empty($filters['excludemodules']) and !empty($modinfosections[$section->section
])) {
220 foreach ($modinfosections[$section->section
] as $cmid) {
221 $cm = $modinfo->cms
[$cmid];
222 $cminfo = cm_info
::create($cm);
223 $activitydates = \core\activity_dates
::get_dates_for_module($cminfo, $USER->id
);
225 // Stop here if the module is not visible to the user on the course main page:
226 // The user can't access the module and the user can't view the module on the course page.
227 if (!$cm->uservisible
&& !$cm->is_visible_on_course_page()) {
231 // This becomes true when we are filtering and we found the value to filter with.
235 if (!empty($filters['cmid'])) {
236 if ($cmid != $filters['cmid']) {
243 // Filter by module name and id.
244 if (!empty($filters['modname'])) {
245 if ($cm->modname
!= $filters['modname']) {
247 } else if (!empty($filters['modid'])) {
248 if ($cm->instance
!= $filters['modid']) {
251 // Note that if we are only filtering by modname we don't break the loop.
259 $modcontext = context_module
::instance($cm->id
);
261 //common info (for people being able to see the module or availability dates)
262 $module['id'] = $cm->id
;
263 $module['name'] = \core_external\util
::format_string($cm->name
, $modcontext);
264 $module['instance'] = $cm->instance
;
265 $module['contextid'] = $modcontext->id
;
266 $module['modname'] = (string) $cm->modname
;
267 $module['modplural'] = (string) $cm->modplural
;
268 $module['modicon'] = $cm->get_icon_url()->out(false);
269 $module['purpose'] = plugin_supports('mod', $cm->modname
, FEATURE_MOD_PURPOSE
, MOD_PURPOSE_OTHER
);
270 $module['indent'] = $cm->indent
;
271 $module['onclick'] = $cm->onclick
;
272 $module['afterlink'] = $cm->afterlink
;
273 $activitybadgedata = $cm->get_activitybadge();
274 if (!empty($activitybadgedata)) {
275 $module['activitybadge'] = $activitybadgedata;
277 $module['customdata'] = json_encode($cm->customdata
);
278 $module['completion'] = $cm->completion
;
279 $module['downloadcontent'] = $cm->downloadcontent
;
280 $module['noviewlink'] = plugin_supports('mod', $cm->modname
, FEATURE_NO_VIEW_LINK
, false);
281 $module['dates'] = $activitydates;
282 $module['groupmode'] = $cm->groupmode
;
284 // Check module completion.
285 $completion = $completioninfo->is_enabled($cm);
286 if ($completion != COMPLETION_DISABLED
) {
287 $exporter = new \core_completion\external\
completion_info_exporter($course, $cm, $USER->id
);
288 $renderer = $PAGE->get_renderer('core');
289 $modulecompletiondata = (array)$exporter->export($renderer);
290 $module['completiondata'] = $modulecompletiondata;
293 if (!empty($cm->showdescription
) or $module['noviewlink']) {
294 // We want to use the external format. However from reading get_formatted_content(), $cm->content format is always FORMAT_HTML.
295 $options = array('noclean' => true);
296 list($module['description'], $descriptionformat) = \core_external\util
::format_text($cm->content
,
297 FORMAT_HTML
, $modcontext, $cm->modname
, 'intro', $cm->id
, $options);
302 if ($url) { //labels don't have url
303 $module['url'] = $url->out(false);
306 $canviewhidden = has_capability('moodle/course:viewhiddenactivities',
307 context_module
::instance($cm->id
));
308 //user that can view hidden module should know about the visibility
309 $module['visible'] = $cm->visible
;
310 $module['visibleoncoursepage'] = $cm->visibleoncoursepage
;
311 $module['uservisible'] = $cm->uservisible
;
312 if (!empty($cm->availableinfo
)) {
313 $module['availabilityinfo'] = \core_availability\info
::format_info($cm->availableinfo
, $course);
316 // Availability date (also send to user who can see hidden module).
317 if ($CFG->enableavailability
&& ($canviewhidden ||
$canupdatecourse)) {
318 $module['availability'] = $cm->availability
;
321 // Return contents only if the user can access to the module.
322 if ($cm->uservisible
) {
323 $baseurl = 'webservice/pluginfile.php';
325 // Call $modulename_export_contents (each module callback take care about checking the capabilities).
326 require_once($CFG->dirroot
. '/mod/' . $cm->modname
. '/lib.php');
327 $getcontentfunction = $cm->modname
.'_export_contents';
328 if (function_exists($getcontentfunction)) {
329 $contents = $getcontentfunction($cm, $baseurl);
330 $module['contentsinfo'] = array(
331 'filescount' => count($contents),
334 'mimetypes' => array(),
336 foreach ($contents as $content) {
337 // Check repository file (only main file).
338 if (!isset($module['contentsinfo']['repositorytype'])) {
339 $module['contentsinfo']['repositorytype'] =
340 isset($content['repositorytype']) ?
$content['repositorytype'] : '';
342 if (isset($content['filesize'])) {
343 $module['contentsinfo']['filessize'] +
= $content['filesize'];
345 if (isset($content['timemodified']) &&
346 ($content['timemodified'] > $module['contentsinfo']['lastmodified'])) {
348 $module['contentsinfo']['lastmodified'] = $content['timemodified'];
350 if (isset($content['mimetype'])) {
351 $module['contentsinfo']['mimetypes'][$content['mimetype']] = $content['mimetype'];
355 if (empty($filters['excludecontents']) and !empty($contents)) {
356 $module['contents'] = $contents;
358 $module['contents'] = array();
363 // Assign result to $sectioncontents, there is an exception,
364 // stealth activities in non-visible sections for students go to a special section.
365 if (!empty($filters['includestealthmodules']) && !$section->uservisible
&& $cm->is_stealth()) {
366 $stealthmodules[] = $module;
368 $sectioncontents[] = $module;
371 // If we just did a filtering, break the loop.
378 $sectionvalues['modules'] = $sectioncontents;
380 // assign result to $coursecontents
381 $coursecontents[$key] = $sectionvalues;
383 // Break the loop if we are filtering.
389 // Now that we have iterated over all the sections and activities, check the visibility.
390 // We didn't this before to be able to retrieve stealth activities.
391 foreach ($coursecontents as $sectionnumber => $sectioncontents) {
392 $section = $sections[$sectionnumber];
394 if (!$courseformat->is_section_visible($section)) {
395 unset($coursecontents[$sectionnumber]);
399 // Remove section and modules information if the section is not visible for the user.
400 if (!$section->uservisible
) {
401 $coursecontents[$sectionnumber]['modules'] = array();
402 // Remove summary information if the section is completely hidden only,
403 // even if the section is not user visible, the summary is always displayed among the availability information.
404 if (!$section->visible
) {
405 $coursecontents[$sectionnumber]['summary'] = '';
410 // Include stealth modules in special section (without any info).
411 if (!empty($stealthmodules)) {
412 $coursecontents[] = array(
416 'summaryformat' => FORMAT_MOODLE
,
417 'modules' => $stealthmodules
422 return $coursecontents;
426 * Returns description of method result value
428 * @return \core_external\external_description
431 public static function get_course_contents_returns() {
432 $completiondefinition = \core_completion\external\completion_info_exporter
::get_read_structure(VALUE_DEFAULT
, []);
434 return new external_multiple_structure(
435 new external_single_structure(
437 'id' => new external_value(PARAM_INT
, 'Section ID'),
438 'name' => new external_value(PARAM_RAW
, 'Section name'),
439 'visible' => new external_value(PARAM_INT
, 'is the section visible', VALUE_OPTIONAL
),
440 'summary' => new external_value(PARAM_RAW
, 'Section description'),
441 'summaryformat' => new external_format_value('summary'),
442 'section' => new external_value(PARAM_INT
, 'Section number inside the course', VALUE_OPTIONAL
),
443 'hiddenbynumsections' => new external_value(PARAM_INT
, 'Whether is a section hidden in the course format',
445 'uservisible' => new external_value(PARAM_BOOL
, 'Is the section visible for the user?', VALUE_OPTIONAL
),
446 'availabilityinfo' => new external_value(PARAM_RAW
, 'Availability information.', VALUE_OPTIONAL
),
447 'modules' => new external_multiple_structure(
448 new external_single_structure(
450 'id' => new external_value(PARAM_INT
, 'activity id'),
451 'url' => new external_value(PARAM_URL
, 'activity url', VALUE_OPTIONAL
),
452 'name' => new external_value(PARAM_RAW
, 'activity module name'),
453 'instance' => new external_value(PARAM_INT
, 'instance id', VALUE_OPTIONAL
),
454 'contextid' => new external_value(PARAM_INT
, 'Activity context id.', VALUE_OPTIONAL
),
455 'description' => new external_value(PARAM_RAW
, 'activity description', VALUE_OPTIONAL
),
456 'visible' => new external_value(PARAM_INT
, 'is the module visible', VALUE_OPTIONAL
),
457 'uservisible' => new external_value(PARAM_BOOL
, 'Is the module visible for the user?',
459 'availabilityinfo' => new external_value(PARAM_RAW
, 'Availability information.',
461 'visibleoncoursepage' => new external_value(PARAM_INT
, 'is the module visible on course page',
463 'modicon' => new external_value(PARAM_URL
, 'activity icon url'),
464 'modname' => new external_value(PARAM_PLUGIN
, 'activity module type'),
465 'purpose' => new external_value(PARAM_ALPHA
, 'the module purpose'),
466 'modplural' => new external_value(PARAM_TEXT
, 'activity module plural name'),
467 'availability' => new external_value(PARAM_RAW
, 'module availability settings', VALUE_OPTIONAL
),
468 'indent' => new external_value(PARAM_INT
, 'number of identation in the site'),
469 'onclick' => new external_value(PARAM_RAW
, 'Onclick action.', VALUE_OPTIONAL
),
470 'afterlink' => new external_value(PARAM_RAW
, 'After link info to be displayed.',
472 'activitybadge' => self
::get_activitybadge_structure(),
473 'customdata' => new external_value(PARAM_RAW
, 'Custom data (JSON encoded).', VALUE_OPTIONAL
),
474 'noviewlink' => new external_value(PARAM_BOOL
, 'Whether the module has no view page',
476 'completion' => new external_value(PARAM_INT
, 'Type of completion tracking:
477 0 means none, 1 manual, 2 automatic.', VALUE_OPTIONAL
),
478 'completiondata' => $completiondefinition,
479 'downloadcontent' => new external_value(PARAM_INT
, 'The download content value', VALUE_OPTIONAL
),
480 'dates' => new external_multiple_structure(
481 new external_single_structure(
483 'label' => new external_value(PARAM_TEXT
, 'date label'),
484 'timestamp' => new external_value(PARAM_INT
, 'date timestamp'),
485 'relativeto' => new external_value(PARAM_INT
, 'relative date timestamp',
487 'dataid' => new external_value(PARAM_NOTAGS
, 'cm data id', VALUE_OPTIONAL
),
494 'groupmode' => new external_value(PARAM_INT
, 'Group mode value', VALUE_OPTIONAL
),
495 'contents' => new external_multiple_structure(
496 new external_single_structure(
499 'type'=> new external_value(PARAM_TEXT
, 'a file or a folder or external link'),
500 'filename'=> new external_value(PARAM_FILE
, 'filename'),
501 'filepath'=> new external_value(PARAM_PATH
, 'filepath'),
502 'filesize'=> new external_value(PARAM_INT
, 'filesize'),
503 'fileurl' => new external_value(PARAM_URL
, 'downloadable file url', VALUE_OPTIONAL
),
504 'content' => new external_value(PARAM_RAW
, 'Raw content, will be used when type is content', VALUE_OPTIONAL
),
505 'timecreated' => new external_value(PARAM_INT
, 'Time created'),
506 'timemodified' => new external_value(PARAM_INT
, 'Time modified'),
507 'sortorder' => new external_value(PARAM_INT
, 'Content sort order'),
508 'mimetype' => new external_value(PARAM_RAW
, 'File mime type.', VALUE_OPTIONAL
),
509 'isexternalfile' => new external_value(PARAM_BOOL
, 'Whether is an external file.',
511 'repositorytype' => new external_value(PARAM_PLUGIN
, 'The repository type for external files.',
514 // copyright related info
515 'userid' => new external_value(PARAM_INT
, 'User who added this content to moodle'),
516 'author' => new external_value(PARAM_TEXT
, 'Content owner'),
517 'license' => new external_value(PARAM_TEXT
, 'Content license'),
518 'tags' => new external_multiple_structure(
519 \core_tag\external\tag_item_exporter
::get_read_structure(), 'Tags',
523 ), 'Course contents', VALUE_DEFAULT
, array()
525 'contentsinfo' => new external_single_structure(
527 'filescount' => new external_value(PARAM_INT
, 'Total number of files.'),
528 'filessize' => new external_value(PARAM_INT
, 'Total files size.'),
529 'lastmodified' => new external_value(PARAM_INT
, 'Last time files were modified.'),
530 'mimetypes' => new external_multiple_structure(
531 new external_value(PARAM_RAW
, 'File mime type.'),
534 'repositorytype' => new external_value(PARAM_PLUGIN
, 'The repository type for
535 the main file.', VALUE_OPTIONAL
),
536 ), 'Contents summary information.', VALUE_OPTIONAL
547 * Returns description of activitybadge data.
549 * @return external_description
551 protected static function get_activitybadge_structure(): external_description
{
552 return new external_single_structure(
554 'badgecontent' => new external_value(
556 'The content to be displayed in the activity badge',
559 'badgestyle' => new external_value(
561 'The style for the activity badge',
564 'badgeurl' => new external_value(
566 'An optional URL to redirect the user when the activity badge is clicked',
569 'badgeelementid' => new external_value(
571 'An optional id in case the module wants to add some code for the activity badge',
574 'badgeextraattributes' => new external_multiple_structure(
575 new external_single_structure(
577 'name' => new external_value(
579 'The attribute name',
582 'value' => new external_value(
584 'The attribute value',
588 'Each of the attribute names and values',
591 'An optional array of extra HTML attributes to add to the badge element',
595 'Activity badge to display near the name',
601 * Returns description of method parameters
603 * @return external_function_parameters
606 public static function get_courses_parameters() {
607 return new external_function_parameters(
608 array('options' => new external_single_structure(
609 array('ids' => new external_multiple_structure(
610 new external_value(PARAM_INT
, 'Course id')
611 , 'List of course id. If empty return all courses
612 except front page course.',
614 ), 'options - operator OR is used', VALUE_DEFAULT
, array())
622 * @param array $options It contains an array (list of ids)
626 public static function get_courses($options = array()) {
628 require_once($CFG->dirroot
. "/course/lib.php");
631 $params = self
::validate_parameters(self
::get_courses_parameters(),
632 array('options' => $options));
635 if (!array_key_exists('ids', $params['options'])
636 or empty($params['options']['ids'])) {
637 $courses = $DB->get_records('course');
639 $courses = $DB->get_records_list('course', 'id', $params['options']['ids']);
642 //create return value
643 $coursesinfo = array();
644 foreach ($courses as $course) {
646 // now security checks
647 $context = context_course
::instance($course->id
, IGNORE_MISSING
);
648 $courseformatoptions = course_get_format($course)->get_format_options();
650 self
::validate_context($context);
651 } catch (Exception
$e) {
652 $exceptionparam = new stdClass();
653 $exceptionparam->message
= $e->getMessage();
654 $exceptionparam->courseid
= $course->id
;
655 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
657 if ($course->id
!= SITEID
) {
658 require_capability('moodle/course:view', $context);
661 $courseinfo = array();
662 $courseinfo['id'] = $course->id
;
663 $courseinfo['fullname'] = \core_external\util
::format_string($course->fullname
, $context);
664 $courseinfo['shortname'] = \core_external\util
::format_string($course->shortname
, $context);
665 $courseinfo['displayname'] = \core_external\util
::format_string(get_course_display_name_for_list($course), $context);
666 $courseinfo['categoryid'] = $course->category
;
667 list($courseinfo['summary'], $courseinfo['summaryformat']) =
668 \core_external\util
::format_text($course->summary
, $course->summaryformat
, $context, 'course', 'summary', 0);
669 $courseinfo['format'] = $course->format
;
670 $courseinfo['startdate'] = $course->startdate
;
671 $courseinfo['enddate'] = $course->enddate
;
672 $courseinfo['showactivitydates'] = $course->showactivitydates
;
673 $courseinfo['showcompletionconditions'] = $course->showcompletionconditions
;
674 if (array_key_exists('numsections', $courseformatoptions)) {
675 // For backward-compartibility
676 $courseinfo['numsections'] = $courseformatoptions['numsections'];
678 $courseinfo['pdfexportfont'] = $course->pdfexportfont
;
680 $handler = core_course\customfield\course_handler
::create();
681 if ($customfields = $handler->export_instance_data($course->id
)) {
682 $courseinfo['customfields'] = [];
683 foreach ($customfields as $data) {
684 $courseinfo['customfields'][] = [
685 'type' => $data->get_type(),
686 'value' => $data->get_value(),
687 'valueraw' => $data->get_data_controller()->get_value(),
688 'name' => $data->get_name(),
689 'shortname' => $data->get_shortname()
694 //some field should be returned only if the user has update permission
695 $courseadmin = has_capability('moodle/course:update', $context);
697 $courseinfo['categorysortorder'] = $course->sortorder
;
698 $courseinfo['idnumber'] = $course->idnumber
;
699 $courseinfo['showgrades'] = $course->showgrades
;
700 $courseinfo['showreports'] = $course->showreports
;
701 $courseinfo['newsitems'] = $course->newsitems
;
702 $courseinfo['visible'] = $course->visible
;
703 $courseinfo['maxbytes'] = $course->maxbytes
;
704 if (array_key_exists('hiddensections', $courseformatoptions)) {
705 // For backward-compartibility
706 $courseinfo['hiddensections'] = $courseformatoptions['hiddensections'];
708 // Return numsections for backward-compatibility with clients who expect it.
709 $courseinfo['numsections'] = course_get_format($course)->get_last_section_number();
710 $courseinfo['groupmode'] = $course->groupmode
;
711 $courseinfo['groupmodeforce'] = $course->groupmodeforce
;
712 $courseinfo['defaultgroupingid'] = $course->defaultgroupingid
;
713 $courseinfo['lang'] = clean_param($course->lang
, PARAM_LANG
);
714 $courseinfo['timecreated'] = $course->timecreated
;
715 $courseinfo['timemodified'] = $course->timemodified
;
716 $courseinfo['forcetheme'] = clean_param($course->theme
, PARAM_THEME
);
717 $courseinfo['enablecompletion'] = $course->enablecompletion
;
718 $courseinfo['completionnotify'] = $course->completionnotify
;
719 $courseinfo['courseformatoptions'] = array();
720 foreach ($courseformatoptions as $key => $value) {
721 $courseinfo['courseformatoptions'][] = array(
728 if ($courseadmin or $course->visible
729 or has_capability('moodle/course:viewhiddencourses', $context)) {
730 $coursesinfo[] = $courseinfo;
738 * Returns description of method result value
740 * @return \core_external\external_description
743 public static function get_courses_returns() {
744 return new external_multiple_structure(
745 new external_single_structure(
747 'id' => new external_value(PARAM_INT
, 'course id'),
748 'shortname' => new external_value(PARAM_RAW
, 'course short name'),
749 'categoryid' => new external_value(PARAM_INT
, 'category id'),
750 'categorysortorder' => new external_value(PARAM_INT
,
751 'sort order into the category', VALUE_OPTIONAL
),
752 'fullname' => new external_value(PARAM_RAW
, 'full name'),
753 'displayname' => new external_value(PARAM_RAW
, 'course display name'),
754 'idnumber' => new external_value(PARAM_RAW
, 'id number', VALUE_OPTIONAL
),
755 'summary' => new external_value(PARAM_RAW
, 'summary'),
756 'summaryformat' => new external_format_value('summary'),
757 'format' => new external_value(PARAM_PLUGIN
,
758 'course format: weeks, topics, social, site,..'),
759 'showgrades' => new external_value(PARAM_INT
,
760 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL
),
761 'newsitems' => new external_value(PARAM_INT
,
762 'number of recent items appearing on the course page', VALUE_OPTIONAL
),
763 'startdate' => new external_value(PARAM_INT
,
764 'timestamp when the course start'),
765 'enddate' => new external_value(PARAM_INT
,
766 'timestamp when the course end'),
767 'numsections' => new external_value(PARAM_INT
,
768 '(deprecated, use courseformatoptions) number of weeks/topics',
770 'maxbytes' => new external_value(PARAM_INT
,
771 'largest size of file that can be uploaded into the course',
773 'showreports' => new external_value(PARAM_INT
,
774 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL
),
775 'visible' => new external_value(PARAM_INT
,
776 '1: available to student, 0:not available', VALUE_OPTIONAL
),
777 'hiddensections' => new external_value(PARAM_INT
,
778 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
780 'groupmode' => new external_value(PARAM_INT
, 'no group, separate, visible',
782 'groupmodeforce' => new external_value(PARAM_INT
, '1: yes, 0: no',
784 'defaultgroupingid' => new external_value(PARAM_INT
, 'default grouping id',
786 'timecreated' => new external_value(PARAM_INT
,
787 'timestamp when the course have been created', VALUE_OPTIONAL
),
788 'timemodified' => new external_value(PARAM_INT
,
789 'timestamp when the course have been modified', VALUE_OPTIONAL
),
790 'enablecompletion' => new external_value(PARAM_INT
,
791 'Enabled, control via completion and activity settings. Disbaled,
792 not shown in activity settings.',
794 'completionnotify' => new external_value(PARAM_INT
,
795 '1: yes 0: no', VALUE_OPTIONAL
),
796 'lang' => new external_value(PARAM_SAFEDIR
,
797 'forced course language', VALUE_OPTIONAL
),
798 'forcetheme' => new external_value(PARAM_PLUGIN
,
799 'name of the force theme', VALUE_OPTIONAL
),
800 'courseformatoptions' => new external_multiple_structure(
801 new external_single_structure(
802 array('name' => new external_value(PARAM_ALPHANUMEXT
, 'course format option name'),
803 'value' => new external_value(PARAM_RAW
, 'course format option value')
804 )), 'additional options for particular course format', VALUE_OPTIONAL
806 'showactivitydates' => new external_value(PARAM_BOOL
, 'Whether the activity dates are shown or not'),
807 'showcompletionconditions' => new external_value(PARAM_BOOL
,
808 'Whether the activity completion conditions are shown or not'),
809 'customfields' => new external_multiple_structure(
810 new external_single_structure(
811 ['name' => new external_value(PARAM_RAW
, 'The name of the custom field'),
812 'shortname' => new external_value(PARAM_ALPHANUMEXT
, 'The shortname of the custom field'),
813 'type' => new external_value(PARAM_COMPONENT
,
814 'The type of the custom field - text, checkbox...'),
815 'valueraw' => new external_value(PARAM_RAW
, 'The raw value of the custom field'),
816 'value' => new external_value(PARAM_RAW
, 'The value of the custom field')]
817 ), 'Custom fields and associated values', VALUE_OPTIONAL
),
824 * Return array of all editable course custom fields indexed by their shortname
826 * @param \context $context
827 * @param int $courseid
828 * @return \core_customfield\field_controller[]
830 public static function get_editable_customfields(\context
$context, int $courseid = 0): array {
833 $handler = \core_course\customfield\course_handler
::create();
834 $handler->set_parent_context($context);
836 foreach ($handler->get_editable_fields($courseid) as $field) {
837 $result[$field->get('shortname')] = $field;
844 * Returns description of method parameters
846 * @return external_function_parameters
849 public static function create_courses_parameters() {
850 $courseconfig = get_config('moodlecourse'); //needed for many default values
851 return new external_function_parameters(
853 'courses' => new external_multiple_structure(
854 new external_single_structure(
856 'fullname' => new external_value(PARAM_TEXT
, 'full name'),
857 'shortname' => new external_value(PARAM_TEXT
, 'course short name'),
858 'categoryid' => new external_value(PARAM_INT
, 'category id'),
859 'idnumber' => new external_value(PARAM_RAW
, 'id number', VALUE_OPTIONAL
),
860 'summary' => new external_value(PARAM_RAW
, 'summary', VALUE_OPTIONAL
),
861 'summaryformat' => new external_format_value('summary', VALUE_DEFAULT
),
862 'format' => new external_value(PARAM_PLUGIN
,
863 'course format: weeks, topics, social, site,..',
864 VALUE_DEFAULT
, $courseconfig->format
),
865 'showgrades' => new external_value(PARAM_INT
,
866 '1 if grades are shown, otherwise 0', VALUE_DEFAULT
,
867 $courseconfig->showgrades
),
868 'newsitems' => new external_value(PARAM_INT
,
869 'number of recent items appearing on the course page',
870 VALUE_DEFAULT
, $courseconfig->newsitems
),
871 'startdate' => new external_value(PARAM_INT
,
872 'timestamp when the course start', VALUE_OPTIONAL
),
873 'enddate' => new external_value(PARAM_INT
,
874 'timestamp when the course end', VALUE_OPTIONAL
),
875 'numsections' => new external_value(PARAM_INT
,
876 '(deprecated, use courseformatoptions) number of weeks/topics',
878 'maxbytes' => new external_value(PARAM_INT
,
879 'largest size of file that can be uploaded into the course',
880 VALUE_DEFAULT
, $courseconfig->maxbytes
),
881 'showreports' => new external_value(PARAM_INT
,
882 'are activity report shown (yes = 1, no =0)', VALUE_DEFAULT
,
883 $courseconfig->showreports
),
884 'visible' => new external_value(PARAM_INT
,
885 '1: available to student, 0:not available', VALUE_OPTIONAL
),
886 'hiddensections' => new external_value(PARAM_INT
,
887 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
889 'groupmode' => new external_value(PARAM_INT
, 'no group, separate, visible',
890 VALUE_DEFAULT
, $courseconfig->groupmode
),
891 'groupmodeforce' => new external_value(PARAM_INT
, '1: yes, 0: no',
892 VALUE_DEFAULT
, $courseconfig->groupmodeforce
),
893 'defaultgroupingid' => new external_value(PARAM_INT
, 'default grouping id',
895 'enablecompletion' => new external_value(PARAM_INT
,
896 'Enabled, control via completion and activity settings. Disabled,
897 not shown in activity settings.',
899 'completionnotify' => new external_value(PARAM_INT
,
900 '1: yes 0: no', VALUE_OPTIONAL
),
901 'lang' => new external_value(PARAM_SAFEDIR
,
902 'forced course language', VALUE_OPTIONAL
),
903 'forcetheme' => new external_value(PARAM_PLUGIN
,
904 'name of the force theme', VALUE_OPTIONAL
),
905 'courseformatoptions' => new external_multiple_structure(
906 new external_single_structure(
907 array('name' => new external_value(PARAM_ALPHANUMEXT
, 'course format option name'),
908 'value' => new external_value(PARAM_RAW
, 'course format option value')
910 'additional options for particular course format', VALUE_OPTIONAL
),
911 'customfields' => new external_multiple_structure(
912 new external_single_structure(
914 'shortname' => new external_value(PARAM_ALPHANUMEXT
, 'The shortname of the custom field'),
915 'value' => new external_value(PARAM_RAW
, 'The value of the custom field'),
916 )), 'custom fields for the course', VALUE_OPTIONAL
918 )), 'courses to create'
927 * @param array $courses
928 * @return array courses (id and shortname only)
931 public static function create_courses($courses) {
933 require_once($CFG->dirroot
. "/course/lib.php");
934 require_once($CFG->libdir
. '/completionlib.php');
936 $params = self
::validate_parameters(self
::create_courses_parameters(),
937 array('courses' => $courses));
939 $availablethemes = core_component
::get_plugin_list('theme');
940 $availablelangs = get_string_manager()->get_list_of_translations();
942 $transaction = $DB->start_delegated_transaction();
944 foreach ($params['courses'] as $course) {
946 // Ensure the current user is allowed to run this function
947 $context = context_coursecat
::instance($course['categoryid'], IGNORE_MISSING
);
949 self
::validate_context($context);
950 } catch (Exception
$e) {
951 $exceptionparam = new stdClass();
952 $exceptionparam->message
= $e->getMessage();
953 $exceptionparam->catid
= $course['categoryid'];
954 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
956 require_capability('moodle/course:create', $context);
958 // Fullname and short name are required to be non-empty.
959 if (trim($course['fullname']) === '') {
960 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'fullname');
961 } else if (trim($course['shortname']) === '') {
962 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'shortname');
965 // Make sure lang is valid
966 if (array_key_exists('lang', $course)) {
967 if (empty($availablelangs[$course['lang']])) {
968 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
970 if (!has_capability('moodle/course:setforcedlanguage', $context)) {
971 unset($course['lang']);
975 // Make sure theme is valid
976 if (array_key_exists('forcetheme', $course)) {
977 if (!empty($CFG->allowcoursethemes
)) {
978 if (empty($availablethemes[$course['forcetheme']])) {
979 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
981 $course['theme'] = $course['forcetheme'];
986 //force visibility if ws user doesn't have the permission to set it
987 $category = $DB->get_record('course_categories', array('id' => $course['categoryid']));
988 if (!has_capability('moodle/course:visibility', $context)) {
989 $course['visible'] = $category->visible
;
992 //set default value for completion
993 $courseconfig = get_config('moodlecourse');
994 if (completion_info
::is_enabled_for_site()) {
995 if (!array_key_exists('enablecompletion', $course)) {
996 $course['enablecompletion'] = $courseconfig->enablecompletion
;
999 $course['enablecompletion'] = 0;
1002 $course['category'] = $course['categoryid'];
1005 $course['summaryformat'] = util
::validate_format($course['summaryformat']);
1007 if (!empty($course['courseformatoptions'])) {
1008 foreach ($course['courseformatoptions'] as $option) {
1009 $course[$option['name']] = $option['value'];
1014 if (!empty($course['customfields'])) {
1015 $customfields = self
::get_editable_customfields($context);
1016 foreach ($course['customfields'] as $field) {
1017 if (array_key_exists($field['shortname'], $customfields)) {
1018 // Ensure we're populating the element form fields correctly.
1019 $controller = \core_customfield\data_controller
::create(0, null, $customfields[$field['shortname']]);
1020 $course[$controller->get_form_element_name()] = $field['value'];
1025 //Note: create_course() core function check shortname, idnumber, category
1026 $course['id'] = create_course((object) $course)->id
;
1028 $resultcourses[] = array('id' => $course['id'], 'shortname' => $course['shortname']);
1031 $transaction->allow_commit();
1033 return $resultcourses;
1037 * Returns description of method result value
1039 * @return \core_external\external_description
1042 public static function create_courses_returns() {
1043 return new external_multiple_structure(
1044 new external_single_structure(
1046 'id' => new external_value(PARAM_INT
, 'course id'),
1047 'shortname' => new external_value(PARAM_RAW
, 'short name'),
1056 * @return external_function_parameters
1059 public static function update_courses_parameters() {
1060 return new external_function_parameters(
1062 'courses' => new external_multiple_structure(
1063 new external_single_structure(
1065 'id' => new external_value(PARAM_INT
, 'ID of the course'),
1066 'fullname' => new external_value(PARAM_TEXT
, 'full name', VALUE_OPTIONAL
),
1067 'shortname' => new external_value(PARAM_TEXT
, 'course short name', VALUE_OPTIONAL
),
1068 'categoryid' => new external_value(PARAM_INT
, 'category id', VALUE_OPTIONAL
),
1069 'idnumber' => new external_value(PARAM_RAW
, 'id number', VALUE_OPTIONAL
),
1070 'summary' => new external_value(PARAM_RAW
, 'summary', VALUE_OPTIONAL
),
1071 'summaryformat' => new external_format_value('summary', VALUE_OPTIONAL
),
1072 'format' => new external_value(PARAM_PLUGIN
,
1073 'course format: weeks, topics, social, site,..', VALUE_OPTIONAL
),
1074 'showgrades' => new external_value(PARAM_INT
,
1075 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL
),
1076 'newsitems' => new external_value(PARAM_INT
,
1077 'number of recent items appearing on the course page', VALUE_OPTIONAL
),
1078 'startdate' => new external_value(PARAM_INT
,
1079 'timestamp when the course start', VALUE_OPTIONAL
),
1080 'enddate' => new external_value(PARAM_INT
,
1081 'timestamp when the course end', VALUE_OPTIONAL
),
1082 'numsections' => new external_value(PARAM_INT
,
1083 '(deprecated, use courseformatoptions) number of weeks/topics', VALUE_OPTIONAL
),
1084 'maxbytes' => new external_value(PARAM_INT
,
1085 'largest size of file that can be uploaded into the course', VALUE_OPTIONAL
),
1086 'showreports' => new external_value(PARAM_INT
,
1087 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL
),
1088 'visible' => new external_value(PARAM_INT
,
1089 '1: available to student, 0:not available', VALUE_OPTIONAL
),
1090 'hiddensections' => new external_value(PARAM_INT
,
1091 '(deprecated, use courseformatoptions) How the hidden sections in the course are
1092 displayed to students', VALUE_OPTIONAL
),
1093 'groupmode' => new external_value(PARAM_INT
, 'no group, separate, visible', VALUE_OPTIONAL
),
1094 'groupmodeforce' => new external_value(PARAM_INT
, '1: yes, 0: no', VALUE_OPTIONAL
),
1095 'defaultgroupingid' => new external_value(PARAM_INT
, 'default grouping id', VALUE_OPTIONAL
),
1096 'enablecompletion' => new external_value(PARAM_INT
,
1097 'Enabled, control via completion and activity settings. Disabled,
1098 not shown in activity settings.', VALUE_OPTIONAL
),
1099 'completionnotify' => new external_value(PARAM_INT
, '1: yes 0: no', VALUE_OPTIONAL
),
1100 'lang' => new external_value(PARAM_SAFEDIR
, 'forced course language', VALUE_OPTIONAL
),
1101 'forcetheme' => new external_value(PARAM_PLUGIN
, 'name of the force theme', VALUE_OPTIONAL
),
1102 'courseformatoptions' => new external_multiple_structure(
1103 new external_single_structure(
1104 array('name' => new external_value(PARAM_ALPHANUMEXT
, 'course format option name'),
1105 'value' => new external_value(PARAM_RAW
, 'course format option value')
1106 )), 'additional options for particular course format', VALUE_OPTIONAL
),
1107 'customfields' => new external_multiple_structure(
1108 new external_single_structure(
1110 'shortname' => new external_value(PARAM_ALPHANUMEXT
, 'The shortname of the custom field'),
1111 'value' => new external_value(PARAM_RAW
, 'The value of the custom field')
1113 ), 'Custom fields', VALUE_OPTIONAL
),
1115 ), 'courses to update'
1124 * @param array $courses
1127 public static function update_courses($courses) {
1129 require_once($CFG->dirroot
. "/course/lib.php");
1130 $warnings = array();
1132 $params = self
::validate_parameters(self
::update_courses_parameters(),
1133 array('courses' => $courses));
1135 $availablethemes = core_component
::get_plugin_list('theme');
1136 $availablelangs = get_string_manager()->get_list_of_translations();
1138 foreach ($params['courses'] as $course) {
1139 // Catch any exception while updating course and return as warning to user.
1141 // Ensure the current user is allowed to run this function.
1142 $context = context_course
::instance($course['id'], MUST_EXIST
);
1143 self
::validate_context($context);
1145 $oldcourse = course_get_format($course['id'])->get_course();
1147 require_capability('moodle/course:update', $context);
1149 // Check if user can change category.
1150 if (array_key_exists('categoryid', $course) && ($oldcourse->category
!= $course['categoryid'])) {
1151 require_capability('moodle/course:changecategory', $context);
1152 $course['category'] = $course['categoryid'];
1155 // Check if the user can change fullname, and the new value is non-empty.
1156 if (array_key_exists('fullname', $course) && ($oldcourse->fullname
!= $course['fullname'])) {
1157 require_capability('moodle/course:changefullname', $context);
1158 if (trim($course['fullname']) === '') {
1159 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'fullname');
1163 // Check if the user can change shortname, and the new value is non-empty.
1164 if (array_key_exists('shortname', $course) && ($oldcourse->shortname
!= $course['shortname'])) {
1165 require_capability('moodle/course:changeshortname', $context);
1166 if (trim($course['shortname']) === '') {
1167 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'shortname');
1171 // Check if the user can change the idnumber.
1172 if (array_key_exists('idnumber', $course) && ($oldcourse->idnumber
!= $course['idnumber'])) {
1173 require_capability('moodle/course:changeidnumber', $context);
1176 // Check if user can change summary.
1177 if (array_key_exists('summary', $course) && ($oldcourse->summary
!= $course['summary'])) {
1178 require_capability('moodle/course:changesummary', $context);
1182 if (array_key_exists('summaryformat', $course) && ($oldcourse->summaryformat
!= $course['summaryformat'])) {
1183 require_capability('moodle/course:changesummary', $context);
1184 $course['summaryformat'] = util
::validate_format($course['summaryformat']);
1187 // Check if user can change visibility.
1188 if (array_key_exists('visible', $course) && ($oldcourse->visible
!= $course['visible'])) {
1189 require_capability('moodle/course:visibility', $context);
1192 // Make sure lang is valid.
1193 if (array_key_exists('lang', $course) && ($oldcourse->lang
!= $course['lang'])) {
1194 require_capability('moodle/course:setforcedlanguage', $context);
1195 if (empty($availablelangs[$course['lang']])) {
1196 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
1200 // Make sure theme is valid.
1201 if (array_key_exists('forcetheme', $course)) {
1202 if (!empty($CFG->allowcoursethemes
)) {
1203 if (empty($availablethemes[$course['forcetheme']])) {
1204 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
1206 $course['theme'] = $course['forcetheme'];
1211 // Make sure completion is enabled before setting it.
1212 if (array_key_exists('enabledcompletion', $course) && !completion_info
::is_enabled_for_site()) {
1213 $course['enabledcompletion'] = 0;
1216 // Make sure maxbytes are less then CFG->maxbytes.
1217 if (array_key_exists('maxbytes', $course)) {
1218 // We allow updates back to 0 max bytes, a special value denoting the course uses the site limit.
1219 // Otherwise, either use the size specified, or cap at the max size for the course.
1220 if ($course['maxbytes'] != 0) {
1221 $course['maxbytes'] = get_max_upload_file_size($CFG->maxbytes
, $course['maxbytes']);
1225 if (!empty($course['courseformatoptions'])) {
1226 foreach ($course['courseformatoptions'] as $option) {
1227 if (isset($option['name']) && isset($option['value'])) {
1228 $course[$option['name']] = $option['value'];
1234 if (isset($course['customfields'])) {
1235 $customfields = self
::get_editable_customfields($context, $course['id']);
1236 foreach ($course['customfields'] as $field) {
1237 if (array_key_exists($field['shortname'], $customfields)) {
1238 // Ensure we're populating the element form fields correctly.
1239 $controller = \core_customfield\data_controller
::create(0, null, $customfields[$field['shortname']]);
1240 $course[$controller->get_form_element_name()] = $field['value'];
1245 // Update course if user has all required capabilities.
1246 update_course((object) $course);
1247 } catch (Exception
$e) {
1249 $warning['item'] = 'course';
1250 $warning['itemid'] = $course['id'];
1251 if ($e instanceof moodle_exception
) {
1252 $warning['warningcode'] = $e->errorcode
;
1254 $warning['warningcode'] = $e->getCode();
1256 $warning['message'] = $e->getMessage();
1257 $warnings[] = $warning;
1262 $result['warnings'] = $warnings;
1267 * Returns description of method result value
1269 * @return \core_external\external_description
1272 public static function update_courses_returns() {
1273 return new external_single_structure(
1275 'warnings' => new external_warnings()
1281 * Returns description of method parameters
1283 * @return external_function_parameters
1286 public static function delete_courses_parameters() {
1287 return new external_function_parameters(
1289 'courseids' => new external_multiple_structure(new external_value(PARAM_INT
, 'course ID')),
1297 * @param array $courseids A list of course ids
1300 public static function delete_courses($courseids) {
1302 require_once($CFG->dirroot
."/course/lib.php");
1304 // Parameter validation.
1305 $params = self
::validate_parameters(self
::delete_courses_parameters(), array('courseids'=>$courseids));
1307 $warnings = array();
1309 foreach ($params['courseids'] as $courseid) {
1310 $course = $DB->get_record('course', array('id' => $courseid));
1312 if ($course === false) {
1313 $warnings[] = array(
1315 'itemid' => $courseid,
1316 'warningcode' => 'unknowncourseidnumber',
1317 'message' => 'Unknown course ID ' . $courseid
1322 // Check if the context is valid.
1323 $coursecontext = context_course
::instance($course->id
);
1324 self
::validate_context($coursecontext);
1326 // Check if the current user has permission.
1327 if (!can_delete_course($courseid)) {
1328 $warnings[] = array(
1330 'itemid' => $courseid,
1331 'warningcode' => 'cannotdeletecourse',
1332 'message' => 'You do not have the permission to delete this course' . $courseid
1337 if (delete_course($course, false) === false) {
1338 $warnings[] = array(
1340 'itemid' => $courseid,
1341 'warningcode' => 'cannotdeletecategorycourse',
1342 'message' => 'Course ' . $courseid . ' failed to be deleted'
1348 fix_course_sortorder();
1350 return array('warnings' => $warnings);
1354 * Returns description of method result value
1356 * @return \core_external\external_description
1359 public static function delete_courses_returns() {
1360 return new external_single_structure(
1362 'warnings' => new external_warnings()
1368 * Returns description of method parameters
1370 * @return external_function_parameters
1373 public static function duplicate_course_parameters() {
1374 return new external_function_parameters(
1376 'courseid' => new external_value(PARAM_INT
, 'course to duplicate id'),
1377 'fullname' => new external_value(PARAM_TEXT
, 'duplicated course full name'),
1378 'shortname' => new external_value(PARAM_TEXT
, 'duplicated course short name'),
1379 'categoryid' => new external_value(PARAM_INT
, 'duplicated course category parent'),
1380 'visible' => new external_value(PARAM_INT
, 'duplicated course visible, default to yes', VALUE_DEFAULT
, 1),
1381 'options' => new external_multiple_structure(
1382 new external_single_structure(
1384 'name' => new external_value(PARAM_ALPHAEXT
, 'The backup option name:
1385 "activities" (int) Include course activites (default to 1 that is equal to yes),
1386 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1387 "filters" (int) Include course filters (default to 1 that is equal to yes),
1388 "users" (int) Include users (default to 0 that is equal to no),
1389 "enrolments" (int) Include enrolment methods (default to 1 - restore only with users),
1390 "role_assignments" (int) Include role assignments (default to 0 that is equal to no),
1391 "comments" (int) Include user comments (default to 0 that is equal to no),
1392 "userscompletion" (int) Include user course completion information (default to 0 that is equal to no),
1393 "logs" (int) Include course logs (default to 0 that is equal to no),
1394 "grade_histories" (int) Include histories (default to 0 that is equal to no)'
1396 'value' => new external_value(PARAM_RAW
, 'the value for the option 1 (yes) or 0 (no)'
1399 ), 'Course duplication options', VALUE_DEFAULT
, array()
1406 * Duplicate a course
1408 * @param int $courseid
1409 * @param string $fullname Duplicated course fullname
1410 * @param string $shortname Duplicated course shortname
1411 * @param int $categoryid Duplicated course parent category id
1412 * @param int $visible Duplicated course availability
1413 * @param array $options List of backup options
1414 * @return array New course info
1417 public static function duplicate_course($courseid, $fullname, $shortname, $categoryid, $visible = 1, $options = array()) {
1418 global $CFG, $USER, $DB;
1419 require_once($CFG->dirroot
. '/backup/util/includes/backup_includes.php');
1420 require_once($CFG->dirroot
. '/backup/util/includes/restore_includes.php');
1422 // Parameter validation.
1423 $params = self
::validate_parameters(
1424 self
::duplicate_course_parameters(),
1426 'courseid' => $courseid,
1427 'fullname' => $fullname,
1428 'shortname' => $shortname,
1429 'categoryid' => $categoryid,
1430 'visible' => $visible,
1431 'options' => $options
1435 // Context validation.
1437 if (! ($course = $DB->get_record('course', array('id'=>$params['courseid'])))) {
1438 throw new moodle_exception('invalidcourseid', 'error');
1441 // Category where duplicated course is going to be created.
1442 $categorycontext = context_coursecat
::instance($params['categoryid']);
1443 self
::validate_context($categorycontext);
1445 // Course to be duplicated.
1446 $coursecontext = context_course
::instance($course->id
);
1447 self
::validate_context($coursecontext);
1449 $backupdefaults = array(
1454 'enrolments' => backup
::ENROL_WITHUSERS
,
1455 'role_assignments' => 0,
1457 'userscompletion' => 0,
1459 'grade_histories' => 0
1462 $backupsettings = array();
1463 // Check for backup and restore options.
1464 if (!empty($params['options'])) {
1465 foreach ($params['options'] as $option) {
1467 // Strict check for a correct value (allways 1 or 0, true or false).
1468 $value = clean_param($option['value'], PARAM_INT
);
1470 if ($value !== 0 and $value !== 1) {
1471 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1474 if (!isset($backupdefaults[$option['name']])) {
1475 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1478 $backupsettings[$option['name']] = $value;
1482 // Capability checking.
1484 // The backup controller check for this currently, this may be redundant.
1485 require_capability('moodle/course:create', $categorycontext);
1486 require_capability('moodle/restore:restorecourse', $categorycontext);
1487 require_capability('moodle/backup:backupcourse', $coursecontext);
1489 if (!empty($backupsettings['users'])) {
1490 require_capability('moodle/backup:userinfo', $coursecontext);
1491 require_capability('moodle/restore:userinfo', $categorycontext);
1494 // Check if the shortname is used.
1495 if ($foundcourses = $DB->get_records('course', array('shortname'=>$shortname))) {
1496 foreach ($foundcourses as $foundcourse) {
1497 $foundcoursenames[] = $foundcourse->fullname
;
1500 $foundcoursenamestring = implode(',', $foundcoursenames);
1501 throw new moodle_exception('shortnametaken', '', '', $foundcoursenamestring);
1504 // Backup the course.
1506 $bc = new backup_controller(backup
::TYPE_1COURSE
, $course->id
, backup
::FORMAT_MOODLE
,
1507 backup
::INTERACTIVE_NO
, backup
::MODE_SAMESITE
, $USER->id
);
1509 foreach ($backupsettings as $name => $value) {
1510 if ($setting = $bc->get_plan()->get_setting($name)) {
1511 $bc->get_plan()->get_setting($name)->set_value($value);
1515 $backupid = $bc->get_backupid();
1516 $backupbasepath = $bc->get_plan()->get_basepath();
1518 $bc->execute_plan();
1519 $results = $bc->get_results();
1520 $file = $results['backup_destination'];
1524 // Restore the backup immediately.
1526 // Check if we need to unzip the file because the backup temp dir does not contains backup files.
1527 if (!file_exists($backupbasepath . "/moodle_backup.xml")) {
1528 $file->extract_to_pathname(get_file_packer('application/vnd.moodle.backup'), $backupbasepath);
1531 // Create new course.
1532 $newcourseid = restore_dbops
::create_new_course($params['fullname'], $params['shortname'], $params['categoryid']);
1534 $rc = new restore_controller($backupid, $newcourseid,
1535 backup
::INTERACTIVE_NO
, backup
::MODE_SAMESITE
, $USER->id
, backup
::TARGET_NEW_COURSE
);
1537 foreach ($backupsettings as $name => $value) {
1538 $setting = $rc->get_plan()->get_setting($name);
1539 if ($setting->get_status() == backup_setting
::NOT_LOCKED
) {
1540 $setting->set_value($value);
1544 if (!$rc->execute_precheck()) {
1545 $precheckresults = $rc->get_precheck_results();
1546 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1547 if (empty($CFG->keeptempdirectoriesonbackup
)) {
1548 fulldelete($backupbasepath);
1553 foreach ($precheckresults['errors'] as $error) {
1554 $errorinfo .= $error;
1557 if (array_key_exists('warnings', $precheckresults)) {
1558 foreach ($precheckresults['warnings'] as $warning) {
1559 $errorinfo .= $warning;
1563 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1567 $rc->execute_plan();
1570 $course = $DB->get_record('course', array('id' => $newcourseid), '*', MUST_EXIST
);
1571 $course->fullname
= $params['fullname'];
1572 $course->shortname
= $params['shortname'];
1573 $course->visible
= $params['visible'];
1575 // Set shortname and fullname back.
1576 $DB->update_record('course', $course);
1578 if (empty($CFG->keeptempdirectoriesonbackup
)) {
1579 fulldelete($backupbasepath);
1582 // Delete the course backup file created by this WebService. Originally located in the course backups area.
1585 return array('id' => $course->id
, 'shortname' => $course->shortname
);
1589 * Returns description of method result value
1591 * @return \core_external\external_description
1594 public static function duplicate_course_returns() {
1595 return new external_single_structure(
1597 'id' => new external_value(PARAM_INT
, 'course id'),
1598 'shortname' => new external_value(PARAM_RAW
, 'short name'),
1604 * Returns description of method parameters for import_course
1606 * @return external_function_parameters
1609 public static function import_course_parameters() {
1610 return new external_function_parameters(
1612 'importfrom' => new external_value(PARAM_INT
, 'the id of the course we are importing from'),
1613 'importto' => new external_value(PARAM_INT
, 'the id of the course we are importing to'),
1614 'deletecontent' => new external_value(PARAM_INT
, 'whether to delete the course content where we are importing to (default to 0 = No)', VALUE_DEFAULT
, 0),
1615 'options' => new external_multiple_structure(
1616 new external_single_structure(
1618 'name' => new external_value(PARAM_ALPHA
, 'The backup option name:
1619 "activities" (int) Include course activites (default to 1 that is equal to yes),
1620 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1621 "filters" (int) Include course filters (default to 1 that is equal to yes)'
1623 'value' => new external_value(PARAM_RAW
, 'the value for the option 1 (yes) or 0 (no)'
1626 ), 'Course import options', VALUE_DEFAULT
, array()
1635 * @param int $importfrom The id of the course we are importing from
1636 * @param int $importto The id of the course we are importing to
1637 * @param bool $deletecontent Whether to delete the course we are importing to content
1638 * @param array $options List of backup options
1642 public static function import_course($importfrom, $importto, $deletecontent = 0, $options = array()) {
1643 global $CFG, $USER, $DB;
1644 require_once($CFG->dirroot
. '/backup/util/includes/backup_includes.php');
1645 require_once($CFG->dirroot
. '/backup/util/includes/restore_includes.php');
1647 // Parameter validation.
1648 $params = self
::validate_parameters(
1649 self
::import_course_parameters(),
1651 'importfrom' => $importfrom,
1652 'importto' => $importto,
1653 'deletecontent' => $deletecontent,
1654 'options' => $options
1658 if ($params['deletecontent'] !== 0 and $params['deletecontent'] !== 1) {
1659 throw new moodle_exception('invalidextparam', 'webservice', '', $params['deletecontent']);
1662 // Context validation.
1664 if (! ($importfrom = $DB->get_record('course', array('id'=>$params['importfrom'])))) {
1665 throw new moodle_exception('invalidcourseid', 'error');
1668 if (! ($importto = $DB->get_record('course', array('id'=>$params['importto'])))) {
1669 throw new moodle_exception('invalidcourseid', 'error');
1672 $importfromcontext = context_course
::instance($importfrom->id
);
1673 self
::validate_context($importfromcontext);
1675 $importtocontext = context_course
::instance($importto->id
);
1676 self
::validate_context($importtocontext);
1678 $backupdefaults = array(
1684 $backupsettings = array();
1686 // Check for backup and restore options.
1687 if (!empty($params['options'])) {
1688 foreach ($params['options'] as $option) {
1690 // Strict check for a correct value (allways 1 or 0, true or false).
1691 $value = clean_param($option['value'], PARAM_INT
);
1693 if ($value !== 0 and $value !== 1) {
1694 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1697 if (!isset($backupdefaults[$option['name']])) {
1698 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1701 $backupsettings[$option['name']] = $value;
1705 // Capability checking.
1707 require_capability('moodle/backup:backuptargetimport', $importfromcontext);
1708 require_capability('moodle/restore:restoretargetimport', $importtocontext);
1710 $bc = new backup_controller(backup
::TYPE_1COURSE
, $importfrom->id
, backup
::FORMAT_MOODLE
,
1711 backup
::INTERACTIVE_NO
, backup
::MODE_IMPORT
, $USER->id
);
1713 foreach ($backupsettings as $name => $value) {
1714 $bc->get_plan()->get_setting($name)->set_value($value);
1717 $backupid = $bc->get_backupid();
1718 $backupbasepath = $bc->get_plan()->get_basepath();
1720 $bc->execute_plan();
1723 // Restore the backup immediately.
1725 // Check if we must delete the contents of the destination course.
1726 if ($params['deletecontent']) {
1727 $restoretarget = backup
::TARGET_EXISTING_DELETING
;
1729 $restoretarget = backup
::TARGET_EXISTING_ADDING
;
1732 $rc = new restore_controller($backupid, $importto->id
,
1733 backup
::INTERACTIVE_NO
, backup
::MODE_IMPORT
, $USER->id
, $restoretarget);
1735 foreach ($backupsettings as $name => $value) {
1736 $rc->get_plan()->get_setting($name)->set_value($value);
1739 if (!$rc->execute_precheck()) {
1740 $precheckresults = $rc->get_precheck_results();
1741 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1742 if (empty($CFG->keeptempdirectoriesonbackup
)) {
1743 fulldelete($backupbasepath);
1748 foreach ($precheckresults['errors'] as $error) {
1749 $errorinfo .= $error;
1752 if (array_key_exists('warnings', $precheckresults)) {
1753 foreach ($precheckresults['warnings'] as $warning) {
1754 $errorinfo .= $warning;
1758 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1761 if ($restoretarget == backup
::TARGET_EXISTING_DELETING
) {
1762 restore_dbops
::delete_course_content($importto->id
);
1766 $rc->execute_plan();
1769 if (empty($CFG->keeptempdirectoriesonbackup
)) {
1770 fulldelete($backupbasepath);
1777 * Returns description of method result value
1779 * @return \core_external\external_description
1782 public static function import_course_returns() {
1787 * Returns description of method parameters
1789 * @return external_function_parameters
1792 public static function get_categories_parameters() {
1793 return new external_function_parameters(
1795 'criteria' => new external_multiple_structure(
1796 new external_single_structure(
1798 'key' => new external_value(PARAM_ALPHA
,
1799 'The category column to search, expected keys (value format) are:'.
1800 '"id" (int) the category id,'.
1801 '"ids" (string) category ids separated by commas,'.
1802 '"name" (string) the category name,'.
1803 '"parent" (int) the parent category id,'.
1804 '"idnumber" (string) category idnumber'.
1805 ' - user must have \'moodle/category:manage\' to search on idnumber,'.
1806 '"visible" (int) whether the returned categories must be visible or hidden. If the key is not passed,
1807 then the function return all categories that the user can see.'.
1808 ' - user must have \'moodle/category:manage\' or \'moodle/category:viewhiddencategories\' to search on visible,'.
1809 '"theme" (string) only return the categories having this theme'.
1810 ' - user must have \'moodle/category:manage\' to search on theme'),
1811 'value' => new external_value(PARAM_RAW
, 'the value to match')
1813 ), 'criteria', VALUE_DEFAULT
, array()
1815 'addsubcategories' => new external_value(PARAM_BOOL
, 'return the sub categories infos
1816 (1 - default) otherwise only the category info (0)', VALUE_DEFAULT
, 1)
1824 * @param array $criteria Criteria to match the results
1825 * @param booln $addsubcategories obtain only the category (false) or its subcategories (true - default)
1826 * @return array list of categories
1829 public static function get_categories($criteria = array(), $addsubcategories = true) {
1831 require_once($CFG->dirroot
. "/course/lib.php");
1833 // Validate parameters.
1834 $params = self
::validate_parameters(self
::get_categories_parameters(),
1835 array('criteria' => $criteria, 'addsubcategories' => $addsubcategories));
1837 // Retrieve the categories.
1838 $categories = array();
1839 if (!empty($params['criteria'])) {
1841 $conditions = array();
1843 foreach ($params['criteria'] as $crit) {
1844 $key = trim($crit['key']);
1846 // Trying to avoid duplicate keys.
1847 if (!isset($conditions[$key])) {
1849 $context = context_system
::instance();
1853 $value = clean_param($crit['value'], PARAM_INT
);
1854 $conditions[$key] = $value;
1855 $wheres[] = $key . " = :" . $key;
1859 $value = clean_param($crit['value'], PARAM_SEQUENCE
);
1860 $ids = explode(',', $value);
1861 list($sqlids, $paramids) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED
);
1862 $conditions = array_merge($conditions, $paramids);
1863 $wheres[] = 'id ' . $sqlids;
1867 if (has_capability('moodle/category:manage', $context)) {
1868 $value = clean_param($crit['value'], PARAM_RAW
);
1869 $conditions[$key] = $value;
1870 $wheres[] = $key . " = :" . $key;
1872 // We must throw an exception.
1873 // Otherwise the dev client would think no idnumber exists.
1874 throw new moodle_exception('criteriaerror',
1875 'webservice', '', null,
1876 'You don\'t have the permissions to search on the "idnumber" field.');
1881 $value = clean_param($crit['value'], PARAM_TEXT
);
1882 $conditions[$key] = $value;
1883 $wheres[] = $key . " = :" . $key;
1887 $value = clean_param($crit['value'], PARAM_INT
);
1888 $conditions[$key] = $value;
1889 $wheres[] = $key . " = :" . $key;
1893 if (has_capability('moodle/category:viewhiddencategories', $context)) {
1894 $value = clean_param($crit['value'], PARAM_INT
);
1895 $conditions[$key] = $value;
1896 $wheres[] = $key . " = :" . $key;
1898 throw new moodle_exception('criteriaerror',
1899 'webservice', '', null,
1900 'You don\'t have the permissions to search on the "visible" field.');
1905 if (has_capability('moodle/category:manage', $context)) {
1906 $value = clean_param($crit['value'], PARAM_THEME
);
1907 $conditions[$key] = $value;
1908 $wheres[] = $key . " = :" . $key;
1910 throw new moodle_exception('criteriaerror',
1911 'webservice', '', null,
1912 'You don\'t have the permissions to search on the "theme" field.');
1917 throw new moodle_exception('criteriaerror',
1918 'webservice', '', null,
1919 'You can not search on this criteria: ' . $key);
1924 if (!empty($wheres)) {
1925 $wheres = implode(" AND ", $wheres);
1927 $categories = $DB->get_records_select('course_categories', $wheres, $conditions);
1929 // Retrieve its sub subcategories (all levels).
1930 if ($categories and !empty($params['addsubcategories'])) {
1931 $newcategories = array();
1933 // Check if we required visible/theme checks.
1934 $additionalselect = '';
1935 $additionalparams = array();
1936 if (isset($conditions['visible'])) {
1937 $additionalselect .= ' AND visible = :visible';
1938 $additionalparams['visible'] = $conditions['visible'];
1940 if (isset($conditions['theme'])) {
1941 $additionalselect .= ' AND theme= :theme';
1942 $additionalparams['theme'] = $conditions['theme'];
1945 foreach ($categories as $category) {
1946 $sqlselect = $DB->sql_like('path', ':path') . $additionalselect;
1947 $sqlparams = array('path' => $category->path
.'/%') +
$additionalparams; // It will NOT include the specified category.
1948 $subcategories = $DB->get_records_select('course_categories', $sqlselect, $sqlparams);
1949 $newcategories = $newcategories +
$subcategories; // Both arrays have integer as keys.
1951 $categories = $categories +
$newcategories;
1956 // Retrieve all categories in the database.
1957 $categories = $DB->get_records('course_categories');
1960 // The not returned categories. key => category id, value => reason of exclusion.
1961 $excludedcats = array();
1963 // The returned categories.
1964 $categoriesinfo = array();
1966 // We need to sort the categories by path.
1967 // The parent cats need to be checked by the algo first.
1968 usort($categories, "core_course_external::compare_categories_by_path");
1970 foreach ($categories as $category) {
1972 // Check if the category is a child of an excluded category, if yes exclude it too (excluded => do not return).
1973 $parents = explode('/', $category->path
);
1974 unset($parents[0]); // First key is always empty because path start with / => /1/2/4.
1975 foreach ($parents as $parentid) {
1976 // Note: when the parent exclusion was due to the context,
1977 // the sub category could still be returned.
1978 if (isset($excludedcats[$parentid]) and $excludedcats[$parentid] != 'context') {
1979 $excludedcats[$category->id
] = 'parent';
1983 // Check the user can use the category context.
1984 $context = context_coursecat
::instance($category->id
);
1986 self
::validate_context($context);
1987 } catch (Exception
$e) {
1988 $excludedcats[$category->id
] = 'context';
1990 // If it was the requested category then throw an exception.
1991 if (isset($params['categoryid']) && $category->id
== $params['categoryid']) {
1992 $exceptionparam = new stdClass();
1993 $exceptionparam->message
= $e->getMessage();
1994 $exceptionparam->catid
= $category->id
;
1995 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
1999 // Return the category information.
2000 if (!isset($excludedcats[$category->id
])) {
2002 // Final check to see if the category is visible to the user.
2003 if (core_course_category
::can_view_category($category)) {
2005 $categoryinfo = array();
2006 $categoryinfo['id'] = $category->id
;
2007 $categoryinfo['name'] = \core_external\util
::format_string($category->name
, $context);
2008 list($categoryinfo['description'], $categoryinfo['descriptionformat']) =
2009 \core_external\util
::format_text($category->description
, $category->descriptionformat
,
2010 $context, 'coursecat', 'description', null);
2011 $categoryinfo['parent'] = $category->parent
;
2012 $categoryinfo['sortorder'] = $category->sortorder
;
2013 $categoryinfo['coursecount'] = $category->coursecount
;
2014 $categoryinfo['depth'] = $category->depth
;
2015 $categoryinfo['path'] = $category->path
;
2017 // Some fields only returned for admin.
2018 if (has_capability('moodle/category:manage', $context)) {
2019 $categoryinfo['idnumber'] = $category->idnumber
;
2020 $categoryinfo['visible'] = $category->visible
;
2021 $categoryinfo['visibleold'] = $category->visibleold
;
2022 $categoryinfo['timemodified'] = $category->timemodified
;
2023 $categoryinfo['theme'] = clean_param($category->theme
, PARAM_THEME
);
2026 $categoriesinfo[] = $categoryinfo;
2028 $excludedcats[$category->id
] = 'visibility';
2033 // Sorting the resulting array so it looks a bit better for the client developer.
2034 usort($categoriesinfo, "core_course_external::compare_categories_by_sortorder");
2036 return $categoriesinfo;
2040 * Sort categories array by path
2041 * private function: only used by get_categories
2043 * @param stdClass $category1
2044 * @param stdClass $category2
2045 * @return int result of strcmp
2048 private static function compare_categories_by_path($category1, $category2) {
2049 return strcmp($category1->path
, $category2->path
);
2053 * Sort categories array by sortorder
2054 * private function: only used by get_categories
2056 * @param array $category1
2057 * @param array $category2
2058 * @return int result of strcmp
2061 private static function compare_categories_by_sortorder($category1, $category2) {
2062 return strcmp($category1['sortorder'], $category2['sortorder']);
2066 * Returns description of method result value
2068 * @return \core_external\external_description
2071 public static function get_categories_returns() {
2072 return new external_multiple_structure(
2073 new external_single_structure(
2075 'id' => new external_value(PARAM_INT
, 'category id'),
2076 'name' => new external_value(PARAM_RAW
, 'category name'),
2077 'idnumber' => new external_value(PARAM_RAW
, 'category id number', VALUE_OPTIONAL
),
2078 'description' => new external_value(PARAM_RAW
, 'category description'),
2079 'descriptionformat' => new external_format_value('description'),
2080 'parent' => new external_value(PARAM_INT
, 'parent category id'),
2081 'sortorder' => new external_value(PARAM_INT
, 'category sorting order'),
2082 'coursecount' => new external_value(PARAM_INT
, 'number of courses in this category'),
2083 'visible' => new external_value(PARAM_INT
, '1: available, 0:not available', VALUE_OPTIONAL
),
2084 'visibleold' => new external_value(PARAM_INT
, '1: available, 0:not available', VALUE_OPTIONAL
),
2085 'timemodified' => new external_value(PARAM_INT
, 'timestamp', VALUE_OPTIONAL
),
2086 'depth' => new external_value(PARAM_INT
, 'category depth'),
2087 'path' => new external_value(PARAM_TEXT
, 'category path'),
2088 'theme' => new external_value(PARAM_THEME
, 'category theme', VALUE_OPTIONAL
),
2089 ), 'List of categories'
2095 * Returns description of method parameters
2097 * @return external_function_parameters
2100 public static function create_categories_parameters() {
2101 return new external_function_parameters(
2103 'categories' => new external_multiple_structure(
2104 new external_single_structure(
2106 'name' => new external_value(PARAM_TEXT
, 'new category name'),
2107 'parent' => new external_value(PARAM_INT
,
2108 'the parent category id inside which the new category will be created
2109 - set to 0 for a root category',
2111 'idnumber' => new external_value(PARAM_RAW
,
2112 'the new category idnumber', VALUE_OPTIONAL
),
2113 'description' => new external_value(PARAM_RAW
,
2114 'the new category description', VALUE_OPTIONAL
),
2115 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT
),
2116 'theme' => new external_value(PARAM_THEME
,
2117 'the new category theme. This option must be enabled on moodle',
2129 * @param array $categories - see create_categories_parameters() for the array structure
2130 * @return array - see create_categories_returns() for the array structure
2133 public static function create_categories($categories) {
2136 $params = self
::validate_parameters(self
::create_categories_parameters(),
2137 array('categories' => $categories));
2139 $transaction = $DB->start_delegated_transaction();
2141 $createdcategories = array();
2142 foreach ($params['categories'] as $category) {
2143 if ($category['parent']) {
2144 if (!$DB->record_exists('course_categories', array('id' => $category['parent']))) {
2145 throw new moodle_exception('unknowcategory');
2147 $context = context_coursecat
::instance($category['parent']);
2149 $context = context_system
::instance();
2151 self
::validate_context($context);
2152 require_capability('moodle/category:manage', $context);
2154 // this will validate format and throw an exception if there are errors
2155 util
::validate_format($category['descriptionformat']);
2157 $newcategory = core_course_category
::create($category);
2158 $context = context_coursecat
::instance($newcategory->id
);
2160 $createdcategories[] = array(
2161 'id' => $newcategory->id
,
2162 'name' => \core_external\util
::format_string($newcategory->name
, $context),
2166 $transaction->allow_commit();
2168 return $createdcategories;
2172 * Returns description of method parameters
2174 * @return external_function_parameters
2177 public static function create_categories_returns() {
2178 return new external_multiple_structure(
2179 new external_single_structure(
2181 'id' => new external_value(PARAM_INT
, 'new category id'),
2182 'name' => new external_value(PARAM_RAW
, 'new category name'),
2189 * Returns description of method parameters
2191 * @return external_function_parameters
2194 public static function update_categories_parameters() {
2195 return new external_function_parameters(
2197 'categories' => new external_multiple_structure(
2198 new external_single_structure(
2200 'id' => new external_value(PARAM_INT
, 'course id'),
2201 'name' => new external_value(PARAM_TEXT
, 'category name', VALUE_OPTIONAL
),
2202 'idnumber' => new external_value(PARAM_RAW
, 'category id number', VALUE_OPTIONAL
),
2203 'parent' => new external_value(PARAM_INT
, 'parent category id', VALUE_OPTIONAL
),
2204 'description' => new external_value(PARAM_RAW
, 'category description', VALUE_OPTIONAL
),
2205 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT
),
2206 'theme' => new external_value(PARAM_THEME
,
2207 'the category theme. This option must be enabled on moodle', VALUE_OPTIONAL
),
2218 * @param array $categories The list of categories to update
2222 public static function update_categories($categories) {
2225 // Validate parameters.
2226 $params = self
::validate_parameters(self
::update_categories_parameters(), array('categories' => $categories));
2228 $transaction = $DB->start_delegated_transaction();
2230 foreach ($params['categories'] as $cat) {
2231 $category = core_course_category
::get($cat['id']);
2233 $categorycontext = context_coursecat
::instance($cat['id']);
2234 self
::validate_context($categorycontext);
2235 require_capability('moodle/category:manage', $categorycontext);
2237 // If the category parent is being changed, check for capability in the new parent category
2238 if (isset($cat['parent']) && ($cat['parent'] !== $category->parent
)) {
2239 if ($cat['parent'] == 0) {
2240 // Creating a top level category requires capability in the system context
2241 $parentcontext = context_system
::instance();
2244 $parentcontext = context_coursecat
::instance($cat['parent']);
2246 self
::validate_context($parentcontext);
2247 require_capability('moodle/category:manage', $parentcontext);
2250 // this will throw an exception if descriptionformat is not valid
2251 util
::validate_format($cat['descriptionformat']);
2253 $category->update($cat);
2256 $transaction->allow_commit();
2260 * Returns description of method result value
2262 * @return \core_external\external_description
2265 public static function update_categories_returns() {
2270 * Returns description of method parameters
2272 * @return external_function_parameters
2275 public static function delete_categories_parameters() {
2276 return new external_function_parameters(
2278 'categories' => new external_multiple_structure(
2279 new external_single_structure(
2281 'id' => new external_value(PARAM_INT
, 'category id to delete'),
2282 'newparent' => new external_value(PARAM_INT
,
2283 'the parent category to move the contents to, if specified', VALUE_OPTIONAL
),
2284 'recursive' => new external_value(PARAM_BOOL
, '1: recursively delete all contents inside this
2285 category, 0 (default): move contents to newparent or current parent category (except if parent is root)', VALUE_DEFAULT
, 0)
2296 * @param array $categories A list of category ids
2300 public static function delete_categories($categories) {
2302 require_once($CFG->dirroot
. "/course/lib.php");
2304 // Validate parameters.
2305 $params = self
::validate_parameters(self
::delete_categories_parameters(), array('categories' => $categories));
2307 $transaction = $DB->start_delegated_transaction();
2309 foreach ($params['categories'] as $category) {
2310 $deletecat = core_course_category
::get($category['id'], MUST_EXIST
);
2311 $context = context_coursecat
::instance($deletecat->id
);
2312 require_capability('moodle/category:manage', $context);
2313 self
::validate_context($context);
2314 self
::validate_context(get_category_or_system_context($deletecat->parent
));
2316 if ($category['recursive']) {
2317 // If recursive was specified, then we recursively delete the category's contents.
2318 if ($deletecat->can_delete_full()) {
2319 $deletecat->delete_full(false);
2321 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2324 // In this situation, we don't delete the category's contents, we either move it to newparent or parent.
2325 // If the parent is the root, moving is not supported (because a course must always be inside a category).
2326 // We must move to an existing category.
2327 if (!empty($category['newparent'])) {
2328 $newparentcat = core_course_category
::get($category['newparent']);
2330 $newparentcat = core_course_category
::get($deletecat->parent
);
2333 // This operation is not allowed. We must move contents to an existing category.
2334 if (!$newparentcat->id
) {
2335 throw new moodle_exception('movecatcontentstoroot');
2338 self
::validate_context(context_coursecat
::instance($newparentcat->id
));
2339 if ($deletecat->can_move_content_to($newparentcat->id
)) {
2340 $deletecat->delete_move($newparentcat->id
, false);
2342 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2347 $transaction->allow_commit();
2351 * Returns description of method parameters
2353 * @return external_function_parameters
2356 public static function delete_categories_returns() {
2361 * Describes the parameters for delete_modules.
2363 * @return external_function_parameters
2366 public static function delete_modules_parameters() {
2367 return new external_function_parameters (
2369 'cmids' => new external_multiple_structure(new external_value(PARAM_INT
, 'course module ID',
2370 VALUE_REQUIRED
, '', NULL_NOT_ALLOWED
), 'Array of course module IDs'),
2376 * Deletes a list of provided module instances.
2378 * @param array $cmids the course module ids
2381 public static function delete_modules($cmids) {
2384 // Require course file containing the course delete module function.
2385 require_once($CFG->dirroot
. "/course/lib.php");
2387 // Clean the parameters.
2388 $params = self
::validate_parameters(self
::delete_modules_parameters(), array('cmids' => $cmids));
2390 // Keep track of the course ids we have performed a capability check on to avoid repeating.
2391 $arrcourseschecked = array();
2393 foreach ($params['cmids'] as $cmid) {
2394 // Get the course module.
2395 $cm = $DB->get_record('course_modules', array('id' => $cmid), '*', MUST_EXIST
);
2397 // Check if we have not yet confirmed they have permission in this course.
2398 if (!in_array($cm->course
, $arrcourseschecked)) {
2399 // Ensure the current user has required permission in this course.
2400 $context = context_course
::instance($cm->course
);
2401 self
::validate_context($context);
2402 // Add to the array.
2403 $arrcourseschecked[] = $cm->course
;
2406 // Ensure they can delete this module.
2407 $modcontext = context_module
::instance($cm->id
);
2408 require_capability('moodle/course:manageactivities', $modcontext);
2410 // Delete the module.
2411 course_delete_module($cm->id
);
2416 * Describes the delete_modules return value.
2418 * @return external_single_structure
2421 public static function delete_modules_returns() {
2426 * Returns description of method parameters
2428 * @return external_function_parameters
2431 public static function view_course_parameters() {
2432 return new external_function_parameters(
2434 'courseid' => new external_value(PARAM_INT
, 'id of the course'),
2435 'sectionnumber' => new external_value(PARAM_INT
, 'section number', VALUE_DEFAULT
, 0)
2441 * Trigger the course viewed event.
2443 * @param int $courseid id of course
2444 * @param int $sectionnumber sectionnumber (0, 1, 2...)
2445 * @return array of warnings and status result
2447 * @throws moodle_exception
2449 public static function view_course($courseid, $sectionnumber = 0) {
2451 require_once($CFG->dirroot
. "/course/lib.php");
2453 $params = self
::validate_parameters(self
::view_course_parameters(),
2455 'courseid' => $courseid,
2456 'sectionnumber' => $sectionnumber
2459 $warnings = array();
2461 $course = get_course($params['courseid']);
2462 $context = context_course
::instance($course->id
);
2463 self
::validate_context($context);
2465 if (!empty($params['sectionnumber'])) {
2467 // Get section details and check it exists.
2468 $modinfo = get_fast_modinfo($course);
2469 $coursesection = $modinfo->get_section_info($params['sectionnumber'], MUST_EXIST
);
2471 // Check user is allowed to see it.
2472 if (!$coursesection->uservisible
) {
2473 require_capability('moodle/course:viewhiddensections', $context);
2477 course_view($context, $params['sectionnumber']);
2480 $result['status'] = true;
2481 $result['warnings'] = $warnings;
2486 * Returns description of method result value
2488 * @return \core_external\external_description
2491 public static function view_course_returns() {
2492 return new external_single_structure(
2494 'status' => new external_value(PARAM_BOOL
, 'status: true if success'),
2495 'warnings' => new external_warnings()
2501 * Returns description of method parameters
2503 * @return external_function_parameters
2506 public static function search_courses_parameters() {
2507 return new external_function_parameters(
2509 'criterianame' => new external_value(PARAM_ALPHA
, 'criteria name
2510 (search, modulelist (only admins), blocklist (only admins), tagid)'),
2511 'criteriavalue' => new external_value(PARAM_RAW
, 'criteria value'),
2512 'page' => new external_value(PARAM_INT
, 'page number (0 based)', VALUE_DEFAULT
, 0),
2513 'perpage' => new external_value(PARAM_INT
, 'items per page', VALUE_DEFAULT
, 0),
2514 'requiredcapabilities' => new external_multiple_structure(
2515 new external_value(PARAM_CAPABILITY
, 'Capability string used to filter courses by permission'),
2516 'Optional list of required capabilities (used to filter the list)', VALUE_DEFAULT
, array()
2518 'limittoenrolled' => new external_value(PARAM_BOOL
, 'limit to enrolled courses', VALUE_DEFAULT
, 0),
2519 'onlywithcompletion' => new external_value(PARAM_BOOL
, 'limit to courses where completion is enabled',
2526 * Return the course information that is public (visible by every one)
2528 * @param core_course_list_element $course course in list object
2529 * @param stdClass $coursecontext course context object
2530 * @return array the course information
2533 protected static function get_course_public_information(core_course_list_element
$course, $coursecontext) {
2536 static $categoriescache = array();
2538 // Category information.
2539 if (!array_key_exists($course->category
, $categoriescache)) {
2540 $categoriescache[$course->category
] = core_course_category
::get($course->category
, IGNORE_MISSING
);
2542 $category = $categoriescache[$course->category
];
2544 // Retrieve course overview used files.
2546 foreach ($course->get_course_overviewfiles() as $file) {
2547 $fileurl = moodle_url
::make_webservice_pluginfile_url($file->get_contextid(), $file->get_component(),
2548 $file->get_filearea(), null, $file->get_filepath(),
2549 $file->get_filename())->out(false);
2551 'filename' => $file->get_filename(),
2552 'fileurl' => $fileurl,
2553 'filesize' => $file->get_filesize(),
2554 'filepath' => $file->get_filepath(),
2555 'mimetype' => $file->get_mimetype(),
2556 'timemodified' => $file->get_timemodified(),
2560 // Retrieve the course contacts,
2561 // we need here the users fullname since if we are not enrolled can be difficult to obtain them via other Web Services.
2562 $coursecontacts = array();
2563 foreach ($course->get_course_contacts() as $contact) {
2564 $coursecontacts[] = array(
2565 'id' => $contact['user']->id
,
2566 'fullname' => $contact['username'],
2567 'roles' => array_map(function($role){
2568 return array('id' => $role->id
, 'name' => $role->displayname
);
2569 }, $contact['roles']),
2570 'role' => array('id' => $contact['role']->id
, 'name' => $contact['role']->displayname
),
2571 'rolename' => $contact['rolename']
2575 // Allowed enrolment methods (maybe we can self-enrol).
2576 $enroltypes = array();
2577 $instances = enrol_get_instances($course->id
, true);
2578 foreach ($instances as $instance) {
2579 $enroltypes[] = $instance->enrol
;
2583 list($summary, $summaryformat) =
2584 \core_external\util
::format_text($course->summary
, $course->summaryformat
, $coursecontext, 'course', 'summary', null);
2587 if (!empty($category)) {
2588 $categoryname = \core_external\util
::format_string($category->name
, $category->get_context());
2591 $displayname = get_course_display_name_for_list($course);
2592 $coursereturns = array();
2593 $coursereturns['id'] = $course->id
;
2594 $coursereturns['fullname'] = \core_external\util
::format_string($course->fullname
, $coursecontext);
2595 $coursereturns['displayname'] = \core_external\util
::format_string($displayname, $coursecontext);
2596 $coursereturns['shortname'] = \core_external\util
::format_string($course->shortname
, $coursecontext);
2597 $coursereturns['categoryid'] = $course->category
;
2598 $coursereturns['categoryname'] = $categoryname;
2599 $coursereturns['summary'] = $summary;
2600 $coursereturns['summaryformat'] = $summaryformat;
2601 $coursereturns['summaryfiles'] = util
::get_area_files($coursecontext->id
, 'course', 'summary', false, false);
2602 $coursereturns['overviewfiles'] = $files;
2603 $coursereturns['contacts'] = $coursecontacts;
2604 $coursereturns['enrollmentmethods'] = $enroltypes;
2605 $coursereturns['sortorder'] = $course->sortorder
;
2606 $coursereturns['showactivitydates'] = $course->showactivitydates
;
2607 $coursereturns['showcompletionconditions'] = $course->showcompletionconditions
;
2609 $handler = core_course\customfield\course_handler
::create();
2610 if ($customfields = $handler->export_instance_data($course->id
)) {
2611 $coursereturns['customfields'] = [];
2612 foreach ($customfields as $data) {
2613 $coursereturns['customfields'][] = [
2614 'type' => $data->get_type(),
2615 'value' => $data->get_value(),
2616 'valueraw' => $data->get_data_controller()->get_value(),
2617 'name' => $data->get_name(),
2618 'shortname' => $data->get_shortname()
2623 $courseimage = \core_course\external\course_summary_exporter
::get_course_image($course);
2624 if (!$courseimage) {
2625 $courseimage = $OUTPUT->get_generated_url_for_course($coursecontext);
2627 $coursereturns['courseimage'] = $courseimage;
2629 return $coursereturns;
2633 * Search courses following the specified criteria.
2635 * @param string $criterianame Criteria name (search, modulelist (only admins), blocklist (only admins), tagid)
2636 * @param string $criteriavalue Criteria value
2637 * @param int $page Page number (for pagination)
2638 * @param int $perpage Items per page
2639 * @param array $requiredcapabilities Optional list of required capabilities (used to filter the list).
2640 * @param int $limittoenrolled Limit to only enrolled courses
2641 * @param int onlywithcompletion Limit to only courses where completion is enabled
2642 * @return array of course objects and warnings
2644 * @throws moodle_exception
2646 public static function search_courses($criterianame,
2650 $requiredcapabilities=array(),
2652 $onlywithcompletion=0) {
2655 $warnings = array();
2657 $parameters = array(
2658 'criterianame' => $criterianame,
2659 'criteriavalue' => $criteriavalue,
2661 'perpage' => $perpage,
2662 'requiredcapabilities' => $requiredcapabilities,
2663 'limittoenrolled' => $limittoenrolled,
2664 'onlywithcompletion' => $onlywithcompletion
2666 $params = self
::validate_parameters(self
::search_courses_parameters(), $parameters);
2667 self
::validate_context(context_system
::instance());
2669 $allowedcriterianames = array('search', 'modulelist', 'blocklist', 'tagid');
2670 if (!in_array($params['criterianame'], $allowedcriterianames)) {
2671 throw new invalid_parameter_exception('Invalid value for criterianame parameter (value: '.$params['criterianame'].'),' .
2672 'allowed values are: '.implode(',', $allowedcriterianames));
2675 if ($params['criterianame'] == 'modulelist' or $params['criterianame'] == 'blocklist') {
2676 require_capability('moodle/site:config', context_system
::instance());
2680 'search' => PARAM_RAW
,
2681 'modulelist' => PARAM_PLUGIN
,
2682 'blocklist' => PARAM_INT
,
2683 'tagid' => PARAM_INT
2685 $params['criteriavalue'] = clean_param($params['criteriavalue'], $paramtype[$params['criterianame']]);
2687 // Prepare the search API options.
2688 $searchcriteria = array();
2689 $searchcriteria[$params['criterianame']] = $params['criteriavalue'];
2690 if ($params['onlywithcompletion']) {
2691 $searchcriteria['onlywithcompletion'] = true;
2695 if ($params['perpage'] != 0) {
2696 $offset = $params['page'] * $params['perpage'];
2697 $options = array('offset' => $offset, 'limit' => $params['perpage']);
2700 // Search the courses.
2701 $courses = core_course_category
::search_courses($searchcriteria, $options, $params['requiredcapabilities']);
2702 $totalcount = core_course_category
::search_courses_count($searchcriteria, $options, $params['requiredcapabilities']);
2704 if (!empty($limittoenrolled)) {
2705 // Get the courses where the current user has access.
2706 $enrolled = enrol_get_my_courses(array('id', 'cacherev'));
2709 $finalcourses = array();
2710 $categoriescache = array();
2712 foreach ($courses as $course) {
2713 if (!empty($limittoenrolled)) {
2714 // Filter out not enrolled courses.
2715 if (!isset($enrolled[$course->id
])) {
2721 $coursecontext = context_course
::instance($course->id
);
2723 $finalcourses[] = self
::get_course_public_information($course, $coursecontext);
2727 'total' => $totalcount,
2728 'courses' => $finalcourses,
2729 'warnings' => $warnings
2734 * Returns a course structure definition
2736 * @param boolean $onlypublicdata set to true, to retrieve only fields viewable by anyone when the course is visible
2737 * @return external_single_structure the course structure
2740 protected static function get_course_structure($onlypublicdata = true) {
2741 $coursestructure = array(
2742 'id' => new external_value(PARAM_INT
, 'course id'),
2743 'fullname' => new external_value(PARAM_RAW
, 'course full name'),
2744 'displayname' => new external_value(PARAM_RAW
, 'course display name'),
2745 'shortname' => new external_value(PARAM_RAW
, 'course short name'),
2746 'courseimage' => new external_value(PARAM_URL
, 'Course image', VALUE_OPTIONAL
),
2747 'categoryid' => new external_value(PARAM_INT
, 'category id'),
2748 'categoryname' => new external_value(PARAM_RAW
, 'category name'),
2749 'sortorder' => new external_value(PARAM_INT
, 'Sort order in the category', VALUE_OPTIONAL
),
2750 'summary' => new external_value(PARAM_RAW
, 'summary'),
2751 'summaryformat' => new external_format_value('summary'),
2752 'summaryfiles' => new external_files('summary files in the summary field', VALUE_OPTIONAL
),
2753 'overviewfiles' => new external_files('additional overview files attached to this course'),
2754 'showactivitydates' => new external_value(PARAM_BOOL
, 'Whether the activity dates are shown or not'),
2755 'showcompletionconditions' => new external_value(PARAM_BOOL
,
2756 'Whether the activity completion conditions are shown or not'),
2757 'contacts' => new external_multiple_structure(
2758 new external_single_structure(
2760 'id' => new external_value(PARAM_INT
, 'contact user id'),
2761 'fullname' => new external_value(PARAM_NOTAGS
, 'contact user fullname'),
2766 'enrollmentmethods' => new external_multiple_structure(
2767 new external_value(PARAM_PLUGIN
, 'enrollment method'),
2768 'enrollment methods list'
2770 'customfields' => new external_multiple_structure(
2771 new external_single_structure(
2773 'name' => new external_value(PARAM_RAW
, 'The name of the custom field'),
2774 'shortname' => new external_value(PARAM_RAW
,
2775 'The shortname of the custom field - to be able to build the field class in the code'),
2776 'type' => new external_value(PARAM_ALPHANUMEXT
,
2777 'The type of the custom field - text field, checkbox...'),
2778 'valueraw' => new external_value(PARAM_RAW
, 'The raw value of the custom field'),
2779 'value' => new external_value(PARAM_RAW
, 'The value of the custom field'),
2781 ), 'Custom fields', VALUE_OPTIONAL
),
2784 if (!$onlypublicdata) {
2786 'idnumber' => new external_value(PARAM_RAW
, 'Id number', VALUE_OPTIONAL
),
2787 'format' => new external_value(PARAM_PLUGIN
, 'Course format: weeks, topics, social, site,..', VALUE_OPTIONAL
),
2788 'showgrades' => new external_value(PARAM_INT
, '1 if grades are shown, otherwise 0', VALUE_OPTIONAL
),
2789 'newsitems' => new external_value(PARAM_INT
, 'Number of recent items appearing on the course page', VALUE_OPTIONAL
),
2790 'startdate' => new external_value(PARAM_INT
, 'Timestamp when the course start', VALUE_OPTIONAL
),
2791 'enddate' => new external_value(PARAM_INT
, 'Timestamp when the course end', VALUE_OPTIONAL
),
2792 'maxbytes' => new external_value(PARAM_INT
, 'Largest size of file that can be uploaded into', VALUE_OPTIONAL
),
2793 'showreports' => new external_value(PARAM_INT
, 'Are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL
),
2794 'visible' => new external_value(PARAM_INT
, '1: available to student, 0:not available', VALUE_OPTIONAL
),
2795 'groupmode' => new external_value(PARAM_INT
, 'no group, separate, visible', VALUE_OPTIONAL
),
2796 'groupmodeforce' => new external_value(PARAM_INT
, '1: yes, 0: no', VALUE_OPTIONAL
),
2797 'defaultgroupingid' => new external_value(PARAM_INT
, 'default grouping id', VALUE_OPTIONAL
),
2798 'enablecompletion' => new external_value(PARAM_INT
, 'Completion enabled? 1: yes 0: no', VALUE_OPTIONAL
),
2799 'completionnotify' => new external_value(PARAM_INT
, '1: yes 0: no', VALUE_OPTIONAL
),
2800 'lang' => new external_value(PARAM_SAFEDIR
, 'Forced course language', VALUE_OPTIONAL
),
2801 'theme' => new external_value(PARAM_PLUGIN
, 'Fame of the forced theme', VALUE_OPTIONAL
),
2802 'marker' => new external_value(PARAM_INT
, 'Current course marker', VALUE_OPTIONAL
),
2803 'legacyfiles' => new external_value(PARAM_INT
, 'If legacy files are enabled', VALUE_OPTIONAL
),
2804 'calendartype' => new external_value(PARAM_PLUGIN
, 'Calendar type', VALUE_OPTIONAL
),
2805 'timecreated' => new external_value(PARAM_INT
, 'Time when the course was created', VALUE_OPTIONAL
),
2806 'timemodified' => new external_value(PARAM_INT
, 'Last time the course was updated', VALUE_OPTIONAL
),
2807 'requested' => new external_value(PARAM_INT
, 'If is a requested course', VALUE_OPTIONAL
),
2808 'cacherev' => new external_value(PARAM_INT
, 'Cache revision number', VALUE_OPTIONAL
),
2809 'filters' => new external_multiple_structure(
2810 new external_single_structure(
2812 'filter' => new external_value(PARAM_PLUGIN
, 'Filter plugin name'),
2813 'localstate' => new external_value(PARAM_INT
, 'Filter state: 1 for on, -1 for off, 0 if inherit'),
2814 'inheritedstate' => new external_value(PARAM_INT
, '1 or 0 to use when localstate is set to inherit'),
2817 'Course filters', VALUE_OPTIONAL
2819 'courseformatoptions' => new external_multiple_structure(
2820 new external_single_structure(
2822 'name' => new external_value(PARAM_RAW
, 'Course format option name.'),
2823 'value' => new external_value(PARAM_RAW
, 'Course format option value.'),
2826 'Additional options for particular course format.', VALUE_OPTIONAL
2828 'communicationroomname' => new external_value(PARAM_TEXT
, 'Communication tool room name.', VALUE_OPTIONAL
),
2829 'communicationroomurl' => new external_value(PARAM_RAW
, 'Communication tool room URL.', VALUE_OPTIONAL
),
2831 $coursestructure = array_merge($coursestructure, $extra);
2833 return new external_single_structure($coursestructure);
2837 * Returns description of method result value
2839 * @return \core_external\external_description
2842 public static function search_courses_returns() {
2843 return new external_single_structure(
2845 'total' => new external_value(PARAM_INT
, 'total course count'),
2846 'courses' => new external_multiple_structure(self
::get_course_structure(), 'course'),
2847 'warnings' => new external_warnings()
2853 * Returns description of method parameters
2855 * @return external_function_parameters
2858 public static function get_course_module_parameters() {
2859 return new external_function_parameters(
2861 'cmid' => new external_value(PARAM_INT
, 'The course module id')
2867 * Return information about a course module.
2869 * @param int $cmid the course module id
2870 * @return array of warnings and the course module
2872 * @throws moodle_exception
2874 public static function get_course_module($cmid) {
2877 $params = self
::validate_parameters(self
::get_course_module_parameters(), array('cmid' => $cmid));
2878 $warnings = array();
2880 $cm = get_coursemodule_from_id(null, $params['cmid'], 0, true, MUST_EXIST
);
2881 $context = context_module
::instance($cm->id
);
2882 self
::validate_context($context);
2884 // If the user has permissions to manage the activity, return all the information.
2885 if (has_capability('moodle/course:manageactivities', $context)) {
2886 require_once($CFG->dirroot
. '/course/modlib.php');
2887 require_once($CFG->libdir
. '/gradelib.php');
2890 // Get the extra information: grade, advanced grading and outcomes data.
2891 $course = get_course($cm->course
);
2892 list($newcm, $newcontext, $module, $extrainfo, $cw) = get_moduleinfo_data($cm, $course);
2894 $gradeinfo = array('grade', 'gradepass', 'gradecat');
2895 foreach ($gradeinfo as $gfield) {
2896 if (isset($extrainfo->{$gfield})) {
2897 $info->{$gfield} = $extrainfo->{$gfield};
2900 if (isset($extrainfo->grade
) and $extrainfo->grade
< 0) {
2901 $info->scale
= $DB->get_field('scale', 'scale', array('id' => abs($extrainfo->grade
)));
2903 // Advanced grading.
2904 if (isset($extrainfo->_advancedgradingdata
)) {
2905 $info->advancedgrading
= array();
2906 foreach ($extrainfo as $key => $val) {
2907 if (strpos($key, 'advancedgradingmethod_') === 0) {
2908 $info->advancedgrading
[] = array(
2909 'area' => str_replace('advancedgradingmethod_', '', $key),
2916 foreach ($extrainfo as $key => $val) {
2917 if (strpos($key, 'outcome_') === 0) {
2918 if (!isset($info->outcomes
)) {
2919 $info->outcomes
= array();
2921 $id = str_replace('outcome_', '', $key);
2922 $outcome = grade_outcome
::fetch(array('id' => $id));
2923 $scaleitems = $outcome->load_scale();
2924 $info->outcomes
[] = array(
2926 'name' => \core_external\util
::format_string($outcome->get_name(), $context),
2927 'scale' => $scaleitems->scale
2932 // Return information is safe to show to any user.
2933 $info = new stdClass();
2934 $info->id
= $cm->id
;
2935 $info->course
= $cm->course
;
2936 $info->module
= $cm->module
;
2937 $info->modname
= $cm->modname
;
2938 $info->instance
= $cm->instance
;
2939 $info->section
= $cm->section
;
2940 $info->sectionnum
= $cm->sectionnum
;
2941 $info->groupmode
= $cm->groupmode
;
2942 $info->groupingid
= $cm->groupingid
;
2943 $info->completion
= $cm->completion
;
2944 $info->downloadcontent
= $cm->downloadcontent
;
2947 $info->name
= \core_external\util
::format_string($cm->name
, $context);
2949 $result['cm'] = $info;
2950 $result['warnings'] = $warnings;
2955 * Returns description of method result value
2957 * @return \core_external\external_description
2960 public static function get_course_module_returns() {
2961 return new external_single_structure(
2963 'cm' => new external_single_structure(
2965 'id' => new external_value(PARAM_INT
, 'The course module id'),
2966 'course' => new external_value(PARAM_INT
, 'The course id'),
2967 'module' => new external_value(PARAM_INT
, 'The module type id'),
2968 'name' => new external_value(PARAM_RAW
, 'The activity name'),
2969 'modname' => new external_value(PARAM_COMPONENT
, 'The module component name (forum, assign, etc..)'),
2970 'instance' => new external_value(PARAM_INT
, 'The activity instance id'),
2971 'section' => new external_value(PARAM_INT
, 'The module section id'),
2972 'sectionnum' => new external_value(PARAM_INT
, 'The module section number'),
2973 'groupmode' => new external_value(PARAM_INT
, 'Group mode'),
2974 'groupingid' => new external_value(PARAM_INT
, 'Grouping id'),
2975 'completion' => new external_value(PARAM_INT
, 'If completion is enabled'),
2976 'idnumber' => new external_value(PARAM_RAW
, 'Module id number', VALUE_OPTIONAL
),
2977 'added' => new external_value(PARAM_INT
, 'Time added', VALUE_OPTIONAL
),
2978 'score' => new external_value(PARAM_INT
, 'Score', VALUE_OPTIONAL
),
2979 'indent' => new external_value(PARAM_INT
, 'Indentation', VALUE_OPTIONAL
),
2980 'visible' => new external_value(PARAM_INT
, 'If visible', VALUE_OPTIONAL
),
2981 'visibleoncoursepage' => new external_value(PARAM_INT
, 'If visible on course page', VALUE_OPTIONAL
),
2982 'visibleold' => new external_value(PARAM_INT
, 'Visible old', VALUE_OPTIONAL
),
2983 'completiongradeitemnumber' => new external_value(PARAM_INT
, 'Completion grade item', VALUE_OPTIONAL
),
2984 'completionpassgrade' => new external_value(PARAM_INT
, 'Completion pass grade setting', VALUE_OPTIONAL
),
2985 'completionview' => new external_value(PARAM_INT
, 'Completion view setting', VALUE_OPTIONAL
),
2986 'completionexpected' => new external_value(PARAM_INT
, 'Completion time expected', VALUE_OPTIONAL
),
2987 'showdescription' => new external_value(PARAM_INT
, 'If the description is showed', VALUE_OPTIONAL
),
2988 'downloadcontent' => new external_value(PARAM_INT
, 'The download content value', VALUE_OPTIONAL
),
2989 'availability' => new external_value(PARAM_RAW
, 'Availability settings', VALUE_OPTIONAL
),
2990 'grade' => new external_value(PARAM_FLOAT
, 'Grade (max value or scale id)', VALUE_OPTIONAL
),
2991 'scale' => new external_value(PARAM_TEXT
, 'Scale items (if used)', VALUE_OPTIONAL
),
2992 'gradepass' => new external_value(PARAM_RAW
, 'Grade to pass (float)', VALUE_OPTIONAL
),
2993 'gradecat' => new external_value(PARAM_INT
, 'Grade category', VALUE_OPTIONAL
),
2994 'advancedgrading' => new external_multiple_structure(
2995 new external_single_structure(
2997 'area' => new external_value(PARAM_AREA
, 'Gradable area name'),
2998 'method' => new external_value(PARAM_COMPONENT
, 'Grading method'),
3001 'Advanced grading settings', VALUE_OPTIONAL
3003 'outcomes' => new external_multiple_structure(
3004 new external_single_structure(
3006 'id' => new external_value(PARAM_ALPHANUMEXT
, 'Outcome id'),
3007 'name' => new external_value(PARAM_RAW
, 'Outcome full name'),
3008 'scale' => new external_value(PARAM_TEXT
, 'Scale items')
3011 'Outcomes information', VALUE_OPTIONAL
3015 'warnings' => new external_warnings()
3021 * Returns description of method parameters
3023 * @return external_function_parameters
3026 public static function get_course_module_by_instance_parameters() {
3027 return new external_function_parameters(
3029 'module' => new external_value(PARAM_COMPONENT
, 'The module name'),
3030 'instance' => new external_value(PARAM_INT
, 'The module instance id')
3036 * Return information about a course module.
3038 * @param string $module the module name
3039 * @param int $instance the activity instance id
3040 * @return array of warnings and the course module
3042 * @throws moodle_exception
3044 public static function get_course_module_by_instance($module, $instance) {
3046 $params = self
::validate_parameters(self
::get_course_module_by_instance_parameters(),
3048 'module' => $module,
3049 'instance' => $instance,
3052 $warnings = array();
3053 $cm = get_coursemodule_from_instance($params['module'], $params['instance'], 0, false, MUST_EXIST
);
3055 return self
::get_course_module($cm->id
);
3059 * Returns description of method result value
3061 * @return \core_external\external_description
3064 public static function get_course_module_by_instance_returns() {
3065 return self
::get_course_module_returns();
3069 * Returns description of method parameters
3071 * @return external_function_parameters
3074 public static function get_user_navigation_options_parameters() {
3075 return new external_function_parameters(
3077 'courseids' => new external_multiple_structure(new external_value(PARAM_INT
, 'Course id.')),
3083 * Return a list of navigation options in a set of courses that are avaialable or not for the current user.
3085 * @param array $courseids a list of course ids
3086 * @return array of warnings and the options availability
3088 * @throws moodle_exception
3090 public static function get_user_navigation_options($courseids) {
3092 require_once($CFG->dirroot
. '/course/lib.php');
3094 // Parameter validation.
3095 $params = self
::validate_parameters(self
::get_user_navigation_options_parameters(), array('courseids' => $courseids));
3096 $courseoptions = array();
3098 list($courses, $warnings) = util
::validate_courses($params['courseids'], array(), true);
3100 if (!empty($courses)) {
3101 foreach ($courses as $course) {
3102 // Fix the context for the frontpage.
3103 if ($course->id
== SITEID
) {
3104 $course->context
= context_system
::instance();
3106 $navoptions = course_get_user_navigation_options($course->context
, $course);
3108 foreach ($navoptions as $name => $available) {
3111 'available' => $available,
3115 $courseoptions[] = array(
3116 'id' => $course->id
,
3117 'options' => $options
3123 'courses' => $courseoptions,
3124 'warnings' => $warnings
3130 * Returns description of method result value
3132 * @return \core_external\external_description
3135 public static function get_user_navigation_options_returns() {
3136 return new external_single_structure(
3138 'courses' => new external_multiple_structure(
3139 new external_single_structure(
3141 'id' => new external_value(PARAM_INT
, 'Course id'),
3142 'options' => new external_multiple_structure(
3143 new external_single_structure(
3145 'name' => new external_value(PARAM_ALPHANUMEXT
, 'Option name'),
3146 'available' => new external_value(PARAM_BOOL
, 'Whether the option is available or not'),
3151 ), 'List of courses'
3153 'warnings' => new external_warnings()
3159 * Returns description of method parameters
3161 * @return external_function_parameters
3164 public static function get_user_administration_options_parameters() {
3165 return new external_function_parameters(
3167 'courseids' => new external_multiple_structure(new external_value(PARAM_INT
, 'Course id.')),
3173 * Return a list of administration options in a set of courses that are available or not for the current user.
3175 * @param array $courseids a list of course ids
3176 * @return array of warnings and the options availability
3178 * @throws moodle_exception
3180 public static function get_user_administration_options($courseids) {
3182 require_once($CFG->dirroot
. '/course/lib.php');
3184 // Parameter validation.
3185 $params = self
::validate_parameters(self
::get_user_administration_options_parameters(), array('courseids' => $courseids));
3186 $courseoptions = array();
3188 list($courses, $warnings) = util
::validate_courses($params['courseids'], array(), true);
3190 if (!empty($courses)) {
3191 foreach ($courses as $course) {
3192 $adminoptions = course_get_user_administration_options($course, $course->context
);
3194 foreach ($adminoptions as $name => $available) {
3197 'available' => $available,
3201 $courseoptions[] = array(
3202 'id' => $course->id
,
3203 'options' => $options
3209 'courses' => $courseoptions,
3210 'warnings' => $warnings
3216 * Returns description of method result value
3218 * @return \core_external\external_description
3221 public static function get_user_administration_options_returns() {
3222 return self
::get_user_navigation_options_returns();
3226 * Returns description of method parameters
3228 * @return external_function_parameters
3231 public static function get_courses_by_field_parameters() {
3232 return new external_function_parameters(
3234 'field' => new external_value(PARAM_ALPHA
, 'The field to search can be left empty for all courses or:
3236 ids: comma separated course ids
3237 shortname: course short name
3238 idnumber: course id number
3239 category: category id the course belongs to
3240 ', VALUE_DEFAULT
, ''),
3241 'value' => new external_value(PARAM_RAW
, 'The value to match', VALUE_DEFAULT
, '')
3248 * Get courses matching a specific field (id/s, shortname, idnumber, category)
3250 * @param string $field field name to search, or empty for all courses
3251 * @param string $value value to search
3252 * @return array list of courses and warnings
3253 * @throws invalid_parameter_exception
3256 public static function get_courses_by_field($field = '', $value = '') {
3258 require_once($CFG->dirroot
. '/course/lib.php');
3259 require_once($CFG->libdir
. '/filterlib.php');
3261 $params = self
::validate_parameters(self
::get_courses_by_field_parameters(),
3267 $warnings = array();
3269 if (empty($params['field'])) {
3270 $courses = $DB->get_records('course', null, 'id ASC');
3272 switch ($params['field']) {
3275 $value = clean_param($params['value'], PARAM_INT
);
3278 $value = clean_param($params['value'], PARAM_SEQUENCE
);
3281 $value = clean_param($params['value'], PARAM_TEXT
);
3284 $value = clean_param($params['value'], PARAM_RAW
);
3287 throw new invalid_parameter_exception('Invalid field name');
3290 if ($params['field'] === 'ids') {
3291 // Preload categories to avoid loading one at a time.
3292 $courseids = explode(',', $value);
3293 list ($listsql, $listparams) = $DB->get_in_or_equal($courseids);
3294 $categoryids = $DB->get_fieldset_sql("
3295 SELECT DISTINCT cc.id
3297 JOIN {course_categories} cc ON cc.id = c.category
3298 WHERE c.id $listsql", $listparams);
3299 core_course_category
::get_many($categoryids);
3301 // Load and validate all courses. This is called because it loads the courses
3302 // more efficiently.
3303 list ($courses, $warnings) = util
::validate_courses($courseids, [],
3306 $courses = $DB->get_records('course', array($params['field'] => $value), 'id ASC');
3310 $iscommapiavailable = \core_communication\api
::is_available();
3312 $coursesdata = array();
3313 foreach ($courses as $course) {
3314 $context = context_course
::instance($course->id
);
3315 $canupdatecourse = has_capability('moodle/course:update', $context);
3316 $canviewhiddencourses = has_capability('moodle/course:viewhiddencourses', $context);
3318 // Check if the course is visible in the site for the user.
3319 if (!$course->visible
and !$canviewhiddencourses and !$canupdatecourse) {
3322 // Get the public course information, even if we are not enrolled.
3323 $courseinlist = new core_course_list_element($course);
3325 // Now, check if we have access to the course, unless it was already checked.
3327 if (empty($course->contextvalidated
)) {
3328 self
::validate_context($context);
3330 } catch (Exception
$e) {
3331 // User can not access the course, check if they can see the public information about the course and return it.
3332 if (core_course_category
::can_view_course_info($course)) {
3333 $coursesdata[$course->id
] = self
::get_course_public_information($courseinlist, $context);
3337 $coursesdata[$course->id
] = self
::get_course_public_information($courseinlist, $context);
3338 // Return information for any user that can access the course.
3339 $coursefields = array('format', 'showgrades', 'newsitems', 'startdate', 'enddate', 'maxbytes', 'showreports', 'visible',
3340 'groupmode', 'groupmodeforce', 'defaultgroupingid', 'enablecompletion', 'completionnotify', 'lang', 'theme',
3344 $coursesdata[$course->id
]['filters'] = filter_get_available_in_context($context);
3346 // Information for managers only.
3347 if ($canupdatecourse) {
3348 $managerfields = array('idnumber', 'legacyfiles', 'calendartype', 'timecreated', 'timemodified', 'requested',
3350 $coursefields = array_merge($coursefields, $managerfields);
3354 foreach ($coursefields as $field) {
3355 $coursesdata[$course->id
][$field] = $course->{$field};
3358 // Clean lang and auth fields for external functions (it may content uninstalled themes or language packs).
3359 if (isset($coursesdata[$course->id
]['theme'])) {
3360 $coursesdata[$course->id
]['theme'] = clean_param($coursesdata[$course->id
]['theme'], PARAM_THEME
);
3362 if (isset($coursesdata[$course->id
]['lang'])) {
3363 $coursesdata[$course->id
]['lang'] = clean_param($coursesdata[$course->id
]['lang'], PARAM_LANG
);
3366 $courseformatoptions = course_get_format($course)->get_config_for_external();
3367 foreach ($courseformatoptions as $key => $value) {
3368 $coursesdata[$course->id
]['courseformatoptions'][] = array(
3374 // Communication tools for the course.
3375 if ($iscommapiavailable) {
3376 $communication = \core_communication\api
::load_by_instance(
3378 component
: 'core_course',
3379 instancetype
: 'coursecommunication',
3380 instanceid
: $course->id
3382 if ($communication->get_provider()) {
3383 $coursesdata[$course->id
]['communicationroomname'] = \core_external\util
::format_string($communication->get_room_name(), $context);
3384 // This will be usually an URL, however, it is better to consider that can be anything a plugin might return, this is why we will use PARAM_RAW.
3385 $coursesdata[$course->id
]['communicationroomurl'] = $communication->get_communication_room_url();
3391 'courses' => $coursesdata,
3392 'warnings' => $warnings
3397 * Returns description of method result value
3399 * @return \core_external\external_description
3402 public static function get_courses_by_field_returns() {
3403 // Course structure, including not only public viewable fields.
3404 return new external_single_structure(
3406 'courses' => new external_multiple_structure(self
::get_course_structure(false), 'Course'),
3407 'warnings' => new external_warnings()
3413 * Returns description of method parameters
3415 * @return external_function_parameters
3418 public static function check_updates_parameters() {
3419 return new external_function_parameters(
3421 'courseid' => new external_value(PARAM_INT
, 'Course id to check'),
3422 'tocheck' => new external_multiple_structure(
3423 new external_single_structure(
3425 'contextlevel' => new external_value(PARAM_ALPHA
, 'The context level for the file location.
3426 Only module supported right now.'),
3427 'id' => new external_value(PARAM_INT
, 'Context instance id'),
3428 'since' => new external_value(PARAM_INT
, 'Check updates since this time stamp'),
3431 'Instances to check'
3433 'filter' => new external_multiple_structure(
3434 new external_value(PARAM_ALPHANUM
, 'Area name: configuration, fileareas, completion, ratings, comments,
3435 gradeitems, outcomes'),
3436 'Check only for updates in these areas', VALUE_DEFAULT
, array()
3443 * Check if there is updates affecting the user for the given course and contexts.
3444 * Right now only modules are supported.
3445 * This WS calls mod_check_updates_since for each module to check if there is any update the user should we aware of.
3447 * @param int $courseid the list of modules to check
3448 * @param array $tocheck the list of modules to check
3449 * @param array $filter check only for updates in these areas
3450 * @return array list of updates and warnings
3451 * @throws moodle_exception
3454 public static function check_updates($courseid, $tocheck, $filter = array()) {
3456 require_once($CFG->dirroot
. "/course/lib.php");
3458 $params = self
::validate_parameters(
3459 self
::check_updates_parameters(),
3461 'courseid' => $courseid,
3462 'tocheck' => $tocheck,
3463 'filter' => $filter,
3467 $course = get_course($params['courseid']);
3468 $context = context_course
::instance($course->id
);
3469 self
::validate_context($context);
3471 list($instances, $warnings) = course_check_updates($course, $params['tocheck'], $filter);
3473 $instancesformatted = array();
3474 foreach ($instances as $instance) {
3476 foreach ($instance['updates'] as $name => $data) {
3477 if (empty($data->updated
)) {
3480 $updatedata = array(
3483 if (!empty($data->timeupdated
)) {
3484 $updatedata['timeupdated'] = $data->timeupdated
;
3486 if (!empty($data->itemids
)) {
3487 $updatedata['itemids'] = $data->itemids
;
3489 $updates[] = $updatedata;
3491 if (!empty($updates)) {
3492 $instancesformatted[] = array(
3493 'contextlevel' => $instance['contextlevel'],
3494 'id' => $instance['id'],
3495 'updates' => $updates
3501 'instances' => $instancesformatted,
3502 'warnings' => $warnings
3507 * Returns description of method result value
3509 * @return \core_external\external_description
3512 public static function check_updates_returns() {
3513 return new external_single_structure(
3515 'instances' => new external_multiple_structure(
3516 new external_single_structure(
3518 'contextlevel' => new external_value(PARAM_ALPHA
, 'The context level'),
3519 'id' => new external_value(PARAM_INT
, 'Instance id'),
3520 'updates' => new external_multiple_structure(
3521 new external_single_structure(
3523 'name' => new external_value(PARAM_ALPHANUMEXT
, 'Name of the area updated.'),
3524 'timeupdated' => new external_value(PARAM_INT
, 'Last time was updated', VALUE_OPTIONAL
),
3525 'itemids' => new external_multiple_structure(
3526 new external_value(PARAM_INT
, 'Instance id'),
3527 'The ids of the items updated',
3536 'warnings' => new external_warnings()
3542 * Returns description of method parameters
3544 * @return external_function_parameters
3547 public static function get_updates_since_parameters() {
3548 return new external_function_parameters(
3550 'courseid' => new external_value(PARAM_INT
, 'Course id to check'),
3551 'since' => new external_value(PARAM_INT
, 'Check updates since this time stamp'),
3552 'filter' => new external_multiple_structure(
3553 new external_value(PARAM_ALPHANUM
, 'Area name: configuration, fileareas, completion, ratings, comments,
3554 gradeitems, outcomes'),
3555 'Check only for updates in these areas', VALUE_DEFAULT
, array()
3562 * Check if there are updates affecting the user for the given course since the given time stamp.
3564 * This function is a wrapper of self::check_updates for retrieving all the updates since a given time for all the activities.
3566 * @param int $courseid the list of modules to check
3567 * @param int $since check updates since this time stamp
3568 * @param array $filter check only for updates in these areas
3569 * @return array list of updates and warnings
3570 * @throws moodle_exception
3573 public static function get_updates_since($courseid, $since, $filter = array()) {
3576 $params = self
::validate_parameters(
3577 self
::get_updates_since_parameters(),
3579 'courseid' => $courseid,
3581 'filter' => $filter,
3585 $course = get_course($params['courseid']);
3586 $modinfo = get_fast_modinfo($course);
3589 // Retrieve all the visible course modules for the current user.
3590 $cms = $modinfo->get_cms();
3591 foreach ($cms as $cm) {
3592 if (!$cm->uservisible
) {
3597 'contextlevel' => 'module',
3598 'since' => $params['since'],
3602 return self
::check_updates($course->id
, $tocheck, $params['filter']);
3606 * Returns description of method result value
3608 * @return \core_external\external_description
3611 public static function get_updates_since_returns() {
3612 return self
::check_updates_returns();
3616 * Parameters for function edit_module()
3619 * @return external_function_parameters
3621 public static function edit_module_parameters() {
3622 return new external_function_parameters(
3624 'action' => new external_value(PARAM_ALPHA
,
3625 'action: hide, show, stealth, duplicate, delete, moveleft, moveright, group...', VALUE_REQUIRED
),
3626 'id' => new external_value(PARAM_INT
, 'course module id', VALUE_REQUIRED
),
3627 'sectionreturn' => new external_value(PARAM_INT
, 'section to return to', VALUE_DEFAULT
, null),
3632 * Performs one of the edit module actions and return new html for AJAX
3634 * Returns html to replace the current module html with, for example:
3635 * - empty string for "delete" action,
3636 * - two modules html for "duplicate" action
3637 * - updated module html for everything else
3639 * Throws exception if operation is not permitted/possible
3642 * @param string $action
3644 * @param null|int $sectionreturn
3647 public static function edit_module($action, $id, $sectionreturn = null) {
3649 // Validate and normalize parameters.
3650 $params = self
::validate_parameters(self
::edit_module_parameters(),
3651 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3652 $action = $params['action'];
3653 $id = $params['id'];
3654 $sectionreturn = $params['sectionreturn'];
3656 // Set of permissions an editing user may have.
3658 'moodle/course:update',
3659 'moodle/course:manageactivities',
3660 'moodle/course:activityvisibility',
3661 'moodle/course:sectionvisibility',
3662 'moodle/course:movesections',
3663 'moodle/course:setcurrentsection',
3665 $PAGE->set_other_editing_capability($contextarray);
3667 list($course, $cm) = get_course_and_cm_from_cmid($id);
3668 $modcontext = context_module
::instance($cm->id
);
3669 $coursecontext = context_course
::instance($course->id
);
3670 self
::validate_context($modcontext);
3671 $format = course_get_format($course);
3672 if (!is_null($sectionreturn)) {
3673 $format->set_sectionnum($sectionreturn);
3675 $renderer = $format->get_renderer($PAGE);
3681 require_capability('moodle/course:activityvisibility', $modcontext);
3682 $visible = ($action === 'hide') ?
0 : 1;
3683 $visibleoncoursepage = ($action === 'stealth') ?
0 : 1;
3684 set_coursemodule_visible($id, $visible, $visibleoncoursepage);
3685 \core\event\course_module_updated
::create_from_cm($cm, $modcontext)->trigger();
3688 require_capability('moodle/course:manageactivities', $coursecontext);
3689 require_capability('moodle/backup:backuptargetimport', $coursecontext);
3690 require_capability('moodle/restore:restoretargetimport', $coursecontext);
3691 if (!course_allowed_module($course, $cm->modname
)) {
3692 throw new moodle_exception('No permission to create that activity');
3694 if ($newcm = duplicate_module($course, $cm)) {
3696 $modinfo = $format->get_modinfo();
3697 $section = $modinfo->get_section_info($newcm->sectionnum
);
3698 $cm = $modinfo->get_cm($id);
3700 // Get both original and new element html.
3701 $result = $renderer->course_section_updated_cm_item($format, $section, $cm);
3702 $result .= $renderer->course_section_updated_cm_item($format, $section, $newcm);
3706 case 'groupsseparate':
3707 case 'groupsvisible':
3709 require_capability('moodle/course:manageactivities', $modcontext);
3710 if ($action === 'groupsseparate') {
3711 $newgroupmode = SEPARATEGROUPS
;
3712 } else if ($action === 'groupsvisible') {
3713 $newgroupmode = VISIBLEGROUPS
;
3715 $newgroupmode = NOGROUPS
;
3717 if (set_coursemodule_groupmode($cm->id
, $newgroupmode)) {
3718 \core\event\course_module_updated
::create_from_cm($cm, $modcontext)->trigger();
3723 require_capability('moodle/course:manageactivities', $modcontext);
3724 $indent = $cm->indent +
(($action === 'moveright') ?
1 : -1);
3725 if ($cm->indent
>= 0) {
3726 $DB->update_record('course_modules', array('id' => $cm->id
, 'indent' => $indent));
3727 rebuild_course_cache($cm->course
);
3731 require_capability('moodle/course:manageactivities', $modcontext);
3732 course_delete_module($cm->id
, true);
3735 throw new coding_exception('Unrecognised action');
3738 $modinfo = $format->get_modinfo();
3739 $section = $modinfo->get_section_info($cm->sectionnum
);
3740 $cm = $modinfo->get_cm($id);
3741 return $renderer->course_section_updated_cm_item($format, $section, $cm);
3745 * Return structure for edit_module()
3748 * @return \core_external\external_description
3750 public static function edit_module_returns() {
3751 return new external_value(PARAM_RAW
, 'html to replace the current module with');
3755 * Parameters for function get_module()
3758 * @return external_function_parameters
3760 public static function get_module_parameters() {
3761 return new external_function_parameters(
3763 'id' => new external_value(PARAM_INT
, 'course module id', VALUE_REQUIRED
),
3764 'sectionreturn' => new external_value(PARAM_INT
, 'section to return to', VALUE_DEFAULT
, null),
3769 * Returns html for displaying one activity module on course page
3773 * @param null|int $sectionreturn
3776 public static function get_module($id, $sectionreturn = null) {
3778 // Validate and normalize parameters.
3779 $params = self
::validate_parameters(self
::get_module_parameters(),
3780 array('id' => $id, 'sectionreturn' => $sectionreturn));
3781 $id = $params['id'];
3782 $sectionreturn = $params['sectionreturn'];
3784 // Set of permissions an editing user may have.
3786 'moodle/course:update',
3787 'moodle/course:manageactivities',
3788 'moodle/course:activityvisibility',
3789 'moodle/course:sectionvisibility',
3790 'moodle/course:movesections',
3791 'moodle/course:setcurrentsection',
3793 $PAGE->set_other_editing_capability($contextarray);
3795 // Validate access to the course (note, this is html for the course view page, we don't validate access to the module).
3796 list($course, $cm) = get_course_and_cm_from_cmid($id);
3797 self
::validate_context(context_course
::instance($course->id
));
3799 $format = course_get_format($course);
3800 if (!is_null($sectionreturn)) {
3801 $format->set_sectionnum($sectionreturn);
3803 $renderer = $format->get_renderer($PAGE);
3805 $modinfo = $format->get_modinfo();
3806 $section = $modinfo->get_section_info($cm->sectionnum
);
3807 return $renderer->course_section_updated_cm_item($format, $section, $cm);
3811 * Return structure for get_module()
3814 * @return \core_external\external_description
3816 public static function get_module_returns() {
3817 return new external_value(PARAM_RAW
, 'html to replace the current module with');
3821 * Parameters for function edit_section()
3824 * @return external_function_parameters
3826 public static function edit_section_parameters() {
3827 return new external_function_parameters(
3829 'action' => new external_value(PARAM_ALPHA
, 'action: hide, show, stealth, setmarker, removemarker', VALUE_REQUIRED
),
3830 'id' => new external_value(PARAM_INT
, 'course section id', VALUE_REQUIRED
),
3831 'sectionreturn' => new external_value(PARAM_INT
, 'section to return to', VALUE_DEFAULT
, null),
3836 * Performs one of the edit section actions
3839 * @param string $action
3840 * @param int $id section id
3841 * @param int $sectionreturn section to return to
3844 public static function edit_section($action, $id, $sectionreturn) {
3846 // Validate and normalize parameters.
3847 $params = self
::validate_parameters(self
::edit_section_parameters(),
3848 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3849 $action = $params['action'];
3850 $id = $params['id'];
3851 $sr = $params['sectionreturn'];
3853 $section = $DB->get_record('course_sections', array('id' => $id), '*', MUST_EXIST
);
3854 $coursecontext = context_course
::instance($section->course
);
3855 self
::validate_context($coursecontext);
3857 $rv = course_get_format($section->course
)->section_action($section, $action, $sectionreturn);
3859 return json_encode($rv);
3866 * Return structure for edit_section()
3869 * @return \core_external\external_description
3871 public static function edit_section_returns() {
3872 return new external_value(PARAM_RAW
, 'Additional data for javascript (JSON-encoded string)');
3876 * Returns description of method parameters
3878 * @return external_function_parameters
3880 public static function get_enrolled_courses_by_timeline_classification_parameters() {
3881 return new external_function_parameters(
3883 'classification' => new external_value(PARAM_ALPHA
, 'future, inprogress, or past'),
3884 'limit' => new external_value(PARAM_INT
, 'Result set limit', VALUE_DEFAULT
, 0),
3885 'offset' => new external_value(PARAM_INT
, 'Result set offset', VALUE_DEFAULT
, 0),
3886 'sort' => new external_value(PARAM_TEXT
, 'Sort string', VALUE_DEFAULT
, null),
3887 'customfieldname' => new external_value(PARAM_ALPHANUMEXT
, 'Used when classification = customfield',
3888 VALUE_DEFAULT
, null),
3889 'customfieldvalue' => new external_value(PARAM_RAW
, 'Used when classification = customfield',
3890 VALUE_DEFAULT
, null),
3891 'searchvalue' => new external_value(PARAM_RAW
, 'The value a user wishes to search against',
3892 VALUE_DEFAULT
, null),
3898 * Get courses matching the given timeline classification.
3900 * NOTE: The offset applies to the unfiltered full set of courses before the classification
3901 * filtering is done.
3903 * If the user is enrolled in 5 courses:
3904 * c1, c2, c3, c4, and c5
3905 * And c4 and c5 are 'future' courses
3907 * If a request comes in for future courses with an offset of 1 it will mean that
3908 * c1 is skipped (because the offset applies *before* the classification filtering)
3909 * and c4 and c5 will be return.
3911 * @param string $classification past, inprogress, or future
3912 * @param int $limit Result set limit
3913 * @param int $offset Offset the full course set before timeline classification is applied
3914 * @param string $sort SQL sort string for results
3915 * @param string $customfieldname
3916 * @param string $customfieldvalue
3917 * @param string $searchvalue
3918 * @return array list of courses and warnings
3919 * @throws invalid_parameter_exception
3921 public static function get_enrolled_courses_by_timeline_classification(
3922 string $classification,
3925 string $sort = null,
3926 string $customfieldname = null,
3927 string $customfieldvalue = null,
3928 string $searchvalue = null
3930 global $CFG, $PAGE, $USER;
3931 require_once($CFG->dirroot
. '/course/lib.php');
3933 $params = self
::validate_parameters(self
::get_enrolled_courses_by_timeline_classification_parameters(),
3935 'classification' => $classification,
3937 'offset' => $offset,
3939 'customfieldvalue' => $customfieldvalue,
3940 'searchvalue' => $searchvalue,
3944 $classification = $params['classification'];
3945 $limit = $params['limit'];
3946 $offset = $params['offset'];
3947 $sort = $params['sort'];
3948 $customfieldvalue = $params['customfieldvalue'];
3949 $searchvalue = clean_param($params['searchvalue'], PARAM_TEXT
);
3951 switch($classification) {
3952 case COURSE_TIMELINE_ALLINCLUDINGHIDDEN
:
3954 case COURSE_TIMELINE_ALL
:
3956 case COURSE_TIMELINE_PAST
:
3958 case COURSE_TIMELINE_INPROGRESS
:
3960 case COURSE_TIMELINE_FUTURE
:
3962 case COURSE_FAVOURITES
:
3964 case COURSE_TIMELINE_HIDDEN
:
3966 case COURSE_TIMELINE_SEARCH
:
3968 case COURSE_CUSTOMFIELD
:
3971 throw new invalid_parameter_exception('Invalid classification');
3974 self
::validate_context(context_user
::instance($USER->id
));
3976 $requiredproperties = course_summary_exporter
::define_properties();
3977 $fields = join(',', array_keys($requiredproperties));
3978 $hiddencourses = get_hidden_courses_on_timeline();
3981 // If the timeline requires really all courses, get really all courses.
3982 if ($classification == COURSE_TIMELINE_ALLINCLUDINGHIDDEN
) {
3983 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields, COURSE_DB_QUERY_LIMIT
);
3985 // Otherwise if the timeline requires the hidden courses then restrict the result to only $hiddencourses.
3986 } else if ($classification == COURSE_TIMELINE_HIDDEN
) {
3987 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields,
3988 COURSE_DB_QUERY_LIMIT
, $hiddencourses);
3990 // Otherwise get the requested courses and exclude the hidden courses.
3991 } else if ($classification == COURSE_TIMELINE_SEARCH
) {
3992 // Prepare the search API options.
3993 $searchcriteria['search'] = $searchvalue;
3994 $options = ['idonly' => true];
3995 $courses = course_get_enrolled_courses_for_logged_in_user_from_search(
4000 COURSE_DB_QUERY_LIMIT
,
4005 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields,
4006 COURSE_DB_QUERY_LIMIT
, [], $hiddencourses);
4009 $favouritecourseids = [];
4010 $ufservice = \core_favourites\service_factory
::get_service_for_user_context(\context_user
::instance($USER->id
));
4011 $favourites = $ufservice->find_favourites_by_type('core_course', 'courses');
4014 $favouritecourseids = array_map(
4015 function($favourite) {
4016 return $favourite->itemid
;
4020 if ($classification == COURSE_FAVOURITES
) {
4021 list($filteredcourses, $processedcount) = course_filter_courses_by_favourites(
4023 $favouritecourseids,
4026 } else if ($classification == COURSE_CUSTOMFIELD
) {
4027 list($filteredcourses, $processedcount) = course_filter_courses_by_customfield(
4034 list($filteredcourses, $processedcount) = course_filter_courses_by_timeline_classification(
4041 $renderer = $PAGE->get_renderer('core');
4042 $formattedcourses = array_map(function($course) use ($renderer, $favouritecourseids) {
4043 if ($course == null) {
4046 context_helper
::preload_from_record($course);
4047 $context = context_course
::instance($course->id
);
4048 $isfavourite = false;
4049 if (in_array($course->id
, $favouritecourseids)) {
4050 $isfavourite = true;
4052 $exporter = new course_summary_exporter($course, ['context' => $context, 'isfavourite' => $isfavourite]);
4053 return $exporter->export($renderer);
4054 }, $filteredcourses);
4056 $formattedcourses = array_filter($formattedcourses, function($course) {
4057 if ($course != null) {
4063 'courses' => $formattedcourses,
4064 'nextoffset' => $offset +
$processedcount
4069 * Returns description of method result value
4071 * @return \core_external\external_description
4073 public static function get_enrolled_courses_by_timeline_classification_returns() {
4074 return new external_single_structure(
4076 'courses' => new external_multiple_structure(course_summary_exporter
::get_read_structure(), 'Course'),
4077 'nextoffset' => new external_value(PARAM_INT
, 'Offset for the next request')
4083 * Returns description of method parameters
4085 * @return external_function_parameters
4087 public static function set_favourite_courses_parameters() {
4088 return new external_function_parameters(
4090 'courses' => new external_multiple_structure(
4091 new external_single_structure(
4093 'id' => new external_value(PARAM_INT
, 'course ID'),
4094 'favourite' => new external_value(PARAM_BOOL
, 'favourite status')
4103 * Set the course favourite status for an array of courses.
4105 * @param array $courses List with course id's and favourite status.
4106 * @return array Array with an array of favourite courses.
4108 public static function set_favourite_courses(
4113 $params = self
::validate_parameters(self
::set_favourite_courses_parameters(),
4115 'courses' => $courses
4121 $ufservice = \core_favourites\service_factory
::get_service_for_user_context(\context_user
::instance($USER->id
));
4123 foreach ($params['courses'] as $course) {
4127 $favouriteexists = $ufservice->favourite_exists('core_course', 'courses', $course['id'],
4128 \context_course
::instance($course['id']));
4130 if ($course['favourite']) {
4131 if (!$favouriteexists) {
4133 $ufservice->create_favourite('core_course', 'courses', $course['id'],
4134 \context_course
::instance($course['id']));
4135 } catch (Exception
$e) {
4136 $warning['courseid'] = $course['id'];
4137 if ($e instanceof moodle_exception
) {
4138 $warning['warningcode'] = $e->errorcode
;
4140 $warning['warningcode'] = $e->getCode();
4142 $warning['message'] = $e->getMessage();
4143 $warnings[] = $warning;
4144 $warnings[] = $warning;
4147 $warning['courseid'] = $course['id'];
4148 $warning['warningcode'] = 'coursealreadyfavourited';
4149 $warning['message'] = 'Course already favourited';
4150 $warnings[] = $warning;
4153 if ($favouriteexists) {
4155 $ufservice->delete_favourite('core_course', 'courses', $course['id'],
4156 \context_course
::instance($course['id']));
4157 } catch (Exception
$e) {
4158 $warning['courseid'] = $course['id'];
4159 if ($e instanceof moodle_exception
) {
4160 $warning['warningcode'] = $e->errorcode
;
4162 $warning['warningcode'] = $e->getCode();
4164 $warning['message'] = $e->getMessage();
4165 $warnings[] = $warning;
4166 $warnings[] = $warning;
4169 $warning['courseid'] = $course['id'];
4170 $warning['warningcode'] = 'cannotdeletefavourite';
4171 $warning['message'] = 'Could not delete favourite status for course';
4172 $warnings[] = $warning;
4178 'warnings' => $warnings
4183 * Returns description of method result value
4185 * @return \core_external\external_description
4187 public static function set_favourite_courses_returns() {
4188 return new external_single_structure(
4190 'warnings' => new external_warnings()
4196 * Returns description of method parameters
4198 * @return external_function_parameters
4201 public static function get_recent_courses_parameters() {
4202 return new external_function_parameters(
4204 'userid' => new external_value(PARAM_INT
, 'id of the user, default to current user', VALUE_DEFAULT
, 0),
4205 'limit' => new external_value(PARAM_INT
, 'result set limit', VALUE_DEFAULT
, 0),
4206 'offset' => new external_value(PARAM_INT
, 'Result set offset', VALUE_DEFAULT
, 0),
4207 'sort' => new external_value(PARAM_TEXT
, 'Sort string', VALUE_DEFAULT
, null)
4213 * Get last accessed courses adding additional course information like images.
4215 * @param int $userid User id from which the courses will be obtained
4216 * @param int $limit Restrict result set to this amount
4217 * @param int $offset Skip this number of records from the start of the result set
4218 * @param string|null $sort SQL string for sorting
4219 * @return array List of courses
4220 * @throws invalid_parameter_exception
4222 public static function get_recent_courses(int $userid = 0, int $limit = 0, int $offset = 0, string $sort = null) {
4223 global $USER, $PAGE;
4225 if (empty($userid)) {
4226 $userid = $USER->id
;
4229 $params = self
::validate_parameters(self
::get_recent_courses_parameters(),
4231 'userid' => $userid,
4233 'offset' => $offset,
4238 $userid = $params['userid'];
4239 $limit = $params['limit'];
4240 $offset = $params['offset'];
4241 $sort = $params['sort'];
4243 $usercontext = context_user
::instance($userid);
4245 self
::validate_context($usercontext);
4247 if ($userid != $USER->id
and !has_capability('moodle/user:viewdetails', $usercontext)) {
4251 $courses = course_get_recent_courses($userid, $limit, $offset, $sort);
4253 $renderer = $PAGE->get_renderer('core');
4255 $recentcourses = array_map(function($course) use ($renderer) {
4256 context_helper
::preload_from_record($course);
4257 $context = context_course
::instance($course->id
);
4258 $isfavourite = !empty($course->component
);
4259 $exporter = new course_summary_exporter($course, ['context' => $context, 'isfavourite' => $isfavourite]);
4260 return $exporter->export($renderer);
4263 return $recentcourses;
4267 * Returns description of method result value
4269 * @return \core_external\external_description
4272 public static function get_recent_courses_returns() {
4273 return new external_multiple_structure(course_summary_exporter
::get_read_structure(), 'Courses');
4277 * Returns description of method parameters
4279 * @return external_function_parameters
4281 public static function get_enrolled_users_by_cmid_parameters() {
4282 return new external_function_parameters([
4283 'cmid' => new external_value(PARAM_INT
, 'id of the course module', VALUE_REQUIRED
),
4284 'groupid' => new external_value(PARAM_INT
, 'id of the group', VALUE_DEFAULT
, 0),
4285 'onlyactive' => new external_value(PARAM_BOOL
, 'whether to return only active users or all.',
4286 VALUE_DEFAULT
, false),
4291 * Get all users in a course for a given cmid.
4293 * @param int $cmid Course Module id from which the users will be obtained
4294 * @param int $groupid Group id from which the users will be obtained
4295 * @param bool $onlyactive Whether to return only the active enrolled users or all enrolled users in the course.
4296 * @return array List of users
4297 * @throws invalid_parameter_exception
4299 public static function get_enrolled_users_by_cmid(int $cmid, int $groupid = 0, bool $onlyactive = false) {
4303 self
::validate_parameters(self
::get_enrolled_users_by_cmid_parameters(), [
4305 'groupid' => $groupid,
4306 'onlyactive' => $onlyactive,
4309 list($course, $cm) = get_course_and_cm_from_cmid($cmid);
4310 $coursecontext = context_course
::instance($course->id
);
4311 self
::validate_context($coursecontext);
4313 $enrolledusers = get_enrolled_users($coursecontext, '', $groupid, 'u.*', null, 0, 0, $onlyactive);
4315 $users = array_map(function ($user) use ($PAGE) {
4316 $user->fullname
= fullname($user);
4317 $userpicture = new user_picture($user);
4318 $userpicture->size
= 1;
4319 $user->profileimage
= $userpicture->get_url($PAGE)->out(false);
4326 'warnings' => $warnings,
4331 * Returns description of method result value
4333 * @return \core_external\external_description
4335 public static function get_enrolled_users_by_cmid_returns() {
4336 return new external_single_structure([
4337 'users' => new external_multiple_structure(self
::user_description()),
4338 'warnings' => new external_warnings(),
4343 * Create user return value description.
4345 * @return \core_external\external_description
4347 public static function user_description() {
4348 $userfields = array(
4349 'id' => new external_value(core_user
::get_property_type('id'), 'ID of the user'),
4350 'profileimage' => new external_value(PARAM_URL
, 'The location of the users larger image', VALUE_OPTIONAL
),
4351 'fullname' => new external_value(PARAM_TEXT
, 'The full name of the user', VALUE_OPTIONAL
),
4352 'firstname' => new external_value(
4353 core_user
::get_property_type('firstname'),
4354 'The first name(s) of the user',
4356 'lastname' => new external_value(
4357 core_user
::get_property_type('lastname'),
4358 'The family name of the user',
4361 return new external_single_structure($userfields);
4365 * Returns description of method parameters.
4367 * @return external_function_parameters
4369 public static function add_content_item_to_user_favourites_parameters() {
4370 return new external_function_parameters([
4371 'componentname' => new external_value(PARAM_TEXT
,
4372 'frankenstyle name of the component to which the content item belongs', VALUE_REQUIRED
),
4373 'contentitemid' => new external_value(PARAM_INT
, 'id of the content item', VALUE_REQUIRED
, '', NULL_NOT_ALLOWED
)
4378 * Add a content item to a user's favourites.
4380 * @param string $componentname the name of the component from which this content item originates.
4381 * @param int $contentitemid the id of the content item.
4382 * @return stdClass the exporter content item.
4384 public static function add_content_item_to_user_favourites(string $componentname, int $contentitemid) {
4388 'componentname' => $componentname,
4389 'contentitemid' => $contentitemid,
4390 ] = self
::validate_parameters(self
::add_content_item_to_user_favourites_parameters(),
4392 'componentname' => $componentname,
4393 'contentitemid' => $contentitemid,
4397 self
::validate_context(context_user
::instance($USER->id
));
4399 $contentitemservice = \core_course\local\factory\content_item_service_factory
::get_content_item_service();
4401 return $contentitemservice->add_to_user_favourites($USER, $componentname, $contentitemid);
4405 * Returns description of method result value.
4407 * @return \core_external\external_description
4409 public static function add_content_item_to_user_favourites_returns() {
4410 return \core_course\local\exporters\course_content_item_exporter
::get_read_structure();
4414 * Returns description of method parameters.
4416 * @return external_function_parameters
4418 public static function remove_content_item_from_user_favourites_parameters() {
4419 return new external_function_parameters([
4420 'componentname' => new external_value(PARAM_TEXT
,
4421 'frankenstyle name of the component to which the content item belongs', VALUE_REQUIRED
),
4422 'contentitemid' => new external_value(PARAM_INT
, 'id of the content item', VALUE_REQUIRED
, '', NULL_NOT_ALLOWED
),
4427 * Remove a content item from a user's favourites.
4429 * @param string $componentname the name of the component from which this content item originates.
4430 * @param int $contentitemid the id of the content item.
4431 * @return stdClass the exported content item.
4433 public static function remove_content_item_from_user_favourites(string $componentname, int $contentitemid) {
4437 'componentname' => $componentname,
4438 'contentitemid' => $contentitemid,
4439 ] = self
::validate_parameters(self
::remove_content_item_from_user_favourites_parameters(),
4441 'componentname' => $componentname,
4442 'contentitemid' => $contentitemid,
4446 self
::validate_context(context_user
::instance($USER->id
));
4448 $contentitemservice = \core_course\local\factory\content_item_service_factory
::get_content_item_service();
4450 return $contentitemservice->remove_from_user_favourites($USER, $componentname, $contentitemid);
4454 * Returns description of method result value.
4456 * @return \core_external\external_description
4458 public static function remove_content_item_from_user_favourites_returns() {
4459 return \core_course\local\exporters\course_content_item_exporter
::get_read_structure();
4463 * Returns description of method result value
4465 * @return \core_external\external_description
4467 public static function get_course_content_items_returns() {
4468 return new external_single_structure([
4469 'content_items' => new external_multiple_structure(
4470 \core_course\local\exporters\course_content_item_exporter
::get_read_structure()
4476 * Returns description of method parameters
4478 * @return external_function_parameters
4480 public static function get_course_content_items_parameters() {
4481 return new external_function_parameters([
4482 'courseid' => new external_value(PARAM_INT
, 'ID of the course', VALUE_REQUIRED
),
4487 * Given a course ID fetch all accessible modules for that course
4489 * @param int $courseid The course we want to fetch the modules for
4490 * @return array Contains array of modules and their metadata
4492 public static function get_course_content_items(int $courseid) {
4496 'courseid' => $courseid,
4497 ] = self
::validate_parameters(self
::get_course_content_items_parameters(), [
4498 'courseid' => $courseid,
4501 $coursecontext = context_course
::instance($courseid);
4502 self
::validate_context($coursecontext);
4503 $course = get_course($courseid);
4505 $contentitemservice = \core_course\local\factory\content_item_service_factory
::get_content_item_service();
4507 $contentitems = $contentitemservice->get_content_items_for_user_in_course($USER, $course);
4508 return ['content_items' => $contentitems];
4512 * Returns description of method parameters.
4514 * @return external_function_parameters
4516 public static function toggle_activity_recommendation_parameters() {
4517 return new external_function_parameters([
4518 'area' => new external_value(PARAM_TEXT
, 'The favourite area (itemtype)', VALUE_REQUIRED
),
4519 'id' => new external_value(PARAM_INT
, 'id of the activity or whatever', VALUE_REQUIRED
),
4524 * Update the recommendation for an activity item.
4526 * @param string $area identifier for this activity.
4527 * @param int $id Associated id. This is needed in conjunction with the area to find the recommendation.
4528 * @return array some warnings or something.
4530 public static function toggle_activity_recommendation(string $area, int $id): array {
4531 ['area' => $area, 'id' => $id] = self
::validate_parameters(self
::toggle_activity_recommendation_parameters(),
4532 ['area' => $area, 'id' => $id]);
4534 $context = context_system
::instance();
4535 self
::validate_context($context);
4537 require_capability('moodle/course:recommendactivity', $context);
4539 $manager = \core_course\local\factory\content_item_service_factory
::get_content_item_service();
4541 $status = $manager->toggle_recommendation($area, $id);
4542 return ['id' => $id, 'area' => $area, 'status' => $status];
4548 * @return \core_external\external_description
4550 public static function toggle_activity_recommendation_returns() {
4551 return new external_single_structure(
4553 'id' => new external_value(PARAM_INT
, 'id of the activity or whatever'),
4554 'area' => new external_value(PARAM_TEXT
, 'The favourite area (itemtype)'),
4555 'status' => new external_value(PARAM_BOOL
, 'If created or deleted'),
4561 * Returns description of method parameters
4563 * @return external_function_parameters
4565 public static function get_activity_chooser_footer_parameters() {
4566 return new external_function_parameters([
4567 'courseid' => new external_value(PARAM_INT
, 'ID of the course', VALUE_REQUIRED
),
4568 'sectionid' => new external_value(PARAM_INT
, 'ID of the section', VALUE_REQUIRED
),
4573 * Given a course ID we need to build up a footre for the chooser.
4575 * @param int $courseid The course we want to fetch the modules for
4576 * @param int $sectionid The section we want to fetch the modules for
4579 public static function get_activity_chooser_footer(int $courseid, int $sectionid) {
4581 'courseid' => $courseid,
4582 'sectionid' => $sectionid,
4583 ] = self
::validate_parameters(self
::get_activity_chooser_footer_parameters(), [
4584 'courseid' => $courseid,
4585 'sectionid' => $sectionid,
4588 $coursecontext = context_course
::instance($courseid);
4589 self
::validate_context($coursecontext);
4591 $activeplugin = get_config('core', 'activitychooseractivefooter');
4593 if ($activeplugin !== COURSE_CHOOSER_FOOTER_NONE
) {
4594 $footerdata = component_callback($activeplugin, 'custom_chooser_footer', [$courseid, $sectionid]);
4597 'customfooterjs' => $footerdata->get_footer_js_file(),
4598 'customfootertemplate' => $footerdata->get_footer_template(),
4599 'customcarouseltemplate' => $footerdata->get_carousel_template(),
4609 * Returns description of method result value
4611 * @return \core_external\external_description
4613 public static function get_activity_chooser_footer_returns() {
4614 return new external_single_structure(
4616 'footer' => new external_value(PARAM_BOOL
, 'Is a footer being return by this request?', VALUE_REQUIRED
),
4617 'customfooterjs' => new external_value(PARAM_RAW
, 'The path to the plugin JS file', VALUE_OPTIONAL
),
4618 'customfootertemplate' => new external_value(PARAM_RAW
, 'The prerendered footer', VALUE_OPTIONAL
),
4619 'customcarouseltemplate' => new external_value(PARAM_RAW
, 'Either "" or the prerendered carousel page',