MDL-80949 mod_data: Remove unused Allow autolink param for text field
[moodle.git] / course / externallib.php
blob2021386db3b43a36940efe0266afacefe529badc
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * External course API
21 * @package core_course
22 * @category external
23 * @copyright 2009 Petr Skodak
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') || die;
29 use core_course\external\course_summary_exporter;
30 use core_external\external_api;
31 use core_external\external_description;
32 use core_external\external_files;
33 use core_external\external_format_value;
34 use core_external\external_function_parameters;
35 use core_external\external_multiple_structure;
36 use core_external\external_single_structure;
37 use core_external\external_value;
38 use core_external\external_warnings;
39 use core_external\util;
40 require_once(__DIR__ . "/lib.php");
42 /**
43 * Course external functions
45 * @package core_course
46 * @category external
47 * @copyright 2011 Jerome Mouneyrac
48 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
49 * @since Moodle 2.2
51 class core_course_external extends external_api {
53 /**
54 * Returns description of method parameters
56 * @return external_function_parameters
57 * @since Moodle 2.9 Options available
58 * @since Moodle 2.2
60 public static function get_course_contents_parameters() {
61 return new external_function_parameters(
62 array('courseid' => new external_value(PARAM_INT, 'course id'),
63 'options' => new external_multiple_structure (
64 new external_single_structure(
65 array(
66 'name' => new external_value(PARAM_ALPHANUM,
67 'The expected keys (value format) are:
68 excludemodules (bool) Do not return modules, return only the sections structure
69 excludecontents (bool) Do not return module contents (i.e: files inside a resource)
70 includestealthmodules (bool) Return stealth modules for students in a special
71 section (with id -1)
72 sectionid (int) Return only this section
73 sectionnumber (int) Return only this section with number (order)
74 cmid (int) Return only this module information (among the whole sections structure)
75 modname (string) Return only modules with this name "label, forum, etc..."
76 modid (int) Return only the module with this id (to be used with modname'),
77 'value' => new external_value(PARAM_RAW, 'the value of the option,
78 this param is personaly validated in the external function.')
80 ), 'Options, used since Moodle 2.9', VALUE_DEFAULT, array())
85 /**
86 * Get course contents
88 * @param int $courseid course id
89 * @param array $options Options for filtering the results, used since Moodle 2.9
90 * @return array
91 * @since Moodle 2.9 Options available
92 * @since Moodle 2.2
94 public static function get_course_contents($courseid, $options = array()) {
95 global $CFG, $DB, $USER, $PAGE;
96 require_once($CFG->dirroot . "/course/lib.php");
97 require_once($CFG->libdir . '/completionlib.php');
99 //validate parameter
100 $params = self::validate_parameters(self::get_course_contents_parameters(),
101 array('courseid' => $courseid, 'options' => $options));
103 $filters = array();
104 if (!empty($params['options'])) {
106 foreach ($params['options'] as $option) {
107 $name = trim($option['name']);
108 // Avoid duplicated options.
109 if (!isset($filters[$name])) {
110 switch ($name) {
111 case 'excludemodules':
112 case 'excludecontents':
113 case 'includestealthmodules':
114 $value = clean_param($option['value'], PARAM_BOOL);
115 $filters[$name] = $value;
116 break;
117 case 'sectionid':
118 case 'sectionnumber':
119 case 'cmid':
120 case 'modid':
121 $value = clean_param($option['value'], PARAM_INT);
122 if (is_numeric($value)) {
123 $filters[$name] = $value;
124 } else {
125 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
127 break;
128 case 'modname':
129 $value = clean_param($option['value'], PARAM_PLUGIN);
130 if ($value) {
131 $filters[$name] = $value;
132 } else {
133 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
135 break;
136 default:
137 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
143 //retrieve the course
144 $course = $DB->get_record('course', array('id' => $params['courseid']), '*', MUST_EXIST);
146 // now security checks
147 $context = context_course::instance($course->id, IGNORE_MISSING);
148 try {
149 self::validate_context($context);
150 } catch (Exception $e) {
151 $exceptionparam = new stdClass();
152 $exceptionparam->message = $e->getMessage();
153 $exceptionparam->courseid = $course->id;
154 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
157 $canupdatecourse = has_capability('moodle/course:update', $context);
159 //create return value
160 $coursecontents = array();
162 if ($canupdatecourse or $course->visible
163 or has_capability('moodle/course:viewhiddencourses', $context)) {
165 //retrieve sections
166 $modinfo = get_fast_modinfo($course);
167 $sections = $modinfo->get_section_info_all();
168 $courseformat = course_get_format($course);
169 $coursenumsections = $courseformat->get_last_section_number();
170 $stealthmodules = array(); // Array to keep all the modules available but not visible in a course section/topic.
172 $completioninfo = new completion_info($course);
174 //for each sections (first displayed to last displayed)
175 $modinfosections = $modinfo->get_sections();
176 foreach ($sections as $key => $section) {
178 // This becomes true when we are filtering and we found the value to filter with.
179 $sectionfound = false;
181 // Filter by section id.
182 if (!empty($filters['sectionid'])) {
183 if ($section->id != $filters['sectionid']) {
184 continue;
185 } else {
186 $sectionfound = true;
190 // Filter by section number. Note that 0 is a valid section number.
191 if (isset($filters['sectionnumber'])) {
192 if ($key != $filters['sectionnumber']) {
193 continue;
194 } else {
195 $sectionfound = true;
199 // reset $sectioncontents
200 $sectionvalues = array();
201 $sectionvalues['id'] = $section->id;
202 $sectionvalues['name'] = get_section_name($course, $section);
203 $sectionvalues['visible'] = $section->visible;
205 $options = (object) array('noclean' => true);
206 list($sectionvalues['summary'], $sectionvalues['summaryformat']) =
207 \core_external\util::format_text($section->summary, $section->summaryformat,
208 $context, 'course', 'section', $section->id, $options);
209 $sectionvalues['section'] = $section->section;
210 $sectionvalues['hiddenbynumsections'] = $section->section > $coursenumsections ? 1 : 0;
211 $sectionvalues['uservisible'] = $section->uservisible;
212 if (!empty($section->availableinfo)) {
213 $sectionvalues['availabilityinfo'] = \core_availability\info::format_info($section->availableinfo, $course);
216 $sectioncontents = array();
218 // For each module of the section.
219 if (empty($filters['excludemodules']) and !empty($modinfosections[$section->section])) {
220 foreach ($modinfosections[$section->section] as $cmid) {
221 $cm = $modinfo->cms[$cmid];
222 $cminfo = cm_info::create($cm);
223 $activitydates = \core\activity_dates::get_dates_for_module($cminfo, $USER->id);
225 // Stop here if the module is not visible to the user on the course main page:
226 // The user can't access the module and the user can't view the module on the course page.
227 if (!$cm->uservisible && !$cm->is_visible_on_course_page()) {
228 continue;
231 // This becomes true when we are filtering and we found the value to filter with.
232 $modfound = false;
234 // Filter by cmid.
235 if (!empty($filters['cmid'])) {
236 if ($cmid != $filters['cmid']) {
237 continue;
238 } else {
239 $modfound = true;
243 // Filter by module name and id.
244 if (!empty($filters['modname'])) {
245 if ($cm->modname != $filters['modname']) {
246 continue;
247 } else if (!empty($filters['modid'])) {
248 if ($cm->instance != $filters['modid']) {
249 continue;
250 } else {
251 // Note that if we are only filtering by modname we don't break the loop.
252 $modfound = true;
257 $module = array();
259 $modcontext = context_module::instance($cm->id);
261 $isbrandedfunction = $cm->modname.'_is_branded';
262 $isbranded = function_exists($isbrandedfunction) ? $isbrandedfunction() : false;
264 // Common info (for people being able to see the module or availability dates).
265 $module['id'] = $cm->id;
266 $module['name'] = \core_external\util::format_string($cm->name, $modcontext);
267 $module['instance'] = $cm->instance;
268 $module['contextid'] = $modcontext->id;
269 $module['modname'] = (string) $cm->modname;
270 $module['modplural'] = (string) $cm->modplural;
271 $module['modicon'] = $cm->get_icon_url()->out(false);
272 $module['purpose'] = plugin_supports('mod', $cm->modname, FEATURE_MOD_PURPOSE, MOD_PURPOSE_OTHER);
273 $module['branded'] = $isbranded;
274 $module['indent'] = $cm->indent;
275 $module['onclick'] = $cm->onclick;
276 $module['afterlink'] = $cm->afterlink;
277 $activitybadgedata = $cm->get_activitybadge();
278 if (!empty($activitybadgedata)) {
279 $module['activitybadge'] = $activitybadgedata;
281 $module['customdata'] = json_encode($cm->customdata);
282 $module['completion'] = $cm->completion;
283 $module['downloadcontent'] = $cm->downloadcontent;
284 $module['noviewlink'] = plugin_supports('mod', $cm->modname, FEATURE_NO_VIEW_LINK, false);
285 $module['dates'] = $activitydates;
286 $module['groupmode'] = $cm->groupmode;
288 // Check module completion.
289 $completion = $completioninfo->is_enabled($cm);
290 if ($completion != COMPLETION_DISABLED) {
291 $exporter = new \core_completion\external\completion_info_exporter($course, $cm, $USER->id);
292 $renderer = $PAGE->get_renderer('core');
293 $modulecompletiondata = (array)$exporter->export($renderer);
294 $module['completiondata'] = $modulecompletiondata;
297 if (!empty($cm->showdescription) or $module['noviewlink']) {
298 // We want to use the external format. However from reading get_formatted_content(), $cm->content format is always FORMAT_HTML.
299 $options = array('noclean' => true);
300 list($module['description'], $descriptionformat) = \core_external\util::format_text($cm->content,
301 FORMAT_HTML, $modcontext, $cm->modname, 'intro', $cm->id, $options);
304 //url of the module
305 $url = $cm->url;
306 if ($url) { //labels don't have url
307 $module['url'] = $url->out(false);
310 $canviewhidden = has_capability('moodle/course:viewhiddenactivities',
311 context_module::instance($cm->id));
312 //user that can view hidden module should know about the visibility
313 $module['visible'] = $cm->visible;
314 $module['visibleoncoursepage'] = $cm->visibleoncoursepage;
315 $module['uservisible'] = $cm->uservisible;
316 if (!empty($cm->availableinfo)) {
317 $module['availabilityinfo'] = \core_availability\info::format_info($cm->availableinfo, $course);
320 // Availability date (also send to user who can see hidden module).
321 if ($CFG->enableavailability && ($canviewhidden || $canupdatecourse)) {
322 $module['availability'] = $cm->availability;
325 // Return contents only if the user can access to the module.
326 if ($cm->uservisible) {
327 $baseurl = 'webservice/pluginfile.php';
329 // Call $modulename_export_contents (each module callback take care about checking the capabilities).
330 require_once($CFG->dirroot . '/mod/' . $cm->modname . '/lib.php');
331 $getcontentfunction = $cm->modname.'_export_contents';
332 if (function_exists($getcontentfunction)) {
333 $contents = $getcontentfunction($cm, $baseurl);
334 $module['contentsinfo'] = array(
335 'filescount' => count($contents),
336 'filessize' => 0,
337 'lastmodified' => 0,
338 'mimetypes' => array(),
340 foreach ($contents as $content) {
341 // Check repository file (only main file).
342 if (!isset($module['contentsinfo']['repositorytype'])) {
343 $module['contentsinfo']['repositorytype'] =
344 isset($content['repositorytype']) ? $content['repositorytype'] : '';
346 if (isset($content['filesize'])) {
347 $module['contentsinfo']['filessize'] += $content['filesize'];
349 if (isset($content['timemodified']) &&
350 ($content['timemodified'] > $module['contentsinfo']['lastmodified'])) {
352 $module['contentsinfo']['lastmodified'] = $content['timemodified'];
354 if (isset($content['mimetype'])) {
355 $module['contentsinfo']['mimetypes'][$content['mimetype']] = $content['mimetype'];
359 if (empty($filters['excludecontents']) and !empty($contents)) {
360 $module['contents'] = $contents;
361 } else {
362 $module['contents'] = array();
367 // Assign result to $sectioncontents, there is an exception,
368 // stealth activities in non-visible sections for students go to a special section.
369 if (!empty($filters['includestealthmodules']) && !$section->uservisible && $cm->is_stealth()) {
370 $stealthmodules[] = $module;
371 } else {
372 $sectioncontents[] = $module;
375 // If we just did a filtering, break the loop.
376 if ($modfound) {
377 break;
382 $sectionvalues['modules'] = $sectioncontents;
384 // assign result to $coursecontents
385 $coursecontents[$key] = $sectionvalues;
387 // Break the loop if we are filtering.
388 if ($sectionfound) {
389 break;
393 // Now that we have iterated over all the sections and activities, check the visibility.
394 // We didn't this before to be able to retrieve stealth activities.
395 foreach ($coursecontents as $sectionnumber => $sectioncontents) {
396 $section = $sections[$sectionnumber];
398 if (!$courseformat->is_section_visible($section)) {
399 unset($coursecontents[$sectionnumber]);
400 continue;
403 // Remove section and modules information if the section is not visible for the user.
404 if (!$section->uservisible) {
405 $coursecontents[$sectionnumber]['modules'] = array();
406 // Remove summary information if the section is completely hidden only,
407 // even if the section is not user visible, the summary is always displayed among the availability information.
408 if (!$section->visible) {
409 $coursecontents[$sectionnumber]['summary'] = '';
414 // Include stealth modules in special section (without any info).
415 if (!empty($stealthmodules)) {
416 $coursecontents[] = array(
417 'id' => -1,
418 'name' => '',
419 'summary' => '',
420 'summaryformat' => FORMAT_MOODLE,
421 'modules' => $stealthmodules
426 return $coursecontents;
430 * Returns description of method result value
432 * @return \core_external\external_description
433 * @since Moodle 2.2
435 public static function get_course_contents_returns() {
436 $completiondefinition = \core_completion\external\completion_info_exporter::get_read_structure(VALUE_DEFAULT, []);
438 return new external_multiple_structure(
439 new external_single_structure(
440 array(
441 'id' => new external_value(PARAM_INT, 'Section ID'),
442 'name' => new external_value(PARAM_RAW, 'Section name'),
443 'visible' => new external_value(PARAM_INT, 'is the section visible', VALUE_OPTIONAL),
444 'summary' => new external_value(PARAM_RAW, 'Section description'),
445 'summaryformat' => new external_format_value('summary'),
446 'section' => new external_value(PARAM_INT, 'Section number inside the course', VALUE_OPTIONAL),
447 'hiddenbynumsections' => new external_value(PARAM_INT, 'Whether is a section hidden in the course format',
448 VALUE_OPTIONAL),
449 'uservisible' => new external_value(PARAM_BOOL, 'Is the section visible for the user?', VALUE_OPTIONAL),
450 'availabilityinfo' => new external_value(PARAM_RAW, 'Availability information.', VALUE_OPTIONAL),
451 'modules' => new external_multiple_structure(
452 new external_single_structure(
453 array(
454 'id' => new external_value(PARAM_INT, 'activity id'),
455 'url' => new external_value(PARAM_URL, 'activity url', VALUE_OPTIONAL),
456 'name' => new external_value(PARAM_RAW, 'activity module name'),
457 'instance' => new external_value(PARAM_INT, 'instance id', VALUE_OPTIONAL),
458 'contextid' => new external_value(PARAM_INT, 'Activity context id.', VALUE_OPTIONAL),
459 'description' => new external_value(PARAM_RAW, 'activity description', VALUE_OPTIONAL),
460 'visible' => new external_value(PARAM_INT, 'is the module visible', VALUE_OPTIONAL),
461 'uservisible' => new external_value(PARAM_BOOL, 'Is the module visible for the user?',
462 VALUE_OPTIONAL),
463 'availabilityinfo' => new external_value(PARAM_RAW, 'Availability information.',
464 VALUE_OPTIONAL),
465 'visibleoncoursepage' => new external_value(PARAM_INT, 'is the module visible on course page',
466 VALUE_OPTIONAL),
467 'modicon' => new external_value(PARAM_URL, 'activity icon url'),
468 'modname' => new external_value(PARAM_PLUGIN, 'activity module type'),
469 'purpose' => new external_value(PARAM_ALPHA, 'the module purpose'),
470 'branded' => new external_value(PARAM_BOOL, 'Whether the module is branded or not',
471 VALUE_OPTIONAL),
472 'modplural' => new external_value(PARAM_TEXT, 'activity module plural name'),
473 'availability' => new external_value(PARAM_RAW, 'module availability settings', VALUE_OPTIONAL),
474 'indent' => new external_value(PARAM_INT, 'number of identation in the site'),
475 'onclick' => new external_value(PARAM_RAW, 'Onclick action.', VALUE_OPTIONAL),
476 'afterlink' => new external_value(PARAM_RAW, 'After link info to be displayed.',
477 VALUE_OPTIONAL),
478 'activitybadge' => self::get_activitybadge_structure(),
479 'customdata' => new external_value(PARAM_RAW, 'Custom data (JSON encoded).', VALUE_OPTIONAL),
480 'noviewlink' => new external_value(PARAM_BOOL, 'Whether the module has no view page',
481 VALUE_OPTIONAL),
482 'completion' => new external_value(PARAM_INT, 'Type of completion tracking:
483 0 means none, 1 manual, 2 automatic.', VALUE_OPTIONAL),
484 'completiondata' => $completiondefinition,
485 'downloadcontent' => new external_value(PARAM_INT, 'The download content value', VALUE_OPTIONAL),
486 'dates' => new external_multiple_structure(
487 new external_single_structure(
488 array(
489 'label' => new external_value(PARAM_TEXT, 'date label'),
490 'timestamp' => new external_value(PARAM_INT, 'date timestamp'),
491 'relativeto' => new external_value(PARAM_INT, 'relative date timestamp',
492 VALUE_OPTIONAL),
493 'dataid' => new external_value(PARAM_NOTAGS, 'cm data id', VALUE_OPTIONAL),
496 'Course dates',
497 VALUE_DEFAULT,
500 'groupmode' => new external_value(PARAM_INT, 'Group mode value', VALUE_OPTIONAL),
501 'contents' => new external_multiple_structure(
502 new external_single_structure(
503 array(
504 // content info
505 'type'=> new external_value(PARAM_TEXT, 'a file or a folder or external link'),
506 'filename'=> new external_value(PARAM_FILE, 'filename'),
507 'filepath'=> new external_value(PARAM_PATH, 'filepath'),
508 'filesize'=> new external_value(PARAM_INT, 'filesize'),
509 'fileurl' => new external_value(PARAM_URL, 'downloadable file url', VALUE_OPTIONAL),
510 'content' => new external_value(PARAM_RAW, 'Raw content, will be used when type is content', VALUE_OPTIONAL),
511 'timecreated' => new external_value(PARAM_INT, 'Time created'),
512 'timemodified' => new external_value(PARAM_INT, 'Time modified'),
513 'sortorder' => new external_value(PARAM_INT, 'Content sort order'),
514 'mimetype' => new external_value(PARAM_RAW, 'File mime type.', VALUE_OPTIONAL),
515 'isexternalfile' => new external_value(PARAM_BOOL, 'Whether is an external file.',
516 VALUE_OPTIONAL),
517 'repositorytype' => new external_value(PARAM_PLUGIN, 'The repository type for external files.',
518 VALUE_OPTIONAL),
520 // copyright related info
521 'userid' => new external_value(PARAM_INT, 'User who added this content to moodle'),
522 'author' => new external_value(PARAM_TEXT, 'Content owner'),
523 'license' => new external_value(PARAM_TEXT, 'Content license'),
524 'tags' => new external_multiple_structure(
525 \core_tag\external\tag_item_exporter::get_read_structure(), 'Tags',
526 VALUE_OPTIONAL
529 ), 'Course contents', VALUE_DEFAULT, array()
531 'contentsinfo' => new external_single_structure(
532 array(
533 'filescount' => new external_value(PARAM_INT, 'Total number of files.'),
534 'filessize' => new external_value(PARAM_INT, 'Total files size.'),
535 'lastmodified' => new external_value(PARAM_INT, 'Last time files were modified.'),
536 'mimetypes' => new external_multiple_structure(
537 new external_value(PARAM_RAW, 'File mime type.'),
538 'Files mime types.'
540 'repositorytype' => new external_value(PARAM_PLUGIN, 'The repository type for
541 the main file.', VALUE_OPTIONAL),
542 ), 'Contents summary information.', VALUE_OPTIONAL
545 ), 'list of module'
553 * Returns description of activitybadge data.
555 * @return external_description
557 protected static function get_activitybadge_structure(): external_description {
558 return new external_single_structure(
560 'badgecontent' => new external_value(
561 PARAM_TEXT,
562 'The content to be displayed in the activity badge',
563 VALUE_OPTIONAL
565 'badgestyle' => new external_value(
566 PARAM_TEXT,
567 'The style for the activity badge',
568 VALUE_OPTIONAL
570 'badgeurl' => new external_value(
571 PARAM_URL,
572 'An optional URL to redirect the user when the activity badge is clicked',
573 VALUE_OPTIONAL
575 'badgeelementid' => new external_value(
576 PARAM_ALPHANUMEXT,
577 'An optional id in case the module wants to add some code for the activity badge',
578 VALUE_OPTIONAL
580 'badgeextraattributes' => new external_multiple_structure(
581 new external_single_structure(
583 'name' => new external_value(
584 PARAM_TEXT,
585 'The attribute name',
586 VALUE_OPTIONAL
588 'value' => new external_value(
589 PARAM_TEXT,
590 'The attribute value',
591 VALUE_OPTIONAL
594 'Each of the attribute names and values',
595 VALUE_OPTIONAL
597 'An optional array of extra HTML attributes to add to the badge element',
598 VALUE_OPTIONAL
601 'Activity badge to display near the name',
602 VALUE_OPTIONAL
607 * Returns description of method parameters
609 * @return external_function_parameters
610 * @since Moodle 2.3
612 public static function get_courses_parameters() {
613 return new external_function_parameters(
614 array('options' => new external_single_structure(
615 array('ids' => new external_multiple_structure(
616 new external_value(PARAM_INT, 'Course id')
617 , 'List of course id. If empty return all courses
618 except front page course.',
619 VALUE_OPTIONAL)
620 ), 'options - operator OR is used', VALUE_DEFAULT, array())
626 * Get courses
628 * @param array $options It contains an array (list of ids)
629 * @return array
630 * @since Moodle 2.2
632 public static function get_courses($options = array()) {
633 global $CFG, $DB;
634 require_once($CFG->dirroot . "/course/lib.php");
636 //validate parameter
637 $params = self::validate_parameters(self::get_courses_parameters(),
638 array('options' => $options));
640 //retrieve courses
641 if (!array_key_exists('ids', $params['options'])
642 or empty($params['options']['ids'])) {
643 $courses = $DB->get_records('course');
644 } else {
645 $courses = $DB->get_records_list('course', 'id', $params['options']['ids']);
648 //create return value
649 $coursesinfo = array();
650 foreach ($courses as $course) {
652 // now security checks
653 $context = context_course::instance($course->id, IGNORE_MISSING);
654 $courseformatoptions = course_get_format($course)->get_format_options();
655 try {
656 self::validate_context($context);
657 } catch (Exception $e) {
658 $exceptionparam = new stdClass();
659 $exceptionparam->message = $e->getMessage();
660 $exceptionparam->courseid = $course->id;
661 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
663 if ($course->id != SITEID) {
664 require_capability('moodle/course:view', $context);
667 $courseinfo = array();
668 $courseinfo['id'] = $course->id;
669 $courseinfo['fullname'] = \core_external\util::format_string($course->fullname, $context);
670 $courseinfo['shortname'] = \core_external\util::format_string($course->shortname, $context);
671 $courseinfo['displayname'] = \core_external\util::format_string(get_course_display_name_for_list($course), $context);
672 $courseinfo['categoryid'] = $course->category;
673 list($courseinfo['summary'], $courseinfo['summaryformat']) =
674 \core_external\util::format_text($course->summary, $course->summaryformat, $context, 'course', 'summary', 0);
675 $courseinfo['format'] = $course->format;
676 $courseinfo['startdate'] = $course->startdate;
677 $courseinfo['enddate'] = $course->enddate;
678 $courseinfo['showactivitydates'] = $course->showactivitydates;
679 $courseinfo['showcompletionconditions'] = $course->showcompletionconditions;
680 if (array_key_exists('numsections', $courseformatoptions)) {
681 // For backward-compartibility
682 $courseinfo['numsections'] = $courseformatoptions['numsections'];
684 $courseinfo['pdfexportfont'] = $course->pdfexportfont;
686 $handler = core_course\customfield\course_handler::create();
687 if ($customfields = $handler->export_instance_data($course->id)) {
688 $courseinfo['customfields'] = [];
689 foreach ($customfields as $data) {
690 $courseinfo['customfields'][] = [
691 'type' => $data->get_type(),
692 'value' => $data->get_value(),
693 'valueraw' => $data->get_data_controller()->get_value(),
694 'name' => $data->get_name(),
695 'shortname' => $data->get_shortname()
700 //some field should be returned only if the user has update permission
701 $courseadmin = has_capability('moodle/course:update', $context);
702 if ($courseadmin) {
703 $courseinfo['categorysortorder'] = $course->sortorder;
704 $courseinfo['idnumber'] = $course->idnumber;
705 $courseinfo['showgrades'] = $course->showgrades;
706 $courseinfo['showreports'] = $course->showreports;
707 $courseinfo['newsitems'] = $course->newsitems;
708 $courseinfo['visible'] = $course->visible;
709 $courseinfo['maxbytes'] = $course->maxbytes;
710 if (array_key_exists('hiddensections', $courseformatoptions)) {
711 // For backward-compartibility
712 $courseinfo['hiddensections'] = $courseformatoptions['hiddensections'];
714 // Return numsections for backward-compatibility with clients who expect it.
715 $courseinfo['numsections'] = course_get_format($course)->get_last_section_number();
716 $courseinfo['groupmode'] = $course->groupmode;
717 $courseinfo['groupmodeforce'] = $course->groupmodeforce;
718 $courseinfo['defaultgroupingid'] = $course->defaultgroupingid;
719 $courseinfo['lang'] = clean_param($course->lang, PARAM_LANG);
720 $courseinfo['timecreated'] = $course->timecreated;
721 $courseinfo['timemodified'] = $course->timemodified;
722 $courseinfo['forcetheme'] = clean_param($course->theme, PARAM_THEME);
723 $courseinfo['enablecompletion'] = $course->enablecompletion;
724 $courseinfo['completionnotify'] = $course->completionnotify;
725 $courseinfo['courseformatoptions'] = array();
726 foreach ($courseformatoptions as $key => $value) {
727 $courseinfo['courseformatoptions'][] = array(
728 'name' => $key,
729 'value' => $value
734 if ($courseadmin or $course->visible
735 or has_capability('moodle/course:viewhiddencourses', $context)) {
736 $coursesinfo[] = $courseinfo;
740 return $coursesinfo;
744 * Returns description of method result value
746 * @return \core_external\external_description
747 * @since Moodle 2.2
749 public static function get_courses_returns() {
750 return new external_multiple_structure(
751 new external_single_structure(
752 array(
753 'id' => new external_value(PARAM_INT, 'course id'),
754 'shortname' => new external_value(PARAM_RAW, 'course short name'),
755 'categoryid' => new external_value(PARAM_INT, 'category id'),
756 'categorysortorder' => new external_value(PARAM_INT,
757 'sort order into the category', VALUE_OPTIONAL),
758 'fullname' => new external_value(PARAM_RAW, 'full name'),
759 'displayname' => new external_value(PARAM_RAW, 'course display name'),
760 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
761 'summary' => new external_value(PARAM_RAW, 'summary'),
762 'summaryformat' => new external_format_value('summary'),
763 'format' => new external_value(PARAM_PLUGIN,
764 'course format: weeks, topics, social, site,..'),
765 'showgrades' => new external_value(PARAM_INT,
766 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
767 'newsitems' => new external_value(PARAM_INT,
768 'number of recent items appearing on the course page', VALUE_OPTIONAL),
769 'startdate' => new external_value(PARAM_INT,
770 'timestamp when the course start'),
771 'enddate' => new external_value(PARAM_INT,
772 'timestamp when the course end'),
773 'numsections' => new external_value(PARAM_INT,
774 '(deprecated, use courseformatoptions) number of weeks/topics',
775 VALUE_OPTIONAL),
776 'maxbytes' => new external_value(PARAM_INT,
777 'largest size of file that can be uploaded into the course',
778 VALUE_OPTIONAL),
779 'showreports' => new external_value(PARAM_INT,
780 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
781 'visible' => new external_value(PARAM_INT,
782 '1: available to student, 0:not available', VALUE_OPTIONAL),
783 'hiddensections' => new external_value(PARAM_INT,
784 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
785 VALUE_OPTIONAL),
786 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
787 VALUE_OPTIONAL),
788 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
789 VALUE_OPTIONAL),
790 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
791 VALUE_OPTIONAL),
792 'timecreated' => new external_value(PARAM_INT,
793 'timestamp when the course have been created', VALUE_OPTIONAL),
794 'timemodified' => new external_value(PARAM_INT,
795 'timestamp when the course have been modified', VALUE_OPTIONAL),
796 'enablecompletion' => new external_value(PARAM_INT,
797 'Enabled, control via completion and activity settings. Disbaled,
798 not shown in activity settings.',
799 VALUE_OPTIONAL),
800 'completionnotify' => new external_value(PARAM_INT,
801 '1: yes 0: no', VALUE_OPTIONAL),
802 'lang' => new external_value(PARAM_SAFEDIR,
803 'forced course language', VALUE_OPTIONAL),
804 'forcetheme' => new external_value(PARAM_PLUGIN,
805 'name of the force theme', VALUE_OPTIONAL),
806 'courseformatoptions' => new external_multiple_structure(
807 new external_single_structure(
808 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
809 'value' => new external_value(PARAM_RAW, 'course format option value')
810 )), 'additional options for particular course format', VALUE_OPTIONAL
812 'showactivitydates' => new external_value(PARAM_BOOL, 'Whether the activity dates are shown or not'),
813 'showcompletionconditions' => new external_value(PARAM_BOOL,
814 'Whether the activity completion conditions are shown or not'),
815 'customfields' => new external_multiple_structure(
816 new external_single_structure(
817 ['name' => new external_value(PARAM_RAW, 'The name of the custom field'),
818 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'The shortname of the custom field'),
819 'type' => new external_value(PARAM_COMPONENT,
820 'The type of the custom field - text, checkbox...'),
821 'valueraw' => new external_value(PARAM_RAW, 'The raw value of the custom field'),
822 'value' => new external_value(PARAM_RAW, 'The value of the custom field')]
823 ), 'Custom fields and associated values', VALUE_OPTIONAL),
824 ), 'course'
830 * Return array of all editable course custom fields indexed by their shortname
832 * @param \context $context
833 * @param int $courseid
834 * @return \core_customfield\field_controller[]
836 public static function get_editable_customfields(\context $context, int $courseid = 0): array {
837 $result = [];
839 $handler = \core_course\customfield\course_handler::create();
840 $handler->set_parent_context($context);
842 foreach ($handler->get_editable_fields($courseid) as $field) {
843 $result[$field->get('shortname')] = $field;
846 return $result;
850 * Returns description of method parameters
852 * @return external_function_parameters
853 * @since Moodle 2.2
855 public static function create_courses_parameters() {
856 $courseconfig = get_config('moodlecourse'); //needed for many default values
857 return new external_function_parameters(
858 array(
859 'courses' => new external_multiple_structure(
860 new external_single_structure(
861 array(
862 'fullname' => new external_value(PARAM_TEXT, 'full name'),
863 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
864 'categoryid' => new external_value(PARAM_INT, 'category id'),
865 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
866 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
867 'summaryformat' => new external_format_value('summary', VALUE_DEFAULT),
868 'format' => new external_value(PARAM_PLUGIN,
869 'course format: weeks, topics, social, site,..',
870 VALUE_DEFAULT, $courseconfig->format),
871 'showgrades' => new external_value(PARAM_INT,
872 '1 if grades are shown, otherwise 0', VALUE_DEFAULT,
873 $courseconfig->showgrades),
874 'newsitems' => new external_value(PARAM_INT,
875 'number of recent items appearing on the course page',
876 VALUE_DEFAULT, $courseconfig->newsitems),
877 'startdate' => new external_value(PARAM_INT,
878 'timestamp when the course start', VALUE_OPTIONAL),
879 'enddate' => new external_value(PARAM_INT,
880 'timestamp when the course end', VALUE_OPTIONAL),
881 'numsections' => new external_value(PARAM_INT,
882 '(deprecated, use courseformatoptions) number of weeks/topics',
883 VALUE_OPTIONAL),
884 'maxbytes' => new external_value(PARAM_INT,
885 'largest size of file that can be uploaded into the course',
886 VALUE_DEFAULT, $courseconfig->maxbytes),
887 'showreports' => new external_value(PARAM_INT,
888 'are activity report shown (yes = 1, no =0)', VALUE_DEFAULT,
889 $courseconfig->showreports),
890 'visible' => new external_value(PARAM_INT,
891 '1: available to student, 0:not available', VALUE_OPTIONAL),
892 'hiddensections' => new external_value(PARAM_INT,
893 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
894 VALUE_OPTIONAL),
895 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
896 VALUE_DEFAULT, $courseconfig->groupmode),
897 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
898 VALUE_DEFAULT, $courseconfig->groupmodeforce),
899 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
900 VALUE_DEFAULT, 0),
901 'enablecompletion' => new external_value(PARAM_INT,
902 'Enabled, control via completion and activity settings. Disabled,
903 not shown in activity settings.',
904 VALUE_OPTIONAL),
905 'completionnotify' => new external_value(PARAM_INT,
906 '1: yes 0: no', VALUE_OPTIONAL),
907 'lang' => new external_value(PARAM_SAFEDIR,
908 'forced course language', VALUE_OPTIONAL),
909 'forcetheme' => new external_value(PARAM_PLUGIN,
910 'name of the force theme', VALUE_OPTIONAL),
911 'courseformatoptions' => new external_multiple_structure(
912 new external_single_structure(
913 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
914 'value' => new external_value(PARAM_RAW, 'course format option value')
916 'additional options for particular course format', VALUE_OPTIONAL),
917 'customfields' => new external_multiple_structure(
918 new external_single_structure(
919 array(
920 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'The shortname of the custom field'),
921 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
922 )), 'custom fields for the course', VALUE_OPTIONAL
924 )), 'courses to create'
931 * Create courses
933 * @param array $courses
934 * @return array courses (id and shortname only)
935 * @since Moodle 2.2
937 public static function create_courses($courses) {
938 global $CFG, $DB;
939 require_once($CFG->dirroot . "/course/lib.php");
940 require_once($CFG->libdir . '/completionlib.php');
942 $params = self::validate_parameters(self::create_courses_parameters(),
943 array('courses' => $courses));
945 $availablethemes = core_component::get_plugin_list('theme');
946 $availablelangs = get_string_manager()->get_list_of_translations();
948 $transaction = $DB->start_delegated_transaction();
950 foreach ($params['courses'] as $course) {
952 // Ensure the current user is allowed to run this function
953 $context = context_coursecat::instance($course['categoryid'], IGNORE_MISSING);
954 try {
955 self::validate_context($context);
956 } catch (Exception $e) {
957 $exceptionparam = new stdClass();
958 $exceptionparam->message = $e->getMessage();
959 $exceptionparam->catid = $course['categoryid'];
960 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
962 require_capability('moodle/course:create', $context);
964 // Fullname and short name are required to be non-empty.
965 if (trim($course['fullname']) === '') {
966 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'fullname');
967 } else if (trim($course['shortname']) === '') {
968 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'shortname');
971 // Make sure lang is valid
972 if (array_key_exists('lang', $course)) {
973 if (empty($availablelangs[$course['lang']])) {
974 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
976 if (!has_capability('moodle/course:setforcedlanguage', $context)) {
977 unset($course['lang']);
981 // Make sure theme is valid
982 if (array_key_exists('forcetheme', $course)) {
983 if (!empty($CFG->allowcoursethemes)) {
984 if (empty($availablethemes[$course['forcetheme']])) {
985 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
986 } else {
987 $course['theme'] = $course['forcetheme'];
992 //force visibility if ws user doesn't have the permission to set it
993 $category = $DB->get_record('course_categories', array('id' => $course['categoryid']));
994 if (!has_capability('moodle/course:visibility', $context)) {
995 $course['visible'] = $category->visible;
998 //set default value for completion
999 $courseconfig = get_config('moodlecourse');
1000 if (completion_info::is_enabled_for_site()) {
1001 if (!array_key_exists('enablecompletion', $course)) {
1002 $course['enablecompletion'] = $courseconfig->enablecompletion;
1004 } else {
1005 $course['enablecompletion'] = 0;
1008 $course['category'] = $course['categoryid'];
1010 // Summary format.
1011 $course['summaryformat'] = util::validate_format($course['summaryformat']);
1013 if (!empty($course['courseformatoptions'])) {
1014 foreach ($course['courseformatoptions'] as $option) {
1015 $course[$option['name']] = $option['value'];
1019 // Custom fields.
1020 if (!empty($course['customfields'])) {
1021 $customfields = self::get_editable_customfields($context);
1022 foreach ($course['customfields'] as $field) {
1023 if (array_key_exists($field['shortname'], $customfields)) {
1024 // Ensure we're populating the element form fields correctly.
1025 $controller = \core_customfield\data_controller::create(0, null, $customfields[$field['shortname']]);
1026 $course[$controller->get_form_element_name()] = $field['value'];
1031 //Note: create_course() core function check shortname, idnumber, category
1032 $course['id'] = create_course((object) $course)->id;
1034 $resultcourses[] = array('id' => $course['id'], 'shortname' => $course['shortname']);
1037 $transaction->allow_commit();
1039 return $resultcourses;
1043 * Returns description of method result value
1045 * @return \core_external\external_description
1046 * @since Moodle 2.2
1048 public static function create_courses_returns() {
1049 return new external_multiple_structure(
1050 new external_single_structure(
1051 array(
1052 'id' => new external_value(PARAM_INT, 'course id'),
1053 'shortname' => new external_value(PARAM_RAW, 'short name'),
1060 * Update courses
1062 * @return external_function_parameters
1063 * @since Moodle 2.5
1065 public static function update_courses_parameters() {
1066 return new external_function_parameters(
1067 array(
1068 'courses' => new external_multiple_structure(
1069 new external_single_structure(
1070 array(
1071 'id' => new external_value(PARAM_INT, 'ID of the course'),
1072 'fullname' => new external_value(PARAM_TEXT, 'full name', VALUE_OPTIONAL),
1073 'shortname' => new external_value(PARAM_TEXT, 'course short name', VALUE_OPTIONAL),
1074 'categoryid' => new external_value(PARAM_INT, 'category id', VALUE_OPTIONAL),
1075 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
1076 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
1077 'summaryformat' => new external_format_value('summary', VALUE_OPTIONAL),
1078 'format' => new external_value(PARAM_PLUGIN,
1079 'course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
1080 'showgrades' => new external_value(PARAM_INT,
1081 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
1082 'newsitems' => new external_value(PARAM_INT,
1083 'number of recent items appearing on the course page', VALUE_OPTIONAL),
1084 'startdate' => new external_value(PARAM_INT,
1085 'timestamp when the course start', VALUE_OPTIONAL),
1086 'enddate' => new external_value(PARAM_INT,
1087 'timestamp when the course end', VALUE_OPTIONAL),
1088 'numsections' => new external_value(PARAM_INT,
1089 '(deprecated, use courseformatoptions) number of weeks/topics', VALUE_OPTIONAL),
1090 'maxbytes' => new external_value(PARAM_INT,
1091 'largest size of file that can be uploaded into the course', VALUE_OPTIONAL),
1092 'showreports' => new external_value(PARAM_INT,
1093 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
1094 'visible' => new external_value(PARAM_INT,
1095 '1: available to student, 0:not available', VALUE_OPTIONAL),
1096 'hiddensections' => new external_value(PARAM_INT,
1097 '(deprecated, use courseformatoptions) How the hidden sections in the course are
1098 displayed to students', VALUE_OPTIONAL),
1099 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
1100 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
1101 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
1102 'enablecompletion' => new external_value(PARAM_INT,
1103 'Enabled, control via completion and activity settings. Disabled,
1104 not shown in activity settings.', VALUE_OPTIONAL),
1105 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
1106 'lang' => new external_value(PARAM_SAFEDIR, 'forced course language', VALUE_OPTIONAL),
1107 'forcetheme' => new external_value(PARAM_PLUGIN, 'name of the force theme', VALUE_OPTIONAL),
1108 'courseformatoptions' => new external_multiple_structure(
1109 new external_single_structure(
1110 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
1111 'value' => new external_value(PARAM_RAW, 'course format option value')
1112 )), 'additional options for particular course format', VALUE_OPTIONAL),
1113 'customfields' => new external_multiple_structure(
1114 new external_single_structure(
1116 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'The shortname of the custom field'),
1117 'value' => new external_value(PARAM_RAW, 'The value of the custom field')
1119 ), 'Custom fields', VALUE_OPTIONAL),
1121 ), 'courses to update'
1128 * Update courses
1130 * @param array $courses
1131 * @since Moodle 2.5
1133 public static function update_courses($courses) {
1134 global $CFG, $DB;
1135 require_once($CFG->dirroot . "/course/lib.php");
1136 $warnings = array();
1138 $params = self::validate_parameters(self::update_courses_parameters(),
1139 array('courses' => $courses));
1141 $availablethemes = core_component::get_plugin_list('theme');
1142 $availablelangs = get_string_manager()->get_list_of_translations();
1144 foreach ($params['courses'] as $course) {
1145 // Catch any exception while updating course and return as warning to user.
1146 try {
1147 // Ensure the current user is allowed to run this function.
1148 $context = context_course::instance($course['id'], MUST_EXIST);
1149 self::validate_context($context);
1151 $oldcourse = course_get_format($course['id'])->get_course();
1153 require_capability('moodle/course:update', $context);
1155 // Check if user can change category.
1156 if (array_key_exists('categoryid', $course) && ($oldcourse->category != $course['categoryid'])) {
1157 require_capability('moodle/course:changecategory', $context);
1158 $course['category'] = $course['categoryid'];
1161 // Check if the user can change fullname, and the new value is non-empty.
1162 if (array_key_exists('fullname', $course) && ($oldcourse->fullname != $course['fullname'])) {
1163 require_capability('moodle/course:changefullname', $context);
1164 if (trim($course['fullname']) === '') {
1165 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'fullname');
1169 // Check if the user can change shortname, and the new value is non-empty.
1170 if (array_key_exists('shortname', $course) && ($oldcourse->shortname != $course['shortname'])) {
1171 require_capability('moodle/course:changeshortname', $context);
1172 if (trim($course['shortname']) === '') {
1173 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'shortname');
1177 // Check if the user can change the idnumber.
1178 if (array_key_exists('idnumber', $course) && ($oldcourse->idnumber != $course['idnumber'])) {
1179 require_capability('moodle/course:changeidnumber', $context);
1182 // Check if user can change summary.
1183 if (array_key_exists('summary', $course) && ($oldcourse->summary != $course['summary'])) {
1184 require_capability('moodle/course:changesummary', $context);
1187 // Summary format.
1188 if (array_key_exists('summaryformat', $course) && ($oldcourse->summaryformat != $course['summaryformat'])) {
1189 require_capability('moodle/course:changesummary', $context);
1190 $course['summaryformat'] = util::validate_format($course['summaryformat']);
1193 // Check if user can change visibility.
1194 if (array_key_exists('visible', $course) && ($oldcourse->visible != $course['visible'])) {
1195 require_capability('moodle/course:visibility', $context);
1198 // Make sure lang is valid.
1199 if (array_key_exists('lang', $course) && ($oldcourse->lang != $course['lang'])) {
1200 require_capability('moodle/course:setforcedlanguage', $context);
1201 if (empty($availablelangs[$course['lang']])) {
1202 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
1206 // Make sure theme is valid.
1207 if (array_key_exists('forcetheme', $course)) {
1208 if (!empty($CFG->allowcoursethemes)) {
1209 if (empty($availablethemes[$course['forcetheme']])) {
1210 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
1211 } else {
1212 $course['theme'] = $course['forcetheme'];
1217 // Make sure completion is enabled before setting it.
1218 if (array_key_exists('enabledcompletion', $course) && !completion_info::is_enabled_for_site()) {
1219 $course['enabledcompletion'] = 0;
1222 // Make sure maxbytes are less then CFG->maxbytes.
1223 if (array_key_exists('maxbytes', $course)) {
1224 // We allow updates back to 0 max bytes, a special value denoting the course uses the site limit.
1225 // Otherwise, either use the size specified, or cap at the max size for the course.
1226 if ($course['maxbytes'] != 0) {
1227 $course['maxbytes'] = get_max_upload_file_size($CFG->maxbytes, $course['maxbytes']);
1231 if (!empty($course['courseformatoptions'])) {
1232 foreach ($course['courseformatoptions'] as $option) {
1233 if (isset($option['name']) && isset($option['value'])) {
1234 $course[$option['name']] = $option['value'];
1239 // Custom fields.
1240 if (isset($course['customfields'])) {
1241 $customfields = self::get_editable_customfields($context, $course['id']);
1242 foreach ($course['customfields'] as $field) {
1243 if (array_key_exists($field['shortname'], $customfields)) {
1244 // Ensure we're populating the element form fields correctly.
1245 $controller = \core_customfield\data_controller::create(0, null, $customfields[$field['shortname']]);
1246 $course[$controller->get_form_element_name()] = $field['value'];
1251 // Update course if user has all required capabilities.
1252 update_course((object) $course);
1253 } catch (Exception $e) {
1254 $warning = array();
1255 $warning['item'] = 'course';
1256 $warning['itemid'] = $course['id'];
1257 if ($e instanceof moodle_exception) {
1258 $warning['warningcode'] = $e->errorcode;
1259 } else {
1260 $warning['warningcode'] = $e->getCode();
1262 $warning['message'] = $e->getMessage();
1263 $warnings[] = $warning;
1267 $result = array();
1268 $result['warnings'] = $warnings;
1269 return $result;
1273 * Returns description of method result value
1275 * @return \core_external\external_description
1276 * @since Moodle 2.5
1278 public static function update_courses_returns() {
1279 return new external_single_structure(
1280 array(
1281 'warnings' => new external_warnings()
1287 * Returns description of method parameters
1289 * @return external_function_parameters
1290 * @since Moodle 2.2
1292 public static function delete_courses_parameters() {
1293 return new external_function_parameters(
1294 array(
1295 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'course ID')),
1301 * Delete courses
1303 * @param array $courseids A list of course ids
1304 * @since Moodle 2.2
1306 public static function delete_courses($courseids) {
1307 global $CFG, $DB;
1308 require_once($CFG->dirroot."/course/lib.php");
1310 // Parameter validation.
1311 $params = self::validate_parameters(self::delete_courses_parameters(), array('courseids'=>$courseids));
1313 $warnings = array();
1315 foreach ($params['courseids'] as $courseid) {
1316 $course = $DB->get_record('course', array('id' => $courseid));
1318 if ($course === false) {
1319 $warnings[] = array(
1320 'item' => 'course',
1321 'itemid' => $courseid,
1322 'warningcode' => 'unknowncourseidnumber',
1323 'message' => 'Unknown course ID ' . $courseid
1325 continue;
1328 // Check if the context is valid.
1329 $coursecontext = context_course::instance($course->id);
1330 self::validate_context($coursecontext);
1332 // Check if the current user has permission.
1333 if (!can_delete_course($courseid)) {
1334 $warnings[] = array(
1335 'item' => 'course',
1336 'itemid' => $courseid,
1337 'warningcode' => 'cannotdeletecourse',
1338 'message' => 'You do not have the permission to delete this course' . $courseid
1340 continue;
1343 if (delete_course($course, false) === false) {
1344 $warnings[] = array(
1345 'item' => 'course',
1346 'itemid' => $courseid,
1347 'warningcode' => 'cannotdeletecategorycourse',
1348 'message' => 'Course ' . $courseid . ' failed to be deleted'
1350 continue;
1354 fix_course_sortorder();
1356 return array('warnings' => $warnings);
1360 * Returns description of method result value
1362 * @return \core_external\external_description
1363 * @since Moodle 2.2
1365 public static function delete_courses_returns() {
1366 return new external_single_structure(
1367 array(
1368 'warnings' => new external_warnings()
1374 * Returns description of method parameters
1376 * @return external_function_parameters
1377 * @since Moodle 2.3
1379 public static function duplicate_course_parameters() {
1380 return new external_function_parameters(
1381 array(
1382 'courseid' => new external_value(PARAM_INT, 'course to duplicate id'),
1383 'fullname' => new external_value(PARAM_TEXT, 'duplicated course full name'),
1384 'shortname' => new external_value(PARAM_TEXT, 'duplicated course short name'),
1385 'categoryid' => new external_value(PARAM_INT, 'duplicated course category parent'),
1386 'visible' => new external_value(PARAM_INT, 'duplicated course visible, default to yes', VALUE_DEFAULT, 1),
1387 'options' => new external_multiple_structure(
1388 new external_single_structure(
1389 array(
1390 'name' => new external_value(PARAM_ALPHAEXT, 'The backup option name:
1391 "activities" (int) Include course activites (default to 1 that is equal to yes),
1392 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1393 "filters" (int) Include course filters (default to 1 that is equal to yes),
1394 "users" (int) Include users (default to 0 that is equal to no),
1395 "enrolments" (int) Include enrolment methods (default to 1 - restore only with users),
1396 "role_assignments" (int) Include role assignments (default to 0 that is equal to no),
1397 "comments" (int) Include user comments (default to 0 that is equal to no),
1398 "userscompletion" (int) Include user course completion information (default to 0 that is equal to no),
1399 "logs" (int) Include course logs (default to 0 that is equal to no),
1400 "grade_histories" (int) Include histories (default to 0 that is equal to no)'
1402 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1405 ), 'Course duplication options', VALUE_DEFAULT, array()
1412 * Duplicate a course
1414 * @param int $courseid
1415 * @param string $fullname Duplicated course fullname
1416 * @param string $shortname Duplicated course shortname
1417 * @param int $categoryid Duplicated course parent category id
1418 * @param int $visible Duplicated course availability
1419 * @param array $options List of backup options
1420 * @return array New course info
1421 * @since Moodle 2.3
1423 public static function duplicate_course($courseid, $fullname, $shortname, $categoryid, $visible = 1, $options = array()) {
1424 global $CFG, $USER, $DB;
1425 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1426 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1428 // Parameter validation.
1429 $params = self::validate_parameters(
1430 self::duplicate_course_parameters(),
1431 array(
1432 'courseid' => $courseid,
1433 'fullname' => $fullname,
1434 'shortname' => $shortname,
1435 'categoryid' => $categoryid,
1436 'visible' => $visible,
1437 'options' => $options
1441 // Context validation.
1443 if (! ($course = $DB->get_record('course', array('id'=>$params['courseid'])))) {
1444 throw new moodle_exception('invalidcourseid', 'error');
1447 // Category where duplicated course is going to be created.
1448 $categorycontext = context_coursecat::instance($params['categoryid']);
1449 self::validate_context($categorycontext);
1451 // Course to be duplicated.
1452 $coursecontext = context_course::instance($course->id);
1453 self::validate_context($coursecontext);
1455 $backupdefaults = array(
1456 'activities' => 1,
1457 'blocks' => 1,
1458 'filters' => 1,
1459 'users' => 0,
1460 'enrolments' => backup::ENROL_WITHUSERS,
1461 'role_assignments' => 0,
1462 'comments' => 0,
1463 'userscompletion' => 0,
1464 'logs' => 0,
1465 'grade_histories' => 0
1468 $backupsettings = array();
1469 // Check for backup and restore options.
1470 if (!empty($params['options'])) {
1471 foreach ($params['options'] as $option) {
1473 // Strict check for a correct value (allways 1 or 0, true or false).
1474 $value = clean_param($option['value'], PARAM_INT);
1476 if ($value !== 0 and $value !== 1) {
1477 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1480 if (!isset($backupdefaults[$option['name']])) {
1481 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1484 $backupsettings[$option['name']] = $value;
1488 // Capability checking.
1490 // The backup controller check for this currently, this may be redundant.
1491 require_capability('moodle/course:create', $categorycontext);
1492 require_capability('moodle/restore:restorecourse', $categorycontext);
1493 require_capability('moodle/backup:backupcourse', $coursecontext);
1495 if (!empty($backupsettings['users'])) {
1496 require_capability('moodle/backup:userinfo', $coursecontext);
1497 require_capability('moodle/restore:userinfo', $categorycontext);
1500 // Check if the shortname is used.
1501 if ($foundcourses = $DB->get_records('course', array('shortname'=>$shortname))) {
1502 foreach ($foundcourses as $foundcourse) {
1503 $foundcoursenames[] = $foundcourse->fullname;
1506 $foundcoursenamestring = implode(',', $foundcoursenames);
1507 throw new moodle_exception('shortnametaken', '', '', $foundcoursenamestring);
1510 // Backup the course.
1512 $bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE,
1513 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id);
1515 foreach ($backupsettings as $name => $value) {
1516 if ($setting = $bc->get_plan()->get_setting($name)) {
1517 $bc->get_plan()->get_setting($name)->set_value($value);
1521 $backupid = $bc->get_backupid();
1522 $backupbasepath = $bc->get_plan()->get_basepath();
1524 $bc->execute_plan();
1525 $results = $bc->get_results();
1526 $file = $results['backup_destination'];
1528 $bc->destroy();
1530 // Restore the backup immediately.
1532 // Check if we need to unzip the file because the backup temp dir does not contains backup files.
1533 if (!file_exists($backupbasepath . "/moodle_backup.xml")) {
1534 $file->extract_to_pathname(get_file_packer('application/vnd.moodle.backup'), $backupbasepath);
1537 // Create new course.
1538 $newcourseid = restore_dbops::create_new_course($params['fullname'], $params['shortname'], $params['categoryid']);
1540 $rc = new restore_controller($backupid, $newcourseid,
1541 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id, backup::TARGET_NEW_COURSE);
1543 foreach ($backupsettings as $name => $value) {
1544 $setting = $rc->get_plan()->get_setting($name);
1545 if ($setting->get_status() == backup_setting::NOT_LOCKED) {
1546 $setting->set_value($value);
1550 if (!$rc->execute_precheck()) {
1551 $precheckresults = $rc->get_precheck_results();
1552 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1553 if (empty($CFG->keeptempdirectoriesonbackup)) {
1554 fulldelete($backupbasepath);
1557 $errorinfo = '';
1559 foreach ($precheckresults['errors'] as $error) {
1560 $errorinfo .= $error;
1563 if (array_key_exists('warnings', $precheckresults)) {
1564 foreach ($precheckresults['warnings'] as $warning) {
1565 $errorinfo .= $warning;
1569 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1573 $rc->execute_plan();
1574 $rc->destroy();
1576 $course = $DB->get_record('course', array('id' => $newcourseid), '*', MUST_EXIST);
1577 $course->fullname = $params['fullname'];
1578 $course->shortname = $params['shortname'];
1579 $course->visible = $params['visible'];
1581 // Set shortname and fullname back.
1582 $DB->update_record('course', $course);
1584 if (empty($CFG->keeptempdirectoriesonbackup)) {
1585 fulldelete($backupbasepath);
1588 // Delete the course backup file created by this WebService. Originally located in the course backups area.
1589 $file->delete();
1591 return array('id' => $course->id, 'shortname' => $course->shortname);
1595 * Returns description of method result value
1597 * @return \core_external\external_description
1598 * @since Moodle 2.3
1600 public static function duplicate_course_returns() {
1601 return new external_single_structure(
1602 array(
1603 'id' => new external_value(PARAM_INT, 'course id'),
1604 'shortname' => new external_value(PARAM_RAW, 'short name'),
1610 * Returns description of method parameters for import_course
1612 * @return external_function_parameters
1613 * @since Moodle 2.4
1615 public static function import_course_parameters() {
1616 return new external_function_parameters(
1617 array(
1618 'importfrom' => new external_value(PARAM_INT, 'the id of the course we are importing from'),
1619 'importto' => new external_value(PARAM_INT, 'the id of the course we are importing to'),
1620 'deletecontent' => new external_value(PARAM_INT, 'whether to delete the course content where we are importing to (default to 0 = No)', VALUE_DEFAULT, 0),
1621 'options' => new external_multiple_structure(
1622 new external_single_structure(
1623 array(
1624 'name' => new external_value(PARAM_ALPHA, 'The backup option name:
1625 "activities" (int) Include course activites (default to 1 that is equal to yes),
1626 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1627 "filters" (int) Include course filters (default to 1 that is equal to yes)'
1629 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1632 ), 'Course import options', VALUE_DEFAULT, array()
1639 * Imports a course
1641 * @param int $importfrom The id of the course we are importing from
1642 * @param int $importto The id of the course we are importing to
1643 * @param bool $deletecontent Whether to delete the course we are importing to content
1644 * @param array $options List of backup options
1645 * @return null
1646 * @since Moodle 2.4
1648 public static function import_course($importfrom, $importto, $deletecontent = 0, $options = array()) {
1649 global $CFG, $USER, $DB;
1650 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1651 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1653 // Parameter validation.
1654 $params = self::validate_parameters(
1655 self::import_course_parameters(),
1656 array(
1657 'importfrom' => $importfrom,
1658 'importto' => $importto,
1659 'deletecontent' => $deletecontent,
1660 'options' => $options
1664 if ($params['deletecontent'] !== 0 and $params['deletecontent'] !== 1) {
1665 throw new moodle_exception('invalidextparam', 'webservice', '', $params['deletecontent']);
1668 // Context validation.
1670 if (! ($importfrom = $DB->get_record('course', array('id'=>$params['importfrom'])))) {
1671 throw new moodle_exception('invalidcourseid', 'error');
1674 if (! ($importto = $DB->get_record('course', array('id'=>$params['importto'])))) {
1675 throw new moodle_exception('invalidcourseid', 'error');
1678 $importfromcontext = context_course::instance($importfrom->id);
1679 self::validate_context($importfromcontext);
1681 $importtocontext = context_course::instance($importto->id);
1682 self::validate_context($importtocontext);
1684 $backupdefaults = array(
1685 'activities' => 1,
1686 'blocks' => 1,
1687 'filters' => 1
1690 $backupsettings = array();
1692 // Check for backup and restore options.
1693 if (!empty($params['options'])) {
1694 foreach ($params['options'] as $option) {
1696 // Strict check for a correct value (allways 1 or 0, true or false).
1697 $value = clean_param($option['value'], PARAM_INT);
1699 if ($value !== 0 and $value !== 1) {
1700 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1703 if (!isset($backupdefaults[$option['name']])) {
1704 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1707 $backupsettings[$option['name']] = $value;
1711 // Capability checking.
1713 require_capability('moodle/backup:backuptargetimport', $importfromcontext);
1714 require_capability('moodle/restore:restoretargetimport', $importtocontext);
1716 $bc = new backup_controller(backup::TYPE_1COURSE, $importfrom->id, backup::FORMAT_MOODLE,
1717 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
1719 foreach ($backupsettings as $name => $value) {
1720 $bc->get_plan()->get_setting($name)->set_value($value);
1723 $backupid = $bc->get_backupid();
1724 $backupbasepath = $bc->get_plan()->get_basepath();
1726 $bc->execute_plan();
1727 $bc->destroy();
1729 // Restore the backup immediately.
1731 // Check if we must delete the contents of the destination course.
1732 if ($params['deletecontent']) {
1733 $restoretarget = backup::TARGET_EXISTING_DELETING;
1734 } else {
1735 $restoretarget = backup::TARGET_EXISTING_ADDING;
1738 $rc = new restore_controller($backupid, $importto->id,
1739 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, $restoretarget);
1741 foreach ($backupsettings as $name => $value) {
1742 $rc->get_plan()->get_setting($name)->set_value($value);
1745 if (!$rc->execute_precheck()) {
1746 $precheckresults = $rc->get_precheck_results();
1747 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1748 if (empty($CFG->keeptempdirectoriesonbackup)) {
1749 fulldelete($backupbasepath);
1752 $errorinfo = '';
1754 foreach ($precheckresults['errors'] as $error) {
1755 $errorinfo .= $error;
1758 if (array_key_exists('warnings', $precheckresults)) {
1759 foreach ($precheckresults['warnings'] as $warning) {
1760 $errorinfo .= $warning;
1764 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1766 } else {
1767 if ($restoretarget == backup::TARGET_EXISTING_DELETING) {
1768 restore_dbops::delete_course_content($importto->id);
1772 $rc->execute_plan();
1773 $rc->destroy();
1775 if (empty($CFG->keeptempdirectoriesonbackup)) {
1776 fulldelete($backupbasepath);
1779 return null;
1783 * Returns description of method result value
1785 * @return \core_external\external_description
1786 * @since Moodle 2.4
1788 public static function import_course_returns() {
1789 return null;
1793 * Returns description of method parameters
1795 * @return external_function_parameters
1796 * @since Moodle 2.3
1798 public static function get_categories_parameters() {
1799 return new external_function_parameters(
1800 array(
1801 'criteria' => new external_multiple_structure(
1802 new external_single_structure(
1803 array(
1804 'key' => new external_value(PARAM_ALPHA,
1805 'The category column to search, expected keys (value format) are:'.
1806 '"id" (int) the category id,'.
1807 '"ids" (string) category ids separated by commas,'.
1808 '"name" (string) the category name,'.
1809 '"parent" (int) the parent category id,'.
1810 '"idnumber" (string) category idnumber'.
1811 ' - user must have \'moodle/category:manage\' to search on idnumber,'.
1812 '"visible" (int) whether the returned categories must be visible or hidden. If the key is not passed,
1813 then the function return all categories that the user can see.'.
1814 ' - user must have \'moodle/category:manage\' or \'moodle/category:viewhiddencategories\' to search on visible,'.
1815 '"theme" (string) only return the categories having this theme'.
1816 ' - user must have \'moodle/category:manage\' to search on theme'),
1817 'value' => new external_value(PARAM_RAW, 'the value to match')
1819 ), 'criteria', VALUE_DEFAULT, array()
1821 'addsubcategories' => new external_value(PARAM_BOOL, 'return the sub categories infos
1822 (1 - default) otherwise only the category info (0)', VALUE_DEFAULT, 1)
1828 * Get categories
1830 * @param array $criteria Criteria to match the results
1831 * @param booln $addsubcategories obtain only the category (false) or its subcategories (true - default)
1832 * @return array list of categories
1833 * @since Moodle 2.3
1835 public static function get_categories($criteria = array(), $addsubcategories = true) {
1836 global $CFG, $DB;
1837 require_once($CFG->dirroot . "/course/lib.php");
1839 // Validate parameters.
1840 $params = self::validate_parameters(self::get_categories_parameters(),
1841 array('criteria' => $criteria, 'addsubcategories' => $addsubcategories));
1843 // Retrieve the categories.
1844 $categories = array();
1845 if (!empty($params['criteria'])) {
1847 $conditions = array();
1848 $wheres = array();
1849 foreach ($params['criteria'] as $crit) {
1850 $key = trim($crit['key']);
1852 // Trying to avoid duplicate keys.
1853 if (!isset($conditions[$key])) {
1855 $context = context_system::instance();
1856 $value = null;
1857 switch ($key) {
1858 case 'id':
1859 $value = clean_param($crit['value'], PARAM_INT);
1860 $conditions[$key] = $value;
1861 $wheres[] = $key . " = :" . $key;
1862 break;
1864 case 'ids':
1865 $value = clean_param($crit['value'], PARAM_SEQUENCE);
1866 $ids = explode(',', $value);
1867 list($sqlids, $paramids) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED);
1868 $conditions = array_merge($conditions, $paramids);
1869 $wheres[] = 'id ' . $sqlids;
1870 break;
1872 case 'idnumber':
1873 if (has_capability('moodle/category:manage', $context)) {
1874 $value = clean_param($crit['value'], PARAM_RAW);
1875 $conditions[$key] = $value;
1876 $wheres[] = $key . " = :" . $key;
1877 } else {
1878 // We must throw an exception.
1879 // Otherwise the dev client would think no idnumber exists.
1880 throw new moodle_exception('criteriaerror',
1881 'webservice', '', null,
1882 'You don\'t have the permissions to search on the "idnumber" field.');
1884 break;
1886 case 'name':
1887 $value = clean_param($crit['value'], PARAM_TEXT);
1888 $conditions[$key] = $value;
1889 $wheres[] = $key . " = :" . $key;
1890 break;
1892 case 'parent':
1893 $value = clean_param($crit['value'], PARAM_INT);
1894 $conditions[$key] = $value;
1895 $wheres[] = $key . " = :" . $key;
1896 break;
1898 case 'visible':
1899 if (has_capability('moodle/category:viewhiddencategories', $context)) {
1900 $value = clean_param($crit['value'], PARAM_INT);
1901 $conditions[$key] = $value;
1902 $wheres[] = $key . " = :" . $key;
1903 } else {
1904 throw new moodle_exception('criteriaerror',
1905 'webservice', '', null,
1906 'You don\'t have the permissions to search on the "visible" field.');
1908 break;
1910 case 'theme':
1911 if (has_capability('moodle/category:manage', $context)) {
1912 $value = clean_param($crit['value'], PARAM_THEME);
1913 $conditions[$key] = $value;
1914 $wheres[] = $key . " = :" . $key;
1915 } else {
1916 throw new moodle_exception('criteriaerror',
1917 'webservice', '', null,
1918 'You don\'t have the permissions to search on the "theme" field.');
1920 break;
1922 default:
1923 throw new moodle_exception('criteriaerror',
1924 'webservice', '', null,
1925 'You can not search on this criteria: ' . $key);
1930 if (!empty($wheres)) {
1931 $wheres = implode(" AND ", $wheres);
1933 $categories = $DB->get_records_select('course_categories', $wheres, $conditions);
1935 // Retrieve its sub subcategories (all levels).
1936 if ($categories and !empty($params['addsubcategories'])) {
1937 $newcategories = array();
1939 // Check if we required visible/theme checks.
1940 $additionalselect = '';
1941 $additionalparams = array();
1942 if (isset($conditions['visible'])) {
1943 $additionalselect .= ' AND visible = :visible';
1944 $additionalparams['visible'] = $conditions['visible'];
1946 if (isset($conditions['theme'])) {
1947 $additionalselect .= ' AND theme= :theme';
1948 $additionalparams['theme'] = $conditions['theme'];
1951 foreach ($categories as $category) {
1952 $sqlselect = $DB->sql_like('path', ':path') . $additionalselect;
1953 $sqlparams = array('path' => $category->path.'/%') + $additionalparams; // It will NOT include the specified category.
1954 $subcategories = $DB->get_records_select('course_categories', $sqlselect, $sqlparams);
1955 $newcategories = $newcategories + $subcategories; // Both arrays have integer as keys.
1957 $categories = $categories + $newcategories;
1961 } else {
1962 // Retrieve all categories in the database.
1963 $categories = $DB->get_records('course_categories');
1966 // The not returned categories. key => category id, value => reason of exclusion.
1967 $excludedcats = array();
1969 // The returned categories.
1970 $categoriesinfo = array();
1972 // We need to sort the categories by path.
1973 // The parent cats need to be checked by the algo first.
1974 usort($categories, "core_course_external::compare_categories_by_path");
1976 foreach ($categories as $category) {
1978 // Check if the category is a child of an excluded category, if yes exclude it too (excluded => do not return).
1979 $parents = explode('/', $category->path);
1980 unset($parents[0]); // First key is always empty because path start with / => /1/2/4.
1981 foreach ($parents as $parentid) {
1982 // Note: when the parent exclusion was due to the context,
1983 // the sub category could still be returned.
1984 if (isset($excludedcats[$parentid]) and $excludedcats[$parentid] != 'context') {
1985 $excludedcats[$category->id] = 'parent';
1989 // Check the user can use the category context.
1990 $context = context_coursecat::instance($category->id);
1991 try {
1992 self::validate_context($context);
1993 } catch (Exception $e) {
1994 $excludedcats[$category->id] = 'context';
1996 // If it was the requested category then throw an exception.
1997 if (isset($params['categoryid']) && $category->id == $params['categoryid']) {
1998 $exceptionparam = new stdClass();
1999 $exceptionparam->message = $e->getMessage();
2000 $exceptionparam->catid = $category->id;
2001 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
2005 // Return the category information.
2006 if (!isset($excludedcats[$category->id])) {
2008 // Final check to see if the category is visible to the user.
2009 if (core_course_category::can_view_category($category)) {
2011 $categoryinfo = array();
2012 $categoryinfo['id'] = $category->id;
2013 $categoryinfo['name'] = \core_external\util::format_string($category->name, $context);
2014 list($categoryinfo['description'], $categoryinfo['descriptionformat']) =
2015 \core_external\util::format_text($category->description, $category->descriptionformat,
2016 $context, 'coursecat', 'description', null);
2017 $categoryinfo['parent'] = $category->parent;
2018 $categoryinfo['sortorder'] = $category->sortorder;
2019 $categoryinfo['coursecount'] = $category->coursecount;
2020 $categoryinfo['depth'] = $category->depth;
2021 $categoryinfo['path'] = $category->path;
2023 // Some fields only returned for admin.
2024 if (has_capability('moodle/category:manage', $context)) {
2025 $categoryinfo['idnumber'] = $category->idnumber;
2026 $categoryinfo['visible'] = $category->visible;
2027 $categoryinfo['visibleold'] = $category->visibleold;
2028 $categoryinfo['timemodified'] = $category->timemodified;
2029 $categoryinfo['theme'] = clean_param($category->theme, PARAM_THEME);
2032 $categoriesinfo[] = $categoryinfo;
2033 } else {
2034 $excludedcats[$category->id] = 'visibility';
2039 // Sorting the resulting array so it looks a bit better for the client developer.
2040 usort($categoriesinfo, "core_course_external::compare_categories_by_sortorder");
2042 return $categoriesinfo;
2046 * Sort categories array by path
2047 * private function: only used by get_categories
2049 * @param stdClass $category1
2050 * @param stdClass $category2
2051 * @return int result of strcmp
2052 * @since Moodle 2.3
2054 private static function compare_categories_by_path($category1, $category2) {
2055 return strcmp($category1->path, $category2->path);
2059 * Sort categories array by sortorder
2060 * private function: only used by get_categories
2062 * @param array $category1
2063 * @param array $category2
2064 * @return int result of strcmp
2065 * @since Moodle 2.3
2067 private static function compare_categories_by_sortorder($category1, $category2) {
2068 return strcmp($category1['sortorder'], $category2['sortorder']);
2072 * Returns description of method result value
2074 * @return \core_external\external_description
2075 * @since Moodle 2.3
2077 public static function get_categories_returns() {
2078 return new external_multiple_structure(
2079 new external_single_structure(
2080 array(
2081 'id' => new external_value(PARAM_INT, 'category id'),
2082 'name' => new external_value(PARAM_RAW, 'category name'),
2083 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
2084 'description' => new external_value(PARAM_RAW, 'category description'),
2085 'descriptionformat' => new external_format_value('description'),
2086 'parent' => new external_value(PARAM_INT, 'parent category id'),
2087 'sortorder' => new external_value(PARAM_INT, 'category sorting order'),
2088 'coursecount' => new external_value(PARAM_INT, 'number of courses in this category'),
2089 'visible' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
2090 'visibleold' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
2091 'timemodified' => new external_value(PARAM_INT, 'timestamp', VALUE_OPTIONAL),
2092 'depth' => new external_value(PARAM_INT, 'category depth'),
2093 'path' => new external_value(PARAM_TEXT, 'category path'),
2094 'theme' => new external_value(PARAM_THEME, 'category theme', VALUE_OPTIONAL),
2095 ), 'List of categories'
2101 * Returns description of method parameters
2103 * @return external_function_parameters
2104 * @since Moodle 2.3
2106 public static function create_categories_parameters() {
2107 return new external_function_parameters(
2108 array(
2109 'categories' => new external_multiple_structure(
2110 new external_single_structure(
2111 array(
2112 'name' => new external_value(PARAM_TEXT, 'new category name'),
2113 'parent' => new external_value(PARAM_INT,
2114 'the parent category id inside which the new category will be created
2115 - set to 0 for a root category',
2116 VALUE_DEFAULT, 0),
2117 'idnumber' => new external_value(PARAM_RAW,
2118 'the new category idnumber', VALUE_OPTIONAL),
2119 'description' => new external_value(PARAM_RAW,
2120 'the new category description', VALUE_OPTIONAL),
2121 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
2122 'theme' => new external_value(PARAM_THEME,
2123 'the new category theme. This option must be enabled on moodle',
2124 VALUE_OPTIONAL),
2133 * Create categories
2135 * @param array $categories - see create_categories_parameters() for the array structure
2136 * @return array - see create_categories_returns() for the array structure
2137 * @since Moodle 2.3
2139 public static function create_categories($categories) {
2140 global $DB;
2142 $params = self::validate_parameters(self::create_categories_parameters(),
2143 array('categories' => $categories));
2145 $transaction = $DB->start_delegated_transaction();
2147 $createdcategories = array();
2148 foreach ($params['categories'] as $category) {
2149 if ($category['parent']) {
2150 if (!$DB->record_exists('course_categories', array('id' => $category['parent']))) {
2151 throw new moodle_exception('unknowcategory');
2153 $context = context_coursecat::instance($category['parent']);
2154 } else {
2155 $context = context_system::instance();
2157 self::validate_context($context);
2158 require_capability('moodle/category:manage', $context);
2160 // this will validate format and throw an exception if there are errors
2161 util::validate_format($category['descriptionformat']);
2163 $newcategory = core_course_category::create($category);
2164 $context = context_coursecat::instance($newcategory->id);
2166 $createdcategories[] = array(
2167 'id' => $newcategory->id,
2168 'name' => \core_external\util::format_string($newcategory->name, $context),
2172 $transaction->allow_commit();
2174 return $createdcategories;
2178 * Returns description of method parameters
2180 * @return external_function_parameters
2181 * @since Moodle 2.3
2183 public static function create_categories_returns() {
2184 return new external_multiple_structure(
2185 new external_single_structure(
2186 array(
2187 'id' => new external_value(PARAM_INT, 'new category id'),
2188 'name' => new external_value(PARAM_RAW, 'new category name'),
2195 * Returns description of method parameters
2197 * @return external_function_parameters
2198 * @since Moodle 2.3
2200 public static function update_categories_parameters() {
2201 return new external_function_parameters(
2202 array(
2203 'categories' => new external_multiple_structure(
2204 new external_single_structure(
2205 array(
2206 'id' => new external_value(PARAM_INT, 'course id'),
2207 'name' => new external_value(PARAM_TEXT, 'category name', VALUE_OPTIONAL),
2208 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
2209 'parent' => new external_value(PARAM_INT, 'parent category id', VALUE_OPTIONAL),
2210 'description' => new external_value(PARAM_RAW, 'category description', VALUE_OPTIONAL),
2211 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
2212 'theme' => new external_value(PARAM_THEME,
2213 'the category theme. This option must be enabled on moodle', VALUE_OPTIONAL),
2222 * Update categories
2224 * @param array $categories The list of categories to update
2225 * @return null
2226 * @since Moodle 2.3
2228 public static function update_categories($categories) {
2229 global $DB;
2231 // Validate parameters.
2232 $params = self::validate_parameters(self::update_categories_parameters(), array('categories' => $categories));
2234 $transaction = $DB->start_delegated_transaction();
2236 foreach ($params['categories'] as $cat) {
2237 $category = core_course_category::get($cat['id']);
2239 $categorycontext = context_coursecat::instance($cat['id']);
2240 self::validate_context($categorycontext);
2241 require_capability('moodle/category:manage', $categorycontext);
2243 // If the category parent is being changed, check for capability in the new parent category
2244 if (isset($cat['parent']) && ($cat['parent'] !== $category->parent)) {
2245 if ($cat['parent'] == 0) {
2246 // Creating a top level category requires capability in the system context
2247 $parentcontext = context_system::instance();
2248 } else {
2249 // Category context
2250 $parentcontext = context_coursecat::instance($cat['parent']);
2252 self::validate_context($parentcontext);
2253 require_capability('moodle/category:manage', $parentcontext);
2256 // this will throw an exception if descriptionformat is not valid
2257 util::validate_format($cat['descriptionformat']);
2259 $category->update($cat);
2262 $transaction->allow_commit();
2266 * Returns description of method result value
2268 * @return \core_external\external_description
2269 * @since Moodle 2.3
2271 public static function update_categories_returns() {
2272 return null;
2276 * Returns description of method parameters
2278 * @return external_function_parameters
2279 * @since Moodle 2.3
2281 public static function delete_categories_parameters() {
2282 return new external_function_parameters(
2283 array(
2284 'categories' => new external_multiple_structure(
2285 new external_single_structure(
2286 array(
2287 'id' => new external_value(PARAM_INT, 'category id to delete'),
2288 'newparent' => new external_value(PARAM_INT,
2289 'the parent category to move the contents to, if specified', VALUE_OPTIONAL),
2290 'recursive' => new external_value(PARAM_BOOL, '1: recursively delete all contents inside this
2291 category, 0 (default): move contents to newparent or current parent category (except if parent is root)', VALUE_DEFAULT, 0)
2300 * Delete categories
2302 * @param array $categories A list of category ids
2303 * @return array
2304 * @since Moodle 2.3
2306 public static function delete_categories($categories) {
2307 global $CFG, $DB;
2308 require_once($CFG->dirroot . "/course/lib.php");
2310 // Validate parameters.
2311 $params = self::validate_parameters(self::delete_categories_parameters(), array('categories' => $categories));
2313 $transaction = $DB->start_delegated_transaction();
2315 foreach ($params['categories'] as $category) {
2316 $deletecat = core_course_category::get($category['id'], MUST_EXIST);
2317 $context = context_coursecat::instance($deletecat->id);
2318 require_capability('moodle/category:manage', $context);
2319 self::validate_context($context);
2320 self::validate_context(get_category_or_system_context($deletecat->parent));
2322 if ($category['recursive']) {
2323 // If recursive was specified, then we recursively delete the category's contents.
2324 if ($deletecat->can_delete_full()) {
2325 $deletecat->delete_full(false);
2326 } else {
2327 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2329 } else {
2330 // In this situation, we don't delete the category's contents, we either move it to newparent or parent.
2331 // If the parent is the root, moving is not supported (because a course must always be inside a category).
2332 // We must move to an existing category.
2333 if (!empty($category['newparent'])) {
2334 $newparentcat = core_course_category::get($category['newparent']);
2335 } else {
2336 $newparentcat = core_course_category::get($deletecat->parent);
2339 // This operation is not allowed. We must move contents to an existing category.
2340 if (!$newparentcat->id) {
2341 throw new moodle_exception('movecatcontentstoroot');
2344 self::validate_context(context_coursecat::instance($newparentcat->id));
2345 if ($deletecat->can_move_content_to($newparentcat->id)) {
2346 $deletecat->delete_move($newparentcat->id, false);
2347 } else {
2348 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2353 $transaction->allow_commit();
2357 * Returns description of method parameters
2359 * @return external_function_parameters
2360 * @since Moodle 2.3
2362 public static function delete_categories_returns() {
2363 return null;
2367 * Describes the parameters for delete_modules.
2369 * @return external_function_parameters
2370 * @since Moodle 2.5
2372 public static function delete_modules_parameters() {
2373 return new external_function_parameters (
2374 array(
2375 'cmids' => new external_multiple_structure(new external_value(PARAM_INT, 'course module ID',
2376 VALUE_REQUIRED, '', NULL_NOT_ALLOWED), 'Array of course module IDs'),
2382 * Deletes a list of provided module instances.
2384 * @param array $cmids the course module ids
2385 * @since Moodle 2.5
2387 public static function delete_modules($cmids) {
2388 global $CFG, $DB;
2390 // Require course file containing the course delete module function.
2391 require_once($CFG->dirroot . "/course/lib.php");
2393 // Clean the parameters.
2394 $params = self::validate_parameters(self::delete_modules_parameters(), array('cmids' => $cmids));
2396 // Keep track of the course ids we have performed a capability check on to avoid repeating.
2397 $arrcourseschecked = array();
2399 foreach ($params['cmids'] as $cmid) {
2400 // Get the course module.
2401 $cm = $DB->get_record('course_modules', array('id' => $cmid), '*', MUST_EXIST);
2403 // Check if we have not yet confirmed they have permission in this course.
2404 if (!in_array($cm->course, $arrcourseschecked)) {
2405 // Ensure the current user has required permission in this course.
2406 $context = context_course::instance($cm->course);
2407 self::validate_context($context);
2408 // Add to the array.
2409 $arrcourseschecked[] = $cm->course;
2412 // Ensure they can delete this module.
2413 $modcontext = context_module::instance($cm->id);
2414 require_capability('moodle/course:manageactivities', $modcontext);
2416 // Delete the module.
2417 course_delete_module($cm->id);
2422 * Describes the delete_modules return value.
2424 * @return external_single_structure
2425 * @since Moodle 2.5
2427 public static function delete_modules_returns() {
2428 return null;
2432 * Returns description of method parameters
2434 * @return external_function_parameters
2435 * @since Moodle 2.9
2437 public static function view_course_parameters() {
2438 return new external_function_parameters(
2439 array(
2440 'courseid' => new external_value(PARAM_INT, 'id of the course'),
2441 'sectionnumber' => new external_value(PARAM_INT, 'section number', VALUE_DEFAULT, 0)
2447 * Trigger the course viewed event.
2449 * @param int $courseid id of course
2450 * @param int $sectionnumber sectionnumber (0, 1, 2...)
2451 * @return array of warnings and status result
2452 * @since Moodle 2.9
2453 * @throws moodle_exception
2455 public static function view_course($courseid, $sectionnumber = 0) {
2456 global $CFG;
2457 require_once($CFG->dirroot . "/course/lib.php");
2459 $params = self::validate_parameters(self::view_course_parameters(),
2460 array(
2461 'courseid' => $courseid,
2462 'sectionnumber' => $sectionnumber
2465 $warnings = array();
2467 $course = get_course($params['courseid']);
2468 $context = context_course::instance($course->id);
2469 self::validate_context($context);
2471 if (!empty($params['sectionnumber'])) {
2473 // Get section details and check it exists.
2474 $modinfo = get_fast_modinfo($course);
2475 $coursesection = $modinfo->get_section_info($params['sectionnumber'], MUST_EXIST);
2477 // Check user is allowed to see it.
2478 if (!$coursesection->uservisible) {
2479 require_capability('moodle/course:viewhiddensections', $context);
2483 course_view($context, $params['sectionnumber']);
2485 $result = array();
2486 $result['status'] = true;
2487 $result['warnings'] = $warnings;
2488 return $result;
2492 * Returns description of method result value
2494 * @return \core_external\external_description
2495 * @since Moodle 2.9
2497 public static function view_course_returns() {
2498 return new external_single_structure(
2499 array(
2500 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
2501 'warnings' => new external_warnings()
2507 * Returns description of method parameters
2509 * @return external_function_parameters
2510 * @since Moodle 3.0
2512 public static function search_courses_parameters() {
2513 return new external_function_parameters(
2514 array(
2515 'criterianame' => new external_value(PARAM_ALPHA, 'criteria name
2516 (search, modulelist (only admins), blocklist (only admins), tagid)'),
2517 'criteriavalue' => new external_value(PARAM_RAW, 'criteria value'),
2518 'page' => new external_value(PARAM_INT, 'page number (0 based)', VALUE_DEFAULT, 0),
2519 'perpage' => new external_value(PARAM_INT, 'items per page', VALUE_DEFAULT, 0),
2520 'requiredcapabilities' => new external_multiple_structure(
2521 new external_value(PARAM_CAPABILITY, 'Capability string used to filter courses by permission'),
2522 'Optional list of required capabilities (used to filter the list)', VALUE_DEFAULT, array()
2524 'limittoenrolled' => new external_value(PARAM_BOOL, 'limit to enrolled courses', VALUE_DEFAULT, 0),
2525 'onlywithcompletion' => new external_value(PARAM_BOOL, 'limit to courses where completion is enabled',
2526 VALUE_DEFAULT, 0),
2532 * Return the course information that is public (visible by every one)
2534 * @param core_course_list_element $course course in list object
2535 * @param stdClass $coursecontext course context object
2536 * @return array the course information
2537 * @since Moodle 3.2
2539 protected static function get_course_public_information(core_course_list_element $course, $coursecontext) {
2540 global $OUTPUT;
2542 static $categoriescache = array();
2544 // Category information.
2545 if (!array_key_exists($course->category, $categoriescache)) {
2546 $categoriescache[$course->category] = core_course_category::get($course->category, IGNORE_MISSING);
2548 $category = $categoriescache[$course->category];
2550 // Retrieve course overview used files.
2551 $files = array();
2552 foreach ($course->get_course_overviewfiles() as $file) {
2553 $fileurl = moodle_url::make_webservice_pluginfile_url($file->get_contextid(), $file->get_component(),
2554 $file->get_filearea(), null, $file->get_filepath(),
2555 $file->get_filename())->out(false);
2556 $files[] = array(
2557 'filename' => $file->get_filename(),
2558 'fileurl' => $fileurl,
2559 'filesize' => $file->get_filesize(),
2560 'filepath' => $file->get_filepath(),
2561 'mimetype' => $file->get_mimetype(),
2562 'timemodified' => $file->get_timemodified(),
2566 // Retrieve the course contacts,
2567 // we need here the users fullname since if we are not enrolled can be difficult to obtain them via other Web Services.
2568 $coursecontacts = array();
2569 foreach ($course->get_course_contacts() as $contact) {
2570 $coursecontacts[] = array(
2571 'id' => $contact['user']->id,
2572 'fullname' => $contact['username'],
2573 'roles' => array_map(function($role){
2574 return array('id' => $role->id, 'name' => $role->displayname);
2575 }, $contact['roles']),
2576 'role' => array('id' => $contact['role']->id, 'name' => $contact['role']->displayname),
2577 'rolename' => $contact['rolename']
2581 // Allowed enrolment methods (maybe we can self-enrol).
2582 $enroltypes = array();
2583 $instances = enrol_get_instances($course->id, true);
2584 foreach ($instances as $instance) {
2585 $enroltypes[] = $instance->enrol;
2588 // Format summary.
2589 list($summary, $summaryformat) =
2590 \core_external\util::format_text($course->summary, $course->summaryformat, $coursecontext, 'course', 'summary', null);
2592 $categoryname = '';
2593 if (!empty($category)) {
2594 $categoryname = \core_external\util::format_string($category->name, $category->get_context());
2597 $displayname = get_course_display_name_for_list($course);
2598 $coursereturns = array();
2599 $coursereturns['id'] = $course->id;
2600 $coursereturns['fullname'] = \core_external\util::format_string($course->fullname, $coursecontext);
2601 $coursereturns['displayname'] = \core_external\util::format_string($displayname, $coursecontext);
2602 $coursereturns['shortname'] = \core_external\util::format_string($course->shortname, $coursecontext);
2603 $coursereturns['categoryid'] = $course->category;
2604 $coursereturns['categoryname'] = $categoryname;
2605 $coursereturns['summary'] = $summary;
2606 $coursereturns['summaryformat'] = $summaryformat;
2607 $coursereturns['summaryfiles'] = util::get_area_files($coursecontext->id, 'course', 'summary', false, false);
2608 $coursereturns['overviewfiles'] = $files;
2609 $coursereturns['contacts'] = $coursecontacts;
2610 $coursereturns['enrollmentmethods'] = $enroltypes;
2611 $coursereturns['sortorder'] = $course->sortorder;
2612 $coursereturns['showactivitydates'] = $course->showactivitydates;
2613 $coursereturns['showcompletionconditions'] = $course->showcompletionconditions;
2615 $handler = core_course\customfield\course_handler::create();
2616 if ($customfields = $handler->export_instance_data($course->id)) {
2617 $coursereturns['customfields'] = [];
2618 foreach ($customfields as $data) {
2619 $coursereturns['customfields'][] = [
2620 'type' => $data->get_type(),
2621 'value' => $data->get_value(),
2622 'valueraw' => $data->get_data_controller()->get_value(),
2623 'name' => $data->get_name(),
2624 'shortname' => $data->get_shortname()
2629 $courseimage = \core_course\external\course_summary_exporter::get_course_image($course);
2630 if (!$courseimage) {
2631 $courseimage = $OUTPUT->get_generated_url_for_course($coursecontext);
2633 $coursereturns['courseimage'] = $courseimage;
2635 return $coursereturns;
2639 * Search courses following the specified criteria.
2641 * @param string $criterianame Criteria name (search, modulelist (only admins), blocklist (only admins), tagid)
2642 * @param string $criteriavalue Criteria value
2643 * @param int $page Page number (for pagination)
2644 * @param int $perpage Items per page
2645 * @param array $requiredcapabilities Optional list of required capabilities (used to filter the list).
2646 * @param int $limittoenrolled Limit to only enrolled courses
2647 * @param int onlywithcompletion Limit to only courses where completion is enabled
2648 * @return array of course objects and warnings
2649 * @since Moodle 3.0
2650 * @throws moodle_exception
2652 public static function search_courses($criterianame,
2653 $criteriavalue,
2654 $page=0,
2655 $perpage=0,
2656 $requiredcapabilities=array(),
2657 $limittoenrolled=0,
2658 $onlywithcompletion=0) {
2659 global $CFG;
2661 $warnings = array();
2663 $parameters = array(
2664 'criterianame' => $criterianame,
2665 'criteriavalue' => $criteriavalue,
2666 'page' => $page,
2667 'perpage' => $perpage,
2668 'requiredcapabilities' => $requiredcapabilities,
2669 'limittoenrolled' => $limittoenrolled,
2670 'onlywithcompletion' => $onlywithcompletion
2672 $params = self::validate_parameters(self::search_courses_parameters(), $parameters);
2673 self::validate_context(context_system::instance());
2675 $allowedcriterianames = array('search', 'modulelist', 'blocklist', 'tagid');
2676 if (!in_array($params['criterianame'], $allowedcriterianames)) {
2677 throw new invalid_parameter_exception('Invalid value for criterianame parameter (value: '.$params['criterianame'].'),' .
2678 'allowed values are: '.implode(',', $allowedcriterianames));
2681 if ($params['criterianame'] == 'modulelist' or $params['criterianame'] == 'blocklist') {
2682 require_capability('moodle/site:config', context_system::instance());
2685 $paramtype = array(
2686 'search' => PARAM_RAW,
2687 'modulelist' => PARAM_PLUGIN,
2688 'blocklist' => PARAM_INT,
2689 'tagid' => PARAM_INT
2691 $params['criteriavalue'] = clean_param($params['criteriavalue'], $paramtype[$params['criterianame']]);
2693 // Prepare the search API options.
2694 $searchcriteria = array();
2695 $searchcriteria[$params['criterianame']] = $params['criteriavalue'];
2696 if ($params['onlywithcompletion']) {
2697 $searchcriteria['onlywithcompletion'] = true;
2699 if ($params['limittoenrolled']) {
2700 $searchcriteria['limittoenrolled'] = true;
2703 $options = array();
2704 if ($params['perpage'] != 0) {
2705 $offset = $params['page'] * $params['perpage'];
2706 $options = array('offset' => $offset, 'limit' => $params['perpage']);
2709 // Search the courses.
2710 $courses = core_course_category::search_courses($searchcriteria, $options, $params['requiredcapabilities']);
2711 $totalcount = core_course_category::search_courses_count($searchcriteria, $options, $params['requiredcapabilities']);
2713 $finalcourses = array();
2714 $categoriescache = array();
2716 foreach ($courses as $course) {
2717 $coursecontext = context_course::instance($course->id);
2719 $finalcourses[] = self::get_course_public_information($course, $coursecontext);
2722 return array(
2723 'total' => $totalcount,
2724 'courses' => $finalcourses,
2725 'warnings' => $warnings
2730 * Returns a course structure definition
2732 * @param boolean $onlypublicdata set to true, to retrieve only fields viewable by anyone when the course is visible
2733 * @return external_single_structure the course structure
2734 * @since Moodle 3.2
2736 protected static function get_course_structure($onlypublicdata = true) {
2737 $coursestructure = array(
2738 'id' => new external_value(PARAM_INT, 'course id'),
2739 'fullname' => new external_value(PARAM_RAW, 'course full name'),
2740 'displayname' => new external_value(PARAM_RAW, 'course display name'),
2741 'shortname' => new external_value(PARAM_RAW, 'course short name'),
2742 'courseimage' => new external_value(PARAM_URL, 'Course image', VALUE_OPTIONAL),
2743 'categoryid' => new external_value(PARAM_INT, 'category id'),
2744 'categoryname' => new external_value(PARAM_RAW, 'category name'),
2745 'sortorder' => new external_value(PARAM_INT, 'Sort order in the category', VALUE_OPTIONAL),
2746 'summary' => new external_value(PARAM_RAW, 'summary'),
2747 'summaryformat' => new external_format_value('summary'),
2748 'summaryfiles' => new external_files('summary files in the summary field', VALUE_OPTIONAL),
2749 'overviewfiles' => new external_files('additional overview files attached to this course'),
2750 'showactivitydates' => new external_value(PARAM_BOOL, 'Whether the activity dates are shown or not'),
2751 'showcompletionconditions' => new external_value(PARAM_BOOL,
2752 'Whether the activity completion conditions are shown or not'),
2753 'contacts' => new external_multiple_structure(
2754 new external_single_structure(
2755 array(
2756 'id' => new external_value(PARAM_INT, 'contact user id'),
2757 'fullname' => new external_value(PARAM_NOTAGS, 'contact user fullname'),
2760 'contact users'
2762 'enrollmentmethods' => new external_multiple_structure(
2763 new external_value(PARAM_PLUGIN, 'enrollment method'),
2764 'enrollment methods list'
2766 'customfields' => new external_multiple_structure(
2767 new external_single_structure(
2768 array(
2769 'name' => new external_value(PARAM_RAW, 'The name of the custom field'),
2770 'shortname' => new external_value(PARAM_RAW,
2771 'The shortname of the custom field - to be able to build the field class in the code'),
2772 'type' => new external_value(PARAM_ALPHANUMEXT,
2773 'The type of the custom field - text field, checkbox...'),
2774 'valueraw' => new external_value(PARAM_RAW, 'The raw value of the custom field'),
2775 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
2777 ), 'Custom fields', VALUE_OPTIONAL),
2780 if (!$onlypublicdata) {
2781 $extra = array(
2782 'idnumber' => new external_value(PARAM_RAW, 'Id number', VALUE_OPTIONAL),
2783 'format' => new external_value(PARAM_PLUGIN, 'Course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
2784 'showgrades' => new external_value(PARAM_INT, '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
2785 'newsitems' => new external_value(PARAM_INT, 'Number of recent items appearing on the course page', VALUE_OPTIONAL),
2786 'startdate' => new external_value(PARAM_INT, 'Timestamp when the course start', VALUE_OPTIONAL),
2787 'enddate' => new external_value(PARAM_INT, 'Timestamp when the course end', VALUE_OPTIONAL),
2788 'maxbytes' => new external_value(PARAM_INT, 'Largest size of file that can be uploaded into', VALUE_OPTIONAL),
2789 'showreports' => new external_value(PARAM_INT, 'Are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
2790 'visible' => new external_value(PARAM_INT, '1: available to student, 0:not available', VALUE_OPTIONAL),
2791 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
2792 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
2793 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
2794 'enablecompletion' => new external_value(PARAM_INT, 'Completion enabled? 1: yes 0: no', VALUE_OPTIONAL),
2795 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
2796 'lang' => new external_value(PARAM_SAFEDIR, 'Forced course language', VALUE_OPTIONAL),
2797 'theme' => new external_value(PARAM_PLUGIN, 'Fame of the forced theme', VALUE_OPTIONAL),
2798 'marker' => new external_value(PARAM_INT, 'Current course marker', VALUE_OPTIONAL),
2799 'legacyfiles' => new external_value(PARAM_INT, 'If legacy files are enabled', VALUE_OPTIONAL),
2800 'calendartype' => new external_value(PARAM_PLUGIN, 'Calendar type', VALUE_OPTIONAL),
2801 'timecreated' => new external_value(PARAM_INT, 'Time when the course was created', VALUE_OPTIONAL),
2802 'timemodified' => new external_value(PARAM_INT, 'Last time the course was updated', VALUE_OPTIONAL),
2803 'requested' => new external_value(PARAM_INT, 'If is a requested course', VALUE_OPTIONAL),
2804 'cacherev' => new external_value(PARAM_INT, 'Cache revision number', VALUE_OPTIONAL),
2805 'filters' => new external_multiple_structure(
2806 new external_single_structure(
2807 array(
2808 'filter' => new external_value(PARAM_PLUGIN, 'Filter plugin name'),
2809 'localstate' => new external_value(PARAM_INT, 'Filter state: 1 for on, -1 for off, 0 if inherit'),
2810 'inheritedstate' => new external_value(PARAM_INT, '1 or 0 to use when localstate is set to inherit'),
2813 'Course filters', VALUE_OPTIONAL
2815 'courseformatoptions' => new external_multiple_structure(
2816 new external_single_structure(
2817 array(
2818 'name' => new external_value(PARAM_RAW, 'Course format option name.'),
2819 'value' => new external_value(PARAM_RAW, 'Course format option value.'),
2822 'Additional options for particular course format.', VALUE_OPTIONAL
2824 'communicationroomname' => new external_value(PARAM_TEXT, 'Communication tool room name.', VALUE_OPTIONAL),
2825 'communicationroomurl' => new external_value(PARAM_RAW, 'Communication tool room URL.', VALUE_OPTIONAL),
2827 $coursestructure = array_merge($coursestructure, $extra);
2829 return new external_single_structure($coursestructure);
2833 * Returns description of method result value
2835 * @return \core_external\external_description
2836 * @since Moodle 3.0
2838 public static function search_courses_returns() {
2839 return new external_single_structure(
2840 array(
2841 'total' => new external_value(PARAM_INT, 'total course count'),
2842 'courses' => new external_multiple_structure(self::get_course_structure(), 'course'),
2843 'warnings' => new external_warnings()
2849 * Returns description of method parameters
2851 * @return external_function_parameters
2852 * @since Moodle 3.0
2854 public static function get_course_module_parameters() {
2855 return new external_function_parameters(
2856 array(
2857 'cmid' => new external_value(PARAM_INT, 'The course module id')
2863 * Return information about a course module.
2865 * @param int $cmid the course module id
2866 * @return array of warnings and the course module
2867 * @since Moodle 3.0
2868 * @throws moodle_exception
2870 public static function get_course_module($cmid) {
2871 global $CFG, $DB;
2873 $params = self::validate_parameters(self::get_course_module_parameters(), array('cmid' => $cmid));
2874 $warnings = array();
2876 $cm = get_coursemodule_from_id(null, $params['cmid'], 0, true, MUST_EXIST);
2877 $context = context_module::instance($cm->id);
2878 self::validate_context($context);
2880 // If the user has permissions to manage the activity, return all the information.
2881 if (has_capability('moodle/course:manageactivities', $context)) {
2882 require_once($CFG->dirroot . '/course/modlib.php');
2883 require_once($CFG->libdir . '/gradelib.php');
2885 $info = $cm;
2886 // Get the extra information: grade, advanced grading and outcomes data.
2887 $course = get_course($cm->course);
2888 list($newcm, $newcontext, $module, $extrainfo, $cw) = get_moduleinfo_data($cm, $course);
2889 // Grades.
2890 $gradeinfo = array('grade', 'gradepass', 'gradecat');
2891 foreach ($gradeinfo as $gfield) {
2892 if (isset($extrainfo->{$gfield})) {
2893 $info->{$gfield} = $extrainfo->{$gfield};
2896 if (isset($extrainfo->grade) and $extrainfo->grade < 0) {
2897 $info->scale = $DB->get_field('scale', 'scale', array('id' => abs($extrainfo->grade)));
2899 // Advanced grading.
2900 if (isset($extrainfo->_advancedgradingdata)) {
2901 $info->advancedgrading = array();
2902 foreach ($extrainfo as $key => $val) {
2903 if (strpos($key, 'advancedgradingmethod_') === 0) {
2904 $info->advancedgrading[] = array(
2905 'area' => str_replace('advancedgradingmethod_', '', $key),
2906 'method' => $val
2911 // Outcomes.
2912 foreach ($extrainfo as $key => $val) {
2913 if (strpos($key, 'outcome_') === 0) {
2914 if (!isset($info->outcomes)) {
2915 $info->outcomes = array();
2917 $id = str_replace('outcome_', '', $key);
2918 $outcome = grade_outcome::fetch(array('id' => $id));
2919 $scaleitems = $outcome->load_scale();
2920 $info->outcomes[] = array(
2921 'id' => $id,
2922 'name' => \core_external\util::format_string($outcome->get_name(), $context),
2923 'scale' => $scaleitems->scale
2927 } else {
2928 // Return information is safe to show to any user.
2929 $info = new stdClass();
2930 $info->id = $cm->id;
2931 $info->course = $cm->course;
2932 $info->module = $cm->module;
2933 $info->modname = $cm->modname;
2934 $info->instance = $cm->instance;
2935 $info->section = $cm->section;
2936 $info->sectionnum = $cm->sectionnum;
2937 $info->groupmode = $cm->groupmode;
2938 $info->groupingid = $cm->groupingid;
2939 $info->completion = $cm->completion;
2940 $info->downloadcontent = $cm->downloadcontent;
2942 // Format name.
2943 $info->name = \core_external\util::format_string($cm->name, $context);
2944 $result = array();
2945 $result['cm'] = $info;
2946 $result['warnings'] = $warnings;
2947 return $result;
2951 * Returns description of method result value
2953 * @return \core_external\external_description
2954 * @since Moodle 3.0
2956 public static function get_course_module_returns() {
2957 return new external_single_structure(
2958 array(
2959 'cm' => new external_single_structure(
2960 array(
2961 'id' => new external_value(PARAM_INT, 'The course module id'),
2962 'course' => new external_value(PARAM_INT, 'The course id'),
2963 'module' => new external_value(PARAM_INT, 'The module type id'),
2964 'name' => new external_value(PARAM_RAW, 'The activity name'),
2965 'modname' => new external_value(PARAM_COMPONENT, 'The module component name (forum, assign, etc..)'),
2966 'instance' => new external_value(PARAM_INT, 'The activity instance id'),
2967 'section' => new external_value(PARAM_INT, 'The module section id'),
2968 'sectionnum' => new external_value(PARAM_INT, 'The module section number'),
2969 'groupmode' => new external_value(PARAM_INT, 'Group mode'),
2970 'groupingid' => new external_value(PARAM_INT, 'Grouping id'),
2971 'completion' => new external_value(PARAM_INT, 'If completion is enabled'),
2972 'idnumber' => new external_value(PARAM_RAW, 'Module id number', VALUE_OPTIONAL),
2973 'added' => new external_value(PARAM_INT, 'Time added', VALUE_OPTIONAL),
2974 'score' => new external_value(PARAM_INT, 'Score', VALUE_OPTIONAL),
2975 'indent' => new external_value(PARAM_INT, 'Indentation', VALUE_OPTIONAL),
2976 'visible' => new external_value(PARAM_INT, 'If visible', VALUE_OPTIONAL),
2977 'visibleoncoursepage' => new external_value(PARAM_INT, 'If visible on course page', VALUE_OPTIONAL),
2978 'visibleold' => new external_value(PARAM_INT, 'Visible old', VALUE_OPTIONAL),
2979 'completiongradeitemnumber' => new external_value(PARAM_INT, 'Completion grade item', VALUE_OPTIONAL),
2980 'completionpassgrade' => new external_value(PARAM_INT, 'Completion pass grade setting', VALUE_OPTIONAL),
2981 'completionview' => new external_value(PARAM_INT, 'Completion view setting', VALUE_OPTIONAL),
2982 'completionexpected' => new external_value(PARAM_INT, 'Completion time expected', VALUE_OPTIONAL),
2983 'showdescription' => new external_value(PARAM_INT, 'If the description is showed', VALUE_OPTIONAL),
2984 'downloadcontent' => new external_value(PARAM_INT, 'The download content value', VALUE_OPTIONAL),
2985 'availability' => new external_value(PARAM_RAW, 'Availability settings', VALUE_OPTIONAL),
2986 'grade' => new external_value(PARAM_FLOAT, 'Grade (max value or scale id)', VALUE_OPTIONAL),
2987 'scale' => new external_value(PARAM_TEXT, 'Scale items (if used)', VALUE_OPTIONAL),
2988 'gradepass' => new external_value(PARAM_RAW, 'Grade to pass (float)', VALUE_OPTIONAL),
2989 'gradecat' => new external_value(PARAM_INT, 'Grade category', VALUE_OPTIONAL),
2990 'advancedgrading' => new external_multiple_structure(
2991 new external_single_structure(
2992 array(
2993 'area' => new external_value(PARAM_AREA, 'Gradable area name'),
2994 'method' => new external_value(PARAM_COMPONENT, 'Grading method'),
2997 'Advanced grading settings', VALUE_OPTIONAL
2999 'outcomes' => new external_multiple_structure(
3000 new external_single_structure(
3001 array(
3002 'id' => new external_value(PARAM_ALPHANUMEXT, 'Outcome id'),
3003 'name' => new external_value(PARAM_RAW, 'Outcome full name'),
3004 'scale' => new external_value(PARAM_TEXT, 'Scale items')
3007 'Outcomes information', VALUE_OPTIONAL
3011 'warnings' => new external_warnings()
3017 * Returns description of method parameters
3019 * @return external_function_parameters
3020 * @since Moodle 3.0
3022 public static function get_course_module_by_instance_parameters() {
3023 return new external_function_parameters(
3024 array(
3025 'module' => new external_value(PARAM_COMPONENT, 'The module name'),
3026 'instance' => new external_value(PARAM_INT, 'The module instance id')
3032 * Return information about a course module.
3034 * @param string $module the module name
3035 * @param int $instance the activity instance id
3036 * @return array of warnings and the course module
3037 * @since Moodle 3.0
3038 * @throws moodle_exception
3040 public static function get_course_module_by_instance($module, $instance) {
3042 $params = self::validate_parameters(self::get_course_module_by_instance_parameters(),
3043 array(
3044 'module' => $module,
3045 'instance' => $instance,
3048 $warnings = array();
3049 $cm = get_coursemodule_from_instance($params['module'], $params['instance'], 0, false, MUST_EXIST);
3051 return self::get_course_module($cm->id);
3055 * Returns description of method result value
3057 * @return \core_external\external_description
3058 * @since Moodle 3.0
3060 public static function get_course_module_by_instance_returns() {
3061 return self::get_course_module_returns();
3065 * Returns description of method parameters
3067 * @return external_function_parameters
3068 * @since Moodle 3.2
3070 public static function get_user_navigation_options_parameters() {
3071 return new external_function_parameters(
3072 array(
3073 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
3079 * Return a list of navigation options in a set of courses that are avaialable or not for the current user.
3081 * @param array $courseids a list of course ids
3082 * @return array of warnings and the options availability
3083 * @since Moodle 3.2
3084 * @throws moodle_exception
3086 public static function get_user_navigation_options($courseids) {
3087 global $CFG;
3088 require_once($CFG->dirroot . '/course/lib.php');
3090 // Parameter validation.
3091 $params = self::validate_parameters(self::get_user_navigation_options_parameters(), array('courseids' => $courseids));
3092 $courseoptions = array();
3094 list($courses, $warnings) = util::validate_courses($params['courseids'], array(), true);
3096 if (!empty($courses)) {
3097 foreach ($courses as $course) {
3098 // Fix the context for the frontpage.
3099 if ($course->id == SITEID) {
3100 $course->context = context_system::instance();
3102 $navoptions = course_get_user_navigation_options($course->context, $course);
3103 $options = array();
3104 foreach ($navoptions as $name => $available) {
3105 $options[] = array(
3106 'name' => $name,
3107 'available' => $available,
3111 $courseoptions[] = array(
3112 'id' => $course->id,
3113 'options' => $options
3118 $result = array(
3119 'courses' => $courseoptions,
3120 'warnings' => $warnings
3122 return $result;
3126 * Returns description of method result value
3128 * @return \core_external\external_description
3129 * @since Moodle 3.2
3131 public static function get_user_navigation_options_returns() {
3132 return new external_single_structure(
3133 array(
3134 'courses' => new external_multiple_structure(
3135 new external_single_structure(
3136 array(
3137 'id' => new external_value(PARAM_INT, 'Course id'),
3138 'options' => new external_multiple_structure(
3139 new external_single_structure(
3140 array(
3141 'name' => new external_value(PARAM_ALPHANUMEXT, 'Option name'),
3142 'available' => new external_value(PARAM_BOOL, 'Whether the option is available or not'),
3147 ), 'List of courses'
3149 'warnings' => new external_warnings()
3155 * Returns description of method parameters
3157 * @return external_function_parameters
3158 * @since Moodle 3.2
3160 public static function get_user_administration_options_parameters() {
3161 return new external_function_parameters(
3162 array(
3163 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
3169 * Return a list of administration options in a set of courses that are available or not for the current user.
3171 * @param array $courseids a list of course ids
3172 * @return array of warnings and the options availability
3173 * @since Moodle 3.2
3174 * @throws moodle_exception
3176 public static function get_user_administration_options($courseids) {
3177 global $CFG;
3178 require_once($CFG->dirroot . '/course/lib.php');
3180 // Parameter validation.
3181 $params = self::validate_parameters(self::get_user_administration_options_parameters(), array('courseids' => $courseids));
3182 $courseoptions = array();
3184 list($courses, $warnings) = util::validate_courses($params['courseids'], array(), true);
3186 if (!empty($courses)) {
3187 foreach ($courses as $course) {
3188 $adminoptions = course_get_user_administration_options($course, $course->context);
3189 $options = array();
3190 foreach ($adminoptions as $name => $available) {
3191 $options[] = array(
3192 'name' => $name,
3193 'available' => $available,
3197 $courseoptions[] = array(
3198 'id' => $course->id,
3199 'options' => $options
3204 $result = array(
3205 'courses' => $courseoptions,
3206 'warnings' => $warnings
3208 return $result;
3212 * Returns description of method result value
3214 * @return \core_external\external_description
3215 * @since Moodle 3.2
3217 public static function get_user_administration_options_returns() {
3218 return self::get_user_navigation_options_returns();
3222 * Returns description of method parameters
3224 * @return external_function_parameters
3225 * @since Moodle 3.2
3227 public static function get_courses_by_field_parameters() {
3228 return new external_function_parameters(
3229 array(
3230 'field' => new external_value(PARAM_ALPHA, 'The field to search can be left empty for all courses or:
3231 id: course id
3232 ids: comma separated course ids
3233 shortname: course short name
3234 idnumber: course id number
3235 category: category id the course belongs to
3236 ', VALUE_DEFAULT, ''),
3237 'value' => new external_value(PARAM_RAW, 'The value to match', VALUE_DEFAULT, '')
3244 * Get courses matching a specific field (id/s, shortname, idnumber, category)
3246 * @param string $field field name to search, or empty for all courses
3247 * @param string $value value to search
3248 * @return array list of courses and warnings
3249 * @throws invalid_parameter_exception
3250 * @since Moodle 3.2
3252 public static function get_courses_by_field($field = '', $value = '') {
3253 global $DB, $CFG;
3254 require_once($CFG->dirroot . '/course/lib.php');
3255 require_once($CFG->libdir . '/filterlib.php');
3257 $params = self::validate_parameters(self::get_courses_by_field_parameters(),
3258 array(
3259 'field' => $field,
3260 'value' => $value,
3263 $warnings = array();
3265 if (empty($params['field'])) {
3266 $courses = $DB->get_records('course', null, 'id ASC');
3267 } else {
3268 switch ($params['field']) {
3269 case 'id':
3270 case 'category':
3271 $value = clean_param($params['value'], PARAM_INT);
3272 break;
3273 case 'ids':
3274 $value = clean_param($params['value'], PARAM_SEQUENCE);
3275 break;
3276 case 'shortname':
3277 $value = clean_param($params['value'], PARAM_TEXT);
3278 break;
3279 case 'idnumber':
3280 $value = clean_param($params['value'], PARAM_RAW);
3281 break;
3282 default:
3283 throw new invalid_parameter_exception('Invalid field name');
3286 if ($params['field'] === 'ids') {
3287 // Preload categories to avoid loading one at a time.
3288 $courseids = explode(',', $value);
3289 list ($listsql, $listparams) = $DB->get_in_or_equal($courseids);
3290 $categoryids = $DB->get_fieldset_sql("
3291 SELECT DISTINCT cc.id
3292 FROM {course} c
3293 JOIN {course_categories} cc ON cc.id = c.category
3294 WHERE c.id $listsql", $listparams);
3295 core_course_category::get_many($categoryids);
3297 // Load and validate all courses. This is called because it loads the courses
3298 // more efficiently.
3299 list ($courses, $warnings) = util::validate_courses($courseids, [],
3300 false, true);
3301 } else {
3302 $courses = $DB->get_records('course', array($params['field'] => $value), 'id ASC');
3306 $iscommapiavailable = \core_communication\api::is_available();
3308 $coursesdata = array();
3309 foreach ($courses as $course) {
3310 $context = context_course::instance($course->id);
3311 $canupdatecourse = has_capability('moodle/course:update', $context);
3312 $canviewhiddencourses = has_capability('moodle/course:viewhiddencourses', $context);
3314 // Check if the course is visible in the site for the user.
3315 if (!$course->visible and !$canviewhiddencourses and !$canupdatecourse) {
3316 continue;
3318 // Get the public course information, even if we are not enrolled.
3319 $courseinlist = new core_course_list_element($course);
3321 // Now, check if we have access to the course, unless it was already checked.
3322 try {
3323 if (empty($course->contextvalidated)) {
3324 self::validate_context($context);
3326 } catch (Exception $e) {
3327 // User can not access the course, check if they can see the public information about the course and return it.
3328 if (core_course_category::can_view_course_info($course)) {
3329 $coursesdata[$course->id] = self::get_course_public_information($courseinlist, $context);
3331 continue;
3333 $coursesdata[$course->id] = self::get_course_public_information($courseinlist, $context);
3334 // Return information for any user that can access the course.
3335 $coursefields = array('format', 'showgrades', 'newsitems', 'startdate', 'enddate', 'maxbytes', 'showreports', 'visible',
3336 'groupmode', 'groupmodeforce', 'defaultgroupingid', 'enablecompletion', 'completionnotify', 'lang', 'theme',
3337 'marker');
3339 // Course filters.
3340 $coursesdata[$course->id]['filters'] = filter_get_available_in_context($context);
3342 // Information for managers only.
3343 if ($canupdatecourse) {
3344 $managerfields = array('idnumber', 'legacyfiles', 'calendartype', 'timecreated', 'timemodified', 'requested',
3345 'cacherev');
3346 $coursefields = array_merge($coursefields, $managerfields);
3349 // Populate fields.
3350 foreach ($coursefields as $field) {
3351 $coursesdata[$course->id][$field] = $course->{$field};
3354 // Clean lang and auth fields for external functions (it may content uninstalled themes or language packs).
3355 if (isset($coursesdata[$course->id]['theme'])) {
3356 $coursesdata[$course->id]['theme'] = clean_param($coursesdata[$course->id]['theme'], PARAM_THEME);
3358 if (isset($coursesdata[$course->id]['lang'])) {
3359 $coursesdata[$course->id]['lang'] = clean_param($coursesdata[$course->id]['lang'], PARAM_LANG);
3362 $courseformatoptions = course_get_format($course)->get_config_for_external();
3363 foreach ($courseformatoptions as $key => $value) {
3364 $coursesdata[$course->id]['courseformatoptions'][] = array(
3365 'name' => $key,
3366 'value' => $value
3370 // Communication tools for the course.
3371 if ($iscommapiavailable) {
3372 $communication = \core_communication\api::load_by_instance(
3373 context: $context,
3374 component: 'core_course',
3375 instancetype: 'coursecommunication',
3376 instanceid: $course->id
3378 if ($communication->get_provider()) {
3379 $coursesdata[$course->id]['communicationroomname'] = \core_external\util::format_string($communication->get_room_name(), $context);
3380 // This will be usually an URL, however, it is better to consider that can be anything a plugin might return, this is why we will use PARAM_RAW.
3381 $coursesdata[$course->id]['communicationroomurl'] = $communication->get_communication_room_url();
3386 return array(
3387 'courses' => $coursesdata,
3388 'warnings' => $warnings
3393 * Returns description of method result value
3395 * @return \core_external\external_description
3396 * @since Moodle 3.2
3398 public static function get_courses_by_field_returns() {
3399 // Course structure, including not only public viewable fields.
3400 return new external_single_structure(
3401 array(
3402 'courses' => new external_multiple_structure(self::get_course_structure(false), 'Course'),
3403 'warnings' => new external_warnings()
3409 * Returns description of method parameters
3411 * @return external_function_parameters
3412 * @since Moodle 3.2
3414 public static function check_updates_parameters() {
3415 return new external_function_parameters(
3416 array(
3417 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3418 'tocheck' => new external_multiple_structure(
3419 new external_single_structure(
3420 array(
3421 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level for the file location.
3422 Only module supported right now.'),
3423 'id' => new external_value(PARAM_INT, 'Context instance id'),
3424 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3427 'Instances to check'
3429 'filter' => new external_multiple_structure(
3430 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3431 gradeitems, outcomes'),
3432 'Check only for updates in these areas', VALUE_DEFAULT, array()
3439 * Check if there is updates affecting the user for the given course and contexts.
3440 * Right now only modules are supported.
3441 * This WS calls mod_check_updates_since for each module to check if there is any update the user should we aware of.
3443 * @param int $courseid the list of modules to check
3444 * @param array $tocheck the list of modules to check
3445 * @param array $filter check only for updates in these areas
3446 * @return array list of updates and warnings
3447 * @throws moodle_exception
3448 * @since Moodle 3.2
3450 public static function check_updates($courseid, $tocheck, $filter = array()) {
3451 global $CFG, $DB;
3452 require_once($CFG->dirroot . "/course/lib.php");
3454 $params = self::validate_parameters(
3455 self::check_updates_parameters(),
3456 array(
3457 'courseid' => $courseid,
3458 'tocheck' => $tocheck,
3459 'filter' => $filter,
3463 $course = get_course($params['courseid']);
3464 $context = context_course::instance($course->id);
3465 self::validate_context($context);
3467 list($instances, $warnings) = course_check_updates($course, $params['tocheck'], $filter);
3469 $instancesformatted = array();
3470 foreach ($instances as $instance) {
3471 $updates = array();
3472 foreach ($instance['updates'] as $name => $data) {
3473 if (empty($data->updated)) {
3474 continue;
3476 $updatedata = array(
3477 'name' => $name,
3479 if (!empty($data->timeupdated)) {
3480 $updatedata['timeupdated'] = $data->timeupdated;
3482 if (!empty($data->itemids)) {
3483 $updatedata['itemids'] = $data->itemids;
3485 $updates[] = $updatedata;
3487 if (!empty($updates)) {
3488 $instancesformatted[] = array(
3489 'contextlevel' => $instance['contextlevel'],
3490 'id' => $instance['id'],
3491 'updates' => $updates
3496 return array(
3497 'instances' => $instancesformatted,
3498 'warnings' => $warnings
3503 * Returns description of method result value
3505 * @return \core_external\external_description
3506 * @since Moodle 3.2
3508 public static function check_updates_returns() {
3509 return new external_single_structure(
3510 array(
3511 'instances' => new external_multiple_structure(
3512 new external_single_structure(
3513 array(
3514 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level'),
3515 'id' => new external_value(PARAM_INT, 'Instance id'),
3516 'updates' => new external_multiple_structure(
3517 new external_single_structure(
3518 array(
3519 'name' => new external_value(PARAM_ALPHANUMEXT, 'Name of the area updated.'),
3520 'timeupdated' => new external_value(PARAM_INT, 'Last time was updated', VALUE_OPTIONAL),
3521 'itemids' => new external_multiple_structure(
3522 new external_value(PARAM_INT, 'Instance id'),
3523 'The ids of the items updated',
3524 VALUE_OPTIONAL
3532 'warnings' => new external_warnings()
3538 * Returns description of method parameters
3540 * @return external_function_parameters
3541 * @since Moodle 3.3
3543 public static function get_updates_since_parameters() {
3544 return new external_function_parameters(
3545 array(
3546 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3547 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3548 'filter' => new external_multiple_structure(
3549 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3550 gradeitems, outcomes'),
3551 'Check only for updates in these areas', VALUE_DEFAULT, array()
3558 * Check if there are updates affecting the user for the given course since the given time stamp.
3560 * This function is a wrapper of self::check_updates for retrieving all the updates since a given time for all the activities.
3562 * @param int $courseid the list of modules to check
3563 * @param int $since check updates since this time stamp
3564 * @param array $filter check only for updates in these areas
3565 * @return array list of updates and warnings
3566 * @throws moodle_exception
3567 * @since Moodle 3.3
3569 public static function get_updates_since($courseid, $since, $filter = array()) {
3570 global $CFG, $DB;
3572 $params = self::validate_parameters(
3573 self::get_updates_since_parameters(),
3574 array(
3575 'courseid' => $courseid,
3576 'since' => $since,
3577 'filter' => $filter,
3581 $course = get_course($params['courseid']);
3582 $modinfo = get_fast_modinfo($course);
3583 $tocheck = array();
3585 // Retrieve all the visible course modules for the current user.
3586 $cms = $modinfo->get_cms();
3587 foreach ($cms as $cm) {
3588 if (!$cm->uservisible) {
3589 continue;
3591 $tocheck[] = array(
3592 'id' => $cm->id,
3593 'contextlevel' => 'module',
3594 'since' => $params['since'],
3598 return self::check_updates($course->id, $tocheck, $params['filter']);
3602 * Returns description of method result value
3604 * @return \core_external\external_description
3605 * @since Moodle 3.3
3607 public static function get_updates_since_returns() {
3608 return self::check_updates_returns();
3612 * Parameters for function edit_module()
3614 * @since Moodle 3.3
3615 * @return external_function_parameters
3617 public static function edit_module_parameters() {
3618 return new external_function_parameters(
3619 array(
3620 'action' => new external_value(PARAM_ALPHA,
3621 'action: hide, show, stealth, duplicate, delete, moveleft, moveright, group...', VALUE_REQUIRED),
3622 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3623 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3628 * Performs one of the edit module actions and return new html for AJAX
3630 * Returns html to replace the current module html with, for example:
3631 * - empty string for "delete" action,
3632 * - two modules html for "duplicate" action
3633 * - updated module html for everything else
3635 * Throws exception if operation is not permitted/possible
3637 * @since Moodle 3.3
3638 * @param string $action
3639 * @param int $id
3640 * @param null|int $sectionreturn
3641 * @return string
3643 public static function edit_module($action, $id, $sectionreturn = null) {
3644 global $PAGE, $DB;
3645 // Validate and normalize parameters.
3646 $params = self::validate_parameters(self::edit_module_parameters(),
3647 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3648 $action = $params['action'];
3649 $id = $params['id'];
3650 $sectionreturn = $params['sectionreturn'];
3652 // Set of permissions an editing user may have.
3653 $contextarray = [
3654 'moodle/course:update',
3655 'moodle/course:manageactivities',
3656 'moodle/course:activityvisibility',
3657 'moodle/course:sectionvisibility',
3658 'moodle/course:movesections',
3659 'moodle/course:setcurrentsection',
3661 $PAGE->set_other_editing_capability($contextarray);
3663 list($course, $cm) = get_course_and_cm_from_cmid($id);
3664 $modcontext = context_module::instance($cm->id);
3665 $coursecontext = context_course::instance($course->id);
3666 self::validate_context($modcontext);
3667 $format = course_get_format($course);
3668 if (!is_null($sectionreturn)) {
3669 $format->set_sectionnum($sectionreturn);
3671 $renderer = $format->get_renderer($PAGE);
3673 switch($action) {
3674 case 'hide':
3675 case 'show':
3676 case 'stealth':
3677 require_capability('moodle/course:activityvisibility', $modcontext);
3678 $visible = ($action === 'hide') ? 0 : 1;
3679 $visibleoncoursepage = ($action === 'stealth') ? 0 : 1;
3680 set_coursemodule_visible($id, $visible, $visibleoncoursepage);
3681 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3682 break;
3683 case 'duplicate':
3684 require_capability('moodle/course:manageactivities', $coursecontext);
3685 require_capability('moodle/backup:backuptargetimport', $coursecontext);
3686 require_capability('moodle/restore:restoretargetimport', $coursecontext);
3687 if (!course_allowed_module($course, $cm->modname)) {
3688 throw new moodle_exception('No permission to create that activity');
3690 if ($newcm = duplicate_module($course, $cm)) {
3692 $modinfo = $format->get_modinfo();
3693 $section = $modinfo->get_section_info($newcm->sectionnum);
3694 $cm = $modinfo->get_cm($id);
3696 // Get both original and new element html.
3697 $result = $renderer->course_section_updated_cm_item($format, $section, $cm);
3698 $result .= $renderer->course_section_updated_cm_item($format, $section, $newcm);
3699 return $result;
3701 break;
3702 case 'groupsseparate':
3703 case 'groupsvisible':
3704 case 'groupsnone':
3705 require_capability('moodle/course:manageactivities', $modcontext);
3706 if ($action === 'groupsseparate') {
3707 $newgroupmode = SEPARATEGROUPS;
3708 } else if ($action === 'groupsvisible') {
3709 $newgroupmode = VISIBLEGROUPS;
3710 } else {
3711 $newgroupmode = NOGROUPS;
3713 if (set_coursemodule_groupmode($cm->id, $newgroupmode)) {
3714 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3716 break;
3717 case 'moveleft':
3718 case 'moveright':
3719 require_capability('moodle/course:manageactivities', $modcontext);
3720 $indent = $cm->indent + (($action === 'moveright') ? 1 : -1);
3721 if ($cm->indent >= 0) {
3722 $DB->update_record('course_modules', array('id' => $cm->id, 'indent' => $indent));
3723 rebuild_course_cache($cm->course);
3725 break;
3726 case 'delete':
3727 require_capability('moodle/course:manageactivities', $modcontext);
3728 course_delete_module($cm->id, true);
3729 return '';
3730 default:
3731 throw new coding_exception('Unrecognised action');
3734 $modinfo = $format->get_modinfo();
3735 $section = $modinfo->get_section_info($cm->sectionnum);
3736 $cm = $modinfo->get_cm($id);
3737 return $renderer->course_section_updated_cm_item($format, $section, $cm);
3741 * Return structure for edit_module()
3743 * @since Moodle 3.3
3744 * @return \core_external\external_description
3746 public static function edit_module_returns() {
3747 return new external_value(PARAM_RAW, 'html to replace the current module with');
3751 * Parameters for function get_module()
3753 * @since Moodle 3.3
3754 * @return external_function_parameters
3756 public static function get_module_parameters() {
3757 return new external_function_parameters(
3758 array(
3759 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3760 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3765 * Returns html for displaying one activity module on course page
3767 * @since Moodle 3.3
3768 * @param int $id
3769 * @param null|int $sectionreturn
3770 * @return string
3772 public static function get_module($id, $sectionreturn = null) {
3773 global $PAGE;
3774 // Validate and normalize parameters.
3775 $params = self::validate_parameters(self::get_module_parameters(),
3776 array('id' => $id, 'sectionreturn' => $sectionreturn));
3777 $id = $params['id'];
3778 $sectionreturn = $params['sectionreturn'];
3780 // Set of permissions an editing user may have.
3781 $contextarray = [
3782 'moodle/course:update',
3783 'moodle/course:manageactivities',
3784 'moodle/course:activityvisibility',
3785 'moodle/course:sectionvisibility',
3786 'moodle/course:movesections',
3787 'moodle/course:setcurrentsection',
3789 $PAGE->set_other_editing_capability($contextarray);
3791 // Validate access to the course (note, this is html for the course view page, we don't validate access to the module).
3792 list($course, $cm) = get_course_and_cm_from_cmid($id);
3793 self::validate_context(context_course::instance($course->id));
3795 $format = course_get_format($course);
3796 if (!is_null($sectionreturn)) {
3797 $format->set_sectionnum($sectionreturn);
3799 $renderer = $format->get_renderer($PAGE);
3801 $modinfo = $format->get_modinfo();
3802 $section = $modinfo->get_section_info($cm->sectionnum);
3803 return $renderer->course_section_updated_cm_item($format, $section, $cm);
3807 * Return structure for get_module()
3809 * @since Moodle 3.3
3810 * @return \core_external\external_description
3812 public static function get_module_returns() {
3813 return new external_value(PARAM_RAW, 'html to replace the current module with');
3817 * Parameters for function edit_section()
3819 * @since Moodle 3.3
3820 * @return external_function_parameters
3822 public static function edit_section_parameters() {
3823 return new external_function_parameters(
3824 array(
3825 'action' => new external_value(PARAM_ALPHA, 'action: hide, show, stealth, setmarker, removemarker', VALUE_REQUIRED),
3826 'id' => new external_value(PARAM_INT, 'course section id', VALUE_REQUIRED),
3827 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3832 * Performs one of the edit section actions
3834 * @since Moodle 3.3
3835 * @param string $action
3836 * @param int $id section id
3837 * @param int $sectionreturn section to return to
3838 * @return string
3840 public static function edit_section($action, $id, $sectionreturn) {
3841 global $DB;
3842 // Validate and normalize parameters.
3843 $params = self::validate_parameters(self::edit_section_parameters(),
3844 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3845 $action = $params['action'];
3846 $id = $params['id'];
3847 $sr = $params['sectionreturn'];
3849 $section = $DB->get_record('course_sections', array('id' => $id), '*', MUST_EXIST);
3850 $coursecontext = context_course::instance($section->course);
3851 self::validate_context($coursecontext);
3853 $rv = course_get_format($section->course)->section_action($section, $action, $sectionreturn);
3854 if ($rv) {
3855 return json_encode($rv);
3856 } else {
3857 return null;
3862 * Return structure for edit_section()
3864 * @since Moodle 3.3
3865 * @return \core_external\external_description
3867 public static function edit_section_returns() {
3868 return new external_value(PARAM_RAW, 'Additional data for javascript (JSON-encoded string)');
3872 * Returns description of method parameters
3874 * @return external_function_parameters
3876 public static function get_enrolled_courses_by_timeline_classification_parameters() {
3877 return new external_function_parameters(
3878 array(
3879 'classification' => new external_value(PARAM_ALPHA, 'future, inprogress, or past'),
3880 'limit' => new external_value(PARAM_INT, 'Result set limit', VALUE_DEFAULT, 0),
3881 'offset' => new external_value(PARAM_INT, 'Result set offset', VALUE_DEFAULT, 0),
3882 'sort' => new external_value(PARAM_TEXT, 'Sort string', VALUE_DEFAULT, null),
3883 'customfieldname' => new external_value(PARAM_ALPHANUMEXT, 'Used when classification = customfield',
3884 VALUE_DEFAULT, null),
3885 'customfieldvalue' => new external_value(PARAM_RAW, 'Used when classification = customfield',
3886 VALUE_DEFAULT, null),
3887 'searchvalue' => new external_value(PARAM_RAW, 'The value a user wishes to search against',
3888 VALUE_DEFAULT, null),
3894 * Get courses matching the given timeline classification.
3896 * NOTE: The offset applies to the unfiltered full set of courses before the classification
3897 * filtering is done.
3898 * E.g.
3899 * If the user is enrolled in 5 courses:
3900 * c1, c2, c3, c4, and c5
3901 * And c4 and c5 are 'future' courses
3903 * If a request comes in for future courses with an offset of 1 it will mean that
3904 * c1 is skipped (because the offset applies *before* the classification filtering)
3905 * and c4 and c5 will be return.
3907 * @param string $classification past, inprogress, or future
3908 * @param int $limit Result set limit
3909 * @param int $offset Offset the full course set before timeline classification is applied
3910 * @param string $sort SQL sort string for results
3911 * @param string $customfieldname
3912 * @param string $customfieldvalue
3913 * @param string $searchvalue
3914 * @return array list of courses and warnings
3915 * @throws invalid_parameter_exception
3917 public static function get_enrolled_courses_by_timeline_classification(
3918 string $classification,
3919 int $limit = 0,
3920 int $offset = 0,
3921 string $sort = null,
3922 string $customfieldname = null,
3923 string $customfieldvalue = null,
3924 string $searchvalue = null
3926 global $CFG, $PAGE, $USER;
3927 require_once($CFG->dirroot . '/course/lib.php');
3929 $params = self::validate_parameters(self::get_enrolled_courses_by_timeline_classification_parameters(),
3930 array(
3931 'classification' => $classification,
3932 'limit' => $limit,
3933 'offset' => $offset,
3934 'sort' => $sort,
3935 'customfieldvalue' => $customfieldvalue,
3936 'searchvalue' => $searchvalue,
3940 $classification = $params['classification'];
3941 $limit = $params['limit'];
3942 $offset = $params['offset'];
3943 $sort = $params['sort'];
3944 $customfieldvalue = $params['customfieldvalue'];
3945 $searchvalue = clean_param($params['searchvalue'], PARAM_TEXT);
3947 switch($classification) {
3948 case COURSE_TIMELINE_ALLINCLUDINGHIDDEN:
3949 break;
3950 case COURSE_TIMELINE_ALL:
3951 break;
3952 case COURSE_TIMELINE_PAST:
3953 break;
3954 case COURSE_TIMELINE_INPROGRESS:
3955 break;
3956 case COURSE_TIMELINE_FUTURE:
3957 break;
3958 case COURSE_FAVOURITES:
3959 break;
3960 case COURSE_TIMELINE_HIDDEN:
3961 break;
3962 case COURSE_TIMELINE_SEARCH:
3963 break;
3964 case COURSE_CUSTOMFIELD:
3965 break;
3966 default:
3967 throw new invalid_parameter_exception('Invalid classification');
3970 self::validate_context(context_user::instance($USER->id));
3972 $requiredproperties = course_summary_exporter::define_properties();
3973 $fields = join(',', array_keys($requiredproperties));
3974 $hiddencourses = get_hidden_courses_on_timeline();
3975 $courses = [];
3977 // If the timeline requires really all courses, get really all courses.
3978 if ($classification == COURSE_TIMELINE_ALLINCLUDINGHIDDEN) {
3979 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields, COURSE_DB_QUERY_LIMIT);
3981 // Otherwise if the timeline requires the hidden courses then restrict the result to only $hiddencourses.
3982 } else if ($classification == COURSE_TIMELINE_HIDDEN) {
3983 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields,
3984 COURSE_DB_QUERY_LIMIT, $hiddencourses);
3986 // Otherwise get the requested courses and exclude the hidden courses.
3987 } else if ($classification == COURSE_TIMELINE_SEARCH) {
3988 // Prepare the search API options.
3989 $searchcriteria['search'] = $searchvalue;
3990 $options = ['idonly' => true];
3991 $courses = course_get_enrolled_courses_for_logged_in_user_from_search(
3993 $offset,
3994 $sort,
3995 $fields,
3996 COURSE_DB_QUERY_LIMIT,
3997 $searchcriteria,
3998 $options
4000 } else {
4001 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields,
4002 COURSE_DB_QUERY_LIMIT, [], $hiddencourses);
4005 $favouritecourseids = [];
4006 $ufservice = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($USER->id));
4007 $favourites = $ufservice->find_favourites_by_type('core_course', 'courses');
4009 if ($favourites) {
4010 $favouritecourseids = array_map(
4011 function($favourite) {
4012 return $favourite->itemid;
4013 }, $favourites);
4016 if ($classification == COURSE_FAVOURITES) {
4017 list($filteredcourses, $processedcount) = course_filter_courses_by_favourites(
4018 $courses,
4019 $favouritecourseids,
4020 $limit
4022 } else if ($classification == COURSE_CUSTOMFIELD) {
4023 list($filteredcourses, $processedcount) = course_filter_courses_by_customfield(
4024 $courses,
4025 $customfieldname,
4026 $customfieldvalue,
4027 $limit
4029 } else {
4030 list($filteredcourses, $processedcount) = course_filter_courses_by_timeline_classification(
4031 $courses,
4032 $classification,
4033 $limit
4037 $renderer = $PAGE->get_renderer('core');
4038 $formattedcourses = array_map(function($course) use ($renderer, $favouritecourseids) {
4039 if ($course == null) {
4040 return;
4042 context_helper::preload_from_record($course);
4043 $context = context_course::instance($course->id);
4044 $isfavourite = false;
4045 if (in_array($course->id, $favouritecourseids)) {
4046 $isfavourite = true;
4048 $exporter = new course_summary_exporter($course, ['context' => $context, 'isfavourite' => $isfavourite]);
4049 return $exporter->export($renderer);
4050 }, $filteredcourses);
4052 $formattedcourses = array_filter($formattedcourses, function($course) {
4053 if ($course != null) {
4054 return $course;
4058 return [
4059 'courses' => $formattedcourses,
4060 'nextoffset' => $offset + $processedcount
4065 * Returns description of method result value
4067 * @return \core_external\external_description
4069 public static function get_enrolled_courses_by_timeline_classification_returns() {
4070 return new external_single_structure(
4071 array(
4072 'courses' => new external_multiple_structure(course_summary_exporter::get_read_structure(), 'Course'),
4073 'nextoffset' => new external_value(PARAM_INT, 'Offset for the next request')
4079 * Returns description of method parameters
4081 * @return external_function_parameters
4083 public static function set_favourite_courses_parameters() {
4084 return new external_function_parameters(
4085 array(
4086 'courses' => new external_multiple_structure(
4087 new external_single_structure(
4088 array(
4089 'id' => new external_value(PARAM_INT, 'course ID'),
4090 'favourite' => new external_value(PARAM_BOOL, 'favourite status')
4099 * Set the course favourite status for an array of courses.
4101 * @param array $courses List with course id's and favourite status.
4102 * @return array Array with an array of favourite courses.
4104 public static function set_favourite_courses(
4105 array $courses
4107 global $USER;
4109 $params = self::validate_parameters(self::set_favourite_courses_parameters(),
4110 array(
4111 'courses' => $courses
4115 $warnings = [];
4117 $ufservice = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($USER->id));
4119 foreach ($params['courses'] as $course) {
4121 $warning = [];
4123 $favouriteexists = $ufservice->favourite_exists('core_course', 'courses', $course['id'],
4124 \context_course::instance($course['id']));
4126 if ($course['favourite']) {
4127 if (!$favouriteexists) {
4128 try {
4129 $ufservice->create_favourite('core_course', 'courses', $course['id'],
4130 \context_course::instance($course['id']));
4131 } catch (Exception $e) {
4132 $warning['courseid'] = $course['id'];
4133 if ($e instanceof moodle_exception) {
4134 $warning['warningcode'] = $e->errorcode;
4135 } else {
4136 $warning['warningcode'] = $e->getCode();
4138 $warning['message'] = $e->getMessage();
4139 $warnings[] = $warning;
4140 $warnings[] = $warning;
4142 } else {
4143 $warning['courseid'] = $course['id'];
4144 $warning['warningcode'] = 'coursealreadyfavourited';
4145 $warning['message'] = 'Course already favourited';
4146 $warnings[] = $warning;
4148 } else {
4149 if ($favouriteexists) {
4150 try {
4151 $ufservice->delete_favourite('core_course', 'courses', $course['id'],
4152 \context_course::instance($course['id']));
4153 } catch (Exception $e) {
4154 $warning['courseid'] = $course['id'];
4155 if ($e instanceof moodle_exception) {
4156 $warning['warningcode'] = $e->errorcode;
4157 } else {
4158 $warning['warningcode'] = $e->getCode();
4160 $warning['message'] = $e->getMessage();
4161 $warnings[] = $warning;
4162 $warnings[] = $warning;
4164 } else {
4165 $warning['courseid'] = $course['id'];
4166 $warning['warningcode'] = 'cannotdeletefavourite';
4167 $warning['message'] = 'Could not delete favourite status for course';
4168 $warnings[] = $warning;
4173 return [
4174 'warnings' => $warnings
4179 * Returns description of method result value
4181 * @return \core_external\external_description
4183 public static function set_favourite_courses_returns() {
4184 return new external_single_structure(
4185 array(
4186 'warnings' => new external_warnings()
4192 * Returns description of method parameters
4194 * @return external_function_parameters
4195 * @since Moodle 3.6
4197 public static function get_recent_courses_parameters() {
4198 return new external_function_parameters(
4199 array(
4200 'userid' => new external_value(PARAM_INT, 'id of the user, default to current user', VALUE_DEFAULT, 0),
4201 'limit' => new external_value(PARAM_INT, 'result set limit', VALUE_DEFAULT, 0),
4202 'offset' => new external_value(PARAM_INT, 'Result set offset', VALUE_DEFAULT, 0),
4203 'sort' => new external_value(PARAM_TEXT, 'Sort string', VALUE_DEFAULT, null)
4209 * Get last accessed courses adding additional course information like images.
4211 * @param int $userid User id from which the courses will be obtained
4212 * @param int $limit Restrict result set to this amount
4213 * @param int $offset Skip this number of records from the start of the result set
4214 * @param string|null $sort SQL string for sorting
4215 * @return array List of courses
4216 * @throws invalid_parameter_exception
4218 public static function get_recent_courses(int $userid = 0, int $limit = 0, int $offset = 0, string $sort = null) {
4219 global $USER, $PAGE;
4221 if (empty($userid)) {
4222 $userid = $USER->id;
4225 $params = self::validate_parameters(self::get_recent_courses_parameters(),
4226 array(
4227 'userid' => $userid,
4228 'limit' => $limit,
4229 'offset' => $offset,
4230 'sort' => $sort
4234 $userid = $params['userid'];
4235 $limit = $params['limit'];
4236 $offset = $params['offset'];
4237 $sort = $params['sort'];
4239 $usercontext = context_user::instance($userid);
4241 self::validate_context($usercontext);
4243 if ($userid != $USER->id and !has_capability('moodle/user:viewdetails', $usercontext)) {
4244 return array();
4247 $courses = course_get_recent_courses($userid, $limit, $offset, $sort);
4249 $renderer = $PAGE->get_renderer('core');
4251 $recentcourses = array_map(function($course) use ($renderer) {
4252 context_helper::preload_from_record($course);
4253 $context = context_course::instance($course->id);
4254 $isfavourite = !empty($course->component);
4255 $exporter = new course_summary_exporter($course, ['context' => $context, 'isfavourite' => $isfavourite]);
4256 return $exporter->export($renderer);
4257 }, $courses);
4259 return $recentcourses;
4263 * Returns description of method result value
4265 * @return \core_external\external_description
4266 * @since Moodle 3.6
4268 public static function get_recent_courses_returns() {
4269 return new external_multiple_structure(course_summary_exporter::get_read_structure(), 'Courses');
4273 * Returns description of method parameters
4275 * @return external_function_parameters
4277 public static function get_enrolled_users_by_cmid_parameters() {
4278 return new external_function_parameters([
4279 'cmid' => new external_value(PARAM_INT, 'id of the course module', VALUE_REQUIRED),
4280 'groupid' => new external_value(PARAM_INT, 'id of the group', VALUE_DEFAULT, 0),
4281 'onlyactive' => new external_value(PARAM_BOOL, 'whether to return only active users or all.',
4282 VALUE_DEFAULT, false),
4287 * Get all users in a course for a given cmid.
4289 * @param int $cmid Course Module id from which the users will be obtained
4290 * @param int $groupid Group id from which the users will be obtained
4291 * @param bool $onlyactive Whether to return only the active enrolled users or all enrolled users in the course.
4292 * @return array List of users
4293 * @throws invalid_parameter_exception
4295 public static function get_enrolled_users_by_cmid(int $cmid, int $groupid = 0, bool $onlyactive = false) {
4296 global $PAGE;
4297 $warnings = [];
4299 self::validate_parameters(self::get_enrolled_users_by_cmid_parameters(), [
4300 'cmid' => $cmid,
4301 'groupid' => $groupid,
4302 'onlyactive' => $onlyactive,
4305 list($course, $cm) = get_course_and_cm_from_cmid($cmid);
4306 $coursecontext = context_course::instance($course->id);
4307 self::validate_context($coursecontext);
4309 $enrolledusers = get_enrolled_users($coursecontext, '', $groupid, 'u.*', null, 0, 0, $onlyactive);
4311 $users = array_map(function ($user) use ($PAGE) {
4312 $user->fullname = fullname($user);
4313 $userpicture = new user_picture($user);
4314 $userpicture->size = 1;
4315 $user->profileimage = $userpicture->get_url($PAGE)->out(false);
4316 return $user;
4317 }, $enrolledusers);
4318 sort($users);
4320 return [
4321 'users' => $users,
4322 'warnings' => $warnings,
4327 * Returns description of method result value
4329 * @return \core_external\external_description
4331 public static function get_enrolled_users_by_cmid_returns() {
4332 return new external_single_structure([
4333 'users' => new external_multiple_structure(self::user_description()),
4334 'warnings' => new external_warnings(),
4339 * Create user return value description.
4341 * @return \core_external\external_description
4343 public static function user_description() {
4344 $userfields = array(
4345 'id' => new external_value(core_user::get_property_type('id'), 'ID of the user'),
4346 'profileimage' => new external_value(PARAM_URL, 'The location of the users larger image', VALUE_OPTIONAL),
4347 'fullname' => new external_value(PARAM_TEXT, 'The full name of the user', VALUE_OPTIONAL),
4348 'firstname' => new external_value(
4349 core_user::get_property_type('firstname'),
4350 'The first name(s) of the user',
4351 VALUE_OPTIONAL),
4352 'lastname' => new external_value(
4353 core_user::get_property_type('lastname'),
4354 'The family name of the user',
4355 VALUE_OPTIONAL),
4357 return new external_single_structure($userfields);
4361 * Returns description of method parameters.
4363 * @return external_function_parameters
4365 public static function add_content_item_to_user_favourites_parameters() {
4366 return new external_function_parameters([
4367 'componentname' => new external_value(PARAM_TEXT,
4368 'frankenstyle name of the component to which the content item belongs', VALUE_REQUIRED),
4369 'contentitemid' => new external_value(PARAM_INT, 'id of the content item', VALUE_REQUIRED, '', NULL_NOT_ALLOWED)
4374 * Add a content item to a user's favourites.
4376 * @param string $componentname the name of the component from which this content item originates.
4377 * @param int $contentitemid the id of the content item.
4378 * @return stdClass the exporter content item.
4380 public static function add_content_item_to_user_favourites(string $componentname, int $contentitemid) {
4381 global $USER;
4384 'componentname' => $componentname,
4385 'contentitemid' => $contentitemid,
4386 ] = self::validate_parameters(self::add_content_item_to_user_favourites_parameters(),
4388 'componentname' => $componentname,
4389 'contentitemid' => $contentitemid,
4393 self::validate_context(context_user::instance($USER->id));
4395 $contentitemservice = \core_course\local\factory\content_item_service_factory::get_content_item_service();
4397 return $contentitemservice->add_to_user_favourites($USER, $componentname, $contentitemid);
4401 * Returns description of method result value.
4403 * @return \core_external\external_description
4405 public static function add_content_item_to_user_favourites_returns() {
4406 return \core_course\local\exporters\course_content_item_exporter::get_read_structure();
4410 * Returns description of method parameters.
4412 * @return external_function_parameters
4414 public static function remove_content_item_from_user_favourites_parameters() {
4415 return new external_function_parameters([
4416 'componentname' => new external_value(PARAM_TEXT,
4417 'frankenstyle name of the component to which the content item belongs', VALUE_REQUIRED),
4418 'contentitemid' => new external_value(PARAM_INT, 'id of the content item', VALUE_REQUIRED, '', NULL_NOT_ALLOWED),
4423 * Remove a content item from a user's favourites.
4425 * @param string $componentname the name of the component from which this content item originates.
4426 * @param int $contentitemid the id of the content item.
4427 * @return stdClass the exported content item.
4429 public static function remove_content_item_from_user_favourites(string $componentname, int $contentitemid) {
4430 global $USER;
4433 'componentname' => $componentname,
4434 'contentitemid' => $contentitemid,
4435 ] = self::validate_parameters(self::remove_content_item_from_user_favourites_parameters(),
4437 'componentname' => $componentname,
4438 'contentitemid' => $contentitemid,
4442 self::validate_context(context_user::instance($USER->id));
4444 $contentitemservice = \core_course\local\factory\content_item_service_factory::get_content_item_service();
4446 return $contentitemservice->remove_from_user_favourites($USER, $componentname, $contentitemid);
4450 * Returns description of method result value.
4452 * @return \core_external\external_description
4454 public static function remove_content_item_from_user_favourites_returns() {
4455 return \core_course\local\exporters\course_content_item_exporter::get_read_structure();
4459 * Returns description of method result value
4461 * @return \core_external\external_description
4463 public static function get_course_content_items_returns() {
4464 return new external_single_structure([
4465 'content_items' => new external_multiple_structure(
4466 \core_course\local\exporters\course_content_item_exporter::get_read_structure()
4472 * Returns description of method parameters
4474 * @return external_function_parameters
4476 public static function get_course_content_items_parameters() {
4477 return new external_function_parameters([
4478 'courseid' => new external_value(PARAM_INT, 'ID of the course', VALUE_REQUIRED),
4483 * Given a course ID fetch all accessible modules for that course
4485 * @param int $courseid The course we want to fetch the modules for
4486 * @return array Contains array of modules and their metadata
4488 public static function get_course_content_items(int $courseid) {
4489 global $USER;
4492 'courseid' => $courseid,
4493 ] = self::validate_parameters(self::get_course_content_items_parameters(), [
4494 'courseid' => $courseid,
4497 $coursecontext = context_course::instance($courseid);
4498 self::validate_context($coursecontext);
4499 $course = get_course($courseid);
4501 $contentitemservice = \core_course\local\factory\content_item_service_factory::get_content_item_service();
4503 $contentitems = $contentitemservice->get_content_items_for_user_in_course($USER, $course);
4504 return ['content_items' => $contentitems];
4508 * Returns description of method parameters.
4510 * @return external_function_parameters
4512 public static function toggle_activity_recommendation_parameters() {
4513 return new external_function_parameters([
4514 'area' => new external_value(PARAM_TEXT, 'The favourite area (itemtype)', VALUE_REQUIRED),
4515 'id' => new external_value(PARAM_INT, 'id of the activity or whatever', VALUE_REQUIRED),
4520 * Update the recommendation for an activity item.
4522 * @param string $area identifier for this activity.
4523 * @param int $id Associated id. This is needed in conjunction with the area to find the recommendation.
4524 * @return array some warnings or something.
4526 public static function toggle_activity_recommendation(string $area, int $id): array {
4527 ['area' => $area, 'id' => $id] = self::validate_parameters(self::toggle_activity_recommendation_parameters(),
4528 ['area' => $area, 'id' => $id]);
4530 $context = context_system::instance();
4531 self::validate_context($context);
4533 require_capability('moodle/course:recommendactivity', $context);
4535 $manager = \core_course\local\factory\content_item_service_factory::get_content_item_service();
4537 $status = $manager->toggle_recommendation($area, $id);
4538 return ['id' => $id, 'area' => $area, 'status' => $status];
4542 * Returns warnings.
4544 * @return \core_external\external_description
4546 public static function toggle_activity_recommendation_returns() {
4547 return new external_single_structure(
4549 'id' => new external_value(PARAM_INT, 'id of the activity or whatever'),
4550 'area' => new external_value(PARAM_TEXT, 'The favourite area (itemtype)'),
4551 'status' => new external_value(PARAM_BOOL, 'If created or deleted'),
4557 * Returns description of method parameters
4559 * @return external_function_parameters
4561 public static function get_activity_chooser_footer_parameters() {
4562 return new external_function_parameters([
4563 'courseid' => new external_value(PARAM_INT, 'ID of the course', VALUE_REQUIRED),
4564 'sectionid' => new external_value(PARAM_INT, 'ID of the section', VALUE_REQUIRED),
4569 * Given a course ID we need to build up a footre for the chooser.
4571 * @param int $courseid The course we want to fetch the modules for
4572 * @param int $sectionid The section we want to fetch the modules for
4573 * @return array
4575 public static function get_activity_chooser_footer(int $courseid, int $sectionid) {
4577 'courseid' => $courseid,
4578 'sectionid' => $sectionid,
4579 ] = self::validate_parameters(self::get_activity_chooser_footer_parameters(), [
4580 'courseid' => $courseid,
4581 'sectionid' => $sectionid,
4584 $coursecontext = context_course::instance($courseid);
4585 self::validate_context($coursecontext);
4587 $activeplugin = get_config('core', 'activitychooseractivefooter');
4589 if ($activeplugin !== COURSE_CHOOSER_FOOTER_NONE) {
4590 $footerdata = component_callback($activeplugin, 'custom_chooser_footer', [$courseid, $sectionid]);
4591 return [
4592 'footer' => true,
4593 'customfooterjs' => $footerdata->get_footer_js_file(),
4594 'customfootertemplate' => $footerdata->get_footer_template(),
4595 'customcarouseltemplate' => $footerdata->get_carousel_template(),
4597 } else {
4598 return [
4599 'footer' => false,
4605 * Returns description of method result value
4607 * @return \core_external\external_description
4609 public static function get_activity_chooser_footer_returns() {
4610 return new external_single_structure(
4612 'footer' => new external_value(PARAM_BOOL, 'Is a footer being return by this request?', VALUE_REQUIRED),
4613 'customfooterjs' => new external_value(PARAM_RAW, 'The path to the plugin JS file', VALUE_OPTIONAL),
4614 'customfootertemplate' => new external_value(PARAM_RAW, 'The prerendered footer', VALUE_OPTIONAL),
4615 'customcarouseltemplate' => new external_value(PARAM_RAW, 'Either "" or the prerendered carousel page',
4616 VALUE_OPTIONAL),