Merge branch 'MDL-73493' of git://github.com/paulholden/moodle
[moodle.git] / course / externallib.php
blob42a2369e2452ed2e4cdd8befdb9cf84b6c96746e
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_availability\info;
33 require_once("$CFG->libdir/externallib.php");
34 require_once(__DIR__ . "/lib.php");
36 /**
37 * Course external functions
39 * @package core_course
40 * @category external
41 * @copyright 2011 Jerome Mouneyrac
42 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
43 * @since Moodle 2.2
45 class core_course_external extends external_api {
47 /**
48 * Returns description of method parameters
50 * @return external_function_parameters
51 * @since Moodle 2.9 Options available
52 * @since Moodle 2.2
54 public static function get_course_contents_parameters() {
55 return new external_function_parameters(
56 array('courseid' => new external_value(PARAM_INT, 'course id'),
57 'options' => new external_multiple_structure (
58 new external_single_structure(
59 array(
60 'name' => new external_value(PARAM_ALPHANUM,
61 'The expected keys (value format) are:
62 excludemodules (bool) Do not return modules, return only the sections structure
63 excludecontents (bool) Do not return module contents (i.e: files inside a resource)
64 includestealthmodules (bool) Return stealth modules for students in a special
65 section (with id -1)
66 sectionid (int) Return only this section
67 sectionnumber (int) Return only this section with number (order)
68 cmid (int) Return only this module information (among the whole sections structure)
69 modname (string) Return only modules with this name "label, forum, etc..."
70 modid (int) Return only the module with this id (to be used with modname'),
71 'value' => new external_value(PARAM_RAW, 'the value of the option,
72 this param is personaly validated in the external function.')
74 ), 'Options, used since Moodle 2.9', VALUE_DEFAULT, array())
79 /**
80 * Get course contents
82 * @param int $courseid course id
83 * @param array $options Options for filtering the results, used since Moodle 2.9
84 * @return array
85 * @since Moodle 2.9 Options available
86 * @since Moodle 2.2
88 public static function get_course_contents($courseid, $options = array()) {
89 global $CFG, $DB, $USER, $PAGE;
90 require_once($CFG->dirroot . "/course/lib.php");
91 require_once($CFG->libdir . '/completionlib.php');
93 //validate parameter
94 $params = self::validate_parameters(self::get_course_contents_parameters(),
95 array('courseid' => $courseid, 'options' => $options));
97 $filters = array();
98 if (!empty($params['options'])) {
100 foreach ($params['options'] as $option) {
101 $name = trim($option['name']);
102 // Avoid duplicated options.
103 if (!isset($filters[$name])) {
104 switch ($name) {
105 case 'excludemodules':
106 case 'excludecontents':
107 case 'includestealthmodules':
108 $value = clean_param($option['value'], PARAM_BOOL);
109 $filters[$name] = $value;
110 break;
111 case 'sectionid':
112 case 'sectionnumber':
113 case 'cmid':
114 case 'modid':
115 $value = clean_param($option['value'], PARAM_INT);
116 if (is_numeric($value)) {
117 $filters[$name] = $value;
118 } else {
119 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
121 break;
122 case 'modname':
123 $value = clean_param($option['value'], PARAM_PLUGIN);
124 if ($value) {
125 $filters[$name] = $value;
126 } else {
127 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
129 break;
130 default:
131 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
137 //retrieve the course
138 $course = $DB->get_record('course', array('id' => $params['courseid']), '*', MUST_EXIST);
140 if ($course->id != SITEID) {
141 // Check course format exist.
142 if (!file_exists($CFG->dirroot . '/course/format/' . $course->format . '/lib.php')) {
143 throw new moodle_exception('cannotgetcoursecontents', 'webservice', '', null,
144 get_string('courseformatnotfound', 'error', $course->format));
145 } else {
146 require_once($CFG->dirroot . '/course/format/' . $course->format . '/lib.php');
150 // now security checks
151 $context = context_course::instance($course->id, IGNORE_MISSING);
152 try {
153 self::validate_context($context);
154 } catch (Exception $e) {
155 $exceptionparam = new stdClass();
156 $exceptionparam->message = $e->getMessage();
157 $exceptionparam->courseid = $course->id;
158 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
161 $canupdatecourse = has_capability('moodle/course:update', $context);
163 //create return value
164 $coursecontents = array();
166 if ($canupdatecourse or $course->visible
167 or has_capability('moodle/course:viewhiddencourses', $context)) {
169 //retrieve sections
170 $modinfo = get_fast_modinfo($course);
171 $sections = $modinfo->get_section_info_all();
172 $courseformat = course_get_format($course);
173 $coursenumsections = $courseformat->get_last_section_number();
174 $stealthmodules = array(); // Array to keep all the modules available but not visible in a course section/topic.
176 $completioninfo = new completion_info($course);
178 //for each sections (first displayed to last displayed)
179 $modinfosections = $modinfo->get_sections();
180 foreach ($sections as $key => $section) {
182 // This becomes true when we are filtering and we found the value to filter with.
183 $sectionfound = false;
185 // Filter by section id.
186 if (!empty($filters['sectionid'])) {
187 if ($section->id != $filters['sectionid']) {
188 continue;
189 } else {
190 $sectionfound = true;
194 // Filter by section number. Note that 0 is a valid section number.
195 if (isset($filters['sectionnumber'])) {
196 if ($key != $filters['sectionnumber']) {
197 continue;
198 } else {
199 $sectionfound = true;
203 // reset $sectioncontents
204 $sectionvalues = array();
205 $sectionvalues['id'] = $section->id;
206 $sectionvalues['name'] = get_section_name($course, $section);
207 $sectionvalues['visible'] = $section->visible;
209 $options = (object) array('noclean' => true);
210 list($sectionvalues['summary'], $sectionvalues['summaryformat']) =
211 external_format_text($section->summary, $section->summaryformat,
212 $context->id, 'course', 'section', $section->id, $options);
213 $sectionvalues['section'] = $section->section;
214 $sectionvalues['hiddenbynumsections'] = $section->section > $coursenumsections ? 1 : 0;
215 $sectionvalues['uservisible'] = $section->uservisible;
216 if (!empty($section->availableinfo)) {
217 $sectionvalues['availabilityinfo'] = \core_availability\info::format_info($section->availableinfo, $course);
220 $sectioncontents = array();
222 // For each module of the section.
223 if (empty($filters['excludemodules']) and !empty($modinfosections[$section->section])) {
224 foreach ($modinfosections[$section->section] as $cmid) {
225 $cm = $modinfo->cms[$cmid];
226 $cminfo = cm_info::create($cm);
227 $activitydates = \core\activity_dates::get_dates_for_module($cminfo, $USER->id);
229 // Stop here if the module is not visible to the user on the course main page:
230 // The user can't access the module and the user can't view the module on the course page.
231 if (!$cm->uservisible && !$cm->is_visible_on_course_page()) {
232 continue;
235 // This becomes true when we are filtering and we found the value to filter with.
236 $modfound = false;
238 // Filter by cmid.
239 if (!empty($filters['cmid'])) {
240 if ($cmid != $filters['cmid']) {
241 continue;
242 } else {
243 $modfound = true;
247 // Filter by module name and id.
248 if (!empty($filters['modname'])) {
249 if ($cm->modname != $filters['modname']) {
250 continue;
251 } else if (!empty($filters['modid'])) {
252 if ($cm->instance != $filters['modid']) {
253 continue;
254 } else {
255 // Note that if we are only filtering by modname we don't break the loop.
256 $modfound = true;
261 $module = array();
263 $modcontext = context_module::instance($cm->id);
265 //common info (for people being able to see the module or availability dates)
266 $module['id'] = $cm->id;
267 $module['name'] = external_format_string($cm->name, $modcontext->id);
268 $module['instance'] = $cm->instance;
269 $module['contextid'] = $modcontext->id;
270 $module['modname'] = (string) $cm->modname;
271 $module['modplural'] = (string) $cm->modplural;
272 $module['modicon'] = $cm->get_icon_url()->out(false);
273 $module['indent'] = $cm->indent;
274 $module['onclick'] = $cm->onclick;
275 $module['afterlink'] = $cm->afterlink;
276 $module['customdata'] = json_encode($cm->customdata);
277 $module['completion'] = $cm->completion;
278 $module['downloadcontent'] = $cm->downloadcontent;
279 $module['noviewlink'] = plugin_supports('mod', $cm->modname, FEATURE_NO_VIEW_LINK, false);
280 $module['dates'] = $activitydates;
282 // Check module completion.
283 $completion = $completioninfo->is_enabled($cm);
284 if ($completion != COMPLETION_DISABLED) {
285 $exporter = new \core_completion\external\completion_info_exporter($course, $cm, $USER->id);
286 $renderer = $PAGE->get_renderer('core');
287 $modulecompletiondata = (array)$exporter->export($renderer);
288 $module['completiondata'] = $modulecompletiondata;
291 if (!empty($cm->showdescription) or $module['noviewlink']) {
292 // We want to use the external format. However from reading get_formatted_content(), $cm->content format is always FORMAT_HTML.
293 $options = array('noclean' => true);
294 list($module['description'], $descriptionformat) = external_format_text($cm->content,
295 FORMAT_HTML, $modcontext->id, $cm->modname, 'intro', $cm->id, $options);
298 //url of the module
299 $url = $cm->url;
300 if ($url) { //labels don't have url
301 $module['url'] = $url->out(false);
304 $canviewhidden = has_capability('moodle/course:viewhiddenactivities',
305 context_module::instance($cm->id));
306 //user that can view hidden module should know about the visibility
307 $module['visible'] = $cm->visible;
308 $module['visibleoncoursepage'] = $cm->visibleoncoursepage;
309 $module['uservisible'] = $cm->uservisible;
310 if (!empty($cm->availableinfo)) {
311 $module['availabilityinfo'] = \core_availability\info::format_info($cm->availableinfo, $course);
314 // Availability date (also send to user who can see hidden module).
315 if ($CFG->enableavailability && ($canviewhidden || $canupdatecourse)) {
316 $module['availability'] = $cm->availability;
319 // Return contents only if the user can access to the module.
320 if ($cm->uservisible) {
321 $baseurl = 'webservice/pluginfile.php';
323 // Call $modulename_export_contents (each module callback take care about checking the capabilities).
324 require_once($CFG->dirroot . '/mod/' . $cm->modname . '/lib.php');
325 $getcontentfunction = $cm->modname.'_export_contents';
326 if (function_exists($getcontentfunction)) {
327 $contents = $getcontentfunction($cm, $baseurl);
328 $module['contentsinfo'] = array(
329 'filescount' => count($contents),
330 'filessize' => 0,
331 'lastmodified' => 0,
332 'mimetypes' => array(),
334 foreach ($contents as $content) {
335 // Check repository file (only main file).
336 if (!isset($module['contentsinfo']['repositorytype'])) {
337 $module['contentsinfo']['repositorytype'] =
338 isset($content['repositorytype']) ? $content['repositorytype'] : '';
340 if (isset($content['filesize'])) {
341 $module['contentsinfo']['filessize'] += $content['filesize'];
343 if (isset($content['timemodified']) &&
344 ($content['timemodified'] > $module['contentsinfo']['lastmodified'])) {
346 $module['contentsinfo']['lastmodified'] = $content['timemodified'];
348 if (isset($content['mimetype'])) {
349 $module['contentsinfo']['mimetypes'][$content['mimetype']] = $content['mimetype'];
353 if (empty($filters['excludecontents']) and !empty($contents)) {
354 $module['contents'] = $contents;
355 } else {
356 $module['contents'] = array();
361 // Assign result to $sectioncontents, there is an exception,
362 // stealth activities in non-visible sections for students go to a special section.
363 if (!empty($filters['includestealthmodules']) && !$section->uservisible && $cm->is_stealth()) {
364 $stealthmodules[] = $module;
365 } else {
366 $sectioncontents[] = $module;
369 // If we just did a filtering, break the loop.
370 if ($modfound) {
371 break;
376 $sectionvalues['modules'] = $sectioncontents;
378 // assign result to $coursecontents
379 $coursecontents[$key] = $sectionvalues;
381 // Break the loop if we are filtering.
382 if ($sectionfound) {
383 break;
387 // Now that we have iterated over all the sections and activities, check the visibility.
388 // We didn't this before to be able to retrieve stealth activities.
389 foreach ($coursecontents as $sectionnumber => $sectioncontents) {
390 $section = $sections[$sectionnumber];
391 // Show the section if the user is permitted to access it OR
392 // if it's not available but there is some available info text which explains the reason & should display OR
393 // the course is configured to show hidden sections name.
394 $showsection = $section->uservisible ||
395 ($section->visible && !$section->available && !empty($section->availableinfo)) ||
396 (!$section->visible && empty($courseformat->get_course()->hiddensections));
398 if (!$showsection) {
399 unset($coursecontents[$sectionnumber]);
400 continue;
403 // Remove section and modules information if the section is not visible for the user.
404 if (!$section->uservisible) {
405 $coursecontents[$sectionnumber]['modules'] = array();
406 // Remove summary information if the section is completely hidden only,
407 // even if the section is not user visible, the summary is always displayed among the availability information.
408 if (!$section->visible) {
409 $coursecontents[$sectionnumber]['summary'] = '';
414 // Include stealth modules in special section (without any info).
415 if (!empty($stealthmodules)) {
416 $coursecontents[] = array(
417 'id' => -1,
418 'name' => '',
419 'summary' => '',
420 'summaryformat' => FORMAT_MOODLE,
421 'modules' => $stealthmodules
426 return $coursecontents;
430 * Returns description of method result value
432 * @return external_description
433 * @since Moodle 2.2
435 public static function get_course_contents_returns() {
436 $completiondefinition = \core_completion\external\completion_info_exporter::get_read_structure(VALUE_DEFAULT, []);
438 return new external_multiple_structure(
439 new external_single_structure(
440 array(
441 'id' => new external_value(PARAM_INT, 'Section ID'),
442 'name' => new external_value(PARAM_RAW, 'Section name'),
443 'visible' => new external_value(PARAM_INT, 'is the section visible', VALUE_OPTIONAL),
444 'summary' => new external_value(PARAM_RAW, 'Section description'),
445 'summaryformat' => new external_format_value('summary'),
446 'section' => new external_value(PARAM_INT, 'Section number inside the course', VALUE_OPTIONAL),
447 'hiddenbynumsections' => new external_value(PARAM_INT, 'Whether is a section hidden in the course format',
448 VALUE_OPTIONAL),
449 'uservisible' => new external_value(PARAM_BOOL, 'Is the section visible for the user?', VALUE_OPTIONAL),
450 'availabilityinfo' => new external_value(PARAM_RAW, 'Availability information.', VALUE_OPTIONAL),
451 'modules' => new external_multiple_structure(
452 new external_single_structure(
453 array(
454 'id' => new external_value(PARAM_INT, 'activity id'),
455 'url' => new external_value(PARAM_URL, 'activity url', VALUE_OPTIONAL),
456 'name' => new external_value(PARAM_RAW, 'activity module name'),
457 'instance' => new external_value(PARAM_INT, 'instance id', VALUE_OPTIONAL),
458 'contextid' => new external_value(PARAM_INT, 'Activity context id.', VALUE_OPTIONAL),
459 'description' => new external_value(PARAM_RAW, 'activity description', VALUE_OPTIONAL),
460 'visible' => new external_value(PARAM_INT, 'is the module visible', VALUE_OPTIONAL),
461 'uservisible' => new external_value(PARAM_BOOL, 'Is the module visible for the user?',
462 VALUE_OPTIONAL),
463 'availabilityinfo' => new external_value(PARAM_RAW, 'Availability information.',
464 VALUE_OPTIONAL),
465 'visibleoncoursepage' => new external_value(PARAM_INT, 'is the module visible on course page',
466 VALUE_OPTIONAL),
467 'modicon' => new external_value(PARAM_URL, 'activity icon url'),
468 'modname' => new external_value(PARAM_PLUGIN, 'activity module type'),
469 'modplural' => new external_value(PARAM_TEXT, 'activity module plural name'),
470 'availability' => new external_value(PARAM_RAW, 'module availability settings', VALUE_OPTIONAL),
471 'indent' => new external_value(PARAM_INT, 'number of identation in the site'),
472 'onclick' => new external_value(PARAM_RAW, 'Onclick action.', VALUE_OPTIONAL),
473 'afterlink' => new external_value(PARAM_RAW, 'After link info to be displayed.',
474 VALUE_OPTIONAL),
475 'customdata' => new external_value(PARAM_RAW, 'Custom data (JSON encoded).', VALUE_OPTIONAL),
476 'noviewlink' => new external_value(PARAM_BOOL, 'Whether the module has no view page',
477 VALUE_OPTIONAL),
478 'completion' => new external_value(PARAM_INT, 'Type of completion tracking:
479 0 means none, 1 manual, 2 automatic.', VALUE_OPTIONAL),
480 'completiondata' => $completiondefinition,
481 'downloadcontent' => new external_value(PARAM_INT, 'The download content value', VALUE_OPTIONAL),
482 'dates' => new external_multiple_structure(
483 new external_single_structure(
484 array(
485 'label' => new external_value(PARAM_TEXT, 'date label'),
486 'timestamp' => new external_value(PARAM_INT, 'date timestamp'),
489 VALUE_DEFAULT,
492 'contents' => new external_multiple_structure(
493 new external_single_structure(
494 array(
495 // content info
496 'type'=> new external_value(PARAM_TEXT, 'a file or a folder or external link'),
497 'filename'=> new external_value(PARAM_FILE, 'filename'),
498 'filepath'=> new external_value(PARAM_PATH, 'filepath'),
499 'filesize'=> new external_value(PARAM_INT, 'filesize'),
500 'fileurl' => new external_value(PARAM_URL, 'downloadable file url', VALUE_OPTIONAL),
501 'content' => new external_value(PARAM_RAW, 'Raw content, will be used when type is content', VALUE_OPTIONAL),
502 'timecreated' => new external_value(PARAM_INT, 'Time created'),
503 'timemodified' => new external_value(PARAM_INT, 'Time modified'),
504 'sortorder' => new external_value(PARAM_INT, 'Content sort order'),
505 'mimetype' => new external_value(PARAM_RAW, 'File mime type.', VALUE_OPTIONAL),
506 'isexternalfile' => new external_value(PARAM_BOOL, 'Whether is an external file.',
507 VALUE_OPTIONAL),
508 'repositorytype' => new external_value(PARAM_PLUGIN, 'The repository type for external files.',
509 VALUE_OPTIONAL),
511 // copyright related info
512 'userid' => new external_value(PARAM_INT, 'User who added this content to moodle'),
513 'author' => new external_value(PARAM_TEXT, 'Content owner'),
514 'license' => new external_value(PARAM_TEXT, 'Content license'),
515 'tags' => new external_multiple_structure(
516 \core_tag\external\tag_item_exporter::get_read_structure(), 'Tags',
517 VALUE_OPTIONAL
520 ), VALUE_DEFAULT, array()
522 'contentsinfo' => new external_single_structure(
523 array(
524 'filescount' => new external_value(PARAM_INT, 'Total number of files.'),
525 'filessize' => new external_value(PARAM_INT, 'Total files size.'),
526 'lastmodified' => new external_value(PARAM_INT, 'Last time files were modified.'),
527 'mimetypes' => new external_multiple_structure(
528 new external_value(PARAM_RAW, 'File mime type.'),
529 'Files mime types.'
531 'repositorytype' => new external_value(PARAM_PLUGIN, 'The repository type for
532 the main file.', VALUE_OPTIONAL),
533 ), 'Contents summary information.', VALUE_OPTIONAL
536 ), 'list of module'
544 * Returns description of method parameters
546 * @return external_function_parameters
547 * @since Moodle 2.3
549 public static function get_courses_parameters() {
550 return new external_function_parameters(
551 array('options' => new external_single_structure(
552 array('ids' => new external_multiple_structure(
553 new external_value(PARAM_INT, 'Course id')
554 , 'List of course id. If empty return all courses
555 except front page course.',
556 VALUE_OPTIONAL)
557 ), 'options - operator OR is used', VALUE_DEFAULT, array())
563 * Get courses
565 * @param array $options It contains an array (list of ids)
566 * @return array
567 * @since Moodle 2.2
569 public static function get_courses($options = array()) {
570 global $CFG, $DB;
571 require_once($CFG->dirroot . "/course/lib.php");
573 //validate parameter
574 $params = self::validate_parameters(self::get_courses_parameters(),
575 array('options' => $options));
577 //retrieve courses
578 if (!array_key_exists('ids', $params['options'])
579 or empty($params['options']['ids'])) {
580 $courses = $DB->get_records('course');
581 } else {
582 $courses = $DB->get_records_list('course', 'id', $params['options']['ids']);
585 //create return value
586 $coursesinfo = array();
587 foreach ($courses as $course) {
589 // now security checks
590 $context = context_course::instance($course->id, IGNORE_MISSING);
591 $courseformatoptions = course_get_format($course)->get_format_options();
592 try {
593 self::validate_context($context);
594 } catch (Exception $e) {
595 $exceptionparam = new stdClass();
596 $exceptionparam->message = $e->getMessage();
597 $exceptionparam->courseid = $course->id;
598 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
600 if ($course->id != SITEID) {
601 require_capability('moodle/course:view', $context);
604 $courseinfo = array();
605 $courseinfo['id'] = $course->id;
606 $courseinfo['fullname'] = external_format_string($course->fullname, $context->id);
607 $courseinfo['shortname'] = external_format_string($course->shortname, $context->id);
608 $courseinfo['displayname'] = external_format_string(get_course_display_name_for_list($course), $context->id);
609 $courseinfo['categoryid'] = $course->category;
610 list($courseinfo['summary'], $courseinfo['summaryformat']) =
611 external_format_text($course->summary, $course->summaryformat, $context->id, 'course', 'summary', 0);
612 $courseinfo['format'] = $course->format;
613 $courseinfo['startdate'] = $course->startdate;
614 $courseinfo['enddate'] = $course->enddate;
615 $courseinfo['showactivitydates'] = $course->showactivitydates;
616 $courseinfo['showcompletionconditions'] = $course->showcompletionconditions;
617 if (array_key_exists('numsections', $courseformatoptions)) {
618 // For backward-compartibility
619 $courseinfo['numsections'] = $courseformatoptions['numsections'];
622 $handler = core_course\customfield\course_handler::create();
623 if ($customfields = $handler->export_instance_data($course->id)) {
624 $courseinfo['customfields'] = [];
625 foreach ($customfields as $data) {
626 $courseinfo['customfields'][] = [
627 'type' => $data->get_type(),
628 'value' => $data->get_value(),
629 'valueraw' => $data->get_data_controller()->get_value(),
630 'name' => $data->get_name(),
631 'shortname' => $data->get_shortname()
636 //some field should be returned only if the user has update permission
637 $courseadmin = has_capability('moodle/course:update', $context);
638 if ($courseadmin) {
639 $courseinfo['categorysortorder'] = $course->sortorder;
640 $courseinfo['idnumber'] = $course->idnumber;
641 $courseinfo['showgrades'] = $course->showgrades;
642 $courseinfo['showreports'] = $course->showreports;
643 $courseinfo['newsitems'] = $course->newsitems;
644 $courseinfo['visible'] = $course->visible;
645 $courseinfo['maxbytes'] = $course->maxbytes;
646 if (array_key_exists('hiddensections', $courseformatoptions)) {
647 // For backward-compartibility
648 $courseinfo['hiddensections'] = $courseformatoptions['hiddensections'];
650 // Return numsections for backward-compatibility with clients who expect it.
651 $courseinfo['numsections'] = course_get_format($course)->get_last_section_number();
652 $courseinfo['groupmode'] = $course->groupmode;
653 $courseinfo['groupmodeforce'] = $course->groupmodeforce;
654 $courseinfo['defaultgroupingid'] = $course->defaultgroupingid;
655 $courseinfo['lang'] = clean_param($course->lang, PARAM_LANG);
656 $courseinfo['timecreated'] = $course->timecreated;
657 $courseinfo['timemodified'] = $course->timemodified;
658 $courseinfo['forcetheme'] = clean_param($course->theme, PARAM_THEME);
659 $courseinfo['enablecompletion'] = $course->enablecompletion;
660 $courseinfo['completionnotify'] = $course->completionnotify;
661 $courseinfo['courseformatoptions'] = array();
662 foreach ($courseformatoptions as $key => $value) {
663 $courseinfo['courseformatoptions'][] = array(
664 'name' => $key,
665 'value' => $value
670 if ($courseadmin or $course->visible
671 or has_capability('moodle/course:viewhiddencourses', $context)) {
672 $coursesinfo[] = $courseinfo;
676 return $coursesinfo;
680 * Returns description of method result value
682 * @return external_description
683 * @since Moodle 2.2
685 public static function get_courses_returns() {
686 return new external_multiple_structure(
687 new external_single_structure(
688 array(
689 'id' => new external_value(PARAM_INT, 'course id'),
690 'shortname' => new external_value(PARAM_RAW, 'course short name'),
691 'categoryid' => new external_value(PARAM_INT, 'category id'),
692 'categorysortorder' => new external_value(PARAM_INT,
693 'sort order into the category', VALUE_OPTIONAL),
694 'fullname' => new external_value(PARAM_RAW, 'full name'),
695 'displayname' => new external_value(PARAM_RAW, 'course display name'),
696 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
697 'summary' => new external_value(PARAM_RAW, 'summary'),
698 'summaryformat' => new external_format_value('summary'),
699 'format' => new external_value(PARAM_PLUGIN,
700 'course format: weeks, topics, social, site,..'),
701 'showgrades' => new external_value(PARAM_INT,
702 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
703 'newsitems' => new external_value(PARAM_INT,
704 'number of recent items appearing on the course page', VALUE_OPTIONAL),
705 'startdate' => new external_value(PARAM_INT,
706 'timestamp when the course start'),
707 'enddate' => new external_value(PARAM_INT,
708 'timestamp when the course end'),
709 'numsections' => new external_value(PARAM_INT,
710 '(deprecated, use courseformatoptions) number of weeks/topics',
711 VALUE_OPTIONAL),
712 'maxbytes' => new external_value(PARAM_INT,
713 'largest size of file that can be uploaded into the course',
714 VALUE_OPTIONAL),
715 'showreports' => new external_value(PARAM_INT,
716 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
717 'visible' => new external_value(PARAM_INT,
718 '1: available to student, 0:not available', VALUE_OPTIONAL),
719 'hiddensections' => new external_value(PARAM_INT,
720 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
721 VALUE_OPTIONAL),
722 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
723 VALUE_OPTIONAL),
724 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
725 VALUE_OPTIONAL),
726 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
727 VALUE_OPTIONAL),
728 'timecreated' => new external_value(PARAM_INT,
729 'timestamp when the course have been created', VALUE_OPTIONAL),
730 'timemodified' => new external_value(PARAM_INT,
731 'timestamp when the course have been modified', VALUE_OPTIONAL),
732 'enablecompletion' => new external_value(PARAM_INT,
733 'Enabled, control via completion and activity settings. Disbaled,
734 not shown in activity settings.',
735 VALUE_OPTIONAL),
736 'completionnotify' => new external_value(PARAM_INT,
737 '1: yes 0: no', VALUE_OPTIONAL),
738 'lang' => new external_value(PARAM_SAFEDIR,
739 'forced course language', VALUE_OPTIONAL),
740 'forcetheme' => new external_value(PARAM_PLUGIN,
741 'name of the force theme', VALUE_OPTIONAL),
742 'courseformatoptions' => new external_multiple_structure(
743 new external_single_structure(
744 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
745 'value' => new external_value(PARAM_RAW, 'course format option value')
746 )), 'additional options for particular course format', VALUE_OPTIONAL
748 'showactivitydates' => new external_value(PARAM_BOOL, 'Whether the activity dates are shown or not'),
749 'showcompletionconditions' => new external_value(PARAM_BOOL,
750 'Whether the activity completion conditions are shown or not'),
751 'customfields' => new external_multiple_structure(
752 new external_single_structure(
753 ['name' => new external_value(PARAM_RAW, 'The name of the custom field'),
754 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'The shortname of the custom field'),
755 'type' => new external_value(PARAM_COMPONENT,
756 'The type of the custom field - text, checkbox...'),
757 'valueraw' => new external_value(PARAM_RAW, 'The raw value of the custom field'),
758 'value' => new external_value(PARAM_RAW, 'The value of the custom field')]
759 ), 'Custom fields and associated values', VALUE_OPTIONAL),
760 ), 'course'
766 * Returns description of method parameters
768 * @return external_function_parameters
769 * @since Moodle 2.2
771 public static function create_courses_parameters() {
772 $courseconfig = get_config('moodlecourse'); //needed for many default values
773 return new external_function_parameters(
774 array(
775 'courses' => new external_multiple_structure(
776 new external_single_structure(
777 array(
778 'fullname' => new external_value(PARAM_TEXT, 'full name'),
779 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
780 'categoryid' => new external_value(PARAM_INT, 'category id'),
781 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
782 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
783 'summaryformat' => new external_format_value('summary', VALUE_DEFAULT),
784 'format' => new external_value(PARAM_PLUGIN,
785 'course format: weeks, topics, social, site,..',
786 VALUE_DEFAULT, $courseconfig->format),
787 'showgrades' => new external_value(PARAM_INT,
788 '1 if grades are shown, otherwise 0', VALUE_DEFAULT,
789 $courseconfig->showgrades),
790 'newsitems' => new external_value(PARAM_INT,
791 'number of recent items appearing on the course page',
792 VALUE_DEFAULT, $courseconfig->newsitems),
793 'startdate' => new external_value(PARAM_INT,
794 'timestamp when the course start', VALUE_OPTIONAL),
795 'enddate' => new external_value(PARAM_INT,
796 'timestamp when the course end', VALUE_OPTIONAL),
797 'numsections' => new external_value(PARAM_INT,
798 '(deprecated, use courseformatoptions) number of weeks/topics',
799 VALUE_OPTIONAL),
800 'maxbytes' => new external_value(PARAM_INT,
801 'largest size of file that can be uploaded into the course',
802 VALUE_DEFAULT, $courseconfig->maxbytes),
803 'showreports' => new external_value(PARAM_INT,
804 'are activity report shown (yes = 1, no =0)', VALUE_DEFAULT,
805 $courseconfig->showreports),
806 'visible' => new external_value(PARAM_INT,
807 '1: available to student, 0:not available', VALUE_OPTIONAL),
808 'hiddensections' => new external_value(PARAM_INT,
809 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
810 VALUE_OPTIONAL),
811 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
812 VALUE_DEFAULT, $courseconfig->groupmode),
813 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
814 VALUE_DEFAULT, $courseconfig->groupmodeforce),
815 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
816 VALUE_DEFAULT, 0),
817 'enablecompletion' => new external_value(PARAM_INT,
818 'Enabled, control via completion and activity settings. Disabled,
819 not shown in activity settings.',
820 VALUE_OPTIONAL),
821 'completionnotify' => new external_value(PARAM_INT,
822 '1: yes 0: no', VALUE_OPTIONAL),
823 'lang' => new external_value(PARAM_SAFEDIR,
824 'forced course language', VALUE_OPTIONAL),
825 'forcetheme' => new external_value(PARAM_PLUGIN,
826 'name of the force theme', VALUE_OPTIONAL),
827 'courseformatoptions' => new external_multiple_structure(
828 new external_single_structure(
829 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
830 'value' => new external_value(PARAM_RAW, 'course format option value')
832 'additional options for particular course format', VALUE_OPTIONAL),
833 'customfields' => new external_multiple_structure(
834 new external_single_structure(
835 array(
836 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'The shortname of the custom field'),
837 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
838 )), 'custom fields for the course', VALUE_OPTIONAL
840 )), 'courses to create'
847 * Create courses
849 * @param array $courses
850 * @return array courses (id and shortname only)
851 * @since Moodle 2.2
853 public static function create_courses($courses) {
854 global $CFG, $DB;
855 require_once($CFG->dirroot . "/course/lib.php");
856 require_once($CFG->libdir . '/completionlib.php');
858 $params = self::validate_parameters(self::create_courses_parameters(),
859 array('courses' => $courses));
861 $availablethemes = core_component::get_plugin_list('theme');
862 $availablelangs = get_string_manager()->get_list_of_translations();
864 $transaction = $DB->start_delegated_transaction();
866 foreach ($params['courses'] as $course) {
868 // Ensure the current user is allowed to run this function
869 $context = context_coursecat::instance($course['categoryid'], IGNORE_MISSING);
870 try {
871 self::validate_context($context);
872 } catch (Exception $e) {
873 $exceptionparam = new stdClass();
874 $exceptionparam->message = $e->getMessage();
875 $exceptionparam->catid = $course['categoryid'];
876 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
878 require_capability('moodle/course:create', $context);
880 // Fullname and short name are required to be non-empty.
881 if (trim($course['fullname']) === '') {
882 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'fullname');
883 } else if (trim($course['shortname']) === '') {
884 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'shortname');
887 // Make sure lang is valid
888 if (array_key_exists('lang', $course)) {
889 if (empty($availablelangs[$course['lang']])) {
890 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
892 if (!has_capability('moodle/course:setforcedlanguage', $context)) {
893 unset($course['lang']);
897 // Make sure theme is valid
898 if (array_key_exists('forcetheme', $course)) {
899 if (!empty($CFG->allowcoursethemes)) {
900 if (empty($availablethemes[$course['forcetheme']])) {
901 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
902 } else {
903 $course['theme'] = $course['forcetheme'];
908 //force visibility if ws user doesn't have the permission to set it
909 $category = $DB->get_record('course_categories', array('id' => $course['categoryid']));
910 if (!has_capability('moodle/course:visibility', $context)) {
911 $course['visible'] = $category->visible;
914 //set default value for completion
915 $courseconfig = get_config('moodlecourse');
916 if (completion_info::is_enabled_for_site()) {
917 if (!array_key_exists('enablecompletion', $course)) {
918 $course['enablecompletion'] = $courseconfig->enablecompletion;
920 } else {
921 $course['enablecompletion'] = 0;
924 $course['category'] = $course['categoryid'];
926 // Summary format.
927 $course['summaryformat'] = external_validate_format($course['summaryformat']);
929 if (!empty($course['courseformatoptions'])) {
930 foreach ($course['courseformatoptions'] as $option) {
931 $course[$option['name']] = $option['value'];
935 // Custom fields.
936 if (!empty($course['customfields'])) {
937 foreach ($course['customfields'] as $field) {
938 $course['customfield_'.$field['shortname']] = $field['value'];
942 //Note: create_course() core function check shortname, idnumber, category
943 $course['id'] = create_course((object) $course)->id;
945 $resultcourses[] = array('id' => $course['id'], 'shortname' => $course['shortname']);
948 $transaction->allow_commit();
950 return $resultcourses;
954 * Returns description of method result value
956 * @return external_description
957 * @since Moodle 2.2
959 public static function create_courses_returns() {
960 return new external_multiple_structure(
961 new external_single_structure(
962 array(
963 'id' => new external_value(PARAM_INT, 'course id'),
964 'shortname' => new external_value(PARAM_RAW, 'short name'),
971 * Update courses
973 * @return external_function_parameters
974 * @since Moodle 2.5
976 public static function update_courses_parameters() {
977 return new external_function_parameters(
978 array(
979 'courses' => new external_multiple_structure(
980 new external_single_structure(
981 array(
982 'id' => new external_value(PARAM_INT, 'ID of the course'),
983 'fullname' => new external_value(PARAM_TEXT, 'full name', VALUE_OPTIONAL),
984 'shortname' => new external_value(PARAM_TEXT, 'course short name', VALUE_OPTIONAL),
985 'categoryid' => new external_value(PARAM_INT, 'category id', VALUE_OPTIONAL),
986 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
987 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
988 'summaryformat' => new external_format_value('summary', VALUE_OPTIONAL),
989 'format' => new external_value(PARAM_PLUGIN,
990 'course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
991 'showgrades' => new external_value(PARAM_INT,
992 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
993 'newsitems' => new external_value(PARAM_INT,
994 'number of recent items appearing on the course page', VALUE_OPTIONAL),
995 'startdate' => new external_value(PARAM_INT,
996 'timestamp when the course start', VALUE_OPTIONAL),
997 'enddate' => new external_value(PARAM_INT,
998 'timestamp when the course end', VALUE_OPTIONAL),
999 'numsections' => new external_value(PARAM_INT,
1000 '(deprecated, use courseformatoptions) number of weeks/topics', VALUE_OPTIONAL),
1001 'maxbytes' => new external_value(PARAM_INT,
1002 'largest size of file that can be uploaded into the course', VALUE_OPTIONAL),
1003 'showreports' => new external_value(PARAM_INT,
1004 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
1005 'visible' => new external_value(PARAM_INT,
1006 '1: available to student, 0:not available', VALUE_OPTIONAL),
1007 'hiddensections' => new external_value(PARAM_INT,
1008 '(deprecated, use courseformatoptions) How the hidden sections in the course are
1009 displayed to students', VALUE_OPTIONAL),
1010 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
1011 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
1012 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
1013 'enablecompletion' => new external_value(PARAM_INT,
1014 'Enabled, control via completion and activity settings. Disabled,
1015 not shown in activity settings.', VALUE_OPTIONAL),
1016 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
1017 'lang' => new external_value(PARAM_SAFEDIR, 'forced course language', VALUE_OPTIONAL),
1018 'forcetheme' => new external_value(PARAM_PLUGIN, 'name of the force theme', VALUE_OPTIONAL),
1019 'courseformatoptions' => new external_multiple_structure(
1020 new external_single_structure(
1021 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
1022 'value' => new external_value(PARAM_RAW, 'course format option value')
1023 )), 'additional options for particular course format', VALUE_OPTIONAL),
1024 'customfields' => new external_multiple_structure(
1025 new external_single_structure(
1027 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'The shortname of the custom field'),
1028 'value' => new external_value(PARAM_RAW, 'The value of the custom field')
1030 ), 'Custom fields', VALUE_OPTIONAL),
1032 ), 'courses to update'
1039 * Update courses
1041 * @param array $courses
1042 * @since Moodle 2.5
1044 public static function update_courses($courses) {
1045 global $CFG, $DB;
1046 require_once($CFG->dirroot . "/course/lib.php");
1047 $warnings = array();
1049 $params = self::validate_parameters(self::update_courses_parameters(),
1050 array('courses' => $courses));
1052 $availablethemes = core_component::get_plugin_list('theme');
1053 $availablelangs = get_string_manager()->get_list_of_translations();
1055 foreach ($params['courses'] as $course) {
1056 // Catch any exception while updating course and return as warning to user.
1057 try {
1058 // Ensure the current user is allowed to run this function.
1059 $context = context_course::instance($course['id'], MUST_EXIST);
1060 self::validate_context($context);
1062 $oldcourse = course_get_format($course['id'])->get_course();
1064 require_capability('moodle/course:update', $context);
1066 // Check if user can change category.
1067 if (array_key_exists('categoryid', $course) && ($oldcourse->category != $course['categoryid'])) {
1068 require_capability('moodle/course:changecategory', $context);
1069 $course['category'] = $course['categoryid'];
1072 // Check if the user can change fullname, and the new value is non-empty.
1073 if (array_key_exists('fullname', $course) && ($oldcourse->fullname != $course['fullname'])) {
1074 require_capability('moodle/course:changefullname', $context);
1075 if (trim($course['fullname']) === '') {
1076 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'fullname');
1080 // Check if the user can change shortname, and the new value is non-empty.
1081 if (array_key_exists('shortname', $course) && ($oldcourse->shortname != $course['shortname'])) {
1082 require_capability('moodle/course:changeshortname', $context);
1083 if (trim($course['shortname']) === '') {
1084 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'shortname');
1088 // Check if the user can change the idnumber.
1089 if (array_key_exists('idnumber', $course) && ($oldcourse->idnumber != $course['idnumber'])) {
1090 require_capability('moodle/course:changeidnumber', $context);
1093 // Check if user can change summary.
1094 if (array_key_exists('summary', $course) && ($oldcourse->summary != $course['summary'])) {
1095 require_capability('moodle/course:changesummary', $context);
1098 // Summary format.
1099 if (array_key_exists('summaryformat', $course) && ($oldcourse->summaryformat != $course['summaryformat'])) {
1100 require_capability('moodle/course:changesummary', $context);
1101 $course['summaryformat'] = external_validate_format($course['summaryformat']);
1104 // Check if user can change visibility.
1105 if (array_key_exists('visible', $course) && ($oldcourse->visible != $course['visible'])) {
1106 require_capability('moodle/course:visibility', $context);
1109 // Make sure lang is valid.
1110 if (array_key_exists('lang', $course) && ($oldcourse->lang != $course['lang'])) {
1111 require_capability('moodle/course:setforcedlanguage', $context);
1112 if (empty($availablelangs[$course['lang']])) {
1113 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
1117 // Make sure theme is valid.
1118 if (array_key_exists('forcetheme', $course)) {
1119 if (!empty($CFG->allowcoursethemes)) {
1120 if (empty($availablethemes[$course['forcetheme']])) {
1121 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
1122 } else {
1123 $course['theme'] = $course['forcetheme'];
1128 // Make sure completion is enabled before setting it.
1129 if (array_key_exists('enabledcompletion', $course) && !completion_info::is_enabled_for_site()) {
1130 $course['enabledcompletion'] = 0;
1133 // Make sure maxbytes are less then CFG->maxbytes.
1134 if (array_key_exists('maxbytes', $course)) {
1135 // We allow updates back to 0 max bytes, a special value denoting the course uses the site limit.
1136 // Otherwise, either use the size specified, or cap at the max size for the course.
1137 if ($course['maxbytes'] != 0) {
1138 $course['maxbytes'] = get_max_upload_file_size($CFG->maxbytes, $course['maxbytes']);
1142 if (!empty($course['courseformatoptions'])) {
1143 foreach ($course['courseformatoptions'] as $option) {
1144 if (isset($option['name']) && isset($option['value'])) {
1145 $course[$option['name']] = $option['value'];
1150 // Prepare list of custom fields.
1151 if (isset($course['customfields'])) {
1152 foreach ($course['customfields'] as $field) {
1153 $course['customfield_' . $field['shortname']] = $field['value'];
1157 // Update course if user has all required capabilities.
1158 update_course((object) $course);
1159 } catch (Exception $e) {
1160 $warning = array();
1161 $warning['item'] = 'course';
1162 $warning['itemid'] = $course['id'];
1163 if ($e instanceof moodle_exception) {
1164 $warning['warningcode'] = $e->errorcode;
1165 } else {
1166 $warning['warningcode'] = $e->getCode();
1168 $warning['message'] = $e->getMessage();
1169 $warnings[] = $warning;
1173 $result = array();
1174 $result['warnings'] = $warnings;
1175 return $result;
1179 * Returns description of method result value
1181 * @return external_description
1182 * @since Moodle 2.5
1184 public static function update_courses_returns() {
1185 return new external_single_structure(
1186 array(
1187 'warnings' => new external_warnings()
1193 * Returns description of method parameters
1195 * @return external_function_parameters
1196 * @since Moodle 2.2
1198 public static function delete_courses_parameters() {
1199 return new external_function_parameters(
1200 array(
1201 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'course ID')),
1207 * Delete courses
1209 * @param array $courseids A list of course ids
1210 * @since Moodle 2.2
1212 public static function delete_courses($courseids) {
1213 global $CFG, $DB;
1214 require_once($CFG->dirroot."/course/lib.php");
1216 // Parameter validation.
1217 $params = self::validate_parameters(self::delete_courses_parameters(), array('courseids'=>$courseids));
1219 $warnings = array();
1221 foreach ($params['courseids'] as $courseid) {
1222 $course = $DB->get_record('course', array('id' => $courseid));
1224 if ($course === false) {
1225 $warnings[] = array(
1226 'item' => 'course',
1227 'itemid' => $courseid,
1228 'warningcode' => 'unknowncourseidnumber',
1229 'message' => 'Unknown course ID ' . $courseid
1231 continue;
1234 // Check if the context is valid.
1235 $coursecontext = context_course::instance($course->id);
1236 self::validate_context($coursecontext);
1238 // Check if the current user has permission.
1239 if (!can_delete_course($courseid)) {
1240 $warnings[] = array(
1241 'item' => 'course',
1242 'itemid' => $courseid,
1243 'warningcode' => 'cannotdeletecourse',
1244 'message' => 'You do not have the permission to delete this course' . $courseid
1246 continue;
1249 if (delete_course($course, false) === false) {
1250 $warnings[] = array(
1251 'item' => 'course',
1252 'itemid' => $courseid,
1253 'warningcode' => 'cannotdeletecategorycourse',
1254 'message' => 'Course ' . $courseid . ' failed to be deleted'
1256 continue;
1260 fix_course_sortorder();
1262 return array('warnings' => $warnings);
1266 * Returns description of method result value
1268 * @return external_description
1269 * @since Moodle 2.2
1271 public static function delete_courses_returns() {
1272 return new external_single_structure(
1273 array(
1274 'warnings' => new external_warnings()
1280 * Returns description of method parameters
1282 * @return external_function_parameters
1283 * @since Moodle 2.3
1285 public static function duplicate_course_parameters() {
1286 return new external_function_parameters(
1287 array(
1288 'courseid' => new external_value(PARAM_INT, 'course to duplicate id'),
1289 'fullname' => new external_value(PARAM_TEXT, 'duplicated course full name'),
1290 'shortname' => new external_value(PARAM_TEXT, 'duplicated course short name'),
1291 'categoryid' => new external_value(PARAM_INT, 'duplicated course category parent'),
1292 'visible' => new external_value(PARAM_INT, 'duplicated course visible, default to yes', VALUE_DEFAULT, 1),
1293 'options' => new external_multiple_structure(
1294 new external_single_structure(
1295 array(
1296 'name' => new external_value(PARAM_ALPHAEXT, 'The backup option name:
1297 "activities" (int) Include course activites (default to 1 that is equal to yes),
1298 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1299 "filters" (int) Include course filters (default to 1 that is equal to yes),
1300 "users" (int) Include users (default to 0 that is equal to no),
1301 "enrolments" (int) Include enrolment methods (default to 1 - restore only with users),
1302 "role_assignments" (int) Include role assignments (default to 0 that is equal to no),
1303 "comments" (int) Include user comments (default to 0 that is equal to no),
1304 "userscompletion" (int) Include user course completion information (default to 0 that is equal to no),
1305 "logs" (int) Include course logs (default to 0 that is equal to no),
1306 "grade_histories" (int) Include histories (default to 0 that is equal to no)'
1308 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1311 ), VALUE_DEFAULT, array()
1318 * Duplicate a course
1320 * @param int $courseid
1321 * @param string $fullname Duplicated course fullname
1322 * @param string $shortname Duplicated course shortname
1323 * @param int $categoryid Duplicated course parent category id
1324 * @param int $visible Duplicated course availability
1325 * @param array $options List of backup options
1326 * @return array New course info
1327 * @since Moodle 2.3
1329 public static function duplicate_course($courseid, $fullname, $shortname, $categoryid, $visible = 1, $options = array()) {
1330 global $CFG, $USER, $DB;
1331 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1332 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1334 // Parameter validation.
1335 $params = self::validate_parameters(
1336 self::duplicate_course_parameters(),
1337 array(
1338 'courseid' => $courseid,
1339 'fullname' => $fullname,
1340 'shortname' => $shortname,
1341 'categoryid' => $categoryid,
1342 'visible' => $visible,
1343 'options' => $options
1347 // Context validation.
1349 if (! ($course = $DB->get_record('course', array('id'=>$params['courseid'])))) {
1350 throw new moodle_exception('invalidcourseid', 'error');
1353 // Category where duplicated course is going to be created.
1354 $categorycontext = context_coursecat::instance($params['categoryid']);
1355 self::validate_context($categorycontext);
1357 // Course to be duplicated.
1358 $coursecontext = context_course::instance($course->id);
1359 self::validate_context($coursecontext);
1361 $backupdefaults = array(
1362 'activities' => 1,
1363 'blocks' => 1,
1364 'filters' => 1,
1365 'users' => 0,
1366 'enrolments' => backup::ENROL_WITHUSERS,
1367 'role_assignments' => 0,
1368 'comments' => 0,
1369 'userscompletion' => 0,
1370 'logs' => 0,
1371 'grade_histories' => 0
1374 $backupsettings = array();
1375 // Check for backup and restore options.
1376 if (!empty($params['options'])) {
1377 foreach ($params['options'] as $option) {
1379 // Strict check for a correct value (allways 1 or 0, true or false).
1380 $value = clean_param($option['value'], PARAM_INT);
1382 if ($value !== 0 and $value !== 1) {
1383 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1386 if (!isset($backupdefaults[$option['name']])) {
1387 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1390 $backupsettings[$option['name']] = $value;
1394 // Capability checking.
1396 // The backup controller check for this currently, this may be redundant.
1397 require_capability('moodle/course:create', $categorycontext);
1398 require_capability('moodle/restore:restorecourse', $categorycontext);
1399 require_capability('moodle/backup:backupcourse', $coursecontext);
1401 if (!empty($backupsettings['users'])) {
1402 require_capability('moodle/backup:userinfo', $coursecontext);
1403 require_capability('moodle/restore:userinfo', $categorycontext);
1406 // Check if the shortname is used.
1407 if ($foundcourses = $DB->get_records('course', array('shortname'=>$shortname))) {
1408 foreach ($foundcourses as $foundcourse) {
1409 $foundcoursenames[] = $foundcourse->fullname;
1412 $foundcoursenamestring = implode(',', $foundcoursenames);
1413 throw new moodle_exception('shortnametaken', '', '', $foundcoursenamestring);
1416 // Backup the course.
1418 $bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE,
1419 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id);
1421 foreach ($backupsettings as $name => $value) {
1422 if ($setting = $bc->get_plan()->get_setting($name)) {
1423 $bc->get_plan()->get_setting($name)->set_value($value);
1427 $backupid = $bc->get_backupid();
1428 $backupbasepath = $bc->get_plan()->get_basepath();
1430 $bc->execute_plan();
1431 $results = $bc->get_results();
1432 $file = $results['backup_destination'];
1434 $bc->destroy();
1436 // Restore the backup immediately.
1438 // Check if we need to unzip the file because the backup temp dir does not contains backup files.
1439 if (!file_exists($backupbasepath . "/moodle_backup.xml")) {
1440 $file->extract_to_pathname(get_file_packer('application/vnd.moodle.backup'), $backupbasepath);
1443 // Create new course.
1444 $newcourseid = restore_dbops::create_new_course($params['fullname'], $params['shortname'], $params['categoryid']);
1446 $rc = new restore_controller($backupid, $newcourseid,
1447 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id, backup::TARGET_NEW_COURSE);
1449 foreach ($backupsettings as $name => $value) {
1450 $setting = $rc->get_plan()->get_setting($name);
1451 if ($setting->get_status() == backup_setting::NOT_LOCKED) {
1452 $setting->set_value($value);
1456 if (!$rc->execute_precheck()) {
1457 $precheckresults = $rc->get_precheck_results();
1458 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1459 if (empty($CFG->keeptempdirectoriesonbackup)) {
1460 fulldelete($backupbasepath);
1463 $errorinfo = '';
1465 foreach ($precheckresults['errors'] as $error) {
1466 $errorinfo .= $error;
1469 if (array_key_exists('warnings', $precheckresults)) {
1470 foreach ($precheckresults['warnings'] as $warning) {
1471 $errorinfo .= $warning;
1475 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1479 $rc->execute_plan();
1480 $rc->destroy();
1482 $course = $DB->get_record('course', array('id' => $newcourseid), '*', MUST_EXIST);
1483 $course->fullname = $params['fullname'];
1484 $course->shortname = $params['shortname'];
1485 $course->visible = $params['visible'];
1487 // Set shortname and fullname back.
1488 $DB->update_record('course', $course);
1490 if (empty($CFG->keeptempdirectoriesonbackup)) {
1491 fulldelete($backupbasepath);
1494 // Delete the course backup file created by this WebService. Originally located in the course backups area.
1495 $file->delete();
1497 return array('id' => $course->id, 'shortname' => $course->shortname);
1501 * Returns description of method result value
1503 * @return external_description
1504 * @since Moodle 2.3
1506 public static function duplicate_course_returns() {
1507 return new external_single_structure(
1508 array(
1509 'id' => new external_value(PARAM_INT, 'course id'),
1510 'shortname' => new external_value(PARAM_RAW, 'short name'),
1516 * Returns description of method parameters for import_course
1518 * @return external_function_parameters
1519 * @since Moodle 2.4
1521 public static function import_course_parameters() {
1522 return new external_function_parameters(
1523 array(
1524 'importfrom' => new external_value(PARAM_INT, 'the id of the course we are importing from'),
1525 'importto' => new external_value(PARAM_INT, 'the id of the course we are importing to'),
1526 'deletecontent' => new external_value(PARAM_INT, 'whether to delete the course content where we are importing to (default to 0 = No)', VALUE_DEFAULT, 0),
1527 'options' => new external_multiple_structure(
1528 new external_single_structure(
1529 array(
1530 'name' => new external_value(PARAM_ALPHA, 'The backup option name:
1531 "activities" (int) Include course activites (default to 1 that is equal to yes),
1532 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1533 "filters" (int) Include course filters (default to 1 that is equal to yes)'
1535 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1538 ), VALUE_DEFAULT, array()
1545 * Imports a course
1547 * @param int $importfrom The id of the course we are importing from
1548 * @param int $importto The id of the course we are importing to
1549 * @param bool $deletecontent Whether to delete the course we are importing to content
1550 * @param array $options List of backup options
1551 * @return null
1552 * @since Moodle 2.4
1554 public static function import_course($importfrom, $importto, $deletecontent = 0, $options = array()) {
1555 global $CFG, $USER, $DB;
1556 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1557 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1559 // Parameter validation.
1560 $params = self::validate_parameters(
1561 self::import_course_parameters(),
1562 array(
1563 'importfrom' => $importfrom,
1564 'importto' => $importto,
1565 'deletecontent' => $deletecontent,
1566 'options' => $options
1570 if ($params['deletecontent'] !== 0 and $params['deletecontent'] !== 1) {
1571 throw new moodle_exception('invalidextparam', 'webservice', '', $params['deletecontent']);
1574 // Context validation.
1576 if (! ($importfrom = $DB->get_record('course', array('id'=>$params['importfrom'])))) {
1577 throw new moodle_exception('invalidcourseid', 'error');
1580 if (! ($importto = $DB->get_record('course', array('id'=>$params['importto'])))) {
1581 throw new moodle_exception('invalidcourseid', 'error');
1584 $importfromcontext = context_course::instance($importfrom->id);
1585 self::validate_context($importfromcontext);
1587 $importtocontext = context_course::instance($importto->id);
1588 self::validate_context($importtocontext);
1590 $backupdefaults = array(
1591 'activities' => 1,
1592 'blocks' => 1,
1593 'filters' => 1
1596 $backupsettings = array();
1598 // Check for backup and restore options.
1599 if (!empty($params['options'])) {
1600 foreach ($params['options'] as $option) {
1602 // Strict check for a correct value (allways 1 or 0, true or false).
1603 $value = clean_param($option['value'], PARAM_INT);
1605 if ($value !== 0 and $value !== 1) {
1606 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1609 if (!isset($backupdefaults[$option['name']])) {
1610 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1613 $backupsettings[$option['name']] = $value;
1617 // Capability checking.
1619 require_capability('moodle/backup:backuptargetimport', $importfromcontext);
1620 require_capability('moodle/restore:restoretargetimport', $importtocontext);
1622 $bc = new backup_controller(backup::TYPE_1COURSE, $importfrom->id, backup::FORMAT_MOODLE,
1623 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
1625 foreach ($backupsettings as $name => $value) {
1626 $bc->get_plan()->get_setting($name)->set_value($value);
1629 $backupid = $bc->get_backupid();
1630 $backupbasepath = $bc->get_plan()->get_basepath();
1632 $bc->execute_plan();
1633 $bc->destroy();
1635 // Restore the backup immediately.
1637 // Check if we must delete the contents of the destination course.
1638 if ($params['deletecontent']) {
1639 $restoretarget = backup::TARGET_EXISTING_DELETING;
1640 } else {
1641 $restoretarget = backup::TARGET_EXISTING_ADDING;
1644 $rc = new restore_controller($backupid, $importto->id,
1645 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, $restoretarget);
1647 foreach ($backupsettings as $name => $value) {
1648 $rc->get_plan()->get_setting($name)->set_value($value);
1651 if (!$rc->execute_precheck()) {
1652 $precheckresults = $rc->get_precheck_results();
1653 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1654 if (empty($CFG->keeptempdirectoriesonbackup)) {
1655 fulldelete($backupbasepath);
1658 $errorinfo = '';
1660 foreach ($precheckresults['errors'] as $error) {
1661 $errorinfo .= $error;
1664 if (array_key_exists('warnings', $precheckresults)) {
1665 foreach ($precheckresults['warnings'] as $warning) {
1666 $errorinfo .= $warning;
1670 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1672 } else {
1673 if ($restoretarget == backup::TARGET_EXISTING_DELETING) {
1674 restore_dbops::delete_course_content($importto->id);
1678 $rc->execute_plan();
1679 $rc->destroy();
1681 if (empty($CFG->keeptempdirectoriesonbackup)) {
1682 fulldelete($backupbasepath);
1685 return null;
1689 * Returns description of method result value
1691 * @return external_description
1692 * @since Moodle 2.4
1694 public static function import_course_returns() {
1695 return null;
1699 * Returns description of method parameters
1701 * @return external_function_parameters
1702 * @since Moodle 2.3
1704 public static function get_categories_parameters() {
1705 return new external_function_parameters(
1706 array(
1707 'criteria' => new external_multiple_structure(
1708 new external_single_structure(
1709 array(
1710 'key' => new external_value(PARAM_ALPHA,
1711 'The category column to search, expected keys (value format) are:'.
1712 '"id" (int) the category id,'.
1713 '"ids" (string) category ids separated by commas,'.
1714 '"name" (string) the category name,'.
1715 '"parent" (int) the parent category id,'.
1716 '"idnumber" (string) category idnumber'.
1717 ' - user must have \'moodle/category:manage\' to search on idnumber,'.
1718 '"visible" (int) whether the returned categories must be visible or hidden. If the key is not passed,
1719 then the function return all categories that the user can see.'.
1720 ' - user must have \'moodle/category:manage\' or \'moodle/category:viewhiddencategories\' to search on visible,'.
1721 '"theme" (string) only return the categories having this theme'.
1722 ' - user must have \'moodle/category:manage\' to search on theme'),
1723 'value' => new external_value(PARAM_RAW, 'the value to match')
1725 ), 'criteria', VALUE_DEFAULT, array()
1727 'addsubcategories' => new external_value(PARAM_BOOL, 'return the sub categories infos
1728 (1 - default) otherwise only the category info (0)', VALUE_DEFAULT, 1)
1734 * Get categories
1736 * @param array $criteria Criteria to match the results
1737 * @param booln $addsubcategories obtain only the category (false) or its subcategories (true - default)
1738 * @return array list of categories
1739 * @since Moodle 2.3
1741 public static function get_categories($criteria = array(), $addsubcategories = true) {
1742 global $CFG, $DB;
1743 require_once($CFG->dirroot . "/course/lib.php");
1745 // Validate parameters.
1746 $params = self::validate_parameters(self::get_categories_parameters(),
1747 array('criteria' => $criteria, 'addsubcategories' => $addsubcategories));
1749 // Retrieve the categories.
1750 $categories = array();
1751 if (!empty($params['criteria'])) {
1753 $conditions = array();
1754 $wheres = array();
1755 foreach ($params['criteria'] as $crit) {
1756 $key = trim($crit['key']);
1758 // Trying to avoid duplicate keys.
1759 if (!isset($conditions[$key])) {
1761 $context = context_system::instance();
1762 $value = null;
1763 switch ($key) {
1764 case 'id':
1765 $value = clean_param($crit['value'], PARAM_INT);
1766 $conditions[$key] = $value;
1767 $wheres[] = $key . " = :" . $key;
1768 break;
1770 case 'ids':
1771 $value = clean_param($crit['value'], PARAM_SEQUENCE);
1772 $ids = explode(',', $value);
1773 list($sqlids, $paramids) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED);
1774 $conditions = array_merge($conditions, $paramids);
1775 $wheres[] = 'id ' . $sqlids;
1776 break;
1778 case 'idnumber':
1779 if (has_capability('moodle/category:manage', $context)) {
1780 $value = clean_param($crit['value'], PARAM_RAW);
1781 $conditions[$key] = $value;
1782 $wheres[] = $key . " = :" . $key;
1783 } else {
1784 // We must throw an exception.
1785 // Otherwise the dev client would think no idnumber exists.
1786 throw new moodle_exception('criteriaerror',
1787 'webservice', '', null,
1788 'You don\'t have the permissions to search on the "idnumber" field.');
1790 break;
1792 case 'name':
1793 $value = clean_param($crit['value'], PARAM_TEXT);
1794 $conditions[$key] = $value;
1795 $wheres[] = $key . " = :" . $key;
1796 break;
1798 case 'parent':
1799 $value = clean_param($crit['value'], PARAM_INT);
1800 $conditions[$key] = $value;
1801 $wheres[] = $key . " = :" . $key;
1802 break;
1804 case 'visible':
1805 if (has_capability('moodle/category:viewhiddencategories', $context)) {
1806 $value = clean_param($crit['value'], PARAM_INT);
1807 $conditions[$key] = $value;
1808 $wheres[] = $key . " = :" . $key;
1809 } else {
1810 throw new moodle_exception('criteriaerror',
1811 'webservice', '', null,
1812 'You don\'t have the permissions to search on the "visible" field.');
1814 break;
1816 case 'theme':
1817 if (has_capability('moodle/category:manage', $context)) {
1818 $value = clean_param($crit['value'], PARAM_THEME);
1819 $conditions[$key] = $value;
1820 $wheres[] = $key . " = :" . $key;
1821 } else {
1822 throw new moodle_exception('criteriaerror',
1823 'webservice', '', null,
1824 'You don\'t have the permissions to search on the "theme" field.');
1826 break;
1828 default:
1829 throw new moodle_exception('criteriaerror',
1830 'webservice', '', null,
1831 'You can not search on this criteria: ' . $key);
1836 if (!empty($wheres)) {
1837 $wheres = implode(" AND ", $wheres);
1839 $categories = $DB->get_records_select('course_categories', $wheres, $conditions);
1841 // Retrieve its sub subcategories (all levels).
1842 if ($categories and !empty($params['addsubcategories'])) {
1843 $newcategories = array();
1845 // Check if we required visible/theme checks.
1846 $additionalselect = '';
1847 $additionalparams = array();
1848 if (isset($conditions['visible'])) {
1849 $additionalselect .= ' AND visible = :visible';
1850 $additionalparams['visible'] = $conditions['visible'];
1852 if (isset($conditions['theme'])) {
1853 $additionalselect .= ' AND theme= :theme';
1854 $additionalparams['theme'] = $conditions['theme'];
1857 foreach ($categories as $category) {
1858 $sqlselect = $DB->sql_like('path', ':path') . $additionalselect;
1859 $sqlparams = array('path' => $category->path.'/%') + $additionalparams; // It will NOT include the specified category.
1860 $subcategories = $DB->get_records_select('course_categories', $sqlselect, $sqlparams);
1861 $newcategories = $newcategories + $subcategories; // Both arrays have integer as keys.
1863 $categories = $categories + $newcategories;
1867 } else {
1868 // Retrieve all categories in the database.
1869 $categories = $DB->get_records('course_categories');
1872 // The not returned categories. key => category id, value => reason of exclusion.
1873 $excludedcats = array();
1875 // The returned categories.
1876 $categoriesinfo = array();
1878 // We need to sort the categories by path.
1879 // The parent cats need to be checked by the algo first.
1880 usort($categories, "core_course_external::compare_categories_by_path");
1882 foreach ($categories as $category) {
1884 // Check if the category is a child of an excluded category, if yes exclude it too (excluded => do not return).
1885 $parents = explode('/', $category->path);
1886 unset($parents[0]); // First key is always empty because path start with / => /1/2/4.
1887 foreach ($parents as $parentid) {
1888 // Note: when the parent exclusion was due to the context,
1889 // the sub category could still be returned.
1890 if (isset($excludedcats[$parentid]) and $excludedcats[$parentid] != 'context') {
1891 $excludedcats[$category->id] = 'parent';
1895 // Check the user can use the category context.
1896 $context = context_coursecat::instance($category->id);
1897 try {
1898 self::validate_context($context);
1899 } catch (Exception $e) {
1900 $excludedcats[$category->id] = 'context';
1902 // If it was the requested category then throw an exception.
1903 if (isset($params['categoryid']) && $category->id == $params['categoryid']) {
1904 $exceptionparam = new stdClass();
1905 $exceptionparam->message = $e->getMessage();
1906 $exceptionparam->catid = $category->id;
1907 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
1911 // Return the category information.
1912 if (!isset($excludedcats[$category->id])) {
1914 // Final check to see if the category is visible to the user.
1915 if (core_course_category::can_view_category($category)) {
1917 $categoryinfo = array();
1918 $categoryinfo['id'] = $category->id;
1919 $categoryinfo['name'] = external_format_string($category->name, $context);
1920 list($categoryinfo['description'], $categoryinfo['descriptionformat']) =
1921 external_format_text($category->description, $category->descriptionformat,
1922 $context->id, 'coursecat', 'description', null);
1923 $categoryinfo['parent'] = $category->parent;
1924 $categoryinfo['sortorder'] = $category->sortorder;
1925 $categoryinfo['coursecount'] = $category->coursecount;
1926 $categoryinfo['depth'] = $category->depth;
1927 $categoryinfo['path'] = $category->path;
1929 // Some fields only returned for admin.
1930 if (has_capability('moodle/category:manage', $context)) {
1931 $categoryinfo['idnumber'] = $category->idnumber;
1932 $categoryinfo['visible'] = $category->visible;
1933 $categoryinfo['visibleold'] = $category->visibleold;
1934 $categoryinfo['timemodified'] = $category->timemodified;
1935 $categoryinfo['theme'] = clean_param($category->theme, PARAM_THEME);
1938 $categoriesinfo[] = $categoryinfo;
1939 } else {
1940 $excludedcats[$category->id] = 'visibility';
1945 // Sorting the resulting array so it looks a bit better for the client developer.
1946 usort($categoriesinfo, "core_course_external::compare_categories_by_sortorder");
1948 return $categoriesinfo;
1952 * Sort categories array by path
1953 * private function: only used by get_categories
1955 * @param array $category1
1956 * @param array $category2
1957 * @return int result of strcmp
1958 * @since Moodle 2.3
1960 private static function compare_categories_by_path($category1, $category2) {
1961 return strcmp($category1->path, $category2->path);
1965 * Sort categories array by sortorder
1966 * private function: only used by get_categories
1968 * @param array $category1
1969 * @param array $category2
1970 * @return int result of strcmp
1971 * @since Moodle 2.3
1973 private static function compare_categories_by_sortorder($category1, $category2) {
1974 return strcmp($category1['sortorder'], $category2['sortorder']);
1978 * Returns description of method result value
1980 * @return external_description
1981 * @since Moodle 2.3
1983 public static function get_categories_returns() {
1984 return new external_multiple_structure(
1985 new external_single_structure(
1986 array(
1987 'id' => new external_value(PARAM_INT, 'category id'),
1988 'name' => new external_value(PARAM_RAW, 'category name'),
1989 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1990 'description' => new external_value(PARAM_RAW, 'category description'),
1991 'descriptionformat' => new external_format_value('description'),
1992 'parent' => new external_value(PARAM_INT, 'parent category id'),
1993 'sortorder' => new external_value(PARAM_INT, 'category sorting order'),
1994 'coursecount' => new external_value(PARAM_INT, 'number of courses in this category'),
1995 'visible' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1996 'visibleold' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1997 'timemodified' => new external_value(PARAM_INT, 'timestamp', VALUE_OPTIONAL),
1998 'depth' => new external_value(PARAM_INT, 'category depth'),
1999 'path' => new external_value(PARAM_TEXT, 'category path'),
2000 'theme' => new external_value(PARAM_THEME, 'category theme', VALUE_OPTIONAL),
2001 ), 'List of categories'
2007 * Returns description of method parameters
2009 * @return external_function_parameters
2010 * @since Moodle 2.3
2012 public static function create_categories_parameters() {
2013 return new external_function_parameters(
2014 array(
2015 'categories' => new external_multiple_structure(
2016 new external_single_structure(
2017 array(
2018 'name' => new external_value(PARAM_TEXT, 'new category name'),
2019 'parent' => new external_value(PARAM_INT,
2020 'the parent category id inside which the new category will be created
2021 - set to 0 for a root category',
2022 VALUE_DEFAULT, 0),
2023 'idnumber' => new external_value(PARAM_RAW,
2024 'the new category idnumber', VALUE_OPTIONAL),
2025 'description' => new external_value(PARAM_RAW,
2026 'the new category description', VALUE_OPTIONAL),
2027 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
2028 'theme' => new external_value(PARAM_THEME,
2029 'the new category theme. This option must be enabled on moodle',
2030 VALUE_OPTIONAL),
2039 * Create categories
2041 * @param array $categories - see create_categories_parameters() for the array structure
2042 * @return array - see create_categories_returns() for the array structure
2043 * @since Moodle 2.3
2045 public static function create_categories($categories) {
2046 global $DB;
2048 $params = self::validate_parameters(self::create_categories_parameters(),
2049 array('categories' => $categories));
2051 $transaction = $DB->start_delegated_transaction();
2053 $createdcategories = array();
2054 foreach ($params['categories'] as $category) {
2055 if ($category['parent']) {
2056 if (!$DB->record_exists('course_categories', array('id' => $category['parent']))) {
2057 throw new moodle_exception('unknowcategory');
2059 $context = context_coursecat::instance($category['parent']);
2060 } else {
2061 $context = context_system::instance();
2063 self::validate_context($context);
2064 require_capability('moodle/category:manage', $context);
2066 // this will validate format and throw an exception if there are errors
2067 external_validate_format($category['descriptionformat']);
2069 $newcategory = core_course_category::create($category);
2070 $context = context_coursecat::instance($newcategory->id);
2072 $createdcategories[] = array(
2073 'id' => $newcategory->id,
2074 'name' => external_format_string($newcategory->name, $context),
2078 $transaction->allow_commit();
2080 return $createdcategories;
2084 * Returns description of method parameters
2086 * @return external_function_parameters
2087 * @since Moodle 2.3
2089 public static function create_categories_returns() {
2090 return new external_multiple_structure(
2091 new external_single_structure(
2092 array(
2093 'id' => new external_value(PARAM_INT, 'new category id'),
2094 'name' => new external_value(PARAM_RAW, 'new category name'),
2101 * Returns description of method parameters
2103 * @return external_function_parameters
2104 * @since Moodle 2.3
2106 public static function update_categories_parameters() {
2107 return new external_function_parameters(
2108 array(
2109 'categories' => new external_multiple_structure(
2110 new external_single_structure(
2111 array(
2112 'id' => new external_value(PARAM_INT, 'course id'),
2113 'name' => new external_value(PARAM_TEXT, 'category name', VALUE_OPTIONAL),
2114 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
2115 'parent' => new external_value(PARAM_INT, 'parent category id', VALUE_OPTIONAL),
2116 'description' => new external_value(PARAM_RAW, 'category description', VALUE_OPTIONAL),
2117 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
2118 'theme' => new external_value(PARAM_THEME,
2119 'the category theme. This option must be enabled on moodle', VALUE_OPTIONAL),
2128 * Update categories
2130 * @param array $categories The list of categories to update
2131 * @return null
2132 * @since Moodle 2.3
2134 public static function update_categories($categories) {
2135 global $DB;
2137 // Validate parameters.
2138 $params = self::validate_parameters(self::update_categories_parameters(), array('categories' => $categories));
2140 $transaction = $DB->start_delegated_transaction();
2142 foreach ($params['categories'] as $cat) {
2143 $category = core_course_category::get($cat['id']);
2145 $categorycontext = context_coursecat::instance($cat['id']);
2146 self::validate_context($categorycontext);
2147 require_capability('moodle/category:manage', $categorycontext);
2149 // this will throw an exception if descriptionformat is not valid
2150 external_validate_format($cat['descriptionformat']);
2152 $category->update($cat);
2155 $transaction->allow_commit();
2159 * Returns description of method result value
2161 * @return external_description
2162 * @since Moodle 2.3
2164 public static function update_categories_returns() {
2165 return null;
2169 * Returns description of method parameters
2171 * @return external_function_parameters
2172 * @since Moodle 2.3
2174 public static function delete_categories_parameters() {
2175 return new external_function_parameters(
2176 array(
2177 'categories' => new external_multiple_structure(
2178 new external_single_structure(
2179 array(
2180 'id' => new external_value(PARAM_INT, 'category id to delete'),
2181 'newparent' => new external_value(PARAM_INT,
2182 'the parent category to move the contents to, if specified', VALUE_OPTIONAL),
2183 'recursive' => new external_value(PARAM_BOOL, '1: recursively delete all contents inside this
2184 category, 0 (default): move contents to newparent or current parent category (except if parent is root)', VALUE_DEFAULT, 0)
2193 * Delete categories
2195 * @param array $categories A list of category ids
2196 * @return array
2197 * @since Moodle 2.3
2199 public static function delete_categories($categories) {
2200 global $CFG, $DB;
2201 require_once($CFG->dirroot . "/course/lib.php");
2203 // Validate parameters.
2204 $params = self::validate_parameters(self::delete_categories_parameters(), array('categories' => $categories));
2206 $transaction = $DB->start_delegated_transaction();
2208 foreach ($params['categories'] as $category) {
2209 $deletecat = core_course_category::get($category['id'], MUST_EXIST);
2210 $context = context_coursecat::instance($deletecat->id);
2211 require_capability('moodle/category:manage', $context);
2212 self::validate_context($context);
2213 self::validate_context(get_category_or_system_context($deletecat->parent));
2215 if ($category['recursive']) {
2216 // If recursive was specified, then we recursively delete the category's contents.
2217 if ($deletecat->can_delete_full()) {
2218 $deletecat->delete_full(false);
2219 } else {
2220 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2222 } else {
2223 // In this situation, we don't delete the category's contents, we either move it to newparent or parent.
2224 // If the parent is the root, moving is not supported (because a course must always be inside a category).
2225 // We must move to an existing category.
2226 if (!empty($category['newparent'])) {
2227 $newparentcat = core_course_category::get($category['newparent']);
2228 } else {
2229 $newparentcat = core_course_category::get($deletecat->parent);
2232 // This operation is not allowed. We must move contents to an existing category.
2233 if (!$newparentcat->id) {
2234 throw new moodle_exception('movecatcontentstoroot');
2237 self::validate_context(context_coursecat::instance($newparentcat->id));
2238 if ($deletecat->can_move_content_to($newparentcat->id)) {
2239 $deletecat->delete_move($newparentcat->id, false);
2240 } else {
2241 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2246 $transaction->allow_commit();
2250 * Returns description of method parameters
2252 * @return external_function_parameters
2253 * @since Moodle 2.3
2255 public static function delete_categories_returns() {
2256 return null;
2260 * Describes the parameters for delete_modules.
2262 * @return external_function_parameters
2263 * @since Moodle 2.5
2265 public static function delete_modules_parameters() {
2266 return new external_function_parameters (
2267 array(
2268 'cmids' => new external_multiple_structure(new external_value(PARAM_INT, 'course module ID',
2269 VALUE_REQUIRED, '', NULL_NOT_ALLOWED), 'Array of course module IDs'),
2275 * Deletes a list of provided module instances.
2277 * @param array $cmids the course module ids
2278 * @since Moodle 2.5
2280 public static function delete_modules($cmids) {
2281 global $CFG, $DB;
2283 // Require course file containing the course delete module function.
2284 require_once($CFG->dirroot . "/course/lib.php");
2286 // Clean the parameters.
2287 $params = self::validate_parameters(self::delete_modules_parameters(), array('cmids' => $cmids));
2289 // Keep track of the course ids we have performed a capability check on to avoid repeating.
2290 $arrcourseschecked = array();
2292 foreach ($params['cmids'] as $cmid) {
2293 // Get the course module.
2294 $cm = $DB->get_record('course_modules', array('id' => $cmid), '*', MUST_EXIST);
2296 // Check if we have not yet confirmed they have permission in this course.
2297 if (!in_array($cm->course, $arrcourseschecked)) {
2298 // Ensure the current user has required permission in this course.
2299 $context = context_course::instance($cm->course);
2300 self::validate_context($context);
2301 // Add to the array.
2302 $arrcourseschecked[] = $cm->course;
2305 // Ensure they can delete this module.
2306 $modcontext = context_module::instance($cm->id);
2307 require_capability('moodle/course:manageactivities', $modcontext);
2309 // Delete the module.
2310 course_delete_module($cm->id);
2315 * Describes the delete_modules return value.
2317 * @return external_single_structure
2318 * @since Moodle 2.5
2320 public static function delete_modules_returns() {
2321 return null;
2325 * Returns description of method parameters
2327 * @return external_function_parameters
2328 * @since Moodle 2.9
2330 public static function view_course_parameters() {
2331 return new external_function_parameters(
2332 array(
2333 'courseid' => new external_value(PARAM_INT, 'id of the course'),
2334 'sectionnumber' => new external_value(PARAM_INT, 'section number', VALUE_DEFAULT, 0)
2340 * Trigger the course viewed event.
2342 * @param int $courseid id of course
2343 * @param int $sectionnumber sectionnumber (0, 1, 2...)
2344 * @return array of warnings and status result
2345 * @since Moodle 2.9
2346 * @throws moodle_exception
2348 public static function view_course($courseid, $sectionnumber = 0) {
2349 global $CFG;
2350 require_once($CFG->dirroot . "/course/lib.php");
2352 $params = self::validate_parameters(self::view_course_parameters(),
2353 array(
2354 'courseid' => $courseid,
2355 'sectionnumber' => $sectionnumber
2358 $warnings = array();
2360 $course = get_course($params['courseid']);
2361 $context = context_course::instance($course->id);
2362 self::validate_context($context);
2364 if (!empty($params['sectionnumber'])) {
2366 // Get section details and check it exists.
2367 $modinfo = get_fast_modinfo($course);
2368 $coursesection = $modinfo->get_section_info($params['sectionnumber'], MUST_EXIST);
2370 // Check user is allowed to see it.
2371 if (!$coursesection->uservisible) {
2372 require_capability('moodle/course:viewhiddensections', $context);
2376 course_view($context, $params['sectionnumber']);
2378 $result = array();
2379 $result['status'] = true;
2380 $result['warnings'] = $warnings;
2381 return $result;
2385 * Returns description of method result value
2387 * @return external_description
2388 * @since Moodle 2.9
2390 public static function view_course_returns() {
2391 return new external_single_structure(
2392 array(
2393 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
2394 'warnings' => new external_warnings()
2400 * Returns description of method parameters
2402 * @return external_function_parameters
2403 * @since Moodle 3.0
2405 public static function search_courses_parameters() {
2406 return new external_function_parameters(
2407 array(
2408 'criterianame' => new external_value(PARAM_ALPHA, 'criteria name
2409 (search, modulelist (only admins), blocklist (only admins), tagid)'),
2410 'criteriavalue' => new external_value(PARAM_RAW, 'criteria value'),
2411 'page' => new external_value(PARAM_INT, 'page number (0 based)', VALUE_DEFAULT, 0),
2412 'perpage' => new external_value(PARAM_INT, 'items per page', VALUE_DEFAULT, 0),
2413 'requiredcapabilities' => new external_multiple_structure(
2414 new external_value(PARAM_CAPABILITY, 'Capability string used to filter courses by permission'),
2415 'Optional list of required capabilities (used to filter the list)', VALUE_DEFAULT, array()
2417 'limittoenrolled' => new external_value(PARAM_BOOL, 'limit to enrolled courses', VALUE_DEFAULT, 0),
2418 'onlywithcompletion' => new external_value(PARAM_BOOL, 'limit to courses where completion is enabled',
2419 VALUE_DEFAULT, 0),
2425 * Return the course information that is public (visible by every one)
2427 * @param core_course_list_element $course course in list object
2428 * @param stdClass $coursecontext course context object
2429 * @return array the course information
2430 * @since Moodle 3.2
2432 protected static function get_course_public_information(core_course_list_element $course, $coursecontext) {
2434 static $categoriescache = array();
2436 // Category information.
2437 if (!array_key_exists($course->category, $categoriescache)) {
2438 $categoriescache[$course->category] = core_course_category::get($course->category, IGNORE_MISSING);
2440 $category = $categoriescache[$course->category];
2442 // Retrieve course overview used files.
2443 $files = array();
2444 foreach ($course->get_course_overviewfiles() as $file) {
2445 $fileurl = moodle_url::make_webservice_pluginfile_url($file->get_contextid(), $file->get_component(),
2446 $file->get_filearea(), null, $file->get_filepath(),
2447 $file->get_filename())->out(false);
2448 $files[] = array(
2449 'filename' => $file->get_filename(),
2450 'fileurl' => $fileurl,
2451 'filesize' => $file->get_filesize(),
2452 'filepath' => $file->get_filepath(),
2453 'mimetype' => $file->get_mimetype(),
2454 'timemodified' => $file->get_timemodified(),
2458 // Retrieve the course contacts,
2459 // we need here the users fullname since if we are not enrolled can be difficult to obtain them via other Web Services.
2460 $coursecontacts = array();
2461 foreach ($course->get_course_contacts() as $contact) {
2462 $coursecontacts[] = array(
2463 'id' => $contact['user']->id,
2464 'fullname' => $contact['username'],
2465 'roles' => array_map(function($role){
2466 return array('id' => $role->id, 'name' => $role->displayname);
2467 }, $contact['roles']),
2468 'role' => array('id' => $contact['role']->id, 'name' => $contact['role']->displayname),
2469 'rolename' => $contact['rolename']
2473 // Allowed enrolment methods (maybe we can self-enrol).
2474 $enroltypes = array();
2475 $instances = enrol_get_instances($course->id, true);
2476 foreach ($instances as $instance) {
2477 $enroltypes[] = $instance->enrol;
2480 // Format summary.
2481 list($summary, $summaryformat) =
2482 external_format_text($course->summary, $course->summaryformat, $coursecontext->id, 'course', 'summary', null);
2484 $categoryname = '';
2485 if (!empty($category)) {
2486 $categoryname = external_format_string($category->name, $category->get_context());
2489 $displayname = get_course_display_name_for_list($course);
2490 $coursereturns = array();
2491 $coursereturns['id'] = $course->id;
2492 $coursereturns['fullname'] = external_format_string($course->fullname, $coursecontext->id);
2493 $coursereturns['displayname'] = external_format_string($displayname, $coursecontext->id);
2494 $coursereturns['shortname'] = external_format_string($course->shortname, $coursecontext->id);
2495 $coursereturns['categoryid'] = $course->category;
2496 $coursereturns['categoryname'] = $categoryname;
2497 $coursereturns['summary'] = $summary;
2498 $coursereturns['summaryformat'] = $summaryformat;
2499 $coursereturns['summaryfiles'] = external_util::get_area_files($coursecontext->id, 'course', 'summary', false, false);
2500 $coursereturns['overviewfiles'] = $files;
2501 $coursereturns['contacts'] = $coursecontacts;
2502 $coursereturns['enrollmentmethods'] = $enroltypes;
2503 $coursereturns['sortorder'] = $course->sortorder;
2504 $coursereturns['showactivitydates'] = $course->showactivitydates;
2505 $coursereturns['showcompletionconditions'] = $course->showcompletionconditions;
2507 $handler = core_course\customfield\course_handler::create();
2508 if ($customfields = $handler->export_instance_data($course->id)) {
2509 $coursereturns['customfields'] = [];
2510 foreach ($customfields as $data) {
2511 $coursereturns['customfields'][] = [
2512 'type' => $data->get_type(),
2513 'value' => $data->get_value(),
2514 'valueraw' => $data->get_data_controller()->get_value(),
2515 'name' => $data->get_name(),
2516 'shortname' => $data->get_shortname()
2521 return $coursereturns;
2525 * Search courses following the specified criteria.
2527 * @param string $criterianame Criteria name (search, modulelist (only admins), blocklist (only admins), tagid)
2528 * @param string $criteriavalue Criteria value
2529 * @param int $page Page number (for pagination)
2530 * @param int $perpage Items per page
2531 * @param array $requiredcapabilities Optional list of required capabilities (used to filter the list).
2532 * @param int $limittoenrolled Limit to only enrolled courses
2533 * @param int onlywithcompletion Limit to only courses where completion is enabled
2534 * @return array of course objects and warnings
2535 * @since Moodle 3.0
2536 * @throws moodle_exception
2538 public static function search_courses($criterianame,
2539 $criteriavalue,
2540 $page=0,
2541 $perpage=0,
2542 $requiredcapabilities=array(),
2543 $limittoenrolled=0,
2544 $onlywithcompletion=0) {
2545 global $CFG;
2547 $warnings = array();
2549 $parameters = array(
2550 'criterianame' => $criterianame,
2551 'criteriavalue' => $criteriavalue,
2552 'page' => $page,
2553 'perpage' => $perpage,
2554 'requiredcapabilities' => $requiredcapabilities,
2555 'limittoenrolled' => $limittoenrolled,
2556 'onlywithcompletion' => $onlywithcompletion
2558 $params = self::validate_parameters(self::search_courses_parameters(), $parameters);
2559 self::validate_context(context_system::instance());
2561 $allowedcriterianames = array('search', 'modulelist', 'blocklist', 'tagid');
2562 if (!in_array($params['criterianame'], $allowedcriterianames)) {
2563 throw new invalid_parameter_exception('Invalid value for criterianame parameter (value: '.$params['criterianame'].'),' .
2564 'allowed values are: '.implode(',', $allowedcriterianames));
2567 if ($params['criterianame'] == 'modulelist' or $params['criterianame'] == 'blocklist') {
2568 require_capability('moodle/site:config', context_system::instance());
2571 $paramtype = array(
2572 'search' => PARAM_RAW,
2573 'modulelist' => PARAM_PLUGIN,
2574 'blocklist' => PARAM_INT,
2575 'tagid' => PARAM_INT
2577 $params['criteriavalue'] = clean_param($params['criteriavalue'], $paramtype[$params['criterianame']]);
2579 // Prepare the search API options.
2580 $searchcriteria = array();
2581 $searchcriteria[$params['criterianame']] = $params['criteriavalue'];
2582 if ($params['onlywithcompletion']) {
2583 $searchcriteria['onlywithcompletion'] = true;
2586 $options = array();
2587 if ($params['perpage'] != 0) {
2588 $offset = $params['page'] * $params['perpage'];
2589 $options = array('offset' => $offset, 'limit' => $params['perpage']);
2592 // Search the courses.
2593 $courses = core_course_category::search_courses($searchcriteria, $options, $params['requiredcapabilities']);
2594 $totalcount = core_course_category::search_courses_count($searchcriteria, $options, $params['requiredcapabilities']);
2596 if (!empty($limittoenrolled)) {
2597 // Get the courses where the current user has access.
2598 $enrolled = enrol_get_my_courses(array('id', 'cacherev'));
2601 $finalcourses = array();
2602 $categoriescache = array();
2604 foreach ($courses as $course) {
2605 if (!empty($limittoenrolled)) {
2606 // Filter out not enrolled courses.
2607 if (!isset($enrolled[$course->id])) {
2608 $totalcount--;
2609 continue;
2613 $coursecontext = context_course::instance($course->id);
2615 $finalcourses[] = self::get_course_public_information($course, $coursecontext);
2618 return array(
2619 'total' => $totalcount,
2620 'courses' => $finalcourses,
2621 'warnings' => $warnings
2626 * Returns a course structure definition
2628 * @param boolean $onlypublicdata set to true, to retrieve only fields viewable by anyone when the course is visible
2629 * @return array the course structure
2630 * @since Moodle 3.2
2632 protected static function get_course_structure($onlypublicdata = true) {
2633 $coursestructure = array(
2634 'id' => new external_value(PARAM_INT, 'course id'),
2635 'fullname' => new external_value(PARAM_RAW, 'course full name'),
2636 'displayname' => new external_value(PARAM_RAW, 'course display name'),
2637 'shortname' => new external_value(PARAM_RAW, 'course short name'),
2638 'categoryid' => new external_value(PARAM_INT, 'category id'),
2639 'categoryname' => new external_value(PARAM_RAW, 'category name'),
2640 'sortorder' => new external_value(PARAM_INT, 'Sort order in the category', VALUE_OPTIONAL),
2641 'summary' => new external_value(PARAM_RAW, 'summary'),
2642 'summaryformat' => new external_format_value('summary'),
2643 'summaryfiles' => new external_files('summary files in the summary field', VALUE_OPTIONAL),
2644 'overviewfiles' => new external_files('additional overview files attached to this course'),
2645 'showactivitydates' => new external_value(PARAM_BOOL, 'Whether the activity dates are shown or not'),
2646 'showcompletionconditions' => new external_value(PARAM_BOOL,
2647 'Whether the activity completion conditions are shown or not'),
2648 'contacts' => new external_multiple_structure(
2649 new external_single_structure(
2650 array(
2651 'id' => new external_value(PARAM_INT, 'contact user id'),
2652 'fullname' => new external_value(PARAM_NOTAGS, 'contact user fullname'),
2655 'contact users'
2657 'enrollmentmethods' => new external_multiple_structure(
2658 new external_value(PARAM_PLUGIN, 'enrollment method'),
2659 'enrollment methods list'
2661 'customfields' => new external_multiple_structure(
2662 new external_single_structure(
2663 array(
2664 'name' => new external_value(PARAM_RAW, 'The name of the custom field'),
2665 'shortname' => new external_value(PARAM_RAW,
2666 'The shortname of the custom field - to be able to build the field class in the code'),
2667 'type' => new external_value(PARAM_ALPHANUMEXT,
2668 'The type of the custom field - text field, checkbox...'),
2669 'valueraw' => new external_value(PARAM_RAW, 'The raw value of the custom field'),
2670 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
2672 ), 'Custom fields', VALUE_OPTIONAL),
2675 if (!$onlypublicdata) {
2676 $extra = array(
2677 'idnumber' => new external_value(PARAM_RAW, 'Id number', VALUE_OPTIONAL),
2678 'format' => new external_value(PARAM_PLUGIN, 'Course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
2679 'showgrades' => new external_value(PARAM_INT, '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
2680 'newsitems' => new external_value(PARAM_INT, 'Number of recent items appearing on the course page', VALUE_OPTIONAL),
2681 'startdate' => new external_value(PARAM_INT, 'Timestamp when the course start', VALUE_OPTIONAL),
2682 'enddate' => new external_value(PARAM_INT, 'Timestamp when the course end', VALUE_OPTIONAL),
2683 'maxbytes' => new external_value(PARAM_INT, 'Largest size of file that can be uploaded into', VALUE_OPTIONAL),
2684 'showreports' => new external_value(PARAM_INT, 'Are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
2685 'visible' => new external_value(PARAM_INT, '1: available to student, 0:not available', VALUE_OPTIONAL),
2686 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
2687 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
2688 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
2689 'enablecompletion' => new external_value(PARAM_INT, 'Completion enabled? 1: yes 0: no', VALUE_OPTIONAL),
2690 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
2691 'lang' => new external_value(PARAM_SAFEDIR, 'Forced course language', VALUE_OPTIONAL),
2692 'theme' => new external_value(PARAM_PLUGIN, 'Fame of the forced theme', VALUE_OPTIONAL),
2693 'marker' => new external_value(PARAM_INT, 'Current course marker', VALUE_OPTIONAL),
2694 'legacyfiles' => new external_value(PARAM_INT, 'If legacy files are enabled', VALUE_OPTIONAL),
2695 'calendartype' => new external_value(PARAM_PLUGIN, 'Calendar type', VALUE_OPTIONAL),
2696 'timecreated' => new external_value(PARAM_INT, 'Time when the course was created', VALUE_OPTIONAL),
2697 'timemodified' => new external_value(PARAM_INT, 'Last time the course was updated', VALUE_OPTIONAL),
2698 'requested' => new external_value(PARAM_INT, 'If is a requested course', VALUE_OPTIONAL),
2699 'cacherev' => new external_value(PARAM_INT, 'Cache revision number', VALUE_OPTIONAL),
2700 'filters' => new external_multiple_structure(
2701 new external_single_structure(
2702 array(
2703 'filter' => new external_value(PARAM_PLUGIN, 'Filter plugin name'),
2704 'localstate' => new external_value(PARAM_INT, 'Filter state: 1 for on, -1 for off, 0 if inherit'),
2705 'inheritedstate' => new external_value(PARAM_INT, '1 or 0 to use when localstate is set to inherit'),
2708 'Course filters', VALUE_OPTIONAL
2710 'courseformatoptions' => new external_multiple_structure(
2711 new external_single_structure(
2712 array(
2713 'name' => new external_value(PARAM_RAW, 'Course format option name.'),
2714 'value' => new external_value(PARAM_RAW, 'Course format option value.'),
2717 'Additional options for particular course format.', VALUE_OPTIONAL
2720 $coursestructure = array_merge($coursestructure, $extra);
2722 return new external_single_structure($coursestructure);
2726 * Returns description of method result value
2728 * @return external_description
2729 * @since Moodle 3.0
2731 public static function search_courses_returns() {
2732 return new external_single_structure(
2733 array(
2734 'total' => new external_value(PARAM_INT, 'total course count'),
2735 'courses' => new external_multiple_structure(self::get_course_structure(), 'course'),
2736 'warnings' => new external_warnings()
2742 * Returns description of method parameters
2744 * @return external_function_parameters
2745 * @since Moodle 3.0
2747 public static function get_course_module_parameters() {
2748 return new external_function_parameters(
2749 array(
2750 'cmid' => new external_value(PARAM_INT, 'The course module id')
2756 * Return information about a course module.
2758 * @param int $cmid the course module id
2759 * @return array of warnings and the course module
2760 * @since Moodle 3.0
2761 * @throws moodle_exception
2763 public static function get_course_module($cmid) {
2764 global $CFG, $DB;
2766 $params = self::validate_parameters(self::get_course_module_parameters(), array('cmid' => $cmid));
2767 $warnings = array();
2769 $cm = get_coursemodule_from_id(null, $params['cmid'], 0, true, MUST_EXIST);
2770 $context = context_module::instance($cm->id);
2771 self::validate_context($context);
2773 // If the user has permissions to manage the activity, return all the information.
2774 if (has_capability('moodle/course:manageactivities', $context)) {
2775 require_once($CFG->dirroot . '/course/modlib.php');
2776 require_once($CFG->libdir . '/gradelib.php');
2778 $info = $cm;
2779 // Get the extra information: grade, advanced grading and outcomes data.
2780 $course = get_course($cm->course);
2781 list($newcm, $newcontext, $module, $extrainfo, $cw) = get_moduleinfo_data($cm, $course);
2782 // Grades.
2783 $gradeinfo = array('grade', 'gradepass', 'gradecat');
2784 foreach ($gradeinfo as $gfield) {
2785 if (isset($extrainfo->{$gfield})) {
2786 $info->{$gfield} = $extrainfo->{$gfield};
2789 if (isset($extrainfo->grade) and $extrainfo->grade < 0) {
2790 $info->scale = $DB->get_field('scale', 'scale', array('id' => abs($extrainfo->grade)));
2792 // Advanced grading.
2793 if (isset($extrainfo->_advancedgradingdata)) {
2794 $info->advancedgrading = array();
2795 foreach ($extrainfo as $key => $val) {
2796 if (strpos($key, 'advancedgradingmethod_') === 0) {
2797 $info->advancedgrading[] = array(
2798 'area' => str_replace('advancedgradingmethod_', '', $key),
2799 'method' => $val
2804 // Outcomes.
2805 foreach ($extrainfo as $key => $val) {
2806 if (strpos($key, 'outcome_') === 0) {
2807 if (!isset($info->outcomes)) {
2808 $info->outcomes = array();
2810 $id = str_replace('outcome_', '', $key);
2811 $outcome = grade_outcome::fetch(array('id' => $id));
2812 $scaleitems = $outcome->load_scale();
2813 $info->outcomes[] = array(
2814 'id' => $id,
2815 'name' => external_format_string($outcome->get_name(), $context->id),
2816 'scale' => $scaleitems->scale
2820 } else {
2821 // Return information is safe to show to any user.
2822 $info = new stdClass();
2823 $info->id = $cm->id;
2824 $info->course = $cm->course;
2825 $info->module = $cm->module;
2826 $info->modname = $cm->modname;
2827 $info->instance = $cm->instance;
2828 $info->section = $cm->section;
2829 $info->sectionnum = $cm->sectionnum;
2830 $info->groupmode = $cm->groupmode;
2831 $info->groupingid = $cm->groupingid;
2832 $info->completion = $cm->completion;
2833 $info->downloadcontent = $cm->downloadcontent;
2835 // Format name.
2836 $info->name = external_format_string($cm->name, $context->id);
2837 $result = array();
2838 $result['cm'] = $info;
2839 $result['warnings'] = $warnings;
2840 return $result;
2844 * Returns description of method result value
2846 * @return external_description
2847 * @since Moodle 3.0
2849 public static function get_course_module_returns() {
2850 return new external_single_structure(
2851 array(
2852 'cm' => new external_single_structure(
2853 array(
2854 'id' => new external_value(PARAM_INT, 'The course module id'),
2855 'course' => new external_value(PARAM_INT, 'The course id'),
2856 'module' => new external_value(PARAM_INT, 'The module type id'),
2857 'name' => new external_value(PARAM_RAW, 'The activity name'),
2858 'modname' => new external_value(PARAM_COMPONENT, 'The module component name (forum, assign, etc..)'),
2859 'instance' => new external_value(PARAM_INT, 'The activity instance id'),
2860 'section' => new external_value(PARAM_INT, 'The module section id'),
2861 'sectionnum' => new external_value(PARAM_INT, 'The module section number'),
2862 'groupmode' => new external_value(PARAM_INT, 'Group mode'),
2863 'groupingid' => new external_value(PARAM_INT, 'Grouping id'),
2864 'completion' => new external_value(PARAM_INT, 'If completion is enabled'),
2865 'idnumber' => new external_value(PARAM_RAW, 'Module id number', VALUE_OPTIONAL),
2866 'added' => new external_value(PARAM_INT, 'Time added', VALUE_OPTIONAL),
2867 'score' => new external_value(PARAM_INT, 'Score', VALUE_OPTIONAL),
2868 'indent' => new external_value(PARAM_INT, 'Indentation', VALUE_OPTIONAL),
2869 'visible' => new external_value(PARAM_INT, 'If visible', VALUE_OPTIONAL),
2870 'visibleoncoursepage' => new external_value(PARAM_INT, 'If visible on course page', VALUE_OPTIONAL),
2871 'visibleold' => new external_value(PARAM_INT, 'Visible old', VALUE_OPTIONAL),
2872 'completiongradeitemnumber' => new external_value(PARAM_INT, 'Completion grade item', VALUE_OPTIONAL),
2873 'completionpassgrade' => new external_value(PARAM_INT, 'Completion pass grade setting', VALUE_OPTIONAL),
2874 'completionview' => new external_value(PARAM_INT, 'Completion view setting', VALUE_OPTIONAL),
2875 'completionexpected' => new external_value(PARAM_INT, 'Completion time expected', VALUE_OPTIONAL),
2876 'showdescription' => new external_value(PARAM_INT, 'If the description is showed', VALUE_OPTIONAL),
2877 'downloadcontent' => new external_value(PARAM_INT, 'The download content value', VALUE_OPTIONAL),
2878 'availability' => new external_value(PARAM_RAW, 'Availability settings', VALUE_OPTIONAL),
2879 'grade' => new external_value(PARAM_FLOAT, 'Grade (max value or scale id)', VALUE_OPTIONAL),
2880 'scale' => new external_value(PARAM_TEXT, 'Scale items (if used)', VALUE_OPTIONAL),
2881 'gradepass' => new external_value(PARAM_RAW, 'Grade to pass (float)', VALUE_OPTIONAL),
2882 'gradecat' => new external_value(PARAM_INT, 'Grade category', VALUE_OPTIONAL),
2883 'advancedgrading' => new external_multiple_structure(
2884 new external_single_structure(
2885 array(
2886 'area' => new external_value(PARAM_AREA, 'Gradable area name'),
2887 'method' => new external_value(PARAM_COMPONENT, 'Grading method'),
2890 'Advanced grading settings', VALUE_OPTIONAL
2892 'outcomes' => new external_multiple_structure(
2893 new external_single_structure(
2894 array(
2895 'id' => new external_value(PARAM_ALPHANUMEXT, 'Outcome id'),
2896 'name' => new external_value(PARAM_RAW, 'Outcome full name'),
2897 'scale' => new external_value(PARAM_TEXT, 'Scale items')
2900 'Outcomes information', VALUE_OPTIONAL
2904 'warnings' => new external_warnings()
2910 * Returns description of method parameters
2912 * @return external_function_parameters
2913 * @since Moodle 3.0
2915 public static function get_course_module_by_instance_parameters() {
2916 return new external_function_parameters(
2917 array(
2918 'module' => new external_value(PARAM_COMPONENT, 'The module name'),
2919 'instance' => new external_value(PARAM_INT, 'The module instance id')
2925 * Return information about a course module.
2927 * @param string $module the module name
2928 * @param int $instance the activity instance id
2929 * @return array of warnings and the course module
2930 * @since Moodle 3.0
2931 * @throws moodle_exception
2933 public static function get_course_module_by_instance($module, $instance) {
2935 $params = self::validate_parameters(self::get_course_module_by_instance_parameters(),
2936 array(
2937 'module' => $module,
2938 'instance' => $instance,
2941 $warnings = array();
2942 $cm = get_coursemodule_from_instance($params['module'], $params['instance'], 0, false, MUST_EXIST);
2944 return self::get_course_module($cm->id);
2948 * Returns description of method result value
2950 * @return external_description
2951 * @since Moodle 3.0
2953 public static function get_course_module_by_instance_returns() {
2954 return self::get_course_module_returns();
2958 * Returns description of method parameters
2960 * @return external_function_parameters
2961 * @since Moodle 3.2
2963 public static function get_user_navigation_options_parameters() {
2964 return new external_function_parameters(
2965 array(
2966 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2972 * Return a list of navigation options in a set of courses that are avaialable or not for the current user.
2974 * @param array $courseids a list of course ids
2975 * @return array of warnings and the options availability
2976 * @since Moodle 3.2
2977 * @throws moodle_exception
2979 public static function get_user_navigation_options($courseids) {
2980 global $CFG;
2981 require_once($CFG->dirroot . '/course/lib.php');
2983 // Parameter validation.
2984 $params = self::validate_parameters(self::get_user_navigation_options_parameters(), array('courseids' => $courseids));
2985 $courseoptions = array();
2987 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
2989 if (!empty($courses)) {
2990 foreach ($courses as $course) {
2991 // Fix the context for the frontpage.
2992 if ($course->id == SITEID) {
2993 $course->context = context_system::instance();
2995 $navoptions = course_get_user_navigation_options($course->context, $course);
2996 $options = array();
2997 foreach ($navoptions as $name => $available) {
2998 $options[] = array(
2999 'name' => $name,
3000 'available' => $available,
3004 $courseoptions[] = array(
3005 'id' => $course->id,
3006 'options' => $options
3011 $result = array(
3012 'courses' => $courseoptions,
3013 'warnings' => $warnings
3015 return $result;
3019 * Returns description of method result value
3021 * @return external_description
3022 * @since Moodle 3.2
3024 public static function get_user_navigation_options_returns() {
3025 return new external_single_structure(
3026 array(
3027 'courses' => new external_multiple_structure(
3028 new external_single_structure(
3029 array(
3030 'id' => new external_value(PARAM_INT, 'Course id'),
3031 'options' => new external_multiple_structure(
3032 new external_single_structure(
3033 array(
3034 'name' => new external_value(PARAM_ALPHANUMEXT, 'Option name'),
3035 'available' => new external_value(PARAM_BOOL, 'Whether the option is available or not'),
3040 ), 'List of courses'
3042 'warnings' => new external_warnings()
3048 * Returns description of method parameters
3050 * @return external_function_parameters
3051 * @since Moodle 3.2
3053 public static function get_user_administration_options_parameters() {
3054 return new external_function_parameters(
3055 array(
3056 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
3062 * Return a list of administration options in a set of courses that are available or not for the current user.
3064 * @param array $courseids a list of course ids
3065 * @return array of warnings and the options availability
3066 * @since Moodle 3.2
3067 * @throws moodle_exception
3069 public static function get_user_administration_options($courseids) {
3070 global $CFG;
3071 require_once($CFG->dirroot . '/course/lib.php');
3073 // Parameter validation.
3074 $params = self::validate_parameters(self::get_user_administration_options_parameters(), array('courseids' => $courseids));
3075 $courseoptions = array();
3077 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
3079 if (!empty($courses)) {
3080 foreach ($courses as $course) {
3081 $adminoptions = course_get_user_administration_options($course, $course->context);
3082 $options = array();
3083 foreach ($adminoptions as $name => $available) {
3084 $options[] = array(
3085 'name' => $name,
3086 'available' => $available,
3090 $courseoptions[] = array(
3091 'id' => $course->id,
3092 'options' => $options
3097 $result = array(
3098 'courses' => $courseoptions,
3099 'warnings' => $warnings
3101 return $result;
3105 * Returns description of method result value
3107 * @return external_description
3108 * @since Moodle 3.2
3110 public static function get_user_administration_options_returns() {
3111 return self::get_user_navigation_options_returns();
3115 * Returns description of method parameters
3117 * @return external_function_parameters
3118 * @since Moodle 3.2
3120 public static function get_courses_by_field_parameters() {
3121 return new external_function_parameters(
3122 array(
3123 'field' => new external_value(PARAM_ALPHA, 'The field to search can be left empty for all courses or:
3124 id: course id
3125 ids: comma separated course ids
3126 shortname: course short name
3127 idnumber: course id number
3128 category: category id the course belongs to
3129 ', VALUE_DEFAULT, ''),
3130 'value' => new external_value(PARAM_RAW, 'The value to match', VALUE_DEFAULT, '')
3137 * Get courses matching a specific field (id/s, shortname, idnumber, category)
3139 * @param string $field field name to search, or empty for all courses
3140 * @param string $value value to search
3141 * @return array list of courses and warnings
3142 * @throws invalid_parameter_exception
3143 * @since Moodle 3.2
3145 public static function get_courses_by_field($field = '', $value = '') {
3146 global $DB, $CFG;
3147 require_once($CFG->dirroot . '/course/lib.php');
3148 require_once($CFG->libdir . '/filterlib.php');
3150 $params = self::validate_parameters(self::get_courses_by_field_parameters(),
3151 array(
3152 'field' => $field,
3153 'value' => $value,
3156 $warnings = array();
3158 if (empty($params['field'])) {
3159 $courses = $DB->get_records('course', null, 'id ASC');
3160 } else {
3161 switch ($params['field']) {
3162 case 'id':
3163 case 'category':
3164 $value = clean_param($params['value'], PARAM_INT);
3165 break;
3166 case 'ids':
3167 $value = clean_param($params['value'], PARAM_SEQUENCE);
3168 break;
3169 case 'shortname':
3170 $value = clean_param($params['value'], PARAM_TEXT);
3171 break;
3172 case 'idnumber':
3173 $value = clean_param($params['value'], PARAM_RAW);
3174 break;
3175 default:
3176 throw new invalid_parameter_exception('Invalid field name');
3179 if ($params['field'] === 'ids') {
3180 // Preload categories to avoid loading one at a time.
3181 $courseids = explode(',', $value);
3182 list ($listsql, $listparams) = $DB->get_in_or_equal($courseids);
3183 $categoryids = $DB->get_fieldset_sql("
3184 SELECT DISTINCT cc.id
3185 FROM {course} c
3186 JOIN {course_categories} cc ON cc.id = c.category
3187 WHERE c.id $listsql", $listparams);
3188 core_course_category::get_many($categoryids);
3190 // Load and validate all courses. This is called because it loads the courses
3191 // more efficiently.
3192 list ($courses, $warnings) = external_util::validate_courses($courseids, [],
3193 false, true);
3194 } else {
3195 $courses = $DB->get_records('course', array($params['field'] => $value), 'id ASC');
3199 $coursesdata = array();
3200 foreach ($courses as $course) {
3201 $context = context_course::instance($course->id);
3202 $canupdatecourse = has_capability('moodle/course:update', $context);
3203 $canviewhiddencourses = has_capability('moodle/course:viewhiddencourses', $context);
3205 // Check if the course is visible in the site for the user.
3206 if (!$course->visible and !$canviewhiddencourses and !$canupdatecourse) {
3207 continue;
3209 // Get the public course information, even if we are not enrolled.
3210 $courseinlist = new core_course_list_element($course);
3212 // Now, check if we have access to the course, unless it was already checked.
3213 try {
3214 if (empty($course->contextvalidated)) {
3215 self::validate_context($context);
3217 } catch (Exception $e) {
3218 // User can not access the course, check if they can see the public information about the course and return it.
3219 if (core_course_category::can_view_course_info($course)) {
3220 $coursesdata[$course->id] = self::get_course_public_information($courseinlist, $context);
3222 continue;
3224 $coursesdata[$course->id] = self::get_course_public_information($courseinlist, $context);
3225 // Return information for any user that can access the course.
3226 $coursefields = array('format', 'showgrades', 'newsitems', 'startdate', 'enddate', 'maxbytes', 'showreports', 'visible',
3227 'groupmode', 'groupmodeforce', 'defaultgroupingid', 'enablecompletion', 'completionnotify', 'lang', 'theme',
3228 'marker');
3230 // Course filters.
3231 $coursesdata[$course->id]['filters'] = filter_get_available_in_context($context);
3233 // Information for managers only.
3234 if ($canupdatecourse) {
3235 $managerfields = array('idnumber', 'legacyfiles', 'calendartype', 'timecreated', 'timemodified', 'requested',
3236 'cacherev');
3237 $coursefields = array_merge($coursefields, $managerfields);
3240 // Populate fields.
3241 foreach ($coursefields as $field) {
3242 $coursesdata[$course->id][$field] = $course->{$field};
3245 // Clean lang and auth fields for external functions (it may content uninstalled themes or language packs).
3246 if (isset($coursesdata[$course->id]['theme'])) {
3247 $coursesdata[$course->id]['theme'] = clean_param($coursesdata[$course->id]['theme'], PARAM_THEME);
3249 if (isset($coursesdata[$course->id]['lang'])) {
3250 $coursesdata[$course->id]['lang'] = clean_param($coursesdata[$course->id]['lang'], PARAM_LANG);
3253 $courseformatoptions = course_get_format($course)->get_config_for_external();
3254 foreach ($courseformatoptions as $key => $value) {
3255 $coursesdata[$course->id]['courseformatoptions'][] = array(
3256 'name' => $key,
3257 'value' => $value
3262 return array(
3263 'courses' => $coursesdata,
3264 'warnings' => $warnings
3269 * Returns description of method result value
3271 * @return external_description
3272 * @since Moodle 3.2
3274 public static function get_courses_by_field_returns() {
3275 // Course structure, including not only public viewable fields.
3276 return new external_single_structure(
3277 array(
3278 'courses' => new external_multiple_structure(self::get_course_structure(false), 'Course'),
3279 'warnings' => new external_warnings()
3285 * Returns description of method parameters
3287 * @return external_function_parameters
3288 * @since Moodle 3.2
3290 public static function check_updates_parameters() {
3291 return new external_function_parameters(
3292 array(
3293 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3294 'tocheck' => new external_multiple_structure(
3295 new external_single_structure(
3296 array(
3297 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level for the file location.
3298 Only module supported right now.'),
3299 'id' => new external_value(PARAM_INT, 'Context instance id'),
3300 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3303 'Instances to check'
3305 'filter' => new external_multiple_structure(
3306 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3307 gradeitems, outcomes'),
3308 'Check only for updates in these areas', VALUE_DEFAULT, array()
3315 * Check if there is updates affecting the user for the given course and contexts.
3316 * Right now only modules are supported.
3317 * This WS calls mod_check_updates_since for each module to check if there is any update the user should we aware of.
3319 * @param int $courseid the list of modules to check
3320 * @param array $tocheck the list of modules to check
3321 * @param array $filter check only for updates in these areas
3322 * @return array list of updates and warnings
3323 * @throws moodle_exception
3324 * @since Moodle 3.2
3326 public static function check_updates($courseid, $tocheck, $filter = array()) {
3327 global $CFG, $DB;
3328 require_once($CFG->dirroot . "/course/lib.php");
3330 $params = self::validate_parameters(
3331 self::check_updates_parameters(),
3332 array(
3333 'courseid' => $courseid,
3334 'tocheck' => $tocheck,
3335 'filter' => $filter,
3339 $course = get_course($params['courseid']);
3340 $context = context_course::instance($course->id);
3341 self::validate_context($context);
3343 list($instances, $warnings) = course_check_updates($course, $params['tocheck'], $filter);
3345 $instancesformatted = array();
3346 foreach ($instances as $instance) {
3347 $updates = array();
3348 foreach ($instance['updates'] as $name => $data) {
3349 if (empty($data->updated)) {
3350 continue;
3352 $updatedata = array(
3353 'name' => $name,
3355 if (!empty($data->timeupdated)) {
3356 $updatedata['timeupdated'] = $data->timeupdated;
3358 if (!empty($data->itemids)) {
3359 $updatedata['itemids'] = $data->itemids;
3361 $updates[] = $updatedata;
3363 if (!empty($updates)) {
3364 $instancesformatted[] = array(
3365 'contextlevel' => $instance['contextlevel'],
3366 'id' => $instance['id'],
3367 'updates' => $updates
3372 return array(
3373 'instances' => $instancesformatted,
3374 'warnings' => $warnings
3379 * Returns description of method result value
3381 * @return external_description
3382 * @since Moodle 3.2
3384 public static function check_updates_returns() {
3385 return new external_single_structure(
3386 array(
3387 'instances' => new external_multiple_structure(
3388 new external_single_structure(
3389 array(
3390 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level'),
3391 'id' => new external_value(PARAM_INT, 'Instance id'),
3392 'updates' => new external_multiple_structure(
3393 new external_single_structure(
3394 array(
3395 'name' => new external_value(PARAM_ALPHANUMEXT, 'Name of the area updated.'),
3396 'timeupdated' => new external_value(PARAM_INT, 'Last time was updated', VALUE_OPTIONAL),
3397 'itemids' => new external_multiple_structure(
3398 new external_value(PARAM_INT, 'Instance id'),
3399 'The ids of the items updated',
3400 VALUE_OPTIONAL
3408 'warnings' => new external_warnings()
3414 * Returns description of method parameters
3416 * @return external_function_parameters
3417 * @since Moodle 3.3
3419 public static function get_updates_since_parameters() {
3420 return new external_function_parameters(
3421 array(
3422 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3423 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3424 'filter' => new external_multiple_structure(
3425 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3426 gradeitems, outcomes'),
3427 'Check only for updates in these areas', VALUE_DEFAULT, array()
3434 * Check if there are updates affecting the user for the given course since the given time stamp.
3436 * This function is a wrapper of self::check_updates for retrieving all the updates since a given time for all the activities.
3438 * @param int $courseid the list of modules to check
3439 * @param int $since check updates since this time stamp
3440 * @param array $filter check only for updates in these areas
3441 * @return array list of updates and warnings
3442 * @throws moodle_exception
3443 * @since Moodle 3.3
3445 public static function get_updates_since($courseid, $since, $filter = array()) {
3446 global $CFG, $DB;
3448 $params = self::validate_parameters(
3449 self::get_updates_since_parameters(),
3450 array(
3451 'courseid' => $courseid,
3452 'since' => $since,
3453 'filter' => $filter,
3457 $course = get_course($params['courseid']);
3458 $modinfo = get_fast_modinfo($course);
3459 $tocheck = array();
3461 // Retrieve all the visible course modules for the current user.
3462 $cms = $modinfo->get_cms();
3463 foreach ($cms as $cm) {
3464 if (!$cm->uservisible) {
3465 continue;
3467 $tocheck[] = array(
3468 'id' => $cm->id,
3469 'contextlevel' => 'module',
3470 'since' => $params['since'],
3474 return self::check_updates($course->id, $tocheck, $params['filter']);
3478 * Returns description of method result value
3480 * @return external_description
3481 * @since Moodle 3.3
3483 public static function get_updates_since_returns() {
3484 return self::check_updates_returns();
3488 * Parameters for function edit_module()
3490 * @since Moodle 3.3
3491 * @return external_function_parameters
3493 public static function edit_module_parameters() {
3494 return new external_function_parameters(
3495 array(
3496 'action' => new external_value(PARAM_ALPHA,
3497 'action: hide, show, stealth, duplicate, delete, moveleft, moveright, group...', VALUE_REQUIRED),
3498 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3499 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3504 * Performs one of the edit module actions and return new html for AJAX
3506 * Returns html to replace the current module html with, for example:
3507 * - empty string for "delete" action,
3508 * - two modules html for "duplicate" action
3509 * - updated module html for everything else
3511 * Throws exception if operation is not permitted/possible
3513 * @since Moodle 3.3
3514 * @param string $action
3515 * @param int $id
3516 * @param null|int $sectionreturn
3517 * @return string
3519 public static function edit_module($action, $id, $sectionreturn = null) {
3520 global $PAGE, $DB;
3521 // Validate and normalize parameters.
3522 $params = self::validate_parameters(self::edit_module_parameters(),
3523 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3524 $action = $params['action'];
3525 $id = $params['id'];
3526 $sectionreturn = $params['sectionreturn'];
3528 // Set of permissions an editing user may have.
3529 $contextarray = [
3530 'moodle/course:update',
3531 'moodle/course:manageactivities',
3532 'moodle/course:activityvisibility',
3533 'moodle/course:sectionvisibility',
3534 'moodle/course:movesections',
3535 'moodle/course:setcurrentsection',
3537 $PAGE->set_other_editing_capability($contextarray);
3539 list($course, $cm) = get_course_and_cm_from_cmid($id);
3540 $modcontext = context_module::instance($cm->id);
3541 $coursecontext = context_course::instance($course->id);
3542 self::validate_context($modcontext);
3543 $format = course_get_format($course);
3544 if ($sectionreturn) {
3545 $format->set_section_number($sectionreturn);
3547 $renderer = $format->get_renderer($PAGE);
3549 switch($action) {
3550 case 'hide':
3551 case 'show':
3552 case 'stealth':
3553 require_capability('moodle/course:activityvisibility', $modcontext);
3554 $visible = ($action === 'hide') ? 0 : 1;
3555 $visibleoncoursepage = ($action === 'stealth') ? 0 : 1;
3556 set_coursemodule_visible($id, $visible, $visibleoncoursepage);
3557 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3558 break;
3559 case 'duplicate':
3560 require_capability('moodle/course:manageactivities', $coursecontext);
3561 require_capability('moodle/backup:backuptargetimport', $coursecontext);
3562 require_capability('moodle/restore:restoretargetimport', $coursecontext);
3563 if (!course_allowed_module($course, $cm->modname)) {
3564 throw new moodle_exception('No permission to create that activity');
3566 if ($newcm = duplicate_module($course, $cm)) {
3568 $modinfo = $format->get_modinfo();
3569 $section = $modinfo->get_section_info($newcm->sectionnum);
3570 $cm = $modinfo->get_cm($id);
3572 // Get both original and new element html.
3573 $result = $renderer->course_section_updated_cm_item($format, $section, $cm);
3574 $result .= $renderer->course_section_updated_cm_item($format, $section, $newcm);
3575 return $result;
3577 break;
3578 case 'groupsseparate':
3579 case 'groupsvisible':
3580 case 'groupsnone':
3581 require_capability('moodle/course:manageactivities', $modcontext);
3582 if ($action === 'groupsseparate') {
3583 $newgroupmode = SEPARATEGROUPS;
3584 } else if ($action === 'groupsvisible') {
3585 $newgroupmode = VISIBLEGROUPS;
3586 } else {
3587 $newgroupmode = NOGROUPS;
3589 if (set_coursemodule_groupmode($cm->id, $newgroupmode)) {
3590 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3592 break;
3593 case 'moveleft':
3594 case 'moveright':
3595 require_capability('moodle/course:manageactivities', $modcontext);
3596 $indent = $cm->indent + (($action === 'moveright') ? 1 : -1);
3597 if ($cm->indent >= 0) {
3598 $DB->update_record('course_modules', array('id' => $cm->id, 'indent' => $indent));
3599 rebuild_course_cache($cm->course);
3601 break;
3602 case 'delete':
3603 require_capability('moodle/course:manageactivities', $modcontext);
3604 course_delete_module($cm->id, true);
3605 return '';
3606 default:
3607 throw new coding_exception('Unrecognised action');
3610 $modinfo = $format->get_modinfo();
3611 $section = $modinfo->get_section_info($cm->sectionnum);
3612 $cm = $modinfo->get_cm($id);
3613 return $renderer->course_section_updated_cm_item($format, $section, $cm);
3617 * Return structure for edit_module()
3619 * @since Moodle 3.3
3620 * @return external_description
3622 public static function edit_module_returns() {
3623 return new external_value(PARAM_RAW, 'html to replace the current module with');
3627 * Parameters for function get_module()
3629 * @since Moodle 3.3
3630 * @return external_function_parameters
3632 public static function get_module_parameters() {
3633 return new external_function_parameters(
3634 array(
3635 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3636 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3641 * Returns html for displaying one activity module on course page
3643 * @since Moodle 3.3
3644 * @param int $id
3645 * @param null|int $sectionreturn
3646 * @return string
3648 public static function get_module($id, $sectionreturn = null) {
3649 global $PAGE;
3650 // Validate and normalize parameters.
3651 $params = self::validate_parameters(self::get_module_parameters(),
3652 array('id' => $id, 'sectionreturn' => $sectionreturn));
3653 $id = $params['id'];
3654 $sectionreturn = $params['sectionreturn'];
3656 // Set of permissions an editing user may have.
3657 $contextarray = [
3658 'moodle/course:update',
3659 'moodle/course:manageactivities',
3660 'moodle/course:activityvisibility',
3661 'moodle/course:sectionvisibility',
3662 'moodle/course:movesections',
3663 'moodle/course:setcurrentsection',
3665 $PAGE->set_other_editing_capability($contextarray);
3667 // Validate access to the course (note, this is html for the course view page, we don't validate access to the module).
3668 list($course, $cm) = get_course_and_cm_from_cmid($id);
3669 self::validate_context(context_course::instance($course->id));
3671 $format = course_get_format($course);
3672 if ($sectionreturn) {
3673 $format->set_section_number($sectionreturn);
3675 $renderer = $format->get_renderer($PAGE);
3677 $modinfo = $format->get_modinfo();
3678 $section = $modinfo->get_section_info($cm->sectionnum);
3679 return $renderer->course_section_updated_cm_item($format, $section, $cm);
3683 * Return structure for get_module()
3685 * @since Moodle 3.3
3686 * @return external_description
3688 public static function get_module_returns() {
3689 return new external_value(PARAM_RAW, 'html to replace the current module with');
3693 * Parameters for function edit_section()
3695 * @since Moodle 3.3
3696 * @return external_function_parameters
3698 public static function edit_section_parameters() {
3699 return new external_function_parameters(
3700 array(
3701 'action' => new external_value(PARAM_ALPHA, 'action: hide, show, stealth, setmarker, removemarker', VALUE_REQUIRED),
3702 'id' => new external_value(PARAM_INT, 'course section id', VALUE_REQUIRED),
3703 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3708 * Performs one of the edit section actions
3710 * @since Moodle 3.3
3711 * @param string $action
3712 * @param int $id section id
3713 * @param int $sectionreturn section to return to
3714 * @return string
3716 public static function edit_section($action, $id, $sectionreturn) {
3717 global $DB;
3718 // Validate and normalize parameters.
3719 $params = self::validate_parameters(self::edit_section_parameters(),
3720 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3721 $action = $params['action'];
3722 $id = $params['id'];
3723 $sr = $params['sectionreturn'];
3725 $section = $DB->get_record('course_sections', array('id' => $id), '*', MUST_EXIST);
3726 $coursecontext = context_course::instance($section->course);
3727 self::validate_context($coursecontext);
3729 $rv = course_get_format($section->course)->section_action($section, $action, $sectionreturn);
3730 if ($rv) {
3731 return json_encode($rv);
3732 } else {
3733 return null;
3738 * Return structure for edit_section()
3740 * @since Moodle 3.3
3741 * @return external_description
3743 public static function edit_section_returns() {
3744 return new external_value(PARAM_RAW, 'Additional data for javascript (JSON-encoded string)');
3748 * Returns description of method parameters
3750 * @return external_function_parameters
3752 public static function get_enrolled_courses_by_timeline_classification_parameters() {
3753 return new external_function_parameters(
3754 array(
3755 'classification' => new external_value(PARAM_ALPHA, 'future, inprogress, or past'),
3756 'limit' => new external_value(PARAM_INT, 'Result set limit', VALUE_DEFAULT, 0),
3757 'offset' => new external_value(PARAM_INT, 'Result set offset', VALUE_DEFAULT, 0),
3758 'sort' => new external_value(PARAM_TEXT, 'Sort string', VALUE_DEFAULT, null),
3759 'customfieldname' => new external_value(PARAM_ALPHANUMEXT, 'Used when classification = customfield',
3760 VALUE_DEFAULT, null),
3761 'customfieldvalue' => new external_value(PARAM_RAW, 'Used when classification = customfield',
3762 VALUE_DEFAULT, null),
3763 'searchvalue' => new external_value(PARAM_TEXT, 'The value a user wishes to search against',
3764 VALUE_DEFAULT, null),
3770 * Get courses matching the given timeline classification.
3772 * NOTE: The offset applies to the unfiltered full set of courses before the classification
3773 * filtering is done.
3774 * E.g.
3775 * If the user is enrolled in 5 courses:
3776 * c1, c2, c3, c4, and c5
3777 * And c4 and c5 are 'future' courses
3779 * If a request comes in for future courses with an offset of 1 it will mean that
3780 * c1 is skipped (because the offset applies *before* the classification filtering)
3781 * and c4 and c5 will be return.
3783 * @param string $classification past, inprogress, or future
3784 * @param int $limit Result set limit
3785 * @param int $offset Offset the full course set before timeline classification is applied
3786 * @param string $sort SQL sort string for results
3787 * @param string $customfieldname
3788 * @param string $customfieldvalue
3789 * @param string $searchvalue
3790 * @return array list of courses and warnings
3791 * @throws invalid_parameter_exception
3793 public static function get_enrolled_courses_by_timeline_classification(
3794 string $classification,
3795 int $limit = 0,
3796 int $offset = 0,
3797 string $sort = null,
3798 string $customfieldname = null,
3799 string $customfieldvalue = null,
3800 string $searchvalue = null
3802 global $CFG, $PAGE, $USER;
3803 require_once($CFG->dirroot . '/course/lib.php');
3805 $params = self::validate_parameters(self::get_enrolled_courses_by_timeline_classification_parameters(),
3806 array(
3807 'classification' => $classification,
3808 'limit' => $limit,
3809 'offset' => $offset,
3810 'sort' => $sort,
3811 'customfieldvalue' => $customfieldvalue,
3812 'searchvalue' => $searchvalue,
3816 $classification = $params['classification'];
3817 $limit = $params['limit'];
3818 $offset = $params['offset'];
3819 $sort = $params['sort'];
3820 $customfieldvalue = $params['customfieldvalue'];
3821 $searchvalue = $params['searchvalue'];
3823 switch($classification) {
3824 case COURSE_TIMELINE_ALLINCLUDINGHIDDEN:
3825 break;
3826 case COURSE_TIMELINE_ALL:
3827 break;
3828 case COURSE_TIMELINE_PAST:
3829 break;
3830 case COURSE_TIMELINE_INPROGRESS:
3831 break;
3832 case COURSE_TIMELINE_FUTURE:
3833 break;
3834 case COURSE_FAVOURITES:
3835 break;
3836 case COURSE_TIMELINE_HIDDEN:
3837 break;
3838 case COURSE_TIMELINE_SEARCH:
3839 break;
3840 case COURSE_CUSTOMFIELD:
3841 break;
3842 default:
3843 throw new invalid_parameter_exception('Invalid classification');
3846 self::validate_context(context_user::instance($USER->id));
3848 $requiredproperties = course_summary_exporter::define_properties();
3849 $fields = join(',', array_keys($requiredproperties));
3850 $hiddencourses = get_hidden_courses_on_timeline();
3851 $courses = [];
3853 // If the timeline requires really all courses, get really all courses.
3854 if ($classification == COURSE_TIMELINE_ALLINCLUDINGHIDDEN) {
3855 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields, COURSE_DB_QUERY_LIMIT);
3857 // Otherwise if the timeline requires the hidden courses then restrict the result to only $hiddencourses.
3858 } else if ($classification == COURSE_TIMELINE_HIDDEN) {
3859 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields,
3860 COURSE_DB_QUERY_LIMIT, $hiddencourses);
3862 // Otherwise get the requested courses and exclude the hidden courses.
3863 } else if ($classification == COURSE_TIMELINE_SEARCH) {
3864 // Prepare the search API options.
3865 $searchcriteria['search'] = $searchvalue;
3866 $options = ['idonly' => true];
3867 $courses = course_get_enrolled_courses_for_logged_in_user_from_search(
3869 $offset,
3870 $sort,
3871 $fields,
3872 COURSE_DB_QUERY_LIMIT,
3873 $searchcriteria,
3874 $options
3876 } else {
3877 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields,
3878 COURSE_DB_QUERY_LIMIT, [], $hiddencourses);
3881 $favouritecourseids = [];
3882 $ufservice = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($USER->id));
3883 $favourites = $ufservice->find_favourites_by_type('core_course', 'courses');
3885 if ($favourites) {
3886 $favouritecourseids = array_map(
3887 function($favourite) {
3888 return $favourite->itemid;
3889 }, $favourites);
3892 if ($classification == COURSE_FAVOURITES) {
3893 list($filteredcourses, $processedcount) = course_filter_courses_by_favourites(
3894 $courses,
3895 $favouritecourseids,
3896 $limit
3898 } else if ($classification == COURSE_CUSTOMFIELD) {
3899 list($filteredcourses, $processedcount) = course_filter_courses_by_customfield(
3900 $courses,
3901 $customfieldname,
3902 $customfieldvalue,
3903 $limit
3905 } else {
3906 list($filteredcourses, $processedcount) = course_filter_courses_by_timeline_classification(
3907 $courses,
3908 $classification,
3909 $limit
3913 $renderer = $PAGE->get_renderer('core');
3914 $formattedcourses = array_map(function($course) use ($renderer, $favouritecourseids) {
3915 if ($course == null) {
3916 return;
3918 context_helper::preload_from_record($course);
3919 $context = context_course::instance($course->id);
3920 $isfavourite = false;
3921 if (in_array($course->id, $favouritecourseids)) {
3922 $isfavourite = true;
3924 $exporter = new course_summary_exporter($course, ['context' => $context, 'isfavourite' => $isfavourite]);
3925 return $exporter->export($renderer);
3926 }, $filteredcourses);
3928 $formattedcourses = array_filter($formattedcourses, function($course) {
3929 if ($course != null) {
3930 return $course;
3934 return [
3935 'courses' => $formattedcourses,
3936 'nextoffset' => $offset + $processedcount
3941 * Returns description of method result value
3943 * @return external_description
3945 public static function get_enrolled_courses_by_timeline_classification_returns() {
3946 return new external_single_structure(
3947 array(
3948 'courses' => new external_multiple_structure(course_summary_exporter::get_read_structure(), 'Course'),
3949 'nextoffset' => new external_value(PARAM_INT, 'Offset for the next request')
3955 * Returns description of method parameters
3957 * @return external_function_parameters
3959 public static function set_favourite_courses_parameters() {
3960 return new external_function_parameters(
3961 array(
3962 'courses' => new external_multiple_structure(
3963 new external_single_structure(
3964 array(
3965 'id' => new external_value(PARAM_INT, 'course ID'),
3966 'favourite' => new external_value(PARAM_BOOL, 'favourite status')
3975 * Set the course favourite status for an array of courses.
3977 * @param array $courses List with course id's and favourite status.
3978 * @return array Array with an array of favourite courses.
3980 public static function set_favourite_courses(
3981 array $courses
3983 global $USER;
3985 $params = self::validate_parameters(self::set_favourite_courses_parameters(),
3986 array(
3987 'courses' => $courses
3991 $warnings = [];
3993 $ufservice = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($USER->id));
3995 foreach ($params['courses'] as $course) {
3997 $warning = [];
3999 $favouriteexists = $ufservice->favourite_exists('core_course', 'courses', $course['id'],
4000 \context_course::instance($course['id']));
4002 if ($course['favourite']) {
4003 if (!$favouriteexists) {
4004 try {
4005 $ufservice->create_favourite('core_course', 'courses', $course['id'],
4006 \context_course::instance($course['id']));
4007 } catch (Exception $e) {
4008 $warning['courseid'] = $course['id'];
4009 if ($e instanceof moodle_exception) {
4010 $warning['warningcode'] = $e->errorcode;
4011 } else {
4012 $warning['warningcode'] = $e->getCode();
4014 $warning['message'] = $e->getMessage();
4015 $warnings[] = $warning;
4016 $warnings[] = $warning;
4018 } else {
4019 $warning['courseid'] = $course['id'];
4020 $warning['warningcode'] = 'coursealreadyfavourited';
4021 $warning['message'] = 'Course already favourited';
4022 $warnings[] = $warning;
4024 } else {
4025 if ($favouriteexists) {
4026 try {
4027 $ufservice->delete_favourite('core_course', 'courses', $course['id'],
4028 \context_course::instance($course['id']));
4029 } catch (Exception $e) {
4030 $warning['courseid'] = $course['id'];
4031 if ($e instanceof moodle_exception) {
4032 $warning['warningcode'] = $e->errorcode;
4033 } else {
4034 $warning['warningcode'] = $e->getCode();
4036 $warning['message'] = $e->getMessage();
4037 $warnings[] = $warning;
4038 $warnings[] = $warning;
4040 } else {
4041 $warning['courseid'] = $course['id'];
4042 $warning['warningcode'] = 'cannotdeletefavourite';
4043 $warning['message'] = 'Could not delete favourite status for course';
4044 $warnings[] = $warning;
4049 return [
4050 'warnings' => $warnings
4055 * Returns description of method result value
4057 * @return external_description
4059 public static function set_favourite_courses_returns() {
4060 return new external_single_structure(
4061 array(
4062 'warnings' => new external_warnings()
4068 * Returns description of method parameters
4070 * @return external_function_parameters
4071 * @since Moodle 3.6
4073 public static function get_recent_courses_parameters() {
4074 return new external_function_parameters(
4075 array(
4076 'userid' => new external_value(PARAM_INT, 'id of the user, default to current user', VALUE_DEFAULT, 0),
4077 'limit' => new external_value(PARAM_INT, 'result set limit', VALUE_DEFAULT, 0),
4078 'offset' => new external_value(PARAM_INT, 'Result set offset', VALUE_DEFAULT, 0),
4079 'sort' => new external_value(PARAM_TEXT, 'Sort string', VALUE_DEFAULT, null)
4085 * Get last accessed courses adding additional course information like images.
4087 * @param int $userid User id from which the courses will be obtained
4088 * @param int $limit Restrict result set to this amount
4089 * @param int $offset Skip this number of records from the start of the result set
4090 * @param string|null $sort SQL string for sorting
4091 * @return array List of courses
4092 * @throws invalid_parameter_exception
4094 public static function get_recent_courses(int $userid = 0, int $limit = 0, int $offset = 0, string $sort = null) {
4095 global $USER, $PAGE;
4097 if (empty($userid)) {
4098 $userid = $USER->id;
4101 $params = self::validate_parameters(self::get_recent_courses_parameters(),
4102 array(
4103 'userid' => $userid,
4104 'limit' => $limit,
4105 'offset' => $offset,
4106 'sort' => $sort
4110 $userid = $params['userid'];
4111 $limit = $params['limit'];
4112 $offset = $params['offset'];
4113 $sort = $params['sort'];
4115 $usercontext = context_user::instance($userid);
4117 self::validate_context($usercontext);
4119 if ($userid != $USER->id and !has_capability('moodle/user:viewdetails', $usercontext)) {
4120 return array();
4123 $courses = course_get_recent_courses($userid, $limit, $offset, $sort);
4125 $renderer = $PAGE->get_renderer('core');
4127 $recentcourses = array_map(function($course) use ($renderer) {
4128 context_helper::preload_from_record($course);
4129 $context = context_course::instance($course->id);
4130 $isfavourite = !empty($course->component);
4131 $exporter = new course_summary_exporter($course, ['context' => $context, 'isfavourite' => $isfavourite]);
4132 return $exporter->export($renderer);
4133 }, $courses);
4135 return $recentcourses;
4139 * Returns description of method result value
4141 * @return external_description
4142 * @since Moodle 3.6
4144 public static function get_recent_courses_returns() {
4145 return new external_multiple_structure(course_summary_exporter::get_read_structure(), 'Courses');
4149 * Returns description of method parameters
4151 * @return external_function_parameters
4153 public static function get_enrolled_users_by_cmid_parameters() {
4154 return new external_function_parameters([
4155 'cmid' => new external_value(PARAM_INT, 'id of the course module', VALUE_REQUIRED),
4156 'groupid' => new external_value(PARAM_INT, 'id of the group', VALUE_DEFAULT, 0),
4161 * Get all users in a course for a given cmid.
4163 * @param int $cmid Course Module id from which the users will be obtained
4164 * @param int $groupid Group id from which the users will be obtained
4165 * @return array List of users
4166 * @throws invalid_parameter_exception
4168 public static function get_enrolled_users_by_cmid(int $cmid, int $groupid = 0) {
4169 global $PAGE;
4170 $warnings = [];
4173 'cmid' => $cmid,
4174 'groupid' => $groupid,
4175 ] = self::validate_parameters(self::get_enrolled_users_by_cmid_parameters(), [
4176 'cmid' => $cmid,
4177 'groupid' => $groupid,
4180 list($course, $cm) = get_course_and_cm_from_cmid($cmid);
4181 $coursecontext = context_course::instance($course->id);
4182 self::validate_context($coursecontext);
4184 $enrolledusers = get_enrolled_users($coursecontext, '', $groupid);
4186 $users = array_map(function ($user) use ($PAGE) {
4187 $user->fullname = fullname($user);
4188 $userpicture = new user_picture($user);
4189 $userpicture->size = 1;
4190 $user->profileimage = $userpicture->get_url($PAGE)->out(false);
4191 return $user;
4192 }, $enrolledusers);
4193 sort($users);
4195 return [
4196 'users' => $users,
4197 'warnings' => $warnings,
4202 * Returns description of method result value
4204 * @return external_description
4206 public static function get_enrolled_users_by_cmid_returns() {
4207 return new external_single_structure([
4208 'users' => new external_multiple_structure(self::user_description()),
4209 'warnings' => new external_warnings(),
4214 * Create user return value description.
4216 * @return external_description
4218 public static function user_description() {
4219 $userfields = array(
4220 'id' => new external_value(core_user::get_property_type('id'), 'ID of the user'),
4221 'profileimage' => new external_value(PARAM_URL, 'The location of the users larger image', VALUE_OPTIONAL),
4222 'fullname' => new external_value(PARAM_TEXT, 'The full name of the user', VALUE_OPTIONAL),
4223 'firstname' => new external_value(
4224 core_user::get_property_type('firstname'),
4225 'The first name(s) of the user',
4226 VALUE_OPTIONAL),
4227 'lastname' => new external_value(
4228 core_user::get_property_type('lastname'),
4229 'The family name of the user',
4230 VALUE_OPTIONAL),
4232 return new external_single_structure($userfields);
4236 * Returns description of method parameters.
4238 * @return external_function_parameters
4240 public static function add_content_item_to_user_favourites_parameters() {
4241 return new external_function_parameters([
4242 'componentname' => new external_value(PARAM_TEXT,
4243 'frankenstyle name of the component to which the content item belongs', VALUE_REQUIRED),
4244 'contentitemid' => new external_value(PARAM_INT, 'id of the content item', VALUE_REQUIRED, '', NULL_NOT_ALLOWED)
4249 * Add a content item to a user's favourites.
4251 * @param string $componentname the name of the component from which this content item originates.
4252 * @param int $contentitemid the id of the content item.
4253 * @return stdClass the exporter content item.
4255 public static function add_content_item_to_user_favourites(string $componentname, int $contentitemid) {
4256 global $USER;
4259 'componentname' => $componentname,
4260 'contentitemid' => $contentitemid,
4261 ] = self::validate_parameters(self::add_content_item_to_user_favourites_parameters(),
4263 'componentname' => $componentname,
4264 'contentitemid' => $contentitemid,
4268 self::validate_context(context_user::instance($USER->id));
4270 $contentitemservice = \core_course\local\factory\content_item_service_factory::get_content_item_service();
4272 return $contentitemservice->add_to_user_favourites($USER, $componentname, $contentitemid);
4276 * Returns description of method result value.
4278 * @return external_description
4280 public static function add_content_item_to_user_favourites_returns() {
4281 return \core_course\local\exporters\course_content_item_exporter::get_read_structure();
4285 * Returns description of method parameters.
4287 * @return external_function_parameters
4289 public static function remove_content_item_from_user_favourites_parameters() {
4290 return new external_function_parameters([
4291 'componentname' => new external_value(PARAM_TEXT,
4292 'frankenstyle name of the component to which the content item belongs', VALUE_REQUIRED),
4293 'contentitemid' => new external_value(PARAM_INT, 'id of the content item', VALUE_REQUIRED, '', NULL_NOT_ALLOWED),
4298 * Remove a content item from a user's favourites.
4300 * @param string $componentname the name of the component from which this content item originates.
4301 * @param int $contentitemid the id of the content item.
4302 * @return stdClass the exported content item.
4304 public static function remove_content_item_from_user_favourites(string $componentname, int $contentitemid) {
4305 global $USER;
4308 'componentname' => $componentname,
4309 'contentitemid' => $contentitemid,
4310 ] = self::validate_parameters(self::remove_content_item_from_user_favourites_parameters(),
4312 'componentname' => $componentname,
4313 'contentitemid' => $contentitemid,
4317 self::validate_context(context_user::instance($USER->id));
4319 $contentitemservice = \core_course\local\factory\content_item_service_factory::get_content_item_service();
4321 return $contentitemservice->remove_from_user_favourites($USER, $componentname, $contentitemid);
4325 * Returns description of method result value.
4327 * @return external_description
4329 public static function remove_content_item_from_user_favourites_returns() {
4330 return \core_course\local\exporters\course_content_item_exporter::get_read_structure();
4334 * Returns description of method result value
4336 * @return external_description
4338 public static function get_course_content_items_returns() {
4339 return new external_single_structure([
4340 'content_items' => new external_multiple_structure(
4341 \core_course\local\exporters\course_content_item_exporter::get_read_structure()
4347 * Returns description of method parameters
4349 * @return external_function_parameters
4351 public static function get_course_content_items_parameters() {
4352 return new external_function_parameters([
4353 'courseid' => new external_value(PARAM_INT, 'ID of the course', VALUE_REQUIRED),
4358 * Given a course ID fetch all accessible modules for that course
4360 * @param int $courseid The course we want to fetch the modules for
4361 * @return array Contains array of modules and their metadata
4363 public static function get_course_content_items(int $courseid) {
4364 global $USER;
4367 'courseid' => $courseid,
4368 ] = self::validate_parameters(self::get_course_content_items_parameters(), [
4369 'courseid' => $courseid,
4372 $coursecontext = context_course::instance($courseid);
4373 self::validate_context($coursecontext);
4374 $course = get_course($courseid);
4376 $contentitemservice = \core_course\local\factory\content_item_service_factory::get_content_item_service();
4378 $contentitems = $contentitemservice->get_content_items_for_user_in_course($USER, $course);
4379 return ['content_items' => $contentitems];
4383 * Returns description of method parameters.
4385 * @return external_function_parameters
4387 public static function toggle_activity_recommendation_parameters() {
4388 return new external_function_parameters([
4389 'area' => new external_value(PARAM_TEXT, 'The favourite area (itemtype)', VALUE_REQUIRED),
4390 'id' => new external_value(PARAM_INT, 'id of the activity or whatever', VALUE_REQUIRED),
4395 * Update the recommendation for an activity item.
4397 * @param string $area identifier for this activity.
4398 * @param int $id Associated id. This is needed in conjunction with the area to find the recommendation.
4399 * @return array some warnings or something.
4401 public static function toggle_activity_recommendation(string $area, int $id): array {
4402 ['area' => $area, 'id' => $id] = self::validate_parameters(self::toggle_activity_recommendation_parameters(),
4403 ['area' => $area, 'id' => $id]);
4405 $context = context_system::instance();
4406 self::validate_context($context);
4408 require_capability('moodle/course:recommendactivity', $context);
4410 $manager = \core_course\local\factory\content_item_service_factory::get_content_item_service();
4412 $status = $manager->toggle_recommendation($area, $id);
4413 return ['id' => $id, 'area' => $area, 'status' => $status];
4417 * Returns warnings.
4419 * @return external_description
4421 public static function toggle_activity_recommendation_returns() {
4422 return new external_single_structure(
4424 'id' => new external_value(PARAM_INT, 'id of the activity or whatever'),
4425 'area' => new external_value(PARAM_TEXT, 'The favourite area (itemtype)'),
4426 'status' => new external_value(PARAM_BOOL, 'If created or deleted'),
4432 * Returns description of method parameters
4434 * @return external_function_parameters
4436 public static function get_activity_chooser_footer_parameters() {
4437 return new external_function_parameters([
4438 'courseid' => new external_value(PARAM_INT, 'ID of the course', VALUE_REQUIRED),
4439 'sectionid' => new external_value(PARAM_INT, 'ID of the section', VALUE_REQUIRED),
4444 * Given a course ID we need to build up a footre for the chooser.
4446 * @param int $courseid The course we want to fetch the modules for
4447 * @param int $sectionid The section we want to fetch the modules for
4448 * @return array
4450 public static function get_activity_chooser_footer(int $courseid, int $sectionid) {
4452 'courseid' => $courseid,
4453 'sectionid' => $sectionid,
4454 ] = self::validate_parameters(self::get_activity_chooser_footer_parameters(), [
4455 'courseid' => $courseid,
4456 'sectionid' => $sectionid,
4459 $coursecontext = context_course::instance($courseid);
4460 self::validate_context($coursecontext);
4462 $activeplugin = get_config('core', 'activitychooseractivefooter');
4464 if ($activeplugin !== COURSE_CHOOSER_FOOTER_NONE) {
4465 $footerdata = component_callback($activeplugin, 'custom_chooser_footer', [$courseid, $sectionid]);
4466 return [
4467 'footer' => true,
4468 'customfooterjs' => $footerdata->get_footer_js_file(),
4469 'customfootertemplate' => $footerdata->get_footer_template(),
4470 'customcarouseltemplate' => $footerdata->get_carousel_template(),
4472 } else {
4473 return [
4474 'footer' => false,
4480 * Returns description of method result value
4482 * @return external_description
4484 public static function get_activity_chooser_footer_returns() {
4485 return new external_single_structure(
4487 'footer' => new external_value(PARAM_BOOL, 'Is a footer being return by this request?', VALUE_REQUIRED),
4488 'customfooterjs' => new external_value(PARAM_RAW, 'The path to the plugin JS file', VALUE_OPTIONAL),
4489 'customfootertemplate' => new external_value(PARAM_RAW, 'The prerendered footer', VALUE_OPTIONAL),
4490 'customcarouseltemplate' => new external_value(PARAM_RAW, 'Either "" or the prerendered carousel page',
4491 VALUE_OPTIONAL),