MDL-66375 tool_mobile: Add new option in the disabled features selector
[moodle.git] / course / externallib.php
blob7f3a170a75b6d13db9b114f919887bb6d331d967
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'] = $cm->modname;
265 $module['modplural'] = $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;
273 // Check module completion.
274 $completion = $completioninfo->is_enabled($cm);
275 if ($completion != COMPLETION_DISABLED) {
276 $completiondata = $completioninfo->get_data($cm, true);
277 $module['completiondata'] = array(
278 'state' => $completiondata->completionstate,
279 'timecompleted' => $completiondata->timemodified,
280 'overrideby' => $completiondata->overrideby,
281 'valueused' => core_availability\info::completion_value_used($course, $cm->id)
285 if (!empty($cm->showdescription) or $cm->modname == 'label') {
286 // We want to use the external format. However from reading get_formatted_content(), $cm->content format is always FORMAT_HTML.
287 $options = array('noclean' => true);
288 list($module['description'], $descriptionformat) = external_format_text($cm->content,
289 FORMAT_HTML, $modcontext->id, $cm->modname, 'intro', $cm->id, $options);
292 //url of the module
293 $url = $cm->url;
294 if ($url) { //labels don't have url
295 $module['url'] = $url->out(false);
298 $canviewhidden = has_capability('moodle/course:viewhiddenactivities',
299 context_module::instance($cm->id));
300 //user that can view hidden module should know about the visibility
301 $module['visible'] = $cm->visible;
302 $module['visibleoncoursepage'] = $cm->visibleoncoursepage;
303 $module['uservisible'] = $cm->uservisible;
304 if (!empty($cm->availableinfo)) {
305 $module['availabilityinfo'] = \core_availability\info::format_info($cm->availableinfo, $course);
308 // Availability date (also send to user who can see hidden module).
309 if ($CFG->enableavailability && ($canviewhidden || $canupdatecourse)) {
310 $module['availability'] = $cm->availability;
313 // Return contents only if the user can access to the module.
314 if ($cm->uservisible) {
315 $baseurl = 'webservice/pluginfile.php';
317 // Call $modulename_export_contents (each module callback take care about checking the capabilities).
318 require_once($CFG->dirroot . '/mod/' . $cm->modname . '/lib.php');
319 $getcontentfunction = $cm->modname.'_export_contents';
320 if (function_exists($getcontentfunction)) {
321 $contents = $getcontentfunction($cm, $baseurl);
322 $module['contentsinfo'] = array(
323 'filescount' => count($contents),
324 'filessize' => 0,
325 'lastmodified' => 0,
326 'mimetypes' => array(),
328 foreach ($contents as $content) {
329 // Check repository file (only main file).
330 if (!isset($module['contentsinfo']['repositorytype'])) {
331 $module['contentsinfo']['repositorytype'] =
332 isset($content['repositorytype']) ? $content['repositorytype'] : '';
334 if (isset($content['filesize'])) {
335 $module['contentsinfo']['filessize'] += $content['filesize'];
337 if (isset($content['timemodified']) &&
338 ($content['timemodified'] > $module['contentsinfo']['lastmodified'])) {
340 $module['contentsinfo']['lastmodified'] = $content['timemodified'];
342 if (isset($content['mimetype'])) {
343 $module['contentsinfo']['mimetypes'][$content['mimetype']] = $content['mimetype'];
347 if (empty($filters['excludecontents']) and !empty($contents)) {
348 $module['contents'] = $contents;
349 } else {
350 $module['contents'] = array();
355 // Assign result to $sectioncontents, there is an exception,
356 // stealth activities in non-visible sections for students go to a special section.
357 if (!empty($filters['includestealthmodules']) && !$section->uservisible && $cm->is_stealth()) {
358 $stealthmodules[] = $module;
359 } else {
360 $sectioncontents[] = $module;
363 // If we just did a filtering, break the loop.
364 if ($modfound) {
365 break;
370 $sectionvalues['modules'] = $sectioncontents;
372 // assign result to $coursecontents
373 $coursecontents[$key] = $sectionvalues;
375 // Break the loop if we are filtering.
376 if ($sectionfound) {
377 break;
381 // Now that we have iterated over all the sections and activities, check the visibility.
382 // We didn't this before to be able to retrieve stealth activities.
383 foreach ($coursecontents as $sectionnumber => $sectioncontents) {
384 $section = $sections[$sectionnumber];
385 // Show the section if the user is permitted to access it, OR if it's not available
386 // but there is some available info text which explains the reason & should display.
387 $showsection = $section->uservisible ||
388 ($section->visible && !$section->available &&
389 !empty($section->availableinfo));
391 if (!$showsection) {
392 unset($coursecontents[$sectionnumber]);
393 continue;
396 // Remove modules information if the section is not visible for the user.
397 if (!$section->uservisible) {
398 $coursecontents[$sectionnumber]['modules'] = array();
402 // Include stealth modules in special section (without any info).
403 if (!empty($stealthmodules)) {
404 $coursecontents[] = array(
405 'id' => -1,
406 'name' => '',
407 'summary' => '',
408 'summaryformat' => FORMAT_MOODLE,
409 'modules' => $stealthmodules
414 return $coursecontents;
418 * Returns description of method result value
420 * @return external_description
421 * @since Moodle 2.2
423 public static function get_course_contents_returns() {
424 return new external_multiple_structure(
425 new external_single_structure(
426 array(
427 'id' => new external_value(PARAM_INT, 'Section ID'),
428 'name' => new external_value(PARAM_TEXT, 'Section name'),
429 'visible' => new external_value(PARAM_INT, 'is the section visible', VALUE_OPTIONAL),
430 'summary' => new external_value(PARAM_RAW, 'Section description'),
431 'summaryformat' => new external_format_value('summary'),
432 'section' => new external_value(PARAM_INT, 'Section number inside the course', VALUE_OPTIONAL),
433 'hiddenbynumsections' => new external_value(PARAM_INT, 'Whether is a section hidden in the course format',
434 VALUE_OPTIONAL),
435 'uservisible' => new external_value(PARAM_BOOL, 'Is the section visible for the user?', VALUE_OPTIONAL),
436 'availabilityinfo' => new external_value(PARAM_RAW, 'Availability information.', VALUE_OPTIONAL),
437 'modules' => new external_multiple_structure(
438 new external_single_structure(
439 array(
440 'id' => new external_value(PARAM_INT, 'activity id'),
441 'url' => new external_value(PARAM_URL, 'activity url', VALUE_OPTIONAL),
442 'name' => new external_value(PARAM_RAW, 'activity module name'),
443 'instance' => new external_value(PARAM_INT, 'instance id', VALUE_OPTIONAL),
444 'description' => new external_value(PARAM_RAW, 'activity description', VALUE_OPTIONAL),
445 'visible' => new external_value(PARAM_INT, 'is the module visible', VALUE_OPTIONAL),
446 'uservisible' => new external_value(PARAM_BOOL, 'Is the module visible for the user?',
447 VALUE_OPTIONAL),
448 'availabilityinfo' => new external_value(PARAM_RAW, 'Availability information.',
449 VALUE_OPTIONAL),
450 'visibleoncoursepage' => new external_value(PARAM_INT, 'is the module visible on course page',
451 VALUE_OPTIONAL),
452 'modicon' => new external_value(PARAM_URL, 'activity icon url'),
453 'modname' => new external_value(PARAM_PLUGIN, 'activity module type'),
454 'modplural' => new external_value(PARAM_TEXT, 'activity module plural name'),
455 'availability' => new external_value(PARAM_RAW, 'module availability settings', VALUE_OPTIONAL),
456 'indent' => new external_value(PARAM_INT, 'number of identation in the site'),
457 'onclick' => new external_value(PARAM_RAW, 'Onclick action.', VALUE_OPTIONAL),
458 'afterlink' => new external_value(PARAM_RAW, 'After link info to be displayed.',
459 VALUE_OPTIONAL),
460 'customdata' => new external_value(PARAM_RAW, 'Custom data (JSON encoded).', VALUE_OPTIONAL),
461 'completion' => new external_value(PARAM_INT, 'Type of completion tracking:
462 0 means none, 1 manual, 2 automatic.', VALUE_OPTIONAL),
463 'completiondata' => new external_single_structure(
464 array(
465 'state' => new external_value(PARAM_INT, 'Completion state value:
466 0 means incomplete, 1 complete, 2 complete pass, 3 complete fail'),
467 'timecompleted' => new external_value(PARAM_INT, 'Timestamp for completion status.'),
468 'overrideby' => new external_value(PARAM_INT, 'The user id who has overriden the
469 status.'),
470 'valueused' => new external_value(PARAM_BOOL, 'Whether the completion status affects
471 the availability of another activity.', VALUE_OPTIONAL),
472 ), 'Module completion data.', VALUE_OPTIONAL
474 'contents' => new external_multiple_structure(
475 new external_single_structure(
476 array(
477 // content info
478 'type'=> new external_value(PARAM_TEXT, 'a file or a folder or external link'),
479 'filename'=> new external_value(PARAM_FILE, 'filename'),
480 'filepath'=> new external_value(PARAM_PATH, 'filepath'),
481 'filesize'=> new external_value(PARAM_INT, 'filesize'),
482 'fileurl' => new external_value(PARAM_URL, 'downloadable file url', VALUE_OPTIONAL),
483 'content' => new external_value(PARAM_RAW, 'Raw content, will be used when type is content', VALUE_OPTIONAL),
484 'timecreated' => new external_value(PARAM_INT, 'Time created'),
485 'timemodified' => new external_value(PARAM_INT, 'Time modified'),
486 'sortorder' => new external_value(PARAM_INT, 'Content sort order'),
487 'mimetype' => new external_value(PARAM_RAW, 'File mime type.', VALUE_OPTIONAL),
488 'isexternalfile' => new external_value(PARAM_BOOL, 'Whether is an external file.',
489 VALUE_OPTIONAL),
490 'repositorytype' => new external_value(PARAM_PLUGIN, 'The repository type for external files.',
491 VALUE_OPTIONAL),
493 // copyright related info
494 'userid' => new external_value(PARAM_INT, 'User who added this content to moodle'),
495 'author' => new external_value(PARAM_TEXT, 'Content owner'),
496 'license' => new external_value(PARAM_TEXT, 'Content license'),
497 'tags' => new external_multiple_structure(
498 \core_tag\external\tag_item_exporter::get_read_structure(), 'Tags',
499 VALUE_OPTIONAL
502 ), VALUE_DEFAULT, array()
504 'contentsinfo' => new external_single_structure(
505 array(
506 'filescount' => new external_value(PARAM_INT, 'Total number of files.'),
507 'filessize' => new external_value(PARAM_INT, 'Total files size.'),
508 'lastmodified' => new external_value(PARAM_INT, 'Last time files were modified.'),
509 'mimetypes' => new external_multiple_structure(
510 new external_value(PARAM_RAW, 'File mime type.'),
511 'Files mime types.'
513 'repositorytype' => new external_value(PARAM_PLUGIN, 'The repository type for
514 the main file.', VALUE_OPTIONAL),
515 ), 'Contents summary information.', VALUE_OPTIONAL
518 ), 'list of module'
526 * Returns description of method parameters
528 * @return external_function_parameters
529 * @since Moodle 2.3
531 public static function get_courses_parameters() {
532 return new external_function_parameters(
533 array('options' => new external_single_structure(
534 array('ids' => new external_multiple_structure(
535 new external_value(PARAM_INT, 'Course id')
536 , 'List of course id. If empty return all courses
537 except front page course.',
538 VALUE_OPTIONAL)
539 ), 'options - operator OR is used', VALUE_DEFAULT, array())
545 * Get courses
547 * @param array $options It contains an array (list of ids)
548 * @return array
549 * @since Moodle 2.2
551 public static function get_courses($options = array()) {
552 global $CFG, $DB;
553 require_once($CFG->dirroot . "/course/lib.php");
555 //validate parameter
556 $params = self::validate_parameters(self::get_courses_parameters(),
557 array('options' => $options));
559 //retrieve courses
560 if (!array_key_exists('ids', $params['options'])
561 or empty($params['options']['ids'])) {
562 $courses = $DB->get_records('course');
563 } else {
564 $courses = $DB->get_records_list('course', 'id', $params['options']['ids']);
567 //create return value
568 $coursesinfo = array();
569 foreach ($courses as $course) {
571 // now security checks
572 $context = context_course::instance($course->id, IGNORE_MISSING);
573 $courseformatoptions = course_get_format($course)->get_format_options();
574 try {
575 self::validate_context($context);
576 } catch (Exception $e) {
577 $exceptionparam = new stdClass();
578 $exceptionparam->message = $e->getMessage();
579 $exceptionparam->courseid = $course->id;
580 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
582 if ($course->id != SITEID) {
583 require_capability('moodle/course:view', $context);
586 $courseinfo = array();
587 $courseinfo['id'] = $course->id;
588 $courseinfo['fullname'] = external_format_string($course->fullname, $context->id);
589 $courseinfo['shortname'] = external_format_string($course->shortname, $context->id);
590 $courseinfo['displayname'] = external_format_string(get_course_display_name_for_list($course), $context->id);
591 $courseinfo['categoryid'] = $course->category;
592 list($courseinfo['summary'], $courseinfo['summaryformat']) =
593 external_format_text($course->summary, $course->summaryformat, $context->id, 'course', 'summary', 0);
594 $courseinfo['format'] = $course->format;
595 $courseinfo['startdate'] = $course->startdate;
596 $courseinfo['enddate'] = $course->enddate;
597 if (array_key_exists('numsections', $courseformatoptions)) {
598 // For backward-compartibility
599 $courseinfo['numsections'] = $courseformatoptions['numsections'];
602 $handler = core_course\customfield\course_handler::create();
603 if ($customfields = $handler->export_instance_data($course->id)) {
604 $courseinfo['customfields'] = [];
605 foreach ($customfields as $data) {
606 $courseinfo['customfields'][] = [
607 'type' => $data->get_type(),
608 'value' => $data->get_value(),
609 'name' => $data->get_name(),
610 'shortname' => $data->get_shortname()
615 //some field should be returned only if the user has update permission
616 $courseadmin = has_capability('moodle/course:update', $context);
617 if ($courseadmin) {
618 $courseinfo['categorysortorder'] = $course->sortorder;
619 $courseinfo['idnumber'] = $course->idnumber;
620 $courseinfo['showgrades'] = $course->showgrades;
621 $courseinfo['showreports'] = $course->showreports;
622 $courseinfo['newsitems'] = $course->newsitems;
623 $courseinfo['visible'] = $course->visible;
624 $courseinfo['maxbytes'] = $course->maxbytes;
625 if (array_key_exists('hiddensections', $courseformatoptions)) {
626 // For backward-compartibility
627 $courseinfo['hiddensections'] = $courseformatoptions['hiddensections'];
629 // Return numsections for backward-compatibility with clients who expect it.
630 $courseinfo['numsections'] = course_get_format($course)->get_last_section_number();
631 $courseinfo['groupmode'] = $course->groupmode;
632 $courseinfo['groupmodeforce'] = $course->groupmodeforce;
633 $courseinfo['defaultgroupingid'] = $course->defaultgroupingid;
634 $courseinfo['lang'] = clean_param($course->lang, PARAM_LANG);
635 $courseinfo['timecreated'] = $course->timecreated;
636 $courseinfo['timemodified'] = $course->timemodified;
637 $courseinfo['forcetheme'] = clean_param($course->theme, PARAM_THEME);
638 $courseinfo['enablecompletion'] = $course->enablecompletion;
639 $courseinfo['completionnotify'] = $course->completionnotify;
640 $courseinfo['courseformatoptions'] = array();
641 foreach ($courseformatoptions as $key => $value) {
642 $courseinfo['courseformatoptions'][] = array(
643 'name' => $key,
644 'value' => $value
649 if ($courseadmin or $course->visible
650 or has_capability('moodle/course:viewhiddencourses', $context)) {
651 $coursesinfo[] = $courseinfo;
655 return $coursesinfo;
659 * Returns description of method result value
661 * @return external_description
662 * @since Moodle 2.2
664 public static function get_courses_returns() {
665 return new external_multiple_structure(
666 new external_single_structure(
667 array(
668 'id' => new external_value(PARAM_INT, 'course id'),
669 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
670 'categoryid' => new external_value(PARAM_INT, 'category id'),
671 'categorysortorder' => new external_value(PARAM_INT,
672 'sort order into the category', VALUE_OPTIONAL),
673 'fullname' => new external_value(PARAM_TEXT, 'full name'),
674 'displayname' => new external_value(PARAM_TEXT, 'course display name'),
675 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
676 'summary' => new external_value(PARAM_RAW, 'summary'),
677 'summaryformat' => new external_format_value('summary'),
678 'format' => new external_value(PARAM_PLUGIN,
679 'course format: weeks, topics, social, site,..'),
680 'showgrades' => new external_value(PARAM_INT,
681 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
682 'newsitems' => new external_value(PARAM_INT,
683 'number of recent items appearing on the course page', VALUE_OPTIONAL),
684 'startdate' => new external_value(PARAM_INT,
685 'timestamp when the course start'),
686 'enddate' => new external_value(PARAM_INT,
687 'timestamp when the course end'),
688 'numsections' => new external_value(PARAM_INT,
689 '(deprecated, use courseformatoptions) number of weeks/topics',
690 VALUE_OPTIONAL),
691 'maxbytes' => new external_value(PARAM_INT,
692 'largest size of file that can be uploaded into the course',
693 VALUE_OPTIONAL),
694 'showreports' => new external_value(PARAM_INT,
695 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
696 'visible' => new external_value(PARAM_INT,
697 '1: available to student, 0:not available', VALUE_OPTIONAL),
698 'hiddensections' => new external_value(PARAM_INT,
699 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
700 VALUE_OPTIONAL),
701 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
702 VALUE_OPTIONAL),
703 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
704 VALUE_OPTIONAL),
705 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
706 VALUE_OPTIONAL),
707 'timecreated' => new external_value(PARAM_INT,
708 'timestamp when the course have been created', VALUE_OPTIONAL),
709 'timemodified' => new external_value(PARAM_INT,
710 'timestamp when the course have been modified', VALUE_OPTIONAL),
711 'enablecompletion' => new external_value(PARAM_INT,
712 'Enabled, control via completion and activity settings. Disbaled,
713 not shown in activity settings.',
714 VALUE_OPTIONAL),
715 'completionnotify' => new external_value(PARAM_INT,
716 '1: yes 0: no', VALUE_OPTIONAL),
717 'lang' => new external_value(PARAM_SAFEDIR,
718 'forced course language', VALUE_OPTIONAL),
719 'forcetheme' => new external_value(PARAM_PLUGIN,
720 'name of the force theme', VALUE_OPTIONAL),
721 'courseformatoptions' => new external_multiple_structure(
722 new external_single_structure(
723 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
724 'value' => new external_value(PARAM_RAW, 'course format option value')
725 )), 'additional options for particular course format', VALUE_OPTIONAL
727 'customfields' => new external_multiple_structure(
728 new external_single_structure(
729 ['name' => new external_value(PARAM_TEXT, 'The name of the custom field'),
730 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'The shortname of the custom field'),
731 'type' => new external_value(PARAM_COMPONENT,
732 'The type of the custom field - text, checkbox...'),
733 'value' => new external_value(PARAM_RAW, 'The value of the custom field')]
734 ), 'Custom fields and associated values', VALUE_OPTIONAL),
735 ), 'course'
741 * Returns description of method parameters
743 * @return external_function_parameters
744 * @since Moodle 2.2
746 public static function create_courses_parameters() {
747 $courseconfig = get_config('moodlecourse'); //needed for many default values
748 return new external_function_parameters(
749 array(
750 'courses' => new external_multiple_structure(
751 new external_single_structure(
752 array(
753 'fullname' => new external_value(PARAM_TEXT, 'full name'),
754 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
755 'categoryid' => new external_value(PARAM_INT, 'category id'),
756 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
757 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
758 'summaryformat' => new external_format_value('summary', VALUE_DEFAULT),
759 'format' => new external_value(PARAM_PLUGIN,
760 'course format: weeks, topics, social, site,..',
761 VALUE_DEFAULT, $courseconfig->format),
762 'showgrades' => new external_value(PARAM_INT,
763 '1 if grades are shown, otherwise 0', VALUE_DEFAULT,
764 $courseconfig->showgrades),
765 'newsitems' => new external_value(PARAM_INT,
766 'number of recent items appearing on the course page',
767 VALUE_DEFAULT, $courseconfig->newsitems),
768 'startdate' => new external_value(PARAM_INT,
769 'timestamp when the course start', VALUE_OPTIONAL),
770 'enddate' => new external_value(PARAM_INT,
771 'timestamp when the course end', VALUE_OPTIONAL),
772 'numsections' => new external_value(PARAM_INT,
773 '(deprecated, use courseformatoptions) number of weeks/topics',
774 VALUE_OPTIONAL),
775 'maxbytes' => new external_value(PARAM_INT,
776 'largest size of file that can be uploaded into the course',
777 VALUE_DEFAULT, $courseconfig->maxbytes),
778 'showreports' => new external_value(PARAM_INT,
779 'are activity report shown (yes = 1, no =0)', VALUE_DEFAULT,
780 $courseconfig->showreports),
781 'visible' => new external_value(PARAM_INT,
782 '1: available to student, 0:not available', VALUE_OPTIONAL),
783 'hiddensections' => new external_value(PARAM_INT,
784 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
785 VALUE_OPTIONAL),
786 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
787 VALUE_DEFAULT, $courseconfig->groupmode),
788 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
789 VALUE_DEFAULT, $courseconfig->groupmodeforce),
790 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
791 VALUE_DEFAULT, 0),
792 'enablecompletion' => new external_value(PARAM_INT,
793 'Enabled, control via completion and activity settings. Disabled,
794 not shown in activity settings.',
795 VALUE_OPTIONAL),
796 'completionnotify' => new external_value(PARAM_INT,
797 '1: yes 0: no', VALUE_OPTIONAL),
798 'lang' => new external_value(PARAM_SAFEDIR,
799 'forced course language', VALUE_OPTIONAL),
800 'forcetheme' => new external_value(PARAM_PLUGIN,
801 'name of the force theme', VALUE_OPTIONAL),
802 'courseformatoptions' => new external_multiple_structure(
803 new external_single_structure(
804 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
805 'value' => new external_value(PARAM_RAW, 'course format option value')
807 'additional options for particular course format', VALUE_OPTIONAL),
808 'customfields' => new external_multiple_structure(
809 new external_single_structure(
810 array(
811 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'The shortname of the custom field'),
812 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
813 )), 'custom fields for the course', VALUE_OPTIONAL
815 )), 'courses to create'
822 * Create courses
824 * @param array $courses
825 * @return array courses (id and shortname only)
826 * @since Moodle 2.2
828 public static function create_courses($courses) {
829 global $CFG, $DB;
830 require_once($CFG->dirroot . "/course/lib.php");
831 require_once($CFG->libdir . '/completionlib.php');
833 $params = self::validate_parameters(self::create_courses_parameters(),
834 array('courses' => $courses));
836 $availablethemes = core_component::get_plugin_list('theme');
837 $availablelangs = get_string_manager()->get_list_of_translations();
839 $transaction = $DB->start_delegated_transaction();
841 foreach ($params['courses'] as $course) {
843 // Ensure the current user is allowed to run this function
844 $context = context_coursecat::instance($course['categoryid'], IGNORE_MISSING);
845 try {
846 self::validate_context($context);
847 } catch (Exception $e) {
848 $exceptionparam = new stdClass();
849 $exceptionparam->message = $e->getMessage();
850 $exceptionparam->catid = $course['categoryid'];
851 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
853 require_capability('moodle/course:create', $context);
855 // Make sure lang is valid
856 if (array_key_exists('lang', $course)) {
857 if (empty($availablelangs[$course['lang']])) {
858 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
860 if (!has_capability('moodle/course:setforcedlanguage', $context)) {
861 unset($course['lang']);
865 // Make sure theme is valid
866 if (array_key_exists('forcetheme', $course)) {
867 if (!empty($CFG->allowcoursethemes)) {
868 if (empty($availablethemes[$course['forcetheme']])) {
869 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
870 } else {
871 $course['theme'] = $course['forcetheme'];
876 //force visibility if ws user doesn't have the permission to set it
877 $category = $DB->get_record('course_categories', array('id' => $course['categoryid']));
878 if (!has_capability('moodle/course:visibility', $context)) {
879 $course['visible'] = $category->visible;
882 //set default value for completion
883 $courseconfig = get_config('moodlecourse');
884 if (completion_info::is_enabled_for_site()) {
885 if (!array_key_exists('enablecompletion', $course)) {
886 $course['enablecompletion'] = $courseconfig->enablecompletion;
888 } else {
889 $course['enablecompletion'] = 0;
892 $course['category'] = $course['categoryid'];
894 // Summary format.
895 $course['summaryformat'] = external_validate_format($course['summaryformat']);
897 if (!empty($course['courseformatoptions'])) {
898 foreach ($course['courseformatoptions'] as $option) {
899 $course[$option['name']] = $option['value'];
903 // Custom fields.
904 if (!empty($course['customfields'])) {
905 foreach ($course['customfields'] as $field) {
906 $course['customfield_'.$field['shortname']] = $field['value'];
910 //Note: create_course() core function check shortname, idnumber, category
911 $course['id'] = create_course((object) $course)->id;
913 $resultcourses[] = array('id' => $course['id'], 'shortname' => $course['shortname']);
916 $transaction->allow_commit();
918 return $resultcourses;
922 * Returns description of method result value
924 * @return external_description
925 * @since Moodle 2.2
927 public static function create_courses_returns() {
928 return new external_multiple_structure(
929 new external_single_structure(
930 array(
931 'id' => new external_value(PARAM_INT, 'course id'),
932 'shortname' => new external_value(PARAM_TEXT, 'short name'),
939 * Update courses
941 * @return external_function_parameters
942 * @since Moodle 2.5
944 public static function update_courses_parameters() {
945 return new external_function_parameters(
946 array(
947 'courses' => new external_multiple_structure(
948 new external_single_structure(
949 array(
950 'id' => new external_value(PARAM_INT, 'ID of the course'),
951 'fullname' => new external_value(PARAM_TEXT, 'full name', VALUE_OPTIONAL),
952 'shortname' => new external_value(PARAM_TEXT, 'course short name', VALUE_OPTIONAL),
953 'categoryid' => new external_value(PARAM_INT, 'category id', VALUE_OPTIONAL),
954 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
955 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
956 'summaryformat' => new external_format_value('summary', VALUE_OPTIONAL),
957 'format' => new external_value(PARAM_PLUGIN,
958 'course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
959 'showgrades' => new external_value(PARAM_INT,
960 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
961 'newsitems' => new external_value(PARAM_INT,
962 'number of recent items appearing on the course page', VALUE_OPTIONAL),
963 'startdate' => new external_value(PARAM_INT,
964 'timestamp when the course start', VALUE_OPTIONAL),
965 'enddate' => new external_value(PARAM_INT,
966 'timestamp when the course end', VALUE_OPTIONAL),
967 'numsections' => new external_value(PARAM_INT,
968 '(deprecated, use courseformatoptions) number of weeks/topics', VALUE_OPTIONAL),
969 'maxbytes' => new external_value(PARAM_INT,
970 'largest size of file that can be uploaded into the course', VALUE_OPTIONAL),
971 'showreports' => new external_value(PARAM_INT,
972 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
973 'visible' => new external_value(PARAM_INT,
974 '1: available to student, 0:not available', VALUE_OPTIONAL),
975 'hiddensections' => new external_value(PARAM_INT,
976 '(deprecated, use courseformatoptions) How the hidden sections in the course are
977 displayed to students', VALUE_OPTIONAL),
978 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
979 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
980 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
981 'enablecompletion' => new external_value(PARAM_INT,
982 'Enabled, control via completion and activity settings. Disabled,
983 not shown in activity settings.', VALUE_OPTIONAL),
984 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
985 'lang' => new external_value(PARAM_SAFEDIR, 'forced course language', VALUE_OPTIONAL),
986 'forcetheme' => new external_value(PARAM_PLUGIN, 'name of the force theme', VALUE_OPTIONAL),
987 'courseformatoptions' => new external_multiple_structure(
988 new external_single_structure(
989 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
990 'value' => new external_value(PARAM_RAW, 'course format option value')
991 )), 'additional options for particular course format', VALUE_OPTIONAL),
992 'customfields' => new external_multiple_structure(
993 new external_single_structure(
995 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'The shortname of the custom field'),
996 'value' => new external_value(PARAM_RAW, 'The value of the custom field')
998 ), 'Custom fields', VALUE_OPTIONAL),
1000 ), 'courses to update'
1007 * Update courses
1009 * @param array $courses
1010 * @since Moodle 2.5
1012 public static function update_courses($courses) {
1013 global $CFG, $DB;
1014 require_once($CFG->dirroot . "/course/lib.php");
1015 $warnings = array();
1017 $params = self::validate_parameters(self::update_courses_parameters(),
1018 array('courses' => $courses));
1020 $availablethemes = core_component::get_plugin_list('theme');
1021 $availablelangs = get_string_manager()->get_list_of_translations();
1023 foreach ($params['courses'] as $course) {
1024 // Catch any exception while updating course and return as warning to user.
1025 try {
1026 // Ensure the current user is allowed to run this function.
1027 $context = context_course::instance($course['id'], MUST_EXIST);
1028 self::validate_context($context);
1030 $oldcourse = course_get_format($course['id'])->get_course();
1032 require_capability('moodle/course:update', $context);
1034 // Check if user can change category.
1035 if (array_key_exists('categoryid', $course) && ($oldcourse->category != $course['categoryid'])) {
1036 require_capability('moodle/course:changecategory', $context);
1037 $course['category'] = $course['categoryid'];
1040 // Check if the user can change fullname.
1041 if (array_key_exists('fullname', $course) && ($oldcourse->fullname != $course['fullname'])) {
1042 require_capability('moodle/course:changefullname', $context);
1045 // Check if the user can change shortname.
1046 if (array_key_exists('shortname', $course) && ($oldcourse->shortname != $course['shortname'])) {
1047 require_capability('moodle/course:changeshortname', $context);
1050 // Check if the user can change the idnumber.
1051 if (array_key_exists('idnumber', $course) && ($oldcourse->idnumber != $course['idnumber'])) {
1052 require_capability('moodle/course:changeidnumber', $context);
1055 // Check if user can change summary.
1056 if (array_key_exists('summary', $course) && ($oldcourse->summary != $course['summary'])) {
1057 require_capability('moodle/course:changesummary', $context);
1060 // Summary format.
1061 if (array_key_exists('summaryformat', $course) && ($oldcourse->summaryformat != $course['summaryformat'])) {
1062 require_capability('moodle/course:changesummary', $context);
1063 $course['summaryformat'] = external_validate_format($course['summaryformat']);
1066 // Check if user can change visibility.
1067 if (array_key_exists('visible', $course) && ($oldcourse->visible != $course['visible'])) {
1068 require_capability('moodle/course:visibility', $context);
1071 // Make sure lang is valid.
1072 if (array_key_exists('lang', $course) && ($oldcourse->lang != $course['lang'])) {
1073 require_capability('moodle/course:setforcedlanguage', $context);
1074 if (empty($availablelangs[$course['lang']])) {
1075 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
1079 // Make sure theme is valid.
1080 if (array_key_exists('forcetheme', $course)) {
1081 if (!empty($CFG->allowcoursethemes)) {
1082 if (empty($availablethemes[$course['forcetheme']])) {
1083 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
1084 } else {
1085 $course['theme'] = $course['forcetheme'];
1090 // Make sure completion is enabled before setting it.
1091 if (array_key_exists('enabledcompletion', $course) && !completion_info::is_enabled_for_site()) {
1092 $course['enabledcompletion'] = 0;
1095 // Make sure maxbytes are less then CFG->maxbytes.
1096 if (array_key_exists('maxbytes', $course)) {
1097 // We allow updates back to 0 max bytes, a special value denoting the course uses the site limit.
1098 // Otherwise, either use the size specified, or cap at the max size for the course.
1099 if ($course['maxbytes'] != 0) {
1100 $course['maxbytes'] = get_max_upload_file_size($CFG->maxbytes, $course['maxbytes']);
1104 if (!empty($course['courseformatoptions'])) {
1105 foreach ($course['courseformatoptions'] as $option) {
1106 if (isset($option['name']) && isset($option['value'])) {
1107 $course[$option['name']] = $option['value'];
1112 // Prepare list of custom fields.
1113 if (isset($course['customfields'])) {
1114 foreach ($course['customfields'] as $field) {
1115 $course['customfield_' . $field['shortname']] = $field['value'];
1119 // Update course if user has all required capabilities.
1120 update_course((object) $course);
1121 } catch (Exception $e) {
1122 $warning = array();
1123 $warning['item'] = 'course';
1124 $warning['itemid'] = $course['id'];
1125 if ($e instanceof moodle_exception) {
1126 $warning['warningcode'] = $e->errorcode;
1127 } else {
1128 $warning['warningcode'] = $e->getCode();
1130 $warning['message'] = $e->getMessage();
1131 $warnings[] = $warning;
1135 $result = array();
1136 $result['warnings'] = $warnings;
1137 return $result;
1141 * Returns description of method result value
1143 * @return external_description
1144 * @since Moodle 2.5
1146 public static function update_courses_returns() {
1147 return new external_single_structure(
1148 array(
1149 'warnings' => new external_warnings()
1155 * Returns description of method parameters
1157 * @return external_function_parameters
1158 * @since Moodle 2.2
1160 public static function delete_courses_parameters() {
1161 return new external_function_parameters(
1162 array(
1163 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'course ID')),
1169 * Delete courses
1171 * @param array $courseids A list of course ids
1172 * @since Moodle 2.2
1174 public static function delete_courses($courseids) {
1175 global $CFG, $DB;
1176 require_once($CFG->dirroot."/course/lib.php");
1178 // Parameter validation.
1179 $params = self::validate_parameters(self::delete_courses_parameters(), array('courseids'=>$courseids));
1181 $warnings = array();
1183 foreach ($params['courseids'] as $courseid) {
1184 $course = $DB->get_record('course', array('id' => $courseid));
1186 if ($course === false) {
1187 $warnings[] = array(
1188 'item' => 'course',
1189 'itemid' => $courseid,
1190 'warningcode' => 'unknowncourseidnumber',
1191 'message' => 'Unknown course ID ' . $courseid
1193 continue;
1196 // Check if the context is valid.
1197 $coursecontext = context_course::instance($course->id);
1198 self::validate_context($coursecontext);
1200 // Check if the current user has permission.
1201 if (!can_delete_course($courseid)) {
1202 $warnings[] = array(
1203 'item' => 'course',
1204 'itemid' => $courseid,
1205 'warningcode' => 'cannotdeletecourse',
1206 'message' => 'You do not have the permission to delete this course' . $courseid
1208 continue;
1211 if (delete_course($course, false) === false) {
1212 $warnings[] = array(
1213 'item' => 'course',
1214 'itemid' => $courseid,
1215 'warningcode' => 'cannotdeletecategorycourse',
1216 'message' => 'Course ' . $courseid . ' failed to be deleted'
1218 continue;
1222 fix_course_sortorder();
1224 return array('warnings' => $warnings);
1228 * Returns description of method result value
1230 * @return external_description
1231 * @since Moodle 2.2
1233 public static function delete_courses_returns() {
1234 return new external_single_structure(
1235 array(
1236 'warnings' => new external_warnings()
1242 * Returns description of method parameters
1244 * @return external_function_parameters
1245 * @since Moodle 2.3
1247 public static function duplicate_course_parameters() {
1248 return new external_function_parameters(
1249 array(
1250 'courseid' => new external_value(PARAM_INT, 'course to duplicate id'),
1251 'fullname' => new external_value(PARAM_TEXT, 'duplicated course full name'),
1252 'shortname' => new external_value(PARAM_TEXT, 'duplicated course short name'),
1253 'categoryid' => new external_value(PARAM_INT, 'duplicated course category parent'),
1254 'visible' => new external_value(PARAM_INT, 'duplicated course visible, default to yes', VALUE_DEFAULT, 1),
1255 'options' => new external_multiple_structure(
1256 new external_single_structure(
1257 array(
1258 'name' => new external_value(PARAM_ALPHAEXT, 'The backup option name:
1259 "activities" (int) Include course activites (default to 1 that is equal to yes),
1260 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1261 "filters" (int) Include course filters (default to 1 that is equal to yes),
1262 "users" (int) Include users (default to 0 that is equal to no),
1263 "enrolments" (int) Include enrolment methods (default to 1 - restore only with users),
1264 "role_assignments" (int) Include role assignments (default to 0 that is equal to no),
1265 "comments" (int) Include user comments (default to 0 that is equal to no),
1266 "userscompletion" (int) Include user course completion information (default to 0 that is equal to no),
1267 "logs" (int) Include course logs (default to 0 that is equal to no),
1268 "grade_histories" (int) Include histories (default to 0 that is equal to no)'
1270 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1273 ), VALUE_DEFAULT, array()
1280 * Duplicate a course
1282 * @param int $courseid
1283 * @param string $fullname Duplicated course fullname
1284 * @param string $shortname Duplicated course shortname
1285 * @param int $categoryid Duplicated course parent category id
1286 * @param int $visible Duplicated course availability
1287 * @param array $options List of backup options
1288 * @return array New course info
1289 * @since Moodle 2.3
1291 public static function duplicate_course($courseid, $fullname, $shortname, $categoryid, $visible = 1, $options = array()) {
1292 global $CFG, $USER, $DB;
1293 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1294 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1296 // Parameter validation.
1297 $params = self::validate_parameters(
1298 self::duplicate_course_parameters(),
1299 array(
1300 'courseid' => $courseid,
1301 'fullname' => $fullname,
1302 'shortname' => $shortname,
1303 'categoryid' => $categoryid,
1304 'visible' => $visible,
1305 'options' => $options
1309 // Context validation.
1311 if (! ($course = $DB->get_record('course', array('id'=>$params['courseid'])))) {
1312 throw new moodle_exception('invalidcourseid', 'error');
1315 // Category where duplicated course is going to be created.
1316 $categorycontext = context_coursecat::instance($params['categoryid']);
1317 self::validate_context($categorycontext);
1319 // Course to be duplicated.
1320 $coursecontext = context_course::instance($course->id);
1321 self::validate_context($coursecontext);
1323 $backupdefaults = array(
1324 'activities' => 1,
1325 'blocks' => 1,
1326 'filters' => 1,
1327 'users' => 0,
1328 'enrolments' => backup::ENROL_WITHUSERS,
1329 'role_assignments' => 0,
1330 'comments' => 0,
1331 'userscompletion' => 0,
1332 'logs' => 0,
1333 'grade_histories' => 0
1336 $backupsettings = array();
1337 // Check for backup and restore options.
1338 if (!empty($params['options'])) {
1339 foreach ($params['options'] as $option) {
1341 // Strict check for a correct value (allways 1 or 0, true or false).
1342 $value = clean_param($option['value'], PARAM_INT);
1344 if ($value !== 0 and $value !== 1) {
1345 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1348 if (!isset($backupdefaults[$option['name']])) {
1349 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1352 $backupsettings[$option['name']] = $value;
1356 // Capability checking.
1358 // The backup controller check for this currently, this may be redundant.
1359 require_capability('moodle/course:create', $categorycontext);
1360 require_capability('moodle/restore:restorecourse', $categorycontext);
1361 require_capability('moodle/backup:backupcourse', $coursecontext);
1363 if (!empty($backupsettings['users'])) {
1364 require_capability('moodle/backup:userinfo', $coursecontext);
1365 require_capability('moodle/restore:userinfo', $categorycontext);
1368 // Check if the shortname is used.
1369 if ($foundcourses = $DB->get_records('course', array('shortname'=>$shortname))) {
1370 foreach ($foundcourses as $foundcourse) {
1371 $foundcoursenames[] = $foundcourse->fullname;
1374 $foundcoursenamestring = implode(',', $foundcoursenames);
1375 throw new moodle_exception('shortnametaken', '', '', $foundcoursenamestring);
1378 // Backup the course.
1380 $bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE,
1381 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id);
1383 foreach ($backupsettings as $name => $value) {
1384 if ($setting = $bc->get_plan()->get_setting($name)) {
1385 $bc->get_plan()->get_setting($name)->set_value($value);
1389 $backupid = $bc->get_backupid();
1390 $backupbasepath = $bc->get_plan()->get_basepath();
1392 $bc->execute_plan();
1393 $results = $bc->get_results();
1394 $file = $results['backup_destination'];
1396 $bc->destroy();
1398 // Restore the backup immediately.
1400 // Check if we need to unzip the file because the backup temp dir does not contains backup files.
1401 if (!file_exists($backupbasepath . "/moodle_backup.xml")) {
1402 $file->extract_to_pathname(get_file_packer('application/vnd.moodle.backup'), $backupbasepath);
1405 // Create new course.
1406 $newcourseid = restore_dbops::create_new_course($params['fullname'], $params['shortname'], $params['categoryid']);
1408 $rc = new restore_controller($backupid, $newcourseid,
1409 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id, backup::TARGET_NEW_COURSE);
1411 foreach ($backupsettings as $name => $value) {
1412 $setting = $rc->get_plan()->get_setting($name);
1413 if ($setting->get_status() == backup_setting::NOT_LOCKED) {
1414 $setting->set_value($value);
1418 if (!$rc->execute_precheck()) {
1419 $precheckresults = $rc->get_precheck_results();
1420 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1421 if (empty($CFG->keeptempdirectoriesonbackup)) {
1422 fulldelete($backupbasepath);
1425 $errorinfo = '';
1427 foreach ($precheckresults['errors'] as $error) {
1428 $errorinfo .= $error;
1431 if (array_key_exists('warnings', $precheckresults)) {
1432 foreach ($precheckresults['warnings'] as $warning) {
1433 $errorinfo .= $warning;
1437 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1441 $rc->execute_plan();
1442 $rc->destroy();
1444 $course = $DB->get_record('course', array('id' => $newcourseid), '*', MUST_EXIST);
1445 $course->fullname = $params['fullname'];
1446 $course->shortname = $params['shortname'];
1447 $course->visible = $params['visible'];
1449 // Set shortname and fullname back.
1450 $DB->update_record('course', $course);
1452 if (empty($CFG->keeptempdirectoriesonbackup)) {
1453 fulldelete($backupbasepath);
1456 // Delete the course backup file created by this WebService. Originally located in the course backups area.
1457 $file->delete();
1459 return array('id' => $course->id, 'shortname' => $course->shortname);
1463 * Returns description of method result value
1465 * @return external_description
1466 * @since Moodle 2.3
1468 public static function duplicate_course_returns() {
1469 return new external_single_structure(
1470 array(
1471 'id' => new external_value(PARAM_INT, 'course id'),
1472 'shortname' => new external_value(PARAM_TEXT, 'short name'),
1478 * Returns description of method parameters for import_course
1480 * @return external_function_parameters
1481 * @since Moodle 2.4
1483 public static function import_course_parameters() {
1484 return new external_function_parameters(
1485 array(
1486 'importfrom' => new external_value(PARAM_INT, 'the id of the course we are importing from'),
1487 'importto' => new external_value(PARAM_INT, 'the id of the course we are importing to'),
1488 'deletecontent' => new external_value(PARAM_INT, 'whether to delete the course content where we are importing to (default to 0 = No)', VALUE_DEFAULT, 0),
1489 'options' => new external_multiple_structure(
1490 new external_single_structure(
1491 array(
1492 'name' => new external_value(PARAM_ALPHA, 'The backup option name:
1493 "activities" (int) Include course activites (default to 1 that is equal to yes),
1494 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1495 "filters" (int) Include course filters (default to 1 that is equal to yes)'
1497 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1500 ), VALUE_DEFAULT, array()
1507 * Imports a course
1509 * @param int $importfrom The id of the course we are importing from
1510 * @param int $importto The id of the course we are importing to
1511 * @param bool $deletecontent Whether to delete the course we are importing to content
1512 * @param array $options List of backup options
1513 * @return null
1514 * @since Moodle 2.4
1516 public static function import_course($importfrom, $importto, $deletecontent = 0, $options = array()) {
1517 global $CFG, $USER, $DB;
1518 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1519 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1521 // Parameter validation.
1522 $params = self::validate_parameters(
1523 self::import_course_parameters(),
1524 array(
1525 'importfrom' => $importfrom,
1526 'importto' => $importto,
1527 'deletecontent' => $deletecontent,
1528 'options' => $options
1532 if ($params['deletecontent'] !== 0 and $params['deletecontent'] !== 1) {
1533 throw new moodle_exception('invalidextparam', 'webservice', '', $params['deletecontent']);
1536 // Context validation.
1538 if (! ($importfrom = $DB->get_record('course', array('id'=>$params['importfrom'])))) {
1539 throw new moodle_exception('invalidcourseid', 'error');
1542 if (! ($importto = $DB->get_record('course', array('id'=>$params['importto'])))) {
1543 throw new moodle_exception('invalidcourseid', 'error');
1546 $importfromcontext = context_course::instance($importfrom->id);
1547 self::validate_context($importfromcontext);
1549 $importtocontext = context_course::instance($importto->id);
1550 self::validate_context($importtocontext);
1552 $backupdefaults = array(
1553 'activities' => 1,
1554 'blocks' => 1,
1555 'filters' => 1
1558 $backupsettings = array();
1560 // Check for backup and restore options.
1561 if (!empty($params['options'])) {
1562 foreach ($params['options'] as $option) {
1564 // Strict check for a correct value (allways 1 or 0, true or false).
1565 $value = clean_param($option['value'], PARAM_INT);
1567 if ($value !== 0 and $value !== 1) {
1568 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1571 if (!isset($backupdefaults[$option['name']])) {
1572 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1575 $backupsettings[$option['name']] = $value;
1579 // Capability checking.
1581 require_capability('moodle/backup:backuptargetimport', $importfromcontext);
1582 require_capability('moodle/restore:restoretargetimport', $importtocontext);
1584 $bc = new backup_controller(backup::TYPE_1COURSE, $importfrom->id, backup::FORMAT_MOODLE,
1585 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
1587 foreach ($backupsettings as $name => $value) {
1588 $bc->get_plan()->get_setting($name)->set_value($value);
1591 $backupid = $bc->get_backupid();
1592 $backupbasepath = $bc->get_plan()->get_basepath();
1594 $bc->execute_plan();
1595 $bc->destroy();
1597 // Restore the backup immediately.
1599 // Check if we must delete the contents of the destination course.
1600 if ($params['deletecontent']) {
1601 $restoretarget = backup::TARGET_EXISTING_DELETING;
1602 } else {
1603 $restoretarget = backup::TARGET_EXISTING_ADDING;
1606 $rc = new restore_controller($backupid, $importto->id,
1607 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, $restoretarget);
1609 foreach ($backupsettings as $name => $value) {
1610 $rc->get_plan()->get_setting($name)->set_value($value);
1613 if (!$rc->execute_precheck()) {
1614 $precheckresults = $rc->get_precheck_results();
1615 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1616 if (empty($CFG->keeptempdirectoriesonbackup)) {
1617 fulldelete($backupbasepath);
1620 $errorinfo = '';
1622 foreach ($precheckresults['errors'] as $error) {
1623 $errorinfo .= $error;
1626 if (array_key_exists('warnings', $precheckresults)) {
1627 foreach ($precheckresults['warnings'] as $warning) {
1628 $errorinfo .= $warning;
1632 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1634 } else {
1635 if ($restoretarget == backup::TARGET_EXISTING_DELETING) {
1636 restore_dbops::delete_course_content($importto->id);
1640 $rc->execute_plan();
1641 $rc->destroy();
1643 if (empty($CFG->keeptempdirectoriesonbackup)) {
1644 fulldelete($backupbasepath);
1647 return null;
1651 * Returns description of method result value
1653 * @return external_description
1654 * @since Moodle 2.4
1656 public static function import_course_returns() {
1657 return null;
1661 * Returns description of method parameters
1663 * @return external_function_parameters
1664 * @since Moodle 2.3
1666 public static function get_categories_parameters() {
1667 return new external_function_parameters(
1668 array(
1669 'criteria' => new external_multiple_structure(
1670 new external_single_structure(
1671 array(
1672 'key' => new external_value(PARAM_ALPHA,
1673 'The category column to search, expected keys (value format) are:'.
1674 '"id" (int) the category id,'.
1675 '"ids" (string) category ids separated by commas,'.
1676 '"name" (string) the category name,'.
1677 '"parent" (int) the parent category id,'.
1678 '"idnumber" (string) category idnumber'.
1679 ' - user must have \'moodle/category:manage\' to search on idnumber,'.
1680 '"visible" (int) whether the returned categories must be visible or hidden. If the key is not passed,
1681 then the function return all categories that the user can see.'.
1682 ' - user must have \'moodle/category:manage\' or \'moodle/category:viewhiddencategories\' to search on visible,'.
1683 '"theme" (string) only return the categories having this theme'.
1684 ' - user must have \'moodle/category:manage\' to search on theme'),
1685 'value' => new external_value(PARAM_RAW, 'the value to match')
1687 ), 'criteria', VALUE_DEFAULT, array()
1689 'addsubcategories' => new external_value(PARAM_BOOL, 'return the sub categories infos
1690 (1 - default) otherwise only the category info (0)', VALUE_DEFAULT, 1)
1696 * Get categories
1698 * @param array $criteria Criteria to match the results
1699 * @param booln $addsubcategories obtain only the category (false) or its subcategories (true - default)
1700 * @return array list of categories
1701 * @since Moodle 2.3
1703 public static function get_categories($criteria = array(), $addsubcategories = true) {
1704 global $CFG, $DB;
1705 require_once($CFG->dirroot . "/course/lib.php");
1707 // Validate parameters.
1708 $params = self::validate_parameters(self::get_categories_parameters(),
1709 array('criteria' => $criteria, 'addsubcategories' => $addsubcategories));
1711 // Retrieve the categories.
1712 $categories = array();
1713 if (!empty($params['criteria'])) {
1715 $conditions = array();
1716 $wheres = array();
1717 foreach ($params['criteria'] as $crit) {
1718 $key = trim($crit['key']);
1720 // Trying to avoid duplicate keys.
1721 if (!isset($conditions[$key])) {
1723 $context = context_system::instance();
1724 $value = null;
1725 switch ($key) {
1726 case 'id':
1727 $value = clean_param($crit['value'], PARAM_INT);
1728 $conditions[$key] = $value;
1729 $wheres[] = $key . " = :" . $key;
1730 break;
1732 case 'ids':
1733 $value = clean_param($crit['value'], PARAM_SEQUENCE);
1734 $ids = explode(',', $value);
1735 list($sqlids, $paramids) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED);
1736 $conditions = array_merge($conditions, $paramids);
1737 $wheres[] = 'id ' . $sqlids;
1738 break;
1740 case 'idnumber':
1741 if (has_capability('moodle/category:manage', $context)) {
1742 $value = clean_param($crit['value'], PARAM_RAW);
1743 $conditions[$key] = $value;
1744 $wheres[] = $key . " = :" . $key;
1745 } else {
1746 // We must throw an exception.
1747 // Otherwise the dev client would think no idnumber exists.
1748 throw new moodle_exception('criteriaerror',
1749 'webservice', '', null,
1750 'You don\'t have the permissions to search on the "idnumber" field.');
1752 break;
1754 case 'name':
1755 $value = clean_param($crit['value'], PARAM_TEXT);
1756 $conditions[$key] = $value;
1757 $wheres[] = $key . " = :" . $key;
1758 break;
1760 case 'parent':
1761 $value = clean_param($crit['value'], PARAM_INT);
1762 $conditions[$key] = $value;
1763 $wheres[] = $key . " = :" . $key;
1764 break;
1766 case 'visible':
1767 if (has_capability('moodle/category:viewhiddencategories', $context)) {
1768 $value = clean_param($crit['value'], PARAM_INT);
1769 $conditions[$key] = $value;
1770 $wheres[] = $key . " = :" . $key;
1771 } else {
1772 throw new moodle_exception('criteriaerror',
1773 'webservice', '', null,
1774 'You don\'t have the permissions to search on the "visible" field.');
1776 break;
1778 case 'theme':
1779 if (has_capability('moodle/category:manage', $context)) {
1780 $value = clean_param($crit['value'], PARAM_THEME);
1781 $conditions[$key] = $value;
1782 $wheres[] = $key . " = :" . $key;
1783 } else {
1784 throw new moodle_exception('criteriaerror',
1785 'webservice', '', null,
1786 'You don\'t have the permissions to search on the "theme" field.');
1788 break;
1790 default:
1791 throw new moodle_exception('criteriaerror',
1792 'webservice', '', null,
1793 'You can not search on this criteria: ' . $key);
1798 if (!empty($wheres)) {
1799 $wheres = implode(" AND ", $wheres);
1801 $categories = $DB->get_records_select('course_categories', $wheres, $conditions);
1803 // Retrieve its sub subcategories (all levels).
1804 if ($categories and !empty($params['addsubcategories'])) {
1805 $newcategories = array();
1807 // Check if we required visible/theme checks.
1808 $additionalselect = '';
1809 $additionalparams = array();
1810 if (isset($conditions['visible'])) {
1811 $additionalselect .= ' AND visible = :visible';
1812 $additionalparams['visible'] = $conditions['visible'];
1814 if (isset($conditions['theme'])) {
1815 $additionalselect .= ' AND theme= :theme';
1816 $additionalparams['theme'] = $conditions['theme'];
1819 foreach ($categories as $category) {
1820 $sqlselect = $DB->sql_like('path', ':path') . $additionalselect;
1821 $sqlparams = array('path' => $category->path.'/%') + $additionalparams; // It will NOT include the specified category.
1822 $subcategories = $DB->get_records_select('course_categories', $sqlselect, $sqlparams);
1823 $newcategories = $newcategories + $subcategories; // Both arrays have integer as keys.
1825 $categories = $categories + $newcategories;
1829 } else {
1830 // Retrieve all categories in the database.
1831 $categories = $DB->get_records('course_categories');
1834 // The not returned categories. key => category id, value => reason of exclusion.
1835 $excludedcats = array();
1837 // The returned categories.
1838 $categoriesinfo = array();
1840 // We need to sort the categories by path.
1841 // The parent cats need to be checked by the algo first.
1842 usort($categories, "core_course_external::compare_categories_by_path");
1844 foreach ($categories as $category) {
1846 // Check if the category is a child of an excluded category, if yes exclude it too (excluded => do not return).
1847 $parents = explode('/', $category->path);
1848 unset($parents[0]); // First key is always empty because path start with / => /1/2/4.
1849 foreach ($parents as $parentid) {
1850 // Note: when the parent exclusion was due to the context,
1851 // the sub category could still be returned.
1852 if (isset($excludedcats[$parentid]) and $excludedcats[$parentid] != 'context') {
1853 $excludedcats[$category->id] = 'parent';
1857 // Check the user can use the category context.
1858 $context = context_coursecat::instance($category->id);
1859 try {
1860 self::validate_context($context);
1861 } catch (Exception $e) {
1862 $excludedcats[$category->id] = 'context';
1864 // If it was the requested category then throw an exception.
1865 if (isset($params['categoryid']) && $category->id == $params['categoryid']) {
1866 $exceptionparam = new stdClass();
1867 $exceptionparam->message = $e->getMessage();
1868 $exceptionparam->catid = $category->id;
1869 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
1873 // Return the category information.
1874 if (!isset($excludedcats[$category->id])) {
1876 // Final check to see if the category is visible to the user.
1877 if (core_course_category::can_view_category($category)) {
1879 $categoryinfo = array();
1880 $categoryinfo['id'] = $category->id;
1881 $categoryinfo['name'] = external_format_string($category->name, $context);
1882 list($categoryinfo['description'], $categoryinfo['descriptionformat']) =
1883 external_format_text($category->description, $category->descriptionformat,
1884 $context->id, 'coursecat', 'description', null);
1885 $categoryinfo['parent'] = $category->parent;
1886 $categoryinfo['sortorder'] = $category->sortorder;
1887 $categoryinfo['coursecount'] = $category->coursecount;
1888 $categoryinfo['depth'] = $category->depth;
1889 $categoryinfo['path'] = $category->path;
1891 // Some fields only returned for admin.
1892 if (has_capability('moodle/category:manage', $context)) {
1893 $categoryinfo['idnumber'] = $category->idnumber;
1894 $categoryinfo['visible'] = $category->visible;
1895 $categoryinfo['visibleold'] = $category->visibleold;
1896 $categoryinfo['timemodified'] = $category->timemodified;
1897 $categoryinfo['theme'] = clean_param($category->theme, PARAM_THEME);
1900 $categoriesinfo[] = $categoryinfo;
1901 } else {
1902 $excludedcats[$category->id] = 'visibility';
1907 // Sorting the resulting array so it looks a bit better for the client developer.
1908 usort($categoriesinfo, "core_course_external::compare_categories_by_sortorder");
1910 return $categoriesinfo;
1914 * Sort categories array by path
1915 * private function: only used by get_categories
1917 * @param array $category1
1918 * @param array $category2
1919 * @return int result of strcmp
1920 * @since Moodle 2.3
1922 private static function compare_categories_by_path($category1, $category2) {
1923 return strcmp($category1->path, $category2->path);
1927 * Sort categories array by sortorder
1928 * private function: only used by get_categories
1930 * @param array $category1
1931 * @param array $category2
1932 * @return int result of strcmp
1933 * @since Moodle 2.3
1935 private static function compare_categories_by_sortorder($category1, $category2) {
1936 return strcmp($category1['sortorder'], $category2['sortorder']);
1940 * Returns description of method result value
1942 * @return external_description
1943 * @since Moodle 2.3
1945 public static function get_categories_returns() {
1946 return new external_multiple_structure(
1947 new external_single_structure(
1948 array(
1949 'id' => new external_value(PARAM_INT, 'category id'),
1950 'name' => new external_value(PARAM_TEXT, 'category name'),
1951 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1952 'description' => new external_value(PARAM_RAW, 'category description'),
1953 'descriptionformat' => new external_format_value('description'),
1954 'parent' => new external_value(PARAM_INT, 'parent category id'),
1955 'sortorder' => new external_value(PARAM_INT, 'category sorting order'),
1956 'coursecount' => new external_value(PARAM_INT, 'number of courses in this category'),
1957 'visible' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1958 'visibleold' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1959 'timemodified' => new external_value(PARAM_INT, 'timestamp', VALUE_OPTIONAL),
1960 'depth' => new external_value(PARAM_INT, 'category depth'),
1961 'path' => new external_value(PARAM_TEXT, 'category path'),
1962 'theme' => new external_value(PARAM_THEME, 'category theme', VALUE_OPTIONAL),
1963 ), 'List of categories'
1969 * Returns description of method parameters
1971 * @return external_function_parameters
1972 * @since Moodle 2.3
1974 public static function create_categories_parameters() {
1975 return new external_function_parameters(
1976 array(
1977 'categories' => new external_multiple_structure(
1978 new external_single_structure(
1979 array(
1980 'name' => new external_value(PARAM_TEXT, 'new category name'),
1981 'parent' => new external_value(PARAM_INT,
1982 'the parent category id inside which the new category will be created
1983 - set to 0 for a root category',
1984 VALUE_DEFAULT, 0),
1985 'idnumber' => new external_value(PARAM_RAW,
1986 'the new category idnumber', VALUE_OPTIONAL),
1987 'description' => new external_value(PARAM_RAW,
1988 'the new category description', VALUE_OPTIONAL),
1989 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
1990 'theme' => new external_value(PARAM_THEME,
1991 'the new category theme. This option must be enabled on moodle',
1992 VALUE_OPTIONAL),
2001 * Create categories
2003 * @param array $categories - see create_categories_parameters() for the array structure
2004 * @return array - see create_categories_returns() for the array structure
2005 * @since Moodle 2.3
2007 public static function create_categories($categories) {
2008 global $DB;
2010 $params = self::validate_parameters(self::create_categories_parameters(),
2011 array('categories' => $categories));
2013 $transaction = $DB->start_delegated_transaction();
2015 $createdcategories = array();
2016 foreach ($params['categories'] as $category) {
2017 if ($category['parent']) {
2018 if (!$DB->record_exists('course_categories', array('id' => $category['parent']))) {
2019 throw new moodle_exception('unknowcategory');
2021 $context = context_coursecat::instance($category['parent']);
2022 } else {
2023 $context = context_system::instance();
2025 self::validate_context($context);
2026 require_capability('moodle/category:manage', $context);
2028 // this will validate format and throw an exception if there are errors
2029 external_validate_format($category['descriptionformat']);
2031 $newcategory = core_course_category::create($category);
2032 $context = context_coursecat::instance($newcategory->id);
2034 $createdcategories[] = array(
2035 'id' => $newcategory->id,
2036 'name' => external_format_string($newcategory->name, $context),
2040 $transaction->allow_commit();
2042 return $createdcategories;
2046 * Returns description of method parameters
2048 * @return external_function_parameters
2049 * @since Moodle 2.3
2051 public static function create_categories_returns() {
2052 return new external_multiple_structure(
2053 new external_single_structure(
2054 array(
2055 'id' => new external_value(PARAM_INT, 'new category id'),
2056 'name' => new external_value(PARAM_TEXT, 'new category name'),
2063 * Returns description of method parameters
2065 * @return external_function_parameters
2066 * @since Moodle 2.3
2068 public static function update_categories_parameters() {
2069 return new external_function_parameters(
2070 array(
2071 'categories' => new external_multiple_structure(
2072 new external_single_structure(
2073 array(
2074 'id' => new external_value(PARAM_INT, 'course id'),
2075 'name' => new external_value(PARAM_TEXT, 'category name', VALUE_OPTIONAL),
2076 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
2077 'parent' => new external_value(PARAM_INT, 'parent category id', VALUE_OPTIONAL),
2078 'description' => new external_value(PARAM_RAW, 'category description', VALUE_OPTIONAL),
2079 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
2080 'theme' => new external_value(PARAM_THEME,
2081 'the category theme. This option must be enabled on moodle', VALUE_OPTIONAL),
2090 * Update categories
2092 * @param array $categories The list of categories to update
2093 * @return null
2094 * @since Moodle 2.3
2096 public static function update_categories($categories) {
2097 global $DB;
2099 // Validate parameters.
2100 $params = self::validate_parameters(self::update_categories_parameters(), array('categories' => $categories));
2102 $transaction = $DB->start_delegated_transaction();
2104 foreach ($params['categories'] as $cat) {
2105 $category = core_course_category::get($cat['id']);
2107 $categorycontext = context_coursecat::instance($cat['id']);
2108 self::validate_context($categorycontext);
2109 require_capability('moodle/category:manage', $categorycontext);
2111 // this will throw an exception if descriptionformat is not valid
2112 external_validate_format($cat['descriptionformat']);
2114 $category->update($cat);
2117 $transaction->allow_commit();
2121 * Returns description of method result value
2123 * @return external_description
2124 * @since Moodle 2.3
2126 public static function update_categories_returns() {
2127 return null;
2131 * Returns description of method parameters
2133 * @return external_function_parameters
2134 * @since Moodle 2.3
2136 public static function delete_categories_parameters() {
2137 return new external_function_parameters(
2138 array(
2139 'categories' => new external_multiple_structure(
2140 new external_single_structure(
2141 array(
2142 'id' => new external_value(PARAM_INT, 'category id to delete'),
2143 'newparent' => new external_value(PARAM_INT,
2144 'the parent category to move the contents to, if specified', VALUE_OPTIONAL),
2145 'recursive' => new external_value(PARAM_BOOL, '1: recursively delete all contents inside this
2146 category, 0 (default): move contents to newparent or current parent category (except if parent is root)', VALUE_DEFAULT, 0)
2155 * Delete categories
2157 * @param array $categories A list of category ids
2158 * @return array
2159 * @since Moodle 2.3
2161 public static function delete_categories($categories) {
2162 global $CFG, $DB;
2163 require_once($CFG->dirroot . "/course/lib.php");
2165 // Validate parameters.
2166 $params = self::validate_parameters(self::delete_categories_parameters(), array('categories' => $categories));
2168 $transaction = $DB->start_delegated_transaction();
2170 foreach ($params['categories'] as $category) {
2171 $deletecat = core_course_category::get($category['id'], MUST_EXIST);
2172 $context = context_coursecat::instance($deletecat->id);
2173 require_capability('moodle/category:manage', $context);
2174 self::validate_context($context);
2175 self::validate_context(get_category_or_system_context($deletecat->parent));
2177 if ($category['recursive']) {
2178 // If recursive was specified, then we recursively delete the category's contents.
2179 if ($deletecat->can_delete_full()) {
2180 $deletecat->delete_full(false);
2181 } else {
2182 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2184 } else {
2185 // In this situation, we don't delete the category's contents, we either move it to newparent or parent.
2186 // If the parent is the root, moving is not supported (because a course must always be inside a category).
2187 // We must move to an existing category.
2188 if (!empty($category['newparent'])) {
2189 $newparentcat = core_course_category::get($category['newparent']);
2190 } else {
2191 $newparentcat = core_course_category::get($deletecat->parent);
2194 // This operation is not allowed. We must move contents to an existing category.
2195 if (!$newparentcat->id) {
2196 throw new moodle_exception('movecatcontentstoroot');
2199 self::validate_context(context_coursecat::instance($newparentcat->id));
2200 if ($deletecat->can_move_content_to($newparentcat->id)) {
2201 $deletecat->delete_move($newparentcat->id, false);
2202 } else {
2203 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2208 $transaction->allow_commit();
2212 * Returns description of method parameters
2214 * @return external_function_parameters
2215 * @since Moodle 2.3
2217 public static function delete_categories_returns() {
2218 return null;
2222 * Describes the parameters for delete_modules.
2224 * @return external_function_parameters
2225 * @since Moodle 2.5
2227 public static function delete_modules_parameters() {
2228 return new external_function_parameters (
2229 array(
2230 'cmids' => new external_multiple_structure(new external_value(PARAM_INT, 'course module ID',
2231 VALUE_REQUIRED, '', NULL_NOT_ALLOWED), 'Array of course module IDs'),
2237 * Deletes a list of provided module instances.
2239 * @param array $cmids the course module ids
2240 * @since Moodle 2.5
2242 public static function delete_modules($cmids) {
2243 global $CFG, $DB;
2245 // Require course file containing the course delete module function.
2246 require_once($CFG->dirroot . "/course/lib.php");
2248 // Clean the parameters.
2249 $params = self::validate_parameters(self::delete_modules_parameters(), array('cmids' => $cmids));
2251 // Keep track of the course ids we have performed a capability check on to avoid repeating.
2252 $arrcourseschecked = array();
2254 foreach ($params['cmids'] as $cmid) {
2255 // Get the course module.
2256 $cm = $DB->get_record('course_modules', array('id' => $cmid), '*', MUST_EXIST);
2258 // Check if we have not yet confirmed they have permission in this course.
2259 if (!in_array($cm->course, $arrcourseschecked)) {
2260 // Ensure the current user has required permission in this course.
2261 $context = context_course::instance($cm->course);
2262 self::validate_context($context);
2263 // Add to the array.
2264 $arrcourseschecked[] = $cm->course;
2267 // Ensure they can delete this module.
2268 $modcontext = context_module::instance($cm->id);
2269 require_capability('moodle/course:manageactivities', $modcontext);
2271 // Delete the module.
2272 course_delete_module($cm->id);
2277 * Describes the delete_modules return value.
2279 * @return external_single_structure
2280 * @since Moodle 2.5
2282 public static function delete_modules_returns() {
2283 return null;
2287 * Returns description of method parameters
2289 * @return external_function_parameters
2290 * @since Moodle 2.9
2292 public static function view_course_parameters() {
2293 return new external_function_parameters(
2294 array(
2295 'courseid' => new external_value(PARAM_INT, 'id of the course'),
2296 'sectionnumber' => new external_value(PARAM_INT, 'section number', VALUE_DEFAULT, 0)
2302 * Trigger the course viewed event.
2304 * @param int $courseid id of course
2305 * @param int $sectionnumber sectionnumber (0, 1, 2...)
2306 * @return array of warnings and status result
2307 * @since Moodle 2.9
2308 * @throws moodle_exception
2310 public static function view_course($courseid, $sectionnumber = 0) {
2311 global $CFG;
2312 require_once($CFG->dirroot . "/course/lib.php");
2314 $params = self::validate_parameters(self::view_course_parameters(),
2315 array(
2316 'courseid' => $courseid,
2317 'sectionnumber' => $sectionnumber
2320 $warnings = array();
2322 $course = get_course($params['courseid']);
2323 $context = context_course::instance($course->id);
2324 self::validate_context($context);
2326 if (!empty($params['sectionnumber'])) {
2328 // Get section details and check it exists.
2329 $modinfo = get_fast_modinfo($course);
2330 $coursesection = $modinfo->get_section_info($params['sectionnumber'], MUST_EXIST);
2332 // Check user is allowed to see it.
2333 if (!$coursesection->uservisible) {
2334 require_capability('moodle/course:viewhiddensections', $context);
2338 course_view($context, $params['sectionnumber']);
2340 $result = array();
2341 $result['status'] = true;
2342 $result['warnings'] = $warnings;
2343 return $result;
2347 * Returns description of method result value
2349 * @return external_description
2350 * @since Moodle 2.9
2352 public static function view_course_returns() {
2353 return new external_single_structure(
2354 array(
2355 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
2356 'warnings' => new external_warnings()
2362 * Returns description of method parameters
2364 * @return external_function_parameters
2365 * @since Moodle 3.0
2367 public static function search_courses_parameters() {
2368 return new external_function_parameters(
2369 array(
2370 'criterianame' => new external_value(PARAM_ALPHA, 'criteria name
2371 (search, modulelist (only admins), blocklist (only admins), tagid)'),
2372 'criteriavalue' => new external_value(PARAM_RAW, 'criteria value'),
2373 'page' => new external_value(PARAM_INT, 'page number (0 based)', VALUE_DEFAULT, 0),
2374 'perpage' => new external_value(PARAM_INT, 'items per page', VALUE_DEFAULT, 0),
2375 'requiredcapabilities' => new external_multiple_structure(
2376 new external_value(PARAM_CAPABILITY, 'Capability string used to filter courses by permission'),
2377 'Optional list of required capabilities (used to filter the list)', VALUE_DEFAULT, array()
2379 'limittoenrolled' => new external_value(PARAM_BOOL, 'limit to enrolled courses', VALUE_DEFAULT, 0),
2380 'onlywithcompletion' => new external_value(PARAM_BOOL, 'limit to courses where completion is enabled',
2381 VALUE_DEFAULT, 0),
2387 * Return the course information that is public (visible by every one)
2389 * @param core_course_list_element $course course in list object
2390 * @param stdClass $coursecontext course context object
2391 * @return array the course information
2392 * @since Moodle 3.2
2394 protected static function get_course_public_information(core_course_list_element $course, $coursecontext) {
2396 static $categoriescache = array();
2398 // Category information.
2399 if (!array_key_exists($course->category, $categoriescache)) {
2400 $categoriescache[$course->category] = core_course_category::get($course->category, IGNORE_MISSING);
2402 $category = $categoriescache[$course->category];
2404 // Retrieve course overview used files.
2405 $files = array();
2406 foreach ($course->get_course_overviewfiles() as $file) {
2407 $fileurl = moodle_url::make_webservice_pluginfile_url($file->get_contextid(), $file->get_component(),
2408 $file->get_filearea(), null, $file->get_filepath(),
2409 $file->get_filename())->out(false);
2410 $files[] = array(
2411 'filename' => $file->get_filename(),
2412 'fileurl' => $fileurl,
2413 'filesize' => $file->get_filesize(),
2414 'filepath' => $file->get_filepath(),
2415 'mimetype' => $file->get_mimetype(),
2416 'timemodified' => $file->get_timemodified(),
2420 // Retrieve the course contacts,
2421 // we need here the users fullname since if we are not enrolled can be difficult to obtain them via other Web Services.
2422 $coursecontacts = array();
2423 foreach ($course->get_course_contacts() as $contact) {
2424 $coursecontacts[] = array(
2425 'id' => $contact['user']->id,
2426 'fullname' => $contact['username'],
2427 'roles' => array_map(function($role){
2428 return array('id' => $role->id, 'name' => $role->displayname);
2429 }, $contact['roles']),
2430 'role' => array('id' => $contact['role']->id, 'name' => $contact['role']->displayname),
2431 'rolename' => $contact['rolename']
2435 // Allowed enrolment methods (maybe we can self-enrol).
2436 $enroltypes = array();
2437 $instances = enrol_get_instances($course->id, true);
2438 foreach ($instances as $instance) {
2439 $enroltypes[] = $instance->enrol;
2442 // Format summary.
2443 list($summary, $summaryformat) =
2444 external_format_text($course->summary, $course->summaryformat, $coursecontext->id, 'course', 'summary', null);
2446 $categoryname = '';
2447 if (!empty($category)) {
2448 $categoryname = external_format_string($category->name, $category->get_context());
2451 $displayname = get_course_display_name_for_list($course);
2452 $coursereturns = array();
2453 $coursereturns['id'] = $course->id;
2454 $coursereturns['fullname'] = external_format_string($course->fullname, $coursecontext->id);
2455 $coursereturns['displayname'] = external_format_string($displayname, $coursecontext->id);
2456 $coursereturns['shortname'] = external_format_string($course->shortname, $coursecontext->id);
2457 $coursereturns['categoryid'] = $course->category;
2458 $coursereturns['categoryname'] = $categoryname;
2459 $coursereturns['summary'] = $summary;
2460 $coursereturns['summaryformat'] = $summaryformat;
2461 $coursereturns['summaryfiles'] = external_util::get_area_files($coursecontext->id, 'course', 'summary', false, false);
2462 $coursereturns['overviewfiles'] = $files;
2463 $coursereturns['contacts'] = $coursecontacts;
2464 $coursereturns['enrollmentmethods'] = $enroltypes;
2465 $coursereturns['sortorder'] = $course->sortorder;
2467 $handler = core_course\customfield\course_handler::create();
2468 if ($customfields = $handler->export_instance_data($course->id)) {
2469 $coursereturns['customfields'] = [];
2470 foreach ($customfields as $data) {
2471 $coursereturns['customfields'][] = [
2472 'type' => $data->get_type(),
2473 'value' => $data->get_value(),
2474 'name' => $data->get_name(),
2475 'shortname' => $data->get_shortname()
2480 return $coursereturns;
2484 * Search courses following the specified criteria.
2486 * @param string $criterianame Criteria name (search, modulelist (only admins), blocklist (only admins), tagid)
2487 * @param string $criteriavalue Criteria value
2488 * @param int $page Page number (for pagination)
2489 * @param int $perpage Items per page
2490 * @param array $requiredcapabilities Optional list of required capabilities (used to filter the list).
2491 * @param int $limittoenrolled Limit to only enrolled courses
2492 * @param int onlywithcompletion Limit to only courses where completion is enabled
2493 * @return array of course objects and warnings
2494 * @since Moodle 3.0
2495 * @throws moodle_exception
2497 public static function search_courses($criterianame,
2498 $criteriavalue,
2499 $page=0,
2500 $perpage=0,
2501 $requiredcapabilities=array(),
2502 $limittoenrolled=0,
2503 $onlywithcompletion=0) {
2504 global $CFG;
2506 $warnings = array();
2508 $parameters = array(
2509 'criterianame' => $criterianame,
2510 'criteriavalue' => $criteriavalue,
2511 'page' => $page,
2512 'perpage' => $perpage,
2513 'requiredcapabilities' => $requiredcapabilities,
2514 'limittoenrolled' => $limittoenrolled,
2515 'onlywithcompletion' => $onlywithcompletion
2517 $params = self::validate_parameters(self::search_courses_parameters(), $parameters);
2518 self::validate_context(context_system::instance());
2520 $allowedcriterianames = array('search', 'modulelist', 'blocklist', 'tagid');
2521 if (!in_array($params['criterianame'], $allowedcriterianames)) {
2522 throw new invalid_parameter_exception('Invalid value for criterianame parameter (value: '.$params['criterianame'].'),' .
2523 'allowed values are: '.implode(',', $allowedcriterianames));
2526 if ($params['criterianame'] == 'modulelist' or $params['criterianame'] == 'blocklist') {
2527 require_capability('moodle/site:config', context_system::instance());
2530 $paramtype = array(
2531 'search' => PARAM_RAW,
2532 'modulelist' => PARAM_PLUGIN,
2533 'blocklist' => PARAM_INT,
2534 'tagid' => PARAM_INT
2536 $params['criteriavalue'] = clean_param($params['criteriavalue'], $paramtype[$params['criterianame']]);
2538 // Prepare the search API options.
2539 $searchcriteria = array();
2540 $searchcriteria[$params['criterianame']] = $params['criteriavalue'];
2541 if ($params['onlywithcompletion']) {
2542 $searchcriteria['onlywithcompletion'] = true;
2545 $options = array();
2546 if ($params['perpage'] != 0) {
2547 $offset = $params['page'] * $params['perpage'];
2548 $options = array('offset' => $offset, 'limit' => $params['perpage']);
2551 // Search the courses.
2552 $courses = core_course_category::search_courses($searchcriteria, $options, $params['requiredcapabilities']);
2553 $totalcount = core_course_category::search_courses_count($searchcriteria, $options, $params['requiredcapabilities']);
2555 if (!empty($limittoenrolled)) {
2556 // Get the courses where the current user has access.
2557 $enrolled = enrol_get_my_courses(array('id', 'cacherev'));
2560 $finalcourses = array();
2561 $categoriescache = array();
2563 foreach ($courses as $course) {
2564 if (!empty($limittoenrolled)) {
2565 // Filter out not enrolled courses.
2566 if (!isset($enrolled[$course->id])) {
2567 $totalcount--;
2568 continue;
2572 $coursecontext = context_course::instance($course->id);
2574 $finalcourses[] = self::get_course_public_information($course, $coursecontext);
2577 return array(
2578 'total' => $totalcount,
2579 'courses' => $finalcourses,
2580 'warnings' => $warnings
2585 * Returns a course structure definition
2587 * @param boolean $onlypublicdata set to true, to retrieve only fields viewable by anyone when the course is visible
2588 * @return array the course structure
2589 * @since Moodle 3.2
2591 protected static function get_course_structure($onlypublicdata = true) {
2592 $coursestructure = array(
2593 'id' => new external_value(PARAM_INT, 'course id'),
2594 'fullname' => new external_value(PARAM_TEXT, 'course full name'),
2595 'displayname' => new external_value(PARAM_TEXT, 'course display name'),
2596 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
2597 'categoryid' => new external_value(PARAM_INT, 'category id'),
2598 'categoryname' => new external_value(PARAM_TEXT, 'category name'),
2599 'sortorder' => new external_value(PARAM_INT, 'Sort order in the category', VALUE_OPTIONAL),
2600 'summary' => new external_value(PARAM_RAW, 'summary'),
2601 'summaryformat' => new external_format_value('summary'),
2602 'summaryfiles' => new external_files('summary files in the summary field', VALUE_OPTIONAL),
2603 'overviewfiles' => new external_files('additional overview files attached to this course'),
2604 'contacts' => new external_multiple_structure(
2605 new external_single_structure(
2606 array(
2607 'id' => new external_value(PARAM_INT, 'contact user id'),
2608 'fullname' => new external_value(PARAM_NOTAGS, 'contact user fullname'),
2611 'contact users'
2613 'enrollmentmethods' => new external_multiple_structure(
2614 new external_value(PARAM_PLUGIN, 'enrollment method'),
2615 'enrollment methods list'
2617 'customfields' => new external_multiple_structure(
2618 new external_single_structure(
2619 array(
2620 'name' => new external_value(PARAM_RAW, 'The name of the custom field'),
2621 'shortname' => new external_value(PARAM_RAW,
2622 'The shortname of the custom field - to be able to build the field class in the code'),
2623 'type' => new external_value(PARAM_ALPHANUMEXT,
2624 'The type of the custom field - text field, checkbox...'),
2625 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
2627 ), 'Custom fields', VALUE_OPTIONAL),
2630 if (!$onlypublicdata) {
2631 $extra = array(
2632 'idnumber' => new external_value(PARAM_RAW, 'Id number', VALUE_OPTIONAL),
2633 'format' => new external_value(PARAM_PLUGIN, 'Course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
2634 'showgrades' => new external_value(PARAM_INT, '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
2635 'newsitems' => new external_value(PARAM_INT, 'Number of recent items appearing on the course page', VALUE_OPTIONAL),
2636 'startdate' => new external_value(PARAM_INT, 'Timestamp when the course start', VALUE_OPTIONAL),
2637 'enddate' => new external_value(PARAM_INT, 'Timestamp when the course end', VALUE_OPTIONAL),
2638 'maxbytes' => new external_value(PARAM_INT, 'Largest size of file that can be uploaded into', VALUE_OPTIONAL),
2639 'showreports' => new external_value(PARAM_INT, 'Are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
2640 'visible' => new external_value(PARAM_INT, '1: available to student, 0:not available', VALUE_OPTIONAL),
2641 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
2642 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
2643 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
2644 'enablecompletion' => new external_value(PARAM_INT, 'Completion enabled? 1: yes 0: no', VALUE_OPTIONAL),
2645 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
2646 'lang' => new external_value(PARAM_SAFEDIR, 'Forced course language', VALUE_OPTIONAL),
2647 'theme' => new external_value(PARAM_PLUGIN, 'Fame of the forced theme', VALUE_OPTIONAL),
2648 'marker' => new external_value(PARAM_INT, 'Current course marker', VALUE_OPTIONAL),
2649 'legacyfiles' => new external_value(PARAM_INT, 'If legacy files are enabled', VALUE_OPTIONAL),
2650 'calendartype' => new external_value(PARAM_PLUGIN, 'Calendar type', VALUE_OPTIONAL),
2651 'timecreated' => new external_value(PARAM_INT, 'Time when the course was created', VALUE_OPTIONAL),
2652 'timemodified' => new external_value(PARAM_INT, 'Last time the course was updated', VALUE_OPTIONAL),
2653 'requested' => new external_value(PARAM_INT, 'If is a requested course', VALUE_OPTIONAL),
2654 'cacherev' => new external_value(PARAM_INT, 'Cache revision number', VALUE_OPTIONAL),
2655 'filters' => new external_multiple_structure(
2656 new external_single_structure(
2657 array(
2658 'filter' => new external_value(PARAM_PLUGIN, 'Filter plugin name'),
2659 'localstate' => new external_value(PARAM_INT, 'Filter state: 1 for on, -1 for off, 0 if inherit'),
2660 'inheritedstate' => new external_value(PARAM_INT, '1 or 0 to use when localstate is set to inherit'),
2663 'Course filters', VALUE_OPTIONAL
2665 'courseformatoptions' => new external_multiple_structure(
2666 new external_single_structure(
2667 array(
2668 'name' => new external_value(PARAM_RAW, 'Course format option name.'),
2669 'value' => new external_value(PARAM_RAW, 'Course format option value.'),
2672 'Additional options for particular course format.', VALUE_OPTIONAL
2675 $coursestructure = array_merge($coursestructure, $extra);
2677 return new external_single_structure($coursestructure);
2681 * Returns description of method result value
2683 * @return external_description
2684 * @since Moodle 3.0
2686 public static function search_courses_returns() {
2687 return new external_single_structure(
2688 array(
2689 'total' => new external_value(PARAM_INT, 'total course count'),
2690 'courses' => new external_multiple_structure(self::get_course_structure(), 'course'),
2691 'warnings' => new external_warnings()
2697 * Returns description of method parameters
2699 * @return external_function_parameters
2700 * @since Moodle 3.0
2702 public static function get_course_module_parameters() {
2703 return new external_function_parameters(
2704 array(
2705 'cmid' => new external_value(PARAM_INT, 'The course module id')
2711 * Return information about a course module.
2713 * @param int $cmid the course module id
2714 * @return array of warnings and the course module
2715 * @since Moodle 3.0
2716 * @throws moodle_exception
2718 public static function get_course_module($cmid) {
2719 global $CFG, $DB;
2721 $params = self::validate_parameters(self::get_course_module_parameters(), array('cmid' => $cmid));
2722 $warnings = array();
2724 $cm = get_coursemodule_from_id(null, $params['cmid'], 0, true, MUST_EXIST);
2725 $context = context_module::instance($cm->id);
2726 self::validate_context($context);
2728 // If the user has permissions to manage the activity, return all the information.
2729 if (has_capability('moodle/course:manageactivities', $context)) {
2730 require_once($CFG->dirroot . '/course/modlib.php');
2731 require_once($CFG->libdir . '/gradelib.php');
2733 $info = $cm;
2734 // Get the extra information: grade, advanced grading and outcomes data.
2735 $course = get_course($cm->course);
2736 list($newcm, $newcontext, $module, $extrainfo, $cw) = get_moduleinfo_data($cm, $course);
2737 // Grades.
2738 $gradeinfo = array('grade', 'gradepass', 'gradecat');
2739 foreach ($gradeinfo as $gfield) {
2740 if (isset($extrainfo->{$gfield})) {
2741 $info->{$gfield} = $extrainfo->{$gfield};
2744 if (isset($extrainfo->grade) and $extrainfo->grade < 0) {
2745 $info->scale = $DB->get_field('scale', 'scale', array('id' => abs($extrainfo->grade)));
2747 // Advanced grading.
2748 if (isset($extrainfo->_advancedgradingdata)) {
2749 $info->advancedgrading = array();
2750 foreach ($extrainfo as $key => $val) {
2751 if (strpos($key, 'advancedgradingmethod_') === 0) {
2752 $info->advancedgrading[] = array(
2753 'area' => str_replace('advancedgradingmethod_', '', $key),
2754 'method' => $val
2759 // Outcomes.
2760 foreach ($extrainfo as $key => $val) {
2761 if (strpos($key, 'outcome_') === 0) {
2762 if (!isset($info->outcomes)) {
2763 $info->outcomes = array();
2765 $id = str_replace('outcome_', '', $key);
2766 $outcome = grade_outcome::fetch(array('id' => $id));
2767 $scaleitems = $outcome->load_scale();
2768 $info->outcomes[] = array(
2769 'id' => $id,
2770 'name' => external_format_string($outcome->get_name(), $context->id),
2771 'scale' => $scaleitems->scale
2775 } else {
2776 // Return information is safe to show to any user.
2777 $info = new stdClass();
2778 $info->id = $cm->id;
2779 $info->course = $cm->course;
2780 $info->module = $cm->module;
2781 $info->modname = $cm->modname;
2782 $info->instance = $cm->instance;
2783 $info->section = $cm->section;
2784 $info->sectionnum = $cm->sectionnum;
2785 $info->groupmode = $cm->groupmode;
2786 $info->groupingid = $cm->groupingid;
2787 $info->completion = $cm->completion;
2789 // Format name.
2790 $info->name = external_format_string($cm->name, $context->id);
2791 $result = array();
2792 $result['cm'] = $info;
2793 $result['warnings'] = $warnings;
2794 return $result;
2798 * Returns description of method result value
2800 * @return external_description
2801 * @since Moodle 3.0
2803 public static function get_course_module_returns() {
2804 return new external_single_structure(
2805 array(
2806 'cm' => new external_single_structure(
2807 array(
2808 'id' => new external_value(PARAM_INT, 'The course module id'),
2809 'course' => new external_value(PARAM_INT, 'The course id'),
2810 'module' => new external_value(PARAM_INT, 'The module type id'),
2811 'name' => new external_value(PARAM_RAW, 'The activity name'),
2812 'modname' => new external_value(PARAM_COMPONENT, 'The module component name (forum, assign, etc..)'),
2813 'instance' => new external_value(PARAM_INT, 'The activity instance id'),
2814 'section' => new external_value(PARAM_INT, 'The module section id'),
2815 'sectionnum' => new external_value(PARAM_INT, 'The module section number'),
2816 'groupmode' => new external_value(PARAM_INT, 'Group mode'),
2817 'groupingid' => new external_value(PARAM_INT, 'Grouping id'),
2818 'completion' => new external_value(PARAM_INT, 'If completion is enabled'),
2819 'idnumber' => new external_value(PARAM_RAW, 'Module id number', VALUE_OPTIONAL),
2820 'added' => new external_value(PARAM_INT, 'Time added', VALUE_OPTIONAL),
2821 'score' => new external_value(PARAM_INT, 'Score', VALUE_OPTIONAL),
2822 'indent' => new external_value(PARAM_INT, 'Indentation', VALUE_OPTIONAL),
2823 'visible' => new external_value(PARAM_INT, 'If visible', VALUE_OPTIONAL),
2824 'visibleoncoursepage' => new external_value(PARAM_INT, 'If visible on course page', VALUE_OPTIONAL),
2825 'visibleold' => new external_value(PARAM_INT, 'Visible old', VALUE_OPTIONAL),
2826 'completiongradeitemnumber' => new external_value(PARAM_INT, 'Completion grade item', VALUE_OPTIONAL),
2827 'completionview' => new external_value(PARAM_INT, 'Completion view setting', VALUE_OPTIONAL),
2828 'completionexpected' => new external_value(PARAM_INT, 'Completion time expected', VALUE_OPTIONAL),
2829 'showdescription' => new external_value(PARAM_INT, 'If the description is showed', VALUE_OPTIONAL),
2830 'availability' => new external_value(PARAM_RAW, 'Availability settings', VALUE_OPTIONAL),
2831 'grade' => new external_value(PARAM_FLOAT, 'Grade (max value or scale id)', VALUE_OPTIONAL),
2832 'scale' => new external_value(PARAM_TEXT, 'Scale items (if used)', VALUE_OPTIONAL),
2833 'gradepass' => new external_value(PARAM_RAW, 'Grade to pass (float)', VALUE_OPTIONAL),
2834 'gradecat' => new external_value(PARAM_INT, 'Grade category', VALUE_OPTIONAL),
2835 'advancedgrading' => new external_multiple_structure(
2836 new external_single_structure(
2837 array(
2838 'area' => new external_value(PARAM_AREA, 'Gradable area name'),
2839 'method' => new external_value(PARAM_COMPONENT, 'Grading method'),
2842 'Advanced grading settings', VALUE_OPTIONAL
2844 'outcomes' => new external_multiple_structure(
2845 new external_single_structure(
2846 array(
2847 'id' => new external_value(PARAM_ALPHANUMEXT, 'Outcome id'),
2848 'name' => new external_value(PARAM_TEXT, 'Outcome full name'),
2849 'scale' => new external_value(PARAM_TEXT, 'Scale items')
2852 'Outcomes information', VALUE_OPTIONAL
2856 'warnings' => new external_warnings()
2862 * Returns description of method parameters
2864 * @return external_function_parameters
2865 * @since Moodle 3.0
2867 public static function get_course_module_by_instance_parameters() {
2868 return new external_function_parameters(
2869 array(
2870 'module' => new external_value(PARAM_COMPONENT, 'The module name'),
2871 'instance' => new external_value(PARAM_INT, 'The module instance id')
2877 * Return information about a course module.
2879 * @param string $module the module name
2880 * @param int $instance the activity instance id
2881 * @return array of warnings and the course module
2882 * @since Moodle 3.0
2883 * @throws moodle_exception
2885 public static function get_course_module_by_instance($module, $instance) {
2887 $params = self::validate_parameters(self::get_course_module_by_instance_parameters(),
2888 array(
2889 'module' => $module,
2890 'instance' => $instance,
2893 $warnings = array();
2894 $cm = get_coursemodule_from_instance($params['module'], $params['instance'], 0, false, MUST_EXIST);
2896 return self::get_course_module($cm->id);
2900 * Returns description of method result value
2902 * @return external_description
2903 * @since Moodle 3.0
2905 public static function get_course_module_by_instance_returns() {
2906 return self::get_course_module_returns();
2910 * Returns description of method parameters
2912 * @return external_function_parameters
2913 * @since Moodle 3.2
2915 public static function get_user_navigation_options_parameters() {
2916 return new external_function_parameters(
2917 array(
2918 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2924 * Return a list of navigation options in a set of courses that are avaialable or not for the current user.
2926 * @param array $courseids a list of course ids
2927 * @return array of warnings and the options availability
2928 * @since Moodle 3.2
2929 * @throws moodle_exception
2931 public static function get_user_navigation_options($courseids) {
2932 global $CFG;
2933 require_once($CFG->dirroot . '/course/lib.php');
2935 // Parameter validation.
2936 $params = self::validate_parameters(self::get_user_navigation_options_parameters(), array('courseids' => $courseids));
2937 $courseoptions = array();
2939 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
2941 if (!empty($courses)) {
2942 foreach ($courses as $course) {
2943 // Fix the context for the frontpage.
2944 if ($course->id == SITEID) {
2945 $course->context = context_system::instance();
2947 $navoptions = course_get_user_navigation_options($course->context, $course);
2948 $options = array();
2949 foreach ($navoptions as $name => $available) {
2950 $options[] = array(
2951 'name' => $name,
2952 'available' => $available,
2956 $courseoptions[] = array(
2957 'id' => $course->id,
2958 'options' => $options
2963 $result = array(
2964 'courses' => $courseoptions,
2965 'warnings' => $warnings
2967 return $result;
2971 * Returns description of method result value
2973 * @return external_description
2974 * @since Moodle 3.2
2976 public static function get_user_navigation_options_returns() {
2977 return new external_single_structure(
2978 array(
2979 'courses' => new external_multiple_structure(
2980 new external_single_structure(
2981 array(
2982 'id' => new external_value(PARAM_INT, 'Course id'),
2983 'options' => new external_multiple_structure(
2984 new external_single_structure(
2985 array(
2986 'name' => new external_value(PARAM_ALPHANUMEXT, 'Option name'),
2987 'available' => new external_value(PARAM_BOOL, 'Whether the option is available or not'),
2992 ), 'List of courses'
2994 'warnings' => new external_warnings()
3000 * Returns description of method parameters
3002 * @return external_function_parameters
3003 * @since Moodle 3.2
3005 public static function get_user_administration_options_parameters() {
3006 return new external_function_parameters(
3007 array(
3008 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
3014 * Return a list of administration options in a set of courses that are available or not for the current user.
3016 * @param array $courseids a list of course ids
3017 * @return array of warnings and the options availability
3018 * @since Moodle 3.2
3019 * @throws moodle_exception
3021 public static function get_user_administration_options($courseids) {
3022 global $CFG;
3023 require_once($CFG->dirroot . '/course/lib.php');
3025 // Parameter validation.
3026 $params = self::validate_parameters(self::get_user_administration_options_parameters(), array('courseids' => $courseids));
3027 $courseoptions = array();
3029 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
3031 if (!empty($courses)) {
3032 foreach ($courses as $course) {
3033 $adminoptions = course_get_user_administration_options($course, $course->context);
3034 $options = array();
3035 foreach ($adminoptions as $name => $available) {
3036 $options[] = array(
3037 'name' => $name,
3038 'available' => $available,
3042 $courseoptions[] = array(
3043 'id' => $course->id,
3044 'options' => $options
3049 $result = array(
3050 'courses' => $courseoptions,
3051 'warnings' => $warnings
3053 return $result;
3057 * Returns description of method result value
3059 * @return external_description
3060 * @since Moodle 3.2
3062 public static function get_user_administration_options_returns() {
3063 return self::get_user_navigation_options_returns();
3067 * Returns description of method parameters
3069 * @return external_function_parameters
3070 * @since Moodle 3.2
3072 public static function get_courses_by_field_parameters() {
3073 return new external_function_parameters(
3074 array(
3075 'field' => new external_value(PARAM_ALPHA, 'The field to search can be left empty for all courses or:
3076 id: course id
3077 ids: comma separated course ids
3078 shortname: course short name
3079 idnumber: course id number
3080 category: category id the course belongs to
3081 ', VALUE_DEFAULT, ''),
3082 'value' => new external_value(PARAM_RAW, 'The value to match', VALUE_DEFAULT, '')
3089 * Get courses matching a specific field (id/s, shortname, idnumber, category)
3091 * @param string $field field name to search, or empty for all courses
3092 * @param string $value value to search
3093 * @return array list of courses and warnings
3094 * @throws invalid_parameter_exception
3095 * @since Moodle 3.2
3097 public static function get_courses_by_field($field = '', $value = '') {
3098 global $DB, $CFG;
3099 require_once($CFG->dirroot . '/course/lib.php');
3100 require_once($CFG->libdir . '/filterlib.php');
3102 $params = self::validate_parameters(self::get_courses_by_field_parameters(),
3103 array(
3104 'field' => $field,
3105 'value' => $value,
3108 $warnings = array();
3110 if (empty($params['field'])) {
3111 $courses = $DB->get_records('course', null, 'id ASC');
3112 } else {
3113 switch ($params['field']) {
3114 case 'id':
3115 case 'category':
3116 $value = clean_param($params['value'], PARAM_INT);
3117 break;
3118 case 'ids':
3119 $value = clean_param($params['value'], PARAM_SEQUENCE);
3120 break;
3121 case 'shortname':
3122 $value = clean_param($params['value'], PARAM_TEXT);
3123 break;
3124 case 'idnumber':
3125 $value = clean_param($params['value'], PARAM_RAW);
3126 break;
3127 default:
3128 throw new invalid_parameter_exception('Invalid field name');
3131 if ($params['field'] === 'ids') {
3132 // Preload categories to avoid loading one at a time.
3133 $courseids = explode(',', $value);
3134 list ($listsql, $listparams) = $DB->get_in_or_equal($courseids);
3135 $categoryids = $DB->get_fieldset_sql("
3136 SELECT DISTINCT cc.id
3137 FROM {course} c
3138 JOIN {course_categories} cc ON cc.id = c.category
3139 WHERE c.id $listsql", $listparams);
3140 core_course_category::get_many($categoryids);
3142 // Load and validate all courses. This is called because it loads the courses
3143 // more efficiently.
3144 list ($courses, $warnings) = external_util::validate_courses($courseids, [],
3145 false, true);
3146 } else {
3147 $courses = $DB->get_records('course', array($params['field'] => $value), 'id ASC');
3151 $coursesdata = array();
3152 foreach ($courses as $course) {
3153 $context = context_course::instance($course->id);
3154 $canupdatecourse = has_capability('moodle/course:update', $context);
3155 $canviewhiddencourses = has_capability('moodle/course:viewhiddencourses', $context);
3157 // Check if the course is visible in the site for the user.
3158 if (!$course->visible and !$canviewhiddencourses and !$canupdatecourse) {
3159 continue;
3161 // Get the public course information, even if we are not enrolled.
3162 $courseinlist = new core_course_list_element($course);
3164 // Now, check if we have access to the course, unless it was already checked.
3165 try {
3166 if (empty($course->contextvalidated)) {
3167 self::validate_context($context);
3169 } catch (Exception $e) {
3170 // User can not access the course, check if they can see the public information about the course and return it.
3171 if (core_course_category::can_view_course_info($course)) {
3172 $coursesdata[$course->id] = self::get_course_public_information($courseinlist, $context);
3174 continue;
3176 $coursesdata[$course->id] = self::get_course_public_information($courseinlist, $context);
3177 // Return information for any user that can access the course.
3178 $coursefields = array('format', 'showgrades', 'newsitems', 'startdate', 'enddate', 'maxbytes', 'showreports', 'visible',
3179 'groupmode', 'groupmodeforce', 'defaultgroupingid', 'enablecompletion', 'completionnotify', 'lang', 'theme',
3180 'marker');
3182 // Course filters.
3183 $coursesdata[$course->id]['filters'] = filter_get_available_in_context($context);
3185 // Information for managers only.
3186 if ($canupdatecourse) {
3187 $managerfields = array('idnumber', 'legacyfiles', 'calendartype', 'timecreated', 'timemodified', 'requested',
3188 'cacherev');
3189 $coursefields = array_merge($coursefields, $managerfields);
3192 // Populate fields.
3193 foreach ($coursefields as $field) {
3194 $coursesdata[$course->id][$field] = $course->{$field};
3197 // Clean lang and auth fields for external functions (it may content uninstalled themes or language packs).
3198 if (isset($coursesdata[$course->id]['theme'])) {
3199 $coursesdata[$course->id]['theme'] = clean_param($coursesdata[$course->id]['theme'], PARAM_THEME);
3201 if (isset($coursesdata[$course->id]['lang'])) {
3202 $coursesdata[$course->id]['lang'] = clean_param($coursesdata[$course->id]['lang'], PARAM_LANG);
3205 $courseformatoptions = course_get_format($course)->get_config_for_external();
3206 foreach ($courseformatoptions as $key => $value) {
3207 $coursesdata[$course->id]['courseformatoptions'][] = array(
3208 'name' => $key,
3209 'value' => $value
3214 return array(
3215 'courses' => $coursesdata,
3216 'warnings' => $warnings
3221 * Returns description of method result value
3223 * @return external_description
3224 * @since Moodle 3.2
3226 public static function get_courses_by_field_returns() {
3227 // Course structure, including not only public viewable fields.
3228 return new external_single_structure(
3229 array(
3230 'courses' => new external_multiple_structure(self::get_course_structure(false), 'Course'),
3231 'warnings' => new external_warnings()
3237 * Returns description of method parameters
3239 * @return external_function_parameters
3240 * @since Moodle 3.2
3242 public static function check_updates_parameters() {
3243 return new external_function_parameters(
3244 array(
3245 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3246 'tocheck' => new external_multiple_structure(
3247 new external_single_structure(
3248 array(
3249 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level for the file location.
3250 Only module supported right now.'),
3251 'id' => new external_value(PARAM_INT, 'Context instance id'),
3252 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3255 'Instances to check'
3257 'filter' => new external_multiple_structure(
3258 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3259 gradeitems, outcomes'),
3260 'Check only for updates in these areas', VALUE_DEFAULT, array()
3267 * Check if there is updates affecting the user for the given course and contexts.
3268 * Right now only modules are supported.
3269 * This WS calls mod_check_updates_since for each module to check if there is any update the user should we aware of.
3271 * @param int $courseid the list of modules to check
3272 * @param array $tocheck the list of modules to check
3273 * @param array $filter check only for updates in these areas
3274 * @return array list of updates and warnings
3275 * @throws moodle_exception
3276 * @since Moodle 3.2
3278 public static function check_updates($courseid, $tocheck, $filter = array()) {
3279 global $CFG, $DB;
3280 require_once($CFG->dirroot . "/course/lib.php");
3282 $params = self::validate_parameters(
3283 self::check_updates_parameters(),
3284 array(
3285 'courseid' => $courseid,
3286 'tocheck' => $tocheck,
3287 'filter' => $filter,
3291 $course = get_course($params['courseid']);
3292 $context = context_course::instance($course->id);
3293 self::validate_context($context);
3295 list($instances, $warnings) = course_check_updates($course, $params['tocheck'], $filter);
3297 $instancesformatted = array();
3298 foreach ($instances as $instance) {
3299 $updates = array();
3300 foreach ($instance['updates'] as $name => $data) {
3301 if (empty($data->updated)) {
3302 continue;
3304 $updatedata = array(
3305 'name' => $name,
3307 if (!empty($data->timeupdated)) {
3308 $updatedata['timeupdated'] = $data->timeupdated;
3310 if (!empty($data->itemids)) {
3311 $updatedata['itemids'] = $data->itemids;
3313 $updates[] = $updatedata;
3315 if (!empty($updates)) {
3316 $instancesformatted[] = array(
3317 'contextlevel' => $instance['contextlevel'],
3318 'id' => $instance['id'],
3319 'updates' => $updates
3324 return array(
3325 'instances' => $instancesformatted,
3326 'warnings' => $warnings
3331 * Returns description of method result value
3333 * @return external_description
3334 * @since Moodle 3.2
3336 public static function check_updates_returns() {
3337 return new external_single_structure(
3338 array(
3339 'instances' => new external_multiple_structure(
3340 new external_single_structure(
3341 array(
3342 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level'),
3343 'id' => new external_value(PARAM_INT, 'Instance id'),
3344 'updates' => new external_multiple_structure(
3345 new external_single_structure(
3346 array(
3347 'name' => new external_value(PARAM_ALPHANUMEXT, 'Name of the area updated.'),
3348 'timeupdated' => new external_value(PARAM_INT, 'Last time was updated', VALUE_OPTIONAL),
3349 'itemids' => new external_multiple_structure(
3350 new external_value(PARAM_INT, 'Instance id'),
3351 'The ids of the items updated',
3352 VALUE_OPTIONAL
3360 'warnings' => new external_warnings()
3366 * Returns description of method parameters
3368 * @return external_function_parameters
3369 * @since Moodle 3.3
3371 public static function get_updates_since_parameters() {
3372 return new external_function_parameters(
3373 array(
3374 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3375 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3376 'filter' => new external_multiple_structure(
3377 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3378 gradeitems, outcomes'),
3379 'Check only for updates in these areas', VALUE_DEFAULT, array()
3386 * Check if there are updates affecting the user for the given course since the given time stamp.
3388 * This function is a wrapper of self::check_updates for retrieving all the updates since a given time for all the activities.
3390 * @param int $courseid the list of modules to check
3391 * @param int $since check updates since this time stamp
3392 * @param array $filter check only for updates in these areas
3393 * @return array list of updates and warnings
3394 * @throws moodle_exception
3395 * @since Moodle 3.3
3397 public static function get_updates_since($courseid, $since, $filter = array()) {
3398 global $CFG, $DB;
3400 $params = self::validate_parameters(
3401 self::get_updates_since_parameters(),
3402 array(
3403 'courseid' => $courseid,
3404 'since' => $since,
3405 'filter' => $filter,
3409 $course = get_course($params['courseid']);
3410 $modinfo = get_fast_modinfo($course);
3411 $tocheck = array();
3413 // Retrieve all the visible course modules for the current user.
3414 $cms = $modinfo->get_cms();
3415 foreach ($cms as $cm) {
3416 if (!$cm->uservisible) {
3417 continue;
3419 $tocheck[] = array(
3420 'id' => $cm->id,
3421 'contextlevel' => 'module',
3422 'since' => $params['since'],
3426 return self::check_updates($course->id, $tocheck, $params['filter']);
3430 * Returns description of method result value
3432 * @return external_description
3433 * @since Moodle 3.3
3435 public static function get_updates_since_returns() {
3436 return self::check_updates_returns();
3440 * Parameters for function edit_module()
3442 * @since Moodle 3.3
3443 * @return external_function_parameters
3445 public static function edit_module_parameters() {
3446 return new external_function_parameters(
3447 array(
3448 'action' => new external_value(PARAM_ALPHA,
3449 'action: hide, show, stealth, duplicate, delete, moveleft, moveright, group...', VALUE_REQUIRED),
3450 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3451 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3456 * Performs one of the edit module actions and return new html for AJAX
3458 * Returns html to replace the current module html with, for example:
3459 * - empty string for "delete" action,
3460 * - two modules html for "duplicate" action
3461 * - updated module html for everything else
3463 * Throws exception if operation is not permitted/possible
3465 * @since Moodle 3.3
3466 * @param string $action
3467 * @param int $id
3468 * @param null|int $sectionreturn
3469 * @return string
3471 public static function edit_module($action, $id, $sectionreturn = null) {
3472 global $PAGE, $DB;
3473 // Validate and normalize parameters.
3474 $params = self::validate_parameters(self::edit_module_parameters(),
3475 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3476 $action = $params['action'];
3477 $id = $params['id'];
3478 $sectionreturn = $params['sectionreturn'];
3480 // Set of permissions an editing user may have.
3481 $contextarray = [
3482 'moodle/course:update',
3483 'moodle/course:manageactivities',
3484 'moodle/course:activityvisibility',
3485 'moodle/course:sectionvisibility',
3486 'moodle/course:movesections',
3487 'moodle/course:setcurrentsection',
3489 $PAGE->set_other_editing_capability($contextarray);
3491 list($course, $cm) = get_course_and_cm_from_cmid($id);
3492 $modcontext = context_module::instance($cm->id);
3493 $coursecontext = context_course::instance($course->id);
3494 self::validate_context($modcontext);
3495 $courserenderer = $PAGE->get_renderer('core', 'course');
3496 $completioninfo = new completion_info($course);
3498 switch($action) {
3499 case 'hide':
3500 case 'show':
3501 case 'stealth':
3502 require_capability('moodle/course:activityvisibility', $modcontext);
3503 $visible = ($action === 'hide') ? 0 : 1;
3504 $visibleoncoursepage = ($action === 'stealth') ? 0 : 1;
3505 set_coursemodule_visible($id, $visible, $visibleoncoursepage);
3506 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3507 break;
3508 case 'duplicate':
3509 require_capability('moodle/course:manageactivities', $coursecontext);
3510 require_capability('moodle/backup:backuptargetimport', $coursecontext);
3511 require_capability('moodle/restore:restoretargetimport', $coursecontext);
3512 if (!course_allowed_module($course, $cm->modname)) {
3513 throw new moodle_exception('No permission to create that activity');
3515 if ($newcm = duplicate_module($course, $cm)) {
3516 $cm = get_fast_modinfo($course)->get_cm($id);
3517 $newcm = get_fast_modinfo($course)->get_cm($newcm->id);
3518 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn) .
3519 $courserenderer->course_section_cm_list_item($course, $completioninfo, $newcm, $sectionreturn);
3521 break;
3522 case 'groupsseparate':
3523 case 'groupsvisible':
3524 case 'groupsnone':
3525 require_capability('moodle/course:manageactivities', $modcontext);
3526 if ($action === 'groupsseparate') {
3527 $newgroupmode = SEPARATEGROUPS;
3528 } else if ($action === 'groupsvisible') {
3529 $newgroupmode = VISIBLEGROUPS;
3530 } else {
3531 $newgroupmode = NOGROUPS;
3533 if (set_coursemodule_groupmode($cm->id, $newgroupmode)) {
3534 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3536 break;
3537 case 'moveleft':
3538 case 'moveright':
3539 require_capability('moodle/course:manageactivities', $modcontext);
3540 $indent = $cm->indent + (($action === 'moveright') ? 1 : -1);
3541 if ($cm->indent >= 0) {
3542 $DB->update_record('course_modules', array('id' => $cm->id, 'indent' => $indent));
3543 rebuild_course_cache($cm->course);
3545 break;
3546 case 'delete':
3547 require_capability('moodle/course:manageactivities', $modcontext);
3548 course_delete_module($cm->id, true);
3549 return '';
3550 default:
3551 throw new coding_exception('Unrecognised action');
3554 $cm = get_fast_modinfo($course)->get_cm($id);
3555 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn);
3559 * Return structure for edit_module()
3561 * @since Moodle 3.3
3562 * @return external_description
3564 public static function edit_module_returns() {
3565 return new external_value(PARAM_RAW, 'html to replace the current module with');
3569 * Parameters for function get_module()
3571 * @since Moodle 3.3
3572 * @return external_function_parameters
3574 public static function get_module_parameters() {
3575 return new external_function_parameters(
3576 array(
3577 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3578 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3583 * Returns html for displaying one activity module on course page
3585 * @since Moodle 3.3
3586 * @param int $id
3587 * @param null|int $sectionreturn
3588 * @return string
3590 public static function get_module($id, $sectionreturn = null) {
3591 global $PAGE;
3592 // Validate and normalize parameters.
3593 $params = self::validate_parameters(self::get_module_parameters(),
3594 array('id' => $id, 'sectionreturn' => $sectionreturn));
3595 $id = $params['id'];
3596 $sectionreturn = $params['sectionreturn'];
3598 // Set of permissions an editing user may have.
3599 $contextarray = [
3600 'moodle/course:update',
3601 'moodle/course:manageactivities',
3602 'moodle/course:activityvisibility',
3603 'moodle/course:sectionvisibility',
3604 'moodle/course:movesections',
3605 'moodle/course:setcurrentsection',
3607 $PAGE->set_other_editing_capability($contextarray);
3609 // Validate access to the course (note, this is html for the course view page, we don't validate access to the module).
3610 list($course, $cm) = get_course_and_cm_from_cmid($id);
3611 self::validate_context(context_course::instance($course->id));
3613 $courserenderer = $PAGE->get_renderer('core', 'course');
3614 $completioninfo = new completion_info($course);
3615 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn);
3619 * Return structure for edit_module()
3621 * @since Moodle 3.3
3622 * @return external_description
3624 public static function get_module_returns() {
3625 return new external_value(PARAM_RAW, 'html to replace the current module with');
3629 * Parameters for function edit_section()
3631 * @since Moodle 3.3
3632 * @return external_function_parameters
3634 public static function edit_section_parameters() {
3635 return new external_function_parameters(
3636 array(
3637 'action' => new external_value(PARAM_ALPHA, 'action: hide, show, stealth, setmarker, removemarker', VALUE_REQUIRED),
3638 'id' => new external_value(PARAM_INT, 'course section id', VALUE_REQUIRED),
3639 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3644 * Performs one of the edit section actions
3646 * @since Moodle 3.3
3647 * @param string $action
3648 * @param int $id section id
3649 * @param int $sectionreturn section to return to
3650 * @return string
3652 public static function edit_section($action, $id, $sectionreturn) {
3653 global $DB;
3654 // Validate and normalize parameters.
3655 $params = self::validate_parameters(self::edit_section_parameters(),
3656 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3657 $action = $params['action'];
3658 $id = $params['id'];
3659 $sr = $params['sectionreturn'];
3661 $section = $DB->get_record('course_sections', array('id' => $id), '*', MUST_EXIST);
3662 $coursecontext = context_course::instance($section->course);
3663 self::validate_context($coursecontext);
3665 $rv = course_get_format($section->course)->section_action($section, $action, $sectionreturn);
3666 if ($rv) {
3667 return json_encode($rv);
3668 } else {
3669 return null;
3674 * Return structure for edit_section()
3676 * @since Moodle 3.3
3677 * @return external_description
3679 public static function edit_section_returns() {
3680 return new external_value(PARAM_RAW, 'Additional data for javascript (JSON-encoded string)');
3684 * Returns description of method parameters
3686 * @return external_function_parameters
3688 public static function get_enrolled_courses_by_timeline_classification_parameters() {
3689 return new external_function_parameters(
3690 array(
3691 'classification' => new external_value(PARAM_ALPHA, 'future, inprogress, or past'),
3692 'limit' => new external_value(PARAM_INT, 'Result set limit', VALUE_DEFAULT, 0),
3693 'offset' => new external_value(PARAM_INT, 'Result set offset', VALUE_DEFAULT, 0),
3694 'sort' => new external_value(PARAM_TEXT, 'Sort string', VALUE_DEFAULT, null)
3700 * Get courses matching the given timeline classification.
3702 * NOTE: The offset applies to the unfiltered full set of courses before the classification
3703 * filtering is done.
3704 * E.g.
3705 * If the user is enrolled in 5 courses:
3706 * c1, c2, c3, c4, and c5
3707 * And c4 and c5 are 'future' courses
3709 * If a request comes in for future courses with an offset of 1 it will mean that
3710 * c1 is skipped (because the offset applies *before* the classification filtering)
3711 * and c4 and c5 will be return.
3713 * @param string $classification past, inprogress, or future
3714 * @param int $limit Result set limit
3715 * @param int $offset Offset the full course set before timeline classification is applied
3716 * @param string $sort SQL sort string for results
3717 * @return array list of courses and warnings
3718 * @throws invalid_parameter_exception
3720 public static function get_enrolled_courses_by_timeline_classification(
3721 string $classification,
3722 int $limit = 0,
3723 int $offset = 0,
3724 string $sort = null
3726 global $CFG, $PAGE, $USER;
3727 require_once($CFG->dirroot . '/course/lib.php');
3729 $params = self::validate_parameters(self::get_enrolled_courses_by_timeline_classification_parameters(),
3730 array(
3731 'classification' => $classification,
3732 'limit' => $limit,
3733 'offset' => $offset,
3734 'sort' => $sort,
3738 $classification = $params['classification'];
3739 $limit = $params['limit'];
3740 $offset = $params['offset'];
3741 $sort = $params['sort'];
3743 switch($classification) {
3744 case COURSE_TIMELINE_ALL:
3745 break;
3746 case COURSE_TIMELINE_PAST:
3747 break;
3748 case COURSE_TIMELINE_INPROGRESS:
3749 break;
3750 case COURSE_TIMELINE_FUTURE:
3751 break;
3752 case COURSE_FAVOURITES:
3753 break;
3754 case COURSE_TIMELINE_HIDDEN:
3755 break;
3756 default:
3757 throw new invalid_parameter_exception('Invalid classification');
3760 self::validate_context(context_user::instance($USER->id));
3762 $requiredproperties = course_summary_exporter::define_properties();
3763 $fields = join(',', array_keys($requiredproperties));
3764 $hiddencourses = get_hidden_courses_on_timeline();
3765 $courses = [];
3767 // If the timeline requires the hidden courses then restrict the result to only $hiddencourses else exclude.
3768 if ($classification == COURSE_TIMELINE_HIDDEN) {
3769 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields,
3770 COURSE_DB_QUERY_LIMIT, $hiddencourses);
3771 } else {
3772 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields,
3773 COURSE_DB_QUERY_LIMIT, [], $hiddencourses);
3776 $favouritecourseids = [];
3777 $ufservice = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($USER->id));
3778 $favourites = $ufservice->find_favourites_by_type('core_course', 'courses');
3780 if ($favourites) {
3781 $favouritecourseids = array_map(
3782 function($favourite) {
3783 return $favourite->itemid;
3784 }, $favourites);
3787 if ($classification == COURSE_FAVOURITES) {
3788 list($filteredcourses, $processedcount) = course_filter_courses_by_favourites(
3789 $courses,
3790 $favouritecourseids,
3791 $limit
3793 } else {
3794 list($filteredcourses, $processedcount) = course_filter_courses_by_timeline_classification(
3795 $courses,
3796 $classification,
3797 $limit
3801 $renderer = $PAGE->get_renderer('core');
3802 $formattedcourses = array_map(function($course) use ($renderer, $favouritecourseids) {
3803 context_helper::preload_from_record($course);
3804 $context = context_course::instance($course->id);
3805 $isfavourite = false;
3806 if (in_array($course->id, $favouritecourseids)) {
3807 $isfavourite = true;
3809 $exporter = new course_summary_exporter($course, ['context' => $context, 'isfavourite' => $isfavourite]);
3810 return $exporter->export($renderer);
3811 }, $filteredcourses);
3813 return [
3814 'courses' => $formattedcourses,
3815 'nextoffset' => $offset + $processedcount
3820 * Returns description of method result value
3822 * @return external_description
3824 public static function get_enrolled_courses_by_timeline_classification_returns() {
3825 return new external_single_structure(
3826 array(
3827 'courses' => new external_multiple_structure(course_summary_exporter::get_read_structure(), 'Course'),
3828 'nextoffset' => new external_value(PARAM_INT, 'Offset for the next request')
3834 * Returns description of method parameters
3836 * @return external_function_parameters
3838 public static function set_favourite_courses_parameters() {
3839 return new external_function_parameters(
3840 array(
3841 'courses' => new external_multiple_structure(
3842 new external_single_structure(
3843 array(
3844 'id' => new external_value(PARAM_INT, 'course ID'),
3845 'favourite' => new external_value(PARAM_BOOL, 'favourite status')
3854 * Set the course favourite status for an array of courses.
3856 * @param array $courses List with course id's and favourite status.
3857 * @return array Array with an array of favourite courses.
3859 public static function set_favourite_courses(
3860 array $courses
3862 global $USER;
3864 $params = self::validate_parameters(self::set_favourite_courses_parameters(),
3865 array(
3866 'courses' => $courses
3870 $warnings = [];
3872 $ufservice = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($USER->id));
3874 foreach ($params['courses'] as $course) {
3876 $warning = [];
3878 $favouriteexists = $ufservice->favourite_exists('core_course', 'courses', $course['id'],
3879 \context_course::instance($course['id']));
3881 if ($course['favourite']) {
3882 if (!$favouriteexists) {
3883 try {
3884 $ufservice->create_favourite('core_course', 'courses', $course['id'],
3885 \context_course::instance($course['id']));
3886 } catch (Exception $e) {
3887 $warning['courseid'] = $course['id'];
3888 if ($e instanceof moodle_exception) {
3889 $warning['warningcode'] = $e->errorcode;
3890 } else {
3891 $warning['warningcode'] = $e->getCode();
3893 $warning['message'] = $e->getMessage();
3894 $warnings[] = $warning;
3895 $warnings[] = $warning;
3897 } else {
3898 $warning['courseid'] = $course['id'];
3899 $warning['warningcode'] = 'coursealreadyfavourited';
3900 $warning['message'] = 'Course already favourited';
3901 $warnings[] = $warning;
3903 } else {
3904 if ($favouriteexists) {
3905 try {
3906 $ufservice->delete_favourite('core_course', 'courses', $course['id'],
3907 \context_course::instance($course['id']));
3908 } catch (Exception $e) {
3909 $warning['courseid'] = $course['id'];
3910 if ($e instanceof moodle_exception) {
3911 $warning['warningcode'] = $e->errorcode;
3912 } else {
3913 $warning['warningcode'] = $e->getCode();
3915 $warning['message'] = $e->getMessage();
3916 $warnings[] = $warning;
3917 $warnings[] = $warning;
3919 } else {
3920 $warning['courseid'] = $course['id'];
3921 $warning['warningcode'] = 'cannotdeletefavourite';
3922 $warning['message'] = 'Could not delete favourite status for course';
3923 $warnings[] = $warning;
3928 return [
3929 'warnings' => $warnings
3934 * Returns description of method result value
3936 * @return external_description
3938 public static function set_favourite_courses_returns() {
3939 return new external_single_structure(
3940 array(
3941 'warnings' => new external_warnings()
3947 * Returns description of method parameters
3949 * @return external_function_parameters
3950 * @since Moodle 3.6
3952 public static function get_recent_courses_parameters() {
3953 return new external_function_parameters(
3954 array(
3955 'userid' => new external_value(PARAM_INT, 'id of the user, default to current user', VALUE_DEFAULT, 0),
3956 'limit' => new external_value(PARAM_INT, 'result set limit', VALUE_DEFAULT, 0),
3957 'offset' => new external_value(PARAM_INT, 'Result set offset', VALUE_DEFAULT, 0),
3958 'sort' => new external_value(PARAM_TEXT, 'Sort string', VALUE_DEFAULT, null)
3964 * Get last accessed courses adding additional course information like images.
3966 * @param int $userid User id from which the courses will be obtained
3967 * @param int $limit Restrict result set to this amount
3968 * @param int $offset Skip this number of records from the start of the result set
3969 * @param string|null $sort SQL string for sorting
3970 * @return array List of courses
3971 * @throws invalid_parameter_exception
3973 public static function get_recent_courses(int $userid = 0, int $limit = 0, int $offset = 0, string $sort = null) {
3974 global $USER, $PAGE;
3976 if (empty($userid)) {
3977 $userid = $USER->id;
3980 $params = self::validate_parameters(self::get_recent_courses_parameters(),
3981 array(
3982 'userid' => $userid,
3983 'limit' => $limit,
3984 'offset' => $offset,
3985 'sort' => $sort
3989 $userid = $params['userid'];
3990 $limit = $params['limit'];
3991 $offset = $params['offset'];
3992 $sort = $params['sort'];
3994 $usercontext = context_user::instance($userid);
3996 self::validate_context($usercontext);
3998 if ($userid != $USER->id and !has_capability('moodle/user:viewdetails', $usercontext)) {
3999 return array();
4002 $courses = course_get_recent_courses($userid, $limit, $offset, $sort);
4004 $renderer = $PAGE->get_renderer('core');
4006 $recentcourses = array_map(function($course) use ($renderer) {
4007 context_helper::preload_from_record($course);
4008 $context = context_course::instance($course->id);
4009 $isfavourite = !empty($course->component);
4010 $exporter = new course_summary_exporter($course, ['context' => $context, 'isfavourite' => $isfavourite]);
4011 return $exporter->export($renderer);
4012 }, $courses);
4014 return $recentcourses;
4018 * Returns description of method result value
4020 * @return external_description
4021 * @since Moodle 3.6
4023 public static function get_recent_courses_returns() {
4024 return new external_multiple_structure(course_summary_exporter::get_read_structure(), 'Courses');