2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
21 * @package core_course
23 * @copyright 2009 Petr Skodak
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') ||
die;
29 use core_course\external\course_summary_exporter
;
31 require_once("$CFG->libdir/externallib.php");
32 require_once(__DIR__
. "/lib.php");
35 * Course external functions
37 * @package core_course
39 * @copyright 2011 Jerome Mouneyrac
40 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
43 class core_course_external
extends external_api
{
46 * Returns description of method parameters
48 * @return external_function_parameters
49 * @since Moodle 2.9 Options available
52 public static function get_course_contents_parameters() {
53 return new external_function_parameters(
54 array('courseid' => new external_value(PARAM_INT
, 'course id'),
55 'options' => new external_multiple_structure (
56 new external_single_structure(
58 'name' => new external_value(PARAM_ALPHANUM
,
59 'The expected keys (value format) are:
60 excludemodules (bool) Do not return modules, return only the sections structure
61 excludecontents (bool) Do not return module contents (i.e: files inside a resource)
62 includestealthmodules (bool) Return stealth modules for students in a special
64 sectionid (int) Return only this section
65 sectionnumber (int) Return only this section with number (order)
66 cmid (int) Return only this module information (among the whole sections structure)
67 modname (string) Return only modules with this name "label, forum, etc..."
68 modid (int) Return only the module with this id (to be used with modname'),
69 'value' => new external_value(PARAM_RAW
, 'the value of the option,
70 this param is personaly validated in the external function.')
72 ), 'Options, used since Moodle 2.9', VALUE_DEFAULT
, array())
80 * @param int $courseid course id
81 * @param array $options Options for filtering the results, used since Moodle 2.9
83 * @since Moodle 2.9 Options available
86 public static function get_course_contents($courseid, $options = array()) {
88 require_once($CFG->dirroot
. "/course/lib.php");
89 require_once($CFG->libdir
. '/completionlib.php');
92 $params = self
::validate_parameters(self
::get_course_contents_parameters(),
93 array('courseid' => $courseid, 'options' => $options));
96 if (!empty($params['options'])) {
98 foreach ($params['options'] as $option) {
99 $name = trim($option['name']);
100 // Avoid duplicated options.
101 if (!isset($filters[$name])) {
103 case 'excludemodules':
104 case 'excludecontents':
105 case 'includestealthmodules':
106 $value = clean_param($option['value'], PARAM_BOOL
);
107 $filters[$name] = $value;
110 case 'sectionnumber':
113 $value = clean_param($option['value'], PARAM_INT
);
114 if (is_numeric($value)) {
115 $filters[$name] = $value;
117 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
121 $value = clean_param($option['value'], PARAM_PLUGIN
);
123 $filters[$name] = $value;
125 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
129 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
135 //retrieve the course
136 $course = $DB->get_record('course', array('id' => $params['courseid']), '*', MUST_EXIST
);
138 if ($course->id
!= SITEID
) {
139 // Check course format exist.
140 if (!file_exists($CFG->dirroot
. '/course/format/' . $course->format
. '/lib.php')) {
141 throw new moodle_exception('cannotgetcoursecontents', 'webservice', '', null,
142 get_string('courseformatnotfound', 'error', $course->format
));
144 require_once($CFG->dirroot
. '/course/format/' . $course->format
. '/lib.php');
148 // now security checks
149 $context = context_course
::instance($course->id
, IGNORE_MISSING
);
151 self
::validate_context($context);
152 } catch (Exception
$e) {
153 $exceptionparam = new stdClass();
154 $exceptionparam->message
= $e->getMessage();
155 $exceptionparam->courseid
= $course->id
;
156 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
159 $canupdatecourse = has_capability('moodle/course:update', $context);
161 //create return value
162 $coursecontents = array();
164 if ($canupdatecourse or $course->visible
165 or has_capability('moodle/course:viewhiddencourses', $context)) {
168 $modinfo = get_fast_modinfo($course);
169 $sections = $modinfo->get_section_info_all();
170 $courseformat = course_get_format($course);
171 $coursenumsections = $courseformat->get_last_section_number();
172 $stealthmodules = array(); // Array to keep all the modules available but not visible in a course section/topic.
174 $completioninfo = new completion_info($course);
176 //for each sections (first displayed to last displayed)
177 $modinfosections = $modinfo->get_sections();
178 foreach ($sections as $key => $section) {
180 // This becomes true when we are filtering and we found the value to filter with.
181 $sectionfound = false;
183 // Filter by section id.
184 if (!empty($filters['sectionid'])) {
185 if ($section->id
!= $filters['sectionid']) {
188 $sectionfound = true;
192 // Filter by section number. Note that 0 is a valid section number.
193 if (isset($filters['sectionnumber'])) {
194 if ($key != $filters['sectionnumber']) {
197 $sectionfound = true;
201 // reset $sectioncontents
202 $sectionvalues = array();
203 $sectionvalues['id'] = $section->id
;
204 $sectionvalues['name'] = get_section_name($course, $section);
205 $sectionvalues['visible'] = $section->visible
;
207 $options = (object) array('noclean' => true);
208 list($sectionvalues['summary'], $sectionvalues['summaryformat']) =
209 external_format_text($section->summary
, $section->summaryformat
,
210 $context->id
, 'course', 'section', $section->id
, $options);
211 $sectionvalues['section'] = $section->section
;
212 $sectionvalues['hiddenbynumsections'] = $section->section
> $coursenumsections ?
1 : 0;
213 $sectionvalues['uservisible'] = $section->uservisible
;
214 if (!empty($section->availableinfo
)) {
215 $sectionvalues['availabilityinfo'] = \core_availability\info
::format_info($section->availableinfo
, $course);
218 $sectioncontents = array();
220 // For each module of the section.
221 if (empty($filters['excludemodules']) and !empty($modinfosections[$section->section
])) {
222 foreach ($modinfosections[$section->section
] as $cmid) {
223 $cm = $modinfo->cms
[$cmid];
225 // Stop here if the module is not visible to the user on the course main page:
226 // The user can't access the module and the user can't view the module on the course page.
227 if (!$cm->uservisible
&& !$cm->is_visible_on_course_page()) {
231 // This becomes true when we are filtering and we found the value to filter with.
235 if (!empty($filters['cmid'])) {
236 if ($cmid != $filters['cmid']) {
243 // Filter by module name and id.
244 if (!empty($filters['modname'])) {
245 if ($cm->modname
!= $filters['modname']) {
247 } else if (!empty($filters['modid'])) {
248 if ($cm->instance
!= $filters['modid']) {
251 // Note that if we are only filtering by modname we don't break the loop.
259 $modcontext = context_module
::instance($cm->id
);
261 //common info (for people being able to see the module or availability dates)
262 $module['id'] = $cm->id
;
263 $module['name'] = external_format_string($cm->name
, $modcontext->id
);
264 $module['instance'] = $cm->instance
;
265 $module['modname'] = (string) $cm->modname
;
266 $module['modplural'] = (string) $cm->modplural
;
267 $module['modicon'] = $cm->get_icon_url()->out(false);
268 $module['indent'] = $cm->indent
;
269 $module['onclick'] = $cm->onclick
;
270 $module['afterlink'] = $cm->afterlink
;
271 $module['customdata'] = json_encode($cm->customdata
);
272 $module['completion'] = $cm->completion
;
273 $module['noviewlink'] = plugin_supports('mod', $cm->modname
, FEATURE_NO_VIEW_LINK
, false);
275 // Check module completion.
276 $completion = $completioninfo->is_enabled($cm);
277 if ($completion != COMPLETION_DISABLED
) {
278 $completiondata = $completioninfo->get_data($cm, true);
279 $module['completiondata'] = array(
280 'state' => $completiondata->completionstate
,
281 'timecompleted' => $completiondata->timemodified
,
282 'overrideby' => $completiondata->overrideby
,
283 'valueused' => core_availability\info
::completion_value_used($course, $cm->id
)
287 if (!empty($cm->showdescription
) or $module['noviewlink']) {
288 // We want to use the external format. However from reading get_formatted_content(), $cm->content format is always FORMAT_HTML.
289 $options = array('noclean' => true);
290 list($module['description'], $descriptionformat) = external_format_text($cm->content
,
291 FORMAT_HTML
, $modcontext->id
, $cm->modname
, 'intro', $cm->id
, $options);
296 if ($url) { //labels don't have url
297 $module['url'] = $url->out(false);
300 $canviewhidden = has_capability('moodle/course:viewhiddenactivities',
301 context_module
::instance($cm->id
));
302 //user that can view hidden module should know about the visibility
303 $module['visible'] = $cm->visible
;
304 $module['visibleoncoursepage'] = $cm->visibleoncoursepage
;
305 $module['uservisible'] = $cm->uservisible
;
306 if (!empty($cm->availableinfo
)) {
307 $module['availabilityinfo'] = \core_availability\info
::format_info($cm->availableinfo
, $course);
310 // Availability date (also send to user who can see hidden module).
311 if ($CFG->enableavailability
&& ($canviewhidden ||
$canupdatecourse)) {
312 $module['availability'] = $cm->availability
;
315 // Return contents only if the user can access to the module.
316 if ($cm->uservisible
) {
317 $baseurl = 'webservice/pluginfile.php';
319 // Call $modulename_export_contents (each module callback take care about checking the capabilities).
320 require_once($CFG->dirroot
. '/mod/' . $cm->modname
. '/lib.php');
321 $getcontentfunction = $cm->modname
.'_export_contents';
322 if (function_exists($getcontentfunction)) {
323 $contents = $getcontentfunction($cm, $baseurl);
324 $module['contentsinfo'] = array(
325 'filescount' => count($contents),
328 'mimetypes' => array(),
330 foreach ($contents as $content) {
331 // Check repository file (only main file).
332 if (!isset($module['contentsinfo']['repositorytype'])) {
333 $module['contentsinfo']['repositorytype'] =
334 isset($content['repositorytype']) ?
$content['repositorytype'] : '';
336 if (isset($content['filesize'])) {
337 $module['contentsinfo']['filessize'] +
= $content['filesize'];
339 if (isset($content['timemodified']) &&
340 ($content['timemodified'] > $module['contentsinfo']['lastmodified'])) {
342 $module['contentsinfo']['lastmodified'] = $content['timemodified'];
344 if (isset($content['mimetype'])) {
345 $module['contentsinfo']['mimetypes'][$content['mimetype']] = $content['mimetype'];
349 if (empty($filters['excludecontents']) and !empty($contents)) {
350 $module['contents'] = $contents;
352 $module['contents'] = array();
357 // Assign result to $sectioncontents, there is an exception,
358 // stealth activities in non-visible sections for students go to a special section.
359 if (!empty($filters['includestealthmodules']) && !$section->uservisible
&& $cm->is_stealth()) {
360 $stealthmodules[] = $module;
362 $sectioncontents[] = $module;
365 // If we just did a filtering, break the loop.
372 $sectionvalues['modules'] = $sectioncontents;
374 // assign result to $coursecontents
375 $coursecontents[$key] = $sectionvalues;
377 // Break the loop if we are filtering.
383 // Now that we have iterated over all the sections and activities, check the visibility.
384 // We didn't this before to be able to retrieve stealth activities.
385 foreach ($coursecontents as $sectionnumber => $sectioncontents) {
386 $section = $sections[$sectionnumber];
387 // Show the section if the user is permitted to access it OR
388 // if it's not available but there is some available info text which explains the reason & should display OR
389 // the course is configured to show hidden sections name.
390 $showsection = $section->uservisible ||
391 ($section->visible
&& !$section->available
&& !empty($section->availableinfo
)) ||
392 (!$section->visible
&& empty($courseformat->get_course()->hiddensections
));
395 unset($coursecontents[$sectionnumber]);
399 // Remove section and modules information if the section is not visible for the user.
400 if (!$section->uservisible
) {
401 $coursecontents[$sectionnumber]['modules'] = array();
402 // Remove summary information if the section is completely hidden only,
403 // even if the section is not user visible, the summary is always displayed among the availability information.
404 if (!$section->visible
) {
405 $coursecontents[$sectionnumber]['summary'] = '';
410 // Include stealth modules in special section (without any info).
411 if (!empty($stealthmodules)) {
412 $coursecontents[] = array(
416 'summaryformat' => FORMAT_MOODLE
,
417 'modules' => $stealthmodules
422 return $coursecontents;
426 * Returns description of method result value
428 * @return external_description
431 public static function get_course_contents_returns() {
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 'description' => new external_value(PARAM_RAW
, 'activity description', VALUE_OPTIONAL
),
453 'visible' => new external_value(PARAM_INT
, 'is the module visible', VALUE_OPTIONAL
),
454 'uservisible' => new external_value(PARAM_BOOL
, 'Is the module visible for the user?',
456 'availabilityinfo' => new external_value(PARAM_RAW
, 'Availability information.',
458 'visibleoncoursepage' => new external_value(PARAM_INT
, 'is the module visible on course page',
460 'modicon' => new external_value(PARAM_URL
, 'activity icon url'),
461 'modname' => new external_value(PARAM_PLUGIN
, 'activity module type'),
462 'modplural' => new external_value(PARAM_TEXT
, 'activity module plural name'),
463 'availability' => new external_value(PARAM_RAW
, 'module availability settings', VALUE_OPTIONAL
),
464 'indent' => new external_value(PARAM_INT
, 'number of identation in the site'),
465 'onclick' => new external_value(PARAM_RAW
, 'Onclick action.', VALUE_OPTIONAL
),
466 'afterlink' => new external_value(PARAM_RAW
, 'After link info to be displayed.',
468 'customdata' => new external_value(PARAM_RAW
, 'Custom data (JSON encoded).', VALUE_OPTIONAL
),
469 'noviewlink' => new external_value(PARAM_BOOL
, 'Whether the module has no view page',
471 'completion' => new external_value(PARAM_INT
, 'Type of completion tracking:
472 0 means none, 1 manual, 2 automatic.', VALUE_OPTIONAL
),
473 'completiondata' => new external_single_structure(
475 'state' => new external_value(PARAM_INT
, 'Completion state value:
476 0 means incomplete, 1 complete, 2 complete pass, 3 complete fail'),
477 'timecompleted' => new external_value(PARAM_INT
, 'Timestamp for completion status.'),
478 'overrideby' => new external_value(PARAM_INT
, 'The user id who has overriden the
480 'valueused' => new external_value(PARAM_BOOL
, 'Whether the completion status affects
481 the availability of another activity.', VALUE_OPTIONAL
),
482 ), 'Module completion data.', VALUE_OPTIONAL
484 'contents' => new external_multiple_structure(
485 new external_single_structure(
488 'type'=> new external_value(PARAM_TEXT
, 'a file or a folder or external link'),
489 'filename'=> new external_value(PARAM_FILE
, 'filename'),
490 'filepath'=> new external_value(PARAM_PATH
, 'filepath'),
491 'filesize'=> new external_value(PARAM_INT
, 'filesize'),
492 'fileurl' => new external_value(PARAM_URL
, 'downloadable file url', VALUE_OPTIONAL
),
493 'content' => new external_value(PARAM_RAW
, 'Raw content, will be used when type is content', VALUE_OPTIONAL
),
494 'timecreated' => new external_value(PARAM_INT
, 'Time created'),
495 'timemodified' => new external_value(PARAM_INT
, 'Time modified'),
496 'sortorder' => new external_value(PARAM_INT
, 'Content sort order'),
497 'mimetype' => new external_value(PARAM_RAW
, 'File mime type.', VALUE_OPTIONAL
),
498 'isexternalfile' => new external_value(PARAM_BOOL
, 'Whether is an external file.',
500 'repositorytype' => new external_value(PARAM_PLUGIN
, 'The repository type for external files.',
503 // copyright related info
504 'userid' => new external_value(PARAM_INT
, 'User who added this content to moodle'),
505 'author' => new external_value(PARAM_TEXT
, 'Content owner'),
506 'license' => new external_value(PARAM_TEXT
, 'Content license'),
507 'tags' => new external_multiple_structure(
508 \core_tag\external\tag_item_exporter
::get_read_structure(), 'Tags',
512 ), VALUE_DEFAULT
, array()
514 'contentsinfo' => new external_single_structure(
516 'filescount' => new external_value(PARAM_INT
, 'Total number of files.'),
517 'filessize' => new external_value(PARAM_INT
, 'Total files size.'),
518 'lastmodified' => new external_value(PARAM_INT
, 'Last time files were modified.'),
519 'mimetypes' => new external_multiple_structure(
520 new external_value(PARAM_RAW
, 'File mime type.'),
523 'repositorytype' => new external_value(PARAM_PLUGIN
, 'The repository type for
524 the main file.', VALUE_OPTIONAL
),
525 ), 'Contents summary information.', VALUE_OPTIONAL
536 * Returns description of method parameters
538 * @return external_function_parameters
541 public static function get_courses_parameters() {
542 return new external_function_parameters(
543 array('options' => new external_single_structure(
544 array('ids' => new external_multiple_structure(
545 new external_value(PARAM_INT
, 'Course id')
546 , 'List of course id. If empty return all courses
547 except front page course.',
549 ), 'options - operator OR is used', VALUE_DEFAULT
, array())
557 * @param array $options It contains an array (list of ids)
561 public static function get_courses($options = array()) {
563 require_once($CFG->dirroot
. "/course/lib.php");
566 $params = self
::validate_parameters(self
::get_courses_parameters(),
567 array('options' => $options));
570 if (!array_key_exists('ids', $params['options'])
571 or empty($params['options']['ids'])) {
572 $courses = $DB->get_records('course');
574 $courses = $DB->get_records_list('course', 'id', $params['options']['ids']);
577 //create return value
578 $coursesinfo = array();
579 foreach ($courses as $course) {
581 // now security checks
582 $context = context_course
::instance($course->id
, IGNORE_MISSING
);
583 $courseformatoptions = course_get_format($course)->get_format_options();
585 self
::validate_context($context);
586 } catch (Exception
$e) {
587 $exceptionparam = new stdClass();
588 $exceptionparam->message
= $e->getMessage();
589 $exceptionparam->courseid
= $course->id
;
590 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
592 if ($course->id
!= SITEID
) {
593 require_capability('moodle/course:view', $context);
596 $courseinfo = array();
597 $courseinfo['id'] = $course->id
;
598 $courseinfo['fullname'] = external_format_string($course->fullname
, $context->id
);
599 $courseinfo['shortname'] = external_format_string($course->shortname
, $context->id
);
600 $courseinfo['displayname'] = external_format_string(get_course_display_name_for_list($course), $context->id
);
601 $courseinfo['categoryid'] = $course->category
;
602 list($courseinfo['summary'], $courseinfo['summaryformat']) =
603 external_format_text($course->summary
, $course->summaryformat
, $context->id
, 'course', 'summary', 0);
604 $courseinfo['format'] = $course->format
;
605 $courseinfo['startdate'] = $course->startdate
;
606 $courseinfo['enddate'] = $course->enddate
;
607 if (array_key_exists('numsections', $courseformatoptions)) {
608 // For backward-compartibility
609 $courseinfo['numsections'] = $courseformatoptions['numsections'];
612 $handler = core_course\customfield\course_handler
::create();
613 if ($customfields = $handler->export_instance_data($course->id
)) {
614 $courseinfo['customfields'] = [];
615 foreach ($customfields as $data) {
616 $courseinfo['customfields'][] = [
617 'type' => $data->get_type(),
618 'value' => $data->get_value(),
619 'name' => $data->get_name(),
620 'shortname' => $data->get_shortname()
625 //some field should be returned only if the user has update permission
626 $courseadmin = has_capability('moodle/course:update', $context);
628 $courseinfo['categorysortorder'] = $course->sortorder
;
629 $courseinfo['idnumber'] = $course->idnumber
;
630 $courseinfo['showgrades'] = $course->showgrades
;
631 $courseinfo['showreports'] = $course->showreports
;
632 $courseinfo['newsitems'] = $course->newsitems
;
633 $courseinfo['visible'] = $course->visible
;
634 $courseinfo['maxbytes'] = $course->maxbytes
;
635 if (array_key_exists('hiddensections', $courseformatoptions)) {
636 // For backward-compartibility
637 $courseinfo['hiddensections'] = $courseformatoptions['hiddensections'];
639 // Return numsections for backward-compatibility with clients who expect it.
640 $courseinfo['numsections'] = course_get_format($course)->get_last_section_number();
641 $courseinfo['groupmode'] = $course->groupmode
;
642 $courseinfo['groupmodeforce'] = $course->groupmodeforce
;
643 $courseinfo['defaultgroupingid'] = $course->defaultgroupingid
;
644 $courseinfo['lang'] = clean_param($course->lang
, PARAM_LANG
);
645 $courseinfo['timecreated'] = $course->timecreated
;
646 $courseinfo['timemodified'] = $course->timemodified
;
647 $courseinfo['forcetheme'] = clean_param($course->theme
, PARAM_THEME
);
648 $courseinfo['enablecompletion'] = $course->enablecompletion
;
649 $courseinfo['completionnotify'] = $course->completionnotify
;
650 $courseinfo['courseformatoptions'] = array();
651 foreach ($courseformatoptions as $key => $value) {
652 $courseinfo['courseformatoptions'][] = array(
659 if ($courseadmin or $course->visible
660 or has_capability('moodle/course:viewhiddencourses', $context)) {
661 $coursesinfo[] = $courseinfo;
669 * Returns description of method result value
671 * @return external_description
674 public static function get_courses_returns() {
675 return new external_multiple_structure(
676 new external_single_structure(
678 'id' => new external_value(PARAM_INT
, 'course id'),
679 'shortname' => new external_value(PARAM_RAW
, 'course short name'),
680 'categoryid' => new external_value(PARAM_INT
, 'category id'),
681 'categorysortorder' => new external_value(PARAM_INT
,
682 'sort order into the category', VALUE_OPTIONAL
),
683 'fullname' => new external_value(PARAM_RAW
, 'full name'),
684 'displayname' => new external_value(PARAM_RAW
, 'course display name'),
685 'idnumber' => new external_value(PARAM_RAW
, 'id number', VALUE_OPTIONAL
),
686 'summary' => new external_value(PARAM_RAW
, 'summary'),
687 'summaryformat' => new external_format_value('summary'),
688 'format' => new external_value(PARAM_PLUGIN
,
689 'course format: weeks, topics, social, site,..'),
690 'showgrades' => new external_value(PARAM_INT
,
691 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL
),
692 'newsitems' => new external_value(PARAM_INT
,
693 'number of recent items appearing on the course page', VALUE_OPTIONAL
),
694 'startdate' => new external_value(PARAM_INT
,
695 'timestamp when the course start'),
696 'enddate' => new external_value(PARAM_INT
,
697 'timestamp when the course end'),
698 'numsections' => new external_value(PARAM_INT
,
699 '(deprecated, use courseformatoptions) number of weeks/topics',
701 'maxbytes' => new external_value(PARAM_INT
,
702 'largest size of file that can be uploaded into the course',
704 'showreports' => new external_value(PARAM_INT
,
705 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL
),
706 'visible' => new external_value(PARAM_INT
,
707 '1: available to student, 0:not available', VALUE_OPTIONAL
),
708 'hiddensections' => new external_value(PARAM_INT
,
709 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
711 'groupmode' => new external_value(PARAM_INT
, 'no group, separate, visible',
713 'groupmodeforce' => new external_value(PARAM_INT
, '1: yes, 0: no',
715 'defaultgroupingid' => new external_value(PARAM_INT
, 'default grouping id',
717 'timecreated' => new external_value(PARAM_INT
,
718 'timestamp when the course have been created', VALUE_OPTIONAL
),
719 'timemodified' => new external_value(PARAM_INT
,
720 'timestamp when the course have been modified', VALUE_OPTIONAL
),
721 'enablecompletion' => new external_value(PARAM_INT
,
722 'Enabled, control via completion and activity settings. Disbaled,
723 not shown in activity settings.',
725 'completionnotify' => new external_value(PARAM_INT
,
726 '1: yes 0: no', VALUE_OPTIONAL
),
727 'lang' => new external_value(PARAM_SAFEDIR
,
728 'forced course language', VALUE_OPTIONAL
),
729 'forcetheme' => new external_value(PARAM_PLUGIN
,
730 'name of the force theme', VALUE_OPTIONAL
),
731 'courseformatoptions' => new external_multiple_structure(
732 new external_single_structure(
733 array('name' => new external_value(PARAM_ALPHANUMEXT
, 'course format option name'),
734 'value' => new external_value(PARAM_RAW
, 'course format option value')
735 )), 'additional options for particular course format', VALUE_OPTIONAL
737 'customfields' => new external_multiple_structure(
738 new external_single_structure(
739 ['name' => new external_value(PARAM_RAW
, 'The name of the custom field'),
740 'shortname' => new external_value(PARAM_ALPHANUMEXT
, 'The shortname of the custom field'),
741 'type' => new external_value(PARAM_COMPONENT
,
742 'The type of the custom field - text, checkbox...'),
743 'value' => new external_value(PARAM_RAW
, 'The value of the custom field')]
744 ), 'Custom fields and associated values', VALUE_OPTIONAL
),
751 * Returns description of method parameters
753 * @return external_function_parameters
756 public static function create_courses_parameters() {
757 $courseconfig = get_config('moodlecourse'); //needed for many default values
758 return new external_function_parameters(
760 'courses' => new external_multiple_structure(
761 new external_single_structure(
763 'fullname' => new external_value(PARAM_TEXT
, 'full name'),
764 'shortname' => new external_value(PARAM_TEXT
, 'course short name'),
765 'categoryid' => new external_value(PARAM_INT
, 'category id'),
766 'idnumber' => new external_value(PARAM_RAW
, 'id number', VALUE_OPTIONAL
),
767 'summary' => new external_value(PARAM_RAW
, 'summary', VALUE_OPTIONAL
),
768 'summaryformat' => new external_format_value('summary', VALUE_DEFAULT
),
769 'format' => new external_value(PARAM_PLUGIN
,
770 'course format: weeks, topics, social, site,..',
771 VALUE_DEFAULT
, $courseconfig->format
),
772 'showgrades' => new external_value(PARAM_INT
,
773 '1 if grades are shown, otherwise 0', VALUE_DEFAULT
,
774 $courseconfig->showgrades
),
775 'newsitems' => new external_value(PARAM_INT
,
776 'number of recent items appearing on the course page',
777 VALUE_DEFAULT
, $courseconfig->newsitems
),
778 'startdate' => new external_value(PARAM_INT
,
779 'timestamp when the course start', VALUE_OPTIONAL
),
780 'enddate' => new external_value(PARAM_INT
,
781 'timestamp when the course end', VALUE_OPTIONAL
),
782 'numsections' => new external_value(PARAM_INT
,
783 '(deprecated, use courseformatoptions) number of weeks/topics',
785 'maxbytes' => new external_value(PARAM_INT
,
786 'largest size of file that can be uploaded into the course',
787 VALUE_DEFAULT
, $courseconfig->maxbytes
),
788 'showreports' => new external_value(PARAM_INT
,
789 'are activity report shown (yes = 1, no =0)', VALUE_DEFAULT
,
790 $courseconfig->showreports
),
791 'visible' => new external_value(PARAM_INT
,
792 '1: available to student, 0:not available', VALUE_OPTIONAL
),
793 'hiddensections' => new external_value(PARAM_INT
,
794 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
796 'groupmode' => new external_value(PARAM_INT
, 'no group, separate, visible',
797 VALUE_DEFAULT
, $courseconfig->groupmode
),
798 'groupmodeforce' => new external_value(PARAM_INT
, '1: yes, 0: no',
799 VALUE_DEFAULT
, $courseconfig->groupmodeforce
),
800 'defaultgroupingid' => new external_value(PARAM_INT
, 'default grouping id',
802 'enablecompletion' => new external_value(PARAM_INT
,
803 'Enabled, control via completion and activity settings. Disabled,
804 not shown in activity settings.',
806 'completionnotify' => new external_value(PARAM_INT
,
807 '1: yes 0: no', VALUE_OPTIONAL
),
808 'lang' => new external_value(PARAM_SAFEDIR
,
809 'forced course language', VALUE_OPTIONAL
),
810 'forcetheme' => new external_value(PARAM_PLUGIN
,
811 'name of the force theme', VALUE_OPTIONAL
),
812 'courseformatoptions' => new external_multiple_structure(
813 new external_single_structure(
814 array('name' => new external_value(PARAM_ALPHANUMEXT
, 'course format option name'),
815 'value' => new external_value(PARAM_RAW
, 'course format option value')
817 'additional options for particular course format', VALUE_OPTIONAL
),
818 'customfields' => new external_multiple_structure(
819 new external_single_structure(
821 'shortname' => new external_value(PARAM_ALPHANUMEXT
, 'The shortname of the custom field'),
822 'value' => new external_value(PARAM_RAW
, 'The value of the custom field'),
823 )), 'custom fields for the course', VALUE_OPTIONAL
825 )), 'courses to create'
834 * @param array $courses
835 * @return array courses (id and shortname only)
838 public static function create_courses($courses) {
840 require_once($CFG->dirroot
. "/course/lib.php");
841 require_once($CFG->libdir
. '/completionlib.php');
843 $params = self
::validate_parameters(self
::create_courses_parameters(),
844 array('courses' => $courses));
846 $availablethemes = core_component
::get_plugin_list('theme');
847 $availablelangs = get_string_manager()->get_list_of_translations();
849 $transaction = $DB->start_delegated_transaction();
851 foreach ($params['courses'] as $course) {
853 // Ensure the current user is allowed to run this function
854 $context = context_coursecat
::instance($course['categoryid'], IGNORE_MISSING
);
856 self
::validate_context($context);
857 } catch (Exception
$e) {
858 $exceptionparam = new stdClass();
859 $exceptionparam->message
= $e->getMessage();
860 $exceptionparam->catid
= $course['categoryid'];
861 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
863 require_capability('moodle/course:create', $context);
865 // Fullname and short name are required to be non-empty.
866 if (trim($course['fullname']) === '') {
867 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'fullname');
868 } else if (trim($course['shortname']) === '') {
869 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'shortname');
872 // Make sure lang is valid
873 if (array_key_exists('lang', $course)) {
874 if (empty($availablelangs[$course['lang']])) {
875 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
877 if (!has_capability('moodle/course:setforcedlanguage', $context)) {
878 unset($course['lang']);
882 // Make sure theme is valid
883 if (array_key_exists('forcetheme', $course)) {
884 if (!empty($CFG->allowcoursethemes
)) {
885 if (empty($availablethemes[$course['forcetheme']])) {
886 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
888 $course['theme'] = $course['forcetheme'];
893 //force visibility if ws user doesn't have the permission to set it
894 $category = $DB->get_record('course_categories', array('id' => $course['categoryid']));
895 if (!has_capability('moodle/course:visibility', $context)) {
896 $course['visible'] = $category->visible
;
899 //set default value for completion
900 $courseconfig = get_config('moodlecourse');
901 if (completion_info
::is_enabled_for_site()) {
902 if (!array_key_exists('enablecompletion', $course)) {
903 $course['enablecompletion'] = $courseconfig->enablecompletion
;
906 $course['enablecompletion'] = 0;
909 $course['category'] = $course['categoryid'];
912 $course['summaryformat'] = external_validate_format($course['summaryformat']);
914 if (!empty($course['courseformatoptions'])) {
915 foreach ($course['courseformatoptions'] as $option) {
916 $course[$option['name']] = $option['value'];
921 if (!empty($course['customfields'])) {
922 foreach ($course['customfields'] as $field) {
923 $course['customfield_'.$field['shortname']] = $field['value'];
927 //Note: create_course() core function check shortname, idnumber, category
928 $course['id'] = create_course((object) $course)->id
;
930 $resultcourses[] = array('id' => $course['id'], 'shortname' => $course['shortname']);
933 $transaction->allow_commit();
935 return $resultcourses;
939 * Returns description of method result value
941 * @return external_description
944 public static function create_courses_returns() {
945 return new external_multiple_structure(
946 new external_single_structure(
948 'id' => new external_value(PARAM_INT
, 'course id'),
949 'shortname' => new external_value(PARAM_RAW
, 'short name'),
958 * @return external_function_parameters
961 public static function update_courses_parameters() {
962 return new external_function_parameters(
964 'courses' => new external_multiple_structure(
965 new external_single_structure(
967 'id' => new external_value(PARAM_INT
, 'ID of the course'),
968 'fullname' => new external_value(PARAM_TEXT
, 'full name', VALUE_OPTIONAL
),
969 'shortname' => new external_value(PARAM_TEXT
, 'course short name', VALUE_OPTIONAL
),
970 'categoryid' => new external_value(PARAM_INT
, 'category id', VALUE_OPTIONAL
),
971 'idnumber' => new external_value(PARAM_RAW
, 'id number', VALUE_OPTIONAL
),
972 'summary' => new external_value(PARAM_RAW
, 'summary', VALUE_OPTIONAL
),
973 'summaryformat' => new external_format_value('summary', VALUE_OPTIONAL
),
974 'format' => new external_value(PARAM_PLUGIN
,
975 'course format: weeks, topics, social, site,..', VALUE_OPTIONAL
),
976 'showgrades' => new external_value(PARAM_INT
,
977 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL
),
978 'newsitems' => new external_value(PARAM_INT
,
979 'number of recent items appearing on the course page', VALUE_OPTIONAL
),
980 'startdate' => new external_value(PARAM_INT
,
981 'timestamp when the course start', VALUE_OPTIONAL
),
982 'enddate' => new external_value(PARAM_INT
,
983 'timestamp when the course end', VALUE_OPTIONAL
),
984 'numsections' => new external_value(PARAM_INT
,
985 '(deprecated, use courseformatoptions) number of weeks/topics', VALUE_OPTIONAL
),
986 'maxbytes' => new external_value(PARAM_INT
,
987 'largest size of file that can be uploaded into the course', VALUE_OPTIONAL
),
988 'showreports' => new external_value(PARAM_INT
,
989 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL
),
990 'visible' => new external_value(PARAM_INT
,
991 '1: available to student, 0:not available', VALUE_OPTIONAL
),
992 'hiddensections' => new external_value(PARAM_INT
,
993 '(deprecated, use courseformatoptions) How the hidden sections in the course are
994 displayed to students', VALUE_OPTIONAL
),
995 'groupmode' => new external_value(PARAM_INT
, 'no group, separate, visible', VALUE_OPTIONAL
),
996 'groupmodeforce' => new external_value(PARAM_INT
, '1: yes, 0: no', VALUE_OPTIONAL
),
997 'defaultgroupingid' => new external_value(PARAM_INT
, 'default grouping id', VALUE_OPTIONAL
),
998 'enablecompletion' => new external_value(PARAM_INT
,
999 'Enabled, control via completion and activity settings. Disabled,
1000 not shown in activity settings.', VALUE_OPTIONAL
),
1001 'completionnotify' => new external_value(PARAM_INT
, '1: yes 0: no', VALUE_OPTIONAL
),
1002 'lang' => new external_value(PARAM_SAFEDIR
, 'forced course language', VALUE_OPTIONAL
),
1003 'forcetheme' => new external_value(PARAM_PLUGIN
, 'name of the force theme', VALUE_OPTIONAL
),
1004 'courseformatoptions' => new external_multiple_structure(
1005 new external_single_structure(
1006 array('name' => new external_value(PARAM_ALPHANUMEXT
, 'course format option name'),
1007 'value' => new external_value(PARAM_RAW
, 'course format option value')
1008 )), 'additional options for particular course format', VALUE_OPTIONAL
),
1009 'customfields' => new external_multiple_structure(
1010 new external_single_structure(
1012 'shortname' => new external_value(PARAM_ALPHANUMEXT
, 'The shortname of the custom field'),
1013 'value' => new external_value(PARAM_RAW
, 'The value of the custom field')
1015 ), 'Custom fields', VALUE_OPTIONAL
),
1017 ), 'courses to update'
1026 * @param array $courses
1029 public static function update_courses($courses) {
1031 require_once($CFG->dirroot
. "/course/lib.php");
1032 $warnings = array();
1034 $params = self
::validate_parameters(self
::update_courses_parameters(),
1035 array('courses' => $courses));
1037 $availablethemes = core_component
::get_plugin_list('theme');
1038 $availablelangs = get_string_manager()->get_list_of_translations();
1040 foreach ($params['courses'] as $course) {
1041 // Catch any exception while updating course and return as warning to user.
1043 // Ensure the current user is allowed to run this function.
1044 $context = context_course
::instance($course['id'], MUST_EXIST
);
1045 self
::validate_context($context);
1047 $oldcourse = course_get_format($course['id'])->get_course();
1049 require_capability('moodle/course:update', $context);
1051 // Check if user can change category.
1052 if (array_key_exists('categoryid', $course) && ($oldcourse->category
!= $course['categoryid'])) {
1053 require_capability('moodle/course:changecategory', $context);
1054 $course['category'] = $course['categoryid'];
1057 // Check if the user can change fullname, and the new value is non-empty.
1058 if (array_key_exists('fullname', $course) && ($oldcourse->fullname
!= $course['fullname'])) {
1059 require_capability('moodle/course:changefullname', $context);
1060 if (trim($course['fullname']) === '') {
1061 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'fullname');
1065 // Check if the user can change shortname, and the new value is non-empty.
1066 if (array_key_exists('shortname', $course) && ($oldcourse->shortname
!= $course['shortname'])) {
1067 require_capability('moodle/course:changeshortname', $context);
1068 if (trim($course['shortname']) === '') {
1069 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'shortname');
1073 // Check if the user can change the idnumber.
1074 if (array_key_exists('idnumber', $course) && ($oldcourse->idnumber
!= $course['idnumber'])) {
1075 require_capability('moodle/course:changeidnumber', $context);
1078 // Check if user can change summary.
1079 if (array_key_exists('summary', $course) && ($oldcourse->summary
!= $course['summary'])) {
1080 require_capability('moodle/course:changesummary', $context);
1084 if (array_key_exists('summaryformat', $course) && ($oldcourse->summaryformat
!= $course['summaryformat'])) {
1085 require_capability('moodle/course:changesummary', $context);
1086 $course['summaryformat'] = external_validate_format($course['summaryformat']);
1089 // Check if user can change visibility.
1090 if (array_key_exists('visible', $course) && ($oldcourse->visible
!= $course['visible'])) {
1091 require_capability('moodle/course:visibility', $context);
1094 // Make sure lang is valid.
1095 if (array_key_exists('lang', $course) && ($oldcourse->lang
!= $course['lang'])) {
1096 require_capability('moodle/course:setforcedlanguage', $context);
1097 if (empty($availablelangs[$course['lang']])) {
1098 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
1102 // Make sure theme is valid.
1103 if (array_key_exists('forcetheme', $course)) {
1104 if (!empty($CFG->allowcoursethemes
)) {
1105 if (empty($availablethemes[$course['forcetheme']])) {
1106 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
1108 $course['theme'] = $course['forcetheme'];
1113 // Make sure completion is enabled before setting it.
1114 if (array_key_exists('enabledcompletion', $course) && !completion_info
::is_enabled_for_site()) {
1115 $course['enabledcompletion'] = 0;
1118 // Make sure maxbytes are less then CFG->maxbytes.
1119 if (array_key_exists('maxbytes', $course)) {
1120 // We allow updates back to 0 max bytes, a special value denoting the course uses the site limit.
1121 // Otherwise, either use the size specified, or cap at the max size for the course.
1122 if ($course['maxbytes'] != 0) {
1123 $course['maxbytes'] = get_max_upload_file_size($CFG->maxbytes
, $course['maxbytes']);
1127 if (!empty($course['courseformatoptions'])) {
1128 foreach ($course['courseformatoptions'] as $option) {
1129 if (isset($option['name']) && isset($option['value'])) {
1130 $course[$option['name']] = $option['value'];
1135 // Prepare list of custom fields.
1136 if (isset($course['customfields'])) {
1137 foreach ($course['customfields'] as $field) {
1138 $course['customfield_' . $field['shortname']] = $field['value'];
1142 // Update course if user has all required capabilities.
1143 update_course((object) $course);
1144 } catch (Exception
$e) {
1146 $warning['item'] = 'course';
1147 $warning['itemid'] = $course['id'];
1148 if ($e instanceof moodle_exception
) {
1149 $warning['warningcode'] = $e->errorcode
;
1151 $warning['warningcode'] = $e->getCode();
1153 $warning['message'] = $e->getMessage();
1154 $warnings[] = $warning;
1159 $result['warnings'] = $warnings;
1164 * Returns description of method result value
1166 * @return external_description
1169 public static function update_courses_returns() {
1170 return new external_single_structure(
1172 'warnings' => new external_warnings()
1178 * Returns description of method parameters
1180 * @return external_function_parameters
1183 public static function delete_courses_parameters() {
1184 return new external_function_parameters(
1186 'courseids' => new external_multiple_structure(new external_value(PARAM_INT
, 'course ID')),
1194 * @param array $courseids A list of course ids
1197 public static function delete_courses($courseids) {
1199 require_once($CFG->dirroot
."/course/lib.php");
1201 // Parameter validation.
1202 $params = self
::validate_parameters(self
::delete_courses_parameters(), array('courseids'=>$courseids));
1204 $warnings = array();
1206 foreach ($params['courseids'] as $courseid) {
1207 $course = $DB->get_record('course', array('id' => $courseid));
1209 if ($course === false) {
1210 $warnings[] = array(
1212 'itemid' => $courseid,
1213 'warningcode' => 'unknowncourseidnumber',
1214 'message' => 'Unknown course ID ' . $courseid
1219 // Check if the context is valid.
1220 $coursecontext = context_course
::instance($course->id
);
1221 self
::validate_context($coursecontext);
1223 // Check if the current user has permission.
1224 if (!can_delete_course($courseid)) {
1225 $warnings[] = array(
1227 'itemid' => $courseid,
1228 'warningcode' => 'cannotdeletecourse',
1229 'message' => 'You do not have the permission to delete this course' . $courseid
1234 if (delete_course($course, false) === false) {
1235 $warnings[] = array(
1237 'itemid' => $courseid,
1238 'warningcode' => 'cannotdeletecategorycourse',
1239 'message' => 'Course ' . $courseid . ' failed to be deleted'
1245 fix_course_sortorder();
1247 return array('warnings' => $warnings);
1251 * Returns description of method result value
1253 * @return external_description
1256 public static function delete_courses_returns() {
1257 return new external_single_structure(
1259 'warnings' => new external_warnings()
1265 * Returns description of method parameters
1267 * @return external_function_parameters
1270 public static function duplicate_course_parameters() {
1271 return new external_function_parameters(
1273 'courseid' => new external_value(PARAM_INT
, 'course to duplicate id'),
1274 'fullname' => new external_value(PARAM_TEXT
, 'duplicated course full name'),
1275 'shortname' => new external_value(PARAM_TEXT
, 'duplicated course short name'),
1276 'categoryid' => new external_value(PARAM_INT
, 'duplicated course category parent'),
1277 'visible' => new external_value(PARAM_INT
, 'duplicated course visible, default to yes', VALUE_DEFAULT
, 1),
1278 'options' => new external_multiple_structure(
1279 new external_single_structure(
1281 'name' => new external_value(PARAM_ALPHAEXT
, 'The backup option name:
1282 "activities" (int) Include course activites (default to 1 that is equal to yes),
1283 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1284 "filters" (int) Include course filters (default to 1 that is equal to yes),
1285 "users" (int) Include users (default to 0 that is equal to no),
1286 "enrolments" (int) Include enrolment methods (default to 1 - restore only with users),
1287 "role_assignments" (int) Include role assignments (default to 0 that is equal to no),
1288 "comments" (int) Include user comments (default to 0 that is equal to no),
1289 "userscompletion" (int) Include user course completion information (default to 0 that is equal to no),
1290 "logs" (int) Include course logs (default to 0 that is equal to no),
1291 "grade_histories" (int) Include histories (default to 0 that is equal to no)'
1293 'value' => new external_value(PARAM_RAW
, 'the value for the option 1 (yes) or 0 (no)'
1296 ), VALUE_DEFAULT
, array()
1303 * Duplicate a course
1305 * @param int $courseid
1306 * @param string $fullname Duplicated course fullname
1307 * @param string $shortname Duplicated course shortname
1308 * @param int $categoryid Duplicated course parent category id
1309 * @param int $visible Duplicated course availability
1310 * @param array $options List of backup options
1311 * @return array New course info
1314 public static function duplicate_course($courseid, $fullname, $shortname, $categoryid, $visible = 1, $options = array()) {
1315 global $CFG, $USER, $DB;
1316 require_once($CFG->dirroot
. '/backup/util/includes/backup_includes.php');
1317 require_once($CFG->dirroot
. '/backup/util/includes/restore_includes.php');
1319 // Parameter validation.
1320 $params = self
::validate_parameters(
1321 self
::duplicate_course_parameters(),
1323 'courseid' => $courseid,
1324 'fullname' => $fullname,
1325 'shortname' => $shortname,
1326 'categoryid' => $categoryid,
1327 'visible' => $visible,
1328 'options' => $options
1332 // Context validation.
1334 if (! ($course = $DB->get_record('course', array('id'=>$params['courseid'])))) {
1335 throw new moodle_exception('invalidcourseid', 'error');
1338 // Category where duplicated course is going to be created.
1339 $categorycontext = context_coursecat
::instance($params['categoryid']);
1340 self
::validate_context($categorycontext);
1342 // Course to be duplicated.
1343 $coursecontext = context_course
::instance($course->id
);
1344 self
::validate_context($coursecontext);
1346 $backupdefaults = array(
1351 'enrolments' => backup
::ENROL_WITHUSERS
,
1352 'role_assignments' => 0,
1354 'userscompletion' => 0,
1356 'grade_histories' => 0
1359 $backupsettings = array();
1360 // Check for backup and restore options.
1361 if (!empty($params['options'])) {
1362 foreach ($params['options'] as $option) {
1364 // Strict check for a correct value (allways 1 or 0, true or false).
1365 $value = clean_param($option['value'], PARAM_INT
);
1367 if ($value !== 0 and $value !== 1) {
1368 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1371 if (!isset($backupdefaults[$option['name']])) {
1372 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1375 $backupsettings[$option['name']] = $value;
1379 // Capability checking.
1381 // The backup controller check for this currently, this may be redundant.
1382 require_capability('moodle/course:create', $categorycontext);
1383 require_capability('moodle/restore:restorecourse', $categorycontext);
1384 require_capability('moodle/backup:backupcourse', $coursecontext);
1386 if (!empty($backupsettings['users'])) {
1387 require_capability('moodle/backup:userinfo', $coursecontext);
1388 require_capability('moodle/restore:userinfo', $categorycontext);
1391 // Check if the shortname is used.
1392 if ($foundcourses = $DB->get_records('course', array('shortname'=>$shortname))) {
1393 foreach ($foundcourses as $foundcourse) {
1394 $foundcoursenames[] = $foundcourse->fullname
;
1397 $foundcoursenamestring = implode(',', $foundcoursenames);
1398 throw new moodle_exception('shortnametaken', '', '', $foundcoursenamestring);
1401 // Backup the course.
1403 $bc = new backup_controller(backup
::TYPE_1COURSE
, $course->id
, backup
::FORMAT_MOODLE
,
1404 backup
::INTERACTIVE_NO
, backup
::MODE_SAMESITE
, $USER->id
);
1406 foreach ($backupsettings as $name => $value) {
1407 if ($setting = $bc->get_plan()->get_setting($name)) {
1408 $bc->get_plan()->get_setting($name)->set_value($value);
1412 $backupid = $bc->get_backupid();
1413 $backupbasepath = $bc->get_plan()->get_basepath();
1415 $bc->execute_plan();
1416 $results = $bc->get_results();
1417 $file = $results['backup_destination'];
1421 // Restore the backup immediately.
1423 // Check if we need to unzip the file because the backup temp dir does not contains backup files.
1424 if (!file_exists($backupbasepath . "/moodle_backup.xml")) {
1425 $file->extract_to_pathname(get_file_packer('application/vnd.moodle.backup'), $backupbasepath);
1428 // Create new course.
1429 $newcourseid = restore_dbops
::create_new_course($params['fullname'], $params['shortname'], $params['categoryid']);
1431 $rc = new restore_controller($backupid, $newcourseid,
1432 backup
::INTERACTIVE_NO
, backup
::MODE_SAMESITE
, $USER->id
, backup
::TARGET_NEW_COURSE
);
1434 foreach ($backupsettings as $name => $value) {
1435 $setting = $rc->get_plan()->get_setting($name);
1436 if ($setting->get_status() == backup_setting
::NOT_LOCKED
) {
1437 $setting->set_value($value);
1441 if (!$rc->execute_precheck()) {
1442 $precheckresults = $rc->get_precheck_results();
1443 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1444 if (empty($CFG->keeptempdirectoriesonbackup
)) {
1445 fulldelete($backupbasepath);
1450 foreach ($precheckresults['errors'] as $error) {
1451 $errorinfo .= $error;
1454 if (array_key_exists('warnings', $precheckresults)) {
1455 foreach ($precheckresults['warnings'] as $warning) {
1456 $errorinfo .= $warning;
1460 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1464 $rc->execute_plan();
1467 $course = $DB->get_record('course', array('id' => $newcourseid), '*', MUST_EXIST
);
1468 $course->fullname
= $params['fullname'];
1469 $course->shortname
= $params['shortname'];
1470 $course->visible
= $params['visible'];
1472 // Set shortname and fullname back.
1473 $DB->update_record('course', $course);
1475 if (empty($CFG->keeptempdirectoriesonbackup
)) {
1476 fulldelete($backupbasepath);
1479 // Delete the course backup file created by this WebService. Originally located in the course backups area.
1482 return array('id' => $course->id
, 'shortname' => $course->shortname
);
1486 * Returns description of method result value
1488 * @return external_description
1491 public static function duplicate_course_returns() {
1492 return new external_single_structure(
1494 'id' => new external_value(PARAM_INT
, 'course id'),
1495 'shortname' => new external_value(PARAM_RAW
, 'short name'),
1501 * Returns description of method parameters for import_course
1503 * @return external_function_parameters
1506 public static function import_course_parameters() {
1507 return new external_function_parameters(
1509 'importfrom' => new external_value(PARAM_INT
, 'the id of the course we are importing from'),
1510 'importto' => new external_value(PARAM_INT
, 'the id of the course we are importing to'),
1511 'deletecontent' => new external_value(PARAM_INT
, 'whether to delete the course content where we are importing to (default to 0 = No)', VALUE_DEFAULT
, 0),
1512 'options' => new external_multiple_structure(
1513 new external_single_structure(
1515 'name' => new external_value(PARAM_ALPHA
, 'The backup option name:
1516 "activities" (int) Include course activites (default to 1 that is equal to yes),
1517 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1518 "filters" (int) Include course filters (default to 1 that is equal to yes)'
1520 'value' => new external_value(PARAM_RAW
, 'the value for the option 1 (yes) or 0 (no)'
1523 ), VALUE_DEFAULT
, array()
1532 * @param int $importfrom The id of the course we are importing from
1533 * @param int $importto The id of the course we are importing to
1534 * @param bool $deletecontent Whether to delete the course we are importing to content
1535 * @param array $options List of backup options
1539 public static function import_course($importfrom, $importto, $deletecontent = 0, $options = array()) {
1540 global $CFG, $USER, $DB;
1541 require_once($CFG->dirroot
. '/backup/util/includes/backup_includes.php');
1542 require_once($CFG->dirroot
. '/backup/util/includes/restore_includes.php');
1544 // Parameter validation.
1545 $params = self
::validate_parameters(
1546 self
::import_course_parameters(),
1548 'importfrom' => $importfrom,
1549 'importto' => $importto,
1550 'deletecontent' => $deletecontent,
1551 'options' => $options
1555 if ($params['deletecontent'] !== 0 and $params['deletecontent'] !== 1) {
1556 throw new moodle_exception('invalidextparam', 'webservice', '', $params['deletecontent']);
1559 // Context validation.
1561 if (! ($importfrom = $DB->get_record('course', array('id'=>$params['importfrom'])))) {
1562 throw new moodle_exception('invalidcourseid', 'error');
1565 if (! ($importto = $DB->get_record('course', array('id'=>$params['importto'])))) {
1566 throw new moodle_exception('invalidcourseid', 'error');
1569 $importfromcontext = context_course
::instance($importfrom->id
);
1570 self
::validate_context($importfromcontext);
1572 $importtocontext = context_course
::instance($importto->id
);
1573 self
::validate_context($importtocontext);
1575 $backupdefaults = array(
1581 $backupsettings = array();
1583 // Check for backup and restore options.
1584 if (!empty($params['options'])) {
1585 foreach ($params['options'] as $option) {
1587 // Strict check for a correct value (allways 1 or 0, true or false).
1588 $value = clean_param($option['value'], PARAM_INT
);
1590 if ($value !== 0 and $value !== 1) {
1591 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1594 if (!isset($backupdefaults[$option['name']])) {
1595 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1598 $backupsettings[$option['name']] = $value;
1602 // Capability checking.
1604 require_capability('moodle/backup:backuptargetimport', $importfromcontext);
1605 require_capability('moodle/restore:restoretargetimport', $importtocontext);
1607 $bc = new backup_controller(backup
::TYPE_1COURSE
, $importfrom->id
, backup
::FORMAT_MOODLE
,
1608 backup
::INTERACTIVE_NO
, backup
::MODE_IMPORT
, $USER->id
);
1610 foreach ($backupsettings as $name => $value) {
1611 $bc->get_plan()->get_setting($name)->set_value($value);
1614 $backupid = $bc->get_backupid();
1615 $backupbasepath = $bc->get_plan()->get_basepath();
1617 $bc->execute_plan();
1620 // Restore the backup immediately.
1622 // Check if we must delete the contents of the destination course.
1623 if ($params['deletecontent']) {
1624 $restoretarget = backup
::TARGET_EXISTING_DELETING
;
1626 $restoretarget = backup
::TARGET_EXISTING_ADDING
;
1629 $rc = new restore_controller($backupid, $importto->id
,
1630 backup
::INTERACTIVE_NO
, backup
::MODE_IMPORT
, $USER->id
, $restoretarget);
1632 foreach ($backupsettings as $name => $value) {
1633 $rc->get_plan()->get_setting($name)->set_value($value);
1636 if (!$rc->execute_precheck()) {
1637 $precheckresults = $rc->get_precheck_results();
1638 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1639 if (empty($CFG->keeptempdirectoriesonbackup
)) {
1640 fulldelete($backupbasepath);
1645 foreach ($precheckresults['errors'] as $error) {
1646 $errorinfo .= $error;
1649 if (array_key_exists('warnings', $precheckresults)) {
1650 foreach ($precheckresults['warnings'] as $warning) {
1651 $errorinfo .= $warning;
1655 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1658 if ($restoretarget == backup
::TARGET_EXISTING_DELETING
) {
1659 restore_dbops
::delete_course_content($importto->id
);
1663 $rc->execute_plan();
1666 if (empty($CFG->keeptempdirectoriesonbackup
)) {
1667 fulldelete($backupbasepath);
1674 * Returns description of method result value
1676 * @return external_description
1679 public static function import_course_returns() {
1684 * Returns description of method parameters
1686 * @return external_function_parameters
1689 public static function get_categories_parameters() {
1690 return new external_function_parameters(
1692 'criteria' => new external_multiple_structure(
1693 new external_single_structure(
1695 'key' => new external_value(PARAM_ALPHA
,
1696 'The category column to search, expected keys (value format) are:'.
1697 '"id" (int) the category id,'.
1698 '"ids" (string) category ids separated by commas,'.
1699 '"name" (string) the category name,'.
1700 '"parent" (int) the parent category id,'.
1701 '"idnumber" (string) category idnumber'.
1702 ' - user must have \'moodle/category:manage\' to search on idnumber,'.
1703 '"visible" (int) whether the returned categories must be visible or hidden. If the key is not passed,
1704 then the function return all categories that the user can see.'.
1705 ' - user must have \'moodle/category:manage\' or \'moodle/category:viewhiddencategories\' to search on visible,'.
1706 '"theme" (string) only return the categories having this theme'.
1707 ' - user must have \'moodle/category:manage\' to search on theme'),
1708 'value' => new external_value(PARAM_RAW
, 'the value to match')
1710 ), 'criteria', VALUE_DEFAULT
, array()
1712 'addsubcategories' => new external_value(PARAM_BOOL
, 'return the sub categories infos
1713 (1 - default) otherwise only the category info (0)', VALUE_DEFAULT
, 1)
1721 * @param array $criteria Criteria to match the results
1722 * @param booln $addsubcategories obtain only the category (false) or its subcategories (true - default)
1723 * @return array list of categories
1726 public static function get_categories($criteria = array(), $addsubcategories = true) {
1728 require_once($CFG->dirroot
. "/course/lib.php");
1730 // Validate parameters.
1731 $params = self
::validate_parameters(self
::get_categories_parameters(),
1732 array('criteria' => $criteria, 'addsubcategories' => $addsubcategories));
1734 // Retrieve the categories.
1735 $categories = array();
1736 if (!empty($params['criteria'])) {
1738 $conditions = array();
1740 foreach ($params['criteria'] as $crit) {
1741 $key = trim($crit['key']);
1743 // Trying to avoid duplicate keys.
1744 if (!isset($conditions[$key])) {
1746 $context = context_system
::instance();
1750 $value = clean_param($crit['value'], PARAM_INT
);
1751 $conditions[$key] = $value;
1752 $wheres[] = $key . " = :" . $key;
1756 $value = clean_param($crit['value'], PARAM_SEQUENCE
);
1757 $ids = explode(',', $value);
1758 list($sqlids, $paramids) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED
);
1759 $conditions = array_merge($conditions, $paramids);
1760 $wheres[] = 'id ' . $sqlids;
1764 if (has_capability('moodle/category:manage', $context)) {
1765 $value = clean_param($crit['value'], PARAM_RAW
);
1766 $conditions[$key] = $value;
1767 $wheres[] = $key . " = :" . $key;
1769 // We must throw an exception.
1770 // Otherwise the dev client would think no idnumber exists.
1771 throw new moodle_exception('criteriaerror',
1772 'webservice', '', null,
1773 'You don\'t have the permissions to search on the "idnumber" field.');
1778 $value = clean_param($crit['value'], PARAM_TEXT
);
1779 $conditions[$key] = $value;
1780 $wheres[] = $key . " = :" . $key;
1784 $value = clean_param($crit['value'], PARAM_INT
);
1785 $conditions[$key] = $value;
1786 $wheres[] = $key . " = :" . $key;
1790 if (has_capability('moodle/category:viewhiddencategories', $context)) {
1791 $value = clean_param($crit['value'], PARAM_INT
);
1792 $conditions[$key] = $value;
1793 $wheres[] = $key . " = :" . $key;
1795 throw new moodle_exception('criteriaerror',
1796 'webservice', '', null,
1797 'You don\'t have the permissions to search on the "visible" field.');
1802 if (has_capability('moodle/category:manage', $context)) {
1803 $value = clean_param($crit['value'], PARAM_THEME
);
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 "theme" field.');
1814 throw new moodle_exception('criteriaerror',
1815 'webservice', '', null,
1816 'You can not search on this criteria: ' . $key);
1821 if (!empty($wheres)) {
1822 $wheres = implode(" AND ", $wheres);
1824 $categories = $DB->get_records_select('course_categories', $wheres, $conditions);
1826 // Retrieve its sub subcategories (all levels).
1827 if ($categories and !empty($params['addsubcategories'])) {
1828 $newcategories = array();
1830 // Check if we required visible/theme checks.
1831 $additionalselect = '';
1832 $additionalparams = array();
1833 if (isset($conditions['visible'])) {
1834 $additionalselect .= ' AND visible = :visible';
1835 $additionalparams['visible'] = $conditions['visible'];
1837 if (isset($conditions['theme'])) {
1838 $additionalselect .= ' AND theme= :theme';
1839 $additionalparams['theme'] = $conditions['theme'];
1842 foreach ($categories as $category) {
1843 $sqlselect = $DB->sql_like('path', ':path') . $additionalselect;
1844 $sqlparams = array('path' => $category->path
.'/%') +
$additionalparams; // It will NOT include the specified category.
1845 $subcategories = $DB->get_records_select('course_categories', $sqlselect, $sqlparams);
1846 $newcategories = $newcategories +
$subcategories; // Both arrays have integer as keys.
1848 $categories = $categories +
$newcategories;
1853 // Retrieve all categories in the database.
1854 $categories = $DB->get_records('course_categories');
1857 // The not returned categories. key => category id, value => reason of exclusion.
1858 $excludedcats = array();
1860 // The returned categories.
1861 $categoriesinfo = array();
1863 // We need to sort the categories by path.
1864 // The parent cats need to be checked by the algo first.
1865 usort($categories, "core_course_external::compare_categories_by_path");
1867 foreach ($categories as $category) {
1869 // Check if the category is a child of an excluded category, if yes exclude it too (excluded => do not return).
1870 $parents = explode('/', $category->path
);
1871 unset($parents[0]); // First key is always empty because path start with / => /1/2/4.
1872 foreach ($parents as $parentid) {
1873 // Note: when the parent exclusion was due to the context,
1874 // the sub category could still be returned.
1875 if (isset($excludedcats[$parentid]) and $excludedcats[$parentid] != 'context') {
1876 $excludedcats[$category->id
] = 'parent';
1880 // Check the user can use the category context.
1881 $context = context_coursecat
::instance($category->id
);
1883 self
::validate_context($context);
1884 } catch (Exception
$e) {
1885 $excludedcats[$category->id
] = 'context';
1887 // If it was the requested category then throw an exception.
1888 if (isset($params['categoryid']) && $category->id
== $params['categoryid']) {
1889 $exceptionparam = new stdClass();
1890 $exceptionparam->message
= $e->getMessage();
1891 $exceptionparam->catid
= $category->id
;
1892 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
1896 // Return the category information.
1897 if (!isset($excludedcats[$category->id
])) {
1899 // Final check to see if the category is visible to the user.
1900 if (core_course_category
::can_view_category($category)) {
1902 $categoryinfo = array();
1903 $categoryinfo['id'] = $category->id
;
1904 $categoryinfo['name'] = external_format_string($category->name
, $context);
1905 list($categoryinfo['description'], $categoryinfo['descriptionformat']) =
1906 external_format_text($category->description
, $category->descriptionformat
,
1907 $context->id
, 'coursecat', 'description', null);
1908 $categoryinfo['parent'] = $category->parent
;
1909 $categoryinfo['sortorder'] = $category->sortorder
;
1910 $categoryinfo['coursecount'] = $category->coursecount
;
1911 $categoryinfo['depth'] = $category->depth
;
1912 $categoryinfo['path'] = $category->path
;
1914 // Some fields only returned for admin.
1915 if (has_capability('moodle/category:manage', $context)) {
1916 $categoryinfo['idnumber'] = $category->idnumber
;
1917 $categoryinfo['visible'] = $category->visible
;
1918 $categoryinfo['visibleold'] = $category->visibleold
;
1919 $categoryinfo['timemodified'] = $category->timemodified
;
1920 $categoryinfo['theme'] = clean_param($category->theme
, PARAM_THEME
);
1923 $categoriesinfo[] = $categoryinfo;
1925 $excludedcats[$category->id
] = 'visibility';
1930 // Sorting the resulting array so it looks a bit better for the client developer.
1931 usort($categoriesinfo, "core_course_external::compare_categories_by_sortorder");
1933 return $categoriesinfo;
1937 * Sort categories array by path
1938 * private function: only used by get_categories
1940 * @param array $category1
1941 * @param array $category2
1942 * @return int result of strcmp
1945 private static function compare_categories_by_path($category1, $category2) {
1946 return strcmp($category1->path
, $category2->path
);
1950 * Sort categories array by sortorder
1951 * private function: only used by get_categories
1953 * @param array $category1
1954 * @param array $category2
1955 * @return int result of strcmp
1958 private static function compare_categories_by_sortorder($category1, $category2) {
1959 return strcmp($category1['sortorder'], $category2['sortorder']);
1963 * Returns description of method result value
1965 * @return external_description
1968 public static function get_categories_returns() {
1969 return new external_multiple_structure(
1970 new external_single_structure(
1972 'id' => new external_value(PARAM_INT
, 'category id'),
1973 'name' => new external_value(PARAM_RAW
, 'category name'),
1974 'idnumber' => new external_value(PARAM_RAW
, 'category id number', VALUE_OPTIONAL
),
1975 'description' => new external_value(PARAM_RAW
, 'category description'),
1976 'descriptionformat' => new external_format_value('description'),
1977 'parent' => new external_value(PARAM_INT
, 'parent category id'),
1978 'sortorder' => new external_value(PARAM_INT
, 'category sorting order'),
1979 'coursecount' => new external_value(PARAM_INT
, 'number of courses in this category'),
1980 'visible' => new external_value(PARAM_INT
, '1: available, 0:not available', VALUE_OPTIONAL
),
1981 'visibleold' => new external_value(PARAM_INT
, '1: available, 0:not available', VALUE_OPTIONAL
),
1982 'timemodified' => new external_value(PARAM_INT
, 'timestamp', VALUE_OPTIONAL
),
1983 'depth' => new external_value(PARAM_INT
, 'category depth'),
1984 'path' => new external_value(PARAM_TEXT
, 'category path'),
1985 'theme' => new external_value(PARAM_THEME
, 'category theme', VALUE_OPTIONAL
),
1986 ), 'List of categories'
1992 * Returns description of method parameters
1994 * @return external_function_parameters
1997 public static function create_categories_parameters() {
1998 return new external_function_parameters(
2000 'categories' => new external_multiple_structure(
2001 new external_single_structure(
2003 'name' => new external_value(PARAM_TEXT
, 'new category name'),
2004 'parent' => new external_value(PARAM_INT
,
2005 'the parent category id inside which the new category will be created
2006 - set to 0 for a root category',
2008 'idnumber' => new external_value(PARAM_RAW
,
2009 'the new category idnumber', VALUE_OPTIONAL
),
2010 'description' => new external_value(PARAM_RAW
,
2011 'the new category description', VALUE_OPTIONAL
),
2012 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT
),
2013 'theme' => new external_value(PARAM_THEME
,
2014 'the new category theme. This option must be enabled on moodle',
2026 * @param array $categories - see create_categories_parameters() for the array structure
2027 * @return array - see create_categories_returns() for the array structure
2030 public static function create_categories($categories) {
2033 $params = self
::validate_parameters(self
::create_categories_parameters(),
2034 array('categories' => $categories));
2036 $transaction = $DB->start_delegated_transaction();
2038 $createdcategories = array();
2039 foreach ($params['categories'] as $category) {
2040 if ($category['parent']) {
2041 if (!$DB->record_exists('course_categories', array('id' => $category['parent']))) {
2042 throw new moodle_exception('unknowcategory');
2044 $context = context_coursecat
::instance($category['parent']);
2046 $context = context_system
::instance();
2048 self
::validate_context($context);
2049 require_capability('moodle/category:manage', $context);
2051 // this will validate format and throw an exception if there are errors
2052 external_validate_format($category['descriptionformat']);
2054 $newcategory = core_course_category
::create($category);
2055 $context = context_coursecat
::instance($newcategory->id
);
2057 $createdcategories[] = array(
2058 'id' => $newcategory->id
,
2059 'name' => external_format_string($newcategory->name
, $context),
2063 $transaction->allow_commit();
2065 return $createdcategories;
2069 * Returns description of method parameters
2071 * @return external_function_parameters
2074 public static function create_categories_returns() {
2075 return new external_multiple_structure(
2076 new external_single_structure(
2078 'id' => new external_value(PARAM_INT
, 'new category id'),
2079 'name' => new external_value(PARAM_RAW
, 'new category name'),
2086 * Returns description of method parameters
2088 * @return external_function_parameters
2091 public static function update_categories_parameters() {
2092 return new external_function_parameters(
2094 'categories' => new external_multiple_structure(
2095 new external_single_structure(
2097 'id' => new external_value(PARAM_INT
, 'course id'),
2098 'name' => new external_value(PARAM_TEXT
, 'category name', VALUE_OPTIONAL
),
2099 'idnumber' => new external_value(PARAM_RAW
, 'category id number', VALUE_OPTIONAL
),
2100 'parent' => new external_value(PARAM_INT
, 'parent category id', VALUE_OPTIONAL
),
2101 'description' => new external_value(PARAM_RAW
, 'category description', VALUE_OPTIONAL
),
2102 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT
),
2103 'theme' => new external_value(PARAM_THEME
,
2104 'the category theme. This option must be enabled on moodle', VALUE_OPTIONAL
),
2115 * @param array $categories The list of categories to update
2119 public static function update_categories($categories) {
2122 // Validate parameters.
2123 $params = self
::validate_parameters(self
::update_categories_parameters(), array('categories' => $categories));
2125 $transaction = $DB->start_delegated_transaction();
2127 foreach ($params['categories'] as $cat) {
2128 $category = core_course_category
::get($cat['id']);
2130 $categorycontext = context_coursecat
::instance($cat['id']);
2131 self
::validate_context($categorycontext);
2132 require_capability('moodle/category:manage', $categorycontext);
2134 // this will throw an exception if descriptionformat is not valid
2135 external_validate_format($cat['descriptionformat']);
2137 $category->update($cat);
2140 $transaction->allow_commit();
2144 * Returns description of method result value
2146 * @return external_description
2149 public static function update_categories_returns() {
2154 * Returns description of method parameters
2156 * @return external_function_parameters
2159 public static function delete_categories_parameters() {
2160 return new external_function_parameters(
2162 'categories' => new external_multiple_structure(
2163 new external_single_structure(
2165 'id' => new external_value(PARAM_INT
, 'category id to delete'),
2166 'newparent' => new external_value(PARAM_INT
,
2167 'the parent category to move the contents to, if specified', VALUE_OPTIONAL
),
2168 'recursive' => new external_value(PARAM_BOOL
, '1: recursively delete all contents inside this
2169 category, 0 (default): move contents to newparent or current parent category (except if parent is root)', VALUE_DEFAULT
, 0)
2180 * @param array $categories A list of category ids
2184 public static function delete_categories($categories) {
2186 require_once($CFG->dirroot
. "/course/lib.php");
2188 // Validate parameters.
2189 $params = self
::validate_parameters(self
::delete_categories_parameters(), array('categories' => $categories));
2191 $transaction = $DB->start_delegated_transaction();
2193 foreach ($params['categories'] as $category) {
2194 $deletecat = core_course_category
::get($category['id'], MUST_EXIST
);
2195 $context = context_coursecat
::instance($deletecat->id
);
2196 require_capability('moodle/category:manage', $context);
2197 self
::validate_context($context);
2198 self
::validate_context(get_category_or_system_context($deletecat->parent
));
2200 if ($category['recursive']) {
2201 // If recursive was specified, then we recursively delete the category's contents.
2202 if ($deletecat->can_delete_full()) {
2203 $deletecat->delete_full(false);
2205 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2208 // In this situation, we don't delete the category's contents, we either move it to newparent or parent.
2209 // If the parent is the root, moving is not supported (because a course must always be inside a category).
2210 // We must move to an existing category.
2211 if (!empty($category['newparent'])) {
2212 $newparentcat = core_course_category
::get($category['newparent']);
2214 $newparentcat = core_course_category
::get($deletecat->parent
);
2217 // This operation is not allowed. We must move contents to an existing category.
2218 if (!$newparentcat->id
) {
2219 throw new moodle_exception('movecatcontentstoroot');
2222 self
::validate_context(context_coursecat
::instance($newparentcat->id
));
2223 if ($deletecat->can_move_content_to($newparentcat->id
)) {
2224 $deletecat->delete_move($newparentcat->id
, false);
2226 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2231 $transaction->allow_commit();
2235 * Returns description of method parameters
2237 * @return external_function_parameters
2240 public static function delete_categories_returns() {
2245 * Describes the parameters for delete_modules.
2247 * @return external_function_parameters
2250 public static function delete_modules_parameters() {
2251 return new external_function_parameters (
2253 'cmids' => new external_multiple_structure(new external_value(PARAM_INT
, 'course module ID',
2254 VALUE_REQUIRED
, '', NULL_NOT_ALLOWED
), 'Array of course module IDs'),
2260 * Deletes a list of provided module instances.
2262 * @param array $cmids the course module ids
2265 public static function delete_modules($cmids) {
2268 // Require course file containing the course delete module function.
2269 require_once($CFG->dirroot
. "/course/lib.php");
2271 // Clean the parameters.
2272 $params = self
::validate_parameters(self
::delete_modules_parameters(), array('cmids' => $cmids));
2274 // Keep track of the course ids we have performed a capability check on to avoid repeating.
2275 $arrcourseschecked = array();
2277 foreach ($params['cmids'] as $cmid) {
2278 // Get the course module.
2279 $cm = $DB->get_record('course_modules', array('id' => $cmid), '*', MUST_EXIST
);
2281 // Check if we have not yet confirmed they have permission in this course.
2282 if (!in_array($cm->course
, $arrcourseschecked)) {
2283 // Ensure the current user has required permission in this course.
2284 $context = context_course
::instance($cm->course
);
2285 self
::validate_context($context);
2286 // Add to the array.
2287 $arrcourseschecked[] = $cm->course
;
2290 // Ensure they can delete this module.
2291 $modcontext = context_module
::instance($cm->id
);
2292 require_capability('moodle/course:manageactivities', $modcontext);
2294 // Delete the module.
2295 course_delete_module($cm->id
);
2300 * Describes the delete_modules return value.
2302 * @return external_single_structure
2305 public static function delete_modules_returns() {
2310 * Returns description of method parameters
2312 * @return external_function_parameters
2315 public static function view_course_parameters() {
2316 return new external_function_parameters(
2318 'courseid' => new external_value(PARAM_INT
, 'id of the course'),
2319 'sectionnumber' => new external_value(PARAM_INT
, 'section number', VALUE_DEFAULT
, 0)
2325 * Trigger the course viewed event.
2327 * @param int $courseid id of course
2328 * @param int $sectionnumber sectionnumber (0, 1, 2...)
2329 * @return array of warnings and status result
2331 * @throws moodle_exception
2333 public static function view_course($courseid, $sectionnumber = 0) {
2335 require_once($CFG->dirroot
. "/course/lib.php");
2337 $params = self
::validate_parameters(self
::view_course_parameters(),
2339 'courseid' => $courseid,
2340 'sectionnumber' => $sectionnumber
2343 $warnings = array();
2345 $course = get_course($params['courseid']);
2346 $context = context_course
::instance($course->id
);
2347 self
::validate_context($context);
2349 if (!empty($params['sectionnumber'])) {
2351 // Get section details and check it exists.
2352 $modinfo = get_fast_modinfo($course);
2353 $coursesection = $modinfo->get_section_info($params['sectionnumber'], MUST_EXIST
);
2355 // Check user is allowed to see it.
2356 if (!$coursesection->uservisible
) {
2357 require_capability('moodle/course:viewhiddensections', $context);
2361 course_view($context, $params['sectionnumber']);
2364 $result['status'] = true;
2365 $result['warnings'] = $warnings;
2370 * Returns description of method result value
2372 * @return external_description
2375 public static function view_course_returns() {
2376 return new external_single_structure(
2378 'status' => new external_value(PARAM_BOOL
, 'status: true if success'),
2379 'warnings' => new external_warnings()
2385 * Returns description of method parameters
2387 * @return external_function_parameters
2390 public static function search_courses_parameters() {
2391 return new external_function_parameters(
2393 'criterianame' => new external_value(PARAM_ALPHA
, 'criteria name
2394 (search, modulelist (only admins), blocklist (only admins), tagid)'),
2395 'criteriavalue' => new external_value(PARAM_RAW
, 'criteria value'),
2396 'page' => new external_value(PARAM_INT
, 'page number (0 based)', VALUE_DEFAULT
, 0),
2397 'perpage' => new external_value(PARAM_INT
, 'items per page', VALUE_DEFAULT
, 0),
2398 'requiredcapabilities' => new external_multiple_structure(
2399 new external_value(PARAM_CAPABILITY
, 'Capability string used to filter courses by permission'),
2400 'Optional list of required capabilities (used to filter the list)', VALUE_DEFAULT
, array()
2402 'limittoenrolled' => new external_value(PARAM_BOOL
, 'limit to enrolled courses', VALUE_DEFAULT
, 0),
2403 'onlywithcompletion' => new external_value(PARAM_BOOL
, 'limit to courses where completion is enabled',
2410 * Return the course information that is public (visible by every one)
2412 * @param core_course_list_element $course course in list object
2413 * @param stdClass $coursecontext course context object
2414 * @return array the course information
2417 protected static function get_course_public_information(core_course_list_element
$course, $coursecontext) {
2419 static $categoriescache = array();
2421 // Category information.
2422 if (!array_key_exists($course->category
, $categoriescache)) {
2423 $categoriescache[$course->category
] = core_course_category
::get($course->category
, IGNORE_MISSING
);
2425 $category = $categoriescache[$course->category
];
2427 // Retrieve course overview used files.
2429 foreach ($course->get_course_overviewfiles() as $file) {
2430 $fileurl = moodle_url
::make_webservice_pluginfile_url($file->get_contextid(), $file->get_component(),
2431 $file->get_filearea(), null, $file->get_filepath(),
2432 $file->get_filename())->out(false);
2434 'filename' => $file->get_filename(),
2435 'fileurl' => $fileurl,
2436 'filesize' => $file->get_filesize(),
2437 'filepath' => $file->get_filepath(),
2438 'mimetype' => $file->get_mimetype(),
2439 'timemodified' => $file->get_timemodified(),
2443 // Retrieve the course contacts,
2444 // we need here the users fullname since if we are not enrolled can be difficult to obtain them via other Web Services.
2445 $coursecontacts = array();
2446 foreach ($course->get_course_contacts() as $contact) {
2447 $coursecontacts[] = array(
2448 'id' => $contact['user']->id
,
2449 'fullname' => $contact['username'],
2450 'roles' => array_map(function($role){
2451 return array('id' => $role->id
, 'name' => $role->displayname
);
2452 }, $contact['roles']),
2453 'role' => array('id' => $contact['role']->id
, 'name' => $contact['role']->displayname
),
2454 'rolename' => $contact['rolename']
2458 // Allowed enrolment methods (maybe we can self-enrol).
2459 $enroltypes = array();
2460 $instances = enrol_get_instances($course->id
, true);
2461 foreach ($instances as $instance) {
2462 $enroltypes[] = $instance->enrol
;
2466 list($summary, $summaryformat) =
2467 external_format_text($course->summary
, $course->summaryformat
, $coursecontext->id
, 'course', 'summary', null);
2470 if (!empty($category)) {
2471 $categoryname = external_format_string($category->name
, $category->get_context());
2474 $displayname = get_course_display_name_for_list($course);
2475 $coursereturns = array();
2476 $coursereturns['id'] = $course->id
;
2477 $coursereturns['fullname'] = external_format_string($course->fullname
, $coursecontext->id
);
2478 $coursereturns['displayname'] = external_format_string($displayname, $coursecontext->id
);
2479 $coursereturns['shortname'] = external_format_string($course->shortname
, $coursecontext->id
);
2480 $coursereturns['categoryid'] = $course->category
;
2481 $coursereturns['categoryname'] = $categoryname;
2482 $coursereturns['summary'] = $summary;
2483 $coursereturns['summaryformat'] = $summaryformat;
2484 $coursereturns['summaryfiles'] = external_util
::get_area_files($coursecontext->id
, 'course', 'summary', false, false);
2485 $coursereturns['overviewfiles'] = $files;
2486 $coursereturns['contacts'] = $coursecontacts;
2487 $coursereturns['enrollmentmethods'] = $enroltypes;
2488 $coursereturns['sortorder'] = $course->sortorder
;
2490 $handler = core_course\customfield\course_handler
::create();
2491 if ($customfields = $handler->export_instance_data($course->id
)) {
2492 $coursereturns['customfields'] = [];
2493 foreach ($customfields as $data) {
2494 $coursereturns['customfields'][] = [
2495 'type' => $data->get_type(),
2496 'value' => $data->get_value(),
2497 'name' => $data->get_name(),
2498 'shortname' => $data->get_shortname()
2503 return $coursereturns;
2507 * Search courses following the specified criteria.
2509 * @param string $criterianame Criteria name (search, modulelist (only admins), blocklist (only admins), tagid)
2510 * @param string $criteriavalue Criteria value
2511 * @param int $page Page number (for pagination)
2512 * @param int $perpage Items per page
2513 * @param array $requiredcapabilities Optional list of required capabilities (used to filter the list).
2514 * @param int $limittoenrolled Limit to only enrolled courses
2515 * @param int onlywithcompletion Limit to only courses where completion is enabled
2516 * @return array of course objects and warnings
2518 * @throws moodle_exception
2520 public static function search_courses($criterianame,
2524 $requiredcapabilities=array(),
2526 $onlywithcompletion=0) {
2529 $warnings = array();
2531 $parameters = array(
2532 'criterianame' => $criterianame,
2533 'criteriavalue' => $criteriavalue,
2535 'perpage' => $perpage,
2536 'requiredcapabilities' => $requiredcapabilities,
2537 'limittoenrolled' => $limittoenrolled,
2538 'onlywithcompletion' => $onlywithcompletion
2540 $params = self
::validate_parameters(self
::search_courses_parameters(), $parameters);
2541 self
::validate_context(context_system
::instance());
2543 $allowedcriterianames = array('search', 'modulelist', 'blocklist', 'tagid');
2544 if (!in_array($params['criterianame'], $allowedcriterianames)) {
2545 throw new invalid_parameter_exception('Invalid value for criterianame parameter (value: '.$params['criterianame'].'),' .
2546 'allowed values are: '.implode(',', $allowedcriterianames));
2549 if ($params['criterianame'] == 'modulelist' or $params['criterianame'] == 'blocklist') {
2550 require_capability('moodle/site:config', context_system
::instance());
2554 'search' => PARAM_RAW
,
2555 'modulelist' => PARAM_PLUGIN
,
2556 'blocklist' => PARAM_INT
,
2557 'tagid' => PARAM_INT
2559 $params['criteriavalue'] = clean_param($params['criteriavalue'], $paramtype[$params['criterianame']]);
2561 // Prepare the search API options.
2562 $searchcriteria = array();
2563 $searchcriteria[$params['criterianame']] = $params['criteriavalue'];
2564 if ($params['onlywithcompletion']) {
2565 $searchcriteria['onlywithcompletion'] = true;
2569 if ($params['perpage'] != 0) {
2570 $offset = $params['page'] * $params['perpage'];
2571 $options = array('offset' => $offset, 'limit' => $params['perpage']);
2574 // Search the courses.
2575 $courses = core_course_category
::search_courses($searchcriteria, $options, $params['requiredcapabilities']);
2576 $totalcount = core_course_category
::search_courses_count($searchcriteria, $options, $params['requiredcapabilities']);
2578 if (!empty($limittoenrolled)) {
2579 // Get the courses where the current user has access.
2580 $enrolled = enrol_get_my_courses(array('id', 'cacherev'));
2583 $finalcourses = array();
2584 $categoriescache = array();
2586 foreach ($courses as $course) {
2587 if (!empty($limittoenrolled)) {
2588 // Filter out not enrolled courses.
2589 if (!isset($enrolled[$course->id
])) {
2595 $coursecontext = context_course
::instance($course->id
);
2597 $finalcourses[] = self
::get_course_public_information($course, $coursecontext);
2601 'total' => $totalcount,
2602 'courses' => $finalcourses,
2603 'warnings' => $warnings
2608 * Returns a course structure definition
2610 * @param boolean $onlypublicdata set to true, to retrieve only fields viewable by anyone when the course is visible
2611 * @return array the course structure
2614 protected static function get_course_structure($onlypublicdata = true) {
2615 $coursestructure = array(
2616 'id' => new external_value(PARAM_INT
, 'course id'),
2617 'fullname' => new external_value(PARAM_RAW
, 'course full name'),
2618 'displayname' => new external_value(PARAM_RAW
, 'course display name'),
2619 'shortname' => new external_value(PARAM_RAW
, 'course short name'),
2620 'categoryid' => new external_value(PARAM_INT
, 'category id'),
2621 'categoryname' => new external_value(PARAM_RAW
, 'category name'),
2622 'sortorder' => new external_value(PARAM_INT
, 'Sort order in the category', VALUE_OPTIONAL
),
2623 'summary' => new external_value(PARAM_RAW
, 'summary'),
2624 'summaryformat' => new external_format_value('summary'),
2625 'summaryfiles' => new external_files('summary files in the summary field', VALUE_OPTIONAL
),
2626 'overviewfiles' => new external_files('additional overview files attached to this course'),
2627 'contacts' => new external_multiple_structure(
2628 new external_single_structure(
2630 'id' => new external_value(PARAM_INT
, 'contact user id'),
2631 'fullname' => new external_value(PARAM_NOTAGS
, 'contact user fullname'),
2636 'enrollmentmethods' => new external_multiple_structure(
2637 new external_value(PARAM_PLUGIN
, 'enrollment method'),
2638 'enrollment methods list'
2640 'customfields' => new external_multiple_structure(
2641 new external_single_structure(
2643 'name' => new external_value(PARAM_RAW
, 'The name of the custom field'),
2644 'shortname' => new external_value(PARAM_RAW
,
2645 'The shortname of the custom field - to be able to build the field class in the code'),
2646 'type' => new external_value(PARAM_ALPHANUMEXT
,
2647 'The type of the custom field - text field, checkbox...'),
2648 'value' => new external_value(PARAM_RAW
, 'The value of the custom field'),
2650 ), 'Custom fields', VALUE_OPTIONAL
),
2653 if (!$onlypublicdata) {
2655 'idnumber' => new external_value(PARAM_RAW
, 'Id number', VALUE_OPTIONAL
),
2656 'format' => new external_value(PARAM_PLUGIN
, 'Course format: weeks, topics, social, site,..', VALUE_OPTIONAL
),
2657 'showgrades' => new external_value(PARAM_INT
, '1 if grades are shown, otherwise 0', VALUE_OPTIONAL
),
2658 'newsitems' => new external_value(PARAM_INT
, 'Number of recent items appearing on the course page', VALUE_OPTIONAL
),
2659 'startdate' => new external_value(PARAM_INT
, 'Timestamp when the course start', VALUE_OPTIONAL
),
2660 'enddate' => new external_value(PARAM_INT
, 'Timestamp when the course end', VALUE_OPTIONAL
),
2661 'maxbytes' => new external_value(PARAM_INT
, 'Largest size of file that can be uploaded into', VALUE_OPTIONAL
),
2662 'showreports' => new external_value(PARAM_INT
, 'Are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL
),
2663 'visible' => new external_value(PARAM_INT
, '1: available to student, 0:not available', VALUE_OPTIONAL
),
2664 'groupmode' => new external_value(PARAM_INT
, 'no group, separate, visible', VALUE_OPTIONAL
),
2665 'groupmodeforce' => new external_value(PARAM_INT
, '1: yes, 0: no', VALUE_OPTIONAL
),
2666 'defaultgroupingid' => new external_value(PARAM_INT
, 'default grouping id', VALUE_OPTIONAL
),
2667 'enablecompletion' => new external_value(PARAM_INT
, 'Completion enabled? 1: yes 0: no', VALUE_OPTIONAL
),
2668 'completionnotify' => new external_value(PARAM_INT
, '1: yes 0: no', VALUE_OPTIONAL
),
2669 'lang' => new external_value(PARAM_SAFEDIR
, 'Forced course language', VALUE_OPTIONAL
),
2670 'theme' => new external_value(PARAM_PLUGIN
, 'Fame of the forced theme', VALUE_OPTIONAL
),
2671 'marker' => new external_value(PARAM_INT
, 'Current course marker', VALUE_OPTIONAL
),
2672 'legacyfiles' => new external_value(PARAM_INT
, 'If legacy files are enabled', VALUE_OPTIONAL
),
2673 'calendartype' => new external_value(PARAM_PLUGIN
, 'Calendar type', VALUE_OPTIONAL
),
2674 'timecreated' => new external_value(PARAM_INT
, 'Time when the course was created', VALUE_OPTIONAL
),
2675 'timemodified' => new external_value(PARAM_INT
, 'Last time the course was updated', VALUE_OPTIONAL
),
2676 'requested' => new external_value(PARAM_INT
, 'If is a requested course', VALUE_OPTIONAL
),
2677 'cacherev' => new external_value(PARAM_INT
, 'Cache revision number', VALUE_OPTIONAL
),
2678 'filters' => new external_multiple_structure(
2679 new external_single_structure(
2681 'filter' => new external_value(PARAM_PLUGIN
, 'Filter plugin name'),
2682 'localstate' => new external_value(PARAM_INT
, 'Filter state: 1 for on, -1 for off, 0 if inherit'),
2683 'inheritedstate' => new external_value(PARAM_INT
, '1 or 0 to use when localstate is set to inherit'),
2686 'Course filters', VALUE_OPTIONAL
2688 'courseformatoptions' => new external_multiple_structure(
2689 new external_single_structure(
2691 'name' => new external_value(PARAM_RAW
, 'Course format option name.'),
2692 'value' => new external_value(PARAM_RAW
, 'Course format option value.'),
2695 'Additional options for particular course format.', VALUE_OPTIONAL
2698 $coursestructure = array_merge($coursestructure, $extra);
2700 return new external_single_structure($coursestructure);
2704 * Returns description of method result value
2706 * @return external_description
2709 public static function search_courses_returns() {
2710 return new external_single_structure(
2712 'total' => new external_value(PARAM_INT
, 'total course count'),
2713 'courses' => new external_multiple_structure(self
::get_course_structure(), 'course'),
2714 'warnings' => new external_warnings()
2720 * Returns description of method parameters
2722 * @return external_function_parameters
2725 public static function get_course_module_parameters() {
2726 return new external_function_parameters(
2728 'cmid' => new external_value(PARAM_INT
, 'The course module id')
2734 * Return information about a course module.
2736 * @param int $cmid the course module id
2737 * @return array of warnings and the course module
2739 * @throws moodle_exception
2741 public static function get_course_module($cmid) {
2744 $params = self
::validate_parameters(self
::get_course_module_parameters(), array('cmid' => $cmid));
2745 $warnings = array();
2747 $cm = get_coursemodule_from_id(null, $params['cmid'], 0, true, MUST_EXIST
);
2748 $context = context_module
::instance($cm->id
);
2749 self
::validate_context($context);
2751 // If the user has permissions to manage the activity, return all the information.
2752 if (has_capability('moodle/course:manageactivities', $context)) {
2753 require_once($CFG->dirroot
. '/course/modlib.php');
2754 require_once($CFG->libdir
. '/gradelib.php');
2757 // Get the extra information: grade, advanced grading and outcomes data.
2758 $course = get_course($cm->course
);
2759 list($newcm, $newcontext, $module, $extrainfo, $cw) = get_moduleinfo_data($cm, $course);
2761 $gradeinfo = array('grade', 'gradepass', 'gradecat');
2762 foreach ($gradeinfo as $gfield) {
2763 if (isset($extrainfo->{$gfield})) {
2764 $info->{$gfield} = $extrainfo->{$gfield};
2767 if (isset($extrainfo->grade
) and $extrainfo->grade
< 0) {
2768 $info->scale
= $DB->get_field('scale', 'scale', array('id' => abs($extrainfo->grade
)));
2770 // Advanced grading.
2771 if (isset($extrainfo->_advancedgradingdata
)) {
2772 $info->advancedgrading
= array();
2773 foreach ($extrainfo as $key => $val) {
2774 if (strpos($key, 'advancedgradingmethod_') === 0) {
2775 $info->advancedgrading
[] = array(
2776 'area' => str_replace('advancedgradingmethod_', '', $key),
2783 foreach ($extrainfo as $key => $val) {
2784 if (strpos($key, 'outcome_') === 0) {
2785 if (!isset($info->outcomes
)) {
2786 $info->outcomes
= array();
2788 $id = str_replace('outcome_', '', $key);
2789 $outcome = grade_outcome
::fetch(array('id' => $id));
2790 $scaleitems = $outcome->load_scale();
2791 $info->outcomes
[] = array(
2793 'name' => external_format_string($outcome->get_name(), $context->id
),
2794 'scale' => $scaleitems->scale
2799 // Return information is safe to show to any user.
2800 $info = new stdClass();
2801 $info->id
= $cm->id
;
2802 $info->course
= $cm->course
;
2803 $info->module
= $cm->module
;
2804 $info->modname
= $cm->modname
;
2805 $info->instance
= $cm->instance
;
2806 $info->section
= $cm->section
;
2807 $info->sectionnum
= $cm->sectionnum
;
2808 $info->groupmode
= $cm->groupmode
;
2809 $info->groupingid
= $cm->groupingid
;
2810 $info->completion
= $cm->completion
;
2813 $info->name
= external_format_string($cm->name
, $context->id
);
2815 $result['cm'] = $info;
2816 $result['warnings'] = $warnings;
2821 * Returns description of method result value
2823 * @return external_description
2826 public static function get_course_module_returns() {
2827 return new external_single_structure(
2829 'cm' => new external_single_structure(
2831 'id' => new external_value(PARAM_INT
, 'The course module id'),
2832 'course' => new external_value(PARAM_INT
, 'The course id'),
2833 'module' => new external_value(PARAM_INT
, 'The module type id'),
2834 'name' => new external_value(PARAM_RAW
, 'The activity name'),
2835 'modname' => new external_value(PARAM_COMPONENT
, 'The module component name (forum, assign, etc..)'),
2836 'instance' => new external_value(PARAM_INT
, 'The activity instance id'),
2837 'section' => new external_value(PARAM_INT
, 'The module section id'),
2838 'sectionnum' => new external_value(PARAM_INT
, 'The module section number'),
2839 'groupmode' => new external_value(PARAM_INT
, 'Group mode'),
2840 'groupingid' => new external_value(PARAM_INT
, 'Grouping id'),
2841 'completion' => new external_value(PARAM_INT
, 'If completion is enabled'),
2842 'idnumber' => new external_value(PARAM_RAW
, 'Module id number', VALUE_OPTIONAL
),
2843 'added' => new external_value(PARAM_INT
, 'Time added', VALUE_OPTIONAL
),
2844 'score' => new external_value(PARAM_INT
, 'Score', VALUE_OPTIONAL
),
2845 'indent' => new external_value(PARAM_INT
, 'Indentation', VALUE_OPTIONAL
),
2846 'visible' => new external_value(PARAM_INT
, 'If visible', VALUE_OPTIONAL
),
2847 'visibleoncoursepage' => new external_value(PARAM_INT
, 'If visible on course page', VALUE_OPTIONAL
),
2848 'visibleold' => new external_value(PARAM_INT
, 'Visible old', VALUE_OPTIONAL
),
2849 'completiongradeitemnumber' => new external_value(PARAM_INT
, 'Completion grade item', VALUE_OPTIONAL
),
2850 'completionview' => new external_value(PARAM_INT
, 'Completion view setting', VALUE_OPTIONAL
),
2851 'completionexpected' => new external_value(PARAM_INT
, 'Completion time expected', VALUE_OPTIONAL
),
2852 'showdescription' => new external_value(PARAM_INT
, 'If the description is showed', VALUE_OPTIONAL
),
2853 'availability' => new external_value(PARAM_RAW
, 'Availability settings', VALUE_OPTIONAL
),
2854 'grade' => new external_value(PARAM_FLOAT
, 'Grade (max value or scale id)', VALUE_OPTIONAL
),
2855 'scale' => new external_value(PARAM_TEXT
, 'Scale items (if used)', VALUE_OPTIONAL
),
2856 'gradepass' => new external_value(PARAM_RAW
, 'Grade to pass (float)', VALUE_OPTIONAL
),
2857 'gradecat' => new external_value(PARAM_INT
, 'Grade category', VALUE_OPTIONAL
),
2858 'advancedgrading' => new external_multiple_structure(
2859 new external_single_structure(
2861 'area' => new external_value(PARAM_AREA
, 'Gradable area name'),
2862 'method' => new external_value(PARAM_COMPONENT
, 'Grading method'),
2865 'Advanced grading settings', VALUE_OPTIONAL
2867 'outcomes' => new external_multiple_structure(
2868 new external_single_structure(
2870 'id' => new external_value(PARAM_ALPHANUMEXT
, 'Outcome id'),
2871 'name' => new external_value(PARAM_RAW
, 'Outcome full name'),
2872 'scale' => new external_value(PARAM_TEXT
, 'Scale items')
2875 'Outcomes information', VALUE_OPTIONAL
2879 'warnings' => new external_warnings()
2885 * Returns description of method parameters
2887 * @return external_function_parameters
2890 public static function get_course_module_by_instance_parameters() {
2891 return new external_function_parameters(
2893 'module' => new external_value(PARAM_COMPONENT
, 'The module name'),
2894 'instance' => new external_value(PARAM_INT
, 'The module instance id')
2900 * Return information about a course module.
2902 * @param string $module the module name
2903 * @param int $instance the activity instance id
2904 * @return array of warnings and the course module
2906 * @throws moodle_exception
2908 public static function get_course_module_by_instance($module, $instance) {
2910 $params = self
::validate_parameters(self
::get_course_module_by_instance_parameters(),
2912 'module' => $module,
2913 'instance' => $instance,
2916 $warnings = array();
2917 $cm = get_coursemodule_from_instance($params['module'], $params['instance'], 0, false, MUST_EXIST
);
2919 return self
::get_course_module($cm->id
);
2923 * Returns description of method result value
2925 * @return external_description
2928 public static function get_course_module_by_instance_returns() {
2929 return self
::get_course_module_returns();
2933 * Returns description of method parameters
2935 * @return external_function_parameters
2938 public static function get_user_navigation_options_parameters() {
2939 return new external_function_parameters(
2941 'courseids' => new external_multiple_structure(new external_value(PARAM_INT
, 'Course id.')),
2947 * Return a list of navigation options in a set of courses that are avaialable or not for the current user.
2949 * @param array $courseids a list of course ids
2950 * @return array of warnings and the options availability
2952 * @throws moodle_exception
2954 public static function get_user_navigation_options($courseids) {
2956 require_once($CFG->dirroot
. '/course/lib.php');
2958 // Parameter validation.
2959 $params = self
::validate_parameters(self
::get_user_navigation_options_parameters(), array('courseids' => $courseids));
2960 $courseoptions = array();
2962 list($courses, $warnings) = external_util
::validate_courses($params['courseids'], array(), true);
2964 if (!empty($courses)) {
2965 foreach ($courses as $course) {
2966 // Fix the context for the frontpage.
2967 if ($course->id
== SITEID
) {
2968 $course->context
= context_system
::instance();
2970 $navoptions = course_get_user_navigation_options($course->context
, $course);
2972 foreach ($navoptions as $name => $available) {
2975 'available' => $available,
2979 $courseoptions[] = array(
2980 'id' => $course->id
,
2981 'options' => $options
2987 'courses' => $courseoptions,
2988 'warnings' => $warnings
2994 * Returns description of method result value
2996 * @return external_description
2999 public static function get_user_navigation_options_returns() {
3000 return new external_single_structure(
3002 'courses' => new external_multiple_structure(
3003 new external_single_structure(
3005 'id' => new external_value(PARAM_INT
, 'Course id'),
3006 'options' => new external_multiple_structure(
3007 new external_single_structure(
3009 'name' => new external_value(PARAM_ALPHANUMEXT
, 'Option name'),
3010 'available' => new external_value(PARAM_BOOL
, 'Whether the option is available or not'),
3015 ), 'List of courses'
3017 'warnings' => new external_warnings()
3023 * Returns description of method parameters
3025 * @return external_function_parameters
3028 public static function get_user_administration_options_parameters() {
3029 return new external_function_parameters(
3031 'courseids' => new external_multiple_structure(new external_value(PARAM_INT
, 'Course id.')),
3037 * Return a list of administration options in a set of courses that are available or not for the current user.
3039 * @param array $courseids a list of course ids
3040 * @return array of warnings and the options availability
3042 * @throws moodle_exception
3044 public static function get_user_administration_options($courseids) {
3046 require_once($CFG->dirroot
. '/course/lib.php');
3048 // Parameter validation.
3049 $params = self
::validate_parameters(self
::get_user_administration_options_parameters(), array('courseids' => $courseids));
3050 $courseoptions = array();
3052 list($courses, $warnings) = external_util
::validate_courses($params['courseids'], array(), true);
3054 if (!empty($courses)) {
3055 foreach ($courses as $course) {
3056 $adminoptions = course_get_user_administration_options($course, $course->context
);
3058 foreach ($adminoptions as $name => $available) {
3061 'available' => $available,
3065 $courseoptions[] = array(
3066 'id' => $course->id
,
3067 'options' => $options
3073 'courses' => $courseoptions,
3074 'warnings' => $warnings
3080 * Returns description of method result value
3082 * @return external_description
3085 public static function get_user_administration_options_returns() {
3086 return self
::get_user_navigation_options_returns();
3090 * Returns description of method parameters
3092 * @return external_function_parameters
3095 public static function get_courses_by_field_parameters() {
3096 return new external_function_parameters(
3098 'field' => new external_value(PARAM_ALPHA
, 'The field to search can be left empty for all courses or:
3100 ids: comma separated course ids
3101 shortname: course short name
3102 idnumber: course id number
3103 category: category id the course belongs to
3104 ', VALUE_DEFAULT
, ''),
3105 'value' => new external_value(PARAM_RAW
, 'The value to match', VALUE_DEFAULT
, '')
3112 * Get courses matching a specific field (id/s, shortname, idnumber, category)
3114 * @param string $field field name to search, or empty for all courses
3115 * @param string $value value to search
3116 * @return array list of courses and warnings
3117 * @throws invalid_parameter_exception
3120 public static function get_courses_by_field($field = '', $value = '') {
3122 require_once($CFG->dirroot
. '/course/lib.php');
3123 require_once($CFG->libdir
. '/filterlib.php');
3125 $params = self
::validate_parameters(self
::get_courses_by_field_parameters(),
3131 $warnings = array();
3133 if (empty($params['field'])) {
3134 $courses = $DB->get_records('course', null, 'id ASC');
3136 switch ($params['field']) {
3139 $value = clean_param($params['value'], PARAM_INT
);
3142 $value = clean_param($params['value'], PARAM_SEQUENCE
);
3145 $value = clean_param($params['value'], PARAM_TEXT
);
3148 $value = clean_param($params['value'], PARAM_RAW
);
3151 throw new invalid_parameter_exception('Invalid field name');
3154 if ($params['field'] === 'ids') {
3155 // Preload categories to avoid loading one at a time.
3156 $courseids = explode(',', $value);
3157 list ($listsql, $listparams) = $DB->get_in_or_equal($courseids);
3158 $categoryids = $DB->get_fieldset_sql("
3159 SELECT DISTINCT cc.id
3161 JOIN {course_categories} cc ON cc.id = c.category
3162 WHERE c.id $listsql", $listparams);
3163 core_course_category
::get_many($categoryids);
3165 // Load and validate all courses. This is called because it loads the courses
3166 // more efficiently.
3167 list ($courses, $warnings) = external_util
::validate_courses($courseids, [],
3170 $courses = $DB->get_records('course', array($params['field'] => $value), 'id ASC');
3174 $coursesdata = array();
3175 foreach ($courses as $course) {
3176 $context = context_course
::instance($course->id
);
3177 $canupdatecourse = has_capability('moodle/course:update', $context);
3178 $canviewhiddencourses = has_capability('moodle/course:viewhiddencourses', $context);
3180 // Check if the course is visible in the site for the user.
3181 if (!$course->visible
and !$canviewhiddencourses and !$canupdatecourse) {
3184 // Get the public course information, even if we are not enrolled.
3185 $courseinlist = new core_course_list_element($course);
3187 // Now, check if we have access to the course, unless it was already checked.
3189 if (empty($course->contextvalidated
)) {
3190 self
::validate_context($context);
3192 } catch (Exception
$e) {
3193 // User can not access the course, check if they can see the public information about the course and return it.
3194 if (core_course_category
::can_view_course_info($course)) {
3195 $coursesdata[$course->id
] = self
::get_course_public_information($courseinlist, $context);
3199 $coursesdata[$course->id
] = self
::get_course_public_information($courseinlist, $context);
3200 // Return information for any user that can access the course.
3201 $coursefields = array('format', 'showgrades', 'newsitems', 'startdate', 'enddate', 'maxbytes', 'showreports', 'visible',
3202 'groupmode', 'groupmodeforce', 'defaultgroupingid', 'enablecompletion', 'completionnotify', 'lang', 'theme',
3206 $coursesdata[$course->id
]['filters'] = filter_get_available_in_context($context);
3208 // Information for managers only.
3209 if ($canupdatecourse) {
3210 $managerfields = array('idnumber', 'legacyfiles', 'calendartype', 'timecreated', 'timemodified', 'requested',
3212 $coursefields = array_merge($coursefields, $managerfields);
3216 foreach ($coursefields as $field) {
3217 $coursesdata[$course->id
][$field] = $course->{$field};
3220 // Clean lang and auth fields for external functions (it may content uninstalled themes or language packs).
3221 if (isset($coursesdata[$course->id
]['theme'])) {
3222 $coursesdata[$course->id
]['theme'] = clean_param($coursesdata[$course->id
]['theme'], PARAM_THEME
);
3224 if (isset($coursesdata[$course->id
]['lang'])) {
3225 $coursesdata[$course->id
]['lang'] = clean_param($coursesdata[$course->id
]['lang'], PARAM_LANG
);
3228 $courseformatoptions = course_get_format($course)->get_config_for_external();
3229 foreach ($courseformatoptions as $key => $value) {
3230 $coursesdata[$course->id
]['courseformatoptions'][] = array(
3238 'courses' => $coursesdata,
3239 'warnings' => $warnings
3244 * Returns description of method result value
3246 * @return external_description
3249 public static function get_courses_by_field_returns() {
3250 // Course structure, including not only public viewable fields.
3251 return new external_single_structure(
3253 'courses' => new external_multiple_structure(self
::get_course_structure(false), 'Course'),
3254 'warnings' => new external_warnings()
3260 * Returns description of method parameters
3262 * @return external_function_parameters
3265 public static function check_updates_parameters() {
3266 return new external_function_parameters(
3268 'courseid' => new external_value(PARAM_INT
, 'Course id to check'),
3269 'tocheck' => new external_multiple_structure(
3270 new external_single_structure(
3272 'contextlevel' => new external_value(PARAM_ALPHA
, 'The context level for the file location.
3273 Only module supported right now.'),
3274 'id' => new external_value(PARAM_INT
, 'Context instance id'),
3275 'since' => new external_value(PARAM_INT
, 'Check updates since this time stamp'),
3278 'Instances to check'
3280 'filter' => new external_multiple_structure(
3281 new external_value(PARAM_ALPHANUM
, 'Area name: configuration, fileareas, completion, ratings, comments,
3282 gradeitems, outcomes'),
3283 'Check only for updates in these areas', VALUE_DEFAULT
, array()
3290 * Check if there is updates affecting the user for the given course and contexts.
3291 * Right now only modules are supported.
3292 * This WS calls mod_check_updates_since for each module to check if there is any update the user should we aware of.
3294 * @param int $courseid the list of modules to check
3295 * @param array $tocheck the list of modules to check
3296 * @param array $filter check only for updates in these areas
3297 * @return array list of updates and warnings
3298 * @throws moodle_exception
3301 public static function check_updates($courseid, $tocheck, $filter = array()) {
3303 require_once($CFG->dirroot
. "/course/lib.php");
3305 $params = self
::validate_parameters(
3306 self
::check_updates_parameters(),
3308 'courseid' => $courseid,
3309 'tocheck' => $tocheck,
3310 'filter' => $filter,
3314 $course = get_course($params['courseid']);
3315 $context = context_course
::instance($course->id
);
3316 self
::validate_context($context);
3318 list($instances, $warnings) = course_check_updates($course, $params['tocheck'], $filter);
3320 $instancesformatted = array();
3321 foreach ($instances as $instance) {
3323 foreach ($instance['updates'] as $name => $data) {
3324 if (empty($data->updated
)) {
3327 $updatedata = array(
3330 if (!empty($data->timeupdated
)) {
3331 $updatedata['timeupdated'] = $data->timeupdated
;
3333 if (!empty($data->itemids
)) {
3334 $updatedata['itemids'] = $data->itemids
;
3336 $updates[] = $updatedata;
3338 if (!empty($updates)) {
3339 $instancesformatted[] = array(
3340 'contextlevel' => $instance['contextlevel'],
3341 'id' => $instance['id'],
3342 'updates' => $updates
3348 'instances' => $instancesformatted,
3349 'warnings' => $warnings
3354 * Returns description of method result value
3356 * @return external_description
3359 public static function check_updates_returns() {
3360 return new external_single_structure(
3362 'instances' => new external_multiple_structure(
3363 new external_single_structure(
3365 'contextlevel' => new external_value(PARAM_ALPHA
, 'The context level'),
3366 'id' => new external_value(PARAM_INT
, 'Instance id'),
3367 'updates' => new external_multiple_structure(
3368 new external_single_structure(
3370 'name' => new external_value(PARAM_ALPHANUMEXT
, 'Name of the area updated.'),
3371 'timeupdated' => new external_value(PARAM_INT
, 'Last time was updated', VALUE_OPTIONAL
),
3372 'itemids' => new external_multiple_structure(
3373 new external_value(PARAM_INT
, 'Instance id'),
3374 'The ids of the items updated',
3383 'warnings' => new external_warnings()
3389 * Returns description of method parameters
3391 * @return external_function_parameters
3394 public static function get_updates_since_parameters() {
3395 return new external_function_parameters(
3397 'courseid' => new external_value(PARAM_INT
, 'Course id to check'),
3398 'since' => new external_value(PARAM_INT
, 'Check updates since this time stamp'),
3399 'filter' => new external_multiple_structure(
3400 new external_value(PARAM_ALPHANUM
, 'Area name: configuration, fileareas, completion, ratings, comments,
3401 gradeitems, outcomes'),
3402 'Check only for updates in these areas', VALUE_DEFAULT
, array()
3409 * Check if there are updates affecting the user for the given course since the given time stamp.
3411 * This function is a wrapper of self::check_updates for retrieving all the updates since a given time for all the activities.
3413 * @param int $courseid the list of modules to check
3414 * @param int $since check updates since this time stamp
3415 * @param array $filter check only for updates in these areas
3416 * @return array list of updates and warnings
3417 * @throws moodle_exception
3420 public static function get_updates_since($courseid, $since, $filter = array()) {
3423 $params = self
::validate_parameters(
3424 self
::get_updates_since_parameters(),
3426 'courseid' => $courseid,
3428 'filter' => $filter,
3432 $course = get_course($params['courseid']);
3433 $modinfo = get_fast_modinfo($course);
3436 // Retrieve all the visible course modules for the current user.
3437 $cms = $modinfo->get_cms();
3438 foreach ($cms as $cm) {
3439 if (!$cm->uservisible
) {
3444 'contextlevel' => 'module',
3445 'since' => $params['since'],
3449 return self
::check_updates($course->id
, $tocheck, $params['filter']);
3453 * Returns description of method result value
3455 * @return external_description
3458 public static function get_updates_since_returns() {
3459 return self
::check_updates_returns();
3463 * Parameters for function edit_module()
3466 * @return external_function_parameters
3468 public static function edit_module_parameters() {
3469 return new external_function_parameters(
3471 'action' => new external_value(PARAM_ALPHA
,
3472 'action: hide, show, stealth, duplicate, delete, moveleft, moveright, group...', VALUE_REQUIRED
),
3473 'id' => new external_value(PARAM_INT
, 'course module id', VALUE_REQUIRED
),
3474 'sectionreturn' => new external_value(PARAM_INT
, 'section to return to', VALUE_DEFAULT
, null),
3479 * Performs one of the edit module actions and return new html for AJAX
3481 * Returns html to replace the current module html with, for example:
3482 * - empty string for "delete" action,
3483 * - two modules html for "duplicate" action
3484 * - updated module html for everything else
3486 * Throws exception if operation is not permitted/possible
3489 * @param string $action
3491 * @param null|int $sectionreturn
3494 public static function edit_module($action, $id, $sectionreturn = null) {
3496 // Validate and normalize parameters.
3497 $params = self
::validate_parameters(self
::edit_module_parameters(),
3498 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3499 $action = $params['action'];
3500 $id = $params['id'];
3501 $sectionreturn = $params['sectionreturn'];
3503 // Set of permissions an editing user may have.
3505 'moodle/course:update',
3506 'moodle/course:manageactivities',
3507 'moodle/course:activityvisibility',
3508 'moodle/course:sectionvisibility',
3509 'moodle/course:movesections',
3510 'moodle/course:setcurrentsection',
3512 $PAGE->set_other_editing_capability($contextarray);
3514 list($course, $cm) = get_course_and_cm_from_cmid($id);
3515 $modcontext = context_module
::instance($cm->id
);
3516 $coursecontext = context_course
::instance($course->id
);
3517 self
::validate_context($modcontext);
3518 $courserenderer = $PAGE->get_renderer('core', 'course');
3519 $completioninfo = new completion_info($course);
3525 require_capability('moodle/course:activityvisibility', $modcontext);
3526 $visible = ($action === 'hide') ?
0 : 1;
3527 $visibleoncoursepage = ($action === 'stealth') ?
0 : 1;
3528 set_coursemodule_visible($id, $visible, $visibleoncoursepage);
3529 \core\event\course_module_updated
::create_from_cm($cm, $modcontext)->trigger();
3532 require_capability('moodle/course:manageactivities', $coursecontext);
3533 require_capability('moodle/backup:backuptargetimport', $coursecontext);
3534 require_capability('moodle/restore:restoretargetimport', $coursecontext);
3535 if (!course_allowed_module($course, $cm->modname
)) {
3536 throw new moodle_exception('No permission to create that activity');
3538 if ($newcm = duplicate_module($course, $cm)) {
3539 $cm = get_fast_modinfo($course)->get_cm($id);
3540 $newcm = get_fast_modinfo($course)->get_cm($newcm->id
);
3541 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn) .
3542 $courserenderer->course_section_cm_list_item($course, $completioninfo, $newcm, $sectionreturn);
3545 case 'groupsseparate':
3546 case 'groupsvisible':
3548 require_capability('moodle/course:manageactivities', $modcontext);
3549 if ($action === 'groupsseparate') {
3550 $newgroupmode = SEPARATEGROUPS
;
3551 } else if ($action === 'groupsvisible') {
3552 $newgroupmode = VISIBLEGROUPS
;
3554 $newgroupmode = NOGROUPS
;
3556 if (set_coursemodule_groupmode($cm->id
, $newgroupmode)) {
3557 \core\event\course_module_updated
::create_from_cm($cm, $modcontext)->trigger();
3562 require_capability('moodle/course:manageactivities', $modcontext);
3563 $indent = $cm->indent +
(($action === 'moveright') ?
1 : -1);
3564 if ($cm->indent
>= 0) {
3565 $DB->update_record('course_modules', array('id' => $cm->id
, 'indent' => $indent));
3566 rebuild_course_cache($cm->course
);
3570 require_capability('moodle/course:manageactivities', $modcontext);
3571 course_delete_module($cm->id
, true);
3574 throw new coding_exception('Unrecognised action');
3577 $cm = get_fast_modinfo($course)->get_cm($id);
3578 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn);
3582 * Return structure for edit_module()
3585 * @return external_description
3587 public static function edit_module_returns() {
3588 return new external_value(PARAM_RAW
, 'html to replace the current module with');
3592 * Parameters for function get_module()
3595 * @return external_function_parameters
3597 public static function get_module_parameters() {
3598 return new external_function_parameters(
3600 'id' => new external_value(PARAM_INT
, 'course module id', VALUE_REQUIRED
),
3601 'sectionreturn' => new external_value(PARAM_INT
, 'section to return to', VALUE_DEFAULT
, null),
3606 * Returns html for displaying one activity module on course page
3610 * @param null|int $sectionreturn
3613 public static function get_module($id, $sectionreturn = null) {
3615 // Validate and normalize parameters.
3616 $params = self
::validate_parameters(self
::get_module_parameters(),
3617 array('id' => $id, 'sectionreturn' => $sectionreturn));
3618 $id = $params['id'];
3619 $sectionreturn = $params['sectionreturn'];
3621 // Set of permissions an editing user may have.
3623 'moodle/course:update',
3624 'moodle/course:manageactivities',
3625 'moodle/course:activityvisibility',
3626 'moodle/course:sectionvisibility',
3627 'moodle/course:movesections',
3628 'moodle/course:setcurrentsection',
3630 $PAGE->set_other_editing_capability($contextarray);
3632 // Validate access to the course (note, this is html for the course view page, we don't validate access to the module).
3633 list($course, $cm) = get_course_and_cm_from_cmid($id);
3634 self
::validate_context(context_course
::instance($course->id
));
3636 $courserenderer = $PAGE->get_renderer('core', 'course');
3637 $completioninfo = new completion_info($course);
3638 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn);
3642 * Return structure for get_module()
3645 * @return external_description
3647 public static function get_module_returns() {
3648 return new external_value(PARAM_RAW
, 'html to replace the current module with');
3652 * Parameters for function edit_section()
3655 * @return external_function_parameters
3657 public static function edit_section_parameters() {
3658 return new external_function_parameters(
3660 'action' => new external_value(PARAM_ALPHA
, 'action: hide, show, stealth, setmarker, removemarker', VALUE_REQUIRED
),
3661 'id' => new external_value(PARAM_INT
, 'course section id', VALUE_REQUIRED
),
3662 'sectionreturn' => new external_value(PARAM_INT
, 'section to return to', VALUE_DEFAULT
, null),
3667 * Performs one of the edit section actions
3670 * @param string $action
3671 * @param int $id section id
3672 * @param int $sectionreturn section to return to
3675 public static function edit_section($action, $id, $sectionreturn) {
3677 // Validate and normalize parameters.
3678 $params = self
::validate_parameters(self
::edit_section_parameters(),
3679 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3680 $action = $params['action'];
3681 $id = $params['id'];
3682 $sr = $params['sectionreturn'];
3684 $section = $DB->get_record('course_sections', array('id' => $id), '*', MUST_EXIST
);
3685 $coursecontext = context_course
::instance($section->course
);
3686 self
::validate_context($coursecontext);
3688 $rv = course_get_format($section->course
)->section_action($section, $action, $sectionreturn);
3690 return json_encode($rv);
3697 * Return structure for edit_section()
3700 * @return external_description
3702 public static function edit_section_returns() {
3703 return new external_value(PARAM_RAW
, 'Additional data for javascript (JSON-encoded string)');
3707 * Returns description of method parameters
3709 * @return external_function_parameters
3711 public static function get_enrolled_courses_by_timeline_classification_parameters() {
3712 return new external_function_parameters(
3714 'classification' => new external_value(PARAM_ALPHA
, 'future, inprogress, or past'),
3715 'limit' => new external_value(PARAM_INT
, 'Result set limit', VALUE_DEFAULT
, 0),
3716 'offset' => new external_value(PARAM_INT
, 'Result set offset', VALUE_DEFAULT
, 0),
3717 'sort' => new external_value(PARAM_TEXT
, 'Sort string', VALUE_DEFAULT
, null),
3718 'customfieldname' => new external_value(PARAM_ALPHANUMEXT
, 'Used when classification = customfield',
3719 VALUE_DEFAULT
, null),
3720 'customfieldvalue' => new external_value(PARAM_RAW
, 'Used when classification = customfield',
3721 VALUE_DEFAULT
, null),
3727 * Get courses matching the given timeline classification.
3729 * NOTE: The offset applies to the unfiltered full set of courses before the classification
3730 * filtering is done.
3732 * If the user is enrolled in 5 courses:
3733 * c1, c2, c3, c4, and c5
3734 * And c4 and c5 are 'future' courses
3736 * If a request comes in for future courses with an offset of 1 it will mean that
3737 * c1 is skipped (because the offset applies *before* the classification filtering)
3738 * and c4 and c5 will be return.
3740 * @param string $classification past, inprogress, or future
3741 * @param int $limit Result set limit
3742 * @param int $offset Offset the full course set before timeline classification is applied
3743 * @param string $sort SQL sort string for results
3744 * @param string $customfieldname
3745 * @param string $customfieldvalue
3746 * @return array list of courses and warnings
3747 * @throws invalid_parameter_exception
3749 public static function get_enrolled_courses_by_timeline_classification(
3750 string $classification,
3753 string $sort = null,
3754 string $customfieldname = null,
3755 string $customfieldvalue = null
3757 global $CFG, $PAGE, $USER;
3758 require_once($CFG->dirroot
. '/course/lib.php');
3760 $params = self
::validate_parameters(self
::get_enrolled_courses_by_timeline_classification_parameters(),
3762 'classification' => $classification,
3764 'offset' => $offset,
3766 'customfieldvalue' => $customfieldvalue,
3770 $classification = $params['classification'];
3771 $limit = $params['limit'];
3772 $offset = $params['offset'];
3773 $sort = $params['sort'];
3774 $customfieldvalue = $params['customfieldvalue'];
3776 switch($classification) {
3777 case COURSE_TIMELINE_ALLINCLUDINGHIDDEN
:
3779 case COURSE_TIMELINE_ALL
:
3781 case COURSE_TIMELINE_PAST
:
3783 case COURSE_TIMELINE_INPROGRESS
:
3785 case COURSE_TIMELINE_FUTURE
:
3787 case COURSE_FAVOURITES
:
3789 case COURSE_TIMELINE_HIDDEN
:
3791 case COURSE_CUSTOMFIELD
:
3794 throw new invalid_parameter_exception('Invalid classification');
3797 self
::validate_context(context_user
::instance($USER->id
));
3799 $requiredproperties = course_summary_exporter
::define_properties();
3800 $fields = join(',', array_keys($requiredproperties));
3801 $hiddencourses = get_hidden_courses_on_timeline();
3804 // If the timeline requires really all courses, get really all courses.
3805 if ($classification == COURSE_TIMELINE_ALLINCLUDINGHIDDEN
) {
3806 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields, COURSE_DB_QUERY_LIMIT
);
3808 // Otherwise if the timeline requires the hidden courses then restrict the result to only $hiddencourses.
3809 } else if ($classification == COURSE_TIMELINE_HIDDEN
) {
3810 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields,
3811 COURSE_DB_QUERY_LIMIT
, $hiddencourses);
3813 // Otherwise get the requested courses and exclude the hidden courses.
3815 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields,
3816 COURSE_DB_QUERY_LIMIT
, [], $hiddencourses);
3819 $favouritecourseids = [];
3820 $ufservice = \core_favourites\service_factory
::get_service_for_user_context(\context_user
::instance($USER->id
));
3821 $favourites = $ufservice->find_favourites_by_type('core_course', 'courses');
3824 $favouritecourseids = array_map(
3825 function($favourite) {
3826 return $favourite->itemid
;
3830 if ($classification == COURSE_FAVOURITES
) {
3831 list($filteredcourses, $processedcount) = course_filter_courses_by_favourites(
3833 $favouritecourseids,
3836 } else if ($classification == COURSE_CUSTOMFIELD
) {
3837 list($filteredcourses, $processedcount) = course_filter_courses_by_customfield(
3844 list($filteredcourses, $processedcount) = course_filter_courses_by_timeline_classification(
3851 $renderer = $PAGE->get_renderer('core');
3852 $formattedcourses = array_map(function($course) use ($renderer, $favouritecourseids) {
3853 context_helper
::preload_from_record($course);
3854 $context = context_course
::instance($course->id
);
3855 $isfavourite = false;
3856 if (in_array($course->id
, $favouritecourseids)) {
3857 $isfavourite = true;
3859 $exporter = new course_summary_exporter($course, ['context' => $context, 'isfavourite' => $isfavourite]);
3860 return $exporter->export($renderer);
3861 }, $filteredcourses);
3864 'courses' => $formattedcourses,
3865 'nextoffset' => $offset +
$processedcount
3870 * Returns description of method result value
3872 * @return external_description
3874 public static function get_enrolled_courses_by_timeline_classification_returns() {
3875 return new external_single_structure(
3877 'courses' => new external_multiple_structure(course_summary_exporter
::get_read_structure(), 'Course'),
3878 'nextoffset' => new external_value(PARAM_INT
, 'Offset for the next request')
3884 * Returns description of method parameters
3886 * @return external_function_parameters
3888 public static function set_favourite_courses_parameters() {
3889 return new external_function_parameters(
3891 'courses' => new external_multiple_structure(
3892 new external_single_structure(
3894 'id' => new external_value(PARAM_INT
, 'course ID'),
3895 'favourite' => new external_value(PARAM_BOOL
, 'favourite status')
3904 * Set the course favourite status for an array of courses.
3906 * @param array $courses List with course id's and favourite status.
3907 * @return array Array with an array of favourite courses.
3909 public static function set_favourite_courses(
3914 $params = self
::validate_parameters(self
::set_favourite_courses_parameters(),
3916 'courses' => $courses
3922 $ufservice = \core_favourites\service_factory
::get_service_for_user_context(\context_user
::instance($USER->id
));
3924 foreach ($params['courses'] as $course) {
3928 $favouriteexists = $ufservice->favourite_exists('core_course', 'courses', $course['id'],
3929 \context_course
::instance($course['id']));
3931 if ($course['favourite']) {
3932 if (!$favouriteexists) {
3934 $ufservice->create_favourite('core_course', 'courses', $course['id'],
3935 \context_course
::instance($course['id']));
3936 } catch (Exception
$e) {
3937 $warning['courseid'] = $course['id'];
3938 if ($e instanceof moodle_exception
) {
3939 $warning['warningcode'] = $e->errorcode
;
3941 $warning['warningcode'] = $e->getCode();
3943 $warning['message'] = $e->getMessage();
3944 $warnings[] = $warning;
3945 $warnings[] = $warning;
3948 $warning['courseid'] = $course['id'];
3949 $warning['warningcode'] = 'coursealreadyfavourited';
3950 $warning['message'] = 'Course already favourited';
3951 $warnings[] = $warning;
3954 if ($favouriteexists) {
3956 $ufservice->delete_favourite('core_course', 'courses', $course['id'],
3957 \context_course
::instance($course['id']));
3958 } catch (Exception
$e) {
3959 $warning['courseid'] = $course['id'];
3960 if ($e instanceof moodle_exception
) {
3961 $warning['warningcode'] = $e->errorcode
;
3963 $warning['warningcode'] = $e->getCode();
3965 $warning['message'] = $e->getMessage();
3966 $warnings[] = $warning;
3967 $warnings[] = $warning;
3970 $warning['courseid'] = $course['id'];
3971 $warning['warningcode'] = 'cannotdeletefavourite';
3972 $warning['message'] = 'Could not delete favourite status for course';
3973 $warnings[] = $warning;
3979 'warnings' => $warnings
3984 * Returns description of method result value
3986 * @return external_description
3988 public static function set_favourite_courses_returns() {
3989 return new external_single_structure(
3991 'warnings' => new external_warnings()
3997 * Returns description of method parameters
3999 * @return external_function_parameters
4002 public static function get_recent_courses_parameters() {
4003 return new external_function_parameters(
4005 'userid' => new external_value(PARAM_INT
, 'id of the user, default to current user', VALUE_DEFAULT
, 0),
4006 'limit' => new external_value(PARAM_INT
, 'result set limit', VALUE_DEFAULT
, 0),
4007 'offset' => new external_value(PARAM_INT
, 'Result set offset', VALUE_DEFAULT
, 0),
4008 'sort' => new external_value(PARAM_TEXT
, 'Sort string', VALUE_DEFAULT
, null)
4014 * Get last accessed courses adding additional course information like images.
4016 * @param int $userid User id from which the courses will be obtained
4017 * @param int $limit Restrict result set to this amount
4018 * @param int $offset Skip this number of records from the start of the result set
4019 * @param string|null $sort SQL string for sorting
4020 * @return array List of courses
4021 * @throws invalid_parameter_exception
4023 public static function get_recent_courses(int $userid = 0, int $limit = 0, int $offset = 0, string $sort = null) {
4024 global $USER, $PAGE;
4026 if (empty($userid)) {
4027 $userid = $USER->id
;
4030 $params = self
::validate_parameters(self
::get_recent_courses_parameters(),
4032 'userid' => $userid,
4034 'offset' => $offset,
4039 $userid = $params['userid'];
4040 $limit = $params['limit'];
4041 $offset = $params['offset'];
4042 $sort = $params['sort'];
4044 $usercontext = context_user
::instance($userid);
4046 self
::validate_context($usercontext);
4048 if ($userid != $USER->id
and !has_capability('moodle/user:viewdetails', $usercontext)) {
4052 $courses = course_get_recent_courses($userid, $limit, $offset, $sort);
4054 $renderer = $PAGE->get_renderer('core');
4056 $recentcourses = array_map(function($course) use ($renderer) {
4057 context_helper
::preload_from_record($course);
4058 $context = context_course
::instance($course->id
);
4059 $isfavourite = !empty($course->component
);
4060 $exporter = new course_summary_exporter($course, ['context' => $context, 'isfavourite' => $isfavourite]);
4061 return $exporter->export($renderer);
4064 return $recentcourses;
4068 * Returns description of method result value
4070 * @return external_description
4073 public static function get_recent_courses_returns() {
4074 return new external_multiple_structure(course_summary_exporter
::get_read_structure(), 'Courses');
4078 * Returns description of method parameters
4080 * @return external_function_parameters
4082 public static function get_enrolled_users_by_cmid_parameters() {
4083 return new external_function_parameters([
4084 'cmid' => new external_value(PARAM_INT
, 'id of the course module', VALUE_REQUIRED
),
4085 'groupid' => new external_value(PARAM_INT
, 'id of the group', VALUE_DEFAULT
, 0),
4090 * Get all users in a course for a given cmid.
4092 * @param int $cmid Course Module id from which the users will be obtained
4093 * @param int $groupid Group id from which the users will be obtained
4094 * @return array List of users
4095 * @throws invalid_parameter_exception
4097 public static function get_enrolled_users_by_cmid(int $cmid, int $groupid = 0) {
4103 'groupid' => $groupid,
4104 ] = self
::validate_parameters(self
::get_enrolled_users_by_cmid_parameters(), [
4106 'groupid' => $groupid,
4109 list($course, $cm) = get_course_and_cm_from_cmid($cmid);
4110 $coursecontext = context_course
::instance($course->id
);
4111 self
::validate_context($coursecontext);
4113 $enrolledusers = get_enrolled_users($coursecontext, '', $groupid);
4115 $users = array_map(function ($user) use ($PAGE) {
4116 $user->fullname
= fullname($user);
4117 $userpicture = new user_picture($user);
4118 $userpicture->size
= 1;
4119 $user->profileimage
= $userpicture->get_url($PAGE)->out(false);
4126 'warnings' => $warnings,
4131 * Returns description of method result value
4133 * @return external_description
4135 public static function get_enrolled_users_by_cmid_returns() {
4136 return new external_single_structure([
4137 'users' => new external_multiple_structure(self
::user_description()),
4138 'warnings' => new external_warnings(),
4143 * Create user return value description.
4145 * @return external_description
4147 public static function user_description() {
4148 $userfields = array(
4149 'id' => new external_value(core_user
::get_property_type('id'), 'ID of the user'),
4150 'profileimage' => new external_value(PARAM_URL
, 'The location of the users larger image', VALUE_OPTIONAL
),
4151 'fullname' => new external_value(PARAM_TEXT
, 'The full name of the user', VALUE_OPTIONAL
),
4152 'firstname' => new external_value(
4153 core_user
::get_property_type('firstname'),
4154 'The first name(s) of the user',
4156 'lastname' => new external_value(
4157 core_user
::get_property_type('lastname'),
4158 'The family name of the user',
4161 return new external_single_structure($userfields);
4165 * Returns description of method parameters.
4167 * @return external_function_parameters
4169 public static function add_content_item_to_user_favourites_parameters() {
4170 return new external_function_parameters([
4171 'componentname' => new external_value(PARAM_TEXT
,
4172 'frankenstyle name of the component to which the content item belongs', VALUE_REQUIRED
),
4173 'contentitemid' => new external_value(PARAM_INT
, 'id of the content item', VALUE_REQUIRED
, '', NULL_NOT_ALLOWED
)
4178 * Add a content item to a user's favourites.
4180 * @param string $componentname the name of the component from which this content item originates.
4181 * @param int $contentitemid the id of the content item.
4182 * @return stdClass the exporter content item.
4184 public static function add_content_item_to_user_favourites(string $componentname, int $contentitemid) {
4188 'componentname' => $componentname,
4189 'contentitemid' => $contentitemid,
4190 ] = self
::validate_parameters(self
::add_content_item_to_user_favourites_parameters(),
4192 'componentname' => $componentname,
4193 'contentitemid' => $contentitemid,
4197 self
::validate_context(context_user
::instance($USER->id
));
4199 $contentitemservice = \core_course\local\factory\content_item_service_factory
::get_content_item_service();
4201 return $contentitemservice->add_to_user_favourites($USER, $componentname, $contentitemid);
4205 * Returns description of method result value.
4207 * @return external_description
4209 public static function add_content_item_to_user_favourites_returns() {
4210 return \core_course\local\exporters\course_content_item_exporter
::get_read_structure();
4214 * Returns description of method parameters.
4216 * @return external_function_parameters
4218 public static function remove_content_item_from_user_favourites_parameters() {
4219 return new external_function_parameters([
4220 'componentname' => new external_value(PARAM_TEXT
,
4221 'frankenstyle name of the component to which the content item belongs', VALUE_REQUIRED
),
4222 'contentitemid' => new external_value(PARAM_INT
, 'id of the content item', VALUE_REQUIRED
, '', NULL_NOT_ALLOWED
),
4227 * Remove a content item from a user's favourites.
4229 * @param string $componentname the name of the component from which this content item originates.
4230 * @param int $contentitemid the id of the content item.
4231 * @return stdClass the exported content item.
4233 public static function remove_content_item_from_user_favourites(string $componentname, int $contentitemid) {
4237 'componentname' => $componentname,
4238 'contentitemid' => $contentitemid,
4239 ] = self
::validate_parameters(self
::remove_content_item_from_user_favourites_parameters(),
4241 'componentname' => $componentname,
4242 'contentitemid' => $contentitemid,
4246 self
::validate_context(context_user
::instance($USER->id
));
4248 $contentitemservice = \core_course\local\factory\content_item_service_factory
::get_content_item_service();
4250 return $contentitemservice->remove_from_user_favourites($USER, $componentname, $contentitemid);
4254 * Returns description of method result value.
4256 * @return external_description
4258 public static function remove_content_item_from_user_favourites_returns() {
4259 return \core_course\local\exporters\course_content_item_exporter
::get_read_structure();
4263 * Returns description of method result value
4265 * @return external_description
4267 public static function get_course_content_items_returns() {
4268 return new external_single_structure([
4269 'content_items' => new external_multiple_structure(
4270 \core_course\local\exporters\course_content_item_exporter
::get_read_structure()
4276 * Returns description of method parameters
4278 * @return external_function_parameters
4280 public static function get_course_content_items_parameters() {
4281 return new external_function_parameters([
4282 'courseid' => new external_value(PARAM_INT
, 'ID of the course', VALUE_REQUIRED
),
4287 * Given a course ID fetch all accessible modules for that course
4289 * @param int $courseid The course we want to fetch the modules for
4290 * @return array Contains array of modules and their metadata
4292 public static function get_course_content_items(int $courseid) {
4296 'courseid' => $courseid,
4297 ] = self
::validate_parameters(self
::get_course_content_items_parameters(), [
4298 'courseid' => $courseid,
4301 $coursecontext = context_course
::instance($courseid);
4302 self
::validate_context($coursecontext);
4303 $course = get_course($courseid);
4305 $contentitemservice = \core_course\local\factory\content_item_service_factory
::get_content_item_service();
4307 $contentitems = $contentitemservice->get_content_items_for_user_in_course($USER, $course);
4308 return ['content_items' => $contentitems];
4312 * Returns description of method parameters.
4314 * @return external_function_parameters
4316 public static function toggle_activity_recommendation_parameters() {
4317 return new external_function_parameters([
4318 'area' => new external_value(PARAM_TEXT
, 'The favourite area (itemtype)', VALUE_REQUIRED
),
4319 'id' => new external_value(PARAM_INT
, 'id of the activity or whatever', VALUE_REQUIRED
),
4324 * Update the recommendation for an activity item.
4326 * @param string $area identifier for this activity.
4327 * @param int $id Associated id. This is needed in conjunction with the area to find the recommendation.
4328 * @return array some warnings or something.
4330 public static function toggle_activity_recommendation(string $area, int $id): array {
4331 ['area' => $area, 'id' => $id] = self
::validate_parameters(self
::toggle_activity_recommendation_parameters(),
4332 ['area' => $area, 'id' => $id]);
4334 $context = context_system
::instance();
4335 self
::validate_context($context);
4337 require_capability('moodle/course:recommendactivity', $context);
4339 $manager = \core_course\local\factory\content_item_service_factory
::get_content_item_service();
4341 $status = $manager->toggle_recommendation($area, $id);
4342 return ['id' => $id, 'area' => $area, 'status' => $status];
4348 * @return external_description
4350 public static function toggle_activity_recommendation_returns() {
4351 return new external_single_structure(
4353 'id' => new external_value(PARAM_INT
, 'id of the activity or whatever'),
4354 'area' => new external_value(PARAM_TEXT
, 'The favourite area (itemtype)'),
4355 'status' => new external_value(PARAM_BOOL
, 'If created or deleted'),
4361 * Returns description of method parameters
4363 * @return external_function_parameters
4365 public static function get_activity_chooser_footer_parameters() {
4366 return new external_function_parameters([
4367 'courseid' => new external_value(PARAM_INT
, 'ID of the course', VALUE_REQUIRED
),
4368 'sectionid' => new external_value(PARAM_INT
, 'ID of the section', VALUE_REQUIRED
),
4373 * Given a course ID we need to build up a footre for the chooser.
4375 * @param int $courseid The course we want to fetch the modules for
4376 * @param int $sectionid The section we want to fetch the modules for
4379 public static function get_activity_chooser_footer(int $courseid, int $sectionid) {
4381 'courseid' => $courseid,
4382 'sectionid' => $sectionid,
4383 ] = self
::validate_parameters(self
::get_activity_chooser_footer_parameters(), [
4384 'courseid' => $courseid,
4385 'sectionid' => $sectionid,
4388 $coursecontext = context_course
::instance($courseid);
4389 self
::validate_context($coursecontext);
4391 $pluginswithfunction = get_plugins_with_function('custom_chooser_footer', 'lib.php');
4392 if ($pluginswithfunction) {
4393 foreach ($pluginswithfunction as $plugintype => $plugins) {
4394 foreach ($plugins as $pluginfunction) {
4395 $footerdata = $pluginfunction($courseid, $sectionid);
4396 break; // Only a single plugin can modify the footer.
4398 break; // Only a single plugin can modify the footer.
4402 'customfooterjs' => $footerdata->get_footer_js_file(),
4403 'customfootertemplate' => $footerdata->get_footer_template(),
4404 'customcarouseltemplate' => $footerdata->get_carousel_template(),
4414 * Returns description of method result value
4416 * @return external_description
4418 public static function get_activity_chooser_footer_returns() {
4419 return new external_single_structure(
4421 'footer' => new external_value(PARAM_BOOL
, 'Is a footer being return by this request?', VALUE_REQUIRED
),
4422 'customfooterjs' => new external_value(PARAM_RAW
, 'The path to the plugin JS file', VALUE_OPTIONAL
),
4423 'customfootertemplate' => new external_value(PARAM_RAW
, 'The prerendered footer', VALUE_OPTIONAL
),
4424 'customcarouseltemplate' => new external_value(PARAM_RAW
, 'Either "" or the prerendered carousel page',