MDL-71305 core_question: Use toggle button for flag question element
[moodle.git] / course / externallib.php
blob2ed81936116930c553c240f29388a15270879865
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];
392 if (!$courseformat->is_section_visible($section)) {
393 unset($coursecontents[$sectionnumber]);
394 continue;
397 // Remove section and modules information if the section is not visible for the user.
398 if (!$section->uservisible) {
399 $coursecontents[$sectionnumber]['modules'] = array();
400 // Remove summary information if the section is completely hidden only,
401 // even if the section is not user visible, the summary is always displayed among the availability information.
402 if (!$section->visible) {
403 $coursecontents[$sectionnumber]['summary'] = '';
408 // Include stealth modules in special section (without any info).
409 if (!empty($stealthmodules)) {
410 $coursecontents[] = array(
411 'id' => -1,
412 'name' => '',
413 'summary' => '',
414 'summaryformat' => FORMAT_MOODLE,
415 'modules' => $stealthmodules
420 return $coursecontents;
424 * Returns description of method result value
426 * @return external_description
427 * @since Moodle 2.2
429 public static function get_course_contents_returns() {
430 $completiondefinition = \core_completion\external\completion_info_exporter::get_read_structure(VALUE_DEFAULT, []);
432 return new external_multiple_structure(
433 new external_single_structure(
434 array(
435 'id' => new external_value(PARAM_INT, 'Section ID'),
436 'name' => new external_value(PARAM_RAW, 'Section name'),
437 'visible' => new external_value(PARAM_INT, 'is the section visible', VALUE_OPTIONAL),
438 'summary' => new external_value(PARAM_RAW, 'Section description'),
439 'summaryformat' => new external_format_value('summary'),
440 'section' => new external_value(PARAM_INT, 'Section number inside the course', VALUE_OPTIONAL),
441 'hiddenbynumsections' => new external_value(PARAM_INT, 'Whether is a section hidden in the course format',
442 VALUE_OPTIONAL),
443 'uservisible' => new external_value(PARAM_BOOL, 'Is the section visible for the user?', VALUE_OPTIONAL),
444 'availabilityinfo' => new external_value(PARAM_RAW, 'Availability information.', VALUE_OPTIONAL),
445 'modules' => new external_multiple_structure(
446 new external_single_structure(
447 array(
448 'id' => new external_value(PARAM_INT, 'activity id'),
449 'url' => new external_value(PARAM_URL, 'activity url', VALUE_OPTIONAL),
450 'name' => new external_value(PARAM_RAW, 'activity module name'),
451 'instance' => new external_value(PARAM_INT, 'instance id', VALUE_OPTIONAL),
452 'contextid' => new external_value(PARAM_INT, 'Activity context id.', VALUE_OPTIONAL),
453 'description' => new external_value(PARAM_RAW, 'activity description', VALUE_OPTIONAL),
454 'visible' => new external_value(PARAM_INT, 'is the module visible', VALUE_OPTIONAL),
455 'uservisible' => new external_value(PARAM_BOOL, 'Is the module visible for the user?',
456 VALUE_OPTIONAL),
457 'availabilityinfo' => new external_value(PARAM_RAW, 'Availability information.',
458 VALUE_OPTIONAL),
459 'visibleoncoursepage' => new external_value(PARAM_INT, 'is the module visible on course page',
460 VALUE_OPTIONAL),
461 'modicon' => new external_value(PARAM_URL, 'activity icon url'),
462 'modname' => new external_value(PARAM_PLUGIN, 'activity module type'),
463 'modplural' => new external_value(PARAM_TEXT, 'activity module plural name'),
464 'availability' => new external_value(PARAM_RAW, 'module availability settings', VALUE_OPTIONAL),
465 'indent' => new external_value(PARAM_INT, 'number of identation in the site'),
466 'onclick' => new external_value(PARAM_RAW, 'Onclick action.', VALUE_OPTIONAL),
467 'afterlink' => new external_value(PARAM_RAW, 'After link info to be displayed.',
468 VALUE_OPTIONAL),
469 'customdata' => new external_value(PARAM_RAW, 'Custom data (JSON encoded).', VALUE_OPTIONAL),
470 'noviewlink' => new external_value(PARAM_BOOL, 'Whether the module has no view page',
471 VALUE_OPTIONAL),
472 'completion' => new external_value(PARAM_INT, 'Type of completion tracking:
473 0 means none, 1 manual, 2 automatic.', VALUE_OPTIONAL),
474 'completiondata' => $completiondefinition,
475 'downloadcontent' => new external_value(PARAM_INT, 'The download content value', VALUE_OPTIONAL),
476 'dates' => new external_multiple_structure(
477 new external_single_structure(
478 array(
479 'label' => new external_value(PARAM_TEXT, 'date label'),
480 'timestamp' => new external_value(PARAM_INT, 'date timestamp'),
483 VALUE_DEFAULT,
486 'contents' => new external_multiple_structure(
487 new external_single_structure(
488 array(
489 // content info
490 'type'=> new external_value(PARAM_TEXT, 'a file or a folder or external link'),
491 'filename'=> new external_value(PARAM_FILE, 'filename'),
492 'filepath'=> new external_value(PARAM_PATH, 'filepath'),
493 'filesize'=> new external_value(PARAM_INT, 'filesize'),
494 'fileurl' => new external_value(PARAM_URL, 'downloadable file url', VALUE_OPTIONAL),
495 'content' => new external_value(PARAM_RAW, 'Raw content, will be used when type is content', VALUE_OPTIONAL),
496 'timecreated' => new external_value(PARAM_INT, 'Time created'),
497 'timemodified' => new external_value(PARAM_INT, 'Time modified'),
498 'sortorder' => new external_value(PARAM_INT, 'Content sort order'),
499 'mimetype' => new external_value(PARAM_RAW, 'File mime type.', VALUE_OPTIONAL),
500 'isexternalfile' => new external_value(PARAM_BOOL, 'Whether is an external file.',
501 VALUE_OPTIONAL),
502 'repositorytype' => new external_value(PARAM_PLUGIN, 'The repository type for external files.',
503 VALUE_OPTIONAL),
505 // copyright related info
506 'userid' => new external_value(PARAM_INT, 'User who added this content to moodle'),
507 'author' => new external_value(PARAM_TEXT, 'Content owner'),
508 'license' => new external_value(PARAM_TEXT, 'Content license'),
509 'tags' => new external_multiple_structure(
510 \core_tag\external\tag_item_exporter::get_read_structure(), 'Tags',
511 VALUE_OPTIONAL
514 ), VALUE_DEFAULT, array()
516 'contentsinfo' => new external_single_structure(
517 array(
518 'filescount' => new external_value(PARAM_INT, 'Total number of files.'),
519 'filessize' => new external_value(PARAM_INT, 'Total files size.'),
520 'lastmodified' => new external_value(PARAM_INT, 'Last time files were modified.'),
521 'mimetypes' => new external_multiple_structure(
522 new external_value(PARAM_RAW, 'File mime type.'),
523 'Files mime types.'
525 'repositorytype' => new external_value(PARAM_PLUGIN, 'The repository type for
526 the main file.', VALUE_OPTIONAL),
527 ), 'Contents summary information.', VALUE_OPTIONAL
530 ), 'list of module'
538 * Returns description of method parameters
540 * @return external_function_parameters
541 * @since Moodle 2.3
543 public static function get_courses_parameters() {
544 return new external_function_parameters(
545 array('options' => new external_single_structure(
546 array('ids' => new external_multiple_structure(
547 new external_value(PARAM_INT, 'Course id')
548 , 'List of course id. If empty return all courses
549 except front page course.',
550 VALUE_OPTIONAL)
551 ), 'options - operator OR is used', VALUE_DEFAULT, array())
557 * Get courses
559 * @param array $options It contains an array (list of ids)
560 * @return array
561 * @since Moodle 2.2
563 public static function get_courses($options = array()) {
564 global $CFG, $DB;
565 require_once($CFG->dirroot . "/course/lib.php");
567 //validate parameter
568 $params = self::validate_parameters(self::get_courses_parameters(),
569 array('options' => $options));
571 //retrieve courses
572 if (!array_key_exists('ids', $params['options'])
573 or empty($params['options']['ids'])) {
574 $courses = $DB->get_records('course');
575 } else {
576 $courses = $DB->get_records_list('course', 'id', $params['options']['ids']);
579 //create return value
580 $coursesinfo = array();
581 foreach ($courses as $course) {
583 // now security checks
584 $context = context_course::instance($course->id, IGNORE_MISSING);
585 $courseformatoptions = course_get_format($course)->get_format_options();
586 try {
587 self::validate_context($context);
588 } catch (Exception $e) {
589 $exceptionparam = new stdClass();
590 $exceptionparam->message = $e->getMessage();
591 $exceptionparam->courseid = $course->id;
592 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
594 if ($course->id != SITEID) {
595 require_capability('moodle/course:view', $context);
598 $courseinfo = array();
599 $courseinfo['id'] = $course->id;
600 $courseinfo['fullname'] = external_format_string($course->fullname, $context->id);
601 $courseinfo['shortname'] = external_format_string($course->shortname, $context->id);
602 $courseinfo['displayname'] = external_format_string(get_course_display_name_for_list($course), $context->id);
603 $courseinfo['categoryid'] = $course->category;
604 list($courseinfo['summary'], $courseinfo['summaryformat']) =
605 external_format_text($course->summary, $course->summaryformat, $context->id, 'course', 'summary', 0);
606 $courseinfo['format'] = $course->format;
607 $courseinfo['startdate'] = $course->startdate;
608 $courseinfo['enddate'] = $course->enddate;
609 $courseinfo['showactivitydates'] = $course->showactivitydates;
610 $courseinfo['showcompletionconditions'] = $course->showcompletionconditions;
611 if (array_key_exists('numsections', $courseformatoptions)) {
612 // For backward-compartibility
613 $courseinfo['numsections'] = $courseformatoptions['numsections'];
616 $handler = core_course\customfield\course_handler::create();
617 if ($customfields = $handler->export_instance_data($course->id)) {
618 $courseinfo['customfields'] = [];
619 foreach ($customfields as $data) {
620 $courseinfo['customfields'][] = [
621 'type' => $data->get_type(),
622 'value' => $data->get_value(),
623 'valueraw' => $data->get_data_controller()->get_value(),
624 'name' => $data->get_name(),
625 'shortname' => $data->get_shortname()
630 //some field should be returned only if the user has update permission
631 $courseadmin = has_capability('moodle/course:update', $context);
632 if ($courseadmin) {
633 $courseinfo['categorysortorder'] = $course->sortorder;
634 $courseinfo['idnumber'] = $course->idnumber;
635 $courseinfo['showgrades'] = $course->showgrades;
636 $courseinfo['showreports'] = $course->showreports;
637 $courseinfo['newsitems'] = $course->newsitems;
638 $courseinfo['visible'] = $course->visible;
639 $courseinfo['maxbytes'] = $course->maxbytes;
640 if (array_key_exists('hiddensections', $courseformatoptions)) {
641 // For backward-compartibility
642 $courseinfo['hiddensections'] = $courseformatoptions['hiddensections'];
644 // Return numsections for backward-compatibility with clients who expect it.
645 $courseinfo['numsections'] = course_get_format($course)->get_last_section_number();
646 $courseinfo['groupmode'] = $course->groupmode;
647 $courseinfo['groupmodeforce'] = $course->groupmodeforce;
648 $courseinfo['defaultgroupingid'] = $course->defaultgroupingid;
649 $courseinfo['lang'] = clean_param($course->lang, PARAM_LANG);
650 $courseinfo['timecreated'] = $course->timecreated;
651 $courseinfo['timemodified'] = $course->timemodified;
652 $courseinfo['forcetheme'] = clean_param($course->theme, PARAM_THEME);
653 $courseinfo['enablecompletion'] = $course->enablecompletion;
654 $courseinfo['completionnotify'] = $course->completionnotify;
655 $courseinfo['courseformatoptions'] = array();
656 foreach ($courseformatoptions as $key => $value) {
657 $courseinfo['courseformatoptions'][] = array(
658 'name' => $key,
659 'value' => $value
664 if ($courseadmin or $course->visible
665 or has_capability('moodle/course:viewhiddencourses', $context)) {
666 $coursesinfo[] = $courseinfo;
670 return $coursesinfo;
674 * Returns description of method result value
676 * @return external_description
677 * @since Moodle 2.2
679 public static function get_courses_returns() {
680 return new external_multiple_structure(
681 new external_single_structure(
682 array(
683 'id' => new external_value(PARAM_INT, 'course id'),
684 'shortname' => new external_value(PARAM_RAW, 'course short name'),
685 'categoryid' => new external_value(PARAM_INT, 'category id'),
686 'categorysortorder' => new external_value(PARAM_INT,
687 'sort order into the category', VALUE_OPTIONAL),
688 'fullname' => new external_value(PARAM_RAW, 'full name'),
689 'displayname' => new external_value(PARAM_RAW, 'course display name'),
690 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
691 'summary' => new external_value(PARAM_RAW, 'summary'),
692 'summaryformat' => new external_format_value('summary'),
693 'format' => new external_value(PARAM_PLUGIN,
694 'course format: weeks, topics, social, site,..'),
695 'showgrades' => new external_value(PARAM_INT,
696 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
697 'newsitems' => new external_value(PARAM_INT,
698 'number of recent items appearing on the course page', VALUE_OPTIONAL),
699 'startdate' => new external_value(PARAM_INT,
700 'timestamp when the course start'),
701 'enddate' => new external_value(PARAM_INT,
702 'timestamp when the course end'),
703 'numsections' => new external_value(PARAM_INT,
704 '(deprecated, use courseformatoptions) number of weeks/topics',
705 VALUE_OPTIONAL),
706 'maxbytes' => new external_value(PARAM_INT,
707 'largest size of file that can be uploaded into the course',
708 VALUE_OPTIONAL),
709 'showreports' => new external_value(PARAM_INT,
710 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
711 'visible' => new external_value(PARAM_INT,
712 '1: available to student, 0:not available', VALUE_OPTIONAL),
713 'hiddensections' => new external_value(PARAM_INT,
714 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
715 VALUE_OPTIONAL),
716 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
717 VALUE_OPTIONAL),
718 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
719 VALUE_OPTIONAL),
720 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
721 VALUE_OPTIONAL),
722 'timecreated' => new external_value(PARAM_INT,
723 'timestamp when the course have been created', VALUE_OPTIONAL),
724 'timemodified' => new external_value(PARAM_INT,
725 'timestamp when the course have been modified', VALUE_OPTIONAL),
726 'enablecompletion' => new external_value(PARAM_INT,
727 'Enabled, control via completion and activity settings. Disbaled,
728 not shown in activity settings.',
729 VALUE_OPTIONAL),
730 'completionnotify' => new external_value(PARAM_INT,
731 '1: yes 0: no', VALUE_OPTIONAL),
732 'lang' => new external_value(PARAM_SAFEDIR,
733 'forced course language', VALUE_OPTIONAL),
734 'forcetheme' => new external_value(PARAM_PLUGIN,
735 'name of the force theme', VALUE_OPTIONAL),
736 'courseformatoptions' => new external_multiple_structure(
737 new external_single_structure(
738 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
739 'value' => new external_value(PARAM_RAW, 'course format option value')
740 )), 'additional options for particular course format', VALUE_OPTIONAL
742 'showactivitydates' => new external_value(PARAM_BOOL, 'Whether the activity dates are shown or not'),
743 'showcompletionconditions' => new external_value(PARAM_BOOL,
744 'Whether the activity completion conditions are shown or not'),
745 'customfields' => new external_multiple_structure(
746 new external_single_structure(
747 ['name' => new external_value(PARAM_RAW, 'The name of the custom field'),
748 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'The shortname of the custom field'),
749 'type' => new external_value(PARAM_COMPONENT,
750 'The type of the custom field - text, checkbox...'),
751 'valueraw' => new external_value(PARAM_RAW, 'The raw value of the custom field'),
752 'value' => new external_value(PARAM_RAW, 'The value of the custom field')]
753 ), 'Custom fields and associated values', VALUE_OPTIONAL),
754 ), 'course'
760 * Returns description of method parameters
762 * @return external_function_parameters
763 * @since Moodle 2.2
765 public static function create_courses_parameters() {
766 $courseconfig = get_config('moodlecourse'); //needed for many default values
767 return new external_function_parameters(
768 array(
769 'courses' => new external_multiple_structure(
770 new external_single_structure(
771 array(
772 'fullname' => new external_value(PARAM_TEXT, 'full name'),
773 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
774 'categoryid' => new external_value(PARAM_INT, 'category id'),
775 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
776 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
777 'summaryformat' => new external_format_value('summary', VALUE_DEFAULT),
778 'format' => new external_value(PARAM_PLUGIN,
779 'course format: weeks, topics, social, site,..',
780 VALUE_DEFAULT, $courseconfig->format),
781 'showgrades' => new external_value(PARAM_INT,
782 '1 if grades are shown, otherwise 0', VALUE_DEFAULT,
783 $courseconfig->showgrades),
784 'newsitems' => new external_value(PARAM_INT,
785 'number of recent items appearing on the course page',
786 VALUE_DEFAULT, $courseconfig->newsitems),
787 'startdate' => new external_value(PARAM_INT,
788 'timestamp when the course start', VALUE_OPTIONAL),
789 'enddate' => new external_value(PARAM_INT,
790 'timestamp when the course end', VALUE_OPTIONAL),
791 'numsections' => new external_value(PARAM_INT,
792 '(deprecated, use courseformatoptions) number of weeks/topics',
793 VALUE_OPTIONAL),
794 'maxbytes' => new external_value(PARAM_INT,
795 'largest size of file that can be uploaded into the course',
796 VALUE_DEFAULT, $courseconfig->maxbytes),
797 'showreports' => new external_value(PARAM_INT,
798 'are activity report shown (yes = 1, no =0)', VALUE_DEFAULT,
799 $courseconfig->showreports),
800 'visible' => new external_value(PARAM_INT,
801 '1: available to student, 0:not available', VALUE_OPTIONAL),
802 'hiddensections' => new external_value(PARAM_INT,
803 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
804 VALUE_OPTIONAL),
805 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
806 VALUE_DEFAULT, $courseconfig->groupmode),
807 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
808 VALUE_DEFAULT, $courseconfig->groupmodeforce),
809 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
810 VALUE_DEFAULT, 0),
811 'enablecompletion' => new external_value(PARAM_INT,
812 'Enabled, control via completion and activity settings. Disabled,
813 not shown in activity settings.',
814 VALUE_OPTIONAL),
815 'completionnotify' => new external_value(PARAM_INT,
816 '1: yes 0: no', VALUE_OPTIONAL),
817 'lang' => new external_value(PARAM_SAFEDIR,
818 'forced course language', VALUE_OPTIONAL),
819 'forcetheme' => new external_value(PARAM_PLUGIN,
820 'name of the force theme', VALUE_OPTIONAL),
821 'courseformatoptions' => new external_multiple_structure(
822 new external_single_structure(
823 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
824 'value' => new external_value(PARAM_RAW, 'course format option value')
826 'additional options for particular course format', VALUE_OPTIONAL),
827 'customfields' => new external_multiple_structure(
828 new external_single_structure(
829 array(
830 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'The shortname of the custom field'),
831 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
832 )), 'custom fields for the course', VALUE_OPTIONAL
834 )), 'courses to create'
841 * Create courses
843 * @param array $courses
844 * @return array courses (id and shortname only)
845 * @since Moodle 2.2
847 public static function create_courses($courses) {
848 global $CFG, $DB;
849 require_once($CFG->dirroot . "/course/lib.php");
850 require_once($CFG->libdir . '/completionlib.php');
852 $params = self::validate_parameters(self::create_courses_parameters(),
853 array('courses' => $courses));
855 $availablethemes = core_component::get_plugin_list('theme');
856 $availablelangs = get_string_manager()->get_list_of_translations();
858 $transaction = $DB->start_delegated_transaction();
860 foreach ($params['courses'] as $course) {
862 // Ensure the current user is allowed to run this function
863 $context = context_coursecat::instance($course['categoryid'], IGNORE_MISSING);
864 try {
865 self::validate_context($context);
866 } catch (Exception $e) {
867 $exceptionparam = new stdClass();
868 $exceptionparam->message = $e->getMessage();
869 $exceptionparam->catid = $course['categoryid'];
870 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
872 require_capability('moodle/course:create', $context);
874 // Fullname and short name are required to be non-empty.
875 if (trim($course['fullname']) === '') {
876 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'fullname');
877 } else if (trim($course['shortname']) === '') {
878 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'shortname');
881 // Make sure lang is valid
882 if (array_key_exists('lang', $course)) {
883 if (empty($availablelangs[$course['lang']])) {
884 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
886 if (!has_capability('moodle/course:setforcedlanguage', $context)) {
887 unset($course['lang']);
891 // Make sure theme is valid
892 if (array_key_exists('forcetheme', $course)) {
893 if (!empty($CFG->allowcoursethemes)) {
894 if (empty($availablethemes[$course['forcetheme']])) {
895 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
896 } else {
897 $course['theme'] = $course['forcetheme'];
902 //force visibility if ws user doesn't have the permission to set it
903 $category = $DB->get_record('course_categories', array('id' => $course['categoryid']));
904 if (!has_capability('moodle/course:visibility', $context)) {
905 $course['visible'] = $category->visible;
908 //set default value for completion
909 $courseconfig = get_config('moodlecourse');
910 if (completion_info::is_enabled_for_site()) {
911 if (!array_key_exists('enablecompletion', $course)) {
912 $course['enablecompletion'] = $courseconfig->enablecompletion;
914 } else {
915 $course['enablecompletion'] = 0;
918 $course['category'] = $course['categoryid'];
920 // Summary format.
921 $course['summaryformat'] = external_validate_format($course['summaryformat']);
923 if (!empty($course['courseformatoptions'])) {
924 foreach ($course['courseformatoptions'] as $option) {
925 $course[$option['name']] = $option['value'];
929 // Custom fields.
930 if (!empty($course['customfields'])) {
931 foreach ($course['customfields'] as $field) {
932 $course['customfield_'.$field['shortname']] = $field['value'];
936 //Note: create_course() core function check shortname, idnumber, category
937 $course['id'] = create_course((object) $course)->id;
939 $resultcourses[] = array('id' => $course['id'], 'shortname' => $course['shortname']);
942 $transaction->allow_commit();
944 return $resultcourses;
948 * Returns description of method result value
950 * @return external_description
951 * @since Moodle 2.2
953 public static function create_courses_returns() {
954 return new external_multiple_structure(
955 new external_single_structure(
956 array(
957 'id' => new external_value(PARAM_INT, 'course id'),
958 'shortname' => new external_value(PARAM_RAW, 'short name'),
965 * Update courses
967 * @return external_function_parameters
968 * @since Moodle 2.5
970 public static function update_courses_parameters() {
971 return new external_function_parameters(
972 array(
973 'courses' => new external_multiple_structure(
974 new external_single_structure(
975 array(
976 'id' => new external_value(PARAM_INT, 'ID of the course'),
977 'fullname' => new external_value(PARAM_TEXT, 'full name', VALUE_OPTIONAL),
978 'shortname' => new external_value(PARAM_TEXT, 'course short name', VALUE_OPTIONAL),
979 'categoryid' => new external_value(PARAM_INT, 'category id', VALUE_OPTIONAL),
980 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
981 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
982 'summaryformat' => new external_format_value('summary', VALUE_OPTIONAL),
983 'format' => new external_value(PARAM_PLUGIN,
984 'course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
985 'showgrades' => new external_value(PARAM_INT,
986 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
987 'newsitems' => new external_value(PARAM_INT,
988 'number of recent items appearing on the course page', VALUE_OPTIONAL),
989 'startdate' => new external_value(PARAM_INT,
990 'timestamp when the course start', VALUE_OPTIONAL),
991 'enddate' => new external_value(PARAM_INT,
992 'timestamp when the course end', VALUE_OPTIONAL),
993 'numsections' => new external_value(PARAM_INT,
994 '(deprecated, use courseformatoptions) number of weeks/topics', VALUE_OPTIONAL),
995 'maxbytes' => new external_value(PARAM_INT,
996 'largest size of file that can be uploaded into the course', VALUE_OPTIONAL),
997 'showreports' => new external_value(PARAM_INT,
998 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
999 'visible' => new external_value(PARAM_INT,
1000 '1: available to student, 0:not available', VALUE_OPTIONAL),
1001 'hiddensections' => new external_value(PARAM_INT,
1002 '(deprecated, use courseformatoptions) How the hidden sections in the course are
1003 displayed to students', VALUE_OPTIONAL),
1004 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
1005 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
1006 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
1007 'enablecompletion' => new external_value(PARAM_INT,
1008 'Enabled, control via completion and activity settings. Disabled,
1009 not shown in activity settings.', VALUE_OPTIONAL),
1010 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
1011 'lang' => new external_value(PARAM_SAFEDIR, 'forced course language', VALUE_OPTIONAL),
1012 'forcetheme' => new external_value(PARAM_PLUGIN, 'name of the force theme', VALUE_OPTIONAL),
1013 'courseformatoptions' => new external_multiple_structure(
1014 new external_single_structure(
1015 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
1016 'value' => new external_value(PARAM_RAW, 'course format option value')
1017 )), 'additional options for particular course format', VALUE_OPTIONAL),
1018 'customfields' => new external_multiple_structure(
1019 new external_single_structure(
1021 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'The shortname of the custom field'),
1022 'value' => new external_value(PARAM_RAW, 'The value of the custom field')
1024 ), 'Custom fields', VALUE_OPTIONAL),
1026 ), 'courses to update'
1033 * Update courses
1035 * @param array $courses
1036 * @since Moodle 2.5
1038 public static function update_courses($courses) {
1039 global $CFG, $DB;
1040 require_once($CFG->dirroot . "/course/lib.php");
1041 $warnings = array();
1043 $params = self::validate_parameters(self::update_courses_parameters(),
1044 array('courses' => $courses));
1046 $availablethemes = core_component::get_plugin_list('theme');
1047 $availablelangs = get_string_manager()->get_list_of_translations();
1049 foreach ($params['courses'] as $course) {
1050 // Catch any exception while updating course and return as warning to user.
1051 try {
1052 // Ensure the current user is allowed to run this function.
1053 $context = context_course::instance($course['id'], MUST_EXIST);
1054 self::validate_context($context);
1056 $oldcourse = course_get_format($course['id'])->get_course();
1058 require_capability('moodle/course:update', $context);
1060 // Check if user can change category.
1061 if (array_key_exists('categoryid', $course) && ($oldcourse->category != $course['categoryid'])) {
1062 require_capability('moodle/course:changecategory', $context);
1063 $course['category'] = $course['categoryid'];
1066 // Check if the user can change fullname, and the new value is non-empty.
1067 if (array_key_exists('fullname', $course) && ($oldcourse->fullname != $course['fullname'])) {
1068 require_capability('moodle/course:changefullname', $context);
1069 if (trim($course['fullname']) === '') {
1070 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'fullname');
1074 // Check if the user can change shortname, and the new value is non-empty.
1075 if (array_key_exists('shortname', $course) && ($oldcourse->shortname != $course['shortname'])) {
1076 require_capability('moodle/course:changeshortname', $context);
1077 if (trim($course['shortname']) === '') {
1078 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'shortname');
1082 // Check if the user can change the idnumber.
1083 if (array_key_exists('idnumber', $course) && ($oldcourse->idnumber != $course['idnumber'])) {
1084 require_capability('moodle/course:changeidnumber', $context);
1087 // Check if user can change summary.
1088 if (array_key_exists('summary', $course) && ($oldcourse->summary != $course['summary'])) {
1089 require_capability('moodle/course:changesummary', $context);
1092 // Summary format.
1093 if (array_key_exists('summaryformat', $course) && ($oldcourse->summaryformat != $course['summaryformat'])) {
1094 require_capability('moodle/course:changesummary', $context);
1095 $course['summaryformat'] = external_validate_format($course['summaryformat']);
1098 // Check if user can change visibility.
1099 if (array_key_exists('visible', $course) && ($oldcourse->visible != $course['visible'])) {
1100 require_capability('moodle/course:visibility', $context);
1103 // Make sure lang is valid.
1104 if (array_key_exists('lang', $course) && ($oldcourse->lang != $course['lang'])) {
1105 require_capability('moodle/course:setforcedlanguage', $context);
1106 if (empty($availablelangs[$course['lang']])) {
1107 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
1111 // Make sure theme is valid.
1112 if (array_key_exists('forcetheme', $course)) {
1113 if (!empty($CFG->allowcoursethemes)) {
1114 if (empty($availablethemes[$course['forcetheme']])) {
1115 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
1116 } else {
1117 $course['theme'] = $course['forcetheme'];
1122 // Make sure completion is enabled before setting it.
1123 if (array_key_exists('enabledcompletion', $course) && !completion_info::is_enabled_for_site()) {
1124 $course['enabledcompletion'] = 0;
1127 // Make sure maxbytes are less then CFG->maxbytes.
1128 if (array_key_exists('maxbytes', $course)) {
1129 // We allow updates back to 0 max bytes, a special value denoting the course uses the site limit.
1130 // Otherwise, either use the size specified, or cap at the max size for the course.
1131 if ($course['maxbytes'] != 0) {
1132 $course['maxbytes'] = get_max_upload_file_size($CFG->maxbytes, $course['maxbytes']);
1136 if (!empty($course['courseformatoptions'])) {
1137 foreach ($course['courseformatoptions'] as $option) {
1138 if (isset($option['name']) && isset($option['value'])) {
1139 $course[$option['name']] = $option['value'];
1144 // Prepare list of custom fields.
1145 if (isset($course['customfields'])) {
1146 foreach ($course['customfields'] as $field) {
1147 $course['customfield_' . $field['shortname']] = $field['value'];
1151 // Update course if user has all required capabilities.
1152 update_course((object) $course);
1153 } catch (Exception $e) {
1154 $warning = array();
1155 $warning['item'] = 'course';
1156 $warning['itemid'] = $course['id'];
1157 if ($e instanceof moodle_exception) {
1158 $warning['warningcode'] = $e->errorcode;
1159 } else {
1160 $warning['warningcode'] = $e->getCode();
1162 $warning['message'] = $e->getMessage();
1163 $warnings[] = $warning;
1167 $result = array();
1168 $result['warnings'] = $warnings;
1169 return $result;
1173 * Returns description of method result value
1175 * @return external_description
1176 * @since Moodle 2.5
1178 public static function update_courses_returns() {
1179 return new external_single_structure(
1180 array(
1181 'warnings' => new external_warnings()
1187 * Returns description of method parameters
1189 * @return external_function_parameters
1190 * @since Moodle 2.2
1192 public static function delete_courses_parameters() {
1193 return new external_function_parameters(
1194 array(
1195 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'course ID')),
1201 * Delete courses
1203 * @param array $courseids A list of course ids
1204 * @since Moodle 2.2
1206 public static function delete_courses($courseids) {
1207 global $CFG, $DB;
1208 require_once($CFG->dirroot."/course/lib.php");
1210 // Parameter validation.
1211 $params = self::validate_parameters(self::delete_courses_parameters(), array('courseids'=>$courseids));
1213 $warnings = array();
1215 foreach ($params['courseids'] as $courseid) {
1216 $course = $DB->get_record('course', array('id' => $courseid));
1218 if ($course === false) {
1219 $warnings[] = array(
1220 'item' => 'course',
1221 'itemid' => $courseid,
1222 'warningcode' => 'unknowncourseidnumber',
1223 'message' => 'Unknown course ID ' . $courseid
1225 continue;
1228 // Check if the context is valid.
1229 $coursecontext = context_course::instance($course->id);
1230 self::validate_context($coursecontext);
1232 // Check if the current user has permission.
1233 if (!can_delete_course($courseid)) {
1234 $warnings[] = array(
1235 'item' => 'course',
1236 'itemid' => $courseid,
1237 'warningcode' => 'cannotdeletecourse',
1238 'message' => 'You do not have the permission to delete this course' . $courseid
1240 continue;
1243 if (delete_course($course, false) === false) {
1244 $warnings[] = array(
1245 'item' => 'course',
1246 'itemid' => $courseid,
1247 'warningcode' => 'cannotdeletecategorycourse',
1248 'message' => 'Course ' . $courseid . ' failed to be deleted'
1250 continue;
1254 fix_course_sortorder();
1256 return array('warnings' => $warnings);
1260 * Returns description of method result value
1262 * @return external_description
1263 * @since Moodle 2.2
1265 public static function delete_courses_returns() {
1266 return new external_single_structure(
1267 array(
1268 'warnings' => new external_warnings()
1274 * Returns description of method parameters
1276 * @return external_function_parameters
1277 * @since Moodle 2.3
1279 public static function duplicate_course_parameters() {
1280 return new external_function_parameters(
1281 array(
1282 'courseid' => new external_value(PARAM_INT, 'course to duplicate id'),
1283 'fullname' => new external_value(PARAM_TEXT, 'duplicated course full name'),
1284 'shortname' => new external_value(PARAM_TEXT, 'duplicated course short name'),
1285 'categoryid' => new external_value(PARAM_INT, 'duplicated course category parent'),
1286 'visible' => new external_value(PARAM_INT, 'duplicated course visible, default to yes', VALUE_DEFAULT, 1),
1287 'options' => new external_multiple_structure(
1288 new external_single_structure(
1289 array(
1290 'name' => new external_value(PARAM_ALPHAEXT, 'The backup option name:
1291 "activities" (int) Include course activites (default to 1 that is equal to yes),
1292 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1293 "filters" (int) Include course filters (default to 1 that is equal to yes),
1294 "users" (int) Include users (default to 0 that is equal to no),
1295 "enrolments" (int) Include enrolment methods (default to 1 - restore only with users),
1296 "role_assignments" (int) Include role assignments (default to 0 that is equal to no),
1297 "comments" (int) Include user comments (default to 0 that is equal to no),
1298 "userscompletion" (int) Include user course completion information (default to 0 that is equal to no),
1299 "logs" (int) Include course logs (default to 0 that is equal to no),
1300 "grade_histories" (int) Include histories (default to 0 that is equal to no)'
1302 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1305 ), VALUE_DEFAULT, array()
1312 * Duplicate a course
1314 * @param int $courseid
1315 * @param string $fullname Duplicated course fullname
1316 * @param string $shortname Duplicated course shortname
1317 * @param int $categoryid Duplicated course parent category id
1318 * @param int $visible Duplicated course availability
1319 * @param array $options List of backup options
1320 * @return array New course info
1321 * @since Moodle 2.3
1323 public static function duplicate_course($courseid, $fullname, $shortname, $categoryid, $visible = 1, $options = array()) {
1324 global $CFG, $USER, $DB;
1325 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1326 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1328 // Parameter validation.
1329 $params = self::validate_parameters(
1330 self::duplicate_course_parameters(),
1331 array(
1332 'courseid' => $courseid,
1333 'fullname' => $fullname,
1334 'shortname' => $shortname,
1335 'categoryid' => $categoryid,
1336 'visible' => $visible,
1337 'options' => $options
1341 // Context validation.
1343 if (! ($course = $DB->get_record('course', array('id'=>$params['courseid'])))) {
1344 throw new moodle_exception('invalidcourseid', 'error');
1347 // Category where duplicated course is going to be created.
1348 $categorycontext = context_coursecat::instance($params['categoryid']);
1349 self::validate_context($categorycontext);
1351 // Course to be duplicated.
1352 $coursecontext = context_course::instance($course->id);
1353 self::validate_context($coursecontext);
1355 $backupdefaults = array(
1356 'activities' => 1,
1357 'blocks' => 1,
1358 'filters' => 1,
1359 'users' => 0,
1360 'enrolments' => backup::ENROL_WITHUSERS,
1361 'role_assignments' => 0,
1362 'comments' => 0,
1363 'userscompletion' => 0,
1364 'logs' => 0,
1365 'grade_histories' => 0
1368 $backupsettings = array();
1369 // Check for backup and restore options.
1370 if (!empty($params['options'])) {
1371 foreach ($params['options'] as $option) {
1373 // Strict check for a correct value (allways 1 or 0, true or false).
1374 $value = clean_param($option['value'], PARAM_INT);
1376 if ($value !== 0 and $value !== 1) {
1377 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1380 if (!isset($backupdefaults[$option['name']])) {
1381 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1384 $backupsettings[$option['name']] = $value;
1388 // Capability checking.
1390 // The backup controller check for this currently, this may be redundant.
1391 require_capability('moodle/course:create', $categorycontext);
1392 require_capability('moodle/restore:restorecourse', $categorycontext);
1393 require_capability('moodle/backup:backupcourse', $coursecontext);
1395 if (!empty($backupsettings['users'])) {
1396 require_capability('moodle/backup:userinfo', $coursecontext);
1397 require_capability('moodle/restore:userinfo', $categorycontext);
1400 // Check if the shortname is used.
1401 if ($foundcourses = $DB->get_records('course', array('shortname'=>$shortname))) {
1402 foreach ($foundcourses as $foundcourse) {
1403 $foundcoursenames[] = $foundcourse->fullname;
1406 $foundcoursenamestring = implode(',', $foundcoursenames);
1407 throw new moodle_exception('shortnametaken', '', '', $foundcoursenamestring);
1410 // Backup the course.
1412 $bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE,
1413 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id);
1415 foreach ($backupsettings as $name => $value) {
1416 if ($setting = $bc->get_plan()->get_setting($name)) {
1417 $bc->get_plan()->get_setting($name)->set_value($value);
1421 $backupid = $bc->get_backupid();
1422 $backupbasepath = $bc->get_plan()->get_basepath();
1424 $bc->execute_plan();
1425 $results = $bc->get_results();
1426 $file = $results['backup_destination'];
1428 $bc->destroy();
1430 // Restore the backup immediately.
1432 // Check if we need to unzip the file because the backup temp dir does not contains backup files.
1433 if (!file_exists($backupbasepath . "/moodle_backup.xml")) {
1434 $file->extract_to_pathname(get_file_packer('application/vnd.moodle.backup'), $backupbasepath);
1437 // Create new course.
1438 $newcourseid = restore_dbops::create_new_course($params['fullname'], $params['shortname'], $params['categoryid']);
1440 $rc = new restore_controller($backupid, $newcourseid,
1441 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id, backup::TARGET_NEW_COURSE);
1443 foreach ($backupsettings as $name => $value) {
1444 $setting = $rc->get_plan()->get_setting($name);
1445 if ($setting->get_status() == backup_setting::NOT_LOCKED) {
1446 $setting->set_value($value);
1450 if (!$rc->execute_precheck()) {
1451 $precheckresults = $rc->get_precheck_results();
1452 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1453 if (empty($CFG->keeptempdirectoriesonbackup)) {
1454 fulldelete($backupbasepath);
1457 $errorinfo = '';
1459 foreach ($precheckresults['errors'] as $error) {
1460 $errorinfo .= $error;
1463 if (array_key_exists('warnings', $precheckresults)) {
1464 foreach ($precheckresults['warnings'] as $warning) {
1465 $errorinfo .= $warning;
1469 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1473 $rc->execute_plan();
1474 $rc->destroy();
1476 $course = $DB->get_record('course', array('id' => $newcourseid), '*', MUST_EXIST);
1477 $course->fullname = $params['fullname'];
1478 $course->shortname = $params['shortname'];
1479 $course->visible = $params['visible'];
1481 // Set shortname and fullname back.
1482 $DB->update_record('course', $course);
1484 if (empty($CFG->keeptempdirectoriesonbackup)) {
1485 fulldelete($backupbasepath);
1488 // Delete the course backup file created by this WebService. Originally located in the course backups area.
1489 $file->delete();
1491 return array('id' => $course->id, 'shortname' => $course->shortname);
1495 * Returns description of method result value
1497 * @return external_description
1498 * @since Moodle 2.3
1500 public static function duplicate_course_returns() {
1501 return new external_single_structure(
1502 array(
1503 'id' => new external_value(PARAM_INT, 'course id'),
1504 'shortname' => new external_value(PARAM_RAW, 'short name'),
1510 * Returns description of method parameters for import_course
1512 * @return external_function_parameters
1513 * @since Moodle 2.4
1515 public static function import_course_parameters() {
1516 return new external_function_parameters(
1517 array(
1518 'importfrom' => new external_value(PARAM_INT, 'the id of the course we are importing from'),
1519 'importto' => new external_value(PARAM_INT, 'the id of the course we are importing to'),
1520 'deletecontent' => new external_value(PARAM_INT, 'whether to delete the course content where we are importing to (default to 0 = No)', VALUE_DEFAULT, 0),
1521 'options' => new external_multiple_structure(
1522 new external_single_structure(
1523 array(
1524 'name' => new external_value(PARAM_ALPHA, 'The backup option name:
1525 "activities" (int) Include course activites (default to 1 that is equal to yes),
1526 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1527 "filters" (int) Include course filters (default to 1 that is equal to yes)'
1529 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1532 ), VALUE_DEFAULT, array()
1539 * Imports a course
1541 * @param int $importfrom The id of the course we are importing from
1542 * @param int $importto The id of the course we are importing to
1543 * @param bool $deletecontent Whether to delete the course we are importing to content
1544 * @param array $options List of backup options
1545 * @return null
1546 * @since Moodle 2.4
1548 public static function import_course($importfrom, $importto, $deletecontent = 0, $options = array()) {
1549 global $CFG, $USER, $DB;
1550 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1551 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1553 // Parameter validation.
1554 $params = self::validate_parameters(
1555 self::import_course_parameters(),
1556 array(
1557 'importfrom' => $importfrom,
1558 'importto' => $importto,
1559 'deletecontent' => $deletecontent,
1560 'options' => $options
1564 if ($params['deletecontent'] !== 0 and $params['deletecontent'] !== 1) {
1565 throw new moodle_exception('invalidextparam', 'webservice', '', $params['deletecontent']);
1568 // Context validation.
1570 if (! ($importfrom = $DB->get_record('course', array('id'=>$params['importfrom'])))) {
1571 throw new moodle_exception('invalidcourseid', 'error');
1574 if (! ($importto = $DB->get_record('course', array('id'=>$params['importto'])))) {
1575 throw new moodle_exception('invalidcourseid', 'error');
1578 $importfromcontext = context_course::instance($importfrom->id);
1579 self::validate_context($importfromcontext);
1581 $importtocontext = context_course::instance($importto->id);
1582 self::validate_context($importtocontext);
1584 $backupdefaults = array(
1585 'activities' => 1,
1586 'blocks' => 1,
1587 'filters' => 1
1590 $backupsettings = array();
1592 // Check for backup and restore options.
1593 if (!empty($params['options'])) {
1594 foreach ($params['options'] as $option) {
1596 // Strict check for a correct value (allways 1 or 0, true or false).
1597 $value = clean_param($option['value'], PARAM_INT);
1599 if ($value !== 0 and $value !== 1) {
1600 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1603 if (!isset($backupdefaults[$option['name']])) {
1604 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1607 $backupsettings[$option['name']] = $value;
1611 // Capability checking.
1613 require_capability('moodle/backup:backuptargetimport', $importfromcontext);
1614 require_capability('moodle/restore:restoretargetimport', $importtocontext);
1616 $bc = new backup_controller(backup::TYPE_1COURSE, $importfrom->id, backup::FORMAT_MOODLE,
1617 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
1619 foreach ($backupsettings as $name => $value) {
1620 $bc->get_plan()->get_setting($name)->set_value($value);
1623 $backupid = $bc->get_backupid();
1624 $backupbasepath = $bc->get_plan()->get_basepath();
1626 $bc->execute_plan();
1627 $bc->destroy();
1629 // Restore the backup immediately.
1631 // Check if we must delete the contents of the destination course.
1632 if ($params['deletecontent']) {
1633 $restoretarget = backup::TARGET_EXISTING_DELETING;
1634 } else {
1635 $restoretarget = backup::TARGET_EXISTING_ADDING;
1638 $rc = new restore_controller($backupid, $importto->id,
1639 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, $restoretarget);
1641 foreach ($backupsettings as $name => $value) {
1642 $rc->get_plan()->get_setting($name)->set_value($value);
1645 if (!$rc->execute_precheck()) {
1646 $precheckresults = $rc->get_precheck_results();
1647 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1648 if (empty($CFG->keeptempdirectoriesonbackup)) {
1649 fulldelete($backupbasepath);
1652 $errorinfo = '';
1654 foreach ($precheckresults['errors'] as $error) {
1655 $errorinfo .= $error;
1658 if (array_key_exists('warnings', $precheckresults)) {
1659 foreach ($precheckresults['warnings'] as $warning) {
1660 $errorinfo .= $warning;
1664 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1666 } else {
1667 if ($restoretarget == backup::TARGET_EXISTING_DELETING) {
1668 restore_dbops::delete_course_content($importto->id);
1672 $rc->execute_plan();
1673 $rc->destroy();
1675 if (empty($CFG->keeptempdirectoriesonbackup)) {
1676 fulldelete($backupbasepath);
1679 return null;
1683 * Returns description of method result value
1685 * @return external_description
1686 * @since Moodle 2.4
1688 public static function import_course_returns() {
1689 return null;
1693 * Returns description of method parameters
1695 * @return external_function_parameters
1696 * @since Moodle 2.3
1698 public static function get_categories_parameters() {
1699 return new external_function_parameters(
1700 array(
1701 'criteria' => new external_multiple_structure(
1702 new external_single_structure(
1703 array(
1704 'key' => new external_value(PARAM_ALPHA,
1705 'The category column to search, expected keys (value format) are:'.
1706 '"id" (int) the category id,'.
1707 '"ids" (string) category ids separated by commas,'.
1708 '"name" (string) the category name,'.
1709 '"parent" (int) the parent category id,'.
1710 '"idnumber" (string) category idnumber'.
1711 ' - user must have \'moodle/category:manage\' to search on idnumber,'.
1712 '"visible" (int) whether the returned categories must be visible or hidden. If the key is not passed,
1713 then the function return all categories that the user can see.'.
1714 ' - user must have \'moodle/category:manage\' or \'moodle/category:viewhiddencategories\' to search on visible,'.
1715 '"theme" (string) only return the categories having this theme'.
1716 ' - user must have \'moodle/category:manage\' to search on theme'),
1717 'value' => new external_value(PARAM_RAW, 'the value to match')
1719 ), 'criteria', VALUE_DEFAULT, array()
1721 'addsubcategories' => new external_value(PARAM_BOOL, 'return the sub categories infos
1722 (1 - default) otherwise only the category info (0)', VALUE_DEFAULT, 1)
1728 * Get categories
1730 * @param array $criteria Criteria to match the results
1731 * @param booln $addsubcategories obtain only the category (false) or its subcategories (true - default)
1732 * @return array list of categories
1733 * @since Moodle 2.3
1735 public static function get_categories($criteria = array(), $addsubcategories = true) {
1736 global $CFG, $DB;
1737 require_once($CFG->dirroot . "/course/lib.php");
1739 // Validate parameters.
1740 $params = self::validate_parameters(self::get_categories_parameters(),
1741 array('criteria' => $criteria, 'addsubcategories' => $addsubcategories));
1743 // Retrieve the categories.
1744 $categories = array();
1745 if (!empty($params['criteria'])) {
1747 $conditions = array();
1748 $wheres = array();
1749 foreach ($params['criteria'] as $crit) {
1750 $key = trim($crit['key']);
1752 // Trying to avoid duplicate keys.
1753 if (!isset($conditions[$key])) {
1755 $context = context_system::instance();
1756 $value = null;
1757 switch ($key) {
1758 case 'id':
1759 $value = clean_param($crit['value'], PARAM_INT);
1760 $conditions[$key] = $value;
1761 $wheres[] = $key . " = :" . $key;
1762 break;
1764 case 'ids':
1765 $value = clean_param($crit['value'], PARAM_SEQUENCE);
1766 $ids = explode(',', $value);
1767 list($sqlids, $paramids) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED);
1768 $conditions = array_merge($conditions, $paramids);
1769 $wheres[] = 'id ' . $sqlids;
1770 break;
1772 case 'idnumber':
1773 if (has_capability('moodle/category:manage', $context)) {
1774 $value = clean_param($crit['value'], PARAM_RAW);
1775 $conditions[$key] = $value;
1776 $wheres[] = $key . " = :" . $key;
1777 } else {
1778 // We must throw an exception.
1779 // Otherwise the dev client would think no idnumber exists.
1780 throw new moodle_exception('criteriaerror',
1781 'webservice', '', null,
1782 'You don\'t have the permissions to search on the "idnumber" field.');
1784 break;
1786 case 'name':
1787 $value = clean_param($crit['value'], PARAM_TEXT);
1788 $conditions[$key] = $value;
1789 $wheres[] = $key . " = :" . $key;
1790 break;
1792 case 'parent':
1793 $value = clean_param($crit['value'], PARAM_INT);
1794 $conditions[$key] = $value;
1795 $wheres[] = $key . " = :" . $key;
1796 break;
1798 case 'visible':
1799 if (has_capability('moodle/category:viewhiddencategories', $context)) {
1800 $value = clean_param($crit['value'], PARAM_INT);
1801 $conditions[$key] = $value;
1802 $wheres[] = $key . " = :" . $key;
1803 } else {
1804 throw new moodle_exception('criteriaerror',
1805 'webservice', '', null,
1806 'You don\'t have the permissions to search on the "visible" field.');
1808 break;
1810 case 'theme':
1811 if (has_capability('moodle/category:manage', $context)) {
1812 $value = clean_param($crit['value'], PARAM_THEME);
1813 $conditions[$key] = $value;
1814 $wheres[] = $key . " = :" . $key;
1815 } else {
1816 throw new moodle_exception('criteriaerror',
1817 'webservice', '', null,
1818 'You don\'t have the permissions to search on the "theme" field.');
1820 break;
1822 default:
1823 throw new moodle_exception('criteriaerror',
1824 'webservice', '', null,
1825 'You can not search on this criteria: ' . $key);
1830 if (!empty($wheres)) {
1831 $wheres = implode(" AND ", $wheres);
1833 $categories = $DB->get_records_select('course_categories', $wheres, $conditions);
1835 // Retrieve its sub subcategories (all levels).
1836 if ($categories and !empty($params['addsubcategories'])) {
1837 $newcategories = array();
1839 // Check if we required visible/theme checks.
1840 $additionalselect = '';
1841 $additionalparams = array();
1842 if (isset($conditions['visible'])) {
1843 $additionalselect .= ' AND visible = :visible';
1844 $additionalparams['visible'] = $conditions['visible'];
1846 if (isset($conditions['theme'])) {
1847 $additionalselect .= ' AND theme= :theme';
1848 $additionalparams['theme'] = $conditions['theme'];
1851 foreach ($categories as $category) {
1852 $sqlselect = $DB->sql_like('path', ':path') . $additionalselect;
1853 $sqlparams = array('path' => $category->path.'/%') + $additionalparams; // It will NOT include the specified category.
1854 $subcategories = $DB->get_records_select('course_categories', $sqlselect, $sqlparams);
1855 $newcategories = $newcategories + $subcategories; // Both arrays have integer as keys.
1857 $categories = $categories + $newcategories;
1861 } else {
1862 // Retrieve all categories in the database.
1863 $categories = $DB->get_records('course_categories');
1866 // The not returned categories. key => category id, value => reason of exclusion.
1867 $excludedcats = array();
1869 // The returned categories.
1870 $categoriesinfo = array();
1872 // We need to sort the categories by path.
1873 // The parent cats need to be checked by the algo first.
1874 usort($categories, "core_course_external::compare_categories_by_path");
1876 foreach ($categories as $category) {
1878 // Check if the category is a child of an excluded category, if yes exclude it too (excluded => do not return).
1879 $parents = explode('/', $category->path);
1880 unset($parents[0]); // First key is always empty because path start with / => /1/2/4.
1881 foreach ($parents as $parentid) {
1882 // Note: when the parent exclusion was due to the context,
1883 // the sub category could still be returned.
1884 if (isset($excludedcats[$parentid]) and $excludedcats[$parentid] != 'context') {
1885 $excludedcats[$category->id] = 'parent';
1889 // Check the user can use the category context.
1890 $context = context_coursecat::instance($category->id);
1891 try {
1892 self::validate_context($context);
1893 } catch (Exception $e) {
1894 $excludedcats[$category->id] = 'context';
1896 // If it was the requested category then throw an exception.
1897 if (isset($params['categoryid']) && $category->id == $params['categoryid']) {
1898 $exceptionparam = new stdClass();
1899 $exceptionparam->message = $e->getMessage();
1900 $exceptionparam->catid = $category->id;
1901 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
1905 // Return the category information.
1906 if (!isset($excludedcats[$category->id])) {
1908 // Final check to see if the category is visible to the user.
1909 if (core_course_category::can_view_category($category)) {
1911 $categoryinfo = array();
1912 $categoryinfo['id'] = $category->id;
1913 $categoryinfo['name'] = external_format_string($category->name, $context);
1914 list($categoryinfo['description'], $categoryinfo['descriptionformat']) =
1915 external_format_text($category->description, $category->descriptionformat,
1916 $context->id, 'coursecat', 'description', null);
1917 $categoryinfo['parent'] = $category->parent;
1918 $categoryinfo['sortorder'] = $category->sortorder;
1919 $categoryinfo['coursecount'] = $category->coursecount;
1920 $categoryinfo['depth'] = $category->depth;
1921 $categoryinfo['path'] = $category->path;
1923 // Some fields only returned for admin.
1924 if (has_capability('moodle/category:manage', $context)) {
1925 $categoryinfo['idnumber'] = $category->idnumber;
1926 $categoryinfo['visible'] = $category->visible;
1927 $categoryinfo['visibleold'] = $category->visibleold;
1928 $categoryinfo['timemodified'] = $category->timemodified;
1929 $categoryinfo['theme'] = clean_param($category->theme, PARAM_THEME);
1932 $categoriesinfo[] = $categoryinfo;
1933 } else {
1934 $excludedcats[$category->id] = 'visibility';
1939 // Sorting the resulting array so it looks a bit better for the client developer.
1940 usort($categoriesinfo, "core_course_external::compare_categories_by_sortorder");
1942 return $categoriesinfo;
1946 * Sort categories array by path
1947 * private function: only used by get_categories
1949 * @param array $category1
1950 * @param array $category2
1951 * @return int result of strcmp
1952 * @since Moodle 2.3
1954 private static function compare_categories_by_path($category1, $category2) {
1955 return strcmp($category1->path, $category2->path);
1959 * Sort categories array by sortorder
1960 * private function: only used by get_categories
1962 * @param array $category1
1963 * @param array $category2
1964 * @return int result of strcmp
1965 * @since Moodle 2.3
1967 private static function compare_categories_by_sortorder($category1, $category2) {
1968 return strcmp($category1['sortorder'], $category2['sortorder']);
1972 * Returns description of method result value
1974 * @return external_description
1975 * @since Moodle 2.3
1977 public static function get_categories_returns() {
1978 return new external_multiple_structure(
1979 new external_single_structure(
1980 array(
1981 'id' => new external_value(PARAM_INT, 'category id'),
1982 'name' => new external_value(PARAM_RAW, 'category name'),
1983 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1984 'description' => new external_value(PARAM_RAW, 'category description'),
1985 'descriptionformat' => new external_format_value('description'),
1986 'parent' => new external_value(PARAM_INT, 'parent category id'),
1987 'sortorder' => new external_value(PARAM_INT, 'category sorting order'),
1988 'coursecount' => new external_value(PARAM_INT, 'number of courses in this category'),
1989 'visible' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1990 'visibleold' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1991 'timemodified' => new external_value(PARAM_INT, 'timestamp', VALUE_OPTIONAL),
1992 'depth' => new external_value(PARAM_INT, 'category depth'),
1993 'path' => new external_value(PARAM_TEXT, 'category path'),
1994 'theme' => new external_value(PARAM_THEME, 'category theme', VALUE_OPTIONAL),
1995 ), 'List of categories'
2001 * Returns description of method parameters
2003 * @return external_function_parameters
2004 * @since Moodle 2.3
2006 public static function create_categories_parameters() {
2007 return new external_function_parameters(
2008 array(
2009 'categories' => new external_multiple_structure(
2010 new external_single_structure(
2011 array(
2012 'name' => new external_value(PARAM_TEXT, 'new category name'),
2013 'parent' => new external_value(PARAM_INT,
2014 'the parent category id inside which the new category will be created
2015 - set to 0 for a root category',
2016 VALUE_DEFAULT, 0),
2017 'idnumber' => new external_value(PARAM_RAW,
2018 'the new category idnumber', VALUE_OPTIONAL),
2019 'description' => new external_value(PARAM_RAW,
2020 'the new category description', VALUE_OPTIONAL),
2021 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
2022 'theme' => new external_value(PARAM_THEME,
2023 'the new category theme. This option must be enabled on moodle',
2024 VALUE_OPTIONAL),
2033 * Create categories
2035 * @param array $categories - see create_categories_parameters() for the array structure
2036 * @return array - see create_categories_returns() for the array structure
2037 * @since Moodle 2.3
2039 public static function create_categories($categories) {
2040 global $DB;
2042 $params = self::validate_parameters(self::create_categories_parameters(),
2043 array('categories' => $categories));
2045 $transaction = $DB->start_delegated_transaction();
2047 $createdcategories = array();
2048 foreach ($params['categories'] as $category) {
2049 if ($category['parent']) {
2050 if (!$DB->record_exists('course_categories', array('id' => $category['parent']))) {
2051 throw new moodle_exception('unknowcategory');
2053 $context = context_coursecat::instance($category['parent']);
2054 } else {
2055 $context = context_system::instance();
2057 self::validate_context($context);
2058 require_capability('moodle/category:manage', $context);
2060 // this will validate format and throw an exception if there are errors
2061 external_validate_format($category['descriptionformat']);
2063 $newcategory = core_course_category::create($category);
2064 $context = context_coursecat::instance($newcategory->id);
2066 $createdcategories[] = array(
2067 'id' => $newcategory->id,
2068 'name' => external_format_string($newcategory->name, $context),
2072 $transaction->allow_commit();
2074 return $createdcategories;
2078 * Returns description of method parameters
2080 * @return external_function_parameters
2081 * @since Moodle 2.3
2083 public static function create_categories_returns() {
2084 return new external_multiple_structure(
2085 new external_single_structure(
2086 array(
2087 'id' => new external_value(PARAM_INT, 'new category id'),
2088 'name' => new external_value(PARAM_RAW, 'new category name'),
2095 * Returns description of method parameters
2097 * @return external_function_parameters
2098 * @since Moodle 2.3
2100 public static function update_categories_parameters() {
2101 return new external_function_parameters(
2102 array(
2103 'categories' => new external_multiple_structure(
2104 new external_single_structure(
2105 array(
2106 'id' => new external_value(PARAM_INT, 'course id'),
2107 'name' => new external_value(PARAM_TEXT, 'category name', VALUE_OPTIONAL),
2108 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
2109 'parent' => new external_value(PARAM_INT, 'parent category id', VALUE_OPTIONAL),
2110 'description' => new external_value(PARAM_RAW, 'category description', VALUE_OPTIONAL),
2111 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
2112 'theme' => new external_value(PARAM_THEME,
2113 'the category theme. This option must be enabled on moodle', VALUE_OPTIONAL),
2122 * Update categories
2124 * @param array $categories The list of categories to update
2125 * @return null
2126 * @since Moodle 2.3
2128 public static function update_categories($categories) {
2129 global $DB;
2131 // Validate parameters.
2132 $params = self::validate_parameters(self::update_categories_parameters(), array('categories' => $categories));
2134 $transaction = $DB->start_delegated_transaction();
2136 foreach ($params['categories'] as $cat) {
2137 $category = core_course_category::get($cat['id']);
2139 $categorycontext = context_coursecat::instance($cat['id']);
2140 self::validate_context($categorycontext);
2141 require_capability('moodle/category:manage', $categorycontext);
2143 // this will throw an exception if descriptionformat is not valid
2144 external_validate_format($cat['descriptionformat']);
2146 $category->update($cat);
2149 $transaction->allow_commit();
2153 * Returns description of method result value
2155 * @return external_description
2156 * @since Moodle 2.3
2158 public static function update_categories_returns() {
2159 return null;
2163 * Returns description of method parameters
2165 * @return external_function_parameters
2166 * @since Moodle 2.3
2168 public static function delete_categories_parameters() {
2169 return new external_function_parameters(
2170 array(
2171 'categories' => new external_multiple_structure(
2172 new external_single_structure(
2173 array(
2174 'id' => new external_value(PARAM_INT, 'category id to delete'),
2175 'newparent' => new external_value(PARAM_INT,
2176 'the parent category to move the contents to, if specified', VALUE_OPTIONAL),
2177 'recursive' => new external_value(PARAM_BOOL, '1: recursively delete all contents inside this
2178 category, 0 (default): move contents to newparent or current parent category (except if parent is root)', VALUE_DEFAULT, 0)
2187 * Delete categories
2189 * @param array $categories A list of category ids
2190 * @return array
2191 * @since Moodle 2.3
2193 public static function delete_categories($categories) {
2194 global $CFG, $DB;
2195 require_once($CFG->dirroot . "/course/lib.php");
2197 // Validate parameters.
2198 $params = self::validate_parameters(self::delete_categories_parameters(), array('categories' => $categories));
2200 $transaction = $DB->start_delegated_transaction();
2202 foreach ($params['categories'] as $category) {
2203 $deletecat = core_course_category::get($category['id'], MUST_EXIST);
2204 $context = context_coursecat::instance($deletecat->id);
2205 require_capability('moodle/category:manage', $context);
2206 self::validate_context($context);
2207 self::validate_context(get_category_or_system_context($deletecat->parent));
2209 if ($category['recursive']) {
2210 // If recursive was specified, then we recursively delete the category's contents.
2211 if ($deletecat->can_delete_full()) {
2212 $deletecat->delete_full(false);
2213 } else {
2214 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2216 } else {
2217 // In this situation, we don't delete the category's contents, we either move it to newparent or parent.
2218 // If the parent is the root, moving is not supported (because a course must always be inside a category).
2219 // We must move to an existing category.
2220 if (!empty($category['newparent'])) {
2221 $newparentcat = core_course_category::get($category['newparent']);
2222 } else {
2223 $newparentcat = core_course_category::get($deletecat->parent);
2226 // This operation is not allowed. We must move contents to an existing category.
2227 if (!$newparentcat->id) {
2228 throw new moodle_exception('movecatcontentstoroot');
2231 self::validate_context(context_coursecat::instance($newparentcat->id));
2232 if ($deletecat->can_move_content_to($newparentcat->id)) {
2233 $deletecat->delete_move($newparentcat->id, false);
2234 } else {
2235 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2240 $transaction->allow_commit();
2244 * Returns description of method parameters
2246 * @return external_function_parameters
2247 * @since Moodle 2.3
2249 public static function delete_categories_returns() {
2250 return null;
2254 * Describes the parameters for delete_modules.
2256 * @return external_function_parameters
2257 * @since Moodle 2.5
2259 public static function delete_modules_parameters() {
2260 return new external_function_parameters (
2261 array(
2262 'cmids' => new external_multiple_structure(new external_value(PARAM_INT, 'course module ID',
2263 VALUE_REQUIRED, '', NULL_NOT_ALLOWED), 'Array of course module IDs'),
2269 * Deletes a list of provided module instances.
2271 * @param array $cmids the course module ids
2272 * @since Moodle 2.5
2274 public static function delete_modules($cmids) {
2275 global $CFG, $DB;
2277 // Require course file containing the course delete module function.
2278 require_once($CFG->dirroot . "/course/lib.php");
2280 // Clean the parameters.
2281 $params = self::validate_parameters(self::delete_modules_parameters(), array('cmids' => $cmids));
2283 // Keep track of the course ids we have performed a capability check on to avoid repeating.
2284 $arrcourseschecked = array();
2286 foreach ($params['cmids'] as $cmid) {
2287 // Get the course module.
2288 $cm = $DB->get_record('course_modules', array('id' => $cmid), '*', MUST_EXIST);
2290 // Check if we have not yet confirmed they have permission in this course.
2291 if (!in_array($cm->course, $arrcourseschecked)) {
2292 // Ensure the current user has required permission in this course.
2293 $context = context_course::instance($cm->course);
2294 self::validate_context($context);
2295 // Add to the array.
2296 $arrcourseschecked[] = $cm->course;
2299 // Ensure they can delete this module.
2300 $modcontext = context_module::instance($cm->id);
2301 require_capability('moodle/course:manageactivities', $modcontext);
2303 // Delete the module.
2304 course_delete_module($cm->id);
2309 * Describes the delete_modules return value.
2311 * @return external_single_structure
2312 * @since Moodle 2.5
2314 public static function delete_modules_returns() {
2315 return null;
2319 * Returns description of method parameters
2321 * @return external_function_parameters
2322 * @since Moodle 2.9
2324 public static function view_course_parameters() {
2325 return new external_function_parameters(
2326 array(
2327 'courseid' => new external_value(PARAM_INT, 'id of the course'),
2328 'sectionnumber' => new external_value(PARAM_INT, 'section number', VALUE_DEFAULT, 0)
2334 * Trigger the course viewed event.
2336 * @param int $courseid id of course
2337 * @param int $sectionnumber sectionnumber (0, 1, 2...)
2338 * @return array of warnings and status result
2339 * @since Moodle 2.9
2340 * @throws moodle_exception
2342 public static function view_course($courseid, $sectionnumber = 0) {
2343 global $CFG;
2344 require_once($CFG->dirroot . "/course/lib.php");
2346 $params = self::validate_parameters(self::view_course_parameters(),
2347 array(
2348 'courseid' => $courseid,
2349 'sectionnumber' => $sectionnumber
2352 $warnings = array();
2354 $course = get_course($params['courseid']);
2355 $context = context_course::instance($course->id);
2356 self::validate_context($context);
2358 if (!empty($params['sectionnumber'])) {
2360 // Get section details and check it exists.
2361 $modinfo = get_fast_modinfo($course);
2362 $coursesection = $modinfo->get_section_info($params['sectionnumber'], MUST_EXIST);
2364 // Check user is allowed to see it.
2365 if (!$coursesection->uservisible) {
2366 require_capability('moodle/course:viewhiddensections', $context);
2370 course_view($context, $params['sectionnumber']);
2372 $result = array();
2373 $result['status'] = true;
2374 $result['warnings'] = $warnings;
2375 return $result;
2379 * Returns description of method result value
2381 * @return external_description
2382 * @since Moodle 2.9
2384 public static function view_course_returns() {
2385 return new external_single_structure(
2386 array(
2387 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
2388 'warnings' => new external_warnings()
2394 * Returns description of method parameters
2396 * @return external_function_parameters
2397 * @since Moodle 3.0
2399 public static function search_courses_parameters() {
2400 return new external_function_parameters(
2401 array(
2402 'criterianame' => new external_value(PARAM_ALPHA, 'criteria name
2403 (search, modulelist (only admins), blocklist (only admins), tagid)'),
2404 'criteriavalue' => new external_value(PARAM_RAW, 'criteria value'),
2405 'page' => new external_value(PARAM_INT, 'page number (0 based)', VALUE_DEFAULT, 0),
2406 'perpage' => new external_value(PARAM_INT, 'items per page', VALUE_DEFAULT, 0),
2407 'requiredcapabilities' => new external_multiple_structure(
2408 new external_value(PARAM_CAPABILITY, 'Capability string used to filter courses by permission'),
2409 'Optional list of required capabilities (used to filter the list)', VALUE_DEFAULT, array()
2411 'limittoenrolled' => new external_value(PARAM_BOOL, 'limit to enrolled courses', VALUE_DEFAULT, 0),
2412 'onlywithcompletion' => new external_value(PARAM_BOOL, 'limit to courses where completion is enabled',
2413 VALUE_DEFAULT, 0),
2419 * Return the course information that is public (visible by every one)
2421 * @param core_course_list_element $course course in list object
2422 * @param stdClass $coursecontext course context object
2423 * @return array the course information
2424 * @since Moodle 3.2
2426 protected static function get_course_public_information(core_course_list_element $course, $coursecontext) {
2428 static $categoriescache = array();
2430 // Category information.
2431 if (!array_key_exists($course->category, $categoriescache)) {
2432 $categoriescache[$course->category] = core_course_category::get($course->category, IGNORE_MISSING);
2434 $category = $categoriescache[$course->category];
2436 // Retrieve course overview used files.
2437 $files = array();
2438 foreach ($course->get_course_overviewfiles() as $file) {
2439 $fileurl = moodle_url::make_webservice_pluginfile_url($file->get_contextid(), $file->get_component(),
2440 $file->get_filearea(), null, $file->get_filepath(),
2441 $file->get_filename())->out(false);
2442 $files[] = array(
2443 'filename' => $file->get_filename(),
2444 'fileurl' => $fileurl,
2445 'filesize' => $file->get_filesize(),
2446 'filepath' => $file->get_filepath(),
2447 'mimetype' => $file->get_mimetype(),
2448 'timemodified' => $file->get_timemodified(),
2452 // Retrieve the course contacts,
2453 // we need here the users fullname since if we are not enrolled can be difficult to obtain them via other Web Services.
2454 $coursecontacts = array();
2455 foreach ($course->get_course_contacts() as $contact) {
2456 $coursecontacts[] = array(
2457 'id' => $contact['user']->id,
2458 'fullname' => $contact['username'],
2459 'roles' => array_map(function($role){
2460 return array('id' => $role->id, 'name' => $role->displayname);
2461 }, $contact['roles']),
2462 'role' => array('id' => $contact['role']->id, 'name' => $contact['role']->displayname),
2463 'rolename' => $contact['rolename']
2467 // Allowed enrolment methods (maybe we can self-enrol).
2468 $enroltypes = array();
2469 $instances = enrol_get_instances($course->id, true);
2470 foreach ($instances as $instance) {
2471 $enroltypes[] = $instance->enrol;
2474 // Format summary.
2475 list($summary, $summaryformat) =
2476 external_format_text($course->summary, $course->summaryformat, $coursecontext->id, 'course', 'summary', null);
2478 $categoryname = '';
2479 if (!empty($category)) {
2480 $categoryname = external_format_string($category->name, $category->get_context());
2483 $displayname = get_course_display_name_for_list($course);
2484 $coursereturns = array();
2485 $coursereturns['id'] = $course->id;
2486 $coursereturns['fullname'] = external_format_string($course->fullname, $coursecontext->id);
2487 $coursereturns['displayname'] = external_format_string($displayname, $coursecontext->id);
2488 $coursereturns['shortname'] = external_format_string($course->shortname, $coursecontext->id);
2489 $coursereturns['categoryid'] = $course->category;
2490 $coursereturns['categoryname'] = $categoryname;
2491 $coursereturns['summary'] = $summary;
2492 $coursereturns['summaryformat'] = $summaryformat;
2493 $coursereturns['summaryfiles'] = external_util::get_area_files($coursecontext->id, 'course', 'summary', false, false);
2494 $coursereturns['overviewfiles'] = $files;
2495 $coursereturns['contacts'] = $coursecontacts;
2496 $coursereturns['enrollmentmethods'] = $enroltypes;
2497 $coursereturns['sortorder'] = $course->sortorder;
2498 $coursereturns['showactivitydates'] = $course->showactivitydates;
2499 $coursereturns['showcompletionconditions'] = $course->showcompletionconditions;
2501 $handler = core_course\customfield\course_handler::create();
2502 if ($customfields = $handler->export_instance_data($course->id)) {
2503 $coursereturns['customfields'] = [];
2504 foreach ($customfields as $data) {
2505 $coursereturns['customfields'][] = [
2506 'type' => $data->get_type(),
2507 'value' => $data->get_value(),
2508 'valueraw' => $data->get_data_controller()->get_value(),
2509 'name' => $data->get_name(),
2510 'shortname' => $data->get_shortname()
2515 return $coursereturns;
2519 * Search courses following the specified criteria.
2521 * @param string $criterianame Criteria name (search, modulelist (only admins), blocklist (only admins), tagid)
2522 * @param string $criteriavalue Criteria value
2523 * @param int $page Page number (for pagination)
2524 * @param int $perpage Items per page
2525 * @param array $requiredcapabilities Optional list of required capabilities (used to filter the list).
2526 * @param int $limittoenrolled Limit to only enrolled courses
2527 * @param int onlywithcompletion Limit to only courses where completion is enabled
2528 * @return array of course objects and warnings
2529 * @since Moodle 3.0
2530 * @throws moodle_exception
2532 public static function search_courses($criterianame,
2533 $criteriavalue,
2534 $page=0,
2535 $perpage=0,
2536 $requiredcapabilities=array(),
2537 $limittoenrolled=0,
2538 $onlywithcompletion=0) {
2539 global $CFG;
2541 $warnings = array();
2543 $parameters = array(
2544 'criterianame' => $criterianame,
2545 'criteriavalue' => $criteriavalue,
2546 'page' => $page,
2547 'perpage' => $perpage,
2548 'requiredcapabilities' => $requiredcapabilities,
2549 'limittoenrolled' => $limittoenrolled,
2550 'onlywithcompletion' => $onlywithcompletion
2552 $params = self::validate_parameters(self::search_courses_parameters(), $parameters);
2553 self::validate_context(context_system::instance());
2555 $allowedcriterianames = array('search', 'modulelist', 'blocklist', 'tagid');
2556 if (!in_array($params['criterianame'], $allowedcriterianames)) {
2557 throw new invalid_parameter_exception('Invalid value for criterianame parameter (value: '.$params['criterianame'].'),' .
2558 'allowed values are: '.implode(',', $allowedcriterianames));
2561 if ($params['criterianame'] == 'modulelist' or $params['criterianame'] == 'blocklist') {
2562 require_capability('moodle/site:config', context_system::instance());
2565 $paramtype = array(
2566 'search' => PARAM_RAW,
2567 'modulelist' => PARAM_PLUGIN,
2568 'blocklist' => PARAM_INT,
2569 'tagid' => PARAM_INT
2571 $params['criteriavalue'] = clean_param($params['criteriavalue'], $paramtype[$params['criterianame']]);
2573 // Prepare the search API options.
2574 $searchcriteria = array();
2575 $searchcriteria[$params['criterianame']] = $params['criteriavalue'];
2576 if ($params['onlywithcompletion']) {
2577 $searchcriteria['onlywithcompletion'] = true;
2580 $options = array();
2581 if ($params['perpage'] != 0) {
2582 $offset = $params['page'] * $params['perpage'];
2583 $options = array('offset' => $offset, 'limit' => $params['perpage']);
2586 // Search the courses.
2587 $courses = core_course_category::search_courses($searchcriteria, $options, $params['requiredcapabilities']);
2588 $totalcount = core_course_category::search_courses_count($searchcriteria, $options, $params['requiredcapabilities']);
2590 if (!empty($limittoenrolled)) {
2591 // Get the courses where the current user has access.
2592 $enrolled = enrol_get_my_courses(array('id', 'cacherev'));
2595 $finalcourses = array();
2596 $categoriescache = array();
2598 foreach ($courses as $course) {
2599 if (!empty($limittoenrolled)) {
2600 // Filter out not enrolled courses.
2601 if (!isset($enrolled[$course->id])) {
2602 $totalcount--;
2603 continue;
2607 $coursecontext = context_course::instance($course->id);
2609 $finalcourses[] = self::get_course_public_information($course, $coursecontext);
2612 return array(
2613 'total' => $totalcount,
2614 'courses' => $finalcourses,
2615 'warnings' => $warnings
2620 * Returns a course structure definition
2622 * @param boolean $onlypublicdata set to true, to retrieve only fields viewable by anyone when the course is visible
2623 * @return array the course structure
2624 * @since Moodle 3.2
2626 protected static function get_course_structure($onlypublicdata = true) {
2627 $coursestructure = array(
2628 'id' => new external_value(PARAM_INT, 'course id'),
2629 'fullname' => new external_value(PARAM_RAW, 'course full name'),
2630 'displayname' => new external_value(PARAM_RAW, 'course display name'),
2631 'shortname' => new external_value(PARAM_RAW, 'course short name'),
2632 'categoryid' => new external_value(PARAM_INT, 'category id'),
2633 'categoryname' => new external_value(PARAM_RAW, 'category name'),
2634 'sortorder' => new external_value(PARAM_INT, 'Sort order in the category', VALUE_OPTIONAL),
2635 'summary' => new external_value(PARAM_RAW, 'summary'),
2636 'summaryformat' => new external_format_value('summary'),
2637 'summaryfiles' => new external_files('summary files in the summary field', VALUE_OPTIONAL),
2638 'overviewfiles' => new external_files('additional overview files attached to this course'),
2639 'showactivitydates' => new external_value(PARAM_BOOL, 'Whether the activity dates are shown or not'),
2640 'showcompletionconditions' => new external_value(PARAM_BOOL,
2641 'Whether the activity completion conditions are shown or not'),
2642 'contacts' => new external_multiple_structure(
2643 new external_single_structure(
2644 array(
2645 'id' => new external_value(PARAM_INT, 'contact user id'),
2646 'fullname' => new external_value(PARAM_NOTAGS, 'contact user fullname'),
2649 'contact users'
2651 'enrollmentmethods' => new external_multiple_structure(
2652 new external_value(PARAM_PLUGIN, 'enrollment method'),
2653 'enrollment methods list'
2655 'customfields' => new external_multiple_structure(
2656 new external_single_structure(
2657 array(
2658 'name' => new external_value(PARAM_RAW, 'The name of the custom field'),
2659 'shortname' => new external_value(PARAM_RAW,
2660 'The shortname of the custom field - to be able to build the field class in the code'),
2661 'type' => new external_value(PARAM_ALPHANUMEXT,
2662 'The type of the custom field - text field, checkbox...'),
2663 'valueraw' => new external_value(PARAM_RAW, 'The raw value of the custom field'),
2664 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
2666 ), 'Custom fields', VALUE_OPTIONAL),
2669 if (!$onlypublicdata) {
2670 $extra = array(
2671 'idnumber' => new external_value(PARAM_RAW, 'Id number', VALUE_OPTIONAL),
2672 'format' => new external_value(PARAM_PLUGIN, 'Course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
2673 'showgrades' => new external_value(PARAM_INT, '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
2674 'newsitems' => new external_value(PARAM_INT, 'Number of recent items appearing on the course page', VALUE_OPTIONAL),
2675 'startdate' => new external_value(PARAM_INT, 'Timestamp when the course start', VALUE_OPTIONAL),
2676 'enddate' => new external_value(PARAM_INT, 'Timestamp when the course end', VALUE_OPTIONAL),
2677 'maxbytes' => new external_value(PARAM_INT, 'Largest size of file that can be uploaded into', VALUE_OPTIONAL),
2678 'showreports' => new external_value(PARAM_INT, 'Are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
2679 'visible' => new external_value(PARAM_INT, '1: available to student, 0:not available', VALUE_OPTIONAL),
2680 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
2681 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
2682 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
2683 'enablecompletion' => new external_value(PARAM_INT, 'Completion enabled? 1: yes 0: no', VALUE_OPTIONAL),
2684 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
2685 'lang' => new external_value(PARAM_SAFEDIR, 'Forced course language', VALUE_OPTIONAL),
2686 'theme' => new external_value(PARAM_PLUGIN, 'Fame of the forced theme', VALUE_OPTIONAL),
2687 'marker' => new external_value(PARAM_INT, 'Current course marker', VALUE_OPTIONAL),
2688 'legacyfiles' => new external_value(PARAM_INT, 'If legacy files are enabled', VALUE_OPTIONAL),
2689 'calendartype' => new external_value(PARAM_PLUGIN, 'Calendar type', VALUE_OPTIONAL),
2690 'timecreated' => new external_value(PARAM_INT, 'Time when the course was created', VALUE_OPTIONAL),
2691 'timemodified' => new external_value(PARAM_INT, 'Last time the course was updated', VALUE_OPTIONAL),
2692 'requested' => new external_value(PARAM_INT, 'If is a requested course', VALUE_OPTIONAL),
2693 'cacherev' => new external_value(PARAM_INT, 'Cache revision number', VALUE_OPTIONAL),
2694 'filters' => new external_multiple_structure(
2695 new external_single_structure(
2696 array(
2697 'filter' => new external_value(PARAM_PLUGIN, 'Filter plugin name'),
2698 'localstate' => new external_value(PARAM_INT, 'Filter state: 1 for on, -1 for off, 0 if inherit'),
2699 'inheritedstate' => new external_value(PARAM_INT, '1 or 0 to use when localstate is set to inherit'),
2702 'Course filters', VALUE_OPTIONAL
2704 'courseformatoptions' => new external_multiple_structure(
2705 new external_single_structure(
2706 array(
2707 'name' => new external_value(PARAM_RAW, 'Course format option name.'),
2708 'value' => new external_value(PARAM_RAW, 'Course format option value.'),
2711 'Additional options for particular course format.', VALUE_OPTIONAL
2714 $coursestructure = array_merge($coursestructure, $extra);
2716 return new external_single_structure($coursestructure);
2720 * Returns description of method result value
2722 * @return external_description
2723 * @since Moodle 3.0
2725 public static function search_courses_returns() {
2726 return new external_single_structure(
2727 array(
2728 'total' => new external_value(PARAM_INT, 'total course count'),
2729 'courses' => new external_multiple_structure(self::get_course_structure(), 'course'),
2730 'warnings' => new external_warnings()
2736 * Returns description of method parameters
2738 * @return external_function_parameters
2739 * @since Moodle 3.0
2741 public static function get_course_module_parameters() {
2742 return new external_function_parameters(
2743 array(
2744 'cmid' => new external_value(PARAM_INT, 'The course module id')
2750 * Return information about a course module.
2752 * @param int $cmid the course module id
2753 * @return array of warnings and the course module
2754 * @since Moodle 3.0
2755 * @throws moodle_exception
2757 public static function get_course_module($cmid) {
2758 global $CFG, $DB;
2760 $params = self::validate_parameters(self::get_course_module_parameters(), array('cmid' => $cmid));
2761 $warnings = array();
2763 $cm = get_coursemodule_from_id(null, $params['cmid'], 0, true, MUST_EXIST);
2764 $context = context_module::instance($cm->id);
2765 self::validate_context($context);
2767 // If the user has permissions to manage the activity, return all the information.
2768 if (has_capability('moodle/course:manageactivities', $context)) {
2769 require_once($CFG->dirroot . '/course/modlib.php');
2770 require_once($CFG->libdir . '/gradelib.php');
2772 $info = $cm;
2773 // Get the extra information: grade, advanced grading and outcomes data.
2774 $course = get_course($cm->course);
2775 list($newcm, $newcontext, $module, $extrainfo, $cw) = get_moduleinfo_data($cm, $course);
2776 // Grades.
2777 $gradeinfo = array('grade', 'gradepass', 'gradecat');
2778 foreach ($gradeinfo as $gfield) {
2779 if (isset($extrainfo->{$gfield})) {
2780 $info->{$gfield} = $extrainfo->{$gfield};
2783 if (isset($extrainfo->grade) and $extrainfo->grade < 0) {
2784 $info->scale = $DB->get_field('scale', 'scale', array('id' => abs($extrainfo->grade)));
2786 // Advanced grading.
2787 if (isset($extrainfo->_advancedgradingdata)) {
2788 $info->advancedgrading = array();
2789 foreach ($extrainfo as $key => $val) {
2790 if (strpos($key, 'advancedgradingmethod_') === 0) {
2791 $info->advancedgrading[] = array(
2792 'area' => str_replace('advancedgradingmethod_', '', $key),
2793 'method' => $val
2798 // Outcomes.
2799 foreach ($extrainfo as $key => $val) {
2800 if (strpos($key, 'outcome_') === 0) {
2801 if (!isset($info->outcomes)) {
2802 $info->outcomes = array();
2804 $id = str_replace('outcome_', '', $key);
2805 $outcome = grade_outcome::fetch(array('id' => $id));
2806 $scaleitems = $outcome->load_scale();
2807 $info->outcomes[] = array(
2808 'id' => $id,
2809 'name' => external_format_string($outcome->get_name(), $context->id),
2810 'scale' => $scaleitems->scale
2814 } else {
2815 // Return information is safe to show to any user.
2816 $info = new stdClass();
2817 $info->id = $cm->id;
2818 $info->course = $cm->course;
2819 $info->module = $cm->module;
2820 $info->modname = $cm->modname;
2821 $info->instance = $cm->instance;
2822 $info->section = $cm->section;
2823 $info->sectionnum = $cm->sectionnum;
2824 $info->groupmode = $cm->groupmode;
2825 $info->groupingid = $cm->groupingid;
2826 $info->completion = $cm->completion;
2827 $info->downloadcontent = $cm->downloadcontent;
2829 // Format name.
2830 $info->name = external_format_string($cm->name, $context->id);
2831 $result = array();
2832 $result['cm'] = $info;
2833 $result['warnings'] = $warnings;
2834 return $result;
2838 * Returns description of method result value
2840 * @return external_description
2841 * @since Moodle 3.0
2843 public static function get_course_module_returns() {
2844 return new external_single_structure(
2845 array(
2846 'cm' => new external_single_structure(
2847 array(
2848 'id' => new external_value(PARAM_INT, 'The course module id'),
2849 'course' => new external_value(PARAM_INT, 'The course id'),
2850 'module' => new external_value(PARAM_INT, 'The module type id'),
2851 'name' => new external_value(PARAM_RAW, 'The activity name'),
2852 'modname' => new external_value(PARAM_COMPONENT, 'The module component name (forum, assign, etc..)'),
2853 'instance' => new external_value(PARAM_INT, 'The activity instance id'),
2854 'section' => new external_value(PARAM_INT, 'The module section id'),
2855 'sectionnum' => new external_value(PARAM_INT, 'The module section number'),
2856 'groupmode' => new external_value(PARAM_INT, 'Group mode'),
2857 'groupingid' => new external_value(PARAM_INT, 'Grouping id'),
2858 'completion' => new external_value(PARAM_INT, 'If completion is enabled'),
2859 'idnumber' => new external_value(PARAM_RAW, 'Module id number', VALUE_OPTIONAL),
2860 'added' => new external_value(PARAM_INT, 'Time added', VALUE_OPTIONAL),
2861 'score' => new external_value(PARAM_INT, 'Score', VALUE_OPTIONAL),
2862 'indent' => new external_value(PARAM_INT, 'Indentation', VALUE_OPTIONAL),
2863 'visible' => new external_value(PARAM_INT, 'If visible', VALUE_OPTIONAL),
2864 'visibleoncoursepage' => new external_value(PARAM_INT, 'If visible on course page', VALUE_OPTIONAL),
2865 'visibleold' => new external_value(PARAM_INT, 'Visible old', VALUE_OPTIONAL),
2866 'completiongradeitemnumber' => new external_value(PARAM_INT, 'Completion grade item', VALUE_OPTIONAL),
2867 'completionpassgrade' => new external_value(PARAM_INT, 'Completion pass grade setting', VALUE_OPTIONAL),
2868 'completionview' => new external_value(PARAM_INT, 'Completion view setting', VALUE_OPTIONAL),
2869 'completionexpected' => new external_value(PARAM_INT, 'Completion time expected', VALUE_OPTIONAL),
2870 'showdescription' => new external_value(PARAM_INT, 'If the description is showed', VALUE_OPTIONAL),
2871 'downloadcontent' => new external_value(PARAM_INT, 'The download content value', VALUE_OPTIONAL),
2872 'availability' => new external_value(PARAM_RAW, 'Availability settings', VALUE_OPTIONAL),
2873 'grade' => new external_value(PARAM_FLOAT, 'Grade (max value or scale id)', VALUE_OPTIONAL),
2874 'scale' => new external_value(PARAM_TEXT, 'Scale items (if used)', VALUE_OPTIONAL),
2875 'gradepass' => new external_value(PARAM_RAW, 'Grade to pass (float)', VALUE_OPTIONAL),
2876 'gradecat' => new external_value(PARAM_INT, 'Grade category', VALUE_OPTIONAL),
2877 'advancedgrading' => new external_multiple_structure(
2878 new external_single_structure(
2879 array(
2880 'area' => new external_value(PARAM_AREA, 'Gradable area name'),
2881 'method' => new external_value(PARAM_COMPONENT, 'Grading method'),
2884 'Advanced grading settings', VALUE_OPTIONAL
2886 'outcomes' => new external_multiple_structure(
2887 new external_single_structure(
2888 array(
2889 'id' => new external_value(PARAM_ALPHANUMEXT, 'Outcome id'),
2890 'name' => new external_value(PARAM_RAW, 'Outcome full name'),
2891 'scale' => new external_value(PARAM_TEXT, 'Scale items')
2894 'Outcomes information', VALUE_OPTIONAL
2898 'warnings' => new external_warnings()
2904 * Returns description of method parameters
2906 * @return external_function_parameters
2907 * @since Moodle 3.0
2909 public static function get_course_module_by_instance_parameters() {
2910 return new external_function_parameters(
2911 array(
2912 'module' => new external_value(PARAM_COMPONENT, 'The module name'),
2913 'instance' => new external_value(PARAM_INT, 'The module instance id')
2919 * Return information about a course module.
2921 * @param string $module the module name
2922 * @param int $instance the activity instance id
2923 * @return array of warnings and the course module
2924 * @since Moodle 3.0
2925 * @throws moodle_exception
2927 public static function get_course_module_by_instance($module, $instance) {
2929 $params = self::validate_parameters(self::get_course_module_by_instance_parameters(),
2930 array(
2931 'module' => $module,
2932 'instance' => $instance,
2935 $warnings = array();
2936 $cm = get_coursemodule_from_instance($params['module'], $params['instance'], 0, false, MUST_EXIST);
2938 return self::get_course_module($cm->id);
2942 * Returns description of method result value
2944 * @return external_description
2945 * @since Moodle 3.0
2947 public static function get_course_module_by_instance_returns() {
2948 return self::get_course_module_returns();
2952 * Returns description of method parameters
2954 * @return external_function_parameters
2955 * @since Moodle 3.2
2957 public static function get_user_navigation_options_parameters() {
2958 return new external_function_parameters(
2959 array(
2960 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2966 * Return a list of navigation options in a set of courses that are avaialable or not for the current user.
2968 * @param array $courseids a list of course ids
2969 * @return array of warnings and the options availability
2970 * @since Moodle 3.2
2971 * @throws moodle_exception
2973 public static function get_user_navigation_options($courseids) {
2974 global $CFG;
2975 require_once($CFG->dirroot . '/course/lib.php');
2977 // Parameter validation.
2978 $params = self::validate_parameters(self::get_user_navigation_options_parameters(), array('courseids' => $courseids));
2979 $courseoptions = array();
2981 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
2983 if (!empty($courses)) {
2984 foreach ($courses as $course) {
2985 // Fix the context for the frontpage.
2986 if ($course->id == SITEID) {
2987 $course->context = context_system::instance();
2989 $navoptions = course_get_user_navigation_options($course->context, $course);
2990 $options = array();
2991 foreach ($navoptions as $name => $available) {
2992 $options[] = array(
2993 'name' => $name,
2994 'available' => $available,
2998 $courseoptions[] = array(
2999 'id' => $course->id,
3000 'options' => $options
3005 $result = array(
3006 'courses' => $courseoptions,
3007 'warnings' => $warnings
3009 return $result;
3013 * Returns description of method result value
3015 * @return external_description
3016 * @since Moodle 3.2
3018 public static function get_user_navigation_options_returns() {
3019 return new external_single_structure(
3020 array(
3021 'courses' => new external_multiple_structure(
3022 new external_single_structure(
3023 array(
3024 'id' => new external_value(PARAM_INT, 'Course id'),
3025 'options' => new external_multiple_structure(
3026 new external_single_structure(
3027 array(
3028 'name' => new external_value(PARAM_ALPHANUMEXT, 'Option name'),
3029 'available' => new external_value(PARAM_BOOL, 'Whether the option is available or not'),
3034 ), 'List of courses'
3036 'warnings' => new external_warnings()
3042 * Returns description of method parameters
3044 * @return external_function_parameters
3045 * @since Moodle 3.2
3047 public static function get_user_administration_options_parameters() {
3048 return new external_function_parameters(
3049 array(
3050 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
3056 * Return a list of administration options in a set of courses that are available or not for the current user.
3058 * @param array $courseids a list of course ids
3059 * @return array of warnings and the options availability
3060 * @since Moodle 3.2
3061 * @throws moodle_exception
3063 public static function get_user_administration_options($courseids) {
3064 global $CFG;
3065 require_once($CFG->dirroot . '/course/lib.php');
3067 // Parameter validation.
3068 $params = self::validate_parameters(self::get_user_administration_options_parameters(), array('courseids' => $courseids));
3069 $courseoptions = array();
3071 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
3073 if (!empty($courses)) {
3074 foreach ($courses as $course) {
3075 $adminoptions = course_get_user_administration_options($course, $course->context);
3076 $options = array();
3077 foreach ($adminoptions as $name => $available) {
3078 $options[] = array(
3079 'name' => $name,
3080 'available' => $available,
3084 $courseoptions[] = array(
3085 'id' => $course->id,
3086 'options' => $options
3091 $result = array(
3092 'courses' => $courseoptions,
3093 'warnings' => $warnings
3095 return $result;
3099 * Returns description of method result value
3101 * @return external_description
3102 * @since Moodle 3.2
3104 public static function get_user_administration_options_returns() {
3105 return self::get_user_navigation_options_returns();
3109 * Returns description of method parameters
3111 * @return external_function_parameters
3112 * @since Moodle 3.2
3114 public static function get_courses_by_field_parameters() {
3115 return new external_function_parameters(
3116 array(
3117 'field' => new external_value(PARAM_ALPHA, 'The field to search can be left empty for all courses or:
3118 id: course id
3119 ids: comma separated course ids
3120 shortname: course short name
3121 idnumber: course id number
3122 category: category id the course belongs to
3123 ', VALUE_DEFAULT, ''),
3124 'value' => new external_value(PARAM_RAW, 'The value to match', VALUE_DEFAULT, '')
3131 * Get courses matching a specific field (id/s, shortname, idnumber, category)
3133 * @param string $field field name to search, or empty for all courses
3134 * @param string $value value to search
3135 * @return array list of courses and warnings
3136 * @throws invalid_parameter_exception
3137 * @since Moodle 3.2
3139 public static function get_courses_by_field($field = '', $value = '') {
3140 global $DB, $CFG;
3141 require_once($CFG->dirroot . '/course/lib.php');
3142 require_once($CFG->libdir . '/filterlib.php');
3144 $params = self::validate_parameters(self::get_courses_by_field_parameters(),
3145 array(
3146 'field' => $field,
3147 'value' => $value,
3150 $warnings = array();
3152 if (empty($params['field'])) {
3153 $courses = $DB->get_records('course', null, 'id ASC');
3154 } else {
3155 switch ($params['field']) {
3156 case 'id':
3157 case 'category':
3158 $value = clean_param($params['value'], PARAM_INT);
3159 break;
3160 case 'ids':
3161 $value = clean_param($params['value'], PARAM_SEQUENCE);
3162 break;
3163 case 'shortname':
3164 $value = clean_param($params['value'], PARAM_TEXT);
3165 break;
3166 case 'idnumber':
3167 $value = clean_param($params['value'], PARAM_RAW);
3168 break;
3169 default:
3170 throw new invalid_parameter_exception('Invalid field name');
3173 if ($params['field'] === 'ids') {
3174 // Preload categories to avoid loading one at a time.
3175 $courseids = explode(',', $value);
3176 list ($listsql, $listparams) = $DB->get_in_or_equal($courseids);
3177 $categoryids = $DB->get_fieldset_sql("
3178 SELECT DISTINCT cc.id
3179 FROM {course} c
3180 JOIN {course_categories} cc ON cc.id = c.category
3181 WHERE c.id $listsql", $listparams);
3182 core_course_category::get_many($categoryids);
3184 // Load and validate all courses. This is called because it loads the courses
3185 // more efficiently.
3186 list ($courses, $warnings) = external_util::validate_courses($courseids, [],
3187 false, true);
3188 } else {
3189 $courses = $DB->get_records('course', array($params['field'] => $value), 'id ASC');
3193 $coursesdata = array();
3194 foreach ($courses as $course) {
3195 $context = context_course::instance($course->id);
3196 $canupdatecourse = has_capability('moodle/course:update', $context);
3197 $canviewhiddencourses = has_capability('moodle/course:viewhiddencourses', $context);
3199 // Check if the course is visible in the site for the user.
3200 if (!$course->visible and !$canviewhiddencourses and !$canupdatecourse) {
3201 continue;
3203 // Get the public course information, even if we are not enrolled.
3204 $courseinlist = new core_course_list_element($course);
3206 // Now, check if we have access to the course, unless it was already checked.
3207 try {
3208 if (empty($course->contextvalidated)) {
3209 self::validate_context($context);
3211 } catch (Exception $e) {
3212 // User can not access the course, check if they can see the public information about the course and return it.
3213 if (core_course_category::can_view_course_info($course)) {
3214 $coursesdata[$course->id] = self::get_course_public_information($courseinlist, $context);
3216 continue;
3218 $coursesdata[$course->id] = self::get_course_public_information($courseinlist, $context);
3219 // Return information for any user that can access the course.
3220 $coursefields = array('format', 'showgrades', 'newsitems', 'startdate', 'enddate', 'maxbytes', 'showreports', 'visible',
3221 'groupmode', 'groupmodeforce', 'defaultgroupingid', 'enablecompletion', 'completionnotify', 'lang', 'theme',
3222 'marker');
3224 // Course filters.
3225 $coursesdata[$course->id]['filters'] = filter_get_available_in_context($context);
3227 // Information for managers only.
3228 if ($canupdatecourse) {
3229 $managerfields = array('idnumber', 'legacyfiles', 'calendartype', 'timecreated', 'timemodified', 'requested',
3230 'cacherev');
3231 $coursefields = array_merge($coursefields, $managerfields);
3234 // Populate fields.
3235 foreach ($coursefields as $field) {
3236 $coursesdata[$course->id][$field] = $course->{$field};
3239 // Clean lang and auth fields for external functions (it may content uninstalled themes or language packs).
3240 if (isset($coursesdata[$course->id]['theme'])) {
3241 $coursesdata[$course->id]['theme'] = clean_param($coursesdata[$course->id]['theme'], PARAM_THEME);
3243 if (isset($coursesdata[$course->id]['lang'])) {
3244 $coursesdata[$course->id]['lang'] = clean_param($coursesdata[$course->id]['lang'], PARAM_LANG);
3247 $courseformatoptions = course_get_format($course)->get_config_for_external();
3248 foreach ($courseformatoptions as $key => $value) {
3249 $coursesdata[$course->id]['courseformatoptions'][] = array(
3250 'name' => $key,
3251 'value' => $value
3256 return array(
3257 'courses' => $coursesdata,
3258 'warnings' => $warnings
3263 * Returns description of method result value
3265 * @return external_description
3266 * @since Moodle 3.2
3268 public static function get_courses_by_field_returns() {
3269 // Course structure, including not only public viewable fields.
3270 return new external_single_structure(
3271 array(
3272 'courses' => new external_multiple_structure(self::get_course_structure(false), 'Course'),
3273 'warnings' => new external_warnings()
3279 * Returns description of method parameters
3281 * @return external_function_parameters
3282 * @since Moodle 3.2
3284 public static function check_updates_parameters() {
3285 return new external_function_parameters(
3286 array(
3287 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3288 'tocheck' => new external_multiple_structure(
3289 new external_single_structure(
3290 array(
3291 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level for the file location.
3292 Only module supported right now.'),
3293 'id' => new external_value(PARAM_INT, 'Context instance id'),
3294 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3297 'Instances to check'
3299 'filter' => new external_multiple_structure(
3300 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3301 gradeitems, outcomes'),
3302 'Check only for updates in these areas', VALUE_DEFAULT, array()
3309 * Check if there is updates affecting the user for the given course and contexts.
3310 * Right now only modules are supported.
3311 * This WS calls mod_check_updates_since for each module to check if there is any update the user should we aware of.
3313 * @param int $courseid the list of modules to check
3314 * @param array $tocheck the list of modules to check
3315 * @param array $filter check only for updates in these areas
3316 * @return array list of updates and warnings
3317 * @throws moodle_exception
3318 * @since Moodle 3.2
3320 public static function check_updates($courseid, $tocheck, $filter = array()) {
3321 global $CFG, $DB;
3322 require_once($CFG->dirroot . "/course/lib.php");
3324 $params = self::validate_parameters(
3325 self::check_updates_parameters(),
3326 array(
3327 'courseid' => $courseid,
3328 'tocheck' => $tocheck,
3329 'filter' => $filter,
3333 $course = get_course($params['courseid']);
3334 $context = context_course::instance($course->id);
3335 self::validate_context($context);
3337 list($instances, $warnings) = course_check_updates($course, $params['tocheck'], $filter);
3339 $instancesformatted = array();
3340 foreach ($instances as $instance) {
3341 $updates = array();
3342 foreach ($instance['updates'] as $name => $data) {
3343 if (empty($data->updated)) {
3344 continue;
3346 $updatedata = array(
3347 'name' => $name,
3349 if (!empty($data->timeupdated)) {
3350 $updatedata['timeupdated'] = $data->timeupdated;
3352 if (!empty($data->itemids)) {
3353 $updatedata['itemids'] = $data->itemids;
3355 $updates[] = $updatedata;
3357 if (!empty($updates)) {
3358 $instancesformatted[] = array(
3359 'contextlevel' => $instance['contextlevel'],
3360 'id' => $instance['id'],
3361 'updates' => $updates
3366 return array(
3367 'instances' => $instancesformatted,
3368 'warnings' => $warnings
3373 * Returns description of method result value
3375 * @return external_description
3376 * @since Moodle 3.2
3378 public static function check_updates_returns() {
3379 return new external_single_structure(
3380 array(
3381 'instances' => new external_multiple_structure(
3382 new external_single_structure(
3383 array(
3384 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level'),
3385 'id' => new external_value(PARAM_INT, 'Instance id'),
3386 'updates' => new external_multiple_structure(
3387 new external_single_structure(
3388 array(
3389 'name' => new external_value(PARAM_ALPHANUMEXT, 'Name of the area updated.'),
3390 'timeupdated' => new external_value(PARAM_INT, 'Last time was updated', VALUE_OPTIONAL),
3391 'itemids' => new external_multiple_structure(
3392 new external_value(PARAM_INT, 'Instance id'),
3393 'The ids of the items updated',
3394 VALUE_OPTIONAL
3402 'warnings' => new external_warnings()
3408 * Returns description of method parameters
3410 * @return external_function_parameters
3411 * @since Moodle 3.3
3413 public static function get_updates_since_parameters() {
3414 return new external_function_parameters(
3415 array(
3416 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3417 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3418 'filter' => new external_multiple_structure(
3419 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3420 gradeitems, outcomes'),
3421 'Check only for updates in these areas', VALUE_DEFAULT, array()
3428 * Check if there are updates affecting the user for the given course since the given time stamp.
3430 * This function is a wrapper of self::check_updates for retrieving all the updates since a given time for all the activities.
3432 * @param int $courseid the list of modules to check
3433 * @param int $since check updates since this time stamp
3434 * @param array $filter check only for updates in these areas
3435 * @return array list of updates and warnings
3436 * @throws moodle_exception
3437 * @since Moodle 3.3
3439 public static function get_updates_since($courseid, $since, $filter = array()) {
3440 global $CFG, $DB;
3442 $params = self::validate_parameters(
3443 self::get_updates_since_parameters(),
3444 array(
3445 'courseid' => $courseid,
3446 'since' => $since,
3447 'filter' => $filter,
3451 $course = get_course($params['courseid']);
3452 $modinfo = get_fast_modinfo($course);
3453 $tocheck = array();
3455 // Retrieve all the visible course modules for the current user.
3456 $cms = $modinfo->get_cms();
3457 foreach ($cms as $cm) {
3458 if (!$cm->uservisible) {
3459 continue;
3461 $tocheck[] = array(
3462 'id' => $cm->id,
3463 'contextlevel' => 'module',
3464 'since' => $params['since'],
3468 return self::check_updates($course->id, $tocheck, $params['filter']);
3472 * Returns description of method result value
3474 * @return external_description
3475 * @since Moodle 3.3
3477 public static function get_updates_since_returns() {
3478 return self::check_updates_returns();
3482 * Parameters for function edit_module()
3484 * @since Moodle 3.3
3485 * @return external_function_parameters
3487 public static function edit_module_parameters() {
3488 return new external_function_parameters(
3489 array(
3490 'action' => new external_value(PARAM_ALPHA,
3491 'action: hide, show, stealth, duplicate, delete, moveleft, moveright, group...', VALUE_REQUIRED),
3492 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3493 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3498 * Performs one of the edit module actions and return new html for AJAX
3500 * Returns html to replace the current module html with, for example:
3501 * - empty string for "delete" action,
3502 * - two modules html for "duplicate" action
3503 * - updated module html for everything else
3505 * Throws exception if operation is not permitted/possible
3507 * @since Moodle 3.3
3508 * @param string $action
3509 * @param int $id
3510 * @param null|int $sectionreturn
3511 * @return string
3513 public static function edit_module($action, $id, $sectionreturn = null) {
3514 global $PAGE, $DB;
3515 // Validate and normalize parameters.
3516 $params = self::validate_parameters(self::edit_module_parameters(),
3517 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3518 $action = $params['action'];
3519 $id = $params['id'];
3520 $sectionreturn = $params['sectionreturn'];
3522 // Set of permissions an editing user may have.
3523 $contextarray = [
3524 'moodle/course:update',
3525 'moodle/course:manageactivities',
3526 'moodle/course:activityvisibility',
3527 'moodle/course:sectionvisibility',
3528 'moodle/course:movesections',
3529 'moodle/course:setcurrentsection',
3531 $PAGE->set_other_editing_capability($contextarray);
3533 list($course, $cm) = get_course_and_cm_from_cmid($id);
3534 $modcontext = context_module::instance($cm->id);
3535 $coursecontext = context_course::instance($course->id);
3536 self::validate_context($modcontext);
3537 $format = course_get_format($course);
3538 if ($sectionreturn) {
3539 $format->set_section_number($sectionreturn);
3541 $renderer = $format->get_renderer($PAGE);
3543 switch($action) {
3544 case 'hide':
3545 case 'show':
3546 case 'stealth':
3547 require_capability('moodle/course:activityvisibility', $modcontext);
3548 $visible = ($action === 'hide') ? 0 : 1;
3549 $visibleoncoursepage = ($action === 'stealth') ? 0 : 1;
3550 set_coursemodule_visible($id, $visible, $visibleoncoursepage);
3551 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3552 break;
3553 case 'duplicate':
3554 require_capability('moodle/course:manageactivities', $coursecontext);
3555 require_capability('moodle/backup:backuptargetimport', $coursecontext);
3556 require_capability('moodle/restore:restoretargetimport', $coursecontext);
3557 if (!course_allowed_module($course, $cm->modname)) {
3558 throw new moodle_exception('No permission to create that activity');
3560 if ($newcm = duplicate_module($course, $cm)) {
3562 $modinfo = $format->get_modinfo();
3563 $section = $modinfo->get_section_info($newcm->sectionnum);
3564 $cm = $modinfo->get_cm($id);
3566 // Get both original and new element html.
3567 $result = $renderer->course_section_updated_cm_item($format, $section, $cm);
3568 $result .= $renderer->course_section_updated_cm_item($format, $section, $newcm);
3569 return $result;
3571 break;
3572 case 'groupsseparate':
3573 case 'groupsvisible':
3574 case 'groupsnone':
3575 require_capability('moodle/course:manageactivities', $modcontext);
3576 if ($action === 'groupsseparate') {
3577 $newgroupmode = SEPARATEGROUPS;
3578 } else if ($action === 'groupsvisible') {
3579 $newgroupmode = VISIBLEGROUPS;
3580 } else {
3581 $newgroupmode = NOGROUPS;
3583 if (set_coursemodule_groupmode($cm->id, $newgroupmode)) {
3584 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3586 break;
3587 case 'moveleft':
3588 case 'moveright':
3589 require_capability('moodle/course:manageactivities', $modcontext);
3590 $indent = $cm->indent + (($action === 'moveright') ? 1 : -1);
3591 if ($cm->indent >= 0) {
3592 $DB->update_record('course_modules', array('id' => $cm->id, 'indent' => $indent));
3593 rebuild_course_cache($cm->course);
3595 break;
3596 case 'delete':
3597 require_capability('moodle/course:manageactivities', $modcontext);
3598 course_delete_module($cm->id, true);
3599 return '';
3600 default:
3601 throw new coding_exception('Unrecognised action');
3604 $modinfo = $format->get_modinfo();
3605 $section = $modinfo->get_section_info($cm->sectionnum);
3606 $cm = $modinfo->get_cm($id);
3607 return $renderer->course_section_updated_cm_item($format, $section, $cm);
3611 * Return structure for edit_module()
3613 * @since Moodle 3.3
3614 * @return external_description
3616 public static function edit_module_returns() {
3617 return new external_value(PARAM_RAW, 'html to replace the current module with');
3621 * Parameters for function get_module()
3623 * @since Moodle 3.3
3624 * @return external_function_parameters
3626 public static function get_module_parameters() {
3627 return new external_function_parameters(
3628 array(
3629 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3630 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3635 * Returns html for displaying one activity module on course page
3637 * @since Moodle 3.3
3638 * @param int $id
3639 * @param null|int $sectionreturn
3640 * @return string
3642 public static function get_module($id, $sectionreturn = null) {
3643 global $PAGE;
3644 // Validate and normalize parameters.
3645 $params = self::validate_parameters(self::get_module_parameters(),
3646 array('id' => $id, 'sectionreturn' => $sectionreturn));
3647 $id = $params['id'];
3648 $sectionreturn = $params['sectionreturn'];
3650 // Set of permissions an editing user may have.
3651 $contextarray = [
3652 'moodle/course:update',
3653 'moodle/course:manageactivities',
3654 'moodle/course:activityvisibility',
3655 'moodle/course:sectionvisibility',
3656 'moodle/course:movesections',
3657 'moodle/course:setcurrentsection',
3659 $PAGE->set_other_editing_capability($contextarray);
3661 // Validate access to the course (note, this is html for the course view page, we don't validate access to the module).
3662 list($course, $cm) = get_course_and_cm_from_cmid($id);
3663 self::validate_context(context_course::instance($course->id));
3665 $format = course_get_format($course);
3666 if ($sectionreturn) {
3667 $format->set_section_number($sectionreturn);
3669 $renderer = $format->get_renderer($PAGE);
3671 $modinfo = $format->get_modinfo();
3672 $section = $modinfo->get_section_info($cm->sectionnum);
3673 return $renderer->course_section_updated_cm_item($format, $section, $cm);
3677 * Return structure for get_module()
3679 * @since Moodle 3.3
3680 * @return external_description
3682 public static function get_module_returns() {
3683 return new external_value(PARAM_RAW, 'html to replace the current module with');
3687 * Parameters for function edit_section()
3689 * @since Moodle 3.3
3690 * @return external_function_parameters
3692 public static function edit_section_parameters() {
3693 return new external_function_parameters(
3694 array(
3695 'action' => new external_value(PARAM_ALPHA, 'action: hide, show, stealth, setmarker, removemarker', VALUE_REQUIRED),
3696 'id' => new external_value(PARAM_INT, 'course section id', VALUE_REQUIRED),
3697 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3702 * Performs one of the edit section actions
3704 * @since Moodle 3.3
3705 * @param string $action
3706 * @param int $id section id
3707 * @param int $sectionreturn section to return to
3708 * @return string
3710 public static function edit_section($action, $id, $sectionreturn) {
3711 global $DB;
3712 // Validate and normalize parameters.
3713 $params = self::validate_parameters(self::edit_section_parameters(),
3714 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3715 $action = $params['action'];
3716 $id = $params['id'];
3717 $sr = $params['sectionreturn'];
3719 $section = $DB->get_record('course_sections', array('id' => $id), '*', MUST_EXIST);
3720 $coursecontext = context_course::instance($section->course);
3721 self::validate_context($coursecontext);
3723 $rv = course_get_format($section->course)->section_action($section, $action, $sectionreturn);
3724 if ($rv) {
3725 return json_encode($rv);
3726 } else {
3727 return null;
3732 * Return structure for edit_section()
3734 * @since Moodle 3.3
3735 * @return external_description
3737 public static function edit_section_returns() {
3738 return new external_value(PARAM_RAW, 'Additional data for javascript (JSON-encoded string)');
3742 * Returns description of method parameters
3744 * @return external_function_parameters
3746 public static function get_enrolled_courses_by_timeline_classification_parameters() {
3747 return new external_function_parameters(
3748 array(
3749 'classification' => new external_value(PARAM_ALPHA, 'future, inprogress, or past'),
3750 'limit' => new external_value(PARAM_INT, 'Result set limit', VALUE_DEFAULT, 0),
3751 'offset' => new external_value(PARAM_INT, 'Result set offset', VALUE_DEFAULT, 0),
3752 'sort' => new external_value(PARAM_TEXT, 'Sort string', VALUE_DEFAULT, null),
3753 'customfieldname' => new external_value(PARAM_ALPHANUMEXT, 'Used when classification = customfield',
3754 VALUE_DEFAULT, null),
3755 'customfieldvalue' => new external_value(PARAM_RAW, 'Used when classification = customfield',
3756 VALUE_DEFAULT, null),
3757 'searchvalue' => new external_value(PARAM_TEXT, 'The value a user wishes to search against',
3758 VALUE_DEFAULT, null),
3764 * Get courses matching the given timeline classification.
3766 * NOTE: The offset applies to the unfiltered full set of courses before the classification
3767 * filtering is done.
3768 * E.g.
3769 * If the user is enrolled in 5 courses:
3770 * c1, c2, c3, c4, and c5
3771 * And c4 and c5 are 'future' courses
3773 * If a request comes in for future courses with an offset of 1 it will mean that
3774 * c1 is skipped (because the offset applies *before* the classification filtering)
3775 * and c4 and c5 will be return.
3777 * @param string $classification past, inprogress, or future
3778 * @param int $limit Result set limit
3779 * @param int $offset Offset the full course set before timeline classification is applied
3780 * @param string $sort SQL sort string for results
3781 * @param string $customfieldname
3782 * @param string $customfieldvalue
3783 * @param string $searchvalue
3784 * @return array list of courses and warnings
3785 * @throws invalid_parameter_exception
3787 public static function get_enrolled_courses_by_timeline_classification(
3788 string $classification,
3789 int $limit = 0,
3790 int $offset = 0,
3791 string $sort = null,
3792 string $customfieldname = null,
3793 string $customfieldvalue = null,
3794 string $searchvalue = null
3796 global $CFG, $PAGE, $USER;
3797 require_once($CFG->dirroot . '/course/lib.php');
3799 $params = self::validate_parameters(self::get_enrolled_courses_by_timeline_classification_parameters(),
3800 array(
3801 'classification' => $classification,
3802 'limit' => $limit,
3803 'offset' => $offset,
3804 'sort' => $sort,
3805 'customfieldvalue' => $customfieldvalue,
3806 'searchvalue' => $searchvalue,
3810 $classification = $params['classification'];
3811 $limit = $params['limit'];
3812 $offset = $params['offset'];
3813 $sort = $params['sort'];
3814 $customfieldvalue = $params['customfieldvalue'];
3815 $searchvalue = $params['searchvalue'];
3817 switch($classification) {
3818 case COURSE_TIMELINE_ALLINCLUDINGHIDDEN:
3819 break;
3820 case COURSE_TIMELINE_ALL:
3821 break;
3822 case COURSE_TIMELINE_PAST:
3823 break;
3824 case COURSE_TIMELINE_INPROGRESS:
3825 break;
3826 case COURSE_TIMELINE_FUTURE:
3827 break;
3828 case COURSE_FAVOURITES:
3829 break;
3830 case COURSE_TIMELINE_HIDDEN:
3831 break;
3832 case COURSE_TIMELINE_SEARCH:
3833 break;
3834 case COURSE_CUSTOMFIELD:
3835 break;
3836 default:
3837 throw new invalid_parameter_exception('Invalid classification');
3840 self::validate_context(context_user::instance($USER->id));
3842 $requiredproperties = course_summary_exporter::define_properties();
3843 $fields = join(',', array_keys($requiredproperties));
3844 $hiddencourses = get_hidden_courses_on_timeline();
3845 $courses = [];
3847 // If the timeline requires really all courses, get really all courses.
3848 if ($classification == COURSE_TIMELINE_ALLINCLUDINGHIDDEN) {
3849 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields, COURSE_DB_QUERY_LIMIT);
3851 // Otherwise if the timeline requires the hidden courses then restrict the result to only $hiddencourses.
3852 } else if ($classification == COURSE_TIMELINE_HIDDEN) {
3853 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields,
3854 COURSE_DB_QUERY_LIMIT, $hiddencourses);
3856 // Otherwise get the requested courses and exclude the hidden courses.
3857 } else if ($classification == COURSE_TIMELINE_SEARCH) {
3858 // Prepare the search API options.
3859 $searchcriteria['search'] = $searchvalue;
3860 $options = ['idonly' => true];
3861 $courses = course_get_enrolled_courses_for_logged_in_user_from_search(
3863 $offset,
3864 $sort,
3865 $fields,
3866 COURSE_DB_QUERY_LIMIT,
3867 $searchcriteria,
3868 $options
3870 } else {
3871 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields,
3872 COURSE_DB_QUERY_LIMIT, [], $hiddencourses);
3875 $favouritecourseids = [];
3876 $ufservice = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($USER->id));
3877 $favourites = $ufservice->find_favourites_by_type('core_course', 'courses');
3879 if ($favourites) {
3880 $favouritecourseids = array_map(
3881 function($favourite) {
3882 return $favourite->itemid;
3883 }, $favourites);
3886 if ($classification == COURSE_FAVOURITES) {
3887 list($filteredcourses, $processedcount) = course_filter_courses_by_favourites(
3888 $courses,
3889 $favouritecourseids,
3890 $limit
3892 } else if ($classification == COURSE_CUSTOMFIELD) {
3893 list($filteredcourses, $processedcount) = course_filter_courses_by_customfield(
3894 $courses,
3895 $customfieldname,
3896 $customfieldvalue,
3897 $limit
3899 } else {
3900 list($filteredcourses, $processedcount) = course_filter_courses_by_timeline_classification(
3901 $courses,
3902 $classification,
3903 $limit
3907 $renderer = $PAGE->get_renderer('core');
3908 $formattedcourses = array_map(function($course) use ($renderer, $favouritecourseids) {
3909 if ($course == null) {
3910 return;
3912 context_helper::preload_from_record($course);
3913 $context = context_course::instance($course->id);
3914 $isfavourite = false;
3915 if (in_array($course->id, $favouritecourseids)) {
3916 $isfavourite = true;
3918 $exporter = new course_summary_exporter($course, ['context' => $context, 'isfavourite' => $isfavourite]);
3919 return $exporter->export($renderer);
3920 }, $filteredcourses);
3922 $formattedcourses = array_filter($formattedcourses, function($course) {
3923 if ($course != null) {
3924 return $course;
3928 return [
3929 'courses' => $formattedcourses,
3930 'nextoffset' => $offset + $processedcount
3935 * Returns description of method result value
3937 * @return external_description
3939 public static function get_enrolled_courses_by_timeline_classification_returns() {
3940 return new external_single_structure(
3941 array(
3942 'courses' => new external_multiple_structure(course_summary_exporter::get_read_structure(), 'Course'),
3943 'nextoffset' => new external_value(PARAM_INT, 'Offset for the next request')
3949 * Returns description of method parameters
3951 * @return external_function_parameters
3953 public static function set_favourite_courses_parameters() {
3954 return new external_function_parameters(
3955 array(
3956 'courses' => new external_multiple_structure(
3957 new external_single_structure(
3958 array(
3959 'id' => new external_value(PARAM_INT, 'course ID'),
3960 'favourite' => new external_value(PARAM_BOOL, 'favourite status')
3969 * Set the course favourite status for an array of courses.
3971 * @param array $courses List with course id's and favourite status.
3972 * @return array Array with an array of favourite courses.
3974 public static function set_favourite_courses(
3975 array $courses
3977 global $USER;
3979 $params = self::validate_parameters(self::set_favourite_courses_parameters(),
3980 array(
3981 'courses' => $courses
3985 $warnings = [];
3987 $ufservice = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($USER->id));
3989 foreach ($params['courses'] as $course) {
3991 $warning = [];
3993 $favouriteexists = $ufservice->favourite_exists('core_course', 'courses', $course['id'],
3994 \context_course::instance($course['id']));
3996 if ($course['favourite']) {
3997 if (!$favouriteexists) {
3998 try {
3999 $ufservice->create_favourite('core_course', 'courses', $course['id'],
4000 \context_course::instance($course['id']));
4001 } catch (Exception $e) {
4002 $warning['courseid'] = $course['id'];
4003 if ($e instanceof moodle_exception) {
4004 $warning['warningcode'] = $e->errorcode;
4005 } else {
4006 $warning['warningcode'] = $e->getCode();
4008 $warning['message'] = $e->getMessage();
4009 $warnings[] = $warning;
4010 $warnings[] = $warning;
4012 } else {
4013 $warning['courseid'] = $course['id'];
4014 $warning['warningcode'] = 'coursealreadyfavourited';
4015 $warning['message'] = 'Course already favourited';
4016 $warnings[] = $warning;
4018 } else {
4019 if ($favouriteexists) {
4020 try {
4021 $ufservice->delete_favourite('core_course', 'courses', $course['id'],
4022 \context_course::instance($course['id']));
4023 } catch (Exception $e) {
4024 $warning['courseid'] = $course['id'];
4025 if ($e instanceof moodle_exception) {
4026 $warning['warningcode'] = $e->errorcode;
4027 } else {
4028 $warning['warningcode'] = $e->getCode();
4030 $warning['message'] = $e->getMessage();
4031 $warnings[] = $warning;
4032 $warnings[] = $warning;
4034 } else {
4035 $warning['courseid'] = $course['id'];
4036 $warning['warningcode'] = 'cannotdeletefavourite';
4037 $warning['message'] = 'Could not delete favourite status for course';
4038 $warnings[] = $warning;
4043 return [
4044 'warnings' => $warnings
4049 * Returns description of method result value
4051 * @return external_description
4053 public static function set_favourite_courses_returns() {
4054 return new external_single_structure(
4055 array(
4056 'warnings' => new external_warnings()
4062 * Returns description of method parameters
4064 * @return external_function_parameters
4065 * @since Moodle 3.6
4067 public static function get_recent_courses_parameters() {
4068 return new external_function_parameters(
4069 array(
4070 'userid' => new external_value(PARAM_INT, 'id of the user, default to current user', VALUE_DEFAULT, 0),
4071 'limit' => new external_value(PARAM_INT, 'result set limit', VALUE_DEFAULT, 0),
4072 'offset' => new external_value(PARAM_INT, 'Result set offset', VALUE_DEFAULT, 0),
4073 'sort' => new external_value(PARAM_TEXT, 'Sort string', VALUE_DEFAULT, null)
4079 * Get last accessed courses adding additional course information like images.
4081 * @param int $userid User id from which the courses will be obtained
4082 * @param int $limit Restrict result set to this amount
4083 * @param int $offset Skip this number of records from the start of the result set
4084 * @param string|null $sort SQL string for sorting
4085 * @return array List of courses
4086 * @throws invalid_parameter_exception
4088 public static function get_recent_courses(int $userid = 0, int $limit = 0, int $offset = 0, string $sort = null) {
4089 global $USER, $PAGE;
4091 if (empty($userid)) {
4092 $userid = $USER->id;
4095 $params = self::validate_parameters(self::get_recent_courses_parameters(),
4096 array(
4097 'userid' => $userid,
4098 'limit' => $limit,
4099 'offset' => $offset,
4100 'sort' => $sort
4104 $userid = $params['userid'];
4105 $limit = $params['limit'];
4106 $offset = $params['offset'];
4107 $sort = $params['sort'];
4109 $usercontext = context_user::instance($userid);
4111 self::validate_context($usercontext);
4113 if ($userid != $USER->id and !has_capability('moodle/user:viewdetails', $usercontext)) {
4114 return array();
4117 $courses = course_get_recent_courses($userid, $limit, $offset, $sort);
4119 $renderer = $PAGE->get_renderer('core');
4121 $recentcourses = array_map(function($course) use ($renderer) {
4122 context_helper::preload_from_record($course);
4123 $context = context_course::instance($course->id);
4124 $isfavourite = !empty($course->component);
4125 $exporter = new course_summary_exporter($course, ['context' => $context, 'isfavourite' => $isfavourite]);
4126 return $exporter->export($renderer);
4127 }, $courses);
4129 return $recentcourses;
4133 * Returns description of method result value
4135 * @return external_description
4136 * @since Moodle 3.6
4138 public static function get_recent_courses_returns() {
4139 return new external_multiple_structure(course_summary_exporter::get_read_structure(), 'Courses');
4143 * Returns description of method parameters
4145 * @return external_function_parameters
4147 public static function get_enrolled_users_by_cmid_parameters() {
4148 return new external_function_parameters([
4149 'cmid' => new external_value(PARAM_INT, 'id of the course module', VALUE_REQUIRED),
4150 'groupid' => new external_value(PARAM_INT, 'id of the group', VALUE_DEFAULT, 0),
4155 * Get all users in a course for a given cmid.
4157 * @param int $cmid Course Module id from which the users will be obtained
4158 * @param int $groupid Group id from which the users will be obtained
4159 * @return array List of users
4160 * @throws invalid_parameter_exception
4162 public static function get_enrolled_users_by_cmid(int $cmid, int $groupid = 0) {
4163 global $PAGE;
4164 $warnings = [];
4167 'cmid' => $cmid,
4168 'groupid' => $groupid,
4169 ] = self::validate_parameters(self::get_enrolled_users_by_cmid_parameters(), [
4170 'cmid' => $cmid,
4171 'groupid' => $groupid,
4174 list($course, $cm) = get_course_and_cm_from_cmid($cmid);
4175 $coursecontext = context_course::instance($course->id);
4176 self::validate_context($coursecontext);
4178 $enrolledusers = get_enrolled_users($coursecontext, '', $groupid);
4180 $users = array_map(function ($user) use ($PAGE) {
4181 $user->fullname = fullname($user);
4182 $userpicture = new user_picture($user);
4183 $userpicture->size = 1;
4184 $user->profileimage = $userpicture->get_url($PAGE)->out(false);
4185 return $user;
4186 }, $enrolledusers);
4187 sort($users);
4189 return [
4190 'users' => $users,
4191 'warnings' => $warnings,
4196 * Returns description of method result value
4198 * @return external_description
4200 public static function get_enrolled_users_by_cmid_returns() {
4201 return new external_single_structure([
4202 'users' => new external_multiple_structure(self::user_description()),
4203 'warnings' => new external_warnings(),
4208 * Create user return value description.
4210 * @return external_description
4212 public static function user_description() {
4213 $userfields = array(
4214 'id' => new external_value(core_user::get_property_type('id'), 'ID of the user'),
4215 'profileimage' => new external_value(PARAM_URL, 'The location of the users larger image', VALUE_OPTIONAL),
4216 'fullname' => new external_value(PARAM_TEXT, 'The full name of the user', VALUE_OPTIONAL),
4217 'firstname' => new external_value(
4218 core_user::get_property_type('firstname'),
4219 'The first name(s) of the user',
4220 VALUE_OPTIONAL),
4221 'lastname' => new external_value(
4222 core_user::get_property_type('lastname'),
4223 'The family name of the user',
4224 VALUE_OPTIONAL),
4226 return new external_single_structure($userfields);
4230 * Returns description of method parameters.
4232 * @return external_function_parameters
4234 public static function add_content_item_to_user_favourites_parameters() {
4235 return new external_function_parameters([
4236 'componentname' => new external_value(PARAM_TEXT,
4237 'frankenstyle name of the component to which the content item belongs', VALUE_REQUIRED),
4238 'contentitemid' => new external_value(PARAM_INT, 'id of the content item', VALUE_REQUIRED, '', NULL_NOT_ALLOWED)
4243 * Add a content item to a user's favourites.
4245 * @param string $componentname the name of the component from which this content item originates.
4246 * @param int $contentitemid the id of the content item.
4247 * @return stdClass the exporter content item.
4249 public static function add_content_item_to_user_favourites(string $componentname, int $contentitemid) {
4250 global $USER;
4253 'componentname' => $componentname,
4254 'contentitemid' => $contentitemid,
4255 ] = self::validate_parameters(self::add_content_item_to_user_favourites_parameters(),
4257 'componentname' => $componentname,
4258 'contentitemid' => $contentitemid,
4262 self::validate_context(context_user::instance($USER->id));
4264 $contentitemservice = \core_course\local\factory\content_item_service_factory::get_content_item_service();
4266 return $contentitemservice->add_to_user_favourites($USER, $componentname, $contentitemid);
4270 * Returns description of method result value.
4272 * @return external_description
4274 public static function add_content_item_to_user_favourites_returns() {
4275 return \core_course\local\exporters\course_content_item_exporter::get_read_structure();
4279 * Returns description of method parameters.
4281 * @return external_function_parameters
4283 public static function remove_content_item_from_user_favourites_parameters() {
4284 return new external_function_parameters([
4285 'componentname' => new external_value(PARAM_TEXT,
4286 'frankenstyle name of the component to which the content item belongs', VALUE_REQUIRED),
4287 'contentitemid' => new external_value(PARAM_INT, 'id of the content item', VALUE_REQUIRED, '', NULL_NOT_ALLOWED),
4292 * Remove a content item from a user's favourites.
4294 * @param string $componentname the name of the component from which this content item originates.
4295 * @param int $contentitemid the id of the content item.
4296 * @return stdClass the exported content item.
4298 public static function remove_content_item_from_user_favourites(string $componentname, int $contentitemid) {
4299 global $USER;
4302 'componentname' => $componentname,
4303 'contentitemid' => $contentitemid,
4304 ] = self::validate_parameters(self::remove_content_item_from_user_favourites_parameters(),
4306 'componentname' => $componentname,
4307 'contentitemid' => $contentitemid,
4311 self::validate_context(context_user::instance($USER->id));
4313 $contentitemservice = \core_course\local\factory\content_item_service_factory::get_content_item_service();
4315 return $contentitemservice->remove_from_user_favourites($USER, $componentname, $contentitemid);
4319 * Returns description of method result value.
4321 * @return external_description
4323 public static function remove_content_item_from_user_favourites_returns() {
4324 return \core_course\local\exporters\course_content_item_exporter::get_read_structure();
4328 * Returns description of method result value
4330 * @return external_description
4332 public static function get_course_content_items_returns() {
4333 return new external_single_structure([
4334 'content_items' => new external_multiple_structure(
4335 \core_course\local\exporters\course_content_item_exporter::get_read_structure()
4341 * Returns description of method parameters
4343 * @return external_function_parameters
4345 public static function get_course_content_items_parameters() {
4346 return new external_function_parameters([
4347 'courseid' => new external_value(PARAM_INT, 'ID of the course', VALUE_REQUIRED),
4352 * Given a course ID fetch all accessible modules for that course
4354 * @param int $courseid The course we want to fetch the modules for
4355 * @return array Contains array of modules and their metadata
4357 public static function get_course_content_items(int $courseid) {
4358 global $USER;
4361 'courseid' => $courseid,
4362 ] = self::validate_parameters(self::get_course_content_items_parameters(), [
4363 'courseid' => $courseid,
4366 $coursecontext = context_course::instance($courseid);
4367 self::validate_context($coursecontext);
4368 $course = get_course($courseid);
4370 $contentitemservice = \core_course\local\factory\content_item_service_factory::get_content_item_service();
4372 $contentitems = $contentitemservice->get_content_items_for_user_in_course($USER, $course);
4373 return ['content_items' => $contentitems];
4377 * Returns description of method parameters.
4379 * @return external_function_parameters
4381 public static function toggle_activity_recommendation_parameters() {
4382 return new external_function_parameters([
4383 'area' => new external_value(PARAM_TEXT, 'The favourite area (itemtype)', VALUE_REQUIRED),
4384 'id' => new external_value(PARAM_INT, 'id of the activity or whatever', VALUE_REQUIRED),
4389 * Update the recommendation for an activity item.
4391 * @param string $area identifier for this activity.
4392 * @param int $id Associated id. This is needed in conjunction with the area to find the recommendation.
4393 * @return array some warnings or something.
4395 public static function toggle_activity_recommendation(string $area, int $id): array {
4396 ['area' => $area, 'id' => $id] = self::validate_parameters(self::toggle_activity_recommendation_parameters(),
4397 ['area' => $area, 'id' => $id]);
4399 $context = context_system::instance();
4400 self::validate_context($context);
4402 require_capability('moodle/course:recommendactivity', $context);
4404 $manager = \core_course\local\factory\content_item_service_factory::get_content_item_service();
4406 $status = $manager->toggle_recommendation($area, $id);
4407 return ['id' => $id, 'area' => $area, 'status' => $status];
4411 * Returns warnings.
4413 * @return external_description
4415 public static function toggle_activity_recommendation_returns() {
4416 return new external_single_structure(
4418 'id' => new external_value(PARAM_INT, 'id of the activity or whatever'),
4419 'area' => new external_value(PARAM_TEXT, 'The favourite area (itemtype)'),
4420 'status' => new external_value(PARAM_BOOL, 'If created or deleted'),
4426 * Returns description of method parameters
4428 * @return external_function_parameters
4430 public static function get_activity_chooser_footer_parameters() {
4431 return new external_function_parameters([
4432 'courseid' => new external_value(PARAM_INT, 'ID of the course', VALUE_REQUIRED),
4433 'sectionid' => new external_value(PARAM_INT, 'ID of the section', VALUE_REQUIRED),
4438 * Given a course ID we need to build up a footre for the chooser.
4440 * @param int $courseid The course we want to fetch the modules for
4441 * @param int $sectionid The section we want to fetch the modules for
4442 * @return array
4444 public static function get_activity_chooser_footer(int $courseid, int $sectionid) {
4446 'courseid' => $courseid,
4447 'sectionid' => $sectionid,
4448 ] = self::validate_parameters(self::get_activity_chooser_footer_parameters(), [
4449 'courseid' => $courseid,
4450 'sectionid' => $sectionid,
4453 $coursecontext = context_course::instance($courseid);
4454 self::validate_context($coursecontext);
4456 $activeplugin = get_config('core', 'activitychooseractivefooter');
4458 if ($activeplugin !== COURSE_CHOOSER_FOOTER_NONE) {
4459 $footerdata = component_callback($activeplugin, 'custom_chooser_footer', [$courseid, $sectionid]);
4460 return [
4461 'footer' => true,
4462 'customfooterjs' => $footerdata->get_footer_js_file(),
4463 'customfootertemplate' => $footerdata->get_footer_template(),
4464 'customcarouseltemplate' => $footerdata->get_carousel_template(),
4466 } else {
4467 return [
4468 'footer' => false,
4474 * Returns description of method result value
4476 * @return external_description
4478 public static function get_activity_chooser_footer_returns() {
4479 return new external_single_structure(
4481 'footer' => new external_value(PARAM_BOOL, 'Is a footer being return by this request?', VALUE_REQUIRED),
4482 'customfooterjs' => new external_value(PARAM_RAW, 'The path to the plugin JS file', VALUE_OPTIONAL),
4483 'customfootertemplate' => new external_value(PARAM_RAW, 'The prerendered footer', VALUE_OPTIONAL),
4484 'customcarouseltemplate' => new external_value(PARAM_RAW, 'Either "" or the prerendered carousel page',
4485 VALUE_OPTIONAL),