MDL-62660 tool_dataprivacy: Add scheduled task to expire data requests
[moodle.git] / course / externallib.php
blob455a52815e4e1335445391d94a7c0dd3fb7fd3cb
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 require_once("$CFG->libdir/externallib.php");
31 /**
32 * Course external functions
34 * @package core_course
35 * @category external
36 * @copyright 2011 Jerome Mouneyrac
37 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 * @since Moodle 2.2
40 class core_course_external extends external_api {
42 /**
43 * Returns description of method parameters
45 * @return external_function_parameters
46 * @since Moodle 2.9 Options available
47 * @since Moodle 2.2
49 public static function get_course_contents_parameters() {
50 return new external_function_parameters(
51 array('courseid' => new external_value(PARAM_INT, 'course id'),
52 'options' => new external_multiple_structure (
53 new external_single_structure(
54 array(
55 'name' => new external_value(PARAM_ALPHANUM,
56 'The expected keys (value format) are:
57 excludemodules (bool) Do not return modules, return only the sections structure
58 excludecontents (bool) Do not return module contents (i.e: files inside a resource)
59 sectionid (int) Return only this section
60 sectionnumber (int) Return only this section with number (order)
61 cmid (int) Return only this module information (among the whole sections structure)
62 modname (string) Return only modules with this name "label, forum, etc..."
63 modid (int) Return only the module with this id (to be used with modname'),
64 'value' => new external_value(PARAM_RAW, 'the value of the option,
65 this param is personaly validated in the external function.')
67 ), 'Options, used since Moodle 2.9', VALUE_DEFAULT, array())
72 /**
73 * Get course contents
75 * @param int $courseid course id
76 * @param array $options Options for filtering the results, used since Moodle 2.9
77 * @return array
78 * @since Moodle 2.9 Options available
79 * @since Moodle 2.2
81 public static function get_course_contents($courseid, $options = array()) {
82 global $CFG, $DB;
83 require_once($CFG->dirroot . "/course/lib.php");
85 //validate parameter
86 $params = self::validate_parameters(self::get_course_contents_parameters(),
87 array('courseid' => $courseid, 'options' => $options));
89 $filters = array();
90 if (!empty($params['options'])) {
92 foreach ($params['options'] as $option) {
93 $name = trim($option['name']);
94 // Avoid duplicated options.
95 if (!isset($filters[$name])) {
96 switch ($name) {
97 case 'excludemodules':
98 case 'excludecontents':
99 $value = clean_param($option['value'], PARAM_BOOL);
100 $filters[$name] = $value;
101 break;
102 case 'sectionid':
103 case 'sectionnumber':
104 case 'cmid':
105 case 'modid':
106 $value = clean_param($option['value'], PARAM_INT);
107 if (is_numeric($value)) {
108 $filters[$name] = $value;
109 } else {
110 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
112 break;
113 case 'modname':
114 $value = clean_param($option['value'], PARAM_PLUGIN);
115 if ($value) {
116 $filters[$name] = $value;
117 } else {
118 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
120 break;
121 default:
122 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
128 //retrieve the course
129 $course = $DB->get_record('course', array('id' => $params['courseid']), '*', MUST_EXIST);
131 if ($course->id != SITEID) {
132 // Check course format exist.
133 if (!file_exists($CFG->dirroot . '/course/format/' . $course->format . '/lib.php')) {
134 throw new moodle_exception('cannotgetcoursecontents', 'webservice', '', null,
135 get_string('courseformatnotfound', 'error', $course->format));
136 } else {
137 require_once($CFG->dirroot . '/course/format/' . $course->format . '/lib.php');
141 // now security checks
142 $context = context_course::instance($course->id, IGNORE_MISSING);
143 try {
144 self::validate_context($context);
145 } catch (Exception $e) {
146 $exceptionparam = new stdClass();
147 $exceptionparam->message = $e->getMessage();
148 $exceptionparam->courseid = $course->id;
149 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
152 $canupdatecourse = has_capability('moodle/course:update', $context);
154 //create return value
155 $coursecontents = array();
157 if ($canupdatecourse or $course->visible
158 or has_capability('moodle/course:viewhiddencourses', $context)) {
160 //retrieve sections
161 $modinfo = get_fast_modinfo($course);
162 $sections = $modinfo->get_section_info_all();
163 $coursenumsections = course_get_format($course)->get_last_section_number();
165 //for each sections (first displayed to last displayed)
166 $modinfosections = $modinfo->get_sections();
167 foreach ($sections as $key => $section) {
169 // Show the section if the user is permitted to access it, OR if it's not available
170 // but there is some available info text which explains the reason & should display.
171 $showsection = $section->uservisible ||
172 ($section->visible && !$section->available &&
173 !empty($section->availableinfo));
175 if (!$showsection) {
176 continue;
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 (if it is visible).
220 if ($section->uservisible and 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;
269 if (!empty($cm->showdescription) or $cm->modname == 'label') {
270 // We want to use the external format. However from reading get_formatted_content(), $cm->content format is always FORMAT_HTML.
271 $options = array('noclean' => true);
272 list($module['description'], $descriptionformat) = external_format_text($cm->content,
273 FORMAT_HTML, $modcontext->id, $cm->modname, 'intro', $cm->id, $options);
276 //url of the module
277 $url = $cm->url;
278 if ($url) { //labels don't have url
279 $module['url'] = $url->out(false);
282 $canviewhidden = has_capability('moodle/course:viewhiddenactivities',
283 context_module::instance($cm->id));
284 //user that can view hidden module should know about the visibility
285 $module['visible'] = $cm->visible;
286 $module['visibleoncoursepage'] = $cm->visibleoncoursepage;
287 $module['uservisible'] = $cm->uservisible;
288 if (!empty($cm->availableinfo)) {
289 $module['availabilityinfo'] = \core_availability\info::format_info($cm->availableinfo, $course);
292 // Availability date (also send to user who can see hidden module).
293 if ($CFG->enableavailability && ($canviewhidden || $canupdatecourse)) {
294 $module['availability'] = $cm->availability;
297 // Return contents only if the user can access to the module.
298 if ($cm->uservisible) {
299 $baseurl = 'webservice/pluginfile.php';
301 // Call $modulename_export_contents (each module callback take care about checking the capabilities).
302 require_once($CFG->dirroot . '/mod/' . $cm->modname . '/lib.php');
303 $getcontentfunction = $cm->modname.'_export_contents';
304 if (function_exists($getcontentfunction)) {
305 if (empty($filters['excludecontents']) and $contents = $getcontentfunction($cm, $baseurl)) {
306 $module['contents'] = $contents;
307 } else {
308 $module['contents'] = array();
313 //assign result to $sectioncontents
314 $sectioncontents[] = $module;
316 // If we just did a filtering, break the loop.
317 if ($modfound) {
318 break;
323 $sectionvalues['modules'] = $sectioncontents;
325 // assign result to $coursecontents
326 $coursecontents[] = $sectionvalues;
328 // Break the loop if we are filtering.
329 if ($sectionfound) {
330 break;
334 return $coursecontents;
338 * Returns description of method result value
340 * @return external_description
341 * @since Moodle 2.2
343 public static function get_course_contents_returns() {
344 return new external_multiple_structure(
345 new external_single_structure(
346 array(
347 'id' => new external_value(PARAM_INT, 'Section ID'),
348 'name' => new external_value(PARAM_TEXT, 'Section name'),
349 'visible' => new external_value(PARAM_INT, 'is the section visible', VALUE_OPTIONAL),
350 'summary' => new external_value(PARAM_RAW, 'Section description'),
351 'summaryformat' => new external_format_value('summary'),
352 'section' => new external_value(PARAM_INT, 'Section number inside the course', VALUE_OPTIONAL),
353 'hiddenbynumsections' => new external_value(PARAM_INT, 'Whether is a section hidden in the course format',
354 VALUE_OPTIONAL),
355 'uservisible' => new external_value(PARAM_BOOL, 'Is the section visible for the user?', VALUE_OPTIONAL),
356 'availabilityinfo' => new external_value(PARAM_RAW, 'Availability information.', VALUE_OPTIONAL),
357 'modules' => new external_multiple_structure(
358 new external_single_structure(
359 array(
360 'id' => new external_value(PARAM_INT, 'activity id'),
361 'url' => new external_value(PARAM_URL, 'activity url', VALUE_OPTIONAL),
362 'name' => new external_value(PARAM_RAW, 'activity module name'),
363 'instance' => new external_value(PARAM_INT, 'instance id', VALUE_OPTIONAL),
364 'description' => new external_value(PARAM_RAW, 'activity description', VALUE_OPTIONAL),
365 'visible' => new external_value(PARAM_INT, 'is the module visible', VALUE_OPTIONAL),
366 'uservisible' => new external_value(PARAM_BOOL, 'Is the module visible for the user?',
367 VALUE_OPTIONAL),
368 'availabilityinfo' => new external_value(PARAM_RAW, 'Availability information.',
369 VALUE_OPTIONAL),
370 'visibleoncoursepage' => new external_value(PARAM_INT, 'is the module visible on course page',
371 VALUE_OPTIONAL),
372 'modicon' => new external_value(PARAM_URL, 'activity icon url'),
373 'modname' => new external_value(PARAM_PLUGIN, 'activity module type'),
374 'modplural' => new external_value(PARAM_TEXT, 'activity module plural name'),
375 'availability' => new external_value(PARAM_RAW, 'module availability settings', VALUE_OPTIONAL),
376 'indent' => new external_value(PARAM_INT, 'number of identation in the site'),
377 'contents' => new external_multiple_structure(
378 new external_single_structure(
379 array(
380 // content info
381 'type'=> new external_value(PARAM_TEXT, 'a file or a folder or external link'),
382 'filename'=> new external_value(PARAM_FILE, 'filename'),
383 'filepath'=> new external_value(PARAM_PATH, 'filepath'),
384 'filesize'=> new external_value(PARAM_INT, 'filesize'),
385 'fileurl' => new external_value(PARAM_URL, 'downloadable file url', VALUE_OPTIONAL),
386 'content' => new external_value(PARAM_RAW, 'Raw content, will be used when type is content', VALUE_OPTIONAL),
387 'timecreated' => new external_value(PARAM_INT, 'Time created'),
388 'timemodified' => new external_value(PARAM_INT, 'Time modified'),
389 'sortorder' => new external_value(PARAM_INT, 'Content sort order'),
390 'mimetype' => new external_value(PARAM_RAW, 'File mime type.', VALUE_OPTIONAL),
391 'isexternalfile' => new external_value(PARAM_BOOL, 'Whether is an external file.',
392 VALUE_OPTIONAL),
393 'repositorytype' => new external_value(PARAM_PLUGIN, 'The repository type for external files.',
394 VALUE_OPTIONAL),
396 // copyright related info
397 'userid' => new external_value(PARAM_INT, 'User who added this content to moodle'),
398 'author' => new external_value(PARAM_TEXT, 'Content owner'),
399 'license' => new external_value(PARAM_TEXT, 'Content license'),
401 ), VALUE_DEFAULT, array()
404 ), 'list of module'
412 * Returns description of method parameters
414 * @return external_function_parameters
415 * @since Moodle 2.3
417 public static function get_courses_parameters() {
418 return new external_function_parameters(
419 array('options' => new external_single_structure(
420 array('ids' => new external_multiple_structure(
421 new external_value(PARAM_INT, 'Course id')
422 , 'List of course id. If empty return all courses
423 except front page course.',
424 VALUE_OPTIONAL)
425 ), 'options - operator OR is used', VALUE_DEFAULT, array())
431 * Get courses
433 * @param array $options It contains an array (list of ids)
434 * @return array
435 * @since Moodle 2.2
437 public static function get_courses($options = array()) {
438 global $CFG, $DB;
439 require_once($CFG->dirroot . "/course/lib.php");
441 //validate parameter
442 $params = self::validate_parameters(self::get_courses_parameters(),
443 array('options' => $options));
445 //retrieve courses
446 if (!array_key_exists('ids', $params['options'])
447 or empty($params['options']['ids'])) {
448 $courses = $DB->get_records('course');
449 } else {
450 $courses = $DB->get_records_list('course', 'id', $params['options']['ids']);
453 //create return value
454 $coursesinfo = array();
455 foreach ($courses as $course) {
457 // now security checks
458 $context = context_course::instance($course->id, IGNORE_MISSING);
459 $courseformatoptions = course_get_format($course)->get_format_options();
460 try {
461 self::validate_context($context);
462 } catch (Exception $e) {
463 $exceptionparam = new stdClass();
464 $exceptionparam->message = $e->getMessage();
465 $exceptionparam->courseid = $course->id;
466 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
468 if ($course->id != SITEID) {
469 require_capability('moodle/course:view', $context);
472 $courseinfo = array();
473 $courseinfo['id'] = $course->id;
474 $courseinfo['fullname'] = external_format_string($course->fullname, $context->id);
475 $courseinfo['shortname'] = external_format_string($course->shortname, $context->id);
476 $courseinfo['displayname'] = external_format_string(get_course_display_name_for_list($course), $context->id);
477 $courseinfo['categoryid'] = $course->category;
478 list($courseinfo['summary'], $courseinfo['summaryformat']) =
479 external_format_text($course->summary, $course->summaryformat, $context->id, 'course', 'summary', 0);
480 $courseinfo['format'] = $course->format;
481 $courseinfo['startdate'] = $course->startdate;
482 $courseinfo['enddate'] = $course->enddate;
483 if (array_key_exists('numsections', $courseformatoptions)) {
484 // For backward-compartibility
485 $courseinfo['numsections'] = $courseformatoptions['numsections'];
488 //some field should be returned only if the user has update permission
489 $courseadmin = has_capability('moodle/course:update', $context);
490 if ($courseadmin) {
491 $courseinfo['categorysortorder'] = $course->sortorder;
492 $courseinfo['idnumber'] = $course->idnumber;
493 $courseinfo['showgrades'] = $course->showgrades;
494 $courseinfo['showreports'] = $course->showreports;
495 $courseinfo['newsitems'] = $course->newsitems;
496 $courseinfo['visible'] = $course->visible;
497 $courseinfo['maxbytes'] = $course->maxbytes;
498 if (array_key_exists('hiddensections', $courseformatoptions)) {
499 // For backward-compartibility
500 $courseinfo['hiddensections'] = $courseformatoptions['hiddensections'];
502 // Return numsections for backward-compatibility with clients who expect it.
503 $courseinfo['numsections'] = course_get_format($course)->get_last_section_number();
504 $courseinfo['groupmode'] = $course->groupmode;
505 $courseinfo['groupmodeforce'] = $course->groupmodeforce;
506 $courseinfo['defaultgroupingid'] = $course->defaultgroupingid;
507 $courseinfo['lang'] = clean_param($course->lang, PARAM_LANG);
508 $courseinfo['timecreated'] = $course->timecreated;
509 $courseinfo['timemodified'] = $course->timemodified;
510 $courseinfo['forcetheme'] = clean_param($course->theme, PARAM_THEME);
511 $courseinfo['enablecompletion'] = $course->enablecompletion;
512 $courseinfo['completionnotify'] = $course->completionnotify;
513 $courseinfo['courseformatoptions'] = array();
514 foreach ($courseformatoptions as $key => $value) {
515 $courseinfo['courseformatoptions'][] = array(
516 'name' => $key,
517 'value' => $value
522 if ($courseadmin or $course->visible
523 or has_capability('moodle/course:viewhiddencourses', $context)) {
524 $coursesinfo[] = $courseinfo;
528 return $coursesinfo;
532 * Returns description of method result value
534 * @return external_description
535 * @since Moodle 2.2
537 public static function get_courses_returns() {
538 return new external_multiple_structure(
539 new external_single_structure(
540 array(
541 'id' => new external_value(PARAM_INT, 'course id'),
542 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
543 'categoryid' => new external_value(PARAM_INT, 'category id'),
544 'categorysortorder' => new external_value(PARAM_INT,
545 'sort order into the category', VALUE_OPTIONAL),
546 'fullname' => new external_value(PARAM_TEXT, 'full name'),
547 'displayname' => new external_value(PARAM_TEXT, 'course display name'),
548 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
549 'summary' => new external_value(PARAM_RAW, 'summary'),
550 'summaryformat' => new external_format_value('summary'),
551 'format' => new external_value(PARAM_PLUGIN,
552 'course format: weeks, topics, social, site,..'),
553 'showgrades' => new external_value(PARAM_INT,
554 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
555 'newsitems' => new external_value(PARAM_INT,
556 'number of recent items appearing on the course page', VALUE_OPTIONAL),
557 'startdate' => new external_value(PARAM_INT,
558 'timestamp when the course start'),
559 'enddate' => new external_value(PARAM_INT,
560 'timestamp when the course end'),
561 'numsections' => new external_value(PARAM_INT,
562 '(deprecated, use courseformatoptions) number of weeks/topics',
563 VALUE_OPTIONAL),
564 'maxbytes' => new external_value(PARAM_INT,
565 'largest size of file that can be uploaded into the course',
566 VALUE_OPTIONAL),
567 'showreports' => new external_value(PARAM_INT,
568 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
569 'visible' => new external_value(PARAM_INT,
570 '1: available to student, 0:not available', VALUE_OPTIONAL),
571 'hiddensections' => new external_value(PARAM_INT,
572 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
573 VALUE_OPTIONAL),
574 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
575 VALUE_OPTIONAL),
576 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
577 VALUE_OPTIONAL),
578 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
579 VALUE_OPTIONAL),
580 'timecreated' => new external_value(PARAM_INT,
581 'timestamp when the course have been created', VALUE_OPTIONAL),
582 'timemodified' => new external_value(PARAM_INT,
583 'timestamp when the course have been modified', VALUE_OPTIONAL),
584 'enablecompletion' => new external_value(PARAM_INT,
585 'Enabled, control via completion and activity settings. Disbaled,
586 not shown in activity settings.',
587 VALUE_OPTIONAL),
588 'completionnotify' => new external_value(PARAM_INT,
589 '1: yes 0: no', VALUE_OPTIONAL),
590 'lang' => new external_value(PARAM_SAFEDIR,
591 'forced course language', VALUE_OPTIONAL),
592 'forcetheme' => new external_value(PARAM_PLUGIN,
593 'name of the force theme', VALUE_OPTIONAL),
594 'courseformatoptions' => new external_multiple_structure(
595 new external_single_structure(
596 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
597 'value' => new external_value(PARAM_RAW, 'course format option value')
599 'additional options for particular course format', VALUE_OPTIONAL
601 ), 'course'
607 * Returns description of method parameters
609 * @return external_function_parameters
610 * @since Moodle 2.2
612 public static function create_courses_parameters() {
613 $courseconfig = get_config('moodlecourse'); //needed for many default values
614 return new external_function_parameters(
615 array(
616 'courses' => new external_multiple_structure(
617 new external_single_structure(
618 array(
619 'fullname' => new external_value(PARAM_TEXT, 'full name'),
620 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
621 'categoryid' => new external_value(PARAM_INT, 'category id'),
622 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
623 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
624 'summaryformat' => new external_format_value('summary', VALUE_DEFAULT),
625 'format' => new external_value(PARAM_PLUGIN,
626 'course format: weeks, topics, social, site,..',
627 VALUE_DEFAULT, $courseconfig->format),
628 'showgrades' => new external_value(PARAM_INT,
629 '1 if grades are shown, otherwise 0', VALUE_DEFAULT,
630 $courseconfig->showgrades),
631 'newsitems' => new external_value(PARAM_INT,
632 'number of recent items appearing on the course page',
633 VALUE_DEFAULT, $courseconfig->newsitems),
634 'startdate' => new external_value(PARAM_INT,
635 'timestamp when the course start', VALUE_OPTIONAL),
636 'enddate' => new external_value(PARAM_INT,
637 'timestamp when the course end', VALUE_OPTIONAL),
638 'numsections' => new external_value(PARAM_INT,
639 '(deprecated, use courseformatoptions) number of weeks/topics',
640 VALUE_OPTIONAL),
641 'maxbytes' => new external_value(PARAM_INT,
642 'largest size of file that can be uploaded into the course',
643 VALUE_DEFAULT, $courseconfig->maxbytes),
644 'showreports' => new external_value(PARAM_INT,
645 'are activity report shown (yes = 1, no =0)', VALUE_DEFAULT,
646 $courseconfig->showreports),
647 'visible' => new external_value(PARAM_INT,
648 '1: available to student, 0:not available', VALUE_OPTIONAL),
649 'hiddensections' => new external_value(PARAM_INT,
650 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
651 VALUE_OPTIONAL),
652 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
653 VALUE_DEFAULT, $courseconfig->groupmode),
654 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
655 VALUE_DEFAULT, $courseconfig->groupmodeforce),
656 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
657 VALUE_DEFAULT, 0),
658 'enablecompletion' => new external_value(PARAM_INT,
659 'Enabled, control via completion and activity settings. Disabled,
660 not shown in activity settings.',
661 VALUE_OPTIONAL),
662 'completionnotify' => new external_value(PARAM_INT,
663 '1: yes 0: no', VALUE_OPTIONAL),
664 'lang' => new external_value(PARAM_SAFEDIR,
665 'forced course language', VALUE_OPTIONAL),
666 'forcetheme' => new external_value(PARAM_PLUGIN,
667 'name of the force theme', VALUE_OPTIONAL),
668 'courseformatoptions' => new external_multiple_structure(
669 new external_single_structure(
670 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
671 'value' => new external_value(PARAM_RAW, 'course format option value')
673 'additional options for particular course format', VALUE_OPTIONAL),
675 ), 'courses to create'
682 * Create courses
684 * @param array $courses
685 * @return array courses (id and shortname only)
686 * @since Moodle 2.2
688 public static function create_courses($courses) {
689 global $CFG, $DB;
690 require_once($CFG->dirroot . "/course/lib.php");
691 require_once($CFG->libdir . '/completionlib.php');
693 $params = self::validate_parameters(self::create_courses_parameters(),
694 array('courses' => $courses));
696 $availablethemes = core_component::get_plugin_list('theme');
697 $availablelangs = get_string_manager()->get_list_of_translations();
699 $transaction = $DB->start_delegated_transaction();
701 foreach ($params['courses'] as $course) {
703 // Ensure the current user is allowed to run this function
704 $context = context_coursecat::instance($course['categoryid'], IGNORE_MISSING);
705 try {
706 self::validate_context($context);
707 } catch (Exception $e) {
708 $exceptionparam = new stdClass();
709 $exceptionparam->message = $e->getMessage();
710 $exceptionparam->catid = $course['categoryid'];
711 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
713 require_capability('moodle/course:create', $context);
715 // Make sure lang is valid
716 if (array_key_exists('lang', $course)) {
717 if (empty($availablelangs[$course['lang']])) {
718 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
720 if (!has_capability('moodle/course:setforcedlanguage', $context)) {
721 unset($course['lang']);
725 // Make sure theme is valid
726 if (array_key_exists('forcetheme', $course)) {
727 if (!empty($CFG->allowcoursethemes)) {
728 if (empty($availablethemes[$course['forcetheme']])) {
729 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
730 } else {
731 $course['theme'] = $course['forcetheme'];
736 //force visibility if ws user doesn't have the permission to set it
737 $category = $DB->get_record('course_categories', array('id' => $course['categoryid']));
738 if (!has_capability('moodle/course:visibility', $context)) {
739 $course['visible'] = $category->visible;
742 //set default value for completion
743 $courseconfig = get_config('moodlecourse');
744 if (completion_info::is_enabled_for_site()) {
745 if (!array_key_exists('enablecompletion', $course)) {
746 $course['enablecompletion'] = $courseconfig->enablecompletion;
748 } else {
749 $course['enablecompletion'] = 0;
752 $course['category'] = $course['categoryid'];
754 // Summary format.
755 $course['summaryformat'] = external_validate_format($course['summaryformat']);
757 if (!empty($course['courseformatoptions'])) {
758 foreach ($course['courseformatoptions'] as $option) {
759 $course[$option['name']] = $option['value'];
763 //Note: create_course() core function check shortname, idnumber, category
764 $course['id'] = create_course((object) $course)->id;
766 $resultcourses[] = array('id' => $course['id'], 'shortname' => $course['shortname']);
769 $transaction->allow_commit();
771 return $resultcourses;
775 * Returns description of method result value
777 * @return external_description
778 * @since Moodle 2.2
780 public static function create_courses_returns() {
781 return new external_multiple_structure(
782 new external_single_structure(
783 array(
784 'id' => new external_value(PARAM_INT, 'course id'),
785 'shortname' => new external_value(PARAM_TEXT, 'short name'),
792 * Update courses
794 * @return external_function_parameters
795 * @since Moodle 2.5
797 public static function update_courses_parameters() {
798 return new external_function_parameters(
799 array(
800 'courses' => new external_multiple_structure(
801 new external_single_structure(
802 array(
803 'id' => new external_value(PARAM_INT, 'ID of the course'),
804 'fullname' => new external_value(PARAM_TEXT, 'full name', VALUE_OPTIONAL),
805 'shortname' => new external_value(PARAM_TEXT, 'course short name', VALUE_OPTIONAL),
806 'categoryid' => new external_value(PARAM_INT, 'category id', VALUE_OPTIONAL),
807 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
808 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
809 'summaryformat' => new external_format_value('summary', VALUE_OPTIONAL),
810 'format' => new external_value(PARAM_PLUGIN,
811 'course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
812 'showgrades' => new external_value(PARAM_INT,
813 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
814 'newsitems' => new external_value(PARAM_INT,
815 'number of recent items appearing on the course page', VALUE_OPTIONAL),
816 'startdate' => new external_value(PARAM_INT,
817 'timestamp when the course start', VALUE_OPTIONAL),
818 'enddate' => new external_value(PARAM_INT,
819 'timestamp when the course end', VALUE_OPTIONAL),
820 'numsections' => new external_value(PARAM_INT,
821 '(deprecated, use courseformatoptions) number of weeks/topics', VALUE_OPTIONAL),
822 'maxbytes' => new external_value(PARAM_INT,
823 'largest size of file that can be uploaded into the course', VALUE_OPTIONAL),
824 'showreports' => new external_value(PARAM_INT,
825 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
826 'visible' => new external_value(PARAM_INT,
827 '1: available to student, 0:not available', VALUE_OPTIONAL),
828 'hiddensections' => new external_value(PARAM_INT,
829 '(deprecated, use courseformatoptions) How the hidden sections in the course are
830 displayed to students', VALUE_OPTIONAL),
831 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
832 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
833 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
834 'enablecompletion' => new external_value(PARAM_INT,
835 'Enabled, control via completion and activity settings. Disabled,
836 not shown in activity settings.', VALUE_OPTIONAL),
837 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
838 'lang' => new external_value(PARAM_SAFEDIR, 'forced course language', VALUE_OPTIONAL),
839 'forcetheme' => new external_value(PARAM_PLUGIN, 'name of the force theme', VALUE_OPTIONAL),
840 'courseformatoptions' => new external_multiple_structure(
841 new external_single_structure(
842 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
843 'value' => new external_value(PARAM_RAW, 'course format option value')
845 'additional options for particular course format', VALUE_OPTIONAL),
847 ), 'courses to update'
854 * Update courses
856 * @param array $courses
857 * @since Moodle 2.5
859 public static function update_courses($courses) {
860 global $CFG, $DB;
861 require_once($CFG->dirroot . "/course/lib.php");
862 $warnings = array();
864 $params = self::validate_parameters(self::update_courses_parameters(),
865 array('courses' => $courses));
867 $availablethemes = core_component::get_plugin_list('theme');
868 $availablelangs = get_string_manager()->get_list_of_translations();
870 foreach ($params['courses'] as $course) {
871 // Catch any exception while updating course and return as warning to user.
872 try {
873 // Ensure the current user is allowed to run this function.
874 $context = context_course::instance($course['id'], MUST_EXIST);
875 self::validate_context($context);
877 $oldcourse = course_get_format($course['id'])->get_course();
879 require_capability('moodle/course:update', $context);
881 // Check if user can change category.
882 if (array_key_exists('categoryid', $course) && ($oldcourse->category != $course['categoryid'])) {
883 require_capability('moodle/course:changecategory', $context);
884 $course['category'] = $course['categoryid'];
887 // Check if the user can change fullname.
888 if (array_key_exists('fullname', $course) && ($oldcourse->fullname != $course['fullname'])) {
889 require_capability('moodle/course:changefullname', $context);
892 // Check if the user can change shortname.
893 if (array_key_exists('shortname', $course) && ($oldcourse->shortname != $course['shortname'])) {
894 require_capability('moodle/course:changeshortname', $context);
897 // Check if the user can change the idnumber.
898 if (array_key_exists('idnumber', $course) && ($oldcourse->idnumber != $course['idnumber'])) {
899 require_capability('moodle/course:changeidnumber', $context);
902 // Check if user can change summary.
903 if (array_key_exists('summary', $course) && ($oldcourse->summary != $course['summary'])) {
904 require_capability('moodle/course:changesummary', $context);
907 // Summary format.
908 if (array_key_exists('summaryformat', $course) && ($oldcourse->summaryformat != $course['summaryformat'])) {
909 require_capability('moodle/course:changesummary', $context);
910 $course['summaryformat'] = external_validate_format($course['summaryformat']);
913 // Check if user can change visibility.
914 if (array_key_exists('visible', $course) && ($oldcourse->visible != $course['visible'])) {
915 require_capability('moodle/course:visibility', $context);
918 // Make sure lang is valid.
919 if (array_key_exists('lang', $course) && ($oldcourse->lang != $course['lang'])) {
920 require_capability('moodle/course:setforcedlanguage', $context);
921 if (empty($availablelangs[$course['lang']])) {
922 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
926 // Make sure theme is valid.
927 if (array_key_exists('forcetheme', $course)) {
928 if (!empty($CFG->allowcoursethemes)) {
929 if (empty($availablethemes[$course['forcetheme']])) {
930 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
931 } else {
932 $course['theme'] = $course['forcetheme'];
937 // Make sure completion is enabled before setting it.
938 if (array_key_exists('enabledcompletion', $course) && !completion_info::is_enabled_for_site()) {
939 $course['enabledcompletion'] = 0;
942 // Make sure maxbytes are less then CFG->maxbytes.
943 if (array_key_exists('maxbytes', $course)) {
944 // We allow updates back to 0 max bytes, a special value denoting the course uses the site limit.
945 // Otherwise, either use the size specified, or cap at the max size for the course.
946 if ($course['maxbytes'] != 0) {
947 $course['maxbytes'] = get_max_upload_file_size($CFG->maxbytes, $course['maxbytes']);
951 if (!empty($course['courseformatoptions'])) {
952 foreach ($course['courseformatoptions'] as $option) {
953 if (isset($option['name']) && isset($option['value'])) {
954 $course[$option['name']] = $option['value'];
959 // Update course if user has all required capabilities.
960 update_course((object) $course);
961 } catch (Exception $e) {
962 $warning = array();
963 $warning['item'] = 'course';
964 $warning['itemid'] = $course['id'];
965 if ($e instanceof moodle_exception) {
966 $warning['warningcode'] = $e->errorcode;
967 } else {
968 $warning['warningcode'] = $e->getCode();
970 $warning['message'] = $e->getMessage();
971 $warnings[] = $warning;
975 $result = array();
976 $result['warnings'] = $warnings;
977 return $result;
981 * Returns description of method result value
983 * @return external_description
984 * @since Moodle 2.5
986 public static function update_courses_returns() {
987 return new external_single_structure(
988 array(
989 'warnings' => new external_warnings()
995 * Returns description of method parameters
997 * @return external_function_parameters
998 * @since Moodle 2.2
1000 public static function delete_courses_parameters() {
1001 return new external_function_parameters(
1002 array(
1003 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'course ID')),
1009 * Delete courses
1011 * @param array $courseids A list of course ids
1012 * @since Moodle 2.2
1014 public static function delete_courses($courseids) {
1015 global $CFG, $DB;
1016 require_once($CFG->dirroot."/course/lib.php");
1018 // Parameter validation.
1019 $params = self::validate_parameters(self::delete_courses_parameters(), array('courseids'=>$courseids));
1021 $warnings = array();
1023 foreach ($params['courseids'] as $courseid) {
1024 $course = $DB->get_record('course', array('id' => $courseid));
1026 if ($course === false) {
1027 $warnings[] = array(
1028 'item' => 'course',
1029 'itemid' => $courseid,
1030 'warningcode' => 'unknowncourseidnumber',
1031 'message' => 'Unknown course ID ' . $courseid
1033 continue;
1036 // Check if the context is valid.
1037 $coursecontext = context_course::instance($course->id);
1038 self::validate_context($coursecontext);
1040 // Check if the current user has permission.
1041 if (!can_delete_course($courseid)) {
1042 $warnings[] = array(
1043 'item' => 'course',
1044 'itemid' => $courseid,
1045 'warningcode' => 'cannotdeletecourse',
1046 'message' => 'You do not have the permission to delete this course' . $courseid
1048 continue;
1051 if (delete_course($course, false) === false) {
1052 $warnings[] = array(
1053 'item' => 'course',
1054 'itemid' => $courseid,
1055 'warningcode' => 'cannotdeletecategorycourse',
1056 'message' => 'Course ' . $courseid . ' failed to be deleted'
1058 continue;
1062 fix_course_sortorder();
1064 return array('warnings' => $warnings);
1068 * Returns description of method result value
1070 * @return external_description
1071 * @since Moodle 2.2
1073 public static function delete_courses_returns() {
1074 return new external_single_structure(
1075 array(
1076 'warnings' => new external_warnings()
1082 * Returns description of method parameters
1084 * @return external_function_parameters
1085 * @since Moodle 2.3
1087 public static function duplicate_course_parameters() {
1088 return new external_function_parameters(
1089 array(
1090 'courseid' => new external_value(PARAM_INT, 'course to duplicate id'),
1091 'fullname' => new external_value(PARAM_TEXT, 'duplicated course full name'),
1092 'shortname' => new external_value(PARAM_TEXT, 'duplicated course short name'),
1093 'categoryid' => new external_value(PARAM_INT, 'duplicated course category parent'),
1094 'visible' => new external_value(PARAM_INT, 'duplicated course visible, default to yes', VALUE_DEFAULT, 1),
1095 'options' => new external_multiple_structure(
1096 new external_single_structure(
1097 array(
1098 'name' => new external_value(PARAM_ALPHAEXT, 'The backup option name:
1099 "activities" (int) Include course activites (default to 1 that is equal to yes),
1100 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1101 "filters" (int) Include course filters (default to 1 that is equal to yes),
1102 "users" (int) Include users (default to 0 that is equal to no),
1103 "enrolments" (int) Include enrolment methods (default to 1 - restore only with users),
1104 "role_assignments" (int) Include role assignments (default to 0 that is equal to no),
1105 "comments" (int) Include user comments (default to 0 that is equal to no),
1106 "userscompletion" (int) Include user course completion information (default to 0 that is equal to no),
1107 "logs" (int) Include course logs (default to 0 that is equal to no),
1108 "grade_histories" (int) Include histories (default to 0 that is equal to no)'
1110 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1113 ), VALUE_DEFAULT, array()
1120 * Duplicate a course
1122 * @param int $courseid
1123 * @param string $fullname Duplicated course fullname
1124 * @param string $shortname Duplicated course shortname
1125 * @param int $categoryid Duplicated course parent category id
1126 * @param int $visible Duplicated course availability
1127 * @param array $options List of backup options
1128 * @return array New course info
1129 * @since Moodle 2.3
1131 public static function duplicate_course($courseid, $fullname, $shortname, $categoryid, $visible = 1, $options = array()) {
1132 global $CFG, $USER, $DB;
1133 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1134 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1136 // Parameter validation.
1137 $params = self::validate_parameters(
1138 self::duplicate_course_parameters(),
1139 array(
1140 'courseid' => $courseid,
1141 'fullname' => $fullname,
1142 'shortname' => $shortname,
1143 'categoryid' => $categoryid,
1144 'visible' => $visible,
1145 'options' => $options
1149 // Context validation.
1151 if (! ($course = $DB->get_record('course', array('id'=>$params['courseid'])))) {
1152 throw new moodle_exception('invalidcourseid', 'error');
1155 // Category where duplicated course is going to be created.
1156 $categorycontext = context_coursecat::instance($params['categoryid']);
1157 self::validate_context($categorycontext);
1159 // Course to be duplicated.
1160 $coursecontext = context_course::instance($course->id);
1161 self::validate_context($coursecontext);
1163 $backupdefaults = array(
1164 'activities' => 1,
1165 'blocks' => 1,
1166 'filters' => 1,
1167 'users' => 0,
1168 'enrolments' => backup::ENROL_WITHUSERS,
1169 'role_assignments' => 0,
1170 'comments' => 0,
1171 'userscompletion' => 0,
1172 'logs' => 0,
1173 'grade_histories' => 0
1176 $backupsettings = array();
1177 // Check for backup and restore options.
1178 if (!empty($params['options'])) {
1179 foreach ($params['options'] as $option) {
1181 // Strict check for a correct value (allways 1 or 0, true or false).
1182 $value = clean_param($option['value'], PARAM_INT);
1184 if ($value !== 0 and $value !== 1) {
1185 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1188 if (!isset($backupdefaults[$option['name']])) {
1189 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1192 $backupsettings[$option['name']] = $value;
1196 // Capability checking.
1198 // The backup controller check for this currently, this may be redundant.
1199 require_capability('moodle/course:create', $categorycontext);
1200 require_capability('moodle/restore:restorecourse', $categorycontext);
1201 require_capability('moodle/backup:backupcourse', $coursecontext);
1203 if (!empty($backupsettings['users'])) {
1204 require_capability('moodle/backup:userinfo', $coursecontext);
1205 require_capability('moodle/restore:userinfo', $categorycontext);
1208 // Check if the shortname is used.
1209 if ($foundcourses = $DB->get_records('course', array('shortname'=>$shortname))) {
1210 foreach ($foundcourses as $foundcourse) {
1211 $foundcoursenames[] = $foundcourse->fullname;
1214 $foundcoursenamestring = implode(',', $foundcoursenames);
1215 throw new moodle_exception('shortnametaken', '', '', $foundcoursenamestring);
1218 // Backup the course.
1220 $bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE,
1221 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id);
1223 foreach ($backupsettings as $name => $value) {
1224 if ($setting = $bc->get_plan()->get_setting($name)) {
1225 $bc->get_plan()->get_setting($name)->set_value($value);
1229 $backupid = $bc->get_backupid();
1230 $backupbasepath = $bc->get_plan()->get_basepath();
1232 $bc->execute_plan();
1233 $results = $bc->get_results();
1234 $file = $results['backup_destination'];
1236 $bc->destroy();
1238 // Restore the backup immediately.
1240 // Check if we need to unzip the file because the backup temp dir does not contains backup files.
1241 if (!file_exists($backupbasepath . "/moodle_backup.xml")) {
1242 $file->extract_to_pathname(get_file_packer('application/vnd.moodle.backup'), $backupbasepath);
1245 // Create new course.
1246 $newcourseid = restore_dbops::create_new_course($params['fullname'], $params['shortname'], $params['categoryid']);
1248 $rc = new restore_controller($backupid, $newcourseid,
1249 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id, backup::TARGET_NEW_COURSE);
1251 foreach ($backupsettings as $name => $value) {
1252 $setting = $rc->get_plan()->get_setting($name);
1253 if ($setting->get_status() == backup_setting::NOT_LOCKED) {
1254 $setting->set_value($value);
1258 if (!$rc->execute_precheck()) {
1259 $precheckresults = $rc->get_precheck_results();
1260 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1261 if (empty($CFG->keeptempdirectoriesonbackup)) {
1262 fulldelete($backupbasepath);
1265 $errorinfo = '';
1267 foreach ($precheckresults['errors'] as $error) {
1268 $errorinfo .= $error;
1271 if (array_key_exists('warnings', $precheckresults)) {
1272 foreach ($precheckresults['warnings'] as $warning) {
1273 $errorinfo .= $warning;
1277 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1281 $rc->execute_plan();
1282 $rc->destroy();
1284 $course = $DB->get_record('course', array('id' => $newcourseid), '*', MUST_EXIST);
1285 $course->fullname = $params['fullname'];
1286 $course->shortname = $params['shortname'];
1287 $course->visible = $params['visible'];
1289 // Set shortname and fullname back.
1290 $DB->update_record('course', $course);
1292 if (empty($CFG->keeptempdirectoriesonbackup)) {
1293 fulldelete($backupbasepath);
1296 // Delete the course backup file created by this WebService. Originally located in the course backups area.
1297 $file->delete();
1299 return array('id' => $course->id, 'shortname' => $course->shortname);
1303 * Returns description of method result value
1305 * @return external_description
1306 * @since Moodle 2.3
1308 public static function duplicate_course_returns() {
1309 return new external_single_structure(
1310 array(
1311 'id' => new external_value(PARAM_INT, 'course id'),
1312 'shortname' => new external_value(PARAM_TEXT, 'short name'),
1318 * Returns description of method parameters for import_course
1320 * @return external_function_parameters
1321 * @since Moodle 2.4
1323 public static function import_course_parameters() {
1324 return new external_function_parameters(
1325 array(
1326 'importfrom' => new external_value(PARAM_INT, 'the id of the course we are importing from'),
1327 'importto' => new external_value(PARAM_INT, 'the id of the course we are importing to'),
1328 'deletecontent' => new external_value(PARAM_INT, 'whether to delete the course content where we are importing to (default to 0 = No)', VALUE_DEFAULT, 0),
1329 'options' => new external_multiple_structure(
1330 new external_single_structure(
1331 array(
1332 'name' => new external_value(PARAM_ALPHA, 'The backup option name:
1333 "activities" (int) Include course activites (default to 1 that is equal to yes),
1334 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1335 "filters" (int) Include course filters (default to 1 that is equal to yes)'
1337 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1340 ), VALUE_DEFAULT, array()
1347 * Imports a course
1349 * @param int $importfrom The id of the course we are importing from
1350 * @param int $importto The id of the course we are importing to
1351 * @param bool $deletecontent Whether to delete the course we are importing to content
1352 * @param array $options List of backup options
1353 * @return null
1354 * @since Moodle 2.4
1356 public static function import_course($importfrom, $importto, $deletecontent = 0, $options = array()) {
1357 global $CFG, $USER, $DB;
1358 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1359 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1361 // Parameter validation.
1362 $params = self::validate_parameters(
1363 self::import_course_parameters(),
1364 array(
1365 'importfrom' => $importfrom,
1366 'importto' => $importto,
1367 'deletecontent' => $deletecontent,
1368 'options' => $options
1372 if ($params['deletecontent'] !== 0 and $params['deletecontent'] !== 1) {
1373 throw new moodle_exception('invalidextparam', 'webservice', '', $params['deletecontent']);
1376 // Context validation.
1378 if (! ($importfrom = $DB->get_record('course', array('id'=>$params['importfrom'])))) {
1379 throw new moodle_exception('invalidcourseid', 'error');
1382 if (! ($importto = $DB->get_record('course', array('id'=>$params['importto'])))) {
1383 throw new moodle_exception('invalidcourseid', 'error');
1386 $importfromcontext = context_course::instance($importfrom->id);
1387 self::validate_context($importfromcontext);
1389 $importtocontext = context_course::instance($importto->id);
1390 self::validate_context($importtocontext);
1392 $backupdefaults = array(
1393 'activities' => 1,
1394 'blocks' => 1,
1395 'filters' => 1
1398 $backupsettings = array();
1400 // Check for backup and restore options.
1401 if (!empty($params['options'])) {
1402 foreach ($params['options'] as $option) {
1404 // Strict check for a correct value (allways 1 or 0, true or false).
1405 $value = clean_param($option['value'], PARAM_INT);
1407 if ($value !== 0 and $value !== 1) {
1408 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1411 if (!isset($backupdefaults[$option['name']])) {
1412 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1415 $backupsettings[$option['name']] = $value;
1419 // Capability checking.
1421 require_capability('moodle/backup:backuptargetimport', $importfromcontext);
1422 require_capability('moodle/restore:restoretargetimport', $importtocontext);
1424 $bc = new backup_controller(backup::TYPE_1COURSE, $importfrom->id, backup::FORMAT_MOODLE,
1425 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
1427 foreach ($backupsettings as $name => $value) {
1428 $bc->get_plan()->get_setting($name)->set_value($value);
1431 $backupid = $bc->get_backupid();
1432 $backupbasepath = $bc->get_plan()->get_basepath();
1434 $bc->execute_plan();
1435 $bc->destroy();
1437 // Restore the backup immediately.
1439 // Check if we must delete the contents of the destination course.
1440 if ($params['deletecontent']) {
1441 $restoretarget = backup::TARGET_EXISTING_DELETING;
1442 } else {
1443 $restoretarget = backup::TARGET_EXISTING_ADDING;
1446 $rc = new restore_controller($backupid, $importto->id,
1447 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, $restoretarget);
1449 foreach ($backupsettings as $name => $value) {
1450 $rc->get_plan()->get_setting($name)->set_value($value);
1453 if (!$rc->execute_precheck()) {
1454 $precheckresults = $rc->get_precheck_results();
1455 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1456 if (empty($CFG->keeptempdirectoriesonbackup)) {
1457 fulldelete($backupbasepath);
1460 $errorinfo = '';
1462 foreach ($precheckresults['errors'] as $error) {
1463 $errorinfo .= $error;
1466 if (array_key_exists('warnings', $precheckresults)) {
1467 foreach ($precheckresults['warnings'] as $warning) {
1468 $errorinfo .= $warning;
1472 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1474 } else {
1475 if ($restoretarget == backup::TARGET_EXISTING_DELETING) {
1476 restore_dbops::delete_course_content($importto->id);
1480 $rc->execute_plan();
1481 $rc->destroy();
1483 if (empty($CFG->keeptempdirectoriesonbackup)) {
1484 fulldelete($backupbasepath);
1487 return null;
1491 * Returns description of method result value
1493 * @return external_description
1494 * @since Moodle 2.4
1496 public static function import_course_returns() {
1497 return null;
1501 * Returns description of method parameters
1503 * @return external_function_parameters
1504 * @since Moodle 2.3
1506 public static function get_categories_parameters() {
1507 return new external_function_parameters(
1508 array(
1509 'criteria' => new external_multiple_structure(
1510 new external_single_structure(
1511 array(
1512 'key' => new external_value(PARAM_ALPHA,
1513 'The category column to search, expected keys (value format) are:'.
1514 '"id" (int) the category id,'.
1515 '"ids" (string) category ids separated by commas,'.
1516 '"name" (string) the category name,'.
1517 '"parent" (int) the parent category id,'.
1518 '"idnumber" (string) category idnumber'.
1519 ' - user must have \'moodle/category:manage\' to search on idnumber,'.
1520 '"visible" (int) whether the returned categories must be visible or hidden. If the key is not passed,
1521 then the function return all categories that the user can see.'.
1522 ' - user must have \'moodle/category:manage\' or \'moodle/category:viewhiddencategories\' to search on visible,'.
1523 '"theme" (string) only return the categories having this theme'.
1524 ' - user must have \'moodle/category:manage\' to search on theme'),
1525 'value' => new external_value(PARAM_RAW, 'the value to match')
1527 ), 'criteria', VALUE_DEFAULT, array()
1529 'addsubcategories' => new external_value(PARAM_BOOL, 'return the sub categories infos
1530 (1 - default) otherwise only the category info (0)', VALUE_DEFAULT, 1)
1536 * Get categories
1538 * @param array $criteria Criteria to match the results
1539 * @param booln $addsubcategories obtain only the category (false) or its subcategories (true - default)
1540 * @return array list of categories
1541 * @since Moodle 2.3
1543 public static function get_categories($criteria = array(), $addsubcategories = true) {
1544 global $CFG, $DB;
1545 require_once($CFG->dirroot . "/course/lib.php");
1547 // Validate parameters.
1548 $params = self::validate_parameters(self::get_categories_parameters(),
1549 array('criteria' => $criteria, 'addsubcategories' => $addsubcategories));
1551 // Retrieve the categories.
1552 $categories = array();
1553 if (!empty($params['criteria'])) {
1555 $conditions = array();
1556 $wheres = array();
1557 foreach ($params['criteria'] as $crit) {
1558 $key = trim($crit['key']);
1560 // Trying to avoid duplicate keys.
1561 if (!isset($conditions[$key])) {
1563 $context = context_system::instance();
1564 $value = null;
1565 switch ($key) {
1566 case 'id':
1567 $value = clean_param($crit['value'], PARAM_INT);
1568 $conditions[$key] = $value;
1569 $wheres[] = $key . " = :" . $key;
1570 break;
1572 case 'ids':
1573 $value = clean_param($crit['value'], PARAM_SEQUENCE);
1574 $ids = explode(',', $value);
1575 list($sqlids, $paramids) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED);
1576 $conditions = array_merge($conditions, $paramids);
1577 $wheres[] = 'id ' . $sqlids;
1578 break;
1580 case 'idnumber':
1581 if (has_capability('moodle/category:manage', $context)) {
1582 $value = clean_param($crit['value'], PARAM_RAW);
1583 $conditions[$key] = $value;
1584 $wheres[] = $key . " = :" . $key;
1585 } else {
1586 // We must throw an exception.
1587 // Otherwise the dev client would think no idnumber exists.
1588 throw new moodle_exception('criteriaerror',
1589 'webservice', '', null,
1590 'You don\'t have the permissions to search on the "idnumber" field.');
1592 break;
1594 case 'name':
1595 $value = clean_param($crit['value'], PARAM_TEXT);
1596 $conditions[$key] = $value;
1597 $wheres[] = $key . " = :" . $key;
1598 break;
1600 case 'parent':
1601 $value = clean_param($crit['value'], PARAM_INT);
1602 $conditions[$key] = $value;
1603 $wheres[] = $key . " = :" . $key;
1604 break;
1606 case 'visible':
1607 if (has_capability('moodle/category:viewhiddencategories', $context)) {
1608 $value = clean_param($crit['value'], PARAM_INT);
1609 $conditions[$key] = $value;
1610 $wheres[] = $key . " = :" . $key;
1611 } else {
1612 throw new moodle_exception('criteriaerror',
1613 'webservice', '', null,
1614 'You don\'t have the permissions to search on the "visible" field.');
1616 break;
1618 case 'theme':
1619 if (has_capability('moodle/category:manage', $context)) {
1620 $value = clean_param($crit['value'], PARAM_THEME);
1621 $conditions[$key] = $value;
1622 $wheres[] = $key . " = :" . $key;
1623 } else {
1624 throw new moodle_exception('criteriaerror',
1625 'webservice', '', null,
1626 'You don\'t have the permissions to search on the "theme" field.');
1628 break;
1630 default:
1631 throw new moodle_exception('criteriaerror',
1632 'webservice', '', null,
1633 'You can not search on this criteria: ' . $key);
1638 if (!empty($wheres)) {
1639 $wheres = implode(" AND ", $wheres);
1641 $categories = $DB->get_records_select('course_categories', $wheres, $conditions);
1643 // Retrieve its sub subcategories (all levels).
1644 if ($categories and !empty($params['addsubcategories'])) {
1645 $newcategories = array();
1647 // Check if we required visible/theme checks.
1648 $additionalselect = '';
1649 $additionalparams = array();
1650 if (isset($conditions['visible'])) {
1651 $additionalselect .= ' AND visible = :visible';
1652 $additionalparams['visible'] = $conditions['visible'];
1654 if (isset($conditions['theme'])) {
1655 $additionalselect .= ' AND theme= :theme';
1656 $additionalparams['theme'] = $conditions['theme'];
1659 foreach ($categories as $category) {
1660 $sqlselect = $DB->sql_like('path', ':path') . $additionalselect;
1661 $sqlparams = array('path' => $category->path.'/%') + $additionalparams; // It will NOT include the specified category.
1662 $subcategories = $DB->get_records_select('course_categories', $sqlselect, $sqlparams);
1663 $newcategories = $newcategories + $subcategories; // Both arrays have integer as keys.
1665 $categories = $categories + $newcategories;
1669 } else {
1670 // Retrieve all categories in the database.
1671 $categories = $DB->get_records('course_categories');
1674 // The not returned categories. key => category id, value => reason of exclusion.
1675 $excludedcats = array();
1677 // The returned categories.
1678 $categoriesinfo = array();
1680 // We need to sort the categories by path.
1681 // The parent cats need to be checked by the algo first.
1682 usort($categories, "core_course_external::compare_categories_by_path");
1684 foreach ($categories as $category) {
1686 // Check if the category is a child of an excluded category, if yes exclude it too (excluded => do not return).
1687 $parents = explode('/', $category->path);
1688 unset($parents[0]); // First key is always empty because path start with / => /1/2/4.
1689 foreach ($parents as $parentid) {
1690 // Note: when the parent exclusion was due to the context,
1691 // the sub category could still be returned.
1692 if (isset($excludedcats[$parentid]) and $excludedcats[$parentid] != 'context') {
1693 $excludedcats[$category->id] = 'parent';
1697 // Check the user can use the category context.
1698 $context = context_coursecat::instance($category->id);
1699 try {
1700 self::validate_context($context);
1701 } catch (Exception $e) {
1702 $excludedcats[$category->id] = 'context';
1704 // If it was the requested category then throw an exception.
1705 if (isset($params['categoryid']) && $category->id == $params['categoryid']) {
1706 $exceptionparam = new stdClass();
1707 $exceptionparam->message = $e->getMessage();
1708 $exceptionparam->catid = $category->id;
1709 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
1713 // Return the category information.
1714 if (!isset($excludedcats[$category->id])) {
1716 // Final check to see if the category is visible to the user.
1717 if ($category->visible or has_capability('moodle/category:viewhiddencategories', $context)) {
1719 $categoryinfo = array();
1720 $categoryinfo['id'] = $category->id;
1721 $categoryinfo['name'] = external_format_string($category->name, $context);
1722 list($categoryinfo['description'], $categoryinfo['descriptionformat']) =
1723 external_format_text($category->description, $category->descriptionformat,
1724 $context->id, 'coursecat', 'description', null);
1725 $categoryinfo['parent'] = $category->parent;
1726 $categoryinfo['sortorder'] = $category->sortorder;
1727 $categoryinfo['coursecount'] = $category->coursecount;
1728 $categoryinfo['depth'] = $category->depth;
1729 $categoryinfo['path'] = $category->path;
1731 // Some fields only returned for admin.
1732 if (has_capability('moodle/category:manage', $context)) {
1733 $categoryinfo['idnumber'] = $category->idnumber;
1734 $categoryinfo['visible'] = $category->visible;
1735 $categoryinfo['visibleold'] = $category->visibleold;
1736 $categoryinfo['timemodified'] = $category->timemodified;
1737 $categoryinfo['theme'] = clean_param($category->theme, PARAM_THEME);
1740 $categoriesinfo[] = $categoryinfo;
1741 } else {
1742 $excludedcats[$category->id] = 'visibility';
1747 // Sorting the resulting array so it looks a bit better for the client developer.
1748 usort($categoriesinfo, "core_course_external::compare_categories_by_sortorder");
1750 return $categoriesinfo;
1754 * Sort categories array by path
1755 * private function: only used by get_categories
1757 * @param array $category1
1758 * @param array $category2
1759 * @return int result of strcmp
1760 * @since Moodle 2.3
1762 private static function compare_categories_by_path($category1, $category2) {
1763 return strcmp($category1->path, $category2->path);
1767 * Sort categories array by sortorder
1768 * private function: only used by get_categories
1770 * @param array $category1
1771 * @param array $category2
1772 * @return int result of strcmp
1773 * @since Moodle 2.3
1775 private static function compare_categories_by_sortorder($category1, $category2) {
1776 return strcmp($category1['sortorder'], $category2['sortorder']);
1780 * Returns description of method result value
1782 * @return external_description
1783 * @since Moodle 2.3
1785 public static function get_categories_returns() {
1786 return new external_multiple_structure(
1787 new external_single_structure(
1788 array(
1789 'id' => new external_value(PARAM_INT, 'category id'),
1790 'name' => new external_value(PARAM_TEXT, 'category name'),
1791 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1792 'description' => new external_value(PARAM_RAW, 'category description'),
1793 'descriptionformat' => new external_format_value('description'),
1794 'parent' => new external_value(PARAM_INT, 'parent category id'),
1795 'sortorder' => new external_value(PARAM_INT, 'category sorting order'),
1796 'coursecount' => new external_value(PARAM_INT, 'number of courses in this category'),
1797 'visible' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1798 'visibleold' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1799 'timemodified' => new external_value(PARAM_INT, 'timestamp', VALUE_OPTIONAL),
1800 'depth' => new external_value(PARAM_INT, 'category depth'),
1801 'path' => new external_value(PARAM_TEXT, 'category path'),
1802 'theme' => new external_value(PARAM_THEME, 'category theme', VALUE_OPTIONAL),
1803 ), 'List of categories'
1809 * Returns description of method parameters
1811 * @return external_function_parameters
1812 * @since Moodle 2.3
1814 public static function create_categories_parameters() {
1815 return new external_function_parameters(
1816 array(
1817 'categories' => new external_multiple_structure(
1818 new external_single_structure(
1819 array(
1820 'name' => new external_value(PARAM_TEXT, 'new category name'),
1821 'parent' => new external_value(PARAM_INT,
1822 'the parent category id inside which the new category will be created
1823 - set to 0 for a root category',
1824 VALUE_DEFAULT, 0),
1825 'idnumber' => new external_value(PARAM_RAW,
1826 'the new category idnumber', VALUE_OPTIONAL),
1827 'description' => new external_value(PARAM_RAW,
1828 'the new category description', VALUE_OPTIONAL),
1829 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
1830 'theme' => new external_value(PARAM_THEME,
1831 'the new category theme. This option must be enabled on moodle',
1832 VALUE_OPTIONAL),
1841 * Create categories
1843 * @param array $categories - see create_categories_parameters() for the array structure
1844 * @return array - see create_categories_returns() for the array structure
1845 * @since Moodle 2.3
1847 public static function create_categories($categories) {
1848 global $CFG, $DB;
1849 require_once($CFG->libdir . "/coursecatlib.php");
1851 $params = self::validate_parameters(self::create_categories_parameters(),
1852 array('categories' => $categories));
1854 $transaction = $DB->start_delegated_transaction();
1856 $createdcategories = array();
1857 foreach ($params['categories'] as $category) {
1858 if ($category['parent']) {
1859 if (!$DB->record_exists('course_categories', array('id' => $category['parent']))) {
1860 throw new moodle_exception('unknowcategory');
1862 $context = context_coursecat::instance($category['parent']);
1863 } else {
1864 $context = context_system::instance();
1866 self::validate_context($context);
1867 require_capability('moodle/category:manage', $context);
1869 // this will validate format and throw an exception if there are errors
1870 external_validate_format($category['descriptionformat']);
1872 $newcategory = coursecat::create($category);
1873 $context = context_coursecat::instance($newcategory->id);
1875 $createdcategories[] = array(
1876 'id' => $newcategory->id,
1877 'name' => external_format_string($newcategory->name, $context),
1881 $transaction->allow_commit();
1883 return $createdcategories;
1887 * Returns description of method parameters
1889 * @return external_function_parameters
1890 * @since Moodle 2.3
1892 public static function create_categories_returns() {
1893 return new external_multiple_structure(
1894 new external_single_structure(
1895 array(
1896 'id' => new external_value(PARAM_INT, 'new category id'),
1897 'name' => new external_value(PARAM_TEXT, 'new category name'),
1904 * Returns description of method parameters
1906 * @return external_function_parameters
1907 * @since Moodle 2.3
1909 public static function update_categories_parameters() {
1910 return new external_function_parameters(
1911 array(
1912 'categories' => new external_multiple_structure(
1913 new external_single_structure(
1914 array(
1915 'id' => new external_value(PARAM_INT, 'course id'),
1916 'name' => new external_value(PARAM_TEXT, 'category name', VALUE_OPTIONAL),
1917 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1918 'parent' => new external_value(PARAM_INT, 'parent category id', VALUE_OPTIONAL),
1919 'description' => new external_value(PARAM_RAW, 'category description', VALUE_OPTIONAL),
1920 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
1921 'theme' => new external_value(PARAM_THEME,
1922 'the category theme. This option must be enabled on moodle', VALUE_OPTIONAL),
1931 * Update categories
1933 * @param array $categories The list of categories to update
1934 * @return null
1935 * @since Moodle 2.3
1937 public static function update_categories($categories) {
1938 global $CFG, $DB;
1939 require_once($CFG->libdir . "/coursecatlib.php");
1941 // Validate parameters.
1942 $params = self::validate_parameters(self::update_categories_parameters(), array('categories' => $categories));
1944 $transaction = $DB->start_delegated_transaction();
1946 foreach ($params['categories'] as $cat) {
1947 $category = coursecat::get($cat['id']);
1949 $categorycontext = context_coursecat::instance($cat['id']);
1950 self::validate_context($categorycontext);
1951 require_capability('moodle/category:manage', $categorycontext);
1953 // this will throw an exception if descriptionformat is not valid
1954 external_validate_format($cat['descriptionformat']);
1956 $category->update($cat);
1959 $transaction->allow_commit();
1963 * Returns description of method result value
1965 * @return external_description
1966 * @since Moodle 2.3
1968 public static function update_categories_returns() {
1969 return null;
1973 * Returns description of method parameters
1975 * @return external_function_parameters
1976 * @since Moodle 2.3
1978 public static function delete_categories_parameters() {
1979 return new external_function_parameters(
1980 array(
1981 'categories' => new external_multiple_structure(
1982 new external_single_structure(
1983 array(
1984 'id' => new external_value(PARAM_INT, 'category id to delete'),
1985 'newparent' => new external_value(PARAM_INT,
1986 'the parent category to move the contents to, if specified', VALUE_OPTIONAL),
1987 'recursive' => new external_value(PARAM_BOOL, '1: recursively delete all contents inside this
1988 category, 0 (default): move contents to newparent or current parent category (except if parent is root)', VALUE_DEFAULT, 0)
1997 * Delete categories
1999 * @param array $categories A list of category ids
2000 * @return array
2001 * @since Moodle 2.3
2003 public static function delete_categories($categories) {
2004 global $CFG, $DB;
2005 require_once($CFG->dirroot . "/course/lib.php");
2006 require_once($CFG->libdir . "/coursecatlib.php");
2008 // Validate parameters.
2009 $params = self::validate_parameters(self::delete_categories_parameters(), array('categories' => $categories));
2011 $transaction = $DB->start_delegated_transaction();
2013 foreach ($params['categories'] as $category) {
2014 $deletecat = coursecat::get($category['id'], MUST_EXIST);
2015 $context = context_coursecat::instance($deletecat->id);
2016 require_capability('moodle/category:manage', $context);
2017 self::validate_context($context);
2018 self::validate_context(get_category_or_system_context($deletecat->parent));
2020 if ($category['recursive']) {
2021 // If recursive was specified, then we recursively delete the category's contents.
2022 if ($deletecat->can_delete_full()) {
2023 $deletecat->delete_full(false);
2024 } else {
2025 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2027 } else {
2028 // In this situation, we don't delete the category's contents, we either move it to newparent or parent.
2029 // If the parent is the root, moving is not supported (because a course must always be inside a category).
2030 // We must move to an existing category.
2031 if (!empty($category['newparent'])) {
2032 $newparentcat = coursecat::get($category['newparent']);
2033 } else {
2034 $newparentcat = coursecat::get($deletecat->parent);
2037 // This operation is not allowed. We must move contents to an existing category.
2038 if (!$newparentcat->id) {
2039 throw new moodle_exception('movecatcontentstoroot');
2042 self::validate_context(context_coursecat::instance($newparentcat->id));
2043 if ($deletecat->can_move_content_to($newparentcat->id)) {
2044 $deletecat->delete_move($newparentcat->id, false);
2045 } else {
2046 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2051 $transaction->allow_commit();
2055 * Returns description of method parameters
2057 * @return external_function_parameters
2058 * @since Moodle 2.3
2060 public static function delete_categories_returns() {
2061 return null;
2065 * Describes the parameters for delete_modules.
2067 * @return external_function_parameters
2068 * @since Moodle 2.5
2070 public static function delete_modules_parameters() {
2071 return new external_function_parameters (
2072 array(
2073 'cmids' => new external_multiple_structure(new external_value(PARAM_INT, 'course module ID',
2074 VALUE_REQUIRED, '', NULL_NOT_ALLOWED), 'Array of course module IDs'),
2080 * Deletes a list of provided module instances.
2082 * @param array $cmids the course module ids
2083 * @since Moodle 2.5
2085 public static function delete_modules($cmids) {
2086 global $CFG, $DB;
2088 // Require course file containing the course delete module function.
2089 require_once($CFG->dirroot . "/course/lib.php");
2091 // Clean the parameters.
2092 $params = self::validate_parameters(self::delete_modules_parameters(), array('cmids' => $cmids));
2094 // Keep track of the course ids we have performed a capability check on to avoid repeating.
2095 $arrcourseschecked = array();
2097 foreach ($params['cmids'] as $cmid) {
2098 // Get the course module.
2099 $cm = $DB->get_record('course_modules', array('id' => $cmid), '*', MUST_EXIST);
2101 // Check if we have not yet confirmed they have permission in this course.
2102 if (!in_array($cm->course, $arrcourseschecked)) {
2103 // Ensure the current user has required permission in this course.
2104 $context = context_course::instance($cm->course);
2105 self::validate_context($context);
2106 // Add to the array.
2107 $arrcourseschecked[] = $cm->course;
2110 // Ensure they can delete this module.
2111 $modcontext = context_module::instance($cm->id);
2112 require_capability('moodle/course:manageactivities', $modcontext);
2114 // Delete the module.
2115 course_delete_module($cm->id);
2120 * Describes the delete_modules return value.
2122 * @return external_single_structure
2123 * @since Moodle 2.5
2125 public static function delete_modules_returns() {
2126 return null;
2130 * Returns description of method parameters
2132 * @return external_function_parameters
2133 * @since Moodle 2.9
2135 public static function view_course_parameters() {
2136 return new external_function_parameters(
2137 array(
2138 'courseid' => new external_value(PARAM_INT, 'id of the course'),
2139 'sectionnumber' => new external_value(PARAM_INT, 'section number', VALUE_DEFAULT, 0)
2145 * Trigger the course viewed event.
2147 * @param int $courseid id of course
2148 * @param int $sectionnumber sectionnumber (0, 1, 2...)
2149 * @return array of warnings and status result
2150 * @since Moodle 2.9
2151 * @throws moodle_exception
2153 public static function view_course($courseid, $sectionnumber = 0) {
2154 global $CFG;
2155 require_once($CFG->dirroot . "/course/lib.php");
2157 $params = self::validate_parameters(self::view_course_parameters(),
2158 array(
2159 'courseid' => $courseid,
2160 'sectionnumber' => $sectionnumber
2163 $warnings = array();
2165 $course = get_course($params['courseid']);
2166 $context = context_course::instance($course->id);
2167 self::validate_context($context);
2169 if (!empty($params['sectionnumber'])) {
2171 // Get section details and check it exists.
2172 $modinfo = get_fast_modinfo($course);
2173 $coursesection = $modinfo->get_section_info($params['sectionnumber'], MUST_EXIST);
2175 // Check user is allowed to see it.
2176 if (!$coursesection->uservisible) {
2177 require_capability('moodle/course:viewhiddensections', $context);
2181 course_view($context, $params['sectionnumber']);
2183 $result = array();
2184 $result['status'] = true;
2185 $result['warnings'] = $warnings;
2186 return $result;
2190 * Returns description of method result value
2192 * @return external_description
2193 * @since Moodle 2.9
2195 public static function view_course_returns() {
2196 return new external_single_structure(
2197 array(
2198 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
2199 'warnings' => new external_warnings()
2205 * Returns description of method parameters
2207 * @return external_function_parameters
2208 * @since Moodle 3.0
2210 public static function search_courses_parameters() {
2211 return new external_function_parameters(
2212 array(
2213 'criterianame' => new external_value(PARAM_ALPHA, 'criteria name
2214 (search, modulelist (only admins), blocklist (only admins), tagid)'),
2215 'criteriavalue' => new external_value(PARAM_RAW, 'criteria value'),
2216 'page' => new external_value(PARAM_INT, 'page number (0 based)', VALUE_DEFAULT, 0),
2217 'perpage' => new external_value(PARAM_INT, 'items per page', VALUE_DEFAULT, 0),
2218 'requiredcapabilities' => new external_multiple_structure(
2219 new external_value(PARAM_CAPABILITY, 'Capability string used to filter courses by permission'),
2220 'Optional list of required capabilities (used to filter the list)', VALUE_DEFAULT, array()
2222 'limittoenrolled' => new external_value(PARAM_BOOL, 'limit to enrolled courses', VALUE_DEFAULT, 0),
2228 * Return the course information that is public (visible by every one)
2230 * @param course_in_list $course course in list object
2231 * @param stdClass $coursecontext course context object
2232 * @return array the course information
2233 * @since Moodle 3.2
2235 protected static function get_course_public_information(course_in_list $course, $coursecontext) {
2237 static $categoriescache = array();
2239 // Category information.
2240 if (!array_key_exists($course->category, $categoriescache)) {
2241 $categoriescache[$course->category] = coursecat::get($course->category, IGNORE_MISSING);
2243 $category = $categoriescache[$course->category];
2245 // Retrieve course overview used files.
2246 $files = array();
2247 foreach ($course->get_course_overviewfiles() as $file) {
2248 $fileurl = moodle_url::make_webservice_pluginfile_url($file->get_contextid(), $file->get_component(),
2249 $file->get_filearea(), null, $file->get_filepath(),
2250 $file->get_filename())->out(false);
2251 $files[] = array(
2252 'filename' => $file->get_filename(),
2253 'fileurl' => $fileurl,
2254 'filesize' => $file->get_filesize(),
2255 'filepath' => $file->get_filepath(),
2256 'mimetype' => $file->get_mimetype(),
2257 'timemodified' => $file->get_timemodified(),
2261 // Retrieve the course contacts,
2262 // we need here the users fullname since if we are not enrolled can be difficult to obtain them via other Web Services.
2263 $coursecontacts = array();
2264 foreach ($course->get_course_contacts() as $contact) {
2265 $coursecontacts[] = array(
2266 'id' => $contact['user']->id,
2267 'fullname' => $contact['username']
2271 // Allowed enrolment methods (maybe we can self-enrol).
2272 $enroltypes = array();
2273 $instances = enrol_get_instances($course->id, true);
2274 foreach ($instances as $instance) {
2275 $enroltypes[] = $instance->enrol;
2278 // Format summary.
2279 list($summary, $summaryformat) =
2280 external_format_text($course->summary, $course->summaryformat, $coursecontext->id, 'course', 'summary', null);
2282 $categoryname = '';
2283 if (!empty($category)) {
2284 $categoryname = external_format_string($category->name, $category->get_context());
2287 $displayname = get_course_display_name_for_list($course);
2288 $coursereturns = array();
2289 $coursereturns['id'] = $course->id;
2290 $coursereturns['fullname'] = external_format_string($course->fullname, $coursecontext->id);
2291 $coursereturns['displayname'] = external_format_string($displayname, $coursecontext->id);
2292 $coursereturns['shortname'] = external_format_string($course->shortname, $coursecontext->id);
2293 $coursereturns['categoryid'] = $course->category;
2294 $coursereturns['categoryname'] = $categoryname;
2295 $coursereturns['summary'] = $summary;
2296 $coursereturns['summaryformat'] = $summaryformat;
2297 $coursereturns['summaryfiles'] = external_util::get_area_files($coursecontext->id, 'course', 'summary', false, false);
2298 $coursereturns['overviewfiles'] = $files;
2299 $coursereturns['contacts'] = $coursecontacts;
2300 $coursereturns['enrollmentmethods'] = $enroltypes;
2301 $coursereturns['sortorder'] = $course->sortorder;
2302 return $coursereturns;
2306 * Search courses following the specified criteria.
2308 * @param string $criterianame Criteria name (search, modulelist (only admins), blocklist (only admins), tagid)
2309 * @param string $criteriavalue Criteria value
2310 * @param int $page Page number (for pagination)
2311 * @param int $perpage Items per page
2312 * @param array $requiredcapabilities Optional list of required capabilities (used to filter the list).
2313 * @param int $limittoenrolled Limit to only enrolled courses
2314 * @return array of course objects and warnings
2315 * @since Moodle 3.0
2316 * @throws moodle_exception
2318 public static function search_courses($criterianame,
2319 $criteriavalue,
2320 $page=0,
2321 $perpage=0,
2322 $requiredcapabilities=array(),
2323 $limittoenrolled=0) {
2324 global $CFG;
2325 require_once($CFG->libdir . '/coursecatlib.php');
2327 $warnings = array();
2329 $parameters = array(
2330 'criterianame' => $criterianame,
2331 'criteriavalue' => $criteriavalue,
2332 'page' => $page,
2333 'perpage' => $perpage,
2334 'requiredcapabilities' => $requiredcapabilities
2336 $params = self::validate_parameters(self::search_courses_parameters(), $parameters);
2337 self::validate_context(context_system::instance());
2339 $allowedcriterianames = array('search', 'modulelist', 'blocklist', 'tagid');
2340 if (!in_array($params['criterianame'], $allowedcriterianames)) {
2341 throw new invalid_parameter_exception('Invalid value for criterianame parameter (value: '.$params['criterianame'].'),' .
2342 'allowed values are: '.implode(',', $allowedcriterianames));
2345 if ($params['criterianame'] == 'modulelist' or $params['criterianame'] == 'blocklist') {
2346 require_capability('moodle/site:config', context_system::instance());
2349 $paramtype = array(
2350 'search' => PARAM_RAW,
2351 'modulelist' => PARAM_PLUGIN,
2352 'blocklist' => PARAM_INT,
2353 'tagid' => PARAM_INT
2355 $params['criteriavalue'] = clean_param($params['criteriavalue'], $paramtype[$params['criterianame']]);
2357 // Prepare the search API options.
2358 $searchcriteria = array();
2359 $searchcriteria[$params['criterianame']] = $params['criteriavalue'];
2361 $options = array();
2362 if ($params['perpage'] != 0) {
2363 $offset = $params['page'] * $params['perpage'];
2364 $options = array('offset' => $offset, 'limit' => $params['perpage']);
2367 // Search the courses.
2368 $courses = coursecat::search_courses($searchcriteria, $options, $params['requiredcapabilities']);
2369 $totalcount = coursecat::search_courses_count($searchcriteria, $options, $params['requiredcapabilities']);
2371 if (!empty($limittoenrolled)) {
2372 // Get the courses where the current user has access.
2373 $enrolled = enrol_get_my_courses(array('id', 'cacherev'));
2376 $finalcourses = array();
2377 $categoriescache = array();
2379 foreach ($courses as $course) {
2380 if (!empty($limittoenrolled)) {
2381 // Filter out not enrolled courses.
2382 if (!isset($enrolled[$course->id])) {
2383 $totalcount--;
2384 continue;
2388 $coursecontext = context_course::instance($course->id);
2390 $finalcourses[] = self::get_course_public_information($course, $coursecontext);
2393 return array(
2394 'total' => $totalcount,
2395 'courses' => $finalcourses,
2396 'warnings' => $warnings
2401 * Returns a course structure definition
2403 * @param boolean $onlypublicdata set to true, to retrieve only fields viewable by anyone when the course is visible
2404 * @return array the course structure
2405 * @since Moodle 3.2
2407 protected static function get_course_structure($onlypublicdata = true) {
2408 $coursestructure = array(
2409 'id' => new external_value(PARAM_INT, 'course id'),
2410 'fullname' => new external_value(PARAM_TEXT, 'course full name'),
2411 'displayname' => new external_value(PARAM_TEXT, 'course display name'),
2412 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
2413 'categoryid' => new external_value(PARAM_INT, 'category id'),
2414 'categoryname' => new external_value(PARAM_TEXT, 'category name'),
2415 'sortorder' => new external_value(PARAM_INT, 'Sort order in the category', VALUE_OPTIONAL),
2416 'summary' => new external_value(PARAM_RAW, 'summary'),
2417 'summaryformat' => new external_format_value('summary'),
2418 'summaryfiles' => new external_files('summary files in the summary field', VALUE_OPTIONAL),
2419 'overviewfiles' => new external_files('additional overview files attached to this course'),
2420 'contacts' => new external_multiple_structure(
2421 new external_single_structure(
2422 array(
2423 'id' => new external_value(PARAM_INT, 'contact user id'),
2424 'fullname' => new external_value(PARAM_NOTAGS, 'contact user fullname'),
2427 'contact users'
2429 'enrollmentmethods' => new external_multiple_structure(
2430 new external_value(PARAM_PLUGIN, 'enrollment method'),
2431 'enrollment methods list'
2435 if (!$onlypublicdata) {
2436 $extra = array(
2437 'idnumber' => new external_value(PARAM_RAW, 'Id number', VALUE_OPTIONAL),
2438 'format' => new external_value(PARAM_PLUGIN, 'Course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
2439 'showgrades' => new external_value(PARAM_INT, '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
2440 'newsitems' => new external_value(PARAM_INT, 'Number of recent items appearing on the course page', VALUE_OPTIONAL),
2441 'startdate' => new external_value(PARAM_INT, 'Timestamp when the course start', VALUE_OPTIONAL),
2442 'enddate' => new external_value(PARAM_INT, 'Timestamp when the course end', VALUE_OPTIONAL),
2443 'maxbytes' => new external_value(PARAM_INT, 'Largest size of file that can be uploaded into', VALUE_OPTIONAL),
2444 'showreports' => new external_value(PARAM_INT, 'Are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
2445 'visible' => new external_value(PARAM_INT, '1: available to student, 0:not available', VALUE_OPTIONAL),
2446 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
2447 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
2448 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
2449 'enablecompletion' => new external_value(PARAM_INT, 'Completion enabled? 1: yes 0: no', VALUE_OPTIONAL),
2450 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
2451 'lang' => new external_value(PARAM_SAFEDIR, 'Forced course language', VALUE_OPTIONAL),
2452 'theme' => new external_value(PARAM_PLUGIN, 'Fame of the forced theme', VALUE_OPTIONAL),
2453 'marker' => new external_value(PARAM_INT, 'Current course marker', VALUE_OPTIONAL),
2454 'legacyfiles' => new external_value(PARAM_INT, 'If legacy files are enabled', VALUE_OPTIONAL),
2455 'calendartype' => new external_value(PARAM_PLUGIN, 'Calendar type', VALUE_OPTIONAL),
2456 'timecreated' => new external_value(PARAM_INT, 'Time when the course was created', VALUE_OPTIONAL),
2457 'timemodified' => new external_value(PARAM_INT, 'Last time the course was updated', VALUE_OPTIONAL),
2458 'requested' => new external_value(PARAM_INT, 'If is a requested course', VALUE_OPTIONAL),
2459 'cacherev' => new external_value(PARAM_INT, 'Cache revision number', VALUE_OPTIONAL),
2460 'filters' => new external_multiple_structure(
2461 new external_single_structure(
2462 array(
2463 'filter' => new external_value(PARAM_PLUGIN, 'Filter plugin name'),
2464 'localstate' => new external_value(PARAM_INT, 'Filter state: 1 for on, -1 for off, 0 if inherit'),
2465 'inheritedstate' => new external_value(PARAM_INT, '1 or 0 to use when localstate is set to inherit'),
2468 'Course filters', VALUE_OPTIONAL
2470 'courseformatoptions' => new external_multiple_structure(
2471 new external_single_structure(
2472 array(
2473 'name' => new external_value(PARAM_RAW, 'Course format option name.'),
2474 'value' => new external_value(PARAM_RAW, 'Course format option value.'),
2477 'Additional options for particular course format.', VALUE_OPTIONAL
2480 $coursestructure = array_merge($coursestructure, $extra);
2482 return new external_single_structure($coursestructure);
2486 * Returns description of method result value
2488 * @return external_description
2489 * @since Moodle 3.0
2491 public static function search_courses_returns() {
2492 return new external_single_structure(
2493 array(
2494 'total' => new external_value(PARAM_INT, 'total course count'),
2495 'courses' => new external_multiple_structure(self::get_course_structure(), 'course'),
2496 'warnings' => new external_warnings()
2502 * Returns description of method parameters
2504 * @return external_function_parameters
2505 * @since Moodle 3.0
2507 public static function get_course_module_parameters() {
2508 return new external_function_parameters(
2509 array(
2510 'cmid' => new external_value(PARAM_INT, 'The course module id')
2516 * Return information about a course module.
2518 * @param int $cmid the course module id
2519 * @return array of warnings and the course module
2520 * @since Moodle 3.0
2521 * @throws moodle_exception
2523 public static function get_course_module($cmid) {
2524 global $CFG, $DB;
2526 $params = self::validate_parameters(self::get_course_module_parameters(), array('cmid' => $cmid));
2527 $warnings = array();
2529 $cm = get_coursemodule_from_id(null, $params['cmid'], 0, true, MUST_EXIST);
2530 $context = context_module::instance($cm->id);
2531 self::validate_context($context);
2533 // If the user has permissions to manage the activity, return all the information.
2534 if (has_capability('moodle/course:manageactivities', $context)) {
2535 require_once($CFG->dirroot . '/course/modlib.php');
2536 require_once($CFG->libdir . '/gradelib.php');
2538 $info = $cm;
2539 // Get the extra information: grade, advanced grading and outcomes data.
2540 $course = get_course($cm->course);
2541 list($newcm, $newcontext, $module, $extrainfo, $cw) = get_moduleinfo_data($cm, $course);
2542 // Grades.
2543 $gradeinfo = array('grade', 'gradepass', 'gradecat');
2544 foreach ($gradeinfo as $gfield) {
2545 if (isset($extrainfo->{$gfield})) {
2546 $info->{$gfield} = $extrainfo->{$gfield};
2549 if (isset($extrainfo->grade) and $extrainfo->grade < 0) {
2550 $info->scale = $DB->get_field('scale', 'scale', array('id' => abs($extrainfo->grade)));
2552 // Advanced grading.
2553 if (isset($extrainfo->_advancedgradingdata)) {
2554 $info->advancedgrading = array();
2555 foreach ($extrainfo as $key => $val) {
2556 if (strpos($key, 'advancedgradingmethod_') === 0) {
2557 $info->advancedgrading[] = array(
2558 'area' => str_replace('advancedgradingmethod_', '', $key),
2559 'method' => $val
2564 // Outcomes.
2565 foreach ($extrainfo as $key => $val) {
2566 if (strpos($key, 'outcome_') === 0) {
2567 if (!isset($info->outcomes)) {
2568 $info->outcomes = array();
2570 $id = str_replace('outcome_', '', $key);
2571 $outcome = grade_outcome::fetch(array('id' => $id));
2572 $scaleitems = $outcome->load_scale();
2573 $info->outcomes[] = array(
2574 'id' => $id,
2575 'name' => external_format_string($outcome->get_name(), $context->id),
2576 'scale' => $scaleitems->scale
2580 } else {
2581 // Return information is safe to show to any user.
2582 $info = new stdClass();
2583 $info->id = $cm->id;
2584 $info->course = $cm->course;
2585 $info->module = $cm->module;
2586 $info->modname = $cm->modname;
2587 $info->instance = $cm->instance;
2588 $info->section = $cm->section;
2589 $info->sectionnum = $cm->sectionnum;
2590 $info->groupmode = $cm->groupmode;
2591 $info->groupingid = $cm->groupingid;
2592 $info->completion = $cm->completion;
2594 // Format name.
2595 $info->name = external_format_string($cm->name, $context->id);
2596 $result = array();
2597 $result['cm'] = $info;
2598 $result['warnings'] = $warnings;
2599 return $result;
2603 * Returns description of method result value
2605 * @return external_description
2606 * @since Moodle 3.0
2608 public static function get_course_module_returns() {
2609 return new external_single_structure(
2610 array(
2611 'cm' => new external_single_structure(
2612 array(
2613 'id' => new external_value(PARAM_INT, 'The course module id'),
2614 'course' => new external_value(PARAM_INT, 'The course id'),
2615 'module' => new external_value(PARAM_INT, 'The module type id'),
2616 'name' => new external_value(PARAM_RAW, 'The activity name'),
2617 'modname' => new external_value(PARAM_COMPONENT, 'The module component name (forum, assign, etc..)'),
2618 'instance' => new external_value(PARAM_INT, 'The activity instance id'),
2619 'section' => new external_value(PARAM_INT, 'The module section id'),
2620 'sectionnum' => new external_value(PARAM_INT, 'The module section number'),
2621 'groupmode' => new external_value(PARAM_INT, 'Group mode'),
2622 'groupingid' => new external_value(PARAM_INT, 'Grouping id'),
2623 'completion' => new external_value(PARAM_INT, 'If completion is enabled'),
2624 'idnumber' => new external_value(PARAM_RAW, 'Module id number', VALUE_OPTIONAL),
2625 'added' => new external_value(PARAM_INT, 'Time added', VALUE_OPTIONAL),
2626 'score' => new external_value(PARAM_INT, 'Score', VALUE_OPTIONAL),
2627 'indent' => new external_value(PARAM_INT, 'Indentation', VALUE_OPTIONAL),
2628 'visible' => new external_value(PARAM_INT, 'If visible', VALUE_OPTIONAL),
2629 'visibleoncoursepage' => new external_value(PARAM_INT, 'If visible on course page', VALUE_OPTIONAL),
2630 'visibleold' => new external_value(PARAM_INT, 'Visible old', VALUE_OPTIONAL),
2631 'completiongradeitemnumber' => new external_value(PARAM_INT, 'Completion grade item', VALUE_OPTIONAL),
2632 'completionview' => new external_value(PARAM_INT, 'Completion view setting', VALUE_OPTIONAL),
2633 'completionexpected' => new external_value(PARAM_INT, 'Completion time expected', VALUE_OPTIONAL),
2634 'showdescription' => new external_value(PARAM_INT, 'If the description is showed', VALUE_OPTIONAL),
2635 'availability' => new external_value(PARAM_RAW, 'Availability settings', VALUE_OPTIONAL),
2636 'grade' => new external_value(PARAM_FLOAT, 'Grade (max value or scale id)', VALUE_OPTIONAL),
2637 'scale' => new external_value(PARAM_TEXT, 'Scale items (if used)', VALUE_OPTIONAL),
2638 'gradepass' => new external_value(PARAM_RAW, 'Grade to pass (float)', VALUE_OPTIONAL),
2639 'gradecat' => new external_value(PARAM_INT, 'Grade category', VALUE_OPTIONAL),
2640 'advancedgrading' => new external_multiple_structure(
2641 new external_single_structure(
2642 array(
2643 'area' => new external_value(PARAM_AREA, 'Gradable area name'),
2644 'method' => new external_value(PARAM_COMPONENT, 'Grading method'),
2647 'Advanced grading settings', VALUE_OPTIONAL
2649 'outcomes' => new external_multiple_structure(
2650 new external_single_structure(
2651 array(
2652 'id' => new external_value(PARAM_ALPHANUMEXT, 'Outcome id'),
2653 'name' => new external_value(PARAM_TEXT, 'Outcome full name'),
2654 'scale' => new external_value(PARAM_TEXT, 'Scale items')
2657 'Outcomes information', VALUE_OPTIONAL
2661 'warnings' => new external_warnings()
2667 * Returns description of method parameters
2669 * @return external_function_parameters
2670 * @since Moodle 3.0
2672 public static function get_course_module_by_instance_parameters() {
2673 return new external_function_parameters(
2674 array(
2675 'module' => new external_value(PARAM_COMPONENT, 'The module name'),
2676 'instance' => new external_value(PARAM_INT, 'The module instance id')
2682 * Return information about a course module.
2684 * @param string $module the module name
2685 * @param int $instance the activity instance id
2686 * @return array of warnings and the course module
2687 * @since Moodle 3.0
2688 * @throws moodle_exception
2690 public static function get_course_module_by_instance($module, $instance) {
2692 $params = self::validate_parameters(self::get_course_module_by_instance_parameters(),
2693 array(
2694 'module' => $module,
2695 'instance' => $instance,
2698 $warnings = array();
2699 $cm = get_coursemodule_from_instance($params['module'], $params['instance'], 0, false, MUST_EXIST);
2701 return self::get_course_module($cm->id);
2705 * Returns description of method result value
2707 * @return external_description
2708 * @since Moodle 3.0
2710 public static function get_course_module_by_instance_returns() {
2711 return self::get_course_module_returns();
2715 * Returns description of method parameters
2717 * @deprecated since 3.3
2718 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
2719 * @return external_function_parameters
2720 * @since Moodle 3.2
2722 public static function get_activities_overview_parameters() {
2723 return new external_function_parameters(
2724 array(
2725 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2731 * Return activities overview for the given courses.
2733 * @deprecated since 3.3
2734 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
2735 * @param array $courseids a list of course ids
2736 * @return array of warnings and the activities overview
2737 * @since Moodle 3.2
2738 * @throws moodle_exception
2740 public static function get_activities_overview($courseids) {
2741 global $USER;
2743 // Parameter validation.
2744 $params = self::validate_parameters(self::get_activities_overview_parameters(), array('courseids' => $courseids));
2745 $courseoverviews = array();
2747 list($courses, $warnings) = external_util::validate_courses($params['courseids']);
2749 if (!empty($courses)) {
2750 // Add lastaccess to each course (required by print_overview function).
2751 // We need the complete user data, the ws server does not load a complete one.
2752 $user = get_complete_user_data('id', $USER->id);
2753 foreach ($courses as $course) {
2754 if (isset($user->lastcourseaccess[$course->id])) {
2755 $course->lastaccess = $user->lastcourseaccess[$course->id];
2756 } else {
2757 $course->lastaccess = 0;
2761 $overviews = array();
2762 if ($modules = get_plugin_list_with_function('mod', 'print_overview')) {
2763 foreach ($modules as $fname) {
2764 $fname($courses, $overviews);
2768 // Format output.
2769 foreach ($overviews as $courseid => $modules) {
2770 $courseoverviews[$courseid]['id'] = $courseid;
2771 $courseoverviews[$courseid]['overviews'] = array();
2773 foreach ($modules as $modname => $overviewtext) {
2774 $courseoverviews[$courseid]['overviews'][] = array(
2775 'module' => $modname,
2776 'overviewtext' => $overviewtext // This text doesn't need formatting.
2782 $result = array(
2783 'courses' => $courseoverviews,
2784 'warnings' => $warnings
2786 return $result;
2790 * Returns description of method result value
2792 * @deprecated since 3.3
2793 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
2794 * @return external_description
2795 * @since Moodle 3.2
2797 public static function get_activities_overview_returns() {
2798 return new external_single_structure(
2799 array(
2800 'courses' => new external_multiple_structure(
2801 new external_single_structure(
2802 array(
2803 'id' => new external_value(PARAM_INT, 'Course id'),
2804 'overviews' => new external_multiple_structure(
2805 new external_single_structure(
2806 array(
2807 'module' => new external_value(PARAM_PLUGIN, 'Module name'),
2808 'overviewtext' => new external_value(PARAM_RAW, 'Overview text'),
2813 ), 'List of courses'
2815 'warnings' => new external_warnings()
2821 * Marking the method as deprecated.
2823 * @return bool
2825 public static function get_activities_overview_is_deprecated() {
2826 return true;
2830 * Returns description of method parameters
2832 * @return external_function_parameters
2833 * @since Moodle 3.2
2835 public static function get_user_navigation_options_parameters() {
2836 return new external_function_parameters(
2837 array(
2838 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2844 * Return a list of navigation options in a set of courses that are avaialable or not for the current user.
2846 * @param array $courseids a list of course ids
2847 * @return array of warnings and the options availability
2848 * @since Moodle 3.2
2849 * @throws moodle_exception
2851 public static function get_user_navigation_options($courseids) {
2852 global $CFG;
2853 require_once($CFG->dirroot . '/course/lib.php');
2855 // Parameter validation.
2856 $params = self::validate_parameters(self::get_user_navigation_options_parameters(), array('courseids' => $courseids));
2857 $courseoptions = array();
2859 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
2861 if (!empty($courses)) {
2862 foreach ($courses as $course) {
2863 // Fix the context for the frontpage.
2864 if ($course->id == SITEID) {
2865 $course->context = context_system::instance();
2867 $navoptions = course_get_user_navigation_options($course->context, $course);
2868 $options = array();
2869 foreach ($navoptions as $name => $available) {
2870 $options[] = array(
2871 'name' => $name,
2872 'available' => $available,
2876 $courseoptions[] = array(
2877 'id' => $course->id,
2878 'options' => $options
2883 $result = array(
2884 'courses' => $courseoptions,
2885 'warnings' => $warnings
2887 return $result;
2891 * Returns description of method result value
2893 * @return external_description
2894 * @since Moodle 3.2
2896 public static function get_user_navigation_options_returns() {
2897 return new external_single_structure(
2898 array(
2899 'courses' => new external_multiple_structure(
2900 new external_single_structure(
2901 array(
2902 'id' => new external_value(PARAM_INT, 'Course id'),
2903 'options' => new external_multiple_structure(
2904 new external_single_structure(
2905 array(
2906 'name' => new external_value(PARAM_ALPHANUMEXT, 'Option name'),
2907 'available' => new external_value(PARAM_BOOL, 'Whether the option is available or not'),
2912 ), 'List of courses'
2914 'warnings' => new external_warnings()
2920 * Returns description of method parameters
2922 * @return external_function_parameters
2923 * @since Moodle 3.2
2925 public static function get_user_administration_options_parameters() {
2926 return new external_function_parameters(
2927 array(
2928 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2934 * Return a list of administration options in a set of courses that are available or not for the current user.
2936 * @param array $courseids a list of course ids
2937 * @return array of warnings and the options availability
2938 * @since Moodle 3.2
2939 * @throws moodle_exception
2941 public static function get_user_administration_options($courseids) {
2942 global $CFG;
2943 require_once($CFG->dirroot . '/course/lib.php');
2945 // Parameter validation.
2946 $params = self::validate_parameters(self::get_user_administration_options_parameters(), array('courseids' => $courseids));
2947 $courseoptions = array();
2949 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
2951 if (!empty($courses)) {
2952 foreach ($courses as $course) {
2953 $adminoptions = course_get_user_administration_options($course, $course->context);
2954 $options = array();
2955 foreach ($adminoptions as $name => $available) {
2956 $options[] = array(
2957 'name' => $name,
2958 'available' => $available,
2962 $courseoptions[] = array(
2963 'id' => $course->id,
2964 'options' => $options
2969 $result = array(
2970 'courses' => $courseoptions,
2971 'warnings' => $warnings
2973 return $result;
2977 * Returns description of method result value
2979 * @return external_description
2980 * @since Moodle 3.2
2982 public static function get_user_administration_options_returns() {
2983 return self::get_user_navigation_options_returns();
2987 * Returns description of method parameters
2989 * @return external_function_parameters
2990 * @since Moodle 3.2
2992 public static function get_courses_by_field_parameters() {
2993 return new external_function_parameters(
2994 array(
2995 'field' => new external_value(PARAM_ALPHA, 'The field to search can be left empty for all courses or:
2996 id: course id
2997 ids: comma separated course ids
2998 shortname: course short name
2999 idnumber: course id number
3000 category: category id the course belongs to
3001 ', VALUE_DEFAULT, ''),
3002 'value' => new external_value(PARAM_RAW, 'The value to match', VALUE_DEFAULT, '')
3009 * Get courses matching a specific field (id/s, shortname, idnumber, category)
3011 * @param string $field field name to search, or empty for all courses
3012 * @param string $value value to search
3013 * @return array list of courses and warnings
3014 * @throws invalid_parameter_exception
3015 * @since Moodle 3.2
3017 public static function get_courses_by_field($field = '', $value = '') {
3018 global $DB, $CFG;
3019 require_once($CFG->libdir . '/coursecatlib.php');
3020 require_once($CFG->libdir . '/filterlib.php');
3022 $params = self::validate_parameters(self::get_courses_by_field_parameters(),
3023 array(
3024 'field' => $field,
3025 'value' => $value,
3028 $warnings = array();
3030 if (empty($params['field'])) {
3031 $courses = $DB->get_records('course', null, 'id ASC');
3032 } else {
3033 switch ($params['field']) {
3034 case 'id':
3035 case 'category':
3036 $value = clean_param($params['value'], PARAM_INT);
3037 break;
3038 case 'ids':
3039 $value = clean_param($params['value'], PARAM_SEQUENCE);
3040 break;
3041 case 'shortname':
3042 $value = clean_param($params['value'], PARAM_TEXT);
3043 break;
3044 case 'idnumber':
3045 $value = clean_param($params['value'], PARAM_RAW);
3046 break;
3047 default:
3048 throw new invalid_parameter_exception('Invalid field name');
3051 if ($params['field'] === 'ids') {
3052 $courses = $DB->get_records_list('course', 'id', explode(',', $value), 'id ASC');
3053 } else {
3054 $courses = $DB->get_records('course', array($params['field'] => $value), 'id ASC');
3058 $coursesdata = array();
3059 foreach ($courses as $course) {
3060 $context = context_course::instance($course->id);
3061 $canupdatecourse = has_capability('moodle/course:update', $context);
3062 $canviewhiddencourses = has_capability('moodle/course:viewhiddencourses', $context);
3064 // Check if the course is visible in the site for the user.
3065 if (!$course->visible and !$canviewhiddencourses and !$canupdatecourse) {
3066 continue;
3068 // Get the public course information, even if we are not enrolled.
3069 $courseinlist = new course_in_list($course);
3070 $coursesdata[$course->id] = self::get_course_public_information($courseinlist, $context);
3072 // Now, check if we have access to the course.
3073 try {
3074 self::validate_context($context);
3075 } catch (Exception $e) {
3076 continue;
3078 // Return information for any user that can access the course.
3079 $coursefields = array('format', 'showgrades', 'newsitems', 'startdate', 'enddate', 'maxbytes', 'showreports', 'visible',
3080 'groupmode', 'groupmodeforce', 'defaultgroupingid', 'enablecompletion', 'completionnotify', 'lang', 'theme',
3081 'marker');
3083 // Course filters.
3084 $coursesdata[$course->id]['filters'] = filter_get_available_in_context($context);
3086 // Information for managers only.
3087 if ($canupdatecourse) {
3088 $managerfields = array('idnumber', 'legacyfiles', 'calendartype', 'timecreated', 'timemodified', 'requested',
3089 'cacherev');
3090 $coursefields = array_merge($coursefields, $managerfields);
3093 // Populate fields.
3094 foreach ($coursefields as $field) {
3095 $coursesdata[$course->id][$field] = $course->{$field};
3098 // Clean lang and auth fields for external functions (it may content uninstalled themes or language packs).
3099 if (isset($coursesdata[$course->id]['theme'])) {
3100 $coursesdata[$course->id]['theme'] = clean_param($coursesdata[$course->id]['theme'], PARAM_THEME);
3102 if (isset($coursesdata[$course->id]['lang'])) {
3103 $coursesdata[$course->id]['lang'] = clean_param($coursesdata[$course->id]['lang'], PARAM_LANG);
3106 $courseformatoptions = course_get_format($course)->get_config_for_external();
3107 foreach ($courseformatoptions as $key => $value) {
3108 $coursesdata[$course->id]['courseformatoptions'][] = array(
3109 'name' => $key,
3110 'value' => $value
3115 return array(
3116 'courses' => $coursesdata,
3117 'warnings' => $warnings
3122 * Returns description of method result value
3124 * @return external_description
3125 * @since Moodle 3.2
3127 public static function get_courses_by_field_returns() {
3128 // Course structure, including not only public viewable fields.
3129 return new external_single_structure(
3130 array(
3131 'courses' => new external_multiple_structure(self::get_course_structure(false), 'Course'),
3132 'warnings' => new external_warnings()
3138 * Returns description of method parameters
3140 * @return external_function_parameters
3141 * @since Moodle 3.2
3143 public static function check_updates_parameters() {
3144 return new external_function_parameters(
3145 array(
3146 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3147 'tocheck' => new external_multiple_structure(
3148 new external_single_structure(
3149 array(
3150 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level for the file location.
3151 Only module supported right now.'),
3152 'id' => new external_value(PARAM_INT, 'Context instance id'),
3153 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3156 'Instances to check'
3158 'filter' => new external_multiple_structure(
3159 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3160 gradeitems, outcomes'),
3161 'Check only for updates in these areas', VALUE_DEFAULT, array()
3168 * Check if there is updates affecting the user for the given course and contexts.
3169 * Right now only modules are supported.
3170 * This WS calls mod_check_updates_since for each module to check if there is any update the user should we aware of.
3172 * @param int $courseid the list of modules to check
3173 * @param array $tocheck the list of modules to check
3174 * @param array $filter check only for updates in these areas
3175 * @return array list of updates and warnings
3176 * @throws moodle_exception
3177 * @since Moodle 3.2
3179 public static function check_updates($courseid, $tocheck, $filter = array()) {
3180 global $CFG, $DB;
3181 require_once($CFG->dirroot . "/course/lib.php");
3183 $params = self::validate_parameters(
3184 self::check_updates_parameters(),
3185 array(
3186 'courseid' => $courseid,
3187 'tocheck' => $tocheck,
3188 'filter' => $filter,
3192 $course = get_course($params['courseid']);
3193 $context = context_course::instance($course->id);
3194 self::validate_context($context);
3196 list($instances, $warnings) = course_check_updates($course, $params['tocheck'], $filter);
3198 $instancesformatted = array();
3199 foreach ($instances as $instance) {
3200 $updates = array();
3201 foreach ($instance['updates'] as $name => $data) {
3202 if (empty($data->updated)) {
3203 continue;
3205 $updatedata = array(
3206 'name' => $name,
3208 if (!empty($data->timeupdated)) {
3209 $updatedata['timeupdated'] = $data->timeupdated;
3211 if (!empty($data->itemids)) {
3212 $updatedata['itemids'] = $data->itemids;
3214 $updates[] = $updatedata;
3216 if (!empty($updates)) {
3217 $instancesformatted[] = array(
3218 'contextlevel' => $instance['contextlevel'],
3219 'id' => $instance['id'],
3220 'updates' => $updates
3225 return array(
3226 'instances' => $instancesformatted,
3227 'warnings' => $warnings
3232 * Returns description of method result value
3234 * @return external_description
3235 * @since Moodle 3.2
3237 public static function check_updates_returns() {
3238 return new external_single_structure(
3239 array(
3240 'instances' => new external_multiple_structure(
3241 new external_single_structure(
3242 array(
3243 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level'),
3244 'id' => new external_value(PARAM_INT, 'Instance id'),
3245 'updates' => new external_multiple_structure(
3246 new external_single_structure(
3247 array(
3248 'name' => new external_value(PARAM_ALPHANUMEXT, 'Name of the area updated.'),
3249 'timeupdated' => new external_value(PARAM_INT, 'Last time was updated', VALUE_OPTIONAL),
3250 'itemids' => new external_multiple_structure(
3251 new external_value(PARAM_INT, 'Instance id'),
3252 'The ids of the items updated',
3253 VALUE_OPTIONAL
3261 'warnings' => new external_warnings()
3267 * Returns description of method parameters
3269 * @return external_function_parameters
3270 * @since Moodle 3.3
3272 public static function get_updates_since_parameters() {
3273 return new external_function_parameters(
3274 array(
3275 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3276 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3277 'filter' => new external_multiple_structure(
3278 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3279 gradeitems, outcomes'),
3280 'Check only for updates in these areas', VALUE_DEFAULT, array()
3287 * Check if there are updates affecting the user for the given course since the given time stamp.
3289 * This function is a wrapper of self::check_updates for retrieving all the updates since a given time for all the activities.
3291 * @param int $courseid the list of modules to check
3292 * @param int $since check updates since this time stamp
3293 * @param array $filter check only for updates in these areas
3294 * @return array list of updates and warnings
3295 * @throws moodle_exception
3296 * @since Moodle 3.3
3298 public static function get_updates_since($courseid, $since, $filter = array()) {
3299 global $CFG, $DB;
3301 $params = self::validate_parameters(
3302 self::get_updates_since_parameters(),
3303 array(
3304 'courseid' => $courseid,
3305 'since' => $since,
3306 'filter' => $filter,
3310 $course = get_course($params['courseid']);
3311 $modinfo = get_fast_modinfo($course);
3312 $tocheck = array();
3314 // Retrieve all the visible course modules for the current user.
3315 $cms = $modinfo->get_cms();
3316 foreach ($cms as $cm) {
3317 if (!$cm->uservisible) {
3318 continue;
3320 $tocheck[] = array(
3321 'id' => $cm->id,
3322 'contextlevel' => 'module',
3323 'since' => $params['since'],
3327 return self::check_updates($course->id, $tocheck, $params['filter']);
3331 * Returns description of method result value
3333 * @return external_description
3334 * @since Moodle 3.3
3336 public static function get_updates_since_returns() {
3337 return self::check_updates_returns();
3341 * Parameters for function edit_module()
3343 * @since Moodle 3.3
3344 * @return external_function_parameters
3346 public static function edit_module_parameters() {
3347 return new external_function_parameters(
3348 array(
3349 'action' => new external_value(PARAM_ALPHA,
3350 'action: hide, show, stealth, duplicate, delete, moveleft, moveright, group...', VALUE_REQUIRED),
3351 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3352 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3357 * Performs one of the edit module actions and return new html for AJAX
3359 * Returns html to replace the current module html with, for example:
3360 * - empty string for "delete" action,
3361 * - two modules html for "duplicate" action
3362 * - updated module html for everything else
3364 * Throws exception if operation is not permitted/possible
3366 * @since Moodle 3.3
3367 * @param string $action
3368 * @param int $id
3369 * @param null|int $sectionreturn
3370 * @return string
3372 public static function edit_module($action, $id, $sectionreturn = null) {
3373 global $PAGE, $DB;
3374 // Validate and normalize parameters.
3375 $params = self::validate_parameters(self::edit_module_parameters(),
3376 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3377 $action = $params['action'];
3378 $id = $params['id'];
3379 $sectionreturn = $params['sectionreturn'];
3381 list($course, $cm) = get_course_and_cm_from_cmid($id);
3382 $modcontext = context_module::instance($cm->id);
3383 $coursecontext = context_course::instance($course->id);
3384 self::validate_context($modcontext);
3385 $courserenderer = $PAGE->get_renderer('core', 'course');
3386 $completioninfo = new completion_info($course);
3388 switch($action) {
3389 case 'hide':
3390 case 'show':
3391 case 'stealth':
3392 require_capability('moodle/course:activityvisibility', $modcontext);
3393 $visible = ($action === 'hide') ? 0 : 1;
3394 $visibleoncoursepage = ($action === 'stealth') ? 0 : 1;
3395 set_coursemodule_visible($id, $visible, $visibleoncoursepage);
3396 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3397 break;
3398 case 'duplicate':
3399 require_capability('moodle/course:manageactivities', $coursecontext);
3400 require_capability('moodle/backup:backuptargetimport', $coursecontext);
3401 require_capability('moodle/restore:restoretargetimport', $coursecontext);
3402 if (!course_allowed_module($course, $cm->modname)) {
3403 throw new moodle_exception('No permission to create that activity');
3405 if ($newcm = duplicate_module($course, $cm)) {
3406 $cm = get_fast_modinfo($course)->get_cm($id);
3407 $newcm = get_fast_modinfo($course)->get_cm($newcm->id);
3408 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn) .
3409 $courserenderer->course_section_cm_list_item($course, $completioninfo, $newcm, $sectionreturn);
3411 break;
3412 case 'groupsseparate':
3413 case 'groupsvisible':
3414 case 'groupsnone':
3415 require_capability('moodle/course:manageactivities', $modcontext);
3416 if ($action === 'groupsseparate') {
3417 $newgroupmode = SEPARATEGROUPS;
3418 } else if ($action === 'groupsvisible') {
3419 $newgroupmode = VISIBLEGROUPS;
3420 } else {
3421 $newgroupmode = NOGROUPS;
3423 if (set_coursemodule_groupmode($cm->id, $newgroupmode)) {
3424 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3426 break;
3427 case 'moveleft':
3428 case 'moveright':
3429 require_capability('moodle/course:manageactivities', $modcontext);
3430 $indent = $cm->indent + (($action === 'moveright') ? 1 : -1);
3431 if ($cm->indent >= 0) {
3432 $DB->update_record('course_modules', array('id' => $cm->id, 'indent' => $indent));
3433 rebuild_course_cache($cm->course);
3435 break;
3436 case 'delete':
3437 require_capability('moodle/course:manageactivities', $modcontext);
3438 course_delete_module($cm->id, true);
3439 return '';
3440 default:
3441 throw new coding_exception('Unrecognised action');
3444 $cm = get_fast_modinfo($course)->get_cm($id);
3445 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn);
3449 * Return structure for edit_module()
3451 * @since Moodle 3.3
3452 * @return external_description
3454 public static function edit_module_returns() {
3455 return new external_value(PARAM_RAW, 'html to replace the current module with');
3459 * Parameters for function get_module()
3461 * @since Moodle 3.3
3462 * @return external_function_parameters
3464 public static function get_module_parameters() {
3465 return new external_function_parameters(
3466 array(
3467 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3468 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3473 * Returns html for displaying one activity module on course page
3475 * @since Moodle 3.3
3476 * @param int $id
3477 * @param null|int $sectionreturn
3478 * @return string
3480 public static function get_module($id, $sectionreturn = null) {
3481 global $PAGE;
3482 // Validate and normalize parameters.
3483 $params = self::validate_parameters(self::get_module_parameters(),
3484 array('id' => $id, 'sectionreturn' => $sectionreturn));
3485 $id = $params['id'];
3486 $sectionreturn = $params['sectionreturn'];
3488 // Validate access to the course (note, this is html for the course view page, we don't validate access to the module).
3489 list($course, $cm) = get_course_and_cm_from_cmid($id);
3490 self::validate_context(context_course::instance($course->id));
3492 $courserenderer = $PAGE->get_renderer('core', 'course');
3493 $completioninfo = new completion_info($course);
3494 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn);
3498 * Return structure for edit_module()
3500 * @since Moodle 3.3
3501 * @return external_description
3503 public static function get_module_returns() {
3504 return new external_value(PARAM_RAW, 'html to replace the current module with');
3508 * Parameters for function edit_section()
3510 * @since Moodle 3.3
3511 * @return external_function_parameters
3513 public static function edit_section_parameters() {
3514 return new external_function_parameters(
3515 array(
3516 'action' => new external_value(PARAM_ALPHA, 'action: hide, show, stealth, setmarker, removemarker', VALUE_REQUIRED),
3517 'id' => new external_value(PARAM_INT, 'course section id', VALUE_REQUIRED),
3518 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3523 * Performs one of the edit section actions
3525 * @since Moodle 3.3
3526 * @param string $action
3527 * @param int $id section id
3528 * @param int $sectionreturn section to return to
3529 * @return string
3531 public static function edit_section($action, $id, $sectionreturn) {
3532 global $DB;
3533 // Validate and normalize parameters.
3534 $params = self::validate_parameters(self::edit_section_parameters(),
3535 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3536 $action = $params['action'];
3537 $id = $params['id'];
3538 $sr = $params['sectionreturn'];
3540 $section = $DB->get_record('course_sections', array('id' => $id), '*', MUST_EXIST);
3541 $coursecontext = context_course::instance($section->course);
3542 self::validate_context($coursecontext);
3544 $rv = course_get_format($section->course)->section_action($section, $action, $sectionreturn);
3545 if ($rv) {
3546 return json_encode($rv);
3547 } else {
3548 return null;
3553 * Return structure for edit_section()
3555 * @since Moodle 3.3
3556 * @return external_description
3558 public static function edit_section_returns() {
3559 return new external_value(PARAM_RAW, 'Additional data for javascript (JSON-encoded string)');