Merge branch 'MDL-68393-38-availableupdateui' of git://github.com/mudrd8mz/moodle...
[moodle.git] / course / externallib.php
blobb39acfe3a0f17fbe55938a2ea5e6895efdf0aec5
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * External course API
21 * @package core_course
22 * @category external
23 * @copyright 2009 Petr Skodak
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') || die;
29 use core_course\external\course_summary_exporter;
31 require_once("$CFG->libdir/externallib.php");
32 require_once("lib.php");
34 /**
35 * Course external functions
37 * @package core_course
38 * @category external
39 * @copyright 2011 Jerome Mouneyrac
40 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
41 * @since Moodle 2.2
43 class core_course_external extends external_api {
45 /**
46 * Returns description of method parameters
48 * @return external_function_parameters
49 * @since Moodle 2.9 Options available
50 * @since Moodle 2.2
52 public static function get_course_contents_parameters() {
53 return new external_function_parameters(
54 array('courseid' => new external_value(PARAM_INT, 'course id'),
55 'options' => new external_multiple_structure (
56 new external_single_structure(
57 array(
58 'name' => new external_value(PARAM_ALPHANUM,
59 'The expected keys (value format) are:
60 excludemodules (bool) Do not return modules, return only the sections structure
61 excludecontents (bool) Do not return module contents (i.e: files inside a resource)
62 includestealthmodules (bool) Return stealth modules for students in a special
63 section (with id -1)
64 sectionid (int) Return only this section
65 sectionnumber (int) Return only this section with number (order)
66 cmid (int) Return only this module information (among the whole sections structure)
67 modname (string) Return only modules with this name "label, forum, etc..."
68 modid (int) Return only the module with this id (to be used with modname'),
69 'value' => new external_value(PARAM_RAW, 'the value of the option,
70 this param is personaly validated in the external function.')
72 ), 'Options, used since Moodle 2.9', VALUE_DEFAULT, array())
77 /**
78 * Get course contents
80 * @param int $courseid course id
81 * @param array $options Options for filtering the results, used since Moodle 2.9
82 * @return array
83 * @since Moodle 2.9 Options available
84 * @since Moodle 2.2
86 public static function get_course_contents($courseid, $options = array()) {
87 global $CFG, $DB;
88 require_once($CFG->dirroot . "/course/lib.php");
89 require_once($CFG->libdir . '/completionlib.php');
91 //validate parameter
92 $params = self::validate_parameters(self::get_course_contents_parameters(),
93 array('courseid' => $courseid, 'options' => $options));
95 $filters = array();
96 if (!empty($params['options'])) {
98 foreach ($params['options'] as $option) {
99 $name = trim($option['name']);
100 // Avoid duplicated options.
101 if (!isset($filters[$name])) {
102 switch ($name) {
103 case 'excludemodules':
104 case 'excludecontents':
105 case 'includestealthmodules':
106 $value = clean_param($option['value'], PARAM_BOOL);
107 $filters[$name] = $value;
108 break;
109 case 'sectionid':
110 case 'sectionnumber':
111 case 'cmid':
112 case 'modid':
113 $value = clean_param($option['value'], PARAM_INT);
114 if (is_numeric($value)) {
115 $filters[$name] = $value;
116 } else {
117 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
119 break;
120 case 'modname':
121 $value = clean_param($option['value'], PARAM_PLUGIN);
122 if ($value) {
123 $filters[$name] = $value;
124 } else {
125 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
127 break;
128 default:
129 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
135 //retrieve the course
136 $course = $DB->get_record('course', array('id' => $params['courseid']), '*', MUST_EXIST);
138 if ($course->id != SITEID) {
139 // Check course format exist.
140 if (!file_exists($CFG->dirroot . '/course/format/' . $course->format . '/lib.php')) {
141 throw new moodle_exception('cannotgetcoursecontents', 'webservice', '', null,
142 get_string('courseformatnotfound', 'error', $course->format));
143 } else {
144 require_once($CFG->dirroot . '/course/format/' . $course->format . '/lib.php');
148 // now security checks
149 $context = context_course::instance($course->id, IGNORE_MISSING);
150 try {
151 self::validate_context($context);
152 } catch (Exception $e) {
153 $exceptionparam = new stdClass();
154 $exceptionparam->message = $e->getMessage();
155 $exceptionparam->courseid = $course->id;
156 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
159 $canupdatecourse = has_capability('moodle/course:update', $context);
161 //create return value
162 $coursecontents = array();
164 if ($canupdatecourse or $course->visible
165 or has_capability('moodle/course:viewhiddencourses', $context)) {
167 //retrieve sections
168 $modinfo = get_fast_modinfo($course);
169 $sections = $modinfo->get_section_info_all();
170 $coursenumsections = course_get_format($course)->get_last_section_number();
171 $stealthmodules = array(); // Array to keep all the modules available but not visible in a course section/topic.
173 $completioninfo = new completion_info($course);
175 //for each sections (first displayed to last displayed)
176 $modinfosections = $modinfo->get_sections();
177 foreach ($sections as $key => $section) {
179 // This becomes true when we are filtering and we found the value to filter with.
180 $sectionfound = false;
182 // Filter by section id.
183 if (!empty($filters['sectionid'])) {
184 if ($section->id != $filters['sectionid']) {
185 continue;
186 } else {
187 $sectionfound = true;
191 // Filter by section number. Note that 0 is a valid section number.
192 if (isset($filters['sectionnumber'])) {
193 if ($key != $filters['sectionnumber']) {
194 continue;
195 } else {
196 $sectionfound = true;
200 // reset $sectioncontents
201 $sectionvalues = array();
202 $sectionvalues['id'] = $section->id;
203 $sectionvalues['name'] = get_section_name($course, $section);
204 $sectionvalues['visible'] = $section->visible;
206 $options = (object) array('noclean' => true);
207 list($sectionvalues['summary'], $sectionvalues['summaryformat']) =
208 external_format_text($section->summary, $section->summaryformat,
209 $context->id, 'course', 'section', $section->id, $options);
210 $sectionvalues['section'] = $section->section;
211 $sectionvalues['hiddenbynumsections'] = $section->section > $coursenumsections ? 1 : 0;
212 $sectionvalues['uservisible'] = $section->uservisible;
213 if (!empty($section->availableinfo)) {
214 $sectionvalues['availabilityinfo'] = \core_availability\info::format_info($section->availableinfo, $course);
217 $sectioncontents = array();
219 // For each module of the section.
220 if (empty($filters['excludemodules']) and !empty($modinfosections[$section->section])) {
221 foreach ($modinfosections[$section->section] as $cmid) {
222 $cm = $modinfo->cms[$cmid];
224 // Stop here if the module is not visible to the user on the course main page:
225 // The user can't access the module and the user can't view the module on the course page.
226 if (!$cm->uservisible && !$cm->is_visible_on_course_page()) {
227 continue;
230 // This becomes true when we are filtering and we found the value to filter with.
231 $modfound = false;
233 // Filter by cmid.
234 if (!empty($filters['cmid'])) {
235 if ($cmid != $filters['cmid']) {
236 continue;
237 } else {
238 $modfound = true;
242 // Filter by module name and id.
243 if (!empty($filters['modname'])) {
244 if ($cm->modname != $filters['modname']) {
245 continue;
246 } else if (!empty($filters['modid'])) {
247 if ($cm->instance != $filters['modid']) {
248 continue;
249 } else {
250 // Note that if we are only filtering by modname we don't break the loop.
251 $modfound = true;
256 $module = array();
258 $modcontext = context_module::instance($cm->id);
260 //common info (for people being able to see the module or availability dates)
261 $module['id'] = $cm->id;
262 $module['name'] = external_format_string($cm->name, $modcontext->id);
263 $module['instance'] = $cm->instance;
264 $module['modname'] = (string) $cm->modname;
265 $module['modplural'] = (string) $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;
272 $module['noviewlink'] = plugin_supports('mod', $cm->modname, FEATURE_NO_VIEW_LINK, false);
274 // Check module completion.
275 $completion = $completioninfo->is_enabled($cm);
276 if ($completion != COMPLETION_DISABLED) {
277 $completiondata = $completioninfo->get_data($cm, true);
278 $module['completiondata'] = array(
279 'state' => $completiondata->completionstate,
280 'timecompleted' => $completiondata->timemodified,
281 'overrideby' => $completiondata->overrideby,
282 'valueused' => core_availability\info::completion_value_used($course, $cm->id)
286 if (!empty($cm->showdescription) or $module['noviewlink']) {
287 // We want to use the external format. However from reading get_formatted_content(), $cm->content format is always FORMAT_HTML.
288 $options = array('noclean' => true);
289 list($module['description'], $descriptionformat) = external_format_text($cm->content,
290 FORMAT_HTML, $modcontext->id, $cm->modname, 'intro', $cm->id, $options);
293 //url of the module
294 $url = $cm->url;
295 if ($url) { //labels don't have url
296 $module['url'] = $url->out(false);
299 $canviewhidden = has_capability('moodle/course:viewhiddenactivities',
300 context_module::instance($cm->id));
301 //user that can view hidden module should know about the visibility
302 $module['visible'] = $cm->visible;
303 $module['visibleoncoursepage'] = $cm->visibleoncoursepage;
304 $module['uservisible'] = $cm->uservisible;
305 if (!empty($cm->availableinfo)) {
306 $module['availabilityinfo'] = \core_availability\info::format_info($cm->availableinfo, $course);
309 // Availability date (also send to user who can see hidden module).
310 if ($CFG->enableavailability && ($canviewhidden || $canupdatecourse)) {
311 $module['availability'] = $cm->availability;
314 // Return contents only if the user can access to the module.
315 if ($cm->uservisible) {
316 $baseurl = 'webservice/pluginfile.php';
318 // Call $modulename_export_contents (each module callback take care about checking the capabilities).
319 require_once($CFG->dirroot . '/mod/' . $cm->modname . '/lib.php');
320 $getcontentfunction = $cm->modname.'_export_contents';
321 if (function_exists($getcontentfunction)) {
322 $contents = $getcontentfunction($cm, $baseurl);
323 $module['contentsinfo'] = array(
324 'filescount' => count($contents),
325 'filessize' => 0,
326 'lastmodified' => 0,
327 'mimetypes' => array(),
329 foreach ($contents as $content) {
330 // Check repository file (only main file).
331 if (!isset($module['contentsinfo']['repositorytype'])) {
332 $module['contentsinfo']['repositorytype'] =
333 isset($content['repositorytype']) ? $content['repositorytype'] : '';
335 if (isset($content['filesize'])) {
336 $module['contentsinfo']['filessize'] += $content['filesize'];
338 if (isset($content['timemodified']) &&
339 ($content['timemodified'] > $module['contentsinfo']['lastmodified'])) {
341 $module['contentsinfo']['lastmodified'] = $content['timemodified'];
343 if (isset($content['mimetype'])) {
344 $module['contentsinfo']['mimetypes'][$content['mimetype']] = $content['mimetype'];
348 if (empty($filters['excludecontents']) and !empty($contents)) {
349 $module['contents'] = $contents;
350 } else {
351 $module['contents'] = array();
356 // Assign result to $sectioncontents, there is an exception,
357 // stealth activities in non-visible sections for students go to a special section.
358 if (!empty($filters['includestealthmodules']) && !$section->uservisible && $cm->is_stealth()) {
359 $stealthmodules[] = $module;
360 } else {
361 $sectioncontents[] = $module;
364 // If we just did a filtering, break the loop.
365 if ($modfound) {
366 break;
371 $sectionvalues['modules'] = $sectioncontents;
373 // assign result to $coursecontents
374 $coursecontents[$key] = $sectionvalues;
376 // Break the loop if we are filtering.
377 if ($sectionfound) {
378 break;
382 // Now that we have iterated over all the sections and activities, check the visibility.
383 // We didn't this before to be able to retrieve stealth activities.
384 foreach ($coursecontents as $sectionnumber => $sectioncontents) {
385 $section = $sections[$sectionnumber];
386 // Show the section if the user is permitted to access it, OR if it's not available
387 // but there is some available info text which explains the reason & should display.
388 $showsection = $section->uservisible ||
389 ($section->visible && !$section->available &&
390 !empty($section->availableinfo));
392 if (!$showsection) {
393 unset($coursecontents[$sectionnumber]);
394 continue;
397 // Remove modules information if the section is not visible for the user.
398 if (!$section->uservisible) {
399 $coursecontents[$sectionnumber]['modules'] = array();
403 // Include stealth modules in special section (without any info).
404 if (!empty($stealthmodules)) {
405 $coursecontents[] = array(
406 'id' => -1,
407 'name' => '',
408 'summary' => '',
409 'summaryformat' => FORMAT_MOODLE,
410 'modules' => $stealthmodules
415 return $coursecontents;
419 * Returns description of method result value
421 * @return external_description
422 * @since Moodle 2.2
424 public static function get_course_contents_returns() {
425 return new external_multiple_structure(
426 new external_single_structure(
427 array(
428 'id' => new external_value(PARAM_INT, 'Section ID'),
429 'name' => new external_value(PARAM_TEXT, 'Section name'),
430 'visible' => new external_value(PARAM_INT, 'is the section visible', VALUE_OPTIONAL),
431 'summary' => new external_value(PARAM_RAW, 'Section description'),
432 'summaryformat' => new external_format_value('summary'),
433 'section' => new external_value(PARAM_INT, 'Section number inside the course', VALUE_OPTIONAL),
434 'hiddenbynumsections' => new external_value(PARAM_INT, 'Whether is a section hidden in the course format',
435 VALUE_OPTIONAL),
436 'uservisible' => new external_value(PARAM_BOOL, 'Is the section visible for the user?', VALUE_OPTIONAL),
437 'availabilityinfo' => new external_value(PARAM_RAW, 'Availability information.', VALUE_OPTIONAL),
438 'modules' => new external_multiple_structure(
439 new external_single_structure(
440 array(
441 'id' => new external_value(PARAM_INT, 'activity id'),
442 'url' => new external_value(PARAM_URL, 'activity url', VALUE_OPTIONAL),
443 'name' => new external_value(PARAM_RAW, 'activity module name'),
444 'instance' => new external_value(PARAM_INT, 'instance id', VALUE_OPTIONAL),
445 'description' => new external_value(PARAM_RAW, 'activity description', VALUE_OPTIONAL),
446 'visible' => new external_value(PARAM_INT, 'is the module visible', VALUE_OPTIONAL),
447 'uservisible' => new external_value(PARAM_BOOL, 'Is the module visible for the user?',
448 VALUE_OPTIONAL),
449 'availabilityinfo' => new external_value(PARAM_RAW, 'Availability information.',
450 VALUE_OPTIONAL),
451 'visibleoncoursepage' => new external_value(PARAM_INT, 'is the module visible on course page',
452 VALUE_OPTIONAL),
453 'modicon' => new external_value(PARAM_URL, 'activity icon url'),
454 'modname' => new external_value(PARAM_PLUGIN, 'activity module type'),
455 'modplural' => new external_value(PARAM_TEXT, 'activity module plural name'),
456 'availability' => new external_value(PARAM_RAW, 'module availability settings', VALUE_OPTIONAL),
457 'indent' => new external_value(PARAM_INT, 'number of identation in the site'),
458 'onclick' => new external_value(PARAM_RAW, 'Onclick action.', VALUE_OPTIONAL),
459 'afterlink' => new external_value(PARAM_RAW, 'After link info to be displayed.',
460 VALUE_OPTIONAL),
461 'customdata' => new external_value(PARAM_RAW, 'Custom data (JSON encoded).', VALUE_OPTIONAL),
462 'noviewlink' => new external_value(PARAM_BOOL, 'Whether the module has no view page',
463 VALUE_OPTIONAL),
464 'completion' => new external_value(PARAM_INT, 'Type of completion tracking:
465 0 means none, 1 manual, 2 automatic.', VALUE_OPTIONAL),
466 'completiondata' => new external_single_structure(
467 array(
468 'state' => new external_value(PARAM_INT, 'Completion state value:
469 0 means incomplete, 1 complete, 2 complete pass, 3 complete fail'),
470 'timecompleted' => new external_value(PARAM_INT, 'Timestamp for completion status.'),
471 'overrideby' => new external_value(PARAM_INT, 'The user id who has overriden the
472 status.'),
473 'valueused' => new external_value(PARAM_BOOL, 'Whether the completion status affects
474 the availability of another activity.', VALUE_OPTIONAL),
475 ), 'Module completion data.', VALUE_OPTIONAL
477 'contents' => new external_multiple_structure(
478 new external_single_structure(
479 array(
480 // content info
481 'type'=> new external_value(PARAM_TEXT, 'a file or a folder or external link'),
482 'filename'=> new external_value(PARAM_FILE, 'filename'),
483 'filepath'=> new external_value(PARAM_PATH, 'filepath'),
484 'filesize'=> new external_value(PARAM_INT, 'filesize'),
485 'fileurl' => new external_value(PARAM_URL, 'downloadable file url', VALUE_OPTIONAL),
486 'content' => new external_value(PARAM_RAW, 'Raw content, will be used when type is content', VALUE_OPTIONAL),
487 'timecreated' => new external_value(PARAM_INT, 'Time created'),
488 'timemodified' => new external_value(PARAM_INT, 'Time modified'),
489 'sortorder' => new external_value(PARAM_INT, 'Content sort order'),
490 'mimetype' => new external_value(PARAM_RAW, 'File mime type.', VALUE_OPTIONAL),
491 'isexternalfile' => new external_value(PARAM_BOOL, 'Whether is an external file.',
492 VALUE_OPTIONAL),
493 'repositorytype' => new external_value(PARAM_PLUGIN, 'The repository type for external files.',
494 VALUE_OPTIONAL),
496 // copyright related info
497 'userid' => new external_value(PARAM_INT, 'User who added this content to moodle'),
498 'author' => new external_value(PARAM_TEXT, 'Content owner'),
499 'license' => new external_value(PARAM_TEXT, 'Content license'),
500 'tags' => new external_multiple_structure(
501 \core_tag\external\tag_item_exporter::get_read_structure(), 'Tags',
502 VALUE_OPTIONAL
505 ), VALUE_DEFAULT, array()
507 'contentsinfo' => new external_single_structure(
508 array(
509 'filescount' => new external_value(PARAM_INT, 'Total number of files.'),
510 'filessize' => new external_value(PARAM_INT, 'Total files size.'),
511 'lastmodified' => new external_value(PARAM_INT, 'Last time files were modified.'),
512 'mimetypes' => new external_multiple_structure(
513 new external_value(PARAM_RAW, 'File mime type.'),
514 'Files mime types.'
516 'repositorytype' => new external_value(PARAM_PLUGIN, 'The repository type for
517 the main file.', VALUE_OPTIONAL),
518 ), 'Contents summary information.', VALUE_OPTIONAL
521 ), 'list of module'
529 * Returns description of method parameters
531 * @return external_function_parameters
532 * @since Moodle 2.3
534 public static function get_courses_parameters() {
535 return new external_function_parameters(
536 array('options' => new external_single_structure(
537 array('ids' => new external_multiple_structure(
538 new external_value(PARAM_INT, 'Course id')
539 , 'List of course id. If empty return all courses
540 except front page course.',
541 VALUE_OPTIONAL)
542 ), 'options - operator OR is used', VALUE_DEFAULT, array())
548 * Get courses
550 * @param array $options It contains an array (list of ids)
551 * @return array
552 * @since Moodle 2.2
554 public static function get_courses($options = array()) {
555 global $CFG, $DB;
556 require_once($CFG->dirroot . "/course/lib.php");
558 //validate parameter
559 $params = self::validate_parameters(self::get_courses_parameters(),
560 array('options' => $options));
562 //retrieve courses
563 if (!array_key_exists('ids', $params['options'])
564 or empty($params['options']['ids'])) {
565 $courses = $DB->get_records('course');
566 } else {
567 $courses = $DB->get_records_list('course', 'id', $params['options']['ids']);
570 //create return value
571 $coursesinfo = array();
572 foreach ($courses as $course) {
574 // now security checks
575 $context = context_course::instance($course->id, IGNORE_MISSING);
576 $courseformatoptions = course_get_format($course)->get_format_options();
577 try {
578 self::validate_context($context);
579 } catch (Exception $e) {
580 $exceptionparam = new stdClass();
581 $exceptionparam->message = $e->getMessage();
582 $exceptionparam->courseid = $course->id;
583 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
585 if ($course->id != SITEID) {
586 require_capability('moodle/course:view', $context);
589 $courseinfo = array();
590 $courseinfo['id'] = $course->id;
591 $courseinfo['fullname'] = external_format_string($course->fullname, $context->id);
592 $courseinfo['shortname'] = external_format_string($course->shortname, $context->id);
593 $courseinfo['displayname'] = external_format_string(get_course_display_name_for_list($course), $context->id);
594 $courseinfo['categoryid'] = $course->category;
595 list($courseinfo['summary'], $courseinfo['summaryformat']) =
596 external_format_text($course->summary, $course->summaryformat, $context->id, 'course', 'summary', 0);
597 $courseinfo['format'] = $course->format;
598 $courseinfo['startdate'] = $course->startdate;
599 $courseinfo['enddate'] = $course->enddate;
600 if (array_key_exists('numsections', $courseformatoptions)) {
601 // For backward-compartibility
602 $courseinfo['numsections'] = $courseformatoptions['numsections'];
605 $handler = core_course\customfield\course_handler::create();
606 if ($customfields = $handler->export_instance_data($course->id)) {
607 $courseinfo['customfields'] = [];
608 foreach ($customfields as $data) {
609 $courseinfo['customfields'][] = [
610 'type' => $data->get_type(),
611 'value' => $data->get_value(),
612 'name' => $data->get_name(),
613 'shortname' => $data->get_shortname()
618 //some field should be returned only if the user has update permission
619 $courseadmin = has_capability('moodle/course:update', $context);
620 if ($courseadmin) {
621 $courseinfo['categorysortorder'] = $course->sortorder;
622 $courseinfo['idnumber'] = $course->idnumber;
623 $courseinfo['showgrades'] = $course->showgrades;
624 $courseinfo['showreports'] = $course->showreports;
625 $courseinfo['newsitems'] = $course->newsitems;
626 $courseinfo['visible'] = $course->visible;
627 $courseinfo['maxbytes'] = $course->maxbytes;
628 if (array_key_exists('hiddensections', $courseformatoptions)) {
629 // For backward-compartibility
630 $courseinfo['hiddensections'] = $courseformatoptions['hiddensections'];
632 // Return numsections for backward-compatibility with clients who expect it.
633 $courseinfo['numsections'] = course_get_format($course)->get_last_section_number();
634 $courseinfo['groupmode'] = $course->groupmode;
635 $courseinfo['groupmodeforce'] = $course->groupmodeforce;
636 $courseinfo['defaultgroupingid'] = $course->defaultgroupingid;
637 $courseinfo['lang'] = clean_param($course->lang, PARAM_LANG);
638 $courseinfo['timecreated'] = $course->timecreated;
639 $courseinfo['timemodified'] = $course->timemodified;
640 $courseinfo['forcetheme'] = clean_param($course->theme, PARAM_THEME);
641 $courseinfo['enablecompletion'] = $course->enablecompletion;
642 $courseinfo['completionnotify'] = $course->completionnotify;
643 $courseinfo['courseformatoptions'] = array();
644 foreach ($courseformatoptions as $key => $value) {
645 $courseinfo['courseformatoptions'][] = array(
646 'name' => $key,
647 'value' => $value
652 if ($courseadmin or $course->visible
653 or has_capability('moodle/course:viewhiddencourses', $context)) {
654 $coursesinfo[] = $courseinfo;
658 return $coursesinfo;
662 * Returns description of method result value
664 * @return external_description
665 * @since Moodle 2.2
667 public static function get_courses_returns() {
668 return new external_multiple_structure(
669 new external_single_structure(
670 array(
671 'id' => new external_value(PARAM_INT, 'course id'),
672 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
673 'categoryid' => new external_value(PARAM_INT, 'category id'),
674 'categorysortorder' => new external_value(PARAM_INT,
675 'sort order into the category', VALUE_OPTIONAL),
676 'fullname' => new external_value(PARAM_TEXT, 'full name'),
677 'displayname' => new external_value(PARAM_TEXT, 'course display name'),
678 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
679 'summary' => new external_value(PARAM_RAW, 'summary'),
680 'summaryformat' => new external_format_value('summary'),
681 'format' => new external_value(PARAM_PLUGIN,
682 'course format: weeks, topics, social, site,..'),
683 'showgrades' => new external_value(PARAM_INT,
684 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
685 'newsitems' => new external_value(PARAM_INT,
686 'number of recent items appearing on the course page', VALUE_OPTIONAL),
687 'startdate' => new external_value(PARAM_INT,
688 'timestamp when the course start'),
689 'enddate' => new external_value(PARAM_INT,
690 'timestamp when the course end'),
691 'numsections' => new external_value(PARAM_INT,
692 '(deprecated, use courseformatoptions) number of weeks/topics',
693 VALUE_OPTIONAL),
694 'maxbytes' => new external_value(PARAM_INT,
695 'largest size of file that can be uploaded into the course',
696 VALUE_OPTIONAL),
697 'showreports' => new external_value(PARAM_INT,
698 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
699 'visible' => new external_value(PARAM_INT,
700 '1: available to student, 0:not available', VALUE_OPTIONAL),
701 'hiddensections' => new external_value(PARAM_INT,
702 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
703 VALUE_OPTIONAL),
704 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
705 VALUE_OPTIONAL),
706 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
707 VALUE_OPTIONAL),
708 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
709 VALUE_OPTIONAL),
710 'timecreated' => new external_value(PARAM_INT,
711 'timestamp when the course have been created', VALUE_OPTIONAL),
712 'timemodified' => new external_value(PARAM_INT,
713 'timestamp when the course have been modified', VALUE_OPTIONAL),
714 'enablecompletion' => new external_value(PARAM_INT,
715 'Enabled, control via completion and activity settings. Disbaled,
716 not shown in activity settings.',
717 VALUE_OPTIONAL),
718 'completionnotify' => new external_value(PARAM_INT,
719 '1: yes 0: no', VALUE_OPTIONAL),
720 'lang' => new external_value(PARAM_SAFEDIR,
721 'forced course language', VALUE_OPTIONAL),
722 'forcetheme' => new external_value(PARAM_PLUGIN,
723 'name of the force theme', VALUE_OPTIONAL),
724 'courseformatoptions' => new external_multiple_structure(
725 new external_single_structure(
726 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
727 'value' => new external_value(PARAM_RAW, 'course format option value')
728 )), 'additional options for particular course format', VALUE_OPTIONAL
730 'customfields' => new external_multiple_structure(
731 new external_single_structure(
732 ['name' => new external_value(PARAM_TEXT, 'The name of the custom field'),
733 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'The shortname of the custom field'),
734 'type' => new external_value(PARAM_COMPONENT,
735 'The type of the custom field - text, checkbox...'),
736 'value' => new external_value(PARAM_RAW, 'The value of the custom field')]
737 ), 'Custom fields and associated values', VALUE_OPTIONAL),
738 ), 'course'
744 * Returns description of method parameters
746 * @return external_function_parameters
747 * @since Moodle 2.2
749 public static function create_courses_parameters() {
750 $courseconfig = get_config('moodlecourse'); //needed for many default values
751 return new external_function_parameters(
752 array(
753 'courses' => new external_multiple_structure(
754 new external_single_structure(
755 array(
756 'fullname' => new external_value(PARAM_TEXT, 'full name'),
757 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
758 'categoryid' => new external_value(PARAM_INT, 'category id'),
759 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
760 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
761 'summaryformat' => new external_format_value('summary', VALUE_DEFAULT),
762 'format' => new external_value(PARAM_PLUGIN,
763 'course format: weeks, topics, social, site,..',
764 VALUE_DEFAULT, $courseconfig->format),
765 'showgrades' => new external_value(PARAM_INT,
766 '1 if grades are shown, otherwise 0', VALUE_DEFAULT,
767 $courseconfig->showgrades),
768 'newsitems' => new external_value(PARAM_INT,
769 'number of recent items appearing on the course page',
770 VALUE_DEFAULT, $courseconfig->newsitems),
771 'startdate' => new external_value(PARAM_INT,
772 'timestamp when the course start', VALUE_OPTIONAL),
773 'enddate' => new external_value(PARAM_INT,
774 'timestamp when the course end', VALUE_OPTIONAL),
775 'numsections' => new external_value(PARAM_INT,
776 '(deprecated, use courseformatoptions) number of weeks/topics',
777 VALUE_OPTIONAL),
778 'maxbytes' => new external_value(PARAM_INT,
779 'largest size of file that can be uploaded into the course',
780 VALUE_DEFAULT, $courseconfig->maxbytes),
781 'showreports' => new external_value(PARAM_INT,
782 'are activity report shown (yes = 1, no =0)', VALUE_DEFAULT,
783 $courseconfig->showreports),
784 'visible' => new external_value(PARAM_INT,
785 '1: available to student, 0:not available', VALUE_OPTIONAL),
786 'hiddensections' => new external_value(PARAM_INT,
787 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
788 VALUE_OPTIONAL),
789 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
790 VALUE_DEFAULT, $courseconfig->groupmode),
791 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
792 VALUE_DEFAULT, $courseconfig->groupmodeforce),
793 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
794 VALUE_DEFAULT, 0),
795 'enablecompletion' => new external_value(PARAM_INT,
796 'Enabled, control via completion and activity settings. Disabled,
797 not shown in activity settings.',
798 VALUE_OPTIONAL),
799 'completionnotify' => new external_value(PARAM_INT,
800 '1: yes 0: no', VALUE_OPTIONAL),
801 'lang' => new external_value(PARAM_SAFEDIR,
802 'forced course language', VALUE_OPTIONAL),
803 'forcetheme' => new external_value(PARAM_PLUGIN,
804 'name of the force theme', VALUE_OPTIONAL),
805 'courseformatoptions' => new external_multiple_structure(
806 new external_single_structure(
807 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
808 'value' => new external_value(PARAM_RAW, 'course format option value')
810 'additional options for particular course format', VALUE_OPTIONAL),
811 'customfields' => new external_multiple_structure(
812 new external_single_structure(
813 array(
814 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'The shortname of the custom field'),
815 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
816 )), 'custom fields for the course', VALUE_OPTIONAL
818 )), 'courses to create'
825 * Create courses
827 * @param array $courses
828 * @return array courses (id and shortname only)
829 * @since Moodle 2.2
831 public static function create_courses($courses) {
832 global $CFG, $DB;
833 require_once($CFG->dirroot . "/course/lib.php");
834 require_once($CFG->libdir . '/completionlib.php');
836 $params = self::validate_parameters(self::create_courses_parameters(),
837 array('courses' => $courses));
839 $availablethemes = core_component::get_plugin_list('theme');
840 $availablelangs = get_string_manager()->get_list_of_translations();
842 $transaction = $DB->start_delegated_transaction();
844 foreach ($params['courses'] as $course) {
846 // Ensure the current user is allowed to run this function
847 $context = context_coursecat::instance($course['categoryid'], IGNORE_MISSING);
848 try {
849 self::validate_context($context);
850 } catch (Exception $e) {
851 $exceptionparam = new stdClass();
852 $exceptionparam->message = $e->getMessage();
853 $exceptionparam->catid = $course['categoryid'];
854 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
856 require_capability('moodle/course:create', $context);
858 // Make sure lang is valid
859 if (array_key_exists('lang', $course)) {
860 if (empty($availablelangs[$course['lang']])) {
861 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
863 if (!has_capability('moodle/course:setforcedlanguage', $context)) {
864 unset($course['lang']);
868 // Make sure theme is valid
869 if (array_key_exists('forcetheme', $course)) {
870 if (!empty($CFG->allowcoursethemes)) {
871 if (empty($availablethemes[$course['forcetheme']])) {
872 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
873 } else {
874 $course['theme'] = $course['forcetheme'];
879 //force visibility if ws user doesn't have the permission to set it
880 $category = $DB->get_record('course_categories', array('id' => $course['categoryid']));
881 if (!has_capability('moodle/course:visibility', $context)) {
882 $course['visible'] = $category->visible;
885 //set default value for completion
886 $courseconfig = get_config('moodlecourse');
887 if (completion_info::is_enabled_for_site()) {
888 if (!array_key_exists('enablecompletion', $course)) {
889 $course['enablecompletion'] = $courseconfig->enablecompletion;
891 } else {
892 $course['enablecompletion'] = 0;
895 $course['category'] = $course['categoryid'];
897 // Summary format.
898 $course['summaryformat'] = external_validate_format($course['summaryformat']);
900 if (!empty($course['courseformatoptions'])) {
901 foreach ($course['courseformatoptions'] as $option) {
902 $course[$option['name']] = $option['value'];
906 // Custom fields.
907 if (!empty($course['customfields'])) {
908 foreach ($course['customfields'] as $field) {
909 $course['customfield_'.$field['shortname']] = $field['value'];
913 //Note: create_course() core function check shortname, idnumber, category
914 $course['id'] = create_course((object) $course)->id;
916 $resultcourses[] = array('id' => $course['id'], 'shortname' => $course['shortname']);
919 $transaction->allow_commit();
921 return $resultcourses;
925 * Returns description of method result value
927 * @return external_description
928 * @since Moodle 2.2
930 public static function create_courses_returns() {
931 return new external_multiple_structure(
932 new external_single_structure(
933 array(
934 'id' => new external_value(PARAM_INT, 'course id'),
935 'shortname' => new external_value(PARAM_TEXT, 'short name'),
942 * Update courses
944 * @return external_function_parameters
945 * @since Moodle 2.5
947 public static function update_courses_parameters() {
948 return new external_function_parameters(
949 array(
950 'courses' => new external_multiple_structure(
951 new external_single_structure(
952 array(
953 'id' => new external_value(PARAM_INT, 'ID of the course'),
954 'fullname' => new external_value(PARAM_TEXT, 'full name', VALUE_OPTIONAL),
955 'shortname' => new external_value(PARAM_TEXT, 'course short name', VALUE_OPTIONAL),
956 'categoryid' => new external_value(PARAM_INT, 'category id', VALUE_OPTIONAL),
957 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
958 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
959 'summaryformat' => new external_format_value('summary', VALUE_OPTIONAL),
960 'format' => new external_value(PARAM_PLUGIN,
961 'course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
962 'showgrades' => new external_value(PARAM_INT,
963 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
964 'newsitems' => new external_value(PARAM_INT,
965 'number of recent items appearing on the course page', VALUE_OPTIONAL),
966 'startdate' => new external_value(PARAM_INT,
967 'timestamp when the course start', VALUE_OPTIONAL),
968 'enddate' => new external_value(PARAM_INT,
969 'timestamp when the course end', VALUE_OPTIONAL),
970 'numsections' => new external_value(PARAM_INT,
971 '(deprecated, use courseformatoptions) number of weeks/topics', VALUE_OPTIONAL),
972 'maxbytes' => new external_value(PARAM_INT,
973 'largest size of file that can be uploaded into the course', VALUE_OPTIONAL),
974 'showreports' => new external_value(PARAM_INT,
975 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
976 'visible' => new external_value(PARAM_INT,
977 '1: available to student, 0:not available', VALUE_OPTIONAL),
978 'hiddensections' => new external_value(PARAM_INT,
979 '(deprecated, use courseformatoptions) How the hidden sections in the course are
980 displayed to students', VALUE_OPTIONAL),
981 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
982 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
983 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
984 'enablecompletion' => new external_value(PARAM_INT,
985 'Enabled, control via completion and activity settings. Disabled,
986 not shown in activity settings.', VALUE_OPTIONAL),
987 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
988 'lang' => new external_value(PARAM_SAFEDIR, 'forced course language', VALUE_OPTIONAL),
989 'forcetheme' => new external_value(PARAM_PLUGIN, 'name of the force theme', VALUE_OPTIONAL),
990 'courseformatoptions' => new external_multiple_structure(
991 new external_single_structure(
992 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
993 'value' => new external_value(PARAM_RAW, 'course format option value')
994 )), 'additional options for particular course format', VALUE_OPTIONAL),
995 'customfields' => new external_multiple_structure(
996 new external_single_structure(
998 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'The shortname of the custom field'),
999 'value' => new external_value(PARAM_RAW, 'The value of the custom field')
1001 ), 'Custom fields', VALUE_OPTIONAL),
1003 ), 'courses to update'
1010 * Update courses
1012 * @param array $courses
1013 * @since Moodle 2.5
1015 public static function update_courses($courses) {
1016 global $CFG, $DB;
1017 require_once($CFG->dirroot . "/course/lib.php");
1018 $warnings = array();
1020 $params = self::validate_parameters(self::update_courses_parameters(),
1021 array('courses' => $courses));
1023 $availablethemes = core_component::get_plugin_list('theme');
1024 $availablelangs = get_string_manager()->get_list_of_translations();
1026 foreach ($params['courses'] as $course) {
1027 // Catch any exception while updating course and return as warning to user.
1028 try {
1029 // Ensure the current user is allowed to run this function.
1030 $context = context_course::instance($course['id'], MUST_EXIST);
1031 self::validate_context($context);
1033 $oldcourse = course_get_format($course['id'])->get_course();
1035 require_capability('moodle/course:update', $context);
1037 // Check if user can change category.
1038 if (array_key_exists('categoryid', $course) && ($oldcourse->category != $course['categoryid'])) {
1039 require_capability('moodle/course:changecategory', $context);
1040 $course['category'] = $course['categoryid'];
1043 // Check if the user can change fullname.
1044 if (array_key_exists('fullname', $course) && ($oldcourse->fullname != $course['fullname'])) {
1045 require_capability('moodle/course:changefullname', $context);
1048 // Check if the user can change shortname.
1049 if (array_key_exists('shortname', $course) && ($oldcourse->shortname != $course['shortname'])) {
1050 require_capability('moodle/course:changeshortname', $context);
1053 // Check if the user can change the idnumber.
1054 if (array_key_exists('idnumber', $course) && ($oldcourse->idnumber != $course['idnumber'])) {
1055 require_capability('moodle/course:changeidnumber', $context);
1058 // Check if user can change summary.
1059 if (array_key_exists('summary', $course) && ($oldcourse->summary != $course['summary'])) {
1060 require_capability('moodle/course:changesummary', $context);
1063 // Summary format.
1064 if (array_key_exists('summaryformat', $course) && ($oldcourse->summaryformat != $course['summaryformat'])) {
1065 require_capability('moodle/course:changesummary', $context);
1066 $course['summaryformat'] = external_validate_format($course['summaryformat']);
1069 // Check if user can change visibility.
1070 if (array_key_exists('visible', $course) && ($oldcourse->visible != $course['visible'])) {
1071 require_capability('moodle/course:visibility', $context);
1074 // Make sure lang is valid.
1075 if (array_key_exists('lang', $course) && ($oldcourse->lang != $course['lang'])) {
1076 require_capability('moodle/course:setforcedlanguage', $context);
1077 if (empty($availablelangs[$course['lang']])) {
1078 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
1082 // Make sure theme is valid.
1083 if (array_key_exists('forcetheme', $course)) {
1084 if (!empty($CFG->allowcoursethemes)) {
1085 if (empty($availablethemes[$course['forcetheme']])) {
1086 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
1087 } else {
1088 $course['theme'] = $course['forcetheme'];
1093 // Make sure completion is enabled before setting it.
1094 if (array_key_exists('enabledcompletion', $course) && !completion_info::is_enabled_for_site()) {
1095 $course['enabledcompletion'] = 0;
1098 // Make sure maxbytes are less then CFG->maxbytes.
1099 if (array_key_exists('maxbytes', $course)) {
1100 // We allow updates back to 0 max bytes, a special value denoting the course uses the site limit.
1101 // Otherwise, either use the size specified, or cap at the max size for the course.
1102 if ($course['maxbytes'] != 0) {
1103 $course['maxbytes'] = get_max_upload_file_size($CFG->maxbytes, $course['maxbytes']);
1107 if (!empty($course['courseformatoptions'])) {
1108 foreach ($course['courseformatoptions'] as $option) {
1109 if (isset($option['name']) && isset($option['value'])) {
1110 $course[$option['name']] = $option['value'];
1115 // Prepare list of custom fields.
1116 if (isset($course['customfields'])) {
1117 foreach ($course['customfields'] as $field) {
1118 $course['customfield_' . $field['shortname']] = $field['value'];
1122 // Update course if user has all required capabilities.
1123 update_course((object) $course);
1124 } catch (Exception $e) {
1125 $warning = array();
1126 $warning['item'] = 'course';
1127 $warning['itemid'] = $course['id'];
1128 if ($e instanceof moodle_exception) {
1129 $warning['warningcode'] = $e->errorcode;
1130 } else {
1131 $warning['warningcode'] = $e->getCode();
1133 $warning['message'] = $e->getMessage();
1134 $warnings[] = $warning;
1138 $result = array();
1139 $result['warnings'] = $warnings;
1140 return $result;
1144 * Returns description of method result value
1146 * @return external_description
1147 * @since Moodle 2.5
1149 public static function update_courses_returns() {
1150 return new external_single_structure(
1151 array(
1152 'warnings' => new external_warnings()
1158 * Returns description of method parameters
1160 * @return external_function_parameters
1161 * @since Moodle 2.2
1163 public static function delete_courses_parameters() {
1164 return new external_function_parameters(
1165 array(
1166 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'course ID')),
1172 * Delete courses
1174 * @param array $courseids A list of course ids
1175 * @since Moodle 2.2
1177 public static function delete_courses($courseids) {
1178 global $CFG, $DB;
1179 require_once($CFG->dirroot."/course/lib.php");
1181 // Parameter validation.
1182 $params = self::validate_parameters(self::delete_courses_parameters(), array('courseids'=>$courseids));
1184 $warnings = array();
1186 foreach ($params['courseids'] as $courseid) {
1187 $course = $DB->get_record('course', array('id' => $courseid));
1189 if ($course === false) {
1190 $warnings[] = array(
1191 'item' => 'course',
1192 'itemid' => $courseid,
1193 'warningcode' => 'unknowncourseidnumber',
1194 'message' => 'Unknown course ID ' . $courseid
1196 continue;
1199 // Check if the context is valid.
1200 $coursecontext = context_course::instance($course->id);
1201 self::validate_context($coursecontext);
1203 // Check if the current user has permission.
1204 if (!can_delete_course($courseid)) {
1205 $warnings[] = array(
1206 'item' => 'course',
1207 'itemid' => $courseid,
1208 'warningcode' => 'cannotdeletecourse',
1209 'message' => 'You do not have the permission to delete this course' . $courseid
1211 continue;
1214 if (delete_course($course, false) === false) {
1215 $warnings[] = array(
1216 'item' => 'course',
1217 'itemid' => $courseid,
1218 'warningcode' => 'cannotdeletecategorycourse',
1219 'message' => 'Course ' . $courseid . ' failed to be deleted'
1221 continue;
1225 fix_course_sortorder();
1227 return array('warnings' => $warnings);
1231 * Returns description of method result value
1233 * @return external_description
1234 * @since Moodle 2.2
1236 public static function delete_courses_returns() {
1237 return new external_single_structure(
1238 array(
1239 'warnings' => new external_warnings()
1245 * Returns description of method parameters
1247 * @return external_function_parameters
1248 * @since Moodle 2.3
1250 public static function duplicate_course_parameters() {
1251 return new external_function_parameters(
1252 array(
1253 'courseid' => new external_value(PARAM_INT, 'course to duplicate id'),
1254 'fullname' => new external_value(PARAM_TEXT, 'duplicated course full name'),
1255 'shortname' => new external_value(PARAM_TEXT, 'duplicated course short name'),
1256 'categoryid' => new external_value(PARAM_INT, 'duplicated course category parent'),
1257 'visible' => new external_value(PARAM_INT, 'duplicated course visible, default to yes', VALUE_DEFAULT, 1),
1258 'options' => new external_multiple_structure(
1259 new external_single_structure(
1260 array(
1261 'name' => new external_value(PARAM_ALPHAEXT, 'The backup option name:
1262 "activities" (int) Include course activites (default to 1 that is equal to yes),
1263 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1264 "filters" (int) Include course filters (default to 1 that is equal to yes),
1265 "users" (int) Include users (default to 0 that is equal to no),
1266 "enrolments" (int) Include enrolment methods (default to 1 - restore only with users),
1267 "role_assignments" (int) Include role assignments (default to 0 that is equal to no),
1268 "comments" (int) Include user comments (default to 0 that is equal to no),
1269 "userscompletion" (int) Include user course completion information (default to 0 that is equal to no),
1270 "logs" (int) Include course logs (default to 0 that is equal to no),
1271 "grade_histories" (int) Include histories (default to 0 that is equal to no)'
1273 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1276 ), VALUE_DEFAULT, array()
1283 * Duplicate a course
1285 * @param int $courseid
1286 * @param string $fullname Duplicated course fullname
1287 * @param string $shortname Duplicated course shortname
1288 * @param int $categoryid Duplicated course parent category id
1289 * @param int $visible Duplicated course availability
1290 * @param array $options List of backup options
1291 * @return array New course info
1292 * @since Moodle 2.3
1294 public static function duplicate_course($courseid, $fullname, $shortname, $categoryid, $visible = 1, $options = array()) {
1295 global $CFG, $USER, $DB;
1296 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1297 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1299 // Parameter validation.
1300 $params = self::validate_parameters(
1301 self::duplicate_course_parameters(),
1302 array(
1303 'courseid' => $courseid,
1304 'fullname' => $fullname,
1305 'shortname' => $shortname,
1306 'categoryid' => $categoryid,
1307 'visible' => $visible,
1308 'options' => $options
1312 // Context validation.
1314 if (! ($course = $DB->get_record('course', array('id'=>$params['courseid'])))) {
1315 throw new moodle_exception('invalidcourseid', 'error');
1318 // Category where duplicated course is going to be created.
1319 $categorycontext = context_coursecat::instance($params['categoryid']);
1320 self::validate_context($categorycontext);
1322 // Course to be duplicated.
1323 $coursecontext = context_course::instance($course->id);
1324 self::validate_context($coursecontext);
1326 $backupdefaults = array(
1327 'activities' => 1,
1328 'blocks' => 1,
1329 'filters' => 1,
1330 'users' => 0,
1331 'enrolments' => backup::ENROL_WITHUSERS,
1332 'role_assignments' => 0,
1333 'comments' => 0,
1334 'userscompletion' => 0,
1335 'logs' => 0,
1336 'grade_histories' => 0
1339 $backupsettings = array();
1340 // Check for backup and restore options.
1341 if (!empty($params['options'])) {
1342 foreach ($params['options'] as $option) {
1344 // Strict check for a correct value (allways 1 or 0, true or false).
1345 $value = clean_param($option['value'], PARAM_INT);
1347 if ($value !== 0 and $value !== 1) {
1348 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1351 if (!isset($backupdefaults[$option['name']])) {
1352 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1355 $backupsettings[$option['name']] = $value;
1359 // Capability checking.
1361 // The backup controller check for this currently, this may be redundant.
1362 require_capability('moodle/course:create', $categorycontext);
1363 require_capability('moodle/restore:restorecourse', $categorycontext);
1364 require_capability('moodle/backup:backupcourse', $coursecontext);
1366 if (!empty($backupsettings['users'])) {
1367 require_capability('moodle/backup:userinfo', $coursecontext);
1368 require_capability('moodle/restore:userinfo', $categorycontext);
1371 // Check if the shortname is used.
1372 if ($foundcourses = $DB->get_records('course', array('shortname'=>$shortname))) {
1373 foreach ($foundcourses as $foundcourse) {
1374 $foundcoursenames[] = $foundcourse->fullname;
1377 $foundcoursenamestring = implode(',', $foundcoursenames);
1378 throw new moodle_exception('shortnametaken', '', '', $foundcoursenamestring);
1381 // Backup the course.
1383 $bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE,
1384 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id);
1386 foreach ($backupsettings as $name => $value) {
1387 if ($setting = $bc->get_plan()->get_setting($name)) {
1388 $bc->get_plan()->get_setting($name)->set_value($value);
1392 $backupid = $bc->get_backupid();
1393 $backupbasepath = $bc->get_plan()->get_basepath();
1395 $bc->execute_plan();
1396 $results = $bc->get_results();
1397 $file = $results['backup_destination'];
1399 $bc->destroy();
1401 // Restore the backup immediately.
1403 // Check if we need to unzip the file because the backup temp dir does not contains backup files.
1404 if (!file_exists($backupbasepath . "/moodle_backup.xml")) {
1405 $file->extract_to_pathname(get_file_packer('application/vnd.moodle.backup'), $backupbasepath);
1408 // Create new course.
1409 $newcourseid = restore_dbops::create_new_course($params['fullname'], $params['shortname'], $params['categoryid']);
1411 $rc = new restore_controller($backupid, $newcourseid,
1412 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id, backup::TARGET_NEW_COURSE);
1414 foreach ($backupsettings as $name => $value) {
1415 $setting = $rc->get_plan()->get_setting($name);
1416 if ($setting->get_status() == backup_setting::NOT_LOCKED) {
1417 $setting->set_value($value);
1421 if (!$rc->execute_precheck()) {
1422 $precheckresults = $rc->get_precheck_results();
1423 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1424 if (empty($CFG->keeptempdirectoriesonbackup)) {
1425 fulldelete($backupbasepath);
1428 $errorinfo = '';
1430 foreach ($precheckresults['errors'] as $error) {
1431 $errorinfo .= $error;
1434 if (array_key_exists('warnings', $precheckresults)) {
1435 foreach ($precheckresults['warnings'] as $warning) {
1436 $errorinfo .= $warning;
1440 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1444 $rc->execute_plan();
1445 $rc->destroy();
1447 $course = $DB->get_record('course', array('id' => $newcourseid), '*', MUST_EXIST);
1448 $course->fullname = $params['fullname'];
1449 $course->shortname = $params['shortname'];
1450 $course->visible = $params['visible'];
1452 // Set shortname and fullname back.
1453 $DB->update_record('course', $course);
1455 if (empty($CFG->keeptempdirectoriesonbackup)) {
1456 fulldelete($backupbasepath);
1459 // Delete the course backup file created by this WebService. Originally located in the course backups area.
1460 $file->delete();
1462 return array('id' => $course->id, 'shortname' => $course->shortname);
1466 * Returns description of method result value
1468 * @return external_description
1469 * @since Moodle 2.3
1471 public static function duplicate_course_returns() {
1472 return new external_single_structure(
1473 array(
1474 'id' => new external_value(PARAM_INT, 'course id'),
1475 'shortname' => new external_value(PARAM_TEXT, 'short name'),
1481 * Returns description of method parameters for import_course
1483 * @return external_function_parameters
1484 * @since Moodle 2.4
1486 public static function import_course_parameters() {
1487 return new external_function_parameters(
1488 array(
1489 'importfrom' => new external_value(PARAM_INT, 'the id of the course we are importing from'),
1490 'importto' => new external_value(PARAM_INT, 'the id of the course we are importing to'),
1491 'deletecontent' => new external_value(PARAM_INT, 'whether to delete the course content where we are importing to (default to 0 = No)', VALUE_DEFAULT, 0),
1492 'options' => new external_multiple_structure(
1493 new external_single_structure(
1494 array(
1495 'name' => new external_value(PARAM_ALPHA, 'The backup option name:
1496 "activities" (int) Include course activites (default to 1 that is equal to yes),
1497 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1498 "filters" (int) Include course filters (default to 1 that is equal to yes)'
1500 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1503 ), VALUE_DEFAULT, array()
1510 * Imports a course
1512 * @param int $importfrom The id of the course we are importing from
1513 * @param int $importto The id of the course we are importing to
1514 * @param bool $deletecontent Whether to delete the course we are importing to content
1515 * @param array $options List of backup options
1516 * @return null
1517 * @since Moodle 2.4
1519 public static function import_course($importfrom, $importto, $deletecontent = 0, $options = array()) {
1520 global $CFG, $USER, $DB;
1521 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1522 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1524 // Parameter validation.
1525 $params = self::validate_parameters(
1526 self::import_course_parameters(),
1527 array(
1528 'importfrom' => $importfrom,
1529 'importto' => $importto,
1530 'deletecontent' => $deletecontent,
1531 'options' => $options
1535 if ($params['deletecontent'] !== 0 and $params['deletecontent'] !== 1) {
1536 throw new moodle_exception('invalidextparam', 'webservice', '', $params['deletecontent']);
1539 // Context validation.
1541 if (! ($importfrom = $DB->get_record('course', array('id'=>$params['importfrom'])))) {
1542 throw new moodle_exception('invalidcourseid', 'error');
1545 if (! ($importto = $DB->get_record('course', array('id'=>$params['importto'])))) {
1546 throw new moodle_exception('invalidcourseid', 'error');
1549 $importfromcontext = context_course::instance($importfrom->id);
1550 self::validate_context($importfromcontext);
1552 $importtocontext = context_course::instance($importto->id);
1553 self::validate_context($importtocontext);
1555 $backupdefaults = array(
1556 'activities' => 1,
1557 'blocks' => 1,
1558 'filters' => 1
1561 $backupsettings = array();
1563 // Check for backup and restore options.
1564 if (!empty($params['options'])) {
1565 foreach ($params['options'] as $option) {
1567 // Strict check for a correct value (allways 1 or 0, true or false).
1568 $value = clean_param($option['value'], PARAM_INT);
1570 if ($value !== 0 and $value !== 1) {
1571 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1574 if (!isset($backupdefaults[$option['name']])) {
1575 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1578 $backupsettings[$option['name']] = $value;
1582 // Capability checking.
1584 require_capability('moodle/backup:backuptargetimport', $importfromcontext);
1585 require_capability('moodle/restore:restoretargetimport', $importtocontext);
1587 $bc = new backup_controller(backup::TYPE_1COURSE, $importfrom->id, backup::FORMAT_MOODLE,
1588 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
1590 foreach ($backupsettings as $name => $value) {
1591 $bc->get_plan()->get_setting($name)->set_value($value);
1594 $backupid = $bc->get_backupid();
1595 $backupbasepath = $bc->get_plan()->get_basepath();
1597 $bc->execute_plan();
1598 $bc->destroy();
1600 // Restore the backup immediately.
1602 // Check if we must delete the contents of the destination course.
1603 if ($params['deletecontent']) {
1604 $restoretarget = backup::TARGET_EXISTING_DELETING;
1605 } else {
1606 $restoretarget = backup::TARGET_EXISTING_ADDING;
1609 $rc = new restore_controller($backupid, $importto->id,
1610 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, $restoretarget);
1612 foreach ($backupsettings as $name => $value) {
1613 $rc->get_plan()->get_setting($name)->set_value($value);
1616 if (!$rc->execute_precheck()) {
1617 $precheckresults = $rc->get_precheck_results();
1618 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1619 if (empty($CFG->keeptempdirectoriesonbackup)) {
1620 fulldelete($backupbasepath);
1623 $errorinfo = '';
1625 foreach ($precheckresults['errors'] as $error) {
1626 $errorinfo .= $error;
1629 if (array_key_exists('warnings', $precheckresults)) {
1630 foreach ($precheckresults['warnings'] as $warning) {
1631 $errorinfo .= $warning;
1635 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1637 } else {
1638 if ($restoretarget == backup::TARGET_EXISTING_DELETING) {
1639 restore_dbops::delete_course_content($importto->id);
1643 $rc->execute_plan();
1644 $rc->destroy();
1646 if (empty($CFG->keeptempdirectoriesonbackup)) {
1647 fulldelete($backupbasepath);
1650 return null;
1654 * Returns description of method result value
1656 * @return external_description
1657 * @since Moodle 2.4
1659 public static function import_course_returns() {
1660 return null;
1664 * Returns description of method parameters
1666 * @return external_function_parameters
1667 * @since Moodle 2.3
1669 public static function get_categories_parameters() {
1670 return new external_function_parameters(
1671 array(
1672 'criteria' => new external_multiple_structure(
1673 new external_single_structure(
1674 array(
1675 'key' => new external_value(PARAM_ALPHA,
1676 'The category column to search, expected keys (value format) are:'.
1677 '"id" (int) the category id,'.
1678 '"ids" (string) category ids separated by commas,'.
1679 '"name" (string) the category name,'.
1680 '"parent" (int) the parent category id,'.
1681 '"idnumber" (string) category idnumber'.
1682 ' - user must have \'moodle/category:manage\' to search on idnumber,'.
1683 '"visible" (int) whether the returned categories must be visible or hidden. If the key is not passed,
1684 then the function return all categories that the user can see.'.
1685 ' - user must have \'moodle/category:manage\' or \'moodle/category:viewhiddencategories\' to search on visible,'.
1686 '"theme" (string) only return the categories having this theme'.
1687 ' - user must have \'moodle/category:manage\' to search on theme'),
1688 'value' => new external_value(PARAM_RAW, 'the value to match')
1690 ), 'criteria', VALUE_DEFAULT, array()
1692 'addsubcategories' => new external_value(PARAM_BOOL, 'return the sub categories infos
1693 (1 - default) otherwise only the category info (0)', VALUE_DEFAULT, 1)
1699 * Get categories
1701 * @param array $criteria Criteria to match the results
1702 * @param booln $addsubcategories obtain only the category (false) or its subcategories (true - default)
1703 * @return array list of categories
1704 * @since Moodle 2.3
1706 public static function get_categories($criteria = array(), $addsubcategories = true) {
1707 global $CFG, $DB;
1708 require_once($CFG->dirroot . "/course/lib.php");
1710 // Validate parameters.
1711 $params = self::validate_parameters(self::get_categories_parameters(),
1712 array('criteria' => $criteria, 'addsubcategories' => $addsubcategories));
1714 // Retrieve the categories.
1715 $categories = array();
1716 if (!empty($params['criteria'])) {
1718 $conditions = array();
1719 $wheres = array();
1720 foreach ($params['criteria'] as $crit) {
1721 $key = trim($crit['key']);
1723 // Trying to avoid duplicate keys.
1724 if (!isset($conditions[$key])) {
1726 $context = context_system::instance();
1727 $value = null;
1728 switch ($key) {
1729 case 'id':
1730 $value = clean_param($crit['value'], PARAM_INT);
1731 $conditions[$key] = $value;
1732 $wheres[] = $key . " = :" . $key;
1733 break;
1735 case 'ids':
1736 $value = clean_param($crit['value'], PARAM_SEQUENCE);
1737 $ids = explode(',', $value);
1738 list($sqlids, $paramids) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED);
1739 $conditions = array_merge($conditions, $paramids);
1740 $wheres[] = 'id ' . $sqlids;
1741 break;
1743 case 'idnumber':
1744 if (has_capability('moodle/category:manage', $context)) {
1745 $value = clean_param($crit['value'], PARAM_RAW);
1746 $conditions[$key] = $value;
1747 $wheres[] = $key . " = :" . $key;
1748 } else {
1749 // We must throw an exception.
1750 // Otherwise the dev client would think no idnumber exists.
1751 throw new moodle_exception('criteriaerror',
1752 'webservice', '', null,
1753 'You don\'t have the permissions to search on the "idnumber" field.');
1755 break;
1757 case 'name':
1758 $value = clean_param($crit['value'], PARAM_TEXT);
1759 $conditions[$key] = $value;
1760 $wheres[] = $key . " = :" . $key;
1761 break;
1763 case 'parent':
1764 $value = clean_param($crit['value'], PARAM_INT);
1765 $conditions[$key] = $value;
1766 $wheres[] = $key . " = :" . $key;
1767 break;
1769 case 'visible':
1770 if (has_capability('moodle/category:viewhiddencategories', $context)) {
1771 $value = clean_param($crit['value'], PARAM_INT);
1772 $conditions[$key] = $value;
1773 $wheres[] = $key . " = :" . $key;
1774 } else {
1775 throw new moodle_exception('criteriaerror',
1776 'webservice', '', null,
1777 'You don\'t have the permissions to search on the "visible" field.');
1779 break;
1781 case 'theme':
1782 if (has_capability('moodle/category:manage', $context)) {
1783 $value = clean_param($crit['value'], PARAM_THEME);
1784 $conditions[$key] = $value;
1785 $wheres[] = $key . " = :" . $key;
1786 } else {
1787 throw new moodle_exception('criteriaerror',
1788 'webservice', '', null,
1789 'You don\'t have the permissions to search on the "theme" field.');
1791 break;
1793 default:
1794 throw new moodle_exception('criteriaerror',
1795 'webservice', '', null,
1796 'You can not search on this criteria: ' . $key);
1801 if (!empty($wheres)) {
1802 $wheres = implode(" AND ", $wheres);
1804 $categories = $DB->get_records_select('course_categories', $wheres, $conditions);
1806 // Retrieve its sub subcategories (all levels).
1807 if ($categories and !empty($params['addsubcategories'])) {
1808 $newcategories = array();
1810 // Check if we required visible/theme checks.
1811 $additionalselect = '';
1812 $additionalparams = array();
1813 if (isset($conditions['visible'])) {
1814 $additionalselect .= ' AND visible = :visible';
1815 $additionalparams['visible'] = $conditions['visible'];
1817 if (isset($conditions['theme'])) {
1818 $additionalselect .= ' AND theme= :theme';
1819 $additionalparams['theme'] = $conditions['theme'];
1822 foreach ($categories as $category) {
1823 $sqlselect = $DB->sql_like('path', ':path') . $additionalselect;
1824 $sqlparams = array('path' => $category->path.'/%') + $additionalparams; // It will NOT include the specified category.
1825 $subcategories = $DB->get_records_select('course_categories', $sqlselect, $sqlparams);
1826 $newcategories = $newcategories + $subcategories; // Both arrays have integer as keys.
1828 $categories = $categories + $newcategories;
1832 } else {
1833 // Retrieve all categories in the database.
1834 $categories = $DB->get_records('course_categories');
1837 // The not returned categories. key => category id, value => reason of exclusion.
1838 $excludedcats = array();
1840 // The returned categories.
1841 $categoriesinfo = array();
1843 // We need to sort the categories by path.
1844 // The parent cats need to be checked by the algo first.
1845 usort($categories, "core_course_external::compare_categories_by_path");
1847 foreach ($categories as $category) {
1849 // Check if the category is a child of an excluded category, if yes exclude it too (excluded => do not return).
1850 $parents = explode('/', $category->path);
1851 unset($parents[0]); // First key is always empty because path start with / => /1/2/4.
1852 foreach ($parents as $parentid) {
1853 // Note: when the parent exclusion was due to the context,
1854 // the sub category could still be returned.
1855 if (isset($excludedcats[$parentid]) and $excludedcats[$parentid] != 'context') {
1856 $excludedcats[$category->id] = 'parent';
1860 // Check the user can use the category context.
1861 $context = context_coursecat::instance($category->id);
1862 try {
1863 self::validate_context($context);
1864 } catch (Exception $e) {
1865 $excludedcats[$category->id] = 'context';
1867 // If it was the requested category then throw an exception.
1868 if (isset($params['categoryid']) && $category->id == $params['categoryid']) {
1869 $exceptionparam = new stdClass();
1870 $exceptionparam->message = $e->getMessage();
1871 $exceptionparam->catid = $category->id;
1872 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
1876 // Return the category information.
1877 if (!isset($excludedcats[$category->id])) {
1879 // Final check to see if the category is visible to the user.
1880 if (core_course_category::can_view_category($category)) {
1882 $categoryinfo = array();
1883 $categoryinfo['id'] = $category->id;
1884 $categoryinfo['name'] = external_format_string($category->name, $context);
1885 list($categoryinfo['description'], $categoryinfo['descriptionformat']) =
1886 external_format_text($category->description, $category->descriptionformat,
1887 $context->id, 'coursecat', 'description', null);
1888 $categoryinfo['parent'] = $category->parent;
1889 $categoryinfo['sortorder'] = $category->sortorder;
1890 $categoryinfo['coursecount'] = $category->coursecount;
1891 $categoryinfo['depth'] = $category->depth;
1892 $categoryinfo['path'] = $category->path;
1894 // Some fields only returned for admin.
1895 if (has_capability('moodle/category:manage', $context)) {
1896 $categoryinfo['idnumber'] = $category->idnumber;
1897 $categoryinfo['visible'] = $category->visible;
1898 $categoryinfo['visibleold'] = $category->visibleold;
1899 $categoryinfo['timemodified'] = $category->timemodified;
1900 $categoryinfo['theme'] = clean_param($category->theme, PARAM_THEME);
1903 $categoriesinfo[] = $categoryinfo;
1904 } else {
1905 $excludedcats[$category->id] = 'visibility';
1910 // Sorting the resulting array so it looks a bit better for the client developer.
1911 usort($categoriesinfo, "core_course_external::compare_categories_by_sortorder");
1913 return $categoriesinfo;
1917 * Sort categories array by path
1918 * private function: only used by get_categories
1920 * @param array $category1
1921 * @param array $category2
1922 * @return int result of strcmp
1923 * @since Moodle 2.3
1925 private static function compare_categories_by_path($category1, $category2) {
1926 return strcmp($category1->path, $category2->path);
1930 * Sort categories array by sortorder
1931 * private function: only used by get_categories
1933 * @param array $category1
1934 * @param array $category2
1935 * @return int result of strcmp
1936 * @since Moodle 2.3
1938 private static function compare_categories_by_sortorder($category1, $category2) {
1939 return strcmp($category1['sortorder'], $category2['sortorder']);
1943 * Returns description of method result value
1945 * @return external_description
1946 * @since Moodle 2.3
1948 public static function get_categories_returns() {
1949 return new external_multiple_structure(
1950 new external_single_structure(
1951 array(
1952 'id' => new external_value(PARAM_INT, 'category id'),
1953 'name' => new external_value(PARAM_TEXT, 'category name'),
1954 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1955 'description' => new external_value(PARAM_RAW, 'category description'),
1956 'descriptionformat' => new external_format_value('description'),
1957 'parent' => new external_value(PARAM_INT, 'parent category id'),
1958 'sortorder' => new external_value(PARAM_INT, 'category sorting order'),
1959 'coursecount' => new external_value(PARAM_INT, 'number of courses in this category'),
1960 'visible' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1961 'visibleold' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1962 'timemodified' => new external_value(PARAM_INT, 'timestamp', VALUE_OPTIONAL),
1963 'depth' => new external_value(PARAM_INT, 'category depth'),
1964 'path' => new external_value(PARAM_TEXT, 'category path'),
1965 'theme' => new external_value(PARAM_THEME, 'category theme', VALUE_OPTIONAL),
1966 ), 'List of categories'
1972 * Returns description of method parameters
1974 * @return external_function_parameters
1975 * @since Moodle 2.3
1977 public static function create_categories_parameters() {
1978 return new external_function_parameters(
1979 array(
1980 'categories' => new external_multiple_structure(
1981 new external_single_structure(
1982 array(
1983 'name' => new external_value(PARAM_TEXT, 'new category name'),
1984 'parent' => new external_value(PARAM_INT,
1985 'the parent category id inside which the new category will be created
1986 - set to 0 for a root category',
1987 VALUE_DEFAULT, 0),
1988 'idnumber' => new external_value(PARAM_RAW,
1989 'the new category idnumber', VALUE_OPTIONAL),
1990 'description' => new external_value(PARAM_RAW,
1991 'the new category description', VALUE_OPTIONAL),
1992 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
1993 'theme' => new external_value(PARAM_THEME,
1994 'the new category theme. This option must be enabled on moodle',
1995 VALUE_OPTIONAL),
2004 * Create categories
2006 * @param array $categories - see create_categories_parameters() for the array structure
2007 * @return array - see create_categories_returns() for the array structure
2008 * @since Moodle 2.3
2010 public static function create_categories($categories) {
2011 global $DB;
2013 $params = self::validate_parameters(self::create_categories_parameters(),
2014 array('categories' => $categories));
2016 $transaction = $DB->start_delegated_transaction();
2018 $createdcategories = array();
2019 foreach ($params['categories'] as $category) {
2020 if ($category['parent']) {
2021 if (!$DB->record_exists('course_categories', array('id' => $category['parent']))) {
2022 throw new moodle_exception('unknowcategory');
2024 $context = context_coursecat::instance($category['parent']);
2025 } else {
2026 $context = context_system::instance();
2028 self::validate_context($context);
2029 require_capability('moodle/category:manage', $context);
2031 // this will validate format and throw an exception if there are errors
2032 external_validate_format($category['descriptionformat']);
2034 $newcategory = core_course_category::create($category);
2035 $context = context_coursecat::instance($newcategory->id);
2037 $createdcategories[] = array(
2038 'id' => $newcategory->id,
2039 'name' => external_format_string($newcategory->name, $context),
2043 $transaction->allow_commit();
2045 return $createdcategories;
2049 * Returns description of method parameters
2051 * @return external_function_parameters
2052 * @since Moodle 2.3
2054 public static function create_categories_returns() {
2055 return new external_multiple_structure(
2056 new external_single_structure(
2057 array(
2058 'id' => new external_value(PARAM_INT, 'new category id'),
2059 'name' => new external_value(PARAM_TEXT, 'new category name'),
2066 * Returns description of method parameters
2068 * @return external_function_parameters
2069 * @since Moodle 2.3
2071 public static function update_categories_parameters() {
2072 return new external_function_parameters(
2073 array(
2074 'categories' => new external_multiple_structure(
2075 new external_single_structure(
2076 array(
2077 'id' => new external_value(PARAM_INT, 'course id'),
2078 'name' => new external_value(PARAM_TEXT, 'category name', VALUE_OPTIONAL),
2079 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
2080 'parent' => new external_value(PARAM_INT, 'parent category id', VALUE_OPTIONAL),
2081 'description' => new external_value(PARAM_RAW, 'category description', VALUE_OPTIONAL),
2082 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
2083 'theme' => new external_value(PARAM_THEME,
2084 'the category theme. This option must be enabled on moodle', VALUE_OPTIONAL),
2093 * Update categories
2095 * @param array $categories The list of categories to update
2096 * @return null
2097 * @since Moodle 2.3
2099 public static function update_categories($categories) {
2100 global $DB;
2102 // Validate parameters.
2103 $params = self::validate_parameters(self::update_categories_parameters(), array('categories' => $categories));
2105 $transaction = $DB->start_delegated_transaction();
2107 foreach ($params['categories'] as $cat) {
2108 $category = core_course_category::get($cat['id']);
2110 $categorycontext = context_coursecat::instance($cat['id']);
2111 self::validate_context($categorycontext);
2112 require_capability('moodle/category:manage', $categorycontext);
2114 // this will throw an exception if descriptionformat is not valid
2115 external_validate_format($cat['descriptionformat']);
2117 $category->update($cat);
2120 $transaction->allow_commit();
2124 * Returns description of method result value
2126 * @return external_description
2127 * @since Moodle 2.3
2129 public static function update_categories_returns() {
2130 return null;
2134 * Returns description of method parameters
2136 * @return external_function_parameters
2137 * @since Moodle 2.3
2139 public static function delete_categories_parameters() {
2140 return new external_function_parameters(
2141 array(
2142 'categories' => new external_multiple_structure(
2143 new external_single_structure(
2144 array(
2145 'id' => new external_value(PARAM_INT, 'category id to delete'),
2146 'newparent' => new external_value(PARAM_INT,
2147 'the parent category to move the contents to, if specified', VALUE_OPTIONAL),
2148 'recursive' => new external_value(PARAM_BOOL, '1: recursively delete all contents inside this
2149 category, 0 (default): move contents to newparent or current parent category (except if parent is root)', VALUE_DEFAULT, 0)
2158 * Delete categories
2160 * @param array $categories A list of category ids
2161 * @return array
2162 * @since Moodle 2.3
2164 public static function delete_categories($categories) {
2165 global $CFG, $DB;
2166 require_once($CFG->dirroot . "/course/lib.php");
2168 // Validate parameters.
2169 $params = self::validate_parameters(self::delete_categories_parameters(), array('categories' => $categories));
2171 $transaction = $DB->start_delegated_transaction();
2173 foreach ($params['categories'] as $category) {
2174 $deletecat = core_course_category::get($category['id'], MUST_EXIST);
2175 $context = context_coursecat::instance($deletecat->id);
2176 require_capability('moodle/category:manage', $context);
2177 self::validate_context($context);
2178 self::validate_context(get_category_or_system_context($deletecat->parent));
2180 if ($category['recursive']) {
2181 // If recursive was specified, then we recursively delete the category's contents.
2182 if ($deletecat->can_delete_full()) {
2183 $deletecat->delete_full(false);
2184 } else {
2185 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2187 } else {
2188 // In this situation, we don't delete the category's contents, we either move it to newparent or parent.
2189 // If the parent is the root, moving is not supported (because a course must always be inside a category).
2190 // We must move to an existing category.
2191 if (!empty($category['newparent'])) {
2192 $newparentcat = core_course_category::get($category['newparent']);
2193 } else {
2194 $newparentcat = core_course_category::get($deletecat->parent);
2197 // This operation is not allowed. We must move contents to an existing category.
2198 if (!$newparentcat->id) {
2199 throw new moodle_exception('movecatcontentstoroot');
2202 self::validate_context(context_coursecat::instance($newparentcat->id));
2203 if ($deletecat->can_move_content_to($newparentcat->id)) {
2204 $deletecat->delete_move($newparentcat->id, false);
2205 } else {
2206 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2211 $transaction->allow_commit();
2215 * Returns description of method parameters
2217 * @return external_function_parameters
2218 * @since Moodle 2.3
2220 public static function delete_categories_returns() {
2221 return null;
2225 * Describes the parameters for delete_modules.
2227 * @return external_function_parameters
2228 * @since Moodle 2.5
2230 public static function delete_modules_parameters() {
2231 return new external_function_parameters (
2232 array(
2233 'cmids' => new external_multiple_structure(new external_value(PARAM_INT, 'course module ID',
2234 VALUE_REQUIRED, '', NULL_NOT_ALLOWED), 'Array of course module IDs'),
2240 * Deletes a list of provided module instances.
2242 * @param array $cmids the course module ids
2243 * @since Moodle 2.5
2245 public static function delete_modules($cmids) {
2246 global $CFG, $DB;
2248 // Require course file containing the course delete module function.
2249 require_once($CFG->dirroot . "/course/lib.php");
2251 // Clean the parameters.
2252 $params = self::validate_parameters(self::delete_modules_parameters(), array('cmids' => $cmids));
2254 // Keep track of the course ids we have performed a capability check on to avoid repeating.
2255 $arrcourseschecked = array();
2257 foreach ($params['cmids'] as $cmid) {
2258 // Get the course module.
2259 $cm = $DB->get_record('course_modules', array('id' => $cmid), '*', MUST_EXIST);
2261 // Check if we have not yet confirmed they have permission in this course.
2262 if (!in_array($cm->course, $arrcourseschecked)) {
2263 // Ensure the current user has required permission in this course.
2264 $context = context_course::instance($cm->course);
2265 self::validate_context($context);
2266 // Add to the array.
2267 $arrcourseschecked[] = $cm->course;
2270 // Ensure they can delete this module.
2271 $modcontext = context_module::instance($cm->id);
2272 require_capability('moodle/course:manageactivities', $modcontext);
2274 // Delete the module.
2275 course_delete_module($cm->id);
2280 * Describes the delete_modules return value.
2282 * @return external_single_structure
2283 * @since Moodle 2.5
2285 public static function delete_modules_returns() {
2286 return null;
2290 * Returns description of method parameters
2292 * @return external_function_parameters
2293 * @since Moodle 2.9
2295 public static function view_course_parameters() {
2296 return new external_function_parameters(
2297 array(
2298 'courseid' => new external_value(PARAM_INT, 'id of the course'),
2299 'sectionnumber' => new external_value(PARAM_INT, 'section number', VALUE_DEFAULT, 0)
2305 * Trigger the course viewed event.
2307 * @param int $courseid id of course
2308 * @param int $sectionnumber sectionnumber (0, 1, 2...)
2309 * @return array of warnings and status result
2310 * @since Moodle 2.9
2311 * @throws moodle_exception
2313 public static function view_course($courseid, $sectionnumber = 0) {
2314 global $CFG;
2315 require_once($CFG->dirroot . "/course/lib.php");
2317 $params = self::validate_parameters(self::view_course_parameters(),
2318 array(
2319 'courseid' => $courseid,
2320 'sectionnumber' => $sectionnumber
2323 $warnings = array();
2325 $course = get_course($params['courseid']);
2326 $context = context_course::instance($course->id);
2327 self::validate_context($context);
2329 if (!empty($params['sectionnumber'])) {
2331 // Get section details and check it exists.
2332 $modinfo = get_fast_modinfo($course);
2333 $coursesection = $modinfo->get_section_info($params['sectionnumber'], MUST_EXIST);
2335 // Check user is allowed to see it.
2336 if (!$coursesection->uservisible) {
2337 require_capability('moodle/course:viewhiddensections', $context);
2341 course_view($context, $params['sectionnumber']);
2343 $result = array();
2344 $result['status'] = true;
2345 $result['warnings'] = $warnings;
2346 return $result;
2350 * Returns description of method result value
2352 * @return external_description
2353 * @since Moodle 2.9
2355 public static function view_course_returns() {
2356 return new external_single_structure(
2357 array(
2358 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
2359 'warnings' => new external_warnings()
2365 * Returns description of method parameters
2367 * @return external_function_parameters
2368 * @since Moodle 3.0
2370 public static function search_courses_parameters() {
2371 return new external_function_parameters(
2372 array(
2373 'criterianame' => new external_value(PARAM_ALPHA, 'criteria name
2374 (search, modulelist (only admins), blocklist (only admins), tagid)'),
2375 'criteriavalue' => new external_value(PARAM_RAW, 'criteria value'),
2376 'page' => new external_value(PARAM_INT, 'page number (0 based)', VALUE_DEFAULT, 0),
2377 'perpage' => new external_value(PARAM_INT, 'items per page', VALUE_DEFAULT, 0),
2378 'requiredcapabilities' => new external_multiple_structure(
2379 new external_value(PARAM_CAPABILITY, 'Capability string used to filter courses by permission'),
2380 'Optional list of required capabilities (used to filter the list)', VALUE_DEFAULT, array()
2382 'limittoenrolled' => new external_value(PARAM_BOOL, 'limit to enrolled courses', VALUE_DEFAULT, 0),
2383 'onlywithcompletion' => new external_value(PARAM_BOOL, 'limit to courses where completion is enabled',
2384 VALUE_DEFAULT, 0),
2390 * Return the course information that is public (visible by every one)
2392 * @param core_course_list_element $course course in list object
2393 * @param stdClass $coursecontext course context object
2394 * @return array the course information
2395 * @since Moodle 3.2
2397 protected static function get_course_public_information(core_course_list_element $course, $coursecontext) {
2399 static $categoriescache = array();
2401 // Category information.
2402 if (!array_key_exists($course->category, $categoriescache)) {
2403 $categoriescache[$course->category] = core_course_category::get($course->category, IGNORE_MISSING);
2405 $category = $categoriescache[$course->category];
2407 // Retrieve course overview used files.
2408 $files = array();
2409 foreach ($course->get_course_overviewfiles() as $file) {
2410 $fileurl = moodle_url::make_webservice_pluginfile_url($file->get_contextid(), $file->get_component(),
2411 $file->get_filearea(), null, $file->get_filepath(),
2412 $file->get_filename())->out(false);
2413 $files[] = array(
2414 'filename' => $file->get_filename(),
2415 'fileurl' => $fileurl,
2416 'filesize' => $file->get_filesize(),
2417 'filepath' => $file->get_filepath(),
2418 'mimetype' => $file->get_mimetype(),
2419 'timemodified' => $file->get_timemodified(),
2423 // Retrieve the course contacts,
2424 // we need here the users fullname since if we are not enrolled can be difficult to obtain them via other Web Services.
2425 $coursecontacts = array();
2426 foreach ($course->get_course_contacts() as $contact) {
2427 $coursecontacts[] = array(
2428 'id' => $contact['user']->id,
2429 'fullname' => $contact['username'],
2430 'roles' => array_map(function($role){
2431 return array('id' => $role->id, 'name' => $role->displayname);
2432 }, $contact['roles']),
2433 'role' => array('id' => $contact['role']->id, 'name' => $contact['role']->displayname),
2434 'rolename' => $contact['rolename']
2438 // Allowed enrolment methods (maybe we can self-enrol).
2439 $enroltypes = array();
2440 $instances = enrol_get_instances($course->id, true);
2441 foreach ($instances as $instance) {
2442 $enroltypes[] = $instance->enrol;
2445 // Format summary.
2446 list($summary, $summaryformat) =
2447 external_format_text($course->summary, $course->summaryformat, $coursecontext->id, 'course', 'summary', null);
2449 $categoryname = '';
2450 if (!empty($category)) {
2451 $categoryname = external_format_string($category->name, $category->get_context());
2454 $displayname = get_course_display_name_for_list($course);
2455 $coursereturns = array();
2456 $coursereturns['id'] = $course->id;
2457 $coursereturns['fullname'] = external_format_string($course->fullname, $coursecontext->id);
2458 $coursereturns['displayname'] = external_format_string($displayname, $coursecontext->id);
2459 $coursereturns['shortname'] = external_format_string($course->shortname, $coursecontext->id);
2460 $coursereturns['categoryid'] = $course->category;
2461 $coursereturns['categoryname'] = $categoryname;
2462 $coursereturns['summary'] = $summary;
2463 $coursereturns['summaryformat'] = $summaryformat;
2464 $coursereturns['summaryfiles'] = external_util::get_area_files($coursecontext->id, 'course', 'summary', false, false);
2465 $coursereturns['overviewfiles'] = $files;
2466 $coursereturns['contacts'] = $coursecontacts;
2467 $coursereturns['enrollmentmethods'] = $enroltypes;
2468 $coursereturns['sortorder'] = $course->sortorder;
2470 $handler = core_course\customfield\course_handler::create();
2471 if ($customfields = $handler->export_instance_data($course->id)) {
2472 $coursereturns['customfields'] = [];
2473 foreach ($customfields as $data) {
2474 $coursereturns['customfields'][] = [
2475 'type' => $data->get_type(),
2476 'value' => $data->get_value(),
2477 'name' => $data->get_name(),
2478 'shortname' => $data->get_shortname()
2483 return $coursereturns;
2487 * Search courses following the specified criteria.
2489 * @param string $criterianame Criteria name (search, modulelist (only admins), blocklist (only admins), tagid)
2490 * @param string $criteriavalue Criteria value
2491 * @param int $page Page number (for pagination)
2492 * @param int $perpage Items per page
2493 * @param array $requiredcapabilities Optional list of required capabilities (used to filter the list).
2494 * @param int $limittoenrolled Limit to only enrolled courses
2495 * @param int onlywithcompletion Limit to only courses where completion is enabled
2496 * @return array of course objects and warnings
2497 * @since Moodle 3.0
2498 * @throws moodle_exception
2500 public static function search_courses($criterianame,
2501 $criteriavalue,
2502 $page=0,
2503 $perpage=0,
2504 $requiredcapabilities=array(),
2505 $limittoenrolled=0,
2506 $onlywithcompletion=0) {
2507 global $CFG;
2509 $warnings = array();
2511 $parameters = array(
2512 'criterianame' => $criterianame,
2513 'criteriavalue' => $criteriavalue,
2514 'page' => $page,
2515 'perpage' => $perpage,
2516 'requiredcapabilities' => $requiredcapabilities,
2517 'limittoenrolled' => $limittoenrolled,
2518 'onlywithcompletion' => $onlywithcompletion
2520 $params = self::validate_parameters(self::search_courses_parameters(), $parameters);
2521 self::validate_context(context_system::instance());
2523 $allowedcriterianames = array('search', 'modulelist', 'blocklist', 'tagid');
2524 if (!in_array($params['criterianame'], $allowedcriterianames)) {
2525 throw new invalid_parameter_exception('Invalid value for criterianame parameter (value: '.$params['criterianame'].'),' .
2526 'allowed values are: '.implode(',', $allowedcriterianames));
2529 if ($params['criterianame'] == 'modulelist' or $params['criterianame'] == 'blocklist') {
2530 require_capability('moodle/site:config', context_system::instance());
2533 $paramtype = array(
2534 'search' => PARAM_RAW,
2535 'modulelist' => PARAM_PLUGIN,
2536 'blocklist' => PARAM_INT,
2537 'tagid' => PARAM_INT
2539 $params['criteriavalue'] = clean_param($params['criteriavalue'], $paramtype[$params['criterianame']]);
2541 // Prepare the search API options.
2542 $searchcriteria = array();
2543 $searchcriteria[$params['criterianame']] = $params['criteriavalue'];
2544 if ($params['onlywithcompletion']) {
2545 $searchcriteria['onlywithcompletion'] = true;
2548 $options = array();
2549 if ($params['perpage'] != 0) {
2550 $offset = $params['page'] * $params['perpage'];
2551 $options = array('offset' => $offset, 'limit' => $params['perpage']);
2554 // Search the courses.
2555 $courses = core_course_category::search_courses($searchcriteria, $options, $params['requiredcapabilities']);
2556 $totalcount = core_course_category::search_courses_count($searchcriteria, $options, $params['requiredcapabilities']);
2558 if (!empty($limittoenrolled)) {
2559 // Get the courses where the current user has access.
2560 $enrolled = enrol_get_my_courses(array('id', 'cacherev'));
2563 $finalcourses = array();
2564 $categoriescache = array();
2566 foreach ($courses as $course) {
2567 if (!empty($limittoenrolled)) {
2568 // Filter out not enrolled courses.
2569 if (!isset($enrolled[$course->id])) {
2570 $totalcount--;
2571 continue;
2575 $coursecontext = context_course::instance($course->id);
2577 $finalcourses[] = self::get_course_public_information($course, $coursecontext);
2580 return array(
2581 'total' => $totalcount,
2582 'courses' => $finalcourses,
2583 'warnings' => $warnings
2588 * Returns a course structure definition
2590 * @param boolean $onlypublicdata set to true, to retrieve only fields viewable by anyone when the course is visible
2591 * @return array the course structure
2592 * @since Moodle 3.2
2594 protected static function get_course_structure($onlypublicdata = true) {
2595 $coursestructure = array(
2596 'id' => new external_value(PARAM_INT, 'course id'),
2597 'fullname' => new external_value(PARAM_TEXT, 'course full name'),
2598 'displayname' => new external_value(PARAM_TEXT, 'course display name'),
2599 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
2600 'categoryid' => new external_value(PARAM_INT, 'category id'),
2601 'categoryname' => new external_value(PARAM_TEXT, 'category name'),
2602 'sortorder' => new external_value(PARAM_INT, 'Sort order in the category', VALUE_OPTIONAL),
2603 'summary' => new external_value(PARAM_RAW, 'summary'),
2604 'summaryformat' => new external_format_value('summary'),
2605 'summaryfiles' => new external_files('summary files in the summary field', VALUE_OPTIONAL),
2606 'overviewfiles' => new external_files('additional overview files attached to this course'),
2607 'contacts' => new external_multiple_structure(
2608 new external_single_structure(
2609 array(
2610 'id' => new external_value(PARAM_INT, 'contact user id'),
2611 'fullname' => new external_value(PARAM_NOTAGS, 'contact user fullname'),
2614 'contact users'
2616 'enrollmentmethods' => new external_multiple_structure(
2617 new external_value(PARAM_PLUGIN, 'enrollment method'),
2618 'enrollment methods list'
2620 'customfields' => new external_multiple_structure(
2621 new external_single_structure(
2622 array(
2623 'name' => new external_value(PARAM_RAW, 'The name of the custom field'),
2624 'shortname' => new external_value(PARAM_RAW,
2625 'The shortname of the custom field - to be able to build the field class in the code'),
2626 'type' => new external_value(PARAM_ALPHANUMEXT,
2627 'The type of the custom field - text field, checkbox...'),
2628 'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
2630 ), 'Custom fields', VALUE_OPTIONAL),
2633 if (!$onlypublicdata) {
2634 $extra = array(
2635 'idnumber' => new external_value(PARAM_RAW, 'Id number', VALUE_OPTIONAL),
2636 'format' => new external_value(PARAM_PLUGIN, 'Course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
2637 'showgrades' => new external_value(PARAM_INT, '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
2638 'newsitems' => new external_value(PARAM_INT, 'Number of recent items appearing on the course page', VALUE_OPTIONAL),
2639 'startdate' => new external_value(PARAM_INT, 'Timestamp when the course start', VALUE_OPTIONAL),
2640 'enddate' => new external_value(PARAM_INT, 'Timestamp when the course end', VALUE_OPTIONAL),
2641 'maxbytes' => new external_value(PARAM_INT, 'Largest size of file that can be uploaded into', VALUE_OPTIONAL),
2642 'showreports' => new external_value(PARAM_INT, 'Are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
2643 'visible' => new external_value(PARAM_INT, '1: available to student, 0:not available', VALUE_OPTIONAL),
2644 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
2645 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
2646 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
2647 'enablecompletion' => new external_value(PARAM_INT, 'Completion enabled? 1: yes 0: no', VALUE_OPTIONAL),
2648 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
2649 'lang' => new external_value(PARAM_SAFEDIR, 'Forced course language', VALUE_OPTIONAL),
2650 'theme' => new external_value(PARAM_PLUGIN, 'Fame of the forced theme', VALUE_OPTIONAL),
2651 'marker' => new external_value(PARAM_INT, 'Current course marker', VALUE_OPTIONAL),
2652 'legacyfiles' => new external_value(PARAM_INT, 'If legacy files are enabled', VALUE_OPTIONAL),
2653 'calendartype' => new external_value(PARAM_PLUGIN, 'Calendar type', VALUE_OPTIONAL),
2654 'timecreated' => new external_value(PARAM_INT, 'Time when the course was created', VALUE_OPTIONAL),
2655 'timemodified' => new external_value(PARAM_INT, 'Last time the course was updated', VALUE_OPTIONAL),
2656 'requested' => new external_value(PARAM_INT, 'If is a requested course', VALUE_OPTIONAL),
2657 'cacherev' => new external_value(PARAM_INT, 'Cache revision number', VALUE_OPTIONAL),
2658 'filters' => new external_multiple_structure(
2659 new external_single_structure(
2660 array(
2661 'filter' => new external_value(PARAM_PLUGIN, 'Filter plugin name'),
2662 'localstate' => new external_value(PARAM_INT, 'Filter state: 1 for on, -1 for off, 0 if inherit'),
2663 'inheritedstate' => new external_value(PARAM_INT, '1 or 0 to use when localstate is set to inherit'),
2666 'Course filters', VALUE_OPTIONAL
2668 'courseformatoptions' => new external_multiple_structure(
2669 new external_single_structure(
2670 array(
2671 'name' => new external_value(PARAM_RAW, 'Course format option name.'),
2672 'value' => new external_value(PARAM_RAW, 'Course format option value.'),
2675 'Additional options for particular course format.', VALUE_OPTIONAL
2678 $coursestructure = array_merge($coursestructure, $extra);
2680 return new external_single_structure($coursestructure);
2684 * Returns description of method result value
2686 * @return external_description
2687 * @since Moodle 3.0
2689 public static function search_courses_returns() {
2690 return new external_single_structure(
2691 array(
2692 'total' => new external_value(PARAM_INT, 'total course count'),
2693 'courses' => new external_multiple_structure(self::get_course_structure(), 'course'),
2694 'warnings' => new external_warnings()
2700 * Returns description of method parameters
2702 * @return external_function_parameters
2703 * @since Moodle 3.0
2705 public static function get_course_module_parameters() {
2706 return new external_function_parameters(
2707 array(
2708 'cmid' => new external_value(PARAM_INT, 'The course module id')
2714 * Return information about a course module.
2716 * @param int $cmid the course module id
2717 * @return array of warnings and the course module
2718 * @since Moodle 3.0
2719 * @throws moodle_exception
2721 public static function get_course_module($cmid) {
2722 global $CFG, $DB;
2724 $params = self::validate_parameters(self::get_course_module_parameters(), array('cmid' => $cmid));
2725 $warnings = array();
2727 $cm = get_coursemodule_from_id(null, $params['cmid'], 0, true, MUST_EXIST);
2728 $context = context_module::instance($cm->id);
2729 self::validate_context($context);
2731 // If the user has permissions to manage the activity, return all the information.
2732 if (has_capability('moodle/course:manageactivities', $context)) {
2733 require_once($CFG->dirroot . '/course/modlib.php');
2734 require_once($CFG->libdir . '/gradelib.php');
2736 $info = $cm;
2737 // Get the extra information: grade, advanced grading and outcomes data.
2738 $course = get_course($cm->course);
2739 list($newcm, $newcontext, $module, $extrainfo, $cw) = get_moduleinfo_data($cm, $course);
2740 // Grades.
2741 $gradeinfo = array('grade', 'gradepass', 'gradecat');
2742 foreach ($gradeinfo as $gfield) {
2743 if (isset($extrainfo->{$gfield})) {
2744 $info->{$gfield} = $extrainfo->{$gfield};
2747 if (isset($extrainfo->grade) and $extrainfo->grade < 0) {
2748 $info->scale = $DB->get_field('scale', 'scale', array('id' => abs($extrainfo->grade)));
2750 // Advanced grading.
2751 if (isset($extrainfo->_advancedgradingdata)) {
2752 $info->advancedgrading = array();
2753 foreach ($extrainfo as $key => $val) {
2754 if (strpos($key, 'advancedgradingmethod_') === 0) {
2755 $info->advancedgrading[] = array(
2756 'area' => str_replace('advancedgradingmethod_', '', $key),
2757 'method' => $val
2762 // Outcomes.
2763 foreach ($extrainfo as $key => $val) {
2764 if (strpos($key, 'outcome_') === 0) {
2765 if (!isset($info->outcomes)) {
2766 $info->outcomes = array();
2768 $id = str_replace('outcome_', '', $key);
2769 $outcome = grade_outcome::fetch(array('id' => $id));
2770 $scaleitems = $outcome->load_scale();
2771 $info->outcomes[] = array(
2772 'id' => $id,
2773 'name' => external_format_string($outcome->get_name(), $context->id),
2774 'scale' => $scaleitems->scale
2778 } else {
2779 // Return information is safe to show to any user.
2780 $info = new stdClass();
2781 $info->id = $cm->id;
2782 $info->course = $cm->course;
2783 $info->module = $cm->module;
2784 $info->modname = $cm->modname;
2785 $info->instance = $cm->instance;
2786 $info->section = $cm->section;
2787 $info->sectionnum = $cm->sectionnum;
2788 $info->groupmode = $cm->groupmode;
2789 $info->groupingid = $cm->groupingid;
2790 $info->completion = $cm->completion;
2792 // Format name.
2793 $info->name = external_format_string($cm->name, $context->id);
2794 $result = array();
2795 $result['cm'] = $info;
2796 $result['warnings'] = $warnings;
2797 return $result;
2801 * Returns description of method result value
2803 * @return external_description
2804 * @since Moodle 3.0
2806 public static function get_course_module_returns() {
2807 return new external_single_structure(
2808 array(
2809 'cm' => new external_single_structure(
2810 array(
2811 'id' => new external_value(PARAM_INT, 'The course module id'),
2812 'course' => new external_value(PARAM_INT, 'The course id'),
2813 'module' => new external_value(PARAM_INT, 'The module type id'),
2814 'name' => new external_value(PARAM_RAW, 'The activity name'),
2815 'modname' => new external_value(PARAM_COMPONENT, 'The module component name (forum, assign, etc..)'),
2816 'instance' => new external_value(PARAM_INT, 'The activity instance id'),
2817 'section' => new external_value(PARAM_INT, 'The module section id'),
2818 'sectionnum' => new external_value(PARAM_INT, 'The module section number'),
2819 'groupmode' => new external_value(PARAM_INT, 'Group mode'),
2820 'groupingid' => new external_value(PARAM_INT, 'Grouping id'),
2821 'completion' => new external_value(PARAM_INT, 'If completion is enabled'),
2822 'idnumber' => new external_value(PARAM_RAW, 'Module id number', VALUE_OPTIONAL),
2823 'added' => new external_value(PARAM_INT, 'Time added', VALUE_OPTIONAL),
2824 'score' => new external_value(PARAM_INT, 'Score', VALUE_OPTIONAL),
2825 'indent' => new external_value(PARAM_INT, 'Indentation', VALUE_OPTIONAL),
2826 'visible' => new external_value(PARAM_INT, 'If visible', VALUE_OPTIONAL),
2827 'visibleoncoursepage' => new external_value(PARAM_INT, 'If visible on course page', VALUE_OPTIONAL),
2828 'visibleold' => new external_value(PARAM_INT, 'Visible old', VALUE_OPTIONAL),
2829 'completiongradeitemnumber' => new external_value(PARAM_INT, 'Completion grade item', VALUE_OPTIONAL),
2830 'completionview' => new external_value(PARAM_INT, 'Completion view setting', VALUE_OPTIONAL),
2831 'completionexpected' => new external_value(PARAM_INT, 'Completion time expected', VALUE_OPTIONAL),
2832 'showdescription' => new external_value(PARAM_INT, 'If the description is showed', VALUE_OPTIONAL),
2833 'availability' => new external_value(PARAM_RAW, 'Availability settings', VALUE_OPTIONAL),
2834 'grade' => new external_value(PARAM_FLOAT, 'Grade (max value or scale id)', VALUE_OPTIONAL),
2835 'scale' => new external_value(PARAM_TEXT, 'Scale items (if used)', VALUE_OPTIONAL),
2836 'gradepass' => new external_value(PARAM_RAW, 'Grade to pass (float)', VALUE_OPTIONAL),
2837 'gradecat' => new external_value(PARAM_INT, 'Grade category', VALUE_OPTIONAL),
2838 'advancedgrading' => new external_multiple_structure(
2839 new external_single_structure(
2840 array(
2841 'area' => new external_value(PARAM_AREA, 'Gradable area name'),
2842 'method' => new external_value(PARAM_COMPONENT, 'Grading method'),
2845 'Advanced grading settings', VALUE_OPTIONAL
2847 'outcomes' => new external_multiple_structure(
2848 new external_single_structure(
2849 array(
2850 'id' => new external_value(PARAM_ALPHANUMEXT, 'Outcome id'),
2851 'name' => new external_value(PARAM_TEXT, 'Outcome full name'),
2852 'scale' => new external_value(PARAM_TEXT, 'Scale items')
2855 'Outcomes information', VALUE_OPTIONAL
2859 'warnings' => new external_warnings()
2865 * Returns description of method parameters
2867 * @return external_function_parameters
2868 * @since Moodle 3.0
2870 public static function get_course_module_by_instance_parameters() {
2871 return new external_function_parameters(
2872 array(
2873 'module' => new external_value(PARAM_COMPONENT, 'The module name'),
2874 'instance' => new external_value(PARAM_INT, 'The module instance id')
2880 * Return information about a course module.
2882 * @param string $module the module name
2883 * @param int $instance the activity instance id
2884 * @return array of warnings and the course module
2885 * @since Moodle 3.0
2886 * @throws moodle_exception
2888 public static function get_course_module_by_instance($module, $instance) {
2890 $params = self::validate_parameters(self::get_course_module_by_instance_parameters(),
2891 array(
2892 'module' => $module,
2893 'instance' => $instance,
2896 $warnings = array();
2897 $cm = get_coursemodule_from_instance($params['module'], $params['instance'], 0, false, MUST_EXIST);
2899 return self::get_course_module($cm->id);
2903 * Returns description of method result value
2905 * @return external_description
2906 * @since Moodle 3.0
2908 public static function get_course_module_by_instance_returns() {
2909 return self::get_course_module_returns();
2913 * Returns description of method parameters
2915 * @return external_function_parameters
2916 * @since Moodle 3.2
2918 public static function get_user_navigation_options_parameters() {
2919 return new external_function_parameters(
2920 array(
2921 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2927 * Return a list of navigation options in a set of courses that are avaialable or not for the current user.
2929 * @param array $courseids a list of course ids
2930 * @return array of warnings and the options availability
2931 * @since Moodle 3.2
2932 * @throws moodle_exception
2934 public static function get_user_navigation_options($courseids) {
2935 global $CFG;
2936 require_once($CFG->dirroot . '/course/lib.php');
2938 // Parameter validation.
2939 $params = self::validate_parameters(self::get_user_navigation_options_parameters(), array('courseids' => $courseids));
2940 $courseoptions = array();
2942 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
2944 if (!empty($courses)) {
2945 foreach ($courses as $course) {
2946 // Fix the context for the frontpage.
2947 if ($course->id == SITEID) {
2948 $course->context = context_system::instance();
2950 $navoptions = course_get_user_navigation_options($course->context, $course);
2951 $options = array();
2952 foreach ($navoptions as $name => $available) {
2953 $options[] = array(
2954 'name' => $name,
2955 'available' => $available,
2959 $courseoptions[] = array(
2960 'id' => $course->id,
2961 'options' => $options
2966 $result = array(
2967 'courses' => $courseoptions,
2968 'warnings' => $warnings
2970 return $result;
2974 * Returns description of method result value
2976 * @return external_description
2977 * @since Moodle 3.2
2979 public static function get_user_navigation_options_returns() {
2980 return new external_single_structure(
2981 array(
2982 'courses' => new external_multiple_structure(
2983 new external_single_structure(
2984 array(
2985 'id' => new external_value(PARAM_INT, 'Course id'),
2986 'options' => new external_multiple_structure(
2987 new external_single_structure(
2988 array(
2989 'name' => new external_value(PARAM_ALPHANUMEXT, 'Option name'),
2990 'available' => new external_value(PARAM_BOOL, 'Whether the option is available or not'),
2995 ), 'List of courses'
2997 'warnings' => new external_warnings()
3003 * Returns description of method parameters
3005 * @return external_function_parameters
3006 * @since Moodle 3.2
3008 public static function get_user_administration_options_parameters() {
3009 return new external_function_parameters(
3010 array(
3011 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
3017 * Return a list of administration options in a set of courses that are available or not for the current user.
3019 * @param array $courseids a list of course ids
3020 * @return array of warnings and the options availability
3021 * @since Moodle 3.2
3022 * @throws moodle_exception
3024 public static function get_user_administration_options($courseids) {
3025 global $CFG;
3026 require_once($CFG->dirroot . '/course/lib.php');
3028 // Parameter validation.
3029 $params = self::validate_parameters(self::get_user_administration_options_parameters(), array('courseids' => $courseids));
3030 $courseoptions = array();
3032 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
3034 if (!empty($courses)) {
3035 foreach ($courses as $course) {
3036 $adminoptions = course_get_user_administration_options($course, $course->context);
3037 $options = array();
3038 foreach ($adminoptions as $name => $available) {
3039 $options[] = array(
3040 'name' => $name,
3041 'available' => $available,
3045 $courseoptions[] = array(
3046 'id' => $course->id,
3047 'options' => $options
3052 $result = array(
3053 'courses' => $courseoptions,
3054 'warnings' => $warnings
3056 return $result;
3060 * Returns description of method result value
3062 * @return external_description
3063 * @since Moodle 3.2
3065 public static function get_user_administration_options_returns() {
3066 return self::get_user_navigation_options_returns();
3070 * Returns description of method parameters
3072 * @return external_function_parameters
3073 * @since Moodle 3.2
3075 public static function get_courses_by_field_parameters() {
3076 return new external_function_parameters(
3077 array(
3078 'field' => new external_value(PARAM_ALPHA, 'The field to search can be left empty for all courses or:
3079 id: course id
3080 ids: comma separated course ids
3081 shortname: course short name
3082 idnumber: course id number
3083 category: category id the course belongs to
3084 ', VALUE_DEFAULT, ''),
3085 'value' => new external_value(PARAM_RAW, 'The value to match', VALUE_DEFAULT, '')
3092 * Get courses matching a specific field (id/s, shortname, idnumber, category)
3094 * @param string $field field name to search, or empty for all courses
3095 * @param string $value value to search
3096 * @return array list of courses and warnings
3097 * @throws invalid_parameter_exception
3098 * @since Moodle 3.2
3100 public static function get_courses_by_field($field = '', $value = '') {
3101 global $DB, $CFG;
3102 require_once($CFG->dirroot . '/course/lib.php');
3103 require_once($CFG->libdir . '/filterlib.php');
3105 $params = self::validate_parameters(self::get_courses_by_field_parameters(),
3106 array(
3107 'field' => $field,
3108 'value' => $value,
3111 $warnings = array();
3113 if (empty($params['field'])) {
3114 $courses = $DB->get_records('course', null, 'id ASC');
3115 } else {
3116 switch ($params['field']) {
3117 case 'id':
3118 case 'category':
3119 $value = clean_param($params['value'], PARAM_INT);
3120 break;
3121 case 'ids':
3122 $value = clean_param($params['value'], PARAM_SEQUENCE);
3123 break;
3124 case 'shortname':
3125 $value = clean_param($params['value'], PARAM_TEXT);
3126 break;
3127 case 'idnumber':
3128 $value = clean_param($params['value'], PARAM_RAW);
3129 break;
3130 default:
3131 throw new invalid_parameter_exception('Invalid field name');
3134 if ($params['field'] === 'ids') {
3135 // Preload categories to avoid loading one at a time.
3136 $courseids = explode(',', $value);
3137 list ($listsql, $listparams) = $DB->get_in_or_equal($courseids);
3138 $categoryids = $DB->get_fieldset_sql("
3139 SELECT DISTINCT cc.id
3140 FROM {course} c
3141 JOIN {course_categories} cc ON cc.id = c.category
3142 WHERE c.id $listsql", $listparams);
3143 core_course_category::get_many($categoryids);
3145 // Load and validate all courses. This is called because it loads the courses
3146 // more efficiently.
3147 list ($courses, $warnings) = external_util::validate_courses($courseids, [],
3148 false, true);
3149 } else {
3150 $courses = $DB->get_records('course', array($params['field'] => $value), 'id ASC');
3154 $coursesdata = array();
3155 foreach ($courses as $course) {
3156 $context = context_course::instance($course->id);
3157 $canupdatecourse = has_capability('moodle/course:update', $context);
3158 $canviewhiddencourses = has_capability('moodle/course:viewhiddencourses', $context);
3160 // Check if the course is visible in the site for the user.
3161 if (!$course->visible and !$canviewhiddencourses and !$canupdatecourse) {
3162 continue;
3164 // Get the public course information, even if we are not enrolled.
3165 $courseinlist = new core_course_list_element($course);
3167 // Now, check if we have access to the course, unless it was already checked.
3168 try {
3169 if (empty($course->contextvalidated)) {
3170 self::validate_context($context);
3172 } catch (Exception $e) {
3173 // User can not access the course, check if they can see the public information about the course and return it.
3174 if (core_course_category::can_view_course_info($course)) {
3175 $coursesdata[$course->id] = self::get_course_public_information($courseinlist, $context);
3177 continue;
3179 $coursesdata[$course->id] = self::get_course_public_information($courseinlist, $context);
3180 // Return information for any user that can access the course.
3181 $coursefields = array('format', 'showgrades', 'newsitems', 'startdate', 'enddate', 'maxbytes', 'showreports', 'visible',
3182 'groupmode', 'groupmodeforce', 'defaultgroupingid', 'enablecompletion', 'completionnotify', 'lang', 'theme',
3183 'marker');
3185 // Course filters.
3186 $coursesdata[$course->id]['filters'] = filter_get_available_in_context($context);
3188 // Information for managers only.
3189 if ($canupdatecourse) {
3190 $managerfields = array('idnumber', 'legacyfiles', 'calendartype', 'timecreated', 'timemodified', 'requested',
3191 'cacherev');
3192 $coursefields = array_merge($coursefields, $managerfields);
3195 // Populate fields.
3196 foreach ($coursefields as $field) {
3197 $coursesdata[$course->id][$field] = $course->{$field};
3200 // Clean lang and auth fields for external functions (it may content uninstalled themes or language packs).
3201 if (isset($coursesdata[$course->id]['theme'])) {
3202 $coursesdata[$course->id]['theme'] = clean_param($coursesdata[$course->id]['theme'], PARAM_THEME);
3204 if (isset($coursesdata[$course->id]['lang'])) {
3205 $coursesdata[$course->id]['lang'] = clean_param($coursesdata[$course->id]['lang'], PARAM_LANG);
3208 $courseformatoptions = course_get_format($course)->get_config_for_external();
3209 foreach ($courseformatoptions as $key => $value) {
3210 $coursesdata[$course->id]['courseformatoptions'][] = array(
3211 'name' => $key,
3212 'value' => $value
3217 return array(
3218 'courses' => $coursesdata,
3219 'warnings' => $warnings
3224 * Returns description of method result value
3226 * @return external_description
3227 * @since Moodle 3.2
3229 public static function get_courses_by_field_returns() {
3230 // Course structure, including not only public viewable fields.
3231 return new external_single_structure(
3232 array(
3233 'courses' => new external_multiple_structure(self::get_course_structure(false), 'Course'),
3234 'warnings' => new external_warnings()
3240 * Returns description of method parameters
3242 * @return external_function_parameters
3243 * @since Moodle 3.2
3245 public static function check_updates_parameters() {
3246 return new external_function_parameters(
3247 array(
3248 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3249 'tocheck' => new external_multiple_structure(
3250 new external_single_structure(
3251 array(
3252 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level for the file location.
3253 Only module supported right now.'),
3254 'id' => new external_value(PARAM_INT, 'Context instance id'),
3255 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3258 'Instances to check'
3260 'filter' => new external_multiple_structure(
3261 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3262 gradeitems, outcomes'),
3263 'Check only for updates in these areas', VALUE_DEFAULT, array()
3270 * Check if there is updates affecting the user for the given course and contexts.
3271 * Right now only modules are supported.
3272 * This WS calls mod_check_updates_since for each module to check if there is any update the user should we aware of.
3274 * @param int $courseid the list of modules to check
3275 * @param array $tocheck the list of modules to check
3276 * @param array $filter check only for updates in these areas
3277 * @return array list of updates and warnings
3278 * @throws moodle_exception
3279 * @since Moodle 3.2
3281 public static function check_updates($courseid, $tocheck, $filter = array()) {
3282 global $CFG, $DB;
3283 require_once($CFG->dirroot . "/course/lib.php");
3285 $params = self::validate_parameters(
3286 self::check_updates_parameters(),
3287 array(
3288 'courseid' => $courseid,
3289 'tocheck' => $tocheck,
3290 'filter' => $filter,
3294 $course = get_course($params['courseid']);
3295 $context = context_course::instance($course->id);
3296 self::validate_context($context);
3298 list($instances, $warnings) = course_check_updates($course, $params['tocheck'], $filter);
3300 $instancesformatted = array();
3301 foreach ($instances as $instance) {
3302 $updates = array();
3303 foreach ($instance['updates'] as $name => $data) {
3304 if (empty($data->updated)) {
3305 continue;
3307 $updatedata = array(
3308 'name' => $name,
3310 if (!empty($data->timeupdated)) {
3311 $updatedata['timeupdated'] = $data->timeupdated;
3313 if (!empty($data->itemids)) {
3314 $updatedata['itemids'] = $data->itemids;
3316 $updates[] = $updatedata;
3318 if (!empty($updates)) {
3319 $instancesformatted[] = array(
3320 'contextlevel' => $instance['contextlevel'],
3321 'id' => $instance['id'],
3322 'updates' => $updates
3327 return array(
3328 'instances' => $instancesformatted,
3329 'warnings' => $warnings
3334 * Returns description of method result value
3336 * @return external_description
3337 * @since Moodle 3.2
3339 public static function check_updates_returns() {
3340 return new external_single_structure(
3341 array(
3342 'instances' => new external_multiple_structure(
3343 new external_single_structure(
3344 array(
3345 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level'),
3346 'id' => new external_value(PARAM_INT, 'Instance id'),
3347 'updates' => new external_multiple_structure(
3348 new external_single_structure(
3349 array(
3350 'name' => new external_value(PARAM_ALPHANUMEXT, 'Name of the area updated.'),
3351 'timeupdated' => new external_value(PARAM_INT, 'Last time was updated', VALUE_OPTIONAL),
3352 'itemids' => new external_multiple_structure(
3353 new external_value(PARAM_INT, 'Instance id'),
3354 'The ids of the items updated',
3355 VALUE_OPTIONAL
3363 'warnings' => new external_warnings()
3369 * Returns description of method parameters
3371 * @return external_function_parameters
3372 * @since Moodle 3.3
3374 public static function get_updates_since_parameters() {
3375 return new external_function_parameters(
3376 array(
3377 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3378 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3379 'filter' => new external_multiple_structure(
3380 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3381 gradeitems, outcomes'),
3382 'Check only for updates in these areas', VALUE_DEFAULT, array()
3389 * Check if there are updates affecting the user for the given course since the given time stamp.
3391 * This function is a wrapper of self::check_updates for retrieving all the updates since a given time for all the activities.
3393 * @param int $courseid the list of modules to check
3394 * @param int $since check updates since this time stamp
3395 * @param array $filter check only for updates in these areas
3396 * @return array list of updates and warnings
3397 * @throws moodle_exception
3398 * @since Moodle 3.3
3400 public static function get_updates_since($courseid, $since, $filter = array()) {
3401 global $CFG, $DB;
3403 $params = self::validate_parameters(
3404 self::get_updates_since_parameters(),
3405 array(
3406 'courseid' => $courseid,
3407 'since' => $since,
3408 'filter' => $filter,
3412 $course = get_course($params['courseid']);
3413 $modinfo = get_fast_modinfo($course);
3414 $tocheck = array();
3416 // Retrieve all the visible course modules for the current user.
3417 $cms = $modinfo->get_cms();
3418 foreach ($cms as $cm) {
3419 if (!$cm->uservisible) {
3420 continue;
3422 $tocheck[] = array(
3423 'id' => $cm->id,
3424 'contextlevel' => 'module',
3425 'since' => $params['since'],
3429 return self::check_updates($course->id, $tocheck, $params['filter']);
3433 * Returns description of method result value
3435 * @return external_description
3436 * @since Moodle 3.3
3438 public static function get_updates_since_returns() {
3439 return self::check_updates_returns();
3443 * Parameters for function edit_module()
3445 * @since Moodle 3.3
3446 * @return external_function_parameters
3448 public static function edit_module_parameters() {
3449 return new external_function_parameters(
3450 array(
3451 'action' => new external_value(PARAM_ALPHA,
3452 'action: hide, show, stealth, duplicate, delete, moveleft, moveright, group...', VALUE_REQUIRED),
3453 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3454 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3459 * Performs one of the edit module actions and return new html for AJAX
3461 * Returns html to replace the current module html with, for example:
3462 * - empty string for "delete" action,
3463 * - two modules html for "duplicate" action
3464 * - updated module html for everything else
3466 * Throws exception if operation is not permitted/possible
3468 * @since Moodle 3.3
3469 * @param string $action
3470 * @param int $id
3471 * @param null|int $sectionreturn
3472 * @return string
3474 public static function edit_module($action, $id, $sectionreturn = null) {
3475 global $PAGE, $DB;
3476 // Validate and normalize parameters.
3477 $params = self::validate_parameters(self::edit_module_parameters(),
3478 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3479 $action = $params['action'];
3480 $id = $params['id'];
3481 $sectionreturn = $params['sectionreturn'];
3483 // Set of permissions an editing user may have.
3484 $contextarray = [
3485 'moodle/course:update',
3486 'moodle/course:manageactivities',
3487 'moodle/course:activityvisibility',
3488 'moodle/course:sectionvisibility',
3489 'moodle/course:movesections',
3490 'moodle/course:setcurrentsection',
3492 $PAGE->set_other_editing_capability($contextarray);
3494 list($course, $cm) = get_course_and_cm_from_cmid($id);
3495 $modcontext = context_module::instance($cm->id);
3496 $coursecontext = context_course::instance($course->id);
3497 self::validate_context($modcontext);
3498 $courserenderer = $PAGE->get_renderer('core', 'course');
3499 $completioninfo = new completion_info($course);
3501 switch($action) {
3502 case 'hide':
3503 case 'show':
3504 case 'stealth':
3505 require_capability('moodle/course:activityvisibility', $modcontext);
3506 $visible = ($action === 'hide') ? 0 : 1;
3507 $visibleoncoursepage = ($action === 'stealth') ? 0 : 1;
3508 set_coursemodule_visible($id, $visible, $visibleoncoursepage);
3509 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3510 break;
3511 case 'duplicate':
3512 require_capability('moodle/course:manageactivities', $coursecontext);
3513 require_capability('moodle/backup:backuptargetimport', $coursecontext);
3514 require_capability('moodle/restore:restoretargetimport', $coursecontext);
3515 if (!course_allowed_module($course, $cm->modname)) {
3516 throw new moodle_exception('No permission to create that activity');
3518 if ($newcm = duplicate_module($course, $cm)) {
3519 $cm = get_fast_modinfo($course)->get_cm($id);
3520 $newcm = get_fast_modinfo($course)->get_cm($newcm->id);
3521 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn) .
3522 $courserenderer->course_section_cm_list_item($course, $completioninfo, $newcm, $sectionreturn);
3524 break;
3525 case 'groupsseparate':
3526 case 'groupsvisible':
3527 case 'groupsnone':
3528 require_capability('moodle/course:manageactivities', $modcontext);
3529 if ($action === 'groupsseparate') {
3530 $newgroupmode = SEPARATEGROUPS;
3531 } else if ($action === 'groupsvisible') {
3532 $newgroupmode = VISIBLEGROUPS;
3533 } else {
3534 $newgroupmode = NOGROUPS;
3536 if (set_coursemodule_groupmode($cm->id, $newgroupmode)) {
3537 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3539 break;
3540 case 'moveleft':
3541 case 'moveright':
3542 require_capability('moodle/course:manageactivities', $modcontext);
3543 $indent = $cm->indent + (($action === 'moveright') ? 1 : -1);
3544 if ($cm->indent >= 0) {
3545 $DB->update_record('course_modules', array('id' => $cm->id, 'indent' => $indent));
3546 rebuild_course_cache($cm->course);
3548 break;
3549 case 'delete':
3550 require_capability('moodle/course:manageactivities', $modcontext);
3551 course_delete_module($cm->id, true);
3552 return '';
3553 default:
3554 throw new coding_exception('Unrecognised action');
3557 $cm = get_fast_modinfo($course)->get_cm($id);
3558 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn);
3562 * Return structure for edit_module()
3564 * @since Moodle 3.3
3565 * @return external_description
3567 public static function edit_module_returns() {
3568 return new external_value(PARAM_RAW, 'html to replace the current module with');
3572 * Parameters for function get_module()
3574 * @since Moodle 3.3
3575 * @return external_function_parameters
3577 public static function get_module_parameters() {
3578 return new external_function_parameters(
3579 array(
3580 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3581 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3586 * Returns html for displaying one activity module on course page
3588 * @since Moodle 3.3
3589 * @param int $id
3590 * @param null|int $sectionreturn
3591 * @return string
3593 public static function get_module($id, $sectionreturn = null) {
3594 global $PAGE;
3595 // Validate and normalize parameters.
3596 $params = self::validate_parameters(self::get_module_parameters(),
3597 array('id' => $id, 'sectionreturn' => $sectionreturn));
3598 $id = $params['id'];
3599 $sectionreturn = $params['sectionreturn'];
3601 // Set of permissions an editing user may have.
3602 $contextarray = [
3603 'moodle/course:update',
3604 'moodle/course:manageactivities',
3605 'moodle/course:activityvisibility',
3606 'moodle/course:sectionvisibility',
3607 'moodle/course:movesections',
3608 'moodle/course:setcurrentsection',
3610 $PAGE->set_other_editing_capability($contextarray);
3612 // Validate access to the course (note, this is html for the course view page, we don't validate access to the module).
3613 list($course, $cm) = get_course_and_cm_from_cmid($id);
3614 self::validate_context(context_course::instance($course->id));
3616 $courserenderer = $PAGE->get_renderer('core', 'course');
3617 $completioninfo = new completion_info($course);
3618 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn);
3622 * Return structure for get_module()
3624 * @since Moodle 3.3
3625 * @return external_description
3627 public static function get_module_returns() {
3628 return new external_value(PARAM_RAW, 'html to replace the current module with');
3632 * Parameters for function edit_section()
3634 * @since Moodle 3.3
3635 * @return external_function_parameters
3637 public static function edit_section_parameters() {
3638 return new external_function_parameters(
3639 array(
3640 'action' => new external_value(PARAM_ALPHA, 'action: hide, show, stealth, setmarker, removemarker', VALUE_REQUIRED),
3641 'id' => new external_value(PARAM_INT, 'course section id', VALUE_REQUIRED),
3642 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3647 * Performs one of the edit section actions
3649 * @since Moodle 3.3
3650 * @param string $action
3651 * @param int $id section id
3652 * @param int $sectionreturn section to return to
3653 * @return string
3655 public static function edit_section($action, $id, $sectionreturn) {
3656 global $DB;
3657 // Validate and normalize parameters.
3658 $params = self::validate_parameters(self::edit_section_parameters(),
3659 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3660 $action = $params['action'];
3661 $id = $params['id'];
3662 $sr = $params['sectionreturn'];
3664 $section = $DB->get_record('course_sections', array('id' => $id), '*', MUST_EXIST);
3665 $coursecontext = context_course::instance($section->course);
3666 self::validate_context($coursecontext);
3668 $rv = course_get_format($section->course)->section_action($section, $action, $sectionreturn);
3669 if ($rv) {
3670 return json_encode($rv);
3671 } else {
3672 return null;
3677 * Return structure for edit_section()
3679 * @since Moodle 3.3
3680 * @return external_description
3682 public static function edit_section_returns() {
3683 return new external_value(PARAM_RAW, 'Additional data for javascript (JSON-encoded string)');
3687 * Returns description of method parameters
3689 * @return external_function_parameters
3691 public static function get_enrolled_courses_by_timeline_classification_parameters() {
3692 return new external_function_parameters(
3693 array(
3694 'classification' => new external_value(PARAM_ALPHA, 'future, inprogress, or past'),
3695 'limit' => new external_value(PARAM_INT, 'Result set limit', VALUE_DEFAULT, 0),
3696 'offset' => new external_value(PARAM_INT, 'Result set offset', VALUE_DEFAULT, 0),
3697 'sort' => new external_value(PARAM_TEXT, 'Sort string', VALUE_DEFAULT, null),
3698 'customfieldname' => new external_value(PARAM_ALPHANUMEXT, 'Used when classification = customfield',
3699 VALUE_DEFAULT, null),
3700 'customfieldvalue' => new external_value(PARAM_RAW, 'Used when classification = customfield',
3701 VALUE_DEFAULT, null),
3707 * Get courses matching the given timeline classification.
3709 * NOTE: The offset applies to the unfiltered full set of courses before the classification
3710 * filtering is done.
3711 * E.g.
3712 * If the user is enrolled in 5 courses:
3713 * c1, c2, c3, c4, and c5
3714 * And c4 and c5 are 'future' courses
3716 * If a request comes in for future courses with an offset of 1 it will mean that
3717 * c1 is skipped (because the offset applies *before* the classification filtering)
3718 * and c4 and c5 will be return.
3720 * @param string $classification past, inprogress, or future
3721 * @param int $limit Result set limit
3722 * @param int $offset Offset the full course set before timeline classification is applied
3723 * @param string $sort SQL sort string for results
3724 * @param string $customfieldname
3725 * @param string $customfieldvalue
3726 * @return array list of courses and warnings
3727 * @throws invalid_parameter_exception
3729 public static function get_enrolled_courses_by_timeline_classification(
3730 string $classification,
3731 int $limit = 0,
3732 int $offset = 0,
3733 string $sort = null,
3734 string $customfieldname = null,
3735 string $customfieldvalue = null
3737 global $CFG, $PAGE, $USER;
3738 require_once($CFG->dirroot . '/course/lib.php');
3740 $params = self::validate_parameters(self::get_enrolled_courses_by_timeline_classification_parameters(),
3741 array(
3742 'classification' => $classification,
3743 'limit' => $limit,
3744 'offset' => $offset,
3745 'sort' => $sort,
3746 'customfieldvalue' => $customfieldvalue,
3750 $classification = $params['classification'];
3751 $limit = $params['limit'];
3752 $offset = $params['offset'];
3753 $sort = $params['sort'];
3754 $customfieldvalue = $params['customfieldvalue'];
3756 switch($classification) {
3757 case COURSE_TIMELINE_ALLINCLUDINGHIDDEN:
3758 break;
3759 case COURSE_TIMELINE_ALL:
3760 break;
3761 case COURSE_TIMELINE_PAST:
3762 break;
3763 case COURSE_TIMELINE_INPROGRESS:
3764 break;
3765 case COURSE_TIMELINE_FUTURE:
3766 break;
3767 case COURSE_FAVOURITES:
3768 break;
3769 case COURSE_TIMELINE_HIDDEN:
3770 break;
3771 case COURSE_CUSTOMFIELD:
3772 break;
3773 default:
3774 throw new invalid_parameter_exception('Invalid classification');
3777 self::validate_context(context_user::instance($USER->id));
3779 $requiredproperties = course_summary_exporter::define_properties();
3780 $fields = join(',', array_keys($requiredproperties));
3781 $hiddencourses = get_hidden_courses_on_timeline();
3782 $courses = [];
3784 // If the timeline requires really all courses, get really all courses.
3785 if ($classification == COURSE_TIMELINE_ALLINCLUDINGHIDDEN) {
3786 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields, COURSE_DB_QUERY_LIMIT);
3788 // Otherwise if the timeline requires the hidden courses then restrict the result to only $hiddencourses.
3789 } else if ($classification == COURSE_TIMELINE_HIDDEN) {
3790 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields,
3791 COURSE_DB_QUERY_LIMIT, $hiddencourses);
3793 // Otherwise get the requested courses and exclude the hidden courses.
3794 } else {
3795 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields,
3796 COURSE_DB_QUERY_LIMIT, [], $hiddencourses);
3799 $favouritecourseids = [];
3800 $ufservice = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($USER->id));
3801 $favourites = $ufservice->find_favourites_by_type('core_course', 'courses');
3803 if ($favourites) {
3804 $favouritecourseids = array_map(
3805 function($favourite) {
3806 return $favourite->itemid;
3807 }, $favourites);
3810 if ($classification == COURSE_FAVOURITES) {
3811 list($filteredcourses, $processedcount) = course_filter_courses_by_favourites(
3812 $courses,
3813 $favouritecourseids,
3814 $limit
3816 } else if ($classification == COURSE_CUSTOMFIELD) {
3817 list($filteredcourses, $processedcount) = course_filter_courses_by_customfield(
3818 $courses,
3819 $customfieldname,
3820 $customfieldvalue,
3821 $limit
3823 } else {
3824 list($filteredcourses, $processedcount) = course_filter_courses_by_timeline_classification(
3825 $courses,
3826 $classification,
3827 $limit
3831 $renderer = $PAGE->get_renderer('core');
3832 $formattedcourses = array_map(function($course) use ($renderer, $favouritecourseids) {
3833 context_helper::preload_from_record($course);
3834 $context = context_course::instance($course->id);
3835 $isfavourite = false;
3836 if (in_array($course->id, $favouritecourseids)) {
3837 $isfavourite = true;
3839 $exporter = new course_summary_exporter($course, ['context' => $context, 'isfavourite' => $isfavourite]);
3840 return $exporter->export($renderer);
3841 }, $filteredcourses);
3843 return [
3844 'courses' => $formattedcourses,
3845 'nextoffset' => $offset + $processedcount
3850 * Returns description of method result value
3852 * @return external_description
3854 public static function get_enrolled_courses_by_timeline_classification_returns() {
3855 return new external_single_structure(
3856 array(
3857 'courses' => new external_multiple_structure(course_summary_exporter::get_read_structure(), 'Course'),
3858 'nextoffset' => new external_value(PARAM_INT, 'Offset for the next request')
3864 * Returns description of method parameters
3866 * @return external_function_parameters
3868 public static function set_favourite_courses_parameters() {
3869 return new external_function_parameters(
3870 array(
3871 'courses' => new external_multiple_structure(
3872 new external_single_structure(
3873 array(
3874 'id' => new external_value(PARAM_INT, 'course ID'),
3875 'favourite' => new external_value(PARAM_BOOL, 'favourite status')
3884 * Set the course favourite status for an array of courses.
3886 * @param array $courses List with course id's and favourite status.
3887 * @return array Array with an array of favourite courses.
3889 public static function set_favourite_courses(
3890 array $courses
3892 global $USER;
3894 $params = self::validate_parameters(self::set_favourite_courses_parameters(),
3895 array(
3896 'courses' => $courses
3900 $warnings = [];
3902 $ufservice = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($USER->id));
3904 foreach ($params['courses'] as $course) {
3906 $warning = [];
3908 $favouriteexists = $ufservice->favourite_exists('core_course', 'courses', $course['id'],
3909 \context_course::instance($course['id']));
3911 if ($course['favourite']) {
3912 if (!$favouriteexists) {
3913 try {
3914 $ufservice->create_favourite('core_course', 'courses', $course['id'],
3915 \context_course::instance($course['id']));
3916 } catch (Exception $e) {
3917 $warning['courseid'] = $course['id'];
3918 if ($e instanceof moodle_exception) {
3919 $warning['warningcode'] = $e->errorcode;
3920 } else {
3921 $warning['warningcode'] = $e->getCode();
3923 $warning['message'] = $e->getMessage();
3924 $warnings[] = $warning;
3925 $warnings[] = $warning;
3927 } else {
3928 $warning['courseid'] = $course['id'];
3929 $warning['warningcode'] = 'coursealreadyfavourited';
3930 $warning['message'] = 'Course already favourited';
3931 $warnings[] = $warning;
3933 } else {
3934 if ($favouriteexists) {
3935 try {
3936 $ufservice->delete_favourite('core_course', 'courses', $course['id'],
3937 \context_course::instance($course['id']));
3938 } catch (Exception $e) {
3939 $warning['courseid'] = $course['id'];
3940 if ($e instanceof moodle_exception) {
3941 $warning['warningcode'] = $e->errorcode;
3942 } else {
3943 $warning['warningcode'] = $e->getCode();
3945 $warning['message'] = $e->getMessage();
3946 $warnings[] = $warning;
3947 $warnings[] = $warning;
3949 } else {
3950 $warning['courseid'] = $course['id'];
3951 $warning['warningcode'] = 'cannotdeletefavourite';
3952 $warning['message'] = 'Could not delete favourite status for course';
3953 $warnings[] = $warning;
3958 return [
3959 'warnings' => $warnings
3964 * Returns description of method result value
3966 * @return external_description
3968 public static function set_favourite_courses_returns() {
3969 return new external_single_structure(
3970 array(
3971 'warnings' => new external_warnings()
3977 * Returns description of method parameters
3979 * @return external_function_parameters
3980 * @since Moodle 3.6
3982 public static function get_recent_courses_parameters() {
3983 return new external_function_parameters(
3984 array(
3985 'userid' => new external_value(PARAM_INT, 'id of the user, default to current user', VALUE_DEFAULT, 0),
3986 'limit' => new external_value(PARAM_INT, 'result set limit', VALUE_DEFAULT, 0),
3987 'offset' => new external_value(PARAM_INT, 'Result set offset', VALUE_DEFAULT, 0),
3988 'sort' => new external_value(PARAM_TEXT, 'Sort string', VALUE_DEFAULT, null)
3994 * Get last accessed courses adding additional course information like images.
3996 * @param int $userid User id from which the courses will be obtained
3997 * @param int $limit Restrict result set to this amount
3998 * @param int $offset Skip this number of records from the start of the result set
3999 * @param string|null $sort SQL string for sorting
4000 * @return array List of courses
4001 * @throws invalid_parameter_exception
4003 public static function get_recent_courses(int $userid = 0, int $limit = 0, int $offset = 0, string $sort = null) {
4004 global $USER, $PAGE;
4006 if (empty($userid)) {
4007 $userid = $USER->id;
4010 $params = self::validate_parameters(self::get_recent_courses_parameters(),
4011 array(
4012 'userid' => $userid,
4013 'limit' => $limit,
4014 'offset' => $offset,
4015 'sort' => $sort
4019 $userid = $params['userid'];
4020 $limit = $params['limit'];
4021 $offset = $params['offset'];
4022 $sort = $params['sort'];
4024 $usercontext = context_user::instance($userid);
4026 self::validate_context($usercontext);
4028 if ($userid != $USER->id and !has_capability('moodle/user:viewdetails', $usercontext)) {
4029 return array();
4032 $courses = course_get_recent_courses($userid, $limit, $offset, $sort);
4034 $renderer = $PAGE->get_renderer('core');
4036 $recentcourses = array_map(function($course) use ($renderer) {
4037 context_helper::preload_from_record($course);
4038 $context = context_course::instance($course->id);
4039 $isfavourite = !empty($course->component);
4040 $exporter = new course_summary_exporter($course, ['context' => $context, 'isfavourite' => $isfavourite]);
4041 return $exporter->export($renderer);
4042 }, $courses);
4044 return $recentcourses;
4048 * Returns description of method result value
4050 * @return external_description
4051 * @since Moodle 3.6
4053 public static function get_recent_courses_returns() {
4054 return new external_multiple_structure(course_summary_exporter::get_read_structure(), 'Courses');
4058 * Returns description of method parameters
4060 * @return external_function_parameters
4062 public static function get_enrolled_users_by_cmid_parameters() {
4063 return new external_function_parameters([
4064 'cmid' => new external_value(PARAM_INT, 'id of the course module', VALUE_REQUIRED),
4065 'groupid' => new external_value(PARAM_INT, 'id of the group', VALUE_DEFAULT, 0),
4070 * Get all users in a course for a given cmid.
4072 * @param int $cmid Course Module id from which the users will be obtained
4073 * @param int $groupid Group id from which the users will be obtained
4074 * @return array List of users
4075 * @throws invalid_parameter_exception
4077 public static function get_enrolled_users_by_cmid(int $cmid, int $groupid = 0) {
4078 global $PAGE;
4079 $warnings = [];
4082 'cmid' => $cmid,
4083 'groupid' => $groupid,
4084 ] = self::validate_parameters(self::get_enrolled_users_by_cmid_parameters(), [
4085 'cmid' => $cmid,
4086 'groupid' => $groupid,
4089 list($course, $cm) = get_course_and_cm_from_cmid($cmid);
4090 $coursecontext = context_course::instance($course->id);
4091 self::validate_context($coursecontext);
4093 $enrolledusers = get_enrolled_users($coursecontext, '', $groupid);
4095 $users = array_map(function ($user) use ($PAGE) {
4096 $user->fullname = fullname($user);
4097 $userpicture = new user_picture($user);
4098 $userpicture->size = 1;
4099 $user->profileimage = $userpicture->get_url($PAGE)->out(false);
4100 return $user;
4101 }, $enrolledusers);
4102 sort($users);
4104 return [
4105 'users' => $users,
4106 'warnings' => $warnings,
4111 * Returns description of method result value
4113 * @return external_description
4115 public static function get_enrolled_users_by_cmid_returns() {
4116 return new external_single_structure([
4117 'users' => new external_multiple_structure(self::user_description()),
4118 'warnings' => new external_warnings(),
4123 * Create user return value description.
4125 * @return external_description
4127 public static function user_description() {
4128 $userfields = array(
4129 'id' => new external_value(core_user::get_property_type('id'), 'ID of the user'),
4130 'profileimage' => new external_value(PARAM_URL, 'The location of the users larger image', VALUE_OPTIONAL),
4131 'fullname' => new external_value(PARAM_TEXT, 'The full name of the user', VALUE_OPTIONAL),
4132 'firstname' => new external_value(
4133 core_user::get_property_type('firstname'),
4134 'The first name(s) of the user',
4135 VALUE_OPTIONAL),
4136 'lastname' => new external_value(
4137 core_user::get_property_type('lastname'),
4138 'The family name of the user',
4139 VALUE_OPTIONAL),
4141 return new external_single_structure($userfields);