Merge branch 'MDL-80266-main' of https://github.com/andrewnicols/moodle
[moodle.git] / course / externallib.php
blobf3913df67895e54c973bb61fc470ab0cd0634816
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
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.
8 //
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/>.
18 /**
19 * External course API
21 * @package core_course
22 * @category external
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");
42 /**
43 * Course external functions
45 * @package core_course
46 * @category external
47 * @copyright 2011 Jerome Mouneyrac
48 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
49 * @since Moodle 2.2
51 class core_course_external extends external_api {
53 /**
54 * Returns description of method parameters
56 * @return external_function_parameters
57 * @since Moodle 2.9 Options available
58 * @since Moodle 2.2
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(
65 array(
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
71 section (with id -1)
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())
85 /**
86 * Get course contents
88 * @param int $courseid course id
89 * @param array $options Options for filtering the results, used since Moodle 2.9
90 * @return array
91 * @since Moodle 2.9 Options available
92 * @since Moodle 2.2
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');
99 //validate parameter
100 $params = self::validate_parameters(self::get_course_contents_parameters(),
101 array('courseid' => $courseid, 'options' => $options));
103 $filters = array();
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])) {
110 switch ($name) {
111 case 'excludemodules':
112 case 'excludecontents':
113 case 'includestealthmodules':
114 $value = clean_param($option['value'], PARAM_BOOL);
115 $filters[$name] = $value;
116 break;
117 case 'sectionid':
118 case 'sectionnumber':
119 case 'cmid':
120 case 'modid':
121 $value = clean_param($option['value'], PARAM_INT);
122 if (is_numeric($value)) {
123 $filters[$name] = $value;
124 } else {
125 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
127 break;
128 case 'modname':
129 $value = clean_param($option['value'], PARAM_PLUGIN);
130 if ($value) {
131 $filters[$name] = $value;
132 } else {
133 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
135 break;
136 default:
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);
148 try {
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)) {
165 //retrieve sections
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']) {
184 continue;
185 } else {
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']) {
193 continue;
194 } else {
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()) {
228 continue;
231 // This becomes true when we are filtering and we found the value to filter with.
232 $modfound = false;
234 // Filter by cmid.
235 if (!empty($filters['cmid'])) {
236 if ($cmid != $filters['cmid']) {
237 continue;
238 } else {
239 $modfound = true;
243 // Filter by module name and id.
244 if (!empty($filters['modname'])) {
245 if ($cm->modname != $filters['modname']) {
246 continue;
247 } else if (!empty($filters['modid'])) {
248 if ($cm->instance != $filters['modid']) {
249 continue;
250 } else {
251 // Note that if we are only filtering by modname we don't break the loop.
252 $modfound = true;
257 $module = array();
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);
300 //url of the module
301 $url = $cm->url;
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),
332 'filessize' => 0,
333 'lastmodified' => 0,
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;
357 } else {
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;
367 } else {
368 $sectioncontents[] = $module;
371 // If we just did a filtering, break the loop.
372 if ($modfound) {
373 break;
378 $sectionvalues['modules'] = $sectioncontents;
380 // assign result to $coursecontents
381 $coursecontents[$key] = $sectionvalues;
383 // Break the loop if we are filtering.
384 if ($sectionfound) {
385 break;
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]);
396 continue;
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(
413 'id' => -1,
414 'name' => '',
415 'summary' => '',
416 'summaryformat' => FORMAT_MOODLE,
417 'modules' => $stealthmodules
422 return $coursecontents;
426 * Returns description of method result value
428 * @return \core_external\external_description
429 * @since Moodle 2.2
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(
436 array(
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',
444 VALUE_OPTIONAL),
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(
449 array(
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?',
458 VALUE_OPTIONAL),
459 'availabilityinfo' => new external_value(PARAM_RAW, 'Availability information.',
460 VALUE_OPTIONAL),
461 'visibleoncoursepage' => new external_value(PARAM_INT, 'is the module visible on course page',
462 VALUE_OPTIONAL),
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.',
471 VALUE_OPTIONAL),
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',
475 VALUE_OPTIONAL),
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(
482 array(
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',
486 VALUE_OPTIONAL),
487 'dataid' => new external_value(PARAM_NOTAGS, 'cm data id', VALUE_OPTIONAL),
490 'Course dates',
491 VALUE_DEFAULT,
494 'groupmode' => new external_value(PARAM_INT, 'Group mode value', VALUE_OPTIONAL),
495 'contents' => new external_multiple_structure(
496 new external_single_structure(
497 array(
498 // content info
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.',
510 VALUE_OPTIONAL),
511 'repositorytype' => new external_value(PARAM_PLUGIN, 'The repository type for external files.',
512 VALUE_OPTIONAL),
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',
520 VALUE_OPTIONAL
523 ), 'Course contents', VALUE_DEFAULT, array()
525 'contentsinfo' => new external_single_structure(
526 array(
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.'),
532 'Files mime types.'
534 'repositorytype' => new external_value(PARAM_PLUGIN, 'The repository type for
535 the main file.', VALUE_OPTIONAL),
536 ), 'Contents summary information.', VALUE_OPTIONAL
539 ), 'list of module'
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(
555 PARAM_TEXT,
556 'The content to be displayed in the activity badge',
557 VALUE_OPTIONAL
559 'badgestyle' => new external_value(
560 PARAM_TEXT,
561 'The style for the activity badge',
562 VALUE_OPTIONAL
564 'badgeurl' => new external_value(
565 PARAM_URL,
566 'An optional URL to redirect the user when the activity badge is clicked',
567 VALUE_OPTIONAL
569 'badgeelementid' => new external_value(
570 PARAM_ALPHANUMEXT,
571 'An optional id in case the module wants to add some code for the activity badge',
572 VALUE_OPTIONAL
574 'badgeextraattributes' => new external_multiple_structure(
575 new external_single_structure(
577 'name' => new external_value(
578 PARAM_TEXT,
579 'The attribute name',
580 VALUE_OPTIONAL
582 'value' => new external_value(
583 PARAM_TEXT,
584 'The attribute value',
585 VALUE_OPTIONAL
588 'Each of the attribute names and values',
589 VALUE_OPTIONAL
591 'An optional array of extra HTML attributes to add to the badge element',
592 VALUE_OPTIONAL
595 'Activity badge to display near the name',
596 VALUE_OPTIONAL
601 * Returns description of method parameters
603 * @return external_function_parameters
604 * @since Moodle 2.3
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.',
613 VALUE_OPTIONAL)
614 ), 'options - operator OR is used', VALUE_DEFAULT, array())
620 * Get courses
622 * @param array $options It contains an array (list of ids)
623 * @return array
624 * @since Moodle 2.2
626 public static function get_courses($options = array()) {
627 global $CFG, $DB;
628 require_once($CFG->dirroot . "/course/lib.php");
630 //validate parameter
631 $params = self::validate_parameters(self::get_courses_parameters(),
632 array('options' => $options));
634 //retrieve courses
635 if (!array_key_exists('ids', $params['options'])
636 or empty($params['options']['ids'])) {
637 $courses = $DB->get_records('course');
638 } else {
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();
649 try {
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);
696 if ($courseadmin) {
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(
722 'name' => $key,
723 'value' => $value
728 if ($courseadmin or $course->visible
729 or has_capability('moodle/course:viewhiddencourses', $context)) {
730 $coursesinfo[] = $courseinfo;
734 return $coursesinfo;
738 * Returns description of method result value
740 * @return \core_external\external_description
741 * @since Moodle 2.2
743 public static function get_courses_returns() {
744 return new external_multiple_structure(
745 new external_single_structure(
746 array(
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',
769 VALUE_OPTIONAL),
770 'maxbytes' => new external_value(PARAM_INT,
771 'largest size of file that can be uploaded into the course',
772 VALUE_OPTIONAL),
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',
779 VALUE_OPTIONAL),
780 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
781 VALUE_OPTIONAL),
782 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
783 VALUE_OPTIONAL),
784 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
785 VALUE_OPTIONAL),
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.',
793 VALUE_OPTIONAL),
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),
818 ), 'course'
824 * Returns description of method parameters
826 * @return external_function_parameters
827 * @since Moodle 2.2
829 public static function create_courses_parameters() {
830 $courseconfig = get_config('moodlecourse'); //needed for many default values
831 return new external_function_parameters(
832 array(
833 'courses' => new external_multiple_structure(
834 new external_single_structure(
835 array(
836 'fullname' => new external_value(PARAM_TEXT, 'full name'),
837 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
838 'categoryid' => new external_value(PARAM_INT, 'category id'),
839 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
840 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
841 'summaryformat' => new external_format_value('summary', VALUE_DEFAULT),
842 'format' => new external_value(PARAM_PLUGIN,
843 'course format: weeks, topics, social, site,..',
844 VALUE_DEFAULT, $courseconfig->format),
845 'showgrades' => new external_value(PARAM_INT,
846 '1 if grades are shown, otherwise 0', VALUE_DEFAULT,
847 $courseconfig->showgrades),
848 'newsitems' => new external_value(PARAM_INT,
849 'number of recent items appearing on the course page',
850 VALUE_DEFAULT, $courseconfig->newsitems),
851 'startdate' => new external_value(PARAM_INT,
852 'timestamp when the course start', VALUE_OPTIONAL),
853 'enddate' => new external_value(PARAM_INT,
854 'timestamp when the course end', VALUE_OPTIONAL),
855 'numsections' => new external_value(PARAM_INT,
856 '(deprecated, use courseformatoptions) number of weeks/topics',
857 VALUE_OPTIONAL),
858 'maxbytes' => new external_value(PARAM_INT,
859 'largest size of file that can be uploaded into the course',
860 VALUE_DEFAULT, $courseconfig->maxbytes),
861 'showreports' => new external_value(PARAM_INT,
862 'are activity report shown (yes = 1, no =0)', VALUE_DEFAULT,
863 $courseconfig->showreports),
864 'visible' => new external_value(PARAM_INT,
865 '1: available to student, 0:not available', VALUE_OPTIONAL),
866 'hiddensections' => new external_value(PARAM_INT,
867 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
868 VALUE_OPTIONAL),
869 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
870 VALUE_DEFAULT, $courseconfig->groupmode),
871 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
872 VALUE_DEFAULT, $courseconfig->groupmodeforce),
873 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
874 VALUE_DEFAULT, 0),
875 'enablecompletion' => new external_value(PARAM_INT,
876 'Enabled, control via completion and activity settings. Disabled,
877 not shown in activity settings.',
878 VALUE_OPTIONAL),
879 'completionnotify' => new external_value(PARAM_INT,
880 '1: yes 0: no', VALUE_OPTIONAL),
881 'lang' => new external_value(PARAM_SAFEDIR,
882 'forced course language', VALUE_OPTIONAL),
883 'forcetheme' => new external_value(PARAM_PLUGIN,
884 'name of the force theme', VALUE_OPTIONAL),
885 'courseformatoptions' => new external_multiple_structure(
886 new external_single_structure(
887 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
888 'value' => new external_value(PARAM_RAW, 'course format option value')
890 'additional options for particular course format', VALUE_OPTIONAL),
891 'customfields' => new external_multiple_structure(
892 new external_single_structure(
893 array(
894 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'The shortname of the custom field'),
895 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
896 )), 'custom fields for the course', VALUE_OPTIONAL
898 )), 'courses to create'
905 * Create courses
907 * @param array $courses
908 * @return array courses (id and shortname only)
909 * @since Moodle 2.2
911 public static function create_courses($courses) {
912 global $CFG, $DB;
913 require_once($CFG->dirroot . "/course/lib.php");
914 require_once($CFG->libdir . '/completionlib.php');
916 $params = self::validate_parameters(self::create_courses_parameters(),
917 array('courses' => $courses));
919 $availablethemes = core_component::get_plugin_list('theme');
920 $availablelangs = get_string_manager()->get_list_of_translations();
922 $transaction = $DB->start_delegated_transaction();
924 foreach ($params['courses'] as $course) {
926 // Ensure the current user is allowed to run this function
927 $context = context_coursecat::instance($course['categoryid'], IGNORE_MISSING);
928 try {
929 self::validate_context($context);
930 } catch (Exception $e) {
931 $exceptionparam = new stdClass();
932 $exceptionparam->message = $e->getMessage();
933 $exceptionparam->catid = $course['categoryid'];
934 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
936 require_capability('moodle/course:create', $context);
938 // Fullname and short name are required to be non-empty.
939 if (trim($course['fullname']) === '') {
940 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'fullname');
941 } else if (trim($course['shortname']) === '') {
942 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'shortname');
945 // Make sure lang is valid
946 if (array_key_exists('lang', $course)) {
947 if (empty($availablelangs[$course['lang']])) {
948 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
950 if (!has_capability('moodle/course:setforcedlanguage', $context)) {
951 unset($course['lang']);
955 // Make sure theme is valid
956 if (array_key_exists('forcetheme', $course)) {
957 if (!empty($CFG->allowcoursethemes)) {
958 if (empty($availablethemes[$course['forcetheme']])) {
959 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
960 } else {
961 $course['theme'] = $course['forcetheme'];
966 //force visibility if ws user doesn't have the permission to set it
967 $category = $DB->get_record('course_categories', array('id' => $course['categoryid']));
968 if (!has_capability('moodle/course:visibility', $context)) {
969 $course['visible'] = $category->visible;
972 //set default value for completion
973 $courseconfig = get_config('moodlecourse');
974 if (completion_info::is_enabled_for_site()) {
975 if (!array_key_exists('enablecompletion', $course)) {
976 $course['enablecompletion'] = $courseconfig->enablecompletion;
978 } else {
979 $course['enablecompletion'] = 0;
982 $course['category'] = $course['categoryid'];
984 // Summary format.
985 $course['summaryformat'] = util::validate_format($course['summaryformat']);
987 if (!empty($course['courseformatoptions'])) {
988 foreach ($course['courseformatoptions'] as $option) {
989 $course[$option['name']] = $option['value'];
993 // Custom fields.
994 if (!empty($course['customfields'])) {
995 foreach ($course['customfields'] as $field) {
996 $course['customfield_'.$field['shortname']] = $field['value'];
1000 //Note: create_course() core function check shortname, idnumber, category
1001 $course['id'] = create_course((object) $course)->id;
1003 $resultcourses[] = array('id' => $course['id'], 'shortname' => $course['shortname']);
1006 $transaction->allow_commit();
1008 return $resultcourses;
1012 * Returns description of method result value
1014 * @return \core_external\external_description
1015 * @since Moodle 2.2
1017 public static function create_courses_returns() {
1018 return new external_multiple_structure(
1019 new external_single_structure(
1020 array(
1021 'id' => new external_value(PARAM_INT, 'course id'),
1022 'shortname' => new external_value(PARAM_RAW, 'short name'),
1029 * Update courses
1031 * @return external_function_parameters
1032 * @since Moodle 2.5
1034 public static function update_courses_parameters() {
1035 return new external_function_parameters(
1036 array(
1037 'courses' => new external_multiple_structure(
1038 new external_single_structure(
1039 array(
1040 'id' => new external_value(PARAM_INT, 'ID of the course'),
1041 'fullname' => new external_value(PARAM_TEXT, 'full name', VALUE_OPTIONAL),
1042 'shortname' => new external_value(PARAM_TEXT, 'course short name', VALUE_OPTIONAL),
1043 'categoryid' => new external_value(PARAM_INT, 'category id', VALUE_OPTIONAL),
1044 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
1045 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
1046 'summaryformat' => new external_format_value('summary', VALUE_OPTIONAL),
1047 'format' => new external_value(PARAM_PLUGIN,
1048 'course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
1049 'showgrades' => new external_value(PARAM_INT,
1050 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
1051 'newsitems' => new external_value(PARAM_INT,
1052 'number of recent items appearing on the course page', VALUE_OPTIONAL),
1053 'startdate' => new external_value(PARAM_INT,
1054 'timestamp when the course start', VALUE_OPTIONAL),
1055 'enddate' => new external_value(PARAM_INT,
1056 'timestamp when the course end', VALUE_OPTIONAL),
1057 'numsections' => new external_value(PARAM_INT,
1058 '(deprecated, use courseformatoptions) number of weeks/topics', VALUE_OPTIONAL),
1059 'maxbytes' => new external_value(PARAM_INT,
1060 'largest size of file that can be uploaded into the course', VALUE_OPTIONAL),
1061 'showreports' => new external_value(PARAM_INT,
1062 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
1063 'visible' => new external_value(PARAM_INT,
1064 '1: available to student, 0:not available', VALUE_OPTIONAL),
1065 'hiddensections' => new external_value(PARAM_INT,
1066 '(deprecated, use courseformatoptions) How the hidden sections in the course are
1067 displayed to students', VALUE_OPTIONAL),
1068 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
1069 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
1070 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
1071 'enablecompletion' => new external_value(PARAM_INT,
1072 'Enabled, control via completion and activity settings. Disabled,
1073 not shown in activity settings.', VALUE_OPTIONAL),
1074 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
1075 'lang' => new external_value(PARAM_SAFEDIR, 'forced course language', VALUE_OPTIONAL),
1076 'forcetheme' => new external_value(PARAM_PLUGIN, 'name of the force theme', VALUE_OPTIONAL),
1077 'courseformatoptions' => new external_multiple_structure(
1078 new external_single_structure(
1079 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
1080 'value' => new external_value(PARAM_RAW, 'course format option value')
1081 )), 'additional options for particular course format', VALUE_OPTIONAL),
1082 'customfields' => new external_multiple_structure(
1083 new external_single_structure(
1085 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'The shortname of the custom field'),
1086 'value' => new external_value(PARAM_RAW, 'The value of the custom field')
1088 ), 'Custom fields', VALUE_OPTIONAL),
1090 ), 'courses to update'
1097 * Update courses
1099 * @param array $courses
1100 * @since Moodle 2.5
1102 public static function update_courses($courses) {
1103 global $CFG, $DB;
1104 require_once($CFG->dirroot . "/course/lib.php");
1105 $warnings = array();
1107 $params = self::validate_parameters(self::update_courses_parameters(),
1108 array('courses' => $courses));
1110 $availablethemes = core_component::get_plugin_list('theme');
1111 $availablelangs = get_string_manager()->get_list_of_translations();
1113 foreach ($params['courses'] as $course) {
1114 // Catch any exception while updating course and return as warning to user.
1115 try {
1116 // Ensure the current user is allowed to run this function.
1117 $context = context_course::instance($course['id'], MUST_EXIST);
1118 self::validate_context($context);
1120 $oldcourse = course_get_format($course['id'])->get_course();
1122 require_capability('moodle/course:update', $context);
1124 // Check if user can change category.
1125 if (array_key_exists('categoryid', $course) && ($oldcourse->category != $course['categoryid'])) {
1126 require_capability('moodle/course:changecategory', $context);
1127 $course['category'] = $course['categoryid'];
1130 // Check if the user can change fullname, and the new value is non-empty.
1131 if (array_key_exists('fullname', $course) && ($oldcourse->fullname != $course['fullname'])) {
1132 require_capability('moodle/course:changefullname', $context);
1133 if (trim($course['fullname']) === '') {
1134 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'fullname');
1138 // Check if the user can change shortname, and the new value is non-empty.
1139 if (array_key_exists('shortname', $course) && ($oldcourse->shortname != $course['shortname'])) {
1140 require_capability('moodle/course:changeshortname', $context);
1141 if (trim($course['shortname']) === '') {
1142 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'shortname');
1146 // Check if the user can change the idnumber.
1147 if (array_key_exists('idnumber', $course) && ($oldcourse->idnumber != $course['idnumber'])) {
1148 require_capability('moodle/course:changeidnumber', $context);
1151 // Check if user can change summary.
1152 if (array_key_exists('summary', $course) && ($oldcourse->summary != $course['summary'])) {
1153 require_capability('moodle/course:changesummary', $context);
1156 // Summary format.
1157 if (array_key_exists('summaryformat', $course) && ($oldcourse->summaryformat != $course['summaryformat'])) {
1158 require_capability('moodle/course:changesummary', $context);
1159 $course['summaryformat'] = util::validate_format($course['summaryformat']);
1162 // Check if user can change visibility.
1163 if (array_key_exists('visible', $course) && ($oldcourse->visible != $course['visible'])) {
1164 require_capability('moodle/course:visibility', $context);
1167 // Make sure lang is valid.
1168 if (array_key_exists('lang', $course) && ($oldcourse->lang != $course['lang'])) {
1169 require_capability('moodle/course:setforcedlanguage', $context);
1170 if (empty($availablelangs[$course['lang']])) {
1171 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
1175 // Make sure theme is valid.
1176 if (array_key_exists('forcetheme', $course)) {
1177 if (!empty($CFG->allowcoursethemes)) {
1178 if (empty($availablethemes[$course['forcetheme']])) {
1179 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
1180 } else {
1181 $course['theme'] = $course['forcetheme'];
1186 // Make sure completion is enabled before setting it.
1187 if (array_key_exists('enabledcompletion', $course) && !completion_info::is_enabled_for_site()) {
1188 $course['enabledcompletion'] = 0;
1191 // Make sure maxbytes are less then CFG->maxbytes.
1192 if (array_key_exists('maxbytes', $course)) {
1193 // We allow updates back to 0 max bytes, a special value denoting the course uses the site limit.
1194 // Otherwise, either use the size specified, or cap at the max size for the course.
1195 if ($course['maxbytes'] != 0) {
1196 $course['maxbytes'] = get_max_upload_file_size($CFG->maxbytes, $course['maxbytes']);
1200 if (!empty($course['courseformatoptions'])) {
1201 foreach ($course['courseformatoptions'] as $option) {
1202 if (isset($option['name']) && isset($option['value'])) {
1203 $course[$option['name']] = $option['value'];
1208 // Prepare list of custom fields.
1209 if (isset($course['customfields'])) {
1210 foreach ($course['customfields'] as $field) {
1211 $course['customfield_' . $field['shortname']] = $field['value'];
1215 // Update course if user has all required capabilities.
1216 update_course((object) $course);
1217 } catch (Exception $e) {
1218 $warning = array();
1219 $warning['item'] = 'course';
1220 $warning['itemid'] = $course['id'];
1221 if ($e instanceof moodle_exception) {
1222 $warning['warningcode'] = $e->errorcode;
1223 } else {
1224 $warning['warningcode'] = $e->getCode();
1226 $warning['message'] = $e->getMessage();
1227 $warnings[] = $warning;
1231 $result = array();
1232 $result['warnings'] = $warnings;
1233 return $result;
1237 * Returns description of method result value
1239 * @return \core_external\external_description
1240 * @since Moodle 2.5
1242 public static function update_courses_returns() {
1243 return new external_single_structure(
1244 array(
1245 'warnings' => new external_warnings()
1251 * Returns description of method parameters
1253 * @return external_function_parameters
1254 * @since Moodle 2.2
1256 public static function delete_courses_parameters() {
1257 return new external_function_parameters(
1258 array(
1259 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'course ID')),
1265 * Delete courses
1267 * @param array $courseids A list of course ids
1268 * @since Moodle 2.2
1270 public static function delete_courses($courseids) {
1271 global $CFG, $DB;
1272 require_once($CFG->dirroot."/course/lib.php");
1274 // Parameter validation.
1275 $params = self::validate_parameters(self::delete_courses_parameters(), array('courseids'=>$courseids));
1277 $warnings = array();
1279 foreach ($params['courseids'] as $courseid) {
1280 $course = $DB->get_record('course', array('id' => $courseid));
1282 if ($course === false) {
1283 $warnings[] = array(
1284 'item' => 'course',
1285 'itemid' => $courseid,
1286 'warningcode' => 'unknowncourseidnumber',
1287 'message' => 'Unknown course ID ' . $courseid
1289 continue;
1292 // Check if the context is valid.
1293 $coursecontext = context_course::instance($course->id);
1294 self::validate_context($coursecontext);
1296 // Check if the current user has permission.
1297 if (!can_delete_course($courseid)) {
1298 $warnings[] = array(
1299 'item' => 'course',
1300 'itemid' => $courseid,
1301 'warningcode' => 'cannotdeletecourse',
1302 'message' => 'You do not have the permission to delete this course' . $courseid
1304 continue;
1307 if (delete_course($course, false) === false) {
1308 $warnings[] = array(
1309 'item' => 'course',
1310 'itemid' => $courseid,
1311 'warningcode' => 'cannotdeletecategorycourse',
1312 'message' => 'Course ' . $courseid . ' failed to be deleted'
1314 continue;
1318 fix_course_sortorder();
1320 return array('warnings' => $warnings);
1324 * Returns description of method result value
1326 * @return \core_external\external_description
1327 * @since Moodle 2.2
1329 public static function delete_courses_returns() {
1330 return new external_single_structure(
1331 array(
1332 'warnings' => new external_warnings()
1338 * Returns description of method parameters
1340 * @return external_function_parameters
1341 * @since Moodle 2.3
1343 public static function duplicate_course_parameters() {
1344 return new external_function_parameters(
1345 array(
1346 'courseid' => new external_value(PARAM_INT, 'course to duplicate id'),
1347 'fullname' => new external_value(PARAM_TEXT, 'duplicated course full name'),
1348 'shortname' => new external_value(PARAM_TEXT, 'duplicated course short name'),
1349 'categoryid' => new external_value(PARAM_INT, 'duplicated course category parent'),
1350 'visible' => new external_value(PARAM_INT, 'duplicated course visible, default to yes', VALUE_DEFAULT, 1),
1351 'options' => new external_multiple_structure(
1352 new external_single_structure(
1353 array(
1354 'name' => new external_value(PARAM_ALPHAEXT, 'The backup option name:
1355 "activities" (int) Include course activites (default to 1 that is equal to yes),
1356 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1357 "filters" (int) Include course filters (default to 1 that is equal to yes),
1358 "users" (int) Include users (default to 0 that is equal to no),
1359 "enrolments" (int) Include enrolment methods (default to 1 - restore only with users),
1360 "role_assignments" (int) Include role assignments (default to 0 that is equal to no),
1361 "comments" (int) Include user comments (default to 0 that is equal to no),
1362 "userscompletion" (int) Include user course completion information (default to 0 that is equal to no),
1363 "logs" (int) Include course logs (default to 0 that is equal to no),
1364 "grade_histories" (int) Include histories (default to 0 that is equal to no)'
1366 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1369 ), 'Course duplication options', VALUE_DEFAULT, array()
1376 * Duplicate a course
1378 * @param int $courseid
1379 * @param string $fullname Duplicated course fullname
1380 * @param string $shortname Duplicated course shortname
1381 * @param int $categoryid Duplicated course parent category id
1382 * @param int $visible Duplicated course availability
1383 * @param array $options List of backup options
1384 * @return array New course info
1385 * @since Moodle 2.3
1387 public static function duplicate_course($courseid, $fullname, $shortname, $categoryid, $visible = 1, $options = array()) {
1388 global $CFG, $USER, $DB;
1389 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1390 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1392 // Parameter validation.
1393 $params = self::validate_parameters(
1394 self::duplicate_course_parameters(),
1395 array(
1396 'courseid' => $courseid,
1397 'fullname' => $fullname,
1398 'shortname' => $shortname,
1399 'categoryid' => $categoryid,
1400 'visible' => $visible,
1401 'options' => $options
1405 // Context validation.
1407 if (! ($course = $DB->get_record('course', array('id'=>$params['courseid'])))) {
1408 throw new moodle_exception('invalidcourseid', 'error');
1411 // Category where duplicated course is going to be created.
1412 $categorycontext = context_coursecat::instance($params['categoryid']);
1413 self::validate_context($categorycontext);
1415 // Course to be duplicated.
1416 $coursecontext = context_course::instance($course->id);
1417 self::validate_context($coursecontext);
1419 $backupdefaults = array(
1420 'activities' => 1,
1421 'blocks' => 1,
1422 'filters' => 1,
1423 'users' => 0,
1424 'enrolments' => backup::ENROL_WITHUSERS,
1425 'role_assignments' => 0,
1426 'comments' => 0,
1427 'userscompletion' => 0,
1428 'logs' => 0,
1429 'grade_histories' => 0
1432 $backupsettings = array();
1433 // Check for backup and restore options.
1434 if (!empty($params['options'])) {
1435 foreach ($params['options'] as $option) {
1437 // Strict check for a correct value (allways 1 or 0, true or false).
1438 $value = clean_param($option['value'], PARAM_INT);
1440 if ($value !== 0 and $value !== 1) {
1441 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1444 if (!isset($backupdefaults[$option['name']])) {
1445 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1448 $backupsettings[$option['name']] = $value;
1452 // Capability checking.
1454 // The backup controller check for this currently, this may be redundant.
1455 require_capability('moodle/course:create', $categorycontext);
1456 require_capability('moodle/restore:restorecourse', $categorycontext);
1457 require_capability('moodle/backup:backupcourse', $coursecontext);
1459 if (!empty($backupsettings['users'])) {
1460 require_capability('moodle/backup:userinfo', $coursecontext);
1461 require_capability('moodle/restore:userinfo', $categorycontext);
1464 // Check if the shortname is used.
1465 if ($foundcourses = $DB->get_records('course', array('shortname'=>$shortname))) {
1466 foreach ($foundcourses as $foundcourse) {
1467 $foundcoursenames[] = $foundcourse->fullname;
1470 $foundcoursenamestring = implode(',', $foundcoursenames);
1471 throw new moodle_exception('shortnametaken', '', '', $foundcoursenamestring);
1474 // Backup the course.
1476 $bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE,
1477 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id);
1479 foreach ($backupsettings as $name => $value) {
1480 if ($setting = $bc->get_plan()->get_setting($name)) {
1481 $bc->get_plan()->get_setting($name)->set_value($value);
1485 $backupid = $bc->get_backupid();
1486 $backupbasepath = $bc->get_plan()->get_basepath();
1488 $bc->execute_plan();
1489 $results = $bc->get_results();
1490 $file = $results['backup_destination'];
1492 $bc->destroy();
1494 // Restore the backup immediately.
1496 // Check if we need to unzip the file because the backup temp dir does not contains backup files.
1497 if (!file_exists($backupbasepath . "/moodle_backup.xml")) {
1498 $file->extract_to_pathname(get_file_packer('application/vnd.moodle.backup'), $backupbasepath);
1501 // Create new course.
1502 $newcourseid = restore_dbops::create_new_course($params['fullname'], $params['shortname'], $params['categoryid']);
1504 $rc = new restore_controller($backupid, $newcourseid,
1505 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id, backup::TARGET_NEW_COURSE);
1507 foreach ($backupsettings as $name => $value) {
1508 $setting = $rc->get_plan()->get_setting($name);
1509 if ($setting->get_status() == backup_setting::NOT_LOCKED) {
1510 $setting->set_value($value);
1514 if (!$rc->execute_precheck()) {
1515 $precheckresults = $rc->get_precheck_results();
1516 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1517 if (empty($CFG->keeptempdirectoriesonbackup)) {
1518 fulldelete($backupbasepath);
1521 $errorinfo = '';
1523 foreach ($precheckresults['errors'] as $error) {
1524 $errorinfo .= $error;
1527 if (array_key_exists('warnings', $precheckresults)) {
1528 foreach ($precheckresults['warnings'] as $warning) {
1529 $errorinfo .= $warning;
1533 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1537 $rc->execute_plan();
1538 $rc->destroy();
1540 $course = $DB->get_record('course', array('id' => $newcourseid), '*', MUST_EXIST);
1541 $course->fullname = $params['fullname'];
1542 $course->shortname = $params['shortname'];
1543 $course->visible = $params['visible'];
1545 // Set shortname and fullname back.
1546 $DB->update_record('course', $course);
1548 if (empty($CFG->keeptempdirectoriesonbackup)) {
1549 fulldelete($backupbasepath);
1552 // Delete the course backup file created by this WebService. Originally located in the course backups area.
1553 $file->delete();
1555 return array('id' => $course->id, 'shortname' => $course->shortname);
1559 * Returns description of method result value
1561 * @return \core_external\external_description
1562 * @since Moodle 2.3
1564 public static function duplicate_course_returns() {
1565 return new external_single_structure(
1566 array(
1567 'id' => new external_value(PARAM_INT, 'course id'),
1568 'shortname' => new external_value(PARAM_RAW, 'short name'),
1574 * Returns description of method parameters for import_course
1576 * @return external_function_parameters
1577 * @since Moodle 2.4
1579 public static function import_course_parameters() {
1580 return new external_function_parameters(
1581 array(
1582 'importfrom' => new external_value(PARAM_INT, 'the id of the course we are importing from'),
1583 'importto' => new external_value(PARAM_INT, 'the id of the course we are importing to'),
1584 'deletecontent' => new external_value(PARAM_INT, 'whether to delete the course content where we are importing to (default to 0 = No)', VALUE_DEFAULT, 0),
1585 'options' => new external_multiple_structure(
1586 new external_single_structure(
1587 array(
1588 'name' => new external_value(PARAM_ALPHA, 'The backup option name:
1589 "activities" (int) Include course activites (default to 1 that is equal to yes),
1590 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1591 "filters" (int) Include course filters (default to 1 that is equal to yes)'
1593 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1596 ), 'Course import options', VALUE_DEFAULT, array()
1603 * Imports a course
1605 * @param int $importfrom The id of the course we are importing from
1606 * @param int $importto The id of the course we are importing to
1607 * @param bool $deletecontent Whether to delete the course we are importing to content
1608 * @param array $options List of backup options
1609 * @return null
1610 * @since Moodle 2.4
1612 public static function import_course($importfrom, $importto, $deletecontent = 0, $options = array()) {
1613 global $CFG, $USER, $DB;
1614 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1615 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1617 // Parameter validation.
1618 $params = self::validate_parameters(
1619 self::import_course_parameters(),
1620 array(
1621 'importfrom' => $importfrom,
1622 'importto' => $importto,
1623 'deletecontent' => $deletecontent,
1624 'options' => $options
1628 if ($params['deletecontent'] !== 0 and $params['deletecontent'] !== 1) {
1629 throw new moodle_exception('invalidextparam', 'webservice', '', $params['deletecontent']);
1632 // Context validation.
1634 if (! ($importfrom = $DB->get_record('course', array('id'=>$params['importfrom'])))) {
1635 throw new moodle_exception('invalidcourseid', 'error');
1638 if (! ($importto = $DB->get_record('course', array('id'=>$params['importto'])))) {
1639 throw new moodle_exception('invalidcourseid', 'error');
1642 $importfromcontext = context_course::instance($importfrom->id);
1643 self::validate_context($importfromcontext);
1645 $importtocontext = context_course::instance($importto->id);
1646 self::validate_context($importtocontext);
1648 $backupdefaults = array(
1649 'activities' => 1,
1650 'blocks' => 1,
1651 'filters' => 1
1654 $backupsettings = array();
1656 // Check for backup and restore options.
1657 if (!empty($params['options'])) {
1658 foreach ($params['options'] as $option) {
1660 // Strict check for a correct value (allways 1 or 0, true or false).
1661 $value = clean_param($option['value'], PARAM_INT);
1663 if ($value !== 0 and $value !== 1) {
1664 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1667 if (!isset($backupdefaults[$option['name']])) {
1668 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1671 $backupsettings[$option['name']] = $value;
1675 // Capability checking.
1677 require_capability('moodle/backup:backuptargetimport', $importfromcontext);
1678 require_capability('moodle/restore:restoretargetimport', $importtocontext);
1680 $bc = new backup_controller(backup::TYPE_1COURSE, $importfrom->id, backup::FORMAT_MOODLE,
1681 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
1683 foreach ($backupsettings as $name => $value) {
1684 $bc->get_plan()->get_setting($name)->set_value($value);
1687 $backupid = $bc->get_backupid();
1688 $backupbasepath = $bc->get_plan()->get_basepath();
1690 $bc->execute_plan();
1691 $bc->destroy();
1693 // Restore the backup immediately.
1695 // Check if we must delete the contents of the destination course.
1696 if ($params['deletecontent']) {
1697 $restoretarget = backup::TARGET_EXISTING_DELETING;
1698 } else {
1699 $restoretarget = backup::TARGET_EXISTING_ADDING;
1702 $rc = new restore_controller($backupid, $importto->id,
1703 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, $restoretarget);
1705 foreach ($backupsettings as $name => $value) {
1706 $rc->get_plan()->get_setting($name)->set_value($value);
1709 if (!$rc->execute_precheck()) {
1710 $precheckresults = $rc->get_precheck_results();
1711 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1712 if (empty($CFG->keeptempdirectoriesonbackup)) {
1713 fulldelete($backupbasepath);
1716 $errorinfo = '';
1718 foreach ($precheckresults['errors'] as $error) {
1719 $errorinfo .= $error;
1722 if (array_key_exists('warnings', $precheckresults)) {
1723 foreach ($precheckresults['warnings'] as $warning) {
1724 $errorinfo .= $warning;
1728 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1730 } else {
1731 if ($restoretarget == backup::TARGET_EXISTING_DELETING) {
1732 restore_dbops::delete_course_content($importto->id);
1736 $rc->execute_plan();
1737 $rc->destroy();
1739 if (empty($CFG->keeptempdirectoriesonbackup)) {
1740 fulldelete($backupbasepath);
1743 return null;
1747 * Returns description of method result value
1749 * @return \core_external\external_description
1750 * @since Moodle 2.4
1752 public static function import_course_returns() {
1753 return null;
1757 * Returns description of method parameters
1759 * @return external_function_parameters
1760 * @since Moodle 2.3
1762 public static function get_categories_parameters() {
1763 return new external_function_parameters(
1764 array(
1765 'criteria' => new external_multiple_structure(
1766 new external_single_structure(
1767 array(
1768 'key' => new external_value(PARAM_ALPHA,
1769 'The category column to search, expected keys (value format) are:'.
1770 '"id" (int) the category id,'.
1771 '"ids" (string) category ids separated by commas,'.
1772 '"name" (string) the category name,'.
1773 '"parent" (int) the parent category id,'.
1774 '"idnumber" (string) category idnumber'.
1775 ' - user must have \'moodle/category:manage\' to search on idnumber,'.
1776 '"visible" (int) whether the returned categories must be visible or hidden. If the key is not passed,
1777 then the function return all categories that the user can see.'.
1778 ' - user must have \'moodle/category:manage\' or \'moodle/category:viewhiddencategories\' to search on visible,'.
1779 '"theme" (string) only return the categories having this theme'.
1780 ' - user must have \'moodle/category:manage\' to search on theme'),
1781 'value' => new external_value(PARAM_RAW, 'the value to match')
1783 ), 'criteria', VALUE_DEFAULT, array()
1785 'addsubcategories' => new external_value(PARAM_BOOL, 'return the sub categories infos
1786 (1 - default) otherwise only the category info (0)', VALUE_DEFAULT, 1)
1792 * Get categories
1794 * @param array $criteria Criteria to match the results
1795 * @param booln $addsubcategories obtain only the category (false) or its subcategories (true - default)
1796 * @return array list of categories
1797 * @since Moodle 2.3
1799 public static function get_categories($criteria = array(), $addsubcategories = true) {
1800 global $CFG, $DB;
1801 require_once($CFG->dirroot . "/course/lib.php");
1803 // Validate parameters.
1804 $params = self::validate_parameters(self::get_categories_parameters(),
1805 array('criteria' => $criteria, 'addsubcategories' => $addsubcategories));
1807 // Retrieve the categories.
1808 $categories = array();
1809 if (!empty($params['criteria'])) {
1811 $conditions = array();
1812 $wheres = array();
1813 foreach ($params['criteria'] as $crit) {
1814 $key = trim($crit['key']);
1816 // Trying to avoid duplicate keys.
1817 if (!isset($conditions[$key])) {
1819 $context = context_system::instance();
1820 $value = null;
1821 switch ($key) {
1822 case 'id':
1823 $value = clean_param($crit['value'], PARAM_INT);
1824 $conditions[$key] = $value;
1825 $wheres[] = $key . " = :" . $key;
1826 break;
1828 case 'ids':
1829 $value = clean_param($crit['value'], PARAM_SEQUENCE);
1830 $ids = explode(',', $value);
1831 list($sqlids, $paramids) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED);
1832 $conditions = array_merge($conditions, $paramids);
1833 $wheres[] = 'id ' . $sqlids;
1834 break;
1836 case 'idnumber':
1837 if (has_capability('moodle/category:manage', $context)) {
1838 $value = clean_param($crit['value'], PARAM_RAW);
1839 $conditions[$key] = $value;
1840 $wheres[] = $key . " = :" . $key;
1841 } else {
1842 // We must throw an exception.
1843 // Otherwise the dev client would think no idnumber exists.
1844 throw new moodle_exception('criteriaerror',
1845 'webservice', '', null,
1846 'You don\'t have the permissions to search on the "idnumber" field.');
1848 break;
1850 case 'name':
1851 $value = clean_param($crit['value'], PARAM_TEXT);
1852 $conditions[$key] = $value;
1853 $wheres[] = $key . " = :" . $key;
1854 break;
1856 case 'parent':
1857 $value = clean_param($crit['value'], PARAM_INT);
1858 $conditions[$key] = $value;
1859 $wheres[] = $key . " = :" . $key;
1860 break;
1862 case 'visible':
1863 if (has_capability('moodle/category:viewhiddencategories', $context)) {
1864 $value = clean_param($crit['value'], PARAM_INT);
1865 $conditions[$key] = $value;
1866 $wheres[] = $key . " = :" . $key;
1867 } else {
1868 throw new moodle_exception('criteriaerror',
1869 'webservice', '', null,
1870 'You don\'t have the permissions to search on the "visible" field.');
1872 break;
1874 case 'theme':
1875 if (has_capability('moodle/category:manage', $context)) {
1876 $value = clean_param($crit['value'], PARAM_THEME);
1877 $conditions[$key] = $value;
1878 $wheres[] = $key . " = :" . $key;
1879 } else {
1880 throw new moodle_exception('criteriaerror',
1881 'webservice', '', null,
1882 'You don\'t have the permissions to search on the "theme" field.');
1884 break;
1886 default:
1887 throw new moodle_exception('criteriaerror',
1888 'webservice', '', null,
1889 'You can not search on this criteria: ' . $key);
1894 if (!empty($wheres)) {
1895 $wheres = implode(" AND ", $wheres);
1897 $categories = $DB->get_records_select('course_categories', $wheres, $conditions);
1899 // Retrieve its sub subcategories (all levels).
1900 if ($categories and !empty($params['addsubcategories'])) {
1901 $newcategories = array();
1903 // Check if we required visible/theme checks.
1904 $additionalselect = '';
1905 $additionalparams = array();
1906 if (isset($conditions['visible'])) {
1907 $additionalselect .= ' AND visible = :visible';
1908 $additionalparams['visible'] = $conditions['visible'];
1910 if (isset($conditions['theme'])) {
1911 $additionalselect .= ' AND theme= :theme';
1912 $additionalparams['theme'] = $conditions['theme'];
1915 foreach ($categories as $category) {
1916 $sqlselect = $DB->sql_like('path', ':path') . $additionalselect;
1917 $sqlparams = array('path' => $category->path.'/%') + $additionalparams; // It will NOT include the specified category.
1918 $subcategories = $DB->get_records_select('course_categories', $sqlselect, $sqlparams);
1919 $newcategories = $newcategories + $subcategories; // Both arrays have integer as keys.
1921 $categories = $categories + $newcategories;
1925 } else {
1926 // Retrieve all categories in the database.
1927 $categories = $DB->get_records('course_categories');
1930 // The not returned categories. key => category id, value => reason of exclusion.
1931 $excludedcats = array();
1933 // The returned categories.
1934 $categoriesinfo = array();
1936 // We need to sort the categories by path.
1937 // The parent cats need to be checked by the algo first.
1938 usort($categories, "core_course_external::compare_categories_by_path");
1940 foreach ($categories as $category) {
1942 // Check if the category is a child of an excluded category, if yes exclude it too (excluded => do not return).
1943 $parents = explode('/', $category->path);
1944 unset($parents[0]); // First key is always empty because path start with / => /1/2/4.
1945 foreach ($parents as $parentid) {
1946 // Note: when the parent exclusion was due to the context,
1947 // the sub category could still be returned.
1948 if (isset($excludedcats[$parentid]) and $excludedcats[$parentid] != 'context') {
1949 $excludedcats[$category->id] = 'parent';
1953 // Check the user can use the category context.
1954 $context = context_coursecat::instance($category->id);
1955 try {
1956 self::validate_context($context);
1957 } catch (Exception $e) {
1958 $excludedcats[$category->id] = 'context';
1960 // If it was the requested category then throw an exception.
1961 if (isset($params['categoryid']) && $category->id == $params['categoryid']) {
1962 $exceptionparam = new stdClass();
1963 $exceptionparam->message = $e->getMessage();
1964 $exceptionparam->catid = $category->id;
1965 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
1969 // Return the category information.
1970 if (!isset($excludedcats[$category->id])) {
1972 // Final check to see if the category is visible to the user.
1973 if (core_course_category::can_view_category($category)) {
1975 $categoryinfo = array();
1976 $categoryinfo['id'] = $category->id;
1977 $categoryinfo['name'] = \core_external\util::format_string($category->name, $context);
1978 list($categoryinfo['description'], $categoryinfo['descriptionformat']) =
1979 \core_external\util::format_text($category->description, $category->descriptionformat,
1980 $context, 'coursecat', 'description', null);
1981 $categoryinfo['parent'] = $category->parent;
1982 $categoryinfo['sortorder'] = $category->sortorder;
1983 $categoryinfo['coursecount'] = $category->coursecount;
1984 $categoryinfo['depth'] = $category->depth;
1985 $categoryinfo['path'] = $category->path;
1987 // Some fields only returned for admin.
1988 if (has_capability('moodle/category:manage', $context)) {
1989 $categoryinfo['idnumber'] = $category->idnumber;
1990 $categoryinfo['visible'] = $category->visible;
1991 $categoryinfo['visibleold'] = $category->visibleold;
1992 $categoryinfo['timemodified'] = $category->timemodified;
1993 $categoryinfo['theme'] = clean_param($category->theme, PARAM_THEME);
1996 $categoriesinfo[] = $categoryinfo;
1997 } else {
1998 $excludedcats[$category->id] = 'visibility';
2003 // Sorting the resulting array so it looks a bit better for the client developer.
2004 usort($categoriesinfo, "core_course_external::compare_categories_by_sortorder");
2006 return $categoriesinfo;
2010 * Sort categories array by path
2011 * private function: only used by get_categories
2013 * @param stdClass $category1
2014 * @param stdClass $category2
2015 * @return int result of strcmp
2016 * @since Moodle 2.3
2018 private static function compare_categories_by_path($category1, $category2) {
2019 return strcmp($category1->path, $category2->path);
2023 * Sort categories array by sortorder
2024 * private function: only used by get_categories
2026 * @param array $category1
2027 * @param array $category2
2028 * @return int result of strcmp
2029 * @since Moodle 2.3
2031 private static function compare_categories_by_sortorder($category1, $category2) {
2032 return strcmp($category1['sortorder'], $category2['sortorder']);
2036 * Returns description of method result value
2038 * @return \core_external\external_description
2039 * @since Moodle 2.3
2041 public static function get_categories_returns() {
2042 return new external_multiple_structure(
2043 new external_single_structure(
2044 array(
2045 'id' => new external_value(PARAM_INT, 'category id'),
2046 'name' => new external_value(PARAM_RAW, 'category name'),
2047 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
2048 'description' => new external_value(PARAM_RAW, 'category description'),
2049 'descriptionformat' => new external_format_value('description'),
2050 'parent' => new external_value(PARAM_INT, 'parent category id'),
2051 'sortorder' => new external_value(PARAM_INT, 'category sorting order'),
2052 'coursecount' => new external_value(PARAM_INT, 'number of courses in this category'),
2053 'visible' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
2054 'visibleold' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
2055 'timemodified' => new external_value(PARAM_INT, 'timestamp', VALUE_OPTIONAL),
2056 'depth' => new external_value(PARAM_INT, 'category depth'),
2057 'path' => new external_value(PARAM_TEXT, 'category path'),
2058 'theme' => new external_value(PARAM_THEME, 'category theme', VALUE_OPTIONAL),
2059 ), 'List of categories'
2065 * Returns description of method parameters
2067 * @return external_function_parameters
2068 * @since Moodle 2.3
2070 public static function create_categories_parameters() {
2071 return new external_function_parameters(
2072 array(
2073 'categories' => new external_multiple_structure(
2074 new external_single_structure(
2075 array(
2076 'name' => new external_value(PARAM_TEXT, 'new category name'),
2077 'parent' => new external_value(PARAM_INT,
2078 'the parent category id inside which the new category will be created
2079 - set to 0 for a root category',
2080 VALUE_DEFAULT, 0),
2081 'idnumber' => new external_value(PARAM_RAW,
2082 'the new category idnumber', VALUE_OPTIONAL),
2083 'description' => new external_value(PARAM_RAW,
2084 'the new category description', VALUE_OPTIONAL),
2085 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
2086 'theme' => new external_value(PARAM_THEME,
2087 'the new category theme. This option must be enabled on moodle',
2088 VALUE_OPTIONAL),
2097 * Create categories
2099 * @param array $categories - see create_categories_parameters() for the array structure
2100 * @return array - see create_categories_returns() for the array structure
2101 * @since Moodle 2.3
2103 public static function create_categories($categories) {
2104 global $DB;
2106 $params = self::validate_parameters(self::create_categories_parameters(),
2107 array('categories' => $categories));
2109 $transaction = $DB->start_delegated_transaction();
2111 $createdcategories = array();
2112 foreach ($params['categories'] as $category) {
2113 if ($category['parent']) {
2114 if (!$DB->record_exists('course_categories', array('id' => $category['parent']))) {
2115 throw new moodle_exception('unknowcategory');
2117 $context = context_coursecat::instance($category['parent']);
2118 } else {
2119 $context = context_system::instance();
2121 self::validate_context($context);
2122 require_capability('moodle/category:manage', $context);
2124 // this will validate format and throw an exception if there are errors
2125 util::validate_format($category['descriptionformat']);
2127 $newcategory = core_course_category::create($category);
2128 $context = context_coursecat::instance($newcategory->id);
2130 $createdcategories[] = array(
2131 'id' => $newcategory->id,
2132 'name' => \core_external\util::format_string($newcategory->name, $context),
2136 $transaction->allow_commit();
2138 return $createdcategories;
2142 * Returns description of method parameters
2144 * @return external_function_parameters
2145 * @since Moodle 2.3
2147 public static function create_categories_returns() {
2148 return new external_multiple_structure(
2149 new external_single_structure(
2150 array(
2151 'id' => new external_value(PARAM_INT, 'new category id'),
2152 'name' => new external_value(PARAM_RAW, 'new category name'),
2159 * Returns description of method parameters
2161 * @return external_function_parameters
2162 * @since Moodle 2.3
2164 public static function update_categories_parameters() {
2165 return new external_function_parameters(
2166 array(
2167 'categories' => new external_multiple_structure(
2168 new external_single_structure(
2169 array(
2170 'id' => new external_value(PARAM_INT, 'course id'),
2171 'name' => new external_value(PARAM_TEXT, 'category name', VALUE_OPTIONAL),
2172 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
2173 'parent' => new external_value(PARAM_INT, 'parent category id', VALUE_OPTIONAL),
2174 'description' => new external_value(PARAM_RAW, 'category description', VALUE_OPTIONAL),
2175 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
2176 'theme' => new external_value(PARAM_THEME,
2177 'the category theme. This option must be enabled on moodle', VALUE_OPTIONAL),
2186 * Update categories
2188 * @param array $categories The list of categories to update
2189 * @return null
2190 * @since Moodle 2.3
2192 public static function update_categories($categories) {
2193 global $DB;
2195 // Validate parameters.
2196 $params = self::validate_parameters(self::update_categories_parameters(), array('categories' => $categories));
2198 $transaction = $DB->start_delegated_transaction();
2200 foreach ($params['categories'] as $cat) {
2201 $category = core_course_category::get($cat['id']);
2203 $categorycontext = context_coursecat::instance($cat['id']);
2204 self::validate_context($categorycontext);
2205 require_capability('moodle/category:manage', $categorycontext);
2207 // If the category parent is being changed, check for capability in the new parent category
2208 if (isset($cat['parent']) && ($cat['parent'] !== $category->parent)) {
2209 if ($cat['parent'] == 0) {
2210 // Creating a top level category requires capability in the system context
2211 $parentcontext = context_system::instance();
2212 } else {
2213 // Category context
2214 $parentcontext = context_coursecat::instance($cat['parent']);
2216 self::validate_context($parentcontext);
2217 require_capability('moodle/category:manage', $parentcontext);
2220 // this will throw an exception if descriptionformat is not valid
2221 util::validate_format($cat['descriptionformat']);
2223 $category->update($cat);
2226 $transaction->allow_commit();
2230 * Returns description of method result value
2232 * @return \core_external\external_description
2233 * @since Moodle 2.3
2235 public static function update_categories_returns() {
2236 return null;
2240 * Returns description of method parameters
2242 * @return external_function_parameters
2243 * @since Moodle 2.3
2245 public static function delete_categories_parameters() {
2246 return new external_function_parameters(
2247 array(
2248 'categories' => new external_multiple_structure(
2249 new external_single_structure(
2250 array(
2251 'id' => new external_value(PARAM_INT, 'category id to delete'),
2252 'newparent' => new external_value(PARAM_INT,
2253 'the parent category to move the contents to, if specified', VALUE_OPTIONAL),
2254 'recursive' => new external_value(PARAM_BOOL, '1: recursively delete all contents inside this
2255 category, 0 (default): move contents to newparent or current parent category (except if parent is root)', VALUE_DEFAULT, 0)
2264 * Delete categories
2266 * @param array $categories A list of category ids
2267 * @return array
2268 * @since Moodle 2.3
2270 public static function delete_categories($categories) {
2271 global $CFG, $DB;
2272 require_once($CFG->dirroot . "/course/lib.php");
2274 // Validate parameters.
2275 $params = self::validate_parameters(self::delete_categories_parameters(), array('categories' => $categories));
2277 $transaction = $DB->start_delegated_transaction();
2279 foreach ($params['categories'] as $category) {
2280 $deletecat = core_course_category::get($category['id'], MUST_EXIST);
2281 $context = context_coursecat::instance($deletecat->id);
2282 require_capability('moodle/category:manage', $context);
2283 self::validate_context($context);
2284 self::validate_context(get_category_or_system_context($deletecat->parent));
2286 if ($category['recursive']) {
2287 // If recursive was specified, then we recursively delete the category's contents.
2288 if ($deletecat->can_delete_full()) {
2289 $deletecat->delete_full(false);
2290 } else {
2291 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2293 } else {
2294 // In this situation, we don't delete the category's contents, we either move it to newparent or parent.
2295 // If the parent is the root, moving is not supported (because a course must always be inside a category).
2296 // We must move to an existing category.
2297 if (!empty($category['newparent'])) {
2298 $newparentcat = core_course_category::get($category['newparent']);
2299 } else {
2300 $newparentcat = core_course_category::get($deletecat->parent);
2303 // This operation is not allowed. We must move contents to an existing category.
2304 if (!$newparentcat->id) {
2305 throw new moodle_exception('movecatcontentstoroot');
2308 self::validate_context(context_coursecat::instance($newparentcat->id));
2309 if ($deletecat->can_move_content_to($newparentcat->id)) {
2310 $deletecat->delete_move($newparentcat->id, false);
2311 } else {
2312 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2317 $transaction->allow_commit();
2321 * Returns description of method parameters
2323 * @return external_function_parameters
2324 * @since Moodle 2.3
2326 public static function delete_categories_returns() {
2327 return null;
2331 * Describes the parameters for delete_modules.
2333 * @return external_function_parameters
2334 * @since Moodle 2.5
2336 public static function delete_modules_parameters() {
2337 return new external_function_parameters (
2338 array(
2339 'cmids' => new external_multiple_structure(new external_value(PARAM_INT, 'course module ID',
2340 VALUE_REQUIRED, '', NULL_NOT_ALLOWED), 'Array of course module IDs'),
2346 * Deletes a list of provided module instances.
2348 * @param array $cmids the course module ids
2349 * @since Moodle 2.5
2351 public static function delete_modules($cmids) {
2352 global $CFG, $DB;
2354 // Require course file containing the course delete module function.
2355 require_once($CFG->dirroot . "/course/lib.php");
2357 // Clean the parameters.
2358 $params = self::validate_parameters(self::delete_modules_parameters(), array('cmids' => $cmids));
2360 // Keep track of the course ids we have performed a capability check on to avoid repeating.
2361 $arrcourseschecked = array();
2363 foreach ($params['cmids'] as $cmid) {
2364 // Get the course module.
2365 $cm = $DB->get_record('course_modules', array('id' => $cmid), '*', MUST_EXIST);
2367 // Check if we have not yet confirmed they have permission in this course.
2368 if (!in_array($cm->course, $arrcourseschecked)) {
2369 // Ensure the current user has required permission in this course.
2370 $context = context_course::instance($cm->course);
2371 self::validate_context($context);
2372 // Add to the array.
2373 $arrcourseschecked[] = $cm->course;
2376 // Ensure they can delete this module.
2377 $modcontext = context_module::instance($cm->id);
2378 require_capability('moodle/course:manageactivities', $modcontext);
2380 // Delete the module.
2381 course_delete_module($cm->id);
2386 * Describes the delete_modules return value.
2388 * @return external_single_structure
2389 * @since Moodle 2.5
2391 public static function delete_modules_returns() {
2392 return null;
2396 * Returns description of method parameters
2398 * @return external_function_parameters
2399 * @since Moodle 2.9
2401 public static function view_course_parameters() {
2402 return new external_function_parameters(
2403 array(
2404 'courseid' => new external_value(PARAM_INT, 'id of the course'),
2405 'sectionnumber' => new external_value(PARAM_INT, 'section number', VALUE_DEFAULT, 0)
2411 * Trigger the course viewed event.
2413 * @param int $courseid id of course
2414 * @param int $sectionnumber sectionnumber (0, 1, 2...)
2415 * @return array of warnings and status result
2416 * @since Moodle 2.9
2417 * @throws moodle_exception
2419 public static function view_course($courseid, $sectionnumber = 0) {
2420 global $CFG;
2421 require_once($CFG->dirroot . "/course/lib.php");
2423 $params = self::validate_parameters(self::view_course_parameters(),
2424 array(
2425 'courseid' => $courseid,
2426 'sectionnumber' => $sectionnumber
2429 $warnings = array();
2431 $course = get_course($params['courseid']);
2432 $context = context_course::instance($course->id);
2433 self::validate_context($context);
2435 if (!empty($params['sectionnumber'])) {
2437 // Get section details and check it exists.
2438 $modinfo = get_fast_modinfo($course);
2439 $coursesection = $modinfo->get_section_info($params['sectionnumber'], MUST_EXIST);
2441 // Check user is allowed to see it.
2442 if (!$coursesection->uservisible) {
2443 require_capability('moodle/course:viewhiddensections', $context);
2447 course_view($context, $params['sectionnumber']);
2449 $result = array();
2450 $result['status'] = true;
2451 $result['warnings'] = $warnings;
2452 return $result;
2456 * Returns description of method result value
2458 * @return \core_external\external_description
2459 * @since Moodle 2.9
2461 public static function view_course_returns() {
2462 return new external_single_structure(
2463 array(
2464 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
2465 'warnings' => new external_warnings()
2471 * Returns description of method parameters
2473 * @return external_function_parameters
2474 * @since Moodle 3.0
2476 public static function search_courses_parameters() {
2477 return new external_function_parameters(
2478 array(
2479 'criterianame' => new external_value(PARAM_ALPHA, 'criteria name
2480 (search, modulelist (only admins), blocklist (only admins), tagid)'),
2481 'criteriavalue' => new external_value(PARAM_RAW, 'criteria value'),
2482 'page' => new external_value(PARAM_INT, 'page number (0 based)', VALUE_DEFAULT, 0),
2483 'perpage' => new external_value(PARAM_INT, 'items per page', VALUE_DEFAULT, 0),
2484 'requiredcapabilities' => new external_multiple_structure(
2485 new external_value(PARAM_CAPABILITY, 'Capability string used to filter courses by permission'),
2486 'Optional list of required capabilities (used to filter the list)', VALUE_DEFAULT, array()
2488 'limittoenrolled' => new external_value(PARAM_BOOL, 'limit to enrolled courses', VALUE_DEFAULT, 0),
2489 'onlywithcompletion' => new external_value(PARAM_BOOL, 'limit to courses where completion is enabled',
2490 VALUE_DEFAULT, 0),
2496 * Return the course information that is public (visible by every one)
2498 * @param core_course_list_element $course course in list object
2499 * @param stdClass $coursecontext course context object
2500 * @return array the course information
2501 * @since Moodle 3.2
2503 protected static function get_course_public_information(core_course_list_element $course, $coursecontext) {
2504 global $OUTPUT;
2506 static $categoriescache = array();
2508 // Category information.
2509 if (!array_key_exists($course->category, $categoriescache)) {
2510 $categoriescache[$course->category] = core_course_category::get($course->category, IGNORE_MISSING);
2512 $category = $categoriescache[$course->category];
2514 // Retrieve course overview used files.
2515 $files = array();
2516 foreach ($course->get_course_overviewfiles() as $file) {
2517 $fileurl = moodle_url::make_webservice_pluginfile_url($file->get_contextid(), $file->get_component(),
2518 $file->get_filearea(), null, $file->get_filepath(),
2519 $file->get_filename())->out(false);
2520 $files[] = array(
2521 'filename' => $file->get_filename(),
2522 'fileurl' => $fileurl,
2523 'filesize' => $file->get_filesize(),
2524 'filepath' => $file->get_filepath(),
2525 'mimetype' => $file->get_mimetype(),
2526 'timemodified' => $file->get_timemodified(),
2530 // Retrieve the course contacts,
2531 // we need here the users fullname since if we are not enrolled can be difficult to obtain them via other Web Services.
2532 $coursecontacts = array();
2533 foreach ($course->get_course_contacts() as $contact) {
2534 $coursecontacts[] = array(
2535 'id' => $contact['user']->id,
2536 'fullname' => $contact['username'],
2537 'roles' => array_map(function($role){
2538 return array('id' => $role->id, 'name' => $role->displayname);
2539 }, $contact['roles']),
2540 'role' => array('id' => $contact['role']->id, 'name' => $contact['role']->displayname),
2541 'rolename' => $contact['rolename']
2545 // Allowed enrolment methods (maybe we can self-enrol).
2546 $enroltypes = array();
2547 $instances = enrol_get_instances($course->id, true);
2548 foreach ($instances as $instance) {
2549 $enroltypes[] = $instance->enrol;
2552 // Format summary.
2553 list($summary, $summaryformat) =
2554 \core_external\util::format_text($course->summary, $course->summaryformat, $coursecontext, 'course', 'summary', null);
2556 $categoryname = '';
2557 if (!empty($category)) {
2558 $categoryname = \core_external\util::format_string($category->name, $category->get_context());
2561 $displayname = get_course_display_name_for_list($course);
2562 $coursereturns = array();
2563 $coursereturns['id'] = $course->id;
2564 $coursereturns['fullname'] = \core_external\util::format_string($course->fullname, $coursecontext);
2565 $coursereturns['displayname'] = \core_external\util::format_string($displayname, $coursecontext);
2566 $coursereturns['shortname'] = \core_external\util::format_string($course->shortname, $coursecontext);
2567 $coursereturns['categoryid'] = $course->category;
2568 $coursereturns['categoryname'] = $categoryname;
2569 $coursereturns['summary'] = $summary;
2570 $coursereturns['summaryformat'] = $summaryformat;
2571 $coursereturns['summaryfiles'] = util::get_area_files($coursecontext->id, 'course', 'summary', false, false);
2572 $coursereturns['overviewfiles'] = $files;
2573 $coursereturns['contacts'] = $coursecontacts;
2574 $coursereturns['enrollmentmethods'] = $enroltypes;
2575 $coursereturns['sortorder'] = $course->sortorder;
2576 $coursereturns['showactivitydates'] = $course->showactivitydates;
2577 $coursereturns['showcompletionconditions'] = $course->showcompletionconditions;
2579 $handler = core_course\customfield\course_handler::create();
2580 if ($customfields = $handler->export_instance_data($course->id)) {
2581 $coursereturns['customfields'] = [];
2582 foreach ($customfields as $data) {
2583 $coursereturns['customfields'][] = [
2584 'type' => $data->get_type(),
2585 'value' => $data->get_value(),
2586 'valueraw' => $data->get_data_controller()->get_value(),
2587 'name' => $data->get_name(),
2588 'shortname' => $data->get_shortname()
2593 $courseimage = \core_course\external\course_summary_exporter::get_course_image($course);
2594 if (!$courseimage) {
2595 $courseimage = $OUTPUT->get_generated_url_for_course($coursecontext);
2597 $coursereturns['courseimage'] = $courseimage;
2599 return $coursereturns;
2603 * Search courses following the specified criteria.
2605 * @param string $criterianame Criteria name (search, modulelist (only admins), blocklist (only admins), tagid)
2606 * @param string $criteriavalue Criteria value
2607 * @param int $page Page number (for pagination)
2608 * @param int $perpage Items per page
2609 * @param array $requiredcapabilities Optional list of required capabilities (used to filter the list).
2610 * @param int $limittoenrolled Limit to only enrolled courses
2611 * @param int onlywithcompletion Limit to only courses where completion is enabled
2612 * @return array of course objects and warnings
2613 * @since Moodle 3.0
2614 * @throws moodle_exception
2616 public static function search_courses($criterianame,
2617 $criteriavalue,
2618 $page=0,
2619 $perpage=0,
2620 $requiredcapabilities=array(),
2621 $limittoenrolled=0,
2622 $onlywithcompletion=0) {
2623 global $CFG;
2625 $warnings = array();
2627 $parameters = array(
2628 'criterianame' => $criterianame,
2629 'criteriavalue' => $criteriavalue,
2630 'page' => $page,
2631 'perpage' => $perpage,
2632 'requiredcapabilities' => $requiredcapabilities,
2633 'limittoenrolled' => $limittoenrolled,
2634 'onlywithcompletion' => $onlywithcompletion
2636 $params = self::validate_parameters(self::search_courses_parameters(), $parameters);
2637 self::validate_context(context_system::instance());
2639 $allowedcriterianames = array('search', 'modulelist', 'blocklist', 'tagid');
2640 if (!in_array($params['criterianame'], $allowedcriterianames)) {
2641 throw new invalid_parameter_exception('Invalid value for criterianame parameter (value: '.$params['criterianame'].'),' .
2642 'allowed values are: '.implode(',', $allowedcriterianames));
2645 if ($params['criterianame'] == 'modulelist' or $params['criterianame'] == 'blocklist') {
2646 require_capability('moodle/site:config', context_system::instance());
2649 $paramtype = array(
2650 'search' => PARAM_RAW,
2651 'modulelist' => PARAM_PLUGIN,
2652 'blocklist' => PARAM_INT,
2653 'tagid' => PARAM_INT
2655 $params['criteriavalue'] = clean_param($params['criteriavalue'], $paramtype[$params['criterianame']]);
2657 // Prepare the search API options.
2658 $searchcriteria = array();
2659 $searchcriteria[$params['criterianame']] = $params['criteriavalue'];
2660 if ($params['onlywithcompletion']) {
2661 $searchcriteria['onlywithcompletion'] = true;
2664 $options = array();
2665 if ($params['perpage'] != 0) {
2666 $offset = $params['page'] * $params['perpage'];
2667 $options = array('offset' => $offset, 'limit' => $params['perpage']);
2670 // Search the courses.
2671 $courses = core_course_category::search_courses($searchcriteria, $options, $params['requiredcapabilities']);
2672 $totalcount = core_course_category::search_courses_count($searchcriteria, $options, $params['requiredcapabilities']);
2674 if (!empty($limittoenrolled)) {
2675 // Get the courses where the current user has access.
2676 $enrolled = enrol_get_my_courses(array('id', 'cacherev'));
2679 $finalcourses = array();
2680 $categoriescache = array();
2682 foreach ($courses as $course) {
2683 if (!empty($limittoenrolled)) {
2684 // Filter out not enrolled courses.
2685 if (!isset($enrolled[$course->id])) {
2686 $totalcount--;
2687 continue;
2691 $coursecontext = context_course::instance($course->id);
2693 $finalcourses[] = self::get_course_public_information($course, $coursecontext);
2696 return array(
2697 'total' => $totalcount,
2698 'courses' => $finalcourses,
2699 'warnings' => $warnings
2704 * Returns a course structure definition
2706 * @param boolean $onlypublicdata set to true, to retrieve only fields viewable by anyone when the course is visible
2707 * @return external_single_structure the course structure
2708 * @since Moodle 3.2
2710 protected static function get_course_structure($onlypublicdata = true) {
2711 $coursestructure = array(
2712 'id' => new external_value(PARAM_INT, 'course id'),
2713 'fullname' => new external_value(PARAM_RAW, 'course full name'),
2714 'displayname' => new external_value(PARAM_RAW, 'course display name'),
2715 'shortname' => new external_value(PARAM_RAW, 'course short name'),
2716 'courseimage' => new external_value(PARAM_URL, 'Course image', VALUE_OPTIONAL),
2717 'categoryid' => new external_value(PARAM_INT, 'category id'),
2718 'categoryname' => new external_value(PARAM_RAW, 'category name'),
2719 'sortorder' => new external_value(PARAM_INT, 'Sort order in the category', VALUE_OPTIONAL),
2720 'summary' => new external_value(PARAM_RAW, 'summary'),
2721 'summaryformat' => new external_format_value('summary'),
2722 'summaryfiles' => new external_files('summary files in the summary field', VALUE_OPTIONAL),
2723 'overviewfiles' => new external_files('additional overview files attached to this course'),
2724 'showactivitydates' => new external_value(PARAM_BOOL, 'Whether the activity dates are shown or not'),
2725 'showcompletionconditions' => new external_value(PARAM_BOOL,
2726 'Whether the activity completion conditions are shown or not'),
2727 'contacts' => new external_multiple_structure(
2728 new external_single_structure(
2729 array(
2730 'id' => new external_value(PARAM_INT, 'contact user id'),
2731 'fullname' => new external_value(PARAM_NOTAGS, 'contact user fullname'),
2734 'contact users'
2736 'enrollmentmethods' => new external_multiple_structure(
2737 new external_value(PARAM_PLUGIN, 'enrollment method'),
2738 'enrollment methods list'
2740 'customfields' => new external_multiple_structure(
2741 new external_single_structure(
2742 array(
2743 'name' => new external_value(PARAM_RAW, 'The name of the custom field'),
2744 'shortname' => new external_value(PARAM_RAW,
2745 'The shortname of the custom field - to be able to build the field class in the code'),
2746 'type' => new external_value(PARAM_ALPHANUMEXT,
2747 'The type of the custom field - text field, checkbox...'),
2748 'valueraw' => new external_value(PARAM_RAW, 'The raw value of the custom field'),
2749 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
2751 ), 'Custom fields', VALUE_OPTIONAL),
2754 if (!$onlypublicdata) {
2755 $extra = array(
2756 'idnumber' => new external_value(PARAM_RAW, 'Id number', VALUE_OPTIONAL),
2757 'format' => new external_value(PARAM_PLUGIN, 'Course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
2758 'showgrades' => new external_value(PARAM_INT, '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
2759 'newsitems' => new external_value(PARAM_INT, 'Number of recent items appearing on the course page', VALUE_OPTIONAL),
2760 'startdate' => new external_value(PARAM_INT, 'Timestamp when the course start', VALUE_OPTIONAL),
2761 'enddate' => new external_value(PARAM_INT, 'Timestamp when the course end', VALUE_OPTIONAL),
2762 'maxbytes' => new external_value(PARAM_INT, 'Largest size of file that can be uploaded into', VALUE_OPTIONAL),
2763 'showreports' => new external_value(PARAM_INT, 'Are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
2764 'visible' => new external_value(PARAM_INT, '1: available to student, 0:not available', VALUE_OPTIONAL),
2765 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
2766 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
2767 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
2768 'enablecompletion' => new external_value(PARAM_INT, 'Completion enabled? 1: yes 0: no', VALUE_OPTIONAL),
2769 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
2770 'lang' => new external_value(PARAM_SAFEDIR, 'Forced course language', VALUE_OPTIONAL),
2771 'theme' => new external_value(PARAM_PLUGIN, 'Fame of the forced theme', VALUE_OPTIONAL),
2772 'marker' => new external_value(PARAM_INT, 'Current course marker', VALUE_OPTIONAL),
2773 'legacyfiles' => new external_value(PARAM_INT, 'If legacy files are enabled', VALUE_OPTIONAL),
2774 'calendartype' => new external_value(PARAM_PLUGIN, 'Calendar type', VALUE_OPTIONAL),
2775 'timecreated' => new external_value(PARAM_INT, 'Time when the course was created', VALUE_OPTIONAL),
2776 'timemodified' => new external_value(PARAM_INT, 'Last time the course was updated', VALUE_OPTIONAL),
2777 'requested' => new external_value(PARAM_INT, 'If is a requested course', VALUE_OPTIONAL),
2778 'cacherev' => new external_value(PARAM_INT, 'Cache revision number', VALUE_OPTIONAL),
2779 'filters' => new external_multiple_structure(
2780 new external_single_structure(
2781 array(
2782 'filter' => new external_value(PARAM_PLUGIN, 'Filter plugin name'),
2783 'localstate' => new external_value(PARAM_INT, 'Filter state: 1 for on, -1 for off, 0 if inherit'),
2784 'inheritedstate' => new external_value(PARAM_INT, '1 or 0 to use when localstate is set to inherit'),
2787 'Course filters', VALUE_OPTIONAL
2789 'courseformatoptions' => new external_multiple_structure(
2790 new external_single_structure(
2791 array(
2792 'name' => new external_value(PARAM_RAW, 'Course format option name.'),
2793 'value' => new external_value(PARAM_RAW, 'Course format option value.'),
2796 'Additional options for particular course format.', VALUE_OPTIONAL
2798 'communicationroomname' => new external_value(PARAM_TEXT, 'Communication tool room name.', VALUE_OPTIONAL),
2799 'communicationroomurl' => new external_value(PARAM_RAW, 'Communication tool room URL.', VALUE_OPTIONAL),
2801 $coursestructure = array_merge($coursestructure, $extra);
2803 return new external_single_structure($coursestructure);
2807 * Returns description of method result value
2809 * @return \core_external\external_description
2810 * @since Moodle 3.0
2812 public static function search_courses_returns() {
2813 return new external_single_structure(
2814 array(
2815 'total' => new external_value(PARAM_INT, 'total course count'),
2816 'courses' => new external_multiple_structure(self::get_course_structure(), 'course'),
2817 'warnings' => new external_warnings()
2823 * Returns description of method parameters
2825 * @return external_function_parameters
2826 * @since Moodle 3.0
2828 public static function get_course_module_parameters() {
2829 return new external_function_parameters(
2830 array(
2831 'cmid' => new external_value(PARAM_INT, 'The course module id')
2837 * Return information about a course module.
2839 * @param int $cmid the course module id
2840 * @return array of warnings and the course module
2841 * @since Moodle 3.0
2842 * @throws moodle_exception
2844 public static function get_course_module($cmid) {
2845 global $CFG, $DB;
2847 $params = self::validate_parameters(self::get_course_module_parameters(), array('cmid' => $cmid));
2848 $warnings = array();
2850 $cm = get_coursemodule_from_id(null, $params['cmid'], 0, true, MUST_EXIST);
2851 $context = context_module::instance($cm->id);
2852 self::validate_context($context);
2854 // If the user has permissions to manage the activity, return all the information.
2855 if (has_capability('moodle/course:manageactivities', $context)) {
2856 require_once($CFG->dirroot . '/course/modlib.php');
2857 require_once($CFG->libdir . '/gradelib.php');
2859 $info = $cm;
2860 // Get the extra information: grade, advanced grading and outcomes data.
2861 $course = get_course($cm->course);
2862 list($newcm, $newcontext, $module, $extrainfo, $cw) = get_moduleinfo_data($cm, $course);
2863 // Grades.
2864 $gradeinfo = array('grade', 'gradepass', 'gradecat');
2865 foreach ($gradeinfo as $gfield) {
2866 if (isset($extrainfo->{$gfield})) {
2867 $info->{$gfield} = $extrainfo->{$gfield};
2870 if (isset($extrainfo->grade) and $extrainfo->grade < 0) {
2871 $info->scale = $DB->get_field('scale', 'scale', array('id' => abs($extrainfo->grade)));
2873 // Advanced grading.
2874 if (isset($extrainfo->_advancedgradingdata)) {
2875 $info->advancedgrading = array();
2876 foreach ($extrainfo as $key => $val) {
2877 if (strpos($key, 'advancedgradingmethod_') === 0) {
2878 $info->advancedgrading[] = array(
2879 'area' => str_replace('advancedgradingmethod_', '', $key),
2880 'method' => $val
2885 // Outcomes.
2886 foreach ($extrainfo as $key => $val) {
2887 if (strpos($key, 'outcome_') === 0) {
2888 if (!isset($info->outcomes)) {
2889 $info->outcomes = array();
2891 $id = str_replace('outcome_', '', $key);
2892 $outcome = grade_outcome::fetch(array('id' => $id));
2893 $scaleitems = $outcome->load_scale();
2894 $info->outcomes[] = array(
2895 'id' => $id,
2896 'name' => \core_external\util::format_string($outcome->get_name(), $context),
2897 'scale' => $scaleitems->scale
2901 } else {
2902 // Return information is safe to show to any user.
2903 $info = new stdClass();
2904 $info->id = $cm->id;
2905 $info->course = $cm->course;
2906 $info->module = $cm->module;
2907 $info->modname = $cm->modname;
2908 $info->instance = $cm->instance;
2909 $info->section = $cm->section;
2910 $info->sectionnum = $cm->sectionnum;
2911 $info->groupmode = $cm->groupmode;
2912 $info->groupingid = $cm->groupingid;
2913 $info->completion = $cm->completion;
2914 $info->downloadcontent = $cm->downloadcontent;
2916 // Format name.
2917 $info->name = \core_external\util::format_string($cm->name, $context);
2918 $result = array();
2919 $result['cm'] = $info;
2920 $result['warnings'] = $warnings;
2921 return $result;
2925 * Returns description of method result value
2927 * @return \core_external\external_description
2928 * @since Moodle 3.0
2930 public static function get_course_module_returns() {
2931 return new external_single_structure(
2932 array(
2933 'cm' => new external_single_structure(
2934 array(
2935 'id' => new external_value(PARAM_INT, 'The course module id'),
2936 'course' => new external_value(PARAM_INT, 'The course id'),
2937 'module' => new external_value(PARAM_INT, 'The module type id'),
2938 'name' => new external_value(PARAM_RAW, 'The activity name'),
2939 'modname' => new external_value(PARAM_COMPONENT, 'The module component name (forum, assign, etc..)'),
2940 'instance' => new external_value(PARAM_INT, 'The activity instance id'),
2941 'section' => new external_value(PARAM_INT, 'The module section id'),
2942 'sectionnum' => new external_value(PARAM_INT, 'The module section number'),
2943 'groupmode' => new external_value(PARAM_INT, 'Group mode'),
2944 'groupingid' => new external_value(PARAM_INT, 'Grouping id'),
2945 'completion' => new external_value(PARAM_INT, 'If completion is enabled'),
2946 'idnumber' => new external_value(PARAM_RAW, 'Module id number', VALUE_OPTIONAL),
2947 'added' => new external_value(PARAM_INT, 'Time added', VALUE_OPTIONAL),
2948 'score' => new external_value(PARAM_INT, 'Score', VALUE_OPTIONAL),
2949 'indent' => new external_value(PARAM_INT, 'Indentation', VALUE_OPTIONAL),
2950 'visible' => new external_value(PARAM_INT, 'If visible', VALUE_OPTIONAL),
2951 'visibleoncoursepage' => new external_value(PARAM_INT, 'If visible on course page', VALUE_OPTIONAL),
2952 'visibleold' => new external_value(PARAM_INT, 'Visible old', VALUE_OPTIONAL),
2953 'completiongradeitemnumber' => new external_value(PARAM_INT, 'Completion grade item', VALUE_OPTIONAL),
2954 'completionpassgrade' => new external_value(PARAM_INT, 'Completion pass grade setting', VALUE_OPTIONAL),
2955 'completionview' => new external_value(PARAM_INT, 'Completion view setting', VALUE_OPTIONAL),
2956 'completionexpected' => new external_value(PARAM_INT, 'Completion time expected', VALUE_OPTIONAL),
2957 'showdescription' => new external_value(PARAM_INT, 'If the description is showed', VALUE_OPTIONAL),
2958 'downloadcontent' => new external_value(PARAM_INT, 'The download content value', VALUE_OPTIONAL),
2959 'availability' => new external_value(PARAM_RAW, 'Availability settings', VALUE_OPTIONAL),
2960 'grade' => new external_value(PARAM_FLOAT, 'Grade (max value or scale id)', VALUE_OPTIONAL),
2961 'scale' => new external_value(PARAM_TEXT, 'Scale items (if used)', VALUE_OPTIONAL),
2962 'gradepass' => new external_value(PARAM_RAW, 'Grade to pass (float)', VALUE_OPTIONAL),
2963 'gradecat' => new external_value(PARAM_INT, 'Grade category', VALUE_OPTIONAL),
2964 'advancedgrading' => new external_multiple_structure(
2965 new external_single_structure(
2966 array(
2967 'area' => new external_value(PARAM_AREA, 'Gradable area name'),
2968 'method' => new external_value(PARAM_COMPONENT, 'Grading method'),
2971 'Advanced grading settings', VALUE_OPTIONAL
2973 'outcomes' => new external_multiple_structure(
2974 new external_single_structure(
2975 array(
2976 'id' => new external_value(PARAM_ALPHANUMEXT, 'Outcome id'),
2977 'name' => new external_value(PARAM_RAW, 'Outcome full name'),
2978 'scale' => new external_value(PARAM_TEXT, 'Scale items')
2981 'Outcomes information', VALUE_OPTIONAL
2985 'warnings' => new external_warnings()
2991 * Returns description of method parameters
2993 * @return external_function_parameters
2994 * @since Moodle 3.0
2996 public static function get_course_module_by_instance_parameters() {
2997 return new external_function_parameters(
2998 array(
2999 'module' => new external_value(PARAM_COMPONENT, 'The module name'),
3000 'instance' => new external_value(PARAM_INT, 'The module instance id')
3006 * Return information about a course module.
3008 * @param string $module the module name
3009 * @param int $instance the activity instance id
3010 * @return array of warnings and the course module
3011 * @since Moodle 3.0
3012 * @throws moodle_exception
3014 public static function get_course_module_by_instance($module, $instance) {
3016 $params = self::validate_parameters(self::get_course_module_by_instance_parameters(),
3017 array(
3018 'module' => $module,
3019 'instance' => $instance,
3022 $warnings = array();
3023 $cm = get_coursemodule_from_instance($params['module'], $params['instance'], 0, false, MUST_EXIST);
3025 return self::get_course_module($cm->id);
3029 * Returns description of method result value
3031 * @return \core_external\external_description
3032 * @since Moodle 3.0
3034 public static function get_course_module_by_instance_returns() {
3035 return self::get_course_module_returns();
3039 * Returns description of method parameters
3041 * @return external_function_parameters
3042 * @since Moodle 3.2
3044 public static function get_user_navigation_options_parameters() {
3045 return new external_function_parameters(
3046 array(
3047 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
3053 * Return a list of navigation options in a set of courses that are avaialable or not for the current user.
3055 * @param array $courseids a list of course ids
3056 * @return array of warnings and the options availability
3057 * @since Moodle 3.2
3058 * @throws moodle_exception
3060 public static function get_user_navigation_options($courseids) {
3061 global $CFG;
3062 require_once($CFG->dirroot . '/course/lib.php');
3064 // Parameter validation.
3065 $params = self::validate_parameters(self::get_user_navigation_options_parameters(), array('courseids' => $courseids));
3066 $courseoptions = array();
3068 list($courses, $warnings) = util::validate_courses($params['courseids'], array(), true);
3070 if (!empty($courses)) {
3071 foreach ($courses as $course) {
3072 // Fix the context for the frontpage.
3073 if ($course->id == SITEID) {
3074 $course->context = context_system::instance();
3076 $navoptions = course_get_user_navigation_options($course->context, $course);
3077 $options = array();
3078 foreach ($navoptions as $name => $available) {
3079 $options[] = array(
3080 'name' => $name,
3081 'available' => $available,
3085 $courseoptions[] = array(
3086 'id' => $course->id,
3087 'options' => $options
3092 $result = array(
3093 'courses' => $courseoptions,
3094 'warnings' => $warnings
3096 return $result;
3100 * Returns description of method result value
3102 * @return \core_external\external_description
3103 * @since Moodle 3.2
3105 public static function get_user_navigation_options_returns() {
3106 return new external_single_structure(
3107 array(
3108 'courses' => new external_multiple_structure(
3109 new external_single_structure(
3110 array(
3111 'id' => new external_value(PARAM_INT, 'Course id'),
3112 'options' => new external_multiple_structure(
3113 new external_single_structure(
3114 array(
3115 'name' => new external_value(PARAM_ALPHANUMEXT, 'Option name'),
3116 'available' => new external_value(PARAM_BOOL, 'Whether the option is available or not'),
3121 ), 'List of courses'
3123 'warnings' => new external_warnings()
3129 * Returns description of method parameters
3131 * @return external_function_parameters
3132 * @since Moodle 3.2
3134 public static function get_user_administration_options_parameters() {
3135 return new external_function_parameters(
3136 array(
3137 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
3143 * Return a list of administration options in a set of courses that are available or not for the current user.
3145 * @param array $courseids a list of course ids
3146 * @return array of warnings and the options availability
3147 * @since Moodle 3.2
3148 * @throws moodle_exception
3150 public static function get_user_administration_options($courseids) {
3151 global $CFG;
3152 require_once($CFG->dirroot . '/course/lib.php');
3154 // Parameter validation.
3155 $params = self::validate_parameters(self::get_user_administration_options_parameters(), array('courseids' => $courseids));
3156 $courseoptions = array();
3158 list($courses, $warnings) = util::validate_courses($params['courseids'], array(), true);
3160 if (!empty($courses)) {
3161 foreach ($courses as $course) {
3162 $adminoptions = course_get_user_administration_options($course, $course->context);
3163 $options = array();
3164 foreach ($adminoptions as $name => $available) {
3165 $options[] = array(
3166 'name' => $name,
3167 'available' => $available,
3171 $courseoptions[] = array(
3172 'id' => $course->id,
3173 'options' => $options
3178 $result = array(
3179 'courses' => $courseoptions,
3180 'warnings' => $warnings
3182 return $result;
3186 * Returns description of method result value
3188 * @return \core_external\external_description
3189 * @since Moodle 3.2
3191 public static function get_user_administration_options_returns() {
3192 return self::get_user_navigation_options_returns();
3196 * Returns description of method parameters
3198 * @return external_function_parameters
3199 * @since Moodle 3.2
3201 public static function get_courses_by_field_parameters() {
3202 return new external_function_parameters(
3203 array(
3204 'field' => new external_value(PARAM_ALPHA, 'The field to search can be left empty for all courses or:
3205 id: course id
3206 ids: comma separated course ids
3207 shortname: course short name
3208 idnumber: course id number
3209 category: category id the course belongs to
3210 ', VALUE_DEFAULT, ''),
3211 'value' => new external_value(PARAM_RAW, 'The value to match', VALUE_DEFAULT, '')
3218 * Get courses matching a specific field (id/s, shortname, idnumber, category)
3220 * @param string $field field name to search, or empty for all courses
3221 * @param string $value value to search
3222 * @return array list of courses and warnings
3223 * @throws invalid_parameter_exception
3224 * @since Moodle 3.2
3226 public static function get_courses_by_field($field = '', $value = '') {
3227 global $DB, $CFG;
3228 require_once($CFG->dirroot . '/course/lib.php');
3229 require_once($CFG->libdir . '/filterlib.php');
3231 $params = self::validate_parameters(self::get_courses_by_field_parameters(),
3232 array(
3233 'field' => $field,
3234 'value' => $value,
3237 $warnings = array();
3239 if (empty($params['field'])) {
3240 $courses = $DB->get_records('course', null, 'id ASC');
3241 } else {
3242 switch ($params['field']) {
3243 case 'id':
3244 case 'category':
3245 $value = clean_param($params['value'], PARAM_INT);
3246 break;
3247 case 'ids':
3248 $value = clean_param($params['value'], PARAM_SEQUENCE);
3249 break;
3250 case 'shortname':
3251 $value = clean_param($params['value'], PARAM_TEXT);
3252 break;
3253 case 'idnumber':
3254 $value = clean_param($params['value'], PARAM_RAW);
3255 break;
3256 default:
3257 throw new invalid_parameter_exception('Invalid field name');
3260 if ($params['field'] === 'ids') {
3261 // Preload categories to avoid loading one at a time.
3262 $courseids = explode(',', $value);
3263 list ($listsql, $listparams) = $DB->get_in_or_equal($courseids);
3264 $categoryids = $DB->get_fieldset_sql("
3265 SELECT DISTINCT cc.id
3266 FROM {course} c
3267 JOIN {course_categories} cc ON cc.id = c.category
3268 WHERE c.id $listsql", $listparams);
3269 core_course_category::get_many($categoryids);
3271 // Load and validate all courses. This is called because it loads the courses
3272 // more efficiently.
3273 list ($courses, $warnings) = util::validate_courses($courseids, [],
3274 false, true);
3275 } else {
3276 $courses = $DB->get_records('course', array($params['field'] => $value), 'id ASC');
3280 $iscommapiavailable = \core_communication\api::is_available();
3282 $coursesdata = array();
3283 foreach ($courses as $course) {
3284 $context = context_course::instance($course->id);
3285 $canupdatecourse = has_capability('moodle/course:update', $context);
3286 $canviewhiddencourses = has_capability('moodle/course:viewhiddencourses', $context);
3288 // Check if the course is visible in the site for the user.
3289 if (!$course->visible and !$canviewhiddencourses and !$canupdatecourse) {
3290 continue;
3292 // Get the public course information, even if we are not enrolled.
3293 $courseinlist = new core_course_list_element($course);
3295 // Now, check if we have access to the course, unless it was already checked.
3296 try {
3297 if (empty($course->contextvalidated)) {
3298 self::validate_context($context);
3300 } catch (Exception $e) {
3301 // User can not access the course, check if they can see the public information about the course and return it.
3302 if (core_course_category::can_view_course_info($course)) {
3303 $coursesdata[$course->id] = self::get_course_public_information($courseinlist, $context);
3305 continue;
3307 $coursesdata[$course->id] = self::get_course_public_information($courseinlist, $context);
3308 // Return information for any user that can access the course.
3309 $coursefields = array('format', 'showgrades', 'newsitems', 'startdate', 'enddate', 'maxbytes', 'showreports', 'visible',
3310 'groupmode', 'groupmodeforce', 'defaultgroupingid', 'enablecompletion', 'completionnotify', 'lang', 'theme',
3311 'marker');
3313 // Course filters.
3314 $coursesdata[$course->id]['filters'] = filter_get_available_in_context($context);
3316 // Information for managers only.
3317 if ($canupdatecourse) {
3318 $managerfields = array('idnumber', 'legacyfiles', 'calendartype', 'timecreated', 'timemodified', 'requested',
3319 'cacherev');
3320 $coursefields = array_merge($coursefields, $managerfields);
3323 // Populate fields.
3324 foreach ($coursefields as $field) {
3325 $coursesdata[$course->id][$field] = $course->{$field};
3328 // Clean lang and auth fields for external functions (it may content uninstalled themes or language packs).
3329 if (isset($coursesdata[$course->id]['theme'])) {
3330 $coursesdata[$course->id]['theme'] = clean_param($coursesdata[$course->id]['theme'], PARAM_THEME);
3332 if (isset($coursesdata[$course->id]['lang'])) {
3333 $coursesdata[$course->id]['lang'] = clean_param($coursesdata[$course->id]['lang'], PARAM_LANG);
3336 $courseformatoptions = course_get_format($course)->get_config_for_external();
3337 foreach ($courseformatoptions as $key => $value) {
3338 $coursesdata[$course->id]['courseformatoptions'][] = array(
3339 'name' => $key,
3340 'value' => $value
3344 // Communication tools for the course.
3345 if ($iscommapiavailable) {
3346 $communication = \core_communication\api::load_by_instance(
3347 context: $context,
3348 component: 'core_course',
3349 instancetype: 'coursecommunication',
3350 instanceid: $course->id
3352 if ($communication->get_provider()) {
3353 $coursesdata[$course->id]['communicationroomname'] = \core_external\util::format_string($communication->get_room_name(), $context);
3354 // 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.
3355 $coursesdata[$course->id]['communicationroomurl'] = $communication->get_communication_room_url();
3360 return array(
3361 'courses' => $coursesdata,
3362 'warnings' => $warnings
3367 * Returns description of method result value
3369 * @return \core_external\external_description
3370 * @since Moodle 3.2
3372 public static function get_courses_by_field_returns() {
3373 // Course structure, including not only public viewable fields.
3374 return new external_single_structure(
3375 array(
3376 'courses' => new external_multiple_structure(self::get_course_structure(false), 'Course'),
3377 'warnings' => new external_warnings()
3383 * Returns description of method parameters
3385 * @return external_function_parameters
3386 * @since Moodle 3.2
3388 public static function check_updates_parameters() {
3389 return new external_function_parameters(
3390 array(
3391 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3392 'tocheck' => new external_multiple_structure(
3393 new external_single_structure(
3394 array(
3395 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level for the file location.
3396 Only module supported right now.'),
3397 'id' => new external_value(PARAM_INT, 'Context instance id'),
3398 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3401 'Instances to check'
3403 'filter' => new external_multiple_structure(
3404 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3405 gradeitems, outcomes'),
3406 'Check only for updates in these areas', VALUE_DEFAULT, array()
3413 * Check if there is updates affecting the user for the given course and contexts.
3414 * Right now only modules are supported.
3415 * This WS calls mod_check_updates_since for each module to check if there is any update the user should we aware of.
3417 * @param int $courseid the list of modules to check
3418 * @param array $tocheck the list of modules to check
3419 * @param array $filter check only for updates in these areas
3420 * @return array list of updates and warnings
3421 * @throws moodle_exception
3422 * @since Moodle 3.2
3424 public static function check_updates($courseid, $tocheck, $filter = array()) {
3425 global $CFG, $DB;
3426 require_once($CFG->dirroot . "/course/lib.php");
3428 $params = self::validate_parameters(
3429 self::check_updates_parameters(),
3430 array(
3431 'courseid' => $courseid,
3432 'tocheck' => $tocheck,
3433 'filter' => $filter,
3437 $course = get_course($params['courseid']);
3438 $context = context_course::instance($course->id);
3439 self::validate_context($context);
3441 list($instances, $warnings) = course_check_updates($course, $params['tocheck'], $filter);
3443 $instancesformatted = array();
3444 foreach ($instances as $instance) {
3445 $updates = array();
3446 foreach ($instance['updates'] as $name => $data) {
3447 if (empty($data->updated)) {
3448 continue;
3450 $updatedata = array(
3451 'name' => $name,
3453 if (!empty($data->timeupdated)) {
3454 $updatedata['timeupdated'] = $data->timeupdated;
3456 if (!empty($data->itemids)) {
3457 $updatedata['itemids'] = $data->itemids;
3459 $updates[] = $updatedata;
3461 if (!empty($updates)) {
3462 $instancesformatted[] = array(
3463 'contextlevel' => $instance['contextlevel'],
3464 'id' => $instance['id'],
3465 'updates' => $updates
3470 return array(
3471 'instances' => $instancesformatted,
3472 'warnings' => $warnings
3477 * Returns description of method result value
3479 * @return \core_external\external_description
3480 * @since Moodle 3.2
3482 public static function check_updates_returns() {
3483 return new external_single_structure(
3484 array(
3485 'instances' => new external_multiple_structure(
3486 new external_single_structure(
3487 array(
3488 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level'),
3489 'id' => new external_value(PARAM_INT, 'Instance id'),
3490 'updates' => new external_multiple_structure(
3491 new external_single_structure(
3492 array(
3493 'name' => new external_value(PARAM_ALPHANUMEXT, 'Name of the area updated.'),
3494 'timeupdated' => new external_value(PARAM_INT, 'Last time was updated', VALUE_OPTIONAL),
3495 'itemids' => new external_multiple_structure(
3496 new external_value(PARAM_INT, 'Instance id'),
3497 'The ids of the items updated',
3498 VALUE_OPTIONAL
3506 'warnings' => new external_warnings()
3512 * Returns description of method parameters
3514 * @return external_function_parameters
3515 * @since Moodle 3.3
3517 public static function get_updates_since_parameters() {
3518 return new external_function_parameters(
3519 array(
3520 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3521 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3522 'filter' => new external_multiple_structure(
3523 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3524 gradeitems, outcomes'),
3525 'Check only for updates in these areas', VALUE_DEFAULT, array()
3532 * Check if there are updates affecting the user for the given course since the given time stamp.
3534 * This function is a wrapper of self::check_updates for retrieving all the updates since a given time for all the activities.
3536 * @param int $courseid the list of modules to check
3537 * @param int $since check updates since this time stamp
3538 * @param array $filter check only for updates in these areas
3539 * @return array list of updates and warnings
3540 * @throws moodle_exception
3541 * @since Moodle 3.3
3543 public static function get_updates_since($courseid, $since, $filter = array()) {
3544 global $CFG, $DB;
3546 $params = self::validate_parameters(
3547 self::get_updates_since_parameters(),
3548 array(
3549 'courseid' => $courseid,
3550 'since' => $since,
3551 'filter' => $filter,
3555 $course = get_course($params['courseid']);
3556 $modinfo = get_fast_modinfo($course);
3557 $tocheck = array();
3559 // Retrieve all the visible course modules for the current user.
3560 $cms = $modinfo->get_cms();
3561 foreach ($cms as $cm) {
3562 if (!$cm->uservisible) {
3563 continue;
3565 $tocheck[] = array(
3566 'id' => $cm->id,
3567 'contextlevel' => 'module',
3568 'since' => $params['since'],
3572 return self::check_updates($course->id, $tocheck, $params['filter']);
3576 * Returns description of method result value
3578 * @return \core_external\external_description
3579 * @since Moodle 3.3
3581 public static function get_updates_since_returns() {
3582 return self::check_updates_returns();
3586 * Parameters for function edit_module()
3588 * @since Moodle 3.3
3589 * @return external_function_parameters
3591 public static function edit_module_parameters() {
3592 return new external_function_parameters(
3593 array(
3594 'action' => new external_value(PARAM_ALPHA,
3595 'action: hide, show, stealth, duplicate, delete, moveleft, moveright, group...', VALUE_REQUIRED),
3596 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3597 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3602 * Performs one of the edit module actions and return new html for AJAX
3604 * Returns html to replace the current module html with, for example:
3605 * - empty string for "delete" action,
3606 * - two modules html for "duplicate" action
3607 * - updated module html for everything else
3609 * Throws exception if operation is not permitted/possible
3611 * @since Moodle 3.3
3612 * @param string $action
3613 * @param int $id
3614 * @param null|int $sectionreturn
3615 * @return string
3617 public static function edit_module($action, $id, $sectionreturn = null) {
3618 global $PAGE, $DB;
3619 // Validate and normalize parameters.
3620 $params = self::validate_parameters(self::edit_module_parameters(),
3621 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3622 $action = $params['action'];
3623 $id = $params['id'];
3624 $sectionreturn = $params['sectionreturn'];
3626 // Set of permissions an editing user may have.
3627 $contextarray = [
3628 'moodle/course:update',
3629 'moodle/course:manageactivities',
3630 'moodle/course:activityvisibility',
3631 'moodle/course:sectionvisibility',
3632 'moodle/course:movesections',
3633 'moodle/course:setcurrentsection',
3635 $PAGE->set_other_editing_capability($contextarray);
3637 list($course, $cm) = get_course_and_cm_from_cmid($id);
3638 $modcontext = context_module::instance($cm->id);
3639 $coursecontext = context_course::instance($course->id);
3640 self::validate_context($modcontext);
3641 $format = course_get_format($course);
3642 if ($sectionreturn) {
3643 $format->set_section_number($sectionreturn);
3645 $renderer = $format->get_renderer($PAGE);
3647 switch($action) {
3648 case 'hide':
3649 case 'show':
3650 case 'stealth':
3651 require_capability('moodle/course:activityvisibility', $modcontext);
3652 $visible = ($action === 'hide') ? 0 : 1;
3653 $visibleoncoursepage = ($action === 'stealth') ? 0 : 1;
3654 set_coursemodule_visible($id, $visible, $visibleoncoursepage);
3655 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3656 break;
3657 case 'duplicate':
3658 require_capability('moodle/course:manageactivities', $coursecontext);
3659 require_capability('moodle/backup:backuptargetimport', $coursecontext);
3660 require_capability('moodle/restore:restoretargetimport', $coursecontext);
3661 if (!course_allowed_module($course, $cm->modname)) {
3662 throw new moodle_exception('No permission to create that activity');
3664 if ($newcm = duplicate_module($course, $cm)) {
3666 $modinfo = $format->get_modinfo();
3667 $section = $modinfo->get_section_info($newcm->sectionnum);
3668 $cm = $modinfo->get_cm($id);
3670 // Get both original and new element html.
3671 $result = $renderer->course_section_updated_cm_item($format, $section, $cm);
3672 $result .= $renderer->course_section_updated_cm_item($format, $section, $newcm);
3673 return $result;
3675 break;
3676 case 'groupsseparate':
3677 case 'groupsvisible':
3678 case 'groupsnone':
3679 require_capability('moodle/course:manageactivities', $modcontext);
3680 if ($action === 'groupsseparate') {
3681 $newgroupmode = SEPARATEGROUPS;
3682 } else if ($action === 'groupsvisible') {
3683 $newgroupmode = VISIBLEGROUPS;
3684 } else {
3685 $newgroupmode = NOGROUPS;
3687 if (set_coursemodule_groupmode($cm->id, $newgroupmode)) {
3688 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3690 break;
3691 case 'moveleft':
3692 case 'moveright':
3693 require_capability('moodle/course:manageactivities', $modcontext);
3694 $indent = $cm->indent + (($action === 'moveright') ? 1 : -1);
3695 if ($cm->indent >= 0) {
3696 $DB->update_record('course_modules', array('id' => $cm->id, 'indent' => $indent));
3697 rebuild_course_cache($cm->course);
3699 break;
3700 case 'delete':
3701 require_capability('moodle/course:manageactivities', $modcontext);
3702 course_delete_module($cm->id, true);
3703 return '';
3704 default:
3705 throw new coding_exception('Unrecognised action');
3708 $modinfo = $format->get_modinfo();
3709 $section = $modinfo->get_section_info($cm->sectionnum);
3710 $cm = $modinfo->get_cm($id);
3711 return $renderer->course_section_updated_cm_item($format, $section, $cm);
3715 * Return structure for edit_module()
3717 * @since Moodle 3.3
3718 * @return \core_external\external_description
3720 public static function edit_module_returns() {
3721 return new external_value(PARAM_RAW, 'html to replace the current module with');
3725 * Parameters for function get_module()
3727 * @since Moodle 3.3
3728 * @return external_function_parameters
3730 public static function get_module_parameters() {
3731 return new external_function_parameters(
3732 array(
3733 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3734 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3739 * Returns html for displaying one activity module on course page
3741 * @since Moodle 3.3
3742 * @param int $id
3743 * @param null|int $sectionreturn
3744 * @return string
3746 public static function get_module($id, $sectionreturn = null) {
3747 global $PAGE;
3748 // Validate and normalize parameters.
3749 $params = self::validate_parameters(self::get_module_parameters(),
3750 array('id' => $id, 'sectionreturn' => $sectionreturn));
3751 $id = $params['id'];
3752 $sectionreturn = $params['sectionreturn'];
3754 // Set of permissions an editing user may have.
3755 $contextarray = [
3756 'moodle/course:update',
3757 'moodle/course:manageactivities',
3758 'moodle/course:activityvisibility',
3759 'moodle/course:sectionvisibility',
3760 'moodle/course:movesections',
3761 'moodle/course:setcurrentsection',
3763 $PAGE->set_other_editing_capability($contextarray);
3765 // Validate access to the course (note, this is html for the course view page, we don't validate access to the module).
3766 list($course, $cm) = get_course_and_cm_from_cmid($id);
3767 self::validate_context(context_course::instance($course->id));
3769 $format = course_get_format($course);
3770 if ($sectionreturn) {
3771 $format->set_section_number($sectionreturn);
3773 $renderer = $format->get_renderer($PAGE);
3775 $modinfo = $format->get_modinfo();
3776 $section = $modinfo->get_section_info($cm->sectionnum);
3777 return $renderer->course_section_updated_cm_item($format, $section, $cm);
3781 * Return structure for get_module()
3783 * @since Moodle 3.3
3784 * @return \core_external\external_description
3786 public static function get_module_returns() {
3787 return new external_value(PARAM_RAW, 'html to replace the current module with');
3791 * Parameters for function edit_section()
3793 * @since Moodle 3.3
3794 * @return external_function_parameters
3796 public static function edit_section_parameters() {
3797 return new external_function_parameters(
3798 array(
3799 'action' => new external_value(PARAM_ALPHA, 'action: hide, show, stealth, setmarker, removemarker', VALUE_REQUIRED),
3800 'id' => new external_value(PARAM_INT, 'course section id', VALUE_REQUIRED),
3801 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3806 * Performs one of the edit section actions
3808 * @since Moodle 3.3
3809 * @param string $action
3810 * @param int $id section id
3811 * @param int $sectionreturn section to return to
3812 * @return string
3814 public static function edit_section($action, $id, $sectionreturn) {
3815 global $DB;
3816 // Validate and normalize parameters.
3817 $params = self::validate_parameters(self::edit_section_parameters(),
3818 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3819 $action = $params['action'];
3820 $id = $params['id'];
3821 $sr = $params['sectionreturn'];
3823 $section = $DB->get_record('course_sections', array('id' => $id), '*', MUST_EXIST);
3824 $coursecontext = context_course::instance($section->course);
3825 self::validate_context($coursecontext);
3827 $rv = course_get_format($section->course)->section_action($section, $action, $sectionreturn);
3828 if ($rv) {
3829 return json_encode($rv);
3830 } else {
3831 return null;
3836 * Return structure for edit_section()
3838 * @since Moodle 3.3
3839 * @return \core_external\external_description
3841 public static function edit_section_returns() {
3842 return new external_value(PARAM_RAW, 'Additional data for javascript (JSON-encoded string)');
3846 * Returns description of method parameters
3848 * @return external_function_parameters
3850 public static function get_enrolled_courses_by_timeline_classification_parameters() {
3851 return new external_function_parameters(
3852 array(
3853 'classification' => new external_value(PARAM_ALPHA, 'future, inprogress, or past'),
3854 'limit' => new external_value(PARAM_INT, 'Result set limit', VALUE_DEFAULT, 0),
3855 'offset' => new external_value(PARAM_INT, 'Result set offset', VALUE_DEFAULT, 0),
3856 'sort' => new external_value(PARAM_TEXT, 'Sort string', VALUE_DEFAULT, null),
3857 'customfieldname' => new external_value(PARAM_ALPHANUMEXT, 'Used when classification = customfield',
3858 VALUE_DEFAULT, null),
3859 'customfieldvalue' => new external_value(PARAM_RAW, 'Used when classification = customfield',
3860 VALUE_DEFAULT, null),
3861 'searchvalue' => new external_value(PARAM_RAW, 'The value a user wishes to search against',
3862 VALUE_DEFAULT, null),
3868 * Get courses matching the given timeline classification.
3870 * NOTE: The offset applies to the unfiltered full set of courses before the classification
3871 * filtering is done.
3872 * E.g.
3873 * If the user is enrolled in 5 courses:
3874 * c1, c2, c3, c4, and c5
3875 * And c4 and c5 are 'future' courses
3877 * If a request comes in for future courses with an offset of 1 it will mean that
3878 * c1 is skipped (because the offset applies *before* the classification filtering)
3879 * and c4 and c5 will be return.
3881 * @param string $classification past, inprogress, or future
3882 * @param int $limit Result set limit
3883 * @param int $offset Offset the full course set before timeline classification is applied
3884 * @param string $sort SQL sort string for results
3885 * @param string $customfieldname
3886 * @param string $customfieldvalue
3887 * @param string $searchvalue
3888 * @return array list of courses and warnings
3889 * @throws invalid_parameter_exception
3891 public static function get_enrolled_courses_by_timeline_classification(
3892 string $classification,
3893 int $limit = 0,
3894 int $offset = 0,
3895 string $sort = null,
3896 string $customfieldname = null,
3897 string $customfieldvalue = null,
3898 string $searchvalue = null
3900 global $CFG, $PAGE, $USER;
3901 require_once($CFG->dirroot . '/course/lib.php');
3903 $params = self::validate_parameters(self::get_enrolled_courses_by_timeline_classification_parameters(),
3904 array(
3905 'classification' => $classification,
3906 'limit' => $limit,
3907 'offset' => $offset,
3908 'sort' => $sort,
3909 'customfieldvalue' => $customfieldvalue,
3910 'searchvalue' => $searchvalue,
3914 $classification = $params['classification'];
3915 $limit = $params['limit'];
3916 $offset = $params['offset'];
3917 $sort = $params['sort'];
3918 $customfieldvalue = $params['customfieldvalue'];
3919 $searchvalue = clean_param($params['searchvalue'], PARAM_TEXT);
3921 switch($classification) {
3922 case COURSE_TIMELINE_ALLINCLUDINGHIDDEN:
3923 break;
3924 case COURSE_TIMELINE_ALL:
3925 break;
3926 case COURSE_TIMELINE_PAST:
3927 break;
3928 case COURSE_TIMELINE_INPROGRESS:
3929 break;
3930 case COURSE_TIMELINE_FUTURE:
3931 break;
3932 case COURSE_FAVOURITES:
3933 break;
3934 case COURSE_TIMELINE_HIDDEN:
3935 break;
3936 case COURSE_TIMELINE_SEARCH:
3937 break;
3938 case COURSE_CUSTOMFIELD:
3939 break;
3940 default:
3941 throw new invalid_parameter_exception('Invalid classification');
3944 self::validate_context(context_user::instance($USER->id));
3946 $requiredproperties = course_summary_exporter::define_properties();
3947 $fields = join(',', array_keys($requiredproperties));
3948 $hiddencourses = get_hidden_courses_on_timeline();
3949 $courses = [];
3951 // If the timeline requires really all courses, get really all courses.
3952 if ($classification == COURSE_TIMELINE_ALLINCLUDINGHIDDEN) {
3953 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields, COURSE_DB_QUERY_LIMIT);
3955 // Otherwise if the timeline requires the hidden courses then restrict the result to only $hiddencourses.
3956 } else if ($classification == COURSE_TIMELINE_HIDDEN) {
3957 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields,
3958 COURSE_DB_QUERY_LIMIT, $hiddencourses);
3960 // Otherwise get the requested courses and exclude the hidden courses.
3961 } else if ($classification == COURSE_TIMELINE_SEARCH) {
3962 // Prepare the search API options.
3963 $searchcriteria['search'] = $searchvalue;
3964 $options = ['idonly' => true];
3965 $courses = course_get_enrolled_courses_for_logged_in_user_from_search(
3967 $offset,
3968 $sort,
3969 $fields,
3970 COURSE_DB_QUERY_LIMIT,
3971 $searchcriteria,
3972 $options
3974 } else {
3975 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields,
3976 COURSE_DB_QUERY_LIMIT, [], $hiddencourses);
3979 $favouritecourseids = [];
3980 $ufservice = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($USER->id));
3981 $favourites = $ufservice->find_favourites_by_type('core_course', 'courses');
3983 if ($favourites) {
3984 $favouritecourseids = array_map(
3985 function($favourite) {
3986 return $favourite->itemid;
3987 }, $favourites);
3990 if ($classification == COURSE_FAVOURITES) {
3991 list($filteredcourses, $processedcount) = course_filter_courses_by_favourites(
3992 $courses,
3993 $favouritecourseids,
3994 $limit
3996 } else if ($classification == COURSE_CUSTOMFIELD) {
3997 list($filteredcourses, $processedcount) = course_filter_courses_by_customfield(
3998 $courses,
3999 $customfieldname,
4000 $customfieldvalue,
4001 $limit
4003 } else {
4004 list($filteredcourses, $processedcount) = course_filter_courses_by_timeline_classification(
4005 $courses,
4006 $classification,
4007 $limit
4011 $renderer = $PAGE->get_renderer('core');
4012 $formattedcourses = array_map(function($course) use ($renderer, $favouritecourseids) {
4013 if ($course == null) {
4014 return;
4016 context_helper::preload_from_record($course);
4017 $context = context_course::instance($course->id);
4018 $isfavourite = false;
4019 if (in_array($course->id, $favouritecourseids)) {
4020 $isfavourite = true;
4022 $exporter = new course_summary_exporter($course, ['context' => $context, 'isfavourite' => $isfavourite]);
4023 return $exporter->export($renderer);
4024 }, $filteredcourses);
4026 $formattedcourses = array_filter($formattedcourses, function($course) {
4027 if ($course != null) {
4028 return $course;
4032 return [
4033 'courses' => $formattedcourses,
4034 'nextoffset' => $offset + $processedcount
4039 * Returns description of method result value
4041 * @return \core_external\external_description
4043 public static function get_enrolled_courses_by_timeline_classification_returns() {
4044 return new external_single_structure(
4045 array(
4046 'courses' => new external_multiple_structure(course_summary_exporter::get_read_structure(), 'Course'),
4047 'nextoffset' => new external_value(PARAM_INT, 'Offset for the next request')
4053 * Returns description of method parameters
4055 * @return external_function_parameters
4057 public static function set_favourite_courses_parameters() {
4058 return new external_function_parameters(
4059 array(
4060 'courses' => new external_multiple_structure(
4061 new external_single_structure(
4062 array(
4063 'id' => new external_value(PARAM_INT, 'course ID'),
4064 'favourite' => new external_value(PARAM_BOOL, 'favourite status')
4073 * Set the course favourite status for an array of courses.
4075 * @param array $courses List with course id's and favourite status.
4076 * @return array Array with an array of favourite courses.
4078 public static function set_favourite_courses(
4079 array $courses
4081 global $USER;
4083 $params = self::validate_parameters(self::set_favourite_courses_parameters(),
4084 array(
4085 'courses' => $courses
4089 $warnings = [];
4091 $ufservice = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($USER->id));
4093 foreach ($params['courses'] as $course) {
4095 $warning = [];
4097 $favouriteexists = $ufservice->favourite_exists('core_course', 'courses', $course['id'],
4098 \context_course::instance($course['id']));
4100 if ($course['favourite']) {
4101 if (!$favouriteexists) {
4102 try {
4103 $ufservice->create_favourite('core_course', 'courses', $course['id'],
4104 \context_course::instance($course['id']));
4105 } catch (Exception $e) {
4106 $warning['courseid'] = $course['id'];
4107 if ($e instanceof moodle_exception) {
4108 $warning['warningcode'] = $e->errorcode;
4109 } else {
4110 $warning['warningcode'] = $e->getCode();
4112 $warning['message'] = $e->getMessage();
4113 $warnings[] = $warning;
4114 $warnings[] = $warning;
4116 } else {
4117 $warning['courseid'] = $course['id'];
4118 $warning['warningcode'] = 'coursealreadyfavourited';
4119 $warning['message'] = 'Course already favourited';
4120 $warnings[] = $warning;
4122 } else {
4123 if ($favouriteexists) {
4124 try {
4125 $ufservice->delete_favourite('core_course', 'courses', $course['id'],
4126 \context_course::instance($course['id']));
4127 } catch (Exception $e) {
4128 $warning['courseid'] = $course['id'];
4129 if ($e instanceof moodle_exception) {
4130 $warning['warningcode'] = $e->errorcode;
4131 } else {
4132 $warning['warningcode'] = $e->getCode();
4134 $warning['message'] = $e->getMessage();
4135 $warnings[] = $warning;
4136 $warnings[] = $warning;
4138 } else {
4139 $warning['courseid'] = $course['id'];
4140 $warning['warningcode'] = 'cannotdeletefavourite';
4141 $warning['message'] = 'Could not delete favourite status for course';
4142 $warnings[] = $warning;
4147 return [
4148 'warnings' => $warnings
4153 * Returns description of method result value
4155 * @return \core_external\external_description
4157 public static function set_favourite_courses_returns() {
4158 return new external_single_structure(
4159 array(
4160 'warnings' => new external_warnings()
4166 * Returns description of method parameters
4168 * @return external_function_parameters
4169 * @since Moodle 3.6
4171 public static function get_recent_courses_parameters() {
4172 return new external_function_parameters(
4173 array(
4174 'userid' => new external_value(PARAM_INT, 'id of the user, default to current user', VALUE_DEFAULT, 0),
4175 'limit' => new external_value(PARAM_INT, 'result set limit', VALUE_DEFAULT, 0),
4176 'offset' => new external_value(PARAM_INT, 'Result set offset', VALUE_DEFAULT, 0),
4177 'sort' => new external_value(PARAM_TEXT, 'Sort string', VALUE_DEFAULT, null)
4183 * Get last accessed courses adding additional course information like images.
4185 * @param int $userid User id from which the courses will be obtained
4186 * @param int $limit Restrict result set to this amount
4187 * @param int $offset Skip this number of records from the start of the result set
4188 * @param string|null $sort SQL string for sorting
4189 * @return array List of courses
4190 * @throws invalid_parameter_exception
4192 public static function get_recent_courses(int $userid = 0, int $limit = 0, int $offset = 0, string $sort = null) {
4193 global $USER, $PAGE;
4195 if (empty($userid)) {
4196 $userid = $USER->id;
4199 $params = self::validate_parameters(self::get_recent_courses_parameters(),
4200 array(
4201 'userid' => $userid,
4202 'limit' => $limit,
4203 'offset' => $offset,
4204 'sort' => $sort
4208 $userid = $params['userid'];
4209 $limit = $params['limit'];
4210 $offset = $params['offset'];
4211 $sort = $params['sort'];
4213 $usercontext = context_user::instance($userid);
4215 self::validate_context($usercontext);
4217 if ($userid != $USER->id and !has_capability('moodle/user:viewdetails', $usercontext)) {
4218 return array();
4221 $courses = course_get_recent_courses($userid, $limit, $offset, $sort);
4223 $renderer = $PAGE->get_renderer('core');
4225 $recentcourses = array_map(function($course) use ($renderer) {
4226 context_helper::preload_from_record($course);
4227 $context = context_course::instance($course->id);
4228 $isfavourite = !empty($course->component);
4229 $exporter = new course_summary_exporter($course, ['context' => $context, 'isfavourite' => $isfavourite]);
4230 return $exporter->export($renderer);
4231 }, $courses);
4233 return $recentcourses;
4237 * Returns description of method result value
4239 * @return \core_external\external_description
4240 * @since Moodle 3.6
4242 public static function get_recent_courses_returns() {
4243 return new external_multiple_structure(course_summary_exporter::get_read_structure(), 'Courses');
4247 * Returns description of method parameters
4249 * @return external_function_parameters
4251 public static function get_enrolled_users_by_cmid_parameters() {
4252 return new external_function_parameters([
4253 'cmid' => new external_value(PARAM_INT, 'id of the course module', VALUE_REQUIRED),
4254 'groupid' => new external_value(PARAM_INT, 'id of the group', VALUE_DEFAULT, 0),
4255 'onlyactive' => new external_value(PARAM_BOOL, 'whether to return only active users or all.',
4256 VALUE_DEFAULT, false),
4261 * Get all users in a course for a given cmid.
4263 * @param int $cmid Course Module id from which the users will be obtained
4264 * @param int $groupid Group id from which the users will be obtained
4265 * @param bool $onlyactive Whether to return only the active enrolled users or all enrolled users in the course.
4266 * @return array List of users
4267 * @throws invalid_parameter_exception
4269 public static function get_enrolled_users_by_cmid(int $cmid, int $groupid = 0, bool $onlyactive = false) {
4270 global $PAGE;
4271 $warnings = [];
4273 self::validate_parameters(self::get_enrolled_users_by_cmid_parameters(), [
4274 'cmid' => $cmid,
4275 'groupid' => $groupid,
4276 'onlyactive' => $onlyactive,
4279 list($course, $cm) = get_course_and_cm_from_cmid($cmid);
4280 $coursecontext = context_course::instance($course->id);
4281 self::validate_context($coursecontext);
4283 $enrolledusers = get_enrolled_users($coursecontext, '', $groupid, 'u.*', null, 0, 0, $onlyactive);
4285 $users = array_map(function ($user) use ($PAGE) {
4286 $user->fullname = fullname($user);
4287 $userpicture = new user_picture($user);
4288 $userpicture->size = 1;
4289 $user->profileimage = $userpicture->get_url($PAGE)->out(false);
4290 return $user;
4291 }, $enrolledusers);
4292 sort($users);
4294 return [
4295 'users' => $users,
4296 'warnings' => $warnings,
4301 * Returns description of method result value
4303 * @return \core_external\external_description
4305 public static function get_enrolled_users_by_cmid_returns() {
4306 return new external_single_structure([
4307 'users' => new external_multiple_structure(self::user_description()),
4308 'warnings' => new external_warnings(),
4313 * Create user return value description.
4315 * @return \core_external\external_description
4317 public static function user_description() {
4318 $userfields = array(
4319 'id' => new external_value(core_user::get_property_type('id'), 'ID of the user'),
4320 'profileimage' => new external_value(PARAM_URL, 'The location of the users larger image', VALUE_OPTIONAL),
4321 'fullname' => new external_value(PARAM_TEXT, 'The full name of the user', VALUE_OPTIONAL),
4322 'firstname' => new external_value(
4323 core_user::get_property_type('firstname'),
4324 'The first name(s) of the user',
4325 VALUE_OPTIONAL),
4326 'lastname' => new external_value(
4327 core_user::get_property_type('lastname'),
4328 'The family name of the user',
4329 VALUE_OPTIONAL),
4331 return new external_single_structure($userfields);
4335 * Returns description of method parameters.
4337 * @return external_function_parameters
4339 public static function add_content_item_to_user_favourites_parameters() {
4340 return new external_function_parameters([
4341 'componentname' => new external_value(PARAM_TEXT,
4342 'frankenstyle name of the component to which the content item belongs', VALUE_REQUIRED),
4343 'contentitemid' => new external_value(PARAM_INT, 'id of the content item', VALUE_REQUIRED, '', NULL_NOT_ALLOWED)
4348 * Add a content item to a user's favourites.
4350 * @param string $componentname the name of the component from which this content item originates.
4351 * @param int $contentitemid the id of the content item.
4352 * @return stdClass the exporter content item.
4354 public static function add_content_item_to_user_favourites(string $componentname, int $contentitemid) {
4355 global $USER;
4358 'componentname' => $componentname,
4359 'contentitemid' => $contentitemid,
4360 ] = self::validate_parameters(self::add_content_item_to_user_favourites_parameters(),
4362 'componentname' => $componentname,
4363 'contentitemid' => $contentitemid,
4367 self::validate_context(context_user::instance($USER->id));
4369 $contentitemservice = \core_course\local\factory\content_item_service_factory::get_content_item_service();
4371 return $contentitemservice->add_to_user_favourites($USER, $componentname, $contentitemid);
4375 * Returns description of method result value.
4377 * @return \core_external\external_description
4379 public static function add_content_item_to_user_favourites_returns() {
4380 return \core_course\local\exporters\course_content_item_exporter::get_read_structure();
4384 * Returns description of method parameters.
4386 * @return external_function_parameters
4388 public static function remove_content_item_from_user_favourites_parameters() {
4389 return new external_function_parameters([
4390 'componentname' => new external_value(PARAM_TEXT,
4391 'frankenstyle name of the component to which the content item belongs', VALUE_REQUIRED),
4392 'contentitemid' => new external_value(PARAM_INT, 'id of the content item', VALUE_REQUIRED, '', NULL_NOT_ALLOWED),
4397 * Remove a content item from a user's favourites.
4399 * @param string $componentname the name of the component from which this content item originates.
4400 * @param int $contentitemid the id of the content item.
4401 * @return stdClass the exported content item.
4403 public static function remove_content_item_from_user_favourites(string $componentname, int $contentitemid) {
4404 global $USER;
4407 'componentname' => $componentname,
4408 'contentitemid' => $contentitemid,
4409 ] = self::validate_parameters(self::remove_content_item_from_user_favourites_parameters(),
4411 'componentname' => $componentname,
4412 'contentitemid' => $contentitemid,
4416 self::validate_context(context_user::instance($USER->id));
4418 $contentitemservice = \core_course\local\factory\content_item_service_factory::get_content_item_service();
4420 return $contentitemservice->remove_from_user_favourites($USER, $componentname, $contentitemid);
4424 * Returns description of method result value.
4426 * @return \core_external\external_description
4428 public static function remove_content_item_from_user_favourites_returns() {
4429 return \core_course\local\exporters\course_content_item_exporter::get_read_structure();
4433 * Returns description of method result value
4435 * @return \core_external\external_description
4437 public static function get_course_content_items_returns() {
4438 return new external_single_structure([
4439 'content_items' => new external_multiple_structure(
4440 \core_course\local\exporters\course_content_item_exporter::get_read_structure()
4446 * Returns description of method parameters
4448 * @return external_function_parameters
4450 public static function get_course_content_items_parameters() {
4451 return new external_function_parameters([
4452 'courseid' => new external_value(PARAM_INT, 'ID of the course', VALUE_REQUIRED),
4457 * Given a course ID fetch all accessible modules for that course
4459 * @param int $courseid The course we want to fetch the modules for
4460 * @return array Contains array of modules and their metadata
4462 public static function get_course_content_items(int $courseid) {
4463 global $USER;
4466 'courseid' => $courseid,
4467 ] = self::validate_parameters(self::get_course_content_items_parameters(), [
4468 'courseid' => $courseid,
4471 $coursecontext = context_course::instance($courseid);
4472 self::validate_context($coursecontext);
4473 $course = get_course($courseid);
4475 $contentitemservice = \core_course\local\factory\content_item_service_factory::get_content_item_service();
4477 $contentitems = $contentitemservice->get_content_items_for_user_in_course($USER, $course);
4478 return ['content_items' => $contentitems];
4482 * Returns description of method parameters.
4484 * @return external_function_parameters
4486 public static function toggle_activity_recommendation_parameters() {
4487 return new external_function_parameters([
4488 'area' => new external_value(PARAM_TEXT, 'The favourite area (itemtype)', VALUE_REQUIRED),
4489 'id' => new external_value(PARAM_INT, 'id of the activity or whatever', VALUE_REQUIRED),
4494 * Update the recommendation for an activity item.
4496 * @param string $area identifier for this activity.
4497 * @param int $id Associated id. This is needed in conjunction with the area to find the recommendation.
4498 * @return array some warnings or something.
4500 public static function toggle_activity_recommendation(string $area, int $id): array {
4501 ['area' => $area, 'id' => $id] = self::validate_parameters(self::toggle_activity_recommendation_parameters(),
4502 ['area' => $area, 'id' => $id]);
4504 $context = context_system::instance();
4505 self::validate_context($context);
4507 require_capability('moodle/course:recommendactivity', $context);
4509 $manager = \core_course\local\factory\content_item_service_factory::get_content_item_service();
4511 $status = $manager->toggle_recommendation($area, $id);
4512 return ['id' => $id, 'area' => $area, 'status' => $status];
4516 * Returns warnings.
4518 * @return \core_external\external_description
4520 public static function toggle_activity_recommendation_returns() {
4521 return new external_single_structure(
4523 'id' => new external_value(PARAM_INT, 'id of the activity or whatever'),
4524 'area' => new external_value(PARAM_TEXT, 'The favourite area (itemtype)'),
4525 'status' => new external_value(PARAM_BOOL, 'If created or deleted'),
4531 * Returns description of method parameters
4533 * @return external_function_parameters
4535 public static function get_activity_chooser_footer_parameters() {
4536 return new external_function_parameters([
4537 'courseid' => new external_value(PARAM_INT, 'ID of the course', VALUE_REQUIRED),
4538 'sectionid' => new external_value(PARAM_INT, 'ID of the section', VALUE_REQUIRED),
4543 * Given a course ID we need to build up a footre for the chooser.
4545 * @param int $courseid The course we want to fetch the modules for
4546 * @param int $sectionid The section we want to fetch the modules for
4547 * @return array
4549 public static function get_activity_chooser_footer(int $courseid, int $sectionid) {
4551 'courseid' => $courseid,
4552 'sectionid' => $sectionid,
4553 ] = self::validate_parameters(self::get_activity_chooser_footer_parameters(), [
4554 'courseid' => $courseid,
4555 'sectionid' => $sectionid,
4558 $coursecontext = context_course::instance($courseid);
4559 self::validate_context($coursecontext);
4561 $activeplugin = get_config('core', 'activitychooseractivefooter');
4563 if ($activeplugin !== COURSE_CHOOSER_FOOTER_NONE) {
4564 $footerdata = component_callback($activeplugin, 'custom_chooser_footer', [$courseid, $sectionid]);
4565 return [
4566 'footer' => true,
4567 'customfooterjs' => $footerdata->get_footer_js_file(),
4568 'customfootertemplate' => $footerdata->get_footer_template(),
4569 'customcarouseltemplate' => $footerdata->get_carousel_template(),
4571 } else {
4572 return [
4573 'footer' => false,
4579 * Returns description of method result value
4581 * @return \core_external\external_description
4583 public static function get_activity_chooser_footer_returns() {
4584 return new external_single_structure(
4586 'footer' => new external_value(PARAM_BOOL, 'Is a footer being return by this request?', VALUE_REQUIRED),
4587 'customfooterjs' => new external_value(PARAM_RAW, 'The path to the plugin JS file', VALUE_OPTIONAL),
4588 'customfootertemplate' => new external_value(PARAM_RAW, 'The prerendered footer', VALUE_OPTIONAL),
4589 'customcarouseltemplate' => new external_value(PARAM_RAW, 'Either "" or the prerendered carousel page',
4590 VALUE_OPTIONAL),