Merge branch 'MDL-69395_38' of github.com:stronk7/moodle into MOODLE_38_STABLE
[moodle.git] / course / externallib.php
blobe2216e7c967dacd6d013c6ef9b560c557701834b
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;
31 require_once("$CFG->libdir/externallib.php");
32 require_once("lib.php");
34 /**
35 * Course external functions
37 * @package core_course
38 * @category external
39 * @copyright 2011 Jerome Mouneyrac
40 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
41 * @since Moodle 2.2
43 class core_course_external extends external_api {
45 /**
46 * Returns description of method parameters
48 * @return external_function_parameters
49 * @since Moodle 2.9 Options available
50 * @since Moodle 2.2
52 public static function get_course_contents_parameters() {
53 return new external_function_parameters(
54 array('courseid' => new external_value(PARAM_INT, 'course id'),
55 'options' => new external_multiple_structure (
56 new external_single_structure(
57 array(
58 'name' => new external_value(PARAM_ALPHANUM,
59 'The expected keys (value format) are:
60 excludemodules (bool) Do not return modules, return only the sections structure
61 excludecontents (bool) Do not return module contents (i.e: files inside a resource)
62 includestealthmodules (bool) Return stealth modules for students in a special
63 section (with id -1)
64 sectionid (int) Return only this section
65 sectionnumber (int) Return only this section with number (order)
66 cmid (int) Return only this module information (among the whole sections structure)
67 modname (string) Return only modules with this name "label, forum, etc..."
68 modid (int) Return only the module with this id (to be used with modname'),
69 'value' => new external_value(PARAM_RAW, 'the value of the option,
70 this param is personaly validated in the external function.')
72 ), 'Options, used since Moodle 2.9', VALUE_DEFAULT, array())
77 /**
78 * Get course contents
80 * @param int $courseid course id
81 * @param array $options Options for filtering the results, used since Moodle 2.9
82 * @return array
83 * @since Moodle 2.9 Options available
84 * @since Moodle 2.2
86 public static function get_course_contents($courseid, $options = array()) {
87 global $CFG, $DB;
88 require_once($CFG->dirroot . "/course/lib.php");
89 require_once($CFG->libdir . '/completionlib.php');
91 //validate parameter
92 $params = self::validate_parameters(self::get_course_contents_parameters(),
93 array('courseid' => $courseid, 'options' => $options));
95 $filters = array();
96 if (!empty($params['options'])) {
98 foreach ($params['options'] as $option) {
99 $name = trim($option['name']);
100 // Avoid duplicated options.
101 if (!isset($filters[$name])) {
102 switch ($name) {
103 case 'excludemodules':
104 case 'excludecontents':
105 case 'includestealthmodules':
106 $value = clean_param($option['value'], PARAM_BOOL);
107 $filters[$name] = $value;
108 break;
109 case 'sectionid':
110 case 'sectionnumber':
111 case 'cmid':
112 case 'modid':
113 $value = clean_param($option['value'], PARAM_INT);
114 if (is_numeric($value)) {
115 $filters[$name] = $value;
116 } else {
117 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
119 break;
120 case 'modname':
121 $value = clean_param($option['value'], PARAM_PLUGIN);
122 if ($value) {
123 $filters[$name] = $value;
124 } else {
125 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
127 break;
128 default:
129 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
135 //retrieve the course
136 $course = $DB->get_record('course', array('id' => $params['courseid']), '*', MUST_EXIST);
138 if ($course->id != SITEID) {
139 // Check course format exist.
140 if (!file_exists($CFG->dirroot . '/course/format/' . $course->format . '/lib.php')) {
141 throw new moodle_exception('cannotgetcoursecontents', 'webservice', '', null,
142 get_string('courseformatnotfound', 'error', $course->format));
143 } else {
144 require_once($CFG->dirroot . '/course/format/' . $course->format . '/lib.php');
148 // now security checks
149 $context = context_course::instance($course->id, IGNORE_MISSING);
150 try {
151 self::validate_context($context);
152 } catch (Exception $e) {
153 $exceptionparam = new stdClass();
154 $exceptionparam->message = $e->getMessage();
155 $exceptionparam->courseid = $course->id;
156 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
159 $canupdatecourse = has_capability('moodle/course:update', $context);
161 //create return value
162 $coursecontents = array();
164 if ($canupdatecourse or $course->visible
165 or has_capability('moodle/course:viewhiddencourses', $context)) {
167 //retrieve sections
168 $modinfo = get_fast_modinfo($course);
169 $sections = $modinfo->get_section_info_all();
170 $coursenumsections = course_get_format($course)->get_last_section_number();
171 $stealthmodules = array(); // Array to keep all the modules available but not visible in a course section/topic.
173 $completioninfo = new completion_info($course);
175 //for each sections (first displayed to last displayed)
176 $modinfosections = $modinfo->get_sections();
177 foreach ($sections as $key => $section) {
179 // This becomes true when we are filtering and we found the value to filter with.
180 $sectionfound = false;
182 // Filter by section id.
183 if (!empty($filters['sectionid'])) {
184 if ($section->id != $filters['sectionid']) {
185 continue;
186 } else {
187 $sectionfound = true;
191 // Filter by section number. Note that 0 is a valid section number.
192 if (isset($filters['sectionnumber'])) {
193 if ($key != $filters['sectionnumber']) {
194 continue;
195 } else {
196 $sectionfound = true;
200 // reset $sectioncontents
201 $sectionvalues = array();
202 $sectionvalues['id'] = $section->id;
203 $sectionvalues['name'] = get_section_name($course, $section);
204 $sectionvalues['visible'] = $section->visible;
206 $options = (object) array('noclean' => true);
207 list($sectionvalues['summary'], $sectionvalues['summaryformat']) =
208 external_format_text($section->summary, $section->summaryformat,
209 $context->id, 'course', 'section', $section->id, $options);
210 $sectionvalues['section'] = $section->section;
211 $sectionvalues['hiddenbynumsections'] = $section->section > $coursenumsections ? 1 : 0;
212 $sectionvalues['uservisible'] = $section->uservisible;
213 if (!empty($section->availableinfo)) {
214 $sectionvalues['availabilityinfo'] = \core_availability\info::format_info($section->availableinfo, $course);
217 $sectioncontents = array();
219 // For each module of the section.
220 if (empty($filters['excludemodules']) and !empty($modinfosections[$section->section])) {
221 foreach ($modinfosections[$section->section] as $cmid) {
222 $cm = $modinfo->cms[$cmid];
224 // Stop here if the module is not visible to the user on the course main page:
225 // The user can't access the module and the user can't view the module on the course page.
226 if (!$cm->uservisible && !$cm->is_visible_on_course_page()) {
227 continue;
230 // This becomes true when we are filtering and we found the value to filter with.
231 $modfound = false;
233 // Filter by cmid.
234 if (!empty($filters['cmid'])) {
235 if ($cmid != $filters['cmid']) {
236 continue;
237 } else {
238 $modfound = true;
242 // Filter by module name and id.
243 if (!empty($filters['modname'])) {
244 if ($cm->modname != $filters['modname']) {
245 continue;
246 } else if (!empty($filters['modid'])) {
247 if ($cm->instance != $filters['modid']) {
248 continue;
249 } else {
250 // Note that if we are only filtering by modname we don't break the loop.
251 $modfound = true;
256 $module = array();
258 $modcontext = context_module::instance($cm->id);
260 //common info (for people being able to see the module or availability dates)
261 $module['id'] = $cm->id;
262 $module['name'] = external_format_string($cm->name, $modcontext->id);
263 $module['instance'] = $cm->instance;
264 $module['modname'] = (string) $cm->modname;
265 $module['modplural'] = (string) $cm->modplural;
266 $module['modicon'] = $cm->get_icon_url()->out(false);
267 $module['indent'] = $cm->indent;
268 $module['onclick'] = $cm->onclick;
269 $module['afterlink'] = $cm->afterlink;
270 $module['customdata'] = json_encode($cm->customdata);
271 $module['completion'] = $cm->completion;
272 $module['noviewlink'] = plugin_supports('mod', $cm->modname, FEATURE_NO_VIEW_LINK, false);
274 // Check module completion.
275 $completion = $completioninfo->is_enabled($cm);
276 if ($completion != COMPLETION_DISABLED) {
277 $completiondata = $completioninfo->get_data($cm, true);
278 $module['completiondata'] = array(
279 'state' => $completiondata->completionstate,
280 'timecompleted' => $completiondata->timemodified,
281 'overrideby' => $completiondata->overrideby,
282 'valueused' => core_availability\info::completion_value_used($course, $cm->id)
286 if (!empty($cm->showdescription) or $module['noviewlink']) {
287 // We want to use the external format. However from reading get_formatted_content(), $cm->content format is always FORMAT_HTML.
288 $options = array('noclean' => true);
289 list($module['description'], $descriptionformat) = external_format_text($cm->content,
290 FORMAT_HTML, $modcontext->id, $cm->modname, 'intro', $cm->id, $options);
293 //url of the module
294 $url = $cm->url;
295 if ($url) { //labels don't have url
296 $module['url'] = $url->out(false);
299 $canviewhidden = has_capability('moodle/course:viewhiddenactivities',
300 context_module::instance($cm->id));
301 //user that can view hidden module should know about the visibility
302 $module['visible'] = $cm->visible;
303 $module['visibleoncoursepage'] = $cm->visibleoncoursepage;
304 $module['uservisible'] = $cm->uservisible;
305 if (!empty($cm->availableinfo)) {
306 $module['availabilityinfo'] = \core_availability\info::format_info($cm->availableinfo, $course);
309 // Availability date (also send to user who can see hidden module).
310 if ($CFG->enableavailability && ($canviewhidden || $canupdatecourse)) {
311 $module['availability'] = $cm->availability;
314 // Return contents only if the user can access to the module.
315 if ($cm->uservisible) {
316 $baseurl = 'webservice/pluginfile.php';
318 // Call $modulename_export_contents (each module callback take care about checking the capabilities).
319 require_once($CFG->dirroot . '/mod/' . $cm->modname . '/lib.php');
320 $getcontentfunction = $cm->modname.'_export_contents';
321 if (function_exists($getcontentfunction)) {
322 $contents = $getcontentfunction($cm, $baseurl);
323 $module['contentsinfo'] = array(
324 'filescount' => count($contents),
325 'filessize' => 0,
326 'lastmodified' => 0,
327 'mimetypes' => array(),
329 foreach ($contents as $content) {
330 // Check repository file (only main file).
331 if (!isset($module['contentsinfo']['repositorytype'])) {
332 $module['contentsinfo']['repositorytype'] =
333 isset($content['repositorytype']) ? $content['repositorytype'] : '';
335 if (isset($content['filesize'])) {
336 $module['contentsinfo']['filessize'] += $content['filesize'];
338 if (isset($content['timemodified']) &&
339 ($content['timemodified'] > $module['contentsinfo']['lastmodified'])) {
341 $module['contentsinfo']['lastmodified'] = $content['timemodified'];
343 if (isset($content['mimetype'])) {
344 $module['contentsinfo']['mimetypes'][$content['mimetype']] = $content['mimetype'];
348 if (empty($filters['excludecontents']) and !empty($contents)) {
349 $module['contents'] = $contents;
350 } else {
351 $module['contents'] = array();
356 // Assign result to $sectioncontents, there is an exception,
357 // stealth activities in non-visible sections for students go to a special section.
358 if (!empty($filters['includestealthmodules']) && !$section->uservisible && $cm->is_stealth()) {
359 $stealthmodules[] = $module;
360 } else {
361 $sectioncontents[] = $module;
364 // If we just did a filtering, break the loop.
365 if ($modfound) {
366 break;
371 $sectionvalues['modules'] = $sectioncontents;
373 // assign result to $coursecontents
374 $coursecontents[$key] = $sectionvalues;
376 // Break the loop if we are filtering.
377 if ($sectionfound) {
378 break;
382 // Now that we have iterated over all the sections and activities, check the visibility.
383 // We didn't this before to be able to retrieve stealth activities.
384 foreach ($coursecontents as $sectionnumber => $sectioncontents) {
385 $section = $sections[$sectionnumber];
386 // Show the section if the user is permitted to access it, OR if it's not available
387 // but there is some available info text which explains the reason & should display.
388 $showsection = $section->uservisible ||
389 ($section->visible && !$section->available &&
390 !empty($section->availableinfo));
392 if (!$showsection) {
393 unset($coursecontents[$sectionnumber]);
394 continue;
397 // Remove modules information if the section is not visible for the user.
398 if (!$section->uservisible) {
399 $coursecontents[$sectionnumber]['modules'] = array();
403 // Include stealth modules in special section (without any info).
404 if (!empty($stealthmodules)) {
405 $coursecontents[] = array(
406 'id' => -1,
407 'name' => '',
408 'summary' => '',
409 'summaryformat' => FORMAT_MOODLE,
410 'modules' => $stealthmodules
415 return $coursecontents;
419 * Returns description of method result value
421 * @return external_description
422 * @since Moodle 2.2
424 public static function get_course_contents_returns() {
425 return new external_multiple_structure(
426 new external_single_structure(
427 array(
428 'id' => new external_value(PARAM_INT, 'Section ID'),
429 'name' => new external_value(PARAM_TEXT, 'Section name'),
430 'visible' => new external_value(PARAM_INT, 'is the section visible', VALUE_OPTIONAL),
431 'summary' => new external_value(PARAM_RAW, 'Section description'),
432 'summaryformat' => new external_format_value('summary'),
433 'section' => new external_value(PARAM_INT, 'Section number inside the course', VALUE_OPTIONAL),
434 'hiddenbynumsections' => new external_value(PARAM_INT, 'Whether is a section hidden in the course format',
435 VALUE_OPTIONAL),
436 'uservisible' => new external_value(PARAM_BOOL, 'Is the section visible for the user?', VALUE_OPTIONAL),
437 'availabilityinfo' => new external_value(PARAM_RAW, 'Availability information.', VALUE_OPTIONAL),
438 'modules' => new external_multiple_structure(
439 new external_single_structure(
440 array(
441 'id' => new external_value(PARAM_INT, 'activity id'),
442 'url' => new external_value(PARAM_URL, 'activity url', VALUE_OPTIONAL),
443 'name' => new external_value(PARAM_RAW, 'activity module name'),
444 'instance' => new external_value(PARAM_INT, 'instance id', VALUE_OPTIONAL),
445 'description' => new external_value(PARAM_RAW, 'activity description', VALUE_OPTIONAL),
446 'visible' => new external_value(PARAM_INT, 'is the module visible', VALUE_OPTIONAL),
447 'uservisible' => new external_value(PARAM_BOOL, 'Is the module visible for the user?',
448 VALUE_OPTIONAL),
449 'availabilityinfo' => new external_value(PARAM_RAW, 'Availability information.',
450 VALUE_OPTIONAL),
451 'visibleoncoursepage' => new external_value(PARAM_INT, 'is the module visible on course page',
452 VALUE_OPTIONAL),
453 'modicon' => new external_value(PARAM_URL, 'activity icon url'),
454 'modname' => new external_value(PARAM_PLUGIN, 'activity module type'),
455 'modplural' => new external_value(PARAM_TEXT, 'activity module plural name'),
456 'availability' => new external_value(PARAM_RAW, 'module availability settings', VALUE_OPTIONAL),
457 'indent' => new external_value(PARAM_INT, 'number of identation in the site'),
458 'onclick' => new external_value(PARAM_RAW, 'Onclick action.', VALUE_OPTIONAL),
459 'afterlink' => new external_value(PARAM_RAW, 'After link info to be displayed.',
460 VALUE_OPTIONAL),
461 'customdata' => new external_value(PARAM_RAW, 'Custom data (JSON encoded).', VALUE_OPTIONAL),
462 'noviewlink' => new external_value(PARAM_BOOL, 'Whether the module has no view page',
463 VALUE_OPTIONAL),
464 'completion' => new external_value(PARAM_INT, 'Type of completion tracking:
465 0 means none, 1 manual, 2 automatic.', VALUE_OPTIONAL),
466 'completiondata' => new external_single_structure(
467 array(
468 'state' => new external_value(PARAM_INT, 'Completion state value:
469 0 means incomplete, 1 complete, 2 complete pass, 3 complete fail'),
470 'timecompleted' => new external_value(PARAM_INT, 'Timestamp for completion status.'),
471 'overrideby' => new external_value(PARAM_INT, 'The user id who has overriden the
472 status.'),
473 'valueused' => new external_value(PARAM_BOOL, 'Whether the completion status affects
474 the availability of another activity.', VALUE_OPTIONAL),
475 ), 'Module completion data.', VALUE_OPTIONAL
477 'contents' => new external_multiple_structure(
478 new external_single_structure(
479 array(
480 // content info
481 'type'=> new external_value(PARAM_TEXT, 'a file or a folder or external link'),
482 'filename'=> new external_value(PARAM_FILE, 'filename'),
483 'filepath'=> new external_value(PARAM_PATH, 'filepath'),
484 'filesize'=> new external_value(PARAM_INT, 'filesize'),
485 'fileurl' => new external_value(PARAM_URL, 'downloadable file url', VALUE_OPTIONAL),
486 'content' => new external_value(PARAM_RAW, 'Raw content, will be used when type is content', VALUE_OPTIONAL),
487 'timecreated' => new external_value(PARAM_INT, 'Time created'),
488 'timemodified' => new external_value(PARAM_INT, 'Time modified'),
489 'sortorder' => new external_value(PARAM_INT, 'Content sort order'),
490 'mimetype' => new external_value(PARAM_RAW, 'File mime type.', VALUE_OPTIONAL),
491 'isexternalfile' => new external_value(PARAM_BOOL, 'Whether is an external file.',
492 VALUE_OPTIONAL),
493 'repositorytype' => new external_value(PARAM_PLUGIN, 'The repository type for external files.',
494 VALUE_OPTIONAL),
496 // copyright related info
497 'userid' => new external_value(PARAM_INT, 'User who added this content to moodle'),
498 'author' => new external_value(PARAM_TEXT, 'Content owner'),
499 'license' => new external_value(PARAM_TEXT, 'Content license'),
500 'tags' => new external_multiple_structure(
501 \core_tag\external\tag_item_exporter::get_read_structure(), 'Tags',
502 VALUE_OPTIONAL
505 ), VALUE_DEFAULT, array()
507 'contentsinfo' => new external_single_structure(
508 array(
509 'filescount' => new external_value(PARAM_INT, 'Total number of files.'),
510 'filessize' => new external_value(PARAM_INT, 'Total files size.'),
511 'lastmodified' => new external_value(PARAM_INT, 'Last time files were modified.'),
512 'mimetypes' => new external_multiple_structure(
513 new external_value(PARAM_RAW, 'File mime type.'),
514 'Files mime types.'
516 'repositorytype' => new external_value(PARAM_PLUGIN, 'The repository type for
517 the main file.', VALUE_OPTIONAL),
518 ), 'Contents summary information.', VALUE_OPTIONAL
521 ), 'list of module'
529 * Returns description of method parameters
531 * @return external_function_parameters
532 * @since Moodle 2.3
534 public static function get_courses_parameters() {
535 return new external_function_parameters(
536 array('options' => new external_single_structure(
537 array('ids' => new external_multiple_structure(
538 new external_value(PARAM_INT, 'Course id')
539 , 'List of course id. If empty return all courses
540 except front page course.',
541 VALUE_OPTIONAL)
542 ), 'options - operator OR is used', VALUE_DEFAULT, array())
548 * Get courses
550 * @param array $options It contains an array (list of ids)
551 * @return array
552 * @since Moodle 2.2
554 public static function get_courses($options = array()) {
555 global $CFG, $DB;
556 require_once($CFG->dirroot . "/course/lib.php");
558 //validate parameter
559 $params = self::validate_parameters(self::get_courses_parameters(),
560 array('options' => $options));
562 //retrieve courses
563 if (!array_key_exists('ids', $params['options'])
564 or empty($params['options']['ids'])) {
565 $courses = $DB->get_records('course');
566 } else {
567 $courses = $DB->get_records_list('course', 'id', $params['options']['ids']);
570 //create return value
571 $coursesinfo = array();
572 foreach ($courses as $course) {
574 // now security checks
575 $context = context_course::instance($course->id, IGNORE_MISSING);
576 $courseformatoptions = course_get_format($course)->get_format_options();
577 try {
578 self::validate_context($context);
579 } catch (Exception $e) {
580 $exceptionparam = new stdClass();
581 $exceptionparam->message = $e->getMessage();
582 $exceptionparam->courseid = $course->id;
583 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
585 if ($course->id != SITEID) {
586 require_capability('moodle/course:view', $context);
589 $courseinfo = array();
590 $courseinfo['id'] = $course->id;
591 $courseinfo['fullname'] = external_format_string($course->fullname, $context->id);
592 $courseinfo['shortname'] = external_format_string($course->shortname, $context->id);
593 $courseinfo['displayname'] = external_format_string(get_course_display_name_for_list($course), $context->id);
594 $courseinfo['categoryid'] = $course->category;
595 list($courseinfo['summary'], $courseinfo['summaryformat']) =
596 external_format_text($course->summary, $course->summaryformat, $context->id, 'course', 'summary', 0);
597 $courseinfo['format'] = $course->format;
598 $courseinfo['startdate'] = $course->startdate;
599 $courseinfo['enddate'] = $course->enddate;
600 if (array_key_exists('numsections', $courseformatoptions)) {
601 // For backward-compartibility
602 $courseinfo['numsections'] = $courseformatoptions['numsections'];
605 $handler = core_course\customfield\course_handler::create();
606 if ($customfields = $handler->export_instance_data($course->id)) {
607 $courseinfo['customfields'] = [];
608 foreach ($customfields as $data) {
609 $courseinfo['customfields'][] = [
610 'type' => $data->get_type(),
611 'value' => $data->get_value(),
612 'name' => $data->get_name(),
613 'shortname' => $data->get_shortname()
618 //some field should be returned only if the user has update permission
619 $courseadmin = has_capability('moodle/course:update', $context);
620 if ($courseadmin) {
621 $courseinfo['categorysortorder'] = $course->sortorder;
622 $courseinfo['idnumber'] = $course->idnumber;
623 $courseinfo['showgrades'] = $course->showgrades;
624 $courseinfo['showreports'] = $course->showreports;
625 $courseinfo['newsitems'] = $course->newsitems;
626 $courseinfo['visible'] = $course->visible;
627 $courseinfo['maxbytes'] = $course->maxbytes;
628 if (array_key_exists('hiddensections', $courseformatoptions)) {
629 // For backward-compartibility
630 $courseinfo['hiddensections'] = $courseformatoptions['hiddensections'];
632 // Return numsections for backward-compatibility with clients who expect it.
633 $courseinfo['numsections'] = course_get_format($course)->get_last_section_number();
634 $courseinfo['groupmode'] = $course->groupmode;
635 $courseinfo['groupmodeforce'] = $course->groupmodeforce;
636 $courseinfo['defaultgroupingid'] = $course->defaultgroupingid;
637 $courseinfo['lang'] = clean_param($course->lang, PARAM_LANG);
638 $courseinfo['timecreated'] = $course->timecreated;
639 $courseinfo['timemodified'] = $course->timemodified;
640 $courseinfo['forcetheme'] = clean_param($course->theme, PARAM_THEME);
641 $courseinfo['enablecompletion'] = $course->enablecompletion;
642 $courseinfo['completionnotify'] = $course->completionnotify;
643 $courseinfo['courseformatoptions'] = array();
644 foreach ($courseformatoptions as $key => $value) {
645 $courseinfo['courseformatoptions'][] = array(
646 'name' => $key,
647 'value' => $value
652 if ($courseadmin or $course->visible
653 or has_capability('moodle/course:viewhiddencourses', $context)) {
654 $coursesinfo[] = $courseinfo;
658 return $coursesinfo;
662 * Returns description of method result value
664 * @return external_description
665 * @since Moodle 2.2
667 public static function get_courses_returns() {
668 return new external_multiple_structure(
669 new external_single_structure(
670 array(
671 'id' => new external_value(PARAM_INT, 'course id'),
672 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
673 'categoryid' => new external_value(PARAM_INT, 'category id'),
674 'categorysortorder' => new external_value(PARAM_INT,
675 'sort order into the category', VALUE_OPTIONAL),
676 'fullname' => new external_value(PARAM_TEXT, 'full name'),
677 'displayname' => new external_value(PARAM_TEXT, 'course display name'),
678 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
679 'summary' => new external_value(PARAM_RAW, 'summary'),
680 'summaryformat' => new external_format_value('summary'),
681 'format' => new external_value(PARAM_PLUGIN,
682 'course format: weeks, topics, social, site,..'),
683 'showgrades' => new external_value(PARAM_INT,
684 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
685 'newsitems' => new external_value(PARAM_INT,
686 'number of recent items appearing on the course page', VALUE_OPTIONAL),
687 'startdate' => new external_value(PARAM_INT,
688 'timestamp when the course start'),
689 'enddate' => new external_value(PARAM_INT,
690 'timestamp when the course end'),
691 'numsections' => new external_value(PARAM_INT,
692 '(deprecated, use courseformatoptions) number of weeks/topics',
693 VALUE_OPTIONAL),
694 'maxbytes' => new external_value(PARAM_INT,
695 'largest size of file that can be uploaded into the course',
696 VALUE_OPTIONAL),
697 'showreports' => new external_value(PARAM_INT,
698 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
699 'visible' => new external_value(PARAM_INT,
700 '1: available to student, 0:not available', VALUE_OPTIONAL),
701 'hiddensections' => new external_value(PARAM_INT,
702 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
703 VALUE_OPTIONAL),
704 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
705 VALUE_OPTIONAL),
706 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
707 VALUE_OPTIONAL),
708 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
709 VALUE_OPTIONAL),
710 'timecreated' => new external_value(PARAM_INT,
711 'timestamp when the course have been created', VALUE_OPTIONAL),
712 'timemodified' => new external_value(PARAM_INT,
713 'timestamp when the course have been modified', VALUE_OPTIONAL),
714 'enablecompletion' => new external_value(PARAM_INT,
715 'Enabled, control via completion and activity settings. Disbaled,
716 not shown in activity settings.',
717 VALUE_OPTIONAL),
718 'completionnotify' => new external_value(PARAM_INT,
719 '1: yes 0: no', VALUE_OPTIONAL),
720 'lang' => new external_value(PARAM_SAFEDIR,
721 'forced course language', VALUE_OPTIONAL),
722 'forcetheme' => new external_value(PARAM_PLUGIN,
723 'name of the force theme', VALUE_OPTIONAL),
724 'courseformatoptions' => new external_multiple_structure(
725 new external_single_structure(
726 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
727 'value' => new external_value(PARAM_RAW, 'course format option value')
728 )), 'additional options for particular course format', VALUE_OPTIONAL
730 'customfields' => new external_multiple_structure(
731 new external_single_structure(
732 ['name' => new external_value(PARAM_TEXT, 'The name of the custom field'),
733 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'The shortname of the custom field'),
734 'type' => new external_value(PARAM_COMPONENT,
735 'The type of the custom field - text, checkbox...'),
736 'value' => new external_value(PARAM_RAW, 'The value of the custom field')]
737 ), 'Custom fields and associated values', VALUE_OPTIONAL),
738 ), 'course'
744 * Returns description of method parameters
746 * @return external_function_parameters
747 * @since Moodle 2.2
749 public static function create_courses_parameters() {
750 $courseconfig = get_config('moodlecourse'); //needed for many default values
751 return new external_function_parameters(
752 array(
753 'courses' => new external_multiple_structure(
754 new external_single_structure(
755 array(
756 'fullname' => new external_value(PARAM_TEXT, 'full name'),
757 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
758 'categoryid' => new external_value(PARAM_INT, 'category id'),
759 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
760 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
761 'summaryformat' => new external_format_value('summary', VALUE_DEFAULT),
762 'format' => new external_value(PARAM_PLUGIN,
763 'course format: weeks, topics, social, site,..',
764 VALUE_DEFAULT, $courseconfig->format),
765 'showgrades' => new external_value(PARAM_INT,
766 '1 if grades are shown, otherwise 0', VALUE_DEFAULT,
767 $courseconfig->showgrades),
768 'newsitems' => new external_value(PARAM_INT,
769 'number of recent items appearing on the course page',
770 VALUE_DEFAULT, $courseconfig->newsitems),
771 'startdate' => new external_value(PARAM_INT,
772 'timestamp when the course start', VALUE_OPTIONAL),
773 'enddate' => new external_value(PARAM_INT,
774 'timestamp when the course end', VALUE_OPTIONAL),
775 'numsections' => new external_value(PARAM_INT,
776 '(deprecated, use courseformatoptions) number of weeks/topics',
777 VALUE_OPTIONAL),
778 'maxbytes' => new external_value(PARAM_INT,
779 'largest size of file that can be uploaded into the course',
780 VALUE_DEFAULT, $courseconfig->maxbytes),
781 'showreports' => new external_value(PARAM_INT,
782 'are activity report shown (yes = 1, no =0)', VALUE_DEFAULT,
783 $courseconfig->showreports),
784 'visible' => new external_value(PARAM_INT,
785 '1: available to student, 0:not available', VALUE_OPTIONAL),
786 'hiddensections' => new external_value(PARAM_INT,
787 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
788 VALUE_OPTIONAL),
789 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
790 VALUE_DEFAULT, $courseconfig->groupmode),
791 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
792 VALUE_DEFAULT, $courseconfig->groupmodeforce),
793 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
794 VALUE_DEFAULT, 0),
795 'enablecompletion' => new external_value(PARAM_INT,
796 'Enabled, control via completion and activity settings. Disabled,
797 not shown in activity settings.',
798 VALUE_OPTIONAL),
799 'completionnotify' => new external_value(PARAM_INT,
800 '1: yes 0: no', VALUE_OPTIONAL),
801 'lang' => new external_value(PARAM_SAFEDIR,
802 'forced course language', VALUE_OPTIONAL),
803 'forcetheme' => new external_value(PARAM_PLUGIN,
804 'name of the force theme', VALUE_OPTIONAL),
805 'courseformatoptions' => new external_multiple_structure(
806 new external_single_structure(
807 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
808 'value' => new external_value(PARAM_RAW, 'course format option value')
810 'additional options for particular course format', VALUE_OPTIONAL),
811 'customfields' => new external_multiple_structure(
812 new external_single_structure(
813 array(
814 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'The shortname of the custom field'),
815 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
816 )), 'custom fields for the course', VALUE_OPTIONAL
818 )), 'courses to create'
825 * Create courses
827 * @param array $courses
828 * @return array courses (id and shortname only)
829 * @since Moodle 2.2
831 public static function create_courses($courses) {
832 global $CFG, $DB;
833 require_once($CFG->dirroot . "/course/lib.php");
834 require_once($CFG->libdir . '/completionlib.php');
836 $params = self::validate_parameters(self::create_courses_parameters(),
837 array('courses' => $courses));
839 $availablethemes = core_component::get_plugin_list('theme');
840 $availablelangs = get_string_manager()->get_list_of_translations();
842 $transaction = $DB->start_delegated_transaction();
844 foreach ($params['courses'] as $course) {
846 // Ensure the current user is allowed to run this function
847 $context = context_coursecat::instance($course['categoryid'], IGNORE_MISSING);
848 try {
849 self::validate_context($context);
850 } catch (Exception $e) {
851 $exceptionparam = new stdClass();
852 $exceptionparam->message = $e->getMessage();
853 $exceptionparam->catid = $course['categoryid'];
854 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
856 require_capability('moodle/course:create', $context);
858 // Fullname and short name are required to be non-empty.
859 if (trim($course['fullname']) === '') {
860 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'fullname');
861 } else if (trim($course['shortname']) === '') {
862 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'shortname');
865 // Make sure lang is valid
866 if (array_key_exists('lang', $course)) {
867 if (empty($availablelangs[$course['lang']])) {
868 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
870 if (!has_capability('moodle/course:setforcedlanguage', $context)) {
871 unset($course['lang']);
875 // Make sure theme is valid
876 if (array_key_exists('forcetheme', $course)) {
877 if (!empty($CFG->allowcoursethemes)) {
878 if (empty($availablethemes[$course['forcetheme']])) {
879 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
880 } else {
881 $course['theme'] = $course['forcetheme'];
886 //force visibility if ws user doesn't have the permission to set it
887 $category = $DB->get_record('course_categories', array('id' => $course['categoryid']));
888 if (!has_capability('moodle/course:visibility', $context)) {
889 $course['visible'] = $category->visible;
892 //set default value for completion
893 $courseconfig = get_config('moodlecourse');
894 if (completion_info::is_enabled_for_site()) {
895 if (!array_key_exists('enablecompletion', $course)) {
896 $course['enablecompletion'] = $courseconfig->enablecompletion;
898 } else {
899 $course['enablecompletion'] = 0;
902 $course['category'] = $course['categoryid'];
904 // Summary format.
905 $course['summaryformat'] = external_validate_format($course['summaryformat']);
907 if (!empty($course['courseformatoptions'])) {
908 foreach ($course['courseformatoptions'] as $option) {
909 $course[$option['name']] = $option['value'];
913 // Custom fields.
914 if (!empty($course['customfields'])) {
915 foreach ($course['customfields'] as $field) {
916 $course['customfield_'.$field['shortname']] = $field['value'];
920 //Note: create_course() core function check shortname, idnumber, category
921 $course['id'] = create_course((object) $course)->id;
923 $resultcourses[] = array('id' => $course['id'], 'shortname' => $course['shortname']);
926 $transaction->allow_commit();
928 return $resultcourses;
932 * Returns description of method result value
934 * @return external_description
935 * @since Moodle 2.2
937 public static function create_courses_returns() {
938 return new external_multiple_structure(
939 new external_single_structure(
940 array(
941 'id' => new external_value(PARAM_INT, 'course id'),
942 'shortname' => new external_value(PARAM_TEXT, 'short name'),
949 * Update courses
951 * @return external_function_parameters
952 * @since Moodle 2.5
954 public static function update_courses_parameters() {
955 return new external_function_parameters(
956 array(
957 'courses' => new external_multiple_structure(
958 new external_single_structure(
959 array(
960 'id' => new external_value(PARAM_INT, 'ID of the course'),
961 'fullname' => new external_value(PARAM_TEXT, 'full name', VALUE_OPTIONAL),
962 'shortname' => new external_value(PARAM_TEXT, 'course short name', VALUE_OPTIONAL),
963 'categoryid' => new external_value(PARAM_INT, 'category id', VALUE_OPTIONAL),
964 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
965 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
966 'summaryformat' => new external_format_value('summary', VALUE_OPTIONAL),
967 'format' => new external_value(PARAM_PLUGIN,
968 'course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
969 'showgrades' => new external_value(PARAM_INT,
970 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
971 'newsitems' => new external_value(PARAM_INT,
972 'number of recent items appearing on the course page', VALUE_OPTIONAL),
973 'startdate' => new external_value(PARAM_INT,
974 'timestamp when the course start', VALUE_OPTIONAL),
975 'enddate' => new external_value(PARAM_INT,
976 'timestamp when the course end', VALUE_OPTIONAL),
977 'numsections' => new external_value(PARAM_INT,
978 '(deprecated, use courseformatoptions) number of weeks/topics', VALUE_OPTIONAL),
979 'maxbytes' => new external_value(PARAM_INT,
980 'largest size of file that can be uploaded into the course', VALUE_OPTIONAL),
981 'showreports' => new external_value(PARAM_INT,
982 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
983 'visible' => new external_value(PARAM_INT,
984 '1: available to student, 0:not available', VALUE_OPTIONAL),
985 'hiddensections' => new external_value(PARAM_INT,
986 '(deprecated, use courseformatoptions) How the hidden sections in the course are
987 displayed to students', VALUE_OPTIONAL),
988 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
989 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
990 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
991 'enablecompletion' => new external_value(PARAM_INT,
992 'Enabled, control via completion and activity settings. Disabled,
993 not shown in activity settings.', VALUE_OPTIONAL),
994 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
995 'lang' => new external_value(PARAM_SAFEDIR, 'forced course language', VALUE_OPTIONAL),
996 'forcetheme' => new external_value(PARAM_PLUGIN, 'name of the force theme', VALUE_OPTIONAL),
997 'courseformatoptions' => new external_multiple_structure(
998 new external_single_structure(
999 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
1000 'value' => new external_value(PARAM_RAW, 'course format option value')
1001 )), 'additional options for particular course format', VALUE_OPTIONAL),
1002 'customfields' => new external_multiple_structure(
1003 new external_single_structure(
1005 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'The shortname of the custom field'),
1006 'value' => new external_value(PARAM_RAW, 'The value of the custom field')
1008 ), 'Custom fields', VALUE_OPTIONAL),
1010 ), 'courses to update'
1017 * Update courses
1019 * @param array $courses
1020 * @since Moodle 2.5
1022 public static function update_courses($courses) {
1023 global $CFG, $DB;
1024 require_once($CFG->dirroot . "/course/lib.php");
1025 $warnings = array();
1027 $params = self::validate_parameters(self::update_courses_parameters(),
1028 array('courses' => $courses));
1030 $availablethemes = core_component::get_plugin_list('theme');
1031 $availablelangs = get_string_manager()->get_list_of_translations();
1033 foreach ($params['courses'] as $course) {
1034 // Catch any exception while updating course and return as warning to user.
1035 try {
1036 // Ensure the current user is allowed to run this function.
1037 $context = context_course::instance($course['id'], MUST_EXIST);
1038 self::validate_context($context);
1040 $oldcourse = course_get_format($course['id'])->get_course();
1042 require_capability('moodle/course:update', $context);
1044 // Check if user can change category.
1045 if (array_key_exists('categoryid', $course) && ($oldcourse->category != $course['categoryid'])) {
1046 require_capability('moodle/course:changecategory', $context);
1047 $course['category'] = $course['categoryid'];
1050 // Check if the user can change fullname, and the new value is non-empty.
1051 if (array_key_exists('fullname', $course) && ($oldcourse->fullname != $course['fullname'])) {
1052 require_capability('moodle/course:changefullname', $context);
1053 if (trim($course['fullname']) === '') {
1054 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'fullname');
1058 // Check if the user can change shortname, and the new value is non-empty.
1059 if (array_key_exists('shortname', $course) && ($oldcourse->shortname != $course['shortname'])) {
1060 require_capability('moodle/course:changeshortname', $context);
1061 if (trim($course['shortname']) === '') {
1062 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'shortname');
1066 // Check if the user can change the idnumber.
1067 if (array_key_exists('idnumber', $course) && ($oldcourse->idnumber != $course['idnumber'])) {
1068 require_capability('moodle/course:changeidnumber', $context);
1071 // Check if user can change summary.
1072 if (array_key_exists('summary', $course) && ($oldcourse->summary != $course['summary'])) {
1073 require_capability('moodle/course:changesummary', $context);
1076 // Summary format.
1077 if (array_key_exists('summaryformat', $course) && ($oldcourse->summaryformat != $course['summaryformat'])) {
1078 require_capability('moodle/course:changesummary', $context);
1079 $course['summaryformat'] = external_validate_format($course['summaryformat']);
1082 // Check if user can change visibility.
1083 if (array_key_exists('visible', $course) && ($oldcourse->visible != $course['visible'])) {
1084 require_capability('moodle/course:visibility', $context);
1087 // Make sure lang is valid.
1088 if (array_key_exists('lang', $course) && ($oldcourse->lang != $course['lang'])) {
1089 require_capability('moodle/course:setforcedlanguage', $context);
1090 if (empty($availablelangs[$course['lang']])) {
1091 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
1095 // Make sure theme is valid.
1096 if (array_key_exists('forcetheme', $course)) {
1097 if (!empty($CFG->allowcoursethemes)) {
1098 if (empty($availablethemes[$course['forcetheme']])) {
1099 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
1100 } else {
1101 $course['theme'] = $course['forcetheme'];
1106 // Make sure completion is enabled before setting it.
1107 if (array_key_exists('enabledcompletion', $course) && !completion_info::is_enabled_for_site()) {
1108 $course['enabledcompletion'] = 0;
1111 // Make sure maxbytes are less then CFG->maxbytes.
1112 if (array_key_exists('maxbytes', $course)) {
1113 // We allow updates back to 0 max bytes, a special value denoting the course uses the site limit.
1114 // Otherwise, either use the size specified, or cap at the max size for the course.
1115 if ($course['maxbytes'] != 0) {
1116 $course['maxbytes'] = get_max_upload_file_size($CFG->maxbytes, $course['maxbytes']);
1120 if (!empty($course['courseformatoptions'])) {
1121 foreach ($course['courseformatoptions'] as $option) {
1122 if (isset($option['name']) && isset($option['value'])) {
1123 $course[$option['name']] = $option['value'];
1128 // Prepare list of custom fields.
1129 if (isset($course['customfields'])) {
1130 foreach ($course['customfields'] as $field) {
1131 $course['customfield_' . $field['shortname']] = $field['value'];
1135 // Update course if user has all required capabilities.
1136 update_course((object) $course);
1137 } catch (Exception $e) {
1138 $warning = array();
1139 $warning['item'] = 'course';
1140 $warning['itemid'] = $course['id'];
1141 if ($e instanceof moodle_exception) {
1142 $warning['warningcode'] = $e->errorcode;
1143 } else {
1144 $warning['warningcode'] = $e->getCode();
1146 $warning['message'] = $e->getMessage();
1147 $warnings[] = $warning;
1151 $result = array();
1152 $result['warnings'] = $warnings;
1153 return $result;
1157 * Returns description of method result value
1159 * @return external_description
1160 * @since Moodle 2.5
1162 public static function update_courses_returns() {
1163 return new external_single_structure(
1164 array(
1165 'warnings' => new external_warnings()
1171 * Returns description of method parameters
1173 * @return external_function_parameters
1174 * @since Moodle 2.2
1176 public static function delete_courses_parameters() {
1177 return new external_function_parameters(
1178 array(
1179 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'course ID')),
1185 * Delete courses
1187 * @param array $courseids A list of course ids
1188 * @since Moodle 2.2
1190 public static function delete_courses($courseids) {
1191 global $CFG, $DB;
1192 require_once($CFG->dirroot."/course/lib.php");
1194 // Parameter validation.
1195 $params = self::validate_parameters(self::delete_courses_parameters(), array('courseids'=>$courseids));
1197 $warnings = array();
1199 foreach ($params['courseids'] as $courseid) {
1200 $course = $DB->get_record('course', array('id' => $courseid));
1202 if ($course === false) {
1203 $warnings[] = array(
1204 'item' => 'course',
1205 'itemid' => $courseid,
1206 'warningcode' => 'unknowncourseidnumber',
1207 'message' => 'Unknown course ID ' . $courseid
1209 continue;
1212 // Check if the context is valid.
1213 $coursecontext = context_course::instance($course->id);
1214 self::validate_context($coursecontext);
1216 // Check if the current user has permission.
1217 if (!can_delete_course($courseid)) {
1218 $warnings[] = array(
1219 'item' => 'course',
1220 'itemid' => $courseid,
1221 'warningcode' => 'cannotdeletecourse',
1222 'message' => 'You do not have the permission to delete this course' . $courseid
1224 continue;
1227 if (delete_course($course, false) === false) {
1228 $warnings[] = array(
1229 'item' => 'course',
1230 'itemid' => $courseid,
1231 'warningcode' => 'cannotdeletecategorycourse',
1232 'message' => 'Course ' . $courseid . ' failed to be deleted'
1234 continue;
1238 fix_course_sortorder();
1240 return array('warnings' => $warnings);
1244 * Returns description of method result value
1246 * @return external_description
1247 * @since Moodle 2.2
1249 public static function delete_courses_returns() {
1250 return new external_single_structure(
1251 array(
1252 'warnings' => new external_warnings()
1258 * Returns description of method parameters
1260 * @return external_function_parameters
1261 * @since Moodle 2.3
1263 public static function duplicate_course_parameters() {
1264 return new external_function_parameters(
1265 array(
1266 'courseid' => new external_value(PARAM_INT, 'course to duplicate id'),
1267 'fullname' => new external_value(PARAM_TEXT, 'duplicated course full name'),
1268 'shortname' => new external_value(PARAM_TEXT, 'duplicated course short name'),
1269 'categoryid' => new external_value(PARAM_INT, 'duplicated course category parent'),
1270 'visible' => new external_value(PARAM_INT, 'duplicated course visible, default to yes', VALUE_DEFAULT, 1),
1271 'options' => new external_multiple_structure(
1272 new external_single_structure(
1273 array(
1274 'name' => new external_value(PARAM_ALPHAEXT, 'The backup option name:
1275 "activities" (int) Include course activites (default to 1 that is equal to yes),
1276 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1277 "filters" (int) Include course filters (default to 1 that is equal to yes),
1278 "users" (int) Include users (default to 0 that is equal to no),
1279 "enrolments" (int) Include enrolment methods (default to 1 - restore only with users),
1280 "role_assignments" (int) Include role assignments (default to 0 that is equal to no),
1281 "comments" (int) Include user comments (default to 0 that is equal to no),
1282 "userscompletion" (int) Include user course completion information (default to 0 that is equal to no),
1283 "logs" (int) Include course logs (default to 0 that is equal to no),
1284 "grade_histories" (int) Include histories (default to 0 that is equal to no)'
1286 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1289 ), VALUE_DEFAULT, array()
1296 * Duplicate a course
1298 * @param int $courseid
1299 * @param string $fullname Duplicated course fullname
1300 * @param string $shortname Duplicated course shortname
1301 * @param int $categoryid Duplicated course parent category id
1302 * @param int $visible Duplicated course availability
1303 * @param array $options List of backup options
1304 * @return array New course info
1305 * @since Moodle 2.3
1307 public static function duplicate_course($courseid, $fullname, $shortname, $categoryid, $visible = 1, $options = array()) {
1308 global $CFG, $USER, $DB;
1309 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1310 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1312 // Parameter validation.
1313 $params = self::validate_parameters(
1314 self::duplicate_course_parameters(),
1315 array(
1316 'courseid' => $courseid,
1317 'fullname' => $fullname,
1318 'shortname' => $shortname,
1319 'categoryid' => $categoryid,
1320 'visible' => $visible,
1321 'options' => $options
1325 // Context validation.
1327 if (! ($course = $DB->get_record('course', array('id'=>$params['courseid'])))) {
1328 throw new moodle_exception('invalidcourseid', 'error');
1331 // Category where duplicated course is going to be created.
1332 $categorycontext = context_coursecat::instance($params['categoryid']);
1333 self::validate_context($categorycontext);
1335 // Course to be duplicated.
1336 $coursecontext = context_course::instance($course->id);
1337 self::validate_context($coursecontext);
1339 $backupdefaults = array(
1340 'activities' => 1,
1341 'blocks' => 1,
1342 'filters' => 1,
1343 'users' => 0,
1344 'enrolments' => backup::ENROL_WITHUSERS,
1345 'role_assignments' => 0,
1346 'comments' => 0,
1347 'userscompletion' => 0,
1348 'logs' => 0,
1349 'grade_histories' => 0
1352 $backupsettings = array();
1353 // Check for backup and restore options.
1354 if (!empty($params['options'])) {
1355 foreach ($params['options'] as $option) {
1357 // Strict check for a correct value (allways 1 or 0, true or false).
1358 $value = clean_param($option['value'], PARAM_INT);
1360 if ($value !== 0 and $value !== 1) {
1361 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1364 if (!isset($backupdefaults[$option['name']])) {
1365 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1368 $backupsettings[$option['name']] = $value;
1372 // Capability checking.
1374 // The backup controller check for this currently, this may be redundant.
1375 require_capability('moodle/course:create', $categorycontext);
1376 require_capability('moodle/restore:restorecourse', $categorycontext);
1377 require_capability('moodle/backup:backupcourse', $coursecontext);
1379 if (!empty($backupsettings['users'])) {
1380 require_capability('moodle/backup:userinfo', $coursecontext);
1381 require_capability('moodle/restore:userinfo', $categorycontext);
1384 // Check if the shortname is used.
1385 if ($foundcourses = $DB->get_records('course', array('shortname'=>$shortname))) {
1386 foreach ($foundcourses as $foundcourse) {
1387 $foundcoursenames[] = $foundcourse->fullname;
1390 $foundcoursenamestring = implode(',', $foundcoursenames);
1391 throw new moodle_exception('shortnametaken', '', '', $foundcoursenamestring);
1394 // Backup the course.
1396 $bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE,
1397 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id);
1399 foreach ($backupsettings as $name => $value) {
1400 if ($setting = $bc->get_plan()->get_setting($name)) {
1401 $bc->get_plan()->get_setting($name)->set_value($value);
1405 $backupid = $bc->get_backupid();
1406 $backupbasepath = $bc->get_plan()->get_basepath();
1408 $bc->execute_plan();
1409 $results = $bc->get_results();
1410 $file = $results['backup_destination'];
1412 $bc->destroy();
1414 // Restore the backup immediately.
1416 // Check if we need to unzip the file because the backup temp dir does not contains backup files.
1417 if (!file_exists($backupbasepath . "/moodle_backup.xml")) {
1418 $file->extract_to_pathname(get_file_packer('application/vnd.moodle.backup'), $backupbasepath);
1421 // Create new course.
1422 $newcourseid = restore_dbops::create_new_course($params['fullname'], $params['shortname'], $params['categoryid']);
1424 $rc = new restore_controller($backupid, $newcourseid,
1425 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id, backup::TARGET_NEW_COURSE);
1427 foreach ($backupsettings as $name => $value) {
1428 $setting = $rc->get_plan()->get_setting($name);
1429 if ($setting->get_status() == backup_setting::NOT_LOCKED) {
1430 $setting->set_value($value);
1434 if (!$rc->execute_precheck()) {
1435 $precheckresults = $rc->get_precheck_results();
1436 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1437 if (empty($CFG->keeptempdirectoriesonbackup)) {
1438 fulldelete($backupbasepath);
1441 $errorinfo = '';
1443 foreach ($precheckresults['errors'] as $error) {
1444 $errorinfo .= $error;
1447 if (array_key_exists('warnings', $precheckresults)) {
1448 foreach ($precheckresults['warnings'] as $warning) {
1449 $errorinfo .= $warning;
1453 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1457 $rc->execute_plan();
1458 $rc->destroy();
1460 $course = $DB->get_record('course', array('id' => $newcourseid), '*', MUST_EXIST);
1461 $course->fullname = $params['fullname'];
1462 $course->shortname = $params['shortname'];
1463 $course->visible = $params['visible'];
1465 // Set shortname and fullname back.
1466 $DB->update_record('course', $course);
1468 if (empty($CFG->keeptempdirectoriesonbackup)) {
1469 fulldelete($backupbasepath);
1472 // Delete the course backup file created by this WebService. Originally located in the course backups area.
1473 $file->delete();
1475 return array('id' => $course->id, 'shortname' => $course->shortname);
1479 * Returns description of method result value
1481 * @return external_description
1482 * @since Moodle 2.3
1484 public static function duplicate_course_returns() {
1485 return new external_single_structure(
1486 array(
1487 'id' => new external_value(PARAM_INT, 'course id'),
1488 'shortname' => new external_value(PARAM_TEXT, 'short name'),
1494 * Returns description of method parameters for import_course
1496 * @return external_function_parameters
1497 * @since Moodle 2.4
1499 public static function import_course_parameters() {
1500 return new external_function_parameters(
1501 array(
1502 'importfrom' => new external_value(PARAM_INT, 'the id of the course we are importing from'),
1503 'importto' => new external_value(PARAM_INT, 'the id of the course we are importing to'),
1504 'deletecontent' => new external_value(PARAM_INT, 'whether to delete the course content where we are importing to (default to 0 = No)', VALUE_DEFAULT, 0),
1505 'options' => new external_multiple_structure(
1506 new external_single_structure(
1507 array(
1508 'name' => new external_value(PARAM_ALPHA, 'The backup option name:
1509 "activities" (int) Include course activites (default to 1 that is equal to yes),
1510 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1511 "filters" (int) Include course filters (default to 1 that is equal to yes)'
1513 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1516 ), VALUE_DEFAULT, array()
1523 * Imports a course
1525 * @param int $importfrom The id of the course we are importing from
1526 * @param int $importto The id of the course we are importing to
1527 * @param bool $deletecontent Whether to delete the course we are importing to content
1528 * @param array $options List of backup options
1529 * @return null
1530 * @since Moodle 2.4
1532 public static function import_course($importfrom, $importto, $deletecontent = 0, $options = array()) {
1533 global $CFG, $USER, $DB;
1534 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1535 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1537 // Parameter validation.
1538 $params = self::validate_parameters(
1539 self::import_course_parameters(),
1540 array(
1541 'importfrom' => $importfrom,
1542 'importto' => $importto,
1543 'deletecontent' => $deletecontent,
1544 'options' => $options
1548 if ($params['deletecontent'] !== 0 and $params['deletecontent'] !== 1) {
1549 throw new moodle_exception('invalidextparam', 'webservice', '', $params['deletecontent']);
1552 // Context validation.
1554 if (! ($importfrom = $DB->get_record('course', array('id'=>$params['importfrom'])))) {
1555 throw new moodle_exception('invalidcourseid', 'error');
1558 if (! ($importto = $DB->get_record('course', array('id'=>$params['importto'])))) {
1559 throw new moodle_exception('invalidcourseid', 'error');
1562 $importfromcontext = context_course::instance($importfrom->id);
1563 self::validate_context($importfromcontext);
1565 $importtocontext = context_course::instance($importto->id);
1566 self::validate_context($importtocontext);
1568 $backupdefaults = array(
1569 'activities' => 1,
1570 'blocks' => 1,
1571 'filters' => 1
1574 $backupsettings = array();
1576 // Check for backup and restore options.
1577 if (!empty($params['options'])) {
1578 foreach ($params['options'] as $option) {
1580 // Strict check for a correct value (allways 1 or 0, true or false).
1581 $value = clean_param($option['value'], PARAM_INT);
1583 if ($value !== 0 and $value !== 1) {
1584 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1587 if (!isset($backupdefaults[$option['name']])) {
1588 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1591 $backupsettings[$option['name']] = $value;
1595 // Capability checking.
1597 require_capability('moodle/backup:backuptargetimport', $importfromcontext);
1598 require_capability('moodle/restore:restoretargetimport', $importtocontext);
1600 $bc = new backup_controller(backup::TYPE_1COURSE, $importfrom->id, backup::FORMAT_MOODLE,
1601 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
1603 foreach ($backupsettings as $name => $value) {
1604 $bc->get_plan()->get_setting($name)->set_value($value);
1607 $backupid = $bc->get_backupid();
1608 $backupbasepath = $bc->get_plan()->get_basepath();
1610 $bc->execute_plan();
1611 $bc->destroy();
1613 // Restore the backup immediately.
1615 // Check if we must delete the contents of the destination course.
1616 if ($params['deletecontent']) {
1617 $restoretarget = backup::TARGET_EXISTING_DELETING;
1618 } else {
1619 $restoretarget = backup::TARGET_EXISTING_ADDING;
1622 $rc = new restore_controller($backupid, $importto->id,
1623 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, $restoretarget);
1625 foreach ($backupsettings as $name => $value) {
1626 $rc->get_plan()->get_setting($name)->set_value($value);
1629 if (!$rc->execute_precheck()) {
1630 $precheckresults = $rc->get_precheck_results();
1631 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1632 if (empty($CFG->keeptempdirectoriesonbackup)) {
1633 fulldelete($backupbasepath);
1636 $errorinfo = '';
1638 foreach ($precheckresults['errors'] as $error) {
1639 $errorinfo .= $error;
1642 if (array_key_exists('warnings', $precheckresults)) {
1643 foreach ($precheckresults['warnings'] as $warning) {
1644 $errorinfo .= $warning;
1648 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1650 } else {
1651 if ($restoretarget == backup::TARGET_EXISTING_DELETING) {
1652 restore_dbops::delete_course_content($importto->id);
1656 $rc->execute_plan();
1657 $rc->destroy();
1659 if (empty($CFG->keeptempdirectoriesonbackup)) {
1660 fulldelete($backupbasepath);
1663 return null;
1667 * Returns description of method result value
1669 * @return external_description
1670 * @since Moodle 2.4
1672 public static function import_course_returns() {
1673 return null;
1677 * Returns description of method parameters
1679 * @return external_function_parameters
1680 * @since Moodle 2.3
1682 public static function get_categories_parameters() {
1683 return new external_function_parameters(
1684 array(
1685 'criteria' => new external_multiple_structure(
1686 new external_single_structure(
1687 array(
1688 'key' => new external_value(PARAM_ALPHA,
1689 'The category column to search, expected keys (value format) are:'.
1690 '"id" (int) the category id,'.
1691 '"ids" (string) category ids separated by commas,'.
1692 '"name" (string) the category name,'.
1693 '"parent" (int) the parent category id,'.
1694 '"idnumber" (string) category idnumber'.
1695 ' - user must have \'moodle/category:manage\' to search on idnumber,'.
1696 '"visible" (int) whether the returned categories must be visible or hidden. If the key is not passed,
1697 then the function return all categories that the user can see.'.
1698 ' - user must have \'moodle/category:manage\' or \'moodle/category:viewhiddencategories\' to search on visible,'.
1699 '"theme" (string) only return the categories having this theme'.
1700 ' - user must have \'moodle/category:manage\' to search on theme'),
1701 'value' => new external_value(PARAM_RAW, 'the value to match')
1703 ), 'criteria', VALUE_DEFAULT, array()
1705 'addsubcategories' => new external_value(PARAM_BOOL, 'return the sub categories infos
1706 (1 - default) otherwise only the category info (0)', VALUE_DEFAULT, 1)
1712 * Get categories
1714 * @param array $criteria Criteria to match the results
1715 * @param booln $addsubcategories obtain only the category (false) or its subcategories (true - default)
1716 * @return array list of categories
1717 * @since Moodle 2.3
1719 public static function get_categories($criteria = array(), $addsubcategories = true) {
1720 global $CFG, $DB;
1721 require_once($CFG->dirroot . "/course/lib.php");
1723 // Validate parameters.
1724 $params = self::validate_parameters(self::get_categories_parameters(),
1725 array('criteria' => $criteria, 'addsubcategories' => $addsubcategories));
1727 // Retrieve the categories.
1728 $categories = array();
1729 if (!empty($params['criteria'])) {
1731 $conditions = array();
1732 $wheres = array();
1733 foreach ($params['criteria'] as $crit) {
1734 $key = trim($crit['key']);
1736 // Trying to avoid duplicate keys.
1737 if (!isset($conditions[$key])) {
1739 $context = context_system::instance();
1740 $value = null;
1741 switch ($key) {
1742 case 'id':
1743 $value = clean_param($crit['value'], PARAM_INT);
1744 $conditions[$key] = $value;
1745 $wheres[] = $key . " = :" . $key;
1746 break;
1748 case 'ids':
1749 $value = clean_param($crit['value'], PARAM_SEQUENCE);
1750 $ids = explode(',', $value);
1751 list($sqlids, $paramids) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED);
1752 $conditions = array_merge($conditions, $paramids);
1753 $wheres[] = 'id ' . $sqlids;
1754 break;
1756 case 'idnumber':
1757 if (has_capability('moodle/category:manage', $context)) {
1758 $value = clean_param($crit['value'], PARAM_RAW);
1759 $conditions[$key] = $value;
1760 $wheres[] = $key . " = :" . $key;
1761 } else {
1762 // We must throw an exception.
1763 // Otherwise the dev client would think no idnumber exists.
1764 throw new moodle_exception('criteriaerror',
1765 'webservice', '', null,
1766 'You don\'t have the permissions to search on the "idnumber" field.');
1768 break;
1770 case 'name':
1771 $value = clean_param($crit['value'], PARAM_TEXT);
1772 $conditions[$key] = $value;
1773 $wheres[] = $key . " = :" . $key;
1774 break;
1776 case 'parent':
1777 $value = clean_param($crit['value'], PARAM_INT);
1778 $conditions[$key] = $value;
1779 $wheres[] = $key . " = :" . $key;
1780 break;
1782 case 'visible':
1783 if (has_capability('moodle/category:viewhiddencategories', $context)) {
1784 $value = clean_param($crit['value'], PARAM_INT);
1785 $conditions[$key] = $value;
1786 $wheres[] = $key . " = :" . $key;
1787 } else {
1788 throw new moodle_exception('criteriaerror',
1789 'webservice', '', null,
1790 'You don\'t have the permissions to search on the "visible" field.');
1792 break;
1794 case 'theme':
1795 if (has_capability('moodle/category:manage', $context)) {
1796 $value = clean_param($crit['value'], PARAM_THEME);
1797 $conditions[$key] = $value;
1798 $wheres[] = $key . " = :" . $key;
1799 } else {
1800 throw new moodle_exception('criteriaerror',
1801 'webservice', '', null,
1802 'You don\'t have the permissions to search on the "theme" field.');
1804 break;
1806 default:
1807 throw new moodle_exception('criteriaerror',
1808 'webservice', '', null,
1809 'You can not search on this criteria: ' . $key);
1814 if (!empty($wheres)) {
1815 $wheres = implode(" AND ", $wheres);
1817 $categories = $DB->get_records_select('course_categories', $wheres, $conditions);
1819 // Retrieve its sub subcategories (all levels).
1820 if ($categories and !empty($params['addsubcategories'])) {
1821 $newcategories = array();
1823 // Check if we required visible/theme checks.
1824 $additionalselect = '';
1825 $additionalparams = array();
1826 if (isset($conditions['visible'])) {
1827 $additionalselect .= ' AND visible = :visible';
1828 $additionalparams['visible'] = $conditions['visible'];
1830 if (isset($conditions['theme'])) {
1831 $additionalselect .= ' AND theme= :theme';
1832 $additionalparams['theme'] = $conditions['theme'];
1835 foreach ($categories as $category) {
1836 $sqlselect = $DB->sql_like('path', ':path') . $additionalselect;
1837 $sqlparams = array('path' => $category->path.'/%') + $additionalparams; // It will NOT include the specified category.
1838 $subcategories = $DB->get_records_select('course_categories', $sqlselect, $sqlparams);
1839 $newcategories = $newcategories + $subcategories; // Both arrays have integer as keys.
1841 $categories = $categories + $newcategories;
1845 } else {
1846 // Retrieve all categories in the database.
1847 $categories = $DB->get_records('course_categories');
1850 // The not returned categories. key => category id, value => reason of exclusion.
1851 $excludedcats = array();
1853 // The returned categories.
1854 $categoriesinfo = array();
1856 // We need to sort the categories by path.
1857 // The parent cats need to be checked by the algo first.
1858 usort($categories, "core_course_external::compare_categories_by_path");
1860 foreach ($categories as $category) {
1862 // Check if the category is a child of an excluded category, if yes exclude it too (excluded => do not return).
1863 $parents = explode('/', $category->path);
1864 unset($parents[0]); // First key is always empty because path start with / => /1/2/4.
1865 foreach ($parents as $parentid) {
1866 // Note: when the parent exclusion was due to the context,
1867 // the sub category could still be returned.
1868 if (isset($excludedcats[$parentid]) and $excludedcats[$parentid] != 'context') {
1869 $excludedcats[$category->id] = 'parent';
1873 // Check the user can use the category context.
1874 $context = context_coursecat::instance($category->id);
1875 try {
1876 self::validate_context($context);
1877 } catch (Exception $e) {
1878 $excludedcats[$category->id] = 'context';
1880 // If it was the requested category then throw an exception.
1881 if (isset($params['categoryid']) && $category->id == $params['categoryid']) {
1882 $exceptionparam = new stdClass();
1883 $exceptionparam->message = $e->getMessage();
1884 $exceptionparam->catid = $category->id;
1885 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
1889 // Return the category information.
1890 if (!isset($excludedcats[$category->id])) {
1892 // Final check to see if the category is visible to the user.
1893 if (core_course_category::can_view_category($category)) {
1895 $categoryinfo = array();
1896 $categoryinfo['id'] = $category->id;
1897 $categoryinfo['name'] = external_format_string($category->name, $context);
1898 list($categoryinfo['description'], $categoryinfo['descriptionformat']) =
1899 external_format_text($category->description, $category->descriptionformat,
1900 $context->id, 'coursecat', 'description', null);
1901 $categoryinfo['parent'] = $category->parent;
1902 $categoryinfo['sortorder'] = $category->sortorder;
1903 $categoryinfo['coursecount'] = $category->coursecount;
1904 $categoryinfo['depth'] = $category->depth;
1905 $categoryinfo['path'] = $category->path;
1907 // Some fields only returned for admin.
1908 if (has_capability('moodle/category:manage', $context)) {
1909 $categoryinfo['idnumber'] = $category->idnumber;
1910 $categoryinfo['visible'] = $category->visible;
1911 $categoryinfo['visibleold'] = $category->visibleold;
1912 $categoryinfo['timemodified'] = $category->timemodified;
1913 $categoryinfo['theme'] = clean_param($category->theme, PARAM_THEME);
1916 $categoriesinfo[] = $categoryinfo;
1917 } else {
1918 $excludedcats[$category->id] = 'visibility';
1923 // Sorting the resulting array so it looks a bit better for the client developer.
1924 usort($categoriesinfo, "core_course_external::compare_categories_by_sortorder");
1926 return $categoriesinfo;
1930 * Sort categories array by path
1931 * private function: only used by get_categories
1933 * @param array $category1
1934 * @param array $category2
1935 * @return int result of strcmp
1936 * @since Moodle 2.3
1938 private static function compare_categories_by_path($category1, $category2) {
1939 return strcmp($category1->path, $category2->path);
1943 * Sort categories array by sortorder
1944 * private function: only used by get_categories
1946 * @param array $category1
1947 * @param array $category2
1948 * @return int result of strcmp
1949 * @since Moodle 2.3
1951 private static function compare_categories_by_sortorder($category1, $category2) {
1952 return strcmp($category1['sortorder'], $category2['sortorder']);
1956 * Returns description of method result value
1958 * @return external_description
1959 * @since Moodle 2.3
1961 public static function get_categories_returns() {
1962 return new external_multiple_structure(
1963 new external_single_structure(
1964 array(
1965 'id' => new external_value(PARAM_INT, 'category id'),
1966 'name' => new external_value(PARAM_TEXT, 'category name'),
1967 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1968 'description' => new external_value(PARAM_RAW, 'category description'),
1969 'descriptionformat' => new external_format_value('description'),
1970 'parent' => new external_value(PARAM_INT, 'parent category id'),
1971 'sortorder' => new external_value(PARAM_INT, 'category sorting order'),
1972 'coursecount' => new external_value(PARAM_INT, 'number of courses in this category'),
1973 'visible' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1974 'visibleold' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1975 'timemodified' => new external_value(PARAM_INT, 'timestamp', VALUE_OPTIONAL),
1976 'depth' => new external_value(PARAM_INT, 'category depth'),
1977 'path' => new external_value(PARAM_TEXT, 'category path'),
1978 'theme' => new external_value(PARAM_THEME, 'category theme', VALUE_OPTIONAL),
1979 ), 'List of categories'
1985 * Returns description of method parameters
1987 * @return external_function_parameters
1988 * @since Moodle 2.3
1990 public static function create_categories_parameters() {
1991 return new external_function_parameters(
1992 array(
1993 'categories' => new external_multiple_structure(
1994 new external_single_structure(
1995 array(
1996 'name' => new external_value(PARAM_TEXT, 'new category name'),
1997 'parent' => new external_value(PARAM_INT,
1998 'the parent category id inside which the new category will be created
1999 - set to 0 for a root category',
2000 VALUE_DEFAULT, 0),
2001 'idnumber' => new external_value(PARAM_RAW,
2002 'the new category idnumber', VALUE_OPTIONAL),
2003 'description' => new external_value(PARAM_RAW,
2004 'the new category description', VALUE_OPTIONAL),
2005 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
2006 'theme' => new external_value(PARAM_THEME,
2007 'the new category theme. This option must be enabled on moodle',
2008 VALUE_OPTIONAL),
2017 * Create categories
2019 * @param array $categories - see create_categories_parameters() for the array structure
2020 * @return array - see create_categories_returns() for the array structure
2021 * @since Moodle 2.3
2023 public static function create_categories($categories) {
2024 global $DB;
2026 $params = self::validate_parameters(self::create_categories_parameters(),
2027 array('categories' => $categories));
2029 $transaction = $DB->start_delegated_transaction();
2031 $createdcategories = array();
2032 foreach ($params['categories'] as $category) {
2033 if ($category['parent']) {
2034 if (!$DB->record_exists('course_categories', array('id' => $category['parent']))) {
2035 throw new moodle_exception('unknowcategory');
2037 $context = context_coursecat::instance($category['parent']);
2038 } else {
2039 $context = context_system::instance();
2041 self::validate_context($context);
2042 require_capability('moodle/category:manage', $context);
2044 // this will validate format and throw an exception if there are errors
2045 external_validate_format($category['descriptionformat']);
2047 $newcategory = core_course_category::create($category);
2048 $context = context_coursecat::instance($newcategory->id);
2050 $createdcategories[] = array(
2051 'id' => $newcategory->id,
2052 'name' => external_format_string($newcategory->name, $context),
2056 $transaction->allow_commit();
2058 return $createdcategories;
2062 * Returns description of method parameters
2064 * @return external_function_parameters
2065 * @since Moodle 2.3
2067 public static function create_categories_returns() {
2068 return new external_multiple_structure(
2069 new external_single_structure(
2070 array(
2071 'id' => new external_value(PARAM_INT, 'new category id'),
2072 'name' => new external_value(PARAM_TEXT, 'new category name'),
2079 * Returns description of method parameters
2081 * @return external_function_parameters
2082 * @since Moodle 2.3
2084 public static function update_categories_parameters() {
2085 return new external_function_parameters(
2086 array(
2087 'categories' => new external_multiple_structure(
2088 new external_single_structure(
2089 array(
2090 'id' => new external_value(PARAM_INT, 'course id'),
2091 'name' => new external_value(PARAM_TEXT, 'category name', VALUE_OPTIONAL),
2092 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
2093 'parent' => new external_value(PARAM_INT, 'parent category id', VALUE_OPTIONAL),
2094 'description' => new external_value(PARAM_RAW, 'category description', VALUE_OPTIONAL),
2095 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
2096 'theme' => new external_value(PARAM_THEME,
2097 'the category theme. This option must be enabled on moodle', VALUE_OPTIONAL),
2106 * Update categories
2108 * @param array $categories The list of categories to update
2109 * @return null
2110 * @since Moodle 2.3
2112 public static function update_categories($categories) {
2113 global $DB;
2115 // Validate parameters.
2116 $params = self::validate_parameters(self::update_categories_parameters(), array('categories' => $categories));
2118 $transaction = $DB->start_delegated_transaction();
2120 foreach ($params['categories'] as $cat) {
2121 $category = core_course_category::get($cat['id']);
2123 $categorycontext = context_coursecat::instance($cat['id']);
2124 self::validate_context($categorycontext);
2125 require_capability('moodle/category:manage', $categorycontext);
2127 // this will throw an exception if descriptionformat is not valid
2128 external_validate_format($cat['descriptionformat']);
2130 $category->update($cat);
2133 $transaction->allow_commit();
2137 * Returns description of method result value
2139 * @return external_description
2140 * @since Moodle 2.3
2142 public static function update_categories_returns() {
2143 return null;
2147 * Returns description of method parameters
2149 * @return external_function_parameters
2150 * @since Moodle 2.3
2152 public static function delete_categories_parameters() {
2153 return new external_function_parameters(
2154 array(
2155 'categories' => new external_multiple_structure(
2156 new external_single_structure(
2157 array(
2158 'id' => new external_value(PARAM_INT, 'category id to delete'),
2159 'newparent' => new external_value(PARAM_INT,
2160 'the parent category to move the contents to, if specified', VALUE_OPTIONAL),
2161 'recursive' => new external_value(PARAM_BOOL, '1: recursively delete all contents inside this
2162 category, 0 (default): move contents to newparent or current parent category (except if parent is root)', VALUE_DEFAULT, 0)
2171 * Delete categories
2173 * @param array $categories A list of category ids
2174 * @return array
2175 * @since Moodle 2.3
2177 public static function delete_categories($categories) {
2178 global $CFG, $DB;
2179 require_once($CFG->dirroot . "/course/lib.php");
2181 // Validate parameters.
2182 $params = self::validate_parameters(self::delete_categories_parameters(), array('categories' => $categories));
2184 $transaction = $DB->start_delegated_transaction();
2186 foreach ($params['categories'] as $category) {
2187 $deletecat = core_course_category::get($category['id'], MUST_EXIST);
2188 $context = context_coursecat::instance($deletecat->id);
2189 require_capability('moodle/category:manage', $context);
2190 self::validate_context($context);
2191 self::validate_context(get_category_or_system_context($deletecat->parent));
2193 if ($category['recursive']) {
2194 // If recursive was specified, then we recursively delete the category's contents.
2195 if ($deletecat->can_delete_full()) {
2196 $deletecat->delete_full(false);
2197 } else {
2198 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2200 } else {
2201 // In this situation, we don't delete the category's contents, we either move it to newparent or parent.
2202 // If the parent is the root, moving is not supported (because a course must always be inside a category).
2203 // We must move to an existing category.
2204 if (!empty($category['newparent'])) {
2205 $newparentcat = core_course_category::get($category['newparent']);
2206 } else {
2207 $newparentcat = core_course_category::get($deletecat->parent);
2210 // This operation is not allowed. We must move contents to an existing category.
2211 if (!$newparentcat->id) {
2212 throw new moodle_exception('movecatcontentstoroot');
2215 self::validate_context(context_coursecat::instance($newparentcat->id));
2216 if ($deletecat->can_move_content_to($newparentcat->id)) {
2217 $deletecat->delete_move($newparentcat->id, false);
2218 } else {
2219 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2224 $transaction->allow_commit();
2228 * Returns description of method parameters
2230 * @return external_function_parameters
2231 * @since Moodle 2.3
2233 public static function delete_categories_returns() {
2234 return null;
2238 * Describes the parameters for delete_modules.
2240 * @return external_function_parameters
2241 * @since Moodle 2.5
2243 public static function delete_modules_parameters() {
2244 return new external_function_parameters (
2245 array(
2246 'cmids' => new external_multiple_structure(new external_value(PARAM_INT, 'course module ID',
2247 VALUE_REQUIRED, '', NULL_NOT_ALLOWED), 'Array of course module IDs'),
2253 * Deletes a list of provided module instances.
2255 * @param array $cmids the course module ids
2256 * @since Moodle 2.5
2258 public static function delete_modules($cmids) {
2259 global $CFG, $DB;
2261 // Require course file containing the course delete module function.
2262 require_once($CFG->dirroot . "/course/lib.php");
2264 // Clean the parameters.
2265 $params = self::validate_parameters(self::delete_modules_parameters(), array('cmids' => $cmids));
2267 // Keep track of the course ids we have performed a capability check on to avoid repeating.
2268 $arrcourseschecked = array();
2270 foreach ($params['cmids'] as $cmid) {
2271 // Get the course module.
2272 $cm = $DB->get_record('course_modules', array('id' => $cmid), '*', MUST_EXIST);
2274 // Check if we have not yet confirmed they have permission in this course.
2275 if (!in_array($cm->course, $arrcourseschecked)) {
2276 // Ensure the current user has required permission in this course.
2277 $context = context_course::instance($cm->course);
2278 self::validate_context($context);
2279 // Add to the array.
2280 $arrcourseschecked[] = $cm->course;
2283 // Ensure they can delete this module.
2284 $modcontext = context_module::instance($cm->id);
2285 require_capability('moodle/course:manageactivities', $modcontext);
2287 // Delete the module.
2288 course_delete_module($cm->id);
2293 * Describes the delete_modules return value.
2295 * @return external_single_structure
2296 * @since Moodle 2.5
2298 public static function delete_modules_returns() {
2299 return null;
2303 * Returns description of method parameters
2305 * @return external_function_parameters
2306 * @since Moodle 2.9
2308 public static function view_course_parameters() {
2309 return new external_function_parameters(
2310 array(
2311 'courseid' => new external_value(PARAM_INT, 'id of the course'),
2312 'sectionnumber' => new external_value(PARAM_INT, 'section number', VALUE_DEFAULT, 0)
2318 * Trigger the course viewed event.
2320 * @param int $courseid id of course
2321 * @param int $sectionnumber sectionnumber (0, 1, 2...)
2322 * @return array of warnings and status result
2323 * @since Moodle 2.9
2324 * @throws moodle_exception
2326 public static function view_course($courseid, $sectionnumber = 0) {
2327 global $CFG;
2328 require_once($CFG->dirroot . "/course/lib.php");
2330 $params = self::validate_parameters(self::view_course_parameters(),
2331 array(
2332 'courseid' => $courseid,
2333 'sectionnumber' => $sectionnumber
2336 $warnings = array();
2338 $course = get_course($params['courseid']);
2339 $context = context_course::instance($course->id);
2340 self::validate_context($context);
2342 if (!empty($params['sectionnumber'])) {
2344 // Get section details and check it exists.
2345 $modinfo = get_fast_modinfo($course);
2346 $coursesection = $modinfo->get_section_info($params['sectionnumber'], MUST_EXIST);
2348 // Check user is allowed to see it.
2349 if (!$coursesection->uservisible) {
2350 require_capability('moodle/course:viewhiddensections', $context);
2354 course_view($context, $params['sectionnumber']);
2356 $result = array();
2357 $result['status'] = true;
2358 $result['warnings'] = $warnings;
2359 return $result;
2363 * Returns description of method result value
2365 * @return external_description
2366 * @since Moodle 2.9
2368 public static function view_course_returns() {
2369 return new external_single_structure(
2370 array(
2371 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
2372 'warnings' => new external_warnings()
2378 * Returns description of method parameters
2380 * @return external_function_parameters
2381 * @since Moodle 3.0
2383 public static function search_courses_parameters() {
2384 return new external_function_parameters(
2385 array(
2386 'criterianame' => new external_value(PARAM_ALPHA, 'criteria name
2387 (search, modulelist (only admins), blocklist (only admins), tagid)'),
2388 'criteriavalue' => new external_value(PARAM_RAW, 'criteria value'),
2389 'page' => new external_value(PARAM_INT, 'page number (0 based)', VALUE_DEFAULT, 0),
2390 'perpage' => new external_value(PARAM_INT, 'items per page', VALUE_DEFAULT, 0),
2391 'requiredcapabilities' => new external_multiple_structure(
2392 new external_value(PARAM_CAPABILITY, 'Capability string used to filter courses by permission'),
2393 'Optional list of required capabilities (used to filter the list)', VALUE_DEFAULT, array()
2395 'limittoenrolled' => new external_value(PARAM_BOOL, 'limit to enrolled courses', VALUE_DEFAULT, 0),
2396 'onlywithcompletion' => new external_value(PARAM_BOOL, 'limit to courses where completion is enabled',
2397 VALUE_DEFAULT, 0),
2403 * Return the course information that is public (visible by every one)
2405 * @param core_course_list_element $course course in list object
2406 * @param stdClass $coursecontext course context object
2407 * @return array the course information
2408 * @since Moodle 3.2
2410 protected static function get_course_public_information(core_course_list_element $course, $coursecontext) {
2412 static $categoriescache = array();
2414 // Category information.
2415 if (!array_key_exists($course->category, $categoriescache)) {
2416 $categoriescache[$course->category] = core_course_category::get($course->category, IGNORE_MISSING);
2418 $category = $categoriescache[$course->category];
2420 // Retrieve course overview used files.
2421 $files = array();
2422 foreach ($course->get_course_overviewfiles() as $file) {
2423 $fileurl = moodle_url::make_webservice_pluginfile_url($file->get_contextid(), $file->get_component(),
2424 $file->get_filearea(), null, $file->get_filepath(),
2425 $file->get_filename())->out(false);
2426 $files[] = array(
2427 'filename' => $file->get_filename(),
2428 'fileurl' => $fileurl,
2429 'filesize' => $file->get_filesize(),
2430 'filepath' => $file->get_filepath(),
2431 'mimetype' => $file->get_mimetype(),
2432 'timemodified' => $file->get_timemodified(),
2436 // Retrieve the course contacts,
2437 // we need here the users fullname since if we are not enrolled can be difficult to obtain them via other Web Services.
2438 $coursecontacts = array();
2439 foreach ($course->get_course_contacts() as $contact) {
2440 $coursecontacts[] = array(
2441 'id' => $contact['user']->id,
2442 'fullname' => $contact['username'],
2443 'roles' => array_map(function($role){
2444 return array('id' => $role->id, 'name' => $role->displayname);
2445 }, $contact['roles']),
2446 'role' => array('id' => $contact['role']->id, 'name' => $contact['role']->displayname),
2447 'rolename' => $contact['rolename']
2451 // Allowed enrolment methods (maybe we can self-enrol).
2452 $enroltypes = array();
2453 $instances = enrol_get_instances($course->id, true);
2454 foreach ($instances as $instance) {
2455 $enroltypes[] = $instance->enrol;
2458 // Format summary.
2459 list($summary, $summaryformat) =
2460 external_format_text($course->summary, $course->summaryformat, $coursecontext->id, 'course', 'summary', null);
2462 $categoryname = '';
2463 if (!empty($category)) {
2464 $categoryname = external_format_string($category->name, $category->get_context());
2467 $displayname = get_course_display_name_for_list($course);
2468 $coursereturns = array();
2469 $coursereturns['id'] = $course->id;
2470 $coursereturns['fullname'] = external_format_string($course->fullname, $coursecontext->id);
2471 $coursereturns['displayname'] = external_format_string($displayname, $coursecontext->id);
2472 $coursereturns['shortname'] = external_format_string($course->shortname, $coursecontext->id);
2473 $coursereturns['categoryid'] = $course->category;
2474 $coursereturns['categoryname'] = $categoryname;
2475 $coursereturns['summary'] = $summary;
2476 $coursereturns['summaryformat'] = $summaryformat;
2477 $coursereturns['summaryfiles'] = external_util::get_area_files($coursecontext->id, 'course', 'summary', false, false);
2478 $coursereturns['overviewfiles'] = $files;
2479 $coursereturns['contacts'] = $coursecontacts;
2480 $coursereturns['enrollmentmethods'] = $enroltypes;
2481 $coursereturns['sortorder'] = $course->sortorder;
2483 $handler = core_course\customfield\course_handler::create();
2484 if ($customfields = $handler->export_instance_data($course->id)) {
2485 $coursereturns['customfields'] = [];
2486 foreach ($customfields as $data) {
2487 $coursereturns['customfields'][] = [
2488 'type' => $data->get_type(),
2489 'value' => $data->get_value(),
2490 'name' => $data->get_name(),
2491 'shortname' => $data->get_shortname()
2496 return $coursereturns;
2500 * Search courses following the specified criteria.
2502 * @param string $criterianame Criteria name (search, modulelist (only admins), blocklist (only admins), tagid)
2503 * @param string $criteriavalue Criteria value
2504 * @param int $page Page number (for pagination)
2505 * @param int $perpage Items per page
2506 * @param array $requiredcapabilities Optional list of required capabilities (used to filter the list).
2507 * @param int $limittoenrolled Limit to only enrolled courses
2508 * @param int onlywithcompletion Limit to only courses where completion is enabled
2509 * @return array of course objects and warnings
2510 * @since Moodle 3.0
2511 * @throws moodle_exception
2513 public static function search_courses($criterianame,
2514 $criteriavalue,
2515 $page=0,
2516 $perpage=0,
2517 $requiredcapabilities=array(),
2518 $limittoenrolled=0,
2519 $onlywithcompletion=0) {
2520 global $CFG;
2522 $warnings = array();
2524 $parameters = array(
2525 'criterianame' => $criterianame,
2526 'criteriavalue' => $criteriavalue,
2527 'page' => $page,
2528 'perpage' => $perpage,
2529 'requiredcapabilities' => $requiredcapabilities,
2530 'limittoenrolled' => $limittoenrolled,
2531 'onlywithcompletion' => $onlywithcompletion
2533 $params = self::validate_parameters(self::search_courses_parameters(), $parameters);
2534 self::validate_context(context_system::instance());
2536 $allowedcriterianames = array('search', 'modulelist', 'blocklist', 'tagid');
2537 if (!in_array($params['criterianame'], $allowedcriterianames)) {
2538 throw new invalid_parameter_exception('Invalid value for criterianame parameter (value: '.$params['criterianame'].'),' .
2539 'allowed values are: '.implode(',', $allowedcriterianames));
2542 if ($params['criterianame'] == 'modulelist' or $params['criterianame'] == 'blocklist') {
2543 require_capability('moodle/site:config', context_system::instance());
2546 $paramtype = array(
2547 'search' => PARAM_RAW,
2548 'modulelist' => PARAM_PLUGIN,
2549 'blocklist' => PARAM_INT,
2550 'tagid' => PARAM_INT
2552 $params['criteriavalue'] = clean_param($params['criteriavalue'], $paramtype[$params['criterianame']]);
2554 // Prepare the search API options.
2555 $searchcriteria = array();
2556 $searchcriteria[$params['criterianame']] = $params['criteriavalue'];
2557 if ($params['onlywithcompletion']) {
2558 $searchcriteria['onlywithcompletion'] = true;
2561 $options = array();
2562 if ($params['perpage'] != 0) {
2563 $offset = $params['page'] * $params['perpage'];
2564 $options = array('offset' => $offset, 'limit' => $params['perpage']);
2567 // Search the courses.
2568 $courses = core_course_category::search_courses($searchcriteria, $options, $params['requiredcapabilities']);
2569 $totalcount = core_course_category::search_courses_count($searchcriteria, $options, $params['requiredcapabilities']);
2571 if (!empty($limittoenrolled)) {
2572 // Get the courses where the current user has access.
2573 $enrolled = enrol_get_my_courses(array('id', 'cacherev'));
2576 $finalcourses = array();
2577 $categoriescache = array();
2579 foreach ($courses as $course) {
2580 if (!empty($limittoenrolled)) {
2581 // Filter out not enrolled courses.
2582 if (!isset($enrolled[$course->id])) {
2583 $totalcount--;
2584 continue;
2588 $coursecontext = context_course::instance($course->id);
2590 $finalcourses[] = self::get_course_public_information($course, $coursecontext);
2593 return array(
2594 'total' => $totalcount,
2595 'courses' => $finalcourses,
2596 'warnings' => $warnings
2601 * Returns a course structure definition
2603 * @param boolean $onlypublicdata set to true, to retrieve only fields viewable by anyone when the course is visible
2604 * @return array the course structure
2605 * @since Moodle 3.2
2607 protected static function get_course_structure($onlypublicdata = true) {
2608 $coursestructure = array(
2609 'id' => new external_value(PARAM_INT, 'course id'),
2610 'fullname' => new external_value(PARAM_TEXT, 'course full name'),
2611 'displayname' => new external_value(PARAM_TEXT, 'course display name'),
2612 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
2613 'categoryid' => new external_value(PARAM_INT, 'category id'),
2614 'categoryname' => new external_value(PARAM_TEXT, 'category name'),
2615 'sortorder' => new external_value(PARAM_INT, 'Sort order in the category', VALUE_OPTIONAL),
2616 'summary' => new external_value(PARAM_RAW, 'summary'),
2617 'summaryformat' => new external_format_value('summary'),
2618 'summaryfiles' => new external_files('summary files in the summary field', VALUE_OPTIONAL),
2619 'overviewfiles' => new external_files('additional overview files attached to this course'),
2620 'contacts' => new external_multiple_structure(
2621 new external_single_structure(
2622 array(
2623 'id' => new external_value(PARAM_INT, 'contact user id'),
2624 'fullname' => new external_value(PARAM_NOTAGS, 'contact user fullname'),
2627 'contact users'
2629 'enrollmentmethods' => new external_multiple_structure(
2630 new external_value(PARAM_PLUGIN, 'enrollment method'),
2631 'enrollment methods list'
2633 'customfields' => new external_multiple_structure(
2634 new external_single_structure(
2635 array(
2636 'name' => new external_value(PARAM_RAW, 'The name of the custom field'),
2637 'shortname' => new external_value(PARAM_RAW,
2638 'The shortname of the custom field - to be able to build the field class in the code'),
2639 'type' => new external_value(PARAM_ALPHANUMEXT,
2640 'The type of the custom field - text field, checkbox...'),
2641 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
2643 ), 'Custom fields', VALUE_OPTIONAL),
2646 if (!$onlypublicdata) {
2647 $extra = array(
2648 'idnumber' => new external_value(PARAM_RAW, 'Id number', VALUE_OPTIONAL),
2649 'format' => new external_value(PARAM_PLUGIN, 'Course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
2650 'showgrades' => new external_value(PARAM_INT, '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
2651 'newsitems' => new external_value(PARAM_INT, 'Number of recent items appearing on the course page', VALUE_OPTIONAL),
2652 'startdate' => new external_value(PARAM_INT, 'Timestamp when the course start', VALUE_OPTIONAL),
2653 'enddate' => new external_value(PARAM_INT, 'Timestamp when the course end', VALUE_OPTIONAL),
2654 'maxbytes' => new external_value(PARAM_INT, 'Largest size of file that can be uploaded into', VALUE_OPTIONAL),
2655 'showreports' => new external_value(PARAM_INT, 'Are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
2656 'visible' => new external_value(PARAM_INT, '1: available to student, 0:not available', VALUE_OPTIONAL),
2657 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
2658 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
2659 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
2660 'enablecompletion' => new external_value(PARAM_INT, 'Completion enabled? 1: yes 0: no', VALUE_OPTIONAL),
2661 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
2662 'lang' => new external_value(PARAM_SAFEDIR, 'Forced course language', VALUE_OPTIONAL),
2663 'theme' => new external_value(PARAM_PLUGIN, 'Fame of the forced theme', VALUE_OPTIONAL),
2664 'marker' => new external_value(PARAM_INT, 'Current course marker', VALUE_OPTIONAL),
2665 'legacyfiles' => new external_value(PARAM_INT, 'If legacy files are enabled', VALUE_OPTIONAL),
2666 'calendartype' => new external_value(PARAM_PLUGIN, 'Calendar type', VALUE_OPTIONAL),
2667 'timecreated' => new external_value(PARAM_INT, 'Time when the course was created', VALUE_OPTIONAL),
2668 'timemodified' => new external_value(PARAM_INT, 'Last time the course was updated', VALUE_OPTIONAL),
2669 'requested' => new external_value(PARAM_INT, 'If is a requested course', VALUE_OPTIONAL),
2670 'cacherev' => new external_value(PARAM_INT, 'Cache revision number', VALUE_OPTIONAL),
2671 'filters' => new external_multiple_structure(
2672 new external_single_structure(
2673 array(
2674 'filter' => new external_value(PARAM_PLUGIN, 'Filter plugin name'),
2675 'localstate' => new external_value(PARAM_INT, 'Filter state: 1 for on, -1 for off, 0 if inherit'),
2676 'inheritedstate' => new external_value(PARAM_INT, '1 or 0 to use when localstate is set to inherit'),
2679 'Course filters', VALUE_OPTIONAL
2681 'courseformatoptions' => new external_multiple_structure(
2682 new external_single_structure(
2683 array(
2684 'name' => new external_value(PARAM_RAW, 'Course format option name.'),
2685 'value' => new external_value(PARAM_RAW, 'Course format option value.'),
2688 'Additional options for particular course format.', VALUE_OPTIONAL
2691 $coursestructure = array_merge($coursestructure, $extra);
2693 return new external_single_structure($coursestructure);
2697 * Returns description of method result value
2699 * @return external_description
2700 * @since Moodle 3.0
2702 public static function search_courses_returns() {
2703 return new external_single_structure(
2704 array(
2705 'total' => new external_value(PARAM_INT, 'total course count'),
2706 'courses' => new external_multiple_structure(self::get_course_structure(), 'course'),
2707 'warnings' => new external_warnings()
2713 * Returns description of method parameters
2715 * @return external_function_parameters
2716 * @since Moodle 3.0
2718 public static function get_course_module_parameters() {
2719 return new external_function_parameters(
2720 array(
2721 'cmid' => new external_value(PARAM_INT, 'The course module id')
2727 * Return information about a course module.
2729 * @param int $cmid the course module id
2730 * @return array of warnings and the course module
2731 * @since Moodle 3.0
2732 * @throws moodle_exception
2734 public static function get_course_module($cmid) {
2735 global $CFG, $DB;
2737 $params = self::validate_parameters(self::get_course_module_parameters(), array('cmid' => $cmid));
2738 $warnings = array();
2740 $cm = get_coursemodule_from_id(null, $params['cmid'], 0, true, MUST_EXIST);
2741 $context = context_module::instance($cm->id);
2742 self::validate_context($context);
2744 // If the user has permissions to manage the activity, return all the information.
2745 if (has_capability('moodle/course:manageactivities', $context)) {
2746 require_once($CFG->dirroot . '/course/modlib.php');
2747 require_once($CFG->libdir . '/gradelib.php');
2749 $info = $cm;
2750 // Get the extra information: grade, advanced grading and outcomes data.
2751 $course = get_course($cm->course);
2752 list($newcm, $newcontext, $module, $extrainfo, $cw) = get_moduleinfo_data($cm, $course);
2753 // Grades.
2754 $gradeinfo = array('grade', 'gradepass', 'gradecat');
2755 foreach ($gradeinfo as $gfield) {
2756 if (isset($extrainfo->{$gfield})) {
2757 $info->{$gfield} = $extrainfo->{$gfield};
2760 if (isset($extrainfo->grade) and $extrainfo->grade < 0) {
2761 $info->scale = $DB->get_field('scale', 'scale', array('id' => abs($extrainfo->grade)));
2763 // Advanced grading.
2764 if (isset($extrainfo->_advancedgradingdata)) {
2765 $info->advancedgrading = array();
2766 foreach ($extrainfo as $key => $val) {
2767 if (strpos($key, 'advancedgradingmethod_') === 0) {
2768 $info->advancedgrading[] = array(
2769 'area' => str_replace('advancedgradingmethod_', '', $key),
2770 'method' => $val
2775 // Outcomes.
2776 foreach ($extrainfo as $key => $val) {
2777 if (strpos($key, 'outcome_') === 0) {
2778 if (!isset($info->outcomes)) {
2779 $info->outcomes = array();
2781 $id = str_replace('outcome_', '', $key);
2782 $outcome = grade_outcome::fetch(array('id' => $id));
2783 $scaleitems = $outcome->load_scale();
2784 $info->outcomes[] = array(
2785 'id' => $id,
2786 'name' => external_format_string($outcome->get_name(), $context->id),
2787 'scale' => $scaleitems->scale
2791 } else {
2792 // Return information is safe to show to any user.
2793 $info = new stdClass();
2794 $info->id = $cm->id;
2795 $info->course = $cm->course;
2796 $info->module = $cm->module;
2797 $info->modname = $cm->modname;
2798 $info->instance = $cm->instance;
2799 $info->section = $cm->section;
2800 $info->sectionnum = $cm->sectionnum;
2801 $info->groupmode = $cm->groupmode;
2802 $info->groupingid = $cm->groupingid;
2803 $info->completion = $cm->completion;
2805 // Format name.
2806 $info->name = external_format_string($cm->name, $context->id);
2807 $result = array();
2808 $result['cm'] = $info;
2809 $result['warnings'] = $warnings;
2810 return $result;
2814 * Returns description of method result value
2816 * @return external_description
2817 * @since Moodle 3.0
2819 public static function get_course_module_returns() {
2820 return new external_single_structure(
2821 array(
2822 'cm' => new external_single_structure(
2823 array(
2824 'id' => new external_value(PARAM_INT, 'The course module id'),
2825 'course' => new external_value(PARAM_INT, 'The course id'),
2826 'module' => new external_value(PARAM_INT, 'The module type id'),
2827 'name' => new external_value(PARAM_RAW, 'The activity name'),
2828 'modname' => new external_value(PARAM_COMPONENT, 'The module component name (forum, assign, etc..)'),
2829 'instance' => new external_value(PARAM_INT, 'The activity instance id'),
2830 'section' => new external_value(PARAM_INT, 'The module section id'),
2831 'sectionnum' => new external_value(PARAM_INT, 'The module section number'),
2832 'groupmode' => new external_value(PARAM_INT, 'Group mode'),
2833 'groupingid' => new external_value(PARAM_INT, 'Grouping id'),
2834 'completion' => new external_value(PARAM_INT, 'If completion is enabled'),
2835 'idnumber' => new external_value(PARAM_RAW, 'Module id number', VALUE_OPTIONAL),
2836 'added' => new external_value(PARAM_INT, 'Time added', VALUE_OPTIONAL),
2837 'score' => new external_value(PARAM_INT, 'Score', VALUE_OPTIONAL),
2838 'indent' => new external_value(PARAM_INT, 'Indentation', VALUE_OPTIONAL),
2839 'visible' => new external_value(PARAM_INT, 'If visible', VALUE_OPTIONAL),
2840 'visibleoncoursepage' => new external_value(PARAM_INT, 'If visible on course page', VALUE_OPTIONAL),
2841 'visibleold' => new external_value(PARAM_INT, 'Visible old', VALUE_OPTIONAL),
2842 'completiongradeitemnumber' => new external_value(PARAM_INT, 'Completion grade item', VALUE_OPTIONAL),
2843 'completionview' => new external_value(PARAM_INT, 'Completion view setting', VALUE_OPTIONAL),
2844 'completionexpected' => new external_value(PARAM_INT, 'Completion time expected', VALUE_OPTIONAL),
2845 'showdescription' => new external_value(PARAM_INT, 'If the description is showed', VALUE_OPTIONAL),
2846 'availability' => new external_value(PARAM_RAW, 'Availability settings', VALUE_OPTIONAL),
2847 'grade' => new external_value(PARAM_FLOAT, 'Grade (max value or scale id)', VALUE_OPTIONAL),
2848 'scale' => new external_value(PARAM_TEXT, 'Scale items (if used)', VALUE_OPTIONAL),
2849 'gradepass' => new external_value(PARAM_RAW, 'Grade to pass (float)', VALUE_OPTIONAL),
2850 'gradecat' => new external_value(PARAM_INT, 'Grade category', VALUE_OPTIONAL),
2851 'advancedgrading' => new external_multiple_structure(
2852 new external_single_structure(
2853 array(
2854 'area' => new external_value(PARAM_AREA, 'Gradable area name'),
2855 'method' => new external_value(PARAM_COMPONENT, 'Grading method'),
2858 'Advanced grading settings', VALUE_OPTIONAL
2860 'outcomes' => new external_multiple_structure(
2861 new external_single_structure(
2862 array(
2863 'id' => new external_value(PARAM_ALPHANUMEXT, 'Outcome id'),
2864 'name' => new external_value(PARAM_TEXT, 'Outcome full name'),
2865 'scale' => new external_value(PARAM_TEXT, 'Scale items')
2868 'Outcomes information', VALUE_OPTIONAL
2872 'warnings' => new external_warnings()
2878 * Returns description of method parameters
2880 * @return external_function_parameters
2881 * @since Moodle 3.0
2883 public static function get_course_module_by_instance_parameters() {
2884 return new external_function_parameters(
2885 array(
2886 'module' => new external_value(PARAM_COMPONENT, 'The module name'),
2887 'instance' => new external_value(PARAM_INT, 'The module instance id')
2893 * Return information about a course module.
2895 * @param string $module the module name
2896 * @param int $instance the activity instance id
2897 * @return array of warnings and the course module
2898 * @since Moodle 3.0
2899 * @throws moodle_exception
2901 public static function get_course_module_by_instance($module, $instance) {
2903 $params = self::validate_parameters(self::get_course_module_by_instance_parameters(),
2904 array(
2905 'module' => $module,
2906 'instance' => $instance,
2909 $warnings = array();
2910 $cm = get_coursemodule_from_instance($params['module'], $params['instance'], 0, false, MUST_EXIST);
2912 return self::get_course_module($cm->id);
2916 * Returns description of method result value
2918 * @return external_description
2919 * @since Moodle 3.0
2921 public static function get_course_module_by_instance_returns() {
2922 return self::get_course_module_returns();
2926 * Returns description of method parameters
2928 * @return external_function_parameters
2929 * @since Moodle 3.2
2931 public static function get_user_navigation_options_parameters() {
2932 return new external_function_parameters(
2933 array(
2934 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2940 * Return a list of navigation options in a set of courses that are avaialable or not for the current user.
2942 * @param array $courseids a list of course ids
2943 * @return array of warnings and the options availability
2944 * @since Moodle 3.2
2945 * @throws moodle_exception
2947 public static function get_user_navigation_options($courseids) {
2948 global $CFG;
2949 require_once($CFG->dirroot . '/course/lib.php');
2951 // Parameter validation.
2952 $params = self::validate_parameters(self::get_user_navigation_options_parameters(), array('courseids' => $courseids));
2953 $courseoptions = array();
2955 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
2957 if (!empty($courses)) {
2958 foreach ($courses as $course) {
2959 // Fix the context for the frontpage.
2960 if ($course->id == SITEID) {
2961 $course->context = context_system::instance();
2963 $navoptions = course_get_user_navigation_options($course->context, $course);
2964 $options = array();
2965 foreach ($navoptions as $name => $available) {
2966 $options[] = array(
2967 'name' => $name,
2968 'available' => $available,
2972 $courseoptions[] = array(
2973 'id' => $course->id,
2974 'options' => $options
2979 $result = array(
2980 'courses' => $courseoptions,
2981 'warnings' => $warnings
2983 return $result;
2987 * Returns description of method result value
2989 * @return external_description
2990 * @since Moodle 3.2
2992 public static function get_user_navigation_options_returns() {
2993 return new external_single_structure(
2994 array(
2995 'courses' => new external_multiple_structure(
2996 new external_single_structure(
2997 array(
2998 'id' => new external_value(PARAM_INT, 'Course id'),
2999 'options' => new external_multiple_structure(
3000 new external_single_structure(
3001 array(
3002 'name' => new external_value(PARAM_ALPHANUMEXT, 'Option name'),
3003 'available' => new external_value(PARAM_BOOL, 'Whether the option is available or not'),
3008 ), 'List of courses'
3010 'warnings' => new external_warnings()
3016 * Returns description of method parameters
3018 * @return external_function_parameters
3019 * @since Moodle 3.2
3021 public static function get_user_administration_options_parameters() {
3022 return new external_function_parameters(
3023 array(
3024 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
3030 * Return a list of administration options in a set of courses that are available or not for the current user.
3032 * @param array $courseids a list of course ids
3033 * @return array of warnings and the options availability
3034 * @since Moodle 3.2
3035 * @throws moodle_exception
3037 public static function get_user_administration_options($courseids) {
3038 global $CFG;
3039 require_once($CFG->dirroot . '/course/lib.php');
3041 // Parameter validation.
3042 $params = self::validate_parameters(self::get_user_administration_options_parameters(), array('courseids' => $courseids));
3043 $courseoptions = array();
3045 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
3047 if (!empty($courses)) {
3048 foreach ($courses as $course) {
3049 $adminoptions = course_get_user_administration_options($course, $course->context);
3050 $options = array();
3051 foreach ($adminoptions as $name => $available) {
3052 $options[] = array(
3053 'name' => $name,
3054 'available' => $available,
3058 $courseoptions[] = array(
3059 'id' => $course->id,
3060 'options' => $options
3065 $result = array(
3066 'courses' => $courseoptions,
3067 'warnings' => $warnings
3069 return $result;
3073 * Returns description of method result value
3075 * @return external_description
3076 * @since Moodle 3.2
3078 public static function get_user_administration_options_returns() {
3079 return self::get_user_navigation_options_returns();
3083 * Returns description of method parameters
3085 * @return external_function_parameters
3086 * @since Moodle 3.2
3088 public static function get_courses_by_field_parameters() {
3089 return new external_function_parameters(
3090 array(
3091 'field' => new external_value(PARAM_ALPHA, 'The field to search can be left empty for all courses or:
3092 id: course id
3093 ids: comma separated course ids
3094 shortname: course short name
3095 idnumber: course id number
3096 category: category id the course belongs to
3097 ', VALUE_DEFAULT, ''),
3098 'value' => new external_value(PARAM_RAW, 'The value to match', VALUE_DEFAULT, '')
3105 * Get courses matching a specific field (id/s, shortname, idnumber, category)
3107 * @param string $field field name to search, or empty for all courses
3108 * @param string $value value to search
3109 * @return array list of courses and warnings
3110 * @throws invalid_parameter_exception
3111 * @since Moodle 3.2
3113 public static function get_courses_by_field($field = '', $value = '') {
3114 global $DB, $CFG;
3115 require_once($CFG->dirroot . '/course/lib.php');
3116 require_once($CFG->libdir . '/filterlib.php');
3118 $params = self::validate_parameters(self::get_courses_by_field_parameters(),
3119 array(
3120 'field' => $field,
3121 'value' => $value,
3124 $warnings = array();
3126 if (empty($params['field'])) {
3127 $courses = $DB->get_records('course', null, 'id ASC');
3128 } else {
3129 switch ($params['field']) {
3130 case 'id':
3131 case 'category':
3132 $value = clean_param($params['value'], PARAM_INT);
3133 break;
3134 case 'ids':
3135 $value = clean_param($params['value'], PARAM_SEQUENCE);
3136 break;
3137 case 'shortname':
3138 $value = clean_param($params['value'], PARAM_TEXT);
3139 break;
3140 case 'idnumber':
3141 $value = clean_param($params['value'], PARAM_RAW);
3142 break;
3143 default:
3144 throw new invalid_parameter_exception('Invalid field name');
3147 if ($params['field'] === 'ids') {
3148 // Preload categories to avoid loading one at a time.
3149 $courseids = explode(',', $value);
3150 list ($listsql, $listparams) = $DB->get_in_or_equal($courseids);
3151 $categoryids = $DB->get_fieldset_sql("
3152 SELECT DISTINCT cc.id
3153 FROM {course} c
3154 JOIN {course_categories} cc ON cc.id = c.category
3155 WHERE c.id $listsql", $listparams);
3156 core_course_category::get_many($categoryids);
3158 // Load and validate all courses. This is called because it loads the courses
3159 // more efficiently.
3160 list ($courses, $warnings) = external_util::validate_courses($courseids, [],
3161 false, true);
3162 } else {
3163 $courses = $DB->get_records('course', array($params['field'] => $value), 'id ASC');
3167 $coursesdata = array();
3168 foreach ($courses as $course) {
3169 $context = context_course::instance($course->id);
3170 $canupdatecourse = has_capability('moodle/course:update', $context);
3171 $canviewhiddencourses = has_capability('moodle/course:viewhiddencourses', $context);
3173 // Check if the course is visible in the site for the user.
3174 if (!$course->visible and !$canviewhiddencourses and !$canupdatecourse) {
3175 continue;
3177 // Get the public course information, even if we are not enrolled.
3178 $courseinlist = new core_course_list_element($course);
3180 // Now, check if we have access to the course, unless it was already checked.
3181 try {
3182 if (empty($course->contextvalidated)) {
3183 self::validate_context($context);
3185 } catch (Exception $e) {
3186 // User can not access the course, check if they can see the public information about the course and return it.
3187 if (core_course_category::can_view_course_info($course)) {
3188 $coursesdata[$course->id] = self::get_course_public_information($courseinlist, $context);
3190 continue;
3192 $coursesdata[$course->id] = self::get_course_public_information($courseinlist, $context);
3193 // Return information for any user that can access the course.
3194 $coursefields = array('format', 'showgrades', 'newsitems', 'startdate', 'enddate', 'maxbytes', 'showreports', 'visible',
3195 'groupmode', 'groupmodeforce', 'defaultgroupingid', 'enablecompletion', 'completionnotify', 'lang', 'theme',
3196 'marker');
3198 // Course filters.
3199 $coursesdata[$course->id]['filters'] = filter_get_available_in_context($context);
3201 // Information for managers only.
3202 if ($canupdatecourse) {
3203 $managerfields = array('idnumber', 'legacyfiles', 'calendartype', 'timecreated', 'timemodified', 'requested',
3204 'cacherev');
3205 $coursefields = array_merge($coursefields, $managerfields);
3208 // Populate fields.
3209 foreach ($coursefields as $field) {
3210 $coursesdata[$course->id][$field] = $course->{$field};
3213 // Clean lang and auth fields for external functions (it may content uninstalled themes or language packs).
3214 if (isset($coursesdata[$course->id]['theme'])) {
3215 $coursesdata[$course->id]['theme'] = clean_param($coursesdata[$course->id]['theme'], PARAM_THEME);
3217 if (isset($coursesdata[$course->id]['lang'])) {
3218 $coursesdata[$course->id]['lang'] = clean_param($coursesdata[$course->id]['lang'], PARAM_LANG);
3221 $courseformatoptions = course_get_format($course)->get_config_for_external();
3222 foreach ($courseformatoptions as $key => $value) {
3223 $coursesdata[$course->id]['courseformatoptions'][] = array(
3224 'name' => $key,
3225 'value' => $value
3230 return array(
3231 'courses' => $coursesdata,
3232 'warnings' => $warnings
3237 * Returns description of method result value
3239 * @return external_description
3240 * @since Moodle 3.2
3242 public static function get_courses_by_field_returns() {
3243 // Course structure, including not only public viewable fields.
3244 return new external_single_structure(
3245 array(
3246 'courses' => new external_multiple_structure(self::get_course_structure(false), 'Course'),
3247 'warnings' => new external_warnings()
3253 * Returns description of method parameters
3255 * @return external_function_parameters
3256 * @since Moodle 3.2
3258 public static function check_updates_parameters() {
3259 return new external_function_parameters(
3260 array(
3261 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3262 'tocheck' => new external_multiple_structure(
3263 new external_single_structure(
3264 array(
3265 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level for the file location.
3266 Only module supported right now.'),
3267 'id' => new external_value(PARAM_INT, 'Context instance id'),
3268 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3271 'Instances to check'
3273 'filter' => new external_multiple_structure(
3274 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3275 gradeitems, outcomes'),
3276 'Check only for updates in these areas', VALUE_DEFAULT, array()
3283 * Check if there is updates affecting the user for the given course and contexts.
3284 * Right now only modules are supported.
3285 * This WS calls mod_check_updates_since for each module to check if there is any update the user should we aware of.
3287 * @param int $courseid the list of modules to check
3288 * @param array $tocheck the list of modules to check
3289 * @param array $filter check only for updates in these areas
3290 * @return array list of updates and warnings
3291 * @throws moodle_exception
3292 * @since Moodle 3.2
3294 public static function check_updates($courseid, $tocheck, $filter = array()) {
3295 global $CFG, $DB;
3296 require_once($CFG->dirroot . "/course/lib.php");
3298 $params = self::validate_parameters(
3299 self::check_updates_parameters(),
3300 array(
3301 'courseid' => $courseid,
3302 'tocheck' => $tocheck,
3303 'filter' => $filter,
3307 $course = get_course($params['courseid']);
3308 $context = context_course::instance($course->id);
3309 self::validate_context($context);
3311 list($instances, $warnings) = course_check_updates($course, $params['tocheck'], $filter);
3313 $instancesformatted = array();
3314 foreach ($instances as $instance) {
3315 $updates = array();
3316 foreach ($instance['updates'] as $name => $data) {
3317 if (empty($data->updated)) {
3318 continue;
3320 $updatedata = array(
3321 'name' => $name,
3323 if (!empty($data->timeupdated)) {
3324 $updatedata['timeupdated'] = $data->timeupdated;
3326 if (!empty($data->itemids)) {
3327 $updatedata['itemids'] = $data->itemids;
3329 $updates[] = $updatedata;
3331 if (!empty($updates)) {
3332 $instancesformatted[] = array(
3333 'contextlevel' => $instance['contextlevel'],
3334 'id' => $instance['id'],
3335 'updates' => $updates
3340 return array(
3341 'instances' => $instancesformatted,
3342 'warnings' => $warnings
3347 * Returns description of method result value
3349 * @return external_description
3350 * @since Moodle 3.2
3352 public static function check_updates_returns() {
3353 return new external_single_structure(
3354 array(
3355 'instances' => new external_multiple_structure(
3356 new external_single_structure(
3357 array(
3358 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level'),
3359 'id' => new external_value(PARAM_INT, 'Instance id'),
3360 'updates' => new external_multiple_structure(
3361 new external_single_structure(
3362 array(
3363 'name' => new external_value(PARAM_ALPHANUMEXT, 'Name of the area updated.'),
3364 'timeupdated' => new external_value(PARAM_INT, 'Last time was updated', VALUE_OPTIONAL),
3365 'itemids' => new external_multiple_structure(
3366 new external_value(PARAM_INT, 'Instance id'),
3367 'The ids of the items updated',
3368 VALUE_OPTIONAL
3376 'warnings' => new external_warnings()
3382 * Returns description of method parameters
3384 * @return external_function_parameters
3385 * @since Moodle 3.3
3387 public static function get_updates_since_parameters() {
3388 return new external_function_parameters(
3389 array(
3390 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3391 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3392 'filter' => new external_multiple_structure(
3393 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3394 gradeitems, outcomes'),
3395 'Check only for updates in these areas', VALUE_DEFAULT, array()
3402 * Check if there are updates affecting the user for the given course since the given time stamp.
3404 * This function is a wrapper of self::check_updates for retrieving all the updates since a given time for all the activities.
3406 * @param int $courseid the list of modules to check
3407 * @param int $since check updates since this time stamp
3408 * @param array $filter check only for updates in these areas
3409 * @return array list of updates and warnings
3410 * @throws moodle_exception
3411 * @since Moodle 3.3
3413 public static function get_updates_since($courseid, $since, $filter = array()) {
3414 global $CFG, $DB;
3416 $params = self::validate_parameters(
3417 self::get_updates_since_parameters(),
3418 array(
3419 'courseid' => $courseid,
3420 'since' => $since,
3421 'filter' => $filter,
3425 $course = get_course($params['courseid']);
3426 $modinfo = get_fast_modinfo($course);
3427 $tocheck = array();
3429 // Retrieve all the visible course modules for the current user.
3430 $cms = $modinfo->get_cms();
3431 foreach ($cms as $cm) {
3432 if (!$cm->uservisible) {
3433 continue;
3435 $tocheck[] = array(
3436 'id' => $cm->id,
3437 'contextlevel' => 'module',
3438 'since' => $params['since'],
3442 return self::check_updates($course->id, $tocheck, $params['filter']);
3446 * Returns description of method result value
3448 * @return external_description
3449 * @since Moodle 3.3
3451 public static function get_updates_since_returns() {
3452 return self::check_updates_returns();
3456 * Parameters for function edit_module()
3458 * @since Moodle 3.3
3459 * @return external_function_parameters
3461 public static function edit_module_parameters() {
3462 return new external_function_parameters(
3463 array(
3464 'action' => new external_value(PARAM_ALPHA,
3465 'action: hide, show, stealth, duplicate, delete, moveleft, moveright, group...', VALUE_REQUIRED),
3466 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3467 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3472 * Performs one of the edit module actions and return new html for AJAX
3474 * Returns html to replace the current module html with, for example:
3475 * - empty string for "delete" action,
3476 * - two modules html for "duplicate" action
3477 * - updated module html for everything else
3479 * Throws exception if operation is not permitted/possible
3481 * @since Moodle 3.3
3482 * @param string $action
3483 * @param int $id
3484 * @param null|int $sectionreturn
3485 * @return string
3487 public static function edit_module($action, $id, $sectionreturn = null) {
3488 global $PAGE, $DB;
3489 // Validate and normalize parameters.
3490 $params = self::validate_parameters(self::edit_module_parameters(),
3491 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3492 $action = $params['action'];
3493 $id = $params['id'];
3494 $sectionreturn = $params['sectionreturn'];
3496 // Set of permissions an editing user may have.
3497 $contextarray = [
3498 'moodle/course:update',
3499 'moodle/course:manageactivities',
3500 'moodle/course:activityvisibility',
3501 'moodle/course:sectionvisibility',
3502 'moodle/course:movesections',
3503 'moodle/course:setcurrentsection',
3505 $PAGE->set_other_editing_capability($contextarray);
3507 list($course, $cm) = get_course_and_cm_from_cmid($id);
3508 $modcontext = context_module::instance($cm->id);
3509 $coursecontext = context_course::instance($course->id);
3510 self::validate_context($modcontext);
3511 $courserenderer = $PAGE->get_renderer('core', 'course');
3512 $completioninfo = new completion_info($course);
3514 switch($action) {
3515 case 'hide':
3516 case 'show':
3517 case 'stealth':
3518 require_capability('moodle/course:activityvisibility', $modcontext);
3519 $visible = ($action === 'hide') ? 0 : 1;
3520 $visibleoncoursepage = ($action === 'stealth') ? 0 : 1;
3521 set_coursemodule_visible($id, $visible, $visibleoncoursepage);
3522 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3523 break;
3524 case 'duplicate':
3525 require_capability('moodle/course:manageactivities', $coursecontext);
3526 require_capability('moodle/backup:backuptargetimport', $coursecontext);
3527 require_capability('moodle/restore:restoretargetimport', $coursecontext);
3528 if (!course_allowed_module($course, $cm->modname)) {
3529 throw new moodle_exception('No permission to create that activity');
3531 if ($newcm = duplicate_module($course, $cm)) {
3532 $cm = get_fast_modinfo($course)->get_cm($id);
3533 $newcm = get_fast_modinfo($course)->get_cm($newcm->id);
3534 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn) .
3535 $courserenderer->course_section_cm_list_item($course, $completioninfo, $newcm, $sectionreturn);
3537 break;
3538 case 'groupsseparate':
3539 case 'groupsvisible':
3540 case 'groupsnone':
3541 require_capability('moodle/course:manageactivities', $modcontext);
3542 if ($action === 'groupsseparate') {
3543 $newgroupmode = SEPARATEGROUPS;
3544 } else if ($action === 'groupsvisible') {
3545 $newgroupmode = VISIBLEGROUPS;
3546 } else {
3547 $newgroupmode = NOGROUPS;
3549 if (set_coursemodule_groupmode($cm->id, $newgroupmode)) {
3550 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3552 break;
3553 case 'moveleft':
3554 case 'moveright':
3555 require_capability('moodle/course:manageactivities', $modcontext);
3556 $indent = $cm->indent + (($action === 'moveright') ? 1 : -1);
3557 if ($cm->indent >= 0) {
3558 $DB->update_record('course_modules', array('id' => $cm->id, 'indent' => $indent));
3559 rebuild_course_cache($cm->course);
3561 break;
3562 case 'delete':
3563 require_capability('moodle/course:manageactivities', $modcontext);
3564 course_delete_module($cm->id, true);
3565 return '';
3566 default:
3567 throw new coding_exception('Unrecognised action');
3570 $cm = get_fast_modinfo($course)->get_cm($id);
3571 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn);
3575 * Return structure for edit_module()
3577 * @since Moodle 3.3
3578 * @return external_description
3580 public static function edit_module_returns() {
3581 return new external_value(PARAM_RAW, 'html to replace the current module with');
3585 * Parameters for function get_module()
3587 * @since Moodle 3.3
3588 * @return external_function_parameters
3590 public static function get_module_parameters() {
3591 return new external_function_parameters(
3592 array(
3593 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3594 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3599 * Returns html for displaying one activity module on course page
3601 * @since Moodle 3.3
3602 * @param int $id
3603 * @param null|int $sectionreturn
3604 * @return string
3606 public static function get_module($id, $sectionreturn = null) {
3607 global $PAGE;
3608 // Validate and normalize parameters.
3609 $params = self::validate_parameters(self::get_module_parameters(),
3610 array('id' => $id, 'sectionreturn' => $sectionreturn));
3611 $id = $params['id'];
3612 $sectionreturn = $params['sectionreturn'];
3614 // Set of permissions an editing user may have.
3615 $contextarray = [
3616 'moodle/course:update',
3617 'moodle/course:manageactivities',
3618 'moodle/course:activityvisibility',
3619 'moodle/course:sectionvisibility',
3620 'moodle/course:movesections',
3621 'moodle/course:setcurrentsection',
3623 $PAGE->set_other_editing_capability($contextarray);
3625 // Validate access to the course (note, this is html for the course view page, we don't validate access to the module).
3626 list($course, $cm) = get_course_and_cm_from_cmid($id);
3627 self::validate_context(context_course::instance($course->id));
3629 $courserenderer = $PAGE->get_renderer('core', 'course');
3630 $completioninfo = new completion_info($course);
3631 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn);
3635 * Return structure for get_module()
3637 * @since Moodle 3.3
3638 * @return external_description
3640 public static function get_module_returns() {
3641 return new external_value(PARAM_RAW, 'html to replace the current module with');
3645 * Parameters for function edit_section()
3647 * @since Moodle 3.3
3648 * @return external_function_parameters
3650 public static function edit_section_parameters() {
3651 return new external_function_parameters(
3652 array(
3653 'action' => new external_value(PARAM_ALPHA, 'action: hide, show, stealth, setmarker, removemarker', VALUE_REQUIRED),
3654 'id' => new external_value(PARAM_INT, 'course section id', VALUE_REQUIRED),
3655 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3660 * Performs one of the edit section actions
3662 * @since Moodle 3.3
3663 * @param string $action
3664 * @param int $id section id
3665 * @param int $sectionreturn section to return to
3666 * @return string
3668 public static function edit_section($action, $id, $sectionreturn) {
3669 global $DB;
3670 // Validate and normalize parameters.
3671 $params = self::validate_parameters(self::edit_section_parameters(),
3672 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3673 $action = $params['action'];
3674 $id = $params['id'];
3675 $sr = $params['sectionreturn'];
3677 $section = $DB->get_record('course_sections', array('id' => $id), '*', MUST_EXIST);
3678 $coursecontext = context_course::instance($section->course);
3679 self::validate_context($coursecontext);
3681 $rv = course_get_format($section->course)->section_action($section, $action, $sectionreturn);
3682 if ($rv) {
3683 return json_encode($rv);
3684 } else {
3685 return null;
3690 * Return structure for edit_section()
3692 * @since Moodle 3.3
3693 * @return external_description
3695 public static function edit_section_returns() {
3696 return new external_value(PARAM_RAW, 'Additional data for javascript (JSON-encoded string)');
3700 * Returns description of method parameters
3702 * @return external_function_parameters
3704 public static function get_enrolled_courses_by_timeline_classification_parameters() {
3705 return new external_function_parameters(
3706 array(
3707 'classification' => new external_value(PARAM_ALPHA, 'future, inprogress, or past'),
3708 'limit' => new external_value(PARAM_INT, 'Result set limit', VALUE_DEFAULT, 0),
3709 'offset' => new external_value(PARAM_INT, 'Result set offset', VALUE_DEFAULT, 0),
3710 'sort' => new external_value(PARAM_TEXT, 'Sort string', VALUE_DEFAULT, null),
3711 'customfieldname' => new external_value(PARAM_ALPHANUMEXT, 'Used when classification = customfield',
3712 VALUE_DEFAULT, null),
3713 'customfieldvalue' => new external_value(PARAM_RAW, 'Used when classification = customfield',
3714 VALUE_DEFAULT, null),
3720 * Get courses matching the given timeline classification.
3722 * NOTE: The offset applies to the unfiltered full set of courses before the classification
3723 * filtering is done.
3724 * E.g.
3725 * If the user is enrolled in 5 courses:
3726 * c1, c2, c3, c4, and c5
3727 * And c4 and c5 are 'future' courses
3729 * If a request comes in for future courses with an offset of 1 it will mean that
3730 * c1 is skipped (because the offset applies *before* the classification filtering)
3731 * and c4 and c5 will be return.
3733 * @param string $classification past, inprogress, or future
3734 * @param int $limit Result set limit
3735 * @param int $offset Offset the full course set before timeline classification is applied
3736 * @param string $sort SQL sort string for results
3737 * @param string $customfieldname
3738 * @param string $customfieldvalue
3739 * @return array list of courses and warnings
3740 * @throws invalid_parameter_exception
3742 public static function get_enrolled_courses_by_timeline_classification(
3743 string $classification,
3744 int $limit = 0,
3745 int $offset = 0,
3746 string $sort = null,
3747 string $customfieldname = null,
3748 string $customfieldvalue = null
3750 global $CFG, $PAGE, $USER;
3751 require_once($CFG->dirroot . '/course/lib.php');
3753 $params = self::validate_parameters(self::get_enrolled_courses_by_timeline_classification_parameters(),
3754 array(
3755 'classification' => $classification,
3756 'limit' => $limit,
3757 'offset' => $offset,
3758 'sort' => $sort,
3759 'customfieldvalue' => $customfieldvalue,
3763 $classification = $params['classification'];
3764 $limit = $params['limit'];
3765 $offset = $params['offset'];
3766 $sort = $params['sort'];
3767 $customfieldvalue = $params['customfieldvalue'];
3769 switch($classification) {
3770 case COURSE_TIMELINE_ALLINCLUDINGHIDDEN:
3771 break;
3772 case COURSE_TIMELINE_ALL:
3773 break;
3774 case COURSE_TIMELINE_PAST:
3775 break;
3776 case COURSE_TIMELINE_INPROGRESS:
3777 break;
3778 case COURSE_TIMELINE_FUTURE:
3779 break;
3780 case COURSE_FAVOURITES:
3781 break;
3782 case COURSE_TIMELINE_HIDDEN:
3783 break;
3784 case COURSE_CUSTOMFIELD:
3785 break;
3786 default:
3787 throw new invalid_parameter_exception('Invalid classification');
3790 self::validate_context(context_user::instance($USER->id));
3792 $requiredproperties = course_summary_exporter::define_properties();
3793 $fields = join(',', array_keys($requiredproperties));
3794 $hiddencourses = get_hidden_courses_on_timeline();
3795 $courses = [];
3797 // If the timeline requires really all courses, get really all courses.
3798 if ($classification == COURSE_TIMELINE_ALLINCLUDINGHIDDEN) {
3799 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields, COURSE_DB_QUERY_LIMIT);
3801 // Otherwise if the timeline requires the hidden courses then restrict the result to only $hiddencourses.
3802 } else if ($classification == COURSE_TIMELINE_HIDDEN) {
3803 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields,
3804 COURSE_DB_QUERY_LIMIT, $hiddencourses);
3806 // Otherwise get the requested courses and exclude the hidden courses.
3807 } else {
3808 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields,
3809 COURSE_DB_QUERY_LIMIT, [], $hiddencourses);
3812 $favouritecourseids = [];
3813 $ufservice = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($USER->id));
3814 $favourites = $ufservice->find_favourites_by_type('core_course', 'courses');
3816 if ($favourites) {
3817 $favouritecourseids = array_map(
3818 function($favourite) {
3819 return $favourite->itemid;
3820 }, $favourites);
3823 if ($classification == COURSE_FAVOURITES) {
3824 list($filteredcourses, $processedcount) = course_filter_courses_by_favourites(
3825 $courses,
3826 $favouritecourseids,
3827 $limit
3829 } else if ($classification == COURSE_CUSTOMFIELD) {
3830 list($filteredcourses, $processedcount) = course_filter_courses_by_customfield(
3831 $courses,
3832 $customfieldname,
3833 $customfieldvalue,
3834 $limit
3836 } else {
3837 list($filteredcourses, $processedcount) = course_filter_courses_by_timeline_classification(
3838 $courses,
3839 $classification,
3840 $limit
3844 $renderer = $PAGE->get_renderer('core');
3845 $formattedcourses = array_map(function($course) use ($renderer, $favouritecourseids) {
3846 context_helper::preload_from_record($course);
3847 $context = context_course::instance($course->id);
3848 $isfavourite = false;
3849 if (in_array($course->id, $favouritecourseids)) {
3850 $isfavourite = true;
3852 $exporter = new course_summary_exporter($course, ['context' => $context, 'isfavourite' => $isfavourite]);
3853 return $exporter->export($renderer);
3854 }, $filteredcourses);
3856 return [
3857 'courses' => $formattedcourses,
3858 'nextoffset' => $offset + $processedcount
3863 * Returns description of method result value
3865 * @return external_description
3867 public static function get_enrolled_courses_by_timeline_classification_returns() {
3868 return new external_single_structure(
3869 array(
3870 'courses' => new external_multiple_structure(course_summary_exporter::get_read_structure(), 'Course'),
3871 'nextoffset' => new external_value(PARAM_INT, 'Offset for the next request')
3877 * Returns description of method parameters
3879 * @return external_function_parameters
3881 public static function set_favourite_courses_parameters() {
3882 return new external_function_parameters(
3883 array(
3884 'courses' => new external_multiple_structure(
3885 new external_single_structure(
3886 array(
3887 'id' => new external_value(PARAM_INT, 'course ID'),
3888 'favourite' => new external_value(PARAM_BOOL, 'favourite status')
3897 * Set the course favourite status for an array of courses.
3899 * @param array $courses List with course id's and favourite status.
3900 * @return array Array with an array of favourite courses.
3902 public static function set_favourite_courses(
3903 array $courses
3905 global $USER;
3907 $params = self::validate_parameters(self::set_favourite_courses_parameters(),
3908 array(
3909 'courses' => $courses
3913 $warnings = [];
3915 $ufservice = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($USER->id));
3917 foreach ($params['courses'] as $course) {
3919 $warning = [];
3921 $favouriteexists = $ufservice->favourite_exists('core_course', 'courses', $course['id'],
3922 \context_course::instance($course['id']));
3924 if ($course['favourite']) {
3925 if (!$favouriteexists) {
3926 try {
3927 $ufservice->create_favourite('core_course', 'courses', $course['id'],
3928 \context_course::instance($course['id']));
3929 } catch (Exception $e) {
3930 $warning['courseid'] = $course['id'];
3931 if ($e instanceof moodle_exception) {
3932 $warning['warningcode'] = $e->errorcode;
3933 } else {
3934 $warning['warningcode'] = $e->getCode();
3936 $warning['message'] = $e->getMessage();
3937 $warnings[] = $warning;
3938 $warnings[] = $warning;
3940 } else {
3941 $warning['courseid'] = $course['id'];
3942 $warning['warningcode'] = 'coursealreadyfavourited';
3943 $warning['message'] = 'Course already favourited';
3944 $warnings[] = $warning;
3946 } else {
3947 if ($favouriteexists) {
3948 try {
3949 $ufservice->delete_favourite('core_course', 'courses', $course['id'],
3950 \context_course::instance($course['id']));
3951 } catch (Exception $e) {
3952 $warning['courseid'] = $course['id'];
3953 if ($e instanceof moodle_exception) {
3954 $warning['warningcode'] = $e->errorcode;
3955 } else {
3956 $warning['warningcode'] = $e->getCode();
3958 $warning['message'] = $e->getMessage();
3959 $warnings[] = $warning;
3960 $warnings[] = $warning;
3962 } else {
3963 $warning['courseid'] = $course['id'];
3964 $warning['warningcode'] = 'cannotdeletefavourite';
3965 $warning['message'] = 'Could not delete favourite status for course';
3966 $warnings[] = $warning;
3971 return [
3972 'warnings' => $warnings
3977 * Returns description of method result value
3979 * @return external_description
3981 public static function set_favourite_courses_returns() {
3982 return new external_single_structure(
3983 array(
3984 'warnings' => new external_warnings()
3990 * Returns description of method parameters
3992 * @return external_function_parameters
3993 * @since Moodle 3.6
3995 public static function get_recent_courses_parameters() {
3996 return new external_function_parameters(
3997 array(
3998 'userid' => new external_value(PARAM_INT, 'id of the user, default to current user', VALUE_DEFAULT, 0),
3999 'limit' => new external_value(PARAM_INT, 'result set limit', VALUE_DEFAULT, 0),
4000 'offset' => new external_value(PARAM_INT, 'Result set offset', VALUE_DEFAULT, 0),
4001 'sort' => new external_value(PARAM_TEXT, 'Sort string', VALUE_DEFAULT, null)
4007 * Get last accessed courses adding additional course information like images.
4009 * @param int $userid User id from which the courses will be obtained
4010 * @param int $limit Restrict result set to this amount
4011 * @param int $offset Skip this number of records from the start of the result set
4012 * @param string|null $sort SQL string for sorting
4013 * @return array List of courses
4014 * @throws invalid_parameter_exception
4016 public static function get_recent_courses(int $userid = 0, int $limit = 0, int $offset = 0, string $sort = null) {
4017 global $USER, $PAGE;
4019 if (empty($userid)) {
4020 $userid = $USER->id;
4023 $params = self::validate_parameters(self::get_recent_courses_parameters(),
4024 array(
4025 'userid' => $userid,
4026 'limit' => $limit,
4027 'offset' => $offset,
4028 'sort' => $sort
4032 $userid = $params['userid'];
4033 $limit = $params['limit'];
4034 $offset = $params['offset'];
4035 $sort = $params['sort'];
4037 $usercontext = context_user::instance($userid);
4039 self::validate_context($usercontext);
4041 if ($userid != $USER->id and !has_capability('moodle/user:viewdetails', $usercontext)) {
4042 return array();
4045 $courses = course_get_recent_courses($userid, $limit, $offset, $sort);
4047 $renderer = $PAGE->get_renderer('core');
4049 $recentcourses = array_map(function($course) use ($renderer) {
4050 context_helper::preload_from_record($course);
4051 $context = context_course::instance($course->id);
4052 $isfavourite = !empty($course->component);
4053 $exporter = new course_summary_exporter($course, ['context' => $context, 'isfavourite' => $isfavourite]);
4054 return $exporter->export($renderer);
4055 }, $courses);
4057 return $recentcourses;
4061 * Returns description of method result value
4063 * @return external_description
4064 * @since Moodle 3.6
4066 public static function get_recent_courses_returns() {
4067 return new external_multiple_structure(course_summary_exporter::get_read_structure(), 'Courses');
4071 * Returns description of method parameters
4073 * @return external_function_parameters
4075 public static function get_enrolled_users_by_cmid_parameters() {
4076 return new external_function_parameters([
4077 'cmid' => new external_value(PARAM_INT, 'id of the course module', VALUE_REQUIRED),
4078 'groupid' => new external_value(PARAM_INT, 'id of the group', VALUE_DEFAULT, 0),
4083 * Get all users in a course for a given cmid.
4085 * @param int $cmid Course Module id from which the users will be obtained
4086 * @param int $groupid Group id from which the users will be obtained
4087 * @return array List of users
4088 * @throws invalid_parameter_exception
4090 public static function get_enrolled_users_by_cmid(int $cmid, int $groupid = 0) {
4091 global $PAGE;
4092 $warnings = [];
4095 'cmid' => $cmid,
4096 'groupid' => $groupid,
4097 ] = self::validate_parameters(self::get_enrolled_users_by_cmid_parameters(), [
4098 'cmid' => $cmid,
4099 'groupid' => $groupid,
4102 list($course, $cm) = get_course_and_cm_from_cmid($cmid);
4103 $coursecontext = context_course::instance($course->id);
4104 self::validate_context($coursecontext);
4106 $enrolledusers = get_enrolled_users($coursecontext, '', $groupid);
4108 $users = array_map(function ($user) use ($PAGE) {
4109 $user->fullname = fullname($user);
4110 $userpicture = new user_picture($user);
4111 $userpicture->size = 1;
4112 $user->profileimage = $userpicture->get_url($PAGE)->out(false);
4113 return $user;
4114 }, $enrolledusers);
4115 sort($users);
4117 return [
4118 'users' => $users,
4119 'warnings' => $warnings,
4124 * Returns description of method result value
4126 * @return external_description
4128 public static function get_enrolled_users_by_cmid_returns() {
4129 return new external_single_structure([
4130 'users' => new external_multiple_structure(self::user_description()),
4131 'warnings' => new external_warnings(),
4136 * Create user return value description.
4138 * @return external_description
4140 public static function user_description() {
4141 $userfields = array(
4142 'id' => new external_value(core_user::get_property_type('id'), 'ID of the user'),
4143 'profileimage' => new external_value(PARAM_URL, 'The location of the users larger image', VALUE_OPTIONAL),
4144 'fullname' => new external_value(PARAM_TEXT, 'The full name of the user', VALUE_OPTIONAL),
4145 'firstname' => new external_value(
4146 core_user::get_property_type('firstname'),
4147 'The first name(s) of the user',
4148 VALUE_OPTIONAL),
4149 'lastname' => new external_value(
4150 core_user::get_property_type('lastname'),
4151 'The family name of the user',
4152 VALUE_OPTIONAL),
4154 return new external_single_structure($userfields);