2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
21 * @package core_course
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");
34 * Course external functions
36 * @package core_course
38 * @copyright 2011 Jerome Mouneyrac
39 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
42 class core_course_external extends external_api {
45 * Returns description of method parameters
47 * @return external_function_parameters
48 * @since Moodle 2.9 Options available
51 public static function get_course_contents_parameters() {
52 return new external_function_parameters(
53 array('courseid' => new external_value(PARAM_INT, 'course id'),
54 'options' => new external_multiple_structure (
55 new external_single_structure(
57 'name' => new external_value(PARAM_ALPHANUM,
58 'The expected keys (value format) are:
59 excludemodules (bool) Do not return modules, return only the sections structure
60 excludecontents (bool) Do not return module contents (i.e: files inside a resource)
61 includestealthmodules (bool) Return stealth modules for students in a special
63 sectionid (int) Return only this section
64 sectionnumber (int) Return only this section with number (order)
65 cmid (int) Return only this module information (among the whole sections structure)
66 modname (string) Return only modules with this name "label, forum, etc..."
67 modid (int) Return only the module with this id (to be used with modname'),
68 'value' => new external_value(PARAM_RAW, 'the value of the option,
69 this param is personaly validated in the external function.')
71 ), 'Options, used since Moodle 2.9', VALUE_DEFAULT, array())
79 * @param int $courseid course id
80 * @param array $options Options for filtering the results, used since Moodle 2.9
82 * @since Moodle 2.9 Options available
85 public static function get_course_contents($courseid, $options = array()) {
87 require_once($CFG->dirroot . "/course/lib.php");
90 $params = self::validate_parameters(self::get_course_contents_parameters(),
91 array('courseid' => $courseid, 'options' => $options));
94 if (!empty($params['options'])) {
96 foreach ($params['options'] as $option) {
97 $name = trim($option['name']);
98 // Avoid duplicated options.
99 if (!isset($filters[$name])) {
101 case 'excludemodules':
102 case 'excludecontents':
103 case 'includestealthmodules':
104 $value = clean_param($option['value'], PARAM_BOOL);
105 $filters[$name] = $value;
108 case 'sectionnumber':
111 $value = clean_param($option['value'], PARAM_INT);
112 if (is_numeric($value)) {
113 $filters[$name] = $value;
115 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
119 $value = clean_param($option['value'], PARAM_PLUGIN);
121 $filters[$name] = $value;
123 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
127 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
133 //retrieve the course
134 $course = $DB->get_record('course', array('id' => $params['courseid']), '*', MUST_EXIST);
136 if ($course->id != SITEID) {
137 // Check course format exist.
138 if (!file_exists($CFG->dirroot . '/course/format/' . $course->format . '/lib.php')) {
139 throw new moodle_exception('cannotgetcoursecontents', 'webservice', '', null,
140 get_string('courseformatnotfound', 'error', $course->format));
142 require_once($CFG->dirroot . '/course/format/' . $course->format . '/lib.php');
146 // now security checks
147 $context = context_course::instance($course->id, IGNORE_MISSING);
149 self::validate_context($context);
150 } catch (Exception $e) {
151 $exceptionparam = new stdClass();
152 $exceptionparam->message = $e->getMessage();
153 $exceptionparam->courseid = $course->id;
154 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
157 $canupdatecourse = has_capability('moodle/course:update', $context);
159 //create return value
160 $coursecontents = array();
162 if ($canupdatecourse or $course->visible
163 or has_capability('moodle/course:viewhiddencourses', $context)) {
166 $modinfo = get_fast_modinfo($course);
167 $sections = $modinfo->get_section_info_all();
168 $coursenumsections = course_get_format($course)->get_last_section_number();
169 $stealthmodules = array(); // Array to keep all the modules available but not visible in a course section/topic.
171 //for each sections (first displayed to last displayed)
172 $modinfosections = $modinfo->get_sections();
173 foreach ($sections as $key => $section) {
175 // This becomes true when we are filtering and we found the value to filter with.
176 $sectionfound = false;
178 // Filter by section id.
179 if (!empty($filters['sectionid'])) {
180 if ($section->id != $filters['sectionid']) {
183 $sectionfound = true;
187 // Filter by section number. Note that 0 is a valid section number.
188 if (isset($filters['sectionnumber'])) {
189 if ($key != $filters['sectionnumber']) {
192 $sectionfound = true;
196 // reset $sectioncontents
197 $sectionvalues = array();
198 $sectionvalues['id'] = $section->id;
199 $sectionvalues['name'] = get_section_name($course, $section);
200 $sectionvalues['visible'] = $section->visible;
202 $options = (object) array('noclean' => true);
203 list($sectionvalues['summary'], $sectionvalues['summaryformat']) =
204 external_format_text($section->summary, $section->summaryformat,
205 $context->id, 'course', 'section', $section->id, $options);
206 $sectionvalues['section'] = $section->section;
207 $sectionvalues['hiddenbynumsections'] = $section->section > $coursenumsections ? 1 : 0;
208 $sectionvalues['uservisible'] = $section->uservisible;
209 if (!empty($section->availableinfo)) {
210 $sectionvalues['availabilityinfo'] = \core_availability\info::format_info($section->availableinfo, $course);
213 $sectioncontents = array();
215 // For each module of the section.
216 if (empty($filters['excludemodules']) and !empty($modinfosections[$section->section])) {
217 foreach ($modinfosections[$section->section] as $cmid) {
218 $cm = $modinfo->cms[$cmid];
220 // Stop here if the module is not visible to the user on the course main page:
221 // The user can't access the module and the user can't view the module on the course page.
222 if (!$cm->uservisible && !$cm->is_visible_on_course_page()) {
226 // This becomes true when we are filtering and we found the value to filter with.
230 if (!empty($filters['cmid'])) {
231 if ($cmid != $filters['cmid']) {
238 // Filter by module name and id.
239 if (!empty($filters['modname'])) {
240 if ($cm->modname != $filters['modname']) {
242 } else if (!empty($filters['modid'])) {
243 if ($cm->instance != $filters['modid']) {
246 // Note that if we are only filtering by modname we don't break the loop.
254 $modcontext = context_module::instance($cm->id);
256 //common info (for people being able to see the module or availability dates)
257 $module['id'] = $cm->id;
258 $module['name'] = external_format_string($cm->name, $modcontext->id);
259 $module['instance'] = $cm->instance;
260 $module['modname'] = $cm->modname;
261 $module['modplural'] = $cm->modplural;
262 $module['modicon'] = $cm->get_icon_url()->out(false);
263 $module['indent'] = $cm->indent;
265 if (!empty($cm->showdescription) or $cm->modname == 'label') {
266 // We want to use the external format. However from reading get_formatted_content(), $cm->content format is always FORMAT_HTML.
267 $options = array('noclean' => true);
268 list($module['description'], $descriptionformat) = external_format_text($cm->content,
269 FORMAT_HTML, $modcontext->id, $cm->modname, 'intro', $cm->id, $options);
274 if ($url) { //labels don't have url
275 $module['url'] = $url->out(false);
278 $canviewhidden = has_capability('moodle/course:viewhiddenactivities',
279 context_module::instance($cm->id));
280 //user that can view hidden module should know about the visibility
281 $module['visible'] = $cm->visible;
282 $module['visibleoncoursepage'] = $cm->visibleoncoursepage;
283 $module['uservisible'] = $cm->uservisible;
284 if (!empty($cm->availableinfo)) {
285 $module['availabilityinfo'] = \core_availability\info::format_info($cm->availableinfo, $course);
288 // Availability date (also send to user who can see hidden module).
289 if ($CFG->enableavailability && ($canviewhidden || $canupdatecourse)) {
290 $module['availability'] = $cm->availability;
293 // Return contents only if the user can access to the module.
294 if ($cm->uservisible) {
295 $baseurl = 'webservice/pluginfile.php';
297 // Call $modulename_export_contents (each module callback take care about checking the capabilities).
298 require_once($CFG->dirroot . '/mod/' . $cm->modname . '/lib.php');
299 $getcontentfunction = $cm->modname.'_export_contents';
300 if (function_exists($getcontentfunction)) {
301 if (empty($filters['excludecontents']) and $contents = $getcontentfunction($cm, $baseurl)) {
302 $module['contents'] = $contents;
304 $module['contents'] = array();
309 // Assign result to $sectioncontents, there is an exception,
310 // stealth activities in non-visible sections for students go to a special section.
311 if (!empty($filters['includestealthmodules']) && !$section->uservisible && $cm->is_stealth()) {
312 $stealthmodules[] = $module;
314 $sectioncontents[] = $module;
317 // If we just did a filtering, break the loop.
324 $sectionvalues['modules'] = $sectioncontents;
326 // assign result to $coursecontents
327 $coursecontents[$key] = $sectionvalues;
329 // Break the loop if we are filtering.
335 // Now that we have iterated over all the sections and activities, check the visibility.
336 // We didn't this before to be able to retrieve stealth activities.
337 foreach ($coursecontents as $sectionnumber => $sectioncontents) {
338 $section = $sections[$sectionnumber];
339 // Show the section if the user is permitted to access it, OR if it's not available
340 // but there is some available info text which explains the reason & should display.
341 $showsection = $section->uservisible ||
342 ($section->visible && !$section->available &&
343 !empty($section->availableinfo));
346 unset($coursecontents[$sectionnumber]);
350 // Remove modules information if the section is not visible for the user.
351 if (!$section->uservisible) {
352 $coursecontents[$sectionnumber]['modules'] = array();
356 // Include stealth modules in special section (without any info).
357 if (!empty($stealthmodules)) {
358 $coursecontents[] = array(
362 'summaryformat' => FORMAT_MOODLE,
363 'modules' => $stealthmodules
368 return $coursecontents;
372 * Returns description of method result value
374 * @return external_description
377 public static function get_course_contents_returns() {
378 return new external_multiple_structure(
379 new external_single_structure(
381 'id' => new external_value(PARAM_INT, 'Section ID'),
382 'name' => new external_value(PARAM_TEXT, 'Section name'),
383 'visible' => new external_value(PARAM_INT, 'is the section visible', VALUE_OPTIONAL),
384 'summary' => new external_value(PARAM_RAW, 'Section description'),
385 'summaryformat' => new external_format_value('summary'),
386 'section' => new external_value(PARAM_INT, 'Section number inside the course', VALUE_OPTIONAL),
387 'hiddenbynumsections' => new external_value(PARAM_INT, 'Whether is a section hidden in the course format',
389 'uservisible' => new external_value(PARAM_BOOL, 'Is the section visible for the user?', VALUE_OPTIONAL),
390 'availabilityinfo' => new external_value(PARAM_RAW, 'Availability information.', VALUE_OPTIONAL),
391 'modules' => new external_multiple_structure(
392 new external_single_structure(
394 'id' => new external_value(PARAM_INT, 'activity id'),
395 'url' => new external_value(PARAM_URL, 'activity url', VALUE_OPTIONAL),
396 'name' => new external_value(PARAM_RAW, 'activity module name'),
397 'instance' => new external_value(PARAM_INT, 'instance id', VALUE_OPTIONAL),
398 'description' => new external_value(PARAM_RAW, 'activity description', VALUE_OPTIONAL),
399 'visible' => new external_value(PARAM_INT, 'is the module visible', VALUE_OPTIONAL),
400 'uservisible' => new external_value(PARAM_BOOL, 'Is the module visible for the user?',
402 'availabilityinfo' => new external_value(PARAM_RAW, 'Availability information.',
404 'visibleoncoursepage' => new external_value(PARAM_INT, 'is the module visible on course page',
406 'modicon' => new external_value(PARAM_URL, 'activity icon url'),
407 'modname' => new external_value(PARAM_PLUGIN, 'activity module type'),
408 'modplural' => new external_value(PARAM_TEXT, 'activity module plural name'),
409 'availability' => new external_value(PARAM_RAW, 'module availability settings', VALUE_OPTIONAL),
410 'indent' => new external_value(PARAM_INT, 'number of identation in the site'),
411 'contents' => new external_multiple_structure(
412 new external_single_structure(
415 'type'=> new external_value(PARAM_TEXT, 'a file or a folder or external link'),
416 'filename'=> new external_value(PARAM_FILE, 'filename'),
417 'filepath'=> new external_value(PARAM_PATH, 'filepath'),
418 'filesize'=> new external_value(PARAM_INT, 'filesize'),
419 'fileurl' => new external_value(PARAM_URL, 'downloadable file url', VALUE_OPTIONAL),
420 'content' => new external_value(PARAM_RAW, 'Raw content, will be used when type is content', VALUE_OPTIONAL),
421 'timecreated' => new external_value(PARAM_INT, 'Time created'),
422 'timemodified' => new external_value(PARAM_INT, 'Time modified'),
423 'sortorder' => new external_value(PARAM_INT, 'Content sort order'),
424 'mimetype' => new external_value(PARAM_RAW, 'File mime type.', VALUE_OPTIONAL),
425 'isexternalfile' => new external_value(PARAM_BOOL, 'Whether is an external file.',
427 'repositorytype' => new external_value(PARAM_PLUGIN, 'The repository type for external files.',
430 // copyright related info
431 'userid' => new external_value(PARAM_INT, 'User who added this content to moodle'),
432 'author' => new external_value(PARAM_TEXT, 'Content owner'),
433 'license' => new external_value(PARAM_TEXT, 'Content license'),
435 ), VALUE_DEFAULT, array()
446 * Returns description of method parameters
448 * @return external_function_parameters
451 public static function get_courses_parameters() {
452 return new external_function_parameters(
453 array('options' => new external_single_structure(
454 array('ids' => new external_multiple_structure(
455 new external_value(PARAM_INT, 'Course id')
456 , 'List of course id. If empty return all courses
457 except front page course.',
459 ), 'options - operator OR is used', VALUE_DEFAULT, array())
467 * @param array $options It contains an array (list of ids)
471 public static function get_courses($options = array()) {
473 require_once($CFG->dirroot . "/course/lib.php");
476 $params = self::validate_parameters(self::get_courses_parameters(),
477 array('options' => $options));
480 if (!array_key_exists('ids', $params['options'])
481 or empty($params['options']['ids'])) {
482 $courses = $DB->get_records('course');
484 $courses = $DB->get_records_list('course', 'id', $params['options']['ids']);
487 //create return value
488 $coursesinfo = array();
489 foreach ($courses as $course) {
491 // now security checks
492 $context = context_course::instance($course->id, IGNORE_MISSING);
493 $courseformatoptions = course_get_format($course)->get_format_options();
495 self::validate_context($context);
496 } catch (Exception $e) {
497 $exceptionparam = new stdClass();
498 $exceptionparam->message = $e->getMessage();
499 $exceptionparam->courseid = $course->id;
500 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
502 if ($course->id != SITEID) {
503 require_capability('moodle/course:view', $context);
506 $courseinfo = array();
507 $courseinfo['id'] = $course->id;
508 $courseinfo['fullname'] = external_format_string($course->fullname, $context->id);
509 $courseinfo['shortname'] = external_format_string($course->shortname, $context->id);
510 $courseinfo['displayname'] = external_format_string(get_course_display_name_for_list($course), $context->id);
511 $courseinfo['categoryid'] = $course->category;
512 list($courseinfo['summary'], $courseinfo['summaryformat']) =
513 external_format_text($course->summary, $course->summaryformat, $context->id, 'course', 'summary', 0);
514 $courseinfo['format'] = $course->format;
515 $courseinfo['startdate'] = $course->startdate;
516 $courseinfo['enddate'] = $course->enddate;
517 if (array_key_exists('numsections', $courseformatoptions)) {
518 // For backward-compartibility
519 $courseinfo['numsections'] = $courseformatoptions['numsections'];
522 //some field should be returned only if the user has update permission
523 $courseadmin = has_capability('moodle/course:update', $context);
525 $courseinfo['categorysortorder'] = $course->sortorder;
526 $courseinfo['idnumber'] = $course->idnumber;
527 $courseinfo['showgrades'] = $course->showgrades;
528 $courseinfo['showreports'] = $course->showreports;
529 $courseinfo['newsitems'] = $course->newsitems;
530 $courseinfo['visible'] = $course->visible;
531 $courseinfo['maxbytes'] = $course->maxbytes;
532 if (array_key_exists('hiddensections', $courseformatoptions)) {
533 // For backward-compartibility
534 $courseinfo['hiddensections'] = $courseformatoptions['hiddensections'];
536 // Return numsections for backward-compatibility with clients who expect it.
537 $courseinfo['numsections'] = course_get_format($course)->get_last_section_number();
538 $courseinfo['groupmode'] = $course->groupmode;
539 $courseinfo['groupmodeforce'] = $course->groupmodeforce;
540 $courseinfo['defaultgroupingid'] = $course->defaultgroupingid;
541 $courseinfo['lang'] = clean_param($course->lang, PARAM_LANG);
542 $courseinfo['timecreated'] = $course->timecreated;
543 $courseinfo['timemodified'] = $course->timemodified;
544 $courseinfo['forcetheme'] = clean_param($course->theme, PARAM_THEME);
545 $courseinfo['enablecompletion'] = $course->enablecompletion;
546 $courseinfo['completionnotify'] = $course->completionnotify;
547 $courseinfo['courseformatoptions'] = array();
548 foreach ($courseformatoptions as $key => $value) {
549 $courseinfo['courseformatoptions'][] = array(
556 if ($courseadmin or $course->visible
557 or has_capability('moodle/course:viewhiddencourses', $context)) {
558 $coursesinfo[] = $courseinfo;
566 * Returns description of method result value
568 * @return external_description
571 public static function get_courses_returns() {
572 return new external_multiple_structure(
573 new external_single_structure(
575 'id' => new external_value(PARAM_INT, 'course id'),
576 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
577 'categoryid' => new external_value(PARAM_INT, 'category id'),
578 'categorysortorder' => new external_value(PARAM_INT,
579 'sort order into the category', VALUE_OPTIONAL),
580 'fullname' => new external_value(PARAM_TEXT, 'full name'),
581 'displayname' => new external_value(PARAM_TEXT, 'course display name'),
582 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
583 'summary' => new external_value(PARAM_RAW, 'summary'),
584 'summaryformat' => new external_format_value('summary'),
585 'format' => new external_value(PARAM_PLUGIN,
586 'course format: weeks, topics, social, site,..'),
587 'showgrades' => new external_value(PARAM_INT,
588 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
589 'newsitems' => new external_value(PARAM_INT,
590 'number of recent items appearing on the course page', VALUE_OPTIONAL),
591 'startdate' => new external_value(PARAM_INT,
592 'timestamp when the course start'),
593 'enddate' => new external_value(PARAM_INT,
594 'timestamp when the course end'),
595 'numsections' => new external_value(PARAM_INT,
596 '(deprecated, use courseformatoptions) number of weeks/topics',
598 'maxbytes' => new external_value(PARAM_INT,
599 'largest size of file that can be uploaded into the course',
601 'showreports' => new external_value(PARAM_INT,
602 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
603 'visible' => new external_value(PARAM_INT,
604 '1: available to student, 0:not available', VALUE_OPTIONAL),
605 'hiddensections' => new external_value(PARAM_INT,
606 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
608 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
610 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
612 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
614 'timecreated' => new external_value(PARAM_INT,
615 'timestamp when the course have been created', VALUE_OPTIONAL),
616 'timemodified' => new external_value(PARAM_INT,
617 'timestamp when the course have been modified', VALUE_OPTIONAL),
618 'enablecompletion' => new external_value(PARAM_INT,
619 'Enabled, control via completion and activity settings. Disbaled,
620 not shown in activity settings.',
622 'completionnotify' => new external_value(PARAM_INT,
623 '1: yes 0: no', VALUE_OPTIONAL),
624 'lang' => new external_value(PARAM_SAFEDIR,
625 'forced course language', VALUE_OPTIONAL),
626 'forcetheme' => new external_value(PARAM_PLUGIN,
627 'name of the force theme', VALUE_OPTIONAL),
628 'courseformatoptions' => new external_multiple_structure(
629 new external_single_structure(
630 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
631 'value' => new external_value(PARAM_RAW, 'course format option value')
633 'additional options for particular course format', VALUE_OPTIONAL
641 * Returns description of method parameters
643 * @return external_function_parameters
646 public static function create_courses_parameters() {
647 $courseconfig = get_config('moodlecourse'); //needed for many default values
648 return new external_function_parameters(
650 'courses' => new external_multiple_structure(
651 new external_single_structure(
653 'fullname' => new external_value(PARAM_TEXT, 'full name'),
654 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
655 'categoryid' => new external_value(PARAM_INT, 'category id'),
656 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
657 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
658 'summaryformat' => new external_format_value('summary', VALUE_DEFAULT),
659 'format' => new external_value(PARAM_PLUGIN,
660 'course format: weeks, topics, social, site,..',
661 VALUE_DEFAULT, $courseconfig->format),
662 'showgrades' => new external_value(PARAM_INT,
663 '1 if grades are shown, otherwise 0', VALUE_DEFAULT,
664 $courseconfig->showgrades),
665 'newsitems' => new external_value(PARAM_INT,
666 'number of recent items appearing on the course page',
667 VALUE_DEFAULT, $courseconfig->newsitems),
668 'startdate' => new external_value(PARAM_INT,
669 'timestamp when the course start', VALUE_OPTIONAL),
670 'enddate' => new external_value(PARAM_INT,
671 'timestamp when the course end', VALUE_OPTIONAL),
672 'numsections' => new external_value(PARAM_INT,
673 '(deprecated, use courseformatoptions) number of weeks/topics',
675 'maxbytes' => new external_value(PARAM_INT,
676 'largest size of file that can be uploaded into the course',
677 VALUE_DEFAULT, $courseconfig->maxbytes),
678 'showreports' => new external_value(PARAM_INT,
679 'are activity report shown (yes = 1, no =0)', VALUE_DEFAULT,
680 $courseconfig->showreports),
681 'visible' => new external_value(PARAM_INT,
682 '1: available to student, 0:not available', VALUE_OPTIONAL),
683 'hiddensections' => new external_value(PARAM_INT,
684 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
686 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
687 VALUE_DEFAULT, $courseconfig->groupmode),
688 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
689 VALUE_DEFAULT, $courseconfig->groupmodeforce),
690 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
692 'enablecompletion' => new external_value(PARAM_INT,
693 'Enabled, control via completion and activity settings. Disabled,
694 not shown in activity settings.',
696 'completionnotify' => new external_value(PARAM_INT,
697 '1: yes 0: no', VALUE_OPTIONAL),
698 'lang' => new external_value(PARAM_SAFEDIR,
699 'forced course language', VALUE_OPTIONAL),
700 'forcetheme' => new external_value(PARAM_PLUGIN,
701 'name of the force theme', VALUE_OPTIONAL),
702 'courseformatoptions' => new external_multiple_structure(
703 new external_single_structure(
704 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
705 'value' => new external_value(PARAM_RAW, 'course format option value')
707 'additional options for particular course format', VALUE_OPTIONAL),
709 ), 'courses to create'
718 * @param array $courses
719 * @return array courses (id and shortname only)
722 public static function create_courses($courses) {
724 require_once($CFG->dirroot . "/course/lib.php");
725 require_once($CFG->libdir . '/completionlib.php');
727 $params = self::validate_parameters(self::create_courses_parameters(),
728 array('courses' => $courses));
730 $availablethemes = core_component::get_plugin_list('theme');
731 $availablelangs = get_string_manager()->get_list_of_translations();
733 $transaction = $DB->start_delegated_transaction();
735 foreach ($params['courses'] as $course) {
737 // Ensure the current user is allowed to run this function
738 $context = context_coursecat::instance($course['categoryid'], IGNORE_MISSING);
740 self::validate_context($context);
741 } catch (Exception $e) {
742 $exceptionparam = new stdClass();
743 $exceptionparam->message = $e->getMessage();
744 $exceptionparam->catid = $course['categoryid'];
745 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
747 require_capability('moodle/course:create', $context);
749 // Make sure lang is valid
750 if (array_key_exists('lang', $course)) {
751 if (empty($availablelangs[$course['lang']])) {
752 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
754 if (!has_capability('moodle/course:setforcedlanguage', $context)) {
755 unset($course['lang']);
759 // Make sure theme is valid
760 if (array_key_exists('forcetheme', $course)) {
761 if (!empty($CFG->allowcoursethemes)) {
762 if (empty($availablethemes[$course['forcetheme']])) {
763 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
765 $course['theme'] = $course['forcetheme'];
770 //force visibility if ws user doesn't have the permission to set it
771 $category = $DB->get_record('course_categories', array('id' => $course['categoryid']));
772 if (!has_capability('moodle/course:visibility', $context)) {
773 $course['visible'] = $category->visible;
776 //set default value for completion
777 $courseconfig = get_config('moodlecourse');
778 if (completion_info::is_enabled_for_site()) {
779 if (!array_key_exists('enablecompletion', $course)) {
780 $course['enablecompletion'] = $courseconfig->enablecompletion;
783 $course['enablecompletion'] = 0;
786 $course['category'] = $course['categoryid'];
789 $course['summaryformat'] = external_validate_format($course['summaryformat']);
791 if (!empty($course['courseformatoptions'])) {
792 foreach ($course['courseformatoptions'] as $option) {
793 $course[$option['name']] = $option['value'];
797 //Note: create_course() core function check shortname, idnumber, category
798 $course['id'] = create_course((object) $course)->id;
800 $resultcourses[] = array('id' => $course['id'], 'shortname' => $course['shortname']);
803 $transaction->allow_commit();
805 return $resultcourses;
809 * Returns description of method result value
811 * @return external_description
814 public static function create_courses_returns() {
815 return new external_multiple_structure(
816 new external_single_structure(
818 'id' => new external_value(PARAM_INT, 'course id'),
819 'shortname' => new external_value(PARAM_TEXT, 'short name'),
828 * @return external_function_parameters
831 public static function update_courses_parameters() {
832 return new external_function_parameters(
834 'courses' => new external_multiple_structure(
835 new external_single_structure(
837 'id' => new external_value(PARAM_INT, 'ID of the course'),
838 'fullname' => new external_value(PARAM_TEXT, 'full name', VALUE_OPTIONAL),
839 'shortname' => new external_value(PARAM_TEXT, 'course short name', VALUE_OPTIONAL),
840 'categoryid' => new external_value(PARAM_INT, 'category id', VALUE_OPTIONAL),
841 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
842 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
843 'summaryformat' => new external_format_value('summary', VALUE_OPTIONAL),
844 'format' => new external_value(PARAM_PLUGIN,
845 'course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
846 'showgrades' => new external_value(PARAM_INT,
847 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
848 'newsitems' => new external_value(PARAM_INT,
849 'number of recent items appearing on the course page', VALUE_OPTIONAL),
850 'startdate' => new external_value(PARAM_INT,
851 'timestamp when the course start', VALUE_OPTIONAL),
852 'enddate' => new external_value(PARAM_INT,
853 'timestamp when the course end', VALUE_OPTIONAL),
854 'numsections' => new external_value(PARAM_INT,
855 '(deprecated, use courseformatoptions) number of weeks/topics', VALUE_OPTIONAL),
856 'maxbytes' => new external_value(PARAM_INT,
857 'largest size of file that can be uploaded into the course', VALUE_OPTIONAL),
858 'showreports' => new external_value(PARAM_INT,
859 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
860 'visible' => new external_value(PARAM_INT,
861 '1: available to student, 0:not available', VALUE_OPTIONAL),
862 'hiddensections' => new external_value(PARAM_INT,
863 '(deprecated, use courseformatoptions) How the hidden sections in the course are
864 displayed to students', VALUE_OPTIONAL),
865 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
866 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
867 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
868 'enablecompletion' => new external_value(PARAM_INT,
869 'Enabled, control via completion and activity settings. Disabled,
870 not shown in activity settings.', VALUE_OPTIONAL),
871 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
872 'lang' => new external_value(PARAM_SAFEDIR, 'forced course language', VALUE_OPTIONAL),
873 'forcetheme' => new external_value(PARAM_PLUGIN, 'name of the force theme', VALUE_OPTIONAL),
874 'courseformatoptions' => new external_multiple_structure(
875 new external_single_structure(
876 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
877 'value' => new external_value(PARAM_RAW, 'course format option value')
879 'additional options for particular course format', VALUE_OPTIONAL),
881 ), 'courses to update'
890 * @param array $courses
893 public static function update_courses($courses) {
895 require_once($CFG->dirroot . "/course/lib.php");
898 $params = self::validate_parameters(self::update_courses_parameters(),
899 array('courses' => $courses));
901 $availablethemes = core_component::get_plugin_list('theme');
902 $availablelangs = get_string_manager()->get_list_of_translations();
904 foreach ($params['courses'] as $course) {
905 // Catch any exception while updating course and return as warning to user.
907 // Ensure the current user is allowed to run this function.
908 $context = context_course::instance($course['id'], MUST_EXIST);
909 self::validate_context($context);
911 $oldcourse = course_get_format($course['id'])->get_course();
913 require_capability('moodle/course:update', $context);
915 // Check if user can change category.
916 if (array_key_exists('categoryid', $course) && ($oldcourse->category != $course['categoryid'])) {
917 require_capability('moodle/course:changecategory', $context);
918 $course['category'] = $course['categoryid'];
921 // Check if the user can change fullname.
922 if (array_key_exists('fullname', $course) && ($oldcourse->fullname != $course['fullname'])) {
923 require_capability('moodle/course:changefullname', $context);
926 // Check if the user can change shortname.
927 if (array_key_exists('shortname', $course) && ($oldcourse->shortname != $course['shortname'])) {
928 require_capability('moodle/course:changeshortname', $context);
931 // Check if the user can change the idnumber.
932 if (array_key_exists('idnumber', $course) && ($oldcourse->idnumber != $course['idnumber'])) {
933 require_capability('moodle/course:changeidnumber', $context);
936 // Check if user can change summary.
937 if (array_key_exists('summary', $course) && ($oldcourse->summary != $course['summary'])) {
938 require_capability('moodle/course:changesummary', $context);
942 if (array_key_exists('summaryformat', $course) && ($oldcourse->summaryformat != $course['summaryformat'])) {
943 require_capability('moodle/course:changesummary', $context);
944 $course['summaryformat'] = external_validate_format($course['summaryformat']);
947 // Check if user can change visibility.
948 if (array_key_exists('visible', $course) && ($oldcourse->visible != $course['visible'])) {
949 require_capability('moodle/course:visibility', $context);
952 // Make sure lang is valid.
953 if (array_key_exists('lang', $course) && ($oldcourse->lang != $course['lang'])) {
954 require_capability('moodle/course:setforcedlanguage', $context);
955 if (empty($availablelangs[$course['lang']])) {
956 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
960 // Make sure theme is valid.
961 if (array_key_exists('forcetheme', $course)) {
962 if (!empty($CFG->allowcoursethemes)) {
963 if (empty($availablethemes[$course['forcetheme']])) {
964 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
966 $course['theme'] = $course['forcetheme'];
971 // Make sure completion is enabled before setting it.
972 if (array_key_exists('enabledcompletion', $course) && !completion_info::is_enabled_for_site()) {
973 $course['enabledcompletion'] = 0;
976 // Make sure maxbytes are less then CFG->maxbytes.
977 if (array_key_exists('maxbytes', $course)) {
978 // We allow updates back to 0 max bytes, a special value denoting the course uses the site limit.
979 // Otherwise, either use the size specified, or cap at the max size for the course.
980 if ($course['maxbytes'] != 0) {
981 $course['maxbytes'] = get_max_upload_file_size($CFG->maxbytes, $course['maxbytes']);
985 if (!empty($course['courseformatoptions'])) {
986 foreach ($course['courseformatoptions'] as $option) {
987 if (isset($option['name']) && isset($option['value'])) {
988 $course[$option['name']] = $option['value'];
993 // Update course if user has all required capabilities.
994 update_course((object) $course);
995 } catch (Exception $e) {
997 $warning['item'] = 'course';
998 $warning['itemid'] = $course['id'];
999 if ($e instanceof moodle_exception) {
1000 $warning['warningcode'] = $e->errorcode;
1002 $warning['warningcode'] = $e->getCode();
1004 $warning['message'] = $e->getMessage();
1005 $warnings[] = $warning;
1010 $result['warnings'] = $warnings;
1015 * Returns description of method result value
1017 * @return external_description
1020 public static function update_courses_returns() {
1021 return new external_single_structure(
1023 'warnings' => new external_warnings()
1029 * Returns description of method parameters
1031 * @return external_function_parameters
1034 public static function delete_courses_parameters() {
1035 return new external_function_parameters(
1037 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'course ID')),
1045 * @param array $courseids A list of course ids
1048 public static function delete_courses($courseids) {
1050 require_once($CFG->dirroot."/course/lib.php");
1052 // Parameter validation.
1053 $params = self::validate_parameters(self::delete_courses_parameters(), array('courseids'=>$courseids));
1055 $warnings = array();
1057 foreach ($params['courseids'] as $courseid) {
1058 $course = $DB->get_record('course', array('id' => $courseid));
1060 if ($course === false) {
1061 $warnings[] = array(
1063 'itemid' => $courseid,
1064 'warningcode' => 'unknowncourseidnumber',
1065 'message' => 'Unknown course ID ' . $courseid
1070 // Check if the context is valid.
1071 $coursecontext = context_course::instance($course->id);
1072 self::validate_context($coursecontext);
1074 // Check if the current user has permission.
1075 if (!can_delete_course($courseid)) {
1076 $warnings[] = array(
1078 'itemid' => $courseid,
1079 'warningcode' => 'cannotdeletecourse',
1080 'message' => 'You do not have the permission to delete this course' . $courseid
1085 if (delete_course($course, false) === false) {
1086 $warnings[] = array(
1088 'itemid' => $courseid,
1089 'warningcode' => 'cannotdeletecategorycourse',
1090 'message' => 'Course ' . $courseid . ' failed to be deleted'
1096 fix_course_sortorder();
1098 return array('warnings' => $warnings);
1102 * Returns description of method result value
1104 * @return external_description
1107 public static function delete_courses_returns() {
1108 return new external_single_structure(
1110 'warnings' => new external_warnings()
1116 * Returns description of method parameters
1118 * @return external_function_parameters
1121 public static function duplicate_course_parameters() {
1122 return new external_function_parameters(
1124 'courseid' => new external_value(PARAM_INT, 'course to duplicate id'),
1125 'fullname' => new external_value(PARAM_TEXT, 'duplicated course full name'),
1126 'shortname' => new external_value(PARAM_TEXT, 'duplicated course short name'),
1127 'categoryid' => new external_value(PARAM_INT, 'duplicated course category parent'),
1128 'visible' => new external_value(PARAM_INT, 'duplicated course visible, default to yes', VALUE_DEFAULT, 1),
1129 'options' => new external_multiple_structure(
1130 new external_single_structure(
1132 'name' => new external_value(PARAM_ALPHAEXT, 'The backup option name:
1133 "activities" (int) Include course activites (default to 1 that is equal to yes),
1134 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1135 "filters" (int) Include course filters (default to 1 that is equal to yes),
1136 "users" (int) Include users (default to 0 that is equal to no),
1137 "enrolments" (int) Include enrolment methods (default to 1 - restore only with users),
1138 "role_assignments" (int) Include role assignments (default to 0 that is equal to no),
1139 "comments" (int) Include user comments (default to 0 that is equal to no),
1140 "userscompletion" (int) Include user course completion information (default to 0 that is equal to no),
1141 "logs" (int) Include course logs (default to 0 that is equal to no),
1142 "grade_histories" (int) Include histories (default to 0 that is equal to no)'
1144 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1147 ), VALUE_DEFAULT, array()
1154 * Duplicate a course
1156 * @param int $courseid
1157 * @param string $fullname Duplicated course fullname
1158 * @param string $shortname Duplicated course shortname
1159 * @param int $categoryid Duplicated course parent category id
1160 * @param int $visible Duplicated course availability
1161 * @param array $options List of backup options
1162 * @return array New course info
1165 public static function duplicate_course($courseid, $fullname, $shortname, $categoryid, $visible = 1, $options = array()) {
1166 global $CFG, $USER, $DB;
1167 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1168 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1170 // Parameter validation.
1171 $params = self::validate_parameters(
1172 self::duplicate_course_parameters(),
1174 'courseid' => $courseid,
1175 'fullname' => $fullname,
1176 'shortname' => $shortname,
1177 'categoryid' => $categoryid,
1178 'visible' => $visible,
1179 'options' => $options
1183 // Context validation.
1185 if (! ($course = $DB->get_record('course', array('id'=>$params['courseid'])))) {
1186 throw new moodle_exception('invalidcourseid', 'error');
1189 // Category where duplicated course is going to be created.
1190 $categorycontext = context_coursecat::instance($params['categoryid']);
1191 self::validate_context($categorycontext);
1193 // Course to be duplicated.
1194 $coursecontext = context_course::instance($course->id);
1195 self::validate_context($coursecontext);
1197 $backupdefaults = array(
1202 'enrolments' => backup::ENROL_WITHUSERS,
1203 'role_assignments' => 0,
1205 'userscompletion' => 0,
1207 'grade_histories' => 0
1210 $backupsettings = array();
1211 // Check for backup and restore options.
1212 if (!empty($params['options'])) {
1213 foreach ($params['options'] as $option) {
1215 // Strict check for a correct value (allways 1 or 0, true or false).
1216 $value = clean_param($option['value'], PARAM_INT);
1218 if ($value !== 0 and $value !== 1) {
1219 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1222 if (!isset($backupdefaults[$option['name']])) {
1223 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1226 $backupsettings[$option['name']] = $value;
1230 // Capability checking.
1232 // The backup controller check for this currently, this may be redundant.
1233 require_capability('moodle/course:create', $categorycontext);
1234 require_capability('moodle/restore:restorecourse', $categorycontext);
1235 require_capability('moodle/backup:backupcourse', $coursecontext);
1237 if (!empty($backupsettings['users'])) {
1238 require_capability('moodle/backup:userinfo', $coursecontext);
1239 require_capability('moodle/restore:userinfo', $categorycontext);
1242 // Check if the shortname is used.
1243 if ($foundcourses = $DB->get_records('course', array('shortname'=>$shortname))) {
1244 foreach ($foundcourses as $foundcourse) {
1245 $foundcoursenames[] = $foundcourse->fullname;
1248 $foundcoursenamestring = implode(',', $foundcoursenames);
1249 throw new moodle_exception('shortnametaken', '', '', $foundcoursenamestring);
1252 // Backup the course.
1254 $bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE,
1255 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id);
1257 foreach ($backupsettings as $name => $value) {
1258 if ($setting = $bc->get_plan()->get_setting($name)) {
1259 $bc->get_plan()->get_setting($name)->set_value($value);
1263 $backupid = $bc->get_backupid();
1264 $backupbasepath = $bc->get_plan()->get_basepath();
1266 $bc->execute_plan();
1267 $results = $bc->get_results();
1268 $file = $results['backup_destination'];
1272 // Restore the backup immediately.
1274 // Check if we need to unzip the file because the backup temp dir does not contains backup files.
1275 if (!file_exists($backupbasepath . "/moodle_backup.xml")) {
1276 $file->extract_to_pathname(get_file_packer('application/vnd.moodle.backup'), $backupbasepath);
1279 // Create new course.
1280 $newcourseid = restore_dbops::create_new_course($params['fullname'], $params['shortname'], $params['categoryid']);
1282 $rc = new restore_controller($backupid, $newcourseid,
1283 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id, backup::TARGET_NEW_COURSE);
1285 foreach ($backupsettings as $name => $value) {
1286 $setting = $rc->get_plan()->get_setting($name);
1287 if ($setting->get_status() == backup_setting::NOT_LOCKED) {
1288 $setting->set_value($value);
1292 if (!$rc->execute_precheck()) {
1293 $precheckresults = $rc->get_precheck_results();
1294 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1295 if (empty($CFG->keeptempdirectoriesonbackup)) {
1296 fulldelete($backupbasepath);
1301 foreach ($precheckresults['errors'] as $error) {
1302 $errorinfo .= $error;
1305 if (array_key_exists('warnings', $precheckresults)) {
1306 foreach ($precheckresults['warnings'] as $warning) {
1307 $errorinfo .= $warning;
1311 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1315 $rc->execute_plan();
1318 $course = $DB->get_record('course', array('id' => $newcourseid), '*', MUST_EXIST);
1319 $course->fullname = $params['fullname'];
1320 $course->shortname = $params['shortname'];
1321 $course->visible = $params['visible'];
1323 // Set shortname and fullname back.
1324 $DB->update_record('course', $course);
1326 if (empty($CFG->keeptempdirectoriesonbackup)) {
1327 fulldelete($backupbasepath);
1330 // Delete the course backup file created by this WebService. Originally located in the course backups area.
1333 return array('id' => $course->id, 'shortname' => $course->shortname);
1337 * Returns description of method result value
1339 * @return external_description
1342 public static function duplicate_course_returns() {
1343 return new external_single_structure(
1345 'id' => new external_value(PARAM_INT, 'course id'),
1346 'shortname' => new external_value(PARAM_TEXT, 'short name'),
1352 * Returns description of method parameters for import_course
1354 * @return external_function_parameters
1357 public static function import_course_parameters() {
1358 return new external_function_parameters(
1360 'importfrom' => new external_value(PARAM_INT, 'the id of the course we are importing from'),
1361 'importto' => new external_value(PARAM_INT, 'the id of the course we are importing to'),
1362 'deletecontent' => new external_value(PARAM_INT, 'whether to delete the course content where we are importing to (default to 0 = No)', VALUE_DEFAULT, 0),
1363 'options' => new external_multiple_structure(
1364 new external_single_structure(
1366 'name' => new external_value(PARAM_ALPHA, 'The backup option name:
1367 "activities" (int) Include course activites (default to 1 that is equal to yes),
1368 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1369 "filters" (int) Include course filters (default to 1 that is equal to yes)'
1371 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1374 ), VALUE_DEFAULT, array()
1383 * @param int $importfrom The id of the course we are importing from
1384 * @param int $importto The id of the course we are importing to
1385 * @param bool $deletecontent Whether to delete the course we are importing to content
1386 * @param array $options List of backup options
1390 public static function import_course($importfrom, $importto, $deletecontent = 0, $options = array()) {
1391 global $CFG, $USER, $DB;
1392 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1393 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1395 // Parameter validation.
1396 $params = self::validate_parameters(
1397 self::import_course_parameters(),
1399 'importfrom' => $importfrom,
1400 'importto' => $importto,
1401 'deletecontent' => $deletecontent,
1402 'options' => $options
1406 if ($params['deletecontent'] !== 0 and $params['deletecontent'] !== 1) {
1407 throw new moodle_exception('invalidextparam', 'webservice', '', $params['deletecontent']);
1410 // Context validation.
1412 if (! ($importfrom = $DB->get_record('course', array('id'=>$params['importfrom'])))) {
1413 throw new moodle_exception('invalidcourseid', 'error');
1416 if (! ($importto = $DB->get_record('course', array('id'=>$params['importto'])))) {
1417 throw new moodle_exception('invalidcourseid', 'error');
1420 $importfromcontext = context_course::instance($importfrom->id);
1421 self::validate_context($importfromcontext);
1423 $importtocontext = context_course::instance($importto->id);
1424 self::validate_context($importtocontext);
1426 $backupdefaults = array(
1432 $backupsettings = array();
1434 // Check for backup and restore options.
1435 if (!empty($params['options'])) {
1436 foreach ($params['options'] as $option) {
1438 // Strict check for a correct value (allways 1 or 0, true or false).
1439 $value = clean_param($option['value'], PARAM_INT);
1441 if ($value !== 0 and $value !== 1) {
1442 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1445 if (!isset($backupdefaults[$option['name']])) {
1446 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1449 $backupsettings[$option['name']] = $value;
1453 // Capability checking.
1455 require_capability('moodle/backup:backuptargetimport', $importfromcontext);
1456 require_capability('moodle/restore:restoretargetimport', $importtocontext);
1458 $bc = new backup_controller(backup::TYPE_1COURSE, $importfrom->id, backup::FORMAT_MOODLE,
1459 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
1461 foreach ($backupsettings as $name => $value) {
1462 $bc->get_plan()->get_setting($name)->set_value($value);
1465 $backupid = $bc->get_backupid();
1466 $backupbasepath = $bc->get_plan()->get_basepath();
1468 $bc->execute_plan();
1471 // Restore the backup immediately.
1473 // Check if we must delete the contents of the destination course.
1474 if ($params['deletecontent']) {
1475 $restoretarget = backup::TARGET_EXISTING_DELETING;
1477 $restoretarget = backup::TARGET_EXISTING_ADDING;
1480 $rc = new restore_controller($backupid, $importto->id,
1481 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, $restoretarget);
1483 foreach ($backupsettings as $name => $value) {
1484 $rc->get_plan()->get_setting($name)->set_value($value);
1487 if (!$rc->execute_precheck()) {
1488 $precheckresults = $rc->get_precheck_results();
1489 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1490 if (empty($CFG->keeptempdirectoriesonbackup)) {
1491 fulldelete($backupbasepath);
1496 foreach ($precheckresults['errors'] as $error) {
1497 $errorinfo .= $error;
1500 if (array_key_exists('warnings', $precheckresults)) {
1501 foreach ($precheckresults['warnings'] as $warning) {
1502 $errorinfo .= $warning;
1506 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1509 if ($restoretarget == backup::TARGET_EXISTING_DELETING) {
1510 restore_dbops::delete_course_content($importto->id);
1514 $rc->execute_plan();
1517 if (empty($CFG->keeptempdirectoriesonbackup)) {
1518 fulldelete($backupbasepath);
1525 * Returns description of method result value
1527 * @return external_description
1530 public static function import_course_returns() {
1535 * Returns description of method parameters
1537 * @return external_function_parameters
1540 public static function get_categories_parameters() {
1541 return new external_function_parameters(
1543 'criteria' => new external_multiple_structure(
1544 new external_single_structure(
1546 'key' => new external_value(PARAM_ALPHA,
1547 'The category column to search, expected keys (value format) are:'.
1548 '"id" (int) the category id,'.
1549 '"ids" (string) category ids separated by commas,'.
1550 '"name" (string) the category name,'.
1551 '"parent" (int) the parent category id,'.
1552 '"idnumber" (string) category idnumber'.
1553 ' - user must have \'moodle/category:manage\' to search on idnumber,'.
1554 '"visible" (int) whether the returned categories must be visible or hidden. If the key is not passed,
1555 then the function return all categories that the user can see.'.
1556 ' - user must have \'moodle/category:manage\' or \'moodle/category:viewhiddencategories\' to search on visible,'.
1557 '"theme" (string) only return the categories having this theme'.
1558 ' - user must have \'moodle/category:manage\' to search on theme'),
1559 'value' => new external_value(PARAM_RAW, 'the value to match')
1561 ), 'criteria', VALUE_DEFAULT, array()
1563 'addsubcategories' => new external_value(PARAM_BOOL, 'return the sub categories infos
1564 (1 - default) otherwise only the category info (0)', VALUE_DEFAULT, 1)
1572 * @param array $criteria Criteria to match the results
1573 * @param booln $addsubcategories obtain only the category (false) or its subcategories (true - default)
1574 * @return array list of categories
1577 public static function get_categories($criteria = array(), $addsubcategories = true) {
1579 require_once($CFG->dirroot . "/course/lib.php");
1581 // Validate parameters.
1582 $params = self::validate_parameters(self::get_categories_parameters(),
1583 array('criteria' => $criteria, 'addsubcategories' => $addsubcategories));
1585 // Retrieve the categories.
1586 $categories = array();
1587 if (!empty($params['criteria'])) {
1589 $conditions = array();
1591 foreach ($params['criteria'] as $crit) {
1592 $key = trim($crit['key']);
1594 // Trying to avoid duplicate keys.
1595 if (!isset($conditions[$key])) {
1597 $context = context_system::instance();
1601 $value = clean_param($crit['value'], PARAM_INT);
1602 $conditions[$key] = $value;
1603 $wheres[] = $key . " = :" . $key;
1607 $value = clean_param($crit['value'], PARAM_SEQUENCE);
1608 $ids = explode(',', $value);
1609 list($sqlids, $paramids) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED);
1610 $conditions = array_merge($conditions, $paramids);
1611 $wheres[] = 'id ' . $sqlids;
1615 if (has_capability('moodle/category:manage', $context)) {
1616 $value = clean_param($crit['value'], PARAM_RAW);
1617 $conditions[$key] = $value;
1618 $wheres[] = $key . " = :" . $key;
1620 // We must throw an exception.
1621 // Otherwise the dev client would think no idnumber exists.
1622 throw new moodle_exception('criteriaerror',
1623 'webservice', '', null,
1624 'You don\'t have the permissions to search on the "idnumber" field.');
1629 $value = clean_param($crit['value'], PARAM_TEXT);
1630 $conditions[$key] = $value;
1631 $wheres[] = $key . " = :" . $key;
1635 $value = clean_param($crit['value'], PARAM_INT);
1636 $conditions[$key] = $value;
1637 $wheres[] = $key . " = :" . $key;
1641 if (has_capability('moodle/category:viewhiddencategories', $context)) {
1642 $value = clean_param($crit['value'], PARAM_INT);
1643 $conditions[$key] = $value;
1644 $wheres[] = $key . " = :" . $key;
1646 throw new moodle_exception('criteriaerror',
1647 'webservice', '', null,
1648 'You don\'t have the permissions to search on the "visible" field.');
1653 if (has_capability('moodle/category:manage', $context)) {
1654 $value = clean_param($crit['value'], PARAM_THEME);
1655 $conditions[$key] = $value;
1656 $wheres[] = $key . " = :" . $key;
1658 throw new moodle_exception('criteriaerror',
1659 'webservice', '', null,
1660 'You don\'t have the permissions to search on the "theme" field.');
1665 throw new moodle_exception('criteriaerror',
1666 'webservice', '', null,
1667 'You can not search on this criteria: ' . $key);
1672 if (!empty($wheres)) {
1673 $wheres = implode(" AND ", $wheres);
1675 $categories = $DB->get_records_select('course_categories', $wheres, $conditions);
1677 // Retrieve its sub subcategories (all levels).
1678 if ($categories and !empty($params['addsubcategories'])) {
1679 $newcategories = array();
1681 // Check if we required visible/theme checks.
1682 $additionalselect = '';
1683 $additionalparams = array();
1684 if (isset($conditions['visible'])) {
1685 $additionalselect .= ' AND visible = :visible';
1686 $additionalparams['visible'] = $conditions['visible'];
1688 if (isset($conditions['theme'])) {
1689 $additionalselect .= ' AND theme= :theme';
1690 $additionalparams['theme'] = $conditions['theme'];
1693 foreach ($categories as $category) {
1694 $sqlselect = $DB->sql_like('path', ':path') . $additionalselect;
1695 $sqlparams = array('path' => $category->path.'/%') + $additionalparams; // It will NOT include the specified category.
1696 $subcategories = $DB->get_records_select('course_categories', $sqlselect, $sqlparams);
1697 $newcategories = $newcategories + $subcategories; // Both arrays have integer as keys.
1699 $categories = $categories + $newcategories;
1704 // Retrieve all categories in the database.
1705 $categories = $DB->get_records('course_categories');
1708 // The not returned categories. key => category id, value => reason of exclusion.
1709 $excludedcats = array();
1711 // The returned categories.
1712 $categoriesinfo = array();
1714 // We need to sort the categories by path.
1715 // The parent cats need to be checked by the algo first.
1716 usort($categories, "core_course_external::compare_categories_by_path");
1718 foreach ($categories as $category) {
1720 // Check if the category is a child of an excluded category, if yes exclude it too (excluded => do not return).
1721 $parents = explode('/', $category->path);
1722 unset($parents[0]); // First key is always empty because path start with / => /1/2/4.
1723 foreach ($parents as $parentid) {
1724 // Note: when the parent exclusion was due to the context,
1725 // the sub category could still be returned.
1726 if (isset($excludedcats[$parentid]) and $excludedcats[$parentid] != 'context') {
1727 $excludedcats[$category->id] = 'parent';
1731 // Check the user can use the category context.
1732 $context = context_coursecat::instance($category->id);
1734 self::validate_context($context);
1735 } catch (Exception $e) {
1736 $excludedcats[$category->id] = 'context';
1738 // If it was the requested category then throw an exception.
1739 if (isset($params['categoryid']) && $category->id == $params['categoryid']) {
1740 $exceptionparam = new stdClass();
1741 $exceptionparam->message = $e->getMessage();
1742 $exceptionparam->catid = $category->id;
1743 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
1747 // Return the category information.
1748 if (!isset($excludedcats[$category->id])) {
1750 // Final check to see if the category is visible to the user.
1751 if ($category->visible or has_capability('moodle/category:viewhiddencategories', $context)) {
1753 $categoryinfo = array();
1754 $categoryinfo['id'] = $category->id;
1755 $categoryinfo['name'] = external_format_string($category->name, $context);
1756 list($categoryinfo['description'], $categoryinfo['descriptionformat']) =
1757 external_format_text($category->description, $category->descriptionformat,
1758 $context->id, 'coursecat', 'description', null);
1759 $categoryinfo['parent'] = $category->parent;
1760 $categoryinfo['sortorder'] = $category->sortorder;
1761 $categoryinfo['coursecount'] = $category->coursecount;
1762 $categoryinfo['depth'] = $category->depth;
1763 $categoryinfo['path'] = $category->path;
1765 // Some fields only returned for admin.
1766 if (has_capability('moodle/category:manage', $context)) {
1767 $categoryinfo['idnumber'] = $category->idnumber;
1768 $categoryinfo['visible'] = $category->visible;
1769 $categoryinfo['visibleold'] = $category->visibleold;
1770 $categoryinfo['timemodified'] = $category->timemodified;
1771 $categoryinfo['theme'] = clean_param($category->theme, PARAM_THEME);
1774 $categoriesinfo[] = $categoryinfo;
1776 $excludedcats[$category->id] = 'visibility';
1781 // Sorting the resulting array so it looks a bit better for the client developer.
1782 usort($categoriesinfo, "core_course_external::compare_categories_by_sortorder");
1784 return $categoriesinfo;
1788 * Sort categories array by path
1789 * private function: only used by get_categories
1791 * @param array $category1
1792 * @param array $category2
1793 * @return int result of strcmp
1796 private static function compare_categories_by_path($category1, $category2) {
1797 return strcmp($category1->path, $category2->path);
1801 * Sort categories array by sortorder
1802 * private function: only used by get_categories
1804 * @param array $category1
1805 * @param array $category2
1806 * @return int result of strcmp
1809 private static function compare_categories_by_sortorder($category1, $category2) {
1810 return strcmp($category1['sortorder'], $category2['sortorder']);
1814 * Returns description of method result value
1816 * @return external_description
1819 public static function get_categories_returns() {
1820 return new external_multiple_structure(
1821 new external_single_structure(
1823 'id' => new external_value(PARAM_INT, 'category id'),
1824 'name' => new external_value(PARAM_TEXT, 'category name'),
1825 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1826 'description' => new external_value(PARAM_RAW, 'category description'),
1827 'descriptionformat' => new external_format_value('description'),
1828 'parent' => new external_value(PARAM_INT, 'parent category id'),
1829 'sortorder' => new external_value(PARAM_INT, 'category sorting order'),
1830 'coursecount' => new external_value(PARAM_INT, 'number of courses in this category'),
1831 'visible' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1832 'visibleold' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1833 'timemodified' => new external_value(PARAM_INT, 'timestamp', VALUE_OPTIONAL),
1834 'depth' => new external_value(PARAM_INT, 'category depth'),
1835 'path' => new external_value(PARAM_TEXT, 'category path'),
1836 'theme' => new external_value(PARAM_THEME, 'category theme', VALUE_OPTIONAL),
1837 ), 'List of categories'
1843 * Returns description of method parameters
1845 * @return external_function_parameters
1848 public static function create_categories_parameters() {
1849 return new external_function_parameters(
1851 'categories' => new external_multiple_structure(
1852 new external_single_structure(
1854 'name' => new external_value(PARAM_TEXT, 'new category name'),
1855 'parent' => new external_value(PARAM_INT,
1856 'the parent category id inside which the new category will be created
1857 - set to 0 for a root category',
1859 'idnumber' => new external_value(PARAM_RAW,
1860 'the new category idnumber', VALUE_OPTIONAL),
1861 'description' => new external_value(PARAM_RAW,
1862 'the new category description', VALUE_OPTIONAL),
1863 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
1864 'theme' => new external_value(PARAM_THEME,
1865 'the new category theme. This option must be enabled on moodle',
1877 * @param array $categories - see create_categories_parameters() for the array structure
1878 * @return array - see create_categories_returns() for the array structure
1881 public static function create_categories($categories) {
1884 $params = self::validate_parameters(self::create_categories_parameters(),
1885 array('categories' => $categories));
1887 $transaction = $DB->start_delegated_transaction();
1889 $createdcategories = array();
1890 foreach ($params['categories'] as $category) {
1891 if ($category['parent']) {
1892 if (!$DB->record_exists('course_categories', array('id' => $category['parent']))) {
1893 throw new moodle_exception('unknowcategory');
1895 $context = context_coursecat::instance($category['parent']);
1897 $context = context_system::instance();
1899 self::validate_context($context);
1900 require_capability('moodle/category:manage', $context);
1902 // this will validate format and throw an exception if there are errors
1903 external_validate_format($category['descriptionformat']);
1905 $newcategory = core_course_category::create($category);
1906 $context = context_coursecat::instance($newcategory->id);
1908 $createdcategories[] = array(
1909 'id' => $newcategory->id,
1910 'name' => external_format_string($newcategory->name, $context),
1914 $transaction->allow_commit();
1916 return $createdcategories;
1920 * Returns description of method parameters
1922 * @return external_function_parameters
1925 public static function create_categories_returns() {
1926 return new external_multiple_structure(
1927 new external_single_structure(
1929 'id' => new external_value(PARAM_INT, 'new category id'),
1930 'name' => new external_value(PARAM_TEXT, 'new category name'),
1937 * Returns description of method parameters
1939 * @return external_function_parameters
1942 public static function update_categories_parameters() {
1943 return new external_function_parameters(
1945 'categories' => new external_multiple_structure(
1946 new external_single_structure(
1948 'id' => new external_value(PARAM_INT, 'course id'),
1949 'name' => new external_value(PARAM_TEXT, 'category name', VALUE_OPTIONAL),
1950 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1951 'parent' => new external_value(PARAM_INT, 'parent category id', VALUE_OPTIONAL),
1952 'description' => new external_value(PARAM_RAW, 'category description', VALUE_OPTIONAL),
1953 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
1954 'theme' => new external_value(PARAM_THEME,
1955 'the category theme. This option must be enabled on moodle', VALUE_OPTIONAL),
1966 * @param array $categories The list of categories to update
1970 public static function update_categories($categories) {
1973 // Validate parameters.
1974 $params = self::validate_parameters(self::update_categories_parameters(), array('categories' => $categories));
1976 $transaction = $DB->start_delegated_transaction();
1978 foreach ($params['categories'] as $cat) {
1979 $category = core_course_category::get($cat['id']);
1981 $categorycontext = context_coursecat::instance($cat['id']);
1982 self::validate_context($categorycontext);
1983 require_capability('moodle/category:manage', $categorycontext);
1985 // this will throw an exception if descriptionformat is not valid
1986 external_validate_format($cat['descriptionformat']);
1988 $category->update($cat);
1991 $transaction->allow_commit();
1995 * Returns description of method result value
1997 * @return external_description
2000 public static function update_categories_returns() {
2005 * Returns description of method parameters
2007 * @return external_function_parameters
2010 public static function delete_categories_parameters() {
2011 return new external_function_parameters(
2013 'categories' => new external_multiple_structure(
2014 new external_single_structure(
2016 'id' => new external_value(PARAM_INT, 'category id to delete'),
2017 'newparent' => new external_value(PARAM_INT,
2018 'the parent category to move the contents to, if specified', VALUE_OPTIONAL),
2019 'recursive' => new external_value(PARAM_BOOL, '1: recursively delete all contents inside this
2020 category, 0 (default): move contents to newparent or current parent category (except if parent is root)', VALUE_DEFAULT, 0)
2031 * @param array $categories A list of category ids
2035 public static function delete_categories($categories) {
2037 require_once($CFG->dirroot . "/course/lib.php");
2039 // Validate parameters.
2040 $params = self::validate_parameters(self::delete_categories_parameters(), array('categories' => $categories));
2042 $transaction = $DB->start_delegated_transaction();
2044 foreach ($params['categories'] as $category) {
2045 $deletecat = core_course_category::get($category['id'], MUST_EXIST);
2046 $context = context_coursecat::instance($deletecat->id);
2047 require_capability('moodle/category:manage', $context);
2048 self::validate_context($context);
2049 self::validate_context(get_category_or_system_context($deletecat->parent));
2051 if ($category['recursive']) {
2052 // If recursive was specified, then we recursively delete the category's contents.
2053 if ($deletecat->can_delete_full()) {
2054 $deletecat->delete_full(false);
2056 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2059 // In this situation, we don't delete the category's contents, we either move it to newparent or parent.
2060 // If the parent is the root, moving is not supported (because a course must always be inside a category).
2061 // We must move to an existing category.
2062 if (!empty($category['newparent'])) {
2063 $newparentcat = core_course_category::get($category['newparent']);
2065 $newparentcat = core_course_category::get($deletecat->parent);
2068 // This operation is not allowed. We must move contents to an existing category.
2069 if (!$newparentcat->id) {
2070 throw new moodle_exception('movecatcontentstoroot');
2073 self::validate_context(context_coursecat::instance($newparentcat->id));
2074 if ($deletecat->can_move_content_to($newparentcat->id)) {
2075 $deletecat->delete_move($newparentcat->id, false);
2077 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2082 $transaction->allow_commit();
2086 * Returns description of method parameters
2088 * @return external_function_parameters
2091 public static function delete_categories_returns() {
2096 * Describes the parameters for delete_modules.
2098 * @return external_function_parameters
2101 public static function delete_modules_parameters() {
2102 return new external_function_parameters (
2104 'cmids' => new external_multiple_structure(new external_value(PARAM_INT, 'course module ID',
2105 VALUE_REQUIRED, '', NULL_NOT_ALLOWED), 'Array of course module IDs'),
2111 * Deletes a list of provided module instances.
2113 * @param array $cmids the course module ids
2116 public static function delete_modules($cmids) {
2119 // Require course file containing the course delete module function.
2120 require_once($CFG->dirroot . "/course/lib.php");
2122 // Clean the parameters.
2123 $params = self::validate_parameters(self::delete_modules_parameters(), array('cmids' => $cmids));
2125 // Keep track of the course ids we have performed a capability check on to avoid repeating.
2126 $arrcourseschecked = array();
2128 foreach ($params['cmids'] as $cmid) {
2129 // Get the course module.
2130 $cm = $DB->get_record('course_modules', array('id' => $cmid), '*', MUST_EXIST);
2132 // Check if we have not yet confirmed they have permission in this course.
2133 if (!in_array($cm->course, $arrcourseschecked)) {
2134 // Ensure the current user has required permission in this course.
2135 $context = context_course::instance($cm->course);
2136 self::validate_context($context);
2137 // Add to the array.
2138 $arrcourseschecked[] = $cm->course;
2141 // Ensure they can delete this module.
2142 $modcontext = context_module::instance($cm->id);
2143 require_capability('moodle/course:manageactivities', $modcontext);
2145 // Delete the module.
2146 course_delete_module($cm->id);
2151 * Describes the delete_modules return value.
2153 * @return external_single_structure
2156 public static function delete_modules_returns() {
2161 * Returns description of method parameters
2163 * @return external_function_parameters
2166 public static function view_course_parameters() {
2167 return new external_function_parameters(
2169 'courseid' => new external_value(PARAM_INT, 'id of the course'),
2170 'sectionnumber' => new external_value(PARAM_INT, 'section number', VALUE_DEFAULT, 0)
2176 * Trigger the course viewed event.
2178 * @param int $courseid id of course
2179 * @param int $sectionnumber sectionnumber (0, 1, 2...)
2180 * @return array of warnings and status result
2182 * @throws moodle_exception
2184 public static function view_course($courseid, $sectionnumber = 0) {
2186 require_once($CFG->dirroot . "/course/lib.php");
2188 $params = self::validate_parameters(self::view_course_parameters(),
2190 'courseid' => $courseid,
2191 'sectionnumber' => $sectionnumber
2194 $warnings = array();
2196 $course = get_course($params['courseid']);
2197 $context = context_course::instance($course->id);
2198 self::validate_context($context);
2200 if (!empty($params['sectionnumber'])) {
2202 // Get section details and check it exists.
2203 $modinfo = get_fast_modinfo($course);
2204 $coursesection = $modinfo->get_section_info($params['sectionnumber'], MUST_EXIST);
2206 // Check user is allowed to see it.
2207 if (!$coursesection->uservisible) {
2208 require_capability('moodle/course:viewhiddensections', $context);
2212 course_view($context, $params['sectionnumber']);
2215 $result['status'] = true;
2216 $result['warnings'] = $warnings;
2221 * Returns description of method result value
2223 * @return external_description
2226 public static function view_course_returns() {
2227 return new external_single_structure(
2229 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
2230 'warnings' => new external_warnings()
2236 * Returns description of method parameters
2238 * @return external_function_parameters
2241 public static function search_courses_parameters() {
2242 return new external_function_parameters(
2244 'criterianame' => new external_value(PARAM_ALPHA, 'criteria name
2245 (search, modulelist (only admins), blocklist (only admins), tagid)'),
2246 'criteriavalue' => new external_value(PARAM_RAW, 'criteria value'),
2247 'page' => new external_value(PARAM_INT, 'page number (0 based)', VALUE_DEFAULT, 0),
2248 'perpage' => new external_value(PARAM_INT, 'items per page', VALUE_DEFAULT, 0),
2249 'requiredcapabilities' => new external_multiple_structure(
2250 new external_value(PARAM_CAPABILITY, 'Capability string used to filter courses by permission'),
2251 'Optional list of required capabilities (used to filter the list)', VALUE_DEFAULT, array()
2253 'limittoenrolled' => new external_value(PARAM_BOOL, 'limit to enrolled courses', VALUE_DEFAULT, 0),
2259 * Return the course information that is public (visible by every one)
2261 * @param core_course_list_element $course course in list object
2262 * @param stdClass $coursecontext course context object
2263 * @return array the course information
2266 protected static function get_course_public_information(core_course_list_element $course, $coursecontext) {
2268 static $categoriescache = array();
2270 // Category information.
2271 if (!array_key_exists($course->category, $categoriescache)) {
2272 $categoriescache[$course->category] = core_course_category::get($course->category, IGNORE_MISSING);
2274 $category = $categoriescache[$course->category];
2276 // Retrieve course overview used files.
2278 foreach ($course->get_course_overviewfiles() as $file) {
2279 $fileurl = moodle_url::make_webservice_pluginfile_url($file->get_contextid(), $file->get_component(),
2280 $file->get_filearea(), null, $file->get_filepath(),
2281 $file->get_filename())->out(false);
2283 'filename' => $file->get_filename(),
2284 'fileurl' => $fileurl,
2285 'filesize' => $file->get_filesize(),
2286 'filepath' => $file->get_filepath(),
2287 'mimetype' => $file->get_mimetype(),
2288 'timemodified' => $file->get_timemodified(),
2292 // Retrieve the course contacts,
2293 // we need here the users fullname since if we are not enrolled can be difficult to obtain them via other Web Services.
2294 $coursecontacts = array();
2295 foreach ($course->get_course_contacts() as $contact) {
2296 $coursecontacts[] = array(
2297 'id' => $contact['user']->id,
2298 'fullname' => $contact['username'],
2299 'roles' => array_map(function($role){
2300 return array('id' => $role->id, 'name' => $role->displayname);
2301 }, $contact['roles']),
2302 'role' => array('id' => $contact['role']->id, 'name' => $contact['role']->displayname),
2303 'rolename' => $contact['rolename']
2307 // Allowed enrolment methods (maybe we can self-enrol).
2308 $enroltypes = array();
2309 $instances = enrol_get_instances($course->id, true);
2310 foreach ($instances as $instance) {
2311 $enroltypes[] = $instance->enrol;
2315 list($summary, $summaryformat) =
2316 external_format_text($course->summary, $course->summaryformat, $coursecontext->id, 'course', 'summary', null);
2319 if (!empty($category)) {
2320 $categoryname = external_format_string($category->name, $category->get_context());
2323 $displayname = get_course_display_name_for_list($course);
2324 $coursereturns = array();
2325 $coursereturns['id'] = $course->id;
2326 $coursereturns['fullname'] = external_format_string($course->fullname, $coursecontext->id);
2327 $coursereturns['displayname'] = external_format_string($displayname, $coursecontext->id);
2328 $coursereturns['shortname'] = external_format_string($course->shortname, $coursecontext->id);
2329 $coursereturns['categoryid'] = $course->category;
2330 $coursereturns['categoryname'] = $categoryname;
2331 $coursereturns['summary'] = $summary;
2332 $coursereturns['summaryformat'] = $summaryformat;
2333 $coursereturns['summaryfiles'] = external_util::get_area_files($coursecontext->id, 'course', 'summary', false, false);
2334 $coursereturns['overviewfiles'] = $files;
2335 $coursereturns['contacts'] = $coursecontacts;
2336 $coursereturns['enrollmentmethods'] = $enroltypes;
2337 $coursereturns['sortorder'] = $course->sortorder;
2338 return $coursereturns;
2342 * Search courses following the specified criteria.
2344 * @param string $criterianame Criteria name (search, modulelist (only admins), blocklist (only admins), tagid)
2345 * @param string $criteriavalue Criteria value
2346 * @param int $page Page number (for pagination)
2347 * @param int $perpage Items per page
2348 * @param array $requiredcapabilities Optional list of required capabilities (used to filter the list).
2349 * @param int $limittoenrolled Limit to only enrolled courses
2350 * @return array of course objects and warnings
2352 * @throws moodle_exception
2354 public static function search_courses($criterianame,
2358 $requiredcapabilities=array(),
2359 $limittoenrolled=0) {
2362 $warnings = array();
2364 $parameters = array(
2365 'criterianame' => $criterianame,
2366 'criteriavalue' => $criteriavalue,
2368 'perpage' => $perpage,
2369 'requiredcapabilities' => $requiredcapabilities
2371 $params = self::validate_parameters(self::search_courses_parameters(), $parameters);
2372 self::validate_context(context_system::instance());
2374 $allowedcriterianames = array('search', 'modulelist', 'blocklist', 'tagid');
2375 if (!in_array($params['criterianame'], $allowedcriterianames)) {
2376 throw new invalid_parameter_exception('Invalid value for criterianame parameter (value: '.$params['criterianame'].'),' .
2377 'allowed values are: '.implode(',', $allowedcriterianames));
2380 if ($params['criterianame'] == 'modulelist' or $params['criterianame'] == 'blocklist') {
2381 require_capability('moodle/site:config', context_system::instance());
2385 'search' => PARAM_RAW,
2386 'modulelist' => PARAM_PLUGIN,
2387 'blocklist' => PARAM_INT,
2388 'tagid' => PARAM_INT
2390 $params['criteriavalue'] = clean_param($params['criteriavalue'], $paramtype[$params['criterianame']]);
2392 // Prepare the search API options.
2393 $searchcriteria = array();
2394 $searchcriteria[$params['criterianame']] = $params['criteriavalue'];
2397 if ($params['perpage'] != 0) {
2398 $offset = $params['page'] * $params['perpage'];
2399 $options = array('offset' => $offset, 'limit' => $params['perpage']);
2402 // Search the courses.
2403 $courses = core_course_category::search_courses($searchcriteria, $options, $params['requiredcapabilities']);
2404 $totalcount = core_course_category::search_courses_count($searchcriteria, $options, $params['requiredcapabilities']);
2406 if (!empty($limittoenrolled)) {
2407 // Get the courses where the current user has access.
2408 $enrolled = enrol_get_my_courses(array('id', 'cacherev'));
2411 $finalcourses = array();
2412 $categoriescache = array();
2414 foreach ($courses as $course) {
2415 if (!empty($limittoenrolled)) {
2416 // Filter out not enrolled courses.
2417 if (!isset($enrolled[$course->id])) {
2423 $coursecontext = context_course::instance($course->id);
2425 $finalcourses[] = self::get_course_public_information($course, $coursecontext);
2429 'total' => $totalcount,
2430 'courses' => $finalcourses,
2431 'warnings' => $warnings
2436 * Returns a course structure definition
2438 * @param boolean $onlypublicdata set to true, to retrieve only fields viewable by anyone when the course is visible
2439 * @return array the course structure
2442 protected static function get_course_structure($onlypublicdata = true) {
2443 $coursestructure = array(
2444 'id' => new external_value(PARAM_INT, 'course id'),
2445 'fullname' => new external_value(PARAM_TEXT, 'course full name'),
2446 'displayname' => new external_value(PARAM_TEXT, 'course display name'),
2447 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
2448 'categoryid' => new external_value(PARAM_INT, 'category id'),
2449 'categoryname' => new external_value(PARAM_TEXT, 'category name'),
2450 'sortorder' => new external_value(PARAM_INT, 'Sort order in the category', VALUE_OPTIONAL),
2451 'summary' => new external_value(PARAM_RAW, 'summary'),
2452 'summaryformat' => new external_format_value('summary'),
2453 'summaryfiles' => new external_files('summary files in the summary field', VALUE_OPTIONAL),
2454 'overviewfiles' => new external_files('additional overview files attached to this course'),
2455 'contacts' => new external_multiple_structure(
2456 new external_single_structure(
2458 'id' => new external_value(PARAM_INT, 'contact user id'),
2459 'fullname' => new external_value(PARAM_NOTAGS, 'contact user fullname'),
2464 'enrollmentmethods' => new external_multiple_structure(
2465 new external_value(PARAM_PLUGIN, 'enrollment method'),
2466 'enrollment methods list'
2470 if (!$onlypublicdata) {
2472 'idnumber' => new external_value(PARAM_RAW, 'Id number', VALUE_OPTIONAL),
2473 'format' => new external_value(PARAM_PLUGIN, 'Course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
2474 'showgrades' => new external_value(PARAM_INT, '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
2475 'newsitems' => new external_value(PARAM_INT, 'Number of recent items appearing on the course page', VALUE_OPTIONAL),
2476 'startdate' => new external_value(PARAM_INT, 'Timestamp when the course start', VALUE_OPTIONAL),
2477 'enddate' => new external_value(PARAM_INT, 'Timestamp when the course end', VALUE_OPTIONAL),
2478 'maxbytes' => new external_value(PARAM_INT, 'Largest size of file that can be uploaded into', VALUE_OPTIONAL),
2479 'showreports' => new external_value(PARAM_INT, 'Are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
2480 'visible' => new external_value(PARAM_INT, '1: available to student, 0:not available', VALUE_OPTIONAL),
2481 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
2482 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
2483 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
2484 'enablecompletion' => new external_value(PARAM_INT, 'Completion enabled? 1: yes 0: no', VALUE_OPTIONAL),
2485 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
2486 'lang' => new external_value(PARAM_SAFEDIR, 'Forced course language', VALUE_OPTIONAL),
2487 'theme' => new external_value(PARAM_PLUGIN, 'Fame of the forced theme', VALUE_OPTIONAL),
2488 'marker' => new external_value(PARAM_INT, 'Current course marker', VALUE_OPTIONAL),
2489 'legacyfiles' => new external_value(PARAM_INT, 'If legacy files are enabled', VALUE_OPTIONAL),
2490 'calendartype' => new external_value(PARAM_PLUGIN, 'Calendar type', VALUE_OPTIONAL),
2491 'timecreated' => new external_value(PARAM_INT, 'Time when the course was created', VALUE_OPTIONAL),
2492 'timemodified' => new external_value(PARAM_INT, 'Last time the course was updated', VALUE_OPTIONAL),
2493 'requested' => new external_value(PARAM_INT, 'If is a requested course', VALUE_OPTIONAL),
2494 'cacherev' => new external_value(PARAM_INT, 'Cache revision number', VALUE_OPTIONAL),
2495 'filters' => new external_multiple_structure(
2496 new external_single_structure(
2498 'filter' => new external_value(PARAM_PLUGIN, 'Filter plugin name'),
2499 'localstate' => new external_value(PARAM_INT, 'Filter state: 1 for on, -1 for off, 0 if inherit'),
2500 'inheritedstate' => new external_value(PARAM_INT, '1 or 0 to use when localstate is set to inherit'),
2503 'Course filters', VALUE_OPTIONAL
2505 'courseformatoptions' => new external_multiple_structure(
2506 new external_single_structure(
2508 'name' => new external_value(PARAM_RAW, 'Course format option name.'),
2509 'value' => new external_value(PARAM_RAW, 'Course format option value.'),
2512 'Additional options for particular course format.', VALUE_OPTIONAL
2515 $coursestructure = array_merge($coursestructure, $extra);
2517 return new external_single_structure($coursestructure);
2521 * Returns description of method result value
2523 * @return external_description
2526 public static function search_courses_returns() {
2527 return new external_single_structure(
2529 'total' => new external_value(PARAM_INT, 'total course count'),
2530 'courses' => new external_multiple_structure(self::get_course_structure(), 'course'),
2531 'warnings' => new external_warnings()
2537 * Returns description of method parameters
2539 * @return external_function_parameters
2542 public static function get_course_module_parameters() {
2543 return new external_function_parameters(
2545 'cmid' => new external_value(PARAM_INT, 'The course module id')
2551 * Return information about a course module.
2553 * @param int $cmid the course module id
2554 * @return array of warnings and the course module
2556 * @throws moodle_exception
2558 public static function get_course_module($cmid) {
2561 $params = self::validate_parameters(self::get_course_module_parameters(), array('cmid' => $cmid));
2562 $warnings = array();
2564 $cm = get_coursemodule_from_id(null, $params['cmid'], 0, true, MUST_EXIST);
2565 $context = context_module::instance($cm->id);
2566 self::validate_context($context);
2568 // If the user has permissions to manage the activity, return all the information.
2569 if (has_capability('moodle/course:manageactivities', $context)) {
2570 require_once($CFG->dirroot . '/course/modlib.php');
2571 require_once($CFG->libdir . '/gradelib.php');
2574 // Get the extra information: grade, advanced grading and outcomes data.
2575 $course = get_course($cm->course);
2576 list($newcm, $newcontext, $module, $extrainfo, $cw) = get_moduleinfo_data($cm, $course);
2578 $gradeinfo = array('grade', 'gradepass', 'gradecat');
2579 foreach ($gradeinfo as $gfield) {
2580 if (isset($extrainfo->{$gfield})) {
2581 $info->{$gfield} = $extrainfo->{$gfield};
2584 if (isset($extrainfo->grade) and $extrainfo->grade < 0) {
2585 $info->scale = $DB->get_field('scale', 'scale', array('id' => abs($extrainfo->grade)));
2587 // Advanced grading.
2588 if (isset($extrainfo->_advancedgradingdata)) {
2589 $info->advancedgrading = array();
2590 foreach ($extrainfo as $key => $val) {
2591 if (strpos($key, 'advancedgradingmethod_') === 0) {
2592 $info->advancedgrading[] = array(
2593 'area' => str_replace('advancedgradingmethod_', '', $key),
2600 foreach ($extrainfo as $key => $val) {
2601 if (strpos($key, 'outcome_') === 0) {
2602 if (!isset($info->outcomes)) {
2603 $info->outcomes = array();
2605 $id = str_replace('outcome_', '', $key);
2606 $outcome = grade_outcome::fetch(array('id' => $id));
2607 $scaleitems = $outcome->load_scale();
2608 $info->outcomes[] = array(
2610 'name' => external_format_string($outcome->get_name(), $context->id),
2611 'scale' => $scaleitems->scale
2616 // Return information is safe to show to any user.
2617 $info = new stdClass();
2618 $info->id = $cm->id;
2619 $info->course = $cm->course;
2620 $info->module = $cm->module;
2621 $info->modname = $cm->modname;
2622 $info->instance = $cm->instance;
2623 $info->section = $cm->section;
2624 $info->sectionnum = $cm->sectionnum;
2625 $info->groupmode = $cm->groupmode;
2626 $info->groupingid = $cm->groupingid;
2627 $info->completion = $cm->completion;
2630 $info->name = external_format_string($cm->name, $context->id);
2632 $result['cm'] = $info;
2633 $result['warnings'] = $warnings;
2638 * Returns description of method result value
2640 * @return external_description
2643 public static function get_course_module_returns() {
2644 return new external_single_structure(
2646 'cm' => new external_single_structure(
2648 'id' => new external_value(PARAM_INT, 'The course module id'),
2649 'course' => new external_value(PARAM_INT, 'The course id'),
2650 'module' => new external_value(PARAM_INT, 'The module type id'),
2651 'name' => new external_value(PARAM_RAW, 'The activity name'),
2652 'modname' => new external_value(PARAM_COMPONENT, 'The module component name (forum, assign, etc..)'),
2653 'instance' => new external_value(PARAM_INT, 'The activity instance id'),
2654 'section' => new external_value(PARAM_INT, 'The module section id'),
2655 'sectionnum' => new external_value(PARAM_INT, 'The module section number'),
2656 'groupmode' => new external_value(PARAM_INT, 'Group mode'),
2657 'groupingid' => new external_value(PARAM_INT, 'Grouping id'),
2658 'completion' => new external_value(PARAM_INT, 'If completion is enabled'),
2659 'idnumber' => new external_value(PARAM_RAW, 'Module id number', VALUE_OPTIONAL),
2660 'added' => new external_value(PARAM_INT, 'Time added', VALUE_OPTIONAL),
2661 'score' => new external_value(PARAM_INT, 'Score', VALUE_OPTIONAL),
2662 'indent' => new external_value(PARAM_INT, 'Indentation', VALUE_OPTIONAL),
2663 'visible' => new external_value(PARAM_INT, 'If visible', VALUE_OPTIONAL),
2664 'visibleoncoursepage' => new external_value(PARAM_INT, 'If visible on course page', VALUE_OPTIONAL),
2665 'visibleold' => new external_value(PARAM_INT, 'Visible old', VALUE_OPTIONAL),
2666 'completiongradeitemnumber' => new external_value(PARAM_INT, 'Completion grade item', VALUE_OPTIONAL),
2667 'completionview' => new external_value(PARAM_INT, 'Completion view setting', VALUE_OPTIONAL),
2668 'completionexpected' => new external_value(PARAM_INT, 'Completion time expected', VALUE_OPTIONAL),
2669 'showdescription' => new external_value(PARAM_INT, 'If the description is showed', VALUE_OPTIONAL),
2670 'availability' => new external_value(PARAM_RAW, 'Availability settings', VALUE_OPTIONAL),
2671 'grade' => new external_value(PARAM_FLOAT, 'Grade (max value or scale id)', VALUE_OPTIONAL),
2672 'scale' => new external_value(PARAM_TEXT, 'Scale items (if used)', VALUE_OPTIONAL),
2673 'gradepass' => new external_value(PARAM_RAW, 'Grade to pass (float)', VALUE_OPTIONAL),
2674 'gradecat' => new external_value(PARAM_INT, 'Grade category', VALUE_OPTIONAL),
2675 'advancedgrading' => new external_multiple_structure(
2676 new external_single_structure(
2678 'area' => new external_value(PARAM_AREA, 'Gradable area name'),
2679 'method' => new external_value(PARAM_COMPONENT, 'Grading method'),
2682 'Advanced grading settings', VALUE_OPTIONAL
2684 'outcomes' => new external_multiple_structure(
2685 new external_single_structure(
2687 'id' => new external_value(PARAM_ALPHANUMEXT, 'Outcome id'),
2688 'name' => new external_value(PARAM_TEXT, 'Outcome full name'),
2689 'scale' => new external_value(PARAM_TEXT, 'Scale items')
2692 'Outcomes information', VALUE_OPTIONAL
2696 'warnings' => new external_warnings()
2702 * Returns description of method parameters
2704 * @return external_function_parameters
2707 public static function get_course_module_by_instance_parameters() {
2708 return new external_function_parameters(
2710 'module' => new external_value(PARAM_COMPONENT, 'The module name'),
2711 'instance' => new external_value(PARAM_INT, 'The module instance id')
2717 * Return information about a course module.
2719 * @param string $module the module name
2720 * @param int $instance the activity instance id
2721 * @return array of warnings and the course module
2723 * @throws moodle_exception
2725 public static function get_course_module_by_instance($module, $instance) {
2727 $params = self::validate_parameters(self::get_course_module_by_instance_parameters(),
2729 'module' => $module,
2730 'instance' => $instance,
2733 $warnings = array();
2734 $cm = get_coursemodule_from_instance($params['module'], $params['instance'], 0, false, MUST_EXIST);
2736 return self::get_course_module($cm->id);
2740 * Returns description of method result value
2742 * @return external_description
2745 public static function get_course_module_by_instance_returns() {
2746 return self::get_course_module_returns();
2750 * Returns description of method parameters
2752 * @deprecated since 3.3
2753 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
2754 * @return external_function_parameters
2757 public static function get_activities_overview_parameters() {
2758 return new external_function_parameters(
2760 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2766 * Return activities overview for the given courses.
2768 * @deprecated since 3.3
2769 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
2770 * @param array $courseids a list of course ids
2771 * @return array of warnings and the activities overview
2773 * @throws moodle_exception
2775 public static function get_activities_overview($courseids) {
2778 // Parameter validation.
2779 $params = self::validate_parameters(self::get_activities_overview_parameters(), array('courseids' => $courseids));
2780 $courseoverviews = array();
2782 list($courses, $warnings) = external_util::validate_courses($params['courseids']);
2784 if (!empty($courses)) {
2785 // Add lastaccess to each course (required by print_overview function).
2786 // We need the complete user data, the ws server does not load a complete one.
2787 $user = get_complete_user_data('id', $USER->id);
2788 foreach ($courses as $course) {
2789 if (isset($user->lastcourseaccess[$course->id])) {
2790 $course->lastaccess = $user->lastcourseaccess[$course->id];
2792 $course->lastaccess = 0;
2796 $overviews = array();
2797 if ($modules = get_plugin_list_with_function('mod', 'print_overview')) {
2798 foreach ($modules as $fname) {
2799 $fname($courses, $overviews);
2804 foreach ($overviews as $courseid => $modules) {
2805 $courseoverviews[$courseid]['id'] = $courseid;
2806 $courseoverviews[$courseid]['overviews'] = array();
2808 foreach ($modules as $modname => $overviewtext) {
2809 $courseoverviews[$courseid]['overviews'][] = array(
2810 'module' => $modname,
2811 'overviewtext' => $overviewtext // This text doesn't need formatting.
2818 'courses' => $courseoverviews,
2819 'warnings' => $warnings
2825 * Returns description of method result value
2827 * @deprecated since 3.3
2828 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
2829 * @return external_description
2832 public static function get_activities_overview_returns() {
2833 return new external_single_structure(
2835 'courses' => new external_multiple_structure(
2836 new external_single_structure(
2838 'id' => new external_value(PARAM_INT, 'Course id'),
2839 'overviews' => new external_multiple_structure(
2840 new external_single_structure(
2842 'module' => new external_value(PARAM_PLUGIN, 'Module name'),
2843 'overviewtext' => new external_value(PARAM_RAW, 'Overview text'),
2848 ), 'List of courses'
2850 'warnings' => new external_warnings()
2856 * Marking the method as deprecated.
2860 public static function get_activities_overview_is_deprecated() {
2865 * Returns description of method parameters
2867 * @return external_function_parameters
2870 public static function get_user_navigation_options_parameters() {
2871 return new external_function_parameters(
2873 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2879 * Return a list of navigation options in a set of courses that are avaialable or not for the current user.
2881 * @param array $courseids a list of course ids
2882 * @return array of warnings and the options availability
2884 * @throws moodle_exception
2886 public static function get_user_navigation_options($courseids) {
2888 require_once($CFG->dirroot . '/course/lib.php');
2890 // Parameter validation.
2891 $params = self::validate_parameters(self::get_user_navigation_options_parameters(), array('courseids' => $courseids));
2892 $courseoptions = array();
2894 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
2896 if (!empty($courses)) {
2897 foreach ($courses as $course) {
2898 // Fix the context for the frontpage.
2899 if ($course->id == SITEID) {
2900 $course->context = context_system::instance();
2902 $navoptions = course_get_user_navigation_options($course->context, $course);
2904 foreach ($navoptions as $name => $available) {
2907 'available' => $available,
2911 $courseoptions[] = array(
2912 'id' => $course->id,
2913 'options' => $options
2919 'courses' => $courseoptions,
2920 'warnings' => $warnings
2926 * Returns description of method result value
2928 * @return external_description
2931 public static function get_user_navigation_options_returns() {
2932 return new external_single_structure(
2934 'courses' => new external_multiple_structure(
2935 new external_single_structure(
2937 'id' => new external_value(PARAM_INT, 'Course id'),
2938 'options' => new external_multiple_structure(
2939 new external_single_structure(
2941 'name' => new external_value(PARAM_ALPHANUMEXT, 'Option name'),
2942 'available' => new external_value(PARAM_BOOL, 'Whether the option is available or not'),
2947 ), 'List of courses'
2949 'warnings' => new external_warnings()
2955 * Returns description of method parameters
2957 * @return external_function_parameters
2960 public static function get_user_administration_options_parameters() {
2961 return new external_function_parameters(
2963 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2969 * Return a list of administration options in a set of courses that are available or not for the current user.
2971 * @param array $courseids a list of course ids
2972 * @return array of warnings and the options availability
2974 * @throws moodle_exception
2976 public static function get_user_administration_options($courseids) {
2978 require_once($CFG->dirroot . '/course/lib.php');
2980 // Parameter validation.
2981 $params = self::validate_parameters(self::get_user_administration_options_parameters(), array('courseids' => $courseids));
2982 $courseoptions = array();
2984 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
2986 if (!empty($courses)) {
2987 foreach ($courses as $course) {
2988 $adminoptions = course_get_user_administration_options($course, $course->context);
2990 foreach ($adminoptions as $name => $available) {
2993 'available' => $available,
2997 $courseoptions[] = array(
2998 'id' => $course->id,
2999 'options' => $options
3005 'courses' => $courseoptions,
3006 'warnings' => $warnings
3012 * Returns description of method result value
3014 * @return external_description
3017 public static function get_user_administration_options_returns() {
3018 return self::get_user_navigation_options_returns();
3022 * Returns description of method parameters
3024 * @return external_function_parameters
3027 public static function get_courses_by_field_parameters() {
3028 return new external_function_parameters(
3030 'field' => new external_value(PARAM_ALPHA, 'The field to search can be left empty for all courses or:
3032 ids: comma separated course ids
3033 shortname: course short name
3034 idnumber: course id number
3035 category: category id the course belongs to
3036 ', VALUE_DEFAULT, ''),
3037 'value' => new external_value(PARAM_RAW, 'The value to match', VALUE_DEFAULT, '')