Merge branch 'MDL-62663' of https://github.com/andrewhancox/moodle
[moodle.git] / course / externallib.php
blob07f2d9fb927e4465c7bad4330e8be6bc425c670c
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 $course['maxbytes'] = get_max_upload_file_size($CFG->maxbytes, $course['maxbytes']);
947 if (!empty($course['courseformatoptions'])) {
948 foreach ($course['courseformatoptions'] as $option) {
949 if (isset($option['name']) && isset($option['value'])) {
950 $course[$option['name']] = $option['value'];
955 // Update course if user has all required capabilities.
956 update_course((object) $course);
957 } catch (Exception $e) {
958 $warning = array();
959 $warning['item'] = 'course';
960 $warning['itemid'] = $course['id'];
961 if ($e instanceof moodle_exception) {
962 $warning['warningcode'] = $e->errorcode;
963 } else {
964 $warning['warningcode'] = $e->getCode();
966 $warning['message'] = $e->getMessage();
967 $warnings[] = $warning;
971 $result = array();
972 $result['warnings'] = $warnings;
973 return $result;
977 * Returns description of method result value
979 * @return external_description
980 * @since Moodle 2.5
982 public static function update_courses_returns() {
983 return new external_single_structure(
984 array(
985 'warnings' => new external_warnings()
991 * Returns description of method parameters
993 * @return external_function_parameters
994 * @since Moodle 2.2
996 public static function delete_courses_parameters() {
997 return new external_function_parameters(
998 array(
999 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'course ID')),
1005 * Delete courses
1007 * @param array $courseids A list of course ids
1008 * @since Moodle 2.2
1010 public static function delete_courses($courseids) {
1011 global $CFG, $DB;
1012 require_once($CFG->dirroot."/course/lib.php");
1014 // Parameter validation.
1015 $params = self::validate_parameters(self::delete_courses_parameters(), array('courseids'=>$courseids));
1017 $warnings = array();
1019 foreach ($params['courseids'] as $courseid) {
1020 $course = $DB->get_record('course', array('id' => $courseid));
1022 if ($course === false) {
1023 $warnings[] = array(
1024 'item' => 'course',
1025 'itemid' => $courseid,
1026 'warningcode' => 'unknowncourseidnumber',
1027 'message' => 'Unknown course ID ' . $courseid
1029 continue;
1032 // Check if the context is valid.
1033 $coursecontext = context_course::instance($course->id);
1034 self::validate_context($coursecontext);
1036 // Check if the current user has permission.
1037 if (!can_delete_course($courseid)) {
1038 $warnings[] = array(
1039 'item' => 'course',
1040 'itemid' => $courseid,
1041 'warningcode' => 'cannotdeletecourse',
1042 'message' => 'You do not have the permission to delete this course' . $courseid
1044 continue;
1047 if (delete_course($course, false) === false) {
1048 $warnings[] = array(
1049 'item' => 'course',
1050 'itemid' => $courseid,
1051 'warningcode' => 'cannotdeletecategorycourse',
1052 'message' => 'Course ' . $courseid . ' failed to be deleted'
1054 continue;
1058 fix_course_sortorder();
1060 return array('warnings' => $warnings);
1064 * Returns description of method result value
1066 * @return external_description
1067 * @since Moodle 2.2
1069 public static function delete_courses_returns() {
1070 return new external_single_structure(
1071 array(
1072 'warnings' => new external_warnings()
1078 * Returns description of method parameters
1080 * @return external_function_parameters
1081 * @since Moodle 2.3
1083 public static function duplicate_course_parameters() {
1084 return new external_function_parameters(
1085 array(
1086 'courseid' => new external_value(PARAM_INT, 'course to duplicate id'),
1087 'fullname' => new external_value(PARAM_TEXT, 'duplicated course full name'),
1088 'shortname' => new external_value(PARAM_TEXT, 'duplicated course short name'),
1089 'categoryid' => new external_value(PARAM_INT, 'duplicated course category parent'),
1090 'visible' => new external_value(PARAM_INT, 'duplicated course visible, default to yes', VALUE_DEFAULT, 1),
1091 'options' => new external_multiple_structure(
1092 new external_single_structure(
1093 array(
1094 'name' => new external_value(PARAM_ALPHAEXT, 'The backup option name:
1095 "activities" (int) Include course activites (default to 1 that is equal to yes),
1096 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1097 "filters" (int) Include course filters (default to 1 that is equal to yes),
1098 "users" (int) Include users (default to 0 that is equal to no),
1099 "enrolments" (int) Include enrolment methods (default to 1 - restore only with users),
1100 "role_assignments" (int) Include role assignments (default to 0 that is equal to no),
1101 "comments" (int) Include user comments (default to 0 that is equal to no),
1102 "userscompletion" (int) Include user course completion information (default to 0 that is equal to no),
1103 "logs" (int) Include course logs (default to 0 that is equal to no),
1104 "grade_histories" (int) Include histories (default to 0 that is equal to no)'
1106 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1109 ), VALUE_DEFAULT, array()
1116 * Duplicate a course
1118 * @param int $courseid
1119 * @param string $fullname Duplicated course fullname
1120 * @param string $shortname Duplicated course shortname
1121 * @param int $categoryid Duplicated course parent category id
1122 * @param int $visible Duplicated course availability
1123 * @param array $options List of backup options
1124 * @return array New course info
1125 * @since Moodle 2.3
1127 public static function duplicate_course($courseid, $fullname, $shortname, $categoryid, $visible = 1, $options = array()) {
1128 global $CFG, $USER, $DB;
1129 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1130 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1132 // Parameter validation.
1133 $params = self::validate_parameters(
1134 self::duplicate_course_parameters(),
1135 array(
1136 'courseid' => $courseid,
1137 'fullname' => $fullname,
1138 'shortname' => $shortname,
1139 'categoryid' => $categoryid,
1140 'visible' => $visible,
1141 'options' => $options
1145 // Context validation.
1147 if (! ($course = $DB->get_record('course', array('id'=>$params['courseid'])))) {
1148 throw new moodle_exception('invalidcourseid', 'error');
1151 // Category where duplicated course is going to be created.
1152 $categorycontext = context_coursecat::instance($params['categoryid']);
1153 self::validate_context($categorycontext);
1155 // Course to be duplicated.
1156 $coursecontext = context_course::instance($course->id);
1157 self::validate_context($coursecontext);
1159 $backupdefaults = array(
1160 'activities' => 1,
1161 'blocks' => 1,
1162 'filters' => 1,
1163 'users' => 0,
1164 'enrolments' => backup::ENROL_WITHUSERS,
1165 'role_assignments' => 0,
1166 'comments' => 0,
1167 'userscompletion' => 0,
1168 'logs' => 0,
1169 'grade_histories' => 0
1172 $backupsettings = array();
1173 // Check for backup and restore options.
1174 if (!empty($params['options'])) {
1175 foreach ($params['options'] as $option) {
1177 // Strict check for a correct value (allways 1 or 0, true or false).
1178 $value = clean_param($option['value'], PARAM_INT);
1180 if ($value !== 0 and $value !== 1) {
1181 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1184 if (!isset($backupdefaults[$option['name']])) {
1185 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1188 $backupsettings[$option['name']] = $value;
1192 // Capability checking.
1194 // The backup controller check for this currently, this may be redundant.
1195 require_capability('moodle/course:create', $categorycontext);
1196 require_capability('moodle/restore:restorecourse', $categorycontext);
1197 require_capability('moodle/backup:backupcourse', $coursecontext);
1199 if (!empty($backupsettings['users'])) {
1200 require_capability('moodle/backup:userinfo', $coursecontext);
1201 require_capability('moodle/restore:userinfo', $categorycontext);
1204 // Check if the shortname is used.
1205 if ($foundcourses = $DB->get_records('course', array('shortname'=>$shortname))) {
1206 foreach ($foundcourses as $foundcourse) {
1207 $foundcoursenames[] = $foundcourse->fullname;
1210 $foundcoursenamestring = implode(',', $foundcoursenames);
1211 throw new moodle_exception('shortnametaken', '', '', $foundcoursenamestring);
1214 // Backup the course.
1216 $bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE,
1217 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id);
1219 foreach ($backupsettings as $name => $value) {
1220 if ($setting = $bc->get_plan()->get_setting($name)) {
1221 $bc->get_plan()->get_setting($name)->set_value($value);
1225 $backupid = $bc->get_backupid();
1226 $backupbasepath = $bc->get_plan()->get_basepath();
1228 $bc->execute_plan();
1229 $results = $bc->get_results();
1230 $file = $results['backup_destination'];
1232 $bc->destroy();
1234 // Restore the backup immediately.
1236 // Check if we need to unzip the file because the backup temp dir does not contains backup files.
1237 if (!file_exists($backupbasepath . "/moodle_backup.xml")) {
1238 $file->extract_to_pathname(get_file_packer('application/vnd.moodle.backup'), $backupbasepath);
1241 // Create new course.
1242 $newcourseid = restore_dbops::create_new_course($params['fullname'], $params['shortname'], $params['categoryid']);
1244 $rc = new restore_controller($backupid, $newcourseid,
1245 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id, backup::TARGET_NEW_COURSE);
1247 foreach ($backupsettings as $name => $value) {
1248 $setting = $rc->get_plan()->get_setting($name);
1249 if ($setting->get_status() == backup_setting::NOT_LOCKED) {
1250 $setting->set_value($value);
1254 if (!$rc->execute_precheck()) {
1255 $precheckresults = $rc->get_precheck_results();
1256 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1257 if (empty($CFG->keeptempdirectoriesonbackup)) {
1258 fulldelete($backupbasepath);
1261 $errorinfo = '';
1263 foreach ($precheckresults['errors'] as $error) {
1264 $errorinfo .= $error;
1267 if (array_key_exists('warnings', $precheckresults)) {
1268 foreach ($precheckresults['warnings'] as $warning) {
1269 $errorinfo .= $warning;
1273 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1277 $rc->execute_plan();
1278 $rc->destroy();
1280 $course = $DB->get_record('course', array('id' => $newcourseid), '*', MUST_EXIST);
1281 $course->fullname = $params['fullname'];
1282 $course->shortname = $params['shortname'];
1283 $course->visible = $params['visible'];
1285 // Set shortname and fullname back.
1286 $DB->update_record('course', $course);
1288 if (empty($CFG->keeptempdirectoriesonbackup)) {
1289 fulldelete($backupbasepath);
1292 // Delete the course backup file created by this WebService. Originally located in the course backups area.
1293 $file->delete();
1295 return array('id' => $course->id, 'shortname' => $course->shortname);
1299 * Returns description of method result value
1301 * @return external_description
1302 * @since Moodle 2.3
1304 public static function duplicate_course_returns() {
1305 return new external_single_structure(
1306 array(
1307 'id' => new external_value(PARAM_INT, 'course id'),
1308 'shortname' => new external_value(PARAM_TEXT, 'short name'),
1314 * Returns description of method parameters for import_course
1316 * @return external_function_parameters
1317 * @since Moodle 2.4
1319 public static function import_course_parameters() {
1320 return new external_function_parameters(
1321 array(
1322 'importfrom' => new external_value(PARAM_INT, 'the id of the course we are importing from'),
1323 'importto' => new external_value(PARAM_INT, 'the id of the course we are importing to'),
1324 'deletecontent' => new external_value(PARAM_INT, 'whether to delete the course content where we are importing to (default to 0 = No)', VALUE_DEFAULT, 0),
1325 'options' => new external_multiple_structure(
1326 new external_single_structure(
1327 array(
1328 'name' => new external_value(PARAM_ALPHA, 'The backup option name:
1329 "activities" (int) Include course activites (default to 1 that is equal to yes),
1330 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1331 "filters" (int) Include course filters (default to 1 that is equal to yes)'
1333 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1336 ), VALUE_DEFAULT, array()
1343 * Imports a course
1345 * @param int $importfrom The id of the course we are importing from
1346 * @param int $importto The id of the course we are importing to
1347 * @param bool $deletecontent Whether to delete the course we are importing to content
1348 * @param array $options List of backup options
1349 * @return null
1350 * @since Moodle 2.4
1352 public static function import_course($importfrom, $importto, $deletecontent = 0, $options = array()) {
1353 global $CFG, $USER, $DB;
1354 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1355 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1357 // Parameter validation.
1358 $params = self::validate_parameters(
1359 self::import_course_parameters(),
1360 array(
1361 'importfrom' => $importfrom,
1362 'importto' => $importto,
1363 'deletecontent' => $deletecontent,
1364 'options' => $options
1368 if ($params['deletecontent'] !== 0 and $params['deletecontent'] !== 1) {
1369 throw new moodle_exception('invalidextparam', 'webservice', '', $params['deletecontent']);
1372 // Context validation.
1374 if (! ($importfrom = $DB->get_record('course', array('id'=>$params['importfrom'])))) {
1375 throw new moodle_exception('invalidcourseid', 'error');
1378 if (! ($importto = $DB->get_record('course', array('id'=>$params['importto'])))) {
1379 throw new moodle_exception('invalidcourseid', 'error');
1382 $importfromcontext = context_course::instance($importfrom->id);
1383 self::validate_context($importfromcontext);
1385 $importtocontext = context_course::instance($importto->id);
1386 self::validate_context($importtocontext);
1388 $backupdefaults = array(
1389 'activities' => 1,
1390 'blocks' => 1,
1391 'filters' => 1
1394 $backupsettings = array();
1396 // Check for backup and restore options.
1397 if (!empty($params['options'])) {
1398 foreach ($params['options'] as $option) {
1400 // Strict check for a correct value (allways 1 or 0, true or false).
1401 $value = clean_param($option['value'], PARAM_INT);
1403 if ($value !== 0 and $value !== 1) {
1404 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1407 if (!isset($backupdefaults[$option['name']])) {
1408 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1411 $backupsettings[$option['name']] = $value;
1415 // Capability checking.
1417 require_capability('moodle/backup:backuptargetimport', $importfromcontext);
1418 require_capability('moodle/restore:restoretargetimport', $importtocontext);
1420 $bc = new backup_controller(backup::TYPE_1COURSE, $importfrom->id, backup::FORMAT_MOODLE,
1421 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
1423 foreach ($backupsettings as $name => $value) {
1424 $bc->get_plan()->get_setting($name)->set_value($value);
1427 $backupid = $bc->get_backupid();
1428 $backupbasepath = $bc->get_plan()->get_basepath();
1430 $bc->execute_plan();
1431 $bc->destroy();
1433 // Restore the backup immediately.
1435 // Check if we must delete the contents of the destination course.
1436 if ($params['deletecontent']) {
1437 $restoretarget = backup::TARGET_EXISTING_DELETING;
1438 } else {
1439 $restoretarget = backup::TARGET_EXISTING_ADDING;
1442 $rc = new restore_controller($backupid, $importto->id,
1443 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, $restoretarget);
1445 foreach ($backupsettings as $name => $value) {
1446 $rc->get_plan()->get_setting($name)->set_value($value);
1449 if (!$rc->execute_precheck()) {
1450 $precheckresults = $rc->get_precheck_results();
1451 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1452 if (empty($CFG->keeptempdirectoriesonbackup)) {
1453 fulldelete($backupbasepath);
1456 $errorinfo = '';
1458 foreach ($precheckresults['errors'] as $error) {
1459 $errorinfo .= $error;
1462 if (array_key_exists('warnings', $precheckresults)) {
1463 foreach ($precheckresults['warnings'] as $warning) {
1464 $errorinfo .= $warning;
1468 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1470 } else {
1471 if ($restoretarget == backup::TARGET_EXISTING_DELETING) {
1472 restore_dbops::delete_course_content($importto->id);
1476 $rc->execute_plan();
1477 $rc->destroy();
1479 if (empty($CFG->keeptempdirectoriesonbackup)) {
1480 fulldelete($backupbasepath);
1483 return null;
1487 * Returns description of method result value
1489 * @return external_description
1490 * @since Moodle 2.4
1492 public static function import_course_returns() {
1493 return null;
1497 * Returns description of method parameters
1499 * @return external_function_parameters
1500 * @since Moodle 2.3
1502 public static function get_categories_parameters() {
1503 return new external_function_parameters(
1504 array(
1505 'criteria' => new external_multiple_structure(
1506 new external_single_structure(
1507 array(
1508 'key' => new external_value(PARAM_ALPHA,
1509 'The category column to search, expected keys (value format) are:'.
1510 '"id" (int) the category id,'.
1511 '"ids" (string) category ids separated by commas,'.
1512 '"name" (string) the category name,'.
1513 '"parent" (int) the parent category id,'.
1514 '"idnumber" (string) category idnumber'.
1515 ' - user must have \'moodle/category:manage\' to search on idnumber,'.
1516 '"visible" (int) whether the returned categories must be visible or hidden. If the key is not passed,
1517 then the function return all categories that the user can see.'.
1518 ' - user must have \'moodle/category:manage\' or \'moodle/category:viewhiddencategories\' to search on visible,'.
1519 '"theme" (string) only return the categories having this theme'.
1520 ' - user must have \'moodle/category:manage\' to search on theme'),
1521 'value' => new external_value(PARAM_RAW, 'the value to match')
1523 ), 'criteria', VALUE_DEFAULT, array()
1525 'addsubcategories' => new external_value(PARAM_BOOL, 'return the sub categories infos
1526 (1 - default) otherwise only the category info (0)', VALUE_DEFAULT, 1)
1532 * Get categories
1534 * @param array $criteria Criteria to match the results
1535 * @param booln $addsubcategories obtain only the category (false) or its subcategories (true - default)
1536 * @return array list of categories
1537 * @since Moodle 2.3
1539 public static function get_categories($criteria = array(), $addsubcategories = true) {
1540 global $CFG, $DB;
1541 require_once($CFG->dirroot . "/course/lib.php");
1543 // Validate parameters.
1544 $params = self::validate_parameters(self::get_categories_parameters(),
1545 array('criteria' => $criteria, 'addsubcategories' => $addsubcategories));
1547 // Retrieve the categories.
1548 $categories = array();
1549 if (!empty($params['criteria'])) {
1551 $conditions = array();
1552 $wheres = array();
1553 foreach ($params['criteria'] as $crit) {
1554 $key = trim($crit['key']);
1556 // Trying to avoid duplicate keys.
1557 if (!isset($conditions[$key])) {
1559 $context = context_system::instance();
1560 $value = null;
1561 switch ($key) {
1562 case 'id':
1563 $value = clean_param($crit['value'], PARAM_INT);
1564 $conditions[$key] = $value;
1565 $wheres[] = $key . " = :" . $key;
1566 break;
1568 case 'ids':
1569 $value = clean_param($crit['value'], PARAM_SEQUENCE);
1570 $ids = explode(',', $value);
1571 list($sqlids, $paramids) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED);
1572 $conditions = array_merge($conditions, $paramids);
1573 $wheres[] = 'id ' . $sqlids;
1574 break;
1576 case 'idnumber':
1577 if (has_capability('moodle/category:manage', $context)) {
1578 $value = clean_param($crit['value'], PARAM_RAW);
1579 $conditions[$key] = $value;
1580 $wheres[] = $key . " = :" . $key;
1581 } else {
1582 // We must throw an exception.
1583 // Otherwise the dev client would think no idnumber exists.
1584 throw new moodle_exception('criteriaerror',
1585 'webservice', '', null,
1586 'You don\'t have the permissions to search on the "idnumber" field.');
1588 break;
1590 case 'name':
1591 $value = clean_param($crit['value'], PARAM_TEXT);
1592 $conditions[$key] = $value;
1593 $wheres[] = $key . " = :" . $key;
1594 break;
1596 case 'parent':
1597 $value = clean_param($crit['value'], PARAM_INT);
1598 $conditions[$key] = $value;
1599 $wheres[] = $key . " = :" . $key;
1600 break;
1602 case 'visible':
1603 if (has_capability('moodle/category:viewhiddencategories', $context)) {
1604 $value = clean_param($crit['value'], PARAM_INT);
1605 $conditions[$key] = $value;
1606 $wheres[] = $key . " = :" . $key;
1607 } else {
1608 throw new moodle_exception('criteriaerror',
1609 'webservice', '', null,
1610 'You don\'t have the permissions to search on the "visible" field.');
1612 break;
1614 case 'theme':
1615 if (has_capability('moodle/category:manage', $context)) {
1616 $value = clean_param($crit['value'], PARAM_THEME);
1617 $conditions[$key] = $value;
1618 $wheres[] = $key . " = :" . $key;
1619 } else {
1620 throw new moodle_exception('criteriaerror',
1621 'webservice', '', null,
1622 'You don\'t have the permissions to search on the "theme" field.');
1624 break;
1626 default:
1627 throw new moodle_exception('criteriaerror',
1628 'webservice', '', null,
1629 'You can not search on this criteria: ' . $key);
1634 if (!empty($wheres)) {
1635 $wheres = implode(" AND ", $wheres);
1637 $categories = $DB->get_records_select('course_categories', $wheres, $conditions);
1639 // Retrieve its sub subcategories (all levels).
1640 if ($categories and !empty($params['addsubcategories'])) {
1641 $newcategories = array();
1643 // Check if we required visible/theme checks.
1644 $additionalselect = '';
1645 $additionalparams = array();
1646 if (isset($conditions['visible'])) {
1647 $additionalselect .= ' AND visible = :visible';
1648 $additionalparams['visible'] = $conditions['visible'];
1650 if (isset($conditions['theme'])) {
1651 $additionalselect .= ' AND theme= :theme';
1652 $additionalparams['theme'] = $conditions['theme'];
1655 foreach ($categories as $category) {
1656 $sqlselect = $DB->sql_like('path', ':path') . $additionalselect;
1657 $sqlparams = array('path' => $category->path.'/%') + $additionalparams; // It will NOT include the specified category.
1658 $subcategories = $DB->get_records_select('course_categories', $sqlselect, $sqlparams);
1659 $newcategories = $newcategories + $subcategories; // Both arrays have integer as keys.
1661 $categories = $categories + $newcategories;
1665 } else {
1666 // Retrieve all categories in the database.
1667 $categories = $DB->get_records('course_categories');
1670 // The not returned categories. key => category id, value => reason of exclusion.
1671 $excludedcats = array();
1673 // The returned categories.
1674 $categoriesinfo = array();
1676 // We need to sort the categories by path.
1677 // The parent cats need to be checked by the algo first.
1678 usort($categories, "core_course_external::compare_categories_by_path");
1680 foreach ($categories as $category) {
1682 // Check if the category is a child of an excluded category, if yes exclude it too (excluded => do not return).
1683 $parents = explode('/', $category->path);
1684 unset($parents[0]); // First key is always empty because path start with / => /1/2/4.
1685 foreach ($parents as $parentid) {
1686 // Note: when the parent exclusion was due to the context,
1687 // the sub category could still be returned.
1688 if (isset($excludedcats[$parentid]) and $excludedcats[$parentid] != 'context') {
1689 $excludedcats[$category->id] = 'parent';
1693 // Check the user can use the category context.
1694 $context = context_coursecat::instance($category->id);
1695 try {
1696 self::validate_context($context);
1697 } catch (Exception $e) {
1698 $excludedcats[$category->id] = 'context';
1700 // If it was the requested category then throw an exception.
1701 if (isset($params['categoryid']) && $category->id == $params['categoryid']) {
1702 $exceptionparam = new stdClass();
1703 $exceptionparam->message = $e->getMessage();
1704 $exceptionparam->catid = $category->id;
1705 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
1709 // Return the category information.
1710 if (!isset($excludedcats[$category->id])) {
1712 // Final check to see if the category is visible to the user.
1713 if ($category->visible or has_capability('moodle/category:viewhiddencategories', $context)) {
1715 $categoryinfo = array();
1716 $categoryinfo['id'] = $category->id;
1717 $categoryinfo['name'] = external_format_string($category->name, $context);
1718 list($categoryinfo['description'], $categoryinfo['descriptionformat']) =
1719 external_format_text($category->description, $category->descriptionformat,
1720 $context->id, 'coursecat', 'description', null);
1721 $categoryinfo['parent'] = $category->parent;
1722 $categoryinfo['sortorder'] = $category->sortorder;
1723 $categoryinfo['coursecount'] = $category->coursecount;
1724 $categoryinfo['depth'] = $category->depth;
1725 $categoryinfo['path'] = $category->path;
1727 // Some fields only returned for admin.
1728 if (has_capability('moodle/category:manage', $context)) {
1729 $categoryinfo['idnumber'] = $category->idnumber;
1730 $categoryinfo['visible'] = $category->visible;
1731 $categoryinfo['visibleold'] = $category->visibleold;
1732 $categoryinfo['timemodified'] = $category->timemodified;
1733 $categoryinfo['theme'] = clean_param($category->theme, PARAM_THEME);
1736 $categoriesinfo[] = $categoryinfo;
1737 } else {
1738 $excludedcats[$category->id] = 'visibility';
1743 // Sorting the resulting array so it looks a bit better for the client developer.
1744 usort($categoriesinfo, "core_course_external::compare_categories_by_sortorder");
1746 return $categoriesinfo;
1750 * Sort categories array by path
1751 * private function: only used by get_categories
1753 * @param array $category1
1754 * @param array $category2
1755 * @return int result of strcmp
1756 * @since Moodle 2.3
1758 private static function compare_categories_by_path($category1, $category2) {
1759 return strcmp($category1->path, $category2->path);
1763 * Sort categories array by sortorder
1764 * private function: only used by get_categories
1766 * @param array $category1
1767 * @param array $category2
1768 * @return int result of strcmp
1769 * @since Moodle 2.3
1771 private static function compare_categories_by_sortorder($category1, $category2) {
1772 return strcmp($category1['sortorder'], $category2['sortorder']);
1776 * Returns description of method result value
1778 * @return external_description
1779 * @since Moodle 2.3
1781 public static function get_categories_returns() {
1782 return new external_multiple_structure(
1783 new external_single_structure(
1784 array(
1785 'id' => new external_value(PARAM_INT, 'category id'),
1786 'name' => new external_value(PARAM_TEXT, 'category name'),
1787 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1788 'description' => new external_value(PARAM_RAW, 'category description'),
1789 'descriptionformat' => new external_format_value('description'),
1790 'parent' => new external_value(PARAM_INT, 'parent category id'),
1791 'sortorder' => new external_value(PARAM_INT, 'category sorting order'),
1792 'coursecount' => new external_value(PARAM_INT, 'number of courses in this category'),
1793 'visible' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1794 'visibleold' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1795 'timemodified' => new external_value(PARAM_INT, 'timestamp', VALUE_OPTIONAL),
1796 'depth' => new external_value(PARAM_INT, 'category depth'),
1797 'path' => new external_value(PARAM_TEXT, 'category path'),
1798 'theme' => new external_value(PARAM_THEME, 'category theme', VALUE_OPTIONAL),
1799 ), 'List of categories'
1805 * Returns description of method parameters
1807 * @return external_function_parameters
1808 * @since Moodle 2.3
1810 public static function create_categories_parameters() {
1811 return new external_function_parameters(
1812 array(
1813 'categories' => new external_multiple_structure(
1814 new external_single_structure(
1815 array(
1816 'name' => new external_value(PARAM_TEXT, 'new category name'),
1817 'parent' => new external_value(PARAM_INT,
1818 'the parent category id inside which the new category will be created
1819 - set to 0 for a root category',
1820 VALUE_DEFAULT, 0),
1821 'idnumber' => new external_value(PARAM_RAW,
1822 'the new category idnumber', VALUE_OPTIONAL),
1823 'description' => new external_value(PARAM_RAW,
1824 'the new category description', VALUE_OPTIONAL),
1825 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
1826 'theme' => new external_value(PARAM_THEME,
1827 'the new category theme. This option must be enabled on moodle',
1828 VALUE_OPTIONAL),
1837 * Create categories
1839 * @param array $categories - see create_categories_parameters() for the array structure
1840 * @return array - see create_categories_returns() for the array structure
1841 * @since Moodle 2.3
1843 public static function create_categories($categories) {
1844 global $CFG, $DB;
1845 require_once($CFG->libdir . "/coursecatlib.php");
1847 $params = self::validate_parameters(self::create_categories_parameters(),
1848 array('categories' => $categories));
1850 $transaction = $DB->start_delegated_transaction();
1852 $createdcategories = array();
1853 foreach ($params['categories'] as $category) {
1854 if ($category['parent']) {
1855 if (!$DB->record_exists('course_categories', array('id' => $category['parent']))) {
1856 throw new moodle_exception('unknowcategory');
1858 $context = context_coursecat::instance($category['parent']);
1859 } else {
1860 $context = context_system::instance();
1862 self::validate_context($context);
1863 require_capability('moodle/category:manage', $context);
1865 // this will validate format and throw an exception if there are errors
1866 external_validate_format($category['descriptionformat']);
1868 $newcategory = coursecat::create($category);
1869 $context = context_coursecat::instance($newcategory->id);
1871 $createdcategories[] = array(
1872 'id' => $newcategory->id,
1873 'name' => external_format_string($newcategory->name, $context),
1877 $transaction->allow_commit();
1879 return $createdcategories;
1883 * Returns description of method parameters
1885 * @return external_function_parameters
1886 * @since Moodle 2.3
1888 public static function create_categories_returns() {
1889 return new external_multiple_structure(
1890 new external_single_structure(
1891 array(
1892 'id' => new external_value(PARAM_INT, 'new category id'),
1893 'name' => new external_value(PARAM_TEXT, 'new category name'),
1900 * Returns description of method parameters
1902 * @return external_function_parameters
1903 * @since Moodle 2.3
1905 public static function update_categories_parameters() {
1906 return new external_function_parameters(
1907 array(
1908 'categories' => new external_multiple_structure(
1909 new external_single_structure(
1910 array(
1911 'id' => new external_value(PARAM_INT, 'course id'),
1912 'name' => new external_value(PARAM_TEXT, 'category name', VALUE_OPTIONAL),
1913 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1914 'parent' => new external_value(PARAM_INT, 'parent category id', VALUE_OPTIONAL),
1915 'description' => new external_value(PARAM_RAW, 'category description', VALUE_OPTIONAL),
1916 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
1917 'theme' => new external_value(PARAM_THEME,
1918 'the category theme. This option must be enabled on moodle', VALUE_OPTIONAL),
1927 * Update categories
1929 * @param array $categories The list of categories to update
1930 * @return null
1931 * @since Moodle 2.3
1933 public static function update_categories($categories) {
1934 global $CFG, $DB;
1935 require_once($CFG->libdir . "/coursecatlib.php");
1937 // Validate parameters.
1938 $params = self::validate_parameters(self::update_categories_parameters(), array('categories' => $categories));
1940 $transaction = $DB->start_delegated_transaction();
1942 foreach ($params['categories'] as $cat) {
1943 $category = coursecat::get($cat['id']);
1945 $categorycontext = context_coursecat::instance($cat['id']);
1946 self::validate_context($categorycontext);
1947 require_capability('moodle/category:manage', $categorycontext);
1949 // this will throw an exception if descriptionformat is not valid
1950 external_validate_format($cat['descriptionformat']);
1952 $category->update($cat);
1955 $transaction->allow_commit();
1959 * Returns description of method result value
1961 * @return external_description
1962 * @since Moodle 2.3
1964 public static function update_categories_returns() {
1965 return null;
1969 * Returns description of method parameters
1971 * @return external_function_parameters
1972 * @since Moodle 2.3
1974 public static function delete_categories_parameters() {
1975 return new external_function_parameters(
1976 array(
1977 'categories' => new external_multiple_structure(
1978 new external_single_structure(
1979 array(
1980 'id' => new external_value(PARAM_INT, 'category id to delete'),
1981 'newparent' => new external_value(PARAM_INT,
1982 'the parent category to move the contents to, if specified', VALUE_OPTIONAL),
1983 'recursive' => new external_value(PARAM_BOOL, '1: recursively delete all contents inside this
1984 category, 0 (default): move contents to newparent or current parent category (except if parent is root)', VALUE_DEFAULT, 0)
1993 * Delete categories
1995 * @param array $categories A list of category ids
1996 * @return array
1997 * @since Moodle 2.3
1999 public static function delete_categories($categories) {
2000 global $CFG, $DB;
2001 require_once($CFG->dirroot . "/course/lib.php");
2002 require_once($CFG->libdir . "/coursecatlib.php");
2004 // Validate parameters.
2005 $params = self::validate_parameters(self::delete_categories_parameters(), array('categories' => $categories));
2007 $transaction = $DB->start_delegated_transaction();
2009 foreach ($params['categories'] as $category) {
2010 $deletecat = coursecat::get($category['id'], MUST_EXIST);
2011 $context = context_coursecat::instance($deletecat->id);
2012 require_capability('moodle/category:manage', $context);
2013 self::validate_context($context);
2014 self::validate_context(get_category_or_system_context($deletecat->parent));
2016 if ($category['recursive']) {
2017 // If recursive was specified, then we recursively delete the category's contents.
2018 if ($deletecat->can_delete_full()) {
2019 $deletecat->delete_full(false);
2020 } else {
2021 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2023 } else {
2024 // In this situation, we don't delete the category's contents, we either move it to newparent or parent.
2025 // If the parent is the root, moving is not supported (because a course must always be inside a category).
2026 // We must move to an existing category.
2027 if (!empty($category['newparent'])) {
2028 $newparentcat = coursecat::get($category['newparent']);
2029 } else {
2030 $newparentcat = coursecat::get($deletecat->parent);
2033 // This operation is not allowed. We must move contents to an existing category.
2034 if (!$newparentcat->id) {
2035 throw new moodle_exception('movecatcontentstoroot');
2038 self::validate_context(context_coursecat::instance($newparentcat->id));
2039 if ($deletecat->can_move_content_to($newparentcat->id)) {
2040 $deletecat->delete_move($newparentcat->id, false);
2041 } else {
2042 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2047 $transaction->allow_commit();
2051 * Returns description of method parameters
2053 * @return external_function_parameters
2054 * @since Moodle 2.3
2056 public static function delete_categories_returns() {
2057 return null;
2061 * Describes the parameters for delete_modules.
2063 * @return external_function_parameters
2064 * @since Moodle 2.5
2066 public static function delete_modules_parameters() {
2067 return new external_function_parameters (
2068 array(
2069 'cmids' => new external_multiple_structure(new external_value(PARAM_INT, 'course module ID',
2070 VALUE_REQUIRED, '', NULL_NOT_ALLOWED), 'Array of course module IDs'),
2076 * Deletes a list of provided module instances.
2078 * @param array $cmids the course module ids
2079 * @since Moodle 2.5
2081 public static function delete_modules($cmids) {
2082 global $CFG, $DB;
2084 // Require course file containing the course delete module function.
2085 require_once($CFG->dirroot . "/course/lib.php");
2087 // Clean the parameters.
2088 $params = self::validate_parameters(self::delete_modules_parameters(), array('cmids' => $cmids));
2090 // Keep track of the course ids we have performed a capability check on to avoid repeating.
2091 $arrcourseschecked = array();
2093 foreach ($params['cmids'] as $cmid) {
2094 // Get the course module.
2095 $cm = $DB->get_record('course_modules', array('id' => $cmid), '*', MUST_EXIST);
2097 // Check if we have not yet confirmed they have permission in this course.
2098 if (!in_array($cm->course, $arrcourseschecked)) {
2099 // Ensure the current user has required permission in this course.
2100 $context = context_course::instance($cm->course);
2101 self::validate_context($context);
2102 // Add to the array.
2103 $arrcourseschecked[] = $cm->course;
2106 // Ensure they can delete this module.
2107 $modcontext = context_module::instance($cm->id);
2108 require_capability('moodle/course:manageactivities', $modcontext);
2110 // Delete the module.
2111 course_delete_module($cm->id);
2116 * Describes the delete_modules return value.
2118 * @return external_single_structure
2119 * @since Moodle 2.5
2121 public static function delete_modules_returns() {
2122 return null;
2126 * Returns description of method parameters
2128 * @return external_function_parameters
2129 * @since Moodle 2.9
2131 public static function view_course_parameters() {
2132 return new external_function_parameters(
2133 array(
2134 'courseid' => new external_value(PARAM_INT, 'id of the course'),
2135 'sectionnumber' => new external_value(PARAM_INT, 'section number', VALUE_DEFAULT, 0)
2141 * Trigger the course viewed event.
2143 * @param int $courseid id of course
2144 * @param int $sectionnumber sectionnumber (0, 1, 2...)
2145 * @return array of warnings and status result
2146 * @since Moodle 2.9
2147 * @throws moodle_exception
2149 public static function view_course($courseid, $sectionnumber = 0) {
2150 global $CFG;
2151 require_once($CFG->dirroot . "/course/lib.php");
2153 $params = self::validate_parameters(self::view_course_parameters(),
2154 array(
2155 'courseid' => $courseid,
2156 'sectionnumber' => $sectionnumber
2159 $warnings = array();
2161 $course = get_course($params['courseid']);
2162 $context = context_course::instance($course->id);
2163 self::validate_context($context);
2165 if (!empty($params['sectionnumber'])) {
2167 // Get section details and check it exists.
2168 $modinfo = get_fast_modinfo($course);
2169 $coursesection = $modinfo->get_section_info($params['sectionnumber'], MUST_EXIST);
2171 // Check user is allowed to see it.
2172 if (!$coursesection->uservisible) {
2173 require_capability('moodle/course:viewhiddensections', $context);
2177 course_view($context, $params['sectionnumber']);
2179 $result = array();
2180 $result['status'] = true;
2181 $result['warnings'] = $warnings;
2182 return $result;
2186 * Returns description of method result value
2188 * @return external_description
2189 * @since Moodle 2.9
2191 public static function view_course_returns() {
2192 return new external_single_structure(
2193 array(
2194 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
2195 'warnings' => new external_warnings()
2201 * Returns description of method parameters
2203 * @return external_function_parameters
2204 * @since Moodle 3.0
2206 public static function search_courses_parameters() {
2207 return new external_function_parameters(
2208 array(
2209 'criterianame' => new external_value(PARAM_ALPHA, 'criteria name
2210 (search, modulelist (only admins), blocklist (only admins), tagid)'),
2211 'criteriavalue' => new external_value(PARAM_RAW, 'criteria value'),
2212 'page' => new external_value(PARAM_INT, 'page number (0 based)', VALUE_DEFAULT, 0),
2213 'perpage' => new external_value(PARAM_INT, 'items per page', VALUE_DEFAULT, 0),
2214 'requiredcapabilities' => new external_multiple_structure(
2215 new external_value(PARAM_CAPABILITY, 'Capability string used to filter courses by permission'),
2216 'Optional list of required capabilities (used to filter the list)', VALUE_DEFAULT, array()
2218 'limittoenrolled' => new external_value(PARAM_BOOL, 'limit to enrolled courses', VALUE_DEFAULT, 0),
2224 * Return the course information that is public (visible by every one)
2226 * @param course_in_list $course course in list object
2227 * @param stdClass $coursecontext course context object
2228 * @return array the course information
2229 * @since Moodle 3.2
2231 protected static function get_course_public_information(course_in_list $course, $coursecontext) {
2233 static $categoriescache = array();
2235 // Category information.
2236 if (!array_key_exists($course->category, $categoriescache)) {
2237 $categoriescache[$course->category] = coursecat::get($course->category, IGNORE_MISSING);
2239 $category = $categoriescache[$course->category];
2241 // Retrieve course overview used files.
2242 $files = array();
2243 foreach ($course->get_course_overviewfiles() as $file) {
2244 $fileurl = moodle_url::make_webservice_pluginfile_url($file->get_contextid(), $file->get_component(),
2245 $file->get_filearea(), null, $file->get_filepath(),
2246 $file->get_filename())->out(false);
2247 $files[] = array(
2248 'filename' => $file->get_filename(),
2249 'fileurl' => $fileurl,
2250 'filesize' => $file->get_filesize(),
2251 'filepath' => $file->get_filepath(),
2252 'mimetype' => $file->get_mimetype(),
2253 'timemodified' => $file->get_timemodified(),
2257 // Retrieve the course contacts,
2258 // we need here the users fullname since if we are not enrolled can be difficult to obtain them via other Web Services.
2259 $coursecontacts = array();
2260 foreach ($course->get_course_contacts() as $contact) {
2261 $coursecontacts[] = array(
2262 'id' => $contact['user']->id,
2263 'fullname' => $contact['username']
2267 // Allowed enrolment methods (maybe we can self-enrol).
2268 $enroltypes = array();
2269 $instances = enrol_get_instances($course->id, true);
2270 foreach ($instances as $instance) {
2271 $enroltypes[] = $instance->enrol;
2274 // Format summary.
2275 list($summary, $summaryformat) =
2276 external_format_text($course->summary, $course->summaryformat, $coursecontext->id, 'course', 'summary', null);
2278 $categoryname = '';
2279 if (!empty($category)) {
2280 $categoryname = external_format_string($category->name, $category->get_context());
2283 $displayname = get_course_display_name_for_list($course);
2284 $coursereturns = array();
2285 $coursereturns['id'] = $course->id;
2286 $coursereturns['fullname'] = external_format_string($course->fullname, $coursecontext->id);
2287 $coursereturns['displayname'] = external_format_string($displayname, $coursecontext->id);
2288 $coursereturns['shortname'] = external_format_string($course->shortname, $coursecontext->id);
2289 $coursereturns['categoryid'] = $course->category;
2290 $coursereturns['categoryname'] = $categoryname;
2291 $coursereturns['summary'] = $summary;
2292 $coursereturns['summaryformat'] = $summaryformat;
2293 $coursereturns['summaryfiles'] = external_util::get_area_files($coursecontext->id, 'course', 'summary', false, false);
2294 $coursereturns['overviewfiles'] = $files;
2295 $coursereturns['contacts'] = $coursecontacts;
2296 $coursereturns['enrollmentmethods'] = $enroltypes;
2297 $coursereturns['sortorder'] = $course->sortorder;
2298 return $coursereturns;
2302 * Search courses following the specified criteria.
2304 * @param string $criterianame Criteria name (search, modulelist (only admins), blocklist (only admins), tagid)
2305 * @param string $criteriavalue Criteria value
2306 * @param int $page Page number (for pagination)
2307 * @param int $perpage Items per page
2308 * @param array $requiredcapabilities Optional list of required capabilities (used to filter the list).
2309 * @param int $limittoenrolled Limit to only enrolled courses
2310 * @return array of course objects and warnings
2311 * @since Moodle 3.0
2312 * @throws moodle_exception
2314 public static function search_courses($criterianame,
2315 $criteriavalue,
2316 $page=0,
2317 $perpage=0,
2318 $requiredcapabilities=array(),
2319 $limittoenrolled=0) {
2320 global $CFG;
2321 require_once($CFG->libdir . '/coursecatlib.php');
2323 $warnings = array();
2325 $parameters = array(
2326 'criterianame' => $criterianame,
2327 'criteriavalue' => $criteriavalue,
2328 'page' => $page,
2329 'perpage' => $perpage,
2330 'requiredcapabilities' => $requiredcapabilities
2332 $params = self::validate_parameters(self::search_courses_parameters(), $parameters);
2333 self::validate_context(context_system::instance());
2335 $allowedcriterianames = array('search', 'modulelist', 'blocklist', 'tagid');
2336 if (!in_array($params['criterianame'], $allowedcriterianames)) {
2337 throw new invalid_parameter_exception('Invalid value for criterianame parameter (value: '.$params['criterianame'].'),' .
2338 'allowed values are: '.implode(',', $allowedcriterianames));
2341 if ($params['criterianame'] == 'modulelist' or $params['criterianame'] == 'blocklist') {
2342 require_capability('moodle/site:config', context_system::instance());
2345 $paramtype = array(
2346 'search' => PARAM_RAW,
2347 'modulelist' => PARAM_PLUGIN,
2348 'blocklist' => PARAM_INT,
2349 'tagid' => PARAM_INT
2351 $params['criteriavalue'] = clean_param($params['criteriavalue'], $paramtype[$params['criterianame']]);
2353 // Prepare the search API options.
2354 $searchcriteria = array();
2355 $searchcriteria[$params['criterianame']] = $params['criteriavalue'];
2357 $options = array();
2358 if ($params['perpage'] != 0) {
2359 $offset = $params['page'] * $params['perpage'];
2360 $options = array('offset' => $offset, 'limit' => $params['perpage']);
2363 // Search the courses.
2364 $courses = coursecat::search_courses($searchcriteria, $options, $params['requiredcapabilities']);
2365 $totalcount = coursecat::search_courses_count($searchcriteria, $options, $params['requiredcapabilities']);
2367 if (!empty($limittoenrolled)) {
2368 // Get the courses where the current user has access.
2369 $enrolled = enrol_get_my_courses(array('id', 'cacherev'));
2372 $finalcourses = array();
2373 $categoriescache = array();
2375 foreach ($courses as $course) {
2376 if (!empty($limittoenrolled)) {
2377 // Filter out not enrolled courses.
2378 if (!isset($enrolled[$course->id])) {
2379 $totalcount--;
2380 continue;
2384 $coursecontext = context_course::instance($course->id);
2386 $finalcourses[] = self::get_course_public_information($course, $coursecontext);
2389 return array(
2390 'total' => $totalcount,
2391 'courses' => $finalcourses,
2392 'warnings' => $warnings
2397 * Returns a course structure definition
2399 * @param boolean $onlypublicdata set to true, to retrieve only fields viewable by anyone when the course is visible
2400 * @return array the course structure
2401 * @since Moodle 3.2
2403 protected static function get_course_structure($onlypublicdata = true) {
2404 $coursestructure = array(
2405 'id' => new external_value(PARAM_INT, 'course id'),
2406 'fullname' => new external_value(PARAM_TEXT, 'course full name'),
2407 'displayname' => new external_value(PARAM_TEXT, 'course display name'),
2408 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
2409 'categoryid' => new external_value(PARAM_INT, 'category id'),
2410 'categoryname' => new external_value(PARAM_TEXT, 'category name'),
2411 'sortorder' => new external_value(PARAM_INT, 'Sort order in the category', VALUE_OPTIONAL),
2412 'summary' => new external_value(PARAM_RAW, 'summary'),
2413 'summaryformat' => new external_format_value('summary'),
2414 'summaryfiles' => new external_files('summary files in the summary field', VALUE_OPTIONAL),
2415 'overviewfiles' => new external_files('additional overview files attached to this course'),
2416 'contacts' => new external_multiple_structure(
2417 new external_single_structure(
2418 array(
2419 'id' => new external_value(PARAM_INT, 'contact user id'),
2420 'fullname' => new external_value(PARAM_NOTAGS, 'contact user fullname'),
2423 'contact users'
2425 'enrollmentmethods' => new external_multiple_structure(
2426 new external_value(PARAM_PLUGIN, 'enrollment method'),
2427 'enrollment methods list'
2431 if (!$onlypublicdata) {
2432 $extra = array(
2433 'idnumber' => new external_value(PARAM_RAW, 'Id number', VALUE_OPTIONAL),
2434 'format' => new external_value(PARAM_PLUGIN, 'Course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
2435 'showgrades' => new external_value(PARAM_INT, '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
2436 'newsitems' => new external_value(PARAM_INT, 'Number of recent items appearing on the course page', VALUE_OPTIONAL),
2437 'startdate' => new external_value(PARAM_INT, 'Timestamp when the course start', VALUE_OPTIONAL),
2438 'enddate' => new external_value(PARAM_INT, 'Timestamp when the course end', VALUE_OPTIONAL),
2439 'maxbytes' => new external_value(PARAM_INT, 'Largest size of file that can be uploaded into', VALUE_OPTIONAL),
2440 'showreports' => new external_value(PARAM_INT, 'Are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
2441 'visible' => new external_value(PARAM_INT, '1: available to student, 0:not available', VALUE_OPTIONAL),
2442 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
2443 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
2444 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
2445 'enablecompletion' => new external_value(PARAM_INT, 'Completion enabled? 1: yes 0: no', VALUE_OPTIONAL),
2446 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
2447 'lang' => new external_value(PARAM_SAFEDIR, 'Forced course language', VALUE_OPTIONAL),
2448 'theme' => new external_value(PARAM_PLUGIN, 'Fame of the forced theme', VALUE_OPTIONAL),
2449 'marker' => new external_value(PARAM_INT, 'Current course marker', VALUE_OPTIONAL),
2450 'legacyfiles' => new external_value(PARAM_INT, 'If legacy files are enabled', VALUE_OPTIONAL),
2451 'calendartype' => new external_value(PARAM_PLUGIN, 'Calendar type', VALUE_OPTIONAL),
2452 'timecreated' => new external_value(PARAM_INT, 'Time when the course was created', VALUE_OPTIONAL),
2453 'timemodified' => new external_value(PARAM_INT, 'Last time the course was updated', VALUE_OPTIONAL),
2454 'requested' => new external_value(PARAM_INT, 'If is a requested course', VALUE_OPTIONAL),
2455 'cacherev' => new external_value(PARAM_INT, 'Cache revision number', VALUE_OPTIONAL),
2456 'filters' => new external_multiple_structure(
2457 new external_single_structure(
2458 array(
2459 'filter' => new external_value(PARAM_PLUGIN, 'Filter plugin name'),
2460 'localstate' => new external_value(PARAM_INT, 'Filter state: 1 for on, -1 for off, 0 if inherit'),
2461 'inheritedstate' => new external_value(PARAM_INT, '1 or 0 to use when localstate is set to inherit'),
2464 'Course filters', VALUE_OPTIONAL
2466 'courseformatoptions' => new external_multiple_structure(
2467 new external_single_structure(
2468 array(
2469 'name' => new external_value(PARAM_RAW, 'Course format option name.'),
2470 'value' => new external_value(PARAM_RAW, 'Course format option value.'),
2473 'Additional options for particular course format.', VALUE_OPTIONAL
2476 $coursestructure = array_merge($coursestructure, $extra);
2478 return new external_single_structure($coursestructure);
2482 * Returns description of method result value
2484 * @return external_description
2485 * @since Moodle 3.0
2487 public static function search_courses_returns() {
2488 return new external_single_structure(
2489 array(
2490 'total' => new external_value(PARAM_INT, 'total course count'),
2491 'courses' => new external_multiple_structure(self::get_course_structure(), 'course'),
2492 'warnings' => new external_warnings()
2498 * Returns description of method parameters
2500 * @return external_function_parameters
2501 * @since Moodle 3.0
2503 public static function get_course_module_parameters() {
2504 return new external_function_parameters(
2505 array(
2506 'cmid' => new external_value(PARAM_INT, 'The course module id')
2512 * Return information about a course module.
2514 * @param int $cmid the course module id
2515 * @return array of warnings and the course module
2516 * @since Moodle 3.0
2517 * @throws moodle_exception
2519 public static function get_course_module($cmid) {
2520 global $CFG, $DB;
2522 $params = self::validate_parameters(self::get_course_module_parameters(), array('cmid' => $cmid));
2523 $warnings = array();
2525 $cm = get_coursemodule_from_id(null, $params['cmid'], 0, true, MUST_EXIST);
2526 $context = context_module::instance($cm->id);
2527 self::validate_context($context);
2529 // If the user has permissions to manage the activity, return all the information.
2530 if (has_capability('moodle/course:manageactivities', $context)) {
2531 require_once($CFG->dirroot . '/course/modlib.php');
2532 require_once($CFG->libdir . '/gradelib.php');
2534 $info = $cm;
2535 // Get the extra information: grade, advanced grading and outcomes data.
2536 $course = get_course($cm->course);
2537 list($newcm, $newcontext, $module, $extrainfo, $cw) = get_moduleinfo_data($cm, $course);
2538 // Grades.
2539 $gradeinfo = array('grade', 'gradepass', 'gradecat');
2540 foreach ($gradeinfo as $gfield) {
2541 if (isset($extrainfo->{$gfield})) {
2542 $info->{$gfield} = $extrainfo->{$gfield};
2545 if (isset($extrainfo->grade) and $extrainfo->grade < 0) {
2546 $info->scale = $DB->get_field('scale', 'scale', array('id' => abs($extrainfo->grade)));
2548 // Advanced grading.
2549 if (isset($extrainfo->_advancedgradingdata)) {
2550 $info->advancedgrading = array();
2551 foreach ($extrainfo as $key => $val) {
2552 if (strpos($key, 'advancedgradingmethod_') === 0) {
2553 $info->advancedgrading[] = array(
2554 'area' => str_replace('advancedgradingmethod_', '', $key),
2555 'method' => $val
2560 // Outcomes.
2561 foreach ($extrainfo as $key => $val) {
2562 if (strpos($key, 'outcome_') === 0) {
2563 if (!isset($info->outcomes)) {
2564 $info->outcomes = array();
2566 $id = str_replace('outcome_', '', $key);
2567 $outcome = grade_outcome::fetch(array('id' => $id));
2568 $scaleitems = $outcome->load_scale();
2569 $info->outcomes[] = array(
2570 'id' => $id,
2571 'name' => external_format_string($outcome->get_name(), $context->id),
2572 'scale' => $scaleitems->scale
2576 } else {
2577 // Return information is safe to show to any user.
2578 $info = new stdClass();
2579 $info->id = $cm->id;
2580 $info->course = $cm->course;
2581 $info->module = $cm->module;
2582 $info->modname = $cm->modname;
2583 $info->instance = $cm->instance;
2584 $info->section = $cm->section;
2585 $info->sectionnum = $cm->sectionnum;
2586 $info->groupmode = $cm->groupmode;
2587 $info->groupingid = $cm->groupingid;
2588 $info->completion = $cm->completion;
2590 // Format name.
2591 $info->name = external_format_string($cm->name, $context->id);
2592 $result = array();
2593 $result['cm'] = $info;
2594 $result['warnings'] = $warnings;
2595 return $result;
2599 * Returns description of method result value
2601 * @return external_description
2602 * @since Moodle 3.0
2604 public static function get_course_module_returns() {
2605 return new external_single_structure(
2606 array(
2607 'cm' => new external_single_structure(
2608 array(
2609 'id' => new external_value(PARAM_INT, 'The course module id'),
2610 'course' => new external_value(PARAM_INT, 'The course id'),
2611 'module' => new external_value(PARAM_INT, 'The module type id'),
2612 'name' => new external_value(PARAM_RAW, 'The activity name'),
2613 'modname' => new external_value(PARAM_COMPONENT, 'The module component name (forum, assign, etc..)'),
2614 'instance' => new external_value(PARAM_INT, 'The activity instance id'),
2615 'section' => new external_value(PARAM_INT, 'The module section id'),
2616 'sectionnum' => new external_value(PARAM_INT, 'The module section number'),
2617 'groupmode' => new external_value(PARAM_INT, 'Group mode'),
2618 'groupingid' => new external_value(PARAM_INT, 'Grouping id'),
2619 'completion' => new external_value(PARAM_INT, 'If completion is enabled'),
2620 'idnumber' => new external_value(PARAM_RAW, 'Module id number', VALUE_OPTIONAL),
2621 'added' => new external_value(PARAM_INT, 'Time added', VALUE_OPTIONAL),
2622 'score' => new external_value(PARAM_INT, 'Score', VALUE_OPTIONAL),
2623 'indent' => new external_value(PARAM_INT, 'Indentation', VALUE_OPTIONAL),
2624 'visible' => new external_value(PARAM_INT, 'If visible', VALUE_OPTIONAL),
2625 'visibleoncoursepage' => new external_value(PARAM_INT, 'If visible on course page', VALUE_OPTIONAL),
2626 'visibleold' => new external_value(PARAM_INT, 'Visible old', VALUE_OPTIONAL),
2627 'completiongradeitemnumber' => new external_value(PARAM_INT, 'Completion grade item', VALUE_OPTIONAL),
2628 'completionview' => new external_value(PARAM_INT, 'Completion view setting', VALUE_OPTIONAL),
2629 'completionexpected' => new external_value(PARAM_INT, 'Completion time expected', VALUE_OPTIONAL),
2630 'showdescription' => new external_value(PARAM_INT, 'If the description is showed', VALUE_OPTIONAL),
2631 'availability' => new external_value(PARAM_RAW, 'Availability settings', VALUE_OPTIONAL),
2632 'grade' => new external_value(PARAM_FLOAT, 'Grade (max value or scale id)', VALUE_OPTIONAL),
2633 'scale' => new external_value(PARAM_TEXT, 'Scale items (if used)', VALUE_OPTIONAL),
2634 'gradepass' => new external_value(PARAM_RAW, 'Grade to pass (float)', VALUE_OPTIONAL),
2635 'gradecat' => new external_value(PARAM_INT, 'Grade category', VALUE_OPTIONAL),
2636 'advancedgrading' => new external_multiple_structure(
2637 new external_single_structure(
2638 array(
2639 'area' => new external_value(PARAM_AREA, 'Gradable area name'),
2640 'method' => new external_value(PARAM_COMPONENT, 'Grading method'),
2643 'Advanced grading settings', VALUE_OPTIONAL
2645 'outcomes' => new external_multiple_structure(
2646 new external_single_structure(
2647 array(
2648 'id' => new external_value(PARAM_ALPHANUMEXT, 'Outcome id'),
2649 'name' => new external_value(PARAM_TEXT, 'Outcome full name'),
2650 'scale' => new external_value(PARAM_TEXT, 'Scale items')
2653 'Outcomes information', VALUE_OPTIONAL
2657 'warnings' => new external_warnings()
2663 * Returns description of method parameters
2665 * @return external_function_parameters
2666 * @since Moodle 3.0
2668 public static function get_course_module_by_instance_parameters() {
2669 return new external_function_parameters(
2670 array(
2671 'module' => new external_value(PARAM_COMPONENT, 'The module name'),
2672 'instance' => new external_value(PARAM_INT, 'The module instance id')
2678 * Return information about a course module.
2680 * @param string $module the module name
2681 * @param int $instance the activity instance id
2682 * @return array of warnings and the course module
2683 * @since Moodle 3.0
2684 * @throws moodle_exception
2686 public static function get_course_module_by_instance($module, $instance) {
2688 $params = self::validate_parameters(self::get_course_module_by_instance_parameters(),
2689 array(
2690 'module' => $module,
2691 'instance' => $instance,
2694 $warnings = array();
2695 $cm = get_coursemodule_from_instance($params['module'], $params['instance'], 0, false, MUST_EXIST);
2697 return self::get_course_module($cm->id);
2701 * Returns description of method result value
2703 * @return external_description
2704 * @since Moodle 3.0
2706 public static function get_course_module_by_instance_returns() {
2707 return self::get_course_module_returns();
2711 * Returns description of method parameters
2713 * @deprecated since 3.3
2714 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
2715 * @return external_function_parameters
2716 * @since Moodle 3.2
2718 public static function get_activities_overview_parameters() {
2719 return new external_function_parameters(
2720 array(
2721 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2727 * Return activities overview for the given courses.
2729 * @deprecated since 3.3
2730 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
2731 * @param array $courseids a list of course ids
2732 * @return array of warnings and the activities overview
2733 * @since Moodle 3.2
2734 * @throws moodle_exception
2736 public static function get_activities_overview($courseids) {
2737 global $USER;
2739 // Parameter validation.
2740 $params = self::validate_parameters(self::get_activities_overview_parameters(), array('courseids' => $courseids));
2741 $courseoverviews = array();
2743 list($courses, $warnings) = external_util::validate_courses($params['courseids']);
2745 if (!empty($courses)) {
2746 // Add lastaccess to each course (required by print_overview function).
2747 // We need the complete user data, the ws server does not load a complete one.
2748 $user = get_complete_user_data('id', $USER->id);
2749 foreach ($courses as $course) {
2750 if (isset($user->lastcourseaccess[$course->id])) {
2751 $course->lastaccess = $user->lastcourseaccess[$course->id];
2752 } else {
2753 $course->lastaccess = 0;
2757 $overviews = array();
2758 if ($modules = get_plugin_list_with_function('mod', 'print_overview')) {
2759 foreach ($modules as $fname) {
2760 $fname($courses, $overviews);
2764 // Format output.
2765 foreach ($overviews as $courseid => $modules) {
2766 $courseoverviews[$courseid]['id'] = $courseid;
2767 $courseoverviews[$courseid]['overviews'] = array();
2769 foreach ($modules as $modname => $overviewtext) {
2770 $courseoverviews[$courseid]['overviews'][] = array(
2771 'module' => $modname,
2772 'overviewtext' => $overviewtext // This text doesn't need formatting.
2778 $result = array(
2779 'courses' => $courseoverviews,
2780 'warnings' => $warnings
2782 return $result;
2786 * Returns description of method result value
2788 * @deprecated since 3.3
2789 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
2790 * @return external_description
2791 * @since Moodle 3.2
2793 public static function get_activities_overview_returns() {
2794 return new external_single_structure(
2795 array(
2796 'courses' => new external_multiple_structure(
2797 new external_single_structure(
2798 array(
2799 'id' => new external_value(PARAM_INT, 'Course id'),
2800 'overviews' => new external_multiple_structure(
2801 new external_single_structure(
2802 array(
2803 'module' => new external_value(PARAM_PLUGIN, 'Module name'),
2804 'overviewtext' => new external_value(PARAM_RAW, 'Overview text'),
2809 ), 'List of courses'
2811 'warnings' => new external_warnings()
2817 * Marking the method as deprecated.
2819 * @return bool
2821 public static function get_activities_overview_is_deprecated() {
2822 return true;
2826 * Returns description of method parameters
2828 * @return external_function_parameters
2829 * @since Moodle 3.2
2831 public static function get_user_navigation_options_parameters() {
2832 return new external_function_parameters(
2833 array(
2834 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2840 * Return a list of navigation options in a set of courses that are avaialable or not for the current user.
2842 * @param array $courseids a list of course ids
2843 * @return array of warnings and the options availability
2844 * @since Moodle 3.2
2845 * @throws moodle_exception
2847 public static function get_user_navigation_options($courseids) {
2848 global $CFG;
2849 require_once($CFG->dirroot . '/course/lib.php');
2851 // Parameter validation.
2852 $params = self::validate_parameters(self::get_user_navigation_options_parameters(), array('courseids' => $courseids));
2853 $courseoptions = array();
2855 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
2857 if (!empty($courses)) {
2858 foreach ($courses as $course) {
2859 // Fix the context for the frontpage.
2860 if ($course->id == SITEID) {
2861 $course->context = context_system::instance();
2863 $navoptions = course_get_user_navigation_options($course->context, $course);
2864 $options = array();
2865 foreach ($navoptions as $name => $available) {
2866 $options[] = array(
2867 'name' => $name,
2868 'available' => $available,
2872 $courseoptions[] = array(
2873 'id' => $course->id,
2874 'options' => $options
2879 $result = array(
2880 'courses' => $courseoptions,
2881 'warnings' => $warnings
2883 return $result;
2887 * Returns description of method result value
2889 * @return external_description
2890 * @since Moodle 3.2
2892 public static function get_user_navigation_options_returns() {
2893 return new external_single_structure(
2894 array(
2895 'courses' => new external_multiple_structure(
2896 new external_single_structure(
2897 array(
2898 'id' => new external_value(PARAM_INT, 'Course id'),
2899 'options' => new external_multiple_structure(
2900 new external_single_structure(
2901 array(
2902 'name' => new external_value(PARAM_ALPHANUMEXT, 'Option name'),
2903 'available' => new external_value(PARAM_BOOL, 'Whether the option is available or not'),
2908 ), 'List of courses'
2910 'warnings' => new external_warnings()
2916 * Returns description of method parameters
2918 * @return external_function_parameters
2919 * @since Moodle 3.2
2921 public static function get_user_administration_options_parameters() {
2922 return new external_function_parameters(
2923 array(
2924 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2930 * Return a list of administration options in a set of courses that are available or not for the current user.
2932 * @param array $courseids a list of course ids
2933 * @return array of warnings and the options availability
2934 * @since Moodle 3.2
2935 * @throws moodle_exception
2937 public static function get_user_administration_options($courseids) {
2938 global $CFG;
2939 require_once($CFG->dirroot . '/course/lib.php');
2941 // Parameter validation.
2942 $params = self::validate_parameters(self::get_user_administration_options_parameters(), array('courseids' => $courseids));
2943 $courseoptions = array();
2945 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
2947 if (!empty($courses)) {
2948 foreach ($courses as $course) {
2949 $adminoptions = course_get_user_administration_options($course, $course->context);
2950 $options = array();
2951 foreach ($adminoptions as $name => $available) {
2952 $options[] = array(
2953 'name' => $name,
2954 'available' => $available,
2958 $courseoptions[] = array(
2959 'id' => $course->id,
2960 'options' => $options
2965 $result = array(
2966 'courses' => $courseoptions,
2967 'warnings' => $warnings
2969 return $result;
2973 * Returns description of method result value
2975 * @return external_description
2976 * @since Moodle 3.2
2978 public static function get_user_administration_options_returns() {
2979 return self::get_user_navigation_options_returns();
2983 * Returns description of method parameters
2985 * @return external_function_parameters
2986 * @since Moodle 3.2
2988 public static function get_courses_by_field_parameters() {
2989 return new external_function_parameters(
2990 array(
2991 'field' => new external_value(PARAM_ALPHA, 'The field to search can be left empty for all courses or:
2992 id: course id
2993 ids: comma separated course ids
2994 shortname: course short name
2995 idnumber: course id number
2996 category: category id the course belongs to
2997 ', VALUE_DEFAULT, ''),
2998 'value' => new external_value(PARAM_RAW, 'The value to match', VALUE_DEFAULT, '')
3005 * Get courses matching a specific field (id/s, shortname, idnumber, category)
3007 * @param string $field field name to search, or empty for all courses
3008 * @param string $value value to search
3009 * @return array list of courses and warnings
3010 * @throws invalid_parameter_exception
3011 * @since Moodle 3.2
3013 public static function get_courses_by_field($field = '', $value = '') {
3014 global $DB, $CFG;
3015 require_once($CFG->libdir . '/coursecatlib.php');
3016 require_once($CFG->libdir . '/filterlib.php');
3018 $params = self::validate_parameters(self::get_courses_by_field_parameters(),
3019 array(
3020 'field' => $field,
3021 'value' => $value,
3024 $warnings = array();
3026 if (empty($params['field'])) {
3027 $courses = $DB->get_records('course', null, 'id ASC');
3028 } else {
3029 switch ($params['field']) {
3030 case 'id':
3031 case 'category':
3032 $value = clean_param($params['value'], PARAM_INT);
3033 break;
3034 case 'ids':
3035 $value = clean_param($params['value'], PARAM_SEQUENCE);
3036 break;
3037 case 'shortname':
3038 $value = clean_param($params['value'], PARAM_TEXT);
3039 break;
3040 case 'idnumber':
3041 $value = clean_param($params['value'], PARAM_RAW);
3042 break;
3043 default:
3044 throw new invalid_parameter_exception('Invalid field name');
3047 if ($params['field'] === 'ids') {
3048 $courses = $DB->get_records_list('course', 'id', explode(',', $value), 'id ASC');
3049 } else {
3050 $courses = $DB->get_records('course', array($params['field'] => $value), 'id ASC');
3054 $coursesdata = array();
3055 foreach ($courses as $course) {
3056 $context = context_course::instance($course->id);
3057 $canupdatecourse = has_capability('moodle/course:update', $context);
3058 $canviewhiddencourses = has_capability('moodle/course:viewhiddencourses', $context);
3060 // Check if the course is visible in the site for the user.
3061 if (!$course->visible and !$canviewhiddencourses and !$canupdatecourse) {
3062 continue;
3064 // Get the public course information, even if we are not enrolled.
3065 $courseinlist = new course_in_list($course);
3066 $coursesdata[$course->id] = self::get_course_public_information($courseinlist, $context);
3068 // Now, check if we have access to the course.
3069 try {
3070 self::validate_context($context);
3071 } catch (Exception $e) {
3072 continue;
3074 // Return information for any user that can access the course.
3075 $coursefields = array('format', 'showgrades', 'newsitems', 'startdate', 'enddate', 'maxbytes', 'showreports', 'visible',
3076 'groupmode', 'groupmodeforce', 'defaultgroupingid', 'enablecompletion', 'completionnotify', 'lang', 'theme',
3077 'marker');
3079 // Course filters.
3080 $coursesdata[$course->id]['filters'] = filter_get_available_in_context($context);
3082 // Information for managers only.
3083 if ($canupdatecourse) {
3084 $managerfields = array('idnumber', 'legacyfiles', 'calendartype', 'timecreated', 'timemodified', 'requested',
3085 'cacherev');
3086 $coursefields = array_merge($coursefields, $managerfields);
3089 // Populate fields.
3090 foreach ($coursefields as $field) {
3091 $coursesdata[$course->id][$field] = $course->{$field};
3094 // Clean lang and auth fields for external functions (it may content uninstalled themes or language packs).
3095 if (isset($coursesdata[$course->id]['theme'])) {
3096 $coursesdata[$course->id]['theme'] = clean_param($coursesdata[$course->id]['theme'], PARAM_THEME);
3098 if (isset($coursesdata[$course->id]['lang'])) {
3099 $coursesdata[$course->id]['lang'] = clean_param($coursesdata[$course->id]['lang'], PARAM_LANG);
3102 $courseformatoptions = course_get_format($course)->get_config_for_external();
3103 foreach ($courseformatoptions as $key => $value) {
3104 $coursesdata[$course->id]['courseformatoptions'][] = array(
3105 'name' => $key,
3106 'value' => $value
3111 return array(
3112 'courses' => $coursesdata,
3113 'warnings' => $warnings
3118 * Returns description of method result value
3120 * @return external_description
3121 * @since Moodle 3.2
3123 public static function get_courses_by_field_returns() {
3124 // Course structure, including not only public viewable fields.
3125 return new external_single_structure(
3126 array(
3127 'courses' => new external_multiple_structure(self::get_course_structure(false), 'Course'),
3128 'warnings' => new external_warnings()
3134 * Returns description of method parameters
3136 * @return external_function_parameters
3137 * @since Moodle 3.2
3139 public static function check_updates_parameters() {
3140 return new external_function_parameters(
3141 array(
3142 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3143 'tocheck' => new external_multiple_structure(
3144 new external_single_structure(
3145 array(
3146 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level for the file location.
3147 Only module supported right now.'),
3148 'id' => new external_value(PARAM_INT, 'Context instance id'),
3149 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3152 'Instances to check'
3154 'filter' => new external_multiple_structure(
3155 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3156 gradeitems, outcomes'),
3157 'Check only for updates in these areas', VALUE_DEFAULT, array()
3164 * Check if there is updates affecting the user for the given course and contexts.
3165 * Right now only modules are supported.
3166 * This WS calls mod_check_updates_since for each module to check if there is any update the user should we aware of.
3168 * @param int $courseid the list of modules to check
3169 * @param array $tocheck the list of modules to check
3170 * @param array $filter check only for updates in these areas
3171 * @return array list of updates and warnings
3172 * @throws moodle_exception
3173 * @since Moodle 3.2
3175 public static function check_updates($courseid, $tocheck, $filter = array()) {
3176 global $CFG, $DB;
3177 require_once($CFG->dirroot . "/course/lib.php");
3179 $params = self::validate_parameters(
3180 self::check_updates_parameters(),
3181 array(
3182 'courseid' => $courseid,
3183 'tocheck' => $tocheck,
3184 'filter' => $filter,
3188 $course = get_course($params['courseid']);
3189 $context = context_course::instance($course->id);
3190 self::validate_context($context);
3192 list($instances, $warnings) = course_check_updates($course, $params['tocheck'], $filter);
3194 $instancesformatted = array();
3195 foreach ($instances as $instance) {
3196 $updates = array();
3197 foreach ($instance['updates'] as $name => $data) {
3198 if (empty($data->updated)) {
3199 continue;
3201 $updatedata = array(
3202 'name' => $name,
3204 if (!empty($data->timeupdated)) {
3205 $updatedata['timeupdated'] = $data->timeupdated;
3207 if (!empty($data->itemids)) {
3208 $updatedata['itemids'] = $data->itemids;
3210 $updates[] = $updatedata;
3212 if (!empty($updates)) {
3213 $instancesformatted[] = array(
3214 'contextlevel' => $instance['contextlevel'],
3215 'id' => $instance['id'],
3216 'updates' => $updates
3221 return array(
3222 'instances' => $instancesformatted,
3223 'warnings' => $warnings
3228 * Returns description of method result value
3230 * @return external_description
3231 * @since Moodle 3.2
3233 public static function check_updates_returns() {
3234 return new external_single_structure(
3235 array(
3236 'instances' => new external_multiple_structure(
3237 new external_single_structure(
3238 array(
3239 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level'),
3240 'id' => new external_value(PARAM_INT, 'Instance id'),
3241 'updates' => new external_multiple_structure(
3242 new external_single_structure(
3243 array(
3244 'name' => new external_value(PARAM_ALPHANUMEXT, 'Name of the area updated.'),
3245 'timeupdated' => new external_value(PARAM_INT, 'Last time was updated', VALUE_OPTIONAL),
3246 'itemids' => new external_multiple_structure(
3247 new external_value(PARAM_INT, 'Instance id'),
3248 'The ids of the items updated',
3249 VALUE_OPTIONAL
3257 'warnings' => new external_warnings()
3263 * Returns description of method parameters
3265 * @return external_function_parameters
3266 * @since Moodle 3.3
3268 public static function get_updates_since_parameters() {
3269 return new external_function_parameters(
3270 array(
3271 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3272 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3273 'filter' => new external_multiple_structure(
3274 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3275 gradeitems, outcomes'),
3276 'Check only for updates in these areas', VALUE_DEFAULT, array()
3283 * Check if there are updates affecting the user for the given course since the given time stamp.
3285 * This function is a wrapper of self::check_updates for retrieving all the updates since a given time for all the activities.
3287 * @param int $courseid the list of modules to check
3288 * @param int $since check updates since this time stamp
3289 * @param array $filter check only for updates in these areas
3290 * @return array list of updates and warnings
3291 * @throws moodle_exception
3292 * @since Moodle 3.3
3294 public static function get_updates_since($courseid, $since, $filter = array()) {
3295 global $CFG, $DB;
3297 $params = self::validate_parameters(
3298 self::get_updates_since_parameters(),
3299 array(
3300 'courseid' => $courseid,
3301 'since' => $since,
3302 'filter' => $filter,
3306 $course = get_course($params['courseid']);
3307 $modinfo = get_fast_modinfo($course);
3308 $tocheck = array();
3310 // Retrieve all the visible course modules for the current user.
3311 $cms = $modinfo->get_cms();
3312 foreach ($cms as $cm) {
3313 if (!$cm->uservisible) {
3314 continue;
3316 $tocheck[] = array(
3317 'id' => $cm->id,
3318 'contextlevel' => 'module',
3319 'since' => $params['since'],
3323 return self::check_updates($course->id, $tocheck, $params['filter']);
3327 * Returns description of method result value
3329 * @return external_description
3330 * @since Moodle 3.3
3332 public static function get_updates_since_returns() {
3333 return self::check_updates_returns();
3337 * Parameters for function edit_module()
3339 * @since Moodle 3.3
3340 * @return external_function_parameters
3342 public static function edit_module_parameters() {
3343 return new external_function_parameters(
3344 array(
3345 'action' => new external_value(PARAM_ALPHA,
3346 'action: hide, show, stealth, duplicate, delete, moveleft, moveright, group...', VALUE_REQUIRED),
3347 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3348 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3353 * Performs one of the edit module actions and return new html for AJAX
3355 * Returns html to replace the current module html with, for example:
3356 * - empty string for "delete" action,
3357 * - two modules html for "duplicate" action
3358 * - updated module html for everything else
3360 * Throws exception if operation is not permitted/possible
3362 * @since Moodle 3.3
3363 * @param string $action
3364 * @param int $id
3365 * @param null|int $sectionreturn
3366 * @return string
3368 public static function edit_module($action, $id, $sectionreturn = null) {
3369 global $PAGE, $DB;
3370 // Validate and normalize parameters.
3371 $params = self::validate_parameters(self::edit_module_parameters(),
3372 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3373 $action = $params['action'];
3374 $id = $params['id'];
3375 $sectionreturn = $params['sectionreturn'];
3377 list($course, $cm) = get_course_and_cm_from_cmid($id);
3378 $modcontext = context_module::instance($cm->id);
3379 $coursecontext = context_course::instance($course->id);
3380 self::validate_context($modcontext);
3381 $courserenderer = $PAGE->get_renderer('core', 'course');
3382 $completioninfo = new completion_info($course);
3384 switch($action) {
3385 case 'hide':
3386 case 'show':
3387 case 'stealth':
3388 require_capability('moodle/course:activityvisibility', $modcontext);
3389 $visible = ($action === 'hide') ? 0 : 1;
3390 $visibleoncoursepage = ($action === 'stealth') ? 0 : 1;
3391 set_coursemodule_visible($id, $visible, $visibleoncoursepage);
3392 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3393 break;
3394 case 'duplicate':
3395 require_capability('moodle/course:manageactivities', $coursecontext);
3396 require_capability('moodle/backup:backuptargetimport', $coursecontext);
3397 require_capability('moodle/restore:restoretargetimport', $coursecontext);
3398 if (!course_allowed_module($course, $cm->modname)) {
3399 throw new moodle_exception('No permission to create that activity');
3401 if ($newcm = duplicate_module($course, $cm)) {
3402 $cm = get_fast_modinfo($course)->get_cm($id);
3403 $newcm = get_fast_modinfo($course)->get_cm($newcm->id);
3404 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn) .
3405 $courserenderer->course_section_cm_list_item($course, $completioninfo, $newcm, $sectionreturn);
3407 break;
3408 case 'groupsseparate':
3409 case 'groupsvisible':
3410 case 'groupsnone':
3411 require_capability('moodle/course:manageactivities', $modcontext);
3412 if ($action === 'groupsseparate') {
3413 $newgroupmode = SEPARATEGROUPS;
3414 } else if ($action === 'groupsvisible') {
3415 $newgroupmode = VISIBLEGROUPS;
3416 } else {
3417 $newgroupmode = NOGROUPS;
3419 if (set_coursemodule_groupmode($cm->id, $newgroupmode)) {
3420 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3422 break;
3423 case 'moveleft':
3424 case 'moveright':
3425 require_capability('moodle/course:manageactivities', $modcontext);
3426 $indent = $cm->indent + (($action === 'moveright') ? 1 : -1);
3427 if ($cm->indent >= 0) {
3428 $DB->update_record('course_modules', array('id' => $cm->id, 'indent' => $indent));
3429 rebuild_course_cache($cm->course);
3431 break;
3432 case 'delete':
3433 require_capability('moodle/course:manageactivities', $modcontext);
3434 course_delete_module($cm->id, true);
3435 return '';
3436 default:
3437 throw new coding_exception('Unrecognised action');
3440 $cm = get_fast_modinfo($course)->get_cm($id);
3441 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn);
3445 * Return structure for edit_module()
3447 * @since Moodle 3.3
3448 * @return external_description
3450 public static function edit_module_returns() {
3451 return new external_value(PARAM_RAW, 'html to replace the current module with');
3455 * Parameters for function get_module()
3457 * @since Moodle 3.3
3458 * @return external_function_parameters
3460 public static function get_module_parameters() {
3461 return new external_function_parameters(
3462 array(
3463 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3464 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3469 * Returns html for displaying one activity module on course page
3471 * @since Moodle 3.3
3472 * @param int $id
3473 * @param null|int $sectionreturn
3474 * @return string
3476 public static function get_module($id, $sectionreturn = null) {
3477 global $PAGE;
3478 // Validate and normalize parameters.
3479 $params = self::validate_parameters(self::get_module_parameters(),
3480 array('id' => $id, 'sectionreturn' => $sectionreturn));
3481 $id = $params['id'];
3482 $sectionreturn = $params['sectionreturn'];
3484 // Validate access to the course (note, this is html for the course view page, we don't validate access to the module).
3485 list($course, $cm) = get_course_and_cm_from_cmid($id);
3486 self::validate_context(context_course::instance($course->id));
3488 $courserenderer = $PAGE->get_renderer('core', 'course');
3489 $completioninfo = new completion_info($course);
3490 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn);
3494 * Return structure for edit_module()
3496 * @since Moodle 3.3
3497 * @return external_description
3499 public static function get_module_returns() {
3500 return new external_value(PARAM_RAW, 'html to replace the current module with');
3504 * Parameters for function edit_section()
3506 * @since Moodle 3.3
3507 * @return external_function_parameters
3509 public static function edit_section_parameters() {
3510 return new external_function_parameters(
3511 array(
3512 'action' => new external_value(PARAM_ALPHA, 'action: hide, show, stealth, setmarker, removemarker', VALUE_REQUIRED),
3513 'id' => new external_value(PARAM_INT, 'course section id', VALUE_REQUIRED),
3514 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3519 * Performs one of the edit section actions
3521 * @since Moodle 3.3
3522 * @param string $action
3523 * @param int $id section id
3524 * @param int $sectionreturn section to return to
3525 * @return string
3527 public static function edit_section($action, $id, $sectionreturn) {
3528 global $DB;
3529 // Validate and normalize parameters.
3530 $params = self::validate_parameters(self::edit_section_parameters(),
3531 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3532 $action = $params['action'];
3533 $id = $params['id'];
3534 $sr = $params['sectionreturn'];
3536 $section = $DB->get_record('course_sections', array('id' => $id), '*', MUST_EXIST);
3537 $coursecontext = context_course::instance($section->course);
3538 self::validate_context($coursecontext);
3540 $rv = course_get_format($section->course)->section_action($section, $action, $sectionreturn);
3541 if ($rv) {
3542 return json_encode($rv);
3543 } else {
3544 return null;
3549 * Return structure for edit_section()
3551 * @since Moodle 3.3
3552 * @return external_description
3554 public static function edit_section_returns() {
3555 return new external_value(PARAM_RAW, 'Additional data for javascript (JSON-encoded string)');