MDL-63854 competencies, themes: misplaced dropdown arrows
[moodle.git] / course / externallib.php
blob8d5997663df7ed4f33480a8c053049d983b54e39
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");
32 require_once("lib.php");
34 /**
35 * Course external functions
37 * @package core_course
38 * @category external
39 * @copyright 2011 Jerome Mouneyrac
40 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
41 * @since Moodle 2.2
43 class core_course_external extends external_api {
45 /**
46 * Returns description of method parameters
48 * @return external_function_parameters
49 * @since Moodle 2.9 Options available
50 * @since Moodle 2.2
52 public static function get_course_contents_parameters() {
53 return new external_function_parameters(
54 array('courseid' => new external_value(PARAM_INT, 'course id'),
55 'options' => new external_multiple_structure (
56 new external_single_structure(
57 array(
58 'name' => new external_value(PARAM_ALPHANUM,
59 'The expected keys (value format) are:
60 excludemodules (bool) Do not return modules, return only the sections structure
61 excludecontents (bool) Do not return module contents (i.e: files inside a resource)
62 includestealthmodules (bool) Return stealth modules for students in a special
63 section (with id -1)
64 sectionid (int) Return only this section
65 sectionnumber (int) Return only this section with number (order)
66 cmid (int) Return only this module information (among the whole sections structure)
67 modname (string) Return only modules with this name "label, forum, etc..."
68 modid (int) Return only the module with this id (to be used with modname'),
69 'value' => new external_value(PARAM_RAW, 'the value of the option,
70 this param is personaly validated in the external function.')
72 ), 'Options, used since Moodle 2.9', VALUE_DEFAULT, array())
77 /**
78 * Get course contents
80 * @param int $courseid course id
81 * @param array $options Options for filtering the results, used since Moodle 2.9
82 * @return array
83 * @since Moodle 2.9 Options available
84 * @since Moodle 2.2
86 public static function get_course_contents($courseid, $options = array()) {
87 global $CFG, $DB;
88 require_once($CFG->dirroot . "/course/lib.php");
89 require_once($CFG->libdir . '/completionlib.php');
91 //validate parameter
92 $params = self::validate_parameters(self::get_course_contents_parameters(),
93 array('courseid' => $courseid, 'options' => $options));
95 $filters = array();
96 if (!empty($params['options'])) {
98 foreach ($params['options'] as $option) {
99 $name = trim($option['name']);
100 // Avoid duplicated options.
101 if (!isset($filters[$name])) {
102 switch ($name) {
103 case 'excludemodules':
104 case 'excludecontents':
105 case 'includestealthmodules':
106 $value = clean_param($option['value'], PARAM_BOOL);
107 $filters[$name] = $value;
108 break;
109 case 'sectionid':
110 case 'sectionnumber':
111 case 'cmid':
112 case 'modid':
113 $value = clean_param($option['value'], PARAM_INT);
114 if (is_numeric($value)) {
115 $filters[$name] = $value;
116 } else {
117 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
119 break;
120 case 'modname':
121 $value = clean_param($option['value'], PARAM_PLUGIN);
122 if ($value) {
123 $filters[$name] = $value;
124 } else {
125 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
127 break;
128 default:
129 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
135 //retrieve the course
136 $course = $DB->get_record('course', array('id' => $params['courseid']), '*', MUST_EXIST);
138 if ($course->id != SITEID) {
139 // Check course format exist.
140 if (!file_exists($CFG->dirroot . '/course/format/' . $course->format . '/lib.php')) {
141 throw new moodle_exception('cannotgetcoursecontents', 'webservice', '', null,
142 get_string('courseformatnotfound', 'error', $course->format));
143 } else {
144 require_once($CFG->dirroot . '/course/format/' . $course->format . '/lib.php');
148 // now security checks
149 $context = context_course::instance($course->id, IGNORE_MISSING);
150 try {
151 self::validate_context($context);
152 } catch (Exception $e) {
153 $exceptionparam = new stdClass();
154 $exceptionparam->message = $e->getMessage();
155 $exceptionparam->courseid = $course->id;
156 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
159 $canupdatecourse = has_capability('moodle/course:update', $context);
161 //create return value
162 $coursecontents = array();
164 if ($canupdatecourse or $course->visible
165 or has_capability('moodle/course:viewhiddencourses', $context)) {
167 //retrieve sections
168 $modinfo = get_fast_modinfo($course);
169 $sections = $modinfo->get_section_info_all();
170 $coursenumsections = course_get_format($course)->get_last_section_number();
171 $stealthmodules = array(); // Array to keep all the modules available but not visible in a course section/topic.
173 $completioninfo = new completion_info($course);
175 //for each sections (first displayed to last displayed)
176 $modinfosections = $modinfo->get_sections();
177 foreach ($sections as $key => $section) {
179 // This becomes true when we are filtering and we found the value to filter with.
180 $sectionfound = false;
182 // Filter by section id.
183 if (!empty($filters['sectionid'])) {
184 if ($section->id != $filters['sectionid']) {
185 continue;
186 } else {
187 $sectionfound = true;
191 // Filter by section number. Note that 0 is a valid section number.
192 if (isset($filters['sectionnumber'])) {
193 if ($key != $filters['sectionnumber']) {
194 continue;
195 } else {
196 $sectionfound = true;
200 // reset $sectioncontents
201 $sectionvalues = array();
202 $sectionvalues['id'] = $section->id;
203 $sectionvalues['name'] = get_section_name($course, $section);
204 $sectionvalues['visible'] = $section->visible;
206 $options = (object) array('noclean' => true);
207 list($sectionvalues['summary'], $sectionvalues['summaryformat']) =
208 external_format_text($section->summary, $section->summaryformat,
209 $context->id, 'course', 'section', $section->id, $options);
210 $sectionvalues['section'] = $section->section;
211 $sectionvalues['hiddenbynumsections'] = $section->section > $coursenumsections ? 1 : 0;
212 $sectionvalues['uservisible'] = $section->uservisible;
213 if (!empty($section->availableinfo)) {
214 $sectionvalues['availabilityinfo'] = \core_availability\info::format_info($section->availableinfo, $course);
217 $sectioncontents = array();
219 // For each module of the section.
220 if (empty($filters['excludemodules']) and !empty($modinfosections[$section->section])) {
221 foreach ($modinfosections[$section->section] as $cmid) {
222 $cm = $modinfo->cms[$cmid];
224 // Stop here if the module is not visible to the user on the course main page:
225 // The user can't access the module and the user can't view the module on the course page.
226 if (!$cm->uservisible && !$cm->is_visible_on_course_page()) {
227 continue;
230 // This becomes true when we are filtering and we found the value to filter with.
231 $modfound = false;
233 // Filter by cmid.
234 if (!empty($filters['cmid'])) {
235 if ($cmid != $filters['cmid']) {
236 continue;
237 } else {
238 $modfound = true;
242 // Filter by module name and id.
243 if (!empty($filters['modname'])) {
244 if ($cm->modname != $filters['modname']) {
245 continue;
246 } else if (!empty($filters['modid'])) {
247 if ($cm->instance != $filters['modid']) {
248 continue;
249 } else {
250 // Note that if we are only filtering by modname we don't break the loop.
251 $modfound = true;
256 $module = array();
258 $modcontext = context_module::instance($cm->id);
260 //common info (for people being able to see the module or availability dates)
261 $module['id'] = $cm->id;
262 $module['name'] = external_format_string($cm->name, $modcontext->id);
263 $module['instance'] = $cm->instance;
264 $module['modname'] = $cm->modname;
265 $module['modplural'] = $cm->modplural;
266 $module['modicon'] = $cm->get_icon_url()->out(false);
267 $module['indent'] = $cm->indent;
268 $module['onclick'] = $cm->onclick;
269 $module['afterlink'] = $cm->afterlink;
270 $module['customdata'] = json_encode($cm->customdata);
271 $module['completion'] = $cm->completion;
273 // Check module completion.
274 $completion = $completioninfo->is_enabled($cm);
275 if ($completion != COMPLETION_DISABLED) {
276 $completiondata = $completioninfo->get_data($cm, true);
277 $module['completiondata'] = array(
278 'state' => $completiondata->completionstate,
279 'timecompleted' => $completiondata->timemodified,
280 'overrideby' => $completiondata->overrideby
284 if (!empty($cm->showdescription) or $cm->modname == 'label') {
285 // We want to use the external format. However from reading get_formatted_content(), $cm->content format is always FORMAT_HTML.
286 $options = array('noclean' => true);
287 list($module['description'], $descriptionformat) = external_format_text($cm->content,
288 FORMAT_HTML, $modcontext->id, $cm->modname, 'intro', $cm->id, $options);
291 //url of the module
292 $url = $cm->url;
293 if ($url) { //labels don't have url
294 $module['url'] = $url->out(false);
297 $canviewhidden = has_capability('moodle/course:viewhiddenactivities',
298 context_module::instance($cm->id));
299 //user that can view hidden module should know about the visibility
300 $module['visible'] = $cm->visible;
301 $module['visibleoncoursepage'] = $cm->visibleoncoursepage;
302 $module['uservisible'] = $cm->uservisible;
303 if (!empty($cm->availableinfo)) {
304 $module['availabilityinfo'] = \core_availability\info::format_info($cm->availableinfo, $course);
307 // Availability date (also send to user who can see hidden module).
308 if ($CFG->enableavailability && ($canviewhidden || $canupdatecourse)) {
309 $module['availability'] = $cm->availability;
312 // Return contents only if the user can access to the module.
313 if ($cm->uservisible) {
314 $baseurl = 'webservice/pluginfile.php';
316 // Call $modulename_export_contents (each module callback take care about checking the capabilities).
317 require_once($CFG->dirroot . '/mod/' . $cm->modname . '/lib.php');
318 $getcontentfunction = $cm->modname.'_export_contents';
319 if (function_exists($getcontentfunction)) {
320 if (empty($filters['excludecontents']) and $contents = $getcontentfunction($cm, $baseurl)) {
321 $module['contents'] = $contents;
322 } else {
323 $module['contents'] = array();
328 // Assign result to $sectioncontents, there is an exception,
329 // stealth activities in non-visible sections for students go to a special section.
330 if (!empty($filters['includestealthmodules']) && !$section->uservisible && $cm->is_stealth()) {
331 $stealthmodules[] = $module;
332 } else {
333 $sectioncontents[] = $module;
336 // If we just did a filtering, break the loop.
337 if ($modfound) {
338 break;
343 $sectionvalues['modules'] = $sectioncontents;
345 // assign result to $coursecontents
346 $coursecontents[$key] = $sectionvalues;
348 // Break the loop if we are filtering.
349 if ($sectionfound) {
350 break;
354 // Now that we have iterated over all the sections and activities, check the visibility.
355 // We didn't this before to be able to retrieve stealth activities.
356 foreach ($coursecontents as $sectionnumber => $sectioncontents) {
357 $section = $sections[$sectionnumber];
358 // Show the section if the user is permitted to access it, OR if it's not available
359 // but there is some available info text which explains the reason & should display.
360 $showsection = $section->uservisible ||
361 ($section->visible && !$section->available &&
362 !empty($section->availableinfo));
364 if (!$showsection) {
365 unset($coursecontents[$sectionnumber]);
366 continue;
369 // Remove modules information if the section is not visible for the user.
370 if (!$section->uservisible) {
371 $coursecontents[$sectionnumber]['modules'] = array();
375 // Include stealth modules in special section (without any info).
376 if (!empty($stealthmodules)) {
377 $coursecontents[] = array(
378 'id' => -1,
379 'name' => '',
380 'summary' => '',
381 'summaryformat' => FORMAT_MOODLE,
382 'modules' => $stealthmodules
387 return $coursecontents;
391 * Returns description of method result value
393 * @return external_description
394 * @since Moodle 2.2
396 public static function get_course_contents_returns() {
397 return new external_multiple_structure(
398 new external_single_structure(
399 array(
400 'id' => new external_value(PARAM_INT, 'Section ID'),
401 'name' => new external_value(PARAM_TEXT, 'Section name'),
402 'visible' => new external_value(PARAM_INT, 'is the section visible', VALUE_OPTIONAL),
403 'summary' => new external_value(PARAM_RAW, 'Section description'),
404 'summaryformat' => new external_format_value('summary'),
405 'section' => new external_value(PARAM_INT, 'Section number inside the course', VALUE_OPTIONAL),
406 'hiddenbynumsections' => new external_value(PARAM_INT, 'Whether is a section hidden in the course format',
407 VALUE_OPTIONAL),
408 'uservisible' => new external_value(PARAM_BOOL, 'Is the section visible for the user?', VALUE_OPTIONAL),
409 'availabilityinfo' => new external_value(PARAM_RAW, 'Availability information.', VALUE_OPTIONAL),
410 'modules' => new external_multiple_structure(
411 new external_single_structure(
412 array(
413 'id' => new external_value(PARAM_INT, 'activity id'),
414 'url' => new external_value(PARAM_URL, 'activity url', VALUE_OPTIONAL),
415 'name' => new external_value(PARAM_RAW, 'activity module name'),
416 'instance' => new external_value(PARAM_INT, 'instance id', VALUE_OPTIONAL),
417 'description' => new external_value(PARAM_RAW, 'activity description', VALUE_OPTIONAL),
418 'visible' => new external_value(PARAM_INT, 'is the module visible', VALUE_OPTIONAL),
419 'uservisible' => new external_value(PARAM_BOOL, 'Is the module visible for the user?',
420 VALUE_OPTIONAL),
421 'availabilityinfo' => new external_value(PARAM_RAW, 'Availability information.',
422 VALUE_OPTIONAL),
423 'visibleoncoursepage' => new external_value(PARAM_INT, 'is the module visible on course page',
424 VALUE_OPTIONAL),
425 'modicon' => new external_value(PARAM_URL, 'activity icon url'),
426 'modname' => new external_value(PARAM_PLUGIN, 'activity module type'),
427 'modplural' => new external_value(PARAM_TEXT, 'activity module plural name'),
428 'availability' => new external_value(PARAM_RAW, 'module availability settings', VALUE_OPTIONAL),
429 'indent' => new external_value(PARAM_INT, 'number of identation in the site'),
430 'onclick' => new external_value(PARAM_RAW, 'Onclick action.', VALUE_OPTIONAL),
431 'afterlink' => new external_value(PARAM_RAW, 'After link info to be displayed.',
432 VALUE_OPTIONAL),
433 'customdata' => new external_value(PARAM_RAW, 'Custom data (JSON encoded).', VALUE_OPTIONAL),
434 'completion' => new external_value(PARAM_INT, 'Type of completion tracking:
435 0 means none, 1 manual, 2 automatic.', VALUE_OPTIONAL),
436 'completiondata' => new external_single_structure(
437 array(
438 'state' => new external_value(PARAM_INT, 'Completion state value:
439 0 means incomplete, 1 complete, 2 complete pass, 3 complete fail'),
440 'timecompleted' => new external_value(PARAM_INT, 'Timestamp for completion status.'),
441 'overrideby' => new external_value(PARAM_INT, 'The user id who has overriden the
442 status.'),
443 ), 'Module completion data.', VALUE_OPTIONAL
445 'contents' => new external_multiple_structure(
446 new external_single_structure(
447 array(
448 // content info
449 'type'=> new external_value(PARAM_TEXT, 'a file or a folder or external link'),
450 'filename'=> new external_value(PARAM_FILE, 'filename'),
451 'filepath'=> new external_value(PARAM_PATH, 'filepath'),
452 'filesize'=> new external_value(PARAM_INT, 'filesize'),
453 'fileurl' => new external_value(PARAM_URL, 'downloadable file url', VALUE_OPTIONAL),
454 'content' => new external_value(PARAM_RAW, 'Raw content, will be used when type is content', VALUE_OPTIONAL),
455 'timecreated' => new external_value(PARAM_INT, 'Time created'),
456 'timemodified' => new external_value(PARAM_INT, 'Time modified'),
457 'sortorder' => new external_value(PARAM_INT, 'Content sort order'),
458 'mimetype' => new external_value(PARAM_RAW, 'File mime type.', VALUE_OPTIONAL),
459 'isexternalfile' => new external_value(PARAM_BOOL, 'Whether is an external file.',
460 VALUE_OPTIONAL),
461 'repositorytype' => new external_value(PARAM_PLUGIN, 'The repository type for external files.',
462 VALUE_OPTIONAL),
464 // copyright related info
465 'userid' => new external_value(PARAM_INT, 'User who added this content to moodle'),
466 'author' => new external_value(PARAM_TEXT, 'Content owner'),
467 'license' => new external_value(PARAM_TEXT, 'Content license'),
469 ), VALUE_DEFAULT, array()
472 ), 'list of module'
480 * Returns description of method parameters
482 * @return external_function_parameters
483 * @since Moodle 2.3
485 public static function get_courses_parameters() {
486 return new external_function_parameters(
487 array('options' => new external_single_structure(
488 array('ids' => new external_multiple_structure(
489 new external_value(PARAM_INT, 'Course id')
490 , 'List of course id. If empty return all courses
491 except front page course.',
492 VALUE_OPTIONAL)
493 ), 'options - operator OR is used', VALUE_DEFAULT, array())
499 * Get courses
501 * @param array $options It contains an array (list of ids)
502 * @return array
503 * @since Moodle 2.2
505 public static function get_courses($options = array()) {
506 global $CFG, $DB;
507 require_once($CFG->dirroot . "/course/lib.php");
509 //validate parameter
510 $params = self::validate_parameters(self::get_courses_parameters(),
511 array('options' => $options));
513 //retrieve courses
514 if (!array_key_exists('ids', $params['options'])
515 or empty($params['options']['ids'])) {
516 $courses = $DB->get_records('course');
517 } else {
518 $courses = $DB->get_records_list('course', 'id', $params['options']['ids']);
521 //create return value
522 $coursesinfo = array();
523 foreach ($courses as $course) {
525 // now security checks
526 $context = context_course::instance($course->id, IGNORE_MISSING);
527 $courseformatoptions = course_get_format($course)->get_format_options();
528 try {
529 self::validate_context($context);
530 } catch (Exception $e) {
531 $exceptionparam = new stdClass();
532 $exceptionparam->message = $e->getMessage();
533 $exceptionparam->courseid = $course->id;
534 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
536 if ($course->id != SITEID) {
537 require_capability('moodle/course:view', $context);
540 $courseinfo = array();
541 $courseinfo['id'] = $course->id;
542 $courseinfo['fullname'] = external_format_string($course->fullname, $context->id);
543 $courseinfo['shortname'] = external_format_string($course->shortname, $context->id);
544 $courseinfo['displayname'] = external_format_string(get_course_display_name_for_list($course), $context->id);
545 $courseinfo['categoryid'] = $course->category;
546 list($courseinfo['summary'], $courseinfo['summaryformat']) =
547 external_format_text($course->summary, $course->summaryformat, $context->id, 'course', 'summary', 0);
548 $courseinfo['format'] = $course->format;
549 $courseinfo['startdate'] = $course->startdate;
550 $courseinfo['enddate'] = $course->enddate;
551 if (array_key_exists('numsections', $courseformatoptions)) {
552 // For backward-compartibility
553 $courseinfo['numsections'] = $courseformatoptions['numsections'];
556 //some field should be returned only if the user has update permission
557 $courseadmin = has_capability('moodle/course:update', $context);
558 if ($courseadmin) {
559 $courseinfo['categorysortorder'] = $course->sortorder;
560 $courseinfo['idnumber'] = $course->idnumber;
561 $courseinfo['showgrades'] = $course->showgrades;
562 $courseinfo['showreports'] = $course->showreports;
563 $courseinfo['newsitems'] = $course->newsitems;
564 $courseinfo['visible'] = $course->visible;
565 $courseinfo['maxbytes'] = $course->maxbytes;
566 if (array_key_exists('hiddensections', $courseformatoptions)) {
567 // For backward-compartibility
568 $courseinfo['hiddensections'] = $courseformatoptions['hiddensections'];
570 // Return numsections for backward-compatibility with clients who expect it.
571 $courseinfo['numsections'] = course_get_format($course)->get_last_section_number();
572 $courseinfo['groupmode'] = $course->groupmode;
573 $courseinfo['groupmodeforce'] = $course->groupmodeforce;
574 $courseinfo['defaultgroupingid'] = $course->defaultgroupingid;
575 $courseinfo['lang'] = clean_param($course->lang, PARAM_LANG);
576 $courseinfo['timecreated'] = $course->timecreated;
577 $courseinfo['timemodified'] = $course->timemodified;
578 $courseinfo['forcetheme'] = clean_param($course->theme, PARAM_THEME);
579 $courseinfo['enablecompletion'] = $course->enablecompletion;
580 $courseinfo['completionnotify'] = $course->completionnotify;
581 $courseinfo['courseformatoptions'] = array();
582 foreach ($courseformatoptions as $key => $value) {
583 $courseinfo['courseformatoptions'][] = array(
584 'name' => $key,
585 'value' => $value
590 if ($courseadmin or $course->visible
591 or has_capability('moodle/course:viewhiddencourses', $context)) {
592 $coursesinfo[] = $courseinfo;
596 return $coursesinfo;
600 * Returns description of method result value
602 * @return external_description
603 * @since Moodle 2.2
605 public static function get_courses_returns() {
606 return new external_multiple_structure(
607 new external_single_structure(
608 array(
609 'id' => new external_value(PARAM_INT, 'course id'),
610 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
611 'categoryid' => new external_value(PARAM_INT, 'category id'),
612 'categorysortorder' => new external_value(PARAM_INT,
613 'sort order into the category', VALUE_OPTIONAL),
614 'fullname' => new external_value(PARAM_TEXT, 'full name'),
615 'displayname' => new external_value(PARAM_TEXT, 'course display name'),
616 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
617 'summary' => new external_value(PARAM_RAW, 'summary'),
618 'summaryformat' => new external_format_value('summary'),
619 'format' => new external_value(PARAM_PLUGIN,
620 'course format: weeks, topics, social, site,..'),
621 'showgrades' => new external_value(PARAM_INT,
622 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
623 'newsitems' => new external_value(PARAM_INT,
624 'number of recent items appearing on the course page', VALUE_OPTIONAL),
625 'startdate' => new external_value(PARAM_INT,
626 'timestamp when the course start'),
627 'enddate' => new external_value(PARAM_INT,
628 'timestamp when the course end'),
629 'numsections' => new external_value(PARAM_INT,
630 '(deprecated, use courseformatoptions) number of weeks/topics',
631 VALUE_OPTIONAL),
632 'maxbytes' => new external_value(PARAM_INT,
633 'largest size of file that can be uploaded into the course',
634 VALUE_OPTIONAL),
635 'showreports' => new external_value(PARAM_INT,
636 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
637 'visible' => new external_value(PARAM_INT,
638 '1: available to student, 0:not available', VALUE_OPTIONAL),
639 'hiddensections' => new external_value(PARAM_INT,
640 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
641 VALUE_OPTIONAL),
642 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
643 VALUE_OPTIONAL),
644 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
645 VALUE_OPTIONAL),
646 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
647 VALUE_OPTIONAL),
648 'timecreated' => new external_value(PARAM_INT,
649 'timestamp when the course have been created', VALUE_OPTIONAL),
650 'timemodified' => new external_value(PARAM_INT,
651 'timestamp when the course have been modified', VALUE_OPTIONAL),
652 'enablecompletion' => new external_value(PARAM_INT,
653 'Enabled, control via completion and activity settings. Disbaled,
654 not shown in activity settings.',
655 VALUE_OPTIONAL),
656 'completionnotify' => new external_value(PARAM_INT,
657 '1: yes 0: no', VALUE_OPTIONAL),
658 'lang' => new external_value(PARAM_SAFEDIR,
659 'forced course language', VALUE_OPTIONAL),
660 'forcetheme' => new external_value(PARAM_PLUGIN,
661 'name of the force theme', VALUE_OPTIONAL),
662 'courseformatoptions' => new external_multiple_structure(
663 new external_single_structure(
664 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
665 'value' => new external_value(PARAM_RAW, 'course format option value')
667 'additional options for particular course format', VALUE_OPTIONAL
669 ), 'course'
675 * Returns description of method parameters
677 * @return external_function_parameters
678 * @since Moodle 2.2
680 public static function create_courses_parameters() {
681 $courseconfig = get_config('moodlecourse'); //needed for many default values
682 return new external_function_parameters(
683 array(
684 'courses' => new external_multiple_structure(
685 new external_single_structure(
686 array(
687 'fullname' => new external_value(PARAM_TEXT, 'full name'),
688 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
689 'categoryid' => new external_value(PARAM_INT, 'category id'),
690 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
691 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
692 'summaryformat' => new external_format_value('summary', VALUE_DEFAULT),
693 'format' => new external_value(PARAM_PLUGIN,
694 'course format: weeks, topics, social, site,..',
695 VALUE_DEFAULT, $courseconfig->format),
696 'showgrades' => new external_value(PARAM_INT,
697 '1 if grades are shown, otherwise 0', VALUE_DEFAULT,
698 $courseconfig->showgrades),
699 'newsitems' => new external_value(PARAM_INT,
700 'number of recent items appearing on the course page',
701 VALUE_DEFAULT, $courseconfig->newsitems),
702 'startdate' => new external_value(PARAM_INT,
703 'timestamp when the course start', VALUE_OPTIONAL),
704 'enddate' => new external_value(PARAM_INT,
705 'timestamp when the course end', VALUE_OPTIONAL),
706 'numsections' => new external_value(PARAM_INT,
707 '(deprecated, use courseformatoptions) number of weeks/topics',
708 VALUE_OPTIONAL),
709 'maxbytes' => new external_value(PARAM_INT,
710 'largest size of file that can be uploaded into the course',
711 VALUE_DEFAULT, $courseconfig->maxbytes),
712 'showreports' => new external_value(PARAM_INT,
713 'are activity report shown (yes = 1, no =0)', VALUE_DEFAULT,
714 $courseconfig->showreports),
715 'visible' => new external_value(PARAM_INT,
716 '1: available to student, 0:not available', VALUE_OPTIONAL),
717 'hiddensections' => new external_value(PARAM_INT,
718 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
719 VALUE_OPTIONAL),
720 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
721 VALUE_DEFAULT, $courseconfig->groupmode),
722 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
723 VALUE_DEFAULT, $courseconfig->groupmodeforce),
724 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
725 VALUE_DEFAULT, 0),
726 'enablecompletion' => new external_value(PARAM_INT,
727 'Enabled, control via completion and activity settings. Disabled,
728 not shown in activity settings.',
729 VALUE_OPTIONAL),
730 'completionnotify' => new external_value(PARAM_INT,
731 '1: yes 0: no', VALUE_OPTIONAL),
732 'lang' => new external_value(PARAM_SAFEDIR,
733 'forced course language', VALUE_OPTIONAL),
734 'forcetheme' => new external_value(PARAM_PLUGIN,
735 'name of the force theme', VALUE_OPTIONAL),
736 'courseformatoptions' => new external_multiple_structure(
737 new external_single_structure(
738 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
739 'value' => new external_value(PARAM_RAW, 'course format option value')
741 'additional options for particular course format', VALUE_OPTIONAL),
743 ), 'courses to create'
750 * Create courses
752 * @param array $courses
753 * @return array courses (id and shortname only)
754 * @since Moodle 2.2
756 public static function create_courses($courses) {
757 global $CFG, $DB;
758 require_once($CFG->dirroot . "/course/lib.php");
759 require_once($CFG->libdir . '/completionlib.php');
761 $params = self::validate_parameters(self::create_courses_parameters(),
762 array('courses' => $courses));
764 $availablethemes = core_component::get_plugin_list('theme');
765 $availablelangs = get_string_manager()->get_list_of_translations();
767 $transaction = $DB->start_delegated_transaction();
769 foreach ($params['courses'] as $course) {
771 // Ensure the current user is allowed to run this function
772 $context = context_coursecat::instance($course['categoryid'], IGNORE_MISSING);
773 try {
774 self::validate_context($context);
775 } catch (Exception $e) {
776 $exceptionparam = new stdClass();
777 $exceptionparam->message = $e->getMessage();
778 $exceptionparam->catid = $course['categoryid'];
779 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
781 require_capability('moodle/course:create', $context);
783 // Make sure lang is valid
784 if (array_key_exists('lang', $course)) {
785 if (empty($availablelangs[$course['lang']])) {
786 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
788 if (!has_capability('moodle/course:setforcedlanguage', $context)) {
789 unset($course['lang']);
793 // Make sure theme is valid
794 if (array_key_exists('forcetheme', $course)) {
795 if (!empty($CFG->allowcoursethemes)) {
796 if (empty($availablethemes[$course['forcetheme']])) {
797 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
798 } else {
799 $course['theme'] = $course['forcetheme'];
804 //force visibility if ws user doesn't have the permission to set it
805 $category = $DB->get_record('course_categories', array('id' => $course['categoryid']));
806 if (!has_capability('moodle/course:visibility', $context)) {
807 $course['visible'] = $category->visible;
810 //set default value for completion
811 $courseconfig = get_config('moodlecourse');
812 if (completion_info::is_enabled_for_site()) {
813 if (!array_key_exists('enablecompletion', $course)) {
814 $course['enablecompletion'] = $courseconfig->enablecompletion;
816 } else {
817 $course['enablecompletion'] = 0;
820 $course['category'] = $course['categoryid'];
822 // Summary format.
823 $course['summaryformat'] = external_validate_format($course['summaryformat']);
825 if (!empty($course['courseformatoptions'])) {
826 foreach ($course['courseformatoptions'] as $option) {
827 $course[$option['name']] = $option['value'];
831 //Note: create_course() core function check shortname, idnumber, category
832 $course['id'] = create_course((object) $course)->id;
834 $resultcourses[] = array('id' => $course['id'], 'shortname' => $course['shortname']);
837 $transaction->allow_commit();
839 return $resultcourses;
843 * Returns description of method result value
845 * @return external_description
846 * @since Moodle 2.2
848 public static function create_courses_returns() {
849 return new external_multiple_structure(
850 new external_single_structure(
851 array(
852 'id' => new external_value(PARAM_INT, 'course id'),
853 'shortname' => new external_value(PARAM_TEXT, 'short name'),
860 * Update courses
862 * @return external_function_parameters
863 * @since Moodle 2.5
865 public static function update_courses_parameters() {
866 return new external_function_parameters(
867 array(
868 'courses' => new external_multiple_structure(
869 new external_single_structure(
870 array(
871 'id' => new external_value(PARAM_INT, 'ID of the course'),
872 'fullname' => new external_value(PARAM_TEXT, 'full name', VALUE_OPTIONAL),
873 'shortname' => new external_value(PARAM_TEXT, 'course short name', VALUE_OPTIONAL),
874 'categoryid' => new external_value(PARAM_INT, 'category id', VALUE_OPTIONAL),
875 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
876 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
877 'summaryformat' => new external_format_value('summary', VALUE_OPTIONAL),
878 'format' => new external_value(PARAM_PLUGIN,
879 'course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
880 'showgrades' => new external_value(PARAM_INT,
881 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
882 'newsitems' => new external_value(PARAM_INT,
883 'number of recent items appearing on the course page', VALUE_OPTIONAL),
884 'startdate' => new external_value(PARAM_INT,
885 'timestamp when the course start', VALUE_OPTIONAL),
886 'enddate' => new external_value(PARAM_INT,
887 'timestamp when the course end', VALUE_OPTIONAL),
888 'numsections' => new external_value(PARAM_INT,
889 '(deprecated, use courseformatoptions) number of weeks/topics', VALUE_OPTIONAL),
890 'maxbytes' => new external_value(PARAM_INT,
891 'largest size of file that can be uploaded into the course', VALUE_OPTIONAL),
892 'showreports' => new external_value(PARAM_INT,
893 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
894 'visible' => new external_value(PARAM_INT,
895 '1: available to student, 0:not available', VALUE_OPTIONAL),
896 'hiddensections' => new external_value(PARAM_INT,
897 '(deprecated, use courseformatoptions) How the hidden sections in the course are
898 displayed to students', VALUE_OPTIONAL),
899 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
900 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
901 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
902 'enablecompletion' => new external_value(PARAM_INT,
903 'Enabled, control via completion and activity settings. Disabled,
904 not shown in activity settings.', VALUE_OPTIONAL),
905 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
906 'lang' => new external_value(PARAM_SAFEDIR, 'forced course language', VALUE_OPTIONAL),
907 'forcetheme' => new external_value(PARAM_PLUGIN, 'name of the force theme', VALUE_OPTIONAL),
908 'courseformatoptions' => new external_multiple_structure(
909 new external_single_structure(
910 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
911 'value' => new external_value(PARAM_RAW, 'course format option value')
913 'additional options for particular course format', VALUE_OPTIONAL),
915 ), 'courses to update'
922 * Update courses
924 * @param array $courses
925 * @since Moodle 2.5
927 public static function update_courses($courses) {
928 global $CFG, $DB;
929 require_once($CFG->dirroot . "/course/lib.php");
930 $warnings = array();
932 $params = self::validate_parameters(self::update_courses_parameters(),
933 array('courses' => $courses));
935 $availablethemes = core_component::get_plugin_list('theme');
936 $availablelangs = get_string_manager()->get_list_of_translations();
938 foreach ($params['courses'] as $course) {
939 // Catch any exception while updating course and return as warning to user.
940 try {
941 // Ensure the current user is allowed to run this function.
942 $context = context_course::instance($course['id'], MUST_EXIST);
943 self::validate_context($context);
945 $oldcourse = course_get_format($course['id'])->get_course();
947 require_capability('moodle/course:update', $context);
949 // Check if user can change category.
950 if (array_key_exists('categoryid', $course) && ($oldcourse->category != $course['categoryid'])) {
951 require_capability('moodle/course:changecategory', $context);
952 $course['category'] = $course['categoryid'];
955 // Check if the user can change fullname.
956 if (array_key_exists('fullname', $course) && ($oldcourse->fullname != $course['fullname'])) {
957 require_capability('moodle/course:changefullname', $context);
960 // Check if the user can change shortname.
961 if (array_key_exists('shortname', $course) && ($oldcourse->shortname != $course['shortname'])) {
962 require_capability('moodle/course:changeshortname', $context);
965 // Check if the user can change the idnumber.
966 if (array_key_exists('idnumber', $course) && ($oldcourse->idnumber != $course['idnumber'])) {
967 require_capability('moodle/course:changeidnumber', $context);
970 // Check if user can change summary.
971 if (array_key_exists('summary', $course) && ($oldcourse->summary != $course['summary'])) {
972 require_capability('moodle/course:changesummary', $context);
975 // Summary format.
976 if (array_key_exists('summaryformat', $course) && ($oldcourse->summaryformat != $course['summaryformat'])) {
977 require_capability('moodle/course:changesummary', $context);
978 $course['summaryformat'] = external_validate_format($course['summaryformat']);
981 // Check if user can change visibility.
982 if (array_key_exists('visible', $course) && ($oldcourse->visible != $course['visible'])) {
983 require_capability('moodle/course:visibility', $context);
986 // Make sure lang is valid.
987 if (array_key_exists('lang', $course) && ($oldcourse->lang != $course['lang'])) {
988 require_capability('moodle/course:setforcedlanguage', $context);
989 if (empty($availablelangs[$course['lang']])) {
990 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
994 // Make sure theme is valid.
995 if (array_key_exists('forcetheme', $course)) {
996 if (!empty($CFG->allowcoursethemes)) {
997 if (empty($availablethemes[$course['forcetheme']])) {
998 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
999 } else {
1000 $course['theme'] = $course['forcetheme'];
1005 // Make sure completion is enabled before setting it.
1006 if (array_key_exists('enabledcompletion', $course) && !completion_info::is_enabled_for_site()) {
1007 $course['enabledcompletion'] = 0;
1010 // Make sure maxbytes are less then CFG->maxbytes.
1011 if (array_key_exists('maxbytes', $course)) {
1012 // We allow updates back to 0 max bytes, a special value denoting the course uses the site limit.
1013 // Otherwise, either use the size specified, or cap at the max size for the course.
1014 if ($course['maxbytes'] != 0) {
1015 $course['maxbytes'] = get_max_upload_file_size($CFG->maxbytes, $course['maxbytes']);
1019 if (!empty($course['courseformatoptions'])) {
1020 foreach ($course['courseformatoptions'] as $option) {
1021 if (isset($option['name']) && isset($option['value'])) {
1022 $course[$option['name']] = $option['value'];
1027 // Update course if user has all required capabilities.
1028 update_course((object) $course);
1029 } catch (Exception $e) {
1030 $warning = array();
1031 $warning['item'] = 'course';
1032 $warning['itemid'] = $course['id'];
1033 if ($e instanceof moodle_exception) {
1034 $warning['warningcode'] = $e->errorcode;
1035 } else {
1036 $warning['warningcode'] = $e->getCode();
1038 $warning['message'] = $e->getMessage();
1039 $warnings[] = $warning;
1043 $result = array();
1044 $result['warnings'] = $warnings;
1045 return $result;
1049 * Returns description of method result value
1051 * @return external_description
1052 * @since Moodle 2.5
1054 public static function update_courses_returns() {
1055 return new external_single_structure(
1056 array(
1057 'warnings' => new external_warnings()
1063 * Returns description of method parameters
1065 * @return external_function_parameters
1066 * @since Moodle 2.2
1068 public static function delete_courses_parameters() {
1069 return new external_function_parameters(
1070 array(
1071 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'course ID')),
1077 * Delete courses
1079 * @param array $courseids A list of course ids
1080 * @since Moodle 2.2
1082 public static function delete_courses($courseids) {
1083 global $CFG, $DB;
1084 require_once($CFG->dirroot."/course/lib.php");
1086 // Parameter validation.
1087 $params = self::validate_parameters(self::delete_courses_parameters(), array('courseids'=>$courseids));
1089 $warnings = array();
1091 foreach ($params['courseids'] as $courseid) {
1092 $course = $DB->get_record('course', array('id' => $courseid));
1094 if ($course === false) {
1095 $warnings[] = array(
1096 'item' => 'course',
1097 'itemid' => $courseid,
1098 'warningcode' => 'unknowncourseidnumber',
1099 'message' => 'Unknown course ID ' . $courseid
1101 continue;
1104 // Check if the context is valid.
1105 $coursecontext = context_course::instance($course->id);
1106 self::validate_context($coursecontext);
1108 // Check if the current user has permission.
1109 if (!can_delete_course($courseid)) {
1110 $warnings[] = array(
1111 'item' => 'course',
1112 'itemid' => $courseid,
1113 'warningcode' => 'cannotdeletecourse',
1114 'message' => 'You do not have the permission to delete this course' . $courseid
1116 continue;
1119 if (delete_course($course, false) === false) {
1120 $warnings[] = array(
1121 'item' => 'course',
1122 'itemid' => $courseid,
1123 'warningcode' => 'cannotdeletecategorycourse',
1124 'message' => 'Course ' . $courseid . ' failed to be deleted'
1126 continue;
1130 fix_course_sortorder();
1132 return array('warnings' => $warnings);
1136 * Returns description of method result value
1138 * @return external_description
1139 * @since Moodle 2.2
1141 public static function delete_courses_returns() {
1142 return new external_single_structure(
1143 array(
1144 'warnings' => new external_warnings()
1150 * Returns description of method parameters
1152 * @return external_function_parameters
1153 * @since Moodle 2.3
1155 public static function duplicate_course_parameters() {
1156 return new external_function_parameters(
1157 array(
1158 'courseid' => new external_value(PARAM_INT, 'course to duplicate id'),
1159 'fullname' => new external_value(PARAM_TEXT, 'duplicated course full name'),
1160 'shortname' => new external_value(PARAM_TEXT, 'duplicated course short name'),
1161 'categoryid' => new external_value(PARAM_INT, 'duplicated course category parent'),
1162 'visible' => new external_value(PARAM_INT, 'duplicated course visible, default to yes', VALUE_DEFAULT, 1),
1163 'options' => new external_multiple_structure(
1164 new external_single_structure(
1165 array(
1166 'name' => new external_value(PARAM_ALPHAEXT, 'The backup option name:
1167 "activities" (int) Include course activites (default to 1 that is equal to yes),
1168 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1169 "filters" (int) Include course filters (default to 1 that is equal to yes),
1170 "users" (int) Include users (default to 0 that is equal to no),
1171 "enrolments" (int) Include enrolment methods (default to 1 - restore only with users),
1172 "role_assignments" (int) Include role assignments (default to 0 that is equal to no),
1173 "comments" (int) Include user comments (default to 0 that is equal to no),
1174 "userscompletion" (int) Include user course completion information (default to 0 that is equal to no),
1175 "logs" (int) Include course logs (default to 0 that is equal to no),
1176 "grade_histories" (int) Include histories (default to 0 that is equal to no)'
1178 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1181 ), VALUE_DEFAULT, array()
1188 * Duplicate a course
1190 * @param int $courseid
1191 * @param string $fullname Duplicated course fullname
1192 * @param string $shortname Duplicated course shortname
1193 * @param int $categoryid Duplicated course parent category id
1194 * @param int $visible Duplicated course availability
1195 * @param array $options List of backup options
1196 * @return array New course info
1197 * @since Moodle 2.3
1199 public static function duplicate_course($courseid, $fullname, $shortname, $categoryid, $visible = 1, $options = array()) {
1200 global $CFG, $USER, $DB;
1201 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1202 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1204 // Parameter validation.
1205 $params = self::validate_parameters(
1206 self::duplicate_course_parameters(),
1207 array(
1208 'courseid' => $courseid,
1209 'fullname' => $fullname,
1210 'shortname' => $shortname,
1211 'categoryid' => $categoryid,
1212 'visible' => $visible,
1213 'options' => $options
1217 // Context validation.
1219 if (! ($course = $DB->get_record('course', array('id'=>$params['courseid'])))) {
1220 throw new moodle_exception('invalidcourseid', 'error');
1223 // Category where duplicated course is going to be created.
1224 $categorycontext = context_coursecat::instance($params['categoryid']);
1225 self::validate_context($categorycontext);
1227 // Course to be duplicated.
1228 $coursecontext = context_course::instance($course->id);
1229 self::validate_context($coursecontext);
1231 $backupdefaults = array(
1232 'activities' => 1,
1233 'blocks' => 1,
1234 'filters' => 1,
1235 'users' => 0,
1236 'enrolments' => backup::ENROL_WITHUSERS,
1237 'role_assignments' => 0,
1238 'comments' => 0,
1239 'userscompletion' => 0,
1240 'logs' => 0,
1241 'grade_histories' => 0
1244 $backupsettings = array();
1245 // Check for backup and restore options.
1246 if (!empty($params['options'])) {
1247 foreach ($params['options'] as $option) {
1249 // Strict check for a correct value (allways 1 or 0, true or false).
1250 $value = clean_param($option['value'], PARAM_INT);
1252 if ($value !== 0 and $value !== 1) {
1253 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1256 if (!isset($backupdefaults[$option['name']])) {
1257 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1260 $backupsettings[$option['name']] = $value;
1264 // Capability checking.
1266 // The backup controller check for this currently, this may be redundant.
1267 require_capability('moodle/course:create', $categorycontext);
1268 require_capability('moodle/restore:restorecourse', $categorycontext);
1269 require_capability('moodle/backup:backupcourse', $coursecontext);
1271 if (!empty($backupsettings['users'])) {
1272 require_capability('moodle/backup:userinfo', $coursecontext);
1273 require_capability('moodle/restore:userinfo', $categorycontext);
1276 // Check if the shortname is used.
1277 if ($foundcourses = $DB->get_records('course', array('shortname'=>$shortname))) {
1278 foreach ($foundcourses as $foundcourse) {
1279 $foundcoursenames[] = $foundcourse->fullname;
1282 $foundcoursenamestring = implode(',', $foundcoursenames);
1283 throw new moodle_exception('shortnametaken', '', '', $foundcoursenamestring);
1286 // Backup the course.
1288 $bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE,
1289 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id);
1291 foreach ($backupsettings as $name => $value) {
1292 if ($setting = $bc->get_plan()->get_setting($name)) {
1293 $bc->get_plan()->get_setting($name)->set_value($value);
1297 $backupid = $bc->get_backupid();
1298 $backupbasepath = $bc->get_plan()->get_basepath();
1300 $bc->execute_plan();
1301 $results = $bc->get_results();
1302 $file = $results['backup_destination'];
1304 $bc->destroy();
1306 // Restore the backup immediately.
1308 // Check if we need to unzip the file because the backup temp dir does not contains backup files.
1309 if (!file_exists($backupbasepath . "/moodle_backup.xml")) {
1310 $file->extract_to_pathname(get_file_packer('application/vnd.moodle.backup'), $backupbasepath);
1313 // Create new course.
1314 $newcourseid = restore_dbops::create_new_course($params['fullname'], $params['shortname'], $params['categoryid']);
1316 $rc = new restore_controller($backupid, $newcourseid,
1317 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id, backup::TARGET_NEW_COURSE);
1319 foreach ($backupsettings as $name => $value) {
1320 $setting = $rc->get_plan()->get_setting($name);
1321 if ($setting->get_status() == backup_setting::NOT_LOCKED) {
1322 $setting->set_value($value);
1326 if (!$rc->execute_precheck()) {
1327 $precheckresults = $rc->get_precheck_results();
1328 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1329 if (empty($CFG->keeptempdirectoriesonbackup)) {
1330 fulldelete($backupbasepath);
1333 $errorinfo = '';
1335 foreach ($precheckresults['errors'] as $error) {
1336 $errorinfo .= $error;
1339 if (array_key_exists('warnings', $precheckresults)) {
1340 foreach ($precheckresults['warnings'] as $warning) {
1341 $errorinfo .= $warning;
1345 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1349 $rc->execute_plan();
1350 $rc->destroy();
1352 $course = $DB->get_record('course', array('id' => $newcourseid), '*', MUST_EXIST);
1353 $course->fullname = $params['fullname'];
1354 $course->shortname = $params['shortname'];
1355 $course->visible = $params['visible'];
1357 // Set shortname and fullname back.
1358 $DB->update_record('course', $course);
1360 if (empty($CFG->keeptempdirectoriesonbackup)) {
1361 fulldelete($backupbasepath);
1364 // Delete the course backup file created by this WebService. Originally located in the course backups area.
1365 $file->delete();
1367 return array('id' => $course->id, 'shortname' => $course->shortname);
1371 * Returns description of method result value
1373 * @return external_description
1374 * @since Moodle 2.3
1376 public static function duplicate_course_returns() {
1377 return new external_single_structure(
1378 array(
1379 'id' => new external_value(PARAM_INT, 'course id'),
1380 'shortname' => new external_value(PARAM_TEXT, 'short name'),
1386 * Returns description of method parameters for import_course
1388 * @return external_function_parameters
1389 * @since Moodle 2.4
1391 public static function import_course_parameters() {
1392 return new external_function_parameters(
1393 array(
1394 'importfrom' => new external_value(PARAM_INT, 'the id of the course we are importing from'),
1395 'importto' => new external_value(PARAM_INT, 'the id of the course we are importing to'),
1396 'deletecontent' => new external_value(PARAM_INT, 'whether to delete the course content where we are importing to (default to 0 = No)', VALUE_DEFAULT, 0),
1397 'options' => new external_multiple_structure(
1398 new external_single_structure(
1399 array(
1400 'name' => new external_value(PARAM_ALPHA, 'The backup option name:
1401 "activities" (int) Include course activites (default to 1 that is equal to yes),
1402 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1403 "filters" (int) Include course filters (default to 1 that is equal to yes)'
1405 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1408 ), VALUE_DEFAULT, array()
1415 * Imports a course
1417 * @param int $importfrom The id of the course we are importing from
1418 * @param int $importto The id of the course we are importing to
1419 * @param bool $deletecontent Whether to delete the course we are importing to content
1420 * @param array $options List of backup options
1421 * @return null
1422 * @since Moodle 2.4
1424 public static function import_course($importfrom, $importto, $deletecontent = 0, $options = array()) {
1425 global $CFG, $USER, $DB;
1426 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1427 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1429 // Parameter validation.
1430 $params = self::validate_parameters(
1431 self::import_course_parameters(),
1432 array(
1433 'importfrom' => $importfrom,
1434 'importto' => $importto,
1435 'deletecontent' => $deletecontent,
1436 'options' => $options
1440 if ($params['deletecontent'] !== 0 and $params['deletecontent'] !== 1) {
1441 throw new moodle_exception('invalidextparam', 'webservice', '', $params['deletecontent']);
1444 // Context validation.
1446 if (! ($importfrom = $DB->get_record('course', array('id'=>$params['importfrom'])))) {
1447 throw new moodle_exception('invalidcourseid', 'error');
1450 if (! ($importto = $DB->get_record('course', array('id'=>$params['importto'])))) {
1451 throw new moodle_exception('invalidcourseid', 'error');
1454 $importfromcontext = context_course::instance($importfrom->id);
1455 self::validate_context($importfromcontext);
1457 $importtocontext = context_course::instance($importto->id);
1458 self::validate_context($importtocontext);
1460 $backupdefaults = array(
1461 'activities' => 1,
1462 'blocks' => 1,
1463 'filters' => 1
1466 $backupsettings = array();
1468 // Check for backup and restore options.
1469 if (!empty($params['options'])) {
1470 foreach ($params['options'] as $option) {
1472 // Strict check for a correct value (allways 1 or 0, true or false).
1473 $value = clean_param($option['value'], PARAM_INT);
1475 if ($value !== 0 and $value !== 1) {
1476 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1479 if (!isset($backupdefaults[$option['name']])) {
1480 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1483 $backupsettings[$option['name']] = $value;
1487 // Capability checking.
1489 require_capability('moodle/backup:backuptargetimport', $importfromcontext);
1490 require_capability('moodle/restore:restoretargetimport', $importtocontext);
1492 $bc = new backup_controller(backup::TYPE_1COURSE, $importfrom->id, backup::FORMAT_MOODLE,
1493 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
1495 foreach ($backupsettings as $name => $value) {
1496 $bc->get_plan()->get_setting($name)->set_value($value);
1499 $backupid = $bc->get_backupid();
1500 $backupbasepath = $bc->get_plan()->get_basepath();
1502 $bc->execute_plan();
1503 $bc->destroy();
1505 // Restore the backup immediately.
1507 // Check if we must delete the contents of the destination course.
1508 if ($params['deletecontent']) {
1509 $restoretarget = backup::TARGET_EXISTING_DELETING;
1510 } else {
1511 $restoretarget = backup::TARGET_EXISTING_ADDING;
1514 $rc = new restore_controller($backupid, $importto->id,
1515 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, $restoretarget);
1517 foreach ($backupsettings as $name => $value) {
1518 $rc->get_plan()->get_setting($name)->set_value($value);
1521 if (!$rc->execute_precheck()) {
1522 $precheckresults = $rc->get_precheck_results();
1523 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1524 if (empty($CFG->keeptempdirectoriesonbackup)) {
1525 fulldelete($backupbasepath);
1528 $errorinfo = '';
1530 foreach ($precheckresults['errors'] as $error) {
1531 $errorinfo .= $error;
1534 if (array_key_exists('warnings', $precheckresults)) {
1535 foreach ($precheckresults['warnings'] as $warning) {
1536 $errorinfo .= $warning;
1540 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1542 } else {
1543 if ($restoretarget == backup::TARGET_EXISTING_DELETING) {
1544 restore_dbops::delete_course_content($importto->id);
1548 $rc->execute_plan();
1549 $rc->destroy();
1551 if (empty($CFG->keeptempdirectoriesonbackup)) {
1552 fulldelete($backupbasepath);
1555 return null;
1559 * Returns description of method result value
1561 * @return external_description
1562 * @since Moodle 2.4
1564 public static function import_course_returns() {
1565 return null;
1569 * Returns description of method parameters
1571 * @return external_function_parameters
1572 * @since Moodle 2.3
1574 public static function get_categories_parameters() {
1575 return new external_function_parameters(
1576 array(
1577 'criteria' => new external_multiple_structure(
1578 new external_single_structure(
1579 array(
1580 'key' => new external_value(PARAM_ALPHA,
1581 'The category column to search, expected keys (value format) are:'.
1582 '"id" (int) the category id,'.
1583 '"ids" (string) category ids separated by commas,'.
1584 '"name" (string) the category name,'.
1585 '"parent" (int) the parent category id,'.
1586 '"idnumber" (string) category idnumber'.
1587 ' - user must have \'moodle/category:manage\' to search on idnumber,'.
1588 '"visible" (int) whether the returned categories must be visible or hidden. If the key is not passed,
1589 then the function return all categories that the user can see.'.
1590 ' - user must have \'moodle/category:manage\' or \'moodle/category:viewhiddencategories\' to search on visible,'.
1591 '"theme" (string) only return the categories having this theme'.
1592 ' - user must have \'moodle/category:manage\' to search on theme'),
1593 'value' => new external_value(PARAM_RAW, 'the value to match')
1595 ), 'criteria', VALUE_DEFAULT, array()
1597 'addsubcategories' => new external_value(PARAM_BOOL, 'return the sub categories infos
1598 (1 - default) otherwise only the category info (0)', VALUE_DEFAULT, 1)
1604 * Get categories
1606 * @param array $criteria Criteria to match the results
1607 * @param booln $addsubcategories obtain only the category (false) or its subcategories (true - default)
1608 * @return array list of categories
1609 * @since Moodle 2.3
1611 public static function get_categories($criteria = array(), $addsubcategories = true) {
1612 global $CFG, $DB;
1613 require_once($CFG->dirroot . "/course/lib.php");
1615 // Validate parameters.
1616 $params = self::validate_parameters(self::get_categories_parameters(),
1617 array('criteria' => $criteria, 'addsubcategories' => $addsubcategories));
1619 // Retrieve the categories.
1620 $categories = array();
1621 if (!empty($params['criteria'])) {
1623 $conditions = array();
1624 $wheres = array();
1625 foreach ($params['criteria'] as $crit) {
1626 $key = trim($crit['key']);
1628 // Trying to avoid duplicate keys.
1629 if (!isset($conditions[$key])) {
1631 $context = context_system::instance();
1632 $value = null;
1633 switch ($key) {
1634 case 'id':
1635 $value = clean_param($crit['value'], PARAM_INT);
1636 $conditions[$key] = $value;
1637 $wheres[] = $key . " = :" . $key;
1638 break;
1640 case 'ids':
1641 $value = clean_param($crit['value'], PARAM_SEQUENCE);
1642 $ids = explode(',', $value);
1643 list($sqlids, $paramids) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED);
1644 $conditions = array_merge($conditions, $paramids);
1645 $wheres[] = 'id ' . $sqlids;
1646 break;
1648 case 'idnumber':
1649 if (has_capability('moodle/category:manage', $context)) {
1650 $value = clean_param($crit['value'], PARAM_RAW);
1651 $conditions[$key] = $value;
1652 $wheres[] = $key . " = :" . $key;
1653 } else {
1654 // We must throw an exception.
1655 // Otherwise the dev client would think no idnumber exists.
1656 throw new moodle_exception('criteriaerror',
1657 'webservice', '', null,
1658 'You don\'t have the permissions to search on the "idnumber" field.');
1660 break;
1662 case 'name':
1663 $value = clean_param($crit['value'], PARAM_TEXT);
1664 $conditions[$key] = $value;
1665 $wheres[] = $key . " = :" . $key;
1666 break;
1668 case 'parent':
1669 $value = clean_param($crit['value'], PARAM_INT);
1670 $conditions[$key] = $value;
1671 $wheres[] = $key . " = :" . $key;
1672 break;
1674 case 'visible':
1675 if (has_capability('moodle/category:viewhiddencategories', $context)) {
1676 $value = clean_param($crit['value'], PARAM_INT);
1677 $conditions[$key] = $value;
1678 $wheres[] = $key . " = :" . $key;
1679 } else {
1680 throw new moodle_exception('criteriaerror',
1681 'webservice', '', null,
1682 'You don\'t have the permissions to search on the "visible" field.');
1684 break;
1686 case 'theme':
1687 if (has_capability('moodle/category:manage', $context)) {
1688 $value = clean_param($crit['value'], PARAM_THEME);
1689 $conditions[$key] = $value;
1690 $wheres[] = $key . " = :" . $key;
1691 } else {
1692 throw new moodle_exception('criteriaerror',
1693 'webservice', '', null,
1694 'You don\'t have the permissions to search on the "theme" field.');
1696 break;
1698 default:
1699 throw new moodle_exception('criteriaerror',
1700 'webservice', '', null,
1701 'You can not search on this criteria: ' . $key);
1706 if (!empty($wheres)) {
1707 $wheres = implode(" AND ", $wheres);
1709 $categories = $DB->get_records_select('course_categories', $wheres, $conditions);
1711 // Retrieve its sub subcategories (all levels).
1712 if ($categories and !empty($params['addsubcategories'])) {
1713 $newcategories = array();
1715 // Check if we required visible/theme checks.
1716 $additionalselect = '';
1717 $additionalparams = array();
1718 if (isset($conditions['visible'])) {
1719 $additionalselect .= ' AND visible = :visible';
1720 $additionalparams['visible'] = $conditions['visible'];
1722 if (isset($conditions['theme'])) {
1723 $additionalselect .= ' AND theme= :theme';
1724 $additionalparams['theme'] = $conditions['theme'];
1727 foreach ($categories as $category) {
1728 $sqlselect = $DB->sql_like('path', ':path') . $additionalselect;
1729 $sqlparams = array('path' => $category->path.'/%') + $additionalparams; // It will NOT include the specified category.
1730 $subcategories = $DB->get_records_select('course_categories', $sqlselect, $sqlparams);
1731 $newcategories = $newcategories + $subcategories; // Both arrays have integer as keys.
1733 $categories = $categories + $newcategories;
1737 } else {
1738 // Retrieve all categories in the database.
1739 $categories = $DB->get_records('course_categories');
1742 // The not returned categories. key => category id, value => reason of exclusion.
1743 $excludedcats = array();
1745 // The returned categories.
1746 $categoriesinfo = array();
1748 // We need to sort the categories by path.
1749 // The parent cats need to be checked by the algo first.
1750 usort($categories, "core_course_external::compare_categories_by_path");
1752 foreach ($categories as $category) {
1754 // Check if the category is a child of an excluded category, if yes exclude it too (excluded => do not return).
1755 $parents = explode('/', $category->path);
1756 unset($parents[0]); // First key is always empty because path start with / => /1/2/4.
1757 foreach ($parents as $parentid) {
1758 // Note: when the parent exclusion was due to the context,
1759 // the sub category could still be returned.
1760 if (isset($excludedcats[$parentid]) and $excludedcats[$parentid] != 'context') {
1761 $excludedcats[$category->id] = 'parent';
1765 // Check the user can use the category context.
1766 $context = context_coursecat::instance($category->id);
1767 try {
1768 self::validate_context($context);
1769 } catch (Exception $e) {
1770 $excludedcats[$category->id] = 'context';
1772 // If it was the requested category then throw an exception.
1773 if (isset($params['categoryid']) && $category->id == $params['categoryid']) {
1774 $exceptionparam = new stdClass();
1775 $exceptionparam->message = $e->getMessage();
1776 $exceptionparam->catid = $category->id;
1777 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
1781 // Return the category information.
1782 if (!isset($excludedcats[$category->id])) {
1784 // Final check to see if the category is visible to the user.
1785 if ($category->visible or has_capability('moodle/category:viewhiddencategories', $context)) {
1787 $categoryinfo = array();
1788 $categoryinfo['id'] = $category->id;
1789 $categoryinfo['name'] = external_format_string($category->name, $context);
1790 list($categoryinfo['description'], $categoryinfo['descriptionformat']) =
1791 external_format_text($category->description, $category->descriptionformat,
1792 $context->id, 'coursecat', 'description', null);
1793 $categoryinfo['parent'] = $category->parent;
1794 $categoryinfo['sortorder'] = $category->sortorder;
1795 $categoryinfo['coursecount'] = $category->coursecount;
1796 $categoryinfo['depth'] = $category->depth;
1797 $categoryinfo['path'] = $category->path;
1799 // Some fields only returned for admin.
1800 if (has_capability('moodle/category:manage', $context)) {
1801 $categoryinfo['idnumber'] = $category->idnumber;
1802 $categoryinfo['visible'] = $category->visible;
1803 $categoryinfo['visibleold'] = $category->visibleold;
1804 $categoryinfo['timemodified'] = $category->timemodified;
1805 $categoryinfo['theme'] = clean_param($category->theme, PARAM_THEME);
1808 $categoriesinfo[] = $categoryinfo;
1809 } else {
1810 $excludedcats[$category->id] = 'visibility';
1815 // Sorting the resulting array so it looks a bit better for the client developer.
1816 usort($categoriesinfo, "core_course_external::compare_categories_by_sortorder");
1818 return $categoriesinfo;
1822 * Sort categories array by path
1823 * private function: only used by get_categories
1825 * @param array $category1
1826 * @param array $category2
1827 * @return int result of strcmp
1828 * @since Moodle 2.3
1830 private static function compare_categories_by_path($category1, $category2) {
1831 return strcmp($category1->path, $category2->path);
1835 * Sort categories array by sortorder
1836 * private function: only used by get_categories
1838 * @param array $category1
1839 * @param array $category2
1840 * @return int result of strcmp
1841 * @since Moodle 2.3
1843 private static function compare_categories_by_sortorder($category1, $category2) {
1844 return strcmp($category1['sortorder'], $category2['sortorder']);
1848 * Returns description of method result value
1850 * @return external_description
1851 * @since Moodle 2.3
1853 public static function get_categories_returns() {
1854 return new external_multiple_structure(
1855 new external_single_structure(
1856 array(
1857 'id' => new external_value(PARAM_INT, 'category id'),
1858 'name' => new external_value(PARAM_TEXT, 'category name'),
1859 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1860 'description' => new external_value(PARAM_RAW, 'category description'),
1861 'descriptionformat' => new external_format_value('description'),
1862 'parent' => new external_value(PARAM_INT, 'parent category id'),
1863 'sortorder' => new external_value(PARAM_INT, 'category sorting order'),
1864 'coursecount' => new external_value(PARAM_INT, 'number of courses in this category'),
1865 'visible' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1866 'visibleold' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1867 'timemodified' => new external_value(PARAM_INT, 'timestamp', VALUE_OPTIONAL),
1868 'depth' => new external_value(PARAM_INT, 'category depth'),
1869 'path' => new external_value(PARAM_TEXT, 'category path'),
1870 'theme' => new external_value(PARAM_THEME, 'category theme', VALUE_OPTIONAL),
1871 ), 'List of categories'
1877 * Returns description of method parameters
1879 * @return external_function_parameters
1880 * @since Moodle 2.3
1882 public static function create_categories_parameters() {
1883 return new external_function_parameters(
1884 array(
1885 'categories' => new external_multiple_structure(
1886 new external_single_structure(
1887 array(
1888 'name' => new external_value(PARAM_TEXT, 'new category name'),
1889 'parent' => new external_value(PARAM_INT,
1890 'the parent category id inside which the new category will be created
1891 - set to 0 for a root category',
1892 VALUE_DEFAULT, 0),
1893 'idnumber' => new external_value(PARAM_RAW,
1894 'the new category idnumber', VALUE_OPTIONAL),
1895 'description' => new external_value(PARAM_RAW,
1896 'the new category description', VALUE_OPTIONAL),
1897 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
1898 'theme' => new external_value(PARAM_THEME,
1899 'the new category theme. This option must be enabled on moodle',
1900 VALUE_OPTIONAL),
1909 * Create categories
1911 * @param array $categories - see create_categories_parameters() for the array structure
1912 * @return array - see create_categories_returns() for the array structure
1913 * @since Moodle 2.3
1915 public static function create_categories($categories) {
1916 global $DB;
1918 $params = self::validate_parameters(self::create_categories_parameters(),
1919 array('categories' => $categories));
1921 $transaction = $DB->start_delegated_transaction();
1923 $createdcategories = array();
1924 foreach ($params['categories'] as $category) {
1925 if ($category['parent']) {
1926 if (!$DB->record_exists('course_categories', array('id' => $category['parent']))) {
1927 throw new moodle_exception('unknowcategory');
1929 $context = context_coursecat::instance($category['parent']);
1930 } else {
1931 $context = context_system::instance();
1933 self::validate_context($context);
1934 require_capability('moodle/category:manage', $context);
1936 // this will validate format and throw an exception if there are errors
1937 external_validate_format($category['descriptionformat']);
1939 $newcategory = core_course_category::create($category);
1940 $context = context_coursecat::instance($newcategory->id);
1942 $createdcategories[] = array(
1943 'id' => $newcategory->id,
1944 'name' => external_format_string($newcategory->name, $context),
1948 $transaction->allow_commit();
1950 return $createdcategories;
1954 * Returns description of method parameters
1956 * @return external_function_parameters
1957 * @since Moodle 2.3
1959 public static function create_categories_returns() {
1960 return new external_multiple_structure(
1961 new external_single_structure(
1962 array(
1963 'id' => new external_value(PARAM_INT, 'new category id'),
1964 'name' => new external_value(PARAM_TEXT, 'new category name'),
1971 * Returns description of method parameters
1973 * @return external_function_parameters
1974 * @since Moodle 2.3
1976 public static function update_categories_parameters() {
1977 return new external_function_parameters(
1978 array(
1979 'categories' => new external_multiple_structure(
1980 new external_single_structure(
1981 array(
1982 'id' => new external_value(PARAM_INT, 'course id'),
1983 'name' => new external_value(PARAM_TEXT, 'category name', VALUE_OPTIONAL),
1984 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1985 'parent' => new external_value(PARAM_INT, 'parent category id', VALUE_OPTIONAL),
1986 'description' => new external_value(PARAM_RAW, 'category description', VALUE_OPTIONAL),
1987 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
1988 'theme' => new external_value(PARAM_THEME,
1989 'the category theme. This option must be enabled on moodle', VALUE_OPTIONAL),
1998 * Update categories
2000 * @param array $categories The list of categories to update
2001 * @return null
2002 * @since Moodle 2.3
2004 public static function update_categories($categories) {
2005 global $DB;
2007 // Validate parameters.
2008 $params = self::validate_parameters(self::update_categories_parameters(), array('categories' => $categories));
2010 $transaction = $DB->start_delegated_transaction();
2012 foreach ($params['categories'] as $cat) {
2013 $category = core_course_category::get($cat['id']);
2015 $categorycontext = context_coursecat::instance($cat['id']);
2016 self::validate_context($categorycontext);
2017 require_capability('moodle/category:manage', $categorycontext);
2019 // this will throw an exception if descriptionformat is not valid
2020 external_validate_format($cat['descriptionformat']);
2022 $category->update($cat);
2025 $transaction->allow_commit();
2029 * Returns description of method result value
2031 * @return external_description
2032 * @since Moodle 2.3
2034 public static function update_categories_returns() {
2035 return null;
2039 * Returns description of method parameters
2041 * @return external_function_parameters
2042 * @since Moodle 2.3
2044 public static function delete_categories_parameters() {
2045 return new external_function_parameters(
2046 array(
2047 'categories' => new external_multiple_structure(
2048 new external_single_structure(
2049 array(
2050 'id' => new external_value(PARAM_INT, 'category id to delete'),
2051 'newparent' => new external_value(PARAM_INT,
2052 'the parent category to move the contents to, if specified', VALUE_OPTIONAL),
2053 'recursive' => new external_value(PARAM_BOOL, '1: recursively delete all contents inside this
2054 category, 0 (default): move contents to newparent or current parent category (except if parent is root)', VALUE_DEFAULT, 0)
2063 * Delete categories
2065 * @param array $categories A list of category ids
2066 * @return array
2067 * @since Moodle 2.3
2069 public static function delete_categories($categories) {
2070 global $CFG, $DB;
2071 require_once($CFG->dirroot . "/course/lib.php");
2073 // Validate parameters.
2074 $params = self::validate_parameters(self::delete_categories_parameters(), array('categories' => $categories));
2076 $transaction = $DB->start_delegated_transaction();
2078 foreach ($params['categories'] as $category) {
2079 $deletecat = core_course_category::get($category['id'], MUST_EXIST);
2080 $context = context_coursecat::instance($deletecat->id);
2081 require_capability('moodle/category:manage', $context);
2082 self::validate_context($context);
2083 self::validate_context(get_category_or_system_context($deletecat->parent));
2085 if ($category['recursive']) {
2086 // If recursive was specified, then we recursively delete the category's contents.
2087 if ($deletecat->can_delete_full()) {
2088 $deletecat->delete_full(false);
2089 } else {
2090 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2092 } else {
2093 // In this situation, we don't delete the category's contents, we either move it to newparent or parent.
2094 // If the parent is the root, moving is not supported (because a course must always be inside a category).
2095 // We must move to an existing category.
2096 if (!empty($category['newparent'])) {
2097 $newparentcat = core_course_category::get($category['newparent']);
2098 } else {
2099 $newparentcat = core_course_category::get($deletecat->parent);
2102 // This operation is not allowed. We must move contents to an existing category.
2103 if (!$newparentcat->id) {
2104 throw new moodle_exception('movecatcontentstoroot');
2107 self::validate_context(context_coursecat::instance($newparentcat->id));
2108 if ($deletecat->can_move_content_to($newparentcat->id)) {
2109 $deletecat->delete_move($newparentcat->id, false);
2110 } else {
2111 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2116 $transaction->allow_commit();
2120 * Returns description of method parameters
2122 * @return external_function_parameters
2123 * @since Moodle 2.3
2125 public static function delete_categories_returns() {
2126 return null;
2130 * Describes the parameters for delete_modules.
2132 * @return external_function_parameters
2133 * @since Moodle 2.5
2135 public static function delete_modules_parameters() {
2136 return new external_function_parameters (
2137 array(
2138 'cmids' => new external_multiple_structure(new external_value(PARAM_INT, 'course module ID',
2139 VALUE_REQUIRED, '', NULL_NOT_ALLOWED), 'Array of course module IDs'),
2145 * Deletes a list of provided module instances.
2147 * @param array $cmids the course module ids
2148 * @since Moodle 2.5
2150 public static function delete_modules($cmids) {
2151 global $CFG, $DB;
2153 // Require course file containing the course delete module function.
2154 require_once($CFG->dirroot . "/course/lib.php");
2156 // Clean the parameters.
2157 $params = self::validate_parameters(self::delete_modules_parameters(), array('cmids' => $cmids));
2159 // Keep track of the course ids we have performed a capability check on to avoid repeating.
2160 $arrcourseschecked = array();
2162 foreach ($params['cmids'] as $cmid) {
2163 // Get the course module.
2164 $cm = $DB->get_record('course_modules', array('id' => $cmid), '*', MUST_EXIST);
2166 // Check if we have not yet confirmed they have permission in this course.
2167 if (!in_array($cm->course, $arrcourseschecked)) {
2168 // Ensure the current user has required permission in this course.
2169 $context = context_course::instance($cm->course);
2170 self::validate_context($context);
2171 // Add to the array.
2172 $arrcourseschecked[] = $cm->course;
2175 // Ensure they can delete this module.
2176 $modcontext = context_module::instance($cm->id);
2177 require_capability('moodle/course:manageactivities', $modcontext);
2179 // Delete the module.
2180 course_delete_module($cm->id);
2185 * Describes the delete_modules return value.
2187 * @return external_single_structure
2188 * @since Moodle 2.5
2190 public static function delete_modules_returns() {
2191 return null;
2195 * Returns description of method parameters
2197 * @return external_function_parameters
2198 * @since Moodle 2.9
2200 public static function view_course_parameters() {
2201 return new external_function_parameters(
2202 array(
2203 'courseid' => new external_value(PARAM_INT, 'id of the course'),
2204 'sectionnumber' => new external_value(PARAM_INT, 'section number', VALUE_DEFAULT, 0)
2210 * Trigger the course viewed event.
2212 * @param int $courseid id of course
2213 * @param int $sectionnumber sectionnumber (0, 1, 2...)
2214 * @return array of warnings and status result
2215 * @since Moodle 2.9
2216 * @throws moodle_exception
2218 public static function view_course($courseid, $sectionnumber = 0) {
2219 global $CFG;
2220 require_once($CFG->dirroot . "/course/lib.php");
2222 $params = self::validate_parameters(self::view_course_parameters(),
2223 array(
2224 'courseid' => $courseid,
2225 'sectionnumber' => $sectionnumber
2228 $warnings = array();
2230 $course = get_course($params['courseid']);
2231 $context = context_course::instance($course->id);
2232 self::validate_context($context);
2234 if (!empty($params['sectionnumber'])) {
2236 // Get section details and check it exists.
2237 $modinfo = get_fast_modinfo($course);
2238 $coursesection = $modinfo->get_section_info($params['sectionnumber'], MUST_EXIST);
2240 // Check user is allowed to see it.
2241 if (!$coursesection->uservisible) {
2242 require_capability('moodle/course:viewhiddensections', $context);
2246 course_view($context, $params['sectionnumber']);
2248 $result = array();
2249 $result['status'] = true;
2250 $result['warnings'] = $warnings;
2251 return $result;
2255 * Returns description of method result value
2257 * @return external_description
2258 * @since Moodle 2.9
2260 public static function view_course_returns() {
2261 return new external_single_structure(
2262 array(
2263 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
2264 'warnings' => new external_warnings()
2270 * Returns description of method parameters
2272 * @return external_function_parameters
2273 * @since Moodle 3.0
2275 public static function search_courses_parameters() {
2276 return new external_function_parameters(
2277 array(
2278 'criterianame' => new external_value(PARAM_ALPHA, 'criteria name
2279 (search, modulelist (only admins), blocklist (only admins), tagid)'),
2280 'criteriavalue' => new external_value(PARAM_RAW, 'criteria value'),
2281 'page' => new external_value(PARAM_INT, 'page number (0 based)', VALUE_DEFAULT, 0),
2282 'perpage' => new external_value(PARAM_INT, 'items per page', VALUE_DEFAULT, 0),
2283 'requiredcapabilities' => new external_multiple_structure(
2284 new external_value(PARAM_CAPABILITY, 'Capability string used to filter courses by permission'),
2285 'Optional list of required capabilities (used to filter the list)', VALUE_DEFAULT, array()
2287 'limittoenrolled' => new external_value(PARAM_BOOL, 'limit to enrolled courses', VALUE_DEFAULT, 0),
2293 * Return the course information that is public (visible by every one)
2295 * @param core_course_list_element $course course in list object
2296 * @param stdClass $coursecontext course context object
2297 * @return array the course information
2298 * @since Moodle 3.2
2300 protected static function get_course_public_information(core_course_list_element $course, $coursecontext) {
2302 static $categoriescache = array();
2304 // Category information.
2305 if (!array_key_exists($course->category, $categoriescache)) {
2306 $categoriescache[$course->category] = core_course_category::get($course->category, IGNORE_MISSING);
2308 $category = $categoriescache[$course->category];
2310 // Retrieve course overview used files.
2311 $files = array();
2312 foreach ($course->get_course_overviewfiles() as $file) {
2313 $fileurl = moodle_url::make_webservice_pluginfile_url($file->get_contextid(), $file->get_component(),
2314 $file->get_filearea(), null, $file->get_filepath(),
2315 $file->get_filename())->out(false);
2316 $files[] = array(
2317 'filename' => $file->get_filename(),
2318 'fileurl' => $fileurl,
2319 'filesize' => $file->get_filesize(),
2320 'filepath' => $file->get_filepath(),
2321 'mimetype' => $file->get_mimetype(),
2322 'timemodified' => $file->get_timemodified(),
2326 // Retrieve the course contacts,
2327 // we need here the users fullname since if we are not enrolled can be difficult to obtain them via other Web Services.
2328 $coursecontacts = array();
2329 foreach ($course->get_course_contacts() as $contact) {
2330 $coursecontacts[] = array(
2331 'id' => $contact['user']->id,
2332 'fullname' => $contact['username'],
2333 'roles' => array_map(function($role){
2334 return array('id' => $role->id, 'name' => $role->displayname);
2335 }, $contact['roles']),
2336 'role' => array('id' => $contact['role']->id, 'name' => $contact['role']->displayname),
2337 'rolename' => $contact['rolename']
2341 // Allowed enrolment methods (maybe we can self-enrol).
2342 $enroltypes = array();
2343 $instances = enrol_get_instances($course->id, true);
2344 foreach ($instances as $instance) {
2345 $enroltypes[] = $instance->enrol;
2348 // Format summary.
2349 list($summary, $summaryformat) =
2350 external_format_text($course->summary, $course->summaryformat, $coursecontext->id, 'course', 'summary', null);
2352 $categoryname = '';
2353 if (!empty($category)) {
2354 $categoryname = external_format_string($category->name, $category->get_context());
2357 $displayname = get_course_display_name_for_list($course);
2358 $coursereturns = array();
2359 $coursereturns['id'] = $course->id;
2360 $coursereturns['fullname'] = external_format_string($course->fullname, $coursecontext->id);
2361 $coursereturns['displayname'] = external_format_string($displayname, $coursecontext->id);
2362 $coursereturns['shortname'] = external_format_string($course->shortname, $coursecontext->id);
2363 $coursereturns['categoryid'] = $course->category;
2364 $coursereturns['categoryname'] = $categoryname;
2365 $coursereturns['summary'] = $summary;
2366 $coursereturns['summaryformat'] = $summaryformat;
2367 $coursereturns['summaryfiles'] = external_util::get_area_files($coursecontext->id, 'course', 'summary', false, false);
2368 $coursereturns['overviewfiles'] = $files;
2369 $coursereturns['contacts'] = $coursecontacts;
2370 $coursereturns['enrollmentmethods'] = $enroltypes;
2371 $coursereturns['sortorder'] = $course->sortorder;
2372 return $coursereturns;
2376 * Search courses following the specified criteria.
2378 * @param string $criterianame Criteria name (search, modulelist (only admins), blocklist (only admins), tagid)
2379 * @param string $criteriavalue Criteria value
2380 * @param int $page Page number (for pagination)
2381 * @param int $perpage Items per page
2382 * @param array $requiredcapabilities Optional list of required capabilities (used to filter the list).
2383 * @param int $limittoenrolled Limit to only enrolled courses
2384 * @return array of course objects and warnings
2385 * @since Moodle 3.0
2386 * @throws moodle_exception
2388 public static function search_courses($criterianame,
2389 $criteriavalue,
2390 $page=0,
2391 $perpage=0,
2392 $requiredcapabilities=array(),
2393 $limittoenrolled=0) {
2394 global $CFG;
2396 $warnings = array();
2398 $parameters = array(
2399 'criterianame' => $criterianame,
2400 'criteriavalue' => $criteriavalue,
2401 'page' => $page,
2402 'perpage' => $perpage,
2403 'requiredcapabilities' => $requiredcapabilities
2405 $params = self::validate_parameters(self::search_courses_parameters(), $parameters);
2406 self::validate_context(context_system::instance());
2408 $allowedcriterianames = array('search', 'modulelist', 'blocklist', 'tagid');
2409 if (!in_array($params['criterianame'], $allowedcriterianames)) {
2410 throw new invalid_parameter_exception('Invalid value for criterianame parameter (value: '.$params['criterianame'].'),' .
2411 'allowed values are: '.implode(',', $allowedcriterianames));
2414 if ($params['criterianame'] == 'modulelist' or $params['criterianame'] == 'blocklist') {
2415 require_capability('moodle/site:config', context_system::instance());
2418 $paramtype = array(
2419 'search' => PARAM_RAW,
2420 'modulelist' => PARAM_PLUGIN,
2421 'blocklist' => PARAM_INT,
2422 'tagid' => PARAM_INT
2424 $params['criteriavalue'] = clean_param($params['criteriavalue'], $paramtype[$params['criterianame']]);
2426 // Prepare the search API options.
2427 $searchcriteria = array();
2428 $searchcriteria[$params['criterianame']] = $params['criteriavalue'];
2430 $options = array();
2431 if ($params['perpage'] != 0) {
2432 $offset = $params['page'] * $params['perpage'];
2433 $options = array('offset' => $offset, 'limit' => $params['perpage']);
2436 // Search the courses.
2437 $courses = core_course_category::search_courses($searchcriteria, $options, $params['requiredcapabilities']);
2438 $totalcount = core_course_category::search_courses_count($searchcriteria, $options, $params['requiredcapabilities']);
2440 if (!empty($limittoenrolled)) {
2441 // Get the courses where the current user has access.
2442 $enrolled = enrol_get_my_courses(array('id', 'cacherev'));
2445 $finalcourses = array();
2446 $categoriescache = array();
2448 foreach ($courses as $course) {
2449 if (!empty($limittoenrolled)) {
2450 // Filter out not enrolled courses.
2451 if (!isset($enrolled[$course->id])) {
2452 $totalcount--;
2453 continue;
2457 $coursecontext = context_course::instance($course->id);
2459 $finalcourses[] = self::get_course_public_information($course, $coursecontext);
2462 return array(
2463 'total' => $totalcount,
2464 'courses' => $finalcourses,
2465 'warnings' => $warnings
2470 * Returns a course structure definition
2472 * @param boolean $onlypublicdata set to true, to retrieve only fields viewable by anyone when the course is visible
2473 * @return array the course structure
2474 * @since Moodle 3.2
2476 protected static function get_course_structure($onlypublicdata = true) {
2477 $coursestructure = array(
2478 'id' => new external_value(PARAM_INT, 'course id'),
2479 'fullname' => new external_value(PARAM_TEXT, 'course full name'),
2480 'displayname' => new external_value(PARAM_TEXT, 'course display name'),
2481 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
2482 'categoryid' => new external_value(PARAM_INT, 'category id'),
2483 'categoryname' => new external_value(PARAM_TEXT, 'category name'),
2484 'sortorder' => new external_value(PARAM_INT, 'Sort order in the category', VALUE_OPTIONAL),
2485 'summary' => new external_value(PARAM_RAW, 'summary'),
2486 'summaryformat' => new external_format_value('summary'),
2487 'summaryfiles' => new external_files('summary files in the summary field', VALUE_OPTIONAL),
2488 'overviewfiles' => new external_files('additional overview files attached to this course'),
2489 'contacts' => new external_multiple_structure(
2490 new external_single_structure(
2491 array(
2492 'id' => new external_value(PARAM_INT, 'contact user id'),
2493 'fullname' => new external_value(PARAM_NOTAGS, 'contact user fullname'),
2496 'contact users'
2498 'enrollmentmethods' => new external_multiple_structure(
2499 new external_value(PARAM_PLUGIN, 'enrollment method'),
2500 'enrollment methods list'
2504 if (!$onlypublicdata) {
2505 $extra = array(
2506 'idnumber' => new external_value(PARAM_RAW, 'Id number', VALUE_OPTIONAL),
2507 'format' => new external_value(PARAM_PLUGIN, 'Course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
2508 'showgrades' => new external_value(PARAM_INT, '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
2509 'newsitems' => new external_value(PARAM_INT, 'Number of recent items appearing on the course page', VALUE_OPTIONAL),
2510 'startdate' => new external_value(PARAM_INT, 'Timestamp when the course start', VALUE_OPTIONAL),
2511 'enddate' => new external_value(PARAM_INT, 'Timestamp when the course end', VALUE_OPTIONAL),
2512 'maxbytes' => new external_value(PARAM_INT, 'Largest size of file that can be uploaded into', VALUE_OPTIONAL),
2513 'showreports' => new external_value(PARAM_INT, 'Are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
2514 'visible' => new external_value(PARAM_INT, '1: available to student, 0:not available', VALUE_OPTIONAL),
2515 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
2516 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
2517 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
2518 'enablecompletion' => new external_value(PARAM_INT, 'Completion enabled? 1: yes 0: no', VALUE_OPTIONAL),
2519 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
2520 'lang' => new external_value(PARAM_SAFEDIR, 'Forced course language', VALUE_OPTIONAL),
2521 'theme' => new external_value(PARAM_PLUGIN, 'Fame of the forced theme', VALUE_OPTIONAL),
2522 'marker' => new external_value(PARAM_INT, 'Current course marker', VALUE_OPTIONAL),
2523 'legacyfiles' => new external_value(PARAM_INT, 'If legacy files are enabled', VALUE_OPTIONAL),
2524 'calendartype' => new external_value(PARAM_PLUGIN, 'Calendar type', VALUE_OPTIONAL),
2525 'timecreated' => new external_value(PARAM_INT, 'Time when the course was created', VALUE_OPTIONAL),
2526 'timemodified' => new external_value(PARAM_INT, 'Last time the course was updated', VALUE_OPTIONAL),
2527 'requested' => new external_value(PARAM_INT, 'If is a requested course', VALUE_OPTIONAL),
2528 'cacherev' => new external_value(PARAM_INT, 'Cache revision number', VALUE_OPTIONAL),
2529 'filters' => new external_multiple_structure(
2530 new external_single_structure(
2531 array(
2532 'filter' => new external_value(PARAM_PLUGIN, 'Filter plugin name'),
2533 'localstate' => new external_value(PARAM_INT, 'Filter state: 1 for on, -1 for off, 0 if inherit'),
2534 'inheritedstate' => new external_value(PARAM_INT, '1 or 0 to use when localstate is set to inherit'),
2537 'Course filters', VALUE_OPTIONAL
2539 'courseformatoptions' => new external_multiple_structure(
2540 new external_single_structure(
2541 array(
2542 'name' => new external_value(PARAM_RAW, 'Course format option name.'),
2543 'value' => new external_value(PARAM_RAW, 'Course format option value.'),
2546 'Additional options for particular course format.', VALUE_OPTIONAL
2549 $coursestructure = array_merge($coursestructure, $extra);
2551 return new external_single_structure($coursestructure);
2555 * Returns description of method result value
2557 * @return external_description
2558 * @since Moodle 3.0
2560 public static function search_courses_returns() {
2561 return new external_single_structure(
2562 array(
2563 'total' => new external_value(PARAM_INT, 'total course count'),
2564 'courses' => new external_multiple_structure(self::get_course_structure(), 'course'),
2565 'warnings' => new external_warnings()
2571 * Returns description of method parameters
2573 * @return external_function_parameters
2574 * @since Moodle 3.0
2576 public static function get_course_module_parameters() {
2577 return new external_function_parameters(
2578 array(
2579 'cmid' => new external_value(PARAM_INT, 'The course module id')
2585 * Return information about a course module.
2587 * @param int $cmid the course module id
2588 * @return array of warnings and the course module
2589 * @since Moodle 3.0
2590 * @throws moodle_exception
2592 public static function get_course_module($cmid) {
2593 global $CFG, $DB;
2595 $params = self::validate_parameters(self::get_course_module_parameters(), array('cmid' => $cmid));
2596 $warnings = array();
2598 $cm = get_coursemodule_from_id(null, $params['cmid'], 0, true, MUST_EXIST);
2599 $context = context_module::instance($cm->id);
2600 self::validate_context($context);
2602 // If the user has permissions to manage the activity, return all the information.
2603 if (has_capability('moodle/course:manageactivities', $context)) {
2604 require_once($CFG->dirroot . '/course/modlib.php');
2605 require_once($CFG->libdir . '/gradelib.php');
2607 $info = $cm;
2608 // Get the extra information: grade, advanced grading and outcomes data.
2609 $course = get_course($cm->course);
2610 list($newcm, $newcontext, $module, $extrainfo, $cw) = get_moduleinfo_data($cm, $course);
2611 // Grades.
2612 $gradeinfo = array('grade', 'gradepass', 'gradecat');
2613 foreach ($gradeinfo as $gfield) {
2614 if (isset($extrainfo->{$gfield})) {
2615 $info->{$gfield} = $extrainfo->{$gfield};
2618 if (isset($extrainfo->grade) and $extrainfo->grade < 0) {
2619 $info->scale = $DB->get_field('scale', 'scale', array('id' => abs($extrainfo->grade)));
2621 // Advanced grading.
2622 if (isset($extrainfo->_advancedgradingdata)) {
2623 $info->advancedgrading = array();
2624 foreach ($extrainfo as $key => $val) {
2625 if (strpos($key, 'advancedgradingmethod_') === 0) {
2626 $info->advancedgrading[] = array(
2627 'area' => str_replace('advancedgradingmethod_', '', $key),
2628 'method' => $val
2633 // Outcomes.
2634 foreach ($extrainfo as $key => $val) {
2635 if (strpos($key, 'outcome_') === 0) {
2636 if (!isset($info->outcomes)) {
2637 $info->outcomes = array();
2639 $id = str_replace('outcome_', '', $key);
2640 $outcome = grade_outcome::fetch(array('id' => $id));
2641 $scaleitems = $outcome->load_scale();
2642 $info->outcomes[] = array(
2643 'id' => $id,
2644 'name' => external_format_string($outcome->get_name(), $context->id),
2645 'scale' => $scaleitems->scale
2649 } else {
2650 // Return information is safe to show to any user.
2651 $info = new stdClass();
2652 $info->id = $cm->id;
2653 $info->course = $cm->course;
2654 $info->module = $cm->module;
2655 $info->modname = $cm->modname;
2656 $info->instance = $cm->instance;
2657 $info->section = $cm->section;
2658 $info->sectionnum = $cm->sectionnum;
2659 $info->groupmode = $cm->groupmode;
2660 $info->groupingid = $cm->groupingid;
2661 $info->completion = $cm->completion;
2663 // Format name.
2664 $info->name = external_format_string($cm->name, $context->id);
2665 $result = array();
2666 $result['cm'] = $info;
2667 $result['warnings'] = $warnings;
2668 return $result;
2672 * Returns description of method result value
2674 * @return external_description
2675 * @since Moodle 3.0
2677 public static function get_course_module_returns() {
2678 return new external_single_structure(
2679 array(
2680 'cm' => new external_single_structure(
2681 array(
2682 'id' => new external_value(PARAM_INT, 'The course module id'),
2683 'course' => new external_value(PARAM_INT, 'The course id'),
2684 'module' => new external_value(PARAM_INT, 'The module type id'),
2685 'name' => new external_value(PARAM_RAW, 'The activity name'),
2686 'modname' => new external_value(PARAM_COMPONENT, 'The module component name (forum, assign, etc..)'),
2687 'instance' => new external_value(PARAM_INT, 'The activity instance id'),
2688 'section' => new external_value(PARAM_INT, 'The module section id'),
2689 'sectionnum' => new external_value(PARAM_INT, 'The module section number'),
2690 'groupmode' => new external_value(PARAM_INT, 'Group mode'),
2691 'groupingid' => new external_value(PARAM_INT, 'Grouping id'),
2692 'completion' => new external_value(PARAM_INT, 'If completion is enabled'),
2693 'idnumber' => new external_value(PARAM_RAW, 'Module id number', VALUE_OPTIONAL),
2694 'added' => new external_value(PARAM_INT, 'Time added', VALUE_OPTIONAL),
2695 'score' => new external_value(PARAM_INT, 'Score', VALUE_OPTIONAL),
2696 'indent' => new external_value(PARAM_INT, 'Indentation', VALUE_OPTIONAL),
2697 'visible' => new external_value(PARAM_INT, 'If visible', VALUE_OPTIONAL),
2698 'visibleoncoursepage' => new external_value(PARAM_INT, 'If visible on course page', VALUE_OPTIONAL),
2699 'visibleold' => new external_value(PARAM_INT, 'Visible old', VALUE_OPTIONAL),
2700 'completiongradeitemnumber' => new external_value(PARAM_INT, 'Completion grade item', VALUE_OPTIONAL),
2701 'completionview' => new external_value(PARAM_INT, 'Completion view setting', VALUE_OPTIONAL),
2702 'completionexpected' => new external_value(PARAM_INT, 'Completion time expected', VALUE_OPTIONAL),
2703 'showdescription' => new external_value(PARAM_INT, 'If the description is showed', VALUE_OPTIONAL),
2704 'availability' => new external_value(PARAM_RAW, 'Availability settings', VALUE_OPTIONAL),
2705 'grade' => new external_value(PARAM_FLOAT, 'Grade (max value or scale id)', VALUE_OPTIONAL),
2706 'scale' => new external_value(PARAM_TEXT, 'Scale items (if used)', VALUE_OPTIONAL),
2707 'gradepass' => new external_value(PARAM_RAW, 'Grade to pass (float)', VALUE_OPTIONAL),
2708 'gradecat' => new external_value(PARAM_INT, 'Grade category', VALUE_OPTIONAL),
2709 'advancedgrading' => new external_multiple_structure(
2710 new external_single_structure(
2711 array(
2712 'area' => new external_value(PARAM_AREA, 'Gradable area name'),
2713 'method' => new external_value(PARAM_COMPONENT, 'Grading method'),
2716 'Advanced grading settings', VALUE_OPTIONAL
2718 'outcomes' => new external_multiple_structure(
2719 new external_single_structure(
2720 array(
2721 'id' => new external_value(PARAM_ALPHANUMEXT, 'Outcome id'),
2722 'name' => new external_value(PARAM_TEXT, 'Outcome full name'),
2723 'scale' => new external_value(PARAM_TEXT, 'Scale items')
2726 'Outcomes information', VALUE_OPTIONAL
2730 'warnings' => new external_warnings()
2736 * Returns description of method parameters
2738 * @return external_function_parameters
2739 * @since Moodle 3.0
2741 public static function get_course_module_by_instance_parameters() {
2742 return new external_function_parameters(
2743 array(
2744 'module' => new external_value(PARAM_COMPONENT, 'The module name'),
2745 'instance' => new external_value(PARAM_INT, 'The module instance id')
2751 * Return information about a course module.
2753 * @param string $module the module name
2754 * @param int $instance the activity instance id
2755 * @return array of warnings and the course module
2756 * @since Moodle 3.0
2757 * @throws moodle_exception
2759 public static function get_course_module_by_instance($module, $instance) {
2761 $params = self::validate_parameters(self::get_course_module_by_instance_parameters(),
2762 array(
2763 'module' => $module,
2764 'instance' => $instance,
2767 $warnings = array();
2768 $cm = get_coursemodule_from_instance($params['module'], $params['instance'], 0, false, MUST_EXIST);
2770 return self::get_course_module($cm->id);
2774 * Returns description of method result value
2776 * @return external_description
2777 * @since Moodle 3.0
2779 public static function get_course_module_by_instance_returns() {
2780 return self::get_course_module_returns();
2784 * Returns description of method parameters
2786 * @deprecated since 3.3
2787 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
2788 * @return external_function_parameters
2789 * @since Moodle 3.2
2791 public static function get_activities_overview_parameters() {
2792 return new external_function_parameters(
2793 array(
2794 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2800 * Return activities overview for the given courses.
2802 * @deprecated since 3.3
2803 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
2804 * @param array $courseids a list of course ids
2805 * @return array of warnings and the activities overview
2806 * @since Moodle 3.2
2807 * @throws moodle_exception
2809 public static function get_activities_overview($courseids) {
2810 global $USER;
2812 // Parameter validation.
2813 $params = self::validate_parameters(self::get_activities_overview_parameters(), array('courseids' => $courseids));
2814 $courseoverviews = array();
2816 list($courses, $warnings) = external_util::validate_courses($params['courseids']);
2818 if (!empty($courses)) {
2819 // Add lastaccess to each course (required by print_overview function).
2820 // We need the complete user data, the ws server does not load a complete one.
2821 $user = get_complete_user_data('id', $USER->id);
2822 foreach ($courses as $course) {
2823 if (isset($user->lastcourseaccess[$course->id])) {
2824 $course->lastaccess = $user->lastcourseaccess[$course->id];
2825 } else {
2826 $course->lastaccess = 0;
2830 $overviews = array();
2831 if ($modules = get_plugin_list_with_function('mod', 'print_overview')) {
2832 foreach ($modules as $fname) {
2833 $fname($courses, $overviews);
2837 // Format output.
2838 foreach ($overviews as $courseid => $modules) {
2839 $courseoverviews[$courseid]['id'] = $courseid;
2840 $courseoverviews[$courseid]['overviews'] = array();
2842 foreach ($modules as $modname => $overviewtext) {
2843 $courseoverviews[$courseid]['overviews'][] = array(
2844 'module' => $modname,
2845 'overviewtext' => $overviewtext // This text doesn't need formatting.
2851 $result = array(
2852 'courses' => $courseoverviews,
2853 'warnings' => $warnings
2855 return $result;
2859 * Returns description of method result value
2861 * @deprecated since 3.3
2862 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
2863 * @return external_description
2864 * @since Moodle 3.2
2866 public static function get_activities_overview_returns() {
2867 return new external_single_structure(
2868 array(
2869 'courses' => new external_multiple_structure(
2870 new external_single_structure(
2871 array(
2872 'id' => new external_value(PARAM_INT, 'Course id'),
2873 'overviews' => new external_multiple_structure(
2874 new external_single_structure(
2875 array(
2876 'module' => new external_value(PARAM_PLUGIN, 'Module name'),
2877 'overviewtext' => new external_value(PARAM_RAW, 'Overview text'),
2882 ), 'List of courses'
2884 'warnings' => new external_warnings()
2890 * Marking the method as deprecated.
2892 * @return bool
2894 public static function get_activities_overview_is_deprecated() {
2895 return true;
2899 * Returns description of method parameters
2901 * @return external_function_parameters
2902 * @since Moodle 3.2
2904 public static function get_user_navigation_options_parameters() {
2905 return new external_function_parameters(
2906 array(
2907 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2913 * Return a list of navigation options in a set of courses that are avaialable or not for the current user.
2915 * @param array $courseids a list of course ids
2916 * @return array of warnings and the options availability
2917 * @since Moodle 3.2
2918 * @throws moodle_exception
2920 public static function get_user_navigation_options($courseids) {
2921 global $CFG;
2922 require_once($CFG->dirroot . '/course/lib.php');
2924 // Parameter validation.
2925 $params = self::validate_parameters(self::get_user_navigation_options_parameters(), array('courseids' => $courseids));
2926 $courseoptions = array();
2928 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
2930 if (!empty($courses)) {
2931 foreach ($courses as $course) {
2932 // Fix the context for the frontpage.
2933 if ($course->id == SITEID) {
2934 $course->context = context_system::instance();
2936 $navoptions = course_get_user_navigation_options($course->context, $course);
2937 $options = array();
2938 foreach ($navoptions as $name => $available) {
2939 $options[] = array(
2940 'name' => $name,
2941 'available' => $available,
2945 $courseoptions[] = array(
2946 'id' => $course->id,
2947 'options' => $options
2952 $result = array(
2953 'courses' => $courseoptions,
2954 'warnings' => $warnings
2956 return $result;
2960 * Returns description of method result value
2962 * @return external_description
2963 * @since Moodle 3.2
2965 public static function get_user_navigation_options_returns() {
2966 return new external_single_structure(
2967 array(
2968 'courses' => new external_multiple_structure(
2969 new external_single_structure(
2970 array(
2971 'id' => new external_value(PARAM_INT, 'Course id'),
2972 'options' => new external_multiple_structure(
2973 new external_single_structure(
2974 array(
2975 'name' => new external_value(PARAM_ALPHANUMEXT, 'Option name'),
2976 'available' => new external_value(PARAM_BOOL, 'Whether the option is available or not'),
2981 ), 'List of courses'
2983 'warnings' => new external_warnings()
2989 * Returns description of method parameters
2991 * @return external_function_parameters
2992 * @since Moodle 3.2
2994 public static function get_user_administration_options_parameters() {
2995 return new external_function_parameters(
2996 array(
2997 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
3003 * Return a list of administration options in a set of courses that are available or not for the current user.
3005 * @param array $courseids a list of course ids
3006 * @return array of warnings and the options availability
3007 * @since Moodle 3.2
3008 * @throws moodle_exception
3010 public static function get_user_administration_options($courseids) {
3011 global $CFG;
3012 require_once($CFG->dirroot . '/course/lib.php');
3014 // Parameter validation.
3015 $params = self::validate_parameters(self::get_user_administration_options_parameters(), array('courseids' => $courseids));
3016 $courseoptions = array();
3018 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
3020 if (!empty($courses)) {
3021 foreach ($courses as $course) {
3022 $adminoptions = course_get_user_administration_options($course, $course->context);
3023 $options = array();
3024 foreach ($adminoptions as $name => $available) {
3025 $options[] = array(
3026 'name' => $name,
3027 'available' => $available,
3031 $courseoptions[] = array(
3032 'id' => $course->id,
3033 'options' => $options
3038 $result = array(
3039 'courses' => $courseoptions,
3040 'warnings' => $warnings
3042 return $result;
3046 * Returns description of method result value
3048 * @return external_description
3049 * @since Moodle 3.2
3051 public static function get_user_administration_options_returns() {
3052 return self::get_user_navigation_options_returns();
3056 * Returns description of method parameters
3058 * @return external_function_parameters
3059 * @since Moodle 3.2
3061 public static function get_courses_by_field_parameters() {
3062 return new external_function_parameters(
3063 array(
3064 'field' => new external_value(PARAM_ALPHA, 'The field to search can be left empty for all courses or:
3065 id: course id
3066 ids: comma separated course ids
3067 shortname: course short name
3068 idnumber: course id number
3069 category: category id the course belongs to
3070 ', VALUE_DEFAULT, ''),
3071 'value' => new external_value(PARAM_RAW, 'The value to match', VALUE_DEFAULT, '')
3078 * Get courses matching a specific field (id/s, shortname, idnumber, category)
3080 * @param string $field field name to search, or empty for all courses
3081 * @param string $value value to search
3082 * @return array list of courses and warnings
3083 * @throws invalid_parameter_exception
3084 * @since Moodle 3.2
3086 public static function get_courses_by_field($field = '', $value = '') {
3087 global $DB, $CFG;
3088 require_once($CFG->dirroot . '/course/lib.php');
3089 require_once($CFG->libdir . '/filterlib.php');
3091 $params = self::validate_parameters(self::get_courses_by_field_parameters(),
3092 array(
3093 'field' => $field,
3094 'value' => $value,
3097 $warnings = array();
3099 if (empty($params['field'])) {
3100 $courses = $DB->get_records('course', null, 'id ASC');
3101 } else {
3102 switch ($params['field']) {
3103 case 'id':
3104 case 'category':
3105 $value = clean_param($params['value'], PARAM_INT);
3106 break;
3107 case 'ids':
3108 $value = clean_param($params['value'], PARAM_SEQUENCE);
3109 break;
3110 case 'shortname':
3111 $value = clean_param($params['value'], PARAM_TEXT);
3112 break;
3113 case 'idnumber':
3114 $value = clean_param($params['value'], PARAM_RAW);
3115 break;
3116 default:
3117 throw new invalid_parameter_exception('Invalid field name');
3120 if ($params['field'] === 'ids') {
3121 $courses = $DB->get_records_list('course', 'id', explode(',', $value), 'id ASC');
3122 } else {
3123 $courses = $DB->get_records('course', array($params['field'] => $value), 'id ASC');
3127 $coursesdata = array();
3128 foreach ($courses as $course) {
3129 $context = context_course::instance($course->id);
3130 $canupdatecourse = has_capability('moodle/course:update', $context);
3131 $canviewhiddencourses = has_capability('moodle/course:viewhiddencourses', $context);
3133 // Check if the course is visible in the site for the user.
3134 if (!$course->visible and !$canviewhiddencourses and !$canupdatecourse) {
3135 continue;
3137 // Get the public course information, even if we are not enrolled.
3138 $courseinlist = new core_course_list_element($course);
3139 $coursesdata[$course->id] = self::get_course_public_information($courseinlist, $context);
3141 // Now, check if we have access to the course.
3142 try {
3143 self::validate_context($context);
3144 } catch (Exception $e) {
3145 continue;
3147 // Return information for any user that can access the course.
3148 $coursefields = array('format', 'showgrades', 'newsitems', 'startdate', 'enddate', 'maxbytes', 'showreports', 'visible',
3149 'groupmode', 'groupmodeforce', 'defaultgroupingid', 'enablecompletion', 'completionnotify', 'lang', 'theme',
3150 'marker');
3152 // Course filters.
3153 $coursesdata[$course->id]['filters'] = filter_get_available_in_context($context);
3155 // Information for managers only.
3156 if ($canupdatecourse) {
3157 $managerfields = array('idnumber', 'legacyfiles', 'calendartype', 'timecreated', 'timemodified', 'requested',
3158 'cacherev');
3159 $coursefields = array_merge($coursefields, $managerfields);
3162 // Populate fields.
3163 foreach ($coursefields as $field) {
3164 $coursesdata[$course->id][$field] = $course->{$field};
3167 // Clean lang and auth fields for external functions (it may content uninstalled themes or language packs).
3168 if (isset($coursesdata[$course->id]['theme'])) {
3169 $coursesdata[$course->id]['theme'] = clean_param($coursesdata[$course->id]['theme'], PARAM_THEME);
3171 if (isset($coursesdata[$course->id]['lang'])) {
3172 $coursesdata[$course->id]['lang'] = clean_param($coursesdata[$course->id]['lang'], PARAM_LANG);
3175 $courseformatoptions = course_get_format($course)->get_config_for_external();
3176 foreach ($courseformatoptions as $key => $value) {
3177 $coursesdata[$course->id]['courseformatoptions'][] = array(
3178 'name' => $key,
3179 'value' => $value
3184 return array(
3185 'courses' => $coursesdata,
3186 'warnings' => $warnings
3191 * Returns description of method result value
3193 * @return external_description
3194 * @since Moodle 3.2
3196 public static function get_courses_by_field_returns() {
3197 // Course structure, including not only public viewable fields.
3198 return new external_single_structure(
3199 array(
3200 'courses' => new external_multiple_structure(self::get_course_structure(false), 'Course'),
3201 'warnings' => new external_warnings()
3207 * Returns description of method parameters
3209 * @return external_function_parameters
3210 * @since Moodle 3.2
3212 public static function check_updates_parameters() {
3213 return new external_function_parameters(
3214 array(
3215 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3216 'tocheck' => new external_multiple_structure(
3217 new external_single_structure(
3218 array(
3219 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level for the file location.
3220 Only module supported right now.'),
3221 'id' => new external_value(PARAM_INT, 'Context instance id'),
3222 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3225 'Instances to check'
3227 'filter' => new external_multiple_structure(
3228 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3229 gradeitems, outcomes'),
3230 'Check only for updates in these areas', VALUE_DEFAULT, array()
3237 * Check if there is updates affecting the user for the given course and contexts.
3238 * Right now only modules are supported.
3239 * This WS calls mod_check_updates_since for each module to check if there is any update the user should we aware of.
3241 * @param int $courseid the list of modules to check
3242 * @param array $tocheck the list of modules to check
3243 * @param array $filter check only for updates in these areas
3244 * @return array list of updates and warnings
3245 * @throws moodle_exception
3246 * @since Moodle 3.2
3248 public static function check_updates($courseid, $tocheck, $filter = array()) {
3249 global $CFG, $DB;
3250 require_once($CFG->dirroot . "/course/lib.php");
3252 $params = self::validate_parameters(
3253 self::check_updates_parameters(),
3254 array(
3255 'courseid' => $courseid,
3256 'tocheck' => $tocheck,
3257 'filter' => $filter,
3261 $course = get_course($params['courseid']);
3262 $context = context_course::instance($course->id);
3263 self::validate_context($context);
3265 list($instances, $warnings) = course_check_updates($course, $params['tocheck'], $filter);
3267 $instancesformatted = array();
3268 foreach ($instances as $instance) {
3269 $updates = array();
3270 foreach ($instance['updates'] as $name => $data) {
3271 if (empty($data->updated)) {
3272 continue;
3274 $updatedata = array(
3275 'name' => $name,
3277 if (!empty($data->timeupdated)) {
3278 $updatedata['timeupdated'] = $data->timeupdated;
3280 if (!empty($data->itemids)) {
3281 $updatedata['itemids'] = $data->itemids;
3283 $updates[] = $updatedata;
3285 if (!empty($updates)) {
3286 $instancesformatted[] = array(
3287 'contextlevel' => $instance['contextlevel'],
3288 'id' => $instance['id'],
3289 'updates' => $updates
3294 return array(
3295 'instances' => $instancesformatted,
3296 'warnings' => $warnings
3301 * Returns description of method result value
3303 * @return external_description
3304 * @since Moodle 3.2
3306 public static function check_updates_returns() {
3307 return new external_single_structure(
3308 array(
3309 'instances' => new external_multiple_structure(
3310 new external_single_structure(
3311 array(
3312 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level'),
3313 'id' => new external_value(PARAM_INT, 'Instance id'),
3314 'updates' => new external_multiple_structure(
3315 new external_single_structure(
3316 array(
3317 'name' => new external_value(PARAM_ALPHANUMEXT, 'Name of the area updated.'),
3318 'timeupdated' => new external_value(PARAM_INT, 'Last time was updated', VALUE_OPTIONAL),
3319 'itemids' => new external_multiple_structure(
3320 new external_value(PARAM_INT, 'Instance id'),
3321 'The ids of the items updated',
3322 VALUE_OPTIONAL
3330 'warnings' => new external_warnings()
3336 * Returns description of method parameters
3338 * @return external_function_parameters
3339 * @since Moodle 3.3
3341 public static function get_updates_since_parameters() {
3342 return new external_function_parameters(
3343 array(
3344 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3345 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3346 'filter' => new external_multiple_structure(
3347 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3348 gradeitems, outcomes'),
3349 'Check only for updates in these areas', VALUE_DEFAULT, array()
3356 * Check if there are updates affecting the user for the given course since the given time stamp.
3358 * This function is a wrapper of self::check_updates for retrieving all the updates since a given time for all the activities.
3360 * @param int $courseid the list of modules to check
3361 * @param int $since check updates since this time stamp
3362 * @param array $filter check only for updates in these areas
3363 * @return array list of updates and warnings
3364 * @throws moodle_exception
3365 * @since Moodle 3.3
3367 public static function get_updates_since($courseid, $since, $filter = array()) {
3368 global $CFG, $DB;
3370 $params = self::validate_parameters(
3371 self::get_updates_since_parameters(),
3372 array(
3373 'courseid' => $courseid,
3374 'since' => $since,
3375 'filter' => $filter,
3379 $course = get_course($params['courseid']);
3380 $modinfo = get_fast_modinfo($course);
3381 $tocheck = array();
3383 // Retrieve all the visible course modules for the current user.
3384 $cms = $modinfo->get_cms();
3385 foreach ($cms as $cm) {
3386 if (!$cm->uservisible) {
3387 continue;
3389 $tocheck[] = array(
3390 'id' => $cm->id,
3391 'contextlevel' => 'module',
3392 'since' => $params['since'],
3396 return self::check_updates($course->id, $tocheck, $params['filter']);
3400 * Returns description of method result value
3402 * @return external_description
3403 * @since Moodle 3.3
3405 public static function get_updates_since_returns() {
3406 return self::check_updates_returns();
3410 * Parameters for function edit_module()
3412 * @since Moodle 3.3
3413 * @return external_function_parameters
3415 public static function edit_module_parameters() {
3416 return new external_function_parameters(
3417 array(
3418 'action' => new external_value(PARAM_ALPHA,
3419 'action: hide, show, stealth, duplicate, delete, moveleft, moveright, group...', VALUE_REQUIRED),
3420 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3421 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3426 * Performs one of the edit module actions and return new html for AJAX
3428 * Returns html to replace the current module html with, for example:
3429 * - empty string for "delete" action,
3430 * - two modules html for "duplicate" action
3431 * - updated module html for everything else
3433 * Throws exception if operation is not permitted/possible
3435 * @since Moodle 3.3
3436 * @param string $action
3437 * @param int $id
3438 * @param null|int $sectionreturn
3439 * @return string
3441 public static function edit_module($action, $id, $sectionreturn = null) {
3442 global $PAGE, $DB;
3443 // Validate and normalize parameters.
3444 $params = self::validate_parameters(self::edit_module_parameters(),
3445 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3446 $action = $params['action'];
3447 $id = $params['id'];
3448 $sectionreturn = $params['sectionreturn'];
3450 list($course, $cm) = get_course_and_cm_from_cmid($id);
3451 $modcontext = context_module::instance($cm->id);
3452 $coursecontext = context_course::instance($course->id);
3453 self::validate_context($modcontext);
3454 $courserenderer = $PAGE->get_renderer('core', 'course');
3455 $completioninfo = new completion_info($course);
3457 switch($action) {
3458 case 'hide':
3459 case 'show':
3460 case 'stealth':
3461 require_capability('moodle/course:activityvisibility', $modcontext);
3462 $visible = ($action === 'hide') ? 0 : 1;
3463 $visibleoncoursepage = ($action === 'stealth') ? 0 : 1;
3464 set_coursemodule_visible($id, $visible, $visibleoncoursepage);
3465 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3466 break;
3467 case 'duplicate':
3468 require_capability('moodle/course:manageactivities', $coursecontext);
3469 require_capability('moodle/backup:backuptargetimport', $coursecontext);
3470 require_capability('moodle/restore:restoretargetimport', $coursecontext);
3471 if (!course_allowed_module($course, $cm->modname)) {
3472 throw new moodle_exception('No permission to create that activity');
3474 if ($newcm = duplicate_module($course, $cm)) {
3475 $cm = get_fast_modinfo($course)->get_cm($id);
3476 $newcm = get_fast_modinfo($course)->get_cm($newcm->id);
3477 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn) .
3478 $courserenderer->course_section_cm_list_item($course, $completioninfo, $newcm, $sectionreturn);
3480 break;
3481 case 'groupsseparate':
3482 case 'groupsvisible':
3483 case 'groupsnone':
3484 require_capability('moodle/course:manageactivities', $modcontext);
3485 if ($action === 'groupsseparate') {
3486 $newgroupmode = SEPARATEGROUPS;
3487 } else if ($action === 'groupsvisible') {
3488 $newgroupmode = VISIBLEGROUPS;
3489 } else {
3490 $newgroupmode = NOGROUPS;
3492 if (set_coursemodule_groupmode($cm->id, $newgroupmode)) {
3493 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3495 break;
3496 case 'moveleft':
3497 case 'moveright':
3498 require_capability('moodle/course:manageactivities', $modcontext);
3499 $indent = $cm->indent + (($action === 'moveright') ? 1 : -1);
3500 if ($cm->indent >= 0) {
3501 $DB->update_record('course_modules', array('id' => $cm->id, 'indent' => $indent));
3502 rebuild_course_cache($cm->course);
3504 break;
3505 case 'delete':
3506 require_capability('moodle/course:manageactivities', $modcontext);
3507 course_delete_module($cm->id, true);
3508 return '';
3509 default:
3510 throw new coding_exception('Unrecognised action');
3513 $cm = get_fast_modinfo($course)->get_cm($id);
3514 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn);
3518 * Return structure for edit_module()
3520 * @since Moodle 3.3
3521 * @return external_description
3523 public static function edit_module_returns() {
3524 return new external_value(PARAM_RAW, 'html to replace the current module with');
3528 * Parameters for function get_module()
3530 * @since Moodle 3.3
3531 * @return external_function_parameters
3533 public static function get_module_parameters() {
3534 return new external_function_parameters(
3535 array(
3536 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3537 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3542 * Returns html for displaying one activity module on course page
3544 * @since Moodle 3.3
3545 * @param int $id
3546 * @param null|int $sectionreturn
3547 * @return string
3549 public static function get_module($id, $sectionreturn = null) {
3550 global $PAGE;
3551 // Validate and normalize parameters.
3552 $params = self::validate_parameters(self::get_module_parameters(),
3553 array('id' => $id, 'sectionreturn' => $sectionreturn));
3554 $id = $params['id'];
3555 $sectionreturn = $params['sectionreturn'];
3557 // Validate access to the course (note, this is html for the course view page, we don't validate access to the module).
3558 list($course, $cm) = get_course_and_cm_from_cmid($id);
3559 self::validate_context(context_course::instance($course->id));
3561 $courserenderer = $PAGE->get_renderer('core', 'course');
3562 $completioninfo = new completion_info($course);
3563 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn);
3567 * Return structure for edit_module()
3569 * @since Moodle 3.3
3570 * @return external_description
3572 public static function get_module_returns() {
3573 return new external_value(PARAM_RAW, 'html to replace the current module with');
3577 * Parameters for function edit_section()
3579 * @since Moodle 3.3
3580 * @return external_function_parameters
3582 public static function edit_section_parameters() {
3583 return new external_function_parameters(
3584 array(
3585 'action' => new external_value(PARAM_ALPHA, 'action: hide, show, stealth, setmarker, removemarker', VALUE_REQUIRED),
3586 'id' => new external_value(PARAM_INT, 'course section id', VALUE_REQUIRED),
3587 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3592 * Performs one of the edit section actions
3594 * @since Moodle 3.3
3595 * @param string $action
3596 * @param int $id section id
3597 * @param int $sectionreturn section to return to
3598 * @return string
3600 public static function edit_section($action, $id, $sectionreturn) {
3601 global $DB;
3602 // Validate and normalize parameters.
3603 $params = self::validate_parameters(self::edit_section_parameters(),
3604 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3605 $action = $params['action'];
3606 $id = $params['id'];
3607 $sr = $params['sectionreturn'];
3609 $section = $DB->get_record('course_sections', array('id' => $id), '*', MUST_EXIST);
3610 $coursecontext = context_course::instance($section->course);
3611 self::validate_context($coursecontext);
3613 $rv = course_get_format($section->course)->section_action($section, $action, $sectionreturn);
3614 if ($rv) {
3615 return json_encode($rv);
3616 } else {
3617 return null;
3622 * Return structure for edit_section()
3624 * @since Moodle 3.3
3625 * @return external_description
3627 public static function edit_section_returns() {
3628 return new external_value(PARAM_RAW, 'Additional data for javascript (JSON-encoded string)');
3632 * Returns description of method parameters
3634 * @return external_function_parameters
3636 public static function get_enrolled_courses_by_timeline_classification_parameters() {
3637 return new external_function_parameters(
3638 array(
3639 'classification' => new external_value(PARAM_ALPHA, 'future, inprogress, or past'),
3640 'limit' => new external_value(PARAM_INT, 'Result set limit', VALUE_DEFAULT, 0),
3641 'offset' => new external_value(PARAM_INT, 'Result set offset', VALUE_DEFAULT, 0),
3642 'sort' => new external_value(PARAM_TEXT, 'Sort string', VALUE_DEFAULT, null)
3648 * Get courses matching the given timeline classification.
3650 * NOTE: The offset applies to the unfiltered full set of courses before the classification
3651 * filtering is done.
3652 * E.g.
3653 * If the user is enrolled in 5 courses:
3654 * c1, c2, c3, c4, and c5
3655 * And c4 and c5 are 'future' courses
3657 * If a request comes in for future courses with an offset of 1 it will mean that
3658 * c1 is skipped (because the offset applies *before* the classification filtering)
3659 * and c4 and c5 will be return.
3661 * @param string $classification past, inprogress, or future
3662 * @param int $limit Result set limit
3663 * @param int $offset Offset the full course set before timeline classification is applied
3664 * @param string $sort SQL sort string for results
3665 * @return array list of courses and warnings
3666 * @throws invalid_parameter_exception
3668 public static function get_enrolled_courses_by_timeline_classification(
3669 string $classification,
3670 int $limit = 0,
3671 int $offset = 0,
3672 string $sort = null
3674 global $CFG, $PAGE, $USER;
3675 require_once($CFG->dirroot . '/course/lib.php');
3677 $params = self::validate_parameters(self::get_enrolled_courses_by_timeline_classification_parameters(),
3678 array(
3679 'classification' => $classification,
3680 'limit' => $limit,
3681 'offset' => $offset,
3682 'sort' => $sort,
3686 $classification = $params['classification'];
3687 $limit = $params['limit'];
3688 $offset = $params['offset'];
3689 $sort = $params['sort'];
3691 switch($classification) {
3692 case COURSE_TIMELINE_ALL:
3693 break;
3694 case COURSE_TIMELINE_PAST:
3695 break;
3696 case COURSE_TIMELINE_INPROGRESS:
3697 break;
3698 case COURSE_TIMELINE_FUTURE:
3699 break;
3700 case COURSE_FAVOURITES:
3701 break;
3702 case COURSE_TIMELINE_HIDDEN:
3703 break;
3704 default:
3705 throw new invalid_parameter_exception('Invalid classification');
3708 self::validate_context(context_user::instance($USER->id));
3710 $requiredproperties = course_summary_exporter::define_properties();
3711 $fields = join(',', array_keys($requiredproperties));
3712 $hiddencourses = get_hidden_courses_on_timeline();
3713 $courses = [];
3715 // If the timeline requires the hidden courses then restrict the result to only $hiddencourses else exclude.
3716 if ($classification == COURSE_TIMELINE_HIDDEN) {
3717 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields,
3718 COURSE_DB_QUERY_LIMIT, $hiddencourses);
3719 } else {
3720 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields,
3721 COURSE_DB_QUERY_LIMIT, [], $hiddencourses);
3724 $favouritecourseids = [];
3725 $ufservice = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($USER->id));
3726 $favourites = $ufservice->find_favourites_by_type('core_course', 'courses');
3728 if ($favourites) {
3729 $favouritecourseids = array_map(
3730 function($favourite) {
3731 return $favourite->itemid;
3732 }, $favourites);
3735 if ($classification == COURSE_FAVOURITES) {
3736 list($filteredcourses, $processedcount) = course_filter_courses_by_favourites(
3737 $courses,
3738 $favouritecourseids,
3739 $limit
3741 } else {
3742 list($filteredcourses, $processedcount) = course_filter_courses_by_timeline_classification(
3743 $courses,
3744 $classification,
3745 $limit
3749 $renderer = $PAGE->get_renderer('core');
3750 $formattedcourses = array_map(function($course) use ($renderer, $favouritecourseids) {
3751 context_helper::preload_from_record($course);
3752 $context = context_course::instance($course->id);
3753 $isfavourite = false;
3754 if (in_array($course->id, $favouritecourseids)) {
3755 $isfavourite = true;
3757 $exporter = new course_summary_exporter($course, ['context' => $context, 'isfavourite' => $isfavourite]);
3758 return $exporter->export($renderer);
3759 }, $filteredcourses);
3761 return [
3762 'courses' => $formattedcourses,
3763 'nextoffset' => $offset + $processedcount
3768 * Returns description of method result value
3770 * @return external_description
3772 public static function get_enrolled_courses_by_timeline_classification_returns() {
3773 return new external_single_structure(
3774 array(
3775 'courses' => new external_multiple_structure(course_summary_exporter::get_read_structure(), 'Course'),
3776 'nextoffset' => new external_value(PARAM_INT, 'Offset for the next request')
3782 * Returns description of method parameters
3784 * @return external_function_parameters
3786 public static function set_favourite_courses_parameters() {
3787 return new external_function_parameters(
3788 array(
3789 'courses' => new external_multiple_structure(
3790 new external_single_structure(
3791 array(
3792 'id' => new external_value(PARAM_INT, 'course ID'),
3793 'favourite' => new external_value(PARAM_BOOL, 'favourite status')
3802 * Set the course favourite status for an array of courses.
3804 * @param array $courses List with course id's and favourite status.
3805 * @return array Array with an array of favourite courses.
3807 public static function set_favourite_courses(
3808 array $courses
3810 global $USER;
3812 $params = self::validate_parameters(self::set_favourite_courses_parameters(),
3813 array(
3814 'courses' => $courses
3818 $warnings = [];
3820 $ufservice = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($USER->id));
3822 foreach ($params['courses'] as $course) {
3824 $warning = [];
3826 $favouriteexists = $ufservice->favourite_exists('core_course', 'courses', $course['id'], \context_system::instance());
3828 if ($course['favourite']) {
3829 if (!$favouriteexists) {
3830 try {
3831 $ufservice->create_favourite('core_course', 'courses', $course['id'], \context_system::instance());
3832 } catch (Exception $e) {
3833 $warning['courseid'] = $course['id'];
3834 if ($e instanceof moodle_exception) {
3835 $warning['warningcode'] = $e->errorcode;
3836 } else {
3837 $warning['warningcode'] = $e->getCode();
3839 $warning['message'] = $e->getMessage();
3840 $warnings[] = $warning;
3841 $warnings[] = $warning;
3843 } else {
3844 $warning['courseid'] = $course['id'];
3845 $warning['warningcode'] = 'coursealreadyfavourited';
3846 $warning['message'] = 'Course already favourited';
3847 $warnings[] = $warning;
3849 } else {
3850 if ($favouriteexists) {
3851 try {
3852 $ufservice->delete_favourite('core_course', 'courses', $course['id'], \context_system::instance());
3853 } catch (Exception $e) {
3854 $warning['courseid'] = $course['id'];
3855 if ($e instanceof moodle_exception) {
3856 $warning['warningcode'] = $e->errorcode;
3857 } else {
3858 $warning['warningcode'] = $e->getCode();
3860 $warning['message'] = $e->getMessage();
3861 $warnings[] = $warning;
3862 $warnings[] = $warning;
3864 } else {
3865 $warning['courseid'] = $course['id'];
3866 $warning['warningcode'] = 'cannotdeletefavourite';
3867 $warning['message'] = 'Could not delete favourite status for course';
3868 $warnings[] = $warning;
3873 return [
3874 'warnings' => $warnings
3879 * Returns description of method result value
3881 * @return external_description
3883 public static function set_favourite_courses_returns() {
3884 return new external_single_structure(
3885 array(
3886 'warnings' => new external_warnings()
3892 * Returns description of method parameters
3894 * @return external_function_parameters
3895 * @since Moodle 3.6
3897 public static function get_recent_courses_parameters() {
3898 return new external_function_parameters(
3899 array(
3900 'userid' => new external_value(PARAM_INT, 'id of the user, default to current user', VALUE_DEFAULT, 0),
3901 'limit' => new external_value(PARAM_INT, 'result set limit', VALUE_DEFAULT, 0),
3902 'offset' => new external_value(PARAM_INT, 'Result set offset', VALUE_DEFAULT, 0),
3903 'sort' => new external_value(PARAM_TEXT, 'Sort string', VALUE_DEFAULT, null)
3909 * Get last accessed courses adding additional course information like images.
3911 * @param int $userid User id from which the courses will be obtained
3912 * @param int $limit Restrict result set to this amount
3913 * @param int $offset Skip this number of records from the start of the result set
3914 * @param string|null $sort SQL string for sorting
3915 * @return array List of courses
3916 * @throws invalid_parameter_exception
3918 public static function get_recent_courses(int $userid = 0, int $limit = 0, int $offset = 0, string $sort = null) {
3919 global $USER, $PAGE;
3921 if (empty($userid)) {
3922 $userid = $USER->id;
3925 $params = self::validate_parameters(self::get_recent_courses_parameters(),
3926 array(
3927 'userid' => $userid,
3928 'limit' => $limit,
3929 'offset' => $offset,
3930 'sort' => $sort
3934 $userid = $params['userid'];
3935 $limit = $params['limit'];
3936 $offset = $params['offset'];
3937 $sort = $params['sort'];
3939 $usercontext = context_user::instance($userid);
3941 self::validate_context($usercontext);
3943 if ($userid != $USER->id and !has_capability('moodle/user:viewdetails', $usercontext)) {
3944 return array();
3947 $courses = course_get_recent_courses($userid, $limit, $offset, $sort);
3949 $renderer = $PAGE->get_renderer('core');
3951 $recentcourses = array_map(function($course) use ($renderer) {
3952 context_helper::preload_from_record($course);
3953 $context = context_course::instance($course->id);
3954 $isfavourite = !empty($course->component);
3955 $exporter = new course_summary_exporter($course, ['context' => $context, 'isfavourite' => $isfavourite]);
3956 return $exporter->export($renderer);
3957 }, $courses);
3959 return $recentcourses;
3963 * Returns description of method result value
3965 * @return external_description
3966 * @since Moodle 3.6
3968 public static function get_recent_courses_returns() {
3969 return new external_multiple_structure(course_summary_exporter::get_read_structure(), 'Courses');