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
;
30 use core_availability\info
;
33 require_once("$CFG->libdir/externallib.php");
34 require_once(__DIR__
. "/lib.php");
37 * Course external functions
39 * @package core_course
41 * @copyright 2011 Jerome Mouneyrac
42 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
45 class core_course_external
extends external_api
{
48 * Returns description of method parameters
50 * @return external_function_parameters
51 * @since Moodle 2.9 Options available
54 public static function get_course_contents_parameters() {
55 return new external_function_parameters(
56 array('courseid' => new external_value(PARAM_INT
, 'course id'),
57 'options' => new external_multiple_structure (
58 new external_single_structure(
60 'name' => new external_value(PARAM_ALPHANUM
,
61 'The expected keys (value format) are:
62 excludemodules (bool) Do not return modules, return only the sections structure
63 excludecontents (bool) Do not return module contents (i.e: files inside a resource)
64 includestealthmodules (bool) Return stealth modules for students in a special
66 sectionid (int) Return only this section
67 sectionnumber (int) Return only this section with number (order)
68 cmid (int) Return only this module information (among the whole sections structure)
69 modname (string) Return only modules with this name "label, forum, etc..."
70 modid (int) Return only the module with this id (to be used with modname'),
71 'value' => new external_value(PARAM_RAW
, 'the value of the option,
72 this param is personaly validated in the external function.')
74 ), 'Options, used since Moodle 2.9', VALUE_DEFAULT
, array())
82 * @param int $courseid course id
83 * @param array $options Options for filtering the results, used since Moodle 2.9
85 * @since Moodle 2.9 Options available
88 public static function get_course_contents($courseid, $options = array()) {
89 global $CFG, $DB, $USER, $PAGE;
90 require_once($CFG->dirroot
. "/course/lib.php");
91 require_once($CFG->libdir
. '/completionlib.php');
94 $params = self
::validate_parameters(self
::get_course_contents_parameters(),
95 array('courseid' => $courseid, 'options' => $options));
98 if (!empty($params['options'])) {
100 foreach ($params['options'] as $option) {
101 $name = trim($option['name']);
102 // Avoid duplicated options.
103 if (!isset($filters[$name])) {
105 case 'excludemodules':
106 case 'excludecontents':
107 case 'includestealthmodules':
108 $value = clean_param($option['value'], PARAM_BOOL
);
109 $filters[$name] = $value;
112 case 'sectionnumber':
115 $value = clean_param($option['value'], PARAM_INT
);
116 if (is_numeric($value)) {
117 $filters[$name] = $value;
119 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
123 $value = clean_param($option['value'], PARAM_PLUGIN
);
125 $filters[$name] = $value;
127 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
131 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
137 //retrieve the course
138 $course = $DB->get_record('course', array('id' => $params['courseid']), '*', MUST_EXIST
);
140 if ($course->id
!= SITEID
) {
141 // Check course format exist.
142 if (!file_exists($CFG->dirroot
. '/course/format/' . $course->format
. '/lib.php')) {
143 throw new moodle_exception('cannotgetcoursecontents', 'webservice', '', null,
144 get_string('courseformatnotfound', 'error', $course->format
));
146 require_once($CFG->dirroot
. '/course/format/' . $course->format
. '/lib.php');
150 // now security checks
151 $context = context_course
::instance($course->id
, IGNORE_MISSING
);
153 self
::validate_context($context);
154 } catch (Exception
$e) {
155 $exceptionparam = new stdClass();
156 $exceptionparam->message
= $e->getMessage();
157 $exceptionparam->courseid
= $course->id
;
158 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
161 $canupdatecourse = has_capability('moodle/course:update', $context);
163 //create return value
164 $coursecontents = array();
166 if ($canupdatecourse or $course->visible
167 or has_capability('moodle/course:viewhiddencourses', $context)) {
170 $modinfo = get_fast_modinfo($course);
171 $sections = $modinfo->get_section_info_all();
172 $courseformat = course_get_format($course);
173 $coursenumsections = $courseformat->get_last_section_number();
174 $stealthmodules = array(); // Array to keep all the modules available but not visible in a course section/topic.
176 $completioninfo = new completion_info($course);
178 //for each sections (first displayed to last displayed)
179 $modinfosections = $modinfo->get_sections();
180 foreach ($sections as $key => $section) {
182 // This becomes true when we are filtering and we found the value to filter with.
183 $sectionfound = false;
185 // Filter by section id.
186 if (!empty($filters['sectionid'])) {
187 if ($section->id
!= $filters['sectionid']) {
190 $sectionfound = true;
194 // Filter by section number. Note that 0 is a valid section number.
195 if (isset($filters['sectionnumber'])) {
196 if ($key != $filters['sectionnumber']) {
199 $sectionfound = true;
203 // reset $sectioncontents
204 $sectionvalues = array();
205 $sectionvalues['id'] = $section->id
;
206 $sectionvalues['name'] = get_section_name($course, $section);
207 $sectionvalues['visible'] = $section->visible
;
209 $options = (object) array('noclean' => true);
210 list($sectionvalues['summary'], $sectionvalues['summaryformat']) =
211 external_format_text($section->summary
, $section->summaryformat
,
212 $context->id
, 'course', 'section', $section->id
, $options);
213 $sectionvalues['section'] = $section->section
;
214 $sectionvalues['hiddenbynumsections'] = $section->section
> $coursenumsections ?
1 : 0;
215 $sectionvalues['uservisible'] = $section->uservisible
;
216 if (!empty($section->availableinfo
)) {
217 $sectionvalues['availabilityinfo'] = \core_availability\info
::format_info($section->availableinfo
, $course);
220 $sectioncontents = array();
222 // For each module of the section.
223 if (empty($filters['excludemodules']) and !empty($modinfosections[$section->section
])) {
224 foreach ($modinfosections[$section->section
] as $cmid) {
225 $cm = $modinfo->cms
[$cmid];
226 $cminfo = cm_info
::create($cm);
227 $activitydates = \core\activity_dates
::get_dates_for_module($cminfo, $USER->id
);
229 // Stop here if the module is not visible to the user on the course main page:
230 // The user can't access the module and the user can't view the module on the course page.
231 if (!$cm->uservisible
&& !$cm->is_visible_on_course_page()) {
235 // This becomes true when we are filtering and we found the value to filter with.
239 if (!empty($filters['cmid'])) {
240 if ($cmid != $filters['cmid']) {
247 // Filter by module name and id.
248 if (!empty($filters['modname'])) {
249 if ($cm->modname
!= $filters['modname']) {
251 } else if (!empty($filters['modid'])) {
252 if ($cm->instance
!= $filters['modid']) {
255 // Note that if we are only filtering by modname we don't break the loop.
263 $modcontext = context_module
::instance($cm->id
);
265 //common info (for people being able to see the module or availability dates)
266 $module['id'] = $cm->id
;
267 $module['name'] = external_format_string($cm->name
, $modcontext->id
);
268 $module['instance'] = $cm->instance
;
269 $module['contextid'] = $modcontext->id
;
270 $module['modname'] = (string) $cm->modname
;
271 $module['modplural'] = (string) $cm->modplural
;
272 $module['modicon'] = $cm->get_icon_url()->out(false);
273 $module['indent'] = $cm->indent
;
274 $module['onclick'] = $cm->onclick
;
275 $module['afterlink'] = $cm->afterlink
;
276 $module['customdata'] = json_encode($cm->customdata
);
277 $module['completion'] = $cm->completion
;
278 $module['downloadcontent'] = $cm->downloadcontent
;
279 $module['noviewlink'] = plugin_supports('mod', $cm->modname
, FEATURE_NO_VIEW_LINK
, false);
280 $module['dates'] = $activitydates;
282 // Check module completion.
283 $completion = $completioninfo->is_enabled($cm);
284 if ($completion != COMPLETION_DISABLED
) {
285 $exporter = new \core_completion\external\
completion_info_exporter($course, $cm, $USER->id
);
286 $renderer = $PAGE->get_renderer('core');
287 $modulecompletiondata = (array)$exporter->export($renderer);
288 $module['completiondata'] = $modulecompletiondata;
291 if (!empty($cm->showdescription
) or $module['noviewlink']) {
292 // We want to use the external format. However from reading get_formatted_content(), $cm->content format is always FORMAT_HTML.
293 $options = array('noclean' => true);
294 list($module['description'], $descriptionformat) = external_format_text($cm->content
,
295 FORMAT_HTML
, $modcontext->id
, $cm->modname
, 'intro', $cm->id
, $options);
300 if ($url) { //labels don't have url
301 $module['url'] = $url->out(false);
304 $canviewhidden = has_capability('moodle/course:viewhiddenactivities',
305 context_module
::instance($cm->id
));
306 //user that can view hidden module should know about the visibility
307 $module['visible'] = $cm->visible
;
308 $module['visibleoncoursepage'] = $cm->visibleoncoursepage
;
309 $module['uservisible'] = $cm->uservisible
;
310 if (!empty($cm->availableinfo
)) {
311 $module['availabilityinfo'] = \core_availability\info
::format_info($cm->availableinfo
, $course);
314 // Availability date (also send to user who can see hidden module).
315 if ($CFG->enableavailability
&& ($canviewhidden ||
$canupdatecourse)) {
316 $module['availability'] = $cm->availability
;
319 // Return contents only if the user can access to the module.
320 if ($cm->uservisible
) {
321 $baseurl = 'webservice/pluginfile.php';
323 // Call $modulename_export_contents (each module callback take care about checking the capabilities).
324 require_once($CFG->dirroot
. '/mod/' . $cm->modname
. '/lib.php');
325 $getcontentfunction = $cm->modname
.'_export_contents';
326 if (function_exists($getcontentfunction)) {
327 $contents = $getcontentfunction($cm, $baseurl);
328 $module['contentsinfo'] = array(
329 'filescount' => count($contents),
332 'mimetypes' => array(),
334 foreach ($contents as $content) {
335 // Check repository file (only main file).
336 if (!isset($module['contentsinfo']['repositorytype'])) {
337 $module['contentsinfo']['repositorytype'] =
338 isset($content['repositorytype']) ?
$content['repositorytype'] : '';
340 if (isset($content['filesize'])) {
341 $module['contentsinfo']['filessize'] +
= $content['filesize'];
343 if (isset($content['timemodified']) &&
344 ($content['timemodified'] > $module['contentsinfo']['lastmodified'])) {
346 $module['contentsinfo']['lastmodified'] = $content['timemodified'];
348 if (isset($content['mimetype'])) {
349 $module['contentsinfo']['mimetypes'][$content['mimetype']] = $content['mimetype'];
353 if (empty($filters['excludecontents']) and !empty($contents)) {
354 $module['contents'] = $contents;
356 $module['contents'] = array();
361 // Assign result to $sectioncontents, there is an exception,
362 // stealth activities in non-visible sections for students go to a special section.
363 if (!empty($filters['includestealthmodules']) && !$section->uservisible
&& $cm->is_stealth()) {
364 $stealthmodules[] = $module;
366 $sectioncontents[] = $module;
369 // If we just did a filtering, break the loop.
376 $sectionvalues['modules'] = $sectioncontents;
378 // assign result to $coursecontents
379 $coursecontents[$key] = $sectionvalues;
381 // Break the loop if we are filtering.
387 // Now that we have iterated over all the sections and activities, check the visibility.
388 // We didn't this before to be able to retrieve stealth activities.
389 foreach ($coursecontents as $sectionnumber => $sectioncontents) {
390 $section = $sections[$sectionnumber];
392 if (!$courseformat->is_section_visible($section)) {
393 unset($coursecontents[$sectionnumber]);
397 // Remove section and modules information if the section is not visible for the user.
398 if (!$section->uservisible
) {
399 $coursecontents[$sectionnumber]['modules'] = array();
400 // Remove summary information if the section is completely hidden only,
401 // even if the section is not user visible, the summary is always displayed among the availability information.
402 if (!$section->visible
) {
403 $coursecontents[$sectionnumber]['summary'] = '';
408 // Include stealth modules in special section (without any info).
409 if (!empty($stealthmodules)) {
410 $coursecontents[] = array(
414 'summaryformat' => FORMAT_MOODLE
,
415 'modules' => $stealthmodules
420 return $coursecontents;
424 * Returns description of method result value
426 * @return external_description
429 public static function get_course_contents_returns() {
430 $completiondefinition = \core_completion\external\completion_info_exporter
::get_read_structure(VALUE_DEFAULT
, []);
432 return new external_multiple_structure(
433 new external_single_structure(
435 'id' => new external_value(PARAM_INT
, 'Section ID'),
436 'name' => new external_value(PARAM_RAW
, 'Section name'),
437 'visible' => new external_value(PARAM_INT
, 'is the section visible', VALUE_OPTIONAL
),
438 'summary' => new external_value(PARAM_RAW
, 'Section description'),
439 'summaryformat' => new external_format_value('summary'),
440 'section' => new external_value(PARAM_INT
, 'Section number inside the course', VALUE_OPTIONAL
),
441 'hiddenbynumsections' => new external_value(PARAM_INT
, 'Whether is a section hidden in the course format',
443 'uservisible' => new external_value(PARAM_BOOL
, 'Is the section visible for the user?', VALUE_OPTIONAL
),
444 'availabilityinfo' => new external_value(PARAM_RAW
, 'Availability information.', VALUE_OPTIONAL
),
445 'modules' => new external_multiple_structure(
446 new external_single_structure(
448 'id' => new external_value(PARAM_INT
, 'activity id'),
449 'url' => new external_value(PARAM_URL
, 'activity url', VALUE_OPTIONAL
),
450 'name' => new external_value(PARAM_RAW
, 'activity module name'),
451 'instance' => new external_value(PARAM_INT
, 'instance id', VALUE_OPTIONAL
),
452 'contextid' => new external_value(PARAM_INT
, 'Activity context id.', VALUE_OPTIONAL
),
453 'description' => new external_value(PARAM_RAW
, 'activity description', VALUE_OPTIONAL
),
454 'visible' => new external_value(PARAM_INT
, 'is the module visible', VALUE_OPTIONAL
),
455 'uservisible' => new external_value(PARAM_BOOL
, 'Is the module visible for the user?',
457 'availabilityinfo' => new external_value(PARAM_RAW
, 'Availability information.',
459 'visibleoncoursepage' => new external_value(PARAM_INT
, 'is the module visible on course page',
461 'modicon' => new external_value(PARAM_URL
, 'activity icon url'),
462 'modname' => new external_value(PARAM_PLUGIN
, 'activity module type'),
463 'modplural' => new external_value(PARAM_TEXT
, 'activity module plural name'),
464 'availability' => new external_value(PARAM_RAW
, 'module availability settings', VALUE_OPTIONAL
),
465 'indent' => new external_value(PARAM_INT
, 'number of identation in the site'),
466 'onclick' => new external_value(PARAM_RAW
, 'Onclick action.', VALUE_OPTIONAL
),
467 'afterlink' => new external_value(PARAM_RAW
, 'After link info to be displayed.',
469 'customdata' => new external_value(PARAM_RAW
, 'Custom data (JSON encoded).', VALUE_OPTIONAL
),
470 'noviewlink' => new external_value(PARAM_BOOL
, 'Whether the module has no view page',
472 'completion' => new external_value(PARAM_INT
, 'Type of completion tracking:
473 0 means none, 1 manual, 2 automatic.', VALUE_OPTIONAL
),
474 'completiondata' => $completiondefinition,
475 'downloadcontent' => new external_value(PARAM_INT
, 'The download content value', VALUE_OPTIONAL
),
476 'dates' => new external_multiple_structure(
477 new external_single_structure(
479 'label' => new external_value(PARAM_TEXT
, 'date label'),
480 'timestamp' => new external_value(PARAM_INT
, 'date timestamp'),
481 'relativeto' => new external_value(PARAM_INT
, 'relative date timestamp',
483 'dataid' => new external_value(PARAM_NOTAGS
, 'cm data id', VALUE_OPTIONAL
),
489 'contents' => new external_multiple_structure(
490 new external_single_structure(
493 'type'=> new external_value(PARAM_TEXT
, 'a file or a folder or external link'),
494 'filename'=> new external_value(PARAM_FILE
, 'filename'),
495 'filepath'=> new external_value(PARAM_PATH
, 'filepath'),
496 'filesize'=> new external_value(PARAM_INT
, 'filesize'),
497 'fileurl' => new external_value(PARAM_URL
, 'downloadable file url', VALUE_OPTIONAL
),
498 'content' => new external_value(PARAM_RAW
, 'Raw content, will be used when type is content', VALUE_OPTIONAL
),
499 'timecreated' => new external_value(PARAM_INT
, 'Time created'),
500 'timemodified' => new external_value(PARAM_INT
, 'Time modified'),
501 'sortorder' => new external_value(PARAM_INT
, 'Content sort order'),
502 'mimetype' => new external_value(PARAM_RAW
, 'File mime type.', VALUE_OPTIONAL
),
503 'isexternalfile' => new external_value(PARAM_BOOL
, 'Whether is an external file.',
505 'repositorytype' => new external_value(PARAM_PLUGIN
, 'The repository type for external files.',
508 // copyright related info
509 'userid' => new external_value(PARAM_INT
, 'User who added this content to moodle'),
510 'author' => new external_value(PARAM_TEXT
, 'Content owner'),
511 'license' => new external_value(PARAM_TEXT
, 'Content license'),
512 'tags' => new external_multiple_structure(
513 \core_tag\external\tag_item_exporter
::get_read_structure(), 'Tags',
517 ), VALUE_DEFAULT
, array()
519 'contentsinfo' => new external_single_structure(
521 'filescount' => new external_value(PARAM_INT
, 'Total number of files.'),
522 'filessize' => new external_value(PARAM_INT
, 'Total files size.'),
523 'lastmodified' => new external_value(PARAM_INT
, 'Last time files were modified.'),
524 'mimetypes' => new external_multiple_structure(
525 new external_value(PARAM_RAW
, 'File mime type.'),
528 'repositorytype' => new external_value(PARAM_PLUGIN
, 'The repository type for
529 the main file.', VALUE_OPTIONAL
),
530 ), 'Contents summary information.', VALUE_OPTIONAL
541 * Returns description of method parameters
543 * @return external_function_parameters
546 public static function get_courses_parameters() {
547 return new external_function_parameters(
548 array('options' => new external_single_structure(
549 array('ids' => new external_multiple_structure(
550 new external_value(PARAM_INT
, 'Course id')
551 , 'List of course id. If empty return all courses
552 except front page course.',
554 ), 'options - operator OR is used', VALUE_DEFAULT
, array())
562 * @param array $options It contains an array (list of ids)
566 public static function get_courses($options = array()) {
568 require_once($CFG->dirroot
. "/course/lib.php");
571 $params = self
::validate_parameters(self
::get_courses_parameters(),
572 array('options' => $options));
575 if (!array_key_exists('ids', $params['options'])
576 or empty($params['options']['ids'])) {
577 $courses = $DB->get_records('course');
579 $courses = $DB->get_records_list('course', 'id', $params['options']['ids']);
582 //create return value
583 $coursesinfo = array();
584 foreach ($courses as $course) {
586 // now security checks
587 $context = context_course
::instance($course->id
, IGNORE_MISSING
);
588 $courseformatoptions = course_get_format($course)->get_format_options();
590 self
::validate_context($context);
591 } catch (Exception
$e) {
592 $exceptionparam = new stdClass();
593 $exceptionparam->message
= $e->getMessage();
594 $exceptionparam->courseid
= $course->id
;
595 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
597 if ($course->id
!= SITEID
) {
598 require_capability('moodle/course:view', $context);
601 $courseinfo = array();
602 $courseinfo['id'] = $course->id
;
603 $courseinfo['fullname'] = external_format_string($course->fullname
, $context->id
);
604 $courseinfo['shortname'] = external_format_string($course->shortname
, $context->id
);
605 $courseinfo['displayname'] = external_format_string(get_course_display_name_for_list($course), $context->id
);
606 $courseinfo['categoryid'] = $course->category
;
607 list($courseinfo['summary'], $courseinfo['summaryformat']) =
608 external_format_text($course->summary
, $course->summaryformat
, $context->id
, 'course', 'summary', 0);
609 $courseinfo['format'] = $course->format
;
610 $courseinfo['startdate'] = $course->startdate
;
611 $courseinfo['enddate'] = $course->enddate
;
612 $courseinfo['showactivitydates'] = $course->showactivitydates
;
613 $courseinfo['showcompletionconditions'] = $course->showcompletionconditions
;
614 if (array_key_exists('numsections', $courseformatoptions)) {
615 // For backward-compartibility
616 $courseinfo['numsections'] = $courseformatoptions['numsections'];
619 $handler = core_course\customfield\course_handler
::create();
620 if ($customfields = $handler->export_instance_data($course->id
)) {
621 $courseinfo['customfields'] = [];
622 foreach ($customfields as $data) {
623 $courseinfo['customfields'][] = [
624 'type' => $data->get_type(),
625 'value' => $data->get_value(),
626 'valueraw' => $data->get_data_controller()->get_value(),
627 'name' => $data->get_name(),
628 'shortname' => $data->get_shortname()
633 //some field should be returned only if the user has update permission
634 $courseadmin = has_capability('moodle/course:update', $context);
636 $courseinfo['categorysortorder'] = $course->sortorder
;
637 $courseinfo['idnumber'] = $course->idnumber
;
638 $courseinfo['showgrades'] = $course->showgrades
;
639 $courseinfo['showreports'] = $course->showreports
;
640 $courseinfo['newsitems'] = $course->newsitems
;
641 $courseinfo['visible'] = $course->visible
;
642 $courseinfo['maxbytes'] = $course->maxbytes
;
643 if (array_key_exists('hiddensections', $courseformatoptions)) {
644 // For backward-compartibility
645 $courseinfo['hiddensections'] = $courseformatoptions['hiddensections'];
647 // Return numsections for backward-compatibility with clients who expect it.
648 $courseinfo['numsections'] = course_get_format($course)->get_last_section_number();
649 $courseinfo['groupmode'] = $course->groupmode
;
650 $courseinfo['groupmodeforce'] = $course->groupmodeforce
;
651 $courseinfo['defaultgroupingid'] = $course->defaultgroupingid
;
652 $courseinfo['lang'] = clean_param($course->lang
, PARAM_LANG
);
653 $courseinfo['timecreated'] = $course->timecreated
;
654 $courseinfo['timemodified'] = $course->timemodified
;
655 $courseinfo['forcetheme'] = clean_param($course->theme
, PARAM_THEME
);
656 $courseinfo['enablecompletion'] = $course->enablecompletion
;
657 $courseinfo['completionnotify'] = $course->completionnotify
;
658 $courseinfo['courseformatoptions'] = array();
659 foreach ($courseformatoptions as $key => $value) {
660 $courseinfo['courseformatoptions'][] = array(
667 if ($courseadmin or $course->visible
668 or has_capability('moodle/course:viewhiddencourses', $context)) {
669 $coursesinfo[] = $courseinfo;
677 * Returns description of method result value
679 * @return external_description
682 public static function get_courses_returns() {
683 return new external_multiple_structure(
684 new external_single_structure(
686 'id' => new external_value(PARAM_INT
, 'course id'),
687 'shortname' => new external_value(PARAM_RAW
, 'course short name'),
688 'categoryid' => new external_value(PARAM_INT
, 'category id'),
689 'categorysortorder' => new external_value(PARAM_INT
,
690 'sort order into the category', VALUE_OPTIONAL
),
691 'fullname' => new external_value(PARAM_RAW
, 'full name'),
692 'displayname' => new external_value(PARAM_RAW
, 'course display name'),
693 'idnumber' => new external_value(PARAM_RAW
, 'id number', VALUE_OPTIONAL
),
694 'summary' => new external_value(PARAM_RAW
, 'summary'),
695 'summaryformat' => new external_format_value('summary'),
696 'format' => new external_value(PARAM_PLUGIN
,
697 'course format: weeks, topics, social, site,..'),
698 'showgrades' => new external_value(PARAM_INT
,
699 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL
),
700 'newsitems' => new external_value(PARAM_INT
,
701 'number of recent items appearing on the course page', VALUE_OPTIONAL
),
702 'startdate' => new external_value(PARAM_INT
,
703 'timestamp when the course start'),
704 'enddate' => new external_value(PARAM_INT
,
705 'timestamp when the course end'),
706 'numsections' => new external_value(PARAM_INT
,
707 '(deprecated, use courseformatoptions) number of weeks/topics',
709 'maxbytes' => new external_value(PARAM_INT
,
710 'largest size of file that can be uploaded into the course',
712 'showreports' => new external_value(PARAM_INT
,
713 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL
),
714 'visible' => new external_value(PARAM_INT
,
715 '1: available to student, 0:not available', VALUE_OPTIONAL
),
716 'hiddensections' => new external_value(PARAM_INT
,
717 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
719 'groupmode' => new external_value(PARAM_INT
, 'no group, separate, visible',
721 'groupmodeforce' => new external_value(PARAM_INT
, '1: yes, 0: no',
723 'defaultgroupingid' => new external_value(PARAM_INT
, 'default grouping id',
725 'timecreated' => new external_value(PARAM_INT
,
726 'timestamp when the course have been created', VALUE_OPTIONAL
),
727 'timemodified' => new external_value(PARAM_INT
,
728 'timestamp when the course have been modified', VALUE_OPTIONAL
),
729 'enablecompletion' => new external_value(PARAM_INT
,
730 'Enabled, control via completion and activity settings. Disbaled,
731 not shown in activity settings.',
733 'completionnotify' => new external_value(PARAM_INT
,
734 '1: yes 0: no', VALUE_OPTIONAL
),
735 'lang' => new external_value(PARAM_SAFEDIR
,
736 'forced course language', VALUE_OPTIONAL
),
737 'forcetheme' => new external_value(PARAM_PLUGIN
,
738 'name of the force theme', VALUE_OPTIONAL
),
739 'courseformatoptions' => new external_multiple_structure(
740 new external_single_structure(
741 array('name' => new external_value(PARAM_ALPHANUMEXT
, 'course format option name'),
742 'value' => new external_value(PARAM_RAW
, 'course format option value')
743 )), 'additional options for particular course format', VALUE_OPTIONAL
745 'showactivitydates' => new external_value(PARAM_BOOL
, 'Whether the activity dates are shown or not'),
746 'showcompletionconditions' => new external_value(PARAM_BOOL
,
747 'Whether the activity completion conditions are shown or not'),
748 'customfields' => new external_multiple_structure(
749 new external_single_structure(
750 ['name' => new external_value(PARAM_RAW
, 'The name of the custom field'),
751 'shortname' => new external_value(PARAM_ALPHANUMEXT
, 'The shortname of the custom field'),
752 'type' => new external_value(PARAM_COMPONENT
,
753 'The type of the custom field - text, checkbox...'),
754 'valueraw' => new external_value(PARAM_RAW
, 'The raw value of the custom field'),
755 'value' => new external_value(PARAM_RAW
, 'The value of the custom field')]
756 ), 'Custom fields and associated values', VALUE_OPTIONAL
),
763 * Returns description of method parameters
765 * @return external_function_parameters
768 public static function create_courses_parameters() {
769 $courseconfig = get_config('moodlecourse'); //needed for many default values
770 return new external_function_parameters(
772 'courses' => new external_multiple_structure(
773 new external_single_structure(
775 'fullname' => new external_value(PARAM_TEXT
, 'full name'),
776 'shortname' => new external_value(PARAM_TEXT
, 'course short name'),
777 'categoryid' => new external_value(PARAM_INT
, 'category id'),
778 'idnumber' => new external_value(PARAM_RAW
, 'id number', VALUE_OPTIONAL
),
779 'summary' => new external_value(PARAM_RAW
, 'summary', VALUE_OPTIONAL
),
780 'summaryformat' => new external_format_value('summary', VALUE_DEFAULT
),
781 'format' => new external_value(PARAM_PLUGIN
,
782 'course format: weeks, topics, social, site,..',
783 VALUE_DEFAULT
, $courseconfig->format
),
784 'showgrades' => new external_value(PARAM_INT
,
785 '1 if grades are shown, otherwise 0', VALUE_DEFAULT
,
786 $courseconfig->showgrades
),
787 'newsitems' => new external_value(PARAM_INT
,
788 'number of recent items appearing on the course page',
789 VALUE_DEFAULT
, $courseconfig->newsitems
),
790 'startdate' => new external_value(PARAM_INT
,
791 'timestamp when the course start', VALUE_OPTIONAL
),
792 'enddate' => new external_value(PARAM_INT
,
793 'timestamp when the course end', VALUE_OPTIONAL
),
794 'numsections' => new external_value(PARAM_INT
,
795 '(deprecated, use courseformatoptions) number of weeks/topics',
797 'maxbytes' => new external_value(PARAM_INT
,
798 'largest size of file that can be uploaded into the course',
799 VALUE_DEFAULT
, $courseconfig->maxbytes
),
800 'showreports' => new external_value(PARAM_INT
,
801 'are activity report shown (yes = 1, no =0)', VALUE_DEFAULT
,
802 $courseconfig->showreports
),
803 'visible' => new external_value(PARAM_INT
,
804 '1: available to student, 0:not available', VALUE_OPTIONAL
),
805 'hiddensections' => new external_value(PARAM_INT
,
806 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
808 'groupmode' => new external_value(PARAM_INT
, 'no group, separate, visible',
809 VALUE_DEFAULT
, $courseconfig->groupmode
),
810 'groupmodeforce' => new external_value(PARAM_INT
, '1: yes, 0: no',
811 VALUE_DEFAULT
, $courseconfig->groupmodeforce
),
812 'defaultgroupingid' => new external_value(PARAM_INT
, 'default grouping id',
814 'enablecompletion' => new external_value(PARAM_INT
,
815 'Enabled, control via completion and activity settings. Disabled,
816 not shown in activity settings.',
818 'completionnotify' => new external_value(PARAM_INT
,
819 '1: yes 0: no', VALUE_OPTIONAL
),
820 'lang' => new external_value(PARAM_SAFEDIR
,
821 'forced course language', VALUE_OPTIONAL
),
822 'forcetheme' => new external_value(PARAM_PLUGIN
,
823 'name of the force theme', VALUE_OPTIONAL
),
824 'courseformatoptions' => new external_multiple_structure(
825 new external_single_structure(
826 array('name' => new external_value(PARAM_ALPHANUMEXT
, 'course format option name'),
827 'value' => new external_value(PARAM_RAW
, 'course format option value')
829 'additional options for particular course format', VALUE_OPTIONAL
),
830 'customfields' => new external_multiple_structure(
831 new external_single_structure(
833 'shortname' => new external_value(PARAM_ALPHANUMEXT
, 'The shortname of the custom field'),
834 'value' => new external_value(PARAM_RAW
, 'The value of the custom field'),
835 )), 'custom fields for the course', VALUE_OPTIONAL
837 )), 'courses to create'
846 * @param array $courses
847 * @return array courses (id and shortname only)
850 public static function create_courses($courses) {
852 require_once($CFG->dirroot
. "/course/lib.php");
853 require_once($CFG->libdir
. '/completionlib.php');
855 $params = self
::validate_parameters(self
::create_courses_parameters(),
856 array('courses' => $courses));
858 $availablethemes = core_component
::get_plugin_list('theme');
859 $availablelangs = get_string_manager()->get_list_of_translations();
861 $transaction = $DB->start_delegated_transaction();
863 foreach ($params['courses'] as $course) {
865 // Ensure the current user is allowed to run this function
866 $context = context_coursecat
::instance($course['categoryid'], IGNORE_MISSING
);
868 self
::validate_context($context);
869 } catch (Exception
$e) {
870 $exceptionparam = new stdClass();
871 $exceptionparam->message
= $e->getMessage();
872 $exceptionparam->catid
= $course['categoryid'];
873 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
875 require_capability('moodle/course:create', $context);
877 // Fullname and short name are required to be non-empty.
878 if (trim($course['fullname']) === '') {
879 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'fullname');
880 } else if (trim($course['shortname']) === '') {
881 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'shortname');
884 // Make sure lang is valid
885 if (array_key_exists('lang', $course)) {
886 if (empty($availablelangs[$course['lang']])) {
887 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
889 if (!has_capability('moodle/course:setforcedlanguage', $context)) {
890 unset($course['lang']);
894 // Make sure theme is valid
895 if (array_key_exists('forcetheme', $course)) {
896 if (!empty($CFG->allowcoursethemes
)) {
897 if (empty($availablethemes[$course['forcetheme']])) {
898 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
900 $course['theme'] = $course['forcetheme'];
905 //force visibility if ws user doesn't have the permission to set it
906 $category = $DB->get_record('course_categories', array('id' => $course['categoryid']));
907 if (!has_capability('moodle/course:visibility', $context)) {
908 $course['visible'] = $category->visible
;
911 //set default value for completion
912 $courseconfig = get_config('moodlecourse');
913 if (completion_info
::is_enabled_for_site()) {
914 if (!array_key_exists('enablecompletion', $course)) {
915 $course['enablecompletion'] = $courseconfig->enablecompletion
;
918 $course['enablecompletion'] = 0;
921 $course['category'] = $course['categoryid'];
924 $course['summaryformat'] = external_validate_format($course['summaryformat']);
926 if (!empty($course['courseformatoptions'])) {
927 foreach ($course['courseformatoptions'] as $option) {
928 $course[$option['name']] = $option['value'];
933 if (!empty($course['customfields'])) {
934 foreach ($course['customfields'] as $field) {
935 $course['customfield_'.$field['shortname']] = $field['value'];
939 //Note: create_course() core function check shortname, idnumber, category
940 $course['id'] = create_course((object) $course)->id
;
942 $resultcourses[] = array('id' => $course['id'], 'shortname' => $course['shortname']);
945 $transaction->allow_commit();
947 return $resultcourses;
951 * Returns description of method result value
953 * @return external_description
956 public static function create_courses_returns() {
957 return new external_multiple_structure(
958 new external_single_structure(
960 'id' => new external_value(PARAM_INT
, 'course id'),
961 'shortname' => new external_value(PARAM_RAW
, 'short name'),
970 * @return external_function_parameters
973 public static function update_courses_parameters() {
974 return new external_function_parameters(
976 'courses' => new external_multiple_structure(
977 new external_single_structure(
979 'id' => new external_value(PARAM_INT
, 'ID of the course'),
980 'fullname' => new external_value(PARAM_TEXT
, 'full name', VALUE_OPTIONAL
),
981 'shortname' => new external_value(PARAM_TEXT
, 'course short name', VALUE_OPTIONAL
),
982 'categoryid' => new external_value(PARAM_INT
, 'category id', VALUE_OPTIONAL
),
983 'idnumber' => new external_value(PARAM_RAW
, 'id number', VALUE_OPTIONAL
),
984 'summary' => new external_value(PARAM_RAW
, 'summary', VALUE_OPTIONAL
),
985 'summaryformat' => new external_format_value('summary', VALUE_OPTIONAL
),
986 'format' => new external_value(PARAM_PLUGIN
,
987 'course format: weeks, topics, social, site,..', VALUE_OPTIONAL
),
988 'showgrades' => new external_value(PARAM_INT
,
989 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL
),
990 'newsitems' => new external_value(PARAM_INT
,
991 'number of recent items appearing on the course page', VALUE_OPTIONAL
),
992 'startdate' => new external_value(PARAM_INT
,
993 'timestamp when the course start', VALUE_OPTIONAL
),
994 'enddate' => new external_value(PARAM_INT
,
995 'timestamp when the course end', VALUE_OPTIONAL
),
996 'numsections' => new external_value(PARAM_INT
,
997 '(deprecated, use courseformatoptions) number of weeks/topics', VALUE_OPTIONAL
),
998 'maxbytes' => new external_value(PARAM_INT
,
999 'largest size of file that can be uploaded into the course', VALUE_OPTIONAL
),
1000 'showreports' => new external_value(PARAM_INT
,
1001 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL
),
1002 'visible' => new external_value(PARAM_INT
,
1003 '1: available to student, 0:not available', VALUE_OPTIONAL
),
1004 'hiddensections' => new external_value(PARAM_INT
,
1005 '(deprecated, use courseformatoptions) How the hidden sections in the course are
1006 displayed to students', VALUE_OPTIONAL
),
1007 'groupmode' => new external_value(PARAM_INT
, 'no group, separate, visible', VALUE_OPTIONAL
),
1008 'groupmodeforce' => new external_value(PARAM_INT
, '1: yes, 0: no', VALUE_OPTIONAL
),
1009 'defaultgroupingid' => new external_value(PARAM_INT
, 'default grouping id', VALUE_OPTIONAL
),
1010 'enablecompletion' => new external_value(PARAM_INT
,
1011 'Enabled, control via completion and activity settings. Disabled,
1012 not shown in activity settings.', VALUE_OPTIONAL
),
1013 'completionnotify' => new external_value(PARAM_INT
, '1: yes 0: no', VALUE_OPTIONAL
),
1014 'lang' => new external_value(PARAM_SAFEDIR
, 'forced course language', VALUE_OPTIONAL
),
1015 'forcetheme' => new external_value(PARAM_PLUGIN
, 'name of the force theme', VALUE_OPTIONAL
),
1016 'courseformatoptions' => new external_multiple_structure(
1017 new external_single_structure(
1018 array('name' => new external_value(PARAM_ALPHANUMEXT
, 'course format option name'),
1019 'value' => new external_value(PARAM_RAW
, 'course format option value')
1020 )), 'additional options for particular course format', VALUE_OPTIONAL
),
1021 'customfields' => new external_multiple_structure(
1022 new external_single_structure(
1024 'shortname' => new external_value(PARAM_ALPHANUMEXT
, 'The shortname of the custom field'),
1025 'value' => new external_value(PARAM_RAW
, 'The value of the custom field')
1027 ), 'Custom fields', VALUE_OPTIONAL
),
1029 ), 'courses to update'
1038 * @param array $courses
1041 public static function update_courses($courses) {
1043 require_once($CFG->dirroot
. "/course/lib.php");
1044 $warnings = array();
1046 $params = self
::validate_parameters(self
::update_courses_parameters(),
1047 array('courses' => $courses));
1049 $availablethemes = core_component
::get_plugin_list('theme');
1050 $availablelangs = get_string_manager()->get_list_of_translations();
1052 foreach ($params['courses'] as $course) {
1053 // Catch any exception while updating course and return as warning to user.
1055 // Ensure the current user is allowed to run this function.
1056 $context = context_course
::instance($course['id'], MUST_EXIST
);
1057 self
::validate_context($context);
1059 $oldcourse = course_get_format($course['id'])->get_course();
1061 require_capability('moodle/course:update', $context);
1063 // Check if user can change category.
1064 if (array_key_exists('categoryid', $course) && ($oldcourse->category
!= $course['categoryid'])) {
1065 require_capability('moodle/course:changecategory', $context);
1066 $course['category'] = $course['categoryid'];
1069 // Check if the user can change fullname, and the new value is non-empty.
1070 if (array_key_exists('fullname', $course) && ($oldcourse->fullname
!= $course['fullname'])) {
1071 require_capability('moodle/course:changefullname', $context);
1072 if (trim($course['fullname']) === '') {
1073 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'fullname');
1077 // Check if the user can change shortname, and the new value is non-empty.
1078 if (array_key_exists('shortname', $course) && ($oldcourse->shortname
!= $course['shortname'])) {
1079 require_capability('moodle/course:changeshortname', $context);
1080 if (trim($course['shortname']) === '') {
1081 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'shortname');
1085 // Check if the user can change the idnumber.
1086 if (array_key_exists('idnumber', $course) && ($oldcourse->idnumber
!= $course['idnumber'])) {
1087 require_capability('moodle/course:changeidnumber', $context);
1090 // Check if user can change summary.
1091 if (array_key_exists('summary', $course) && ($oldcourse->summary
!= $course['summary'])) {
1092 require_capability('moodle/course:changesummary', $context);
1096 if (array_key_exists('summaryformat', $course) && ($oldcourse->summaryformat
!= $course['summaryformat'])) {
1097 require_capability('moodle/course:changesummary', $context);
1098 $course['summaryformat'] = external_validate_format($course['summaryformat']);
1101 // Check if user can change visibility.
1102 if (array_key_exists('visible', $course) && ($oldcourse->visible
!= $course['visible'])) {
1103 require_capability('moodle/course:visibility', $context);
1106 // Make sure lang is valid.
1107 if (array_key_exists('lang', $course) && ($oldcourse->lang
!= $course['lang'])) {
1108 require_capability('moodle/course:setforcedlanguage', $context);
1109 if (empty($availablelangs[$course['lang']])) {
1110 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
1114 // Make sure theme is valid.
1115 if (array_key_exists('forcetheme', $course)) {
1116 if (!empty($CFG->allowcoursethemes
)) {
1117 if (empty($availablethemes[$course['forcetheme']])) {
1118 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
1120 $course['theme'] = $course['forcetheme'];
1125 // Make sure completion is enabled before setting it.
1126 if (array_key_exists('enabledcompletion', $course) && !completion_info
::is_enabled_for_site()) {
1127 $course['enabledcompletion'] = 0;
1130 // Make sure maxbytes are less then CFG->maxbytes.
1131 if (array_key_exists('maxbytes', $course)) {
1132 // We allow updates back to 0 max bytes, a special value denoting the course uses the site limit.
1133 // Otherwise, either use the size specified, or cap at the max size for the course.
1134 if ($course['maxbytes'] != 0) {
1135 $course['maxbytes'] = get_max_upload_file_size($CFG->maxbytes
, $course['maxbytes']);
1139 if (!empty($course['courseformatoptions'])) {
1140 foreach ($course['courseformatoptions'] as $option) {
1141 if (isset($option['name']) && isset($option['value'])) {
1142 $course[$option['name']] = $option['value'];
1147 // Prepare list of custom fields.
1148 if (isset($course['customfields'])) {
1149 foreach ($course['customfields'] as $field) {
1150 $course['customfield_' . $field['shortname']] = $field['value'];
1154 // Update course if user has all required capabilities.
1155 update_course((object) $course);
1156 } catch (Exception
$e) {
1158 $warning['item'] = 'course';
1159 $warning['itemid'] = $course['id'];
1160 if ($e instanceof moodle_exception
) {
1161 $warning['warningcode'] = $e->errorcode
;
1163 $warning['warningcode'] = $e->getCode();
1165 $warning['message'] = $e->getMessage();
1166 $warnings[] = $warning;
1171 $result['warnings'] = $warnings;
1176 * Returns description of method result value
1178 * @return external_description
1181 public static function update_courses_returns() {
1182 return new external_single_structure(
1184 'warnings' => new external_warnings()
1190 * Returns description of method parameters
1192 * @return external_function_parameters
1195 public static function delete_courses_parameters() {
1196 return new external_function_parameters(
1198 'courseids' => new external_multiple_structure(new external_value(PARAM_INT
, 'course ID')),
1206 * @param array $courseids A list of course ids
1209 public static function delete_courses($courseids) {
1211 require_once($CFG->dirroot
."/course/lib.php");
1213 // Parameter validation.
1214 $params = self
::validate_parameters(self
::delete_courses_parameters(), array('courseids'=>$courseids));
1216 $warnings = array();
1218 foreach ($params['courseids'] as $courseid) {
1219 $course = $DB->get_record('course', array('id' => $courseid));
1221 if ($course === false) {
1222 $warnings[] = array(
1224 'itemid' => $courseid,
1225 'warningcode' => 'unknowncourseidnumber',
1226 'message' => 'Unknown course ID ' . $courseid
1231 // Check if the context is valid.
1232 $coursecontext = context_course
::instance($course->id
);
1233 self
::validate_context($coursecontext);
1235 // Check if the current user has permission.
1236 if (!can_delete_course($courseid)) {
1237 $warnings[] = array(
1239 'itemid' => $courseid,
1240 'warningcode' => 'cannotdeletecourse',
1241 'message' => 'You do not have the permission to delete this course' . $courseid
1246 if (delete_course($course, false) === false) {
1247 $warnings[] = array(
1249 'itemid' => $courseid,
1250 'warningcode' => 'cannotdeletecategorycourse',
1251 'message' => 'Course ' . $courseid . ' failed to be deleted'
1257 fix_course_sortorder();
1259 return array('warnings' => $warnings);
1263 * Returns description of method result value
1265 * @return external_description
1268 public static function delete_courses_returns() {
1269 return new external_single_structure(
1271 'warnings' => new external_warnings()
1277 * Returns description of method parameters
1279 * @return external_function_parameters
1282 public static function duplicate_course_parameters() {
1283 return new external_function_parameters(
1285 'courseid' => new external_value(PARAM_INT
, 'course to duplicate id'),
1286 'fullname' => new external_value(PARAM_TEXT
, 'duplicated course full name'),
1287 'shortname' => new external_value(PARAM_TEXT
, 'duplicated course short name'),
1288 'categoryid' => new external_value(PARAM_INT
, 'duplicated course category parent'),
1289 'visible' => new external_value(PARAM_INT
, 'duplicated course visible, default to yes', VALUE_DEFAULT
, 1),
1290 'options' => new external_multiple_structure(
1291 new external_single_structure(
1293 'name' => new external_value(PARAM_ALPHAEXT
, 'The backup option name:
1294 "activities" (int) Include course activites (default to 1 that is equal to yes),
1295 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1296 "filters" (int) Include course filters (default to 1 that is equal to yes),
1297 "users" (int) Include users (default to 0 that is equal to no),
1298 "enrolments" (int) Include enrolment methods (default to 1 - restore only with users),
1299 "role_assignments" (int) Include role assignments (default to 0 that is equal to no),
1300 "comments" (int) Include user comments (default to 0 that is equal to no),
1301 "userscompletion" (int) Include user course completion information (default to 0 that is equal to no),
1302 "logs" (int) Include course logs (default to 0 that is equal to no),
1303 "grade_histories" (int) Include histories (default to 0 that is equal to no)'
1305 'value' => new external_value(PARAM_RAW
, 'the value for the option 1 (yes) or 0 (no)'
1308 ), VALUE_DEFAULT
, array()
1315 * Duplicate a course
1317 * @param int $courseid
1318 * @param string $fullname Duplicated course fullname
1319 * @param string $shortname Duplicated course shortname
1320 * @param int $categoryid Duplicated course parent category id
1321 * @param int $visible Duplicated course availability
1322 * @param array $options List of backup options
1323 * @return array New course info
1326 public static function duplicate_course($courseid, $fullname, $shortname, $categoryid, $visible = 1, $options = array()) {
1327 global $CFG, $USER, $DB;
1328 require_once($CFG->dirroot
. '/backup/util/includes/backup_includes.php');
1329 require_once($CFG->dirroot
. '/backup/util/includes/restore_includes.php');
1331 // Parameter validation.
1332 $params = self
::validate_parameters(
1333 self
::duplicate_course_parameters(),
1335 'courseid' => $courseid,
1336 'fullname' => $fullname,
1337 'shortname' => $shortname,
1338 'categoryid' => $categoryid,
1339 'visible' => $visible,
1340 'options' => $options
1344 // Context validation.
1346 if (! ($course = $DB->get_record('course', array('id'=>$params['courseid'])))) {
1347 throw new moodle_exception('invalidcourseid', 'error');
1350 // Category where duplicated course is going to be created.
1351 $categorycontext = context_coursecat
::instance($params['categoryid']);
1352 self
::validate_context($categorycontext);
1354 // Course to be duplicated.
1355 $coursecontext = context_course
::instance($course->id
);
1356 self
::validate_context($coursecontext);
1358 $backupdefaults = array(
1363 'enrolments' => backup
::ENROL_WITHUSERS
,
1364 'role_assignments' => 0,
1366 'userscompletion' => 0,
1368 'grade_histories' => 0
1371 $backupsettings = array();
1372 // Check for backup and restore options.
1373 if (!empty($params['options'])) {
1374 foreach ($params['options'] as $option) {
1376 // Strict check for a correct value (allways 1 or 0, true or false).
1377 $value = clean_param($option['value'], PARAM_INT
);
1379 if ($value !== 0 and $value !== 1) {
1380 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1383 if (!isset($backupdefaults[$option['name']])) {
1384 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1387 $backupsettings[$option['name']] = $value;
1391 // Capability checking.
1393 // The backup controller check for this currently, this may be redundant.
1394 require_capability('moodle/course:create', $categorycontext);
1395 require_capability('moodle/restore:restorecourse', $categorycontext);
1396 require_capability('moodle/backup:backupcourse', $coursecontext);
1398 if (!empty($backupsettings['users'])) {
1399 require_capability('moodle/backup:userinfo', $coursecontext);
1400 require_capability('moodle/restore:userinfo', $categorycontext);
1403 // Check if the shortname is used.
1404 if ($foundcourses = $DB->get_records('course', array('shortname'=>$shortname))) {
1405 foreach ($foundcourses as $foundcourse) {
1406 $foundcoursenames[] = $foundcourse->fullname
;
1409 $foundcoursenamestring = implode(',', $foundcoursenames);
1410 throw new moodle_exception('shortnametaken', '', '', $foundcoursenamestring);
1413 // Backup the course.
1415 $bc = new backup_controller(backup
::TYPE_1COURSE
, $course->id
, backup
::FORMAT_MOODLE
,
1416 backup
::INTERACTIVE_NO
, backup
::MODE_SAMESITE
, $USER->id
);
1418 foreach ($backupsettings as $name => $value) {
1419 if ($setting = $bc->get_plan()->get_setting($name)) {
1420 $bc->get_plan()->get_setting($name)->set_value($value);
1424 $backupid = $bc->get_backupid();
1425 $backupbasepath = $bc->get_plan()->get_basepath();
1427 $bc->execute_plan();
1428 $results = $bc->get_results();
1429 $file = $results['backup_destination'];
1433 // Restore the backup immediately.
1435 // Check if we need to unzip the file because the backup temp dir does not contains backup files.
1436 if (!file_exists($backupbasepath . "/moodle_backup.xml")) {
1437 $file->extract_to_pathname(get_file_packer('application/vnd.moodle.backup'), $backupbasepath);
1440 // Create new course.
1441 $newcourseid = restore_dbops
::create_new_course($params['fullname'], $params['shortname'], $params['categoryid']);
1443 $rc = new restore_controller($backupid, $newcourseid,
1444 backup
::INTERACTIVE_NO
, backup
::MODE_SAMESITE
, $USER->id
, backup
::TARGET_NEW_COURSE
);
1446 foreach ($backupsettings as $name => $value) {
1447 $setting = $rc->get_plan()->get_setting($name);
1448 if ($setting->get_status() == backup_setting
::NOT_LOCKED
) {
1449 $setting->set_value($value);
1453 if (!$rc->execute_precheck()) {
1454 $precheckresults = $rc->get_precheck_results();
1455 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1456 if (empty($CFG->keeptempdirectoriesonbackup
)) {
1457 fulldelete($backupbasepath);
1462 foreach ($precheckresults['errors'] as $error) {
1463 $errorinfo .= $error;
1466 if (array_key_exists('warnings', $precheckresults)) {
1467 foreach ($precheckresults['warnings'] as $warning) {
1468 $errorinfo .= $warning;
1472 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1476 $rc->execute_plan();
1479 $course = $DB->get_record('course', array('id' => $newcourseid), '*', MUST_EXIST
);
1480 $course->fullname
= $params['fullname'];
1481 $course->shortname
= $params['shortname'];
1482 $course->visible
= $params['visible'];
1484 // Set shortname and fullname back.
1485 $DB->update_record('course', $course);
1487 if (empty($CFG->keeptempdirectoriesonbackup
)) {
1488 fulldelete($backupbasepath);
1491 // Delete the course backup file created by this WebService. Originally located in the course backups area.
1494 return array('id' => $course->id
, 'shortname' => $course->shortname
);
1498 * Returns description of method result value
1500 * @return external_description
1503 public static function duplicate_course_returns() {
1504 return new external_single_structure(
1506 'id' => new external_value(PARAM_INT
, 'course id'),
1507 'shortname' => new external_value(PARAM_RAW
, 'short name'),
1513 * Returns description of method parameters for import_course
1515 * @return external_function_parameters
1518 public static function import_course_parameters() {
1519 return new external_function_parameters(
1521 'importfrom' => new external_value(PARAM_INT
, 'the id of the course we are importing from'),
1522 'importto' => new external_value(PARAM_INT
, 'the id of the course we are importing to'),
1523 'deletecontent' => new external_value(PARAM_INT
, 'whether to delete the course content where we are importing to (default to 0 = No)', VALUE_DEFAULT
, 0),
1524 'options' => new external_multiple_structure(
1525 new external_single_structure(
1527 'name' => new external_value(PARAM_ALPHA
, 'The backup option name:
1528 "activities" (int) Include course activites (default to 1 that is equal to yes),
1529 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1530 "filters" (int) Include course filters (default to 1 that is equal to yes)'
1532 'value' => new external_value(PARAM_RAW
, 'the value for the option 1 (yes) or 0 (no)'
1535 ), VALUE_DEFAULT
, array()
1544 * @param int $importfrom The id of the course we are importing from
1545 * @param int $importto The id of the course we are importing to
1546 * @param bool $deletecontent Whether to delete the course we are importing to content
1547 * @param array $options List of backup options
1551 public static function import_course($importfrom, $importto, $deletecontent = 0, $options = array()) {
1552 global $CFG, $USER, $DB;
1553 require_once($CFG->dirroot
. '/backup/util/includes/backup_includes.php');
1554 require_once($CFG->dirroot
. '/backup/util/includes/restore_includes.php');
1556 // Parameter validation.
1557 $params = self
::validate_parameters(
1558 self
::import_course_parameters(),
1560 'importfrom' => $importfrom,
1561 'importto' => $importto,
1562 'deletecontent' => $deletecontent,
1563 'options' => $options
1567 if ($params['deletecontent'] !== 0 and $params['deletecontent'] !== 1) {
1568 throw new moodle_exception('invalidextparam', 'webservice', '', $params['deletecontent']);
1571 // Context validation.
1573 if (! ($importfrom = $DB->get_record('course', array('id'=>$params['importfrom'])))) {
1574 throw new moodle_exception('invalidcourseid', 'error');
1577 if (! ($importto = $DB->get_record('course', array('id'=>$params['importto'])))) {
1578 throw new moodle_exception('invalidcourseid', 'error');
1581 $importfromcontext = context_course
::instance($importfrom->id
);
1582 self
::validate_context($importfromcontext);
1584 $importtocontext = context_course
::instance($importto->id
);
1585 self
::validate_context($importtocontext);
1587 $backupdefaults = array(
1593 $backupsettings = array();
1595 // Check for backup and restore options.
1596 if (!empty($params['options'])) {
1597 foreach ($params['options'] as $option) {
1599 // Strict check for a correct value (allways 1 or 0, true or false).
1600 $value = clean_param($option['value'], PARAM_INT
);
1602 if ($value !== 0 and $value !== 1) {
1603 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1606 if (!isset($backupdefaults[$option['name']])) {
1607 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1610 $backupsettings[$option['name']] = $value;
1614 // Capability checking.
1616 require_capability('moodle/backup:backuptargetimport', $importfromcontext);
1617 require_capability('moodle/restore:restoretargetimport', $importtocontext);
1619 $bc = new backup_controller(backup
::TYPE_1COURSE
, $importfrom->id
, backup
::FORMAT_MOODLE
,
1620 backup
::INTERACTIVE_NO
, backup
::MODE_IMPORT
, $USER->id
);
1622 foreach ($backupsettings as $name => $value) {
1623 $bc->get_plan()->get_setting($name)->set_value($value);
1626 $backupid = $bc->get_backupid();
1627 $backupbasepath = $bc->get_plan()->get_basepath();
1629 $bc->execute_plan();
1632 // Restore the backup immediately.
1634 // Check if we must delete the contents of the destination course.
1635 if ($params['deletecontent']) {
1636 $restoretarget = backup
::TARGET_EXISTING_DELETING
;
1638 $restoretarget = backup
::TARGET_EXISTING_ADDING
;
1641 $rc = new restore_controller($backupid, $importto->id
,
1642 backup
::INTERACTIVE_NO
, backup
::MODE_IMPORT
, $USER->id
, $restoretarget);
1644 foreach ($backupsettings as $name => $value) {
1645 $rc->get_plan()->get_setting($name)->set_value($value);
1648 if (!$rc->execute_precheck()) {
1649 $precheckresults = $rc->get_precheck_results();
1650 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1651 if (empty($CFG->keeptempdirectoriesonbackup
)) {
1652 fulldelete($backupbasepath);
1657 foreach ($precheckresults['errors'] as $error) {
1658 $errorinfo .= $error;
1661 if (array_key_exists('warnings', $precheckresults)) {
1662 foreach ($precheckresults['warnings'] as $warning) {
1663 $errorinfo .= $warning;
1667 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1670 if ($restoretarget == backup
::TARGET_EXISTING_DELETING
) {
1671 restore_dbops
::delete_course_content($importto->id
);
1675 $rc->execute_plan();
1678 if (empty($CFG->keeptempdirectoriesonbackup
)) {
1679 fulldelete($backupbasepath);
1686 * Returns description of method result value
1688 * @return external_description
1691 public static function import_course_returns() {
1696 * Returns description of method parameters
1698 * @return external_function_parameters
1701 public static function get_categories_parameters() {
1702 return new external_function_parameters(
1704 'criteria' => new external_multiple_structure(
1705 new external_single_structure(
1707 'key' => new external_value(PARAM_ALPHA
,
1708 'The category column to search, expected keys (value format) are:'.
1709 '"id" (int) the category id,'.
1710 '"ids" (string) category ids separated by commas,'.
1711 '"name" (string) the category name,'.
1712 '"parent" (int) the parent category id,'.
1713 '"idnumber" (string) category idnumber'.
1714 ' - user must have \'moodle/category:manage\' to search on idnumber,'.
1715 '"visible" (int) whether the returned categories must be visible or hidden. If the key is not passed,
1716 then the function return all categories that the user can see.'.
1717 ' - user must have \'moodle/category:manage\' or \'moodle/category:viewhiddencategories\' to search on visible,'.
1718 '"theme" (string) only return the categories having this theme'.
1719 ' - user must have \'moodle/category:manage\' to search on theme'),
1720 'value' => new external_value(PARAM_RAW
, 'the value to match')
1722 ), 'criteria', VALUE_DEFAULT
, array()
1724 'addsubcategories' => new external_value(PARAM_BOOL
, 'return the sub categories infos
1725 (1 - default) otherwise only the category info (0)', VALUE_DEFAULT
, 1)
1733 * @param array $criteria Criteria to match the results
1734 * @param booln $addsubcategories obtain only the category (false) or its subcategories (true - default)
1735 * @return array list of categories
1738 public static function get_categories($criteria = array(), $addsubcategories = true) {
1740 require_once($CFG->dirroot
. "/course/lib.php");
1742 // Validate parameters.
1743 $params = self
::validate_parameters(self
::get_categories_parameters(),
1744 array('criteria' => $criteria, 'addsubcategories' => $addsubcategories));
1746 // Retrieve the categories.
1747 $categories = array();
1748 if (!empty($params['criteria'])) {
1750 $conditions = array();
1752 foreach ($params['criteria'] as $crit) {
1753 $key = trim($crit['key']);
1755 // Trying to avoid duplicate keys.
1756 if (!isset($conditions[$key])) {
1758 $context = context_system
::instance();
1762 $value = clean_param($crit['value'], PARAM_INT
);
1763 $conditions[$key] = $value;
1764 $wheres[] = $key . " = :" . $key;
1768 $value = clean_param($crit['value'], PARAM_SEQUENCE
);
1769 $ids = explode(',', $value);
1770 list($sqlids, $paramids) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED
);
1771 $conditions = array_merge($conditions, $paramids);
1772 $wheres[] = 'id ' . $sqlids;
1776 if (has_capability('moodle/category:manage', $context)) {
1777 $value = clean_param($crit['value'], PARAM_RAW
);
1778 $conditions[$key] = $value;
1779 $wheres[] = $key . " = :" . $key;
1781 // We must throw an exception.
1782 // Otherwise the dev client would think no idnumber exists.
1783 throw new moodle_exception('criteriaerror',
1784 'webservice', '', null,
1785 'You don\'t have the permissions to search on the "idnumber" field.');
1790 $value = clean_param($crit['value'], PARAM_TEXT
);
1791 $conditions[$key] = $value;
1792 $wheres[] = $key . " = :" . $key;
1796 $value = clean_param($crit['value'], PARAM_INT
);
1797 $conditions[$key] = $value;
1798 $wheres[] = $key . " = :" . $key;
1802 if (has_capability('moodle/category:viewhiddencategories', $context)) {
1803 $value = clean_param($crit['value'], PARAM_INT
);
1804 $conditions[$key] = $value;
1805 $wheres[] = $key . " = :" . $key;
1807 throw new moodle_exception('criteriaerror',
1808 'webservice', '', null,
1809 'You don\'t have the permissions to search on the "visible" field.');
1814 if (has_capability('moodle/category:manage', $context)) {
1815 $value = clean_param($crit['value'], PARAM_THEME
);
1816 $conditions[$key] = $value;
1817 $wheres[] = $key . " = :" . $key;
1819 throw new moodle_exception('criteriaerror',
1820 'webservice', '', null,
1821 'You don\'t have the permissions to search on the "theme" field.');
1826 throw new moodle_exception('criteriaerror',
1827 'webservice', '', null,
1828 'You can not search on this criteria: ' . $key);
1833 if (!empty($wheres)) {
1834 $wheres = implode(" AND ", $wheres);
1836 $categories = $DB->get_records_select('course_categories', $wheres, $conditions);
1838 // Retrieve its sub subcategories (all levels).
1839 if ($categories and !empty($params['addsubcategories'])) {
1840 $newcategories = array();
1842 // Check if we required visible/theme checks.
1843 $additionalselect = '';
1844 $additionalparams = array();
1845 if (isset($conditions['visible'])) {
1846 $additionalselect .= ' AND visible = :visible';
1847 $additionalparams['visible'] = $conditions['visible'];
1849 if (isset($conditions['theme'])) {
1850 $additionalselect .= ' AND theme= :theme';
1851 $additionalparams['theme'] = $conditions['theme'];
1854 foreach ($categories as $category) {
1855 $sqlselect = $DB->sql_like('path', ':path') . $additionalselect;
1856 $sqlparams = array('path' => $category->path
.'/%') +
$additionalparams; // It will NOT include the specified category.
1857 $subcategories = $DB->get_records_select('course_categories', $sqlselect, $sqlparams);
1858 $newcategories = $newcategories +
$subcategories; // Both arrays have integer as keys.
1860 $categories = $categories +
$newcategories;
1865 // Retrieve all categories in the database.
1866 $categories = $DB->get_records('course_categories');
1869 // The not returned categories. key => category id, value => reason of exclusion.
1870 $excludedcats = array();
1872 // The returned categories.
1873 $categoriesinfo = array();
1875 // We need to sort the categories by path.
1876 // The parent cats need to be checked by the algo first.
1877 usort($categories, "core_course_external::compare_categories_by_path");
1879 foreach ($categories as $category) {
1881 // Check if the category is a child of an excluded category, if yes exclude it too (excluded => do not return).
1882 $parents = explode('/', $category->path
);
1883 unset($parents[0]); // First key is always empty because path start with / => /1/2/4.
1884 foreach ($parents as $parentid) {
1885 // Note: when the parent exclusion was due to the context,
1886 // the sub category could still be returned.
1887 if (isset($excludedcats[$parentid]) and $excludedcats[$parentid] != 'context') {
1888 $excludedcats[$category->id
] = 'parent';
1892 // Check the user can use the category context.
1893 $context = context_coursecat
::instance($category->id
);
1895 self
::validate_context($context);
1896 } catch (Exception
$e) {
1897 $excludedcats[$category->id
] = 'context';
1899 // If it was the requested category then throw an exception.
1900 if (isset($params['categoryid']) && $category->id
== $params['categoryid']) {
1901 $exceptionparam = new stdClass();
1902 $exceptionparam->message
= $e->getMessage();
1903 $exceptionparam->catid
= $category->id
;
1904 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
1908 // Return the category information.
1909 if (!isset($excludedcats[$category->id
])) {
1911 // Final check to see if the category is visible to the user.
1912 if (core_course_category
::can_view_category($category)) {
1914 $categoryinfo = array();
1915 $categoryinfo['id'] = $category->id
;
1916 $categoryinfo['name'] = external_format_string($category->name
, $context);
1917 list($categoryinfo['description'], $categoryinfo['descriptionformat']) =
1918 external_format_text($category->description
, $category->descriptionformat
,
1919 $context->id
, 'coursecat', 'description', null);
1920 $categoryinfo['parent'] = $category->parent
;
1921 $categoryinfo['sortorder'] = $category->sortorder
;
1922 $categoryinfo['coursecount'] = $category->coursecount
;
1923 $categoryinfo['depth'] = $category->depth
;
1924 $categoryinfo['path'] = $category->path
;
1926 // Some fields only returned for admin.
1927 if (has_capability('moodle/category:manage', $context)) {
1928 $categoryinfo['idnumber'] = $category->idnumber
;
1929 $categoryinfo['visible'] = $category->visible
;
1930 $categoryinfo['visibleold'] = $category->visibleold
;
1931 $categoryinfo['timemodified'] = $category->timemodified
;
1932 $categoryinfo['theme'] = clean_param($category->theme
, PARAM_THEME
);
1935 $categoriesinfo[] = $categoryinfo;
1937 $excludedcats[$category->id
] = 'visibility';
1942 // Sorting the resulting array so it looks a bit better for the client developer.
1943 usort($categoriesinfo, "core_course_external::compare_categories_by_sortorder");
1945 return $categoriesinfo;
1949 * Sort categories array by path
1950 * private function: only used by get_categories
1952 * @param array $category1
1953 * @param array $category2
1954 * @return int result of strcmp
1957 private static function compare_categories_by_path($category1, $category2) {
1958 return strcmp($category1->path
, $category2->path
);
1962 * Sort categories array by sortorder
1963 * private function: only used by get_categories
1965 * @param array $category1
1966 * @param array $category2
1967 * @return int result of strcmp
1970 private static function compare_categories_by_sortorder($category1, $category2) {
1971 return strcmp($category1['sortorder'], $category2['sortorder']);
1975 * Returns description of method result value
1977 * @return external_description
1980 public static function get_categories_returns() {
1981 return new external_multiple_structure(
1982 new external_single_structure(
1984 'id' => new external_value(PARAM_INT
, 'category id'),
1985 'name' => new external_value(PARAM_RAW
, 'category name'),
1986 'idnumber' => new external_value(PARAM_RAW
, 'category id number', VALUE_OPTIONAL
),
1987 'description' => new external_value(PARAM_RAW
, 'category description'),
1988 'descriptionformat' => new external_format_value('description'),
1989 'parent' => new external_value(PARAM_INT
, 'parent category id'),
1990 'sortorder' => new external_value(PARAM_INT
, 'category sorting order'),
1991 'coursecount' => new external_value(PARAM_INT
, 'number of courses in this category'),
1992 'visible' => new external_value(PARAM_INT
, '1: available, 0:not available', VALUE_OPTIONAL
),
1993 'visibleold' => new external_value(PARAM_INT
, '1: available, 0:not available', VALUE_OPTIONAL
),
1994 'timemodified' => new external_value(PARAM_INT
, 'timestamp', VALUE_OPTIONAL
),
1995 'depth' => new external_value(PARAM_INT
, 'category depth'),
1996 'path' => new external_value(PARAM_TEXT
, 'category path'),
1997 'theme' => new external_value(PARAM_THEME
, 'category theme', VALUE_OPTIONAL
),
1998 ), 'List of categories'
2004 * Returns description of method parameters
2006 * @return external_function_parameters
2009 public static function create_categories_parameters() {
2010 return new external_function_parameters(
2012 'categories' => new external_multiple_structure(
2013 new external_single_structure(
2015 'name' => new external_value(PARAM_TEXT
, 'new category name'),
2016 'parent' => new external_value(PARAM_INT
,
2017 'the parent category id inside which the new category will be created
2018 - set to 0 for a root category',
2020 'idnumber' => new external_value(PARAM_RAW
,
2021 'the new category idnumber', VALUE_OPTIONAL
),
2022 'description' => new external_value(PARAM_RAW
,
2023 'the new category description', VALUE_OPTIONAL
),
2024 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT
),
2025 'theme' => new external_value(PARAM_THEME
,
2026 'the new category theme. This option must be enabled on moodle',
2038 * @param array $categories - see create_categories_parameters() for the array structure
2039 * @return array - see create_categories_returns() for the array structure
2042 public static function create_categories($categories) {
2045 $params = self
::validate_parameters(self
::create_categories_parameters(),
2046 array('categories' => $categories));
2048 $transaction = $DB->start_delegated_transaction();
2050 $createdcategories = array();
2051 foreach ($params['categories'] as $category) {
2052 if ($category['parent']) {
2053 if (!$DB->record_exists('course_categories', array('id' => $category['parent']))) {
2054 throw new moodle_exception('unknowcategory');
2056 $context = context_coursecat
::instance($category['parent']);
2058 $context = context_system
::instance();
2060 self
::validate_context($context);
2061 require_capability('moodle/category:manage', $context);
2063 // this will validate format and throw an exception if there are errors
2064 external_validate_format($category['descriptionformat']);
2066 $newcategory = core_course_category
::create($category);
2067 $context = context_coursecat
::instance($newcategory->id
);
2069 $createdcategories[] = array(
2070 'id' => $newcategory->id
,
2071 'name' => external_format_string($newcategory->name
, $context),
2075 $transaction->allow_commit();
2077 return $createdcategories;
2081 * Returns description of method parameters
2083 * @return external_function_parameters
2086 public static function create_categories_returns() {
2087 return new external_multiple_structure(
2088 new external_single_structure(
2090 'id' => new external_value(PARAM_INT
, 'new category id'),
2091 'name' => new external_value(PARAM_RAW
, 'new category name'),
2098 * Returns description of method parameters
2100 * @return external_function_parameters
2103 public static function update_categories_parameters() {
2104 return new external_function_parameters(
2106 'categories' => new external_multiple_structure(
2107 new external_single_structure(
2109 'id' => new external_value(PARAM_INT
, 'course id'),
2110 'name' => new external_value(PARAM_TEXT
, 'category name', VALUE_OPTIONAL
),
2111 'idnumber' => new external_value(PARAM_RAW
, 'category id number', VALUE_OPTIONAL
),
2112 'parent' => new external_value(PARAM_INT
, 'parent category id', VALUE_OPTIONAL
),
2113 'description' => new external_value(PARAM_RAW
, 'category description', VALUE_OPTIONAL
),
2114 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT
),
2115 'theme' => new external_value(PARAM_THEME
,
2116 'the category theme. This option must be enabled on moodle', VALUE_OPTIONAL
),
2127 * @param array $categories The list of categories to update
2131 public static function update_categories($categories) {
2134 // Validate parameters.
2135 $params = self
::validate_parameters(self
::update_categories_parameters(), array('categories' => $categories));
2137 $transaction = $DB->start_delegated_transaction();
2139 foreach ($params['categories'] as $cat) {
2140 $category = core_course_category
::get($cat['id']);
2142 $categorycontext = context_coursecat
::instance($cat['id']);
2143 self
::validate_context($categorycontext);
2144 require_capability('moodle/category:manage', $categorycontext);
2146 // this will throw an exception if descriptionformat is not valid
2147 external_validate_format($cat['descriptionformat']);
2149 $category->update($cat);
2152 $transaction->allow_commit();
2156 * Returns description of method result value
2158 * @return external_description
2161 public static function update_categories_returns() {
2166 * Returns description of method parameters
2168 * @return external_function_parameters
2171 public static function delete_categories_parameters() {
2172 return new external_function_parameters(
2174 'categories' => new external_multiple_structure(
2175 new external_single_structure(
2177 'id' => new external_value(PARAM_INT
, 'category id to delete'),
2178 'newparent' => new external_value(PARAM_INT
,
2179 'the parent category to move the contents to, if specified', VALUE_OPTIONAL
),
2180 'recursive' => new external_value(PARAM_BOOL
, '1: recursively delete all contents inside this
2181 category, 0 (default): move contents to newparent or current parent category (except if parent is root)', VALUE_DEFAULT
, 0)
2192 * @param array $categories A list of category ids
2196 public static function delete_categories($categories) {
2198 require_once($CFG->dirroot
. "/course/lib.php");
2200 // Validate parameters.
2201 $params = self
::validate_parameters(self
::delete_categories_parameters(), array('categories' => $categories));
2203 $transaction = $DB->start_delegated_transaction();
2205 foreach ($params['categories'] as $category) {
2206 $deletecat = core_course_category
::get($category['id'], MUST_EXIST
);
2207 $context = context_coursecat
::instance($deletecat->id
);
2208 require_capability('moodle/category:manage', $context);
2209 self
::validate_context($context);
2210 self
::validate_context(get_category_or_system_context($deletecat->parent
));
2212 if ($category['recursive']) {
2213 // If recursive was specified, then we recursively delete the category's contents.
2214 if ($deletecat->can_delete_full()) {
2215 $deletecat->delete_full(false);
2217 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2220 // In this situation, we don't delete the category's contents, we either move it to newparent or parent.
2221 // If the parent is the root, moving is not supported (because a course must always be inside a category).
2222 // We must move to an existing category.
2223 if (!empty($category['newparent'])) {
2224 $newparentcat = core_course_category
::get($category['newparent']);
2226 $newparentcat = core_course_category
::get($deletecat->parent
);
2229 // This operation is not allowed. We must move contents to an existing category.
2230 if (!$newparentcat->id
) {
2231 throw new moodle_exception('movecatcontentstoroot');
2234 self
::validate_context(context_coursecat
::instance($newparentcat->id
));
2235 if ($deletecat->can_move_content_to($newparentcat->id
)) {
2236 $deletecat->delete_move($newparentcat->id
, false);
2238 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2243 $transaction->allow_commit();
2247 * Returns description of method parameters
2249 * @return external_function_parameters
2252 public static function delete_categories_returns() {
2257 * Describes the parameters for delete_modules.
2259 * @return external_function_parameters
2262 public static function delete_modules_parameters() {
2263 return new external_function_parameters (
2265 'cmids' => new external_multiple_structure(new external_value(PARAM_INT
, 'course module ID',
2266 VALUE_REQUIRED
, '', NULL_NOT_ALLOWED
), 'Array of course module IDs'),
2272 * Deletes a list of provided module instances.
2274 * @param array $cmids the course module ids
2277 public static function delete_modules($cmids) {
2280 // Require course file containing the course delete module function.
2281 require_once($CFG->dirroot
. "/course/lib.php");
2283 // Clean the parameters.
2284 $params = self
::validate_parameters(self
::delete_modules_parameters(), array('cmids' => $cmids));
2286 // Keep track of the course ids we have performed a capability check on to avoid repeating.
2287 $arrcourseschecked = array();
2289 foreach ($params['cmids'] as $cmid) {
2290 // Get the course module.
2291 $cm = $DB->get_record('course_modules', array('id' => $cmid), '*', MUST_EXIST
);
2293 // Check if we have not yet confirmed they have permission in this course.
2294 if (!in_array($cm->course
, $arrcourseschecked)) {
2295 // Ensure the current user has required permission in this course.
2296 $context = context_course
::instance($cm->course
);
2297 self
::validate_context($context);
2298 // Add to the array.
2299 $arrcourseschecked[] = $cm->course
;
2302 // Ensure they can delete this module.
2303 $modcontext = context_module
::instance($cm->id
);
2304 require_capability('moodle/course:manageactivities', $modcontext);
2306 // Delete the module.
2307 course_delete_module($cm->id
);
2312 * Describes the delete_modules return value.
2314 * @return external_single_structure
2317 public static function delete_modules_returns() {
2322 * Returns description of method parameters
2324 * @return external_function_parameters
2327 public static function view_course_parameters() {
2328 return new external_function_parameters(
2330 'courseid' => new external_value(PARAM_INT
, 'id of the course'),
2331 'sectionnumber' => new external_value(PARAM_INT
, 'section number', VALUE_DEFAULT
, 0)
2337 * Trigger the course viewed event.
2339 * @param int $courseid id of course
2340 * @param int $sectionnumber sectionnumber (0, 1, 2...)
2341 * @return array of warnings and status result
2343 * @throws moodle_exception
2345 public static function view_course($courseid, $sectionnumber = 0) {
2347 require_once($CFG->dirroot
. "/course/lib.php");
2349 $params = self
::validate_parameters(self
::view_course_parameters(),
2351 'courseid' => $courseid,
2352 'sectionnumber' => $sectionnumber
2355 $warnings = array();
2357 $course = get_course($params['courseid']);
2358 $context = context_course
::instance($course->id
);
2359 self
::validate_context($context);
2361 if (!empty($params['sectionnumber'])) {
2363 // Get section details and check it exists.
2364 $modinfo = get_fast_modinfo($course);
2365 $coursesection = $modinfo->get_section_info($params['sectionnumber'], MUST_EXIST
);
2367 // Check user is allowed to see it.
2368 if (!$coursesection->uservisible
) {
2369 require_capability('moodle/course:viewhiddensections', $context);
2373 course_view($context, $params['sectionnumber']);
2376 $result['status'] = true;
2377 $result['warnings'] = $warnings;
2382 * Returns description of method result value
2384 * @return external_description
2387 public static function view_course_returns() {
2388 return new external_single_structure(
2390 'status' => new external_value(PARAM_BOOL
, 'status: true if success'),
2391 'warnings' => new external_warnings()
2397 * Returns description of method parameters
2399 * @return external_function_parameters
2402 public static function search_courses_parameters() {
2403 return new external_function_parameters(
2405 'criterianame' => new external_value(PARAM_ALPHA
, 'criteria name
2406 (search, modulelist (only admins), blocklist (only admins), tagid)'),
2407 'criteriavalue' => new external_value(PARAM_RAW
, 'criteria value'),
2408 'page' => new external_value(PARAM_INT
, 'page number (0 based)', VALUE_DEFAULT
, 0),
2409 'perpage' => new external_value(PARAM_INT
, 'items per page', VALUE_DEFAULT
, 0),
2410 'requiredcapabilities' => new external_multiple_structure(
2411 new external_value(PARAM_CAPABILITY
, 'Capability string used to filter courses by permission'),
2412 'Optional list of required capabilities (used to filter the list)', VALUE_DEFAULT
, array()
2414 'limittoenrolled' => new external_value(PARAM_BOOL
, 'limit to enrolled courses', VALUE_DEFAULT
, 0),
2415 'onlywithcompletion' => new external_value(PARAM_BOOL
, 'limit to courses where completion is enabled',
2422 * Return the course information that is public (visible by every one)
2424 * @param core_course_list_element $course course in list object
2425 * @param stdClass $coursecontext course context object
2426 * @return array the course information
2429 protected static function get_course_public_information(core_course_list_element
$course, $coursecontext) {
2431 static $categoriescache = array();
2433 // Category information.
2434 if (!array_key_exists($course->category
, $categoriescache)) {
2435 $categoriescache[$course->category
] = core_course_category
::get($course->category
, IGNORE_MISSING
);
2437 $category = $categoriescache[$course->category
];
2439 // Retrieve course overview used files.
2441 foreach ($course->get_course_overviewfiles() as $file) {
2442 $fileurl = moodle_url
::make_webservice_pluginfile_url($file->get_contextid(), $file->get_component(),
2443 $file->get_filearea(), null, $file->get_filepath(),
2444 $file->get_filename())->out(false);
2446 'filename' => $file->get_filename(),
2447 'fileurl' => $fileurl,
2448 'filesize' => $file->get_filesize(),
2449 'filepath' => $file->get_filepath(),
2450 'mimetype' => $file->get_mimetype(),
2451 'timemodified' => $file->get_timemodified(),
2455 // Retrieve the course contacts,
2456 // we need here the users fullname since if we are not enrolled can be difficult to obtain them via other Web Services.
2457 $coursecontacts = array();
2458 foreach ($course->get_course_contacts() as $contact) {
2459 $coursecontacts[] = array(
2460 'id' => $contact['user']->id
,
2461 'fullname' => $contact['username'],
2462 'roles' => array_map(function($role){
2463 return array('id' => $role->id
, 'name' => $role->displayname
);
2464 }, $contact['roles']),
2465 'role' => array('id' => $contact['role']->id
, 'name' => $contact['role']->displayname
),
2466 'rolename' => $contact['rolename']
2470 // Allowed enrolment methods (maybe we can self-enrol).
2471 $enroltypes = array();
2472 $instances = enrol_get_instances($course->id
, true);
2473 foreach ($instances as $instance) {
2474 $enroltypes[] = $instance->enrol
;
2478 list($summary, $summaryformat) =
2479 external_format_text($course->summary
, $course->summaryformat
, $coursecontext->id
, 'course', 'summary', null);
2482 if (!empty($category)) {
2483 $categoryname = external_format_string($category->name
, $category->get_context());
2486 $displayname = get_course_display_name_for_list($course);
2487 $coursereturns = array();
2488 $coursereturns['id'] = $course->id
;
2489 $coursereturns['fullname'] = external_format_string($course->fullname
, $coursecontext->id
);
2490 $coursereturns['displayname'] = external_format_string($displayname, $coursecontext->id
);
2491 $coursereturns['shortname'] = external_format_string($course->shortname
, $coursecontext->id
);
2492 $coursereturns['categoryid'] = $course->category
;
2493 $coursereturns['categoryname'] = $categoryname;
2494 $coursereturns['summary'] = $summary;
2495 $coursereturns['summaryformat'] = $summaryformat;
2496 $coursereturns['summaryfiles'] = external_util
::get_area_files($coursecontext->id
, 'course', 'summary', false, false);
2497 $coursereturns['overviewfiles'] = $files;
2498 $coursereturns['contacts'] = $coursecontacts;
2499 $coursereturns['enrollmentmethods'] = $enroltypes;
2500 $coursereturns['sortorder'] = $course->sortorder
;
2501 $coursereturns['showactivitydates'] = $course->showactivitydates
;
2502 $coursereturns['showcompletionconditions'] = $course->showcompletionconditions
;
2504 $handler = core_course\customfield\course_handler
::create();
2505 if ($customfields = $handler->export_instance_data($course->id
)) {
2506 $coursereturns['customfields'] = [];
2507 foreach ($customfields as $data) {
2508 $coursereturns['customfields'][] = [
2509 'type' => $data->get_type(),
2510 'value' => $data->get_value(),
2511 'valueraw' => $data->get_data_controller()->get_value(),
2512 'name' => $data->get_name(),
2513 'shortname' => $data->get_shortname()
2518 return $coursereturns;
2522 * Search courses following the specified criteria.
2524 * @param string $criterianame Criteria name (search, modulelist (only admins), blocklist (only admins), tagid)
2525 * @param string $criteriavalue Criteria value
2526 * @param int $page Page number (for pagination)
2527 * @param int $perpage Items per page
2528 * @param array $requiredcapabilities Optional list of required capabilities (used to filter the list).
2529 * @param int $limittoenrolled Limit to only enrolled courses
2530 * @param int onlywithcompletion Limit to only courses where completion is enabled
2531 * @return array of course objects and warnings
2533 * @throws moodle_exception
2535 public static function search_courses($criterianame,
2539 $requiredcapabilities=array(),
2541 $onlywithcompletion=0) {
2544 $warnings = array();
2546 $parameters = array(
2547 'criterianame' => $criterianame,
2548 'criteriavalue' => $criteriavalue,
2550 'perpage' => $perpage,
2551 'requiredcapabilities' => $requiredcapabilities,
2552 'limittoenrolled' => $limittoenrolled,
2553 'onlywithcompletion' => $onlywithcompletion
2555 $params = self
::validate_parameters(self
::search_courses_parameters(), $parameters);
2556 self
::validate_context(context_system
::instance());
2558 $allowedcriterianames = array('search', 'modulelist', 'blocklist', 'tagid');
2559 if (!in_array($params['criterianame'], $allowedcriterianames)) {
2560 throw new invalid_parameter_exception('Invalid value for criterianame parameter (value: '.$params['criterianame'].'),' .
2561 'allowed values are: '.implode(',', $allowedcriterianames));
2564 if ($params['criterianame'] == 'modulelist' or $params['criterianame'] == 'blocklist') {
2565 require_capability('moodle/site:config', context_system
::instance());
2569 'search' => PARAM_RAW
,
2570 'modulelist' => PARAM_PLUGIN
,
2571 'blocklist' => PARAM_INT
,
2572 'tagid' => PARAM_INT
2574 $params['criteriavalue'] = clean_param($params['criteriavalue'], $paramtype[$params['criterianame']]);
2576 // Prepare the search API options.
2577 $searchcriteria = array();
2578 $searchcriteria[$params['criterianame']] = $params['criteriavalue'];
2579 if ($params['onlywithcompletion']) {
2580 $searchcriteria['onlywithcompletion'] = true;
2584 if ($params['perpage'] != 0) {
2585 $offset = $params['page'] * $params['perpage'];
2586 $options = array('offset' => $offset, 'limit' => $params['perpage']);
2589 // Search the courses.
2590 $courses = core_course_category
::search_courses($searchcriteria, $options, $params['requiredcapabilities']);
2591 $totalcount = core_course_category
::search_courses_count($searchcriteria, $options, $params['requiredcapabilities']);
2593 if (!empty($limittoenrolled)) {
2594 // Get the courses where the current user has access.
2595 $enrolled = enrol_get_my_courses(array('id', 'cacherev'));
2598 $finalcourses = array();
2599 $categoriescache = array();
2601 foreach ($courses as $course) {
2602 if (!empty($limittoenrolled)) {
2603 // Filter out not enrolled courses.
2604 if (!isset($enrolled[$course->id
])) {
2610 $coursecontext = context_course
::instance($course->id
);
2612 $finalcourses[] = self
::get_course_public_information($course, $coursecontext);
2616 'total' => $totalcount,
2617 'courses' => $finalcourses,
2618 'warnings' => $warnings
2623 * Returns a course structure definition
2625 * @param boolean $onlypublicdata set to true, to retrieve only fields viewable by anyone when the course is visible
2626 * @return array the course structure
2629 protected static function get_course_structure($onlypublicdata = true) {
2630 $coursestructure = array(
2631 'id' => new external_value(PARAM_INT
, 'course id'),
2632 'fullname' => new external_value(PARAM_RAW
, 'course full name'),
2633 'displayname' => new external_value(PARAM_RAW
, 'course display name'),
2634 'shortname' => new external_value(PARAM_RAW
, 'course short name'),
2635 'categoryid' => new external_value(PARAM_INT
, 'category id'),
2636 'categoryname' => new external_value(PARAM_RAW
, 'category name'),
2637 'sortorder' => new external_value(PARAM_INT
, 'Sort order in the category', VALUE_OPTIONAL
),
2638 'summary' => new external_value(PARAM_RAW
, 'summary'),
2639 'summaryformat' => new external_format_value('summary'),
2640 'summaryfiles' => new external_files('summary files in the summary field', VALUE_OPTIONAL
),
2641 'overviewfiles' => new external_files('additional overview files attached to this course'),
2642 'showactivitydates' => new external_value(PARAM_BOOL
, 'Whether the activity dates are shown or not'),
2643 'showcompletionconditions' => new external_value(PARAM_BOOL
,
2644 'Whether the activity completion conditions are shown or not'),
2645 'contacts' => new external_multiple_structure(
2646 new external_single_structure(
2648 'id' => new external_value(PARAM_INT
, 'contact user id'),
2649 'fullname' => new external_value(PARAM_NOTAGS
, 'contact user fullname'),
2654 'enrollmentmethods' => new external_multiple_structure(
2655 new external_value(PARAM_PLUGIN
, 'enrollment method'),
2656 'enrollment methods list'
2658 'customfields' => new external_multiple_structure(
2659 new external_single_structure(
2661 'name' => new external_value(PARAM_RAW
, 'The name of the custom field'),
2662 'shortname' => new external_value(PARAM_RAW
,
2663 'The shortname of the custom field - to be able to build the field class in the code'),
2664 'type' => new external_value(PARAM_ALPHANUMEXT
,
2665 'The type of the custom field - text field, checkbox...'),
2666 'valueraw' => new external_value(PARAM_RAW
, 'The raw value of the custom field'),
2667 'value' => new external_value(PARAM_RAW
, 'The value of the custom field'),
2669 ), 'Custom fields', VALUE_OPTIONAL
),
2672 if (!$onlypublicdata) {
2674 'idnumber' => new external_value(PARAM_RAW
, 'Id number', VALUE_OPTIONAL
),
2675 'format' => new external_value(PARAM_PLUGIN
, 'Course format: weeks, topics, social, site,..', VALUE_OPTIONAL
),
2676 'showgrades' => new external_value(PARAM_INT
, '1 if grades are shown, otherwise 0', VALUE_OPTIONAL
),
2677 'newsitems' => new external_value(PARAM_INT
, 'Number of recent items appearing on the course page', VALUE_OPTIONAL
),
2678 'startdate' => new external_value(PARAM_INT
, 'Timestamp when the course start', VALUE_OPTIONAL
),
2679 'enddate' => new external_value(PARAM_INT
, 'Timestamp when the course end', VALUE_OPTIONAL
),
2680 'maxbytes' => new external_value(PARAM_INT
, 'Largest size of file that can be uploaded into', VALUE_OPTIONAL
),
2681 'showreports' => new external_value(PARAM_INT
, 'Are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL
),
2682 'visible' => new external_value(PARAM_INT
, '1: available to student, 0:not available', VALUE_OPTIONAL
),
2683 'groupmode' => new external_value(PARAM_INT
, 'no group, separate, visible', VALUE_OPTIONAL
),
2684 'groupmodeforce' => new external_value(PARAM_INT
, '1: yes, 0: no', VALUE_OPTIONAL
),
2685 'defaultgroupingid' => new external_value(PARAM_INT
, 'default grouping id', VALUE_OPTIONAL
),
2686 'enablecompletion' => new external_value(PARAM_INT
, 'Completion enabled? 1: yes 0: no', VALUE_OPTIONAL
),
2687 'completionnotify' => new external_value(PARAM_INT
, '1: yes 0: no', VALUE_OPTIONAL
),
2688 'lang' => new external_value(PARAM_SAFEDIR
, 'Forced course language', VALUE_OPTIONAL
),
2689 'theme' => new external_value(PARAM_PLUGIN
, 'Fame of the forced theme', VALUE_OPTIONAL
),
2690 'marker' => new external_value(PARAM_INT
, 'Current course marker', VALUE_OPTIONAL
),
2691 'legacyfiles' => new external_value(PARAM_INT
, 'If legacy files are enabled', VALUE_OPTIONAL
),
2692 'calendartype' => new external_value(PARAM_PLUGIN
, 'Calendar type', VALUE_OPTIONAL
),
2693 'timecreated' => new external_value(PARAM_INT
, 'Time when the course was created', VALUE_OPTIONAL
),
2694 'timemodified' => new external_value(PARAM_INT
, 'Last time the course was updated', VALUE_OPTIONAL
),
2695 'requested' => new external_value(PARAM_INT
, 'If is a requested course', VALUE_OPTIONAL
),
2696 'cacherev' => new external_value(PARAM_INT
, 'Cache revision number', VALUE_OPTIONAL
),
2697 'filters' => new external_multiple_structure(
2698 new external_single_structure(
2700 'filter' => new external_value(PARAM_PLUGIN
, 'Filter plugin name'),
2701 'localstate' => new external_value(PARAM_INT
, 'Filter state: 1 for on, -1 for off, 0 if inherit'),
2702 'inheritedstate' => new external_value(PARAM_INT
, '1 or 0 to use when localstate is set to inherit'),
2705 'Course filters', VALUE_OPTIONAL
2707 'courseformatoptions' => new external_multiple_structure(
2708 new external_single_structure(
2710 'name' => new external_value(PARAM_RAW
, 'Course format option name.'),
2711 'value' => new external_value(PARAM_RAW
, 'Course format option value.'),
2714 'Additional options for particular course format.', VALUE_OPTIONAL
2717 $coursestructure = array_merge($coursestructure, $extra);
2719 return new external_single_structure($coursestructure);
2723 * Returns description of method result value
2725 * @return external_description
2728 public static function search_courses_returns() {
2729 return new external_single_structure(
2731 'total' => new external_value(PARAM_INT
, 'total course count'),
2732 'courses' => new external_multiple_structure(self
::get_course_structure(), 'course'),
2733 'warnings' => new external_warnings()
2739 * Returns description of method parameters
2741 * @return external_function_parameters
2744 public static function get_course_module_parameters() {
2745 return new external_function_parameters(
2747 'cmid' => new external_value(PARAM_INT
, 'The course module id')
2753 * Return information about a course module.
2755 * @param int $cmid the course module id
2756 * @return array of warnings and the course module
2758 * @throws moodle_exception
2760 public static function get_course_module($cmid) {
2763 $params = self
::validate_parameters(self
::get_course_module_parameters(), array('cmid' => $cmid));
2764 $warnings = array();
2766 $cm = get_coursemodule_from_id(null, $params['cmid'], 0, true, MUST_EXIST
);
2767 $context = context_module
::instance($cm->id
);
2768 self
::validate_context($context);
2770 // If the user has permissions to manage the activity, return all the information.
2771 if (has_capability('moodle/course:manageactivities', $context)) {
2772 require_once($CFG->dirroot
. '/course/modlib.php');
2773 require_once($CFG->libdir
. '/gradelib.php');
2776 // Get the extra information: grade, advanced grading and outcomes data.
2777 $course = get_course($cm->course
);
2778 list($newcm, $newcontext, $module, $extrainfo, $cw) = get_moduleinfo_data($cm, $course);
2780 $gradeinfo = array('grade', 'gradepass', 'gradecat');
2781 foreach ($gradeinfo as $gfield) {
2782 if (isset($extrainfo->{$gfield})) {
2783 $info->{$gfield} = $extrainfo->{$gfield};
2786 if (isset($extrainfo->grade
) and $extrainfo->grade
< 0) {
2787 $info->scale
= $DB->get_field('scale', 'scale', array('id' => abs($extrainfo->grade
)));
2789 // Advanced grading.
2790 if (isset($extrainfo->_advancedgradingdata
)) {
2791 $info->advancedgrading
= array();
2792 foreach ($extrainfo as $key => $val) {
2793 if (strpos($key, 'advancedgradingmethod_') === 0) {
2794 $info->advancedgrading
[] = array(
2795 'area' => str_replace('advancedgradingmethod_', '', $key),
2802 foreach ($extrainfo as $key => $val) {
2803 if (strpos($key, 'outcome_') === 0) {
2804 if (!isset($info->outcomes
)) {
2805 $info->outcomes
= array();
2807 $id = str_replace('outcome_', '', $key);
2808 $outcome = grade_outcome
::fetch(array('id' => $id));
2809 $scaleitems = $outcome->load_scale();
2810 $info->outcomes
[] = array(
2812 'name' => external_format_string($outcome->get_name(), $context->id
),
2813 'scale' => $scaleitems->scale
2818 // Return information is safe to show to any user.
2819 $info = new stdClass();
2820 $info->id
= $cm->id
;
2821 $info->course
= $cm->course
;
2822 $info->module
= $cm->module
;
2823 $info->modname
= $cm->modname
;
2824 $info->instance
= $cm->instance
;
2825 $info->section
= $cm->section
;
2826 $info->sectionnum
= $cm->sectionnum
;
2827 $info->groupmode
= $cm->groupmode
;
2828 $info->groupingid
= $cm->groupingid
;
2829 $info->completion
= $cm->completion
;
2830 $info->downloadcontent
= $cm->downloadcontent
;
2833 $info->name
= external_format_string($cm->name
, $context->id
);
2835 $result['cm'] = $info;
2836 $result['warnings'] = $warnings;
2841 * Returns description of method result value
2843 * @return external_description
2846 public static function get_course_module_returns() {
2847 return new external_single_structure(
2849 'cm' => new external_single_structure(
2851 'id' => new external_value(PARAM_INT
, 'The course module id'),
2852 'course' => new external_value(PARAM_INT
, 'The course id'),
2853 'module' => new external_value(PARAM_INT
, 'The module type id'),
2854 'name' => new external_value(PARAM_RAW
, 'The activity name'),
2855 'modname' => new external_value(PARAM_COMPONENT
, 'The module component name (forum, assign, etc..)'),
2856 'instance' => new external_value(PARAM_INT
, 'The activity instance id'),
2857 'section' => new external_value(PARAM_INT
, 'The module section id'),
2858 'sectionnum' => new external_value(PARAM_INT
, 'The module section number'),
2859 'groupmode' => new external_value(PARAM_INT
, 'Group mode'),
2860 'groupingid' => new external_value(PARAM_INT
, 'Grouping id'),
2861 'completion' => new external_value(PARAM_INT
, 'If completion is enabled'),
2862 'idnumber' => new external_value(PARAM_RAW
, 'Module id number', VALUE_OPTIONAL
),
2863 'added' => new external_value(PARAM_INT
, 'Time added', VALUE_OPTIONAL
),
2864 'score' => new external_value(PARAM_INT
, 'Score', VALUE_OPTIONAL
),
2865 'indent' => new external_value(PARAM_INT
, 'Indentation', VALUE_OPTIONAL
),
2866 'visible' => new external_value(PARAM_INT
, 'If visible', VALUE_OPTIONAL
),
2867 'visibleoncoursepage' => new external_value(PARAM_INT
, 'If visible on course page', VALUE_OPTIONAL
),
2868 'visibleold' => new external_value(PARAM_INT
, 'Visible old', VALUE_OPTIONAL
),
2869 'completiongradeitemnumber' => new external_value(PARAM_INT
, 'Completion grade item', VALUE_OPTIONAL
),
2870 'completionpassgrade' => new external_value(PARAM_INT
, 'Completion pass grade setting', VALUE_OPTIONAL
),
2871 'completionview' => new external_value(PARAM_INT
, 'Completion view setting', VALUE_OPTIONAL
),
2872 'completionexpected' => new external_value(PARAM_INT
, 'Completion time expected', VALUE_OPTIONAL
),
2873 'showdescription' => new external_value(PARAM_INT
, 'If the description is showed', VALUE_OPTIONAL
),
2874 'downloadcontent' => new external_value(PARAM_INT
, 'The download content value', VALUE_OPTIONAL
),
2875 'availability' => new external_value(PARAM_RAW
, 'Availability settings', VALUE_OPTIONAL
),
2876 'grade' => new external_value(PARAM_FLOAT
, 'Grade (max value or scale id)', VALUE_OPTIONAL
),
2877 'scale' => new external_value(PARAM_TEXT
, 'Scale items (if used)', VALUE_OPTIONAL
),
2878 'gradepass' => new external_value(PARAM_RAW
, 'Grade to pass (float)', VALUE_OPTIONAL
),
2879 'gradecat' => new external_value(PARAM_INT
, 'Grade category', VALUE_OPTIONAL
),
2880 'advancedgrading' => new external_multiple_structure(
2881 new external_single_structure(
2883 'area' => new external_value(PARAM_AREA
, 'Gradable area name'),
2884 'method' => new external_value(PARAM_COMPONENT
, 'Grading method'),
2887 'Advanced grading settings', VALUE_OPTIONAL
2889 'outcomes' => new external_multiple_structure(
2890 new external_single_structure(
2892 'id' => new external_value(PARAM_ALPHANUMEXT
, 'Outcome id'),
2893 'name' => new external_value(PARAM_RAW
, 'Outcome full name'),
2894 'scale' => new external_value(PARAM_TEXT
, 'Scale items')
2897 'Outcomes information', VALUE_OPTIONAL
2901 'warnings' => new external_warnings()
2907 * Returns description of method parameters
2909 * @return external_function_parameters
2912 public static function get_course_module_by_instance_parameters() {
2913 return new external_function_parameters(
2915 'module' => new external_value(PARAM_COMPONENT
, 'The module name'),
2916 'instance' => new external_value(PARAM_INT
, 'The module instance id')
2922 * Return information about a course module.
2924 * @param string $module the module name
2925 * @param int $instance the activity instance id
2926 * @return array of warnings and the course module
2928 * @throws moodle_exception
2930 public static function get_course_module_by_instance($module, $instance) {
2932 $params = self
::validate_parameters(self
::get_course_module_by_instance_parameters(),
2934 'module' => $module,
2935 'instance' => $instance,
2938 $warnings = array();
2939 $cm = get_coursemodule_from_instance($params['module'], $params['instance'], 0, false, MUST_EXIST
);
2941 return self
::get_course_module($cm->id
);
2945 * Returns description of method result value
2947 * @return external_description
2950 public static function get_course_module_by_instance_returns() {
2951 return self
::get_course_module_returns();
2955 * Returns description of method parameters
2957 * @return external_function_parameters
2960 public static function get_user_navigation_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 navigation options in a set of courses that are avaialable 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_navigation_options($courseids) {
2978 require_once($CFG->dirroot
. '/course/lib.php');
2980 // Parameter validation.
2981 $params = self
::validate_parameters(self
::get_user_navigation_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 // Fix the context for the frontpage.
2989 if ($course->id
== SITEID
) {
2990 $course->context
= context_system
::instance();
2992 $navoptions = course_get_user_navigation_options($course->context
, $course);
2994 foreach ($navoptions as $name => $available) {
2997 'available' => $available,
3001 $courseoptions[] = array(
3002 'id' => $course->id
,
3003 'options' => $options
3009 'courses' => $courseoptions,
3010 'warnings' => $warnings
3016 * Returns description of method result value
3018 * @return external_description
3021 public static function get_user_navigation_options_returns() {
3022 return new external_single_structure(
3024 'courses' => new external_multiple_structure(
3025 new external_single_structure(
3027 'id' => new external_value(PARAM_INT
, 'Course id'),
3028 'options' => new external_multiple_structure(
3029 new external_single_structure(
3031 'name' => new external_value(PARAM_ALPHANUMEXT
, 'Option name'),
3032 'available' => new external_value(PARAM_BOOL
, 'Whether the option is available or not'),
3037 ), 'List of courses'
3039 'warnings' => new external_warnings()
3045 * Returns description of method parameters
3047 * @return external_function_parameters
3050 public static function get_user_administration_options_parameters() {
3051 return new external_function_parameters(
3053 'courseids' => new external_multiple_structure(new external_value(PARAM_INT
, 'Course id.')),
3059 * Return a list of administration options in a set of courses that are available or not for the current user.
3061 * @param array $courseids a list of course ids
3062 * @return array of warnings and the options availability
3064 * @throws moodle_exception
3066 public static function get_user_administration_options($courseids) {
3068 require_once($CFG->dirroot
. '/course/lib.php');
3070 // Parameter validation.
3071 $params = self
::validate_parameters(self
::get_user_administration_options_parameters(), array('courseids' => $courseids));
3072 $courseoptions = array();
3074 list($courses, $warnings) = external_util
::validate_courses($params['courseids'], array(), true);
3076 if (!empty($courses)) {
3077 foreach ($courses as $course) {
3078 $adminoptions = course_get_user_administration_options($course, $course->context
);
3080 foreach ($adminoptions as $name => $available) {
3083 'available' => $available,
3087 $courseoptions[] = array(
3088 'id' => $course->id
,
3089 'options' => $options
3095 'courses' => $courseoptions,
3096 'warnings' => $warnings
3102 * Returns description of method result value
3104 * @return external_description
3107 public static function get_user_administration_options_returns() {
3108 return self
::get_user_navigation_options_returns();
3112 * Returns description of method parameters
3114 * @return external_function_parameters
3117 public static function get_courses_by_field_parameters() {
3118 return new external_function_parameters(
3120 'field' => new external_value(PARAM_ALPHA
, 'The field to search can be left empty for all courses or:
3122 ids: comma separated course ids
3123 shortname: course short name
3124 idnumber: course id number
3125 category: category id the course belongs to
3126 ', VALUE_DEFAULT
, ''),
3127 'value' => new external_value(PARAM_RAW
, 'The value to match', VALUE_DEFAULT
, '')
3134 * Get courses matching a specific field (id/s, shortname, idnumber, category)
3136 * @param string $field field name to search, or empty for all courses
3137 * @param string $value value to search
3138 * @return array list of courses and warnings
3139 * @throws invalid_parameter_exception
3142 public static function get_courses_by_field($field = '', $value = '') {
3144 require_once($CFG->dirroot
. '/course/lib.php');
3145 require_once($CFG->libdir
. '/filterlib.php');
3147 $params = self
::validate_parameters(self
::get_courses_by_field_parameters(),
3153 $warnings = array();
3155 if (empty($params['field'])) {
3156 $courses = $DB->get_records('course', null, 'id ASC');
3158 switch ($params['field']) {
3161 $value = clean_param($params['value'], PARAM_INT
);
3164 $value = clean_param($params['value'], PARAM_SEQUENCE
);
3167 $value = clean_param($params['value'], PARAM_TEXT
);
3170 $value = clean_param($params['value'], PARAM_RAW
);
3173 throw new invalid_parameter_exception('Invalid field name');
3176 if ($params['field'] === 'ids') {
3177 // Preload categories to avoid loading one at a time.
3178 $courseids = explode(',', $value);
3179 list ($listsql, $listparams) = $DB->get_in_or_equal($courseids);
3180 $categoryids = $DB->get_fieldset_sql("
3181 SELECT DISTINCT cc.id
3183 JOIN {course_categories} cc ON cc.id = c.category
3184 WHERE c.id $listsql", $listparams);
3185 core_course_category
::get_many($categoryids);
3187 // Load and validate all courses. This is called because it loads the courses
3188 // more efficiently.
3189 list ($courses, $warnings) = external_util
::validate_courses($courseids, [],
3192 $courses = $DB->get_records('course', array($params['field'] => $value), 'id ASC');
3196 $coursesdata = array();
3197 foreach ($courses as $course) {
3198 $context = context_course
::instance($course->id
);
3199 $canupdatecourse = has_capability('moodle/course:update', $context);
3200 $canviewhiddencourses = has_capability('moodle/course:viewhiddencourses', $context);
3202 // Check if the course is visible in the site for the user.
3203 if (!$course->visible
and !$canviewhiddencourses and !$canupdatecourse) {
3206 // Get the public course information, even if we are not enrolled.
3207 $courseinlist = new core_course_list_element($course);
3209 // Now, check if we have access to the course, unless it was already checked.
3211 if (empty($course->contextvalidated
)) {
3212 self
::validate_context($context);
3214 } catch (Exception
$e) {
3215 // User can not access the course, check if they can see the public information about the course and return it.
3216 if (core_course_category
::can_view_course_info($course)) {
3217 $coursesdata[$course->id
] = self
::get_course_public_information($courseinlist, $context);
3221 $coursesdata[$course->id
] = self
::get_course_public_information($courseinlist, $context);
3222 // Return information for any user that can access the course.
3223 $coursefields = array('format', 'showgrades', 'newsitems', 'startdate', 'enddate', 'maxbytes', 'showreports', 'visible',
3224 'groupmode', 'groupmodeforce', 'defaultgroupingid', 'enablecompletion', 'completionnotify', 'lang', 'theme',
3228 $coursesdata[$course->id
]['filters'] = filter_get_available_in_context($context);
3230 // Information for managers only.
3231 if ($canupdatecourse) {
3232 $managerfields = array('idnumber', 'legacyfiles', 'calendartype', 'timecreated', 'timemodified', 'requested',
3234 $coursefields = array_merge($coursefields, $managerfields);
3238 foreach ($coursefields as $field) {
3239 $coursesdata[$course->id
][$field] = $course->{$field};
3242 // Clean lang and auth fields for external functions (it may content uninstalled themes or language packs).
3243 if (isset($coursesdata[$course->id
]['theme'])) {
3244 $coursesdata[$course->id
]['theme'] = clean_param($coursesdata[$course->id
]['theme'], PARAM_THEME
);
3246 if (isset($coursesdata[$course->id
]['lang'])) {
3247 $coursesdata[$course->id
]['lang'] = clean_param($coursesdata[$course->id
]['lang'], PARAM_LANG
);
3250 $courseformatoptions = course_get_format($course)->get_config_for_external();
3251 foreach ($courseformatoptions as $key => $value) {
3252 $coursesdata[$course->id
]['courseformatoptions'][] = array(
3260 'courses' => $coursesdata,
3261 'warnings' => $warnings
3266 * Returns description of method result value
3268 * @return external_description
3271 public static function get_courses_by_field_returns() {
3272 // Course structure, including not only public viewable fields.
3273 return new external_single_structure(
3275 'courses' => new external_multiple_structure(self
::get_course_structure(false), 'Course'),
3276 'warnings' => new external_warnings()
3282 * Returns description of method parameters
3284 * @return external_function_parameters
3287 public static function check_updates_parameters() {
3288 return new external_function_parameters(
3290 'courseid' => new external_value(PARAM_INT
, 'Course id to check'),
3291 'tocheck' => new external_multiple_structure(
3292 new external_single_structure(
3294 'contextlevel' => new external_value(PARAM_ALPHA
, 'The context level for the file location.
3295 Only module supported right now.'),
3296 'id' => new external_value(PARAM_INT
, 'Context instance id'),
3297 'since' => new external_value(PARAM_INT
, 'Check updates since this time stamp'),
3300 'Instances to check'
3302 'filter' => new external_multiple_structure(
3303 new external_value(PARAM_ALPHANUM
, 'Area name: configuration, fileareas, completion, ratings, comments,
3304 gradeitems, outcomes'),
3305 'Check only for updates in these areas', VALUE_DEFAULT
, array()
3312 * Check if there is updates affecting the user for the given course and contexts.
3313 * Right now only modules are supported.
3314 * This WS calls mod_check_updates_since for each module to check if there is any update the user should we aware of.
3316 * @param int $courseid the list of modules to check
3317 * @param array $tocheck the list of modules to check
3318 * @param array $filter check only for updates in these areas
3319 * @return array list of updates and warnings
3320 * @throws moodle_exception
3323 public static function check_updates($courseid, $tocheck, $filter = array()) {
3325 require_once($CFG->dirroot
. "/course/lib.php");
3327 $params = self
::validate_parameters(
3328 self
::check_updates_parameters(),
3330 'courseid' => $courseid,
3331 'tocheck' => $tocheck,
3332 'filter' => $filter,
3336 $course = get_course($params['courseid']);
3337 $context = context_course
::instance($course->id
);
3338 self
::validate_context($context);
3340 list($instances, $warnings) = course_check_updates($course, $params['tocheck'], $filter);
3342 $instancesformatted = array();
3343 foreach ($instances as $instance) {
3345 foreach ($instance['updates'] as $name => $data) {
3346 if (empty($data->updated
)) {
3349 $updatedata = array(
3352 if (!empty($data->timeupdated
)) {
3353 $updatedata['timeupdated'] = $data->timeupdated
;
3355 if (!empty($data->itemids
)) {
3356 $updatedata['itemids'] = $data->itemids
;
3358 $updates[] = $updatedata;
3360 if (!empty($updates)) {
3361 $instancesformatted[] = array(
3362 'contextlevel' => $instance['contextlevel'],
3363 'id' => $instance['id'],
3364 'updates' => $updates
3370 'instances' => $instancesformatted,
3371 'warnings' => $warnings
3376 * Returns description of method result value
3378 * @return external_description
3381 public static function check_updates_returns() {
3382 return new external_single_structure(
3384 'instances' => new external_multiple_structure(
3385 new external_single_structure(
3387 'contextlevel' => new external_value(PARAM_ALPHA
, 'The context level'),
3388 'id' => new external_value(PARAM_INT
, 'Instance id'),
3389 'updates' => new external_multiple_structure(
3390 new external_single_structure(
3392 'name' => new external_value(PARAM_ALPHANUMEXT
, 'Name of the area updated.'),
3393 'timeupdated' => new external_value(PARAM_INT
, 'Last time was updated', VALUE_OPTIONAL
),
3394 'itemids' => new external_multiple_structure(
3395 new external_value(PARAM_INT
, 'Instance id'),
3396 'The ids of the items updated',
3405 'warnings' => new external_warnings()
3411 * Returns description of method parameters
3413 * @return external_function_parameters
3416 public static function get_updates_since_parameters() {
3417 return new external_function_parameters(
3419 'courseid' => new external_value(PARAM_INT
, 'Course id to check'),
3420 'since' => new external_value(PARAM_INT
, 'Check updates since this time stamp'),
3421 'filter' => new external_multiple_structure(
3422 new external_value(PARAM_ALPHANUM
, 'Area name: configuration, fileareas, completion, ratings, comments,
3423 gradeitems, outcomes'),
3424 'Check only for updates in these areas', VALUE_DEFAULT
, array()
3431 * Check if there are updates affecting the user for the given course since the given time stamp.
3433 * This function is a wrapper of self::check_updates for retrieving all the updates since a given time for all the activities.
3435 * @param int $courseid the list of modules to check
3436 * @param int $since check updates since this time stamp
3437 * @param array $filter check only for updates in these areas
3438 * @return array list of updates and warnings
3439 * @throws moodle_exception
3442 public static function get_updates_since($courseid, $since, $filter = array()) {
3445 $params = self
::validate_parameters(
3446 self
::get_updates_since_parameters(),
3448 'courseid' => $courseid,
3450 'filter' => $filter,
3454 $course = get_course($params['courseid']);
3455 $modinfo = get_fast_modinfo($course);
3458 // Retrieve all the visible course modules for the current user.
3459 $cms = $modinfo->get_cms();
3460 foreach ($cms as $cm) {
3461 if (!$cm->uservisible
) {
3466 'contextlevel' => 'module',
3467 'since' => $params['since'],
3471 return self
::check_updates($course->id
, $tocheck, $params['filter']);
3475 * Returns description of method result value
3477 * @return external_description
3480 public static function get_updates_since_returns() {
3481 return self
::check_updates_returns();
3485 * Parameters for function edit_module()
3488 * @return external_function_parameters
3490 public static function edit_module_parameters() {
3491 return new external_function_parameters(
3493 'action' => new external_value(PARAM_ALPHA
,
3494 'action: hide, show, stealth, duplicate, delete, moveleft, moveright, group...', VALUE_REQUIRED
),
3495 'id' => new external_value(PARAM_INT
, 'course module id', VALUE_REQUIRED
),
3496 'sectionreturn' => new external_value(PARAM_INT
, 'section to return to', VALUE_DEFAULT
, null),
3501 * Performs one of the edit module actions and return new html for AJAX
3503 * Returns html to replace the current module html with, for example:
3504 * - empty string for "delete" action,
3505 * - two modules html for "duplicate" action
3506 * - updated module html for everything else
3508 * Throws exception if operation is not permitted/possible
3511 * @param string $action
3513 * @param null|int $sectionreturn
3516 public static function edit_module($action, $id, $sectionreturn = null) {
3518 // Validate and normalize parameters.
3519 $params = self
::validate_parameters(self
::edit_module_parameters(),
3520 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3521 $action = $params['action'];
3522 $id = $params['id'];
3523 $sectionreturn = $params['sectionreturn'];
3525 // Set of permissions an editing user may have.
3527 'moodle/course:update',
3528 'moodle/course:manageactivities',
3529 'moodle/course:activityvisibility',
3530 'moodle/course:sectionvisibility',
3531 'moodle/course:movesections',
3532 'moodle/course:setcurrentsection',
3534 $PAGE->set_other_editing_capability($contextarray);
3536 list($course, $cm) = get_course_and_cm_from_cmid($id);
3537 $modcontext = context_module
::instance($cm->id
);
3538 $coursecontext = context_course
::instance($course->id
);
3539 self
::validate_context($modcontext);
3540 $format = course_get_format($course);
3541 if ($sectionreturn) {
3542 $format->set_section_number($sectionreturn);
3544 $renderer = $format->get_renderer($PAGE);
3550 require_capability('moodle/course:activityvisibility', $modcontext);
3551 $visible = ($action === 'hide') ?
0 : 1;
3552 $visibleoncoursepage = ($action === 'stealth') ?
0 : 1;
3553 set_coursemodule_visible($id, $visible, $visibleoncoursepage);
3554 \core\event\course_module_updated
::create_from_cm($cm, $modcontext)->trigger();
3557 require_capability('moodle/course:manageactivities', $coursecontext);
3558 require_capability('moodle/backup:backuptargetimport', $coursecontext);
3559 require_capability('moodle/restore:restoretargetimport', $coursecontext);
3560 if (!course_allowed_module($course, $cm->modname
)) {
3561 throw new moodle_exception('No permission to create that activity');
3563 if ($newcm = duplicate_module($course, $cm)) {
3565 $modinfo = $format->get_modinfo();
3566 $section = $modinfo->get_section_info($newcm->sectionnum
);
3567 $cm = $modinfo->get_cm($id);
3569 // Get both original and new element html.
3570 $result = $renderer->course_section_updated_cm_item($format, $section, $cm);
3571 $result .= $renderer->course_section_updated_cm_item($format, $section, $newcm);
3575 case 'groupsseparate':
3576 case 'groupsvisible':
3578 require_capability('moodle/course:manageactivities', $modcontext);
3579 if ($action === 'groupsseparate') {
3580 $newgroupmode = SEPARATEGROUPS
;
3581 } else if ($action === 'groupsvisible') {
3582 $newgroupmode = VISIBLEGROUPS
;
3584 $newgroupmode = NOGROUPS
;
3586 if (set_coursemodule_groupmode($cm->id
, $newgroupmode)) {
3587 \core\event\course_module_updated
::create_from_cm($cm, $modcontext)->trigger();
3592 require_capability('moodle/course:manageactivities', $modcontext);
3593 $indent = $cm->indent +
(($action === 'moveright') ?
1 : -1);
3594 if ($cm->indent
>= 0) {
3595 $DB->update_record('course_modules', array('id' => $cm->id
, 'indent' => $indent));
3596 rebuild_course_cache($cm->course
);
3600 require_capability('moodle/course:manageactivities', $modcontext);
3601 course_delete_module($cm->id
, true);
3604 throw new coding_exception('Unrecognised action');
3607 $modinfo = $format->get_modinfo();
3608 $section = $modinfo->get_section_info($cm->sectionnum
);
3609 $cm = $modinfo->get_cm($id);
3610 return $renderer->course_section_updated_cm_item($format, $section, $cm);
3614 * Return structure for edit_module()
3617 * @return external_description
3619 public static function edit_module_returns() {
3620 return new external_value(PARAM_RAW
, 'html to replace the current module with');
3624 * Parameters for function get_module()
3627 * @return external_function_parameters
3629 public static function get_module_parameters() {
3630 return new external_function_parameters(
3632 'id' => new external_value(PARAM_INT
, 'course module id', VALUE_REQUIRED
),
3633 'sectionreturn' => new external_value(PARAM_INT
, 'section to return to', VALUE_DEFAULT
, null),
3638 * Returns html for displaying one activity module on course page
3642 * @param null|int $sectionreturn
3645 public static function get_module($id, $sectionreturn = null) {
3647 // Validate and normalize parameters.
3648 $params = self
::validate_parameters(self
::get_module_parameters(),
3649 array('id' => $id, 'sectionreturn' => $sectionreturn));
3650 $id = $params['id'];
3651 $sectionreturn = $params['sectionreturn'];
3653 // Set of permissions an editing user may have.
3655 'moodle/course:update',
3656 'moodle/course:manageactivities',
3657 'moodle/course:activityvisibility',
3658 'moodle/course:sectionvisibility',
3659 'moodle/course:movesections',
3660 'moodle/course:setcurrentsection',
3662 $PAGE->set_other_editing_capability($contextarray);
3664 // Validate access to the course (note, this is html for the course view page, we don't validate access to the module).
3665 list($course, $cm) = get_course_and_cm_from_cmid($id);
3666 self
::validate_context(context_course
::instance($course->id
));
3668 $format = course_get_format($course);
3669 if ($sectionreturn) {
3670 $format->set_section_number($sectionreturn);
3672 $renderer = $format->get_renderer($PAGE);
3674 $modinfo = $format->get_modinfo();
3675 $section = $modinfo->get_section_info($cm->sectionnum
);
3676 return $renderer->course_section_updated_cm_item($format, $section, $cm);
3680 * Return structure for get_module()
3683 * @return external_description
3685 public static function get_module_returns() {
3686 return new external_value(PARAM_RAW
, 'html to replace the current module with');
3690 * Parameters for function edit_section()
3693 * @return external_function_parameters
3695 public static function edit_section_parameters() {
3696 return new external_function_parameters(
3698 'action' => new external_value(PARAM_ALPHA
, 'action: hide, show, stealth, setmarker, removemarker', VALUE_REQUIRED
),
3699 'id' => new external_value(PARAM_INT
, 'course section id', VALUE_REQUIRED
),
3700 'sectionreturn' => new external_value(PARAM_INT
, 'section to return to', VALUE_DEFAULT
, null),
3705 * Performs one of the edit section actions
3708 * @param string $action
3709 * @param int $id section id
3710 * @param int $sectionreturn section to return to
3713 public static function edit_section($action, $id, $sectionreturn) {
3715 // Validate and normalize parameters.
3716 $params = self
::validate_parameters(self
::edit_section_parameters(),
3717 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3718 $action = $params['action'];
3719 $id = $params['id'];
3720 $sr = $params['sectionreturn'];
3722 $section = $DB->get_record('course_sections', array('id' => $id), '*', MUST_EXIST
);
3723 $coursecontext = context_course
::instance($section->course
);
3724 self
::validate_context($coursecontext);
3726 $rv = course_get_format($section->course
)->section_action($section, $action, $sectionreturn);
3728 return json_encode($rv);
3735 * Return structure for edit_section()
3738 * @return external_description
3740 public static function edit_section_returns() {
3741 return new external_value(PARAM_RAW
, 'Additional data for javascript (JSON-encoded string)');
3745 * Returns description of method parameters
3747 * @return external_function_parameters
3749 public static function get_enrolled_courses_by_timeline_classification_parameters() {
3750 return new external_function_parameters(
3752 'classification' => new external_value(PARAM_ALPHA
, 'future, inprogress, or past'),
3753 'limit' => new external_value(PARAM_INT
, 'Result set limit', VALUE_DEFAULT
, 0),
3754 'offset' => new external_value(PARAM_INT
, 'Result set offset', VALUE_DEFAULT
, 0),
3755 'sort' => new external_value(PARAM_TEXT
, 'Sort string', VALUE_DEFAULT
, null),
3756 'customfieldname' => new external_value(PARAM_ALPHANUMEXT
, 'Used when classification = customfield',
3757 VALUE_DEFAULT
, null),
3758 'customfieldvalue' => new external_value(PARAM_RAW
, 'Used when classification = customfield',
3759 VALUE_DEFAULT
, null),
3760 'searchvalue' => new external_value(PARAM_RAW
, 'The value a user wishes to search against',
3761 VALUE_DEFAULT
, null),
3767 * Get courses matching the given timeline classification.
3769 * NOTE: The offset applies to the unfiltered full set of courses before the classification
3770 * filtering is done.
3772 * If the user is enrolled in 5 courses:
3773 * c1, c2, c3, c4, and c5
3774 * And c4 and c5 are 'future' courses
3776 * If a request comes in for future courses with an offset of 1 it will mean that
3777 * c1 is skipped (because the offset applies *before* the classification filtering)
3778 * and c4 and c5 will be return.
3780 * @param string $classification past, inprogress, or future
3781 * @param int $limit Result set limit
3782 * @param int $offset Offset the full course set before timeline classification is applied
3783 * @param string $sort SQL sort string for results
3784 * @param string $customfieldname
3785 * @param string $customfieldvalue
3786 * @param string $searchvalue
3787 * @return array list of courses and warnings
3788 * @throws invalid_parameter_exception
3790 public static function get_enrolled_courses_by_timeline_classification(
3791 string $classification,
3794 string $sort = null,
3795 string $customfieldname = null,
3796 string $customfieldvalue = null,
3797 string $searchvalue = null
3799 global $CFG, $PAGE, $USER;
3800 require_once($CFG->dirroot
. '/course/lib.php');
3802 $params = self
::validate_parameters(self
::get_enrolled_courses_by_timeline_classification_parameters(),
3804 'classification' => $classification,
3806 'offset' => $offset,
3808 'customfieldvalue' => $customfieldvalue,
3809 'searchvalue' => $searchvalue,
3813 $classification = $params['classification'];
3814 $limit = $params['limit'];
3815 $offset = $params['offset'];
3816 $sort = $params['sort'];
3817 $customfieldvalue = $params['customfieldvalue'];
3818 $searchvalue = clean_param($params['searchvalue'], PARAM_TEXT
);
3820 switch($classification) {
3821 case COURSE_TIMELINE_ALLINCLUDINGHIDDEN
:
3823 case COURSE_TIMELINE_ALL
:
3825 case COURSE_TIMELINE_PAST
:
3827 case COURSE_TIMELINE_INPROGRESS
:
3829 case COURSE_TIMELINE_FUTURE
:
3831 case COURSE_FAVOURITES
:
3833 case COURSE_TIMELINE_HIDDEN
:
3835 case COURSE_TIMELINE_SEARCH
:
3837 case COURSE_CUSTOMFIELD
:
3840 throw new invalid_parameter_exception('Invalid classification');
3843 self
::validate_context(context_user
::instance($USER->id
));
3845 $requiredproperties = course_summary_exporter
::define_properties();
3846 $fields = join(',', array_keys($requiredproperties));
3847 $hiddencourses = get_hidden_courses_on_timeline();
3850 // If the timeline requires really all courses, get really all courses.
3851 if ($classification == COURSE_TIMELINE_ALLINCLUDINGHIDDEN
) {
3852 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields, COURSE_DB_QUERY_LIMIT
);
3854 // Otherwise if the timeline requires the hidden courses then restrict the result to only $hiddencourses.
3855 } else if ($classification == COURSE_TIMELINE_HIDDEN
) {
3856 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields,
3857 COURSE_DB_QUERY_LIMIT
, $hiddencourses);
3859 // Otherwise get the requested courses and exclude the hidden courses.
3860 } else if ($classification == COURSE_TIMELINE_SEARCH
) {
3861 // Prepare the search API options.
3862 $searchcriteria['search'] = $searchvalue;
3863 $options = ['idonly' => true];
3864 $courses = course_get_enrolled_courses_for_logged_in_user_from_search(
3869 COURSE_DB_QUERY_LIMIT
,
3874 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields,
3875 COURSE_DB_QUERY_LIMIT
, [], $hiddencourses);
3878 $favouritecourseids = [];
3879 $ufservice = \core_favourites\service_factory
::get_service_for_user_context(\context_user
::instance($USER->id
));
3880 $favourites = $ufservice->find_favourites_by_type('core_course', 'courses');
3883 $favouritecourseids = array_map(
3884 function($favourite) {
3885 return $favourite->itemid
;
3889 if ($classification == COURSE_FAVOURITES
) {
3890 list($filteredcourses, $processedcount) = course_filter_courses_by_favourites(
3892 $favouritecourseids,
3895 } else if ($classification == COURSE_CUSTOMFIELD
) {
3896 list($filteredcourses, $processedcount) = course_filter_courses_by_customfield(
3903 list($filteredcourses, $processedcount) = course_filter_courses_by_timeline_classification(
3910 $renderer = $PAGE->get_renderer('core');
3911 $formattedcourses = array_map(function($course) use ($renderer, $favouritecourseids) {
3912 if ($course == null) {
3915 context_helper
::preload_from_record($course);
3916 $context = context_course
::instance($course->id
);
3917 $isfavourite = false;
3918 if (in_array($course->id
, $favouritecourseids)) {
3919 $isfavourite = true;
3921 $exporter = new course_summary_exporter($course, ['context' => $context, 'isfavourite' => $isfavourite]);
3922 return $exporter->export($renderer);
3923 }, $filteredcourses);
3925 $formattedcourses = array_filter($formattedcourses, function($course) {
3926 if ($course != null) {
3932 'courses' => $formattedcourses,
3933 'nextoffset' => $offset +
$processedcount
3938 * Returns description of method result value
3940 * @return external_description
3942 public static function get_enrolled_courses_by_timeline_classification_returns() {
3943 return new external_single_structure(
3945 'courses' => new external_multiple_structure(course_summary_exporter
::get_read_structure(), 'Course'),
3946 'nextoffset' => new external_value(PARAM_INT
, 'Offset for the next request')
3952 * Returns description of method parameters
3954 * @return external_function_parameters
3956 public static function set_favourite_courses_parameters() {
3957 return new external_function_parameters(
3959 'courses' => new external_multiple_structure(
3960 new external_single_structure(
3962 'id' => new external_value(PARAM_INT
, 'course ID'),
3963 'favourite' => new external_value(PARAM_BOOL
, 'favourite status')
3972 * Set the course favourite status for an array of courses.
3974 * @param array $courses List with course id's and favourite status.
3975 * @return array Array with an array of favourite courses.
3977 public static function set_favourite_courses(
3982 $params = self
::validate_parameters(self
::set_favourite_courses_parameters(),
3984 'courses' => $courses
3990 $ufservice = \core_favourites\service_factory
::get_service_for_user_context(\context_user
::instance($USER->id
));
3992 foreach ($params['courses'] as $course) {
3996 $favouriteexists = $ufservice->favourite_exists('core_course', 'courses', $course['id'],
3997 \context_course
::instance($course['id']));
3999 if ($course['favourite']) {
4000 if (!$favouriteexists) {
4002 $ufservice->create_favourite('core_course', 'courses', $course['id'],
4003 \context_course
::instance($course['id']));
4004 } catch (Exception
$e) {
4005 $warning['courseid'] = $course['id'];
4006 if ($e instanceof moodle_exception
) {
4007 $warning['warningcode'] = $e->errorcode
;
4009 $warning['warningcode'] = $e->getCode();
4011 $warning['message'] = $e->getMessage();
4012 $warnings[] = $warning;
4013 $warnings[] = $warning;
4016 $warning['courseid'] = $course['id'];
4017 $warning['warningcode'] = 'coursealreadyfavourited';
4018 $warning['message'] = 'Course already favourited';
4019 $warnings[] = $warning;
4022 if ($favouriteexists) {
4024 $ufservice->delete_favourite('core_course', 'courses', $course['id'],
4025 \context_course
::instance($course['id']));
4026 } catch (Exception
$e) {
4027 $warning['courseid'] = $course['id'];
4028 if ($e instanceof moodle_exception
) {
4029 $warning['warningcode'] = $e->errorcode
;
4031 $warning['warningcode'] = $e->getCode();
4033 $warning['message'] = $e->getMessage();
4034 $warnings[] = $warning;
4035 $warnings[] = $warning;
4038 $warning['courseid'] = $course['id'];
4039 $warning['warningcode'] = 'cannotdeletefavourite';
4040 $warning['message'] = 'Could not delete favourite status for course';
4041 $warnings[] = $warning;
4047 'warnings' => $warnings
4052 * Returns description of method result value
4054 * @return external_description
4056 public static function set_favourite_courses_returns() {
4057 return new external_single_structure(
4059 'warnings' => new external_warnings()
4065 * Returns description of method parameters
4067 * @return external_function_parameters
4070 public static function get_recent_courses_parameters() {
4071 return new external_function_parameters(
4073 'userid' => new external_value(PARAM_INT
, 'id of the user, default to current user', VALUE_DEFAULT
, 0),
4074 'limit' => new external_value(PARAM_INT
, 'result set limit', VALUE_DEFAULT
, 0),
4075 'offset' => new external_value(PARAM_INT
, 'Result set offset', VALUE_DEFAULT
, 0),
4076 'sort' => new external_value(PARAM_TEXT
, 'Sort string', VALUE_DEFAULT
, null)
4082 * Get last accessed courses adding additional course information like images.
4084 * @param int $userid User id from which the courses will be obtained
4085 * @param int $limit Restrict result set to this amount
4086 * @param int $offset Skip this number of records from the start of the result set
4087 * @param string|null $sort SQL string for sorting
4088 * @return array List of courses
4089 * @throws invalid_parameter_exception
4091 public static function get_recent_courses(int $userid = 0, int $limit = 0, int $offset = 0, string $sort = null) {
4092 global $USER, $PAGE;
4094 if (empty($userid)) {
4095 $userid = $USER->id
;
4098 $params = self
::validate_parameters(self
::get_recent_courses_parameters(),
4100 'userid' => $userid,
4102 'offset' => $offset,
4107 $userid = $params['userid'];
4108 $limit = $params['limit'];
4109 $offset = $params['offset'];
4110 $sort = $params['sort'];
4112 $usercontext = context_user
::instance($userid);
4114 self
::validate_context($usercontext);
4116 if ($userid != $USER->id
and !has_capability('moodle/user:viewdetails', $usercontext)) {
4120 $courses = course_get_recent_courses($userid, $limit, $offset, $sort);
4122 $renderer = $PAGE->get_renderer('core');
4124 $recentcourses = array_map(function($course) use ($renderer) {
4125 context_helper
::preload_from_record($course);
4126 $context = context_course
::instance($course->id
);
4127 $isfavourite = !empty($course->component
);
4128 $exporter = new course_summary_exporter($course, ['context' => $context, 'isfavourite' => $isfavourite]);
4129 return $exporter->export($renderer);
4132 return $recentcourses;
4136 * Returns description of method result value
4138 * @return external_description
4141 public static function get_recent_courses_returns() {
4142 return new external_multiple_structure(course_summary_exporter
::get_read_structure(), 'Courses');
4146 * Returns description of method parameters
4148 * @return external_function_parameters
4150 public static function get_enrolled_users_by_cmid_parameters() {
4151 return new external_function_parameters([
4152 'cmid' => new external_value(PARAM_INT
, 'id of the course module', VALUE_REQUIRED
),
4153 'groupid' => new external_value(PARAM_INT
, 'id of the group', VALUE_DEFAULT
, 0),
4158 * Get all users in a course for a given cmid.
4160 * @param int $cmid Course Module id from which the users will be obtained
4161 * @param int $groupid Group id from which the users will be obtained
4162 * @return array List of users
4163 * @throws invalid_parameter_exception
4165 public static function get_enrolled_users_by_cmid(int $cmid, int $groupid = 0) {
4171 'groupid' => $groupid,
4172 ] = self
::validate_parameters(self
::get_enrolled_users_by_cmid_parameters(), [
4174 'groupid' => $groupid,
4177 list($course, $cm) = get_course_and_cm_from_cmid($cmid);
4178 $coursecontext = context_course
::instance($course->id
);
4179 self
::validate_context($coursecontext);
4181 $enrolledusers = get_enrolled_users($coursecontext, '', $groupid);
4183 $users = array_map(function ($user) use ($PAGE) {
4184 $user->fullname
= fullname($user);
4185 $userpicture = new user_picture($user);
4186 $userpicture->size
= 1;
4187 $user->profileimage
= $userpicture->get_url($PAGE)->out(false);
4194 'warnings' => $warnings,
4199 * Returns description of method result value
4201 * @return external_description
4203 public static function get_enrolled_users_by_cmid_returns() {
4204 return new external_single_structure([
4205 'users' => new external_multiple_structure(self
::user_description()),
4206 'warnings' => new external_warnings(),
4211 * Create user return value description.
4213 * @return external_description
4215 public static function user_description() {
4216 $userfields = array(
4217 'id' => new external_value(core_user
::get_property_type('id'), 'ID of the user'),
4218 'profileimage' => new external_value(PARAM_URL
, 'The location of the users larger image', VALUE_OPTIONAL
),
4219 'fullname' => new external_value(PARAM_TEXT
, 'The full name of the user', VALUE_OPTIONAL
),
4220 'firstname' => new external_value(
4221 core_user
::get_property_type('firstname'),
4222 'The first name(s) of the user',
4224 'lastname' => new external_value(
4225 core_user
::get_property_type('lastname'),
4226 'The family name of the user',
4229 return new external_single_structure($userfields);
4233 * Returns description of method parameters.
4235 * @return external_function_parameters
4237 public static function add_content_item_to_user_favourites_parameters() {
4238 return new external_function_parameters([
4239 'componentname' => new external_value(PARAM_TEXT
,
4240 'frankenstyle name of the component to which the content item belongs', VALUE_REQUIRED
),
4241 'contentitemid' => new external_value(PARAM_INT
, 'id of the content item', VALUE_REQUIRED
, '', NULL_NOT_ALLOWED
)
4246 * Add a content item to a user's favourites.
4248 * @param string $componentname the name of the component from which this content item originates.
4249 * @param int $contentitemid the id of the content item.
4250 * @return stdClass the exporter content item.
4252 public static function add_content_item_to_user_favourites(string $componentname, int $contentitemid) {
4256 'componentname' => $componentname,
4257 'contentitemid' => $contentitemid,
4258 ] = self
::validate_parameters(self
::add_content_item_to_user_favourites_parameters(),
4260 'componentname' => $componentname,
4261 'contentitemid' => $contentitemid,
4265 self
::validate_context(context_user
::instance($USER->id
));
4267 $contentitemservice = \core_course\local\factory\content_item_service_factory
::get_content_item_service();
4269 return $contentitemservice->add_to_user_favourites($USER, $componentname, $contentitemid);
4273 * Returns description of method result value.
4275 * @return external_description
4277 public static function add_content_item_to_user_favourites_returns() {
4278 return \core_course\local\exporters\course_content_item_exporter
::get_read_structure();
4282 * Returns description of method parameters.
4284 * @return external_function_parameters
4286 public static function remove_content_item_from_user_favourites_parameters() {
4287 return new external_function_parameters([
4288 'componentname' => new external_value(PARAM_TEXT
,
4289 'frankenstyle name of the component to which the content item belongs', VALUE_REQUIRED
),
4290 'contentitemid' => new external_value(PARAM_INT
, 'id of the content item', VALUE_REQUIRED
, '', NULL_NOT_ALLOWED
),
4295 * Remove a content item from a user's favourites.
4297 * @param string $componentname the name of the component from which this content item originates.
4298 * @param int $contentitemid the id of the content item.
4299 * @return stdClass the exported content item.
4301 public static function remove_content_item_from_user_favourites(string $componentname, int $contentitemid) {
4305 'componentname' => $componentname,
4306 'contentitemid' => $contentitemid,
4307 ] = self
::validate_parameters(self
::remove_content_item_from_user_favourites_parameters(),
4309 'componentname' => $componentname,
4310 'contentitemid' => $contentitemid,
4314 self
::validate_context(context_user
::instance($USER->id
));
4316 $contentitemservice = \core_course\local\factory\content_item_service_factory
::get_content_item_service();
4318 return $contentitemservice->remove_from_user_favourites($USER, $componentname, $contentitemid);
4322 * Returns description of method result value.
4324 * @return external_description
4326 public static function remove_content_item_from_user_favourites_returns() {
4327 return \core_course\local\exporters\course_content_item_exporter
::get_read_structure();
4331 * Returns description of method result value
4333 * @return external_description
4335 public static function get_course_content_items_returns() {
4336 return new external_single_structure([
4337 'content_items' => new external_multiple_structure(
4338 \core_course\local\exporters\course_content_item_exporter
::get_read_structure()
4344 * Returns description of method parameters
4346 * @return external_function_parameters
4348 public static function get_course_content_items_parameters() {
4349 return new external_function_parameters([
4350 'courseid' => new external_value(PARAM_INT
, 'ID of the course', VALUE_REQUIRED
),
4355 * Given a course ID fetch all accessible modules for that course
4357 * @param int $courseid The course we want to fetch the modules for
4358 * @return array Contains array of modules and their metadata
4360 public static function get_course_content_items(int $courseid) {
4364 'courseid' => $courseid,
4365 ] = self
::validate_parameters(self
::get_course_content_items_parameters(), [
4366 'courseid' => $courseid,
4369 $coursecontext = context_course
::instance($courseid);
4370 self
::validate_context($coursecontext);
4371 $course = get_course($courseid);
4373 $contentitemservice = \core_course\local\factory\content_item_service_factory
::get_content_item_service();
4375 $contentitems = $contentitemservice->get_content_items_for_user_in_course($USER, $course);
4376 return ['content_items' => $contentitems];
4380 * Returns description of method parameters.
4382 * @return external_function_parameters
4384 public static function toggle_activity_recommendation_parameters() {
4385 return new external_function_parameters([
4386 'area' => new external_value(PARAM_TEXT
, 'The favourite area (itemtype)', VALUE_REQUIRED
),
4387 'id' => new external_value(PARAM_INT
, 'id of the activity or whatever', VALUE_REQUIRED
),
4392 * Update the recommendation for an activity item.
4394 * @param string $area identifier for this activity.
4395 * @param int $id Associated id. This is needed in conjunction with the area to find the recommendation.
4396 * @return array some warnings or something.
4398 public static function toggle_activity_recommendation(string $area, int $id): array {
4399 ['area' => $area, 'id' => $id] = self
::validate_parameters(self
::toggle_activity_recommendation_parameters(),
4400 ['area' => $area, 'id' => $id]);
4402 $context = context_system
::instance();
4403 self
::validate_context($context);
4405 require_capability('moodle/course:recommendactivity', $context);
4407 $manager = \core_course\local\factory\content_item_service_factory
::get_content_item_service();
4409 $status = $manager->toggle_recommendation($area, $id);
4410 return ['id' => $id, 'area' => $area, 'status' => $status];
4416 * @return external_description
4418 public static function toggle_activity_recommendation_returns() {
4419 return new external_single_structure(
4421 'id' => new external_value(PARAM_INT
, 'id of the activity or whatever'),
4422 'area' => new external_value(PARAM_TEXT
, 'The favourite area (itemtype)'),
4423 'status' => new external_value(PARAM_BOOL
, 'If created or deleted'),
4429 * Returns description of method parameters
4431 * @return external_function_parameters
4433 public static function get_activity_chooser_footer_parameters() {
4434 return new external_function_parameters([
4435 'courseid' => new external_value(PARAM_INT
, 'ID of the course', VALUE_REQUIRED
),
4436 'sectionid' => new external_value(PARAM_INT
, 'ID of the section', VALUE_REQUIRED
),
4441 * Given a course ID we need to build up a footre for the chooser.
4443 * @param int $courseid The course we want to fetch the modules for
4444 * @param int $sectionid The section we want to fetch the modules for
4447 public static function get_activity_chooser_footer(int $courseid, int $sectionid) {
4449 'courseid' => $courseid,
4450 'sectionid' => $sectionid,
4451 ] = self
::validate_parameters(self
::get_activity_chooser_footer_parameters(), [
4452 'courseid' => $courseid,
4453 'sectionid' => $sectionid,
4456 $coursecontext = context_course
::instance($courseid);
4457 self
::validate_context($coursecontext);
4459 $activeplugin = get_config('core', 'activitychooseractivefooter');
4461 if ($activeplugin !== COURSE_CHOOSER_FOOTER_NONE
) {
4462 $footerdata = component_callback($activeplugin, 'custom_chooser_footer', [$courseid, $sectionid]);
4465 'customfooterjs' => $footerdata->get_footer_js_file(),
4466 'customfootertemplate' => $footerdata->get_footer_template(),
4467 'customcarouseltemplate' => $footerdata->get_carousel_template(),
4477 * Returns description of method result value
4479 * @return external_description
4481 public static function get_activity_chooser_footer_returns() {
4482 return new external_single_structure(
4484 'footer' => new external_value(PARAM_BOOL
, 'Is a footer being return by this request?', VALUE_REQUIRED
),
4485 'customfooterjs' => new external_value(PARAM_RAW
, 'The path to the plugin JS file', VALUE_OPTIONAL
),
4486 'customfootertemplate' => new external_value(PARAM_RAW
, 'The prerendered footer', VALUE_OPTIONAL
),
4487 'customcarouseltemplate' => new external_value(PARAM_RAW
, 'Either "" or the prerendered carousel page',