MDL-64285 core: Fix environment check test
[moodle.git] / course / externallib.php
blobdb977387af4965bd370dcd6330f88354cab506fb
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 includestealthmodules (bool) Return stealth modules for students in a special
60 section (with id -1)
61 sectionid (int) Return only this section
62 sectionnumber (int) Return only this section with number (order)
63 cmid (int) Return only this module information (among the whole sections structure)
64 modname (string) Return only modules with this name "label, forum, etc..."
65 modid (int) Return only the module with this id (to be used with modname'),
66 'value' => new external_value(PARAM_RAW, 'the value of the option,
67 this param is personaly validated in the external function.')
69 ), 'Options, used since Moodle 2.9', VALUE_DEFAULT, array())
74 /**
75 * Get course contents
77 * @param int $courseid course id
78 * @param array $options Options for filtering the results, used since Moodle 2.9
79 * @return array
80 * @since Moodle 2.9 Options available
81 * @since Moodle 2.2
83 public static function get_course_contents($courseid, $options = array()) {
84 global $CFG, $DB;
85 require_once($CFG->dirroot . "/course/lib.php");
87 //validate parameter
88 $params = self::validate_parameters(self::get_course_contents_parameters(),
89 array('courseid' => $courseid, 'options' => $options));
91 $filters = array();
92 if (!empty($params['options'])) {
94 foreach ($params['options'] as $option) {
95 $name = trim($option['name']);
96 // Avoid duplicated options.
97 if (!isset($filters[$name])) {
98 switch ($name) {
99 case 'excludemodules':
100 case 'excludecontents':
101 case 'includestealthmodules':
102 $value = clean_param($option['value'], PARAM_BOOL);
103 $filters[$name] = $value;
104 break;
105 case 'sectionid':
106 case 'sectionnumber':
107 case 'cmid':
108 case 'modid':
109 $value = clean_param($option['value'], PARAM_INT);
110 if (is_numeric($value)) {
111 $filters[$name] = $value;
112 } else {
113 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
115 break;
116 case 'modname':
117 $value = clean_param($option['value'], PARAM_PLUGIN);
118 if ($value) {
119 $filters[$name] = $value;
120 } else {
121 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
123 break;
124 default:
125 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
131 //retrieve the course
132 $course = $DB->get_record('course', array('id' => $params['courseid']), '*', MUST_EXIST);
134 if ($course->id != SITEID) {
135 // Check course format exist.
136 if (!file_exists($CFG->dirroot . '/course/format/' . $course->format . '/lib.php')) {
137 throw new moodle_exception('cannotgetcoursecontents', 'webservice', '', null,
138 get_string('courseformatnotfound', 'error', $course->format));
139 } else {
140 require_once($CFG->dirroot . '/course/format/' . $course->format . '/lib.php');
144 // now security checks
145 $context = context_course::instance($course->id, IGNORE_MISSING);
146 try {
147 self::validate_context($context);
148 } catch (Exception $e) {
149 $exceptionparam = new stdClass();
150 $exceptionparam->message = $e->getMessage();
151 $exceptionparam->courseid = $course->id;
152 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
155 $canupdatecourse = has_capability('moodle/course:update', $context);
157 //create return value
158 $coursecontents = array();
160 if ($canupdatecourse or $course->visible
161 or has_capability('moodle/course:viewhiddencourses', $context)) {
163 //retrieve sections
164 $modinfo = get_fast_modinfo($course);
165 $sections = $modinfo->get_section_info_all();
166 $coursenumsections = course_get_format($course)->get_last_section_number();
167 $stealthmodules = array(); // Array to keep all the modules available but not visible in a course section/topic.
169 //for each sections (first displayed to last displayed)
170 $modinfosections = $modinfo->get_sections();
171 foreach ($sections as $key => $section) {
173 // This becomes true when we are filtering and we found the value to filter with.
174 $sectionfound = false;
176 // Filter by section id.
177 if (!empty($filters['sectionid'])) {
178 if ($section->id != $filters['sectionid']) {
179 continue;
180 } else {
181 $sectionfound = true;
185 // Filter by section number. Note that 0 is a valid section number.
186 if (isset($filters['sectionnumber'])) {
187 if ($key != $filters['sectionnumber']) {
188 continue;
189 } else {
190 $sectionfound = true;
194 // reset $sectioncontents
195 $sectionvalues = array();
196 $sectionvalues['id'] = $section->id;
197 $sectionvalues['name'] = get_section_name($course, $section);
198 $sectionvalues['visible'] = $section->visible;
200 $options = (object) array('noclean' => true);
201 list($sectionvalues['summary'], $sectionvalues['summaryformat']) =
202 external_format_text($section->summary, $section->summaryformat,
203 $context->id, 'course', 'section', $section->id, $options);
204 $sectionvalues['section'] = $section->section;
205 $sectionvalues['hiddenbynumsections'] = $section->section > $coursenumsections ? 1 : 0;
206 $sectionvalues['uservisible'] = $section->uservisible;
207 if (!empty($section->availableinfo)) {
208 $sectionvalues['availabilityinfo'] = \core_availability\info::format_info($section->availableinfo, $course);
211 $sectioncontents = array();
213 // For each module of the section.
214 if (empty($filters['excludemodules']) and !empty($modinfosections[$section->section])) {
215 foreach ($modinfosections[$section->section] as $cmid) {
216 $cm = $modinfo->cms[$cmid];
218 // Stop here if the module is not visible to the user on the course main page:
219 // The user can't access the module and the user can't view the module on the course page.
220 if (!$cm->uservisible && !$cm->is_visible_on_course_page()) {
221 continue;
224 // This becomes true when we are filtering and we found the value to filter with.
225 $modfound = false;
227 // Filter by cmid.
228 if (!empty($filters['cmid'])) {
229 if ($cmid != $filters['cmid']) {
230 continue;
231 } else {
232 $modfound = true;
236 // Filter by module name and id.
237 if (!empty($filters['modname'])) {
238 if ($cm->modname != $filters['modname']) {
239 continue;
240 } else if (!empty($filters['modid'])) {
241 if ($cm->instance != $filters['modid']) {
242 continue;
243 } else {
244 // Note that if we are only filtering by modname we don't break the loop.
245 $modfound = true;
250 $module = array();
252 $modcontext = context_module::instance($cm->id);
254 //common info (for people being able to see the module or availability dates)
255 $module['id'] = $cm->id;
256 $module['name'] = external_format_string($cm->name, $modcontext->id);
257 $module['instance'] = $cm->instance;
258 $module['modname'] = $cm->modname;
259 $module['modplural'] = $cm->modplural;
260 $module['modicon'] = $cm->get_icon_url()->out(false);
261 $module['indent'] = $cm->indent;
263 if (!empty($cm->showdescription) or $cm->modname == 'label') {
264 // We want to use the external format. However from reading get_formatted_content(), $cm->content format is always FORMAT_HTML.
265 $options = array('noclean' => true);
266 list($module['description'], $descriptionformat) = external_format_text($cm->content,
267 FORMAT_HTML, $modcontext->id, $cm->modname, 'intro', $cm->id, $options);
270 //url of the module
271 $url = $cm->url;
272 if ($url) { //labels don't have url
273 $module['url'] = $url->out(false);
276 $canviewhidden = has_capability('moodle/course:viewhiddenactivities',
277 context_module::instance($cm->id));
278 //user that can view hidden module should know about the visibility
279 $module['visible'] = $cm->visible;
280 $module['visibleoncoursepage'] = $cm->visibleoncoursepage;
281 $module['uservisible'] = $cm->uservisible;
282 if (!empty($cm->availableinfo)) {
283 $module['availabilityinfo'] = \core_availability\info::format_info($cm->availableinfo, $course);
286 // Availability date (also send to user who can see hidden module).
287 if ($CFG->enableavailability && ($canviewhidden || $canupdatecourse)) {
288 $module['availability'] = $cm->availability;
291 // Return contents only if the user can access to the module.
292 if ($cm->uservisible) {
293 $baseurl = 'webservice/pluginfile.php';
295 // Call $modulename_export_contents (each module callback take care about checking the capabilities).
296 require_once($CFG->dirroot . '/mod/' . $cm->modname . '/lib.php');
297 $getcontentfunction = $cm->modname.'_export_contents';
298 if (function_exists($getcontentfunction)) {
299 if (empty($filters['excludecontents']) and $contents = $getcontentfunction($cm, $baseurl)) {
300 $module['contents'] = $contents;
301 } else {
302 $module['contents'] = array();
307 // Assign result to $sectioncontents, there is an exception,
308 // stealth activities in non-visible sections for students go to a special section.
309 if (!empty($filters['includestealthmodules']) && !$section->uservisible && $cm->is_stealth()) {
310 $stealthmodules[] = $module;
311 } else {
312 $sectioncontents[] = $module;
315 // If we just did a filtering, break the loop.
316 if ($modfound) {
317 break;
322 $sectionvalues['modules'] = $sectioncontents;
324 // assign result to $coursecontents
325 $coursecontents[$key] = $sectionvalues;
327 // Break the loop if we are filtering.
328 if ($sectionfound) {
329 break;
333 // Now that we have iterated over all the sections and activities, check the visibility.
334 // We didn't this before to be able to retrieve stealth activities.
335 foreach ($coursecontents as $sectionnumber => $sectioncontents) {
336 $section = $sections[$sectionnumber];
337 // Show the section if the user is permitted to access it, OR if it's not available
338 // but there is some available info text which explains the reason & should display.
339 $showsection = $section->uservisible ||
340 ($section->visible && !$section->available &&
341 !empty($section->availableinfo));
343 if (!$showsection) {
344 unset($coursecontents[$sectionnumber]);
345 continue;
348 // Remove modules information if the section is not visible for the user.
349 if (!$section->uservisible) {
350 $coursecontents[$sectionnumber]['modules'] = array();
354 // Include stealth modules in special section (without any info).
355 if (!empty($stealthmodules)) {
356 $coursecontents[] = array(
357 'id' => -1,
358 'name' => '',
359 'summary' => '',
360 'summaryformat' => FORMAT_MOODLE,
361 'modules' => $stealthmodules
366 return $coursecontents;
370 * Returns description of method result value
372 * @return external_description
373 * @since Moodle 2.2
375 public static function get_course_contents_returns() {
376 return new external_multiple_structure(
377 new external_single_structure(
378 array(
379 'id' => new external_value(PARAM_INT, 'Section ID'),
380 'name' => new external_value(PARAM_TEXT, 'Section name'),
381 'visible' => new external_value(PARAM_INT, 'is the section visible', VALUE_OPTIONAL),
382 'summary' => new external_value(PARAM_RAW, 'Section description'),
383 'summaryformat' => new external_format_value('summary'),
384 'section' => new external_value(PARAM_INT, 'Section number inside the course', VALUE_OPTIONAL),
385 'hiddenbynumsections' => new external_value(PARAM_INT, 'Whether is a section hidden in the course format',
386 VALUE_OPTIONAL),
387 'uservisible' => new external_value(PARAM_BOOL, 'Is the section visible for the user?', VALUE_OPTIONAL),
388 'availabilityinfo' => new external_value(PARAM_RAW, 'Availability information.', VALUE_OPTIONAL),
389 'modules' => new external_multiple_structure(
390 new external_single_structure(
391 array(
392 'id' => new external_value(PARAM_INT, 'activity id'),
393 'url' => new external_value(PARAM_URL, 'activity url', VALUE_OPTIONAL),
394 'name' => new external_value(PARAM_RAW, 'activity module name'),
395 'instance' => new external_value(PARAM_INT, 'instance id', VALUE_OPTIONAL),
396 'description' => new external_value(PARAM_RAW, 'activity description', VALUE_OPTIONAL),
397 'visible' => new external_value(PARAM_INT, 'is the module visible', VALUE_OPTIONAL),
398 'uservisible' => new external_value(PARAM_BOOL, 'Is the module visible for the user?',
399 VALUE_OPTIONAL),
400 'availabilityinfo' => new external_value(PARAM_RAW, 'Availability information.',
401 VALUE_OPTIONAL),
402 'visibleoncoursepage' => new external_value(PARAM_INT, 'is the module visible on course page',
403 VALUE_OPTIONAL),
404 'modicon' => new external_value(PARAM_URL, 'activity icon url'),
405 'modname' => new external_value(PARAM_PLUGIN, 'activity module type'),
406 'modplural' => new external_value(PARAM_TEXT, 'activity module plural name'),
407 'availability' => new external_value(PARAM_RAW, 'module availability settings', VALUE_OPTIONAL),
408 'indent' => new external_value(PARAM_INT, 'number of identation in the site'),
409 'contents' => new external_multiple_structure(
410 new external_single_structure(
411 array(
412 // content info
413 'type'=> new external_value(PARAM_TEXT, 'a file or a folder or external link'),
414 'filename'=> new external_value(PARAM_FILE, 'filename'),
415 'filepath'=> new external_value(PARAM_PATH, 'filepath'),
416 'filesize'=> new external_value(PARAM_INT, 'filesize'),
417 'fileurl' => new external_value(PARAM_URL, 'downloadable file url', VALUE_OPTIONAL),
418 'content' => new external_value(PARAM_RAW, 'Raw content, will be used when type is content', VALUE_OPTIONAL),
419 'timecreated' => new external_value(PARAM_INT, 'Time created'),
420 'timemodified' => new external_value(PARAM_INT, 'Time modified'),
421 'sortorder' => new external_value(PARAM_INT, 'Content sort order'),
422 'mimetype' => new external_value(PARAM_RAW, 'File mime type.', VALUE_OPTIONAL),
423 'isexternalfile' => new external_value(PARAM_BOOL, 'Whether is an external file.',
424 VALUE_OPTIONAL),
425 'repositorytype' => new external_value(PARAM_PLUGIN, 'The repository type for external files.',
426 VALUE_OPTIONAL),
428 // copyright related info
429 'userid' => new external_value(PARAM_INT, 'User who added this content to moodle'),
430 'author' => new external_value(PARAM_TEXT, 'Content owner'),
431 'license' => new external_value(PARAM_TEXT, 'Content license'),
433 ), VALUE_DEFAULT, array()
436 ), 'list of module'
444 * Returns description of method parameters
446 * @return external_function_parameters
447 * @since Moodle 2.3
449 public static function get_courses_parameters() {
450 return new external_function_parameters(
451 array('options' => new external_single_structure(
452 array('ids' => new external_multiple_structure(
453 new external_value(PARAM_INT, 'Course id')
454 , 'List of course id. If empty return all courses
455 except front page course.',
456 VALUE_OPTIONAL)
457 ), 'options - operator OR is used', VALUE_DEFAULT, array())
463 * Get courses
465 * @param array $options It contains an array (list of ids)
466 * @return array
467 * @since Moodle 2.2
469 public static function get_courses($options = array()) {
470 global $CFG, $DB;
471 require_once($CFG->dirroot . "/course/lib.php");
473 //validate parameter
474 $params = self::validate_parameters(self::get_courses_parameters(),
475 array('options' => $options));
477 //retrieve courses
478 if (!array_key_exists('ids', $params['options'])
479 or empty($params['options']['ids'])) {
480 $courses = $DB->get_records('course');
481 } else {
482 $courses = $DB->get_records_list('course', 'id', $params['options']['ids']);
485 //create return value
486 $coursesinfo = array();
487 foreach ($courses as $course) {
489 // now security checks
490 $context = context_course::instance($course->id, IGNORE_MISSING);
491 $courseformatoptions = course_get_format($course)->get_format_options();
492 try {
493 self::validate_context($context);
494 } catch (Exception $e) {
495 $exceptionparam = new stdClass();
496 $exceptionparam->message = $e->getMessage();
497 $exceptionparam->courseid = $course->id;
498 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
500 if ($course->id != SITEID) {
501 require_capability('moodle/course:view', $context);
504 $courseinfo = array();
505 $courseinfo['id'] = $course->id;
506 $courseinfo['fullname'] = external_format_string($course->fullname, $context->id);
507 $courseinfo['shortname'] = external_format_string($course->shortname, $context->id);
508 $courseinfo['displayname'] = external_format_string(get_course_display_name_for_list($course), $context->id);
509 $courseinfo['categoryid'] = $course->category;
510 list($courseinfo['summary'], $courseinfo['summaryformat']) =
511 external_format_text($course->summary, $course->summaryformat, $context->id, 'course', 'summary', 0);
512 $courseinfo['format'] = $course->format;
513 $courseinfo['startdate'] = $course->startdate;
514 $courseinfo['enddate'] = $course->enddate;
515 if (array_key_exists('numsections', $courseformatoptions)) {
516 // For backward-compartibility
517 $courseinfo['numsections'] = $courseformatoptions['numsections'];
520 //some field should be returned only if the user has update permission
521 $courseadmin = has_capability('moodle/course:update', $context);
522 if ($courseadmin) {
523 $courseinfo['categorysortorder'] = $course->sortorder;
524 $courseinfo['idnumber'] = $course->idnumber;
525 $courseinfo['showgrades'] = $course->showgrades;
526 $courseinfo['showreports'] = $course->showreports;
527 $courseinfo['newsitems'] = $course->newsitems;
528 $courseinfo['visible'] = $course->visible;
529 $courseinfo['maxbytes'] = $course->maxbytes;
530 if (array_key_exists('hiddensections', $courseformatoptions)) {
531 // For backward-compartibility
532 $courseinfo['hiddensections'] = $courseformatoptions['hiddensections'];
534 // Return numsections for backward-compatibility with clients who expect it.
535 $courseinfo['numsections'] = course_get_format($course)->get_last_section_number();
536 $courseinfo['groupmode'] = $course->groupmode;
537 $courseinfo['groupmodeforce'] = $course->groupmodeforce;
538 $courseinfo['defaultgroupingid'] = $course->defaultgroupingid;
539 $courseinfo['lang'] = clean_param($course->lang, PARAM_LANG);
540 $courseinfo['timecreated'] = $course->timecreated;
541 $courseinfo['timemodified'] = $course->timemodified;
542 $courseinfo['forcetheme'] = clean_param($course->theme, PARAM_THEME);
543 $courseinfo['enablecompletion'] = $course->enablecompletion;
544 $courseinfo['completionnotify'] = $course->completionnotify;
545 $courseinfo['courseformatoptions'] = array();
546 foreach ($courseformatoptions as $key => $value) {
547 $courseinfo['courseformatoptions'][] = array(
548 'name' => $key,
549 'value' => $value
554 if ($courseadmin or $course->visible
555 or has_capability('moodle/course:viewhiddencourses', $context)) {
556 $coursesinfo[] = $courseinfo;
560 return $coursesinfo;
564 * Returns description of method result value
566 * @return external_description
567 * @since Moodle 2.2
569 public static function get_courses_returns() {
570 return new external_multiple_structure(
571 new external_single_structure(
572 array(
573 'id' => new external_value(PARAM_INT, 'course id'),
574 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
575 'categoryid' => new external_value(PARAM_INT, 'category id'),
576 'categorysortorder' => new external_value(PARAM_INT,
577 'sort order into the category', VALUE_OPTIONAL),
578 'fullname' => new external_value(PARAM_TEXT, 'full name'),
579 'displayname' => new external_value(PARAM_TEXT, 'course display name'),
580 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
581 'summary' => new external_value(PARAM_RAW, 'summary'),
582 'summaryformat' => new external_format_value('summary'),
583 'format' => new external_value(PARAM_PLUGIN,
584 'course format: weeks, topics, social, site,..'),
585 'showgrades' => new external_value(PARAM_INT,
586 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
587 'newsitems' => new external_value(PARAM_INT,
588 'number of recent items appearing on the course page', VALUE_OPTIONAL),
589 'startdate' => new external_value(PARAM_INT,
590 'timestamp when the course start'),
591 'enddate' => new external_value(PARAM_INT,
592 'timestamp when the course end'),
593 'numsections' => new external_value(PARAM_INT,
594 '(deprecated, use courseformatoptions) number of weeks/topics',
595 VALUE_OPTIONAL),
596 'maxbytes' => new external_value(PARAM_INT,
597 'largest size of file that can be uploaded into the course',
598 VALUE_OPTIONAL),
599 'showreports' => new external_value(PARAM_INT,
600 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
601 'visible' => new external_value(PARAM_INT,
602 '1: available to student, 0:not available', VALUE_OPTIONAL),
603 'hiddensections' => new external_value(PARAM_INT,
604 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
605 VALUE_OPTIONAL),
606 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
607 VALUE_OPTIONAL),
608 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
609 VALUE_OPTIONAL),
610 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
611 VALUE_OPTIONAL),
612 'timecreated' => new external_value(PARAM_INT,
613 'timestamp when the course have been created', VALUE_OPTIONAL),
614 'timemodified' => new external_value(PARAM_INT,
615 'timestamp when the course have been modified', VALUE_OPTIONAL),
616 'enablecompletion' => new external_value(PARAM_INT,
617 'Enabled, control via completion and activity settings. Disbaled,
618 not shown in activity settings.',
619 VALUE_OPTIONAL),
620 'completionnotify' => new external_value(PARAM_INT,
621 '1: yes 0: no', VALUE_OPTIONAL),
622 'lang' => new external_value(PARAM_SAFEDIR,
623 'forced course language', VALUE_OPTIONAL),
624 'forcetheme' => new external_value(PARAM_PLUGIN,
625 'name of the force theme', VALUE_OPTIONAL),
626 'courseformatoptions' => new external_multiple_structure(
627 new external_single_structure(
628 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
629 'value' => new external_value(PARAM_RAW, 'course format option value')
631 'additional options for particular course format', VALUE_OPTIONAL
633 ), 'course'
639 * Returns description of method parameters
641 * @return external_function_parameters
642 * @since Moodle 2.2
644 public static function create_courses_parameters() {
645 $courseconfig = get_config('moodlecourse'); //needed for many default values
646 return new external_function_parameters(
647 array(
648 'courses' => new external_multiple_structure(
649 new external_single_structure(
650 array(
651 'fullname' => new external_value(PARAM_TEXT, 'full name'),
652 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
653 'categoryid' => new external_value(PARAM_INT, 'category id'),
654 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
655 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
656 'summaryformat' => new external_format_value('summary', VALUE_DEFAULT),
657 'format' => new external_value(PARAM_PLUGIN,
658 'course format: weeks, topics, social, site,..',
659 VALUE_DEFAULT, $courseconfig->format),
660 'showgrades' => new external_value(PARAM_INT,
661 '1 if grades are shown, otherwise 0', VALUE_DEFAULT,
662 $courseconfig->showgrades),
663 'newsitems' => new external_value(PARAM_INT,
664 'number of recent items appearing on the course page',
665 VALUE_DEFAULT, $courseconfig->newsitems),
666 'startdate' => new external_value(PARAM_INT,
667 'timestamp when the course start', VALUE_OPTIONAL),
668 'enddate' => new external_value(PARAM_INT,
669 'timestamp when the course end', VALUE_OPTIONAL),
670 'numsections' => new external_value(PARAM_INT,
671 '(deprecated, use courseformatoptions) number of weeks/topics',
672 VALUE_OPTIONAL),
673 'maxbytes' => new external_value(PARAM_INT,
674 'largest size of file that can be uploaded into the course',
675 VALUE_DEFAULT, $courseconfig->maxbytes),
676 'showreports' => new external_value(PARAM_INT,
677 'are activity report shown (yes = 1, no =0)', VALUE_DEFAULT,
678 $courseconfig->showreports),
679 'visible' => new external_value(PARAM_INT,
680 '1: available to student, 0:not available', VALUE_OPTIONAL),
681 'hiddensections' => new external_value(PARAM_INT,
682 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
683 VALUE_OPTIONAL),
684 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
685 VALUE_DEFAULT, $courseconfig->groupmode),
686 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
687 VALUE_DEFAULT, $courseconfig->groupmodeforce),
688 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
689 VALUE_DEFAULT, 0),
690 'enablecompletion' => new external_value(PARAM_INT,
691 'Enabled, control via completion and activity settings. Disabled,
692 not shown in activity settings.',
693 VALUE_OPTIONAL),
694 'completionnotify' => new external_value(PARAM_INT,
695 '1: yes 0: no', VALUE_OPTIONAL),
696 'lang' => new external_value(PARAM_SAFEDIR,
697 'forced course language', VALUE_OPTIONAL),
698 'forcetheme' => new external_value(PARAM_PLUGIN,
699 'name of the force theme', VALUE_OPTIONAL),
700 'courseformatoptions' => new external_multiple_structure(
701 new external_single_structure(
702 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
703 'value' => new external_value(PARAM_RAW, 'course format option value')
705 'additional options for particular course format', VALUE_OPTIONAL),
707 ), 'courses to create'
714 * Create courses
716 * @param array $courses
717 * @return array courses (id and shortname only)
718 * @since Moodle 2.2
720 public static function create_courses($courses) {
721 global $CFG, $DB;
722 require_once($CFG->dirroot . "/course/lib.php");
723 require_once($CFG->libdir . '/completionlib.php');
725 $params = self::validate_parameters(self::create_courses_parameters(),
726 array('courses' => $courses));
728 $availablethemes = core_component::get_plugin_list('theme');
729 $availablelangs = get_string_manager()->get_list_of_translations();
731 $transaction = $DB->start_delegated_transaction();
733 foreach ($params['courses'] as $course) {
735 // Ensure the current user is allowed to run this function
736 $context = context_coursecat::instance($course['categoryid'], IGNORE_MISSING);
737 try {
738 self::validate_context($context);
739 } catch (Exception $e) {
740 $exceptionparam = new stdClass();
741 $exceptionparam->message = $e->getMessage();
742 $exceptionparam->catid = $course['categoryid'];
743 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
745 require_capability('moodle/course:create', $context);
747 // Make sure lang is valid
748 if (array_key_exists('lang', $course)) {
749 if (empty($availablelangs[$course['lang']])) {
750 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
752 if (!has_capability('moodle/course:setforcedlanguage', $context)) {
753 unset($course['lang']);
757 // Make sure theme is valid
758 if (array_key_exists('forcetheme', $course)) {
759 if (!empty($CFG->allowcoursethemes)) {
760 if (empty($availablethemes[$course['forcetheme']])) {
761 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
762 } else {
763 $course['theme'] = $course['forcetheme'];
768 //force visibility if ws user doesn't have the permission to set it
769 $category = $DB->get_record('course_categories', array('id' => $course['categoryid']));
770 if (!has_capability('moodle/course:visibility', $context)) {
771 $course['visible'] = $category->visible;
774 //set default value for completion
775 $courseconfig = get_config('moodlecourse');
776 if (completion_info::is_enabled_for_site()) {
777 if (!array_key_exists('enablecompletion', $course)) {
778 $course['enablecompletion'] = $courseconfig->enablecompletion;
780 } else {
781 $course['enablecompletion'] = 0;
784 $course['category'] = $course['categoryid'];
786 // Summary format.
787 $course['summaryformat'] = external_validate_format($course['summaryformat']);
789 if (!empty($course['courseformatoptions'])) {
790 foreach ($course['courseformatoptions'] as $option) {
791 $course[$option['name']] = $option['value'];
795 //Note: create_course() core function check shortname, idnumber, category
796 $course['id'] = create_course((object) $course)->id;
798 $resultcourses[] = array('id' => $course['id'], 'shortname' => $course['shortname']);
801 $transaction->allow_commit();
803 return $resultcourses;
807 * Returns description of method result value
809 * @return external_description
810 * @since Moodle 2.2
812 public static function create_courses_returns() {
813 return new external_multiple_structure(
814 new external_single_structure(
815 array(
816 'id' => new external_value(PARAM_INT, 'course id'),
817 'shortname' => new external_value(PARAM_TEXT, 'short name'),
824 * Update courses
826 * @return external_function_parameters
827 * @since Moodle 2.5
829 public static function update_courses_parameters() {
830 return new external_function_parameters(
831 array(
832 'courses' => new external_multiple_structure(
833 new external_single_structure(
834 array(
835 'id' => new external_value(PARAM_INT, 'ID of the course'),
836 'fullname' => new external_value(PARAM_TEXT, 'full name', VALUE_OPTIONAL),
837 'shortname' => new external_value(PARAM_TEXT, 'course short name', VALUE_OPTIONAL),
838 'categoryid' => new external_value(PARAM_INT, 'category id', VALUE_OPTIONAL),
839 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
840 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
841 'summaryformat' => new external_format_value('summary', VALUE_OPTIONAL),
842 'format' => new external_value(PARAM_PLUGIN,
843 'course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
844 'showgrades' => new external_value(PARAM_INT,
845 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
846 'newsitems' => new external_value(PARAM_INT,
847 'number of recent items appearing on the course page', VALUE_OPTIONAL),
848 'startdate' => new external_value(PARAM_INT,
849 'timestamp when the course start', VALUE_OPTIONAL),
850 'enddate' => new external_value(PARAM_INT,
851 'timestamp when the course end', VALUE_OPTIONAL),
852 'numsections' => new external_value(PARAM_INT,
853 '(deprecated, use courseformatoptions) number of weeks/topics', VALUE_OPTIONAL),
854 'maxbytes' => new external_value(PARAM_INT,
855 'largest size of file that can be uploaded into the course', VALUE_OPTIONAL),
856 'showreports' => new external_value(PARAM_INT,
857 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
858 'visible' => new external_value(PARAM_INT,
859 '1: available to student, 0:not available', VALUE_OPTIONAL),
860 'hiddensections' => new external_value(PARAM_INT,
861 '(deprecated, use courseformatoptions) How the hidden sections in the course are
862 displayed to students', VALUE_OPTIONAL),
863 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
864 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
865 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
866 'enablecompletion' => new external_value(PARAM_INT,
867 'Enabled, control via completion and activity settings. Disabled,
868 not shown in activity settings.', VALUE_OPTIONAL),
869 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
870 'lang' => new external_value(PARAM_SAFEDIR, 'forced course language', VALUE_OPTIONAL),
871 'forcetheme' => new external_value(PARAM_PLUGIN, 'name of the force theme', VALUE_OPTIONAL),
872 'courseformatoptions' => new external_multiple_structure(
873 new external_single_structure(
874 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
875 'value' => new external_value(PARAM_RAW, 'course format option value')
877 'additional options for particular course format', VALUE_OPTIONAL),
879 ), 'courses to update'
886 * Update courses
888 * @param array $courses
889 * @since Moodle 2.5
891 public static function update_courses($courses) {
892 global $CFG, $DB;
893 require_once($CFG->dirroot . "/course/lib.php");
894 $warnings = array();
896 $params = self::validate_parameters(self::update_courses_parameters(),
897 array('courses' => $courses));
899 $availablethemes = core_component::get_plugin_list('theme');
900 $availablelangs = get_string_manager()->get_list_of_translations();
902 foreach ($params['courses'] as $course) {
903 // Catch any exception while updating course and return as warning to user.
904 try {
905 // Ensure the current user is allowed to run this function.
906 $context = context_course::instance($course['id'], MUST_EXIST);
907 self::validate_context($context);
909 $oldcourse = course_get_format($course['id'])->get_course();
911 require_capability('moodle/course:update', $context);
913 // Check if user can change category.
914 if (array_key_exists('categoryid', $course) && ($oldcourse->category != $course['categoryid'])) {
915 require_capability('moodle/course:changecategory', $context);
916 $course['category'] = $course['categoryid'];
919 // Check if the user can change fullname.
920 if (array_key_exists('fullname', $course) && ($oldcourse->fullname != $course['fullname'])) {
921 require_capability('moodle/course:changefullname', $context);
924 // Check if the user can change shortname.
925 if (array_key_exists('shortname', $course) && ($oldcourse->shortname != $course['shortname'])) {
926 require_capability('moodle/course:changeshortname', $context);
929 // Check if the user can change the idnumber.
930 if (array_key_exists('idnumber', $course) && ($oldcourse->idnumber != $course['idnumber'])) {
931 require_capability('moodle/course:changeidnumber', $context);
934 // Check if user can change summary.
935 if (array_key_exists('summary', $course) && ($oldcourse->summary != $course['summary'])) {
936 require_capability('moodle/course:changesummary', $context);
939 // Summary format.
940 if (array_key_exists('summaryformat', $course) && ($oldcourse->summaryformat != $course['summaryformat'])) {
941 require_capability('moodle/course:changesummary', $context);
942 $course['summaryformat'] = external_validate_format($course['summaryformat']);
945 // Check if user can change visibility.
946 if (array_key_exists('visible', $course) && ($oldcourse->visible != $course['visible'])) {
947 require_capability('moodle/course:visibility', $context);
950 // Make sure lang is valid.
951 if (array_key_exists('lang', $course) && ($oldcourse->lang != $course['lang'])) {
952 require_capability('moodle/course:setforcedlanguage', $context);
953 if (empty($availablelangs[$course['lang']])) {
954 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
958 // Make sure theme is valid.
959 if (array_key_exists('forcetheme', $course)) {
960 if (!empty($CFG->allowcoursethemes)) {
961 if (empty($availablethemes[$course['forcetheme']])) {
962 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
963 } else {
964 $course['theme'] = $course['forcetheme'];
969 // Make sure completion is enabled before setting it.
970 if (array_key_exists('enabledcompletion', $course) && !completion_info::is_enabled_for_site()) {
971 $course['enabledcompletion'] = 0;
974 // Make sure maxbytes are less then CFG->maxbytes.
975 if (array_key_exists('maxbytes', $course)) {
976 // We allow updates back to 0 max bytes, a special value denoting the course uses the site limit.
977 // Otherwise, either use the size specified, or cap at the max size for the course.
978 if ($course['maxbytes'] != 0) {
979 $course['maxbytes'] = get_max_upload_file_size($CFG->maxbytes, $course['maxbytes']);
983 if (!empty($course['courseformatoptions'])) {
984 foreach ($course['courseformatoptions'] as $option) {
985 if (isset($option['name']) && isset($option['value'])) {
986 $course[$option['name']] = $option['value'];
991 // Update course if user has all required capabilities.
992 update_course((object) $course);
993 } catch (Exception $e) {
994 $warning = array();
995 $warning['item'] = 'course';
996 $warning['itemid'] = $course['id'];
997 if ($e instanceof moodle_exception) {
998 $warning['warningcode'] = $e->errorcode;
999 } else {
1000 $warning['warningcode'] = $e->getCode();
1002 $warning['message'] = $e->getMessage();
1003 $warnings[] = $warning;
1007 $result = array();
1008 $result['warnings'] = $warnings;
1009 return $result;
1013 * Returns description of method result value
1015 * @return external_description
1016 * @since Moodle 2.5
1018 public static function update_courses_returns() {
1019 return new external_single_structure(
1020 array(
1021 'warnings' => new external_warnings()
1027 * Returns description of method parameters
1029 * @return external_function_parameters
1030 * @since Moodle 2.2
1032 public static function delete_courses_parameters() {
1033 return new external_function_parameters(
1034 array(
1035 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'course ID')),
1041 * Delete courses
1043 * @param array $courseids A list of course ids
1044 * @since Moodle 2.2
1046 public static function delete_courses($courseids) {
1047 global $CFG, $DB;
1048 require_once($CFG->dirroot."/course/lib.php");
1050 // Parameter validation.
1051 $params = self::validate_parameters(self::delete_courses_parameters(), array('courseids'=>$courseids));
1053 $warnings = array();
1055 foreach ($params['courseids'] as $courseid) {
1056 $course = $DB->get_record('course', array('id' => $courseid));
1058 if ($course === false) {
1059 $warnings[] = array(
1060 'item' => 'course',
1061 'itemid' => $courseid,
1062 'warningcode' => 'unknowncourseidnumber',
1063 'message' => 'Unknown course ID ' . $courseid
1065 continue;
1068 // Check if the context is valid.
1069 $coursecontext = context_course::instance($course->id);
1070 self::validate_context($coursecontext);
1072 // Check if the current user has permission.
1073 if (!can_delete_course($courseid)) {
1074 $warnings[] = array(
1075 'item' => 'course',
1076 'itemid' => $courseid,
1077 'warningcode' => 'cannotdeletecourse',
1078 'message' => 'You do not have the permission to delete this course' . $courseid
1080 continue;
1083 if (delete_course($course, false) === false) {
1084 $warnings[] = array(
1085 'item' => 'course',
1086 'itemid' => $courseid,
1087 'warningcode' => 'cannotdeletecategorycourse',
1088 'message' => 'Course ' . $courseid . ' failed to be deleted'
1090 continue;
1094 fix_course_sortorder();
1096 return array('warnings' => $warnings);
1100 * Returns description of method result value
1102 * @return external_description
1103 * @since Moodle 2.2
1105 public static function delete_courses_returns() {
1106 return new external_single_structure(
1107 array(
1108 'warnings' => new external_warnings()
1114 * Returns description of method parameters
1116 * @return external_function_parameters
1117 * @since Moodle 2.3
1119 public static function duplicate_course_parameters() {
1120 return new external_function_parameters(
1121 array(
1122 'courseid' => new external_value(PARAM_INT, 'course to duplicate id'),
1123 'fullname' => new external_value(PARAM_TEXT, 'duplicated course full name'),
1124 'shortname' => new external_value(PARAM_TEXT, 'duplicated course short name'),
1125 'categoryid' => new external_value(PARAM_INT, 'duplicated course category parent'),
1126 'visible' => new external_value(PARAM_INT, 'duplicated course visible, default to yes', VALUE_DEFAULT, 1),
1127 'options' => new external_multiple_structure(
1128 new external_single_structure(
1129 array(
1130 'name' => new external_value(PARAM_ALPHAEXT, 'The backup option name:
1131 "activities" (int) Include course activites (default to 1 that is equal to yes),
1132 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1133 "filters" (int) Include course filters (default to 1 that is equal to yes),
1134 "users" (int) Include users (default to 0 that is equal to no),
1135 "enrolments" (int) Include enrolment methods (default to 1 - restore only with users),
1136 "role_assignments" (int) Include role assignments (default to 0 that is equal to no),
1137 "comments" (int) Include user comments (default to 0 that is equal to no),
1138 "userscompletion" (int) Include user course completion information (default to 0 that is equal to no),
1139 "logs" (int) Include course logs (default to 0 that is equal to no),
1140 "grade_histories" (int) Include histories (default to 0 that is equal to no)'
1142 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1145 ), VALUE_DEFAULT, array()
1152 * Duplicate a course
1154 * @param int $courseid
1155 * @param string $fullname Duplicated course fullname
1156 * @param string $shortname Duplicated course shortname
1157 * @param int $categoryid Duplicated course parent category id
1158 * @param int $visible Duplicated course availability
1159 * @param array $options List of backup options
1160 * @return array New course info
1161 * @since Moodle 2.3
1163 public static function duplicate_course($courseid, $fullname, $shortname, $categoryid, $visible = 1, $options = array()) {
1164 global $CFG, $USER, $DB;
1165 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1166 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1168 // Parameter validation.
1169 $params = self::validate_parameters(
1170 self::duplicate_course_parameters(),
1171 array(
1172 'courseid' => $courseid,
1173 'fullname' => $fullname,
1174 'shortname' => $shortname,
1175 'categoryid' => $categoryid,
1176 'visible' => $visible,
1177 'options' => $options
1181 // Context validation.
1183 if (! ($course = $DB->get_record('course', array('id'=>$params['courseid'])))) {
1184 throw new moodle_exception('invalidcourseid', 'error');
1187 // Category where duplicated course is going to be created.
1188 $categorycontext = context_coursecat::instance($params['categoryid']);
1189 self::validate_context($categorycontext);
1191 // Course to be duplicated.
1192 $coursecontext = context_course::instance($course->id);
1193 self::validate_context($coursecontext);
1195 $backupdefaults = array(
1196 'activities' => 1,
1197 'blocks' => 1,
1198 'filters' => 1,
1199 'users' => 0,
1200 'enrolments' => backup::ENROL_WITHUSERS,
1201 'role_assignments' => 0,
1202 'comments' => 0,
1203 'userscompletion' => 0,
1204 'logs' => 0,
1205 'grade_histories' => 0
1208 $backupsettings = array();
1209 // Check for backup and restore options.
1210 if (!empty($params['options'])) {
1211 foreach ($params['options'] as $option) {
1213 // Strict check for a correct value (allways 1 or 0, true or false).
1214 $value = clean_param($option['value'], PARAM_INT);
1216 if ($value !== 0 and $value !== 1) {
1217 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1220 if (!isset($backupdefaults[$option['name']])) {
1221 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1224 $backupsettings[$option['name']] = $value;
1228 // Capability checking.
1230 // The backup controller check for this currently, this may be redundant.
1231 require_capability('moodle/course:create', $categorycontext);
1232 require_capability('moodle/restore:restorecourse', $categorycontext);
1233 require_capability('moodle/backup:backupcourse', $coursecontext);
1235 if (!empty($backupsettings['users'])) {
1236 require_capability('moodle/backup:userinfo', $coursecontext);
1237 require_capability('moodle/restore:userinfo', $categorycontext);
1240 // Check if the shortname is used.
1241 if ($foundcourses = $DB->get_records('course', array('shortname'=>$shortname))) {
1242 foreach ($foundcourses as $foundcourse) {
1243 $foundcoursenames[] = $foundcourse->fullname;
1246 $foundcoursenamestring = implode(',', $foundcoursenames);
1247 throw new moodle_exception('shortnametaken', '', '', $foundcoursenamestring);
1250 // Backup the course.
1252 $bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE,
1253 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id);
1255 foreach ($backupsettings as $name => $value) {
1256 if ($setting = $bc->get_plan()->get_setting($name)) {
1257 $bc->get_plan()->get_setting($name)->set_value($value);
1261 $backupid = $bc->get_backupid();
1262 $backupbasepath = $bc->get_plan()->get_basepath();
1264 $bc->execute_plan();
1265 $results = $bc->get_results();
1266 $file = $results['backup_destination'];
1268 $bc->destroy();
1270 // Restore the backup immediately.
1272 // Check if we need to unzip the file because the backup temp dir does not contains backup files.
1273 if (!file_exists($backupbasepath . "/moodle_backup.xml")) {
1274 $file->extract_to_pathname(get_file_packer('application/vnd.moodle.backup'), $backupbasepath);
1277 // Create new course.
1278 $newcourseid = restore_dbops::create_new_course($params['fullname'], $params['shortname'], $params['categoryid']);
1280 $rc = new restore_controller($backupid, $newcourseid,
1281 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id, backup::TARGET_NEW_COURSE);
1283 foreach ($backupsettings as $name => $value) {
1284 $setting = $rc->get_plan()->get_setting($name);
1285 if ($setting->get_status() == backup_setting::NOT_LOCKED) {
1286 $setting->set_value($value);
1290 if (!$rc->execute_precheck()) {
1291 $precheckresults = $rc->get_precheck_results();
1292 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1293 if (empty($CFG->keeptempdirectoriesonbackup)) {
1294 fulldelete($backupbasepath);
1297 $errorinfo = '';
1299 foreach ($precheckresults['errors'] as $error) {
1300 $errorinfo .= $error;
1303 if (array_key_exists('warnings', $precheckresults)) {
1304 foreach ($precheckresults['warnings'] as $warning) {
1305 $errorinfo .= $warning;
1309 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1313 $rc->execute_plan();
1314 $rc->destroy();
1316 $course = $DB->get_record('course', array('id' => $newcourseid), '*', MUST_EXIST);
1317 $course->fullname = $params['fullname'];
1318 $course->shortname = $params['shortname'];
1319 $course->visible = $params['visible'];
1321 // Set shortname and fullname back.
1322 $DB->update_record('course', $course);
1324 if (empty($CFG->keeptempdirectoriesonbackup)) {
1325 fulldelete($backupbasepath);
1328 // Delete the course backup file created by this WebService. Originally located in the course backups area.
1329 $file->delete();
1331 return array('id' => $course->id, 'shortname' => $course->shortname);
1335 * Returns description of method result value
1337 * @return external_description
1338 * @since Moodle 2.3
1340 public static function duplicate_course_returns() {
1341 return new external_single_structure(
1342 array(
1343 'id' => new external_value(PARAM_INT, 'course id'),
1344 'shortname' => new external_value(PARAM_TEXT, 'short name'),
1350 * Returns description of method parameters for import_course
1352 * @return external_function_parameters
1353 * @since Moodle 2.4
1355 public static function import_course_parameters() {
1356 return new external_function_parameters(
1357 array(
1358 'importfrom' => new external_value(PARAM_INT, 'the id of the course we are importing from'),
1359 'importto' => new external_value(PARAM_INT, 'the id of the course we are importing to'),
1360 'deletecontent' => new external_value(PARAM_INT, 'whether to delete the course content where we are importing to (default to 0 = No)', VALUE_DEFAULT, 0),
1361 'options' => new external_multiple_structure(
1362 new external_single_structure(
1363 array(
1364 'name' => new external_value(PARAM_ALPHA, 'The backup option name:
1365 "activities" (int) Include course activites (default to 1 that is equal to yes),
1366 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1367 "filters" (int) Include course filters (default to 1 that is equal to yes)'
1369 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1372 ), VALUE_DEFAULT, array()
1379 * Imports a course
1381 * @param int $importfrom The id of the course we are importing from
1382 * @param int $importto The id of the course we are importing to
1383 * @param bool $deletecontent Whether to delete the course we are importing to content
1384 * @param array $options List of backup options
1385 * @return null
1386 * @since Moodle 2.4
1388 public static function import_course($importfrom, $importto, $deletecontent = 0, $options = array()) {
1389 global $CFG, $USER, $DB;
1390 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1391 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1393 // Parameter validation.
1394 $params = self::validate_parameters(
1395 self::import_course_parameters(),
1396 array(
1397 'importfrom' => $importfrom,
1398 'importto' => $importto,
1399 'deletecontent' => $deletecontent,
1400 'options' => $options
1404 if ($params['deletecontent'] !== 0 and $params['deletecontent'] !== 1) {
1405 throw new moodle_exception('invalidextparam', 'webservice', '', $params['deletecontent']);
1408 // Context validation.
1410 if (! ($importfrom = $DB->get_record('course', array('id'=>$params['importfrom'])))) {
1411 throw new moodle_exception('invalidcourseid', 'error');
1414 if (! ($importto = $DB->get_record('course', array('id'=>$params['importto'])))) {
1415 throw new moodle_exception('invalidcourseid', 'error');
1418 $importfromcontext = context_course::instance($importfrom->id);
1419 self::validate_context($importfromcontext);
1421 $importtocontext = context_course::instance($importto->id);
1422 self::validate_context($importtocontext);
1424 $backupdefaults = array(
1425 'activities' => 1,
1426 'blocks' => 1,
1427 'filters' => 1
1430 $backupsettings = array();
1432 // Check for backup and restore options.
1433 if (!empty($params['options'])) {
1434 foreach ($params['options'] as $option) {
1436 // Strict check for a correct value (allways 1 or 0, true or false).
1437 $value = clean_param($option['value'], PARAM_INT);
1439 if ($value !== 0 and $value !== 1) {
1440 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1443 if (!isset($backupdefaults[$option['name']])) {
1444 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1447 $backupsettings[$option['name']] = $value;
1451 // Capability checking.
1453 require_capability('moodle/backup:backuptargetimport', $importfromcontext);
1454 require_capability('moodle/restore:restoretargetimport', $importtocontext);
1456 $bc = new backup_controller(backup::TYPE_1COURSE, $importfrom->id, backup::FORMAT_MOODLE,
1457 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
1459 foreach ($backupsettings as $name => $value) {
1460 $bc->get_plan()->get_setting($name)->set_value($value);
1463 $backupid = $bc->get_backupid();
1464 $backupbasepath = $bc->get_plan()->get_basepath();
1466 $bc->execute_plan();
1467 $bc->destroy();
1469 // Restore the backup immediately.
1471 // Check if we must delete the contents of the destination course.
1472 if ($params['deletecontent']) {
1473 $restoretarget = backup::TARGET_EXISTING_DELETING;
1474 } else {
1475 $restoretarget = backup::TARGET_EXISTING_ADDING;
1478 $rc = new restore_controller($backupid, $importto->id,
1479 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, $restoretarget);
1481 foreach ($backupsettings as $name => $value) {
1482 $rc->get_plan()->get_setting($name)->set_value($value);
1485 if (!$rc->execute_precheck()) {
1486 $precheckresults = $rc->get_precheck_results();
1487 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1488 if (empty($CFG->keeptempdirectoriesonbackup)) {
1489 fulldelete($backupbasepath);
1492 $errorinfo = '';
1494 foreach ($precheckresults['errors'] as $error) {
1495 $errorinfo .= $error;
1498 if (array_key_exists('warnings', $precheckresults)) {
1499 foreach ($precheckresults['warnings'] as $warning) {
1500 $errorinfo .= $warning;
1504 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1506 } else {
1507 if ($restoretarget == backup::TARGET_EXISTING_DELETING) {
1508 restore_dbops::delete_course_content($importto->id);
1512 $rc->execute_plan();
1513 $rc->destroy();
1515 if (empty($CFG->keeptempdirectoriesonbackup)) {
1516 fulldelete($backupbasepath);
1519 return null;
1523 * Returns description of method result value
1525 * @return external_description
1526 * @since Moodle 2.4
1528 public static function import_course_returns() {
1529 return null;
1533 * Returns description of method parameters
1535 * @return external_function_parameters
1536 * @since Moodle 2.3
1538 public static function get_categories_parameters() {
1539 return new external_function_parameters(
1540 array(
1541 'criteria' => new external_multiple_structure(
1542 new external_single_structure(
1543 array(
1544 'key' => new external_value(PARAM_ALPHA,
1545 'The category column to search, expected keys (value format) are:'.
1546 '"id" (int) the category id,'.
1547 '"ids" (string) category ids separated by commas,'.
1548 '"name" (string) the category name,'.
1549 '"parent" (int) the parent category id,'.
1550 '"idnumber" (string) category idnumber'.
1551 ' - user must have \'moodle/category:manage\' to search on idnumber,'.
1552 '"visible" (int) whether the returned categories must be visible or hidden. If the key is not passed,
1553 then the function return all categories that the user can see.'.
1554 ' - user must have \'moodle/category:manage\' or \'moodle/category:viewhiddencategories\' to search on visible,'.
1555 '"theme" (string) only return the categories having this theme'.
1556 ' - user must have \'moodle/category:manage\' to search on theme'),
1557 'value' => new external_value(PARAM_RAW, 'the value to match')
1559 ), 'criteria', VALUE_DEFAULT, array()
1561 'addsubcategories' => new external_value(PARAM_BOOL, 'return the sub categories infos
1562 (1 - default) otherwise only the category info (0)', VALUE_DEFAULT, 1)
1568 * Get categories
1570 * @param array $criteria Criteria to match the results
1571 * @param booln $addsubcategories obtain only the category (false) or its subcategories (true - default)
1572 * @return array list of categories
1573 * @since Moodle 2.3
1575 public static function get_categories($criteria = array(), $addsubcategories = true) {
1576 global $CFG, $DB;
1577 require_once($CFG->dirroot . "/course/lib.php");
1579 // Validate parameters.
1580 $params = self::validate_parameters(self::get_categories_parameters(),
1581 array('criteria' => $criteria, 'addsubcategories' => $addsubcategories));
1583 // Retrieve the categories.
1584 $categories = array();
1585 if (!empty($params['criteria'])) {
1587 $conditions = array();
1588 $wheres = array();
1589 foreach ($params['criteria'] as $crit) {
1590 $key = trim($crit['key']);
1592 // Trying to avoid duplicate keys.
1593 if (!isset($conditions[$key])) {
1595 $context = context_system::instance();
1596 $value = null;
1597 switch ($key) {
1598 case 'id':
1599 $value = clean_param($crit['value'], PARAM_INT);
1600 $conditions[$key] = $value;
1601 $wheres[] = $key . " = :" . $key;
1602 break;
1604 case 'ids':
1605 $value = clean_param($crit['value'], PARAM_SEQUENCE);
1606 $ids = explode(',', $value);
1607 list($sqlids, $paramids) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED);
1608 $conditions = array_merge($conditions, $paramids);
1609 $wheres[] = 'id ' . $sqlids;
1610 break;
1612 case 'idnumber':
1613 if (has_capability('moodle/category:manage', $context)) {
1614 $value = clean_param($crit['value'], PARAM_RAW);
1615 $conditions[$key] = $value;
1616 $wheres[] = $key . " = :" . $key;
1617 } else {
1618 // We must throw an exception.
1619 // Otherwise the dev client would think no idnumber exists.
1620 throw new moodle_exception('criteriaerror',
1621 'webservice', '', null,
1622 'You don\'t have the permissions to search on the "idnumber" field.');
1624 break;
1626 case 'name':
1627 $value = clean_param($crit['value'], PARAM_TEXT);
1628 $conditions[$key] = $value;
1629 $wheres[] = $key . " = :" . $key;
1630 break;
1632 case 'parent':
1633 $value = clean_param($crit['value'], PARAM_INT);
1634 $conditions[$key] = $value;
1635 $wheres[] = $key . " = :" . $key;
1636 break;
1638 case 'visible':
1639 if (has_capability('moodle/category:viewhiddencategories', $context)) {
1640 $value = clean_param($crit['value'], PARAM_INT);
1641 $conditions[$key] = $value;
1642 $wheres[] = $key . " = :" . $key;
1643 } else {
1644 throw new moodle_exception('criteriaerror',
1645 'webservice', '', null,
1646 'You don\'t have the permissions to search on the "visible" field.');
1648 break;
1650 case 'theme':
1651 if (has_capability('moodle/category:manage', $context)) {
1652 $value = clean_param($crit['value'], PARAM_THEME);
1653 $conditions[$key] = $value;
1654 $wheres[] = $key . " = :" . $key;
1655 } else {
1656 throw new moodle_exception('criteriaerror',
1657 'webservice', '', null,
1658 'You don\'t have the permissions to search on the "theme" field.');
1660 break;
1662 default:
1663 throw new moodle_exception('criteriaerror',
1664 'webservice', '', null,
1665 'You can not search on this criteria: ' . $key);
1670 if (!empty($wheres)) {
1671 $wheres = implode(" AND ", $wheres);
1673 $categories = $DB->get_records_select('course_categories', $wheres, $conditions);
1675 // Retrieve its sub subcategories (all levels).
1676 if ($categories and !empty($params['addsubcategories'])) {
1677 $newcategories = array();
1679 // Check if we required visible/theme checks.
1680 $additionalselect = '';
1681 $additionalparams = array();
1682 if (isset($conditions['visible'])) {
1683 $additionalselect .= ' AND visible = :visible';
1684 $additionalparams['visible'] = $conditions['visible'];
1686 if (isset($conditions['theme'])) {
1687 $additionalselect .= ' AND theme= :theme';
1688 $additionalparams['theme'] = $conditions['theme'];
1691 foreach ($categories as $category) {
1692 $sqlselect = $DB->sql_like('path', ':path') . $additionalselect;
1693 $sqlparams = array('path' => $category->path.'/%') + $additionalparams; // It will NOT include the specified category.
1694 $subcategories = $DB->get_records_select('course_categories', $sqlselect, $sqlparams);
1695 $newcategories = $newcategories + $subcategories; // Both arrays have integer as keys.
1697 $categories = $categories + $newcategories;
1701 } else {
1702 // Retrieve all categories in the database.
1703 $categories = $DB->get_records('course_categories');
1706 // The not returned categories. key => category id, value => reason of exclusion.
1707 $excludedcats = array();
1709 // The returned categories.
1710 $categoriesinfo = array();
1712 // We need to sort the categories by path.
1713 // The parent cats need to be checked by the algo first.
1714 usort($categories, "core_course_external::compare_categories_by_path");
1716 foreach ($categories as $category) {
1718 // Check if the category is a child of an excluded category, if yes exclude it too (excluded => do not return).
1719 $parents = explode('/', $category->path);
1720 unset($parents[0]); // First key is always empty because path start with / => /1/2/4.
1721 foreach ($parents as $parentid) {
1722 // Note: when the parent exclusion was due to the context,
1723 // the sub category could still be returned.
1724 if (isset($excludedcats[$parentid]) and $excludedcats[$parentid] != 'context') {
1725 $excludedcats[$category->id] = 'parent';
1729 // Check the user can use the category context.
1730 $context = context_coursecat::instance($category->id);
1731 try {
1732 self::validate_context($context);
1733 } catch (Exception $e) {
1734 $excludedcats[$category->id] = 'context';
1736 // If it was the requested category then throw an exception.
1737 if (isset($params['categoryid']) && $category->id == $params['categoryid']) {
1738 $exceptionparam = new stdClass();
1739 $exceptionparam->message = $e->getMessage();
1740 $exceptionparam->catid = $category->id;
1741 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
1745 // Return the category information.
1746 if (!isset($excludedcats[$category->id])) {
1748 // Final check to see if the category is visible to the user.
1749 if ($category->visible or has_capability('moodle/category:viewhiddencategories', $context)) {
1751 $categoryinfo = array();
1752 $categoryinfo['id'] = $category->id;
1753 $categoryinfo['name'] = external_format_string($category->name, $context);
1754 list($categoryinfo['description'], $categoryinfo['descriptionformat']) =
1755 external_format_text($category->description, $category->descriptionformat,
1756 $context->id, 'coursecat', 'description', null);
1757 $categoryinfo['parent'] = $category->parent;
1758 $categoryinfo['sortorder'] = $category->sortorder;
1759 $categoryinfo['coursecount'] = $category->coursecount;
1760 $categoryinfo['depth'] = $category->depth;
1761 $categoryinfo['path'] = $category->path;
1763 // Some fields only returned for admin.
1764 if (has_capability('moodle/category:manage', $context)) {
1765 $categoryinfo['idnumber'] = $category->idnumber;
1766 $categoryinfo['visible'] = $category->visible;
1767 $categoryinfo['visibleold'] = $category->visibleold;
1768 $categoryinfo['timemodified'] = $category->timemodified;
1769 $categoryinfo['theme'] = clean_param($category->theme, PARAM_THEME);
1772 $categoriesinfo[] = $categoryinfo;
1773 } else {
1774 $excludedcats[$category->id] = 'visibility';
1779 // Sorting the resulting array so it looks a bit better for the client developer.
1780 usort($categoriesinfo, "core_course_external::compare_categories_by_sortorder");
1782 return $categoriesinfo;
1786 * Sort categories array by path
1787 * private function: only used by get_categories
1789 * @param array $category1
1790 * @param array $category2
1791 * @return int result of strcmp
1792 * @since Moodle 2.3
1794 private static function compare_categories_by_path($category1, $category2) {
1795 return strcmp($category1->path, $category2->path);
1799 * Sort categories array by sortorder
1800 * private function: only used by get_categories
1802 * @param array $category1
1803 * @param array $category2
1804 * @return int result of strcmp
1805 * @since Moodle 2.3
1807 private static function compare_categories_by_sortorder($category1, $category2) {
1808 return strcmp($category1['sortorder'], $category2['sortorder']);
1812 * Returns description of method result value
1814 * @return external_description
1815 * @since Moodle 2.3
1817 public static function get_categories_returns() {
1818 return new external_multiple_structure(
1819 new external_single_structure(
1820 array(
1821 'id' => new external_value(PARAM_INT, 'category id'),
1822 'name' => new external_value(PARAM_TEXT, 'category name'),
1823 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1824 'description' => new external_value(PARAM_RAW, 'category description'),
1825 'descriptionformat' => new external_format_value('description'),
1826 'parent' => new external_value(PARAM_INT, 'parent category id'),
1827 'sortorder' => new external_value(PARAM_INT, 'category sorting order'),
1828 'coursecount' => new external_value(PARAM_INT, 'number of courses in this category'),
1829 'visible' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1830 'visibleold' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1831 'timemodified' => new external_value(PARAM_INT, 'timestamp', VALUE_OPTIONAL),
1832 'depth' => new external_value(PARAM_INT, 'category depth'),
1833 'path' => new external_value(PARAM_TEXT, 'category path'),
1834 'theme' => new external_value(PARAM_THEME, 'category theme', VALUE_OPTIONAL),
1835 ), 'List of categories'
1841 * Returns description of method parameters
1843 * @return external_function_parameters
1844 * @since Moodle 2.3
1846 public static function create_categories_parameters() {
1847 return new external_function_parameters(
1848 array(
1849 'categories' => new external_multiple_structure(
1850 new external_single_structure(
1851 array(
1852 'name' => new external_value(PARAM_TEXT, 'new category name'),
1853 'parent' => new external_value(PARAM_INT,
1854 'the parent category id inside which the new category will be created
1855 - set to 0 for a root category',
1856 VALUE_DEFAULT, 0),
1857 'idnumber' => new external_value(PARAM_RAW,
1858 'the new category idnumber', VALUE_OPTIONAL),
1859 'description' => new external_value(PARAM_RAW,
1860 'the new category description', VALUE_OPTIONAL),
1861 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
1862 'theme' => new external_value(PARAM_THEME,
1863 'the new category theme. This option must be enabled on moodle',
1864 VALUE_OPTIONAL),
1873 * Create categories
1875 * @param array $categories - see create_categories_parameters() for the array structure
1876 * @return array - see create_categories_returns() for the array structure
1877 * @since Moodle 2.3
1879 public static function create_categories($categories) {
1880 global $CFG, $DB;
1881 require_once($CFG->libdir . "/coursecatlib.php");
1883 $params = self::validate_parameters(self::create_categories_parameters(),
1884 array('categories' => $categories));
1886 $transaction = $DB->start_delegated_transaction();
1888 $createdcategories = array();
1889 foreach ($params['categories'] as $category) {
1890 if ($category['parent']) {
1891 if (!$DB->record_exists('course_categories', array('id' => $category['parent']))) {
1892 throw new moodle_exception('unknowcategory');
1894 $context = context_coursecat::instance($category['parent']);
1895 } else {
1896 $context = context_system::instance();
1898 self::validate_context($context);
1899 require_capability('moodle/category:manage', $context);
1901 // this will validate format and throw an exception if there are errors
1902 external_validate_format($category['descriptionformat']);
1904 $newcategory = coursecat::create($category);
1905 $context = context_coursecat::instance($newcategory->id);
1907 $createdcategories[] = array(
1908 'id' => $newcategory->id,
1909 'name' => external_format_string($newcategory->name, $context),
1913 $transaction->allow_commit();
1915 return $createdcategories;
1919 * Returns description of method parameters
1921 * @return external_function_parameters
1922 * @since Moodle 2.3
1924 public static function create_categories_returns() {
1925 return new external_multiple_structure(
1926 new external_single_structure(
1927 array(
1928 'id' => new external_value(PARAM_INT, 'new category id'),
1929 'name' => new external_value(PARAM_TEXT, 'new category name'),
1936 * Returns description of method parameters
1938 * @return external_function_parameters
1939 * @since Moodle 2.3
1941 public static function update_categories_parameters() {
1942 return new external_function_parameters(
1943 array(
1944 'categories' => new external_multiple_structure(
1945 new external_single_structure(
1946 array(
1947 'id' => new external_value(PARAM_INT, 'course id'),
1948 'name' => new external_value(PARAM_TEXT, 'category name', VALUE_OPTIONAL),
1949 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1950 'parent' => new external_value(PARAM_INT, 'parent category id', VALUE_OPTIONAL),
1951 'description' => new external_value(PARAM_RAW, 'category description', VALUE_OPTIONAL),
1952 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
1953 'theme' => new external_value(PARAM_THEME,
1954 'the category theme. This option must be enabled on moodle', VALUE_OPTIONAL),
1963 * Update categories
1965 * @param array $categories The list of categories to update
1966 * @return null
1967 * @since Moodle 2.3
1969 public static function update_categories($categories) {
1970 global $CFG, $DB;
1971 require_once($CFG->libdir . "/coursecatlib.php");
1973 // Validate parameters.
1974 $params = self::validate_parameters(self::update_categories_parameters(), array('categories' => $categories));
1976 $transaction = $DB->start_delegated_transaction();
1978 foreach ($params['categories'] as $cat) {
1979 $category = coursecat::get($cat['id']);
1981 $categorycontext = context_coursecat::instance($cat['id']);
1982 self::validate_context($categorycontext);
1983 require_capability('moodle/category:manage', $categorycontext);
1985 // this will throw an exception if descriptionformat is not valid
1986 external_validate_format($cat['descriptionformat']);
1988 $category->update($cat);
1991 $transaction->allow_commit();
1995 * Returns description of method result value
1997 * @return external_description
1998 * @since Moodle 2.3
2000 public static function update_categories_returns() {
2001 return null;
2005 * Returns description of method parameters
2007 * @return external_function_parameters
2008 * @since Moodle 2.3
2010 public static function delete_categories_parameters() {
2011 return new external_function_parameters(
2012 array(
2013 'categories' => new external_multiple_structure(
2014 new external_single_structure(
2015 array(
2016 'id' => new external_value(PARAM_INT, 'category id to delete'),
2017 'newparent' => new external_value(PARAM_INT,
2018 'the parent category to move the contents to, if specified', VALUE_OPTIONAL),
2019 'recursive' => new external_value(PARAM_BOOL, '1: recursively delete all contents inside this
2020 category, 0 (default): move contents to newparent or current parent category (except if parent is root)', VALUE_DEFAULT, 0)
2029 * Delete categories
2031 * @param array $categories A list of category ids
2032 * @return array
2033 * @since Moodle 2.3
2035 public static function delete_categories($categories) {
2036 global $CFG, $DB;
2037 require_once($CFG->dirroot . "/course/lib.php");
2038 require_once($CFG->libdir . "/coursecatlib.php");
2040 // Validate parameters.
2041 $params = self::validate_parameters(self::delete_categories_parameters(), array('categories' => $categories));
2043 $transaction = $DB->start_delegated_transaction();
2045 foreach ($params['categories'] as $category) {
2046 $deletecat = coursecat::get($category['id'], MUST_EXIST);
2047 $context = context_coursecat::instance($deletecat->id);
2048 require_capability('moodle/category:manage', $context);
2049 self::validate_context($context);
2050 self::validate_context(get_category_or_system_context($deletecat->parent));
2052 if ($category['recursive']) {
2053 // If recursive was specified, then we recursively delete the category's contents.
2054 if ($deletecat->can_delete_full()) {
2055 $deletecat->delete_full(false);
2056 } else {
2057 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2059 } else {
2060 // In this situation, we don't delete the category's contents, we either move it to newparent or parent.
2061 // If the parent is the root, moving is not supported (because a course must always be inside a category).
2062 // We must move to an existing category.
2063 if (!empty($category['newparent'])) {
2064 $newparentcat = coursecat::get($category['newparent']);
2065 } else {
2066 $newparentcat = coursecat::get($deletecat->parent);
2069 // This operation is not allowed. We must move contents to an existing category.
2070 if (!$newparentcat->id) {
2071 throw new moodle_exception('movecatcontentstoroot');
2074 self::validate_context(context_coursecat::instance($newparentcat->id));
2075 if ($deletecat->can_move_content_to($newparentcat->id)) {
2076 $deletecat->delete_move($newparentcat->id, false);
2077 } else {
2078 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2083 $transaction->allow_commit();
2087 * Returns description of method parameters
2089 * @return external_function_parameters
2090 * @since Moodle 2.3
2092 public static function delete_categories_returns() {
2093 return null;
2097 * Describes the parameters for delete_modules.
2099 * @return external_function_parameters
2100 * @since Moodle 2.5
2102 public static function delete_modules_parameters() {
2103 return new external_function_parameters (
2104 array(
2105 'cmids' => new external_multiple_structure(new external_value(PARAM_INT, 'course module ID',
2106 VALUE_REQUIRED, '', NULL_NOT_ALLOWED), 'Array of course module IDs'),
2112 * Deletes a list of provided module instances.
2114 * @param array $cmids the course module ids
2115 * @since Moodle 2.5
2117 public static function delete_modules($cmids) {
2118 global $CFG, $DB;
2120 // Require course file containing the course delete module function.
2121 require_once($CFG->dirroot . "/course/lib.php");
2123 // Clean the parameters.
2124 $params = self::validate_parameters(self::delete_modules_parameters(), array('cmids' => $cmids));
2126 // Keep track of the course ids we have performed a capability check on to avoid repeating.
2127 $arrcourseschecked = array();
2129 foreach ($params['cmids'] as $cmid) {
2130 // Get the course module.
2131 $cm = $DB->get_record('course_modules', array('id' => $cmid), '*', MUST_EXIST);
2133 // Check if we have not yet confirmed they have permission in this course.
2134 if (!in_array($cm->course, $arrcourseschecked)) {
2135 // Ensure the current user has required permission in this course.
2136 $context = context_course::instance($cm->course);
2137 self::validate_context($context);
2138 // Add to the array.
2139 $arrcourseschecked[] = $cm->course;
2142 // Ensure they can delete this module.
2143 $modcontext = context_module::instance($cm->id);
2144 require_capability('moodle/course:manageactivities', $modcontext);
2146 // Delete the module.
2147 course_delete_module($cm->id);
2152 * Describes the delete_modules return value.
2154 * @return external_single_structure
2155 * @since Moodle 2.5
2157 public static function delete_modules_returns() {
2158 return null;
2162 * Returns description of method parameters
2164 * @return external_function_parameters
2165 * @since Moodle 2.9
2167 public static function view_course_parameters() {
2168 return new external_function_parameters(
2169 array(
2170 'courseid' => new external_value(PARAM_INT, 'id of the course'),
2171 'sectionnumber' => new external_value(PARAM_INT, 'section number', VALUE_DEFAULT, 0)
2177 * Trigger the course viewed event.
2179 * @param int $courseid id of course
2180 * @param int $sectionnumber sectionnumber (0, 1, 2...)
2181 * @return array of warnings and status result
2182 * @since Moodle 2.9
2183 * @throws moodle_exception
2185 public static function view_course($courseid, $sectionnumber = 0) {
2186 global $CFG;
2187 require_once($CFG->dirroot . "/course/lib.php");
2189 $params = self::validate_parameters(self::view_course_parameters(),
2190 array(
2191 'courseid' => $courseid,
2192 'sectionnumber' => $sectionnumber
2195 $warnings = array();
2197 $course = get_course($params['courseid']);
2198 $context = context_course::instance($course->id);
2199 self::validate_context($context);
2201 if (!empty($params['sectionnumber'])) {
2203 // Get section details and check it exists.
2204 $modinfo = get_fast_modinfo($course);
2205 $coursesection = $modinfo->get_section_info($params['sectionnumber'], MUST_EXIST);
2207 // Check user is allowed to see it.
2208 if (!$coursesection->uservisible) {
2209 require_capability('moodle/course:viewhiddensections', $context);
2213 course_view($context, $params['sectionnumber']);
2215 $result = array();
2216 $result['status'] = true;
2217 $result['warnings'] = $warnings;
2218 return $result;
2222 * Returns description of method result value
2224 * @return external_description
2225 * @since Moodle 2.9
2227 public static function view_course_returns() {
2228 return new external_single_structure(
2229 array(
2230 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
2231 'warnings' => new external_warnings()
2237 * Returns description of method parameters
2239 * @return external_function_parameters
2240 * @since Moodle 3.0
2242 public static function search_courses_parameters() {
2243 return new external_function_parameters(
2244 array(
2245 'criterianame' => new external_value(PARAM_ALPHA, 'criteria name
2246 (search, modulelist (only admins), blocklist (only admins), tagid)'),
2247 'criteriavalue' => new external_value(PARAM_RAW, 'criteria value'),
2248 'page' => new external_value(PARAM_INT, 'page number (0 based)', VALUE_DEFAULT, 0),
2249 'perpage' => new external_value(PARAM_INT, 'items per page', VALUE_DEFAULT, 0),
2250 'requiredcapabilities' => new external_multiple_structure(
2251 new external_value(PARAM_CAPABILITY, 'Capability string used to filter courses by permission'),
2252 'Optional list of required capabilities (used to filter the list)', VALUE_DEFAULT, array()
2254 'limittoenrolled' => new external_value(PARAM_BOOL, 'limit to enrolled courses', VALUE_DEFAULT, 0),
2260 * Return the course information that is public (visible by every one)
2262 * @param course_in_list $course course in list object
2263 * @param stdClass $coursecontext course context object
2264 * @return array the course information
2265 * @since Moodle 3.2
2267 protected static function get_course_public_information(course_in_list $course, $coursecontext) {
2269 static $categoriescache = array();
2271 // Category information.
2272 if (!array_key_exists($course->category, $categoriescache)) {
2273 $categoriescache[$course->category] = coursecat::get($course->category, IGNORE_MISSING);
2275 $category = $categoriescache[$course->category];
2277 // Retrieve course overview used files.
2278 $files = array();
2279 foreach ($course->get_course_overviewfiles() as $file) {
2280 $fileurl = moodle_url::make_webservice_pluginfile_url($file->get_contextid(), $file->get_component(),
2281 $file->get_filearea(), null, $file->get_filepath(),
2282 $file->get_filename())->out(false);
2283 $files[] = array(
2284 'filename' => $file->get_filename(),
2285 'fileurl' => $fileurl,
2286 'filesize' => $file->get_filesize(),
2287 'filepath' => $file->get_filepath(),
2288 'mimetype' => $file->get_mimetype(),
2289 'timemodified' => $file->get_timemodified(),
2293 // Retrieve the course contacts,
2294 // we need here the users fullname since if we are not enrolled can be difficult to obtain them via other Web Services.
2295 $coursecontacts = array();
2296 foreach ($course->get_course_contacts() as $contact) {
2297 $coursecontacts[] = array(
2298 'id' => $contact['user']->id,
2299 'fullname' => $contact['username']
2303 // Allowed enrolment methods (maybe we can self-enrol).
2304 $enroltypes = array();
2305 $instances = enrol_get_instances($course->id, true);
2306 foreach ($instances as $instance) {
2307 $enroltypes[] = $instance->enrol;
2310 // Format summary.
2311 list($summary, $summaryformat) =
2312 external_format_text($course->summary, $course->summaryformat, $coursecontext->id, 'course', 'summary', null);
2314 $categoryname = '';
2315 if (!empty($category)) {
2316 $categoryname = external_format_string($category->name, $category->get_context());
2319 $displayname = get_course_display_name_for_list($course);
2320 $coursereturns = array();
2321 $coursereturns['id'] = $course->id;
2322 $coursereturns['fullname'] = external_format_string($course->fullname, $coursecontext->id);
2323 $coursereturns['displayname'] = external_format_string($displayname, $coursecontext->id);
2324 $coursereturns['shortname'] = external_format_string($course->shortname, $coursecontext->id);
2325 $coursereturns['categoryid'] = $course->category;
2326 $coursereturns['categoryname'] = $categoryname;
2327 $coursereturns['summary'] = $summary;
2328 $coursereturns['summaryformat'] = $summaryformat;
2329 $coursereturns['summaryfiles'] = external_util::get_area_files($coursecontext->id, 'course', 'summary', false, false);
2330 $coursereturns['overviewfiles'] = $files;
2331 $coursereturns['contacts'] = $coursecontacts;
2332 $coursereturns['enrollmentmethods'] = $enroltypes;
2333 $coursereturns['sortorder'] = $course->sortorder;
2334 return $coursereturns;
2338 * Search courses following the specified criteria.
2340 * @param string $criterianame Criteria name (search, modulelist (only admins), blocklist (only admins), tagid)
2341 * @param string $criteriavalue Criteria value
2342 * @param int $page Page number (for pagination)
2343 * @param int $perpage Items per page
2344 * @param array $requiredcapabilities Optional list of required capabilities (used to filter the list).
2345 * @param int $limittoenrolled Limit to only enrolled courses
2346 * @return array of course objects and warnings
2347 * @since Moodle 3.0
2348 * @throws moodle_exception
2350 public static function search_courses($criterianame,
2351 $criteriavalue,
2352 $page=0,
2353 $perpage=0,
2354 $requiredcapabilities=array(),
2355 $limittoenrolled=0) {
2356 global $CFG;
2357 require_once($CFG->libdir . '/coursecatlib.php');
2359 $warnings = array();
2361 $parameters = array(
2362 'criterianame' => $criterianame,
2363 'criteriavalue' => $criteriavalue,
2364 'page' => $page,
2365 'perpage' => $perpage,
2366 'requiredcapabilities' => $requiredcapabilities
2368 $params = self::validate_parameters(self::search_courses_parameters(), $parameters);
2369 self::validate_context(context_system::instance());
2371 $allowedcriterianames = array('search', 'modulelist', 'blocklist', 'tagid');
2372 if (!in_array($params['criterianame'], $allowedcriterianames)) {
2373 throw new invalid_parameter_exception('Invalid value for criterianame parameter (value: '.$params['criterianame'].'),' .
2374 'allowed values are: '.implode(',', $allowedcriterianames));
2377 if ($params['criterianame'] == 'modulelist' or $params['criterianame'] == 'blocklist') {
2378 require_capability('moodle/site:config', context_system::instance());
2381 $paramtype = array(
2382 'search' => PARAM_RAW,
2383 'modulelist' => PARAM_PLUGIN,
2384 'blocklist' => PARAM_INT,
2385 'tagid' => PARAM_INT
2387 $params['criteriavalue'] = clean_param($params['criteriavalue'], $paramtype[$params['criterianame']]);
2389 // Prepare the search API options.
2390 $searchcriteria = array();
2391 $searchcriteria[$params['criterianame']] = $params['criteriavalue'];
2393 $options = array();
2394 if ($params['perpage'] != 0) {
2395 $offset = $params['page'] * $params['perpage'];
2396 $options = array('offset' => $offset, 'limit' => $params['perpage']);
2399 // Search the courses.
2400 $courses = coursecat::search_courses($searchcriteria, $options, $params['requiredcapabilities']);
2401 $totalcount = coursecat::search_courses_count($searchcriteria, $options, $params['requiredcapabilities']);
2403 if (!empty($limittoenrolled)) {
2404 // Get the courses where the current user has access.
2405 $enrolled = enrol_get_my_courses(array('id', 'cacherev'));
2408 $finalcourses = array();
2409 $categoriescache = array();
2411 foreach ($courses as $course) {
2412 if (!empty($limittoenrolled)) {
2413 // Filter out not enrolled courses.
2414 if (!isset($enrolled[$course->id])) {
2415 $totalcount--;
2416 continue;
2420 $coursecontext = context_course::instance($course->id);
2422 $finalcourses[] = self::get_course_public_information($course, $coursecontext);
2425 return array(
2426 'total' => $totalcount,
2427 'courses' => $finalcourses,
2428 'warnings' => $warnings
2433 * Returns a course structure definition
2435 * @param boolean $onlypublicdata set to true, to retrieve only fields viewable by anyone when the course is visible
2436 * @return array the course structure
2437 * @since Moodle 3.2
2439 protected static function get_course_structure($onlypublicdata = true) {
2440 $coursestructure = array(
2441 'id' => new external_value(PARAM_INT, 'course id'),
2442 'fullname' => new external_value(PARAM_TEXT, 'course full name'),
2443 'displayname' => new external_value(PARAM_TEXT, 'course display name'),
2444 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
2445 'categoryid' => new external_value(PARAM_INT, 'category id'),
2446 'categoryname' => new external_value(PARAM_TEXT, 'category name'),
2447 'sortorder' => new external_value(PARAM_INT, 'Sort order in the category', VALUE_OPTIONAL),
2448 'summary' => new external_value(PARAM_RAW, 'summary'),
2449 'summaryformat' => new external_format_value('summary'),
2450 'summaryfiles' => new external_files('summary files in the summary field', VALUE_OPTIONAL),
2451 'overviewfiles' => new external_files('additional overview files attached to this course'),
2452 'contacts' => new external_multiple_structure(
2453 new external_single_structure(
2454 array(
2455 'id' => new external_value(PARAM_INT, 'contact user id'),
2456 'fullname' => new external_value(PARAM_NOTAGS, 'contact user fullname'),
2459 'contact users'
2461 'enrollmentmethods' => new external_multiple_structure(
2462 new external_value(PARAM_PLUGIN, 'enrollment method'),
2463 'enrollment methods list'
2467 if (!$onlypublicdata) {
2468 $extra = array(
2469 'idnumber' => new external_value(PARAM_RAW, 'Id number', VALUE_OPTIONAL),
2470 'format' => new external_value(PARAM_PLUGIN, 'Course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
2471 'showgrades' => new external_value(PARAM_INT, '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
2472 'newsitems' => new external_value(PARAM_INT, 'Number of recent items appearing on the course page', VALUE_OPTIONAL),
2473 'startdate' => new external_value(PARAM_INT, 'Timestamp when the course start', VALUE_OPTIONAL),
2474 'enddate' => new external_value(PARAM_INT, 'Timestamp when the course end', VALUE_OPTIONAL),
2475 'maxbytes' => new external_value(PARAM_INT, 'Largest size of file that can be uploaded into', VALUE_OPTIONAL),
2476 'showreports' => new external_value(PARAM_INT, 'Are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
2477 'visible' => new external_value(PARAM_INT, '1: available to student, 0:not available', VALUE_OPTIONAL),
2478 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
2479 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
2480 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
2481 'enablecompletion' => new external_value(PARAM_INT, 'Completion enabled? 1: yes 0: no', VALUE_OPTIONAL),
2482 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
2483 'lang' => new external_value(PARAM_SAFEDIR, 'Forced course language', VALUE_OPTIONAL),
2484 'theme' => new external_value(PARAM_PLUGIN, 'Fame of the forced theme', VALUE_OPTIONAL),
2485 'marker' => new external_value(PARAM_INT, 'Current course marker', VALUE_OPTIONAL),
2486 'legacyfiles' => new external_value(PARAM_INT, 'If legacy files are enabled', VALUE_OPTIONAL),
2487 'calendartype' => new external_value(PARAM_PLUGIN, 'Calendar type', VALUE_OPTIONAL),
2488 'timecreated' => new external_value(PARAM_INT, 'Time when the course was created', VALUE_OPTIONAL),
2489 'timemodified' => new external_value(PARAM_INT, 'Last time the course was updated', VALUE_OPTIONAL),
2490 'requested' => new external_value(PARAM_INT, 'If is a requested course', VALUE_OPTIONAL),
2491 'cacherev' => new external_value(PARAM_INT, 'Cache revision number', VALUE_OPTIONAL),
2492 'filters' => new external_multiple_structure(
2493 new external_single_structure(
2494 array(
2495 'filter' => new external_value(PARAM_PLUGIN, 'Filter plugin name'),
2496 'localstate' => new external_value(PARAM_INT, 'Filter state: 1 for on, -1 for off, 0 if inherit'),
2497 'inheritedstate' => new external_value(PARAM_INT, '1 or 0 to use when localstate is set to inherit'),
2500 'Course filters', VALUE_OPTIONAL
2502 'courseformatoptions' => new external_multiple_structure(
2503 new external_single_structure(
2504 array(
2505 'name' => new external_value(PARAM_RAW, 'Course format option name.'),
2506 'value' => new external_value(PARAM_RAW, 'Course format option value.'),
2509 'Additional options for particular course format.', VALUE_OPTIONAL
2512 $coursestructure = array_merge($coursestructure, $extra);
2514 return new external_single_structure($coursestructure);
2518 * Returns description of method result value
2520 * @return external_description
2521 * @since Moodle 3.0
2523 public static function search_courses_returns() {
2524 return new external_single_structure(
2525 array(
2526 'total' => new external_value(PARAM_INT, 'total course count'),
2527 'courses' => new external_multiple_structure(self::get_course_structure(), 'course'),
2528 'warnings' => new external_warnings()
2534 * Returns description of method parameters
2536 * @return external_function_parameters
2537 * @since Moodle 3.0
2539 public static function get_course_module_parameters() {
2540 return new external_function_parameters(
2541 array(
2542 'cmid' => new external_value(PARAM_INT, 'The course module id')
2548 * Return information about a course module.
2550 * @param int $cmid the course module id
2551 * @return array of warnings and the course module
2552 * @since Moodle 3.0
2553 * @throws moodle_exception
2555 public static function get_course_module($cmid) {
2556 global $CFG, $DB;
2558 $params = self::validate_parameters(self::get_course_module_parameters(), array('cmid' => $cmid));
2559 $warnings = array();
2561 $cm = get_coursemodule_from_id(null, $params['cmid'], 0, true, MUST_EXIST);
2562 $context = context_module::instance($cm->id);
2563 self::validate_context($context);
2565 // If the user has permissions to manage the activity, return all the information.
2566 if (has_capability('moodle/course:manageactivities', $context)) {
2567 require_once($CFG->dirroot . '/course/modlib.php');
2568 require_once($CFG->libdir . '/gradelib.php');
2570 $info = $cm;
2571 // Get the extra information: grade, advanced grading and outcomes data.
2572 $course = get_course($cm->course);
2573 list($newcm, $newcontext, $module, $extrainfo, $cw) = get_moduleinfo_data($cm, $course);
2574 // Grades.
2575 $gradeinfo = array('grade', 'gradepass', 'gradecat');
2576 foreach ($gradeinfo as $gfield) {
2577 if (isset($extrainfo->{$gfield})) {
2578 $info->{$gfield} = $extrainfo->{$gfield};
2581 if (isset($extrainfo->grade) and $extrainfo->grade < 0) {
2582 $info->scale = $DB->get_field('scale', 'scale', array('id' => abs($extrainfo->grade)));
2584 // Advanced grading.
2585 if (isset($extrainfo->_advancedgradingdata)) {
2586 $info->advancedgrading = array();
2587 foreach ($extrainfo as $key => $val) {
2588 if (strpos($key, 'advancedgradingmethod_') === 0) {
2589 $info->advancedgrading[] = array(
2590 'area' => str_replace('advancedgradingmethod_', '', $key),
2591 'method' => $val
2596 // Outcomes.
2597 foreach ($extrainfo as $key => $val) {
2598 if (strpos($key, 'outcome_') === 0) {
2599 if (!isset($info->outcomes)) {
2600 $info->outcomes = array();
2602 $id = str_replace('outcome_', '', $key);
2603 $outcome = grade_outcome::fetch(array('id' => $id));
2604 $scaleitems = $outcome->load_scale();
2605 $info->outcomes[] = array(
2606 'id' => $id,
2607 'name' => external_format_string($outcome->get_name(), $context->id),
2608 'scale' => $scaleitems->scale
2612 } else {
2613 // Return information is safe to show to any user.
2614 $info = new stdClass();
2615 $info->id = $cm->id;
2616 $info->course = $cm->course;
2617 $info->module = $cm->module;
2618 $info->modname = $cm->modname;
2619 $info->instance = $cm->instance;
2620 $info->section = $cm->section;
2621 $info->sectionnum = $cm->sectionnum;
2622 $info->groupmode = $cm->groupmode;
2623 $info->groupingid = $cm->groupingid;
2624 $info->completion = $cm->completion;
2626 // Format name.
2627 $info->name = external_format_string($cm->name, $context->id);
2628 $result = array();
2629 $result['cm'] = $info;
2630 $result['warnings'] = $warnings;
2631 return $result;
2635 * Returns description of method result value
2637 * @return external_description
2638 * @since Moodle 3.0
2640 public static function get_course_module_returns() {
2641 return new external_single_structure(
2642 array(
2643 'cm' => new external_single_structure(
2644 array(
2645 'id' => new external_value(PARAM_INT, 'The course module id'),
2646 'course' => new external_value(PARAM_INT, 'The course id'),
2647 'module' => new external_value(PARAM_INT, 'The module type id'),
2648 'name' => new external_value(PARAM_RAW, 'The activity name'),
2649 'modname' => new external_value(PARAM_COMPONENT, 'The module component name (forum, assign, etc..)'),
2650 'instance' => new external_value(PARAM_INT, 'The activity instance id'),
2651 'section' => new external_value(PARAM_INT, 'The module section id'),
2652 'sectionnum' => new external_value(PARAM_INT, 'The module section number'),
2653 'groupmode' => new external_value(PARAM_INT, 'Group mode'),
2654 'groupingid' => new external_value(PARAM_INT, 'Grouping id'),
2655 'completion' => new external_value(PARAM_INT, 'If completion is enabled'),
2656 'idnumber' => new external_value(PARAM_RAW, 'Module id number', VALUE_OPTIONAL),
2657 'added' => new external_value(PARAM_INT, 'Time added', VALUE_OPTIONAL),
2658 'score' => new external_value(PARAM_INT, 'Score', VALUE_OPTIONAL),
2659 'indent' => new external_value(PARAM_INT, 'Indentation', VALUE_OPTIONAL),
2660 'visible' => new external_value(PARAM_INT, 'If visible', VALUE_OPTIONAL),
2661 'visibleoncoursepage' => new external_value(PARAM_INT, 'If visible on course page', VALUE_OPTIONAL),
2662 'visibleold' => new external_value(PARAM_INT, 'Visible old', VALUE_OPTIONAL),
2663 'completiongradeitemnumber' => new external_value(PARAM_INT, 'Completion grade item', VALUE_OPTIONAL),
2664 'completionview' => new external_value(PARAM_INT, 'Completion view setting', VALUE_OPTIONAL),
2665 'completionexpected' => new external_value(PARAM_INT, 'Completion time expected', VALUE_OPTIONAL),
2666 'showdescription' => new external_value(PARAM_INT, 'If the description is showed', VALUE_OPTIONAL),
2667 'availability' => new external_value(PARAM_RAW, 'Availability settings', VALUE_OPTIONAL),
2668 'grade' => new external_value(PARAM_FLOAT, 'Grade (max value or scale id)', VALUE_OPTIONAL),
2669 'scale' => new external_value(PARAM_TEXT, 'Scale items (if used)', VALUE_OPTIONAL),
2670 'gradepass' => new external_value(PARAM_RAW, 'Grade to pass (float)', VALUE_OPTIONAL),
2671 'gradecat' => new external_value(PARAM_INT, 'Grade category', VALUE_OPTIONAL),
2672 'advancedgrading' => new external_multiple_structure(
2673 new external_single_structure(
2674 array(
2675 'area' => new external_value(PARAM_AREA, 'Gradable area name'),
2676 'method' => new external_value(PARAM_COMPONENT, 'Grading method'),
2679 'Advanced grading settings', VALUE_OPTIONAL
2681 'outcomes' => new external_multiple_structure(
2682 new external_single_structure(
2683 array(
2684 'id' => new external_value(PARAM_ALPHANUMEXT, 'Outcome id'),
2685 'name' => new external_value(PARAM_TEXT, 'Outcome full name'),
2686 'scale' => new external_value(PARAM_TEXT, 'Scale items')
2689 'Outcomes information', VALUE_OPTIONAL
2693 'warnings' => new external_warnings()
2699 * Returns description of method parameters
2701 * @return external_function_parameters
2702 * @since Moodle 3.0
2704 public static function get_course_module_by_instance_parameters() {
2705 return new external_function_parameters(
2706 array(
2707 'module' => new external_value(PARAM_COMPONENT, 'The module name'),
2708 'instance' => new external_value(PARAM_INT, 'The module instance id')
2714 * Return information about a course module.
2716 * @param string $module the module name
2717 * @param int $instance the activity instance id
2718 * @return array of warnings and the course module
2719 * @since Moodle 3.0
2720 * @throws moodle_exception
2722 public static function get_course_module_by_instance($module, $instance) {
2724 $params = self::validate_parameters(self::get_course_module_by_instance_parameters(),
2725 array(
2726 'module' => $module,
2727 'instance' => $instance,
2730 $warnings = array();
2731 $cm = get_coursemodule_from_instance($params['module'], $params['instance'], 0, false, MUST_EXIST);
2733 return self::get_course_module($cm->id);
2737 * Returns description of method result value
2739 * @return external_description
2740 * @since Moodle 3.0
2742 public static function get_course_module_by_instance_returns() {
2743 return self::get_course_module_returns();
2747 * Returns description of method parameters
2749 * @deprecated since 3.3
2750 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
2751 * @return external_function_parameters
2752 * @since Moodle 3.2
2754 public static function get_activities_overview_parameters() {
2755 return new external_function_parameters(
2756 array(
2757 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2763 * Return activities overview for the given courses.
2765 * @deprecated since 3.3
2766 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
2767 * @param array $courseids a list of course ids
2768 * @return array of warnings and the activities overview
2769 * @since Moodle 3.2
2770 * @throws moodle_exception
2772 public static function get_activities_overview($courseids) {
2773 global $USER;
2775 // Parameter validation.
2776 $params = self::validate_parameters(self::get_activities_overview_parameters(), array('courseids' => $courseids));
2777 $courseoverviews = array();
2779 list($courses, $warnings) = external_util::validate_courses($params['courseids']);
2781 if (!empty($courses)) {
2782 // Add lastaccess to each course (required by print_overview function).
2783 // We need the complete user data, the ws server does not load a complete one.
2784 $user = get_complete_user_data('id', $USER->id);
2785 foreach ($courses as $course) {
2786 if (isset($user->lastcourseaccess[$course->id])) {
2787 $course->lastaccess = $user->lastcourseaccess[$course->id];
2788 } else {
2789 $course->lastaccess = 0;
2793 $overviews = array();
2794 if ($modules = get_plugin_list_with_function('mod', 'print_overview')) {
2795 foreach ($modules as $fname) {
2796 $fname($courses, $overviews);
2800 // Format output.
2801 foreach ($overviews as $courseid => $modules) {
2802 $courseoverviews[$courseid]['id'] = $courseid;
2803 $courseoverviews[$courseid]['overviews'] = array();
2805 foreach ($modules as $modname => $overviewtext) {
2806 $courseoverviews[$courseid]['overviews'][] = array(
2807 'module' => $modname,
2808 'overviewtext' => $overviewtext // This text doesn't need formatting.
2814 $result = array(
2815 'courses' => $courseoverviews,
2816 'warnings' => $warnings
2818 return $result;
2822 * Returns description of method result value
2824 * @deprecated since 3.3
2825 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
2826 * @return external_description
2827 * @since Moodle 3.2
2829 public static function get_activities_overview_returns() {
2830 return new external_single_structure(
2831 array(
2832 'courses' => new external_multiple_structure(
2833 new external_single_structure(
2834 array(
2835 'id' => new external_value(PARAM_INT, 'Course id'),
2836 'overviews' => new external_multiple_structure(
2837 new external_single_structure(
2838 array(
2839 'module' => new external_value(PARAM_PLUGIN, 'Module name'),
2840 'overviewtext' => new external_value(PARAM_RAW, 'Overview text'),
2845 ), 'List of courses'
2847 'warnings' => new external_warnings()
2853 * Marking the method as deprecated.
2855 * @return bool
2857 public static function get_activities_overview_is_deprecated() {
2858 return true;
2862 * Returns description of method parameters
2864 * @return external_function_parameters
2865 * @since Moodle 3.2
2867 public static function get_user_navigation_options_parameters() {
2868 return new external_function_parameters(
2869 array(
2870 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2876 * Return a list of navigation options in a set of courses that are avaialable or not for the current user.
2878 * @param array $courseids a list of course ids
2879 * @return array of warnings and the options availability
2880 * @since Moodle 3.2
2881 * @throws moodle_exception
2883 public static function get_user_navigation_options($courseids) {
2884 global $CFG;
2885 require_once($CFG->dirroot . '/course/lib.php');
2887 // Parameter validation.
2888 $params = self::validate_parameters(self::get_user_navigation_options_parameters(), array('courseids' => $courseids));
2889 $courseoptions = array();
2891 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
2893 if (!empty($courses)) {
2894 foreach ($courses as $course) {
2895 // Fix the context for the frontpage.
2896 if ($course->id == SITEID) {
2897 $course->context = context_system::instance();
2899 $navoptions = course_get_user_navigation_options($course->context, $course);
2900 $options = array();
2901 foreach ($navoptions as $name => $available) {
2902 $options[] = array(
2903 'name' => $name,
2904 'available' => $available,
2908 $courseoptions[] = array(
2909 'id' => $course->id,
2910 'options' => $options
2915 $result = array(
2916 'courses' => $courseoptions,
2917 'warnings' => $warnings
2919 return $result;
2923 * Returns description of method result value
2925 * @return external_description
2926 * @since Moodle 3.2
2928 public static function get_user_navigation_options_returns() {
2929 return new external_single_structure(
2930 array(
2931 'courses' => new external_multiple_structure(
2932 new external_single_structure(
2933 array(
2934 'id' => new external_value(PARAM_INT, 'Course id'),
2935 'options' => new external_multiple_structure(
2936 new external_single_structure(
2937 array(
2938 'name' => new external_value(PARAM_ALPHANUMEXT, 'Option name'),
2939 'available' => new external_value(PARAM_BOOL, 'Whether the option is available or not'),
2944 ), 'List of courses'
2946 'warnings' => new external_warnings()
2952 * Returns description of method parameters
2954 * @return external_function_parameters
2955 * @since Moodle 3.2
2957 public static function get_user_administration_options_parameters() {
2958 return new external_function_parameters(
2959 array(
2960 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2966 * Return a list of administration options in a set of courses that are available or not for the current user.
2968 * @param array $courseids a list of course ids
2969 * @return array of warnings and the options availability
2970 * @since Moodle 3.2
2971 * @throws moodle_exception
2973 public static function get_user_administration_options($courseids) {
2974 global $CFG;
2975 require_once($CFG->dirroot . '/course/lib.php');
2977 // Parameter validation.
2978 $params = self::validate_parameters(self::get_user_administration_options_parameters(), array('courseids' => $courseids));
2979 $courseoptions = array();
2981 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
2983 if (!empty($courses)) {
2984 foreach ($courses as $course) {
2985 $adminoptions = course_get_user_administration_options($course, $course->context);
2986 $options = array();
2987 foreach ($adminoptions as $name => $available) {
2988 $options[] = array(
2989 'name' => $name,
2990 'available' => $available,
2994 $courseoptions[] = array(
2995 'id' => $course->id,
2996 'options' => $options
3001 $result = array(
3002 'courses' => $courseoptions,
3003 'warnings' => $warnings
3005 return $result;
3009 * Returns description of method result value
3011 * @return external_description
3012 * @since Moodle 3.2
3014 public static function get_user_administration_options_returns() {
3015 return self::get_user_navigation_options_returns();
3019 * Returns description of method parameters
3021 * @return external_function_parameters
3022 * @since Moodle 3.2
3024 public static function get_courses_by_field_parameters() {
3025 return new external_function_parameters(
3026 array(
3027 'field' => new external_value(PARAM_ALPHA, 'The field to search can be left empty for all courses or:
3028 id: course id
3029 ids: comma separated course ids
3030 shortname: course short name
3031 idnumber: course id number
3032 category: category id the course belongs to
3033 ', VALUE_DEFAULT, ''),
3034 'value' => new external_value(PARAM_RAW, 'The value to match', VALUE_DEFAULT, '')
3041 * Get courses matching a specific field (id/s, shortname, idnumber, category)
3043 * @param string $field field name to search, or empty for all courses
3044 * @param string $value value to search
3045 * @return array list of courses and warnings
3046 * @throws invalid_parameter_exception
3047 * @since Moodle 3.2
3049 public static function get_courses_by_field($field = '', $value = '') {
3050 global $DB, $CFG;
3051 require_once($CFG->libdir . '/coursecatlib.php');
3052 require_once($CFG->dirroot . '/course/lib.php');
3053 require_once($CFG->libdir . '/filterlib.php');
3055 $params = self::validate_parameters(self::get_courses_by_field_parameters(),
3056 array(
3057 'field' => $field,
3058 'value' => $value,
3061 $warnings = array();
3063 if (empty($params['field'])) {
3064 $courses = $DB->get_records('course', null, 'id ASC');
3065 } else {
3066 switch ($params['field']) {
3067 case 'id':
3068 case 'category':
3069 $value = clean_param($params['value'], PARAM_INT);
3070 break;
3071 case 'ids':
3072 $value = clean_param($params['value'], PARAM_SEQUENCE);
3073 break;
3074 case 'shortname':
3075 $value = clean_param($params['value'], PARAM_TEXT);
3076 break;
3077 case 'idnumber':
3078 $value = clean_param($params['value'], PARAM_RAW);
3079 break;
3080 default:
3081 throw new invalid_parameter_exception('Invalid field name');
3084 if ($params['field'] === 'ids') {
3085 $courses = $DB->get_records_list('course', 'id', explode(',', $value), 'id ASC');
3086 } else {
3087 $courses = $DB->get_records('course', array($params['field'] => $value), 'id ASC');
3091 $coursesdata = array();
3092 foreach ($courses as $course) {
3093 $context = context_course::instance($course->id);
3094 $canupdatecourse = has_capability('moodle/course:update', $context);
3095 $canviewhiddencourses = has_capability('moodle/course:viewhiddencourses', $context);
3097 // Check if the course is visible in the site for the user.
3098 if (!$course->visible and !$canviewhiddencourses and !$canupdatecourse) {
3099 continue;
3101 // Get the public course information, even if we are not enrolled.
3102 $courseinlist = new course_in_list($course);
3103 $coursesdata[$course->id] = self::get_course_public_information($courseinlist, $context);
3105 // Now, check if we have access to the course.
3106 try {
3107 self::validate_context($context);
3108 } catch (Exception $e) {
3109 continue;
3111 // Return information for any user that can access the course.
3112 $coursefields = array('format', 'showgrades', 'newsitems', 'startdate', 'enddate', 'maxbytes', 'showreports', 'visible',
3113 'groupmode', 'groupmodeforce', 'defaultgroupingid', 'enablecompletion', 'completionnotify', 'lang', 'theme',
3114 'marker');
3116 // Course filters.
3117 $coursesdata[$course->id]['filters'] = filter_get_available_in_context($context);
3119 // Information for managers only.
3120 if ($canupdatecourse) {
3121 $managerfields = array('idnumber', 'legacyfiles', 'calendartype', 'timecreated', 'timemodified', 'requested',
3122 'cacherev');
3123 $coursefields = array_merge($coursefields, $managerfields);
3126 // Populate fields.
3127 foreach ($coursefields as $field) {
3128 $coursesdata[$course->id][$field] = $course->{$field};
3131 // Clean lang and auth fields for external functions (it may content uninstalled themes or language packs).
3132 if (isset($coursesdata[$course->id]['theme'])) {
3133 $coursesdata[$course->id]['theme'] = clean_param($coursesdata[$course->id]['theme'], PARAM_THEME);
3135 if (isset($coursesdata[$course->id]['lang'])) {
3136 $coursesdata[$course->id]['lang'] = clean_param($coursesdata[$course->id]['lang'], PARAM_LANG);
3139 $courseformatoptions = course_get_format($course)->get_config_for_external();
3140 foreach ($courseformatoptions as $key => $value) {
3141 $coursesdata[$course->id]['courseformatoptions'][] = array(
3142 'name' => $key,
3143 'value' => $value
3148 return array(
3149 'courses' => $coursesdata,
3150 'warnings' => $warnings
3155 * Returns description of method result value
3157 * @return external_description
3158 * @since Moodle 3.2
3160 public static function get_courses_by_field_returns() {
3161 // Course structure, including not only public viewable fields.
3162 return new external_single_structure(
3163 array(
3164 'courses' => new external_multiple_structure(self::get_course_structure(false), 'Course'),
3165 'warnings' => new external_warnings()
3171 * Returns description of method parameters
3173 * @return external_function_parameters
3174 * @since Moodle 3.2
3176 public static function check_updates_parameters() {
3177 return new external_function_parameters(
3178 array(
3179 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3180 'tocheck' => new external_multiple_structure(
3181 new external_single_structure(
3182 array(
3183 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level for the file location.
3184 Only module supported right now.'),
3185 'id' => new external_value(PARAM_INT, 'Context instance id'),
3186 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3189 'Instances to check'
3191 'filter' => new external_multiple_structure(
3192 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3193 gradeitems, outcomes'),
3194 'Check only for updates in these areas', VALUE_DEFAULT, array()
3201 * Check if there is updates affecting the user for the given course and contexts.
3202 * Right now only modules are supported.
3203 * This WS calls mod_check_updates_since for each module to check if there is any update the user should we aware of.
3205 * @param int $courseid the list of modules to check
3206 * @param array $tocheck the list of modules to check
3207 * @param array $filter check only for updates in these areas
3208 * @return array list of updates and warnings
3209 * @throws moodle_exception
3210 * @since Moodle 3.2
3212 public static function check_updates($courseid, $tocheck, $filter = array()) {
3213 global $CFG, $DB;
3214 require_once($CFG->dirroot . "/course/lib.php");
3216 $params = self::validate_parameters(
3217 self::check_updates_parameters(),
3218 array(
3219 'courseid' => $courseid,
3220 'tocheck' => $tocheck,
3221 'filter' => $filter,
3225 $course = get_course($params['courseid']);
3226 $context = context_course::instance($course->id);
3227 self::validate_context($context);
3229 list($instances, $warnings) = course_check_updates($course, $params['tocheck'], $filter);
3231 $instancesformatted = array();
3232 foreach ($instances as $instance) {
3233 $updates = array();
3234 foreach ($instance['updates'] as $name => $data) {
3235 if (empty($data->updated)) {
3236 continue;
3238 $updatedata = array(
3239 'name' => $name,
3241 if (!empty($data->timeupdated)) {
3242 $updatedata['timeupdated'] = $data->timeupdated;
3244 if (!empty($data->itemids)) {
3245 $updatedata['itemids'] = $data->itemids;
3247 $updates[] = $updatedata;
3249 if (!empty($updates)) {
3250 $instancesformatted[] = array(
3251 'contextlevel' => $instance['contextlevel'],
3252 'id' => $instance['id'],
3253 'updates' => $updates
3258 return array(
3259 'instances' => $instancesformatted,
3260 'warnings' => $warnings
3265 * Returns description of method result value
3267 * @return external_description
3268 * @since Moodle 3.2
3270 public static function check_updates_returns() {
3271 return new external_single_structure(
3272 array(
3273 'instances' => new external_multiple_structure(
3274 new external_single_structure(
3275 array(
3276 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level'),
3277 'id' => new external_value(PARAM_INT, 'Instance id'),
3278 'updates' => new external_multiple_structure(
3279 new external_single_structure(
3280 array(
3281 'name' => new external_value(PARAM_ALPHANUMEXT, 'Name of the area updated.'),
3282 'timeupdated' => new external_value(PARAM_INT, 'Last time was updated', VALUE_OPTIONAL),
3283 'itemids' => new external_multiple_structure(
3284 new external_value(PARAM_INT, 'Instance id'),
3285 'The ids of the items updated',
3286 VALUE_OPTIONAL
3294 'warnings' => new external_warnings()
3300 * Returns description of method parameters
3302 * @return external_function_parameters
3303 * @since Moodle 3.3
3305 public static function get_updates_since_parameters() {
3306 return new external_function_parameters(
3307 array(
3308 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3309 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3310 'filter' => new external_multiple_structure(
3311 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3312 gradeitems, outcomes'),
3313 'Check only for updates in these areas', VALUE_DEFAULT, array()
3320 * Check if there are updates affecting the user for the given course since the given time stamp.
3322 * This function is a wrapper of self::check_updates for retrieving all the updates since a given time for all the activities.
3324 * @param int $courseid the list of modules to check
3325 * @param int $since check updates since this time stamp
3326 * @param array $filter check only for updates in these areas
3327 * @return array list of updates and warnings
3328 * @throws moodle_exception
3329 * @since Moodle 3.3
3331 public static function get_updates_since($courseid, $since, $filter = array()) {
3332 global $CFG, $DB;
3334 $params = self::validate_parameters(
3335 self::get_updates_since_parameters(),
3336 array(
3337 'courseid' => $courseid,
3338 'since' => $since,
3339 'filter' => $filter,
3343 $course = get_course($params['courseid']);
3344 $modinfo = get_fast_modinfo($course);
3345 $tocheck = array();
3347 // Retrieve all the visible course modules for the current user.
3348 $cms = $modinfo->get_cms();
3349 foreach ($cms as $cm) {
3350 if (!$cm->uservisible) {
3351 continue;
3353 $tocheck[] = array(
3354 'id' => $cm->id,
3355 'contextlevel' => 'module',
3356 'since' => $params['since'],
3360 return self::check_updates($course->id, $tocheck, $params['filter']);
3364 * Returns description of method result value
3366 * @return external_description
3367 * @since Moodle 3.3
3369 public static function get_updates_since_returns() {
3370 return self::check_updates_returns();
3374 * Parameters for function edit_module()
3376 * @since Moodle 3.3
3377 * @return external_function_parameters
3379 public static function edit_module_parameters() {
3380 return new external_function_parameters(
3381 array(
3382 'action' => new external_value(PARAM_ALPHA,
3383 'action: hide, show, stealth, duplicate, delete, moveleft, moveright, group...', VALUE_REQUIRED),
3384 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3385 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3390 * Performs one of the edit module actions and return new html for AJAX
3392 * Returns html to replace the current module html with, for example:
3393 * - empty string for "delete" action,
3394 * - two modules html for "duplicate" action
3395 * - updated module html for everything else
3397 * Throws exception if operation is not permitted/possible
3399 * @since Moodle 3.3
3400 * @param string $action
3401 * @param int $id
3402 * @param null|int $sectionreturn
3403 * @return string
3405 public static function edit_module($action, $id, $sectionreturn = null) {
3406 global $PAGE, $DB;
3407 // Validate and normalize parameters.
3408 $params = self::validate_parameters(self::edit_module_parameters(),
3409 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3410 $action = $params['action'];
3411 $id = $params['id'];
3412 $sectionreturn = $params['sectionreturn'];
3414 list($course, $cm) = get_course_and_cm_from_cmid($id);
3415 $modcontext = context_module::instance($cm->id);
3416 $coursecontext = context_course::instance($course->id);
3417 self::validate_context($modcontext);
3418 $courserenderer = $PAGE->get_renderer('core', 'course');
3419 $completioninfo = new completion_info($course);
3421 switch($action) {
3422 case 'hide':
3423 case 'show':
3424 case 'stealth':
3425 require_capability('moodle/course:activityvisibility', $modcontext);
3426 $visible = ($action === 'hide') ? 0 : 1;
3427 $visibleoncoursepage = ($action === 'stealth') ? 0 : 1;
3428 set_coursemodule_visible($id, $visible, $visibleoncoursepage);
3429 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3430 break;
3431 case 'duplicate':
3432 require_capability('moodle/course:manageactivities', $coursecontext);
3433 require_capability('moodle/backup:backuptargetimport', $coursecontext);
3434 require_capability('moodle/restore:restoretargetimport', $coursecontext);
3435 if (!course_allowed_module($course, $cm->modname)) {
3436 throw new moodle_exception('No permission to create that activity');
3438 if ($newcm = duplicate_module($course, $cm)) {
3439 $cm = get_fast_modinfo($course)->get_cm($id);
3440 $newcm = get_fast_modinfo($course)->get_cm($newcm->id);
3441 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn) .
3442 $courserenderer->course_section_cm_list_item($course, $completioninfo, $newcm, $sectionreturn);
3444 break;
3445 case 'groupsseparate':
3446 case 'groupsvisible':
3447 case 'groupsnone':
3448 require_capability('moodle/course:manageactivities', $modcontext);
3449 if ($action === 'groupsseparate') {
3450 $newgroupmode = SEPARATEGROUPS;
3451 } else if ($action === 'groupsvisible') {
3452 $newgroupmode = VISIBLEGROUPS;
3453 } else {
3454 $newgroupmode = NOGROUPS;
3456 if (set_coursemodule_groupmode($cm->id, $newgroupmode)) {
3457 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3459 break;
3460 case 'moveleft':
3461 case 'moveright':
3462 require_capability('moodle/course:manageactivities', $modcontext);
3463 $indent = $cm->indent + (($action === 'moveright') ? 1 : -1);
3464 if ($cm->indent >= 0) {
3465 $DB->update_record('course_modules', array('id' => $cm->id, 'indent' => $indent));
3466 rebuild_course_cache($cm->course);
3468 break;
3469 case 'delete':
3470 require_capability('moodle/course:manageactivities', $modcontext);
3471 course_delete_module($cm->id, true);
3472 return '';
3473 default:
3474 throw new coding_exception('Unrecognised action');
3477 $cm = get_fast_modinfo($course)->get_cm($id);
3478 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn);
3482 * Return structure for edit_module()
3484 * @since Moodle 3.3
3485 * @return external_description
3487 public static function edit_module_returns() {
3488 return new external_value(PARAM_RAW, 'html to replace the current module with');
3492 * Parameters for function get_module()
3494 * @since Moodle 3.3
3495 * @return external_function_parameters
3497 public static function get_module_parameters() {
3498 return new external_function_parameters(
3499 array(
3500 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3501 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3506 * Returns html for displaying one activity module on course page
3508 * @since Moodle 3.3
3509 * @param int $id
3510 * @param null|int $sectionreturn
3511 * @return string
3513 public static function get_module($id, $sectionreturn = null) {
3514 global $PAGE;
3515 // Validate and normalize parameters.
3516 $params = self::validate_parameters(self::get_module_parameters(),
3517 array('id' => $id, 'sectionreturn' => $sectionreturn));
3518 $id = $params['id'];
3519 $sectionreturn = $params['sectionreturn'];
3521 // Validate access to the course (note, this is html for the course view page, we don't validate access to the module).
3522 list($course, $cm) = get_course_and_cm_from_cmid($id);
3523 self::validate_context(context_course::instance($course->id));
3525 $courserenderer = $PAGE->get_renderer('core', 'course');
3526 $completioninfo = new completion_info($course);
3527 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn);
3531 * Return structure for edit_module()
3533 * @since Moodle 3.3
3534 * @return external_description
3536 public static function get_module_returns() {
3537 return new external_value(PARAM_RAW, 'html to replace the current module with');
3541 * Parameters for function edit_section()
3543 * @since Moodle 3.3
3544 * @return external_function_parameters
3546 public static function edit_section_parameters() {
3547 return new external_function_parameters(
3548 array(
3549 'action' => new external_value(PARAM_ALPHA, 'action: hide, show, stealth, setmarker, removemarker', VALUE_REQUIRED),
3550 'id' => new external_value(PARAM_INT, 'course section id', VALUE_REQUIRED),
3551 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3556 * Performs one of the edit section actions
3558 * @since Moodle 3.3
3559 * @param string $action
3560 * @param int $id section id
3561 * @param int $sectionreturn section to return to
3562 * @return string
3564 public static function edit_section($action, $id, $sectionreturn) {
3565 global $DB;
3566 // Validate and normalize parameters.
3567 $params = self::validate_parameters(self::edit_section_parameters(),
3568 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3569 $action = $params['action'];
3570 $id = $params['id'];
3571 $sr = $params['sectionreturn'];
3573 $section = $DB->get_record('course_sections', array('id' => $id), '*', MUST_EXIST);
3574 $coursecontext = context_course::instance($section->course);
3575 self::validate_context($coursecontext);
3577 $rv = course_get_format($section->course)->section_action($section, $action, $sectionreturn);
3578 if ($rv) {
3579 return json_encode($rv);
3580 } else {
3581 return null;
3586 * Return structure for edit_section()
3588 * @since Moodle 3.3
3589 * @return external_description
3591 public static function edit_section_returns() {
3592 return new external_value(PARAM_RAW, 'Additional data for javascript (JSON-encoded string)');