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("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 $coursenumsections = course_get_format($course)->get_last_section_number();
171 $stealthmodules = array(); // Array to keep all the modules available but not visible in a course section/topic.
173 $completioninfo = new completion_info($course);
175 //for each sections (first displayed to last displayed)
176 $modinfosections = $modinfo->get_sections();
177 foreach ($sections as $key => $section) {
179 // This becomes true when we are filtering and we found the value to filter with.
180 $sectionfound = false;
182 // Filter by section id.
183 if (!empty($filters['sectionid'])) {
184 if ($section->id
!= $filters['sectionid']) {
187 $sectionfound = true;
191 // Filter by section number. Note that 0 is a valid section number.
192 if (isset($filters['sectionnumber'])) {
193 if ($key != $filters['sectionnumber']) {
196 $sectionfound = true;
200 // reset $sectioncontents
201 $sectionvalues = array();
202 $sectionvalues['id'] = $section->id
;
203 $sectionvalues['name'] = get_section_name($course, $section);
204 $sectionvalues['visible'] = $section->visible
;
206 $options = (object) array('noclean' => true);
207 list($sectionvalues['summary'], $sectionvalues['summaryformat']) =
208 external_format_text($section->summary
, $section->summaryformat
,
209 $context->id
, 'course', 'section', $section->id
, $options);
210 $sectionvalues['section'] = $section->section
;
211 $sectionvalues['hiddenbynumsections'] = $section->section
> $coursenumsections ?
1 : 0;
212 $sectionvalues['uservisible'] = $section->uservisible
;
213 if (!empty($section->availableinfo
)) {
214 $sectionvalues['availabilityinfo'] = \core_availability\info
::format_info($section->availableinfo
, $course);
217 $sectioncontents = array();
219 // For each module of the section.
220 if (empty($filters['excludemodules']) and !empty($modinfosections[$section->section
])) {
221 foreach ($modinfosections[$section->section
] as $cmid) {
222 $cm = $modinfo->cms
[$cmid];
224 // Stop here if the module is not visible to the user on the course main page:
225 // The user can't access the module and the user can't view the module on the course page.
226 if (!$cm->uservisible
&& !$cm->is_visible_on_course_page()) {
230 // This becomes true when we are filtering and we found the value to filter with.
234 if (!empty($filters['cmid'])) {
235 if ($cmid != $filters['cmid']) {
242 // Filter by module name and id.
243 if (!empty($filters['modname'])) {
244 if ($cm->modname
!= $filters['modname']) {
246 } else if (!empty($filters['modid'])) {
247 if ($cm->instance
!= $filters['modid']) {
250 // Note that if we are only filtering by modname we don't break the loop.
258 $modcontext = context_module
::instance($cm->id
);
260 //common info (for people being able to see the module or availability dates)
261 $module['id'] = $cm->id
;
262 $module['name'] = external_format_string($cm->name
, $modcontext->id
);
263 $module['instance'] = $cm->instance
;
264 $module['modname'] = $cm->modname
;
265 $module['modplural'] = $cm->modplural
;
266 $module['modicon'] = $cm->get_icon_url()->out(false);
267 $module['indent'] = $cm->indent
;
268 $module['onclick'] = $cm->onclick
;
269 $module['afterlink'] = $cm->afterlink
;
270 $module['customdata'] = json_encode($cm->customdata
);
271 $module['completion'] = $cm->completion
;
273 // Check module completion.
274 $completion = $completioninfo->is_enabled($cm);
275 if ($completion != COMPLETION_DISABLED
) {
276 $completiondata = $completioninfo->get_data($cm, true);
277 $module['completiondata'] = array(
278 'state' => $completiondata->completionstate
,
279 'timecompleted' => $completiondata->timemodified
,
280 'overrideby' => $completiondata->overrideby
,
281 'valueused' => core_availability\info
::completion_value_used($course, $cm->id
)
285 if (!empty($cm->showdescription
) or $cm->modname
== 'label') {
286 // We want to use the external format. However from reading get_formatted_content(), $cm->content format is always FORMAT_HTML.
287 $options = array('noclean' => true);
288 list($module['description'], $descriptionformat) = external_format_text($cm->content
,
289 FORMAT_HTML
, $modcontext->id
, $cm->modname
, 'intro', $cm->id
, $options);
294 if ($url) { //labels don't have url
295 $module['url'] = $url->out(false);
298 $canviewhidden = has_capability('moodle/course:viewhiddenactivities',
299 context_module
::instance($cm->id
));
300 //user that can view hidden module should know about the visibility
301 $module['visible'] = $cm->visible
;
302 $module['visibleoncoursepage'] = $cm->visibleoncoursepage
;
303 $module['uservisible'] = $cm->uservisible
;
304 if (!empty($cm->availableinfo
)) {
305 $module['availabilityinfo'] = \core_availability\info
::format_info($cm->availableinfo
, $course);
308 // Availability date (also send to user who can see hidden module).
309 if ($CFG->enableavailability
&& ($canviewhidden ||
$canupdatecourse)) {
310 $module['availability'] = $cm->availability
;
313 // Return contents only if the user can access to the module.
314 if ($cm->uservisible
) {
315 $baseurl = 'webservice/pluginfile.php';
317 // Call $modulename_export_contents (each module callback take care about checking the capabilities).
318 require_once($CFG->dirroot
. '/mod/' . $cm->modname
. '/lib.php');
319 $getcontentfunction = $cm->modname
.'_export_contents';
320 if (function_exists($getcontentfunction)) {
321 $contents = $getcontentfunction($cm, $baseurl);
322 $module['contentsinfo'] = array(
323 'filescount' => count($contents),
326 'mimetypes' => array(),
328 foreach ($contents as $content) {
329 // Check repository file (only main file).
330 if (!isset($module['contentsinfo']['repositorytype'])) {
331 $module['contentsinfo']['repositorytype'] =
332 isset($content['repositorytype']) ?
$content['repositorytype'] : '';
334 if (isset($content['filesize'])) {
335 $module['contentsinfo']['filessize'] +
= $content['filesize'];
337 if (isset($content['timemodified']) &&
338 ($content['timemodified'] > $module['contentsinfo']['lastmodified'])) {
340 $module['contentsinfo']['lastmodified'] = $content['timemodified'];
342 if (isset($content['mimetype'])) {
343 $module['contentsinfo']['mimetypes'][$content['mimetype']] = $content['mimetype'];
347 if (empty($filters['excludecontents']) and !empty($contents)) {
348 $module['contents'] = $contents;
350 $module['contents'] = array();
355 // Assign result to $sectioncontents, there is an exception,
356 // stealth activities in non-visible sections for students go to a special section.
357 if (!empty($filters['includestealthmodules']) && !$section->uservisible
&& $cm->is_stealth()) {
358 $stealthmodules[] = $module;
360 $sectioncontents[] = $module;
363 // If we just did a filtering, break the loop.
370 $sectionvalues['modules'] = $sectioncontents;
372 // assign result to $coursecontents
373 $coursecontents[$key] = $sectionvalues;
375 // Break the loop if we are filtering.
381 // Now that we have iterated over all the sections and activities, check the visibility.
382 // We didn't this before to be able to retrieve stealth activities.
383 foreach ($coursecontents as $sectionnumber => $sectioncontents) {
384 $section = $sections[$sectionnumber];
385 // Show the section if the user is permitted to access it, OR if it's not available
386 // but there is some available info text which explains the reason & should display.
387 $showsection = $section->uservisible ||
388 ($section->visible
&& !$section->available
&&
389 !empty($section->availableinfo
));
392 unset($coursecontents[$sectionnumber]);
396 // Remove modules information if the section is not visible for the user.
397 if (!$section->uservisible
) {
398 $coursecontents[$sectionnumber]['modules'] = array();
402 // Include stealth modules in special section (without any info).
403 if (!empty($stealthmodules)) {
404 $coursecontents[] = array(
408 'summaryformat' => FORMAT_MOODLE
,
409 'modules' => $stealthmodules
414 return $coursecontents;
418 * Returns description of method result value
420 * @return external_description
423 public static function get_course_contents_returns() {
424 return new external_multiple_structure(
425 new external_single_structure(
427 'id' => new external_value(PARAM_INT
, 'Section ID'),
428 'name' => new external_value(PARAM_TEXT
, 'Section name'),
429 'visible' => new external_value(PARAM_INT
, 'is the section visible', VALUE_OPTIONAL
),
430 'summary' => new external_value(PARAM_RAW
, 'Section description'),
431 'summaryformat' => new external_format_value('summary'),
432 'section' => new external_value(PARAM_INT
, 'Section number inside the course', VALUE_OPTIONAL
),
433 'hiddenbynumsections' => new external_value(PARAM_INT
, 'Whether is a section hidden in the course format',
435 'uservisible' => new external_value(PARAM_BOOL
, 'Is the section visible for the user?', VALUE_OPTIONAL
),
436 'availabilityinfo' => new external_value(PARAM_RAW
, 'Availability information.', VALUE_OPTIONAL
),
437 'modules' => new external_multiple_structure(
438 new external_single_structure(
440 'id' => new external_value(PARAM_INT
, 'activity id'),
441 'url' => new external_value(PARAM_URL
, 'activity url', VALUE_OPTIONAL
),
442 'name' => new external_value(PARAM_RAW
, 'activity module name'),
443 'instance' => new external_value(PARAM_INT
, 'instance id', VALUE_OPTIONAL
),
444 'description' => new external_value(PARAM_RAW
, 'activity description', VALUE_OPTIONAL
),
445 'visible' => new external_value(PARAM_INT
, 'is the module visible', VALUE_OPTIONAL
),
446 'uservisible' => new external_value(PARAM_BOOL
, 'Is the module visible for the user?',
448 'availabilityinfo' => new external_value(PARAM_RAW
, 'Availability information.',
450 'visibleoncoursepage' => new external_value(PARAM_INT
, 'is the module visible on course page',
452 'modicon' => new external_value(PARAM_URL
, 'activity icon url'),
453 'modname' => new external_value(PARAM_PLUGIN
, 'activity module type'),
454 'modplural' => new external_value(PARAM_TEXT
, 'activity module plural name'),
455 'availability' => new external_value(PARAM_RAW
, 'module availability settings', VALUE_OPTIONAL
),
456 'indent' => new external_value(PARAM_INT
, 'number of identation in the site'),
457 'onclick' => new external_value(PARAM_RAW
, 'Onclick action.', VALUE_OPTIONAL
),
458 'afterlink' => new external_value(PARAM_RAW
, 'After link info to be displayed.',
460 'customdata' => new external_value(PARAM_RAW
, 'Custom data (JSON encoded).', VALUE_OPTIONAL
),
461 'completion' => new external_value(PARAM_INT
, 'Type of completion tracking:
462 0 means none, 1 manual, 2 automatic.', VALUE_OPTIONAL
),
463 'completiondata' => new external_single_structure(
465 'state' => new external_value(PARAM_INT
, 'Completion state value:
466 0 means incomplete, 1 complete, 2 complete pass, 3 complete fail'),
467 'timecompleted' => new external_value(PARAM_INT
, 'Timestamp for completion status.'),
468 'overrideby' => new external_value(PARAM_INT
, 'The user id who has overriden the
470 'valueused' => new external_value(PARAM_BOOL
, 'Whether the completion status affects
471 the availability of another activity.', VALUE_OPTIONAL
),
472 ), 'Module completion data.', VALUE_OPTIONAL
474 'contents' => new external_multiple_structure(
475 new external_single_structure(
478 'type'=> new external_value(PARAM_TEXT
, 'a file or a folder or external link'),
479 'filename'=> new external_value(PARAM_FILE
, 'filename'),
480 'filepath'=> new external_value(PARAM_PATH
, 'filepath'),
481 'filesize'=> new external_value(PARAM_INT
, 'filesize'),
482 'fileurl' => new external_value(PARAM_URL
, 'downloadable file url', VALUE_OPTIONAL
),
483 'content' => new external_value(PARAM_RAW
, 'Raw content, will be used when type is content', VALUE_OPTIONAL
),
484 'timecreated' => new external_value(PARAM_INT
, 'Time created'),
485 'timemodified' => new external_value(PARAM_INT
, 'Time modified'),
486 'sortorder' => new external_value(PARAM_INT
, 'Content sort order'),
487 'mimetype' => new external_value(PARAM_RAW
, 'File mime type.', VALUE_OPTIONAL
),
488 'isexternalfile' => new external_value(PARAM_BOOL
, 'Whether is an external file.',
490 'repositorytype' => new external_value(PARAM_PLUGIN
, 'The repository type for external files.',
493 // copyright related info
494 'userid' => new external_value(PARAM_INT
, 'User who added this content to moodle'),
495 'author' => new external_value(PARAM_TEXT
, 'Content owner'),
496 'license' => new external_value(PARAM_TEXT
, 'Content license'),
497 'tags' => new external_multiple_structure(
498 \core_tag\external\tag_item_exporter
::get_read_structure(), 'Tags',
502 ), VALUE_DEFAULT
, array()
504 'contentsinfo' => new external_single_structure(
506 'filescount' => new external_value(PARAM_INT
, 'Total number of files.'),
507 'filessize' => new external_value(PARAM_INT
, 'Total files size.'),
508 'lastmodified' => new external_value(PARAM_INT
, 'Last time files were modified.'),
509 'mimetypes' => new external_multiple_structure(
510 new external_value(PARAM_RAW
, 'File mime type.'),
513 'repositorytype' => new external_value(PARAM_PLUGIN
, 'The repository type for
514 the main file.', VALUE_OPTIONAL
),
515 ), 'Contents summary information.', VALUE_OPTIONAL
526 * Returns description of method parameters
528 * @return external_function_parameters
531 public static function get_courses_parameters() {
532 return new external_function_parameters(
533 array('options' => new external_single_structure(
534 array('ids' => new external_multiple_structure(
535 new external_value(PARAM_INT
, 'Course id')
536 , 'List of course id. If empty return all courses
537 except front page course.',
539 ), 'options - operator OR is used', VALUE_DEFAULT
, array())
547 * @param array $options It contains an array (list of ids)
551 public static function get_courses($options = array()) {
553 require_once($CFG->dirroot
. "/course/lib.php");
556 $params = self
::validate_parameters(self
::get_courses_parameters(),
557 array('options' => $options));
560 if (!array_key_exists('ids', $params['options'])
561 or empty($params['options']['ids'])) {
562 $courses = $DB->get_records('course');
564 $courses = $DB->get_records_list('course', 'id', $params['options']['ids']);
567 //create return value
568 $coursesinfo = array();
569 foreach ($courses as $course) {
571 // now security checks
572 $context = context_course
::instance($course->id
, IGNORE_MISSING
);
573 $courseformatoptions = course_get_format($course)->get_format_options();
575 self
::validate_context($context);
576 } catch (Exception
$e) {
577 $exceptionparam = new stdClass();
578 $exceptionparam->message
= $e->getMessage();
579 $exceptionparam->courseid
= $course->id
;
580 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
582 if ($course->id
!= SITEID
) {
583 require_capability('moodle/course:view', $context);
586 $courseinfo = array();
587 $courseinfo['id'] = $course->id
;
588 $courseinfo['fullname'] = external_format_string($course->fullname
, $context->id
);
589 $courseinfo['shortname'] = external_format_string($course->shortname
, $context->id
);
590 $courseinfo['displayname'] = external_format_string(get_course_display_name_for_list($course), $context->id
);
591 $courseinfo['categoryid'] = $course->category
;
592 list($courseinfo['summary'], $courseinfo['summaryformat']) =
593 external_format_text($course->summary
, $course->summaryformat
, $context->id
, 'course', 'summary', 0);
594 $courseinfo['format'] = $course->format
;
595 $courseinfo['startdate'] = $course->startdate
;
596 $courseinfo['enddate'] = $course->enddate
;
597 if (array_key_exists('numsections', $courseformatoptions)) {
598 // For backward-compartibility
599 $courseinfo['numsections'] = $courseformatoptions['numsections'];
602 $handler = core_course\customfield\course_handler
::create();
603 if ($customfields = $handler->export_instance_data($course->id
)) {
604 $courseinfo['customfields'] = [];
605 foreach ($customfields as $data) {
606 $courseinfo['customfields'][] = [
607 'type' => $data->get_type(),
608 'value' => $data->get_value(),
609 'name' => $data->get_name(),
610 'shortname' => $data->get_shortname()
615 //some field should be returned only if the user has update permission
616 $courseadmin = has_capability('moodle/course:update', $context);
618 $courseinfo['categorysortorder'] = $course->sortorder
;
619 $courseinfo['idnumber'] = $course->idnumber
;
620 $courseinfo['showgrades'] = $course->showgrades
;
621 $courseinfo['showreports'] = $course->showreports
;
622 $courseinfo['newsitems'] = $course->newsitems
;
623 $courseinfo['visible'] = $course->visible
;
624 $courseinfo['maxbytes'] = $course->maxbytes
;
625 if (array_key_exists('hiddensections', $courseformatoptions)) {
626 // For backward-compartibility
627 $courseinfo['hiddensections'] = $courseformatoptions['hiddensections'];
629 // Return numsections for backward-compatibility with clients who expect it.
630 $courseinfo['numsections'] = course_get_format($course)->get_last_section_number();
631 $courseinfo['groupmode'] = $course->groupmode
;
632 $courseinfo['groupmodeforce'] = $course->groupmodeforce
;
633 $courseinfo['defaultgroupingid'] = $course->defaultgroupingid
;
634 $courseinfo['lang'] = clean_param($course->lang
, PARAM_LANG
);
635 $courseinfo['timecreated'] = $course->timecreated
;
636 $courseinfo['timemodified'] = $course->timemodified
;
637 $courseinfo['forcetheme'] = clean_param($course->theme
, PARAM_THEME
);
638 $courseinfo['enablecompletion'] = $course->enablecompletion
;
639 $courseinfo['completionnotify'] = $course->completionnotify
;
640 $courseinfo['courseformatoptions'] = array();
641 foreach ($courseformatoptions as $key => $value) {
642 $courseinfo['courseformatoptions'][] = array(
649 if ($courseadmin or $course->visible
650 or has_capability('moodle/course:viewhiddencourses', $context)) {
651 $coursesinfo[] = $courseinfo;
659 * Returns description of method result value
661 * @return external_description
664 public static function get_courses_returns() {
665 return new external_multiple_structure(
666 new external_single_structure(
668 'id' => new external_value(PARAM_INT
, 'course id'),
669 'shortname' => new external_value(PARAM_TEXT
, 'course short name'),
670 'categoryid' => new external_value(PARAM_INT
, 'category id'),
671 'categorysortorder' => new external_value(PARAM_INT
,
672 'sort order into the category', VALUE_OPTIONAL
),
673 'fullname' => new external_value(PARAM_TEXT
, 'full name'),
674 'displayname' => new external_value(PARAM_TEXT
, 'course display name'),
675 'idnumber' => new external_value(PARAM_RAW
, 'id number', VALUE_OPTIONAL
),
676 'summary' => new external_value(PARAM_RAW
, 'summary'),
677 'summaryformat' => new external_format_value('summary'),
678 'format' => new external_value(PARAM_PLUGIN
,
679 'course format: weeks, topics, social, site,..'),
680 'showgrades' => new external_value(PARAM_INT
,
681 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL
),
682 'newsitems' => new external_value(PARAM_INT
,
683 'number of recent items appearing on the course page', VALUE_OPTIONAL
),
684 'startdate' => new external_value(PARAM_INT
,
685 'timestamp when the course start'),
686 'enddate' => new external_value(PARAM_INT
,
687 'timestamp when the course end'),
688 'numsections' => new external_value(PARAM_INT
,
689 '(deprecated, use courseformatoptions) number of weeks/topics',
691 'maxbytes' => new external_value(PARAM_INT
,
692 'largest size of file that can be uploaded into the course',
694 'showreports' => new external_value(PARAM_INT
,
695 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL
),
696 'visible' => new external_value(PARAM_INT
,
697 '1: available to student, 0:not available', VALUE_OPTIONAL
),
698 'hiddensections' => new external_value(PARAM_INT
,
699 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
701 'groupmode' => new external_value(PARAM_INT
, 'no group, separate, visible',
703 'groupmodeforce' => new external_value(PARAM_INT
, '1: yes, 0: no',
705 'defaultgroupingid' => new external_value(PARAM_INT
, 'default grouping id',
707 'timecreated' => new external_value(PARAM_INT
,
708 'timestamp when the course have been created', VALUE_OPTIONAL
),
709 'timemodified' => new external_value(PARAM_INT
,
710 'timestamp when the course have been modified', VALUE_OPTIONAL
),
711 'enablecompletion' => new external_value(PARAM_INT
,
712 'Enabled, control via completion and activity settings. Disbaled,
713 not shown in activity settings.',
715 'completionnotify' => new external_value(PARAM_INT
,
716 '1: yes 0: no', VALUE_OPTIONAL
),
717 'lang' => new external_value(PARAM_SAFEDIR
,
718 'forced course language', VALUE_OPTIONAL
),
719 'forcetheme' => new external_value(PARAM_PLUGIN
,
720 'name of the force theme', VALUE_OPTIONAL
),
721 'courseformatoptions' => new external_multiple_structure(
722 new external_single_structure(
723 array('name' => new external_value(PARAM_ALPHANUMEXT
, 'course format option name'),
724 'value' => new external_value(PARAM_RAW
, 'course format option value')
725 )), 'additional options for particular course format', VALUE_OPTIONAL
727 'customfields' => new external_multiple_structure(
728 new external_single_structure(
729 ['name' => new external_value(PARAM_TEXT
, 'The name of the custom field'),
730 'shortname' => new external_value(PARAM_ALPHANUMEXT
, 'The shortname of the custom field'),
731 'type' => new external_value(PARAM_COMPONENT
,
732 'The type of the custom field - text, checkbox...'),
733 'value' => new external_value(PARAM_RAW
, 'The value of the custom field')]
734 ), 'Custom fields and associated values', VALUE_OPTIONAL
),
741 * Returns description of method parameters
743 * @return external_function_parameters
746 public static function create_courses_parameters() {
747 $courseconfig = get_config('moodlecourse'); //needed for many default values
748 return new external_function_parameters(
750 'courses' => new external_multiple_structure(
751 new external_single_structure(
753 'fullname' => new external_value(PARAM_TEXT
, 'full name'),
754 'shortname' => new external_value(PARAM_TEXT
, 'course short name'),
755 'categoryid' => new external_value(PARAM_INT
, 'category id'),
756 'idnumber' => new external_value(PARAM_RAW
, 'id number', VALUE_OPTIONAL
),
757 'summary' => new external_value(PARAM_RAW
, 'summary', VALUE_OPTIONAL
),
758 'summaryformat' => new external_format_value('summary', VALUE_DEFAULT
),
759 'format' => new external_value(PARAM_PLUGIN
,
760 'course format: weeks, topics, social, site,..',
761 VALUE_DEFAULT
, $courseconfig->format
),
762 'showgrades' => new external_value(PARAM_INT
,
763 '1 if grades are shown, otherwise 0', VALUE_DEFAULT
,
764 $courseconfig->showgrades
),
765 'newsitems' => new external_value(PARAM_INT
,
766 'number of recent items appearing on the course page',
767 VALUE_DEFAULT
, $courseconfig->newsitems
),
768 'startdate' => new external_value(PARAM_INT
,
769 'timestamp when the course start', VALUE_OPTIONAL
),
770 'enddate' => new external_value(PARAM_INT
,
771 'timestamp when the course end', VALUE_OPTIONAL
),
772 'numsections' => new external_value(PARAM_INT
,
773 '(deprecated, use courseformatoptions) number of weeks/topics',
775 'maxbytes' => new external_value(PARAM_INT
,
776 'largest size of file that can be uploaded into the course',
777 VALUE_DEFAULT
, $courseconfig->maxbytes
),
778 'showreports' => new external_value(PARAM_INT
,
779 'are activity report shown (yes = 1, no =0)', VALUE_DEFAULT
,
780 $courseconfig->showreports
),
781 'visible' => new external_value(PARAM_INT
,
782 '1: available to student, 0:not available', VALUE_OPTIONAL
),
783 'hiddensections' => new external_value(PARAM_INT
,
784 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
786 'groupmode' => new external_value(PARAM_INT
, 'no group, separate, visible',
787 VALUE_DEFAULT
, $courseconfig->groupmode
),
788 'groupmodeforce' => new external_value(PARAM_INT
, '1: yes, 0: no',
789 VALUE_DEFAULT
, $courseconfig->groupmodeforce
),
790 'defaultgroupingid' => new external_value(PARAM_INT
, 'default grouping id',
792 'enablecompletion' => new external_value(PARAM_INT
,
793 'Enabled, control via completion and activity settings. Disabled,
794 not shown in activity settings.',
796 'completionnotify' => new external_value(PARAM_INT
,
797 '1: yes 0: no', VALUE_OPTIONAL
),
798 'lang' => new external_value(PARAM_SAFEDIR
,
799 'forced course language', VALUE_OPTIONAL
),
800 'forcetheme' => new external_value(PARAM_PLUGIN
,
801 'name of the force theme', VALUE_OPTIONAL
),
802 'courseformatoptions' => new external_multiple_structure(
803 new external_single_structure(
804 array('name' => new external_value(PARAM_ALPHANUMEXT
, 'course format option name'),
805 'value' => new external_value(PARAM_RAW
, 'course format option value')
807 'additional options for particular course format', VALUE_OPTIONAL
),
808 'customfields' => new external_multiple_structure(
809 new external_single_structure(
811 'shortname' => new external_value(PARAM_ALPHANUMEXT
, 'The shortname of the custom field'),
812 'value' => new external_value(PARAM_RAW
, 'The value of the custom field'),
813 )), 'custom fields for the course', VALUE_OPTIONAL
815 )), 'courses to create'
824 * @param array $courses
825 * @return array courses (id and shortname only)
828 public static function create_courses($courses) {
830 require_once($CFG->dirroot
. "/course/lib.php");
831 require_once($CFG->libdir
. '/completionlib.php');
833 $params = self
::validate_parameters(self
::create_courses_parameters(),
834 array('courses' => $courses));
836 $availablethemes = core_component
::get_plugin_list('theme');
837 $availablelangs = get_string_manager()->get_list_of_translations();
839 $transaction = $DB->start_delegated_transaction();
841 foreach ($params['courses'] as $course) {
843 // Ensure the current user is allowed to run this function
844 $context = context_coursecat
::instance($course['categoryid'], IGNORE_MISSING
);
846 self
::validate_context($context);
847 } catch (Exception
$e) {
848 $exceptionparam = new stdClass();
849 $exceptionparam->message
= $e->getMessage();
850 $exceptionparam->catid
= $course['categoryid'];
851 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
853 require_capability('moodle/course:create', $context);
855 // Make sure lang is valid
856 if (array_key_exists('lang', $course)) {
857 if (empty($availablelangs[$course['lang']])) {
858 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
860 if (!has_capability('moodle/course:setforcedlanguage', $context)) {
861 unset($course['lang']);
865 // Make sure theme is valid
866 if (array_key_exists('forcetheme', $course)) {
867 if (!empty($CFG->allowcoursethemes
)) {
868 if (empty($availablethemes[$course['forcetheme']])) {
869 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
871 $course['theme'] = $course['forcetheme'];
876 //force visibility if ws user doesn't have the permission to set it
877 $category = $DB->get_record('course_categories', array('id' => $course['categoryid']));
878 if (!has_capability('moodle/course:visibility', $context)) {
879 $course['visible'] = $category->visible
;
882 //set default value for completion
883 $courseconfig = get_config('moodlecourse');
884 if (completion_info
::is_enabled_for_site()) {
885 if (!array_key_exists('enablecompletion', $course)) {
886 $course['enablecompletion'] = $courseconfig->enablecompletion
;
889 $course['enablecompletion'] = 0;
892 $course['category'] = $course['categoryid'];
895 $course['summaryformat'] = external_validate_format($course['summaryformat']);
897 if (!empty($course['courseformatoptions'])) {
898 foreach ($course['courseformatoptions'] as $option) {
899 $course[$option['name']] = $option['value'];
904 if (!empty($course['customfields'])) {
905 foreach ($course['customfields'] as $field) {
906 $course['customfield_'.$field['shortname']] = $field['value'];
910 //Note: create_course() core function check shortname, idnumber, category
911 $course['id'] = create_course((object) $course)->id
;
913 $resultcourses[] = array('id' => $course['id'], 'shortname' => $course['shortname']);
916 $transaction->allow_commit();
918 return $resultcourses;
922 * Returns description of method result value
924 * @return external_description
927 public static function create_courses_returns() {
928 return new external_multiple_structure(
929 new external_single_structure(
931 'id' => new external_value(PARAM_INT
, 'course id'),
932 'shortname' => new external_value(PARAM_TEXT
, 'short name'),
941 * @return external_function_parameters
944 public static function update_courses_parameters() {
945 return new external_function_parameters(
947 'courses' => new external_multiple_structure(
948 new external_single_structure(
950 'id' => new external_value(PARAM_INT
, 'ID of the course'),
951 'fullname' => new external_value(PARAM_TEXT
, 'full name', VALUE_OPTIONAL
),
952 'shortname' => new external_value(PARAM_TEXT
, 'course short name', VALUE_OPTIONAL
),
953 'categoryid' => new external_value(PARAM_INT
, 'category id', VALUE_OPTIONAL
),
954 'idnumber' => new external_value(PARAM_RAW
, 'id number', VALUE_OPTIONAL
),
955 'summary' => new external_value(PARAM_RAW
, 'summary', VALUE_OPTIONAL
),
956 'summaryformat' => new external_format_value('summary', VALUE_OPTIONAL
),
957 'format' => new external_value(PARAM_PLUGIN
,
958 'course format: weeks, topics, social, site,..', VALUE_OPTIONAL
),
959 'showgrades' => new external_value(PARAM_INT
,
960 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL
),
961 'newsitems' => new external_value(PARAM_INT
,
962 'number of recent items appearing on the course page', VALUE_OPTIONAL
),
963 'startdate' => new external_value(PARAM_INT
,
964 'timestamp when the course start', VALUE_OPTIONAL
),
965 'enddate' => new external_value(PARAM_INT
,
966 'timestamp when the course end', VALUE_OPTIONAL
),
967 'numsections' => new external_value(PARAM_INT
,
968 '(deprecated, use courseformatoptions) number of weeks/topics', VALUE_OPTIONAL
),
969 'maxbytes' => new external_value(PARAM_INT
,
970 'largest size of file that can be uploaded into the course', VALUE_OPTIONAL
),
971 'showreports' => new external_value(PARAM_INT
,
972 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL
),
973 'visible' => new external_value(PARAM_INT
,
974 '1: available to student, 0:not available', VALUE_OPTIONAL
),
975 'hiddensections' => new external_value(PARAM_INT
,
976 '(deprecated, use courseformatoptions) How the hidden sections in the course are
977 displayed to students', VALUE_OPTIONAL
),
978 'groupmode' => new external_value(PARAM_INT
, 'no group, separate, visible', VALUE_OPTIONAL
),
979 'groupmodeforce' => new external_value(PARAM_INT
, '1: yes, 0: no', VALUE_OPTIONAL
),
980 'defaultgroupingid' => new external_value(PARAM_INT
, 'default grouping id', VALUE_OPTIONAL
),
981 'enablecompletion' => new external_value(PARAM_INT
,
982 'Enabled, control via completion and activity settings. Disabled,
983 not shown in activity settings.', VALUE_OPTIONAL
),
984 'completionnotify' => new external_value(PARAM_INT
, '1: yes 0: no', VALUE_OPTIONAL
),
985 'lang' => new external_value(PARAM_SAFEDIR
, 'forced course language', VALUE_OPTIONAL
),
986 'forcetheme' => new external_value(PARAM_PLUGIN
, 'name of the force theme', VALUE_OPTIONAL
),
987 'courseformatoptions' => new external_multiple_structure(
988 new external_single_structure(
989 array('name' => new external_value(PARAM_ALPHANUMEXT
, 'course format option name'),
990 'value' => new external_value(PARAM_RAW
, 'course format option value')
991 )), 'additional options for particular course format', VALUE_OPTIONAL
),
992 'customfields' => new external_multiple_structure(
993 new external_single_structure(
995 'shortname' => new external_value(PARAM_ALPHANUMEXT
, 'The shortname of the custom field'),
996 'value' => new external_value(PARAM_RAW
, 'The value of the custom field')
998 ), 'Custom fields', VALUE_OPTIONAL
),
1000 ), 'courses to update'
1009 * @param array $courses
1012 public static function update_courses($courses) {
1014 require_once($CFG->dirroot
. "/course/lib.php");
1015 $warnings = array();
1017 $params = self
::validate_parameters(self
::update_courses_parameters(),
1018 array('courses' => $courses));
1020 $availablethemes = core_component
::get_plugin_list('theme');
1021 $availablelangs = get_string_manager()->get_list_of_translations();
1023 foreach ($params['courses'] as $course) {
1024 // Catch any exception while updating course and return as warning to user.
1026 // Ensure the current user is allowed to run this function.
1027 $context = context_course
::instance($course['id'], MUST_EXIST
);
1028 self
::validate_context($context);
1030 $oldcourse = course_get_format($course['id'])->get_course();
1032 require_capability('moodle/course:update', $context);
1034 // Check if user can change category.
1035 if (array_key_exists('categoryid', $course) && ($oldcourse->category
!= $course['categoryid'])) {
1036 require_capability('moodle/course:changecategory', $context);
1037 $course['category'] = $course['categoryid'];
1040 // Check if the user can change fullname.
1041 if (array_key_exists('fullname', $course) && ($oldcourse->fullname
!= $course['fullname'])) {
1042 require_capability('moodle/course:changefullname', $context);
1045 // Check if the user can change shortname.
1046 if (array_key_exists('shortname', $course) && ($oldcourse->shortname
!= $course['shortname'])) {
1047 require_capability('moodle/course:changeshortname', $context);
1050 // Check if the user can change the idnumber.
1051 if (array_key_exists('idnumber', $course) && ($oldcourse->idnumber
!= $course['idnumber'])) {
1052 require_capability('moodle/course:changeidnumber', $context);
1055 // Check if user can change summary.
1056 if (array_key_exists('summary', $course) && ($oldcourse->summary
!= $course['summary'])) {
1057 require_capability('moodle/course:changesummary', $context);
1061 if (array_key_exists('summaryformat', $course) && ($oldcourse->summaryformat
!= $course['summaryformat'])) {
1062 require_capability('moodle/course:changesummary', $context);
1063 $course['summaryformat'] = external_validate_format($course['summaryformat']);
1066 // Check if user can change visibility.
1067 if (array_key_exists('visible', $course) && ($oldcourse->visible
!= $course['visible'])) {
1068 require_capability('moodle/course:visibility', $context);
1071 // Make sure lang is valid.
1072 if (array_key_exists('lang', $course) && ($oldcourse->lang
!= $course['lang'])) {
1073 require_capability('moodle/course:setforcedlanguage', $context);
1074 if (empty($availablelangs[$course['lang']])) {
1075 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
1079 // Make sure theme is valid.
1080 if (array_key_exists('forcetheme', $course)) {
1081 if (!empty($CFG->allowcoursethemes
)) {
1082 if (empty($availablethemes[$course['forcetheme']])) {
1083 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
1085 $course['theme'] = $course['forcetheme'];
1090 // Make sure completion is enabled before setting it.
1091 if (array_key_exists('enabledcompletion', $course) && !completion_info
::is_enabled_for_site()) {
1092 $course['enabledcompletion'] = 0;
1095 // Make sure maxbytes are less then CFG->maxbytes.
1096 if (array_key_exists('maxbytes', $course)) {
1097 // We allow updates back to 0 max bytes, a special value denoting the course uses the site limit.
1098 // Otherwise, either use the size specified, or cap at the max size for the course.
1099 if ($course['maxbytes'] != 0) {
1100 $course['maxbytes'] = get_max_upload_file_size($CFG->maxbytes
, $course['maxbytes']);
1104 if (!empty($course['courseformatoptions'])) {
1105 foreach ($course['courseformatoptions'] as $option) {
1106 if (isset($option['name']) && isset($option['value'])) {
1107 $course[$option['name']] = $option['value'];
1112 // Prepare list of custom fields.
1113 if (isset($course['customfields'])) {
1114 foreach ($course['customfields'] as $field) {
1115 $course['customfield_' . $field['shortname']] = $field['value'];
1119 // Update course if user has all required capabilities.
1120 update_course((object) $course);
1121 } catch (Exception
$e) {
1123 $warning['item'] = 'course';
1124 $warning['itemid'] = $course['id'];
1125 if ($e instanceof moodle_exception
) {
1126 $warning['warningcode'] = $e->errorcode
;
1128 $warning['warningcode'] = $e->getCode();
1130 $warning['message'] = $e->getMessage();
1131 $warnings[] = $warning;
1136 $result['warnings'] = $warnings;
1141 * Returns description of method result value
1143 * @return external_description
1146 public static function update_courses_returns() {
1147 return new external_single_structure(
1149 'warnings' => new external_warnings()
1155 * Returns description of method parameters
1157 * @return external_function_parameters
1160 public static function delete_courses_parameters() {
1161 return new external_function_parameters(
1163 'courseids' => new external_multiple_structure(new external_value(PARAM_INT
, 'course ID')),
1171 * @param array $courseids A list of course ids
1174 public static function delete_courses($courseids) {
1176 require_once($CFG->dirroot
."/course/lib.php");
1178 // Parameter validation.
1179 $params = self
::validate_parameters(self
::delete_courses_parameters(), array('courseids'=>$courseids));
1181 $warnings = array();
1183 foreach ($params['courseids'] as $courseid) {
1184 $course = $DB->get_record('course', array('id' => $courseid));
1186 if ($course === false) {
1187 $warnings[] = array(
1189 'itemid' => $courseid,
1190 'warningcode' => 'unknowncourseidnumber',
1191 'message' => 'Unknown course ID ' . $courseid
1196 // Check if the context is valid.
1197 $coursecontext = context_course
::instance($course->id
);
1198 self
::validate_context($coursecontext);
1200 // Check if the current user has permission.
1201 if (!can_delete_course($courseid)) {
1202 $warnings[] = array(
1204 'itemid' => $courseid,
1205 'warningcode' => 'cannotdeletecourse',
1206 'message' => 'You do not have the permission to delete this course' . $courseid
1211 if (delete_course($course, false) === false) {
1212 $warnings[] = array(
1214 'itemid' => $courseid,
1215 'warningcode' => 'cannotdeletecategorycourse',
1216 'message' => 'Course ' . $courseid . ' failed to be deleted'
1222 fix_course_sortorder();
1224 return array('warnings' => $warnings);
1228 * Returns description of method result value
1230 * @return external_description
1233 public static function delete_courses_returns() {
1234 return new external_single_structure(
1236 'warnings' => new external_warnings()
1242 * Returns description of method parameters
1244 * @return external_function_parameters
1247 public static function duplicate_course_parameters() {
1248 return new external_function_parameters(
1250 'courseid' => new external_value(PARAM_INT
, 'course to duplicate id'),
1251 'fullname' => new external_value(PARAM_TEXT
, 'duplicated course full name'),
1252 'shortname' => new external_value(PARAM_TEXT
, 'duplicated course short name'),
1253 'categoryid' => new external_value(PARAM_INT
, 'duplicated course category parent'),
1254 'visible' => new external_value(PARAM_INT
, 'duplicated course visible, default to yes', VALUE_DEFAULT
, 1),
1255 'options' => new external_multiple_structure(
1256 new external_single_structure(
1258 'name' => new external_value(PARAM_ALPHAEXT
, 'The backup option name:
1259 "activities" (int) Include course activites (default to 1 that is equal to yes),
1260 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1261 "filters" (int) Include course filters (default to 1 that is equal to yes),
1262 "users" (int) Include users (default to 0 that is equal to no),
1263 "enrolments" (int) Include enrolment methods (default to 1 - restore only with users),
1264 "role_assignments" (int) Include role assignments (default to 0 that is equal to no),
1265 "comments" (int) Include user comments (default to 0 that is equal to no),
1266 "userscompletion" (int) Include user course completion information (default to 0 that is equal to no),
1267 "logs" (int) Include course logs (default to 0 that is equal to no),
1268 "grade_histories" (int) Include histories (default to 0 that is equal to no)'
1270 'value' => new external_value(PARAM_RAW
, 'the value for the option 1 (yes) or 0 (no)'
1273 ), VALUE_DEFAULT
, array()
1280 * Duplicate a course
1282 * @param int $courseid
1283 * @param string $fullname Duplicated course fullname
1284 * @param string $shortname Duplicated course shortname
1285 * @param int $categoryid Duplicated course parent category id
1286 * @param int $visible Duplicated course availability
1287 * @param array $options List of backup options
1288 * @return array New course info
1291 public static function duplicate_course($courseid, $fullname, $shortname, $categoryid, $visible = 1, $options = array()) {
1292 global $CFG, $USER, $DB;
1293 require_once($CFG->dirroot
. '/backup/util/includes/backup_includes.php');
1294 require_once($CFG->dirroot
. '/backup/util/includes/restore_includes.php');
1296 // Parameter validation.
1297 $params = self
::validate_parameters(
1298 self
::duplicate_course_parameters(),
1300 'courseid' => $courseid,
1301 'fullname' => $fullname,
1302 'shortname' => $shortname,
1303 'categoryid' => $categoryid,
1304 'visible' => $visible,
1305 'options' => $options
1309 // Context validation.
1311 if (! ($course = $DB->get_record('course', array('id'=>$params['courseid'])))) {
1312 throw new moodle_exception('invalidcourseid', 'error');
1315 // Category where duplicated course is going to be created.
1316 $categorycontext = context_coursecat
::instance($params['categoryid']);
1317 self
::validate_context($categorycontext);
1319 // Course to be duplicated.
1320 $coursecontext = context_course
::instance($course->id
);
1321 self
::validate_context($coursecontext);
1323 $backupdefaults = array(
1328 'enrolments' => backup
::ENROL_WITHUSERS
,
1329 'role_assignments' => 0,
1331 'userscompletion' => 0,
1333 'grade_histories' => 0
1336 $backupsettings = array();
1337 // Check for backup and restore options.
1338 if (!empty($params['options'])) {
1339 foreach ($params['options'] as $option) {
1341 // Strict check for a correct value (allways 1 or 0, true or false).
1342 $value = clean_param($option['value'], PARAM_INT
);
1344 if ($value !== 0 and $value !== 1) {
1345 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1348 if (!isset($backupdefaults[$option['name']])) {
1349 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1352 $backupsettings[$option['name']] = $value;
1356 // Capability checking.
1358 // The backup controller check for this currently, this may be redundant.
1359 require_capability('moodle/course:create', $categorycontext);
1360 require_capability('moodle/restore:restorecourse', $categorycontext);
1361 require_capability('moodle/backup:backupcourse', $coursecontext);
1363 if (!empty($backupsettings['users'])) {
1364 require_capability('moodle/backup:userinfo', $coursecontext);
1365 require_capability('moodle/restore:userinfo', $categorycontext);
1368 // Check if the shortname is used.
1369 if ($foundcourses = $DB->get_records('course', array('shortname'=>$shortname))) {
1370 foreach ($foundcourses as $foundcourse) {
1371 $foundcoursenames[] = $foundcourse->fullname
;
1374 $foundcoursenamestring = implode(',', $foundcoursenames);
1375 throw new moodle_exception('shortnametaken', '', '', $foundcoursenamestring);
1378 // Backup the course.
1380 $bc = new backup_controller(backup
::TYPE_1COURSE
, $course->id
, backup
::FORMAT_MOODLE
,
1381 backup
::INTERACTIVE_NO
, backup
::MODE_SAMESITE
, $USER->id
);
1383 foreach ($backupsettings as $name => $value) {
1384 if ($setting = $bc->get_plan()->get_setting($name)) {
1385 $bc->get_plan()->get_setting($name)->set_value($value);
1389 $backupid = $bc->get_backupid();
1390 $backupbasepath = $bc->get_plan()->get_basepath();
1392 $bc->execute_plan();
1393 $results = $bc->get_results();
1394 $file = $results['backup_destination'];
1398 // Restore the backup immediately.
1400 // Check if we need to unzip the file because the backup temp dir does not contains backup files.
1401 if (!file_exists($backupbasepath . "/moodle_backup.xml")) {
1402 $file->extract_to_pathname(get_file_packer('application/vnd.moodle.backup'), $backupbasepath);
1405 // Create new course.
1406 $newcourseid = restore_dbops
::create_new_course($params['fullname'], $params['shortname'], $params['categoryid']);
1408 $rc = new restore_controller($backupid, $newcourseid,
1409 backup
::INTERACTIVE_NO
, backup
::MODE_SAMESITE
, $USER->id
, backup
::TARGET_NEW_COURSE
);
1411 foreach ($backupsettings as $name => $value) {
1412 $setting = $rc->get_plan()->get_setting($name);
1413 if ($setting->get_status() == backup_setting
::NOT_LOCKED
) {
1414 $setting->set_value($value);
1418 if (!$rc->execute_precheck()) {
1419 $precheckresults = $rc->get_precheck_results();
1420 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1421 if (empty($CFG->keeptempdirectoriesonbackup
)) {
1422 fulldelete($backupbasepath);
1427 foreach ($precheckresults['errors'] as $error) {
1428 $errorinfo .= $error;
1431 if (array_key_exists('warnings', $precheckresults)) {
1432 foreach ($precheckresults['warnings'] as $warning) {
1433 $errorinfo .= $warning;
1437 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1441 $rc->execute_plan();
1444 $course = $DB->get_record('course', array('id' => $newcourseid), '*', MUST_EXIST
);
1445 $course->fullname
= $params['fullname'];
1446 $course->shortname
= $params['shortname'];
1447 $course->visible
= $params['visible'];
1449 // Set shortname and fullname back.
1450 $DB->update_record('course', $course);
1452 if (empty($CFG->keeptempdirectoriesonbackup
)) {
1453 fulldelete($backupbasepath);
1456 // Delete the course backup file created by this WebService. Originally located in the course backups area.
1459 return array('id' => $course->id
, 'shortname' => $course->shortname
);
1463 * Returns description of method result value
1465 * @return external_description
1468 public static function duplicate_course_returns() {
1469 return new external_single_structure(
1471 'id' => new external_value(PARAM_INT
, 'course id'),
1472 'shortname' => new external_value(PARAM_TEXT
, 'short name'),
1478 * Returns description of method parameters for import_course
1480 * @return external_function_parameters
1483 public static function import_course_parameters() {
1484 return new external_function_parameters(
1486 'importfrom' => new external_value(PARAM_INT
, 'the id of the course we are importing from'),
1487 'importto' => new external_value(PARAM_INT
, 'the id of the course we are importing to'),
1488 'deletecontent' => new external_value(PARAM_INT
, 'whether to delete the course content where we are importing to (default to 0 = No)', VALUE_DEFAULT
, 0),
1489 'options' => new external_multiple_structure(
1490 new external_single_structure(
1492 'name' => new external_value(PARAM_ALPHA
, 'The backup option name:
1493 "activities" (int) Include course activites (default to 1 that is equal to yes),
1494 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1495 "filters" (int) Include course filters (default to 1 that is equal to yes)'
1497 'value' => new external_value(PARAM_RAW
, 'the value for the option 1 (yes) or 0 (no)'
1500 ), VALUE_DEFAULT
, array()
1509 * @param int $importfrom The id of the course we are importing from
1510 * @param int $importto The id of the course we are importing to
1511 * @param bool $deletecontent Whether to delete the course we are importing to content
1512 * @param array $options List of backup options
1516 public static function import_course($importfrom, $importto, $deletecontent = 0, $options = array()) {
1517 global $CFG, $USER, $DB;
1518 require_once($CFG->dirroot
. '/backup/util/includes/backup_includes.php');
1519 require_once($CFG->dirroot
. '/backup/util/includes/restore_includes.php');
1521 // Parameter validation.
1522 $params = self
::validate_parameters(
1523 self
::import_course_parameters(),
1525 'importfrom' => $importfrom,
1526 'importto' => $importto,
1527 'deletecontent' => $deletecontent,
1528 'options' => $options
1532 if ($params['deletecontent'] !== 0 and $params['deletecontent'] !== 1) {
1533 throw new moodle_exception('invalidextparam', 'webservice', '', $params['deletecontent']);
1536 // Context validation.
1538 if (! ($importfrom = $DB->get_record('course', array('id'=>$params['importfrom'])))) {
1539 throw new moodle_exception('invalidcourseid', 'error');
1542 if (! ($importto = $DB->get_record('course', array('id'=>$params['importto'])))) {
1543 throw new moodle_exception('invalidcourseid', 'error');
1546 $importfromcontext = context_course
::instance($importfrom->id
);
1547 self
::validate_context($importfromcontext);
1549 $importtocontext = context_course
::instance($importto->id
);
1550 self
::validate_context($importtocontext);
1552 $backupdefaults = array(
1558 $backupsettings = array();
1560 // Check for backup and restore options.
1561 if (!empty($params['options'])) {
1562 foreach ($params['options'] as $option) {
1564 // Strict check for a correct value (allways 1 or 0, true or false).
1565 $value = clean_param($option['value'], PARAM_INT
);
1567 if ($value !== 0 and $value !== 1) {
1568 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1571 if (!isset($backupdefaults[$option['name']])) {
1572 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1575 $backupsettings[$option['name']] = $value;
1579 // Capability checking.
1581 require_capability('moodle/backup:backuptargetimport', $importfromcontext);
1582 require_capability('moodle/restore:restoretargetimport', $importtocontext);
1584 $bc = new backup_controller(backup
::TYPE_1COURSE
, $importfrom->id
, backup
::FORMAT_MOODLE
,
1585 backup
::INTERACTIVE_NO
, backup
::MODE_IMPORT
, $USER->id
);
1587 foreach ($backupsettings as $name => $value) {
1588 $bc->get_plan()->get_setting($name)->set_value($value);
1591 $backupid = $bc->get_backupid();
1592 $backupbasepath = $bc->get_plan()->get_basepath();
1594 $bc->execute_plan();
1597 // Restore the backup immediately.
1599 // Check if we must delete the contents of the destination course.
1600 if ($params['deletecontent']) {
1601 $restoretarget = backup
::TARGET_EXISTING_DELETING
;
1603 $restoretarget = backup
::TARGET_EXISTING_ADDING
;
1606 $rc = new restore_controller($backupid, $importto->id
,
1607 backup
::INTERACTIVE_NO
, backup
::MODE_IMPORT
, $USER->id
, $restoretarget);
1609 foreach ($backupsettings as $name => $value) {
1610 $rc->get_plan()->get_setting($name)->set_value($value);
1613 if (!$rc->execute_precheck()) {
1614 $precheckresults = $rc->get_precheck_results();
1615 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1616 if (empty($CFG->keeptempdirectoriesonbackup
)) {
1617 fulldelete($backupbasepath);
1622 foreach ($precheckresults['errors'] as $error) {
1623 $errorinfo .= $error;
1626 if (array_key_exists('warnings', $precheckresults)) {
1627 foreach ($precheckresults['warnings'] as $warning) {
1628 $errorinfo .= $warning;
1632 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1635 if ($restoretarget == backup
::TARGET_EXISTING_DELETING
) {
1636 restore_dbops
::delete_course_content($importto->id
);
1640 $rc->execute_plan();
1643 if (empty($CFG->keeptempdirectoriesonbackup
)) {
1644 fulldelete($backupbasepath);
1651 * Returns description of method result value
1653 * @return external_description
1656 public static function import_course_returns() {
1661 * Returns description of method parameters
1663 * @return external_function_parameters
1666 public static function get_categories_parameters() {
1667 return new external_function_parameters(
1669 'criteria' => new external_multiple_structure(
1670 new external_single_structure(
1672 'key' => new external_value(PARAM_ALPHA
,
1673 'The category column to search, expected keys (value format) are:'.
1674 '"id" (int) the category id,'.
1675 '"ids" (string) category ids separated by commas,'.
1676 '"name" (string) the category name,'.
1677 '"parent" (int) the parent category id,'.
1678 '"idnumber" (string) category idnumber'.
1679 ' - user must have \'moodle/category:manage\' to search on idnumber,'.
1680 '"visible" (int) whether the returned categories must be visible or hidden. If the key is not passed,
1681 then the function return all categories that the user can see.'.
1682 ' - user must have \'moodle/category:manage\' or \'moodle/category:viewhiddencategories\' to search on visible,'.
1683 '"theme" (string) only return the categories having this theme'.
1684 ' - user must have \'moodle/category:manage\' to search on theme'),
1685 'value' => new external_value(PARAM_RAW
, 'the value to match')
1687 ), 'criteria', VALUE_DEFAULT
, array()
1689 'addsubcategories' => new external_value(PARAM_BOOL
, 'return the sub categories infos
1690 (1 - default) otherwise only the category info (0)', VALUE_DEFAULT
, 1)
1698 * @param array $criteria Criteria to match the results
1699 * @param booln $addsubcategories obtain only the category (false) or its subcategories (true - default)
1700 * @return array list of categories
1703 public static function get_categories($criteria = array(), $addsubcategories = true) {
1705 require_once($CFG->dirroot
. "/course/lib.php");
1707 // Validate parameters.
1708 $params = self
::validate_parameters(self
::get_categories_parameters(),
1709 array('criteria' => $criteria, 'addsubcategories' => $addsubcategories));
1711 // Retrieve the categories.
1712 $categories = array();
1713 if (!empty($params['criteria'])) {
1715 $conditions = array();
1717 foreach ($params['criteria'] as $crit) {
1718 $key = trim($crit['key']);
1720 // Trying to avoid duplicate keys.
1721 if (!isset($conditions[$key])) {
1723 $context = context_system
::instance();
1727 $value = clean_param($crit['value'], PARAM_INT
);
1728 $conditions[$key] = $value;
1729 $wheres[] = $key . " = :" . $key;
1733 $value = clean_param($crit['value'], PARAM_SEQUENCE
);
1734 $ids = explode(',', $value);
1735 list($sqlids, $paramids) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED
);
1736 $conditions = array_merge($conditions, $paramids);
1737 $wheres[] = 'id ' . $sqlids;
1741 if (has_capability('moodle/category:manage', $context)) {
1742 $value = clean_param($crit['value'], PARAM_RAW
);
1743 $conditions[$key] = $value;
1744 $wheres[] = $key . " = :" . $key;
1746 // We must throw an exception.
1747 // Otherwise the dev client would think no idnumber exists.
1748 throw new moodle_exception('criteriaerror',
1749 'webservice', '', null,
1750 'You don\'t have the permissions to search on the "idnumber" field.');
1755 $value = clean_param($crit['value'], PARAM_TEXT
);
1756 $conditions[$key] = $value;
1757 $wheres[] = $key . " = :" . $key;
1761 $value = clean_param($crit['value'], PARAM_INT
);
1762 $conditions[$key] = $value;
1763 $wheres[] = $key . " = :" . $key;
1767 if (has_capability('moodle/category:viewhiddencategories', $context)) {
1768 $value = clean_param($crit['value'], PARAM_INT
);
1769 $conditions[$key] = $value;
1770 $wheres[] = $key . " = :" . $key;
1772 throw new moodle_exception('criteriaerror',
1773 'webservice', '', null,
1774 'You don\'t have the permissions to search on the "visible" field.');
1779 if (has_capability('moodle/category:manage', $context)) {
1780 $value = clean_param($crit['value'], PARAM_THEME
);
1781 $conditions[$key] = $value;
1782 $wheres[] = $key . " = :" . $key;
1784 throw new moodle_exception('criteriaerror',
1785 'webservice', '', null,
1786 'You don\'t have the permissions to search on the "theme" field.');
1791 throw new moodle_exception('criteriaerror',
1792 'webservice', '', null,
1793 'You can not search on this criteria: ' . $key);
1798 if (!empty($wheres)) {
1799 $wheres = implode(" AND ", $wheres);
1801 $categories = $DB->get_records_select('course_categories', $wheres, $conditions);
1803 // Retrieve its sub subcategories (all levels).
1804 if ($categories and !empty($params['addsubcategories'])) {
1805 $newcategories = array();
1807 // Check if we required visible/theme checks.
1808 $additionalselect = '';
1809 $additionalparams = array();
1810 if (isset($conditions['visible'])) {
1811 $additionalselect .= ' AND visible = :visible';
1812 $additionalparams['visible'] = $conditions['visible'];
1814 if (isset($conditions['theme'])) {
1815 $additionalselect .= ' AND theme= :theme';
1816 $additionalparams['theme'] = $conditions['theme'];
1819 foreach ($categories as $category) {
1820 $sqlselect = $DB->sql_like('path', ':path') . $additionalselect;
1821 $sqlparams = array('path' => $category->path
.'/%') +
$additionalparams; // It will NOT include the specified category.
1822 $subcategories = $DB->get_records_select('course_categories', $sqlselect, $sqlparams);
1823 $newcategories = $newcategories +
$subcategories; // Both arrays have integer as keys.
1825 $categories = $categories +
$newcategories;
1830 // Retrieve all categories in the database.
1831 $categories = $DB->get_records('course_categories');
1834 // The not returned categories. key => category id, value => reason of exclusion.
1835 $excludedcats = array();
1837 // The returned categories.
1838 $categoriesinfo = array();
1840 // We need to sort the categories by path.
1841 // The parent cats need to be checked by the algo first.
1842 usort($categories, "core_course_external::compare_categories_by_path");
1844 foreach ($categories as $category) {
1846 // Check if the category is a child of an excluded category, if yes exclude it too (excluded => do not return).
1847 $parents = explode('/', $category->path
);
1848 unset($parents[0]); // First key is always empty because path start with / => /1/2/4.
1849 foreach ($parents as $parentid) {
1850 // Note: when the parent exclusion was due to the context,
1851 // the sub category could still be returned.
1852 if (isset($excludedcats[$parentid]) and $excludedcats[$parentid] != 'context') {
1853 $excludedcats[$category->id
] = 'parent';
1857 // Check the user can use the category context.
1858 $context = context_coursecat
::instance($category->id
);
1860 self
::validate_context($context);
1861 } catch (Exception
$e) {
1862 $excludedcats[$category->id
] = 'context';
1864 // If it was the requested category then throw an exception.
1865 if (isset($params['categoryid']) && $category->id
== $params['categoryid']) {
1866 $exceptionparam = new stdClass();
1867 $exceptionparam->message
= $e->getMessage();
1868 $exceptionparam->catid
= $category->id
;
1869 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
1873 // Return the category information.
1874 if (!isset($excludedcats[$category->id
])) {
1876 // Final check to see if the category is visible to the user.
1877 if (core_course_category
::can_view_category($category)) {
1879 $categoryinfo = array();
1880 $categoryinfo['id'] = $category->id
;
1881 $categoryinfo['name'] = external_format_string($category->name
, $context);
1882 list($categoryinfo['description'], $categoryinfo['descriptionformat']) =
1883 external_format_text($category->description
, $category->descriptionformat
,
1884 $context->id
, 'coursecat', 'description', null);
1885 $categoryinfo['parent'] = $category->parent
;
1886 $categoryinfo['sortorder'] = $category->sortorder
;
1887 $categoryinfo['coursecount'] = $category->coursecount
;
1888 $categoryinfo['depth'] = $category->depth
;
1889 $categoryinfo['path'] = $category->path
;
1891 // Some fields only returned for admin.
1892 if (has_capability('moodle/category:manage', $context)) {
1893 $categoryinfo['idnumber'] = $category->idnumber
;
1894 $categoryinfo['visible'] = $category->visible
;
1895 $categoryinfo['visibleold'] = $category->visibleold
;
1896 $categoryinfo['timemodified'] = $category->timemodified
;
1897 $categoryinfo['theme'] = clean_param($category->theme
, PARAM_THEME
);
1900 $categoriesinfo[] = $categoryinfo;
1902 $excludedcats[$category->id
] = 'visibility';
1907 // Sorting the resulting array so it looks a bit better for the client developer.
1908 usort($categoriesinfo, "core_course_external::compare_categories_by_sortorder");
1910 return $categoriesinfo;
1914 * Sort categories array by path
1915 * private function: only used by get_categories
1917 * @param array $category1
1918 * @param array $category2
1919 * @return int result of strcmp
1922 private static function compare_categories_by_path($category1, $category2) {
1923 return strcmp($category1->path
, $category2->path
);
1927 * Sort categories array by sortorder
1928 * private function: only used by get_categories
1930 * @param array $category1
1931 * @param array $category2
1932 * @return int result of strcmp
1935 private static function compare_categories_by_sortorder($category1, $category2) {
1936 return strcmp($category1['sortorder'], $category2['sortorder']);
1940 * Returns description of method result value
1942 * @return external_description
1945 public static function get_categories_returns() {
1946 return new external_multiple_structure(
1947 new external_single_structure(
1949 'id' => new external_value(PARAM_INT
, 'category id'),
1950 'name' => new external_value(PARAM_TEXT
, 'category name'),
1951 'idnumber' => new external_value(PARAM_RAW
, 'category id number', VALUE_OPTIONAL
),
1952 'description' => new external_value(PARAM_RAW
, 'category description'),
1953 'descriptionformat' => new external_format_value('description'),
1954 'parent' => new external_value(PARAM_INT
, 'parent category id'),
1955 'sortorder' => new external_value(PARAM_INT
, 'category sorting order'),
1956 'coursecount' => new external_value(PARAM_INT
, 'number of courses in this category'),
1957 'visible' => new external_value(PARAM_INT
, '1: available, 0:not available', VALUE_OPTIONAL
),
1958 'visibleold' => new external_value(PARAM_INT
, '1: available, 0:not available', VALUE_OPTIONAL
),
1959 'timemodified' => new external_value(PARAM_INT
, 'timestamp', VALUE_OPTIONAL
),
1960 'depth' => new external_value(PARAM_INT
, 'category depth'),
1961 'path' => new external_value(PARAM_TEXT
, 'category path'),
1962 'theme' => new external_value(PARAM_THEME
, 'category theme', VALUE_OPTIONAL
),
1963 ), 'List of categories'
1969 * Returns description of method parameters
1971 * @return external_function_parameters
1974 public static function create_categories_parameters() {
1975 return new external_function_parameters(
1977 'categories' => new external_multiple_structure(
1978 new external_single_structure(
1980 'name' => new external_value(PARAM_TEXT
, 'new category name'),
1981 'parent' => new external_value(PARAM_INT
,
1982 'the parent category id inside which the new category will be created
1983 - set to 0 for a root category',
1985 'idnumber' => new external_value(PARAM_RAW
,
1986 'the new category idnumber', VALUE_OPTIONAL
),
1987 'description' => new external_value(PARAM_RAW
,
1988 'the new category description', VALUE_OPTIONAL
),
1989 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT
),
1990 'theme' => new external_value(PARAM_THEME
,
1991 'the new category theme. This option must be enabled on moodle',
2003 * @param array $categories - see create_categories_parameters() for the array structure
2004 * @return array - see create_categories_returns() for the array structure
2007 public static function create_categories($categories) {
2010 $params = self
::validate_parameters(self
::create_categories_parameters(),
2011 array('categories' => $categories));
2013 $transaction = $DB->start_delegated_transaction();
2015 $createdcategories = array();
2016 foreach ($params['categories'] as $category) {
2017 if ($category['parent']) {
2018 if (!$DB->record_exists('course_categories', array('id' => $category['parent']))) {
2019 throw new moodle_exception('unknowcategory');
2021 $context = context_coursecat
::instance($category['parent']);
2023 $context = context_system
::instance();
2025 self
::validate_context($context);
2026 require_capability('moodle/category:manage', $context);
2028 // this will validate format and throw an exception if there are errors
2029 external_validate_format($category['descriptionformat']);
2031 $newcategory = core_course_category
::create($category);
2032 $context = context_coursecat
::instance($newcategory->id
);
2034 $createdcategories[] = array(
2035 'id' => $newcategory->id
,
2036 'name' => external_format_string($newcategory->name
, $context),
2040 $transaction->allow_commit();
2042 return $createdcategories;
2046 * Returns description of method parameters
2048 * @return external_function_parameters
2051 public static function create_categories_returns() {
2052 return new external_multiple_structure(
2053 new external_single_structure(
2055 'id' => new external_value(PARAM_INT
, 'new category id'),
2056 'name' => new external_value(PARAM_TEXT
, 'new category name'),
2063 * Returns description of method parameters
2065 * @return external_function_parameters
2068 public static function update_categories_parameters() {
2069 return new external_function_parameters(
2071 'categories' => new external_multiple_structure(
2072 new external_single_structure(
2074 'id' => new external_value(PARAM_INT
, 'course id'),
2075 'name' => new external_value(PARAM_TEXT
, 'category name', VALUE_OPTIONAL
),
2076 'idnumber' => new external_value(PARAM_RAW
, 'category id number', VALUE_OPTIONAL
),
2077 'parent' => new external_value(PARAM_INT
, 'parent category id', VALUE_OPTIONAL
),
2078 'description' => new external_value(PARAM_RAW
, 'category description', VALUE_OPTIONAL
),
2079 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT
),
2080 'theme' => new external_value(PARAM_THEME
,
2081 'the category theme. This option must be enabled on moodle', VALUE_OPTIONAL
),
2092 * @param array $categories The list of categories to update
2096 public static function update_categories($categories) {
2099 // Validate parameters.
2100 $params = self
::validate_parameters(self
::update_categories_parameters(), array('categories' => $categories));
2102 $transaction = $DB->start_delegated_transaction();
2104 foreach ($params['categories'] as $cat) {
2105 $category = core_course_category
::get($cat['id']);
2107 $categorycontext = context_coursecat
::instance($cat['id']);
2108 self
::validate_context($categorycontext);
2109 require_capability('moodle/category:manage', $categorycontext);
2111 // this will throw an exception if descriptionformat is not valid
2112 external_validate_format($cat['descriptionformat']);
2114 $category->update($cat);
2117 $transaction->allow_commit();
2121 * Returns description of method result value
2123 * @return external_description
2126 public static function update_categories_returns() {
2131 * Returns description of method parameters
2133 * @return external_function_parameters
2136 public static function delete_categories_parameters() {
2137 return new external_function_parameters(
2139 'categories' => new external_multiple_structure(
2140 new external_single_structure(
2142 'id' => new external_value(PARAM_INT
, 'category id to delete'),
2143 'newparent' => new external_value(PARAM_INT
,
2144 'the parent category to move the contents to, if specified', VALUE_OPTIONAL
),
2145 'recursive' => new external_value(PARAM_BOOL
, '1: recursively delete all contents inside this
2146 category, 0 (default): move contents to newparent or current parent category (except if parent is root)', VALUE_DEFAULT
, 0)
2157 * @param array $categories A list of category ids
2161 public static function delete_categories($categories) {
2163 require_once($CFG->dirroot
. "/course/lib.php");
2165 // Validate parameters.
2166 $params = self
::validate_parameters(self
::delete_categories_parameters(), array('categories' => $categories));
2168 $transaction = $DB->start_delegated_transaction();
2170 foreach ($params['categories'] as $category) {
2171 $deletecat = core_course_category
::get($category['id'], MUST_EXIST
);
2172 $context = context_coursecat
::instance($deletecat->id
);
2173 require_capability('moodle/category:manage', $context);
2174 self
::validate_context($context);
2175 self
::validate_context(get_category_or_system_context($deletecat->parent
));
2177 if ($category['recursive']) {
2178 // If recursive was specified, then we recursively delete the category's contents.
2179 if ($deletecat->can_delete_full()) {
2180 $deletecat->delete_full(false);
2182 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2185 // In this situation, we don't delete the category's contents, we either move it to newparent or parent.
2186 // If the parent is the root, moving is not supported (because a course must always be inside a category).
2187 // We must move to an existing category.
2188 if (!empty($category['newparent'])) {
2189 $newparentcat = core_course_category
::get($category['newparent']);
2191 $newparentcat = core_course_category
::get($deletecat->parent
);
2194 // This operation is not allowed. We must move contents to an existing category.
2195 if (!$newparentcat->id
) {
2196 throw new moodle_exception('movecatcontentstoroot');
2199 self
::validate_context(context_coursecat
::instance($newparentcat->id
));
2200 if ($deletecat->can_move_content_to($newparentcat->id
)) {
2201 $deletecat->delete_move($newparentcat->id
, false);
2203 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2208 $transaction->allow_commit();
2212 * Returns description of method parameters
2214 * @return external_function_parameters
2217 public static function delete_categories_returns() {
2222 * Describes the parameters for delete_modules.
2224 * @return external_function_parameters
2227 public static function delete_modules_parameters() {
2228 return new external_function_parameters (
2230 'cmids' => new external_multiple_structure(new external_value(PARAM_INT
, 'course module ID',
2231 VALUE_REQUIRED
, '', NULL_NOT_ALLOWED
), 'Array of course module IDs'),
2237 * Deletes a list of provided module instances.
2239 * @param array $cmids the course module ids
2242 public static function delete_modules($cmids) {
2245 // Require course file containing the course delete module function.
2246 require_once($CFG->dirroot
. "/course/lib.php");
2248 // Clean the parameters.
2249 $params = self
::validate_parameters(self
::delete_modules_parameters(), array('cmids' => $cmids));
2251 // Keep track of the course ids we have performed a capability check on to avoid repeating.
2252 $arrcourseschecked = array();
2254 foreach ($params['cmids'] as $cmid) {
2255 // Get the course module.
2256 $cm = $DB->get_record('course_modules', array('id' => $cmid), '*', MUST_EXIST
);
2258 // Check if we have not yet confirmed they have permission in this course.
2259 if (!in_array($cm->course
, $arrcourseschecked)) {
2260 // Ensure the current user has required permission in this course.
2261 $context = context_course
::instance($cm->course
);
2262 self
::validate_context($context);
2263 // Add to the array.
2264 $arrcourseschecked[] = $cm->course
;
2267 // Ensure they can delete this module.
2268 $modcontext = context_module
::instance($cm->id
);
2269 require_capability('moodle/course:manageactivities', $modcontext);
2271 // Delete the module.
2272 course_delete_module($cm->id
);
2277 * Describes the delete_modules return value.
2279 * @return external_single_structure
2282 public static function delete_modules_returns() {
2287 * Returns description of method parameters
2289 * @return external_function_parameters
2292 public static function view_course_parameters() {
2293 return new external_function_parameters(
2295 'courseid' => new external_value(PARAM_INT
, 'id of the course'),
2296 'sectionnumber' => new external_value(PARAM_INT
, 'section number', VALUE_DEFAULT
, 0)
2302 * Trigger the course viewed event.
2304 * @param int $courseid id of course
2305 * @param int $sectionnumber sectionnumber (0, 1, 2...)
2306 * @return array of warnings and status result
2308 * @throws moodle_exception
2310 public static function view_course($courseid, $sectionnumber = 0) {
2312 require_once($CFG->dirroot
. "/course/lib.php");
2314 $params = self
::validate_parameters(self
::view_course_parameters(),
2316 'courseid' => $courseid,
2317 'sectionnumber' => $sectionnumber
2320 $warnings = array();
2322 $course = get_course($params['courseid']);
2323 $context = context_course
::instance($course->id
);
2324 self
::validate_context($context);
2326 if (!empty($params['sectionnumber'])) {
2328 // Get section details and check it exists.
2329 $modinfo = get_fast_modinfo($course);
2330 $coursesection = $modinfo->get_section_info($params['sectionnumber'], MUST_EXIST
);
2332 // Check user is allowed to see it.
2333 if (!$coursesection->uservisible
) {
2334 require_capability('moodle/course:viewhiddensections', $context);
2338 course_view($context, $params['sectionnumber']);
2341 $result['status'] = true;
2342 $result['warnings'] = $warnings;
2347 * Returns description of method result value
2349 * @return external_description
2352 public static function view_course_returns() {
2353 return new external_single_structure(
2355 'status' => new external_value(PARAM_BOOL
, 'status: true if success'),
2356 'warnings' => new external_warnings()
2362 * Returns description of method parameters
2364 * @return external_function_parameters
2367 public static function search_courses_parameters() {
2368 return new external_function_parameters(
2370 'criterianame' => new external_value(PARAM_ALPHA
, 'criteria name
2371 (search, modulelist (only admins), blocklist (only admins), tagid)'),
2372 'criteriavalue' => new external_value(PARAM_RAW
, 'criteria value'),
2373 'page' => new external_value(PARAM_INT
, 'page number (0 based)', VALUE_DEFAULT
, 0),
2374 'perpage' => new external_value(PARAM_INT
, 'items per page', VALUE_DEFAULT
, 0),
2375 'requiredcapabilities' => new external_multiple_structure(
2376 new external_value(PARAM_CAPABILITY
, 'Capability string used to filter courses by permission'),
2377 'Optional list of required capabilities (used to filter the list)', VALUE_DEFAULT
, array()
2379 'limittoenrolled' => new external_value(PARAM_BOOL
, 'limit to enrolled courses', VALUE_DEFAULT
, 0),
2380 'onlywithcompletion' => new external_value(PARAM_BOOL
, 'limit to courses where completion is enabled',
2387 * Return the course information that is public (visible by every one)
2389 * @param core_course_list_element $course course in list object
2390 * @param stdClass $coursecontext course context object
2391 * @return array the course information
2394 protected static function get_course_public_information(core_course_list_element
$course, $coursecontext) {
2396 static $categoriescache = array();
2398 // Category information.
2399 if (!array_key_exists($course->category
, $categoriescache)) {
2400 $categoriescache[$course->category
] = core_course_category
::get($course->category
, IGNORE_MISSING
);
2402 $category = $categoriescache[$course->category
];
2404 // Retrieve course overview used files.
2406 foreach ($course->get_course_overviewfiles() as $file) {
2407 $fileurl = moodle_url
::make_webservice_pluginfile_url($file->get_contextid(), $file->get_component(),
2408 $file->get_filearea(), null, $file->get_filepath(),
2409 $file->get_filename())->out(false);
2411 'filename' => $file->get_filename(),
2412 'fileurl' => $fileurl,
2413 'filesize' => $file->get_filesize(),
2414 'filepath' => $file->get_filepath(),
2415 'mimetype' => $file->get_mimetype(),
2416 'timemodified' => $file->get_timemodified(),
2420 // Retrieve the course contacts,
2421 // we need here the users fullname since if we are not enrolled can be difficult to obtain them via other Web Services.
2422 $coursecontacts = array();
2423 foreach ($course->get_course_contacts() as $contact) {
2424 $coursecontacts[] = array(
2425 'id' => $contact['user']->id
,
2426 'fullname' => $contact['username'],
2427 'roles' => array_map(function($role){
2428 return array('id' => $role->id
, 'name' => $role->displayname
);
2429 }, $contact['roles']),
2430 'role' => array('id' => $contact['role']->id
, 'name' => $contact['role']->displayname
),
2431 'rolename' => $contact['rolename']
2435 // Allowed enrolment methods (maybe we can self-enrol).
2436 $enroltypes = array();
2437 $instances = enrol_get_instances($course->id
, true);
2438 foreach ($instances as $instance) {
2439 $enroltypes[] = $instance->enrol
;
2443 list($summary, $summaryformat) =
2444 external_format_text($course->summary
, $course->summaryformat
, $coursecontext->id
, 'course', 'summary', null);
2447 if (!empty($category)) {
2448 $categoryname = external_format_string($category->name
, $category->get_context());
2451 $displayname = get_course_display_name_for_list($course);
2452 $coursereturns = array();
2453 $coursereturns['id'] = $course->id
;
2454 $coursereturns['fullname'] = external_format_string($course->fullname
, $coursecontext->id
);
2455 $coursereturns['displayname'] = external_format_string($displayname, $coursecontext->id
);
2456 $coursereturns['shortname'] = external_format_string($course->shortname
, $coursecontext->id
);
2457 $coursereturns['categoryid'] = $course->category
;
2458 $coursereturns['categoryname'] = $categoryname;
2459 $coursereturns['summary'] = $summary;
2460 $coursereturns['summaryformat'] = $summaryformat;
2461 $coursereturns['summaryfiles'] = external_util
::get_area_files($coursecontext->id
, 'course', 'summary', false, false);
2462 $coursereturns['overviewfiles'] = $files;
2463 $coursereturns['contacts'] = $coursecontacts;
2464 $coursereturns['enrollmentmethods'] = $enroltypes;
2465 $coursereturns['sortorder'] = $course->sortorder
;
2467 $handler = core_course\customfield\course_handler
::create();
2468 if ($customfields = $handler->export_instance_data($course->id
)) {
2469 $coursereturns['customfields'] = [];
2470 foreach ($customfields as $data) {
2471 $coursereturns['customfields'][] = [
2472 'type' => $data->get_type(),
2473 'value' => $data->get_value(),
2474 'name' => $data->get_name(),
2475 'shortname' => $data->get_shortname()
2480 return $coursereturns;
2484 * Search courses following the specified criteria.
2486 * @param string $criterianame Criteria name (search, modulelist (only admins), blocklist (only admins), tagid)
2487 * @param string $criteriavalue Criteria value
2488 * @param int $page Page number (for pagination)
2489 * @param int $perpage Items per page
2490 * @param array $requiredcapabilities Optional list of required capabilities (used to filter the list).
2491 * @param int $limittoenrolled Limit to only enrolled courses
2492 * @param int onlywithcompletion Limit to only courses where completion is enabled
2493 * @return array of course objects and warnings
2495 * @throws moodle_exception
2497 public static function search_courses($criterianame,
2501 $requiredcapabilities=array(),
2503 $onlywithcompletion=0) {
2506 $warnings = array();
2508 $parameters = array(
2509 'criterianame' => $criterianame,
2510 'criteriavalue' => $criteriavalue,
2512 'perpage' => $perpage,
2513 'requiredcapabilities' => $requiredcapabilities,
2514 'limittoenrolled' => $limittoenrolled,
2515 'onlywithcompletion' => $onlywithcompletion
2517 $params = self
::validate_parameters(self
::search_courses_parameters(), $parameters);
2518 self
::validate_context(context_system
::instance());
2520 $allowedcriterianames = array('search', 'modulelist', 'blocklist', 'tagid');
2521 if (!in_array($params['criterianame'], $allowedcriterianames)) {
2522 throw new invalid_parameter_exception('Invalid value for criterianame parameter (value: '.$params['criterianame'].'),' .
2523 'allowed values are: '.implode(',', $allowedcriterianames));
2526 if ($params['criterianame'] == 'modulelist' or $params['criterianame'] == 'blocklist') {
2527 require_capability('moodle/site:config', context_system
::instance());
2531 'search' => PARAM_RAW
,
2532 'modulelist' => PARAM_PLUGIN
,
2533 'blocklist' => PARAM_INT
,
2534 'tagid' => PARAM_INT
2536 $params['criteriavalue'] = clean_param($params['criteriavalue'], $paramtype[$params['criterianame']]);
2538 // Prepare the search API options.
2539 $searchcriteria = array();
2540 $searchcriteria[$params['criterianame']] = $params['criteriavalue'];
2541 if ($params['onlywithcompletion']) {
2542 $searchcriteria['onlywithcompletion'] = true;
2546 if ($params['perpage'] != 0) {
2547 $offset = $params['page'] * $params['perpage'];
2548 $options = array('offset' => $offset, 'limit' => $params['perpage']);
2551 // Search the courses.
2552 $courses = core_course_category
::search_courses($searchcriteria, $options, $params['requiredcapabilities']);
2553 $totalcount = core_course_category
::search_courses_count($searchcriteria, $options, $params['requiredcapabilities']);
2555 if (!empty($limittoenrolled)) {
2556 // Get the courses where the current user has access.
2557 $enrolled = enrol_get_my_courses(array('id', 'cacherev'));
2560 $finalcourses = array();
2561 $categoriescache = array();
2563 foreach ($courses as $course) {
2564 if (!empty($limittoenrolled)) {
2565 // Filter out not enrolled courses.
2566 if (!isset($enrolled[$course->id
])) {
2572 $coursecontext = context_course
::instance($course->id
);
2574 $finalcourses[] = self
::get_course_public_information($course, $coursecontext);
2578 'total' => $totalcount,
2579 'courses' => $finalcourses,
2580 'warnings' => $warnings
2585 * Returns a course structure definition
2587 * @param boolean $onlypublicdata set to true, to retrieve only fields viewable by anyone when the course is visible
2588 * @return array the course structure
2591 protected static function get_course_structure($onlypublicdata = true) {
2592 $coursestructure = array(
2593 'id' => new external_value(PARAM_INT
, 'course id'),
2594 'fullname' => new external_value(PARAM_TEXT
, 'course full name'),
2595 'displayname' => new external_value(PARAM_TEXT
, 'course display name'),
2596 'shortname' => new external_value(PARAM_TEXT
, 'course short name'),
2597 'categoryid' => new external_value(PARAM_INT
, 'category id'),
2598 'categoryname' => new external_value(PARAM_TEXT
, 'category name'),
2599 'sortorder' => new external_value(PARAM_INT
, 'Sort order in the category', VALUE_OPTIONAL
),
2600 'summary' => new external_value(PARAM_RAW
, 'summary'),
2601 'summaryformat' => new external_format_value('summary'),
2602 'summaryfiles' => new external_files('summary files in the summary field', VALUE_OPTIONAL
),
2603 'overviewfiles' => new external_files('additional overview files attached to this course'),
2604 'contacts' => new external_multiple_structure(
2605 new external_single_structure(
2607 'id' => new external_value(PARAM_INT
, 'contact user id'),
2608 'fullname' => new external_value(PARAM_NOTAGS
, 'contact user fullname'),
2613 'enrollmentmethods' => new external_multiple_structure(
2614 new external_value(PARAM_PLUGIN
, 'enrollment method'),
2615 'enrollment methods list'
2617 'customfields' => new external_multiple_structure(
2618 new external_single_structure(
2620 'name' => new external_value(PARAM_RAW
, 'The name of the custom field'),
2621 'shortname' => new external_value(PARAM_RAW
,
2622 'The shortname of the custom field - to be able to build the field class in the code'),
2623 'type' => new external_value(PARAM_ALPHANUMEXT
,
2624 'The type of the custom field - text field, checkbox...'),
2625 'value' => new external_value(PARAM_RAW
, 'The value of the custom field'),
2627 ), 'Custom fields', VALUE_OPTIONAL
),
2630 if (!$onlypublicdata) {
2632 'idnumber' => new external_value(PARAM_RAW
, 'Id number', VALUE_OPTIONAL
),
2633 'format' => new external_value(PARAM_PLUGIN
, 'Course format: weeks, topics, social, site,..', VALUE_OPTIONAL
),
2634 'showgrades' => new external_value(PARAM_INT
, '1 if grades are shown, otherwise 0', VALUE_OPTIONAL
),
2635 'newsitems' => new external_value(PARAM_INT
, 'Number of recent items appearing on the course page', VALUE_OPTIONAL
),
2636 'startdate' => new external_value(PARAM_INT
, 'Timestamp when the course start', VALUE_OPTIONAL
),
2637 'enddate' => new external_value(PARAM_INT
, 'Timestamp when the course end', VALUE_OPTIONAL
),
2638 'maxbytes' => new external_value(PARAM_INT
, 'Largest size of file that can be uploaded into', VALUE_OPTIONAL
),
2639 'showreports' => new external_value(PARAM_INT
, 'Are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL
),
2640 'visible' => new external_value(PARAM_INT
, '1: available to student, 0:not available', VALUE_OPTIONAL
),
2641 'groupmode' => new external_value(PARAM_INT
, 'no group, separate, visible', VALUE_OPTIONAL
),
2642 'groupmodeforce' => new external_value(PARAM_INT
, '1: yes, 0: no', VALUE_OPTIONAL
),
2643 'defaultgroupingid' => new external_value(PARAM_INT
, 'default grouping id', VALUE_OPTIONAL
),
2644 'enablecompletion' => new external_value(PARAM_INT
, 'Completion enabled? 1: yes 0: no', VALUE_OPTIONAL
),
2645 'completionnotify' => new external_value(PARAM_INT
, '1: yes 0: no', VALUE_OPTIONAL
),
2646 'lang' => new external_value(PARAM_SAFEDIR
, 'Forced course language', VALUE_OPTIONAL
),
2647 'theme' => new external_value(PARAM_PLUGIN
, 'Fame of the forced theme', VALUE_OPTIONAL
),
2648 'marker' => new external_value(PARAM_INT
, 'Current course marker', VALUE_OPTIONAL
),
2649 'legacyfiles' => new external_value(PARAM_INT
, 'If legacy files are enabled', VALUE_OPTIONAL
),
2650 'calendartype' => new external_value(PARAM_PLUGIN
, 'Calendar type', VALUE_OPTIONAL
),
2651 'timecreated' => new external_value(PARAM_INT
, 'Time when the course was created', VALUE_OPTIONAL
),
2652 'timemodified' => new external_value(PARAM_INT
, 'Last time the course was updated', VALUE_OPTIONAL
),
2653 'requested' => new external_value(PARAM_INT
, 'If is a requested course', VALUE_OPTIONAL
),
2654 'cacherev' => new external_value(PARAM_INT
, 'Cache revision number', VALUE_OPTIONAL
),
2655 'filters' => new external_multiple_structure(
2656 new external_single_structure(
2658 'filter' => new external_value(PARAM_PLUGIN
, 'Filter plugin name'),
2659 'localstate' => new external_value(PARAM_INT
, 'Filter state: 1 for on, -1 for off, 0 if inherit'),
2660 'inheritedstate' => new external_value(PARAM_INT
, '1 or 0 to use when localstate is set to inherit'),
2663 'Course filters', VALUE_OPTIONAL
2665 'courseformatoptions' => new external_multiple_structure(
2666 new external_single_structure(
2668 'name' => new external_value(PARAM_RAW
, 'Course format option name.'),
2669 'value' => new external_value(PARAM_RAW
, 'Course format option value.'),
2672 'Additional options for particular course format.', VALUE_OPTIONAL
2675 $coursestructure = array_merge($coursestructure, $extra);
2677 return new external_single_structure($coursestructure);
2681 * Returns description of method result value
2683 * @return external_description
2686 public static function search_courses_returns() {
2687 return new external_single_structure(
2689 'total' => new external_value(PARAM_INT
, 'total course count'),
2690 'courses' => new external_multiple_structure(self
::get_course_structure(), 'course'),
2691 'warnings' => new external_warnings()
2697 * Returns description of method parameters
2699 * @return external_function_parameters
2702 public static function get_course_module_parameters() {
2703 return new external_function_parameters(
2705 'cmid' => new external_value(PARAM_INT
, 'The course module id')
2711 * Return information about a course module.
2713 * @param int $cmid the course module id
2714 * @return array of warnings and the course module
2716 * @throws moodle_exception
2718 public static function get_course_module($cmid) {
2721 $params = self
::validate_parameters(self
::get_course_module_parameters(), array('cmid' => $cmid));
2722 $warnings = array();
2724 $cm = get_coursemodule_from_id(null, $params['cmid'], 0, true, MUST_EXIST
);
2725 $context = context_module
::instance($cm->id
);
2726 self
::validate_context($context);
2728 // If the user has permissions to manage the activity, return all the information.
2729 if (has_capability('moodle/course:manageactivities', $context)) {
2730 require_once($CFG->dirroot
. '/course/modlib.php');
2731 require_once($CFG->libdir
. '/gradelib.php');
2734 // Get the extra information: grade, advanced grading and outcomes data.
2735 $course = get_course($cm->course
);
2736 list($newcm, $newcontext, $module, $extrainfo, $cw) = get_moduleinfo_data($cm, $course);
2738 $gradeinfo = array('grade', 'gradepass', 'gradecat');
2739 foreach ($gradeinfo as $gfield) {
2740 if (isset($extrainfo->{$gfield})) {
2741 $info->{$gfield} = $extrainfo->{$gfield};
2744 if (isset($extrainfo->grade
) and $extrainfo->grade
< 0) {
2745 $info->scale
= $DB->get_field('scale', 'scale', array('id' => abs($extrainfo->grade
)));
2747 // Advanced grading.
2748 if (isset($extrainfo->_advancedgradingdata
)) {
2749 $info->advancedgrading
= array();
2750 foreach ($extrainfo as $key => $val) {
2751 if (strpos($key, 'advancedgradingmethod_') === 0) {
2752 $info->advancedgrading
[] = array(
2753 'area' => str_replace('advancedgradingmethod_', '', $key),
2760 foreach ($extrainfo as $key => $val) {
2761 if (strpos($key, 'outcome_') === 0) {
2762 if (!isset($info->outcomes
)) {
2763 $info->outcomes
= array();
2765 $id = str_replace('outcome_', '', $key);
2766 $outcome = grade_outcome
::fetch(array('id' => $id));
2767 $scaleitems = $outcome->load_scale();
2768 $info->outcomes
[] = array(
2770 'name' => external_format_string($outcome->get_name(), $context->id
),
2771 'scale' => $scaleitems->scale
2776 // Return information is safe to show to any user.
2777 $info = new stdClass();
2778 $info->id
= $cm->id
;
2779 $info->course
= $cm->course
;
2780 $info->module
= $cm->module
;
2781 $info->modname
= $cm->modname
;
2782 $info->instance
= $cm->instance
;
2783 $info->section
= $cm->section
;
2784 $info->sectionnum
= $cm->sectionnum
;
2785 $info->groupmode
= $cm->groupmode
;
2786 $info->groupingid
= $cm->groupingid
;
2787 $info->completion
= $cm->completion
;
2790 $info->name
= external_format_string($cm->name
, $context->id
);
2792 $result['cm'] = $info;
2793 $result['warnings'] = $warnings;
2798 * Returns description of method result value
2800 * @return external_description
2803 public static function get_course_module_returns() {
2804 return new external_single_structure(
2806 'cm' => new external_single_structure(
2808 'id' => new external_value(PARAM_INT
, 'The course module id'),
2809 'course' => new external_value(PARAM_INT
, 'The course id'),
2810 'module' => new external_value(PARAM_INT
, 'The module type id'),
2811 'name' => new external_value(PARAM_RAW
, 'The activity name'),
2812 'modname' => new external_value(PARAM_COMPONENT
, 'The module component name (forum, assign, etc..)'),
2813 'instance' => new external_value(PARAM_INT
, 'The activity instance id'),
2814 'section' => new external_value(PARAM_INT
, 'The module section id'),
2815 'sectionnum' => new external_value(PARAM_INT
, 'The module section number'),
2816 'groupmode' => new external_value(PARAM_INT
, 'Group mode'),
2817 'groupingid' => new external_value(PARAM_INT
, 'Grouping id'),
2818 'completion' => new external_value(PARAM_INT
, 'If completion is enabled'),
2819 'idnumber' => new external_value(PARAM_RAW
, 'Module id number', VALUE_OPTIONAL
),
2820 'added' => new external_value(PARAM_INT
, 'Time added', VALUE_OPTIONAL
),
2821 'score' => new external_value(PARAM_INT
, 'Score', VALUE_OPTIONAL
),
2822 'indent' => new external_value(PARAM_INT
, 'Indentation', VALUE_OPTIONAL
),
2823 'visible' => new external_value(PARAM_INT
, 'If visible', VALUE_OPTIONAL
),
2824 'visibleoncoursepage' => new external_value(PARAM_INT
, 'If visible on course page', VALUE_OPTIONAL
),
2825 'visibleold' => new external_value(PARAM_INT
, 'Visible old', VALUE_OPTIONAL
),
2826 'completiongradeitemnumber' => new external_value(PARAM_INT
, 'Completion grade item', VALUE_OPTIONAL
),
2827 'completionview' => new external_value(PARAM_INT
, 'Completion view setting', VALUE_OPTIONAL
),
2828 'completionexpected' => new external_value(PARAM_INT
, 'Completion time expected', VALUE_OPTIONAL
),
2829 'showdescription' => new external_value(PARAM_INT
, 'If the description is showed', VALUE_OPTIONAL
),
2830 'availability' => new external_value(PARAM_RAW
, 'Availability settings', VALUE_OPTIONAL
),
2831 'grade' => new external_value(PARAM_FLOAT
, 'Grade (max value or scale id)', VALUE_OPTIONAL
),
2832 'scale' => new external_value(PARAM_TEXT
, 'Scale items (if used)', VALUE_OPTIONAL
),
2833 'gradepass' => new external_value(PARAM_RAW
, 'Grade to pass (float)', VALUE_OPTIONAL
),
2834 'gradecat' => new external_value(PARAM_INT
, 'Grade category', VALUE_OPTIONAL
),
2835 'advancedgrading' => new external_multiple_structure(
2836 new external_single_structure(
2838 'area' => new external_value(PARAM_AREA
, 'Gradable area name'),
2839 'method' => new external_value(PARAM_COMPONENT
, 'Grading method'),
2842 'Advanced grading settings', VALUE_OPTIONAL
2844 'outcomes' => new external_multiple_structure(
2845 new external_single_structure(
2847 'id' => new external_value(PARAM_ALPHANUMEXT
, 'Outcome id'),
2848 'name' => new external_value(PARAM_TEXT
, 'Outcome full name'),
2849 'scale' => new external_value(PARAM_TEXT
, 'Scale items')
2852 'Outcomes information', VALUE_OPTIONAL
2856 'warnings' => new external_warnings()
2862 * Returns description of method parameters
2864 * @return external_function_parameters
2867 public static function get_course_module_by_instance_parameters() {
2868 return new external_function_parameters(
2870 'module' => new external_value(PARAM_COMPONENT
, 'The module name'),
2871 'instance' => new external_value(PARAM_INT
, 'The module instance id')
2877 * Return information about a course module.
2879 * @param string $module the module name
2880 * @param int $instance the activity instance id
2881 * @return array of warnings and the course module
2883 * @throws moodle_exception
2885 public static function get_course_module_by_instance($module, $instance) {
2887 $params = self
::validate_parameters(self
::get_course_module_by_instance_parameters(),
2889 'module' => $module,
2890 'instance' => $instance,
2893 $warnings = array();
2894 $cm = get_coursemodule_from_instance($params['module'], $params['instance'], 0, false, MUST_EXIST
);
2896 return self
::get_course_module($cm->id
);
2900 * Returns description of method result value
2902 * @return external_description
2905 public static function get_course_module_by_instance_returns() {
2906 return self
::get_course_module_returns();
2910 * Returns description of method parameters
2912 * @deprecated since 3.3
2913 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
2914 * @return external_function_parameters
2917 public static function get_activities_overview_parameters() {
2918 return new external_function_parameters(
2920 'courseids' => new external_multiple_structure(new external_value(PARAM_INT
, 'Course id.')),
2926 * Return activities overview for the given courses.
2928 * @deprecated since 3.3
2929 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
2930 * @param array $courseids a list of course ids
2931 * @return array of warnings and the activities overview
2933 * @throws moodle_exception
2935 public static function get_activities_overview($courseids) {
2938 // Parameter validation.
2939 $params = self
::validate_parameters(self
::get_activities_overview_parameters(), array('courseids' => $courseids));
2940 $courseoverviews = array();
2942 list($courses, $warnings) = external_util
::validate_courses($params['courseids']);
2944 if (!empty($courses)) {
2945 // Add lastaccess to each course (required by print_overview function).
2946 // We need the complete user data, the ws server does not load a complete one.
2947 $user = get_complete_user_data('id', $USER->id
);
2948 foreach ($courses as $course) {
2949 if (isset($user->lastcourseaccess
[$course->id
])) {
2950 $course->lastaccess
= $user->lastcourseaccess
[$course->id
];
2952 $course->lastaccess
= 0;
2956 $overviews = array();
2957 if ($modules = get_plugin_list_with_function('mod', 'print_overview')) {
2958 foreach ($modules as $fname) {
2959 $fname($courses, $overviews);
2964 foreach ($overviews as $courseid => $modules) {
2965 $courseoverviews[$courseid]['id'] = $courseid;
2966 $courseoverviews[$courseid]['overviews'] = array();
2968 foreach ($modules as $modname => $overviewtext) {
2969 $courseoverviews[$courseid]['overviews'][] = array(
2970 'module' => $modname,
2971 'overviewtext' => $overviewtext // This text doesn't need formatting.
2978 'courses' => $courseoverviews,
2979 'warnings' => $warnings
2985 * Returns description of method result value
2987 * @deprecated since 3.3
2988 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
2989 * @return external_description
2992 public static function get_activities_overview_returns() {
2993 return new external_single_structure(
2995 'courses' => new external_multiple_structure(
2996 new external_single_structure(
2998 'id' => new external_value(PARAM_INT
, 'Course id'),
2999 'overviews' => new external_multiple_structure(
3000 new external_single_structure(
3002 'module' => new external_value(PARAM_PLUGIN
, 'Module name'),
3003 'overviewtext' => new external_value(PARAM_RAW
, 'Overview text'),
3008 ), 'List of courses'
3010 'warnings' => new external_warnings()
3016 * Marking the method as deprecated.
3020 public static function get_activities_overview_is_deprecated() {
3025 * Returns description of method parameters
3027 * @return external_function_parameters
3030 public static function get_user_navigation_options_parameters() {
3031 return new external_function_parameters(
3033 'courseids' => new external_multiple_structure(new external_value(PARAM_INT
, 'Course id.')),
3039 * Return a list of navigation options in a set of courses that are avaialable or not for the current user.
3041 * @param array $courseids a list of course ids
3042 * @return array of warnings and the options availability
3044 * @throws moodle_exception
3046 public static function get_user_navigation_options($courseids) {
3048 require_once($CFG->dirroot
. '/course/lib.php');
3050 // Parameter validation.
3051 $params = self
::validate_parameters(self
::get_user_navigation_options_parameters(), array('courseids' => $courseids));
3052 $courseoptions = array();
3054 list($courses, $warnings) = external_util
::validate_courses($params['courseids'], array(), true);
3056 if (!empty($courses)) {
3057 foreach ($courses as $course) {
3058 // Fix the context for the frontpage.
3059 if ($course->id
== SITEID
) {
3060 $course->context
= context_system
::instance();
3062 $navoptions = course_get_user_navigation_options($course->context
, $course);
3064 foreach ($navoptions as $name => $available) {
3067 'available' => $available,
3071 $courseoptions[] = array(
3072 'id' => $course->id
,
3073 'options' => $options
3079 'courses' => $courseoptions,
3080 'warnings' => $warnings
3086 * Returns description of method result value
3088 * @return external_description
3091 public static function get_user_navigation_options_returns() {
3092 return new external_single_structure(
3094 'courses' => new external_multiple_structure(
3095 new external_single_structure(
3097 'id' => new external_value(PARAM_INT
, 'Course id'),
3098 'options' => new external_multiple_structure(
3099 new external_single_structure(
3101 'name' => new external_value(PARAM_ALPHANUMEXT
, 'Option name'),
3102 'available' => new external_value(PARAM_BOOL
, 'Whether the option is available or not'),
3107 ), 'List of courses'
3109 'warnings' => new external_warnings()
3115 * Returns description of method parameters
3117 * @return external_function_parameters
3120 public static function get_user_administration_options_parameters() {
3121 return new external_function_parameters(
3123 'courseids' => new external_multiple_structure(new external_value(PARAM_INT
, 'Course id.')),
3129 * Return a list of administration options in a set of courses that are available or not for the current user.
3131 * @param array $courseids a list of course ids
3132 * @return array of warnings and the options availability
3134 * @throws moodle_exception
3136 public static function get_user_administration_options($courseids) {
3138 require_once($CFG->dirroot
. '/course/lib.php');
3140 // Parameter validation.
3141 $params = self
::validate_parameters(self
::get_user_administration_options_parameters(), array('courseids' => $courseids));
3142 $courseoptions = array();
3144 list($courses, $warnings) = external_util
::validate_courses($params['courseids'], array(), true);
3146 if (!empty($courses)) {
3147 foreach ($courses as $course) {
3148 $adminoptions = course_get_user_administration_options($course, $course->context
);
3150 foreach ($adminoptions as $name => $available) {
3153 'available' => $available,
3157 $courseoptions[] = array(
3158 'id' => $course->id
,
3159 'options' => $options
3165 'courses' => $courseoptions,
3166 'warnings' => $warnings
3172 * Returns description of method result value
3174 * @return external_description
3177 public static function get_user_administration_options_returns() {
3178 return self
::get_user_navigation_options_returns();
3182 * Returns description of method parameters
3184 * @return external_function_parameters
3187 public static function get_courses_by_field_parameters() {
3188 return new external_function_parameters(
3190 'field' => new external_value(PARAM_ALPHA
, 'The field to search can be left empty for all courses or:
3192 ids: comma separated course ids
3193 shortname: course short name
3194 idnumber: course id number
3195 category: category id the course belongs to
3196 ', VALUE_DEFAULT
, ''),
3197 'value' => new external_value(PARAM_RAW
, 'The value to match', VALUE_DEFAULT
, '')
3204 * Get courses matching a specific field (id/s, shortname, idnumber, category)
3206 * @param string $field field name to search, or empty for all courses
3207 * @param string $value value to search
3208 * @return array list of courses and warnings
3209 * @throws invalid_parameter_exception
3212 public static function get_courses_by_field($field = '', $value = '') {
3214 require_once($CFG->dirroot
. '/course/lib.php');
3215 require_once($CFG->libdir
. '/filterlib.php');
3217 $params = self
::validate_parameters(self
::get_courses_by_field_parameters(),
3223 $warnings = array();
3225 if (empty($params['field'])) {
3226 $courses = $DB->get_records('course', null, 'id ASC');
3228 switch ($params['field']) {
3231 $value = clean_param($params['value'], PARAM_INT
);
3234 $value = clean_param($params['value'], PARAM_SEQUENCE
);
3237 $value = clean_param($params['value'], PARAM_TEXT
);
3240 $value = clean_param($params['value'], PARAM_RAW
);
3243 throw new invalid_parameter_exception('Invalid field name');
3246 if ($params['field'] === 'ids') {
3247 $courses = $DB->get_records_list('course', 'id', explode(',', $value), 'id ASC');
3249 $courses = $DB->get_records('course', array($params['field'] => $value), 'id ASC');
3253 $coursesdata = array();
3254 foreach ($courses as $course) {
3255 $context = context_course
::instance($course->id
);
3256 $canupdatecourse = has_capability('moodle/course:update', $context);
3257 $canviewhiddencourses = has_capability('moodle/course:viewhiddencourses', $context);
3259 // Check if the course is visible in the site for the user.
3260 if (!$course->visible
and !$canviewhiddencourses and !$canupdatecourse) {
3263 // Get the public course information, even if we are not enrolled.
3264 $courseinlist = new core_course_list_element($course);
3266 // Now, check if we have access to the course.
3268 self
::validate_context($context);
3269 } catch (Exception
$e) {
3270 // User can not access the course, check if they can see the public information about the course and return it.
3271 if (core_course_category
::can_view_course_info($course)) {
3272 $coursesdata[$course->id
] = self
::get_course_public_information($courseinlist, $context);
3276 $coursesdata[$course->id
] = self
::get_course_public_information($courseinlist, $context);
3277 // Return information for any user that can access the course.
3278 $coursefields = array('format', 'showgrades', 'newsitems', 'startdate', 'enddate', 'maxbytes', 'showreports', 'visible',
3279 'groupmode', 'groupmodeforce', 'defaultgroupingid', 'enablecompletion', 'completionnotify', 'lang', 'theme',
3283 $coursesdata[$course->id
]['filters'] = filter_get_available_in_context($context);
3285 // Information for managers only.
3286 if ($canupdatecourse) {
3287 $managerfields = array('idnumber', 'legacyfiles', 'calendartype', 'timecreated', 'timemodified', 'requested',
3289 $coursefields = array_merge($coursefields, $managerfields);
3293 foreach ($coursefields as $field) {
3294 $coursesdata[$course->id
][$field] = $course->{$field};
3297 // Clean lang and auth fields for external functions (it may content uninstalled themes or language packs).
3298 if (isset($coursesdata[$course->id
]['theme'])) {
3299 $coursesdata[$course->id
]['theme'] = clean_param($coursesdata[$course->id
]['theme'], PARAM_THEME
);
3301 if (isset($coursesdata[$course->id
]['lang'])) {
3302 $coursesdata[$course->id
]['lang'] = clean_param($coursesdata[$course->id
]['lang'], PARAM_LANG
);
3305 $courseformatoptions = course_get_format($course)->get_config_for_external();
3306 foreach ($courseformatoptions as $key => $value) {
3307 $coursesdata[$course->id
]['courseformatoptions'][] = array(
3315 'courses' => $coursesdata,
3316 'warnings' => $warnings
3321 * Returns description of method result value
3323 * @return external_description
3326 public static function get_courses_by_field_returns() {
3327 // Course structure, including not only public viewable fields.
3328 return new external_single_structure(
3330 'courses' => new external_multiple_structure(self
::get_course_structure(false), 'Course'),
3331 'warnings' => new external_warnings()
3337 * Returns description of method parameters
3339 * @return external_function_parameters
3342 public static function check_updates_parameters() {
3343 return new external_function_parameters(
3345 'courseid' => new external_value(PARAM_INT
, 'Course id to check'),
3346 'tocheck' => new external_multiple_structure(
3347 new external_single_structure(
3349 'contextlevel' => new external_value(PARAM_ALPHA
, 'The context level for the file location.
3350 Only module supported right now.'),
3351 'id' => new external_value(PARAM_INT
, 'Context instance id'),
3352 'since' => new external_value(PARAM_INT
, 'Check updates since this time stamp'),
3355 'Instances to check'
3357 'filter' => new external_multiple_structure(
3358 new external_value(PARAM_ALPHANUM
, 'Area name: configuration, fileareas, completion, ratings, comments,
3359 gradeitems, outcomes'),
3360 'Check only for updates in these areas', VALUE_DEFAULT
, array()
3367 * Check if there is updates affecting the user for the given course and contexts.
3368 * Right now only modules are supported.
3369 * This WS calls mod_check_updates_since for each module to check if there is any update the user should we aware of.
3371 * @param int $courseid the list of modules to check
3372 * @param array $tocheck the list of modules to check
3373 * @param array $filter check only for updates in these areas
3374 * @return array list of updates and warnings
3375 * @throws moodle_exception
3378 public static function check_updates($courseid, $tocheck, $filter = array()) {
3380 require_once($CFG->dirroot
. "/course/lib.php");
3382 $params = self
::validate_parameters(
3383 self
::check_updates_parameters(),
3385 'courseid' => $courseid,
3386 'tocheck' => $tocheck,
3387 'filter' => $filter,
3391 $course = get_course($params['courseid']);
3392 $context = context_course
::instance($course->id
);
3393 self
::validate_context($context);
3395 list($instances, $warnings) = course_check_updates($course, $params['tocheck'], $filter);
3397 $instancesformatted = array();
3398 foreach ($instances as $instance) {
3400 foreach ($instance['updates'] as $name => $data) {
3401 if (empty($data->updated
)) {
3404 $updatedata = array(
3407 if (!empty($data->timeupdated
)) {
3408 $updatedata['timeupdated'] = $data->timeupdated
;
3410 if (!empty($data->itemids
)) {
3411 $updatedata['itemids'] = $data->itemids
;
3413 $updates[] = $updatedata;
3415 if (!empty($updates)) {
3416 $instancesformatted[] = array(
3417 'contextlevel' => $instance['contextlevel'],
3418 'id' => $instance['id'],
3419 'updates' => $updates
3425 'instances' => $instancesformatted,
3426 'warnings' => $warnings
3431 * Returns description of method result value
3433 * @return external_description
3436 public static function check_updates_returns() {
3437 return new external_single_structure(
3439 'instances' => new external_multiple_structure(
3440 new external_single_structure(
3442 'contextlevel' => new external_value(PARAM_ALPHA
, 'The context level'),
3443 'id' => new external_value(PARAM_INT
, 'Instance id'),
3444 'updates' => new external_multiple_structure(
3445 new external_single_structure(
3447 'name' => new external_value(PARAM_ALPHANUMEXT
, 'Name of the area updated.'),
3448 'timeupdated' => new external_value(PARAM_INT
, 'Last time was updated', VALUE_OPTIONAL
),
3449 'itemids' => new external_multiple_structure(
3450 new external_value(PARAM_INT
, 'Instance id'),
3451 'The ids of the items updated',
3460 'warnings' => new external_warnings()
3466 * Returns description of method parameters
3468 * @return external_function_parameters
3471 public static function get_updates_since_parameters() {
3472 return new external_function_parameters(
3474 'courseid' => new external_value(PARAM_INT
, 'Course id to check'),
3475 'since' => new external_value(PARAM_INT
, 'Check updates since this time stamp'),
3476 'filter' => new external_multiple_structure(
3477 new external_value(PARAM_ALPHANUM
, 'Area name: configuration, fileareas, completion, ratings, comments,
3478 gradeitems, outcomes'),
3479 'Check only for updates in these areas', VALUE_DEFAULT
, array()
3486 * Check if there are updates affecting the user for the given course since the given time stamp.
3488 * This function is a wrapper of self::check_updates for retrieving all the updates since a given time for all the activities.
3490 * @param int $courseid the list of modules to check
3491 * @param int $since check updates since this time stamp
3492 * @param array $filter check only for updates in these areas
3493 * @return array list of updates and warnings
3494 * @throws moodle_exception
3497 public static function get_updates_since($courseid, $since, $filter = array()) {
3500 $params = self
::validate_parameters(
3501 self
::get_updates_since_parameters(),
3503 'courseid' => $courseid,
3505 'filter' => $filter,
3509 $course = get_course($params['courseid']);
3510 $modinfo = get_fast_modinfo($course);
3513 // Retrieve all the visible course modules for the current user.
3514 $cms = $modinfo->get_cms();
3515 foreach ($cms as $cm) {
3516 if (!$cm->uservisible
) {
3521 'contextlevel' => 'module',
3522 'since' => $params['since'],
3526 return self
::check_updates($course->id
, $tocheck, $params['filter']);
3530 * Returns description of method result value
3532 * @return external_description
3535 public static function get_updates_since_returns() {
3536 return self
::check_updates_returns();
3540 * Parameters for function edit_module()
3543 * @return external_function_parameters
3545 public static function edit_module_parameters() {
3546 return new external_function_parameters(
3548 'action' => new external_value(PARAM_ALPHA
,
3549 'action: hide, show, stealth, duplicate, delete, moveleft, moveright, group...', VALUE_REQUIRED
),
3550 'id' => new external_value(PARAM_INT
, 'course module id', VALUE_REQUIRED
),
3551 'sectionreturn' => new external_value(PARAM_INT
, 'section to return to', VALUE_DEFAULT
, null),
3556 * Performs one of the edit module actions and return new html for AJAX
3558 * Returns html to replace the current module html with, for example:
3559 * - empty string for "delete" action,
3560 * - two modules html for "duplicate" action
3561 * - updated module html for everything else
3563 * Throws exception if operation is not permitted/possible
3566 * @param string $action
3568 * @param null|int $sectionreturn
3571 public static function edit_module($action, $id, $sectionreturn = null) {
3573 // Validate and normalize parameters.
3574 $params = self
::validate_parameters(self
::edit_module_parameters(),
3575 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3576 $action = $params['action'];
3577 $id = $params['id'];
3578 $sectionreturn = $params['sectionreturn'];
3580 // Set of permissions an editing user may have.
3582 'moodle/course:update',
3583 'moodle/course:manageactivities',
3584 'moodle/course:activityvisibility',
3585 'moodle/course:sectionvisibility',
3586 'moodle/course:movesections',
3587 'moodle/course:setcurrentsection',
3589 $PAGE->set_other_editing_capability($contextarray);
3591 list($course, $cm) = get_course_and_cm_from_cmid($id);
3592 $modcontext = context_module
::instance($cm->id
);
3593 $coursecontext = context_course
::instance($course->id
);
3594 self
::validate_context($modcontext);
3595 $courserenderer = $PAGE->get_renderer('core', 'course');
3596 $completioninfo = new completion_info($course);
3602 require_capability('moodle/course:activityvisibility', $modcontext);
3603 $visible = ($action === 'hide') ?
0 : 1;
3604 $visibleoncoursepage = ($action === 'stealth') ?
0 : 1;
3605 set_coursemodule_visible($id, $visible, $visibleoncoursepage);
3606 \core\event\course_module_updated
::create_from_cm($cm, $modcontext)->trigger();
3609 require_capability('moodle/course:manageactivities', $coursecontext);
3610 require_capability('moodle/backup:backuptargetimport', $coursecontext);
3611 require_capability('moodle/restore:restoretargetimport', $coursecontext);
3612 if (!course_allowed_module($course, $cm->modname
)) {
3613 throw new moodle_exception('No permission to create that activity');
3615 if ($newcm = duplicate_module($course, $cm)) {
3616 $cm = get_fast_modinfo($course)->get_cm($id);
3617 $newcm = get_fast_modinfo($course)->get_cm($newcm->id
);
3618 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn) .
3619 $courserenderer->course_section_cm_list_item($course, $completioninfo, $newcm, $sectionreturn);
3622 case 'groupsseparate':
3623 case 'groupsvisible':
3625 require_capability('moodle/course:manageactivities', $modcontext);
3626 if ($action === 'groupsseparate') {
3627 $newgroupmode = SEPARATEGROUPS
;
3628 } else if ($action === 'groupsvisible') {
3629 $newgroupmode = VISIBLEGROUPS
;
3631 $newgroupmode = NOGROUPS
;
3633 if (set_coursemodule_groupmode($cm->id
, $newgroupmode)) {
3634 \core\event\course_module_updated
::create_from_cm($cm, $modcontext)->trigger();
3639 require_capability('moodle/course:manageactivities', $modcontext);
3640 $indent = $cm->indent +
(($action === 'moveright') ?
1 : -1);
3641 if ($cm->indent
>= 0) {
3642 $DB->update_record('course_modules', array('id' => $cm->id
, 'indent' => $indent));
3643 rebuild_course_cache($cm->course
);
3647 require_capability('moodle/course:manageactivities', $modcontext);
3648 course_delete_module($cm->id
, true);
3651 throw new coding_exception('Unrecognised action');
3654 $cm = get_fast_modinfo($course)->get_cm($id);
3655 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn);
3659 * Return structure for edit_module()
3662 * @return external_description
3664 public static function edit_module_returns() {
3665 return new external_value(PARAM_RAW
, 'html to replace the current module with');
3669 * Parameters for function get_module()
3672 * @return external_function_parameters
3674 public static function get_module_parameters() {
3675 return new external_function_parameters(
3677 'id' => new external_value(PARAM_INT
, 'course module id', VALUE_REQUIRED
),
3678 'sectionreturn' => new external_value(PARAM_INT
, 'section to return to', VALUE_DEFAULT
, null),
3683 * Returns html for displaying one activity module on course page
3687 * @param null|int $sectionreturn
3690 public static function get_module($id, $sectionreturn = null) {
3692 // Validate and normalize parameters.
3693 $params = self
::validate_parameters(self
::get_module_parameters(),
3694 array('id' => $id, 'sectionreturn' => $sectionreturn));
3695 $id = $params['id'];
3696 $sectionreturn = $params['sectionreturn'];
3698 // Set of permissions an editing user may have.
3700 'moodle/course:update',
3701 'moodle/course:manageactivities',
3702 'moodle/course:activityvisibility',
3703 'moodle/course:sectionvisibility',
3704 'moodle/course:movesections',
3705 'moodle/course:setcurrentsection',
3707 $PAGE->set_other_editing_capability($contextarray);
3709 // Validate access to the course (note, this is html for the course view page, we don't validate access to the module).
3710 list($course, $cm) = get_course_and_cm_from_cmid($id);
3711 self
::validate_context(context_course
::instance($course->id
));
3713 $courserenderer = $PAGE->get_renderer('core', 'course');
3714 $completioninfo = new completion_info($course);
3715 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn);
3719 * Return structure for get_module()
3722 * @return external_description
3724 public static function get_module_returns() {
3725 return new external_value(PARAM_RAW
, 'html to replace the current module with');
3729 * Parameters for function edit_section()
3732 * @return external_function_parameters
3734 public static function edit_section_parameters() {
3735 return new external_function_parameters(
3737 'action' => new external_value(PARAM_ALPHA
, 'action: hide, show, stealth, setmarker, removemarker', VALUE_REQUIRED
),
3738 'id' => new external_value(PARAM_INT
, 'course section id', VALUE_REQUIRED
),
3739 'sectionreturn' => new external_value(PARAM_INT
, 'section to return to', VALUE_DEFAULT
, null),
3744 * Performs one of the edit section actions
3747 * @param string $action
3748 * @param int $id section id
3749 * @param int $sectionreturn section to return to
3752 public static function edit_section($action, $id, $sectionreturn) {
3754 // Validate and normalize parameters.
3755 $params = self
::validate_parameters(self
::edit_section_parameters(),
3756 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3757 $action = $params['action'];
3758 $id = $params['id'];
3759 $sr = $params['sectionreturn'];
3761 $section = $DB->get_record('course_sections', array('id' => $id), '*', MUST_EXIST
);
3762 $coursecontext = context_course
::instance($section->course
);
3763 self
::validate_context($coursecontext);
3765 $rv = course_get_format($section->course
)->section_action($section, $action, $sectionreturn);
3767 return json_encode($rv);
3774 * Return structure for edit_section()
3777 * @return external_description
3779 public static function edit_section_returns() {
3780 return new external_value(PARAM_RAW
, 'Additional data for javascript (JSON-encoded string)');
3784 * Returns description of method parameters
3786 * @return external_function_parameters
3788 public static function get_enrolled_courses_by_timeline_classification_parameters() {
3789 return new external_function_parameters(
3791 'classification' => new external_value(PARAM_ALPHA
, 'future, inprogress, or past'),
3792 'limit' => new external_value(PARAM_INT
, 'Result set limit', VALUE_DEFAULT
, 0),
3793 'offset' => new external_value(PARAM_INT
, 'Result set offset', VALUE_DEFAULT
, 0),
3794 'sort' => new external_value(PARAM_TEXT
, 'Sort string', VALUE_DEFAULT
, null)
3800 * Get courses matching the given timeline classification.
3802 * NOTE: The offset applies to the unfiltered full set of courses before the classification
3803 * filtering is done.
3805 * If the user is enrolled in 5 courses:
3806 * c1, c2, c3, c4, and c5
3807 * And c4 and c5 are 'future' courses
3809 * If a request comes in for future courses with an offset of 1 it will mean that
3810 * c1 is skipped (because the offset applies *before* the classification filtering)
3811 * and c4 and c5 will be return.
3813 * @param string $classification past, inprogress, or future
3814 * @param int $limit Result set limit
3815 * @param int $offset Offset the full course set before timeline classification is applied
3816 * @param string $sort SQL sort string for results
3817 * @return array list of courses and warnings
3818 * @throws invalid_parameter_exception
3820 public static function get_enrolled_courses_by_timeline_classification(
3821 string $classification,
3826 global $CFG, $PAGE, $USER;
3827 require_once($CFG->dirroot
. '/course/lib.php');
3829 $params = self
::validate_parameters(self
::get_enrolled_courses_by_timeline_classification_parameters(),
3831 'classification' => $classification,
3833 'offset' => $offset,
3838 $classification = $params['classification'];
3839 $limit = $params['limit'];
3840 $offset = $params['offset'];
3841 $sort = $params['sort'];
3843 switch($classification) {
3844 case COURSE_TIMELINE_ALL
:
3846 case COURSE_TIMELINE_PAST
:
3848 case COURSE_TIMELINE_INPROGRESS
:
3850 case COURSE_TIMELINE_FUTURE
:
3852 case COURSE_FAVOURITES
:
3854 case COURSE_TIMELINE_HIDDEN
:
3857 throw new invalid_parameter_exception('Invalid classification');
3860 self
::validate_context(context_user
::instance($USER->id
));
3862 $requiredproperties = course_summary_exporter
::define_properties();
3863 $fields = join(',', array_keys($requiredproperties));
3864 $hiddencourses = get_hidden_courses_on_timeline();
3867 // If the timeline requires the hidden courses then restrict the result to only $hiddencourses else exclude.
3868 if ($classification == COURSE_TIMELINE_HIDDEN
) {
3869 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields,
3870 COURSE_DB_QUERY_LIMIT
, $hiddencourses);
3872 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields,
3873 COURSE_DB_QUERY_LIMIT
, [], $hiddencourses);
3876 $favouritecourseids = [];
3877 $ufservice = \core_favourites\service_factory
::get_service_for_user_context(\context_user
::instance($USER->id
));
3878 $favourites = $ufservice->find_favourites_by_type('core_course', 'courses');
3881 $favouritecourseids = array_map(
3882 function($favourite) {
3883 return $favourite->itemid
;
3887 if ($classification == COURSE_FAVOURITES
) {
3888 list($filteredcourses, $processedcount) = course_filter_courses_by_favourites(
3890 $favouritecourseids,
3894 list($filteredcourses, $processedcount) = course_filter_courses_by_timeline_classification(
3901 $renderer = $PAGE->get_renderer('core');
3902 $formattedcourses = array_map(function($course) use ($renderer, $favouritecourseids) {
3903 context_helper
::preload_from_record($course);
3904 $context = context_course
::instance($course->id
);
3905 $isfavourite = false;
3906 if (in_array($course->id
, $favouritecourseids)) {
3907 $isfavourite = true;
3909 $exporter = new course_summary_exporter($course, ['context' => $context, 'isfavourite' => $isfavourite]);
3910 return $exporter->export($renderer);
3911 }, $filteredcourses);
3914 'courses' => $formattedcourses,
3915 'nextoffset' => $offset +
$processedcount
3920 * Returns description of method result value
3922 * @return external_description
3924 public static function get_enrolled_courses_by_timeline_classification_returns() {
3925 return new external_single_structure(
3927 'courses' => new external_multiple_structure(course_summary_exporter
::get_read_structure(), 'Course'),
3928 'nextoffset' => new external_value(PARAM_INT
, 'Offset for the next request')
3934 * Returns description of method parameters
3936 * @return external_function_parameters
3938 public static function set_favourite_courses_parameters() {
3939 return new external_function_parameters(
3941 'courses' => new external_multiple_structure(
3942 new external_single_structure(
3944 'id' => new external_value(PARAM_INT
, 'course ID'),
3945 'favourite' => new external_value(PARAM_BOOL
, 'favourite status')
3954 * Set the course favourite status for an array of courses.
3956 * @param array $courses List with course id's and favourite status.
3957 * @return array Array with an array of favourite courses.
3959 public static function set_favourite_courses(
3964 $params = self
::validate_parameters(self
::set_favourite_courses_parameters(),
3966 'courses' => $courses
3972 $ufservice = \core_favourites\service_factory
::get_service_for_user_context(\context_user
::instance($USER->id
));
3974 foreach ($params['courses'] as $course) {
3978 $favouriteexists = $ufservice->favourite_exists('core_course', 'courses', $course['id'],
3979 \context_course
::instance($course['id']));
3981 if ($course['favourite']) {
3982 if (!$favouriteexists) {
3984 $ufservice->create_favourite('core_course', 'courses', $course['id'],
3985 \context_course
::instance($course['id']));
3986 } catch (Exception
$e) {
3987 $warning['courseid'] = $course['id'];
3988 if ($e instanceof moodle_exception
) {
3989 $warning['warningcode'] = $e->errorcode
;
3991 $warning['warningcode'] = $e->getCode();
3993 $warning['message'] = $e->getMessage();
3994 $warnings[] = $warning;
3995 $warnings[] = $warning;
3998 $warning['courseid'] = $course['id'];
3999 $warning['warningcode'] = 'coursealreadyfavourited';
4000 $warning['message'] = 'Course already favourited';
4001 $warnings[] = $warning;
4004 if ($favouriteexists) {
4006 $ufservice->delete_favourite('core_course', 'courses', $course['id'],
4007 \context_course
::instance($course['id']));
4008 } catch (Exception
$e) {
4009 $warning['courseid'] = $course['id'];
4010 if ($e instanceof moodle_exception
) {
4011 $warning['warningcode'] = $e->errorcode
;
4013 $warning['warningcode'] = $e->getCode();
4015 $warning['message'] = $e->getMessage();
4016 $warnings[] = $warning;
4017 $warnings[] = $warning;
4020 $warning['courseid'] = $course['id'];
4021 $warning['warningcode'] = 'cannotdeletefavourite';
4022 $warning['message'] = 'Could not delete favourite status for course';
4023 $warnings[] = $warning;
4029 'warnings' => $warnings
4034 * Returns description of method result value
4036 * @return external_description
4038 public static function set_favourite_courses_returns() {
4039 return new external_single_structure(
4041 'warnings' => new external_warnings()
4047 * Returns description of method parameters
4049 * @return external_function_parameters
4052 public static function get_recent_courses_parameters() {
4053 return new external_function_parameters(
4055 'userid' => new external_value(PARAM_INT
, 'id of the user, default to current user', VALUE_DEFAULT
, 0),
4056 'limit' => new external_value(PARAM_INT
, 'result set limit', VALUE_DEFAULT
, 0),
4057 'offset' => new external_value(PARAM_INT
, 'Result set offset', VALUE_DEFAULT
, 0),
4058 'sort' => new external_value(PARAM_TEXT
, 'Sort string', VALUE_DEFAULT
, null)
4064 * Get last accessed courses adding additional course information like images.
4066 * @param int $userid User id from which the courses will be obtained
4067 * @param int $limit Restrict result set to this amount
4068 * @param int $offset Skip this number of records from the start of the result set
4069 * @param string|null $sort SQL string for sorting
4070 * @return array List of courses
4071 * @throws invalid_parameter_exception
4073 public static function get_recent_courses(int $userid = 0, int $limit = 0, int $offset = 0, string $sort = null) {
4074 global $USER, $PAGE;
4076 if (empty($userid)) {
4077 $userid = $USER->id
;
4080 $params = self
::validate_parameters(self
::get_recent_courses_parameters(),
4082 'userid' => $userid,
4084 'offset' => $offset,
4089 $userid = $params['userid'];
4090 $limit = $params['limit'];
4091 $offset = $params['offset'];
4092 $sort = $params['sort'];
4094 $usercontext = context_user
::instance($userid);
4096 self
::validate_context($usercontext);
4098 if ($userid != $USER->id
and !has_capability('moodle/user:viewdetails', $usercontext)) {
4102 $courses = course_get_recent_courses($userid, $limit, $offset, $sort);
4104 $renderer = $PAGE->get_renderer('core');
4106 $recentcourses = array_map(function($course) use ($renderer) {
4107 context_helper
::preload_from_record($course);
4108 $context = context_course
::instance($course->id
);
4109 $isfavourite = !empty($course->component
);
4110 $exporter = new course_summary_exporter($course, ['context' => $context, 'isfavourite' => $isfavourite]);
4111 return $exporter->export($renderer);
4114 return $recentcourses;
4118 * Returns description of method result value
4120 * @return external_description
4123 public static function get_recent_courses_returns() {
4124 return new external_multiple_structure(course_summary_exporter
::get_read_structure(), 'Courses');