Merge branch 'MDL-63625-master' of git://github.com/marinaglancy/moodle
[moodle.git] / course / externallib.php
blobea887ce5153eabbfecd997f33568a072139dc635
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * External course API
21 * @package core_course
22 * @category external
23 * @copyright 2009 Petr Skodak
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') || die;
29 use core_course\external\course_summary_exporter;
31 require_once("$CFG->libdir/externallib.php");
33 /**
34 * Course external functions
36 * @package core_course
37 * @category external
38 * @copyright 2011 Jerome Mouneyrac
39 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
40 * @since Moodle 2.2
42 class core_course_external extends external_api {
44 /**
45 * Returns description of method parameters
47 * @return external_function_parameters
48 * @since Moodle 2.9 Options available
49 * @since Moodle 2.2
51 public static function get_course_contents_parameters() {
52 return new external_function_parameters(
53 array('courseid' => new external_value(PARAM_INT, 'course id'),
54 'options' => new external_multiple_structure (
55 new external_single_structure(
56 array(
57 'name' => new external_value(PARAM_ALPHANUM,
58 'The expected keys (value format) are:
59 excludemodules (bool) Do not return modules, return only the sections structure
60 excludecontents (bool) Do not return module contents (i.e: files inside a resource)
61 includestealthmodules (bool) Return stealth modules for students in a special
62 section (with id -1)
63 sectionid (int) Return only this section
64 sectionnumber (int) Return only this section with number (order)
65 cmid (int) Return only this module information (among the whole sections structure)
66 modname (string) Return only modules with this name "label, forum, etc..."
67 modid (int) Return only the module with this id (to be used with modname'),
68 'value' => new external_value(PARAM_RAW, 'the value of the option,
69 this param is personaly validated in the external function.')
71 ), 'Options, used since Moodle 2.9', VALUE_DEFAULT, array())
76 /**
77 * Get course contents
79 * @param int $courseid course id
80 * @param array $options Options for filtering the results, used since Moodle 2.9
81 * @return array
82 * @since Moodle 2.9 Options available
83 * @since Moodle 2.2
85 public static function get_course_contents($courseid, $options = array()) {
86 global $CFG, $DB;
87 require_once($CFG->dirroot . "/course/lib.php");
89 //validate parameter
90 $params = self::validate_parameters(self::get_course_contents_parameters(),
91 array('courseid' => $courseid, 'options' => $options));
93 $filters = array();
94 if (!empty($params['options'])) {
96 foreach ($params['options'] as $option) {
97 $name = trim($option['name']);
98 // Avoid duplicated options.
99 if (!isset($filters[$name])) {
100 switch ($name) {
101 case 'excludemodules':
102 case 'excludecontents':
103 case 'includestealthmodules':
104 $value = clean_param($option['value'], PARAM_BOOL);
105 $filters[$name] = $value;
106 break;
107 case 'sectionid':
108 case 'sectionnumber':
109 case 'cmid':
110 case 'modid':
111 $value = clean_param($option['value'], PARAM_INT);
112 if (is_numeric($value)) {
113 $filters[$name] = $value;
114 } else {
115 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
117 break;
118 case 'modname':
119 $value = clean_param($option['value'], PARAM_PLUGIN);
120 if ($value) {
121 $filters[$name] = $value;
122 } else {
123 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
125 break;
126 default:
127 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
133 //retrieve the course
134 $course = $DB->get_record('course', array('id' => $params['courseid']), '*', MUST_EXIST);
136 if ($course->id != SITEID) {
137 // Check course format exist.
138 if (!file_exists($CFG->dirroot . '/course/format/' . $course->format . '/lib.php')) {
139 throw new moodle_exception('cannotgetcoursecontents', 'webservice', '', null,
140 get_string('courseformatnotfound', 'error', $course->format));
141 } else {
142 require_once($CFG->dirroot . '/course/format/' . $course->format . '/lib.php');
146 // now security checks
147 $context = context_course::instance($course->id, IGNORE_MISSING);
148 try {
149 self::validate_context($context);
150 } catch (Exception $e) {
151 $exceptionparam = new stdClass();
152 $exceptionparam->message = $e->getMessage();
153 $exceptionparam->courseid = $course->id;
154 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
157 $canupdatecourse = has_capability('moodle/course:update', $context);
159 //create return value
160 $coursecontents = array();
162 if ($canupdatecourse or $course->visible
163 or has_capability('moodle/course:viewhiddencourses', $context)) {
165 //retrieve sections
166 $modinfo = get_fast_modinfo($course);
167 $sections = $modinfo->get_section_info_all();
168 $coursenumsections = course_get_format($course)->get_last_section_number();
169 $stealthmodules = array(); // Array to keep all the modules available but not visible in a course section/topic.
171 //for each sections (first displayed to last displayed)
172 $modinfosections = $modinfo->get_sections();
173 foreach ($sections as $key => $section) {
175 // This becomes true when we are filtering and we found the value to filter with.
176 $sectionfound = false;
178 // Filter by section id.
179 if (!empty($filters['sectionid'])) {
180 if ($section->id != $filters['sectionid']) {
181 continue;
182 } else {
183 $sectionfound = true;
187 // Filter by section number. Note that 0 is a valid section number.
188 if (isset($filters['sectionnumber'])) {
189 if ($key != $filters['sectionnumber']) {
190 continue;
191 } else {
192 $sectionfound = true;
196 // reset $sectioncontents
197 $sectionvalues = array();
198 $sectionvalues['id'] = $section->id;
199 $sectionvalues['name'] = get_section_name($course, $section);
200 $sectionvalues['visible'] = $section->visible;
202 $options = (object) array('noclean' => true);
203 list($sectionvalues['summary'], $sectionvalues['summaryformat']) =
204 external_format_text($section->summary, $section->summaryformat,
205 $context->id, 'course', 'section', $section->id, $options);
206 $sectionvalues['section'] = $section->section;
207 $sectionvalues['hiddenbynumsections'] = $section->section > $coursenumsections ? 1 : 0;
208 $sectionvalues['uservisible'] = $section->uservisible;
209 if (!empty($section->availableinfo)) {
210 $sectionvalues['availabilityinfo'] = \core_availability\info::format_info($section->availableinfo, $course);
213 $sectioncontents = array();
215 // For each module of the section.
216 if (empty($filters['excludemodules']) and !empty($modinfosections[$section->section])) {
217 foreach ($modinfosections[$section->section] as $cmid) {
218 $cm = $modinfo->cms[$cmid];
220 // Stop here if the module is not visible to the user on the course main page:
221 // The user can't access the module and the user can't view the module on the course page.
222 if (!$cm->uservisible && !$cm->is_visible_on_course_page()) {
223 continue;
226 // This becomes true when we are filtering and we found the value to filter with.
227 $modfound = false;
229 // Filter by cmid.
230 if (!empty($filters['cmid'])) {
231 if ($cmid != $filters['cmid']) {
232 continue;
233 } else {
234 $modfound = true;
238 // Filter by module name and id.
239 if (!empty($filters['modname'])) {
240 if ($cm->modname != $filters['modname']) {
241 continue;
242 } else if (!empty($filters['modid'])) {
243 if ($cm->instance != $filters['modid']) {
244 continue;
245 } else {
246 // Note that if we are only filtering by modname we don't break the loop.
247 $modfound = true;
252 $module = array();
254 $modcontext = context_module::instance($cm->id);
256 //common info (for people being able to see the module or availability dates)
257 $module['id'] = $cm->id;
258 $module['name'] = external_format_string($cm->name, $modcontext->id);
259 $module['instance'] = $cm->instance;
260 $module['modname'] = $cm->modname;
261 $module['modplural'] = $cm->modplural;
262 $module['modicon'] = $cm->get_icon_url()->out(false);
263 $module['indent'] = $cm->indent;
265 if (!empty($cm->showdescription) or $cm->modname == 'label') {
266 // We want to use the external format. However from reading get_formatted_content(), $cm->content format is always FORMAT_HTML.
267 $options = array('noclean' => true);
268 list($module['description'], $descriptionformat) = external_format_text($cm->content,
269 FORMAT_HTML, $modcontext->id, $cm->modname, 'intro', $cm->id, $options);
272 //url of the module
273 $url = $cm->url;
274 if ($url) { //labels don't have url
275 $module['url'] = $url->out(false);
278 $canviewhidden = has_capability('moodle/course:viewhiddenactivities',
279 context_module::instance($cm->id));
280 //user that can view hidden module should know about the visibility
281 $module['visible'] = $cm->visible;
282 $module['visibleoncoursepage'] = $cm->visibleoncoursepage;
283 $module['uservisible'] = $cm->uservisible;
284 if (!empty($cm->availableinfo)) {
285 $module['availabilityinfo'] = \core_availability\info::format_info($cm->availableinfo, $course);
288 // Availability date (also send to user who can see hidden module).
289 if ($CFG->enableavailability && ($canviewhidden || $canupdatecourse)) {
290 $module['availability'] = $cm->availability;
293 // Return contents only if the user can access to the module.
294 if ($cm->uservisible) {
295 $baseurl = 'webservice/pluginfile.php';
297 // Call $modulename_export_contents (each module callback take care about checking the capabilities).
298 require_once($CFG->dirroot . '/mod/' . $cm->modname . '/lib.php');
299 $getcontentfunction = $cm->modname.'_export_contents';
300 if (function_exists($getcontentfunction)) {
301 if (empty($filters['excludecontents']) and $contents = $getcontentfunction($cm, $baseurl)) {
302 $module['contents'] = $contents;
303 } else {
304 $module['contents'] = array();
309 // Assign result to $sectioncontents, there is an exception,
310 // stealth activities in non-visible sections for students go to a special section.
311 if (!empty($filters['includestealthmodules']) && !$section->uservisible && $cm->is_stealth()) {
312 $stealthmodules[] = $module;
313 } else {
314 $sectioncontents[] = $module;
317 // If we just did a filtering, break the loop.
318 if ($modfound) {
319 break;
324 $sectionvalues['modules'] = $sectioncontents;
326 // assign result to $coursecontents
327 $coursecontents[$key] = $sectionvalues;
329 // Break the loop if we are filtering.
330 if ($sectionfound) {
331 break;
335 // Now that we have iterated over all the sections and activities, check the visibility.
336 // We didn't this before to be able to retrieve stealth activities.
337 foreach ($coursecontents as $sectionnumber => $sectioncontents) {
338 $section = $sections[$sectionnumber];
339 // Show the section if the user is permitted to access it, OR if it's not available
340 // but there is some available info text which explains the reason & should display.
341 $showsection = $section->uservisible ||
342 ($section->visible && !$section->available &&
343 !empty($section->availableinfo));
345 if (!$showsection) {
346 unset($coursecontents[$sectionnumber]);
347 continue;
350 // Remove modules information if the section is not visible for the user.
351 if (!$section->uservisible) {
352 $coursecontents[$sectionnumber]['modules'] = array();
356 // Include stealth modules in special section (without any info).
357 if (!empty($stealthmodules)) {
358 $coursecontents[] = array(
359 'id' => -1,
360 'name' => '',
361 'summary' => '',
362 'summaryformat' => FORMAT_MOODLE,
363 'modules' => $stealthmodules
368 return $coursecontents;
372 * Returns description of method result value
374 * @return external_description
375 * @since Moodle 2.2
377 public static function get_course_contents_returns() {
378 return new external_multiple_structure(
379 new external_single_structure(
380 array(
381 'id' => new external_value(PARAM_INT, 'Section ID'),
382 'name' => new external_value(PARAM_TEXT, 'Section name'),
383 'visible' => new external_value(PARAM_INT, 'is the section visible', VALUE_OPTIONAL),
384 'summary' => new external_value(PARAM_RAW, 'Section description'),
385 'summaryformat' => new external_format_value('summary'),
386 'section' => new external_value(PARAM_INT, 'Section number inside the course', VALUE_OPTIONAL),
387 'hiddenbynumsections' => new external_value(PARAM_INT, 'Whether is a section hidden in the course format',
388 VALUE_OPTIONAL),
389 'uservisible' => new external_value(PARAM_BOOL, 'Is the section visible for the user?', VALUE_OPTIONAL),
390 'availabilityinfo' => new external_value(PARAM_RAW, 'Availability information.', VALUE_OPTIONAL),
391 'modules' => new external_multiple_structure(
392 new external_single_structure(
393 array(
394 'id' => new external_value(PARAM_INT, 'activity id'),
395 'url' => new external_value(PARAM_URL, 'activity url', VALUE_OPTIONAL),
396 'name' => new external_value(PARAM_RAW, 'activity module name'),
397 'instance' => new external_value(PARAM_INT, 'instance id', VALUE_OPTIONAL),
398 'description' => new external_value(PARAM_RAW, 'activity description', VALUE_OPTIONAL),
399 'visible' => new external_value(PARAM_INT, 'is the module visible', VALUE_OPTIONAL),
400 'uservisible' => new external_value(PARAM_BOOL, 'Is the module visible for the user?',
401 VALUE_OPTIONAL),
402 'availabilityinfo' => new external_value(PARAM_RAW, 'Availability information.',
403 VALUE_OPTIONAL),
404 'visibleoncoursepage' => new external_value(PARAM_INT, 'is the module visible on course page',
405 VALUE_OPTIONAL),
406 'modicon' => new external_value(PARAM_URL, 'activity icon url'),
407 'modname' => new external_value(PARAM_PLUGIN, 'activity module type'),
408 'modplural' => new external_value(PARAM_TEXT, 'activity module plural name'),
409 'availability' => new external_value(PARAM_RAW, 'module availability settings', VALUE_OPTIONAL),
410 'indent' => new external_value(PARAM_INT, 'number of identation in the site'),
411 'contents' => new external_multiple_structure(
412 new external_single_structure(
413 array(
414 // content info
415 'type'=> new external_value(PARAM_TEXT, 'a file or a folder or external link'),
416 'filename'=> new external_value(PARAM_FILE, 'filename'),
417 'filepath'=> new external_value(PARAM_PATH, 'filepath'),
418 'filesize'=> new external_value(PARAM_INT, 'filesize'),
419 'fileurl' => new external_value(PARAM_URL, 'downloadable file url', VALUE_OPTIONAL),
420 'content' => new external_value(PARAM_RAW, 'Raw content, will be used when type is content', VALUE_OPTIONAL),
421 'timecreated' => new external_value(PARAM_INT, 'Time created'),
422 'timemodified' => new external_value(PARAM_INT, 'Time modified'),
423 'sortorder' => new external_value(PARAM_INT, 'Content sort order'),
424 'mimetype' => new external_value(PARAM_RAW, 'File mime type.', VALUE_OPTIONAL),
425 'isexternalfile' => new external_value(PARAM_BOOL, 'Whether is an external file.',
426 VALUE_OPTIONAL),
427 'repositorytype' => new external_value(PARAM_PLUGIN, 'The repository type for external files.',
428 VALUE_OPTIONAL),
430 // copyright related info
431 'userid' => new external_value(PARAM_INT, 'User who added this content to moodle'),
432 'author' => new external_value(PARAM_TEXT, 'Content owner'),
433 'license' => new external_value(PARAM_TEXT, 'Content license'),
435 ), VALUE_DEFAULT, array()
438 ), 'list of module'
446 * Returns description of method parameters
448 * @return external_function_parameters
449 * @since Moodle 2.3
451 public static function get_courses_parameters() {
452 return new external_function_parameters(
453 array('options' => new external_single_structure(
454 array('ids' => new external_multiple_structure(
455 new external_value(PARAM_INT, 'Course id')
456 , 'List of course id. If empty return all courses
457 except front page course.',
458 VALUE_OPTIONAL)
459 ), 'options - operator OR is used', VALUE_DEFAULT, array())
465 * Get courses
467 * @param array $options It contains an array (list of ids)
468 * @return array
469 * @since Moodle 2.2
471 public static function get_courses($options = array()) {
472 global $CFG, $DB;
473 require_once($CFG->dirroot . "/course/lib.php");
475 //validate parameter
476 $params = self::validate_parameters(self::get_courses_parameters(),
477 array('options' => $options));
479 //retrieve courses
480 if (!array_key_exists('ids', $params['options'])
481 or empty($params['options']['ids'])) {
482 $courses = $DB->get_records('course');
483 } else {
484 $courses = $DB->get_records_list('course', 'id', $params['options']['ids']);
487 //create return value
488 $coursesinfo = array();
489 foreach ($courses as $course) {
491 // now security checks
492 $context = context_course::instance($course->id, IGNORE_MISSING);
493 $courseformatoptions = course_get_format($course)->get_format_options();
494 try {
495 self::validate_context($context);
496 } catch (Exception $e) {
497 $exceptionparam = new stdClass();
498 $exceptionparam->message = $e->getMessage();
499 $exceptionparam->courseid = $course->id;
500 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
502 if ($course->id != SITEID) {
503 require_capability('moodle/course:view', $context);
506 $courseinfo = array();
507 $courseinfo['id'] = $course->id;
508 $courseinfo['fullname'] = external_format_string($course->fullname, $context->id);
509 $courseinfo['shortname'] = external_format_string($course->shortname, $context->id);
510 $courseinfo['displayname'] = external_format_string(get_course_display_name_for_list($course), $context->id);
511 $courseinfo['categoryid'] = $course->category;
512 list($courseinfo['summary'], $courseinfo['summaryformat']) =
513 external_format_text($course->summary, $course->summaryformat, $context->id, 'course', 'summary', 0);
514 $courseinfo['format'] = $course->format;
515 $courseinfo['startdate'] = $course->startdate;
516 $courseinfo['enddate'] = $course->enddate;
517 if (array_key_exists('numsections', $courseformatoptions)) {
518 // For backward-compartibility
519 $courseinfo['numsections'] = $courseformatoptions['numsections'];
522 //some field should be returned only if the user has update permission
523 $courseadmin = has_capability('moodle/course:update', $context);
524 if ($courseadmin) {
525 $courseinfo['categorysortorder'] = $course->sortorder;
526 $courseinfo['idnumber'] = $course->idnumber;
527 $courseinfo['showgrades'] = $course->showgrades;
528 $courseinfo['showreports'] = $course->showreports;
529 $courseinfo['newsitems'] = $course->newsitems;
530 $courseinfo['visible'] = $course->visible;
531 $courseinfo['maxbytes'] = $course->maxbytes;
532 if (array_key_exists('hiddensections', $courseformatoptions)) {
533 // For backward-compartibility
534 $courseinfo['hiddensections'] = $courseformatoptions['hiddensections'];
536 // Return numsections for backward-compatibility with clients who expect it.
537 $courseinfo['numsections'] = course_get_format($course)->get_last_section_number();
538 $courseinfo['groupmode'] = $course->groupmode;
539 $courseinfo['groupmodeforce'] = $course->groupmodeforce;
540 $courseinfo['defaultgroupingid'] = $course->defaultgroupingid;
541 $courseinfo['lang'] = clean_param($course->lang, PARAM_LANG);
542 $courseinfo['timecreated'] = $course->timecreated;
543 $courseinfo['timemodified'] = $course->timemodified;
544 $courseinfo['forcetheme'] = clean_param($course->theme, PARAM_THEME);
545 $courseinfo['enablecompletion'] = $course->enablecompletion;
546 $courseinfo['completionnotify'] = $course->completionnotify;
547 $courseinfo['courseformatoptions'] = array();
548 foreach ($courseformatoptions as $key => $value) {
549 $courseinfo['courseformatoptions'][] = array(
550 'name' => $key,
551 'value' => $value
556 if ($courseadmin or $course->visible
557 or has_capability('moodle/course:viewhiddencourses', $context)) {
558 $coursesinfo[] = $courseinfo;
562 return $coursesinfo;
566 * Returns description of method result value
568 * @return external_description
569 * @since Moodle 2.2
571 public static function get_courses_returns() {
572 return new external_multiple_structure(
573 new external_single_structure(
574 array(
575 'id' => new external_value(PARAM_INT, 'course id'),
576 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
577 'categoryid' => new external_value(PARAM_INT, 'category id'),
578 'categorysortorder' => new external_value(PARAM_INT,
579 'sort order into the category', VALUE_OPTIONAL),
580 'fullname' => new external_value(PARAM_TEXT, 'full name'),
581 'displayname' => new external_value(PARAM_TEXT, 'course display name'),
582 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
583 'summary' => new external_value(PARAM_RAW, 'summary'),
584 'summaryformat' => new external_format_value('summary'),
585 'format' => new external_value(PARAM_PLUGIN,
586 'course format: weeks, topics, social, site,..'),
587 'showgrades' => new external_value(PARAM_INT,
588 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
589 'newsitems' => new external_value(PARAM_INT,
590 'number of recent items appearing on the course page', VALUE_OPTIONAL),
591 'startdate' => new external_value(PARAM_INT,
592 'timestamp when the course start'),
593 'enddate' => new external_value(PARAM_INT,
594 'timestamp when the course end'),
595 'numsections' => new external_value(PARAM_INT,
596 '(deprecated, use courseformatoptions) number of weeks/topics',
597 VALUE_OPTIONAL),
598 'maxbytes' => new external_value(PARAM_INT,
599 'largest size of file that can be uploaded into the course',
600 VALUE_OPTIONAL),
601 'showreports' => new external_value(PARAM_INT,
602 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
603 'visible' => new external_value(PARAM_INT,
604 '1: available to student, 0:not available', VALUE_OPTIONAL),
605 'hiddensections' => new external_value(PARAM_INT,
606 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
607 VALUE_OPTIONAL),
608 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
609 VALUE_OPTIONAL),
610 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
611 VALUE_OPTIONAL),
612 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
613 VALUE_OPTIONAL),
614 'timecreated' => new external_value(PARAM_INT,
615 'timestamp when the course have been created', VALUE_OPTIONAL),
616 'timemodified' => new external_value(PARAM_INT,
617 'timestamp when the course have been modified', VALUE_OPTIONAL),
618 'enablecompletion' => new external_value(PARAM_INT,
619 'Enabled, control via completion and activity settings. Disbaled,
620 not shown in activity settings.',
621 VALUE_OPTIONAL),
622 'completionnotify' => new external_value(PARAM_INT,
623 '1: yes 0: no', VALUE_OPTIONAL),
624 'lang' => new external_value(PARAM_SAFEDIR,
625 'forced course language', VALUE_OPTIONAL),
626 'forcetheme' => new external_value(PARAM_PLUGIN,
627 'name of the force theme', VALUE_OPTIONAL),
628 'courseformatoptions' => new external_multiple_structure(
629 new external_single_structure(
630 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
631 'value' => new external_value(PARAM_RAW, 'course format option value')
633 'additional options for particular course format', VALUE_OPTIONAL
635 ), 'course'
641 * Returns description of method parameters
643 * @return external_function_parameters
644 * @since Moodle 2.2
646 public static function create_courses_parameters() {
647 $courseconfig = get_config('moodlecourse'); //needed for many default values
648 return new external_function_parameters(
649 array(
650 'courses' => new external_multiple_structure(
651 new external_single_structure(
652 array(
653 'fullname' => new external_value(PARAM_TEXT, 'full name'),
654 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
655 'categoryid' => new external_value(PARAM_INT, 'category id'),
656 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
657 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
658 'summaryformat' => new external_format_value('summary', VALUE_DEFAULT),
659 'format' => new external_value(PARAM_PLUGIN,
660 'course format: weeks, topics, social, site,..',
661 VALUE_DEFAULT, $courseconfig->format),
662 'showgrades' => new external_value(PARAM_INT,
663 '1 if grades are shown, otherwise 0', VALUE_DEFAULT,
664 $courseconfig->showgrades),
665 'newsitems' => new external_value(PARAM_INT,
666 'number of recent items appearing on the course page',
667 VALUE_DEFAULT, $courseconfig->newsitems),
668 'startdate' => new external_value(PARAM_INT,
669 'timestamp when the course start', VALUE_OPTIONAL),
670 'enddate' => new external_value(PARAM_INT,
671 'timestamp when the course end', VALUE_OPTIONAL),
672 'numsections' => new external_value(PARAM_INT,
673 '(deprecated, use courseformatoptions) number of weeks/topics',
674 VALUE_OPTIONAL),
675 'maxbytes' => new external_value(PARAM_INT,
676 'largest size of file that can be uploaded into the course',
677 VALUE_DEFAULT, $courseconfig->maxbytes),
678 'showreports' => new external_value(PARAM_INT,
679 'are activity report shown (yes = 1, no =0)', VALUE_DEFAULT,
680 $courseconfig->showreports),
681 'visible' => new external_value(PARAM_INT,
682 '1: available to student, 0:not available', VALUE_OPTIONAL),
683 'hiddensections' => new external_value(PARAM_INT,
684 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
685 VALUE_OPTIONAL),
686 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
687 VALUE_DEFAULT, $courseconfig->groupmode),
688 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
689 VALUE_DEFAULT, $courseconfig->groupmodeforce),
690 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
691 VALUE_DEFAULT, 0),
692 'enablecompletion' => new external_value(PARAM_INT,
693 'Enabled, control via completion and activity settings. Disabled,
694 not shown in activity settings.',
695 VALUE_OPTIONAL),
696 'completionnotify' => new external_value(PARAM_INT,
697 '1: yes 0: no', VALUE_OPTIONAL),
698 'lang' => new external_value(PARAM_SAFEDIR,
699 'forced course language', VALUE_OPTIONAL),
700 'forcetheme' => new external_value(PARAM_PLUGIN,
701 'name of the force theme', VALUE_OPTIONAL),
702 'courseformatoptions' => new external_multiple_structure(
703 new external_single_structure(
704 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
705 'value' => new external_value(PARAM_RAW, 'course format option value')
707 'additional options for particular course format', VALUE_OPTIONAL),
709 ), 'courses to create'
716 * Create courses
718 * @param array $courses
719 * @return array courses (id and shortname only)
720 * @since Moodle 2.2
722 public static function create_courses($courses) {
723 global $CFG, $DB;
724 require_once($CFG->dirroot . "/course/lib.php");
725 require_once($CFG->libdir . '/completionlib.php');
727 $params = self::validate_parameters(self::create_courses_parameters(),
728 array('courses' => $courses));
730 $availablethemes = core_component::get_plugin_list('theme');
731 $availablelangs = get_string_manager()->get_list_of_translations();
733 $transaction = $DB->start_delegated_transaction();
735 foreach ($params['courses'] as $course) {
737 // Ensure the current user is allowed to run this function
738 $context = context_coursecat::instance($course['categoryid'], IGNORE_MISSING);
739 try {
740 self::validate_context($context);
741 } catch (Exception $e) {
742 $exceptionparam = new stdClass();
743 $exceptionparam->message = $e->getMessage();
744 $exceptionparam->catid = $course['categoryid'];
745 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
747 require_capability('moodle/course:create', $context);
749 // Make sure lang is valid
750 if (array_key_exists('lang', $course)) {
751 if (empty($availablelangs[$course['lang']])) {
752 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
754 if (!has_capability('moodle/course:setforcedlanguage', $context)) {
755 unset($course['lang']);
759 // Make sure theme is valid
760 if (array_key_exists('forcetheme', $course)) {
761 if (!empty($CFG->allowcoursethemes)) {
762 if (empty($availablethemes[$course['forcetheme']])) {
763 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
764 } else {
765 $course['theme'] = $course['forcetheme'];
770 //force visibility if ws user doesn't have the permission to set it
771 $category = $DB->get_record('course_categories', array('id' => $course['categoryid']));
772 if (!has_capability('moodle/course:visibility', $context)) {
773 $course['visible'] = $category->visible;
776 //set default value for completion
777 $courseconfig = get_config('moodlecourse');
778 if (completion_info::is_enabled_for_site()) {
779 if (!array_key_exists('enablecompletion', $course)) {
780 $course['enablecompletion'] = $courseconfig->enablecompletion;
782 } else {
783 $course['enablecompletion'] = 0;
786 $course['category'] = $course['categoryid'];
788 // Summary format.
789 $course['summaryformat'] = external_validate_format($course['summaryformat']);
791 if (!empty($course['courseformatoptions'])) {
792 foreach ($course['courseformatoptions'] as $option) {
793 $course[$option['name']] = $option['value'];
797 //Note: create_course() core function check shortname, idnumber, category
798 $course['id'] = create_course((object) $course)->id;
800 $resultcourses[] = array('id' => $course['id'], 'shortname' => $course['shortname']);
803 $transaction->allow_commit();
805 return $resultcourses;
809 * Returns description of method result value
811 * @return external_description
812 * @since Moodle 2.2
814 public static function create_courses_returns() {
815 return new external_multiple_structure(
816 new external_single_structure(
817 array(
818 'id' => new external_value(PARAM_INT, 'course id'),
819 'shortname' => new external_value(PARAM_TEXT, 'short name'),
826 * Update courses
828 * @return external_function_parameters
829 * @since Moodle 2.5
831 public static function update_courses_parameters() {
832 return new external_function_parameters(
833 array(
834 'courses' => new external_multiple_structure(
835 new external_single_structure(
836 array(
837 'id' => new external_value(PARAM_INT, 'ID of the course'),
838 'fullname' => new external_value(PARAM_TEXT, 'full name', VALUE_OPTIONAL),
839 'shortname' => new external_value(PARAM_TEXT, 'course short name', VALUE_OPTIONAL),
840 'categoryid' => new external_value(PARAM_INT, 'category id', VALUE_OPTIONAL),
841 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
842 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
843 'summaryformat' => new external_format_value('summary', VALUE_OPTIONAL),
844 'format' => new external_value(PARAM_PLUGIN,
845 'course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
846 'showgrades' => new external_value(PARAM_INT,
847 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
848 'newsitems' => new external_value(PARAM_INT,
849 'number of recent items appearing on the course page', VALUE_OPTIONAL),
850 'startdate' => new external_value(PARAM_INT,
851 'timestamp when the course start', VALUE_OPTIONAL),
852 'enddate' => new external_value(PARAM_INT,
853 'timestamp when the course end', VALUE_OPTIONAL),
854 'numsections' => new external_value(PARAM_INT,
855 '(deprecated, use courseformatoptions) number of weeks/topics', VALUE_OPTIONAL),
856 'maxbytes' => new external_value(PARAM_INT,
857 'largest size of file that can be uploaded into the course', VALUE_OPTIONAL),
858 'showreports' => new external_value(PARAM_INT,
859 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
860 'visible' => new external_value(PARAM_INT,
861 '1: available to student, 0:not available', VALUE_OPTIONAL),
862 'hiddensections' => new external_value(PARAM_INT,
863 '(deprecated, use courseformatoptions) How the hidden sections in the course are
864 displayed to students', VALUE_OPTIONAL),
865 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
866 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
867 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
868 'enablecompletion' => new external_value(PARAM_INT,
869 'Enabled, control via completion and activity settings. Disabled,
870 not shown in activity settings.', VALUE_OPTIONAL),
871 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
872 'lang' => new external_value(PARAM_SAFEDIR, 'forced course language', VALUE_OPTIONAL),
873 'forcetheme' => new external_value(PARAM_PLUGIN, 'name of the force theme', VALUE_OPTIONAL),
874 'courseformatoptions' => new external_multiple_structure(
875 new external_single_structure(
876 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
877 'value' => new external_value(PARAM_RAW, 'course format option value')
879 'additional options for particular course format', VALUE_OPTIONAL),
881 ), 'courses to update'
888 * Update courses
890 * @param array $courses
891 * @since Moodle 2.5
893 public static function update_courses($courses) {
894 global $CFG, $DB;
895 require_once($CFG->dirroot . "/course/lib.php");
896 $warnings = array();
898 $params = self::validate_parameters(self::update_courses_parameters(),
899 array('courses' => $courses));
901 $availablethemes = core_component::get_plugin_list('theme');
902 $availablelangs = get_string_manager()->get_list_of_translations();
904 foreach ($params['courses'] as $course) {
905 // Catch any exception while updating course and return as warning to user.
906 try {
907 // Ensure the current user is allowed to run this function.
908 $context = context_course::instance($course['id'], MUST_EXIST);
909 self::validate_context($context);
911 $oldcourse = course_get_format($course['id'])->get_course();
913 require_capability('moodle/course:update', $context);
915 // Check if user can change category.
916 if (array_key_exists('categoryid', $course) && ($oldcourse->category != $course['categoryid'])) {
917 require_capability('moodle/course:changecategory', $context);
918 $course['category'] = $course['categoryid'];
921 // Check if the user can change fullname.
922 if (array_key_exists('fullname', $course) && ($oldcourse->fullname != $course['fullname'])) {
923 require_capability('moodle/course:changefullname', $context);
926 // Check if the user can change shortname.
927 if (array_key_exists('shortname', $course) && ($oldcourse->shortname != $course['shortname'])) {
928 require_capability('moodle/course:changeshortname', $context);
931 // Check if the user can change the idnumber.
932 if (array_key_exists('idnumber', $course) && ($oldcourse->idnumber != $course['idnumber'])) {
933 require_capability('moodle/course:changeidnumber', $context);
936 // Check if user can change summary.
937 if (array_key_exists('summary', $course) && ($oldcourse->summary != $course['summary'])) {
938 require_capability('moodle/course:changesummary', $context);
941 // Summary format.
942 if (array_key_exists('summaryformat', $course) && ($oldcourse->summaryformat != $course['summaryformat'])) {
943 require_capability('moodle/course:changesummary', $context);
944 $course['summaryformat'] = external_validate_format($course['summaryformat']);
947 // Check if user can change visibility.
948 if (array_key_exists('visible', $course) && ($oldcourse->visible != $course['visible'])) {
949 require_capability('moodle/course:visibility', $context);
952 // Make sure lang is valid.
953 if (array_key_exists('lang', $course) && ($oldcourse->lang != $course['lang'])) {
954 require_capability('moodle/course:setforcedlanguage', $context);
955 if (empty($availablelangs[$course['lang']])) {
956 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
960 // Make sure theme is valid.
961 if (array_key_exists('forcetheme', $course)) {
962 if (!empty($CFG->allowcoursethemes)) {
963 if (empty($availablethemes[$course['forcetheme']])) {
964 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
965 } else {
966 $course['theme'] = $course['forcetheme'];
971 // Make sure completion is enabled before setting it.
972 if (array_key_exists('enabledcompletion', $course) && !completion_info::is_enabled_for_site()) {
973 $course['enabledcompletion'] = 0;
976 // Make sure maxbytes are less then CFG->maxbytes.
977 if (array_key_exists('maxbytes', $course)) {
978 // We allow updates back to 0 max bytes, a special value denoting the course uses the site limit.
979 // Otherwise, either use the size specified, or cap at the max size for the course.
980 if ($course['maxbytes'] != 0) {
981 $course['maxbytes'] = get_max_upload_file_size($CFG->maxbytes, $course['maxbytes']);
985 if (!empty($course['courseformatoptions'])) {
986 foreach ($course['courseformatoptions'] as $option) {
987 if (isset($option['name']) && isset($option['value'])) {
988 $course[$option['name']] = $option['value'];
993 // Update course if user has all required capabilities.
994 update_course((object) $course);
995 } catch (Exception $e) {
996 $warning = array();
997 $warning['item'] = 'course';
998 $warning['itemid'] = $course['id'];
999 if ($e instanceof moodle_exception) {
1000 $warning['warningcode'] = $e->errorcode;
1001 } else {
1002 $warning['warningcode'] = $e->getCode();
1004 $warning['message'] = $e->getMessage();
1005 $warnings[] = $warning;
1009 $result = array();
1010 $result['warnings'] = $warnings;
1011 return $result;
1015 * Returns description of method result value
1017 * @return external_description
1018 * @since Moodle 2.5
1020 public static function update_courses_returns() {
1021 return new external_single_structure(
1022 array(
1023 'warnings' => new external_warnings()
1029 * Returns description of method parameters
1031 * @return external_function_parameters
1032 * @since Moodle 2.2
1034 public static function delete_courses_parameters() {
1035 return new external_function_parameters(
1036 array(
1037 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'course ID')),
1043 * Delete courses
1045 * @param array $courseids A list of course ids
1046 * @since Moodle 2.2
1048 public static function delete_courses($courseids) {
1049 global $CFG, $DB;
1050 require_once($CFG->dirroot."/course/lib.php");
1052 // Parameter validation.
1053 $params = self::validate_parameters(self::delete_courses_parameters(), array('courseids'=>$courseids));
1055 $warnings = array();
1057 foreach ($params['courseids'] as $courseid) {
1058 $course = $DB->get_record('course', array('id' => $courseid));
1060 if ($course === false) {
1061 $warnings[] = array(
1062 'item' => 'course',
1063 'itemid' => $courseid,
1064 'warningcode' => 'unknowncourseidnumber',
1065 'message' => 'Unknown course ID ' . $courseid
1067 continue;
1070 // Check if the context is valid.
1071 $coursecontext = context_course::instance($course->id);
1072 self::validate_context($coursecontext);
1074 // Check if the current user has permission.
1075 if (!can_delete_course($courseid)) {
1076 $warnings[] = array(
1077 'item' => 'course',
1078 'itemid' => $courseid,
1079 'warningcode' => 'cannotdeletecourse',
1080 'message' => 'You do not have the permission to delete this course' . $courseid
1082 continue;
1085 if (delete_course($course, false) === false) {
1086 $warnings[] = array(
1087 'item' => 'course',
1088 'itemid' => $courseid,
1089 'warningcode' => 'cannotdeletecategorycourse',
1090 'message' => 'Course ' . $courseid . ' failed to be deleted'
1092 continue;
1096 fix_course_sortorder();
1098 return array('warnings' => $warnings);
1102 * Returns description of method result value
1104 * @return external_description
1105 * @since Moodle 2.2
1107 public static function delete_courses_returns() {
1108 return new external_single_structure(
1109 array(
1110 'warnings' => new external_warnings()
1116 * Returns description of method parameters
1118 * @return external_function_parameters
1119 * @since Moodle 2.3
1121 public static function duplicate_course_parameters() {
1122 return new external_function_parameters(
1123 array(
1124 'courseid' => new external_value(PARAM_INT, 'course to duplicate id'),
1125 'fullname' => new external_value(PARAM_TEXT, 'duplicated course full name'),
1126 'shortname' => new external_value(PARAM_TEXT, 'duplicated course short name'),
1127 'categoryid' => new external_value(PARAM_INT, 'duplicated course category parent'),
1128 'visible' => new external_value(PARAM_INT, 'duplicated course visible, default to yes', VALUE_DEFAULT, 1),
1129 'options' => new external_multiple_structure(
1130 new external_single_structure(
1131 array(
1132 'name' => new external_value(PARAM_ALPHAEXT, 'The backup option name:
1133 "activities" (int) Include course activites (default to 1 that is equal to yes),
1134 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1135 "filters" (int) Include course filters (default to 1 that is equal to yes),
1136 "users" (int) Include users (default to 0 that is equal to no),
1137 "enrolments" (int) Include enrolment methods (default to 1 - restore only with users),
1138 "role_assignments" (int) Include role assignments (default to 0 that is equal to no),
1139 "comments" (int) Include user comments (default to 0 that is equal to no),
1140 "userscompletion" (int) Include user course completion information (default to 0 that is equal to no),
1141 "logs" (int) Include course logs (default to 0 that is equal to no),
1142 "grade_histories" (int) Include histories (default to 0 that is equal to no)'
1144 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1147 ), VALUE_DEFAULT, array()
1154 * Duplicate a course
1156 * @param int $courseid
1157 * @param string $fullname Duplicated course fullname
1158 * @param string $shortname Duplicated course shortname
1159 * @param int $categoryid Duplicated course parent category id
1160 * @param int $visible Duplicated course availability
1161 * @param array $options List of backup options
1162 * @return array New course info
1163 * @since Moodle 2.3
1165 public static function duplicate_course($courseid, $fullname, $shortname, $categoryid, $visible = 1, $options = array()) {
1166 global $CFG, $USER, $DB;
1167 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1168 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1170 // Parameter validation.
1171 $params = self::validate_parameters(
1172 self::duplicate_course_parameters(),
1173 array(
1174 'courseid' => $courseid,
1175 'fullname' => $fullname,
1176 'shortname' => $shortname,
1177 'categoryid' => $categoryid,
1178 'visible' => $visible,
1179 'options' => $options
1183 // Context validation.
1185 if (! ($course = $DB->get_record('course', array('id'=>$params['courseid'])))) {
1186 throw new moodle_exception('invalidcourseid', 'error');
1189 // Category where duplicated course is going to be created.
1190 $categorycontext = context_coursecat::instance($params['categoryid']);
1191 self::validate_context($categorycontext);
1193 // Course to be duplicated.
1194 $coursecontext = context_course::instance($course->id);
1195 self::validate_context($coursecontext);
1197 $backupdefaults = array(
1198 'activities' => 1,
1199 'blocks' => 1,
1200 'filters' => 1,
1201 'users' => 0,
1202 'enrolments' => backup::ENROL_WITHUSERS,
1203 'role_assignments' => 0,
1204 'comments' => 0,
1205 'userscompletion' => 0,
1206 'logs' => 0,
1207 'grade_histories' => 0
1210 $backupsettings = array();
1211 // Check for backup and restore options.
1212 if (!empty($params['options'])) {
1213 foreach ($params['options'] as $option) {
1215 // Strict check for a correct value (allways 1 or 0, true or false).
1216 $value = clean_param($option['value'], PARAM_INT);
1218 if ($value !== 0 and $value !== 1) {
1219 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1222 if (!isset($backupdefaults[$option['name']])) {
1223 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1226 $backupsettings[$option['name']] = $value;
1230 // Capability checking.
1232 // The backup controller check for this currently, this may be redundant.
1233 require_capability('moodle/course:create', $categorycontext);
1234 require_capability('moodle/restore:restorecourse', $categorycontext);
1235 require_capability('moodle/backup:backupcourse', $coursecontext);
1237 if (!empty($backupsettings['users'])) {
1238 require_capability('moodle/backup:userinfo', $coursecontext);
1239 require_capability('moodle/restore:userinfo', $categorycontext);
1242 // Check if the shortname is used.
1243 if ($foundcourses = $DB->get_records('course', array('shortname'=>$shortname))) {
1244 foreach ($foundcourses as $foundcourse) {
1245 $foundcoursenames[] = $foundcourse->fullname;
1248 $foundcoursenamestring = implode(',', $foundcoursenames);
1249 throw new moodle_exception('shortnametaken', '', '', $foundcoursenamestring);
1252 // Backup the course.
1254 $bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE,
1255 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id);
1257 foreach ($backupsettings as $name => $value) {
1258 if ($setting = $bc->get_plan()->get_setting($name)) {
1259 $bc->get_plan()->get_setting($name)->set_value($value);
1263 $backupid = $bc->get_backupid();
1264 $backupbasepath = $bc->get_plan()->get_basepath();
1266 $bc->execute_plan();
1267 $results = $bc->get_results();
1268 $file = $results['backup_destination'];
1270 $bc->destroy();
1272 // Restore the backup immediately.
1274 // Check if we need to unzip the file because the backup temp dir does not contains backup files.
1275 if (!file_exists($backupbasepath . "/moodle_backup.xml")) {
1276 $file->extract_to_pathname(get_file_packer('application/vnd.moodle.backup'), $backupbasepath);
1279 // Create new course.
1280 $newcourseid = restore_dbops::create_new_course($params['fullname'], $params['shortname'], $params['categoryid']);
1282 $rc = new restore_controller($backupid, $newcourseid,
1283 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id, backup::TARGET_NEW_COURSE);
1285 foreach ($backupsettings as $name => $value) {
1286 $setting = $rc->get_plan()->get_setting($name);
1287 if ($setting->get_status() == backup_setting::NOT_LOCKED) {
1288 $setting->set_value($value);
1292 if (!$rc->execute_precheck()) {
1293 $precheckresults = $rc->get_precheck_results();
1294 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1295 if (empty($CFG->keeptempdirectoriesonbackup)) {
1296 fulldelete($backupbasepath);
1299 $errorinfo = '';
1301 foreach ($precheckresults['errors'] as $error) {
1302 $errorinfo .= $error;
1305 if (array_key_exists('warnings', $precheckresults)) {
1306 foreach ($precheckresults['warnings'] as $warning) {
1307 $errorinfo .= $warning;
1311 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1315 $rc->execute_plan();
1316 $rc->destroy();
1318 $course = $DB->get_record('course', array('id' => $newcourseid), '*', MUST_EXIST);
1319 $course->fullname = $params['fullname'];
1320 $course->shortname = $params['shortname'];
1321 $course->visible = $params['visible'];
1323 // Set shortname and fullname back.
1324 $DB->update_record('course', $course);
1326 if (empty($CFG->keeptempdirectoriesonbackup)) {
1327 fulldelete($backupbasepath);
1330 // Delete the course backup file created by this WebService. Originally located in the course backups area.
1331 $file->delete();
1333 return array('id' => $course->id, 'shortname' => $course->shortname);
1337 * Returns description of method result value
1339 * @return external_description
1340 * @since Moodle 2.3
1342 public static function duplicate_course_returns() {
1343 return new external_single_structure(
1344 array(
1345 'id' => new external_value(PARAM_INT, 'course id'),
1346 'shortname' => new external_value(PARAM_TEXT, 'short name'),
1352 * Returns description of method parameters for import_course
1354 * @return external_function_parameters
1355 * @since Moodle 2.4
1357 public static function import_course_parameters() {
1358 return new external_function_parameters(
1359 array(
1360 'importfrom' => new external_value(PARAM_INT, 'the id of the course we are importing from'),
1361 'importto' => new external_value(PARAM_INT, 'the id of the course we are importing to'),
1362 'deletecontent' => new external_value(PARAM_INT, 'whether to delete the course content where we are importing to (default to 0 = No)', VALUE_DEFAULT, 0),
1363 'options' => new external_multiple_structure(
1364 new external_single_structure(
1365 array(
1366 'name' => new external_value(PARAM_ALPHA, 'The backup option name:
1367 "activities" (int) Include course activites (default to 1 that is equal to yes),
1368 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1369 "filters" (int) Include course filters (default to 1 that is equal to yes)'
1371 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1374 ), VALUE_DEFAULT, array()
1381 * Imports a course
1383 * @param int $importfrom The id of the course we are importing from
1384 * @param int $importto The id of the course we are importing to
1385 * @param bool $deletecontent Whether to delete the course we are importing to content
1386 * @param array $options List of backup options
1387 * @return null
1388 * @since Moodle 2.4
1390 public static function import_course($importfrom, $importto, $deletecontent = 0, $options = array()) {
1391 global $CFG, $USER, $DB;
1392 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1393 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1395 // Parameter validation.
1396 $params = self::validate_parameters(
1397 self::import_course_parameters(),
1398 array(
1399 'importfrom' => $importfrom,
1400 'importto' => $importto,
1401 'deletecontent' => $deletecontent,
1402 'options' => $options
1406 if ($params['deletecontent'] !== 0 and $params['deletecontent'] !== 1) {
1407 throw new moodle_exception('invalidextparam', 'webservice', '', $params['deletecontent']);
1410 // Context validation.
1412 if (! ($importfrom = $DB->get_record('course', array('id'=>$params['importfrom'])))) {
1413 throw new moodle_exception('invalidcourseid', 'error');
1416 if (! ($importto = $DB->get_record('course', array('id'=>$params['importto'])))) {
1417 throw new moodle_exception('invalidcourseid', 'error');
1420 $importfromcontext = context_course::instance($importfrom->id);
1421 self::validate_context($importfromcontext);
1423 $importtocontext = context_course::instance($importto->id);
1424 self::validate_context($importtocontext);
1426 $backupdefaults = array(
1427 'activities' => 1,
1428 'blocks' => 1,
1429 'filters' => 1
1432 $backupsettings = array();
1434 // Check for backup and restore options.
1435 if (!empty($params['options'])) {
1436 foreach ($params['options'] as $option) {
1438 // Strict check for a correct value (allways 1 or 0, true or false).
1439 $value = clean_param($option['value'], PARAM_INT);
1441 if ($value !== 0 and $value !== 1) {
1442 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1445 if (!isset($backupdefaults[$option['name']])) {
1446 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1449 $backupsettings[$option['name']] = $value;
1453 // Capability checking.
1455 require_capability('moodle/backup:backuptargetimport', $importfromcontext);
1456 require_capability('moodle/restore:restoretargetimport', $importtocontext);
1458 $bc = new backup_controller(backup::TYPE_1COURSE, $importfrom->id, backup::FORMAT_MOODLE,
1459 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
1461 foreach ($backupsettings as $name => $value) {
1462 $bc->get_plan()->get_setting($name)->set_value($value);
1465 $backupid = $bc->get_backupid();
1466 $backupbasepath = $bc->get_plan()->get_basepath();
1468 $bc->execute_plan();
1469 $bc->destroy();
1471 // Restore the backup immediately.
1473 // Check if we must delete the contents of the destination course.
1474 if ($params['deletecontent']) {
1475 $restoretarget = backup::TARGET_EXISTING_DELETING;
1476 } else {
1477 $restoretarget = backup::TARGET_EXISTING_ADDING;
1480 $rc = new restore_controller($backupid, $importto->id,
1481 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, $restoretarget);
1483 foreach ($backupsettings as $name => $value) {
1484 $rc->get_plan()->get_setting($name)->set_value($value);
1487 if (!$rc->execute_precheck()) {
1488 $precheckresults = $rc->get_precheck_results();
1489 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1490 if (empty($CFG->keeptempdirectoriesonbackup)) {
1491 fulldelete($backupbasepath);
1494 $errorinfo = '';
1496 foreach ($precheckresults['errors'] as $error) {
1497 $errorinfo .= $error;
1500 if (array_key_exists('warnings', $precheckresults)) {
1501 foreach ($precheckresults['warnings'] as $warning) {
1502 $errorinfo .= $warning;
1506 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1508 } else {
1509 if ($restoretarget == backup::TARGET_EXISTING_DELETING) {
1510 restore_dbops::delete_course_content($importto->id);
1514 $rc->execute_plan();
1515 $rc->destroy();
1517 if (empty($CFG->keeptempdirectoriesonbackup)) {
1518 fulldelete($backupbasepath);
1521 return null;
1525 * Returns description of method result value
1527 * @return external_description
1528 * @since Moodle 2.4
1530 public static function import_course_returns() {
1531 return null;
1535 * Returns description of method parameters
1537 * @return external_function_parameters
1538 * @since Moodle 2.3
1540 public static function get_categories_parameters() {
1541 return new external_function_parameters(
1542 array(
1543 'criteria' => new external_multiple_structure(
1544 new external_single_structure(
1545 array(
1546 'key' => new external_value(PARAM_ALPHA,
1547 'The category column to search, expected keys (value format) are:'.
1548 '"id" (int) the category id,'.
1549 '"ids" (string) category ids separated by commas,'.
1550 '"name" (string) the category name,'.
1551 '"parent" (int) the parent category id,'.
1552 '"idnumber" (string) category idnumber'.
1553 ' - user must have \'moodle/category:manage\' to search on idnumber,'.
1554 '"visible" (int) whether the returned categories must be visible or hidden. If the key is not passed,
1555 then the function return all categories that the user can see.'.
1556 ' - user must have \'moodle/category:manage\' or \'moodle/category:viewhiddencategories\' to search on visible,'.
1557 '"theme" (string) only return the categories having this theme'.
1558 ' - user must have \'moodle/category:manage\' to search on theme'),
1559 'value' => new external_value(PARAM_RAW, 'the value to match')
1561 ), 'criteria', VALUE_DEFAULT, array()
1563 'addsubcategories' => new external_value(PARAM_BOOL, 'return the sub categories infos
1564 (1 - default) otherwise only the category info (0)', VALUE_DEFAULT, 1)
1570 * Get categories
1572 * @param array $criteria Criteria to match the results
1573 * @param booln $addsubcategories obtain only the category (false) or its subcategories (true - default)
1574 * @return array list of categories
1575 * @since Moodle 2.3
1577 public static function get_categories($criteria = array(), $addsubcategories = true) {
1578 global $CFG, $DB;
1579 require_once($CFG->dirroot . "/course/lib.php");
1581 // Validate parameters.
1582 $params = self::validate_parameters(self::get_categories_parameters(),
1583 array('criteria' => $criteria, 'addsubcategories' => $addsubcategories));
1585 // Retrieve the categories.
1586 $categories = array();
1587 if (!empty($params['criteria'])) {
1589 $conditions = array();
1590 $wheres = array();
1591 foreach ($params['criteria'] as $crit) {
1592 $key = trim($crit['key']);
1594 // Trying to avoid duplicate keys.
1595 if (!isset($conditions[$key])) {
1597 $context = context_system::instance();
1598 $value = null;
1599 switch ($key) {
1600 case 'id':
1601 $value = clean_param($crit['value'], PARAM_INT);
1602 $conditions[$key] = $value;
1603 $wheres[] = $key . " = :" . $key;
1604 break;
1606 case 'ids':
1607 $value = clean_param($crit['value'], PARAM_SEQUENCE);
1608 $ids = explode(',', $value);
1609 list($sqlids, $paramids) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED);
1610 $conditions = array_merge($conditions, $paramids);
1611 $wheres[] = 'id ' . $sqlids;
1612 break;
1614 case 'idnumber':
1615 if (has_capability('moodle/category:manage', $context)) {
1616 $value = clean_param($crit['value'], PARAM_RAW);
1617 $conditions[$key] = $value;
1618 $wheres[] = $key . " = :" . $key;
1619 } else {
1620 // We must throw an exception.
1621 // Otherwise the dev client would think no idnumber exists.
1622 throw new moodle_exception('criteriaerror',
1623 'webservice', '', null,
1624 'You don\'t have the permissions to search on the "idnumber" field.');
1626 break;
1628 case 'name':
1629 $value = clean_param($crit['value'], PARAM_TEXT);
1630 $conditions[$key] = $value;
1631 $wheres[] = $key . " = :" . $key;
1632 break;
1634 case 'parent':
1635 $value = clean_param($crit['value'], PARAM_INT);
1636 $conditions[$key] = $value;
1637 $wheres[] = $key . " = :" . $key;
1638 break;
1640 case 'visible':
1641 if (has_capability('moodle/category:viewhiddencategories', $context)) {
1642 $value = clean_param($crit['value'], PARAM_INT);
1643 $conditions[$key] = $value;
1644 $wheres[] = $key . " = :" . $key;
1645 } else {
1646 throw new moodle_exception('criteriaerror',
1647 'webservice', '', null,
1648 'You don\'t have the permissions to search on the "visible" field.');
1650 break;
1652 case 'theme':
1653 if (has_capability('moodle/category:manage', $context)) {
1654 $value = clean_param($crit['value'], PARAM_THEME);
1655 $conditions[$key] = $value;
1656 $wheres[] = $key . " = :" . $key;
1657 } else {
1658 throw new moodle_exception('criteriaerror',
1659 'webservice', '', null,
1660 'You don\'t have the permissions to search on the "theme" field.');
1662 break;
1664 default:
1665 throw new moodle_exception('criteriaerror',
1666 'webservice', '', null,
1667 'You can not search on this criteria: ' . $key);
1672 if (!empty($wheres)) {
1673 $wheres = implode(" AND ", $wheres);
1675 $categories = $DB->get_records_select('course_categories', $wheres, $conditions);
1677 // Retrieve its sub subcategories (all levels).
1678 if ($categories and !empty($params['addsubcategories'])) {
1679 $newcategories = array();
1681 // Check if we required visible/theme checks.
1682 $additionalselect = '';
1683 $additionalparams = array();
1684 if (isset($conditions['visible'])) {
1685 $additionalselect .= ' AND visible = :visible';
1686 $additionalparams['visible'] = $conditions['visible'];
1688 if (isset($conditions['theme'])) {
1689 $additionalselect .= ' AND theme= :theme';
1690 $additionalparams['theme'] = $conditions['theme'];
1693 foreach ($categories as $category) {
1694 $sqlselect = $DB->sql_like('path', ':path') . $additionalselect;
1695 $sqlparams = array('path' => $category->path.'/%') + $additionalparams; // It will NOT include the specified category.
1696 $subcategories = $DB->get_records_select('course_categories', $sqlselect, $sqlparams);
1697 $newcategories = $newcategories + $subcategories; // Both arrays have integer as keys.
1699 $categories = $categories + $newcategories;
1703 } else {
1704 // Retrieve all categories in the database.
1705 $categories = $DB->get_records('course_categories');
1708 // The not returned categories. key => category id, value => reason of exclusion.
1709 $excludedcats = array();
1711 // The returned categories.
1712 $categoriesinfo = array();
1714 // We need to sort the categories by path.
1715 // The parent cats need to be checked by the algo first.
1716 usort($categories, "core_course_external::compare_categories_by_path");
1718 foreach ($categories as $category) {
1720 // Check if the category is a child of an excluded category, if yes exclude it too (excluded => do not return).
1721 $parents = explode('/', $category->path);
1722 unset($parents[0]); // First key is always empty because path start with / => /1/2/4.
1723 foreach ($parents as $parentid) {
1724 // Note: when the parent exclusion was due to the context,
1725 // the sub category could still be returned.
1726 if (isset($excludedcats[$parentid]) and $excludedcats[$parentid] != 'context') {
1727 $excludedcats[$category->id] = 'parent';
1731 // Check the user can use the category context.
1732 $context = context_coursecat::instance($category->id);
1733 try {
1734 self::validate_context($context);
1735 } catch (Exception $e) {
1736 $excludedcats[$category->id] = 'context';
1738 // If it was the requested category then throw an exception.
1739 if (isset($params['categoryid']) && $category->id == $params['categoryid']) {
1740 $exceptionparam = new stdClass();
1741 $exceptionparam->message = $e->getMessage();
1742 $exceptionparam->catid = $category->id;
1743 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
1747 // Return the category information.
1748 if (!isset($excludedcats[$category->id])) {
1750 // Final check to see if the category is visible to the user.
1751 if ($category->visible or has_capability('moodle/category:viewhiddencategories', $context)) {
1753 $categoryinfo = array();
1754 $categoryinfo['id'] = $category->id;
1755 $categoryinfo['name'] = external_format_string($category->name, $context);
1756 list($categoryinfo['description'], $categoryinfo['descriptionformat']) =
1757 external_format_text($category->description, $category->descriptionformat,
1758 $context->id, 'coursecat', 'description', null);
1759 $categoryinfo['parent'] = $category->parent;
1760 $categoryinfo['sortorder'] = $category->sortorder;
1761 $categoryinfo['coursecount'] = $category->coursecount;
1762 $categoryinfo['depth'] = $category->depth;
1763 $categoryinfo['path'] = $category->path;
1765 // Some fields only returned for admin.
1766 if (has_capability('moodle/category:manage', $context)) {
1767 $categoryinfo['idnumber'] = $category->idnumber;
1768 $categoryinfo['visible'] = $category->visible;
1769 $categoryinfo['visibleold'] = $category->visibleold;
1770 $categoryinfo['timemodified'] = $category->timemodified;
1771 $categoryinfo['theme'] = clean_param($category->theme, PARAM_THEME);
1774 $categoriesinfo[] = $categoryinfo;
1775 } else {
1776 $excludedcats[$category->id] = 'visibility';
1781 // Sorting the resulting array so it looks a bit better for the client developer.
1782 usort($categoriesinfo, "core_course_external::compare_categories_by_sortorder");
1784 return $categoriesinfo;
1788 * Sort categories array by path
1789 * private function: only used by get_categories
1791 * @param array $category1
1792 * @param array $category2
1793 * @return int result of strcmp
1794 * @since Moodle 2.3
1796 private static function compare_categories_by_path($category1, $category2) {
1797 return strcmp($category1->path, $category2->path);
1801 * Sort categories array by sortorder
1802 * private function: only used by get_categories
1804 * @param array $category1
1805 * @param array $category2
1806 * @return int result of strcmp
1807 * @since Moodle 2.3
1809 private static function compare_categories_by_sortorder($category1, $category2) {
1810 return strcmp($category1['sortorder'], $category2['sortorder']);
1814 * Returns description of method result value
1816 * @return external_description
1817 * @since Moodle 2.3
1819 public static function get_categories_returns() {
1820 return new external_multiple_structure(
1821 new external_single_structure(
1822 array(
1823 'id' => new external_value(PARAM_INT, 'category id'),
1824 'name' => new external_value(PARAM_TEXT, 'category name'),
1825 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1826 'description' => new external_value(PARAM_RAW, 'category description'),
1827 'descriptionformat' => new external_format_value('description'),
1828 'parent' => new external_value(PARAM_INT, 'parent category id'),
1829 'sortorder' => new external_value(PARAM_INT, 'category sorting order'),
1830 'coursecount' => new external_value(PARAM_INT, 'number of courses in this category'),
1831 'visible' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1832 'visibleold' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1833 'timemodified' => new external_value(PARAM_INT, 'timestamp', VALUE_OPTIONAL),
1834 'depth' => new external_value(PARAM_INT, 'category depth'),
1835 'path' => new external_value(PARAM_TEXT, 'category path'),
1836 'theme' => new external_value(PARAM_THEME, 'category theme', VALUE_OPTIONAL),
1837 ), 'List of categories'
1843 * Returns description of method parameters
1845 * @return external_function_parameters
1846 * @since Moodle 2.3
1848 public static function create_categories_parameters() {
1849 return new external_function_parameters(
1850 array(
1851 'categories' => new external_multiple_structure(
1852 new external_single_structure(
1853 array(
1854 'name' => new external_value(PARAM_TEXT, 'new category name'),
1855 'parent' => new external_value(PARAM_INT,
1856 'the parent category id inside which the new category will be created
1857 - set to 0 for a root category',
1858 VALUE_DEFAULT, 0),
1859 'idnumber' => new external_value(PARAM_RAW,
1860 'the new category idnumber', VALUE_OPTIONAL),
1861 'description' => new external_value(PARAM_RAW,
1862 'the new category description', VALUE_OPTIONAL),
1863 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
1864 'theme' => new external_value(PARAM_THEME,
1865 'the new category theme. This option must be enabled on moodle',
1866 VALUE_OPTIONAL),
1875 * Create categories
1877 * @param array $categories - see create_categories_parameters() for the array structure
1878 * @return array - see create_categories_returns() for the array structure
1879 * @since Moodle 2.3
1881 public static function create_categories($categories) {
1882 global $DB;
1884 $params = self::validate_parameters(self::create_categories_parameters(),
1885 array('categories' => $categories));
1887 $transaction = $DB->start_delegated_transaction();
1889 $createdcategories = array();
1890 foreach ($params['categories'] as $category) {
1891 if ($category['parent']) {
1892 if (!$DB->record_exists('course_categories', array('id' => $category['parent']))) {
1893 throw new moodle_exception('unknowcategory');
1895 $context = context_coursecat::instance($category['parent']);
1896 } else {
1897 $context = context_system::instance();
1899 self::validate_context($context);
1900 require_capability('moodle/category:manage', $context);
1902 // this will validate format and throw an exception if there are errors
1903 external_validate_format($category['descriptionformat']);
1905 $newcategory = core_course_category::create($category);
1906 $context = context_coursecat::instance($newcategory->id);
1908 $createdcategories[] = array(
1909 'id' => $newcategory->id,
1910 'name' => external_format_string($newcategory->name, $context),
1914 $transaction->allow_commit();
1916 return $createdcategories;
1920 * Returns description of method parameters
1922 * @return external_function_parameters
1923 * @since Moodle 2.3
1925 public static function create_categories_returns() {
1926 return new external_multiple_structure(
1927 new external_single_structure(
1928 array(
1929 'id' => new external_value(PARAM_INT, 'new category id'),
1930 'name' => new external_value(PARAM_TEXT, 'new category name'),
1937 * Returns description of method parameters
1939 * @return external_function_parameters
1940 * @since Moodle 2.3
1942 public static function update_categories_parameters() {
1943 return new external_function_parameters(
1944 array(
1945 'categories' => new external_multiple_structure(
1946 new external_single_structure(
1947 array(
1948 'id' => new external_value(PARAM_INT, 'course id'),
1949 'name' => new external_value(PARAM_TEXT, 'category name', VALUE_OPTIONAL),
1950 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1951 'parent' => new external_value(PARAM_INT, 'parent category id', VALUE_OPTIONAL),
1952 'description' => new external_value(PARAM_RAW, 'category description', VALUE_OPTIONAL),
1953 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
1954 'theme' => new external_value(PARAM_THEME,
1955 'the category theme. This option must be enabled on moodle', VALUE_OPTIONAL),
1964 * Update categories
1966 * @param array $categories The list of categories to update
1967 * @return null
1968 * @since Moodle 2.3
1970 public static function update_categories($categories) {
1971 global $DB;
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 = core_course_category::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");
2039 // Validate parameters.
2040 $params = self::validate_parameters(self::delete_categories_parameters(), array('categories' => $categories));
2042 $transaction = $DB->start_delegated_transaction();
2044 foreach ($params['categories'] as $category) {
2045 $deletecat = core_course_category::get($category['id'], MUST_EXIST);
2046 $context = context_coursecat::instance($deletecat->id);
2047 require_capability('moodle/category:manage', $context);
2048 self::validate_context($context);
2049 self::validate_context(get_category_or_system_context($deletecat->parent));
2051 if ($category['recursive']) {
2052 // If recursive was specified, then we recursively delete the category's contents.
2053 if ($deletecat->can_delete_full()) {
2054 $deletecat->delete_full(false);
2055 } else {
2056 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2058 } else {
2059 // In this situation, we don't delete the category's contents, we either move it to newparent or parent.
2060 // If the parent is the root, moving is not supported (because a course must always be inside a category).
2061 // We must move to an existing category.
2062 if (!empty($category['newparent'])) {
2063 $newparentcat = core_course_category::get($category['newparent']);
2064 } else {
2065 $newparentcat = core_course_category::get($deletecat->parent);
2068 // This operation is not allowed. We must move contents to an existing category.
2069 if (!$newparentcat->id) {
2070 throw new moodle_exception('movecatcontentstoroot');
2073 self::validate_context(context_coursecat::instance($newparentcat->id));
2074 if ($deletecat->can_move_content_to($newparentcat->id)) {
2075 $deletecat->delete_move($newparentcat->id, false);
2076 } else {
2077 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2082 $transaction->allow_commit();
2086 * Returns description of method parameters
2088 * @return external_function_parameters
2089 * @since Moodle 2.3
2091 public static function delete_categories_returns() {
2092 return null;
2096 * Describes the parameters for delete_modules.
2098 * @return external_function_parameters
2099 * @since Moodle 2.5
2101 public static function delete_modules_parameters() {
2102 return new external_function_parameters (
2103 array(
2104 'cmids' => new external_multiple_structure(new external_value(PARAM_INT, 'course module ID',
2105 VALUE_REQUIRED, '', NULL_NOT_ALLOWED), 'Array of course module IDs'),
2111 * Deletes a list of provided module instances.
2113 * @param array $cmids the course module ids
2114 * @since Moodle 2.5
2116 public static function delete_modules($cmids) {
2117 global $CFG, $DB;
2119 // Require course file containing the course delete module function.
2120 require_once($CFG->dirroot . "/course/lib.php");
2122 // Clean the parameters.
2123 $params = self::validate_parameters(self::delete_modules_parameters(), array('cmids' => $cmids));
2125 // Keep track of the course ids we have performed a capability check on to avoid repeating.
2126 $arrcourseschecked = array();
2128 foreach ($params['cmids'] as $cmid) {
2129 // Get the course module.
2130 $cm = $DB->get_record('course_modules', array('id' => $cmid), '*', MUST_EXIST);
2132 // Check if we have not yet confirmed they have permission in this course.
2133 if (!in_array($cm->course, $arrcourseschecked)) {
2134 // Ensure the current user has required permission in this course.
2135 $context = context_course::instance($cm->course);
2136 self::validate_context($context);
2137 // Add to the array.
2138 $arrcourseschecked[] = $cm->course;
2141 // Ensure they can delete this module.
2142 $modcontext = context_module::instance($cm->id);
2143 require_capability('moodle/course:manageactivities', $modcontext);
2145 // Delete the module.
2146 course_delete_module($cm->id);
2151 * Describes the delete_modules return value.
2153 * @return external_single_structure
2154 * @since Moodle 2.5
2156 public static function delete_modules_returns() {
2157 return null;
2161 * Returns description of method parameters
2163 * @return external_function_parameters
2164 * @since Moodle 2.9
2166 public static function view_course_parameters() {
2167 return new external_function_parameters(
2168 array(
2169 'courseid' => new external_value(PARAM_INT, 'id of the course'),
2170 'sectionnumber' => new external_value(PARAM_INT, 'section number', VALUE_DEFAULT, 0)
2176 * Trigger the course viewed event.
2178 * @param int $courseid id of course
2179 * @param int $sectionnumber sectionnumber (0, 1, 2...)
2180 * @return array of warnings and status result
2181 * @since Moodle 2.9
2182 * @throws moodle_exception
2184 public static function view_course($courseid, $sectionnumber = 0) {
2185 global $CFG;
2186 require_once($CFG->dirroot . "/course/lib.php");
2188 $params = self::validate_parameters(self::view_course_parameters(),
2189 array(
2190 'courseid' => $courseid,
2191 'sectionnumber' => $sectionnumber
2194 $warnings = array();
2196 $course = get_course($params['courseid']);
2197 $context = context_course::instance($course->id);
2198 self::validate_context($context);
2200 if (!empty($params['sectionnumber'])) {
2202 // Get section details and check it exists.
2203 $modinfo = get_fast_modinfo($course);
2204 $coursesection = $modinfo->get_section_info($params['sectionnumber'], MUST_EXIST);
2206 // Check user is allowed to see it.
2207 if (!$coursesection->uservisible) {
2208 require_capability('moodle/course:viewhiddensections', $context);
2212 course_view($context, $params['sectionnumber']);
2214 $result = array();
2215 $result['status'] = true;
2216 $result['warnings'] = $warnings;
2217 return $result;
2221 * Returns description of method result value
2223 * @return external_description
2224 * @since Moodle 2.9
2226 public static function view_course_returns() {
2227 return new external_single_structure(
2228 array(
2229 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
2230 'warnings' => new external_warnings()
2236 * Returns description of method parameters
2238 * @return external_function_parameters
2239 * @since Moodle 3.0
2241 public static function search_courses_parameters() {
2242 return new external_function_parameters(
2243 array(
2244 'criterianame' => new external_value(PARAM_ALPHA, 'criteria name
2245 (search, modulelist (only admins), blocklist (only admins), tagid)'),
2246 'criteriavalue' => new external_value(PARAM_RAW, 'criteria value'),
2247 'page' => new external_value(PARAM_INT, 'page number (0 based)', VALUE_DEFAULT, 0),
2248 'perpage' => new external_value(PARAM_INT, 'items per page', VALUE_DEFAULT, 0),
2249 'requiredcapabilities' => new external_multiple_structure(
2250 new external_value(PARAM_CAPABILITY, 'Capability string used to filter courses by permission'),
2251 'Optional list of required capabilities (used to filter the list)', VALUE_DEFAULT, array()
2253 'limittoenrolled' => new external_value(PARAM_BOOL, 'limit to enrolled courses', VALUE_DEFAULT, 0),
2259 * Return the course information that is public (visible by every one)
2261 * @param core_course_list_element $course course in list object
2262 * @param stdClass $coursecontext course context object
2263 * @return array the course information
2264 * @since Moodle 3.2
2266 protected static function get_course_public_information(core_course_list_element $course, $coursecontext) {
2268 static $categoriescache = array();
2270 // Category information.
2271 if (!array_key_exists($course->category, $categoriescache)) {
2272 $categoriescache[$course->category] = core_course_category::get($course->category, IGNORE_MISSING);
2274 $category = $categoriescache[$course->category];
2276 // Retrieve course overview used files.
2277 $files = array();
2278 foreach ($course->get_course_overviewfiles() as $file) {
2279 $fileurl = moodle_url::make_webservice_pluginfile_url($file->get_contextid(), $file->get_component(),
2280 $file->get_filearea(), null, $file->get_filepath(),
2281 $file->get_filename())->out(false);
2282 $files[] = array(
2283 'filename' => $file->get_filename(),
2284 'fileurl' => $fileurl,
2285 'filesize' => $file->get_filesize(),
2286 'filepath' => $file->get_filepath(),
2287 'mimetype' => $file->get_mimetype(),
2288 'timemodified' => $file->get_timemodified(),
2292 // Retrieve the course contacts,
2293 // we need here the users fullname since if we are not enrolled can be difficult to obtain them via other Web Services.
2294 $coursecontacts = array();
2295 foreach ($course->get_course_contacts() as $contact) {
2296 $coursecontacts[] = array(
2297 'id' => $contact['user']->id,
2298 'fullname' => $contact['username'],
2299 'roles' => array_map(function($role){
2300 return array('id' => $role->id, 'name' => $role->displayname);
2301 }, $contact['roles']),
2302 'role' => array('id' => $contact['role']->id, 'name' => $contact['role']->displayname),
2303 'rolename' => $contact['rolename']
2307 // Allowed enrolment methods (maybe we can self-enrol).
2308 $enroltypes = array();
2309 $instances = enrol_get_instances($course->id, true);
2310 foreach ($instances as $instance) {
2311 $enroltypes[] = $instance->enrol;
2314 // Format summary.
2315 list($summary, $summaryformat) =
2316 external_format_text($course->summary, $course->summaryformat, $coursecontext->id, 'course', 'summary', null);
2318 $categoryname = '';
2319 if (!empty($category)) {
2320 $categoryname = external_format_string($category->name, $category->get_context());
2323 $displayname = get_course_display_name_for_list($course);
2324 $coursereturns = array();
2325 $coursereturns['id'] = $course->id;
2326 $coursereturns['fullname'] = external_format_string($course->fullname, $coursecontext->id);
2327 $coursereturns['displayname'] = external_format_string($displayname, $coursecontext->id);
2328 $coursereturns['shortname'] = external_format_string($course->shortname, $coursecontext->id);
2329 $coursereturns['categoryid'] = $course->category;
2330 $coursereturns['categoryname'] = $categoryname;
2331 $coursereturns['summary'] = $summary;
2332 $coursereturns['summaryformat'] = $summaryformat;
2333 $coursereturns['summaryfiles'] = external_util::get_area_files($coursecontext->id, 'course', 'summary', false, false);
2334 $coursereturns['overviewfiles'] = $files;
2335 $coursereturns['contacts'] = $coursecontacts;
2336 $coursereturns['enrollmentmethods'] = $enroltypes;
2337 $coursereturns['sortorder'] = $course->sortorder;
2338 return $coursereturns;
2342 * Search courses following the specified criteria.
2344 * @param string $criterianame Criteria name (search, modulelist (only admins), blocklist (only admins), tagid)
2345 * @param string $criteriavalue Criteria value
2346 * @param int $page Page number (for pagination)
2347 * @param int $perpage Items per page
2348 * @param array $requiredcapabilities Optional list of required capabilities (used to filter the list).
2349 * @param int $limittoenrolled Limit to only enrolled courses
2350 * @return array of course objects and warnings
2351 * @since Moodle 3.0
2352 * @throws moodle_exception
2354 public static function search_courses($criterianame,
2355 $criteriavalue,
2356 $page=0,
2357 $perpage=0,
2358 $requiredcapabilities=array(),
2359 $limittoenrolled=0) {
2360 global $CFG;
2362 $warnings = array();
2364 $parameters = array(
2365 'criterianame' => $criterianame,
2366 'criteriavalue' => $criteriavalue,
2367 'page' => $page,
2368 'perpage' => $perpage,
2369 'requiredcapabilities' => $requiredcapabilities
2371 $params = self::validate_parameters(self::search_courses_parameters(), $parameters);
2372 self::validate_context(context_system::instance());
2374 $allowedcriterianames = array('search', 'modulelist', 'blocklist', 'tagid');
2375 if (!in_array($params['criterianame'], $allowedcriterianames)) {
2376 throw new invalid_parameter_exception('Invalid value for criterianame parameter (value: '.$params['criterianame'].'),' .
2377 'allowed values are: '.implode(',', $allowedcriterianames));
2380 if ($params['criterianame'] == 'modulelist' or $params['criterianame'] == 'blocklist') {
2381 require_capability('moodle/site:config', context_system::instance());
2384 $paramtype = array(
2385 'search' => PARAM_RAW,
2386 'modulelist' => PARAM_PLUGIN,
2387 'blocklist' => PARAM_INT,
2388 'tagid' => PARAM_INT
2390 $params['criteriavalue'] = clean_param($params['criteriavalue'], $paramtype[$params['criterianame']]);
2392 // Prepare the search API options.
2393 $searchcriteria = array();
2394 $searchcriteria[$params['criterianame']] = $params['criteriavalue'];
2396 $options = array();
2397 if ($params['perpage'] != 0) {
2398 $offset = $params['page'] * $params['perpage'];
2399 $options = array('offset' => $offset, 'limit' => $params['perpage']);
2402 // Search the courses.
2403 $courses = core_course_category::search_courses($searchcriteria, $options, $params['requiredcapabilities']);
2404 $totalcount = core_course_category::search_courses_count($searchcriteria, $options, $params['requiredcapabilities']);
2406 if (!empty($limittoenrolled)) {
2407 // Get the courses where the current user has access.
2408 $enrolled = enrol_get_my_courses(array('id', 'cacherev'));
2411 $finalcourses = array();
2412 $categoriescache = array();
2414 foreach ($courses as $course) {
2415 if (!empty($limittoenrolled)) {
2416 // Filter out not enrolled courses.
2417 if (!isset($enrolled[$course->id])) {
2418 $totalcount--;
2419 continue;
2423 $coursecontext = context_course::instance($course->id);
2425 $finalcourses[] = self::get_course_public_information($course, $coursecontext);
2428 return array(
2429 'total' => $totalcount,
2430 'courses' => $finalcourses,
2431 'warnings' => $warnings
2436 * Returns a course structure definition
2438 * @param boolean $onlypublicdata set to true, to retrieve only fields viewable by anyone when the course is visible
2439 * @return array the course structure
2440 * @since Moodle 3.2
2442 protected static function get_course_structure($onlypublicdata = true) {
2443 $coursestructure = array(
2444 'id' => new external_value(PARAM_INT, 'course id'),
2445 'fullname' => new external_value(PARAM_TEXT, 'course full name'),
2446 'displayname' => new external_value(PARAM_TEXT, 'course display name'),
2447 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
2448 'categoryid' => new external_value(PARAM_INT, 'category id'),
2449 'categoryname' => new external_value(PARAM_TEXT, 'category name'),
2450 'sortorder' => new external_value(PARAM_INT, 'Sort order in the category', VALUE_OPTIONAL),
2451 'summary' => new external_value(PARAM_RAW, 'summary'),
2452 'summaryformat' => new external_format_value('summary'),
2453 'summaryfiles' => new external_files('summary files in the summary field', VALUE_OPTIONAL),
2454 'overviewfiles' => new external_files('additional overview files attached to this course'),
2455 'contacts' => new external_multiple_structure(
2456 new external_single_structure(
2457 array(
2458 'id' => new external_value(PARAM_INT, 'contact user id'),
2459 'fullname' => new external_value(PARAM_NOTAGS, 'contact user fullname'),
2462 'contact users'
2464 'enrollmentmethods' => new external_multiple_structure(
2465 new external_value(PARAM_PLUGIN, 'enrollment method'),
2466 'enrollment methods list'
2470 if (!$onlypublicdata) {
2471 $extra = array(
2472 'idnumber' => new external_value(PARAM_RAW, 'Id number', VALUE_OPTIONAL),
2473 'format' => new external_value(PARAM_PLUGIN, 'Course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
2474 'showgrades' => new external_value(PARAM_INT, '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
2475 'newsitems' => new external_value(PARAM_INT, 'Number of recent items appearing on the course page', VALUE_OPTIONAL),
2476 'startdate' => new external_value(PARAM_INT, 'Timestamp when the course start', VALUE_OPTIONAL),
2477 'enddate' => new external_value(PARAM_INT, 'Timestamp when the course end', VALUE_OPTIONAL),
2478 'maxbytes' => new external_value(PARAM_INT, 'Largest size of file that can be uploaded into', VALUE_OPTIONAL),
2479 'showreports' => new external_value(PARAM_INT, 'Are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
2480 'visible' => new external_value(PARAM_INT, '1: available to student, 0:not available', VALUE_OPTIONAL),
2481 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
2482 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
2483 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
2484 'enablecompletion' => new external_value(PARAM_INT, 'Completion enabled? 1: yes 0: no', VALUE_OPTIONAL),
2485 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
2486 'lang' => new external_value(PARAM_SAFEDIR, 'Forced course language', VALUE_OPTIONAL),
2487 'theme' => new external_value(PARAM_PLUGIN, 'Fame of the forced theme', VALUE_OPTIONAL),
2488 'marker' => new external_value(PARAM_INT, 'Current course marker', VALUE_OPTIONAL),
2489 'legacyfiles' => new external_value(PARAM_INT, 'If legacy files are enabled', VALUE_OPTIONAL),
2490 'calendartype' => new external_value(PARAM_PLUGIN, 'Calendar type', VALUE_OPTIONAL),
2491 'timecreated' => new external_value(PARAM_INT, 'Time when the course was created', VALUE_OPTIONAL),
2492 'timemodified' => new external_value(PARAM_INT, 'Last time the course was updated', VALUE_OPTIONAL),
2493 'requested' => new external_value(PARAM_INT, 'If is a requested course', VALUE_OPTIONAL),
2494 'cacherev' => new external_value(PARAM_INT, 'Cache revision number', VALUE_OPTIONAL),
2495 'filters' => new external_multiple_structure(
2496 new external_single_structure(
2497 array(
2498 'filter' => new external_value(PARAM_PLUGIN, 'Filter plugin name'),
2499 'localstate' => new external_value(PARAM_INT, 'Filter state: 1 for on, -1 for off, 0 if inherit'),
2500 'inheritedstate' => new external_value(PARAM_INT, '1 or 0 to use when localstate is set to inherit'),
2503 'Course filters', VALUE_OPTIONAL
2505 'courseformatoptions' => new external_multiple_structure(
2506 new external_single_structure(
2507 array(
2508 'name' => new external_value(PARAM_RAW, 'Course format option name.'),
2509 'value' => new external_value(PARAM_RAW, 'Course format option value.'),
2512 'Additional options for particular course format.', VALUE_OPTIONAL
2515 $coursestructure = array_merge($coursestructure, $extra);
2517 return new external_single_structure($coursestructure);
2521 * Returns description of method result value
2523 * @return external_description
2524 * @since Moodle 3.0
2526 public static function search_courses_returns() {
2527 return new external_single_structure(
2528 array(
2529 'total' => new external_value(PARAM_INT, 'total course count'),
2530 'courses' => new external_multiple_structure(self::get_course_structure(), 'course'),
2531 'warnings' => new external_warnings()
2537 * Returns description of method parameters
2539 * @return external_function_parameters
2540 * @since Moodle 3.0
2542 public static function get_course_module_parameters() {
2543 return new external_function_parameters(
2544 array(
2545 'cmid' => new external_value(PARAM_INT, 'The course module id')
2551 * Return information about a course module.
2553 * @param int $cmid the course module id
2554 * @return array of warnings and the course module
2555 * @since Moodle 3.0
2556 * @throws moodle_exception
2558 public static function get_course_module($cmid) {
2559 global $CFG, $DB;
2561 $params = self::validate_parameters(self::get_course_module_parameters(), array('cmid' => $cmid));
2562 $warnings = array();
2564 $cm = get_coursemodule_from_id(null, $params['cmid'], 0, true, MUST_EXIST);
2565 $context = context_module::instance($cm->id);
2566 self::validate_context($context);
2568 // If the user has permissions to manage the activity, return all the information.
2569 if (has_capability('moodle/course:manageactivities', $context)) {
2570 require_once($CFG->dirroot . '/course/modlib.php');
2571 require_once($CFG->libdir . '/gradelib.php');
2573 $info = $cm;
2574 // Get the extra information: grade, advanced grading and outcomes data.
2575 $course = get_course($cm->course);
2576 list($newcm, $newcontext, $module, $extrainfo, $cw) = get_moduleinfo_data($cm, $course);
2577 // Grades.
2578 $gradeinfo = array('grade', 'gradepass', 'gradecat');
2579 foreach ($gradeinfo as $gfield) {
2580 if (isset($extrainfo->{$gfield})) {
2581 $info->{$gfield} = $extrainfo->{$gfield};
2584 if (isset($extrainfo->grade) and $extrainfo->grade < 0) {
2585 $info->scale = $DB->get_field('scale', 'scale', array('id' => abs($extrainfo->grade)));
2587 // Advanced grading.
2588 if (isset($extrainfo->_advancedgradingdata)) {
2589 $info->advancedgrading = array();
2590 foreach ($extrainfo as $key => $val) {
2591 if (strpos($key, 'advancedgradingmethod_') === 0) {
2592 $info->advancedgrading[] = array(
2593 'area' => str_replace('advancedgradingmethod_', '', $key),
2594 'method' => $val
2599 // Outcomes.
2600 foreach ($extrainfo as $key => $val) {
2601 if (strpos($key, 'outcome_') === 0) {
2602 if (!isset($info->outcomes)) {
2603 $info->outcomes = array();
2605 $id = str_replace('outcome_', '', $key);
2606 $outcome = grade_outcome::fetch(array('id' => $id));
2607 $scaleitems = $outcome->load_scale();
2608 $info->outcomes[] = array(
2609 'id' => $id,
2610 'name' => external_format_string($outcome->get_name(), $context->id),
2611 'scale' => $scaleitems->scale
2615 } else {
2616 // Return information is safe to show to any user.
2617 $info = new stdClass();
2618 $info->id = $cm->id;
2619 $info->course = $cm->course;
2620 $info->module = $cm->module;
2621 $info->modname = $cm->modname;
2622 $info->instance = $cm->instance;
2623 $info->section = $cm->section;
2624 $info->sectionnum = $cm->sectionnum;
2625 $info->groupmode = $cm->groupmode;
2626 $info->groupingid = $cm->groupingid;
2627 $info->completion = $cm->completion;
2629 // Format name.
2630 $info->name = external_format_string($cm->name, $context->id);
2631 $result = array();
2632 $result['cm'] = $info;
2633 $result['warnings'] = $warnings;
2634 return $result;
2638 * Returns description of method result value
2640 * @return external_description
2641 * @since Moodle 3.0
2643 public static function get_course_module_returns() {
2644 return new external_single_structure(
2645 array(
2646 'cm' => new external_single_structure(
2647 array(
2648 'id' => new external_value(PARAM_INT, 'The course module id'),
2649 'course' => new external_value(PARAM_INT, 'The course id'),
2650 'module' => new external_value(PARAM_INT, 'The module type id'),
2651 'name' => new external_value(PARAM_RAW, 'The activity name'),
2652 'modname' => new external_value(PARAM_COMPONENT, 'The module component name (forum, assign, etc..)'),
2653 'instance' => new external_value(PARAM_INT, 'The activity instance id'),
2654 'section' => new external_value(PARAM_INT, 'The module section id'),
2655 'sectionnum' => new external_value(PARAM_INT, 'The module section number'),
2656 'groupmode' => new external_value(PARAM_INT, 'Group mode'),
2657 'groupingid' => new external_value(PARAM_INT, 'Grouping id'),
2658 'completion' => new external_value(PARAM_INT, 'If completion is enabled'),
2659 'idnumber' => new external_value(PARAM_RAW, 'Module id number', VALUE_OPTIONAL),
2660 'added' => new external_value(PARAM_INT, 'Time added', VALUE_OPTIONAL),
2661 'score' => new external_value(PARAM_INT, 'Score', VALUE_OPTIONAL),
2662 'indent' => new external_value(PARAM_INT, 'Indentation', VALUE_OPTIONAL),
2663 'visible' => new external_value(PARAM_INT, 'If visible', VALUE_OPTIONAL),
2664 'visibleoncoursepage' => new external_value(PARAM_INT, 'If visible on course page', VALUE_OPTIONAL),
2665 'visibleold' => new external_value(PARAM_INT, 'Visible old', VALUE_OPTIONAL),
2666 'completiongradeitemnumber' => new external_value(PARAM_INT, 'Completion grade item', VALUE_OPTIONAL),
2667 'completionview' => new external_value(PARAM_INT, 'Completion view setting', VALUE_OPTIONAL),
2668 'completionexpected' => new external_value(PARAM_INT, 'Completion time expected', VALUE_OPTIONAL),
2669 'showdescription' => new external_value(PARAM_INT, 'If the description is showed', VALUE_OPTIONAL),
2670 'availability' => new external_value(PARAM_RAW, 'Availability settings', VALUE_OPTIONAL),
2671 'grade' => new external_value(PARAM_FLOAT, 'Grade (max value or scale id)', VALUE_OPTIONAL),
2672 'scale' => new external_value(PARAM_TEXT, 'Scale items (if used)', VALUE_OPTIONAL),
2673 'gradepass' => new external_value(PARAM_RAW, 'Grade to pass (float)', VALUE_OPTIONAL),
2674 'gradecat' => new external_value(PARAM_INT, 'Grade category', VALUE_OPTIONAL),
2675 'advancedgrading' => new external_multiple_structure(
2676 new external_single_structure(
2677 array(
2678 'area' => new external_value(PARAM_AREA, 'Gradable area name'),
2679 'method' => new external_value(PARAM_COMPONENT, 'Grading method'),
2682 'Advanced grading settings', VALUE_OPTIONAL
2684 'outcomes' => new external_multiple_structure(
2685 new external_single_structure(
2686 array(
2687 'id' => new external_value(PARAM_ALPHANUMEXT, 'Outcome id'),
2688 'name' => new external_value(PARAM_TEXT, 'Outcome full name'),
2689 'scale' => new external_value(PARAM_TEXT, 'Scale items')
2692 'Outcomes information', VALUE_OPTIONAL
2696 'warnings' => new external_warnings()
2702 * Returns description of method parameters
2704 * @return external_function_parameters
2705 * @since Moodle 3.0
2707 public static function get_course_module_by_instance_parameters() {
2708 return new external_function_parameters(
2709 array(
2710 'module' => new external_value(PARAM_COMPONENT, 'The module name'),
2711 'instance' => new external_value(PARAM_INT, 'The module instance id')
2717 * Return information about a course module.
2719 * @param string $module the module name
2720 * @param int $instance the activity instance id
2721 * @return array of warnings and the course module
2722 * @since Moodle 3.0
2723 * @throws moodle_exception
2725 public static function get_course_module_by_instance($module, $instance) {
2727 $params = self::validate_parameters(self::get_course_module_by_instance_parameters(),
2728 array(
2729 'module' => $module,
2730 'instance' => $instance,
2733 $warnings = array();
2734 $cm = get_coursemodule_from_instance($params['module'], $params['instance'], 0, false, MUST_EXIST);
2736 return self::get_course_module($cm->id);
2740 * Returns description of method result value
2742 * @return external_description
2743 * @since Moodle 3.0
2745 public static function get_course_module_by_instance_returns() {
2746 return self::get_course_module_returns();
2750 * Returns description of method parameters
2752 * @deprecated since 3.3
2753 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
2754 * @return external_function_parameters
2755 * @since Moodle 3.2
2757 public static function get_activities_overview_parameters() {
2758 return new external_function_parameters(
2759 array(
2760 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2766 * Return activities overview for the given courses.
2768 * @deprecated since 3.3
2769 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
2770 * @param array $courseids a list of course ids
2771 * @return array of warnings and the activities overview
2772 * @since Moodle 3.2
2773 * @throws moodle_exception
2775 public static function get_activities_overview($courseids) {
2776 global $USER;
2778 // Parameter validation.
2779 $params = self::validate_parameters(self::get_activities_overview_parameters(), array('courseids' => $courseids));
2780 $courseoverviews = array();
2782 list($courses, $warnings) = external_util::validate_courses($params['courseids']);
2784 if (!empty($courses)) {
2785 // Add lastaccess to each course (required by print_overview function).
2786 // We need the complete user data, the ws server does not load a complete one.
2787 $user = get_complete_user_data('id', $USER->id);
2788 foreach ($courses as $course) {
2789 if (isset($user->lastcourseaccess[$course->id])) {
2790 $course->lastaccess = $user->lastcourseaccess[$course->id];
2791 } else {
2792 $course->lastaccess = 0;
2796 $overviews = array();
2797 if ($modules = get_plugin_list_with_function('mod', 'print_overview')) {
2798 foreach ($modules as $fname) {
2799 $fname($courses, $overviews);
2803 // Format output.
2804 foreach ($overviews as $courseid => $modules) {
2805 $courseoverviews[$courseid]['id'] = $courseid;
2806 $courseoverviews[$courseid]['overviews'] = array();
2808 foreach ($modules as $modname => $overviewtext) {
2809 $courseoverviews[$courseid]['overviews'][] = array(
2810 'module' => $modname,
2811 'overviewtext' => $overviewtext // This text doesn't need formatting.
2817 $result = array(
2818 'courses' => $courseoverviews,
2819 'warnings' => $warnings
2821 return $result;
2825 * Returns description of method result value
2827 * @deprecated since 3.3
2828 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
2829 * @return external_description
2830 * @since Moodle 3.2
2832 public static function get_activities_overview_returns() {
2833 return new external_single_structure(
2834 array(
2835 'courses' => new external_multiple_structure(
2836 new external_single_structure(
2837 array(
2838 'id' => new external_value(PARAM_INT, 'Course id'),
2839 'overviews' => new external_multiple_structure(
2840 new external_single_structure(
2841 array(
2842 'module' => new external_value(PARAM_PLUGIN, 'Module name'),
2843 'overviewtext' => new external_value(PARAM_RAW, 'Overview text'),
2848 ), 'List of courses'
2850 'warnings' => new external_warnings()
2856 * Marking the method as deprecated.
2858 * @return bool
2860 public static function get_activities_overview_is_deprecated() {
2861 return true;
2865 * Returns description of method parameters
2867 * @return external_function_parameters
2868 * @since Moodle 3.2
2870 public static function get_user_navigation_options_parameters() {
2871 return new external_function_parameters(
2872 array(
2873 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2879 * Return a list of navigation options in a set of courses that are avaialable or not for the current user.
2881 * @param array $courseids a list of course ids
2882 * @return array of warnings and the options availability
2883 * @since Moodle 3.2
2884 * @throws moodle_exception
2886 public static function get_user_navigation_options($courseids) {
2887 global $CFG;
2888 require_once($CFG->dirroot . '/course/lib.php');
2890 // Parameter validation.
2891 $params = self::validate_parameters(self::get_user_navigation_options_parameters(), array('courseids' => $courseids));
2892 $courseoptions = array();
2894 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
2896 if (!empty($courses)) {
2897 foreach ($courses as $course) {
2898 // Fix the context for the frontpage.
2899 if ($course->id == SITEID) {
2900 $course->context = context_system::instance();
2902 $navoptions = course_get_user_navigation_options($course->context, $course);
2903 $options = array();
2904 foreach ($navoptions as $name => $available) {
2905 $options[] = array(
2906 'name' => $name,
2907 'available' => $available,
2911 $courseoptions[] = array(
2912 'id' => $course->id,
2913 'options' => $options
2918 $result = array(
2919 'courses' => $courseoptions,
2920 'warnings' => $warnings
2922 return $result;
2926 * Returns description of method result value
2928 * @return external_description
2929 * @since Moodle 3.2
2931 public static function get_user_navigation_options_returns() {
2932 return new external_single_structure(
2933 array(
2934 'courses' => new external_multiple_structure(
2935 new external_single_structure(
2936 array(
2937 'id' => new external_value(PARAM_INT, 'Course id'),
2938 'options' => new external_multiple_structure(
2939 new external_single_structure(
2940 array(
2941 'name' => new external_value(PARAM_ALPHANUMEXT, 'Option name'),
2942 'available' => new external_value(PARAM_BOOL, 'Whether the option is available or not'),
2947 ), 'List of courses'
2949 'warnings' => new external_warnings()
2955 * Returns description of method parameters
2957 * @return external_function_parameters
2958 * @since Moodle 3.2
2960 public static function get_user_administration_options_parameters() {
2961 return new external_function_parameters(
2962 array(
2963 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2969 * Return a list of administration options in a set of courses that are available or not for the current user.
2971 * @param array $courseids a list of course ids
2972 * @return array of warnings and the options availability
2973 * @since Moodle 3.2
2974 * @throws moodle_exception
2976 public static function get_user_administration_options($courseids) {
2977 global $CFG;
2978 require_once($CFG->dirroot . '/course/lib.php');
2980 // Parameter validation.
2981 $params = self::validate_parameters(self::get_user_administration_options_parameters(), array('courseids' => $courseids));
2982 $courseoptions = array();
2984 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
2986 if (!empty($courses)) {
2987 foreach ($courses as $course) {
2988 $adminoptions = course_get_user_administration_options($course, $course->context);
2989 $options = array();
2990 foreach ($adminoptions as $name => $available) {
2991 $options[] = array(
2992 'name' => $name,
2993 'available' => $available,
2997 $courseoptions[] = array(
2998 'id' => $course->id,
2999 'options' => $options
3004 $result = array(
3005 'courses' => $courseoptions,
3006 'warnings' => $warnings
3008 return $result;
3012 * Returns description of method result value
3014 * @return external_description
3015 * @since Moodle 3.2
3017 public static function get_user_administration_options_returns() {
3018 return self::get_user_navigation_options_returns();
3022 * Returns description of method parameters
3024 * @return external_function_parameters
3025 * @since Moodle 3.2
3027 public static function get_courses_by_field_parameters() {
3028 return new external_function_parameters(
3029 array(
3030 'field' => new external_value(PARAM_ALPHA, 'The field to search can be left empty for all courses or:
3031 id: course id
3032 ids: comma separated course ids
3033 shortname: course short name
3034 idnumber: course id number
3035 category: category id the course belongs to
3036 ', VALUE_DEFAULT, ''),
3037 'value' => new external_value(PARAM_RAW, 'The value to match', VALUE_DEFAULT, '')
3044 * Get courses matching a specific field (id/s, shortname, idnumber, category)
3046 * @param string $field field name to search, or empty for all courses
3047 * @param string $value value to search
3048 * @return array list of courses and warnings
3049 * @throws invalid_parameter_exception
3050 * @since Moodle 3.2
3052 public static function get_courses_by_field($field = '', $value = '') {
3053 global $DB, $CFG;
3054 require_once($CFG->dirroot . '/course/lib.php');
3055 require_once($CFG->libdir . '/filterlib.php');
3057 $params = self::validate_parameters(self::get_courses_by_field_parameters(),
3058 array(
3059 'field' => $field,
3060 'value' => $value,
3063 $warnings = array();
3065 if (empty($params['field'])) {
3066 $courses = $DB->get_records('course', null, 'id ASC');
3067 } else {
3068 switch ($params['field']) {
3069 case 'id':
3070 case 'category':
3071 $value = clean_param($params['value'], PARAM_INT);
3072 break;
3073 case 'ids':
3074 $value = clean_param($params['value'], PARAM_SEQUENCE);
3075 break;
3076 case 'shortname':
3077 $value = clean_param($params['value'], PARAM_TEXT);
3078 break;
3079 case 'idnumber':
3080 $value = clean_param($params['value'], PARAM_RAW);
3081 break;
3082 default:
3083 throw new invalid_parameter_exception('Invalid field name');
3086 if ($params['field'] === 'ids') {
3087 $courses = $DB->get_records_list('course', 'id', explode(',', $value), 'id ASC');
3088 } else {
3089 $courses = $DB->get_records('course', array($params['field'] => $value), 'id ASC');
3093 $coursesdata = array();
3094 foreach ($courses as $course) {
3095 $context = context_course::instance($course->id);
3096 $canupdatecourse = has_capability('moodle/course:update', $context);
3097 $canviewhiddencourses = has_capability('moodle/course:viewhiddencourses', $context);
3099 // Check if the course is visible in the site for the user.
3100 if (!$course->visible and !$canviewhiddencourses and !$canupdatecourse) {
3101 continue;
3103 // Get the public course information, even if we are not enrolled.
3104 $courseinlist = new core_course_list_element($course);
3105 $coursesdata[$course->id] = self::get_course_public_information($courseinlist, $context);
3107 // Now, check if we have access to the course.
3108 try {
3109 self::validate_context($context);
3110 } catch (Exception $e) {
3111 continue;
3113 // Return information for any user that can access the course.
3114 $coursefields = array('format', 'showgrades', 'newsitems', 'startdate', 'enddate', 'maxbytes', 'showreports', 'visible',
3115 'groupmode', 'groupmodeforce', 'defaultgroupingid', 'enablecompletion', 'completionnotify', 'lang', 'theme',
3116 'marker');
3118 // Course filters.
3119 $coursesdata[$course->id]['filters'] = filter_get_available_in_context($context);
3121 // Information for managers only.
3122 if ($canupdatecourse) {
3123 $managerfields = array('idnumber', 'legacyfiles', 'calendartype', 'timecreated', 'timemodified', 'requested',
3124 'cacherev');
3125 $coursefields = array_merge($coursefields, $managerfields);
3128 // Populate fields.
3129 foreach ($coursefields as $field) {
3130 $coursesdata[$course->id][$field] = $course->{$field};
3133 // Clean lang and auth fields for external functions (it may content uninstalled themes or language packs).
3134 if (isset($coursesdata[$course->id]['theme'])) {
3135 $coursesdata[$course->id]['theme'] = clean_param($coursesdata[$course->id]['theme'], PARAM_THEME);
3137 if (isset($coursesdata[$course->id]['lang'])) {
3138 $coursesdata[$course->id]['lang'] = clean_param($coursesdata[$course->id]['lang'], PARAM_LANG);
3141 $courseformatoptions = course_get_format($course)->get_config_for_external();
3142 foreach ($courseformatoptions as $key => $value) {
3143 $coursesdata[$course->id]['courseformatoptions'][] = array(
3144 'name' => $key,
3145 'value' => $value
3150 return array(
3151 'courses' => $coursesdata,
3152 'warnings' => $warnings
3157 * Returns description of method result value
3159 * @return external_description
3160 * @since Moodle 3.2
3162 public static function get_courses_by_field_returns() {
3163 // Course structure, including not only public viewable fields.
3164 return new external_single_structure(
3165 array(
3166 'courses' => new external_multiple_structure(self::get_course_structure(false), 'Course'),
3167 'warnings' => new external_warnings()
3173 * Returns description of method parameters
3175 * @return external_function_parameters
3176 * @since Moodle 3.2
3178 public static function check_updates_parameters() {
3179 return new external_function_parameters(
3180 array(
3181 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3182 'tocheck' => new external_multiple_structure(
3183 new external_single_structure(
3184 array(
3185 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level for the file location.
3186 Only module supported right now.'),
3187 'id' => new external_value(PARAM_INT, 'Context instance id'),
3188 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3191 'Instances to check'
3193 'filter' => new external_multiple_structure(
3194 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3195 gradeitems, outcomes'),
3196 'Check only for updates in these areas', VALUE_DEFAULT, array()
3203 * Check if there is updates affecting the user for the given course and contexts.
3204 * Right now only modules are supported.
3205 * This WS calls mod_check_updates_since for each module to check if there is any update the user should we aware of.
3207 * @param int $courseid the list of modules to check
3208 * @param array $tocheck the list of modules to check
3209 * @param array $filter check only for updates in these areas
3210 * @return array list of updates and warnings
3211 * @throws moodle_exception
3212 * @since Moodle 3.2
3214 public static function check_updates($courseid, $tocheck, $filter = array()) {
3215 global $CFG, $DB;
3216 require_once($CFG->dirroot . "/course/lib.php");
3218 $params = self::validate_parameters(
3219 self::check_updates_parameters(),
3220 array(
3221 'courseid' => $courseid,
3222 'tocheck' => $tocheck,
3223 'filter' => $filter,
3227 $course = get_course($params['courseid']);
3228 $context = context_course::instance($course->id);
3229 self::validate_context($context);
3231 list($instances, $warnings) = course_check_updates($course, $params['tocheck'], $filter);
3233 $instancesformatted = array();
3234 foreach ($instances as $instance) {
3235 $updates = array();
3236 foreach ($instance['updates'] as $name => $data) {
3237 if (empty($data->updated)) {
3238 continue;
3240 $updatedata = array(
3241 'name' => $name,
3243 if (!empty($data->timeupdated)) {
3244 $updatedata['timeupdated'] = $data->timeupdated;
3246 if (!empty($data->itemids)) {
3247 $updatedata['itemids'] = $data->itemids;
3249 $updates[] = $updatedata;
3251 if (!empty($updates)) {
3252 $instancesformatted[] = array(
3253 'contextlevel' => $instance['contextlevel'],
3254 'id' => $instance['id'],
3255 'updates' => $updates
3260 return array(
3261 'instances' => $instancesformatted,
3262 'warnings' => $warnings
3267 * Returns description of method result value
3269 * @return external_description
3270 * @since Moodle 3.2
3272 public static function check_updates_returns() {
3273 return new external_single_structure(
3274 array(
3275 'instances' => new external_multiple_structure(
3276 new external_single_structure(
3277 array(
3278 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level'),
3279 'id' => new external_value(PARAM_INT, 'Instance id'),
3280 'updates' => new external_multiple_structure(
3281 new external_single_structure(
3282 array(
3283 'name' => new external_value(PARAM_ALPHANUMEXT, 'Name of the area updated.'),
3284 'timeupdated' => new external_value(PARAM_INT, 'Last time was updated', VALUE_OPTIONAL),
3285 'itemids' => new external_multiple_structure(
3286 new external_value(PARAM_INT, 'Instance id'),
3287 'The ids of the items updated',
3288 VALUE_OPTIONAL
3296 'warnings' => new external_warnings()
3302 * Returns description of method parameters
3304 * @return external_function_parameters
3305 * @since Moodle 3.3
3307 public static function get_updates_since_parameters() {
3308 return new external_function_parameters(
3309 array(
3310 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3311 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3312 'filter' => new external_multiple_structure(
3313 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3314 gradeitems, outcomes'),
3315 'Check only for updates in these areas', VALUE_DEFAULT, array()
3322 * Check if there are updates affecting the user for the given course since the given time stamp.
3324 * This function is a wrapper of self::check_updates for retrieving all the updates since a given time for all the activities.
3326 * @param int $courseid the list of modules to check
3327 * @param int $since check updates since this time stamp
3328 * @param array $filter check only for updates in these areas
3329 * @return array list of updates and warnings
3330 * @throws moodle_exception
3331 * @since Moodle 3.3
3333 public static function get_updates_since($courseid, $since, $filter = array()) {
3334 global $CFG, $DB;
3336 $params = self::validate_parameters(
3337 self::get_updates_since_parameters(),
3338 array(
3339 'courseid' => $courseid,
3340 'since' => $since,
3341 'filter' => $filter,
3345 $course = get_course($params['courseid']);
3346 $modinfo = get_fast_modinfo($course);
3347 $tocheck = array();
3349 // Retrieve all the visible course modules for the current user.
3350 $cms = $modinfo->get_cms();
3351 foreach ($cms as $cm) {
3352 if (!$cm->uservisible) {
3353 continue;
3355 $tocheck[] = array(
3356 'id' => $cm->id,
3357 'contextlevel' => 'module',
3358 'since' => $params['since'],
3362 return self::check_updates($course->id, $tocheck, $params['filter']);
3366 * Returns description of method result value
3368 * @return external_description
3369 * @since Moodle 3.3
3371 public static function get_updates_since_returns() {
3372 return self::check_updates_returns();
3376 * Parameters for function edit_module()
3378 * @since Moodle 3.3
3379 * @return external_function_parameters
3381 public static function edit_module_parameters() {
3382 return new external_function_parameters(
3383 array(
3384 'action' => new external_value(PARAM_ALPHA,
3385 'action: hide, show, stealth, duplicate, delete, moveleft, moveright, group...', VALUE_REQUIRED),
3386 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3387 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3392 * Performs one of the edit module actions and return new html for AJAX
3394 * Returns html to replace the current module html with, for example:
3395 * - empty string for "delete" action,
3396 * - two modules html for "duplicate" action
3397 * - updated module html for everything else
3399 * Throws exception if operation is not permitted/possible
3401 * @since Moodle 3.3
3402 * @param string $action
3403 * @param int $id
3404 * @param null|int $sectionreturn
3405 * @return string
3407 public static function edit_module($action, $id, $sectionreturn = null) {
3408 global $PAGE, $DB;
3409 // Validate and normalize parameters.
3410 $params = self::validate_parameters(self::edit_module_parameters(),
3411 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3412 $action = $params['action'];
3413 $id = $params['id'];
3414 $sectionreturn = $params['sectionreturn'];
3416 list($course, $cm) = get_course_and_cm_from_cmid($id);
3417 $modcontext = context_module::instance($cm->id);
3418 $coursecontext = context_course::instance($course->id);
3419 self::validate_context($modcontext);
3420 $courserenderer = $PAGE->get_renderer('core', 'course');
3421 $completioninfo = new completion_info($course);
3423 switch($action) {
3424 case 'hide':
3425 case 'show':
3426 case 'stealth':
3427 require_capability('moodle/course:activityvisibility', $modcontext);
3428 $visible = ($action === 'hide') ? 0 : 1;
3429 $visibleoncoursepage = ($action === 'stealth') ? 0 : 1;
3430 set_coursemodule_visible($id, $visible, $visibleoncoursepage);
3431 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3432 break;
3433 case 'duplicate':
3434 require_capability('moodle/course:manageactivities', $coursecontext);
3435 require_capability('moodle/backup:backuptargetimport', $coursecontext);
3436 require_capability('moodle/restore:restoretargetimport', $coursecontext);
3437 if (!course_allowed_module($course, $cm->modname)) {
3438 throw new moodle_exception('No permission to create that activity');
3440 if ($newcm = duplicate_module($course, $cm)) {
3441 $cm = get_fast_modinfo($course)->get_cm($id);
3442 $newcm = get_fast_modinfo($course)->get_cm($newcm->id);
3443 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn) .
3444 $courserenderer->course_section_cm_list_item($course, $completioninfo, $newcm, $sectionreturn);
3446 break;
3447 case 'groupsseparate':
3448 case 'groupsvisible':
3449 case 'groupsnone':
3450 require_capability('moodle/course:manageactivities', $modcontext);
3451 if ($action === 'groupsseparate') {
3452 $newgroupmode = SEPARATEGROUPS;
3453 } else if ($action === 'groupsvisible') {
3454 $newgroupmode = VISIBLEGROUPS;
3455 } else {
3456 $newgroupmode = NOGROUPS;
3458 if (set_coursemodule_groupmode($cm->id, $newgroupmode)) {
3459 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3461 break;
3462 case 'moveleft':
3463 case 'moveright':
3464 require_capability('moodle/course:manageactivities', $modcontext);
3465 $indent = $cm->indent + (($action === 'moveright') ? 1 : -1);
3466 if ($cm->indent >= 0) {
3467 $DB->update_record('course_modules', array('id' => $cm->id, 'indent' => $indent));
3468 rebuild_course_cache($cm->course);
3470 break;
3471 case 'delete':
3472 require_capability('moodle/course:manageactivities', $modcontext);
3473 course_delete_module($cm->id, true);
3474 return '';
3475 default:
3476 throw new coding_exception('Unrecognised action');
3479 $cm = get_fast_modinfo($course)->get_cm($id);
3480 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn);
3484 * Return structure for edit_module()
3486 * @since Moodle 3.3
3487 * @return external_description
3489 public static function edit_module_returns() {
3490 return new external_value(PARAM_RAW, 'html to replace the current module with');
3494 * Parameters for function get_module()
3496 * @since Moodle 3.3
3497 * @return external_function_parameters
3499 public static function get_module_parameters() {
3500 return new external_function_parameters(
3501 array(
3502 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3503 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3508 * Returns html for displaying one activity module on course page
3510 * @since Moodle 3.3
3511 * @param int $id
3512 * @param null|int $sectionreturn
3513 * @return string
3515 public static function get_module($id, $sectionreturn = null) {
3516 global $PAGE;
3517 // Validate and normalize parameters.
3518 $params = self::validate_parameters(self::get_module_parameters(),
3519 array('id' => $id, 'sectionreturn' => $sectionreturn));
3520 $id = $params['id'];
3521 $sectionreturn = $params['sectionreturn'];
3523 // Validate access to the course (note, this is html for the course view page, we don't validate access to the module).
3524 list($course, $cm) = get_course_and_cm_from_cmid($id);
3525 self::validate_context(context_course::instance($course->id));
3527 $courserenderer = $PAGE->get_renderer('core', 'course');
3528 $completioninfo = new completion_info($course);
3529 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn);
3533 * Return structure for edit_module()
3535 * @since Moodle 3.3
3536 * @return external_description
3538 public static function get_module_returns() {
3539 return new external_value(PARAM_RAW, 'html to replace the current module with');
3543 * Parameters for function edit_section()
3545 * @since Moodle 3.3
3546 * @return external_function_parameters
3548 public static function edit_section_parameters() {
3549 return new external_function_parameters(
3550 array(
3551 'action' => new external_value(PARAM_ALPHA, 'action: hide, show, stealth, setmarker, removemarker', VALUE_REQUIRED),
3552 'id' => new external_value(PARAM_INT, 'course section id', VALUE_REQUIRED),
3553 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3558 * Performs one of the edit section actions
3560 * @since Moodle 3.3
3561 * @param string $action
3562 * @param int $id section id
3563 * @param int $sectionreturn section to return to
3564 * @return string
3566 public static function edit_section($action, $id, $sectionreturn) {
3567 global $DB;
3568 // Validate and normalize parameters.
3569 $params = self::validate_parameters(self::edit_section_parameters(),
3570 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3571 $action = $params['action'];
3572 $id = $params['id'];
3573 $sr = $params['sectionreturn'];
3575 $section = $DB->get_record('course_sections', array('id' => $id), '*', MUST_EXIST);
3576 $coursecontext = context_course::instance($section->course);
3577 self::validate_context($coursecontext);
3579 $rv = course_get_format($section->course)->section_action($section, $action, $sectionreturn);
3580 if ($rv) {
3581 return json_encode($rv);
3582 } else {
3583 return null;
3588 * Return structure for edit_section()
3590 * @since Moodle 3.3
3591 * @return external_description
3593 public static function edit_section_returns() {
3594 return new external_value(PARAM_RAW, 'Additional data for javascript (JSON-encoded string)');
3598 * Returns description of method parameters
3600 * @return external_function_parameters
3602 public static function get_enrolled_courses_by_timeline_classification_parameters() {
3603 return new external_function_parameters(
3604 array(
3605 'classification' => new external_value(PARAM_ALPHA, 'future, inprogress, or past'),
3606 'limit' => new external_value(PARAM_INT, 'Result set limit', VALUE_DEFAULT, 0),
3607 'offset' => new external_value(PARAM_INT, 'Result set offset', VALUE_DEFAULT, 0),
3608 'sort' => new external_value(PARAM_TEXT, 'Sort string', VALUE_DEFAULT, null)
3614 * Get courses matching the given timeline classification.
3616 * NOTE: The offset applies to the unfiltered full set of courses before the classification
3617 * filtering is done.
3618 * E.g.
3619 * If the user is enrolled in 5 courses:
3620 * c1, c2, c3, c4, and c5
3621 * And c4 and c5 are 'future' courses
3623 * If a request comes in for future courses with an offset of 1 it will mean that
3624 * c1 is skipped (because the offset applies *before* the classification filtering)
3625 * and c4 and c5 will be return.
3627 * @param string $classification past, inprogress, or future
3628 * @param int $limit Result set limit
3629 * @param int $offset Offset the full course set before timeline classification is applied
3630 * @param string $sort SQL sort string for results
3631 * @return array list of courses and warnings
3632 * @throws invalid_parameter_exception
3634 public static function get_enrolled_courses_by_timeline_classification(
3635 string $classification,
3636 int $limit = 0,
3637 int $offset = 0,
3638 string $sort = null
3640 global $CFG, $PAGE, $USER;
3641 require_once($CFG->dirroot . '/course/lib.php');
3643 $params = self::validate_parameters(self::get_enrolled_courses_by_timeline_classification_parameters(),
3644 array(
3645 'classification' => $classification,
3646 'limit' => $limit,
3647 'offset' => $offset,
3648 'sort' => $sort,
3652 $classification = $params['classification'];
3653 $limit = $params['limit'];
3654 $offset = $params['offset'];
3655 $sort = $params['sort'];
3657 switch($classification) {
3658 case COURSE_TIMELINE_ALL:
3659 break;
3660 case COURSE_TIMELINE_PAST:
3661 break;
3662 case COURSE_TIMELINE_INPROGRESS:
3663 break;
3664 case COURSE_TIMELINE_FUTURE:
3665 break;
3666 default:
3667 throw new invalid_parameter_exception('Invalid classification');
3670 self::validate_context(context_user::instance($USER->id));
3672 $requiredproperties = course_summary_exporter::define_properties();
3673 $fields = join(',', array_keys($requiredproperties));
3674 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields);
3675 list($filteredcourses, $processedcount) = course_filter_courses_by_timeline_classification(
3676 $courses,
3677 $classification,
3678 $limit
3681 $renderer = $PAGE->get_renderer('core');
3682 $formattedcourses = array_map(function($course) use ($renderer) {
3683 context_helper::preload_from_record($course);
3684 $context = context_course::instance($course->id);
3685 $exporter = new course_summary_exporter($course, ['context' => $context]);
3686 return $exporter->export($renderer);
3687 }, $filteredcourses);
3689 return [
3690 'courses' => $formattedcourses,
3691 'nextoffset' => $offset + $processedcount
3696 * Returns description of method result value
3698 * @return external_description
3700 public static function get_enrolled_courses_by_timeline_classification_returns() {
3701 return new external_single_structure(
3702 array(
3703 'courses' => new external_multiple_structure(course_summary_exporter::get_read_structure(), 'Course'),
3704 'nextoffset' => new external_value(PARAM_INT, 'Offset for the next request')