Merge branch 'MDL-62032-master' of git://github.com/mihailges/moodle
[moodle.git] / course / externallib.php
blob6b00cccea274ed098d8e2ed0bacb16e847c0e7db
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:manage', $context)
1604 or has_capability('moodle/category:viewhiddencategories',
1605 context_system::instance())) {
1606 $value = clean_param($crit['value'], PARAM_INT);
1607 $conditions[$key] = $value;
1608 $wheres[] = $key . " = :" . $key;
1609 } else {
1610 throw new moodle_exception('criteriaerror',
1611 'webservice', '', null,
1612 'You don\'t have the permissions to search on the "visible" field.');
1614 break;
1616 case 'theme':
1617 if (has_capability('moodle/category:manage', $context)) {
1618 $value = clean_param($crit['value'], PARAM_THEME);
1619 $conditions[$key] = $value;
1620 $wheres[] = $key . " = :" . $key;
1621 } else {
1622 throw new moodle_exception('criteriaerror',
1623 'webservice', '', null,
1624 'You don\'t have the permissions to search on the "theme" field.');
1626 break;
1628 default:
1629 throw new moodle_exception('criteriaerror',
1630 'webservice', '', null,
1631 'You can not search on this criteria: ' . $key);
1636 if (!empty($wheres)) {
1637 $wheres = implode(" AND ", $wheres);
1639 $categories = $DB->get_records_select('course_categories', $wheres, $conditions);
1641 // Retrieve its sub subcategories (all levels).
1642 if ($categories and !empty($params['addsubcategories'])) {
1643 $newcategories = array();
1645 // Check if we required visible/theme checks.
1646 $additionalselect = '';
1647 $additionalparams = array();
1648 if (isset($conditions['visible'])) {
1649 $additionalselect .= ' AND visible = :visible';
1650 $additionalparams['visible'] = $conditions['visible'];
1652 if (isset($conditions['theme'])) {
1653 $additionalselect .= ' AND theme= :theme';
1654 $additionalparams['theme'] = $conditions['theme'];
1657 foreach ($categories as $category) {
1658 $sqlselect = $DB->sql_like('path', ':path') . $additionalselect;
1659 $sqlparams = array('path' => $category->path.'/%') + $additionalparams; // It will NOT include the specified category.
1660 $subcategories = $DB->get_records_select('course_categories', $sqlselect, $sqlparams);
1661 $newcategories = $newcategories + $subcategories; // Both arrays have integer as keys.
1663 $categories = $categories + $newcategories;
1667 } else {
1668 // Retrieve all categories in the database.
1669 $categories = $DB->get_records('course_categories');
1672 // The not returned categories. key => category id, value => reason of exclusion.
1673 $excludedcats = array();
1675 // The returned categories.
1676 $categoriesinfo = array();
1678 // We need to sort the categories by path.
1679 // The parent cats need to be checked by the algo first.
1680 usort($categories, "core_course_external::compare_categories_by_path");
1682 foreach ($categories as $category) {
1684 // Check if the category is a child of an excluded category, if yes exclude it too (excluded => do not return).
1685 $parents = explode('/', $category->path);
1686 unset($parents[0]); // First key is always empty because path start with / => /1/2/4.
1687 foreach ($parents as $parentid) {
1688 // Note: when the parent exclusion was due to the context,
1689 // the sub category could still be returned.
1690 if (isset($excludedcats[$parentid]) and $excludedcats[$parentid] != 'context') {
1691 $excludedcats[$category->id] = 'parent';
1695 // Check the user can use the category context.
1696 $context = context_coursecat::instance($category->id);
1697 try {
1698 self::validate_context($context);
1699 } catch (Exception $e) {
1700 $excludedcats[$category->id] = 'context';
1702 // If it was the requested category then throw an exception.
1703 if (isset($params['categoryid']) && $category->id == $params['categoryid']) {
1704 $exceptionparam = new stdClass();
1705 $exceptionparam->message = $e->getMessage();
1706 $exceptionparam->catid = $category->id;
1707 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
1711 // Return the category information.
1712 if (!isset($excludedcats[$category->id])) {
1714 // Final check to see if the category is visible to the user.
1715 if ($category->visible
1716 or has_capability('moodle/category:viewhiddencategories', context_system::instance())
1717 or has_capability('moodle/category:manage', $context)) {
1719 $categoryinfo = array();
1720 $categoryinfo['id'] = $category->id;
1721 $categoryinfo['name'] = $category->name;
1722 list($categoryinfo['description'], $categoryinfo['descriptionformat']) =
1723 external_format_text($category->description, $category->descriptionformat,
1724 $context->id, 'coursecat', 'description', null);
1725 $categoryinfo['parent'] = $category->parent;
1726 $categoryinfo['sortorder'] = $category->sortorder;
1727 $categoryinfo['coursecount'] = $category->coursecount;
1728 $categoryinfo['depth'] = $category->depth;
1729 $categoryinfo['path'] = $category->path;
1731 // Some fields only returned for admin.
1732 if (has_capability('moodle/category:manage', $context)) {
1733 $categoryinfo['idnumber'] = $category->idnumber;
1734 $categoryinfo['visible'] = $category->visible;
1735 $categoryinfo['visibleold'] = $category->visibleold;
1736 $categoryinfo['timemodified'] = $category->timemodified;
1737 $categoryinfo['theme'] = clean_param($category->theme, PARAM_THEME);
1740 $categoriesinfo[] = $categoryinfo;
1741 } else {
1742 $excludedcats[$category->id] = 'visibility';
1747 // Sorting the resulting array so it looks a bit better for the client developer.
1748 usort($categoriesinfo, "core_course_external::compare_categories_by_sortorder");
1750 return $categoriesinfo;
1754 * Sort categories array by path
1755 * private function: only used by get_categories
1757 * @param array $category1
1758 * @param array $category2
1759 * @return int result of strcmp
1760 * @since Moodle 2.3
1762 private static function compare_categories_by_path($category1, $category2) {
1763 return strcmp($category1->path, $category2->path);
1767 * Sort categories array by sortorder
1768 * private function: only used by get_categories
1770 * @param array $category1
1771 * @param array $category2
1772 * @return int result of strcmp
1773 * @since Moodle 2.3
1775 private static function compare_categories_by_sortorder($category1, $category2) {
1776 return strcmp($category1['sortorder'], $category2['sortorder']);
1780 * Returns description of method result value
1782 * @return external_description
1783 * @since Moodle 2.3
1785 public static function get_categories_returns() {
1786 return new external_multiple_structure(
1787 new external_single_structure(
1788 array(
1789 'id' => new external_value(PARAM_INT, 'category id'),
1790 'name' => new external_value(PARAM_TEXT, 'category name'),
1791 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1792 'description' => new external_value(PARAM_RAW, 'category description'),
1793 'descriptionformat' => new external_format_value('description'),
1794 'parent' => new external_value(PARAM_INT, 'parent category id'),
1795 'sortorder' => new external_value(PARAM_INT, 'category sorting order'),
1796 'coursecount' => new external_value(PARAM_INT, 'number of courses in this category'),
1797 'visible' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1798 'visibleold' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1799 'timemodified' => new external_value(PARAM_INT, 'timestamp', VALUE_OPTIONAL),
1800 'depth' => new external_value(PARAM_INT, 'category depth'),
1801 'path' => new external_value(PARAM_TEXT, 'category path'),
1802 'theme' => new external_value(PARAM_THEME, 'category theme', VALUE_OPTIONAL),
1803 ), 'List of categories'
1809 * Returns description of method parameters
1811 * @return external_function_parameters
1812 * @since Moodle 2.3
1814 public static function create_categories_parameters() {
1815 return new external_function_parameters(
1816 array(
1817 'categories' => new external_multiple_structure(
1818 new external_single_structure(
1819 array(
1820 'name' => new external_value(PARAM_TEXT, 'new category name'),
1821 'parent' => new external_value(PARAM_INT,
1822 'the parent category id inside which the new category will be created
1823 - set to 0 for a root category',
1824 VALUE_DEFAULT, 0),
1825 'idnumber' => new external_value(PARAM_RAW,
1826 'the new category idnumber', VALUE_OPTIONAL),
1827 'description' => new external_value(PARAM_RAW,
1828 'the new category description', VALUE_OPTIONAL),
1829 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
1830 'theme' => new external_value(PARAM_THEME,
1831 'the new category theme. This option must be enabled on moodle',
1832 VALUE_OPTIONAL),
1841 * Create categories
1843 * @param array $categories - see create_categories_parameters() for the array structure
1844 * @return array - see create_categories_returns() for the array structure
1845 * @since Moodle 2.3
1847 public static function create_categories($categories) {
1848 global $CFG, $DB;
1849 require_once($CFG->libdir . "/coursecatlib.php");
1851 $params = self::validate_parameters(self::create_categories_parameters(),
1852 array('categories' => $categories));
1854 $transaction = $DB->start_delegated_transaction();
1856 $createdcategories = array();
1857 foreach ($params['categories'] as $category) {
1858 if ($category['parent']) {
1859 if (!$DB->record_exists('course_categories', array('id' => $category['parent']))) {
1860 throw new moodle_exception('unknowcategory');
1862 $context = context_coursecat::instance($category['parent']);
1863 } else {
1864 $context = context_system::instance();
1866 self::validate_context($context);
1867 require_capability('moodle/category:manage', $context);
1869 // this will validate format and throw an exception if there are errors
1870 external_validate_format($category['descriptionformat']);
1872 $newcategory = coursecat::create($category);
1874 $createdcategories[] = array('id' => $newcategory->id, 'name' => $newcategory->name);
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 $displayname = get_course_display_name_for_list($course);
2279 $coursereturns = array();
2280 $coursereturns['id'] = $course->id;
2281 $coursereturns['fullname'] = external_format_string($course->fullname, $coursecontext->id);
2282 $coursereturns['displayname'] = external_format_string($displayname, $coursecontext->id);
2283 $coursereturns['shortname'] = external_format_string($course->shortname, $coursecontext->id);
2284 $coursereturns['categoryid'] = $course->category;
2285 $coursereturns['categoryname'] = $category == null ? '' : $category->name;
2286 $coursereturns['summary'] = $summary;
2287 $coursereturns['summaryformat'] = $summaryformat;
2288 $coursereturns['summaryfiles'] = external_util::get_area_files($coursecontext->id, 'course', 'summary', false, false);
2289 $coursereturns['overviewfiles'] = $files;
2290 $coursereturns['contacts'] = $coursecontacts;
2291 $coursereturns['enrollmentmethods'] = $enroltypes;
2292 $coursereturns['sortorder'] = $course->sortorder;
2293 return $coursereturns;
2297 * Search courses following the specified criteria.
2299 * @param string $criterianame Criteria name (search, modulelist (only admins), blocklist (only admins), tagid)
2300 * @param string $criteriavalue Criteria value
2301 * @param int $page Page number (for pagination)
2302 * @param int $perpage Items per page
2303 * @param array $requiredcapabilities Optional list of required capabilities (used to filter the list).
2304 * @param int $limittoenrolled Limit to only enrolled courses
2305 * @return array of course objects and warnings
2306 * @since Moodle 3.0
2307 * @throws moodle_exception
2309 public static function search_courses($criterianame,
2310 $criteriavalue,
2311 $page=0,
2312 $perpage=0,
2313 $requiredcapabilities=array(),
2314 $limittoenrolled=0) {
2315 global $CFG;
2316 require_once($CFG->libdir . '/coursecatlib.php');
2318 $warnings = array();
2320 $parameters = array(
2321 'criterianame' => $criterianame,
2322 'criteriavalue' => $criteriavalue,
2323 'page' => $page,
2324 'perpage' => $perpage,
2325 'requiredcapabilities' => $requiredcapabilities
2327 $params = self::validate_parameters(self::search_courses_parameters(), $parameters);
2328 self::validate_context(context_system::instance());
2330 $allowedcriterianames = array('search', 'modulelist', 'blocklist', 'tagid');
2331 if (!in_array($params['criterianame'], $allowedcriterianames)) {
2332 throw new invalid_parameter_exception('Invalid value for criterianame parameter (value: '.$params['criterianame'].'),' .
2333 'allowed values are: '.implode(',', $allowedcriterianames));
2336 if ($params['criterianame'] == 'modulelist' or $params['criterianame'] == 'blocklist') {
2337 require_capability('moodle/site:config', context_system::instance());
2340 $paramtype = array(
2341 'search' => PARAM_RAW,
2342 'modulelist' => PARAM_PLUGIN,
2343 'blocklist' => PARAM_INT,
2344 'tagid' => PARAM_INT
2346 $params['criteriavalue'] = clean_param($params['criteriavalue'], $paramtype[$params['criterianame']]);
2348 // Prepare the search API options.
2349 $searchcriteria = array();
2350 $searchcriteria[$params['criterianame']] = $params['criteriavalue'];
2352 $options = array();
2353 if ($params['perpage'] != 0) {
2354 $offset = $params['page'] * $params['perpage'];
2355 $options = array('offset' => $offset, 'limit' => $params['perpage']);
2358 // Search the courses.
2359 $courses = coursecat::search_courses($searchcriteria, $options, $params['requiredcapabilities']);
2360 $totalcount = coursecat::search_courses_count($searchcriteria, $options, $params['requiredcapabilities']);
2362 if (!empty($limittoenrolled)) {
2363 // Get the courses where the current user has access.
2364 $enrolled = enrol_get_my_courses(array('id', 'cacherev'));
2367 $finalcourses = array();
2368 $categoriescache = array();
2370 foreach ($courses as $course) {
2371 if (!empty($limittoenrolled)) {
2372 // Filter out not enrolled courses.
2373 if (!isset($enrolled[$course->id])) {
2374 $totalcount--;
2375 continue;
2379 $coursecontext = context_course::instance($course->id);
2381 $finalcourses[] = self::get_course_public_information($course, $coursecontext);
2384 return array(
2385 'total' => $totalcount,
2386 'courses' => $finalcourses,
2387 'warnings' => $warnings
2392 * Returns a course structure definition
2394 * @param boolean $onlypublicdata set to true, to retrieve only fields viewable by anyone when the course is visible
2395 * @return array the course structure
2396 * @since Moodle 3.2
2398 protected static function get_course_structure($onlypublicdata = true) {
2399 $coursestructure = array(
2400 'id' => new external_value(PARAM_INT, 'course id'),
2401 'fullname' => new external_value(PARAM_TEXT, 'course full name'),
2402 'displayname' => new external_value(PARAM_TEXT, 'course display name'),
2403 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
2404 'categoryid' => new external_value(PARAM_INT, 'category id'),
2405 'categoryname' => new external_value(PARAM_TEXT, 'category name'),
2406 'sortorder' => new external_value(PARAM_INT, 'Sort order in the category', VALUE_OPTIONAL),
2407 'summary' => new external_value(PARAM_RAW, 'summary'),
2408 'summaryformat' => new external_format_value('summary'),
2409 'summaryfiles' => new external_files('summary files in the summary field', VALUE_OPTIONAL),
2410 'overviewfiles' => new external_files('additional overview files attached to this course'),
2411 'contacts' => new external_multiple_structure(
2412 new external_single_structure(
2413 array(
2414 'id' => new external_value(PARAM_INT, 'contact user id'),
2415 'fullname' => new external_value(PARAM_NOTAGS, 'contact user fullname'),
2418 'contact users'
2420 'enrollmentmethods' => new external_multiple_structure(
2421 new external_value(PARAM_PLUGIN, 'enrollment method'),
2422 'enrollment methods list'
2426 if (!$onlypublicdata) {
2427 $extra = array(
2428 'idnumber' => new external_value(PARAM_RAW, 'Id number', VALUE_OPTIONAL),
2429 'format' => new external_value(PARAM_PLUGIN, 'Course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
2430 'showgrades' => new external_value(PARAM_INT, '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
2431 'newsitems' => new external_value(PARAM_INT, 'Number of recent items appearing on the course page', VALUE_OPTIONAL),
2432 'startdate' => new external_value(PARAM_INT, 'Timestamp when the course start', VALUE_OPTIONAL),
2433 'enddate' => new external_value(PARAM_INT, 'Timestamp when the course end', VALUE_OPTIONAL),
2434 'maxbytes' => new external_value(PARAM_INT, 'Largest size of file that can be uploaded into', VALUE_OPTIONAL),
2435 'showreports' => new external_value(PARAM_INT, 'Are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
2436 'visible' => new external_value(PARAM_INT, '1: available to student, 0:not available', VALUE_OPTIONAL),
2437 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
2438 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
2439 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
2440 'enablecompletion' => new external_value(PARAM_INT, 'Completion enabled? 1: yes 0: no', VALUE_OPTIONAL),
2441 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
2442 'lang' => new external_value(PARAM_SAFEDIR, 'Forced course language', VALUE_OPTIONAL),
2443 'theme' => new external_value(PARAM_PLUGIN, 'Fame of the forced theme', VALUE_OPTIONAL),
2444 'marker' => new external_value(PARAM_INT, 'Current course marker', VALUE_OPTIONAL),
2445 'legacyfiles' => new external_value(PARAM_INT, 'If legacy files are enabled', VALUE_OPTIONAL),
2446 'calendartype' => new external_value(PARAM_PLUGIN, 'Calendar type', VALUE_OPTIONAL),
2447 'timecreated' => new external_value(PARAM_INT, 'Time when the course was created', VALUE_OPTIONAL),
2448 'timemodified' => new external_value(PARAM_INT, 'Last time the course was updated', VALUE_OPTIONAL),
2449 'requested' => new external_value(PARAM_INT, 'If is a requested course', VALUE_OPTIONAL),
2450 'cacherev' => new external_value(PARAM_INT, 'Cache revision number', VALUE_OPTIONAL),
2451 'filters' => new external_multiple_structure(
2452 new external_single_structure(
2453 array(
2454 'filter' => new external_value(PARAM_PLUGIN, 'Filter plugin name'),
2455 'localstate' => new external_value(PARAM_INT, 'Filter state: 1 for on, -1 for off, 0 if inherit'),
2456 'inheritedstate' => new external_value(PARAM_INT, '1 or 0 to use when localstate is set to inherit'),
2459 'Course filters', VALUE_OPTIONAL
2461 'courseformatoptions' => new external_multiple_structure(
2462 new external_single_structure(
2463 array(
2464 'name' => new external_value(PARAM_RAW, 'Course format option name.'),
2465 'value' => new external_value(PARAM_RAW, 'Course format option value.'),
2468 'Additional options for particular course format.', VALUE_OPTIONAL
2471 $coursestructure = array_merge($coursestructure, $extra);
2473 return new external_single_structure($coursestructure);
2477 * Returns description of method result value
2479 * @return external_description
2480 * @since Moodle 3.0
2482 public static function search_courses_returns() {
2483 return new external_single_structure(
2484 array(
2485 'total' => new external_value(PARAM_INT, 'total course count'),
2486 'courses' => new external_multiple_structure(self::get_course_structure(), 'course'),
2487 'warnings' => new external_warnings()
2493 * Returns description of method parameters
2495 * @return external_function_parameters
2496 * @since Moodle 3.0
2498 public static function get_course_module_parameters() {
2499 return new external_function_parameters(
2500 array(
2501 'cmid' => new external_value(PARAM_INT, 'The course module id')
2507 * Return information about a course module.
2509 * @param int $cmid the course module id
2510 * @return array of warnings and the course module
2511 * @since Moodle 3.0
2512 * @throws moodle_exception
2514 public static function get_course_module($cmid) {
2515 global $CFG, $DB;
2517 $params = self::validate_parameters(self::get_course_module_parameters(), array('cmid' => $cmid));
2518 $warnings = array();
2520 $cm = get_coursemodule_from_id(null, $params['cmid'], 0, true, MUST_EXIST);
2521 $context = context_module::instance($cm->id);
2522 self::validate_context($context);
2524 // If the user has permissions to manage the activity, return all the information.
2525 if (has_capability('moodle/course:manageactivities', $context)) {
2526 require_once($CFG->dirroot . '/course/modlib.php');
2527 require_once($CFG->libdir . '/gradelib.php');
2529 $info = $cm;
2530 // Get the extra information: grade, advanced grading and outcomes data.
2531 $course = get_course($cm->course);
2532 list($newcm, $newcontext, $module, $extrainfo, $cw) = get_moduleinfo_data($cm, $course);
2533 // Grades.
2534 $gradeinfo = array('grade', 'gradepass', 'gradecat');
2535 foreach ($gradeinfo as $gfield) {
2536 if (isset($extrainfo->{$gfield})) {
2537 $info->{$gfield} = $extrainfo->{$gfield};
2540 if (isset($extrainfo->grade) and $extrainfo->grade < 0) {
2541 $info->scale = $DB->get_field('scale', 'scale', array('id' => abs($extrainfo->grade)));
2543 // Advanced grading.
2544 if (isset($extrainfo->_advancedgradingdata)) {
2545 $info->advancedgrading = array();
2546 foreach ($extrainfo as $key => $val) {
2547 if (strpos($key, 'advancedgradingmethod_') === 0) {
2548 $info->advancedgrading[] = array(
2549 'area' => str_replace('advancedgradingmethod_', '', $key),
2550 'method' => $val
2555 // Outcomes.
2556 foreach ($extrainfo as $key => $val) {
2557 if (strpos($key, 'outcome_') === 0) {
2558 if (!isset($info->outcomes)) {
2559 $info->outcomes = array();
2561 $id = str_replace('outcome_', '', $key);
2562 $outcome = grade_outcome::fetch(array('id' => $id));
2563 $scaleitems = $outcome->load_scale();
2564 $info->outcomes[] = array(
2565 'id' => $id,
2566 'name' => external_format_string($outcome->get_name(), $context->id),
2567 'scale' => $scaleitems->scale
2571 } else {
2572 // Return information is safe to show to any user.
2573 $info = new stdClass();
2574 $info->id = $cm->id;
2575 $info->course = $cm->course;
2576 $info->module = $cm->module;
2577 $info->modname = $cm->modname;
2578 $info->instance = $cm->instance;
2579 $info->section = $cm->section;
2580 $info->sectionnum = $cm->sectionnum;
2581 $info->groupmode = $cm->groupmode;
2582 $info->groupingid = $cm->groupingid;
2583 $info->completion = $cm->completion;
2585 // Format name.
2586 $info->name = external_format_string($cm->name, $context->id);
2587 $result = array();
2588 $result['cm'] = $info;
2589 $result['warnings'] = $warnings;
2590 return $result;
2594 * Returns description of method result value
2596 * @return external_description
2597 * @since Moodle 3.0
2599 public static function get_course_module_returns() {
2600 return new external_single_structure(
2601 array(
2602 'cm' => new external_single_structure(
2603 array(
2604 'id' => new external_value(PARAM_INT, 'The course module id'),
2605 'course' => new external_value(PARAM_INT, 'The course id'),
2606 'module' => new external_value(PARAM_INT, 'The module type id'),
2607 'name' => new external_value(PARAM_RAW, 'The activity name'),
2608 'modname' => new external_value(PARAM_COMPONENT, 'The module component name (forum, assign, etc..)'),
2609 'instance' => new external_value(PARAM_INT, 'The activity instance id'),
2610 'section' => new external_value(PARAM_INT, 'The module section id'),
2611 'sectionnum' => new external_value(PARAM_INT, 'The module section number'),
2612 'groupmode' => new external_value(PARAM_INT, 'Group mode'),
2613 'groupingid' => new external_value(PARAM_INT, 'Grouping id'),
2614 'completion' => new external_value(PARAM_INT, 'If completion is enabled'),
2615 'idnumber' => new external_value(PARAM_RAW, 'Module id number', VALUE_OPTIONAL),
2616 'added' => new external_value(PARAM_INT, 'Time added', VALUE_OPTIONAL),
2617 'score' => new external_value(PARAM_INT, 'Score', VALUE_OPTIONAL),
2618 'indent' => new external_value(PARAM_INT, 'Indentation', VALUE_OPTIONAL),
2619 'visible' => new external_value(PARAM_INT, 'If visible', VALUE_OPTIONAL),
2620 'visibleoncoursepage' => new external_value(PARAM_INT, 'If visible on course page', VALUE_OPTIONAL),
2621 'visibleold' => new external_value(PARAM_INT, 'Visible old', VALUE_OPTIONAL),
2622 'completiongradeitemnumber' => new external_value(PARAM_INT, 'Completion grade item', VALUE_OPTIONAL),
2623 'completionview' => new external_value(PARAM_INT, 'Completion view setting', VALUE_OPTIONAL),
2624 'completionexpected' => new external_value(PARAM_INT, 'Completion time expected', VALUE_OPTIONAL),
2625 'showdescription' => new external_value(PARAM_INT, 'If the description is showed', VALUE_OPTIONAL),
2626 'availability' => new external_value(PARAM_RAW, 'Availability settings', VALUE_OPTIONAL),
2627 'grade' => new external_value(PARAM_FLOAT, 'Grade (max value or scale id)', VALUE_OPTIONAL),
2628 'scale' => new external_value(PARAM_TEXT, 'Scale items (if used)', VALUE_OPTIONAL),
2629 'gradepass' => new external_value(PARAM_RAW, 'Grade to pass (float)', VALUE_OPTIONAL),
2630 'gradecat' => new external_value(PARAM_INT, 'Grade category', VALUE_OPTIONAL),
2631 'advancedgrading' => new external_multiple_structure(
2632 new external_single_structure(
2633 array(
2634 'area' => new external_value(PARAM_AREA, 'Gradable area name'),
2635 'method' => new external_value(PARAM_COMPONENT, 'Grading method'),
2638 'Advanced grading settings', VALUE_OPTIONAL
2640 'outcomes' => new external_multiple_structure(
2641 new external_single_structure(
2642 array(
2643 'id' => new external_value(PARAM_ALPHANUMEXT, 'Outcome id'),
2644 'name' => new external_value(PARAM_TEXT, 'Outcome full name'),
2645 'scale' => new external_value(PARAM_TEXT, 'Scale items')
2648 'Outcomes information', VALUE_OPTIONAL
2652 'warnings' => new external_warnings()
2658 * Returns description of method parameters
2660 * @return external_function_parameters
2661 * @since Moodle 3.0
2663 public static function get_course_module_by_instance_parameters() {
2664 return new external_function_parameters(
2665 array(
2666 'module' => new external_value(PARAM_COMPONENT, 'The module name'),
2667 'instance' => new external_value(PARAM_INT, 'The module instance id')
2673 * Return information about a course module.
2675 * @param string $module the module name
2676 * @param int $instance the activity instance id
2677 * @return array of warnings and the course module
2678 * @since Moodle 3.0
2679 * @throws moodle_exception
2681 public static function get_course_module_by_instance($module, $instance) {
2683 $params = self::validate_parameters(self::get_course_module_by_instance_parameters(),
2684 array(
2685 'module' => $module,
2686 'instance' => $instance,
2689 $warnings = array();
2690 $cm = get_coursemodule_from_instance($params['module'], $params['instance'], 0, false, MUST_EXIST);
2692 return self::get_course_module($cm->id);
2696 * Returns description of method result value
2698 * @return external_description
2699 * @since Moodle 3.0
2701 public static function get_course_module_by_instance_returns() {
2702 return self::get_course_module_returns();
2706 * Returns description of method parameters
2708 * @deprecated since 3.3
2709 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
2710 * @return external_function_parameters
2711 * @since Moodle 3.2
2713 public static function get_activities_overview_parameters() {
2714 return new external_function_parameters(
2715 array(
2716 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2722 * Return activities overview for the given courses.
2724 * @deprecated since 3.3
2725 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
2726 * @param array $courseids a list of course ids
2727 * @return array of warnings and the activities overview
2728 * @since Moodle 3.2
2729 * @throws moodle_exception
2731 public static function get_activities_overview($courseids) {
2732 global $USER;
2734 // Parameter validation.
2735 $params = self::validate_parameters(self::get_activities_overview_parameters(), array('courseids' => $courseids));
2736 $courseoverviews = array();
2738 list($courses, $warnings) = external_util::validate_courses($params['courseids']);
2740 if (!empty($courses)) {
2741 // Add lastaccess to each course (required by print_overview function).
2742 // We need the complete user data, the ws server does not load a complete one.
2743 $user = get_complete_user_data('id', $USER->id);
2744 foreach ($courses as $course) {
2745 if (isset($user->lastcourseaccess[$course->id])) {
2746 $course->lastaccess = $user->lastcourseaccess[$course->id];
2747 } else {
2748 $course->lastaccess = 0;
2752 $overviews = array();
2753 if ($modules = get_plugin_list_with_function('mod', 'print_overview')) {
2754 foreach ($modules as $fname) {
2755 $fname($courses, $overviews);
2759 // Format output.
2760 foreach ($overviews as $courseid => $modules) {
2761 $courseoverviews[$courseid]['id'] = $courseid;
2762 $courseoverviews[$courseid]['overviews'] = array();
2764 foreach ($modules as $modname => $overviewtext) {
2765 $courseoverviews[$courseid]['overviews'][] = array(
2766 'module' => $modname,
2767 'overviewtext' => $overviewtext // This text doesn't need formatting.
2773 $result = array(
2774 'courses' => $courseoverviews,
2775 'warnings' => $warnings
2777 return $result;
2781 * Returns description of method result value
2783 * @deprecated since 3.3
2784 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
2785 * @return external_description
2786 * @since Moodle 3.2
2788 public static function get_activities_overview_returns() {
2789 return new external_single_structure(
2790 array(
2791 'courses' => new external_multiple_structure(
2792 new external_single_structure(
2793 array(
2794 'id' => new external_value(PARAM_INT, 'Course id'),
2795 'overviews' => new external_multiple_structure(
2796 new external_single_structure(
2797 array(
2798 'module' => new external_value(PARAM_PLUGIN, 'Module name'),
2799 'overviewtext' => new external_value(PARAM_RAW, 'Overview text'),
2804 ), 'List of courses'
2806 'warnings' => new external_warnings()
2812 * Marking the method as deprecated.
2814 * @return bool
2816 public static function get_activities_overview_is_deprecated() {
2817 return true;
2821 * Returns description of method parameters
2823 * @return external_function_parameters
2824 * @since Moodle 3.2
2826 public static function get_user_navigation_options_parameters() {
2827 return new external_function_parameters(
2828 array(
2829 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2835 * Return a list of navigation options in a set of courses that are avaialable or not for the current user.
2837 * @param array $courseids a list of course ids
2838 * @return array of warnings and the options availability
2839 * @since Moodle 3.2
2840 * @throws moodle_exception
2842 public static function get_user_navigation_options($courseids) {
2843 global $CFG;
2844 require_once($CFG->dirroot . '/course/lib.php');
2846 // Parameter validation.
2847 $params = self::validate_parameters(self::get_user_navigation_options_parameters(), array('courseids' => $courseids));
2848 $courseoptions = array();
2850 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
2852 if (!empty($courses)) {
2853 foreach ($courses as $course) {
2854 // Fix the context for the frontpage.
2855 if ($course->id == SITEID) {
2856 $course->context = context_system::instance();
2858 $navoptions = course_get_user_navigation_options($course->context, $course);
2859 $options = array();
2860 foreach ($navoptions as $name => $available) {
2861 $options[] = array(
2862 'name' => $name,
2863 'available' => $available,
2867 $courseoptions[] = array(
2868 'id' => $course->id,
2869 'options' => $options
2874 $result = array(
2875 'courses' => $courseoptions,
2876 'warnings' => $warnings
2878 return $result;
2882 * Returns description of method result value
2884 * @return external_description
2885 * @since Moodle 3.2
2887 public static function get_user_navigation_options_returns() {
2888 return new external_single_structure(
2889 array(
2890 'courses' => new external_multiple_structure(
2891 new external_single_structure(
2892 array(
2893 'id' => new external_value(PARAM_INT, 'Course id'),
2894 'options' => new external_multiple_structure(
2895 new external_single_structure(
2896 array(
2897 'name' => new external_value(PARAM_ALPHANUMEXT, 'Option name'),
2898 'available' => new external_value(PARAM_BOOL, 'Whether the option is available or not'),
2903 ), 'List of courses'
2905 'warnings' => new external_warnings()
2911 * Returns description of method parameters
2913 * @return external_function_parameters
2914 * @since Moodle 3.2
2916 public static function get_user_administration_options_parameters() {
2917 return new external_function_parameters(
2918 array(
2919 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2925 * Return a list of administration options in a set of courses that are available or not for the current user.
2927 * @param array $courseids a list of course ids
2928 * @return array of warnings and the options availability
2929 * @since Moodle 3.2
2930 * @throws moodle_exception
2932 public static function get_user_administration_options($courseids) {
2933 global $CFG;
2934 require_once($CFG->dirroot . '/course/lib.php');
2936 // Parameter validation.
2937 $params = self::validate_parameters(self::get_user_administration_options_parameters(), array('courseids' => $courseids));
2938 $courseoptions = array();
2940 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
2942 if (!empty($courses)) {
2943 foreach ($courses as $course) {
2944 $adminoptions = course_get_user_administration_options($course, $course->context);
2945 $options = array();
2946 foreach ($adminoptions as $name => $available) {
2947 $options[] = array(
2948 'name' => $name,
2949 'available' => $available,
2953 $courseoptions[] = array(
2954 'id' => $course->id,
2955 'options' => $options
2960 $result = array(
2961 'courses' => $courseoptions,
2962 'warnings' => $warnings
2964 return $result;
2968 * Returns description of method result value
2970 * @return external_description
2971 * @since Moodle 3.2
2973 public static function get_user_administration_options_returns() {
2974 return self::get_user_navigation_options_returns();
2978 * Returns description of method parameters
2980 * @return external_function_parameters
2981 * @since Moodle 3.2
2983 public static function get_courses_by_field_parameters() {
2984 return new external_function_parameters(
2985 array(
2986 'field' => new external_value(PARAM_ALPHA, 'The field to search can be left empty for all courses or:
2987 id: course id
2988 ids: comma separated course ids
2989 shortname: course short name
2990 idnumber: course id number
2991 category: category id the course belongs to
2992 ', VALUE_DEFAULT, ''),
2993 'value' => new external_value(PARAM_RAW, 'The value to match', VALUE_DEFAULT, '')
3000 * Get courses matching a specific field (id/s, shortname, idnumber, category)
3002 * @param string $field field name to search, or empty for all courses
3003 * @param string $value value to search
3004 * @return array list of courses and warnings
3005 * @throws invalid_parameter_exception
3006 * @since Moodle 3.2
3008 public static function get_courses_by_field($field = '', $value = '') {
3009 global $DB, $CFG;
3010 require_once($CFG->libdir . '/coursecatlib.php');
3011 require_once($CFG->libdir . '/filterlib.php');
3013 $params = self::validate_parameters(self::get_courses_by_field_parameters(),
3014 array(
3015 'field' => $field,
3016 'value' => $value,
3019 $warnings = array();
3021 if (empty($params['field'])) {
3022 $courses = $DB->get_records('course', null, 'id ASC');
3023 } else {
3024 switch ($params['field']) {
3025 case 'id':
3026 case 'category':
3027 $value = clean_param($params['value'], PARAM_INT);
3028 break;
3029 case 'ids':
3030 $value = clean_param($params['value'], PARAM_SEQUENCE);
3031 break;
3032 case 'shortname':
3033 $value = clean_param($params['value'], PARAM_TEXT);
3034 break;
3035 case 'idnumber':
3036 $value = clean_param($params['value'], PARAM_RAW);
3037 break;
3038 default:
3039 throw new invalid_parameter_exception('Invalid field name');
3042 if ($params['field'] === 'ids') {
3043 $courses = $DB->get_records_list('course', 'id', explode(',', $value), 'id ASC');
3044 } else {
3045 $courses = $DB->get_records('course', array($params['field'] => $value), 'id ASC');
3049 $coursesdata = array();
3050 foreach ($courses as $course) {
3051 $context = context_course::instance($course->id);
3052 $canupdatecourse = has_capability('moodle/course:update', $context);
3053 $canviewhiddencourses = has_capability('moodle/course:viewhiddencourses', $context);
3055 // Check if the course is visible in the site for the user.
3056 if (!$course->visible and !$canviewhiddencourses and !$canupdatecourse) {
3057 continue;
3059 // Get the public course information, even if we are not enrolled.
3060 $courseinlist = new course_in_list($course);
3061 $coursesdata[$course->id] = self::get_course_public_information($courseinlist, $context);
3063 // Now, check if we have access to the course.
3064 try {
3065 self::validate_context($context);
3066 } catch (Exception $e) {
3067 continue;
3069 // Return information for any user that can access the course.
3070 $coursefields = array('format', 'showgrades', 'newsitems', 'startdate', 'enddate', 'maxbytes', 'showreports', 'visible',
3071 'groupmode', 'groupmodeforce', 'defaultgroupingid', 'enablecompletion', 'completionnotify', 'lang', 'theme',
3072 'marker');
3074 // Course filters.
3075 $coursesdata[$course->id]['filters'] = filter_get_available_in_context($context);
3077 // Information for managers only.
3078 if ($canupdatecourse) {
3079 $managerfields = array('idnumber', 'legacyfiles', 'calendartype', 'timecreated', 'timemodified', 'requested',
3080 'cacherev');
3081 $coursefields = array_merge($coursefields, $managerfields);
3084 // Populate fields.
3085 foreach ($coursefields as $field) {
3086 $coursesdata[$course->id][$field] = $course->{$field};
3089 // Clean lang and auth fields for external functions (it may content uninstalled themes or language packs).
3090 if (isset($coursesdata[$course->id]['theme'])) {
3091 $coursesdata[$course->id]['theme'] = clean_param($coursesdata[$course->id]['theme'], PARAM_THEME);
3093 if (isset($coursesdata[$course->id]['lang'])) {
3094 $coursesdata[$course->id]['lang'] = clean_param($coursesdata[$course->id]['lang'], PARAM_LANG);
3097 $courseformatoptions = course_get_format($course)->get_config_for_external();
3098 foreach ($courseformatoptions as $key => $value) {
3099 $coursesdata[$course->id]['courseformatoptions'][] = array(
3100 'name' => $key,
3101 'value' => $value
3106 return array(
3107 'courses' => $coursesdata,
3108 'warnings' => $warnings
3113 * Returns description of method result value
3115 * @return external_description
3116 * @since Moodle 3.2
3118 public static function get_courses_by_field_returns() {
3119 // Course structure, including not only public viewable fields.
3120 return new external_single_structure(
3121 array(
3122 'courses' => new external_multiple_structure(self::get_course_structure(false), 'Course'),
3123 'warnings' => new external_warnings()
3129 * Returns description of method parameters
3131 * @return external_function_parameters
3132 * @since Moodle 3.2
3134 public static function check_updates_parameters() {
3135 return new external_function_parameters(
3136 array(
3137 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3138 'tocheck' => new external_multiple_structure(
3139 new external_single_structure(
3140 array(
3141 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level for the file location.
3142 Only module supported right now.'),
3143 'id' => new external_value(PARAM_INT, 'Context instance id'),
3144 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3147 'Instances to check'
3149 'filter' => new external_multiple_structure(
3150 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3151 gradeitems, outcomes'),
3152 'Check only for updates in these areas', VALUE_DEFAULT, array()
3159 * Check if there is updates affecting the user for the given course and contexts.
3160 * Right now only modules are supported.
3161 * This WS calls mod_check_updates_since for each module to check if there is any update the user should we aware of.
3163 * @param int $courseid the list of modules to check
3164 * @param array $tocheck the list of modules to check
3165 * @param array $filter check only for updates in these areas
3166 * @return array list of updates and warnings
3167 * @throws moodle_exception
3168 * @since Moodle 3.2
3170 public static function check_updates($courseid, $tocheck, $filter = array()) {
3171 global $CFG, $DB;
3172 require_once($CFG->dirroot . "/course/lib.php");
3174 $params = self::validate_parameters(
3175 self::check_updates_parameters(),
3176 array(
3177 'courseid' => $courseid,
3178 'tocheck' => $tocheck,
3179 'filter' => $filter,
3183 $course = get_course($params['courseid']);
3184 $context = context_course::instance($course->id);
3185 self::validate_context($context);
3187 list($instances, $warnings) = course_check_updates($course, $params['tocheck'], $filter);
3189 $instancesformatted = array();
3190 foreach ($instances as $instance) {
3191 $updates = array();
3192 foreach ($instance['updates'] as $name => $data) {
3193 if (empty($data->updated)) {
3194 continue;
3196 $updatedata = array(
3197 'name' => $name,
3199 if (!empty($data->timeupdated)) {
3200 $updatedata['timeupdated'] = $data->timeupdated;
3202 if (!empty($data->itemids)) {
3203 $updatedata['itemids'] = $data->itemids;
3205 $updates[] = $updatedata;
3207 if (!empty($updates)) {
3208 $instancesformatted[] = array(
3209 'contextlevel' => $instance['contextlevel'],
3210 'id' => $instance['id'],
3211 'updates' => $updates
3216 return array(
3217 'instances' => $instancesformatted,
3218 'warnings' => $warnings
3223 * Returns description of method result value
3225 * @return external_description
3226 * @since Moodle 3.2
3228 public static function check_updates_returns() {
3229 return new external_single_structure(
3230 array(
3231 'instances' => new external_multiple_structure(
3232 new external_single_structure(
3233 array(
3234 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level'),
3235 'id' => new external_value(PARAM_INT, 'Instance id'),
3236 'updates' => new external_multiple_structure(
3237 new external_single_structure(
3238 array(
3239 'name' => new external_value(PARAM_ALPHANUMEXT, 'Name of the area updated.'),
3240 'timeupdated' => new external_value(PARAM_INT, 'Last time was updated', VALUE_OPTIONAL),
3241 'itemids' => new external_multiple_structure(
3242 new external_value(PARAM_INT, 'Instance id'),
3243 'The ids of the items updated',
3244 VALUE_OPTIONAL
3252 'warnings' => new external_warnings()
3258 * Returns description of method parameters
3260 * @return external_function_parameters
3261 * @since Moodle 3.3
3263 public static function get_updates_since_parameters() {
3264 return new external_function_parameters(
3265 array(
3266 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3267 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3268 'filter' => new external_multiple_structure(
3269 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3270 gradeitems, outcomes'),
3271 'Check only for updates in these areas', VALUE_DEFAULT, array()
3278 * Check if there are updates affecting the user for the given course since the given time stamp.
3280 * This function is a wrapper of self::check_updates for retrieving all the updates since a given time for all the activities.
3282 * @param int $courseid the list of modules to check
3283 * @param int $since check updates since this time stamp
3284 * @param array $filter check only for updates in these areas
3285 * @return array list of updates and warnings
3286 * @throws moodle_exception
3287 * @since Moodle 3.3
3289 public static function get_updates_since($courseid, $since, $filter = array()) {
3290 global $CFG, $DB;
3292 $params = self::validate_parameters(
3293 self::get_updates_since_parameters(),
3294 array(
3295 'courseid' => $courseid,
3296 'since' => $since,
3297 'filter' => $filter,
3301 $course = get_course($params['courseid']);
3302 $modinfo = get_fast_modinfo($course);
3303 $tocheck = array();
3305 // Retrieve all the visible course modules for the current user.
3306 $cms = $modinfo->get_cms();
3307 foreach ($cms as $cm) {
3308 if (!$cm->uservisible) {
3309 continue;
3311 $tocheck[] = array(
3312 'id' => $cm->id,
3313 'contextlevel' => 'module',
3314 'since' => $params['since'],
3318 return self::check_updates($course->id, $tocheck, $params['filter']);
3322 * Returns description of method result value
3324 * @return external_description
3325 * @since Moodle 3.3
3327 public static function get_updates_since_returns() {
3328 return self::check_updates_returns();
3332 * Parameters for function edit_module()
3334 * @since Moodle 3.3
3335 * @return external_function_parameters
3337 public static function edit_module_parameters() {
3338 return new external_function_parameters(
3339 array(
3340 'action' => new external_value(PARAM_ALPHA,
3341 'action: hide, show, stealth, duplicate, delete, moveleft, moveright, group...', VALUE_REQUIRED),
3342 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3343 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3348 * Performs one of the edit module actions and return new html for AJAX
3350 * Returns html to replace the current module html with, for example:
3351 * - empty string for "delete" action,
3352 * - two modules html for "duplicate" action
3353 * - updated module html for everything else
3355 * Throws exception if operation is not permitted/possible
3357 * @since Moodle 3.3
3358 * @param string $action
3359 * @param int $id
3360 * @param null|int $sectionreturn
3361 * @return string
3363 public static function edit_module($action, $id, $sectionreturn = null) {
3364 global $PAGE, $DB;
3365 // Validate and normalize parameters.
3366 $params = self::validate_parameters(self::edit_module_parameters(),
3367 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3368 $action = $params['action'];
3369 $id = $params['id'];
3370 $sectionreturn = $params['sectionreturn'];
3372 list($course, $cm) = get_course_and_cm_from_cmid($id);
3373 $modcontext = context_module::instance($cm->id);
3374 $coursecontext = context_course::instance($course->id);
3375 self::validate_context($modcontext);
3376 $courserenderer = $PAGE->get_renderer('core', 'course');
3377 $completioninfo = new completion_info($course);
3379 switch($action) {
3380 case 'hide':
3381 case 'show':
3382 case 'stealth':
3383 require_capability('moodle/course:activityvisibility', $modcontext);
3384 $visible = ($action === 'hide') ? 0 : 1;
3385 $visibleoncoursepage = ($action === 'stealth') ? 0 : 1;
3386 set_coursemodule_visible($id, $visible, $visibleoncoursepage);
3387 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3388 break;
3389 case 'duplicate':
3390 require_capability('moodle/course:manageactivities', $coursecontext);
3391 require_capability('moodle/backup:backuptargetimport', $coursecontext);
3392 require_capability('moodle/restore:restoretargetimport', $coursecontext);
3393 if (!course_allowed_module($course, $cm->modname)) {
3394 throw new moodle_exception('No permission to create that activity');
3396 if ($newcm = duplicate_module($course, $cm)) {
3397 $cm = get_fast_modinfo($course)->get_cm($id);
3398 $newcm = get_fast_modinfo($course)->get_cm($newcm->id);
3399 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn) .
3400 $courserenderer->course_section_cm_list_item($course, $completioninfo, $newcm, $sectionreturn);
3402 break;
3403 case 'groupsseparate':
3404 case 'groupsvisible':
3405 case 'groupsnone':
3406 require_capability('moodle/course:manageactivities', $modcontext);
3407 if ($action === 'groupsseparate') {
3408 $newgroupmode = SEPARATEGROUPS;
3409 } else if ($action === 'groupsvisible') {
3410 $newgroupmode = VISIBLEGROUPS;
3411 } else {
3412 $newgroupmode = NOGROUPS;
3414 if (set_coursemodule_groupmode($cm->id, $newgroupmode)) {
3415 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3417 break;
3418 case 'moveleft':
3419 case 'moveright':
3420 require_capability('moodle/course:manageactivities', $modcontext);
3421 $indent = $cm->indent + (($action === 'moveright') ? 1 : -1);
3422 if ($cm->indent >= 0) {
3423 $DB->update_record('course_modules', array('id' => $cm->id, 'indent' => $indent));
3424 rebuild_course_cache($cm->course);
3426 break;
3427 case 'delete':
3428 require_capability('moodle/course:manageactivities', $modcontext);
3429 course_delete_module($cm->id, true);
3430 return '';
3431 default:
3432 throw new coding_exception('Unrecognised action');
3435 $cm = get_fast_modinfo($course)->get_cm($id);
3436 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn);
3440 * Return structure for edit_module()
3442 * @since Moodle 3.3
3443 * @return external_description
3445 public static function edit_module_returns() {
3446 return new external_value(PARAM_RAW, 'html to replace the current module with');
3450 * Parameters for function get_module()
3452 * @since Moodle 3.3
3453 * @return external_function_parameters
3455 public static function get_module_parameters() {
3456 return new external_function_parameters(
3457 array(
3458 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3459 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3464 * Returns html for displaying one activity module on course page
3466 * @since Moodle 3.3
3467 * @param int $id
3468 * @param null|int $sectionreturn
3469 * @return string
3471 public static function get_module($id, $sectionreturn = null) {
3472 global $PAGE;
3473 // Validate and normalize parameters.
3474 $params = self::validate_parameters(self::get_module_parameters(),
3475 array('id' => $id, 'sectionreturn' => $sectionreturn));
3476 $id = $params['id'];
3477 $sectionreturn = $params['sectionreturn'];
3479 // Validate access to the course (note, this is html for the course view page, we don't validate access to the module).
3480 list($course, $cm) = get_course_and_cm_from_cmid($id);
3481 self::validate_context(context_course::instance($course->id));
3483 $courserenderer = $PAGE->get_renderer('core', 'course');
3484 $completioninfo = new completion_info($course);
3485 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn);
3489 * Return structure for edit_module()
3491 * @since Moodle 3.3
3492 * @return external_description
3494 public static function get_module_returns() {
3495 return new external_value(PARAM_RAW, 'html to replace the current module with');
3499 * Parameters for function edit_section()
3501 * @since Moodle 3.3
3502 * @return external_function_parameters
3504 public static function edit_section_parameters() {
3505 return new external_function_parameters(
3506 array(
3507 'action' => new external_value(PARAM_ALPHA, 'action: hide, show, stealth, setmarker, removemarker', VALUE_REQUIRED),
3508 'id' => new external_value(PARAM_INT, 'course section id', VALUE_REQUIRED),
3509 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3514 * Performs one of the edit section actions
3516 * @since Moodle 3.3
3517 * @param string $action
3518 * @param int $id section id
3519 * @param int $sectionreturn section to return to
3520 * @return string
3522 public static function edit_section($action, $id, $sectionreturn) {
3523 global $DB;
3524 // Validate and normalize parameters.
3525 $params = self::validate_parameters(self::edit_section_parameters(),
3526 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3527 $action = $params['action'];
3528 $id = $params['id'];
3529 $sr = $params['sectionreturn'];
3531 $section = $DB->get_record('course_sections', array('id' => $id), '*', MUST_EXIST);
3532 $coursecontext = context_course::instance($section->course);
3533 self::validate_context($coursecontext);
3535 $rv = course_get_format($section->course)->section_action($section, $action, $sectionreturn);
3536 if ($rv) {
3537 return json_encode($rv);
3538 } else {
3539 return null;
3544 * Return structure for edit_section()
3546 * @since Moodle 3.3
3547 * @return external_description
3549 public static function edit_section_returns() {
3550 return new external_value(PARAM_RAW, 'Additional data for javascript (JSON-encoded string)');