MDL-78599 enrol_lti: fix SQL syntax error in course grade sync
[moodle.git] / course / externallib.php
blob0a374127f5b5be50480bb92d37297207a5d090ac
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'),
481 'relativeto' => new external_value(PARAM_INT, 'relative date timestamp',
482 VALUE_OPTIONAL),
483 'dataid' => new external_value(PARAM_NOTAGS, 'cm data id', VALUE_OPTIONAL),
486 'Course dates',
487 VALUE_DEFAULT,
490 'contents' => new external_multiple_structure(
491 new external_single_structure(
492 array(
493 // content info
494 'type'=> new external_value(PARAM_TEXT, 'a file or a folder or external link'),
495 'filename'=> new external_value(PARAM_FILE, 'filename'),
496 'filepath'=> new external_value(PARAM_PATH, 'filepath'),
497 'filesize'=> new external_value(PARAM_INT, 'filesize'),
498 'fileurl' => new external_value(PARAM_URL, 'downloadable file url', VALUE_OPTIONAL),
499 'content' => new external_value(PARAM_RAW, 'Raw content, will be used when type is content', VALUE_OPTIONAL),
500 'timecreated' => new external_value(PARAM_INT, 'Time created'),
501 'timemodified' => new external_value(PARAM_INT, 'Time modified'),
502 'sortorder' => new external_value(PARAM_INT, 'Content sort order'),
503 'mimetype' => new external_value(PARAM_RAW, 'File mime type.', VALUE_OPTIONAL),
504 'isexternalfile' => new external_value(PARAM_BOOL, 'Whether is an external file.',
505 VALUE_OPTIONAL),
506 'repositorytype' => new external_value(PARAM_PLUGIN, 'The repository type for external files.',
507 VALUE_OPTIONAL),
509 // copyright related info
510 'userid' => new external_value(PARAM_INT, 'User who added this content to moodle'),
511 'author' => new external_value(PARAM_TEXT, 'Content owner'),
512 'license' => new external_value(PARAM_TEXT, 'Content license'),
513 'tags' => new external_multiple_structure(
514 \core_tag\external\tag_item_exporter::get_read_structure(), 'Tags',
515 VALUE_OPTIONAL
518 ), 'Course contents', VALUE_DEFAULT, array()
520 'contentsinfo' => new external_single_structure(
521 array(
522 'filescount' => new external_value(PARAM_INT, 'Total number of files.'),
523 'filessize' => new external_value(PARAM_INT, 'Total files size.'),
524 'lastmodified' => new external_value(PARAM_INT, 'Last time files were modified.'),
525 'mimetypes' => new external_multiple_structure(
526 new external_value(PARAM_RAW, 'File mime type.'),
527 'Files mime types.'
529 'repositorytype' => new external_value(PARAM_PLUGIN, 'The repository type for
530 the main file.', VALUE_OPTIONAL),
531 ), 'Contents summary information.', VALUE_OPTIONAL
534 ), 'list of module'
542 * Returns description of method parameters
544 * @return external_function_parameters
545 * @since Moodle 2.3
547 public static function get_courses_parameters() {
548 return new external_function_parameters(
549 array('options' => new external_single_structure(
550 array('ids' => new external_multiple_structure(
551 new external_value(PARAM_INT, 'Course id')
552 , 'List of course id. If empty return all courses
553 except front page course.',
554 VALUE_OPTIONAL)
555 ), 'options - operator OR is used', VALUE_DEFAULT, array())
561 * Get courses
563 * @param array $options It contains an array (list of ids)
564 * @return array
565 * @since Moodle 2.2
567 public static function get_courses($options = array()) {
568 global $CFG, $DB;
569 require_once($CFG->dirroot . "/course/lib.php");
571 //validate parameter
572 $params = self::validate_parameters(self::get_courses_parameters(),
573 array('options' => $options));
575 //retrieve courses
576 if (!array_key_exists('ids', $params['options'])
577 or empty($params['options']['ids'])) {
578 $courses = $DB->get_records('course');
579 } else {
580 $courses = $DB->get_records_list('course', 'id', $params['options']['ids']);
583 //create return value
584 $coursesinfo = array();
585 foreach ($courses as $course) {
587 // now security checks
588 $context = context_course::instance($course->id, IGNORE_MISSING);
589 $courseformatoptions = course_get_format($course)->get_format_options();
590 try {
591 self::validate_context($context);
592 } catch (Exception $e) {
593 $exceptionparam = new stdClass();
594 $exceptionparam->message = $e->getMessage();
595 $exceptionparam->courseid = $course->id;
596 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
598 if ($course->id != SITEID) {
599 require_capability('moodle/course:view', $context);
602 $courseinfo = array();
603 $courseinfo['id'] = $course->id;
604 $courseinfo['fullname'] = external_format_string($course->fullname, $context->id);
605 $courseinfo['shortname'] = external_format_string($course->shortname, $context->id);
606 $courseinfo['displayname'] = external_format_string(get_course_display_name_for_list($course), $context->id);
607 $courseinfo['categoryid'] = $course->category;
608 list($courseinfo['summary'], $courseinfo['summaryformat']) =
609 external_format_text($course->summary, $course->summaryformat, $context->id, 'course', 'summary', 0);
610 $courseinfo['format'] = $course->format;
611 $courseinfo['startdate'] = $course->startdate;
612 $courseinfo['enddate'] = $course->enddate;
613 $courseinfo['showactivitydates'] = $course->showactivitydates;
614 $courseinfo['showcompletionconditions'] = $course->showcompletionconditions;
615 if (array_key_exists('numsections', $courseformatoptions)) {
616 // For backward-compartibility
617 $courseinfo['numsections'] = $courseformatoptions['numsections'];
620 $handler = core_course\customfield\course_handler::create();
621 if ($customfields = $handler->export_instance_data($course->id)) {
622 $courseinfo['customfields'] = [];
623 foreach ($customfields as $data) {
624 $courseinfo['customfields'][] = [
625 'type' => $data->get_type(),
626 'value' => $data->get_value(),
627 'valueraw' => $data->get_data_controller()->get_value(),
628 'name' => $data->get_name(),
629 'shortname' => $data->get_shortname()
634 //some field should be returned only if the user has update permission
635 $courseadmin = has_capability('moodle/course:update', $context);
636 if ($courseadmin) {
637 $courseinfo['categorysortorder'] = $course->sortorder;
638 $courseinfo['idnumber'] = $course->idnumber;
639 $courseinfo['showgrades'] = $course->showgrades;
640 $courseinfo['showreports'] = $course->showreports;
641 $courseinfo['newsitems'] = $course->newsitems;
642 $courseinfo['visible'] = $course->visible;
643 $courseinfo['maxbytes'] = $course->maxbytes;
644 if (array_key_exists('hiddensections', $courseformatoptions)) {
645 // For backward-compartibility
646 $courseinfo['hiddensections'] = $courseformatoptions['hiddensections'];
648 // Return numsections for backward-compatibility with clients who expect it.
649 $courseinfo['numsections'] = course_get_format($course)->get_last_section_number();
650 $courseinfo['groupmode'] = $course->groupmode;
651 $courseinfo['groupmodeforce'] = $course->groupmodeforce;
652 $courseinfo['defaultgroupingid'] = $course->defaultgroupingid;
653 $courseinfo['lang'] = clean_param($course->lang, PARAM_LANG);
654 $courseinfo['timecreated'] = $course->timecreated;
655 $courseinfo['timemodified'] = $course->timemodified;
656 $courseinfo['forcetheme'] = clean_param($course->theme, PARAM_THEME);
657 $courseinfo['enablecompletion'] = $course->enablecompletion;
658 $courseinfo['completionnotify'] = $course->completionnotify;
659 $courseinfo['courseformatoptions'] = array();
660 foreach ($courseformatoptions as $key => $value) {
661 $courseinfo['courseformatoptions'][] = array(
662 'name' => $key,
663 'value' => $value
668 if ($courseadmin or $course->visible
669 or has_capability('moodle/course:viewhiddencourses', $context)) {
670 $coursesinfo[] = $courseinfo;
674 return $coursesinfo;
678 * Returns description of method result value
680 * @return external_description
681 * @since Moodle 2.2
683 public static function get_courses_returns() {
684 return new external_multiple_structure(
685 new external_single_structure(
686 array(
687 'id' => new external_value(PARAM_INT, 'course id'),
688 'shortname' => new external_value(PARAM_RAW, 'course short name'),
689 'categoryid' => new external_value(PARAM_INT, 'category id'),
690 'categorysortorder' => new external_value(PARAM_INT,
691 'sort order into the category', VALUE_OPTIONAL),
692 'fullname' => new external_value(PARAM_RAW, 'full name'),
693 'displayname' => new external_value(PARAM_RAW, 'course display name'),
694 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
695 'summary' => new external_value(PARAM_RAW, 'summary'),
696 'summaryformat' => new external_format_value('summary'),
697 'format' => new external_value(PARAM_PLUGIN,
698 'course format: weeks, topics, social, site,..'),
699 'showgrades' => new external_value(PARAM_INT,
700 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
701 'newsitems' => new external_value(PARAM_INT,
702 'number of recent items appearing on the course page', VALUE_OPTIONAL),
703 'startdate' => new external_value(PARAM_INT,
704 'timestamp when the course start'),
705 'enddate' => new external_value(PARAM_INT,
706 'timestamp when the course end'),
707 'numsections' => new external_value(PARAM_INT,
708 '(deprecated, use courseformatoptions) number of weeks/topics',
709 VALUE_OPTIONAL),
710 'maxbytes' => new external_value(PARAM_INT,
711 'largest size of file that can be uploaded into the course',
712 VALUE_OPTIONAL),
713 'showreports' => new external_value(PARAM_INT,
714 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
715 'visible' => new external_value(PARAM_INT,
716 '1: available to student, 0:not available', VALUE_OPTIONAL),
717 'hiddensections' => new external_value(PARAM_INT,
718 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
719 VALUE_OPTIONAL),
720 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
721 VALUE_OPTIONAL),
722 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
723 VALUE_OPTIONAL),
724 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
725 VALUE_OPTIONAL),
726 'timecreated' => new external_value(PARAM_INT,
727 'timestamp when the course have been created', VALUE_OPTIONAL),
728 'timemodified' => new external_value(PARAM_INT,
729 'timestamp when the course have been modified', VALUE_OPTIONAL),
730 'enablecompletion' => new external_value(PARAM_INT,
731 'Enabled, control via completion and activity settings. Disbaled,
732 not shown in activity settings.',
733 VALUE_OPTIONAL),
734 'completionnotify' => new external_value(PARAM_INT,
735 '1: yes 0: no', VALUE_OPTIONAL),
736 'lang' => new external_value(PARAM_SAFEDIR,
737 'forced course language', VALUE_OPTIONAL),
738 'forcetheme' => new external_value(PARAM_PLUGIN,
739 'name of the force theme', VALUE_OPTIONAL),
740 'courseformatoptions' => new external_multiple_structure(
741 new external_single_structure(
742 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
743 'value' => new external_value(PARAM_RAW, 'course format option value')
744 )), 'additional options for particular course format', VALUE_OPTIONAL
746 'showactivitydates' => new external_value(PARAM_BOOL, 'Whether the activity dates are shown or not'),
747 'showcompletionconditions' => new external_value(PARAM_BOOL,
748 'Whether the activity completion conditions are shown or not'),
749 'customfields' => new external_multiple_structure(
750 new external_single_structure(
751 ['name' => new external_value(PARAM_RAW, 'The name of the custom field'),
752 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'The shortname of the custom field'),
753 'type' => new external_value(PARAM_COMPONENT,
754 'The type of the custom field - text, checkbox...'),
755 'valueraw' => new external_value(PARAM_RAW, 'The raw value of the custom field'),
756 'value' => new external_value(PARAM_RAW, 'The value of the custom field')]
757 ), 'Custom fields and associated values', VALUE_OPTIONAL),
758 ), 'course'
764 * Returns description of method parameters
766 * @return external_function_parameters
767 * @since Moodle 2.2
769 public static function create_courses_parameters() {
770 $courseconfig = get_config('moodlecourse'); //needed for many default values
771 return new external_function_parameters(
772 array(
773 'courses' => new external_multiple_structure(
774 new external_single_structure(
775 array(
776 'fullname' => new external_value(PARAM_TEXT, 'full name'),
777 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
778 'categoryid' => new external_value(PARAM_INT, 'category id'),
779 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
780 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
781 'summaryformat' => new external_format_value('summary', VALUE_DEFAULT),
782 'format' => new external_value(PARAM_PLUGIN,
783 'course format: weeks, topics, social, site,..',
784 VALUE_DEFAULT, $courseconfig->format),
785 'showgrades' => new external_value(PARAM_INT,
786 '1 if grades are shown, otherwise 0', VALUE_DEFAULT,
787 $courseconfig->showgrades),
788 'newsitems' => new external_value(PARAM_INT,
789 'number of recent items appearing on the course page',
790 VALUE_DEFAULT, $courseconfig->newsitems),
791 'startdate' => new external_value(PARAM_INT,
792 'timestamp when the course start', VALUE_OPTIONAL),
793 'enddate' => new external_value(PARAM_INT,
794 'timestamp when the course end', VALUE_OPTIONAL),
795 'numsections' => new external_value(PARAM_INT,
796 '(deprecated, use courseformatoptions) number of weeks/topics',
797 VALUE_OPTIONAL),
798 'maxbytes' => new external_value(PARAM_INT,
799 'largest size of file that can be uploaded into the course',
800 VALUE_DEFAULT, $courseconfig->maxbytes),
801 'showreports' => new external_value(PARAM_INT,
802 'are activity report shown (yes = 1, no =0)', VALUE_DEFAULT,
803 $courseconfig->showreports),
804 'visible' => new external_value(PARAM_INT,
805 '1: available to student, 0:not available', VALUE_OPTIONAL),
806 'hiddensections' => new external_value(PARAM_INT,
807 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
808 VALUE_OPTIONAL),
809 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
810 VALUE_DEFAULT, $courseconfig->groupmode),
811 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
812 VALUE_DEFAULT, $courseconfig->groupmodeforce),
813 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
814 VALUE_DEFAULT, 0),
815 'enablecompletion' => new external_value(PARAM_INT,
816 'Enabled, control via completion and activity settings. Disabled,
817 not shown in activity settings.',
818 VALUE_OPTIONAL),
819 'completionnotify' => new external_value(PARAM_INT,
820 '1: yes 0: no', VALUE_OPTIONAL),
821 'lang' => new external_value(PARAM_SAFEDIR,
822 'forced course language', VALUE_OPTIONAL),
823 'forcetheme' => new external_value(PARAM_PLUGIN,
824 'name of the force theme', VALUE_OPTIONAL),
825 'courseformatoptions' => new external_multiple_structure(
826 new external_single_structure(
827 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
828 'value' => new external_value(PARAM_RAW, 'course format option value')
830 'additional options for particular course format', VALUE_OPTIONAL),
831 'customfields' => new external_multiple_structure(
832 new external_single_structure(
833 array(
834 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'The shortname of the custom field'),
835 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
836 )), 'custom fields for the course', VALUE_OPTIONAL
838 )), 'courses to create'
845 * Create courses
847 * @param array $courses
848 * @return array courses (id and shortname only)
849 * @since Moodle 2.2
851 public static function create_courses($courses) {
852 global $CFG, $DB;
853 require_once($CFG->dirroot . "/course/lib.php");
854 require_once($CFG->libdir . '/completionlib.php');
856 $params = self::validate_parameters(self::create_courses_parameters(),
857 array('courses' => $courses));
859 $availablethemes = core_component::get_plugin_list('theme');
860 $availablelangs = get_string_manager()->get_list_of_translations();
862 $transaction = $DB->start_delegated_transaction();
864 foreach ($params['courses'] as $course) {
866 // Ensure the current user is allowed to run this function
867 $context = context_coursecat::instance($course['categoryid'], IGNORE_MISSING);
868 try {
869 self::validate_context($context);
870 } catch (Exception $e) {
871 $exceptionparam = new stdClass();
872 $exceptionparam->message = $e->getMessage();
873 $exceptionparam->catid = $course['categoryid'];
874 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
876 require_capability('moodle/course:create', $context);
878 // Fullname and short name are required to be non-empty.
879 if (trim($course['fullname']) === '') {
880 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'fullname');
881 } else if (trim($course['shortname']) === '') {
882 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'shortname');
885 // Make sure lang is valid
886 if (array_key_exists('lang', $course)) {
887 if (empty($availablelangs[$course['lang']])) {
888 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
890 if (!has_capability('moodle/course:setforcedlanguage', $context)) {
891 unset($course['lang']);
895 // Make sure theme is valid
896 if (array_key_exists('forcetheme', $course)) {
897 if (!empty($CFG->allowcoursethemes)) {
898 if (empty($availablethemes[$course['forcetheme']])) {
899 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
900 } else {
901 $course['theme'] = $course['forcetheme'];
906 //force visibility if ws user doesn't have the permission to set it
907 $category = $DB->get_record('course_categories', array('id' => $course['categoryid']));
908 if (!has_capability('moodle/course:visibility', $context)) {
909 $course['visible'] = $category->visible;
912 //set default value for completion
913 $courseconfig = get_config('moodlecourse');
914 if (completion_info::is_enabled_for_site()) {
915 if (!array_key_exists('enablecompletion', $course)) {
916 $course['enablecompletion'] = $courseconfig->enablecompletion;
918 } else {
919 $course['enablecompletion'] = 0;
922 $course['category'] = $course['categoryid'];
924 // Summary format.
925 $course['summaryformat'] = external_validate_format($course['summaryformat']);
927 if (!empty($course['courseformatoptions'])) {
928 foreach ($course['courseformatoptions'] as $option) {
929 $course[$option['name']] = $option['value'];
933 // Custom fields.
934 if (!empty($course['customfields'])) {
935 foreach ($course['customfields'] as $field) {
936 $course['customfield_'.$field['shortname']] = $field['value'];
940 //Note: create_course() core function check shortname, idnumber, category
941 $course['id'] = create_course((object) $course)->id;
943 $resultcourses[] = array('id' => $course['id'], 'shortname' => $course['shortname']);
946 $transaction->allow_commit();
948 return $resultcourses;
952 * Returns description of method result value
954 * @return external_description
955 * @since Moodle 2.2
957 public static function create_courses_returns() {
958 return new external_multiple_structure(
959 new external_single_structure(
960 array(
961 'id' => new external_value(PARAM_INT, 'course id'),
962 'shortname' => new external_value(PARAM_RAW, 'short name'),
969 * Update courses
971 * @return external_function_parameters
972 * @since Moodle 2.5
974 public static function update_courses_parameters() {
975 return new external_function_parameters(
976 array(
977 'courses' => new external_multiple_structure(
978 new external_single_structure(
979 array(
980 'id' => new external_value(PARAM_INT, 'ID of the course'),
981 'fullname' => new external_value(PARAM_TEXT, 'full name', VALUE_OPTIONAL),
982 'shortname' => new external_value(PARAM_TEXT, 'course short name', VALUE_OPTIONAL),
983 'categoryid' => new external_value(PARAM_INT, 'category id', VALUE_OPTIONAL),
984 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
985 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
986 'summaryformat' => new external_format_value('summary', VALUE_OPTIONAL),
987 'format' => new external_value(PARAM_PLUGIN,
988 'course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
989 'showgrades' => new external_value(PARAM_INT,
990 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
991 'newsitems' => new external_value(PARAM_INT,
992 'number of recent items appearing on the course page', VALUE_OPTIONAL),
993 'startdate' => new external_value(PARAM_INT,
994 'timestamp when the course start', VALUE_OPTIONAL),
995 'enddate' => new external_value(PARAM_INT,
996 'timestamp when the course end', VALUE_OPTIONAL),
997 'numsections' => new external_value(PARAM_INT,
998 '(deprecated, use courseformatoptions) number of weeks/topics', VALUE_OPTIONAL),
999 'maxbytes' => new external_value(PARAM_INT,
1000 'largest size of file that can be uploaded into the course', VALUE_OPTIONAL),
1001 'showreports' => new external_value(PARAM_INT,
1002 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
1003 'visible' => new external_value(PARAM_INT,
1004 '1: available to student, 0:not available', VALUE_OPTIONAL),
1005 'hiddensections' => new external_value(PARAM_INT,
1006 '(deprecated, use courseformatoptions) How the hidden sections in the course are
1007 displayed to students', VALUE_OPTIONAL),
1008 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
1009 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
1010 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
1011 'enablecompletion' => new external_value(PARAM_INT,
1012 'Enabled, control via completion and activity settings. Disabled,
1013 not shown in activity settings.', VALUE_OPTIONAL),
1014 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
1015 'lang' => new external_value(PARAM_SAFEDIR, 'forced course language', VALUE_OPTIONAL),
1016 'forcetheme' => new external_value(PARAM_PLUGIN, 'name of the force theme', VALUE_OPTIONAL),
1017 'courseformatoptions' => new external_multiple_structure(
1018 new external_single_structure(
1019 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
1020 'value' => new external_value(PARAM_RAW, 'course format option value')
1021 )), 'additional options for particular course format', VALUE_OPTIONAL),
1022 'customfields' => new external_multiple_structure(
1023 new external_single_structure(
1025 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'The shortname of the custom field'),
1026 'value' => new external_value(PARAM_RAW, 'The value of the custom field')
1028 ), 'Custom fields', VALUE_OPTIONAL),
1030 ), 'courses to update'
1037 * Update courses
1039 * @param array $courses
1040 * @since Moodle 2.5
1042 public static function update_courses($courses) {
1043 global $CFG, $DB;
1044 require_once($CFG->dirroot . "/course/lib.php");
1045 $warnings = array();
1047 $params = self::validate_parameters(self::update_courses_parameters(),
1048 array('courses' => $courses));
1050 $availablethemes = core_component::get_plugin_list('theme');
1051 $availablelangs = get_string_manager()->get_list_of_translations();
1053 foreach ($params['courses'] as $course) {
1054 // Catch any exception while updating course and return as warning to user.
1055 try {
1056 // Ensure the current user is allowed to run this function.
1057 $context = context_course::instance($course['id'], MUST_EXIST);
1058 self::validate_context($context);
1060 $oldcourse = course_get_format($course['id'])->get_course();
1062 require_capability('moodle/course:update', $context);
1064 // Check if user can change category.
1065 if (array_key_exists('categoryid', $course) && ($oldcourse->category != $course['categoryid'])) {
1066 require_capability('moodle/course:changecategory', $context);
1067 $course['category'] = $course['categoryid'];
1070 // Check if the user can change fullname, and the new value is non-empty.
1071 if (array_key_exists('fullname', $course) && ($oldcourse->fullname != $course['fullname'])) {
1072 require_capability('moodle/course:changefullname', $context);
1073 if (trim($course['fullname']) === '') {
1074 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'fullname');
1078 // Check if the user can change shortname, and the new value is non-empty.
1079 if (array_key_exists('shortname', $course) && ($oldcourse->shortname != $course['shortname'])) {
1080 require_capability('moodle/course:changeshortname', $context);
1081 if (trim($course['shortname']) === '') {
1082 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'shortname');
1086 // Check if the user can change the idnumber.
1087 if (array_key_exists('idnumber', $course) && ($oldcourse->idnumber != $course['idnumber'])) {
1088 require_capability('moodle/course:changeidnumber', $context);
1091 // Check if user can change summary.
1092 if (array_key_exists('summary', $course) && ($oldcourse->summary != $course['summary'])) {
1093 require_capability('moodle/course:changesummary', $context);
1096 // Summary format.
1097 if (array_key_exists('summaryformat', $course) && ($oldcourse->summaryformat != $course['summaryformat'])) {
1098 require_capability('moodle/course:changesummary', $context);
1099 $course['summaryformat'] = external_validate_format($course['summaryformat']);
1102 // Check if user can change visibility.
1103 if (array_key_exists('visible', $course) && ($oldcourse->visible != $course['visible'])) {
1104 require_capability('moodle/course:visibility', $context);
1107 // Make sure lang is valid.
1108 if (array_key_exists('lang', $course) && ($oldcourse->lang != $course['lang'])) {
1109 require_capability('moodle/course:setforcedlanguage', $context);
1110 if (empty($availablelangs[$course['lang']])) {
1111 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
1115 // Make sure theme is valid.
1116 if (array_key_exists('forcetheme', $course)) {
1117 if (!empty($CFG->allowcoursethemes)) {
1118 if (empty($availablethemes[$course['forcetheme']])) {
1119 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
1120 } else {
1121 $course['theme'] = $course['forcetheme'];
1126 // Make sure completion is enabled before setting it.
1127 if (array_key_exists('enabledcompletion', $course) && !completion_info::is_enabled_for_site()) {
1128 $course['enabledcompletion'] = 0;
1131 // Make sure maxbytes are less then CFG->maxbytes.
1132 if (array_key_exists('maxbytes', $course)) {
1133 // We allow updates back to 0 max bytes, a special value denoting the course uses the site limit.
1134 // Otherwise, either use the size specified, or cap at the max size for the course.
1135 if ($course['maxbytes'] != 0) {
1136 $course['maxbytes'] = get_max_upload_file_size($CFG->maxbytes, $course['maxbytes']);
1140 if (!empty($course['courseformatoptions'])) {
1141 foreach ($course['courseformatoptions'] as $option) {
1142 if (isset($option['name']) && isset($option['value'])) {
1143 $course[$option['name']] = $option['value'];
1148 // Prepare list of custom fields.
1149 if (isset($course['customfields'])) {
1150 foreach ($course['customfields'] as $field) {
1151 $course['customfield_' . $field['shortname']] = $field['value'];
1155 // Update course if user has all required capabilities.
1156 update_course((object) $course);
1157 } catch (Exception $e) {
1158 $warning = array();
1159 $warning['item'] = 'course';
1160 $warning['itemid'] = $course['id'];
1161 if ($e instanceof moodle_exception) {
1162 $warning['warningcode'] = $e->errorcode;
1163 } else {
1164 $warning['warningcode'] = $e->getCode();
1166 $warning['message'] = $e->getMessage();
1167 $warnings[] = $warning;
1171 $result = array();
1172 $result['warnings'] = $warnings;
1173 return $result;
1177 * Returns description of method result value
1179 * @return external_description
1180 * @since Moodle 2.5
1182 public static function update_courses_returns() {
1183 return new external_single_structure(
1184 array(
1185 'warnings' => new external_warnings()
1191 * Returns description of method parameters
1193 * @return external_function_parameters
1194 * @since Moodle 2.2
1196 public static function delete_courses_parameters() {
1197 return new external_function_parameters(
1198 array(
1199 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'course ID')),
1205 * Delete courses
1207 * @param array $courseids A list of course ids
1208 * @since Moodle 2.2
1210 public static function delete_courses($courseids) {
1211 global $CFG, $DB;
1212 require_once($CFG->dirroot."/course/lib.php");
1214 // Parameter validation.
1215 $params = self::validate_parameters(self::delete_courses_parameters(), array('courseids'=>$courseids));
1217 $warnings = array();
1219 foreach ($params['courseids'] as $courseid) {
1220 $course = $DB->get_record('course', array('id' => $courseid));
1222 if ($course === false) {
1223 $warnings[] = array(
1224 'item' => 'course',
1225 'itemid' => $courseid,
1226 'warningcode' => 'unknowncourseidnumber',
1227 'message' => 'Unknown course ID ' . $courseid
1229 continue;
1232 // Check if the context is valid.
1233 $coursecontext = context_course::instance($course->id);
1234 self::validate_context($coursecontext);
1236 // Check if the current user has permission.
1237 if (!can_delete_course($courseid)) {
1238 $warnings[] = array(
1239 'item' => 'course',
1240 'itemid' => $courseid,
1241 'warningcode' => 'cannotdeletecourse',
1242 'message' => 'You do not have the permission to delete this course' . $courseid
1244 continue;
1247 if (delete_course($course, false) === false) {
1248 $warnings[] = array(
1249 'item' => 'course',
1250 'itemid' => $courseid,
1251 'warningcode' => 'cannotdeletecategorycourse',
1252 'message' => 'Course ' . $courseid . ' failed to be deleted'
1254 continue;
1258 fix_course_sortorder();
1260 return array('warnings' => $warnings);
1264 * Returns description of method result value
1266 * @return external_description
1267 * @since Moodle 2.2
1269 public static function delete_courses_returns() {
1270 return new external_single_structure(
1271 array(
1272 'warnings' => new external_warnings()
1278 * Returns description of method parameters
1280 * @return external_function_parameters
1281 * @since Moodle 2.3
1283 public static function duplicate_course_parameters() {
1284 return new external_function_parameters(
1285 array(
1286 'courseid' => new external_value(PARAM_INT, 'course to duplicate id'),
1287 'fullname' => new external_value(PARAM_TEXT, 'duplicated course full name'),
1288 'shortname' => new external_value(PARAM_TEXT, 'duplicated course short name'),
1289 'categoryid' => new external_value(PARAM_INT, 'duplicated course category parent'),
1290 'visible' => new external_value(PARAM_INT, 'duplicated course visible, default to yes', VALUE_DEFAULT, 1),
1291 'options' => new external_multiple_structure(
1292 new external_single_structure(
1293 array(
1294 'name' => new external_value(PARAM_ALPHAEXT, 'The backup option name:
1295 "activities" (int) Include course activites (default to 1 that is equal to yes),
1296 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1297 "filters" (int) Include course filters (default to 1 that is equal to yes),
1298 "users" (int) Include users (default to 0 that is equal to no),
1299 "enrolments" (int) Include enrolment methods (default to 1 - restore only with users),
1300 "role_assignments" (int) Include role assignments (default to 0 that is equal to no),
1301 "comments" (int) Include user comments (default to 0 that is equal to no),
1302 "userscompletion" (int) Include user course completion information (default to 0 that is equal to no),
1303 "logs" (int) Include course logs (default to 0 that is equal to no),
1304 "grade_histories" (int) Include histories (default to 0 that is equal to no)'
1306 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1309 ), 'Course duplication options', VALUE_DEFAULT, array()
1316 * Duplicate a course
1318 * @param int $courseid
1319 * @param string $fullname Duplicated course fullname
1320 * @param string $shortname Duplicated course shortname
1321 * @param int $categoryid Duplicated course parent category id
1322 * @param int $visible Duplicated course availability
1323 * @param array $options List of backup options
1324 * @return array New course info
1325 * @since Moodle 2.3
1327 public static function duplicate_course($courseid, $fullname, $shortname, $categoryid, $visible = 1, $options = array()) {
1328 global $CFG, $USER, $DB;
1329 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1330 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1332 // Parameter validation.
1333 $params = self::validate_parameters(
1334 self::duplicate_course_parameters(),
1335 array(
1336 'courseid' => $courseid,
1337 'fullname' => $fullname,
1338 'shortname' => $shortname,
1339 'categoryid' => $categoryid,
1340 'visible' => $visible,
1341 'options' => $options
1345 // Context validation.
1347 if (! ($course = $DB->get_record('course', array('id'=>$params['courseid'])))) {
1348 throw new moodle_exception('invalidcourseid', 'error');
1351 // Category where duplicated course is going to be created.
1352 $categorycontext = context_coursecat::instance($params['categoryid']);
1353 self::validate_context($categorycontext);
1355 // Course to be duplicated.
1356 $coursecontext = context_course::instance($course->id);
1357 self::validate_context($coursecontext);
1359 $backupdefaults = array(
1360 'activities' => 1,
1361 'blocks' => 1,
1362 'filters' => 1,
1363 'users' => 0,
1364 'enrolments' => backup::ENROL_WITHUSERS,
1365 'role_assignments' => 0,
1366 'comments' => 0,
1367 'userscompletion' => 0,
1368 'logs' => 0,
1369 'grade_histories' => 0
1372 $backupsettings = array();
1373 // Check for backup and restore options.
1374 if (!empty($params['options'])) {
1375 foreach ($params['options'] as $option) {
1377 // Strict check for a correct value (allways 1 or 0, true or false).
1378 $value = clean_param($option['value'], PARAM_INT);
1380 if ($value !== 0 and $value !== 1) {
1381 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1384 if (!isset($backupdefaults[$option['name']])) {
1385 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1388 $backupsettings[$option['name']] = $value;
1392 // Capability checking.
1394 // The backup controller check for this currently, this may be redundant.
1395 require_capability('moodle/course:create', $categorycontext);
1396 require_capability('moodle/restore:restorecourse', $categorycontext);
1397 require_capability('moodle/backup:backupcourse', $coursecontext);
1399 if (!empty($backupsettings['users'])) {
1400 require_capability('moodle/backup:userinfo', $coursecontext);
1401 require_capability('moodle/restore:userinfo', $categorycontext);
1404 // Check if the shortname is used.
1405 if ($foundcourses = $DB->get_records('course', array('shortname'=>$shortname))) {
1406 foreach ($foundcourses as $foundcourse) {
1407 $foundcoursenames[] = $foundcourse->fullname;
1410 $foundcoursenamestring = implode(',', $foundcoursenames);
1411 throw new moodle_exception('shortnametaken', '', '', $foundcoursenamestring);
1414 // Backup the course.
1416 $bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE,
1417 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id);
1419 foreach ($backupsettings as $name => $value) {
1420 if ($setting = $bc->get_plan()->get_setting($name)) {
1421 $bc->get_plan()->get_setting($name)->set_value($value);
1425 $backupid = $bc->get_backupid();
1426 $backupbasepath = $bc->get_plan()->get_basepath();
1428 $bc->execute_plan();
1429 $results = $bc->get_results();
1430 $file = $results['backup_destination'];
1432 $bc->destroy();
1434 // Restore the backup immediately.
1436 // Check if we need to unzip the file because the backup temp dir does not contains backup files.
1437 if (!file_exists($backupbasepath . "/moodle_backup.xml")) {
1438 $file->extract_to_pathname(get_file_packer('application/vnd.moodle.backup'), $backupbasepath);
1441 // Create new course.
1442 $newcourseid = restore_dbops::create_new_course($params['fullname'], $params['shortname'], $params['categoryid']);
1444 $rc = new restore_controller($backupid, $newcourseid,
1445 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id, backup::TARGET_NEW_COURSE);
1447 foreach ($backupsettings as $name => $value) {
1448 $setting = $rc->get_plan()->get_setting($name);
1449 if ($setting->get_status() == backup_setting::NOT_LOCKED) {
1450 $setting->set_value($value);
1454 if (!$rc->execute_precheck()) {
1455 $precheckresults = $rc->get_precheck_results();
1456 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1457 if (empty($CFG->keeptempdirectoriesonbackup)) {
1458 fulldelete($backupbasepath);
1461 $errorinfo = '';
1463 foreach ($precheckresults['errors'] as $error) {
1464 $errorinfo .= $error;
1467 if (array_key_exists('warnings', $precheckresults)) {
1468 foreach ($precheckresults['warnings'] as $warning) {
1469 $errorinfo .= $warning;
1473 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1477 $rc->execute_plan();
1478 $rc->destroy();
1480 $course = $DB->get_record('course', array('id' => $newcourseid), '*', MUST_EXIST);
1481 $course->fullname = $params['fullname'];
1482 $course->shortname = $params['shortname'];
1483 $course->visible = $params['visible'];
1485 // Set shortname and fullname back.
1486 $DB->update_record('course', $course);
1488 if (empty($CFG->keeptempdirectoriesonbackup)) {
1489 fulldelete($backupbasepath);
1492 // Delete the course backup file created by this WebService. Originally located in the course backups area.
1493 $file->delete();
1495 return array('id' => $course->id, 'shortname' => $course->shortname);
1499 * Returns description of method result value
1501 * @return external_description
1502 * @since Moodle 2.3
1504 public static function duplicate_course_returns() {
1505 return new external_single_structure(
1506 array(
1507 'id' => new external_value(PARAM_INT, 'course id'),
1508 'shortname' => new external_value(PARAM_RAW, 'short name'),
1514 * Returns description of method parameters for import_course
1516 * @return external_function_parameters
1517 * @since Moodle 2.4
1519 public static function import_course_parameters() {
1520 return new external_function_parameters(
1521 array(
1522 'importfrom' => new external_value(PARAM_INT, 'the id of the course we are importing from'),
1523 'importto' => new external_value(PARAM_INT, 'the id of the course we are importing to'),
1524 'deletecontent' => new external_value(PARAM_INT, 'whether to delete the course content where we are importing to (default to 0 = No)', VALUE_DEFAULT, 0),
1525 'options' => new external_multiple_structure(
1526 new external_single_structure(
1527 array(
1528 'name' => new external_value(PARAM_ALPHA, 'The backup option name:
1529 "activities" (int) Include course activites (default to 1 that is equal to yes),
1530 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1531 "filters" (int) Include course filters (default to 1 that is equal to yes)'
1533 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1536 ), 'Course import options', VALUE_DEFAULT, array()
1543 * Imports a course
1545 * @param int $importfrom The id of the course we are importing from
1546 * @param int $importto The id of the course we are importing to
1547 * @param bool $deletecontent Whether to delete the course we are importing to content
1548 * @param array $options List of backup options
1549 * @return null
1550 * @since Moodle 2.4
1552 public static function import_course($importfrom, $importto, $deletecontent = 0, $options = array()) {
1553 global $CFG, $USER, $DB;
1554 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1555 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1557 // Parameter validation.
1558 $params = self::validate_parameters(
1559 self::import_course_parameters(),
1560 array(
1561 'importfrom' => $importfrom,
1562 'importto' => $importto,
1563 'deletecontent' => $deletecontent,
1564 'options' => $options
1568 if ($params['deletecontent'] !== 0 and $params['deletecontent'] !== 1) {
1569 throw new moodle_exception('invalidextparam', 'webservice', '', $params['deletecontent']);
1572 // Context validation.
1574 if (! ($importfrom = $DB->get_record('course', array('id'=>$params['importfrom'])))) {
1575 throw new moodle_exception('invalidcourseid', 'error');
1578 if (! ($importto = $DB->get_record('course', array('id'=>$params['importto'])))) {
1579 throw new moodle_exception('invalidcourseid', 'error');
1582 $importfromcontext = context_course::instance($importfrom->id);
1583 self::validate_context($importfromcontext);
1585 $importtocontext = context_course::instance($importto->id);
1586 self::validate_context($importtocontext);
1588 $backupdefaults = array(
1589 'activities' => 1,
1590 'blocks' => 1,
1591 'filters' => 1
1594 $backupsettings = array();
1596 // Check for backup and restore options.
1597 if (!empty($params['options'])) {
1598 foreach ($params['options'] as $option) {
1600 // Strict check for a correct value (allways 1 or 0, true or false).
1601 $value = clean_param($option['value'], PARAM_INT);
1603 if ($value !== 0 and $value !== 1) {
1604 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1607 if (!isset($backupdefaults[$option['name']])) {
1608 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1611 $backupsettings[$option['name']] = $value;
1615 // Capability checking.
1617 require_capability('moodle/backup:backuptargetimport', $importfromcontext);
1618 require_capability('moodle/restore:restoretargetimport', $importtocontext);
1620 $bc = new backup_controller(backup::TYPE_1COURSE, $importfrom->id, backup::FORMAT_MOODLE,
1621 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
1623 foreach ($backupsettings as $name => $value) {
1624 $bc->get_plan()->get_setting($name)->set_value($value);
1627 $backupid = $bc->get_backupid();
1628 $backupbasepath = $bc->get_plan()->get_basepath();
1630 $bc->execute_plan();
1631 $bc->destroy();
1633 // Restore the backup immediately.
1635 // Check if we must delete the contents of the destination course.
1636 if ($params['deletecontent']) {
1637 $restoretarget = backup::TARGET_EXISTING_DELETING;
1638 } else {
1639 $restoretarget = backup::TARGET_EXISTING_ADDING;
1642 $rc = new restore_controller($backupid, $importto->id,
1643 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, $restoretarget);
1645 foreach ($backupsettings as $name => $value) {
1646 $rc->get_plan()->get_setting($name)->set_value($value);
1649 if (!$rc->execute_precheck()) {
1650 $precheckresults = $rc->get_precheck_results();
1651 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1652 if (empty($CFG->keeptempdirectoriesonbackup)) {
1653 fulldelete($backupbasepath);
1656 $errorinfo = '';
1658 foreach ($precheckresults['errors'] as $error) {
1659 $errorinfo .= $error;
1662 if (array_key_exists('warnings', $precheckresults)) {
1663 foreach ($precheckresults['warnings'] as $warning) {
1664 $errorinfo .= $warning;
1668 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1670 } else {
1671 if ($restoretarget == backup::TARGET_EXISTING_DELETING) {
1672 restore_dbops::delete_course_content($importto->id);
1676 $rc->execute_plan();
1677 $rc->destroy();
1679 if (empty($CFG->keeptempdirectoriesonbackup)) {
1680 fulldelete($backupbasepath);
1683 return null;
1687 * Returns description of method result value
1689 * @return external_description
1690 * @since Moodle 2.4
1692 public static function import_course_returns() {
1693 return null;
1697 * Returns description of method parameters
1699 * @return external_function_parameters
1700 * @since Moodle 2.3
1702 public static function get_categories_parameters() {
1703 return new external_function_parameters(
1704 array(
1705 'criteria' => new external_multiple_structure(
1706 new external_single_structure(
1707 array(
1708 'key' => new external_value(PARAM_ALPHA,
1709 'The category column to search, expected keys (value format) are:'.
1710 '"id" (int) the category id,'.
1711 '"ids" (string) category ids separated by commas,'.
1712 '"name" (string) the category name,'.
1713 '"parent" (int) the parent category id,'.
1714 '"idnumber" (string) category idnumber'.
1715 ' - user must have \'moodle/category:manage\' to search on idnumber,'.
1716 '"visible" (int) whether the returned categories must be visible or hidden. If the key is not passed,
1717 then the function return all categories that the user can see.'.
1718 ' - user must have \'moodle/category:manage\' or \'moodle/category:viewhiddencategories\' to search on visible,'.
1719 '"theme" (string) only return the categories having this theme'.
1720 ' - user must have \'moodle/category:manage\' to search on theme'),
1721 'value' => new external_value(PARAM_RAW, 'the value to match')
1723 ), 'criteria', VALUE_DEFAULT, array()
1725 'addsubcategories' => new external_value(PARAM_BOOL, 'return the sub categories infos
1726 (1 - default) otherwise only the category info (0)', VALUE_DEFAULT, 1)
1732 * Get categories
1734 * @param array $criteria Criteria to match the results
1735 * @param booln $addsubcategories obtain only the category (false) or its subcategories (true - default)
1736 * @return array list of categories
1737 * @since Moodle 2.3
1739 public static function get_categories($criteria = array(), $addsubcategories = true) {
1740 global $CFG, $DB;
1741 require_once($CFG->dirroot . "/course/lib.php");
1743 // Validate parameters.
1744 $params = self::validate_parameters(self::get_categories_parameters(),
1745 array('criteria' => $criteria, 'addsubcategories' => $addsubcategories));
1747 // Retrieve the categories.
1748 $categories = array();
1749 if (!empty($params['criteria'])) {
1751 $conditions = array();
1752 $wheres = array();
1753 foreach ($params['criteria'] as $crit) {
1754 $key = trim($crit['key']);
1756 // Trying to avoid duplicate keys.
1757 if (!isset($conditions[$key])) {
1759 $context = context_system::instance();
1760 $value = null;
1761 switch ($key) {
1762 case 'id':
1763 $value = clean_param($crit['value'], PARAM_INT);
1764 $conditions[$key] = $value;
1765 $wheres[] = $key . " = :" . $key;
1766 break;
1768 case 'ids':
1769 $value = clean_param($crit['value'], PARAM_SEQUENCE);
1770 $ids = explode(',', $value);
1771 list($sqlids, $paramids) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED);
1772 $conditions = array_merge($conditions, $paramids);
1773 $wheres[] = 'id ' . $sqlids;
1774 break;
1776 case 'idnumber':
1777 if (has_capability('moodle/category:manage', $context)) {
1778 $value = clean_param($crit['value'], PARAM_RAW);
1779 $conditions[$key] = $value;
1780 $wheres[] = $key . " = :" . $key;
1781 } else {
1782 // We must throw an exception.
1783 // Otherwise the dev client would think no idnumber exists.
1784 throw new moodle_exception('criteriaerror',
1785 'webservice', '', null,
1786 'You don\'t have the permissions to search on the "idnumber" field.');
1788 break;
1790 case 'name':
1791 $value = clean_param($crit['value'], PARAM_TEXT);
1792 $conditions[$key] = $value;
1793 $wheres[] = $key . " = :" . $key;
1794 break;
1796 case 'parent':
1797 $value = clean_param($crit['value'], PARAM_INT);
1798 $conditions[$key] = $value;
1799 $wheres[] = $key . " = :" . $key;
1800 break;
1802 case 'visible':
1803 if (has_capability('moodle/category:viewhiddencategories', $context)) {
1804 $value = clean_param($crit['value'], PARAM_INT);
1805 $conditions[$key] = $value;
1806 $wheres[] = $key . " = :" . $key;
1807 } else {
1808 throw new moodle_exception('criteriaerror',
1809 'webservice', '', null,
1810 'You don\'t have the permissions to search on the "visible" field.');
1812 break;
1814 case 'theme':
1815 if (has_capability('moodle/category:manage', $context)) {
1816 $value = clean_param($crit['value'], PARAM_THEME);
1817 $conditions[$key] = $value;
1818 $wheres[] = $key . " = :" . $key;
1819 } else {
1820 throw new moodle_exception('criteriaerror',
1821 'webservice', '', null,
1822 'You don\'t have the permissions to search on the "theme" field.');
1824 break;
1826 default:
1827 throw new moodle_exception('criteriaerror',
1828 'webservice', '', null,
1829 'You can not search on this criteria: ' . $key);
1834 if (!empty($wheres)) {
1835 $wheres = implode(" AND ", $wheres);
1837 $categories = $DB->get_records_select('course_categories', $wheres, $conditions);
1839 // Retrieve its sub subcategories (all levels).
1840 if ($categories and !empty($params['addsubcategories'])) {
1841 $newcategories = array();
1843 // Check if we required visible/theme checks.
1844 $additionalselect = '';
1845 $additionalparams = array();
1846 if (isset($conditions['visible'])) {
1847 $additionalselect .= ' AND visible = :visible';
1848 $additionalparams['visible'] = $conditions['visible'];
1850 if (isset($conditions['theme'])) {
1851 $additionalselect .= ' AND theme= :theme';
1852 $additionalparams['theme'] = $conditions['theme'];
1855 foreach ($categories as $category) {
1856 $sqlselect = $DB->sql_like('path', ':path') . $additionalselect;
1857 $sqlparams = array('path' => $category->path.'/%') + $additionalparams; // It will NOT include the specified category.
1858 $subcategories = $DB->get_records_select('course_categories', $sqlselect, $sqlparams);
1859 $newcategories = $newcategories + $subcategories; // Both arrays have integer as keys.
1861 $categories = $categories + $newcategories;
1865 } else {
1866 // Retrieve all categories in the database.
1867 $categories = $DB->get_records('course_categories');
1870 // The not returned categories. key => category id, value => reason of exclusion.
1871 $excludedcats = array();
1873 // The returned categories.
1874 $categoriesinfo = array();
1876 // We need to sort the categories by path.
1877 // The parent cats need to be checked by the algo first.
1878 usort($categories, "core_course_external::compare_categories_by_path");
1880 foreach ($categories as $category) {
1882 // Check if the category is a child of an excluded category, if yes exclude it too (excluded => do not return).
1883 $parents = explode('/', $category->path);
1884 unset($parents[0]); // First key is always empty because path start with / => /1/2/4.
1885 foreach ($parents as $parentid) {
1886 // Note: when the parent exclusion was due to the context,
1887 // the sub category could still be returned.
1888 if (isset($excludedcats[$parentid]) and $excludedcats[$parentid] != 'context') {
1889 $excludedcats[$category->id] = 'parent';
1893 // Check the user can use the category context.
1894 $context = context_coursecat::instance($category->id);
1895 try {
1896 self::validate_context($context);
1897 } catch (Exception $e) {
1898 $excludedcats[$category->id] = 'context';
1900 // If it was the requested category then throw an exception.
1901 if (isset($params['categoryid']) && $category->id == $params['categoryid']) {
1902 $exceptionparam = new stdClass();
1903 $exceptionparam->message = $e->getMessage();
1904 $exceptionparam->catid = $category->id;
1905 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
1909 // Return the category information.
1910 if (!isset($excludedcats[$category->id])) {
1912 // Final check to see if the category is visible to the user.
1913 if (core_course_category::can_view_category($category)) {
1915 $categoryinfo = array();
1916 $categoryinfo['id'] = $category->id;
1917 $categoryinfo['name'] = external_format_string($category->name, $context);
1918 list($categoryinfo['description'], $categoryinfo['descriptionformat']) =
1919 external_format_text($category->description, $category->descriptionformat,
1920 $context->id, 'coursecat', 'description', null);
1921 $categoryinfo['parent'] = $category->parent;
1922 $categoryinfo['sortorder'] = $category->sortorder;
1923 $categoryinfo['coursecount'] = $category->coursecount;
1924 $categoryinfo['depth'] = $category->depth;
1925 $categoryinfo['path'] = $category->path;
1927 // Some fields only returned for admin.
1928 if (has_capability('moodle/category:manage', $context)) {
1929 $categoryinfo['idnumber'] = $category->idnumber;
1930 $categoryinfo['visible'] = $category->visible;
1931 $categoryinfo['visibleold'] = $category->visibleold;
1932 $categoryinfo['timemodified'] = $category->timemodified;
1933 $categoryinfo['theme'] = clean_param($category->theme, PARAM_THEME);
1936 $categoriesinfo[] = $categoryinfo;
1937 } else {
1938 $excludedcats[$category->id] = 'visibility';
1943 // Sorting the resulting array so it looks a bit better for the client developer.
1944 usort($categoriesinfo, "core_course_external::compare_categories_by_sortorder");
1946 return $categoriesinfo;
1950 * Sort categories array by path
1951 * private function: only used by get_categories
1953 * @param array $category1
1954 * @param array $category2
1955 * @return int result of strcmp
1956 * @since Moodle 2.3
1958 private static function compare_categories_by_path($category1, $category2) {
1959 return strcmp($category1->path, $category2->path);
1963 * Sort categories array by sortorder
1964 * private function: only used by get_categories
1966 * @param array $category1
1967 * @param array $category2
1968 * @return int result of strcmp
1969 * @since Moodle 2.3
1971 private static function compare_categories_by_sortorder($category1, $category2) {
1972 return strcmp($category1['sortorder'], $category2['sortorder']);
1976 * Returns description of method result value
1978 * @return external_description
1979 * @since Moodle 2.3
1981 public static function get_categories_returns() {
1982 return new external_multiple_structure(
1983 new external_single_structure(
1984 array(
1985 'id' => new external_value(PARAM_INT, 'category id'),
1986 'name' => new external_value(PARAM_RAW, 'category name'),
1987 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1988 'description' => new external_value(PARAM_RAW, 'category description'),
1989 'descriptionformat' => new external_format_value('description'),
1990 'parent' => new external_value(PARAM_INT, 'parent category id'),
1991 'sortorder' => new external_value(PARAM_INT, 'category sorting order'),
1992 'coursecount' => new external_value(PARAM_INT, 'number of courses in this category'),
1993 'visible' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1994 'visibleold' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1995 'timemodified' => new external_value(PARAM_INT, 'timestamp', VALUE_OPTIONAL),
1996 'depth' => new external_value(PARAM_INT, 'category depth'),
1997 'path' => new external_value(PARAM_TEXT, 'category path'),
1998 'theme' => new external_value(PARAM_THEME, 'category theme', VALUE_OPTIONAL),
1999 ), 'List of categories'
2005 * Returns description of method parameters
2007 * @return external_function_parameters
2008 * @since Moodle 2.3
2010 public static function create_categories_parameters() {
2011 return new external_function_parameters(
2012 array(
2013 'categories' => new external_multiple_structure(
2014 new external_single_structure(
2015 array(
2016 'name' => new external_value(PARAM_TEXT, 'new category name'),
2017 'parent' => new external_value(PARAM_INT,
2018 'the parent category id inside which the new category will be created
2019 - set to 0 for a root category',
2020 VALUE_DEFAULT, 0),
2021 'idnumber' => new external_value(PARAM_RAW,
2022 'the new category idnumber', VALUE_OPTIONAL),
2023 'description' => new external_value(PARAM_RAW,
2024 'the new category description', VALUE_OPTIONAL),
2025 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
2026 'theme' => new external_value(PARAM_THEME,
2027 'the new category theme. This option must be enabled on moodle',
2028 VALUE_OPTIONAL),
2037 * Create categories
2039 * @param array $categories - see create_categories_parameters() for the array structure
2040 * @return array - see create_categories_returns() for the array structure
2041 * @since Moodle 2.3
2043 public static function create_categories($categories) {
2044 global $DB;
2046 $params = self::validate_parameters(self::create_categories_parameters(),
2047 array('categories' => $categories));
2049 $transaction = $DB->start_delegated_transaction();
2051 $createdcategories = array();
2052 foreach ($params['categories'] as $category) {
2053 if ($category['parent']) {
2054 if (!$DB->record_exists('course_categories', array('id' => $category['parent']))) {
2055 throw new moodle_exception('unknowcategory');
2057 $context = context_coursecat::instance($category['parent']);
2058 } else {
2059 $context = context_system::instance();
2061 self::validate_context($context);
2062 require_capability('moodle/category:manage', $context);
2064 // this will validate format and throw an exception if there are errors
2065 external_validate_format($category['descriptionformat']);
2067 $newcategory = core_course_category::create($category);
2068 $context = context_coursecat::instance($newcategory->id);
2070 $createdcategories[] = array(
2071 'id' => $newcategory->id,
2072 'name' => external_format_string($newcategory->name, $context),
2076 $transaction->allow_commit();
2078 return $createdcategories;
2082 * Returns description of method parameters
2084 * @return external_function_parameters
2085 * @since Moodle 2.3
2087 public static function create_categories_returns() {
2088 return new external_multiple_structure(
2089 new external_single_structure(
2090 array(
2091 'id' => new external_value(PARAM_INT, 'new category id'),
2092 'name' => new external_value(PARAM_RAW, 'new category name'),
2099 * Returns description of method parameters
2101 * @return external_function_parameters
2102 * @since Moodle 2.3
2104 public static function update_categories_parameters() {
2105 return new external_function_parameters(
2106 array(
2107 'categories' => new external_multiple_structure(
2108 new external_single_structure(
2109 array(
2110 'id' => new external_value(PARAM_INT, 'course id'),
2111 'name' => new external_value(PARAM_TEXT, 'category name', VALUE_OPTIONAL),
2112 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
2113 'parent' => new external_value(PARAM_INT, 'parent category id', VALUE_OPTIONAL),
2114 'description' => new external_value(PARAM_RAW, 'category description', VALUE_OPTIONAL),
2115 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
2116 'theme' => new external_value(PARAM_THEME,
2117 'the category theme. This option must be enabled on moodle', VALUE_OPTIONAL),
2126 * Update categories
2128 * @param array $categories The list of categories to update
2129 * @return null
2130 * @since Moodle 2.3
2132 public static function update_categories($categories) {
2133 global $DB;
2135 // Validate parameters.
2136 $params = self::validate_parameters(self::update_categories_parameters(), array('categories' => $categories));
2138 $transaction = $DB->start_delegated_transaction();
2140 foreach ($params['categories'] as $cat) {
2141 $category = core_course_category::get($cat['id']);
2143 $categorycontext = context_coursecat::instance($cat['id']);
2144 self::validate_context($categorycontext);
2145 require_capability('moodle/category:manage', $categorycontext);
2147 // this will throw an exception if descriptionformat is not valid
2148 external_validate_format($cat['descriptionformat']);
2150 $category->update($cat);
2153 $transaction->allow_commit();
2157 * Returns description of method result value
2159 * @return external_description
2160 * @since Moodle 2.3
2162 public static function update_categories_returns() {
2163 return null;
2167 * Returns description of method parameters
2169 * @return external_function_parameters
2170 * @since Moodle 2.3
2172 public static function delete_categories_parameters() {
2173 return new external_function_parameters(
2174 array(
2175 'categories' => new external_multiple_structure(
2176 new external_single_structure(
2177 array(
2178 'id' => new external_value(PARAM_INT, 'category id to delete'),
2179 'newparent' => new external_value(PARAM_INT,
2180 'the parent category to move the contents to, if specified', VALUE_OPTIONAL),
2181 'recursive' => new external_value(PARAM_BOOL, '1: recursively delete all contents inside this
2182 category, 0 (default): move contents to newparent or current parent category (except if parent is root)', VALUE_DEFAULT, 0)
2191 * Delete categories
2193 * @param array $categories A list of category ids
2194 * @return array
2195 * @since Moodle 2.3
2197 public static function delete_categories($categories) {
2198 global $CFG, $DB;
2199 require_once($CFG->dirroot . "/course/lib.php");
2201 // Validate parameters.
2202 $params = self::validate_parameters(self::delete_categories_parameters(), array('categories' => $categories));
2204 $transaction = $DB->start_delegated_transaction();
2206 foreach ($params['categories'] as $category) {
2207 $deletecat = core_course_category::get($category['id'], MUST_EXIST);
2208 $context = context_coursecat::instance($deletecat->id);
2209 require_capability('moodle/category:manage', $context);
2210 self::validate_context($context);
2211 self::validate_context(get_category_or_system_context($deletecat->parent));
2213 if ($category['recursive']) {
2214 // If recursive was specified, then we recursively delete the category's contents.
2215 if ($deletecat->can_delete_full()) {
2216 $deletecat->delete_full(false);
2217 } else {
2218 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2220 } else {
2221 // In this situation, we don't delete the category's contents, we either move it to newparent or parent.
2222 // If the parent is the root, moving is not supported (because a course must always be inside a category).
2223 // We must move to an existing category.
2224 if (!empty($category['newparent'])) {
2225 $newparentcat = core_course_category::get($category['newparent']);
2226 } else {
2227 $newparentcat = core_course_category::get($deletecat->parent);
2230 // This operation is not allowed. We must move contents to an existing category.
2231 if (!$newparentcat->id) {
2232 throw new moodle_exception('movecatcontentstoroot');
2235 self::validate_context(context_coursecat::instance($newparentcat->id));
2236 if ($deletecat->can_move_content_to($newparentcat->id)) {
2237 $deletecat->delete_move($newparentcat->id, false);
2238 } else {
2239 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2244 $transaction->allow_commit();
2248 * Returns description of method parameters
2250 * @return external_function_parameters
2251 * @since Moodle 2.3
2253 public static function delete_categories_returns() {
2254 return null;
2258 * Describes the parameters for delete_modules.
2260 * @return external_function_parameters
2261 * @since Moodle 2.5
2263 public static function delete_modules_parameters() {
2264 return new external_function_parameters (
2265 array(
2266 'cmids' => new external_multiple_structure(new external_value(PARAM_INT, 'course module ID',
2267 VALUE_REQUIRED, '', NULL_NOT_ALLOWED), 'Array of course module IDs'),
2273 * Deletes a list of provided module instances.
2275 * @param array $cmids the course module ids
2276 * @since Moodle 2.5
2278 public static function delete_modules($cmids) {
2279 global $CFG, $DB;
2281 // Require course file containing the course delete module function.
2282 require_once($CFG->dirroot . "/course/lib.php");
2284 // Clean the parameters.
2285 $params = self::validate_parameters(self::delete_modules_parameters(), array('cmids' => $cmids));
2287 // Keep track of the course ids we have performed a capability check on to avoid repeating.
2288 $arrcourseschecked = array();
2290 foreach ($params['cmids'] as $cmid) {
2291 // Get the course module.
2292 $cm = $DB->get_record('course_modules', array('id' => $cmid), '*', MUST_EXIST);
2294 // Check if we have not yet confirmed they have permission in this course.
2295 if (!in_array($cm->course, $arrcourseschecked)) {
2296 // Ensure the current user has required permission in this course.
2297 $context = context_course::instance($cm->course);
2298 self::validate_context($context);
2299 // Add to the array.
2300 $arrcourseschecked[] = $cm->course;
2303 // Ensure they can delete this module.
2304 $modcontext = context_module::instance($cm->id);
2305 require_capability('moodle/course:manageactivities', $modcontext);
2307 // Delete the module.
2308 course_delete_module($cm->id);
2313 * Describes the delete_modules return value.
2315 * @return external_single_structure
2316 * @since Moodle 2.5
2318 public static function delete_modules_returns() {
2319 return null;
2323 * Returns description of method parameters
2325 * @return external_function_parameters
2326 * @since Moodle 2.9
2328 public static function view_course_parameters() {
2329 return new external_function_parameters(
2330 array(
2331 'courseid' => new external_value(PARAM_INT, 'id of the course'),
2332 'sectionnumber' => new external_value(PARAM_INT, 'section number', VALUE_DEFAULT, 0)
2338 * Trigger the course viewed event.
2340 * @param int $courseid id of course
2341 * @param int $sectionnumber sectionnumber (0, 1, 2...)
2342 * @return array of warnings and status result
2343 * @since Moodle 2.9
2344 * @throws moodle_exception
2346 public static function view_course($courseid, $sectionnumber = 0) {
2347 global $CFG;
2348 require_once($CFG->dirroot . "/course/lib.php");
2350 $params = self::validate_parameters(self::view_course_parameters(),
2351 array(
2352 'courseid' => $courseid,
2353 'sectionnumber' => $sectionnumber
2356 $warnings = array();
2358 $course = get_course($params['courseid']);
2359 $context = context_course::instance($course->id);
2360 self::validate_context($context);
2362 if (!empty($params['sectionnumber'])) {
2364 // Get section details and check it exists.
2365 $modinfo = get_fast_modinfo($course);
2366 $coursesection = $modinfo->get_section_info($params['sectionnumber'], MUST_EXIST);
2368 // Check user is allowed to see it.
2369 if (!$coursesection->uservisible) {
2370 require_capability('moodle/course:viewhiddensections', $context);
2374 course_view($context, $params['sectionnumber']);
2376 $result = array();
2377 $result['status'] = true;
2378 $result['warnings'] = $warnings;
2379 return $result;
2383 * Returns description of method result value
2385 * @return external_description
2386 * @since Moodle 2.9
2388 public static function view_course_returns() {
2389 return new external_single_structure(
2390 array(
2391 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
2392 'warnings' => new external_warnings()
2398 * Returns description of method parameters
2400 * @return external_function_parameters
2401 * @since Moodle 3.0
2403 public static function search_courses_parameters() {
2404 return new external_function_parameters(
2405 array(
2406 'criterianame' => new external_value(PARAM_ALPHA, 'criteria name
2407 (search, modulelist (only admins), blocklist (only admins), tagid)'),
2408 'criteriavalue' => new external_value(PARAM_RAW, 'criteria value'),
2409 'page' => new external_value(PARAM_INT, 'page number (0 based)', VALUE_DEFAULT, 0),
2410 'perpage' => new external_value(PARAM_INT, 'items per page', VALUE_DEFAULT, 0),
2411 'requiredcapabilities' => new external_multiple_structure(
2412 new external_value(PARAM_CAPABILITY, 'Capability string used to filter courses by permission'),
2413 'Optional list of required capabilities (used to filter the list)', VALUE_DEFAULT, array()
2415 'limittoenrolled' => new external_value(PARAM_BOOL, 'limit to enrolled courses', VALUE_DEFAULT, 0),
2416 'onlywithcompletion' => new external_value(PARAM_BOOL, 'limit to courses where completion is enabled',
2417 VALUE_DEFAULT, 0),
2423 * Return the course information that is public (visible by every one)
2425 * @param core_course_list_element $course course in list object
2426 * @param stdClass $coursecontext course context object
2427 * @return array the course information
2428 * @since Moodle 3.2
2430 protected static function get_course_public_information(core_course_list_element $course, $coursecontext) {
2432 static $categoriescache = array();
2434 // Category information.
2435 if (!array_key_exists($course->category, $categoriescache)) {
2436 $categoriescache[$course->category] = core_course_category::get($course->category, IGNORE_MISSING);
2438 $category = $categoriescache[$course->category];
2440 // Retrieve course overview used files.
2441 $files = array();
2442 foreach ($course->get_course_overviewfiles() as $file) {
2443 $fileurl = moodle_url::make_webservice_pluginfile_url($file->get_contextid(), $file->get_component(),
2444 $file->get_filearea(), null, $file->get_filepath(),
2445 $file->get_filename())->out(false);
2446 $files[] = array(
2447 'filename' => $file->get_filename(),
2448 'fileurl' => $fileurl,
2449 'filesize' => $file->get_filesize(),
2450 'filepath' => $file->get_filepath(),
2451 'mimetype' => $file->get_mimetype(),
2452 'timemodified' => $file->get_timemodified(),
2456 // Retrieve the course contacts,
2457 // we need here the users fullname since if we are not enrolled can be difficult to obtain them via other Web Services.
2458 $coursecontacts = array();
2459 foreach ($course->get_course_contacts() as $contact) {
2460 $coursecontacts[] = array(
2461 'id' => $contact['user']->id,
2462 'fullname' => $contact['username'],
2463 'roles' => array_map(function($role){
2464 return array('id' => $role->id, 'name' => $role->displayname);
2465 }, $contact['roles']),
2466 'role' => array('id' => $contact['role']->id, 'name' => $contact['role']->displayname),
2467 'rolename' => $contact['rolename']
2471 // Allowed enrolment methods (maybe we can self-enrol).
2472 $enroltypes = array();
2473 $instances = enrol_get_instances($course->id, true);
2474 foreach ($instances as $instance) {
2475 $enroltypes[] = $instance->enrol;
2478 // Format summary.
2479 list($summary, $summaryformat) =
2480 external_format_text($course->summary, $course->summaryformat, $coursecontext->id, 'course', 'summary', null);
2482 $categoryname = '';
2483 if (!empty($category)) {
2484 $categoryname = external_format_string($category->name, $category->get_context());
2487 $displayname = get_course_display_name_for_list($course);
2488 $coursereturns = array();
2489 $coursereturns['id'] = $course->id;
2490 $coursereturns['fullname'] = external_format_string($course->fullname, $coursecontext->id);
2491 $coursereturns['displayname'] = external_format_string($displayname, $coursecontext->id);
2492 $coursereturns['shortname'] = external_format_string($course->shortname, $coursecontext->id);
2493 $coursereturns['categoryid'] = $course->category;
2494 $coursereturns['categoryname'] = $categoryname;
2495 $coursereturns['summary'] = $summary;
2496 $coursereturns['summaryformat'] = $summaryformat;
2497 $coursereturns['summaryfiles'] = external_util::get_area_files($coursecontext->id, 'course', 'summary', false, false);
2498 $coursereturns['overviewfiles'] = $files;
2499 $coursereturns['contacts'] = $coursecontacts;
2500 $coursereturns['enrollmentmethods'] = $enroltypes;
2501 $coursereturns['sortorder'] = $course->sortorder;
2502 $coursereturns['showactivitydates'] = $course->showactivitydates;
2503 $coursereturns['showcompletionconditions'] = $course->showcompletionconditions;
2505 $handler = core_course\customfield\course_handler::create();
2506 if ($customfields = $handler->export_instance_data($course->id)) {
2507 $coursereturns['customfields'] = [];
2508 foreach ($customfields as $data) {
2509 $coursereturns['customfields'][] = [
2510 'type' => $data->get_type(),
2511 'value' => $data->get_value(),
2512 'valueraw' => $data->get_data_controller()->get_value(),
2513 'name' => $data->get_name(),
2514 'shortname' => $data->get_shortname()
2519 return $coursereturns;
2523 * Search courses following the specified criteria.
2525 * @param string $criterianame Criteria name (search, modulelist (only admins), blocklist (only admins), tagid)
2526 * @param string $criteriavalue Criteria value
2527 * @param int $page Page number (for pagination)
2528 * @param int $perpage Items per page
2529 * @param array $requiredcapabilities Optional list of required capabilities (used to filter the list).
2530 * @param int $limittoenrolled Limit to only enrolled courses
2531 * @param int onlywithcompletion Limit to only courses where completion is enabled
2532 * @return array of course objects and warnings
2533 * @since Moodle 3.0
2534 * @throws moodle_exception
2536 public static function search_courses($criterianame,
2537 $criteriavalue,
2538 $page=0,
2539 $perpage=0,
2540 $requiredcapabilities=array(),
2541 $limittoenrolled=0,
2542 $onlywithcompletion=0) {
2543 global $CFG;
2545 $warnings = array();
2547 $parameters = array(
2548 'criterianame' => $criterianame,
2549 'criteriavalue' => $criteriavalue,
2550 'page' => $page,
2551 'perpage' => $perpage,
2552 'requiredcapabilities' => $requiredcapabilities,
2553 'limittoenrolled' => $limittoenrolled,
2554 'onlywithcompletion' => $onlywithcompletion
2556 $params = self::validate_parameters(self::search_courses_parameters(), $parameters);
2557 self::validate_context(context_system::instance());
2559 $allowedcriterianames = array('search', 'modulelist', 'blocklist', 'tagid');
2560 if (!in_array($params['criterianame'], $allowedcriterianames)) {
2561 throw new invalid_parameter_exception('Invalid value for criterianame parameter (value: '.$params['criterianame'].'),' .
2562 'allowed values are: '.implode(',', $allowedcriterianames));
2565 if ($params['criterianame'] == 'modulelist' or $params['criterianame'] == 'blocklist') {
2566 require_capability('moodle/site:config', context_system::instance());
2569 $paramtype = array(
2570 'search' => PARAM_RAW,
2571 'modulelist' => PARAM_PLUGIN,
2572 'blocklist' => PARAM_INT,
2573 'tagid' => PARAM_INT
2575 $params['criteriavalue'] = clean_param($params['criteriavalue'], $paramtype[$params['criterianame']]);
2577 // Prepare the search API options.
2578 $searchcriteria = array();
2579 $searchcriteria[$params['criterianame']] = $params['criteriavalue'];
2580 if ($params['onlywithcompletion']) {
2581 $searchcriteria['onlywithcompletion'] = true;
2584 $options = array();
2585 if ($params['perpage'] != 0) {
2586 $offset = $params['page'] * $params['perpage'];
2587 $options = array('offset' => $offset, 'limit' => $params['perpage']);
2590 // Search the courses.
2591 $courses = core_course_category::search_courses($searchcriteria, $options, $params['requiredcapabilities']);
2592 $totalcount = core_course_category::search_courses_count($searchcriteria, $options, $params['requiredcapabilities']);
2594 if (!empty($limittoenrolled)) {
2595 // Get the courses where the current user has access.
2596 $enrolled = enrol_get_my_courses(array('id', 'cacherev'));
2599 $finalcourses = array();
2600 $categoriescache = array();
2602 foreach ($courses as $course) {
2603 if (!empty($limittoenrolled)) {
2604 // Filter out not enrolled courses.
2605 if (!isset($enrolled[$course->id])) {
2606 $totalcount--;
2607 continue;
2611 $coursecontext = context_course::instance($course->id);
2613 $finalcourses[] = self::get_course_public_information($course, $coursecontext);
2616 return array(
2617 'total' => $totalcount,
2618 'courses' => $finalcourses,
2619 'warnings' => $warnings
2624 * Returns a course structure definition
2626 * @param boolean $onlypublicdata set to true, to retrieve only fields viewable by anyone when the course is visible
2627 * @return array the course structure
2628 * @since Moodle 3.2
2630 protected static function get_course_structure($onlypublicdata = true) {
2631 $coursestructure = array(
2632 'id' => new external_value(PARAM_INT, 'course id'),
2633 'fullname' => new external_value(PARAM_RAW, 'course full name'),
2634 'displayname' => new external_value(PARAM_RAW, 'course display name'),
2635 'shortname' => new external_value(PARAM_RAW, 'course short name'),
2636 'categoryid' => new external_value(PARAM_INT, 'category id'),
2637 'categoryname' => new external_value(PARAM_RAW, 'category name'),
2638 'sortorder' => new external_value(PARAM_INT, 'Sort order in the category', VALUE_OPTIONAL),
2639 'summary' => new external_value(PARAM_RAW, 'summary'),
2640 'summaryformat' => new external_format_value('summary'),
2641 'summaryfiles' => new external_files('summary files in the summary field', VALUE_OPTIONAL),
2642 'overviewfiles' => new external_files('additional overview files attached to this course'),
2643 'showactivitydates' => new external_value(PARAM_BOOL, 'Whether the activity dates are shown or not'),
2644 'showcompletionconditions' => new external_value(PARAM_BOOL,
2645 'Whether the activity completion conditions are shown or not'),
2646 'contacts' => new external_multiple_structure(
2647 new external_single_structure(
2648 array(
2649 'id' => new external_value(PARAM_INT, 'contact user id'),
2650 'fullname' => new external_value(PARAM_NOTAGS, 'contact user fullname'),
2653 'contact users'
2655 'enrollmentmethods' => new external_multiple_structure(
2656 new external_value(PARAM_PLUGIN, 'enrollment method'),
2657 'enrollment methods list'
2659 'customfields' => new external_multiple_structure(
2660 new external_single_structure(
2661 array(
2662 'name' => new external_value(PARAM_RAW, 'The name of the custom field'),
2663 'shortname' => new external_value(PARAM_RAW,
2664 'The shortname of the custom field - to be able to build the field class in the code'),
2665 'type' => new external_value(PARAM_ALPHANUMEXT,
2666 'The type of the custom field - text field, checkbox...'),
2667 'valueraw' => new external_value(PARAM_RAW, 'The raw value of the custom field'),
2668 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
2670 ), 'Custom fields', VALUE_OPTIONAL),
2673 if (!$onlypublicdata) {
2674 $extra = array(
2675 'idnumber' => new external_value(PARAM_RAW, 'Id number', VALUE_OPTIONAL),
2676 'format' => new external_value(PARAM_PLUGIN, 'Course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
2677 'showgrades' => new external_value(PARAM_INT, '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
2678 'newsitems' => new external_value(PARAM_INT, 'Number of recent items appearing on the course page', VALUE_OPTIONAL),
2679 'startdate' => new external_value(PARAM_INT, 'Timestamp when the course start', VALUE_OPTIONAL),
2680 'enddate' => new external_value(PARAM_INT, 'Timestamp when the course end', VALUE_OPTIONAL),
2681 'maxbytes' => new external_value(PARAM_INT, 'Largest size of file that can be uploaded into', VALUE_OPTIONAL),
2682 'showreports' => new external_value(PARAM_INT, 'Are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
2683 'visible' => new external_value(PARAM_INT, '1: available to student, 0:not available', VALUE_OPTIONAL),
2684 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
2685 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
2686 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
2687 'enablecompletion' => new external_value(PARAM_INT, 'Completion enabled? 1: yes 0: no', VALUE_OPTIONAL),
2688 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
2689 'lang' => new external_value(PARAM_SAFEDIR, 'Forced course language', VALUE_OPTIONAL),
2690 'theme' => new external_value(PARAM_PLUGIN, 'Fame of the forced theme', VALUE_OPTIONAL),
2691 'marker' => new external_value(PARAM_INT, 'Current course marker', VALUE_OPTIONAL),
2692 'legacyfiles' => new external_value(PARAM_INT, 'If legacy files are enabled', VALUE_OPTIONAL),
2693 'calendartype' => new external_value(PARAM_PLUGIN, 'Calendar type', VALUE_OPTIONAL),
2694 'timecreated' => new external_value(PARAM_INT, 'Time when the course was created', VALUE_OPTIONAL),
2695 'timemodified' => new external_value(PARAM_INT, 'Last time the course was updated', VALUE_OPTIONAL),
2696 'requested' => new external_value(PARAM_INT, 'If is a requested course', VALUE_OPTIONAL),
2697 'cacherev' => new external_value(PARAM_INT, 'Cache revision number', VALUE_OPTIONAL),
2698 'filters' => new external_multiple_structure(
2699 new external_single_structure(
2700 array(
2701 'filter' => new external_value(PARAM_PLUGIN, 'Filter plugin name'),
2702 'localstate' => new external_value(PARAM_INT, 'Filter state: 1 for on, -1 for off, 0 if inherit'),
2703 'inheritedstate' => new external_value(PARAM_INT, '1 or 0 to use when localstate is set to inherit'),
2706 'Course filters', VALUE_OPTIONAL
2708 'courseformatoptions' => new external_multiple_structure(
2709 new external_single_structure(
2710 array(
2711 'name' => new external_value(PARAM_RAW, 'Course format option name.'),
2712 'value' => new external_value(PARAM_RAW, 'Course format option value.'),
2715 'Additional options for particular course format.', VALUE_OPTIONAL
2718 $coursestructure = array_merge($coursestructure, $extra);
2720 return new external_single_structure($coursestructure);
2724 * Returns description of method result value
2726 * @return external_description
2727 * @since Moodle 3.0
2729 public static function search_courses_returns() {
2730 return new external_single_structure(
2731 array(
2732 'total' => new external_value(PARAM_INT, 'total course count'),
2733 'courses' => new external_multiple_structure(self::get_course_structure(), 'course'),
2734 'warnings' => new external_warnings()
2740 * Returns description of method parameters
2742 * @return external_function_parameters
2743 * @since Moodle 3.0
2745 public static function get_course_module_parameters() {
2746 return new external_function_parameters(
2747 array(
2748 'cmid' => new external_value(PARAM_INT, 'The course module id')
2754 * Return information about a course module.
2756 * @param int $cmid the course module id
2757 * @return array of warnings and the course module
2758 * @since Moodle 3.0
2759 * @throws moodle_exception
2761 public static function get_course_module($cmid) {
2762 global $CFG, $DB;
2764 $params = self::validate_parameters(self::get_course_module_parameters(), array('cmid' => $cmid));
2765 $warnings = array();
2767 $cm = get_coursemodule_from_id(null, $params['cmid'], 0, true, MUST_EXIST);
2768 $context = context_module::instance($cm->id);
2769 self::validate_context($context);
2771 // If the user has permissions to manage the activity, return all the information.
2772 if (has_capability('moodle/course:manageactivities', $context)) {
2773 require_once($CFG->dirroot . '/course/modlib.php');
2774 require_once($CFG->libdir . '/gradelib.php');
2776 $info = $cm;
2777 // Get the extra information: grade, advanced grading and outcomes data.
2778 $course = get_course($cm->course);
2779 list($newcm, $newcontext, $module, $extrainfo, $cw) = get_moduleinfo_data($cm, $course);
2780 // Grades.
2781 $gradeinfo = array('grade', 'gradepass', 'gradecat');
2782 foreach ($gradeinfo as $gfield) {
2783 if (isset($extrainfo->{$gfield})) {
2784 $info->{$gfield} = $extrainfo->{$gfield};
2787 if (isset($extrainfo->grade) and $extrainfo->grade < 0) {
2788 $info->scale = $DB->get_field('scale', 'scale', array('id' => abs($extrainfo->grade)));
2790 // Advanced grading.
2791 if (isset($extrainfo->_advancedgradingdata)) {
2792 $info->advancedgrading = array();
2793 foreach ($extrainfo as $key => $val) {
2794 if (strpos($key, 'advancedgradingmethod_') === 0) {
2795 $info->advancedgrading[] = array(
2796 'area' => str_replace('advancedgradingmethod_', '', $key),
2797 'method' => $val
2802 // Outcomes.
2803 foreach ($extrainfo as $key => $val) {
2804 if (strpos($key, 'outcome_') === 0) {
2805 if (!isset($info->outcomes)) {
2806 $info->outcomes = array();
2808 $id = str_replace('outcome_', '', $key);
2809 $outcome = grade_outcome::fetch(array('id' => $id));
2810 $scaleitems = $outcome->load_scale();
2811 $info->outcomes[] = array(
2812 'id' => $id,
2813 'name' => external_format_string($outcome->get_name(), $context->id),
2814 'scale' => $scaleitems->scale
2818 } else {
2819 // Return information is safe to show to any user.
2820 $info = new stdClass();
2821 $info->id = $cm->id;
2822 $info->course = $cm->course;
2823 $info->module = $cm->module;
2824 $info->modname = $cm->modname;
2825 $info->instance = $cm->instance;
2826 $info->section = $cm->section;
2827 $info->sectionnum = $cm->sectionnum;
2828 $info->groupmode = $cm->groupmode;
2829 $info->groupingid = $cm->groupingid;
2830 $info->completion = $cm->completion;
2831 $info->downloadcontent = $cm->downloadcontent;
2833 // Format name.
2834 $info->name = external_format_string($cm->name, $context->id);
2835 $result = array();
2836 $result['cm'] = $info;
2837 $result['warnings'] = $warnings;
2838 return $result;
2842 * Returns description of method result value
2844 * @return external_description
2845 * @since Moodle 3.0
2847 public static function get_course_module_returns() {
2848 return new external_single_structure(
2849 array(
2850 'cm' => new external_single_structure(
2851 array(
2852 'id' => new external_value(PARAM_INT, 'The course module id'),
2853 'course' => new external_value(PARAM_INT, 'The course id'),
2854 'module' => new external_value(PARAM_INT, 'The module type id'),
2855 'name' => new external_value(PARAM_RAW, 'The activity name'),
2856 'modname' => new external_value(PARAM_COMPONENT, 'The module component name (forum, assign, etc..)'),
2857 'instance' => new external_value(PARAM_INT, 'The activity instance id'),
2858 'section' => new external_value(PARAM_INT, 'The module section id'),
2859 'sectionnum' => new external_value(PARAM_INT, 'The module section number'),
2860 'groupmode' => new external_value(PARAM_INT, 'Group mode'),
2861 'groupingid' => new external_value(PARAM_INT, 'Grouping id'),
2862 'completion' => new external_value(PARAM_INT, 'If completion is enabled'),
2863 'idnumber' => new external_value(PARAM_RAW, 'Module id number', VALUE_OPTIONAL),
2864 'added' => new external_value(PARAM_INT, 'Time added', VALUE_OPTIONAL),
2865 'score' => new external_value(PARAM_INT, 'Score', VALUE_OPTIONAL),
2866 'indent' => new external_value(PARAM_INT, 'Indentation', VALUE_OPTIONAL),
2867 'visible' => new external_value(PARAM_INT, 'If visible', VALUE_OPTIONAL),
2868 'visibleoncoursepage' => new external_value(PARAM_INT, 'If visible on course page', VALUE_OPTIONAL),
2869 'visibleold' => new external_value(PARAM_INT, 'Visible old', VALUE_OPTIONAL),
2870 'completiongradeitemnumber' => new external_value(PARAM_INT, 'Completion grade item', VALUE_OPTIONAL),
2871 'completionpassgrade' => new external_value(PARAM_INT, 'Completion pass grade setting', VALUE_OPTIONAL),
2872 'completionview' => new external_value(PARAM_INT, 'Completion view setting', VALUE_OPTIONAL),
2873 'completionexpected' => new external_value(PARAM_INT, 'Completion time expected', VALUE_OPTIONAL),
2874 'showdescription' => new external_value(PARAM_INT, 'If the description is showed', VALUE_OPTIONAL),
2875 'downloadcontent' => new external_value(PARAM_INT, 'The download content value', VALUE_OPTIONAL),
2876 'availability' => new external_value(PARAM_RAW, 'Availability settings', VALUE_OPTIONAL),
2877 'grade' => new external_value(PARAM_FLOAT, 'Grade (max value or scale id)', VALUE_OPTIONAL),
2878 'scale' => new external_value(PARAM_TEXT, 'Scale items (if used)', VALUE_OPTIONAL),
2879 'gradepass' => new external_value(PARAM_RAW, 'Grade to pass (float)', VALUE_OPTIONAL),
2880 'gradecat' => new external_value(PARAM_INT, 'Grade category', VALUE_OPTIONAL),
2881 'advancedgrading' => new external_multiple_structure(
2882 new external_single_structure(
2883 array(
2884 'area' => new external_value(PARAM_AREA, 'Gradable area name'),
2885 'method' => new external_value(PARAM_COMPONENT, 'Grading method'),
2888 'Advanced grading settings', VALUE_OPTIONAL
2890 'outcomes' => new external_multiple_structure(
2891 new external_single_structure(
2892 array(
2893 'id' => new external_value(PARAM_ALPHANUMEXT, 'Outcome id'),
2894 'name' => new external_value(PARAM_RAW, 'Outcome full name'),
2895 'scale' => new external_value(PARAM_TEXT, 'Scale items')
2898 'Outcomes information', VALUE_OPTIONAL
2902 'warnings' => new external_warnings()
2908 * Returns description of method parameters
2910 * @return external_function_parameters
2911 * @since Moodle 3.0
2913 public static function get_course_module_by_instance_parameters() {
2914 return new external_function_parameters(
2915 array(
2916 'module' => new external_value(PARAM_COMPONENT, 'The module name'),
2917 'instance' => new external_value(PARAM_INT, 'The module instance id')
2923 * Return information about a course module.
2925 * @param string $module the module name
2926 * @param int $instance the activity instance id
2927 * @return array of warnings and the course module
2928 * @since Moodle 3.0
2929 * @throws moodle_exception
2931 public static function get_course_module_by_instance($module, $instance) {
2933 $params = self::validate_parameters(self::get_course_module_by_instance_parameters(),
2934 array(
2935 'module' => $module,
2936 'instance' => $instance,
2939 $warnings = array();
2940 $cm = get_coursemodule_from_instance($params['module'], $params['instance'], 0, false, MUST_EXIST);
2942 return self::get_course_module($cm->id);
2946 * Returns description of method result value
2948 * @return external_description
2949 * @since Moodle 3.0
2951 public static function get_course_module_by_instance_returns() {
2952 return self::get_course_module_returns();
2956 * Returns description of method parameters
2958 * @return external_function_parameters
2959 * @since Moodle 3.2
2961 public static function get_user_navigation_options_parameters() {
2962 return new external_function_parameters(
2963 array(
2964 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2970 * Return a list of navigation options in a set of courses that are avaialable or not for the current user.
2972 * @param array $courseids a list of course ids
2973 * @return array of warnings and the options availability
2974 * @since Moodle 3.2
2975 * @throws moodle_exception
2977 public static function get_user_navigation_options($courseids) {
2978 global $CFG;
2979 require_once($CFG->dirroot . '/course/lib.php');
2981 // Parameter validation.
2982 $params = self::validate_parameters(self::get_user_navigation_options_parameters(), array('courseids' => $courseids));
2983 $courseoptions = array();
2985 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
2987 if (!empty($courses)) {
2988 foreach ($courses as $course) {
2989 // Fix the context for the frontpage.
2990 if ($course->id == SITEID) {
2991 $course->context = context_system::instance();
2993 $navoptions = course_get_user_navigation_options($course->context, $course);
2994 $options = array();
2995 foreach ($navoptions as $name => $available) {
2996 $options[] = array(
2997 'name' => $name,
2998 'available' => $available,
3002 $courseoptions[] = array(
3003 'id' => $course->id,
3004 'options' => $options
3009 $result = array(
3010 'courses' => $courseoptions,
3011 'warnings' => $warnings
3013 return $result;
3017 * Returns description of method result value
3019 * @return external_description
3020 * @since Moodle 3.2
3022 public static function get_user_navigation_options_returns() {
3023 return new external_single_structure(
3024 array(
3025 'courses' => new external_multiple_structure(
3026 new external_single_structure(
3027 array(
3028 'id' => new external_value(PARAM_INT, 'Course id'),
3029 'options' => new external_multiple_structure(
3030 new external_single_structure(
3031 array(
3032 'name' => new external_value(PARAM_ALPHANUMEXT, 'Option name'),
3033 'available' => new external_value(PARAM_BOOL, 'Whether the option is available or not'),
3038 ), 'List of courses'
3040 'warnings' => new external_warnings()
3046 * Returns description of method parameters
3048 * @return external_function_parameters
3049 * @since Moodle 3.2
3051 public static function get_user_administration_options_parameters() {
3052 return new external_function_parameters(
3053 array(
3054 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
3060 * Return a list of administration options in a set of courses that are available or not for the current user.
3062 * @param array $courseids a list of course ids
3063 * @return array of warnings and the options availability
3064 * @since Moodle 3.2
3065 * @throws moodle_exception
3067 public static function get_user_administration_options($courseids) {
3068 global $CFG;
3069 require_once($CFG->dirroot . '/course/lib.php');
3071 // Parameter validation.
3072 $params = self::validate_parameters(self::get_user_administration_options_parameters(), array('courseids' => $courseids));
3073 $courseoptions = array();
3075 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
3077 if (!empty($courses)) {
3078 foreach ($courses as $course) {
3079 $adminoptions = course_get_user_administration_options($course, $course->context);
3080 $options = array();
3081 foreach ($adminoptions as $name => $available) {
3082 $options[] = array(
3083 'name' => $name,
3084 'available' => $available,
3088 $courseoptions[] = array(
3089 'id' => $course->id,
3090 'options' => $options
3095 $result = array(
3096 'courses' => $courseoptions,
3097 'warnings' => $warnings
3099 return $result;
3103 * Returns description of method result value
3105 * @return external_description
3106 * @since Moodle 3.2
3108 public static function get_user_administration_options_returns() {
3109 return self::get_user_navigation_options_returns();
3113 * Returns description of method parameters
3115 * @return external_function_parameters
3116 * @since Moodle 3.2
3118 public static function get_courses_by_field_parameters() {
3119 return new external_function_parameters(
3120 array(
3121 'field' => new external_value(PARAM_ALPHA, 'The field to search can be left empty for all courses or:
3122 id: course id
3123 ids: comma separated course ids
3124 shortname: course short name
3125 idnumber: course id number
3126 category: category id the course belongs to
3127 ', VALUE_DEFAULT, ''),
3128 'value' => new external_value(PARAM_RAW, 'The value to match', VALUE_DEFAULT, '')
3135 * Get courses matching a specific field (id/s, shortname, idnumber, category)
3137 * @param string $field field name to search, or empty for all courses
3138 * @param string $value value to search
3139 * @return array list of courses and warnings
3140 * @throws invalid_parameter_exception
3141 * @since Moodle 3.2
3143 public static function get_courses_by_field($field = '', $value = '') {
3144 global $DB, $CFG;
3145 require_once($CFG->dirroot . '/course/lib.php');
3146 require_once($CFG->libdir . '/filterlib.php');
3148 $params = self::validate_parameters(self::get_courses_by_field_parameters(),
3149 array(
3150 'field' => $field,
3151 'value' => $value,
3154 $warnings = array();
3156 if (empty($params['field'])) {
3157 $courses = $DB->get_records('course', null, 'id ASC');
3158 } else {
3159 switch ($params['field']) {
3160 case 'id':
3161 case 'category':
3162 $value = clean_param($params['value'], PARAM_INT);
3163 break;
3164 case 'ids':
3165 $value = clean_param($params['value'], PARAM_SEQUENCE);
3166 break;
3167 case 'shortname':
3168 $value = clean_param($params['value'], PARAM_TEXT);
3169 break;
3170 case 'idnumber':
3171 $value = clean_param($params['value'], PARAM_RAW);
3172 break;
3173 default:
3174 throw new invalid_parameter_exception('Invalid field name');
3177 if ($params['field'] === 'ids') {
3178 // Preload categories to avoid loading one at a time.
3179 $courseids = explode(',', $value);
3180 list ($listsql, $listparams) = $DB->get_in_or_equal($courseids);
3181 $categoryids = $DB->get_fieldset_sql("
3182 SELECT DISTINCT cc.id
3183 FROM {course} c
3184 JOIN {course_categories} cc ON cc.id = c.category
3185 WHERE c.id $listsql", $listparams);
3186 core_course_category::get_many($categoryids);
3188 // Load and validate all courses. This is called because it loads the courses
3189 // more efficiently.
3190 list ($courses, $warnings) = external_util::validate_courses($courseids, [],
3191 false, true);
3192 } else {
3193 $courses = $DB->get_records('course', array($params['field'] => $value), 'id ASC');
3197 $coursesdata = array();
3198 foreach ($courses as $course) {
3199 $context = context_course::instance($course->id);
3200 $canupdatecourse = has_capability('moodle/course:update', $context);
3201 $canviewhiddencourses = has_capability('moodle/course:viewhiddencourses', $context);
3203 // Check if the course is visible in the site for the user.
3204 if (!$course->visible and !$canviewhiddencourses and !$canupdatecourse) {
3205 continue;
3207 // Get the public course information, even if we are not enrolled.
3208 $courseinlist = new core_course_list_element($course);
3210 // Now, check if we have access to the course, unless it was already checked.
3211 try {
3212 if (empty($course->contextvalidated)) {
3213 self::validate_context($context);
3215 } catch (Exception $e) {
3216 // User can not access the course, check if they can see the public information about the course and return it.
3217 if (core_course_category::can_view_course_info($course)) {
3218 $coursesdata[$course->id] = self::get_course_public_information($courseinlist, $context);
3220 continue;
3222 $coursesdata[$course->id] = self::get_course_public_information($courseinlist, $context);
3223 // Return information for any user that can access the course.
3224 $coursefields = array('format', 'showgrades', 'newsitems', 'startdate', 'enddate', 'maxbytes', 'showreports', 'visible',
3225 'groupmode', 'groupmodeforce', 'defaultgroupingid', 'enablecompletion', 'completionnotify', 'lang', 'theme',
3226 'marker');
3228 // Course filters.
3229 $coursesdata[$course->id]['filters'] = filter_get_available_in_context($context);
3231 // Information for managers only.
3232 if ($canupdatecourse) {
3233 $managerfields = array('idnumber', 'legacyfiles', 'calendartype', 'timecreated', 'timemodified', 'requested',
3234 'cacherev');
3235 $coursefields = array_merge($coursefields, $managerfields);
3238 // Populate fields.
3239 foreach ($coursefields as $field) {
3240 $coursesdata[$course->id][$field] = $course->{$field};
3243 // Clean lang and auth fields for external functions (it may content uninstalled themes or language packs).
3244 if (isset($coursesdata[$course->id]['theme'])) {
3245 $coursesdata[$course->id]['theme'] = clean_param($coursesdata[$course->id]['theme'], PARAM_THEME);
3247 if (isset($coursesdata[$course->id]['lang'])) {
3248 $coursesdata[$course->id]['lang'] = clean_param($coursesdata[$course->id]['lang'], PARAM_LANG);
3251 $courseformatoptions = course_get_format($course)->get_config_for_external();
3252 foreach ($courseformatoptions as $key => $value) {
3253 $coursesdata[$course->id]['courseformatoptions'][] = array(
3254 'name' => $key,
3255 'value' => $value
3260 return array(
3261 'courses' => $coursesdata,
3262 'warnings' => $warnings
3267 * Returns description of method result value
3269 * @return external_description
3270 * @since Moodle 3.2
3272 public static function get_courses_by_field_returns() {
3273 // Course structure, including not only public viewable fields.
3274 return new external_single_structure(
3275 array(
3276 'courses' => new external_multiple_structure(self::get_course_structure(false), 'Course'),
3277 'warnings' => new external_warnings()
3283 * Returns description of method parameters
3285 * @return external_function_parameters
3286 * @since Moodle 3.2
3288 public static function check_updates_parameters() {
3289 return new external_function_parameters(
3290 array(
3291 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3292 'tocheck' => new external_multiple_structure(
3293 new external_single_structure(
3294 array(
3295 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level for the file location.
3296 Only module supported right now.'),
3297 'id' => new external_value(PARAM_INT, 'Context instance id'),
3298 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3301 'Instances to check'
3303 'filter' => new external_multiple_structure(
3304 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3305 gradeitems, outcomes'),
3306 'Check only for updates in these areas', VALUE_DEFAULT, array()
3313 * Check if there is updates affecting the user for the given course and contexts.
3314 * Right now only modules are supported.
3315 * This WS calls mod_check_updates_since for each module to check if there is any update the user should we aware of.
3317 * @param int $courseid the list of modules to check
3318 * @param array $tocheck the list of modules to check
3319 * @param array $filter check only for updates in these areas
3320 * @return array list of updates and warnings
3321 * @throws moodle_exception
3322 * @since Moodle 3.2
3324 public static function check_updates($courseid, $tocheck, $filter = array()) {
3325 global $CFG, $DB;
3326 require_once($CFG->dirroot . "/course/lib.php");
3328 $params = self::validate_parameters(
3329 self::check_updates_parameters(),
3330 array(
3331 'courseid' => $courseid,
3332 'tocheck' => $tocheck,
3333 'filter' => $filter,
3337 $course = get_course($params['courseid']);
3338 $context = context_course::instance($course->id);
3339 self::validate_context($context);
3341 list($instances, $warnings) = course_check_updates($course, $params['tocheck'], $filter);
3343 $instancesformatted = array();
3344 foreach ($instances as $instance) {
3345 $updates = array();
3346 foreach ($instance['updates'] as $name => $data) {
3347 if (empty($data->updated)) {
3348 continue;
3350 $updatedata = array(
3351 'name' => $name,
3353 if (!empty($data->timeupdated)) {
3354 $updatedata['timeupdated'] = $data->timeupdated;
3356 if (!empty($data->itemids)) {
3357 $updatedata['itemids'] = $data->itemids;
3359 $updates[] = $updatedata;
3361 if (!empty($updates)) {
3362 $instancesformatted[] = array(
3363 'contextlevel' => $instance['contextlevel'],
3364 'id' => $instance['id'],
3365 'updates' => $updates
3370 return array(
3371 'instances' => $instancesformatted,
3372 'warnings' => $warnings
3377 * Returns description of method result value
3379 * @return external_description
3380 * @since Moodle 3.2
3382 public static function check_updates_returns() {
3383 return new external_single_structure(
3384 array(
3385 'instances' => new external_multiple_structure(
3386 new external_single_structure(
3387 array(
3388 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level'),
3389 'id' => new external_value(PARAM_INT, 'Instance id'),
3390 'updates' => new external_multiple_structure(
3391 new external_single_structure(
3392 array(
3393 'name' => new external_value(PARAM_ALPHANUMEXT, 'Name of the area updated.'),
3394 'timeupdated' => new external_value(PARAM_INT, 'Last time was updated', VALUE_OPTIONAL),
3395 'itemids' => new external_multiple_structure(
3396 new external_value(PARAM_INT, 'Instance id'),
3397 'The ids of the items updated',
3398 VALUE_OPTIONAL
3406 'warnings' => new external_warnings()
3412 * Returns description of method parameters
3414 * @return external_function_parameters
3415 * @since Moodle 3.3
3417 public static function get_updates_since_parameters() {
3418 return new external_function_parameters(
3419 array(
3420 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3421 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3422 'filter' => new external_multiple_structure(
3423 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3424 gradeitems, outcomes'),
3425 'Check only for updates in these areas', VALUE_DEFAULT, array()
3432 * Check if there are updates affecting the user for the given course since the given time stamp.
3434 * This function is a wrapper of self::check_updates for retrieving all the updates since a given time for all the activities.
3436 * @param int $courseid the list of modules to check
3437 * @param int $since check updates since this time stamp
3438 * @param array $filter check only for updates in these areas
3439 * @return array list of updates and warnings
3440 * @throws moodle_exception
3441 * @since Moodle 3.3
3443 public static function get_updates_since($courseid, $since, $filter = array()) {
3444 global $CFG, $DB;
3446 $params = self::validate_parameters(
3447 self::get_updates_since_parameters(),
3448 array(
3449 'courseid' => $courseid,
3450 'since' => $since,
3451 'filter' => $filter,
3455 $course = get_course($params['courseid']);
3456 $modinfo = get_fast_modinfo($course);
3457 $tocheck = array();
3459 // Retrieve all the visible course modules for the current user.
3460 $cms = $modinfo->get_cms();
3461 foreach ($cms as $cm) {
3462 if (!$cm->uservisible) {
3463 continue;
3465 $tocheck[] = array(
3466 'id' => $cm->id,
3467 'contextlevel' => 'module',
3468 'since' => $params['since'],
3472 return self::check_updates($course->id, $tocheck, $params['filter']);
3476 * Returns description of method result value
3478 * @return external_description
3479 * @since Moodle 3.3
3481 public static function get_updates_since_returns() {
3482 return self::check_updates_returns();
3486 * Parameters for function edit_module()
3488 * @since Moodle 3.3
3489 * @return external_function_parameters
3491 public static function edit_module_parameters() {
3492 return new external_function_parameters(
3493 array(
3494 'action' => new external_value(PARAM_ALPHA,
3495 'action: hide, show, stealth, duplicate, delete, moveleft, moveright, group...', VALUE_REQUIRED),
3496 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3497 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3502 * Performs one of the edit module actions and return new html for AJAX
3504 * Returns html to replace the current module html with, for example:
3505 * - empty string for "delete" action,
3506 * - two modules html for "duplicate" action
3507 * - updated module html for everything else
3509 * Throws exception if operation is not permitted/possible
3511 * @since Moodle 3.3
3512 * @param string $action
3513 * @param int $id
3514 * @param null|int $sectionreturn
3515 * @return string
3517 public static function edit_module($action, $id, $sectionreturn = null) {
3518 global $PAGE, $DB;
3519 // Validate and normalize parameters.
3520 $params = self::validate_parameters(self::edit_module_parameters(),
3521 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3522 $action = $params['action'];
3523 $id = $params['id'];
3524 $sectionreturn = $params['sectionreturn'];
3526 // Set of permissions an editing user may have.
3527 $contextarray = [
3528 'moodle/course:update',
3529 'moodle/course:manageactivities',
3530 'moodle/course:activityvisibility',
3531 'moodle/course:sectionvisibility',
3532 'moodle/course:movesections',
3533 'moodle/course:setcurrentsection',
3535 $PAGE->set_other_editing_capability($contextarray);
3537 list($course, $cm) = get_course_and_cm_from_cmid($id);
3538 $modcontext = context_module::instance($cm->id);
3539 $coursecontext = context_course::instance($course->id);
3540 self::validate_context($modcontext);
3541 $format = course_get_format($course);
3542 if ($sectionreturn) {
3543 $format->set_section_number($sectionreturn);
3545 $renderer = $format->get_renderer($PAGE);
3547 switch($action) {
3548 case 'hide':
3549 case 'show':
3550 case 'stealth':
3551 require_capability('moodle/course:activityvisibility', $modcontext);
3552 $visible = ($action === 'hide') ? 0 : 1;
3553 $visibleoncoursepage = ($action === 'stealth') ? 0 : 1;
3554 set_coursemodule_visible($id, $visible, $visibleoncoursepage);
3555 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3556 break;
3557 case 'duplicate':
3558 require_capability('moodle/course:manageactivities', $coursecontext);
3559 require_capability('moodle/backup:backuptargetimport', $coursecontext);
3560 require_capability('moodle/restore:restoretargetimport', $coursecontext);
3561 if (!course_allowed_module($course, $cm->modname)) {
3562 throw new moodle_exception('No permission to create that activity');
3564 if ($newcm = duplicate_module($course, $cm)) {
3566 $modinfo = $format->get_modinfo();
3567 $section = $modinfo->get_section_info($newcm->sectionnum);
3568 $cm = $modinfo->get_cm($id);
3570 // Get both original and new element html.
3571 $result = $renderer->course_section_updated_cm_item($format, $section, $cm);
3572 $result .= $renderer->course_section_updated_cm_item($format, $section, $newcm);
3573 return $result;
3575 break;
3576 case 'groupsseparate':
3577 case 'groupsvisible':
3578 case 'groupsnone':
3579 require_capability('moodle/course:manageactivities', $modcontext);
3580 if ($action === 'groupsseparate') {
3581 $newgroupmode = SEPARATEGROUPS;
3582 } else if ($action === 'groupsvisible') {
3583 $newgroupmode = VISIBLEGROUPS;
3584 } else {
3585 $newgroupmode = NOGROUPS;
3587 if (set_coursemodule_groupmode($cm->id, $newgroupmode)) {
3588 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3590 break;
3591 case 'moveleft':
3592 case 'moveright':
3593 require_capability('moodle/course:manageactivities', $modcontext);
3594 $indent = $cm->indent + (($action === 'moveright') ? 1 : -1);
3595 if ($cm->indent >= 0) {
3596 $DB->update_record('course_modules', array('id' => $cm->id, 'indent' => $indent));
3597 rebuild_course_cache($cm->course);
3599 break;
3600 case 'delete':
3601 require_capability('moodle/course:manageactivities', $modcontext);
3602 course_delete_module($cm->id, true);
3603 return '';
3604 default:
3605 throw new coding_exception('Unrecognised action');
3608 $modinfo = $format->get_modinfo();
3609 $section = $modinfo->get_section_info($cm->sectionnum);
3610 $cm = $modinfo->get_cm($id);
3611 return $renderer->course_section_updated_cm_item($format, $section, $cm);
3615 * Return structure for edit_module()
3617 * @since Moodle 3.3
3618 * @return external_description
3620 public static function edit_module_returns() {
3621 return new external_value(PARAM_RAW, 'html to replace the current module with');
3625 * Parameters for function get_module()
3627 * @since Moodle 3.3
3628 * @return external_function_parameters
3630 public static function get_module_parameters() {
3631 return new external_function_parameters(
3632 array(
3633 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3634 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3639 * Returns html for displaying one activity module on course page
3641 * @since Moodle 3.3
3642 * @param int $id
3643 * @param null|int $sectionreturn
3644 * @return string
3646 public static function get_module($id, $sectionreturn = null) {
3647 global $PAGE;
3648 // Validate and normalize parameters.
3649 $params = self::validate_parameters(self::get_module_parameters(),
3650 array('id' => $id, 'sectionreturn' => $sectionreturn));
3651 $id = $params['id'];
3652 $sectionreturn = $params['sectionreturn'];
3654 // Set of permissions an editing user may have.
3655 $contextarray = [
3656 'moodle/course:update',
3657 'moodle/course:manageactivities',
3658 'moodle/course:activityvisibility',
3659 'moodle/course:sectionvisibility',
3660 'moodle/course:movesections',
3661 'moodle/course:setcurrentsection',
3663 $PAGE->set_other_editing_capability($contextarray);
3665 // Validate access to the course (note, this is html for the course view page, we don't validate access to the module).
3666 list($course, $cm) = get_course_and_cm_from_cmid($id);
3667 self::validate_context(context_course::instance($course->id));
3669 $format = course_get_format($course);
3670 if ($sectionreturn) {
3671 $format->set_section_number($sectionreturn);
3673 $renderer = $format->get_renderer($PAGE);
3675 $modinfo = $format->get_modinfo();
3676 $section = $modinfo->get_section_info($cm->sectionnum);
3677 return $renderer->course_section_updated_cm_item($format, $section, $cm);
3681 * Return structure for get_module()
3683 * @since Moodle 3.3
3684 * @return external_description
3686 public static function get_module_returns() {
3687 return new external_value(PARAM_RAW, 'html to replace the current module with');
3691 * Parameters for function edit_section()
3693 * @since Moodle 3.3
3694 * @return external_function_parameters
3696 public static function edit_section_parameters() {
3697 return new external_function_parameters(
3698 array(
3699 'action' => new external_value(PARAM_ALPHA, 'action: hide, show, stealth, setmarker, removemarker', VALUE_REQUIRED),
3700 'id' => new external_value(PARAM_INT, 'course section id', VALUE_REQUIRED),
3701 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3706 * Performs one of the edit section actions
3708 * @since Moodle 3.3
3709 * @param string $action
3710 * @param int $id section id
3711 * @param int $sectionreturn section to return to
3712 * @return string
3714 public static function edit_section($action, $id, $sectionreturn) {
3715 global $DB;
3716 // Validate and normalize parameters.
3717 $params = self::validate_parameters(self::edit_section_parameters(),
3718 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3719 $action = $params['action'];
3720 $id = $params['id'];
3721 $sr = $params['sectionreturn'];
3723 $section = $DB->get_record('course_sections', array('id' => $id), '*', MUST_EXIST);
3724 $coursecontext = context_course::instance($section->course);
3725 self::validate_context($coursecontext);
3727 $rv = course_get_format($section->course)->section_action($section, $action, $sectionreturn);
3728 if ($rv) {
3729 return json_encode($rv);
3730 } else {
3731 return null;
3736 * Return structure for edit_section()
3738 * @since Moodle 3.3
3739 * @return external_description
3741 public static function edit_section_returns() {
3742 return new external_value(PARAM_RAW, 'Additional data for javascript (JSON-encoded string)');
3746 * Returns description of method parameters
3748 * @return external_function_parameters
3750 public static function get_enrolled_courses_by_timeline_classification_parameters() {
3751 return new external_function_parameters(
3752 array(
3753 'classification' => new external_value(PARAM_ALPHA, 'future, inprogress, or past'),
3754 'limit' => new external_value(PARAM_INT, 'Result set limit', VALUE_DEFAULT, 0),
3755 'offset' => new external_value(PARAM_INT, 'Result set offset', VALUE_DEFAULT, 0),
3756 'sort' => new external_value(PARAM_TEXT, 'Sort string', VALUE_DEFAULT, null),
3757 'customfieldname' => new external_value(PARAM_ALPHANUMEXT, 'Used when classification = customfield',
3758 VALUE_DEFAULT, null),
3759 'customfieldvalue' => new external_value(PARAM_RAW, 'Used when classification = customfield',
3760 VALUE_DEFAULT, null),
3761 'searchvalue' => new external_value(PARAM_RAW, 'The value a user wishes to search against',
3762 VALUE_DEFAULT, null),
3768 * Get courses matching the given timeline classification.
3770 * NOTE: The offset applies to the unfiltered full set of courses before the classification
3771 * filtering is done.
3772 * E.g.
3773 * If the user is enrolled in 5 courses:
3774 * c1, c2, c3, c4, and c5
3775 * And c4 and c5 are 'future' courses
3777 * If a request comes in for future courses with an offset of 1 it will mean that
3778 * c1 is skipped (because the offset applies *before* the classification filtering)
3779 * and c4 and c5 will be return.
3781 * @param string $classification past, inprogress, or future
3782 * @param int $limit Result set limit
3783 * @param int $offset Offset the full course set before timeline classification is applied
3784 * @param string $sort SQL sort string for results
3785 * @param string $customfieldname
3786 * @param string $customfieldvalue
3787 * @param string $searchvalue
3788 * @return array list of courses and warnings
3789 * @throws invalid_parameter_exception
3791 public static function get_enrolled_courses_by_timeline_classification(
3792 string $classification,
3793 int $limit = 0,
3794 int $offset = 0,
3795 string $sort = null,
3796 string $customfieldname = null,
3797 string $customfieldvalue = null,
3798 string $searchvalue = null
3800 global $CFG, $PAGE, $USER;
3801 require_once($CFG->dirroot . '/course/lib.php');
3803 $params = self::validate_parameters(self::get_enrolled_courses_by_timeline_classification_parameters(),
3804 array(
3805 'classification' => $classification,
3806 'limit' => $limit,
3807 'offset' => $offset,
3808 'sort' => $sort,
3809 'customfieldvalue' => $customfieldvalue,
3810 'searchvalue' => $searchvalue,
3814 $classification = $params['classification'];
3815 $limit = $params['limit'];
3816 $offset = $params['offset'];
3817 $sort = $params['sort'];
3818 $customfieldvalue = $params['customfieldvalue'];
3819 $searchvalue = clean_param($params['searchvalue'], PARAM_TEXT);
3821 switch($classification) {
3822 case COURSE_TIMELINE_ALLINCLUDINGHIDDEN:
3823 break;
3824 case COURSE_TIMELINE_ALL:
3825 break;
3826 case COURSE_TIMELINE_PAST:
3827 break;
3828 case COURSE_TIMELINE_INPROGRESS:
3829 break;
3830 case COURSE_TIMELINE_FUTURE:
3831 break;
3832 case COURSE_FAVOURITES:
3833 break;
3834 case COURSE_TIMELINE_HIDDEN:
3835 break;
3836 case COURSE_TIMELINE_SEARCH:
3837 break;
3838 case COURSE_CUSTOMFIELD:
3839 break;
3840 default:
3841 throw new invalid_parameter_exception('Invalid classification');
3844 self::validate_context(context_user::instance($USER->id));
3846 $requiredproperties = course_summary_exporter::define_properties();
3847 $fields = join(',', array_keys($requiredproperties));
3848 $hiddencourses = get_hidden_courses_on_timeline();
3849 $courses = [];
3851 // If the timeline requires really all courses, get really all courses.
3852 if ($classification == COURSE_TIMELINE_ALLINCLUDINGHIDDEN) {
3853 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields, COURSE_DB_QUERY_LIMIT);
3855 // Otherwise if the timeline requires the hidden courses then restrict the result to only $hiddencourses.
3856 } else if ($classification == COURSE_TIMELINE_HIDDEN) {
3857 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields,
3858 COURSE_DB_QUERY_LIMIT, $hiddencourses);
3860 // Otherwise get the requested courses and exclude the hidden courses.
3861 } else if ($classification == COURSE_TIMELINE_SEARCH) {
3862 // Prepare the search API options.
3863 $searchcriteria['search'] = $searchvalue;
3864 $options = ['idonly' => true];
3865 $courses = course_get_enrolled_courses_for_logged_in_user_from_search(
3867 $offset,
3868 $sort,
3869 $fields,
3870 COURSE_DB_QUERY_LIMIT,
3871 $searchcriteria,
3872 $options
3874 } else {
3875 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields,
3876 COURSE_DB_QUERY_LIMIT, [], $hiddencourses);
3879 $favouritecourseids = [];
3880 $ufservice = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($USER->id));
3881 $favourites = $ufservice->find_favourites_by_type('core_course', 'courses');
3883 if ($favourites) {
3884 $favouritecourseids = array_map(
3885 function($favourite) {
3886 return $favourite->itemid;
3887 }, $favourites);
3890 if ($classification == COURSE_FAVOURITES) {
3891 list($filteredcourses, $processedcount) = course_filter_courses_by_favourites(
3892 $courses,
3893 $favouritecourseids,
3894 $limit
3896 } else if ($classification == COURSE_CUSTOMFIELD) {
3897 list($filteredcourses, $processedcount) = course_filter_courses_by_customfield(
3898 $courses,
3899 $customfieldname,
3900 $customfieldvalue,
3901 $limit
3903 } else {
3904 list($filteredcourses, $processedcount) = course_filter_courses_by_timeline_classification(
3905 $courses,
3906 $classification,
3907 $limit
3911 $renderer = $PAGE->get_renderer('core');
3912 $formattedcourses = array_map(function($course) use ($renderer, $favouritecourseids) {
3913 if ($course == null) {
3914 return;
3916 context_helper::preload_from_record($course);
3917 $context = context_course::instance($course->id);
3918 $isfavourite = false;
3919 if (in_array($course->id, $favouritecourseids)) {
3920 $isfavourite = true;
3922 $exporter = new course_summary_exporter($course, ['context' => $context, 'isfavourite' => $isfavourite]);
3923 return $exporter->export($renderer);
3924 }, $filteredcourses);
3926 $formattedcourses = array_filter($formattedcourses, function($course) {
3927 if ($course != null) {
3928 return $course;
3932 return [
3933 'courses' => $formattedcourses,
3934 'nextoffset' => $offset + $processedcount
3939 * Returns description of method result value
3941 * @return external_description
3943 public static function get_enrolled_courses_by_timeline_classification_returns() {
3944 return new external_single_structure(
3945 array(
3946 'courses' => new external_multiple_structure(course_summary_exporter::get_read_structure(), 'Course'),
3947 'nextoffset' => new external_value(PARAM_INT, 'Offset for the next request')
3953 * Returns description of method parameters
3955 * @return external_function_parameters
3957 public static function set_favourite_courses_parameters() {
3958 return new external_function_parameters(
3959 array(
3960 'courses' => new external_multiple_structure(
3961 new external_single_structure(
3962 array(
3963 'id' => new external_value(PARAM_INT, 'course ID'),
3964 'favourite' => new external_value(PARAM_BOOL, 'favourite status')
3973 * Set the course favourite status for an array of courses.
3975 * @param array $courses List with course id's and favourite status.
3976 * @return array Array with an array of favourite courses.
3978 public static function set_favourite_courses(
3979 array $courses
3981 global $USER;
3983 $params = self::validate_parameters(self::set_favourite_courses_parameters(),
3984 array(
3985 'courses' => $courses
3989 $warnings = [];
3991 $ufservice = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($USER->id));
3993 foreach ($params['courses'] as $course) {
3995 $warning = [];
3997 $favouriteexists = $ufservice->favourite_exists('core_course', 'courses', $course['id'],
3998 \context_course::instance($course['id']));
4000 if ($course['favourite']) {
4001 if (!$favouriteexists) {
4002 try {
4003 $ufservice->create_favourite('core_course', 'courses', $course['id'],
4004 \context_course::instance($course['id']));
4005 } catch (Exception $e) {
4006 $warning['courseid'] = $course['id'];
4007 if ($e instanceof moodle_exception) {
4008 $warning['warningcode'] = $e->errorcode;
4009 } else {
4010 $warning['warningcode'] = $e->getCode();
4012 $warning['message'] = $e->getMessage();
4013 $warnings[] = $warning;
4014 $warnings[] = $warning;
4016 } else {
4017 $warning['courseid'] = $course['id'];
4018 $warning['warningcode'] = 'coursealreadyfavourited';
4019 $warning['message'] = 'Course already favourited';
4020 $warnings[] = $warning;
4022 } else {
4023 if ($favouriteexists) {
4024 try {
4025 $ufservice->delete_favourite('core_course', 'courses', $course['id'],
4026 \context_course::instance($course['id']));
4027 } catch (Exception $e) {
4028 $warning['courseid'] = $course['id'];
4029 if ($e instanceof moodle_exception) {
4030 $warning['warningcode'] = $e->errorcode;
4031 } else {
4032 $warning['warningcode'] = $e->getCode();
4034 $warning['message'] = $e->getMessage();
4035 $warnings[] = $warning;
4036 $warnings[] = $warning;
4038 } else {
4039 $warning['courseid'] = $course['id'];
4040 $warning['warningcode'] = 'cannotdeletefavourite';
4041 $warning['message'] = 'Could not delete favourite status for course';
4042 $warnings[] = $warning;
4047 return [
4048 'warnings' => $warnings
4053 * Returns description of method result value
4055 * @return external_description
4057 public static function set_favourite_courses_returns() {
4058 return new external_single_structure(
4059 array(
4060 'warnings' => new external_warnings()
4066 * Returns description of method parameters
4068 * @return external_function_parameters
4069 * @since Moodle 3.6
4071 public static function get_recent_courses_parameters() {
4072 return new external_function_parameters(
4073 array(
4074 'userid' => new external_value(PARAM_INT, 'id of the user, default to current user', VALUE_DEFAULT, 0),
4075 'limit' => new external_value(PARAM_INT, 'result set limit', VALUE_DEFAULT, 0),
4076 'offset' => new external_value(PARAM_INT, 'Result set offset', VALUE_DEFAULT, 0),
4077 'sort' => new external_value(PARAM_TEXT, 'Sort string', VALUE_DEFAULT, null)
4083 * Get last accessed courses adding additional course information like images.
4085 * @param int $userid User id from which the courses will be obtained
4086 * @param int $limit Restrict result set to this amount
4087 * @param int $offset Skip this number of records from the start of the result set
4088 * @param string|null $sort SQL string for sorting
4089 * @return array List of courses
4090 * @throws invalid_parameter_exception
4092 public static function get_recent_courses(int $userid = 0, int $limit = 0, int $offset = 0, string $sort = null) {
4093 global $USER, $PAGE;
4095 if (empty($userid)) {
4096 $userid = $USER->id;
4099 $params = self::validate_parameters(self::get_recent_courses_parameters(),
4100 array(
4101 'userid' => $userid,
4102 'limit' => $limit,
4103 'offset' => $offset,
4104 'sort' => $sort
4108 $userid = $params['userid'];
4109 $limit = $params['limit'];
4110 $offset = $params['offset'];
4111 $sort = $params['sort'];
4113 $usercontext = context_user::instance($userid);
4115 self::validate_context($usercontext);
4117 if ($userid != $USER->id and !has_capability('moodle/user:viewdetails', $usercontext)) {
4118 return array();
4121 $courses = course_get_recent_courses($userid, $limit, $offset, $sort);
4123 $renderer = $PAGE->get_renderer('core');
4125 $recentcourses = array_map(function($course) use ($renderer) {
4126 context_helper::preload_from_record($course);
4127 $context = context_course::instance($course->id);
4128 $isfavourite = !empty($course->component);
4129 $exporter = new course_summary_exporter($course, ['context' => $context, 'isfavourite' => $isfavourite]);
4130 return $exporter->export($renderer);
4131 }, $courses);
4133 return $recentcourses;
4137 * Returns description of method result value
4139 * @return external_description
4140 * @since Moodle 3.6
4142 public static function get_recent_courses_returns() {
4143 return new external_multiple_structure(course_summary_exporter::get_read_structure(), 'Courses');
4147 * Returns description of method parameters
4149 * @return external_function_parameters
4151 public static function get_enrolled_users_by_cmid_parameters() {
4152 return new external_function_parameters([
4153 'cmid' => new external_value(PARAM_INT, 'id of the course module', VALUE_REQUIRED),
4154 'groupid' => new external_value(PARAM_INT, 'id of the group', VALUE_DEFAULT, 0),
4155 'onlyactive' => new external_value(PARAM_BOOL, 'whether to return only active users or all.',
4156 VALUE_DEFAULT, false),
4161 * Get all users in a course for a given cmid.
4163 * @param int $cmid Course Module id from which the users will be obtained
4164 * @param int $groupid Group id from which the users will be obtained
4165 * @param bool $onlyactive Whether to return only the active enrolled users or all enrolled users in the course.
4166 * @return array List of users
4167 * @throws invalid_parameter_exception
4169 public static function get_enrolled_users_by_cmid(int $cmid, int $groupid = 0, bool $onlyactive = false) {
4170 global $PAGE;
4171 $warnings = [];
4173 self::validate_parameters(self::get_enrolled_users_by_cmid_parameters(), [
4174 'cmid' => $cmid,
4175 'groupid' => $groupid,
4176 'onlyactive' => $onlyactive,
4179 list($course, $cm) = get_course_and_cm_from_cmid($cmid);
4180 $coursecontext = context_course::instance($course->id);
4181 self::validate_context($coursecontext);
4183 $enrolledusers = get_enrolled_users($coursecontext, '', $groupid, 'u.*', null, 0, 0, $onlyactive);
4185 $users = array_map(function ($user) use ($PAGE) {
4186 $user->fullname = fullname($user);
4187 $userpicture = new user_picture($user);
4188 $userpicture->size = 1;
4189 $user->profileimage = $userpicture->get_url($PAGE)->out(false);
4190 return $user;
4191 }, $enrolledusers);
4192 sort($users);
4194 return [
4195 'users' => $users,
4196 'warnings' => $warnings,
4201 * Returns description of method result value
4203 * @return external_description
4205 public static function get_enrolled_users_by_cmid_returns() {
4206 return new external_single_structure([
4207 'users' => new external_multiple_structure(self::user_description()),
4208 'warnings' => new external_warnings(),
4213 * Create user return value description.
4215 * @return external_description
4217 public static function user_description() {
4218 $userfields = array(
4219 'id' => new external_value(core_user::get_property_type('id'), 'ID of the user'),
4220 'profileimage' => new external_value(PARAM_URL, 'The location of the users larger image', VALUE_OPTIONAL),
4221 'fullname' => new external_value(PARAM_TEXT, 'The full name of the user', VALUE_OPTIONAL),
4222 'firstname' => new external_value(
4223 core_user::get_property_type('firstname'),
4224 'The first name(s) of the user',
4225 VALUE_OPTIONAL),
4226 'lastname' => new external_value(
4227 core_user::get_property_type('lastname'),
4228 'The family name of the user',
4229 VALUE_OPTIONAL),
4231 return new external_single_structure($userfields);
4235 * Returns description of method parameters.
4237 * @return external_function_parameters
4239 public static function add_content_item_to_user_favourites_parameters() {
4240 return new external_function_parameters([
4241 'componentname' => new external_value(PARAM_TEXT,
4242 'frankenstyle name of the component to which the content item belongs', VALUE_REQUIRED),
4243 'contentitemid' => new external_value(PARAM_INT, 'id of the content item', VALUE_REQUIRED, '', NULL_NOT_ALLOWED)
4248 * Add a content item to a user's favourites.
4250 * @param string $componentname the name of the component from which this content item originates.
4251 * @param int $contentitemid the id of the content item.
4252 * @return stdClass the exporter content item.
4254 public static function add_content_item_to_user_favourites(string $componentname, int $contentitemid) {
4255 global $USER;
4258 'componentname' => $componentname,
4259 'contentitemid' => $contentitemid,
4260 ] = self::validate_parameters(self::add_content_item_to_user_favourites_parameters(),
4262 'componentname' => $componentname,
4263 'contentitemid' => $contentitemid,
4267 self::validate_context(context_user::instance($USER->id));
4269 $contentitemservice = \core_course\local\factory\content_item_service_factory::get_content_item_service();
4271 return $contentitemservice->add_to_user_favourites($USER, $componentname, $contentitemid);
4275 * Returns description of method result value.
4277 * @return external_description
4279 public static function add_content_item_to_user_favourites_returns() {
4280 return \core_course\local\exporters\course_content_item_exporter::get_read_structure();
4284 * Returns description of method parameters.
4286 * @return external_function_parameters
4288 public static function remove_content_item_from_user_favourites_parameters() {
4289 return new external_function_parameters([
4290 'componentname' => new external_value(PARAM_TEXT,
4291 'frankenstyle name of the component to which the content item belongs', VALUE_REQUIRED),
4292 'contentitemid' => new external_value(PARAM_INT, 'id of the content item', VALUE_REQUIRED, '', NULL_NOT_ALLOWED),
4297 * Remove a content item from a user's favourites.
4299 * @param string $componentname the name of the component from which this content item originates.
4300 * @param int $contentitemid the id of the content item.
4301 * @return stdClass the exported content item.
4303 public static function remove_content_item_from_user_favourites(string $componentname, int $contentitemid) {
4304 global $USER;
4307 'componentname' => $componentname,
4308 'contentitemid' => $contentitemid,
4309 ] = self::validate_parameters(self::remove_content_item_from_user_favourites_parameters(),
4311 'componentname' => $componentname,
4312 'contentitemid' => $contentitemid,
4316 self::validate_context(context_user::instance($USER->id));
4318 $contentitemservice = \core_course\local\factory\content_item_service_factory::get_content_item_service();
4320 return $contentitemservice->remove_from_user_favourites($USER, $componentname, $contentitemid);
4324 * Returns description of method result value.
4326 * @return external_description
4328 public static function remove_content_item_from_user_favourites_returns() {
4329 return \core_course\local\exporters\course_content_item_exporter::get_read_structure();
4333 * Returns description of method result value
4335 * @return external_description
4337 public static function get_course_content_items_returns() {
4338 return new external_single_structure([
4339 'content_items' => new external_multiple_structure(
4340 \core_course\local\exporters\course_content_item_exporter::get_read_structure()
4346 * Returns description of method parameters
4348 * @return external_function_parameters
4350 public static function get_course_content_items_parameters() {
4351 return new external_function_parameters([
4352 'courseid' => new external_value(PARAM_INT, 'ID of the course', VALUE_REQUIRED),
4357 * Given a course ID fetch all accessible modules for that course
4359 * @param int $courseid The course we want to fetch the modules for
4360 * @return array Contains array of modules and their metadata
4362 public static function get_course_content_items(int $courseid) {
4363 global $USER;
4366 'courseid' => $courseid,
4367 ] = self::validate_parameters(self::get_course_content_items_parameters(), [
4368 'courseid' => $courseid,
4371 $coursecontext = context_course::instance($courseid);
4372 self::validate_context($coursecontext);
4373 $course = get_course($courseid);
4375 $contentitemservice = \core_course\local\factory\content_item_service_factory::get_content_item_service();
4377 $contentitems = $contentitemservice->get_content_items_for_user_in_course($USER, $course);
4378 return ['content_items' => $contentitems];
4382 * Returns description of method parameters.
4384 * @return external_function_parameters
4386 public static function toggle_activity_recommendation_parameters() {
4387 return new external_function_parameters([
4388 'area' => new external_value(PARAM_TEXT, 'The favourite area (itemtype)', VALUE_REQUIRED),
4389 'id' => new external_value(PARAM_INT, 'id of the activity or whatever', VALUE_REQUIRED),
4394 * Update the recommendation for an activity item.
4396 * @param string $area identifier for this activity.
4397 * @param int $id Associated id. This is needed in conjunction with the area to find the recommendation.
4398 * @return array some warnings or something.
4400 public static function toggle_activity_recommendation(string $area, int $id): array {
4401 ['area' => $area, 'id' => $id] = self::validate_parameters(self::toggle_activity_recommendation_parameters(),
4402 ['area' => $area, 'id' => $id]);
4404 $context = context_system::instance();
4405 self::validate_context($context);
4407 require_capability('moodle/course:recommendactivity', $context);
4409 $manager = \core_course\local\factory\content_item_service_factory::get_content_item_service();
4411 $status = $manager->toggle_recommendation($area, $id);
4412 return ['id' => $id, 'area' => $area, 'status' => $status];
4416 * Returns warnings.
4418 * @return external_description
4420 public static function toggle_activity_recommendation_returns() {
4421 return new external_single_structure(
4423 'id' => new external_value(PARAM_INT, 'id of the activity or whatever'),
4424 'area' => new external_value(PARAM_TEXT, 'The favourite area (itemtype)'),
4425 'status' => new external_value(PARAM_BOOL, 'If created or deleted'),
4431 * Returns description of method parameters
4433 * @return external_function_parameters
4435 public static function get_activity_chooser_footer_parameters() {
4436 return new external_function_parameters([
4437 'courseid' => new external_value(PARAM_INT, 'ID of the course', VALUE_REQUIRED),
4438 'sectionid' => new external_value(PARAM_INT, 'ID of the section', VALUE_REQUIRED),
4443 * Given a course ID we need to build up a footre for the chooser.
4445 * @param int $courseid The course we want to fetch the modules for
4446 * @param int $sectionid The section we want to fetch the modules for
4447 * @return array
4449 public static function get_activity_chooser_footer(int $courseid, int $sectionid) {
4451 'courseid' => $courseid,
4452 'sectionid' => $sectionid,
4453 ] = self::validate_parameters(self::get_activity_chooser_footer_parameters(), [
4454 'courseid' => $courseid,
4455 'sectionid' => $sectionid,
4458 $coursecontext = context_course::instance($courseid);
4459 self::validate_context($coursecontext);
4461 $activeplugin = get_config('core', 'activitychooseractivefooter');
4463 if ($activeplugin !== COURSE_CHOOSER_FOOTER_NONE) {
4464 $footerdata = component_callback($activeplugin, 'custom_chooser_footer', [$courseid, $sectionid]);
4465 return [
4466 'footer' => true,
4467 'customfooterjs' => $footerdata->get_footer_js_file(),
4468 'customfootertemplate' => $footerdata->get_footer_template(),
4469 'customcarouseltemplate' => $footerdata->get_carousel_template(),
4471 } else {
4472 return [
4473 'footer' => false,
4479 * Returns description of method result value
4481 * @return external_description
4483 public static function get_activity_chooser_footer_returns() {
4484 return new external_single_structure(
4486 'footer' => new external_value(PARAM_BOOL, 'Is a footer being return by this request?', VALUE_REQUIRED),
4487 'customfooterjs' => new external_value(PARAM_RAW, 'The path to the plugin JS file', VALUE_OPTIONAL),
4488 'customfootertemplate' => new external_value(PARAM_RAW, 'The prerendered footer', VALUE_OPTIONAL),
4489 'customcarouseltemplate' => new external_value(PARAM_RAW, 'Either "" or the prerendered carousel page',
4490 VALUE_OPTIONAL),