Merge branch 'MDL-60991' of https://github.com/mkassaei/moodle
[moodle.git] / course / externallib.php
blob62e868fb4bee937479ea60131caa446c68b40937
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 require_once("$CFG->libdir/externallib.php");
31 /**
32 * Course external functions
34 * @package core_course
35 * @category external
36 * @copyright 2011 Jerome Mouneyrac
37 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 * @since Moodle 2.2
40 class core_course_external extends external_api {
42 /**
43 * Returns description of method parameters
45 * @return external_function_parameters
46 * @since Moodle 2.9 Options available
47 * @since Moodle 2.2
49 public static function get_course_contents_parameters() {
50 return new external_function_parameters(
51 array('courseid' => new external_value(PARAM_INT, 'course id'),
52 'options' => new external_multiple_structure (
53 new external_single_structure(
54 array(
55 'name' => new external_value(PARAM_ALPHANUM,
56 'The expected keys (value format) are:
57 excludemodules (bool) Do not return modules, return only the sections structure
58 excludecontents (bool) Do not return module contents (i.e: files inside a resource)
59 sectionid (int) Return only this section
60 sectionnumber (int) Return only this section with number (order)
61 cmid (int) Return only this module information (among the whole sections structure)
62 modname (string) Return only modules with this name "label, forum, etc..."
63 modid (int) Return only the module with this id (to be used with modname'),
64 'value' => new external_value(PARAM_RAW, 'the value of the option,
65 this param is personaly validated in the external function.')
67 ), 'Options, used since Moodle 2.9', VALUE_DEFAULT, array())
72 /**
73 * Get course contents
75 * @param int $courseid course id
76 * @param array $options Options for filtering the results, used since Moodle 2.9
77 * @return array
78 * @since Moodle 2.9 Options available
79 * @since Moodle 2.2
81 public static function get_course_contents($courseid, $options = array()) {
82 global $CFG, $DB;
83 require_once($CFG->dirroot . "/course/lib.php");
85 //validate parameter
86 $params = self::validate_parameters(self::get_course_contents_parameters(),
87 array('courseid' => $courseid, 'options' => $options));
89 $filters = array();
90 if (!empty($params['options'])) {
92 foreach ($params['options'] as $option) {
93 $name = trim($option['name']);
94 // Avoid duplicated options.
95 if (!isset($filters[$name])) {
96 switch ($name) {
97 case 'excludemodules':
98 case 'excludecontents':
99 $value = clean_param($option['value'], PARAM_BOOL);
100 $filters[$name] = $value;
101 break;
102 case 'sectionid':
103 case 'sectionnumber':
104 case 'cmid':
105 case 'modid':
106 $value = clean_param($option['value'], PARAM_INT);
107 if (is_numeric($value)) {
108 $filters[$name] = $value;
109 } else {
110 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
112 break;
113 case 'modname':
114 $value = clean_param($option['value'], PARAM_PLUGIN);
115 if ($value) {
116 $filters[$name] = $value;
117 } else {
118 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
120 break;
121 default:
122 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
128 //retrieve the course
129 $course = $DB->get_record('course', array('id' => $params['courseid']), '*', MUST_EXIST);
131 if ($course->id != SITEID) {
132 // Check course format exist.
133 if (!file_exists($CFG->dirroot . '/course/format/' . $course->format . '/lib.php')) {
134 throw new moodle_exception('cannotgetcoursecontents', 'webservice', '', null,
135 get_string('courseformatnotfound', 'error', $course->format));
136 } else {
137 require_once($CFG->dirroot . '/course/format/' . $course->format . '/lib.php');
141 // now security checks
142 $context = context_course::instance($course->id, IGNORE_MISSING);
143 try {
144 self::validate_context($context);
145 } catch (Exception $e) {
146 $exceptionparam = new stdClass();
147 $exceptionparam->message = $e->getMessage();
148 $exceptionparam->courseid = $course->id;
149 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
152 $canupdatecourse = has_capability('moodle/course:update', $context);
154 //create return value
155 $coursecontents = array();
157 if ($canupdatecourse or $course->visible
158 or has_capability('moodle/course:viewhiddencourses', $context)) {
160 //retrieve sections
161 $modinfo = get_fast_modinfo($course);
162 $sections = $modinfo->get_section_info_all();
163 $coursenumsections = course_get_format($course)->get_last_section_number();
165 //for each sections (first displayed to last displayed)
166 $modinfosections = $modinfo->get_sections();
167 foreach ($sections as $key => $section) {
169 // Show the section if the user is permitted to access it, OR if it's not available
170 // but there is some available info text which explains the reason & should display.
171 $showsection = $section->uservisible ||
172 ($section->visible && !$section->available &&
173 !empty($section->availableinfo));
175 if (!$showsection) {
176 continue;
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 (if it is visible).
220 if ($section->uservisible and 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'] = $cm->modname;
265 $module['modplural'] = $cm->modplural;
266 $module['modicon'] = $cm->get_icon_url()->out(false);
267 $module['indent'] = $cm->indent;
269 if (!empty($cm->showdescription) or $cm->modname == 'label') {
270 // We want to use the external format. However from reading get_formatted_content(), $cm->content format is always FORMAT_HTML.
271 $options = array('noclean' => true);
272 list($module['description'], $descriptionformat) = external_format_text($cm->content,
273 FORMAT_HTML, $modcontext->id, $cm->modname, 'intro', $cm->id, $options);
276 //url of the module
277 $url = $cm->url;
278 if ($url) { //labels don't have url
279 $module['url'] = $url->out(false);
282 $canviewhidden = has_capability('moodle/course:viewhiddenactivities',
283 context_module::instance($cm->id));
284 //user that can view hidden module should know about the visibility
285 $module['visible'] = $cm->visible;
286 $module['visibleoncoursepage'] = $cm->visibleoncoursepage;
287 $module['uservisible'] = $cm->uservisible;
288 if (!empty($cm->availableinfo)) {
289 $module['availabilityinfo'] = \core_availability\info::format_info($cm->availableinfo, $course);
292 // Availability date (also send to user who can see hidden module).
293 if ($CFG->enableavailability && ($canviewhidden || $canupdatecourse)) {
294 $module['availability'] = $cm->availability;
297 // Return contents only if the user can access to the module.
298 if ($cm->uservisible) {
299 $baseurl = 'webservice/pluginfile.php';
301 // Call $modulename_export_contents (each module callback take care about checking the capabilities).
302 require_once($CFG->dirroot . '/mod/' . $cm->modname . '/lib.php');
303 $getcontentfunction = $cm->modname.'_export_contents';
304 if (function_exists($getcontentfunction)) {
305 if (empty($filters['excludecontents']) and $contents = $getcontentfunction($cm, $baseurl)) {
306 $module['contents'] = $contents;
307 } else {
308 $module['contents'] = array();
313 //assign result to $sectioncontents
314 $sectioncontents[] = $module;
316 // If we just did a filtering, break the loop.
317 if ($modfound) {
318 break;
323 $sectionvalues['modules'] = $sectioncontents;
325 // assign result to $coursecontents
326 $coursecontents[] = $sectionvalues;
328 // Break the loop if we are filtering.
329 if ($sectionfound) {
330 break;
334 return $coursecontents;
338 * Returns description of method result value
340 * @return external_description
341 * @since Moodle 2.2
343 public static function get_course_contents_returns() {
344 return new external_multiple_structure(
345 new external_single_structure(
346 array(
347 'id' => new external_value(PARAM_INT, 'Section ID'),
348 'name' => new external_value(PARAM_TEXT, 'Section name'),
349 'visible' => new external_value(PARAM_INT, 'is the section visible', VALUE_OPTIONAL),
350 'summary' => new external_value(PARAM_RAW, 'Section description'),
351 'summaryformat' => new external_format_value('summary'),
352 'section' => new external_value(PARAM_INT, 'Section number inside the course', VALUE_OPTIONAL),
353 'hiddenbynumsections' => new external_value(PARAM_INT, 'Whether is a section hidden in the course format',
354 VALUE_OPTIONAL),
355 'uservisible' => new external_value(PARAM_BOOL, 'Is the section visible for the user?', VALUE_OPTIONAL),
356 'availabilityinfo' => new external_value(PARAM_RAW, 'Availability information.', VALUE_OPTIONAL),
357 'modules' => new external_multiple_structure(
358 new external_single_structure(
359 array(
360 'id' => new external_value(PARAM_INT, 'activity id'),
361 'url' => new external_value(PARAM_URL, 'activity url', VALUE_OPTIONAL),
362 'name' => new external_value(PARAM_RAW, 'activity module name'),
363 'instance' => new external_value(PARAM_INT, 'instance id', VALUE_OPTIONAL),
364 'description' => new external_value(PARAM_RAW, 'activity description', VALUE_OPTIONAL),
365 'visible' => new external_value(PARAM_INT, 'is the module visible', VALUE_OPTIONAL),
366 'uservisible' => new external_value(PARAM_BOOL, 'Is the module visible for the user?',
367 VALUE_OPTIONAL),
368 'availabilityinfo' => new external_value(PARAM_RAW, 'Availability information.',
369 VALUE_OPTIONAL),
370 'visibleoncoursepage' => new external_value(PARAM_INT, 'is the module visible on course page',
371 VALUE_OPTIONAL),
372 'modicon' => new external_value(PARAM_URL, 'activity icon url'),
373 'modname' => new external_value(PARAM_PLUGIN, 'activity module type'),
374 'modplural' => new external_value(PARAM_TEXT, 'activity module plural name'),
375 'availability' => new external_value(PARAM_RAW, 'module availability settings', VALUE_OPTIONAL),
376 'indent' => new external_value(PARAM_INT, 'number of identation in the site'),
377 'contents' => new external_multiple_structure(
378 new external_single_structure(
379 array(
380 // content info
381 'type'=> new external_value(PARAM_TEXT, 'a file or a folder or external link'),
382 'filename'=> new external_value(PARAM_FILE, 'filename'),
383 'filepath'=> new external_value(PARAM_PATH, 'filepath'),
384 'filesize'=> new external_value(PARAM_INT, 'filesize'),
385 'fileurl' => new external_value(PARAM_URL, 'downloadable file url', VALUE_OPTIONAL),
386 'content' => new external_value(PARAM_RAW, 'Raw content, will be used when type is content', VALUE_OPTIONAL),
387 'timecreated' => new external_value(PARAM_INT, 'Time created'),
388 'timemodified' => new external_value(PARAM_INT, 'Time modified'),
389 'sortorder' => new external_value(PARAM_INT, 'Content sort order'),
390 'mimetype' => new external_value(PARAM_RAW, 'File mime type.', VALUE_OPTIONAL),
391 'isexternalfile' => new external_value(PARAM_BOOL, 'Whether is an external file.',
392 VALUE_OPTIONAL),
393 'repositorytype' => new external_value(PARAM_PLUGIN, 'The repository type for external files.',
394 VALUE_OPTIONAL),
396 // copyright related info
397 'userid' => new external_value(PARAM_INT, 'User who added this content to moodle'),
398 'author' => new external_value(PARAM_TEXT, 'Content owner'),
399 'license' => new external_value(PARAM_TEXT, 'Content license'),
401 ), VALUE_DEFAULT, array()
404 ), 'list of module'
412 * Returns description of method parameters
414 * @return external_function_parameters
415 * @since Moodle 2.3
417 public static function get_courses_parameters() {
418 return new external_function_parameters(
419 array('options' => new external_single_structure(
420 array('ids' => new external_multiple_structure(
421 new external_value(PARAM_INT, 'Course id')
422 , 'List of course id. If empty return all courses
423 except front page course.',
424 VALUE_OPTIONAL)
425 ), 'options - operator OR is used', VALUE_DEFAULT, array())
431 * Get courses
433 * @param array $options It contains an array (list of ids)
434 * @return array
435 * @since Moodle 2.2
437 public static function get_courses($options = array()) {
438 global $CFG, $DB;
439 require_once($CFG->dirroot . "/course/lib.php");
441 //validate parameter
442 $params = self::validate_parameters(self::get_courses_parameters(),
443 array('options' => $options));
445 //retrieve courses
446 if (!array_key_exists('ids', $params['options'])
447 or empty($params['options']['ids'])) {
448 $courses = $DB->get_records('course');
449 } else {
450 $courses = $DB->get_records_list('course', 'id', $params['options']['ids']);
453 //create return value
454 $coursesinfo = array();
455 foreach ($courses as $course) {
457 // now security checks
458 $context = context_course::instance($course->id, IGNORE_MISSING);
459 $courseformatoptions = course_get_format($course)->get_format_options();
460 try {
461 self::validate_context($context);
462 } catch (Exception $e) {
463 $exceptionparam = new stdClass();
464 $exceptionparam->message = $e->getMessage();
465 $exceptionparam->courseid = $course->id;
466 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
468 if ($course->id != SITEID) {
469 require_capability('moodle/course:view', $context);
472 $courseinfo = array();
473 $courseinfo['id'] = $course->id;
474 $courseinfo['fullname'] = external_format_string($course->fullname, $context->id);
475 $courseinfo['shortname'] = external_format_string($course->shortname, $context->id);
476 $courseinfo['displayname'] = external_format_string(get_course_display_name_for_list($course), $context->id);
477 $courseinfo['categoryid'] = $course->category;
478 list($courseinfo['summary'], $courseinfo['summaryformat']) =
479 external_format_text($course->summary, $course->summaryformat, $context->id, 'course', 'summary', 0);
480 $courseinfo['format'] = $course->format;
481 $courseinfo['startdate'] = $course->startdate;
482 $courseinfo['enddate'] = $course->enddate;
483 if (array_key_exists('numsections', $courseformatoptions)) {
484 // For backward-compartibility
485 $courseinfo['numsections'] = $courseformatoptions['numsections'];
488 //some field should be returned only if the user has update permission
489 $courseadmin = has_capability('moodle/course:update', $context);
490 if ($courseadmin) {
491 $courseinfo['categorysortorder'] = $course->sortorder;
492 $courseinfo['idnumber'] = $course->idnumber;
493 $courseinfo['showgrades'] = $course->showgrades;
494 $courseinfo['showreports'] = $course->showreports;
495 $courseinfo['newsitems'] = $course->newsitems;
496 $courseinfo['visible'] = $course->visible;
497 $courseinfo['maxbytes'] = $course->maxbytes;
498 if (array_key_exists('hiddensections', $courseformatoptions)) {
499 // For backward-compartibility
500 $courseinfo['hiddensections'] = $courseformatoptions['hiddensections'];
502 // Return numsections for backward-compatibility with clients who expect it.
503 $courseinfo['numsections'] = course_get_format($course)->get_last_section_number();
504 $courseinfo['groupmode'] = $course->groupmode;
505 $courseinfo['groupmodeforce'] = $course->groupmodeforce;
506 $courseinfo['defaultgroupingid'] = $course->defaultgroupingid;
507 $courseinfo['lang'] = clean_param($course->lang, PARAM_LANG);
508 $courseinfo['timecreated'] = $course->timecreated;
509 $courseinfo['timemodified'] = $course->timemodified;
510 $courseinfo['forcetheme'] = clean_param($course->theme, PARAM_THEME);
511 $courseinfo['enablecompletion'] = $course->enablecompletion;
512 $courseinfo['completionnotify'] = $course->completionnotify;
513 $courseinfo['courseformatoptions'] = array();
514 foreach ($courseformatoptions as $key => $value) {
515 $courseinfo['courseformatoptions'][] = array(
516 'name' => $key,
517 'value' => $value
522 if ($courseadmin or $course->visible
523 or has_capability('moodle/course:viewhiddencourses', $context)) {
524 $coursesinfo[] = $courseinfo;
528 return $coursesinfo;
532 * Returns description of method result value
534 * @return external_description
535 * @since Moodle 2.2
537 public static function get_courses_returns() {
538 return new external_multiple_structure(
539 new external_single_structure(
540 array(
541 'id' => new external_value(PARAM_INT, 'course id'),
542 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
543 'categoryid' => new external_value(PARAM_INT, 'category id'),
544 'categorysortorder' => new external_value(PARAM_INT,
545 'sort order into the category', VALUE_OPTIONAL),
546 'fullname' => new external_value(PARAM_TEXT, 'full name'),
547 'displayname' => new external_value(PARAM_TEXT, 'course display name'),
548 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
549 'summary' => new external_value(PARAM_RAW, 'summary'),
550 'summaryformat' => new external_format_value('summary'),
551 'format' => new external_value(PARAM_PLUGIN,
552 'course format: weeks, topics, social, site,..'),
553 'showgrades' => new external_value(PARAM_INT,
554 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
555 'newsitems' => new external_value(PARAM_INT,
556 'number of recent items appearing on the course page', VALUE_OPTIONAL),
557 'startdate' => new external_value(PARAM_INT,
558 'timestamp when the course start'),
559 'enddate' => new external_value(PARAM_INT,
560 'timestamp when the course end'),
561 'numsections' => new external_value(PARAM_INT,
562 '(deprecated, use courseformatoptions) number of weeks/topics',
563 VALUE_OPTIONAL),
564 'maxbytes' => new external_value(PARAM_INT,
565 'largest size of file that can be uploaded into the course',
566 VALUE_OPTIONAL),
567 'showreports' => new external_value(PARAM_INT,
568 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
569 'visible' => new external_value(PARAM_INT,
570 '1: available to student, 0:not available', VALUE_OPTIONAL),
571 'hiddensections' => new external_value(PARAM_INT,
572 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
573 VALUE_OPTIONAL),
574 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
575 VALUE_OPTIONAL),
576 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
577 VALUE_OPTIONAL),
578 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
579 VALUE_OPTIONAL),
580 'timecreated' => new external_value(PARAM_INT,
581 'timestamp when the course have been created', VALUE_OPTIONAL),
582 'timemodified' => new external_value(PARAM_INT,
583 'timestamp when the course have been modified', VALUE_OPTIONAL),
584 'enablecompletion' => new external_value(PARAM_INT,
585 'Enabled, control via completion and activity settings. Disbaled,
586 not shown in activity settings.',
587 VALUE_OPTIONAL),
588 'completionnotify' => new external_value(PARAM_INT,
589 '1: yes 0: no', VALUE_OPTIONAL),
590 'lang' => new external_value(PARAM_SAFEDIR,
591 'forced course language', VALUE_OPTIONAL),
592 'forcetheme' => new external_value(PARAM_PLUGIN,
593 'name of the force theme', VALUE_OPTIONAL),
594 'courseformatoptions' => new external_multiple_structure(
595 new external_single_structure(
596 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
597 'value' => new external_value(PARAM_RAW, 'course format option value')
599 'additional options for particular course format', VALUE_OPTIONAL
601 ), 'course'
607 * Returns description of method parameters
609 * @return external_function_parameters
610 * @since Moodle 2.2
612 public static function create_courses_parameters() {
613 $courseconfig = get_config('moodlecourse'); //needed for many default values
614 return new external_function_parameters(
615 array(
616 'courses' => new external_multiple_structure(
617 new external_single_structure(
618 array(
619 'fullname' => new external_value(PARAM_TEXT, 'full name'),
620 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
621 'categoryid' => new external_value(PARAM_INT, 'category id'),
622 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
623 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
624 'summaryformat' => new external_format_value('summary', VALUE_DEFAULT),
625 'format' => new external_value(PARAM_PLUGIN,
626 'course format: weeks, topics, social, site,..',
627 VALUE_DEFAULT, $courseconfig->format),
628 'showgrades' => new external_value(PARAM_INT,
629 '1 if grades are shown, otherwise 0', VALUE_DEFAULT,
630 $courseconfig->showgrades),
631 'newsitems' => new external_value(PARAM_INT,
632 'number of recent items appearing on the course page',
633 VALUE_DEFAULT, $courseconfig->newsitems),
634 'startdate' => new external_value(PARAM_INT,
635 'timestamp when the course start', VALUE_OPTIONAL),
636 'enddate' => new external_value(PARAM_INT,
637 'timestamp when the course end', VALUE_OPTIONAL),
638 'numsections' => new external_value(PARAM_INT,
639 '(deprecated, use courseformatoptions) number of weeks/topics',
640 VALUE_OPTIONAL),
641 'maxbytes' => new external_value(PARAM_INT,
642 'largest size of file that can be uploaded into the course',
643 VALUE_DEFAULT, $courseconfig->maxbytes),
644 'showreports' => new external_value(PARAM_INT,
645 'are activity report shown (yes = 1, no =0)', VALUE_DEFAULT,
646 $courseconfig->showreports),
647 'visible' => new external_value(PARAM_INT,
648 '1: available to student, 0:not available', VALUE_OPTIONAL),
649 'hiddensections' => new external_value(PARAM_INT,
650 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
651 VALUE_OPTIONAL),
652 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
653 VALUE_DEFAULT, $courseconfig->groupmode),
654 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
655 VALUE_DEFAULT, $courseconfig->groupmodeforce),
656 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
657 VALUE_DEFAULT, 0),
658 'enablecompletion' => new external_value(PARAM_INT,
659 'Enabled, control via completion and activity settings. Disabled,
660 not shown in activity settings.',
661 VALUE_OPTIONAL),
662 'completionnotify' => new external_value(PARAM_INT,
663 '1: yes 0: no', VALUE_OPTIONAL),
664 'lang' => new external_value(PARAM_SAFEDIR,
665 'forced course language', VALUE_OPTIONAL),
666 'forcetheme' => new external_value(PARAM_PLUGIN,
667 'name of the force theme', VALUE_OPTIONAL),
668 'courseformatoptions' => new external_multiple_structure(
669 new external_single_structure(
670 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
671 'value' => new external_value(PARAM_RAW, 'course format option value')
673 'additional options for particular course format', VALUE_OPTIONAL),
675 ), 'courses to create'
682 * Create courses
684 * @param array $courses
685 * @return array courses (id and shortname only)
686 * @since Moodle 2.2
688 public static function create_courses($courses) {
689 global $CFG, $DB;
690 require_once($CFG->dirroot . "/course/lib.php");
691 require_once($CFG->libdir . '/completionlib.php');
693 $params = self::validate_parameters(self::create_courses_parameters(),
694 array('courses' => $courses));
696 $availablethemes = core_component::get_plugin_list('theme');
697 $availablelangs = get_string_manager()->get_list_of_translations();
699 $transaction = $DB->start_delegated_transaction();
701 foreach ($params['courses'] as $course) {
703 // Ensure the current user is allowed to run this function
704 $context = context_coursecat::instance($course['categoryid'], IGNORE_MISSING);
705 try {
706 self::validate_context($context);
707 } catch (Exception $e) {
708 $exceptionparam = new stdClass();
709 $exceptionparam->message = $e->getMessage();
710 $exceptionparam->catid = $course['categoryid'];
711 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
713 require_capability('moodle/course:create', $context);
715 // Make sure lang is valid
716 if (array_key_exists('lang', $course)) {
717 if (empty($availablelangs[$course['lang']])) {
718 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
720 if (!has_capability('moodle/course:setforcedlanguage', $context)) {
721 unset($course['lang']);
725 // Make sure theme is valid
726 if (array_key_exists('forcetheme', $course)) {
727 if (!empty($CFG->allowcoursethemes)) {
728 if (empty($availablethemes[$course['forcetheme']])) {
729 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
730 } else {
731 $course['theme'] = $course['forcetheme'];
736 //force visibility if ws user doesn't have the permission to set it
737 $category = $DB->get_record('course_categories', array('id' => $course['categoryid']));
738 if (!has_capability('moodle/course:visibility', $context)) {
739 $course['visible'] = $category->visible;
742 //set default value for completion
743 $courseconfig = get_config('moodlecourse');
744 if (completion_info::is_enabled_for_site()) {
745 if (!array_key_exists('enablecompletion', $course)) {
746 $course['enablecompletion'] = $courseconfig->enablecompletion;
748 } else {
749 $course['enablecompletion'] = 0;
752 $course['category'] = $course['categoryid'];
754 // Summary format.
755 $course['summaryformat'] = external_validate_format($course['summaryformat']);
757 if (!empty($course['courseformatoptions'])) {
758 foreach ($course['courseformatoptions'] as $option) {
759 $course[$option['name']] = $option['value'];
763 //Note: create_course() core function check shortname, idnumber, category
764 $course['id'] = create_course((object) $course)->id;
766 $resultcourses[] = array('id' => $course['id'], 'shortname' => $course['shortname']);
769 $transaction->allow_commit();
771 return $resultcourses;
775 * Returns description of method result value
777 * @return external_description
778 * @since Moodle 2.2
780 public static function create_courses_returns() {
781 return new external_multiple_structure(
782 new external_single_structure(
783 array(
784 'id' => new external_value(PARAM_INT, 'course id'),
785 'shortname' => new external_value(PARAM_TEXT, 'short name'),
792 * Update courses
794 * @return external_function_parameters
795 * @since Moodle 2.5
797 public static function update_courses_parameters() {
798 return new external_function_parameters(
799 array(
800 'courses' => new external_multiple_structure(
801 new external_single_structure(
802 array(
803 'id' => new external_value(PARAM_INT, 'ID of the course'),
804 'fullname' => new external_value(PARAM_TEXT, 'full name', VALUE_OPTIONAL),
805 'shortname' => new external_value(PARAM_TEXT, 'course short name', VALUE_OPTIONAL),
806 'categoryid' => new external_value(PARAM_INT, 'category id', VALUE_OPTIONAL),
807 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
808 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
809 'summaryformat' => new external_format_value('summary', VALUE_OPTIONAL),
810 'format' => new external_value(PARAM_PLUGIN,
811 'course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
812 'showgrades' => new external_value(PARAM_INT,
813 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
814 'newsitems' => new external_value(PARAM_INT,
815 'number of recent items appearing on the course page', VALUE_OPTIONAL),
816 'startdate' => new external_value(PARAM_INT,
817 'timestamp when the course start', VALUE_OPTIONAL),
818 'enddate' => new external_value(PARAM_INT,
819 'timestamp when the course end', VALUE_OPTIONAL),
820 'numsections' => new external_value(PARAM_INT,
821 '(deprecated, use courseformatoptions) number of weeks/topics', VALUE_OPTIONAL),
822 'maxbytes' => new external_value(PARAM_INT,
823 'largest size of file that can be uploaded into the course', VALUE_OPTIONAL),
824 'showreports' => new external_value(PARAM_INT,
825 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
826 'visible' => new external_value(PARAM_INT,
827 '1: available to student, 0:not available', VALUE_OPTIONAL),
828 'hiddensections' => new external_value(PARAM_INT,
829 '(deprecated, use courseformatoptions) How the hidden sections in the course are
830 displayed to students', VALUE_OPTIONAL),
831 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
832 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
833 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
834 'enablecompletion' => new external_value(PARAM_INT,
835 'Enabled, control via completion and activity settings. Disabled,
836 not shown in activity settings.', VALUE_OPTIONAL),
837 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
838 'lang' => new external_value(PARAM_SAFEDIR, 'forced course language', VALUE_OPTIONAL),
839 'forcetheme' => new external_value(PARAM_PLUGIN, 'name of the force theme', VALUE_OPTIONAL),
840 'courseformatoptions' => new external_multiple_structure(
841 new external_single_structure(
842 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
843 'value' => new external_value(PARAM_RAW, 'course format option value')
845 'additional options for particular course format', VALUE_OPTIONAL),
847 ), 'courses to update'
854 * Update courses
856 * @param array $courses
857 * @since Moodle 2.5
859 public static function update_courses($courses) {
860 global $CFG, $DB;
861 require_once($CFG->dirroot . "/course/lib.php");
862 $warnings = array();
864 $params = self::validate_parameters(self::update_courses_parameters(),
865 array('courses' => $courses));
867 $availablethemes = core_component::get_plugin_list('theme');
868 $availablelangs = get_string_manager()->get_list_of_translations();
870 foreach ($params['courses'] as $course) {
871 // Catch any exception while updating course and return as warning to user.
872 try {
873 // Ensure the current user is allowed to run this function.
874 $context = context_course::instance($course['id'], MUST_EXIST);
875 self::validate_context($context);
877 $oldcourse = course_get_format($course['id'])->get_course();
879 require_capability('moodle/course:update', $context);
881 // Check if user can change category.
882 if (array_key_exists('categoryid', $course) && ($oldcourse->category != $course['categoryid'])) {
883 require_capability('moodle/course:changecategory', $context);
884 $course['category'] = $course['categoryid'];
887 // Check if the user can change fullname.
888 if (array_key_exists('fullname', $course) && ($oldcourse->fullname != $course['fullname'])) {
889 require_capability('moodle/course:changefullname', $context);
892 // Check if the user can change shortname.
893 if (array_key_exists('shortname', $course) && ($oldcourse->shortname != $course['shortname'])) {
894 require_capability('moodle/course:changeshortname', $context);
897 // Check if the user can change the idnumber.
898 if (array_key_exists('idnumber', $course) && ($oldcourse->idnumber != $course['idnumber'])) {
899 require_capability('moodle/course:changeidnumber', $context);
902 // Check if user can change summary.
903 if (array_key_exists('summary', $course) && ($oldcourse->summary != $course['summary'])) {
904 require_capability('moodle/course:changesummary', $context);
907 // Summary format.
908 if (array_key_exists('summaryformat', $course) && ($oldcourse->summaryformat != $course['summaryformat'])) {
909 require_capability('moodle/course:changesummary', $context);
910 $course['summaryformat'] = external_validate_format($course['summaryformat']);
913 // Check if user can change visibility.
914 if (array_key_exists('visible', $course) && ($oldcourse->visible != $course['visible'])) {
915 require_capability('moodle/course:visibility', $context);
918 // Make sure lang is valid.
919 if (array_key_exists('lang', $course) && ($oldcourse->lang != $course['lang'])) {
920 require_capability('moodle/course:setforcedlanguage', $context);
921 if (empty($availablelangs[$course['lang']])) {
922 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
926 // Make sure theme is valid.
927 if (array_key_exists('forcetheme', $course)) {
928 if (!empty($CFG->allowcoursethemes)) {
929 if (empty($availablethemes[$course['forcetheme']])) {
930 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
931 } else {
932 $course['theme'] = $course['forcetheme'];
937 // Make sure completion is enabled before setting it.
938 if (array_key_exists('enabledcompletion', $course) && !completion_info::is_enabled_for_site()) {
939 $course['enabledcompletion'] = 0;
942 // Make sure maxbytes are less then CFG->maxbytes.
943 if (array_key_exists('maxbytes', $course)) {
944 $course['maxbytes'] = get_max_upload_file_size($CFG->maxbytes, $course['maxbytes']);
947 if (!empty($course['courseformatoptions'])) {
948 foreach ($course['courseformatoptions'] as $option) {
949 if (isset($option['name']) && isset($option['value'])) {
950 $course[$option['name']] = $option['value'];
955 // Update course if user has all required capabilities.
956 update_course((object) $course);
957 } catch (Exception $e) {
958 $warning = array();
959 $warning['item'] = 'course';
960 $warning['itemid'] = $course['id'];
961 if ($e instanceof moodle_exception) {
962 $warning['warningcode'] = $e->errorcode;
963 } else {
964 $warning['warningcode'] = $e->getCode();
966 $warning['message'] = $e->getMessage();
967 $warnings[] = $warning;
971 $result = array();
972 $result['warnings'] = $warnings;
973 return $result;
977 * Returns description of method result value
979 * @return external_description
980 * @since Moodle 2.5
982 public static function update_courses_returns() {
983 return new external_single_structure(
984 array(
985 'warnings' => new external_warnings()
991 * Returns description of method parameters
993 * @return external_function_parameters
994 * @since Moodle 2.2
996 public static function delete_courses_parameters() {
997 return new external_function_parameters(
998 array(
999 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'course ID')),
1005 * Delete courses
1007 * @param array $courseids A list of course ids
1008 * @since Moodle 2.2
1010 public static function delete_courses($courseids) {
1011 global $CFG, $DB;
1012 require_once($CFG->dirroot."/course/lib.php");
1014 // Parameter validation.
1015 $params = self::validate_parameters(self::delete_courses_parameters(), array('courseids'=>$courseids));
1017 $warnings = array();
1019 foreach ($params['courseids'] as $courseid) {
1020 $course = $DB->get_record('course', array('id' => $courseid));
1022 if ($course === false) {
1023 $warnings[] = array(
1024 'item' => 'course',
1025 'itemid' => $courseid,
1026 'warningcode' => 'unknowncourseidnumber',
1027 'message' => 'Unknown course ID ' . $courseid
1029 continue;
1032 // Check if the context is valid.
1033 $coursecontext = context_course::instance($course->id);
1034 self::validate_context($coursecontext);
1036 // Check if the current user has permission.
1037 if (!can_delete_course($courseid)) {
1038 $warnings[] = array(
1039 'item' => 'course',
1040 'itemid' => $courseid,
1041 'warningcode' => 'cannotdeletecourse',
1042 'message' => 'You do not have the permission to delete this course' . $courseid
1044 continue;
1047 if (delete_course($course, false) === false) {
1048 $warnings[] = array(
1049 'item' => 'course',
1050 'itemid' => $courseid,
1051 'warningcode' => 'cannotdeletecategorycourse',
1052 'message' => 'Course ' . $courseid . ' failed to be deleted'
1054 continue;
1058 fix_course_sortorder();
1060 return array('warnings' => $warnings);
1064 * Returns description of method result value
1066 * @return external_description
1067 * @since Moodle 2.2
1069 public static function delete_courses_returns() {
1070 return new external_single_structure(
1071 array(
1072 'warnings' => new external_warnings()
1078 * Returns description of method parameters
1080 * @return external_function_parameters
1081 * @since Moodle 2.3
1083 public static function duplicate_course_parameters() {
1084 return new external_function_parameters(
1085 array(
1086 'courseid' => new external_value(PARAM_INT, 'course to duplicate id'),
1087 'fullname' => new external_value(PARAM_TEXT, 'duplicated course full name'),
1088 'shortname' => new external_value(PARAM_TEXT, 'duplicated course short name'),
1089 'categoryid' => new external_value(PARAM_INT, 'duplicated course category parent'),
1090 'visible' => new external_value(PARAM_INT, 'duplicated course visible, default to yes', VALUE_DEFAULT, 1),
1091 'options' => new external_multiple_structure(
1092 new external_single_structure(
1093 array(
1094 'name' => new external_value(PARAM_ALPHAEXT, 'The backup option name:
1095 "activities" (int) Include course activites (default to 1 that is equal to yes),
1096 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1097 "filters" (int) Include course filters (default to 1 that is equal to yes),
1098 "users" (int) Include users (default to 0 that is equal to no),
1099 "enrolments" (int) Include enrolment methods (default to 1 - restore only with users),
1100 "role_assignments" (int) Include role assignments (default to 0 that is equal to no),
1101 "comments" (int) Include user comments (default to 0 that is equal to no),
1102 "userscompletion" (int) Include user course completion information (default to 0 that is equal to no),
1103 "logs" (int) Include course logs (default to 0 that is equal to no),
1104 "grade_histories" (int) Include histories (default to 0 that is equal to no)'
1106 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1109 ), VALUE_DEFAULT, array()
1116 * Duplicate a course
1118 * @param int $courseid
1119 * @param string $fullname Duplicated course fullname
1120 * @param string $shortname Duplicated course shortname
1121 * @param int $categoryid Duplicated course parent category id
1122 * @param int $visible Duplicated course availability
1123 * @param array $options List of backup options
1124 * @return array New course info
1125 * @since Moodle 2.3
1127 public static function duplicate_course($courseid, $fullname, $shortname, $categoryid, $visible = 1, $options = array()) {
1128 global $CFG, $USER, $DB;
1129 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1130 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1132 // Parameter validation.
1133 $params = self::validate_parameters(
1134 self::duplicate_course_parameters(),
1135 array(
1136 'courseid' => $courseid,
1137 'fullname' => $fullname,
1138 'shortname' => $shortname,
1139 'categoryid' => $categoryid,
1140 'visible' => $visible,
1141 'options' => $options
1145 // Context validation.
1147 if (! ($course = $DB->get_record('course', array('id'=>$params['courseid'])))) {
1148 throw new moodle_exception('invalidcourseid', 'error');
1151 // Category where duplicated course is going to be created.
1152 $categorycontext = context_coursecat::instance($params['categoryid']);
1153 self::validate_context($categorycontext);
1155 // Course to be duplicated.
1156 $coursecontext = context_course::instance($course->id);
1157 self::validate_context($coursecontext);
1159 $backupdefaults = array(
1160 'activities' => 1,
1161 'blocks' => 1,
1162 'filters' => 1,
1163 'users' => 0,
1164 'enrolments' => backup::ENROL_WITHUSERS,
1165 'role_assignments' => 0,
1166 'comments' => 0,
1167 'userscompletion' => 0,
1168 'logs' => 0,
1169 'grade_histories' => 0
1172 $backupsettings = array();
1173 // Check for backup and restore options.
1174 if (!empty($params['options'])) {
1175 foreach ($params['options'] as $option) {
1177 // Strict check for a correct value (allways 1 or 0, true or false).
1178 $value = clean_param($option['value'], PARAM_INT);
1180 if ($value !== 0 and $value !== 1) {
1181 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1184 if (!isset($backupdefaults[$option['name']])) {
1185 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1188 $backupsettings[$option['name']] = $value;
1192 // Capability checking.
1194 // The backup controller check for this currently, this may be redundant.
1195 require_capability('moodle/course:create', $categorycontext);
1196 require_capability('moodle/restore:restorecourse', $categorycontext);
1197 require_capability('moodle/backup:backupcourse', $coursecontext);
1199 if (!empty($backupsettings['users'])) {
1200 require_capability('moodle/backup:userinfo', $coursecontext);
1201 require_capability('moodle/restore:userinfo', $categorycontext);
1204 // Check if the shortname is used.
1205 if ($foundcourses = $DB->get_records('course', array('shortname'=>$shortname))) {
1206 foreach ($foundcourses as $foundcourse) {
1207 $foundcoursenames[] = $foundcourse->fullname;
1210 $foundcoursenamestring = implode(',', $foundcoursenames);
1211 throw new moodle_exception('shortnametaken', '', '', $foundcoursenamestring);
1214 // Backup the course.
1216 $bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE,
1217 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id);
1219 foreach ($backupsettings as $name => $value) {
1220 if ($setting = $bc->get_plan()->get_setting($name)) {
1221 $bc->get_plan()->get_setting($name)->set_value($value);
1225 $backupid = $bc->get_backupid();
1226 $backupbasepath = $bc->get_plan()->get_basepath();
1228 $bc->execute_plan();
1229 $results = $bc->get_results();
1230 $file = $results['backup_destination'];
1232 $bc->destroy();
1234 // Restore the backup immediately.
1236 // Check if we need to unzip the file because the backup temp dir does not contains backup files.
1237 if (!file_exists($backupbasepath . "/moodle_backup.xml")) {
1238 $file->extract_to_pathname(get_file_packer('application/vnd.moodle.backup'), $backupbasepath);
1241 // Create new course.
1242 $newcourseid = restore_dbops::create_new_course($params['fullname'], $params['shortname'], $params['categoryid']);
1244 $rc = new restore_controller($backupid, $newcourseid,
1245 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id, backup::TARGET_NEW_COURSE);
1247 foreach ($backupsettings as $name => $value) {
1248 $setting = $rc->get_plan()->get_setting($name);
1249 if ($setting->get_status() == backup_setting::NOT_LOCKED) {
1250 $setting->set_value($value);
1254 if (!$rc->execute_precheck()) {
1255 $precheckresults = $rc->get_precheck_results();
1256 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1257 if (empty($CFG->keeptempdirectoriesonbackup)) {
1258 fulldelete($backupbasepath);
1261 $errorinfo = '';
1263 foreach ($precheckresults['errors'] as $error) {
1264 $errorinfo .= $error;
1267 if (array_key_exists('warnings', $precheckresults)) {
1268 foreach ($precheckresults['warnings'] as $warning) {
1269 $errorinfo .= $warning;
1273 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1277 $rc->execute_plan();
1278 $rc->destroy();
1280 $course = $DB->get_record('course', array('id' => $newcourseid), '*', MUST_EXIST);
1281 $course->fullname = $params['fullname'];
1282 $course->shortname = $params['shortname'];
1283 $course->visible = $params['visible'];
1285 // Set shortname and fullname back.
1286 $DB->update_record('course', $course);
1288 if (empty($CFG->keeptempdirectoriesonbackup)) {
1289 fulldelete($backupbasepath);
1292 // Delete the course backup file created by this WebService. Originally located in the course backups area.
1293 $file->delete();
1295 return array('id' => $course->id, 'shortname' => $course->shortname);
1299 * Returns description of method result value
1301 * @return external_description
1302 * @since Moodle 2.3
1304 public static function duplicate_course_returns() {
1305 return new external_single_structure(
1306 array(
1307 'id' => new external_value(PARAM_INT, 'course id'),
1308 'shortname' => new external_value(PARAM_TEXT, 'short name'),
1314 * Returns description of method parameters for import_course
1316 * @return external_function_parameters
1317 * @since Moodle 2.4
1319 public static function import_course_parameters() {
1320 return new external_function_parameters(
1321 array(
1322 'importfrom' => new external_value(PARAM_INT, 'the id of the course we are importing from'),
1323 'importto' => new external_value(PARAM_INT, 'the id of the course we are importing to'),
1324 'deletecontent' => new external_value(PARAM_INT, 'whether to delete the course content where we are importing to (default to 0 = No)', VALUE_DEFAULT, 0),
1325 'options' => new external_multiple_structure(
1326 new external_single_structure(
1327 array(
1328 'name' => new external_value(PARAM_ALPHA, 'The backup option name:
1329 "activities" (int) Include course activites (default to 1 that is equal to yes),
1330 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1331 "filters" (int) Include course filters (default to 1 that is equal to yes)'
1333 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1336 ), VALUE_DEFAULT, array()
1343 * Imports a course
1345 * @param int $importfrom The id of the course we are importing from
1346 * @param int $importto The id of the course we are importing to
1347 * @param bool $deletecontent Whether to delete the course we are importing to content
1348 * @param array $options List of backup options
1349 * @return null
1350 * @since Moodle 2.4
1352 public static function import_course($importfrom, $importto, $deletecontent = 0, $options = array()) {
1353 global $CFG, $USER, $DB;
1354 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1355 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1357 // Parameter validation.
1358 $params = self::validate_parameters(
1359 self::import_course_parameters(),
1360 array(
1361 'importfrom' => $importfrom,
1362 'importto' => $importto,
1363 'deletecontent' => $deletecontent,
1364 'options' => $options
1368 if ($params['deletecontent'] !== 0 and $params['deletecontent'] !== 1) {
1369 throw new moodle_exception('invalidextparam', 'webservice', '', $params['deletecontent']);
1372 // Context validation.
1374 if (! ($importfrom = $DB->get_record('course', array('id'=>$params['importfrom'])))) {
1375 throw new moodle_exception('invalidcourseid', 'error');
1378 if (! ($importto = $DB->get_record('course', array('id'=>$params['importto'])))) {
1379 throw new moodle_exception('invalidcourseid', 'error');
1382 $importfromcontext = context_course::instance($importfrom->id);
1383 self::validate_context($importfromcontext);
1385 $importtocontext = context_course::instance($importto->id);
1386 self::validate_context($importtocontext);
1388 $backupdefaults = array(
1389 'activities' => 1,
1390 'blocks' => 1,
1391 'filters' => 1
1394 $backupsettings = array();
1396 // Check for backup and restore options.
1397 if (!empty($params['options'])) {
1398 foreach ($params['options'] as $option) {
1400 // Strict check for a correct value (allways 1 or 0, true or false).
1401 $value = clean_param($option['value'], PARAM_INT);
1403 if ($value !== 0 and $value !== 1) {
1404 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1407 if (!isset($backupdefaults[$option['name']])) {
1408 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1411 $backupsettings[$option['name']] = $value;
1415 // Capability checking.
1417 require_capability('moodle/backup:backuptargetimport', $importfromcontext);
1418 require_capability('moodle/restore:restoretargetimport', $importtocontext);
1420 $bc = new backup_controller(backup::TYPE_1COURSE, $importfrom->id, backup::FORMAT_MOODLE,
1421 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
1423 foreach ($backupsettings as $name => $value) {
1424 $bc->get_plan()->get_setting($name)->set_value($value);
1427 $backupid = $bc->get_backupid();
1428 $backupbasepath = $bc->get_plan()->get_basepath();
1430 $bc->execute_plan();
1431 $bc->destroy();
1433 // Restore the backup immediately.
1435 // Check if we must delete the contents of the destination course.
1436 if ($params['deletecontent']) {
1437 $restoretarget = backup::TARGET_EXISTING_DELETING;
1438 } else {
1439 $restoretarget = backup::TARGET_EXISTING_ADDING;
1442 $rc = new restore_controller($backupid, $importto->id,
1443 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, $restoretarget);
1445 foreach ($backupsettings as $name => $value) {
1446 $rc->get_plan()->get_setting($name)->set_value($value);
1449 if (!$rc->execute_precheck()) {
1450 $precheckresults = $rc->get_precheck_results();
1451 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1452 if (empty($CFG->keeptempdirectoriesonbackup)) {
1453 fulldelete($backupbasepath);
1456 $errorinfo = '';
1458 foreach ($precheckresults['errors'] as $error) {
1459 $errorinfo .= $error;
1462 if (array_key_exists('warnings', $precheckresults)) {
1463 foreach ($precheckresults['warnings'] as $warning) {
1464 $errorinfo .= $warning;
1468 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1470 } else {
1471 if ($restoretarget == backup::TARGET_EXISTING_DELETING) {
1472 restore_dbops::delete_course_content($importto->id);
1476 $rc->execute_plan();
1477 $rc->destroy();
1479 if (empty($CFG->keeptempdirectoriesonbackup)) {
1480 fulldelete($backupbasepath);
1483 return null;
1487 * Returns description of method result value
1489 * @return external_description
1490 * @since Moodle 2.4
1492 public static function import_course_returns() {
1493 return null;
1497 * Returns description of method parameters
1499 * @return external_function_parameters
1500 * @since Moodle 2.3
1502 public static function get_categories_parameters() {
1503 return new external_function_parameters(
1504 array(
1505 'criteria' => new external_multiple_structure(
1506 new external_single_structure(
1507 array(
1508 'key' => new external_value(PARAM_ALPHA,
1509 'The category column to search, expected keys (value format) are:'.
1510 '"id" (int) the category id,'.
1511 '"ids" (string) category ids separated by commas,'.
1512 '"name" (string) the category name,'.
1513 '"parent" (int) the parent category id,'.
1514 '"idnumber" (string) category idnumber'.
1515 ' - user must have \'moodle/category:manage\' to search on idnumber,'.
1516 '"visible" (int) whether the returned categories must be visible or hidden. If the key is not passed,
1517 then the function return all categories that the user can see.'.
1518 ' - user must have \'moodle/category:manage\' or \'moodle/category:viewhiddencategories\' to search on visible,'.
1519 '"theme" (string) only return the categories having this theme'.
1520 ' - user must have \'moodle/category:manage\' to search on theme'),
1521 'value' => new external_value(PARAM_RAW, 'the value to match')
1523 ), 'criteria', VALUE_DEFAULT, array()
1525 'addsubcategories' => new external_value(PARAM_BOOL, 'return the sub categories infos
1526 (1 - default) otherwise only the category info (0)', VALUE_DEFAULT, 1)
1532 * Get categories
1534 * @param array $criteria Criteria to match the results
1535 * @param booln $addsubcategories obtain only the category (false) or its subcategories (true - default)
1536 * @return array list of categories
1537 * @since Moodle 2.3
1539 public static function get_categories($criteria = array(), $addsubcategories = true) {
1540 global $CFG, $DB;
1541 require_once($CFG->dirroot . "/course/lib.php");
1543 // Validate parameters.
1544 $params = self::validate_parameters(self::get_categories_parameters(),
1545 array('criteria' => $criteria, 'addsubcategories' => $addsubcategories));
1547 // Retrieve the categories.
1548 $categories = array();
1549 if (!empty($params['criteria'])) {
1551 $conditions = array();
1552 $wheres = array();
1553 foreach ($params['criteria'] as $crit) {
1554 $key = trim($crit['key']);
1556 // Trying to avoid duplicate keys.
1557 if (!isset($conditions[$key])) {
1559 $context = context_system::instance();
1560 $value = null;
1561 switch ($key) {
1562 case 'id':
1563 $value = clean_param($crit['value'], PARAM_INT);
1564 $conditions[$key] = $value;
1565 $wheres[] = $key . " = :" . $key;
1566 break;
1568 case 'ids':
1569 $value = clean_param($crit['value'], PARAM_SEQUENCE);
1570 $ids = explode(',', $value);
1571 list($sqlids, $paramids) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED);
1572 $conditions = array_merge($conditions, $paramids);
1573 $wheres[] = 'id ' . $sqlids;
1574 break;
1576 case 'idnumber':
1577 if (has_capability('moodle/category:manage', $context)) {
1578 $value = clean_param($crit['value'], PARAM_RAW);
1579 $conditions[$key] = $value;
1580 $wheres[] = $key . " = :" . $key;
1581 } else {
1582 // We must throw an exception.
1583 // Otherwise the dev client would think no idnumber exists.
1584 throw new moodle_exception('criteriaerror',
1585 'webservice', '', null,
1586 'You don\'t have the permissions to search on the "idnumber" field.');
1588 break;
1590 case 'name':
1591 $value = clean_param($crit['value'], PARAM_TEXT);
1592 $conditions[$key] = $value;
1593 $wheres[] = $key . " = :" . $key;
1594 break;
1596 case 'parent':
1597 $value = clean_param($crit['value'], PARAM_INT);
1598 $conditions[$key] = $value;
1599 $wheres[] = $key . " = :" . $key;
1600 break;
1602 case 'visible':
1603 if (has_capability('moodle/category:manage', $context)
1604 or has_capability('moodle/category:viewhiddencategories',
1605 context_system::instance())) {
1606 $value = clean_param($crit['value'], PARAM_INT);
1607 $conditions[$key] = $value;
1608 $wheres[] = $key . " = :" . $key;
1609 } else {
1610 throw new moodle_exception('criteriaerror',
1611 'webservice', '', null,
1612 'You don\'t have the permissions to search on the "visible" field.');
1614 break;
1616 case 'theme':
1617 if (has_capability('moodle/category:manage', $context)) {
1618 $value = clean_param($crit['value'], PARAM_THEME);
1619 $conditions[$key] = $value;
1620 $wheres[] = $key . " = :" . $key;
1621 } else {
1622 throw new moodle_exception('criteriaerror',
1623 'webservice', '', null,
1624 'You don\'t have the permissions to search on the "theme" field.');
1626 break;
1628 default:
1629 throw new moodle_exception('criteriaerror',
1630 'webservice', '', null,
1631 'You can not search on this criteria: ' . $key);
1636 if (!empty($wheres)) {
1637 $wheres = implode(" AND ", $wheres);
1639 $categories = $DB->get_records_select('course_categories', $wheres, $conditions);
1641 // Retrieve its sub subcategories (all levels).
1642 if ($categories and !empty($params['addsubcategories'])) {
1643 $newcategories = array();
1645 // Check if we required visible/theme checks.
1646 $additionalselect = '';
1647 $additionalparams = array();
1648 if (isset($conditions['visible'])) {
1649 $additionalselect .= ' AND visible = :visible';
1650 $additionalparams['visible'] = $conditions['visible'];
1652 if (isset($conditions['theme'])) {
1653 $additionalselect .= ' AND theme= :theme';
1654 $additionalparams['theme'] = $conditions['theme'];
1657 foreach ($categories as $category) {
1658 $sqlselect = $DB->sql_like('path', ':path') . $additionalselect;
1659 $sqlparams = array('path' => $category->path.'/%') + $additionalparams; // It will NOT include the specified category.
1660 $subcategories = $DB->get_records_select('course_categories', $sqlselect, $sqlparams);
1661 $newcategories = $newcategories + $subcategories; // Both arrays have integer as keys.
1663 $categories = $categories + $newcategories;
1667 } else {
1668 // Retrieve all categories in the database.
1669 $categories = $DB->get_records('course_categories');
1672 // The not returned categories. key => category id, value => reason of exclusion.
1673 $excludedcats = array();
1675 // The returned categories.
1676 $categoriesinfo = array();
1678 // We need to sort the categories by path.
1679 // The parent cats need to be checked by the algo first.
1680 usort($categories, "core_course_external::compare_categories_by_path");
1682 foreach ($categories as $category) {
1684 // Check if the category is a child of an excluded category, if yes exclude it too (excluded => do not return).
1685 $parents = explode('/', $category->path);
1686 unset($parents[0]); // First key is always empty because path start with / => /1/2/4.
1687 foreach ($parents as $parentid) {
1688 // Note: when the parent exclusion was due to the context,
1689 // the sub category could still be returned.
1690 if (isset($excludedcats[$parentid]) and $excludedcats[$parentid] != 'context') {
1691 $excludedcats[$category->id] = 'parent';
1695 // Check the user can use the category context.
1696 $context = context_coursecat::instance($category->id);
1697 try {
1698 self::validate_context($context);
1699 } catch (Exception $e) {
1700 $excludedcats[$category->id] = 'context';
1702 // If it was the requested category then throw an exception.
1703 if (isset($params['categoryid']) && $category->id == $params['categoryid']) {
1704 $exceptionparam = new stdClass();
1705 $exceptionparam->message = $e->getMessage();
1706 $exceptionparam->catid = $category->id;
1707 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
1711 // Return the category information.
1712 if (!isset($excludedcats[$category->id])) {
1714 // Final check to see if the category is visible to the user.
1715 if ($category->visible
1716 or has_capability('moodle/category:viewhiddencategories', context_system::instance())
1717 or has_capability('moodle/category:manage', $context)) {
1719 $categoryinfo = array();
1720 $categoryinfo['id'] = $category->id;
1721 $categoryinfo['name'] = $category->name;
1722 list($categoryinfo['description'], $categoryinfo['descriptionformat']) =
1723 external_format_text($category->description, $category->descriptionformat,
1724 $context->id, 'coursecat', 'description', null);
1725 $categoryinfo['parent'] = $category->parent;
1726 $categoryinfo['sortorder'] = $category->sortorder;
1727 $categoryinfo['coursecount'] = $category->coursecount;
1728 $categoryinfo['depth'] = $category->depth;
1729 $categoryinfo['path'] = $category->path;
1731 // Some fields only returned for admin.
1732 if (has_capability('moodle/category:manage', $context)) {
1733 $categoryinfo['idnumber'] = $category->idnumber;
1734 $categoryinfo['visible'] = $category->visible;
1735 $categoryinfo['visibleold'] = $category->visibleold;
1736 $categoryinfo['timemodified'] = $category->timemodified;
1737 $categoryinfo['theme'] = clean_param($category->theme, PARAM_THEME);
1740 $categoriesinfo[] = $categoryinfo;
1741 } else {
1742 $excludedcats[$category->id] = 'visibility';
1747 // Sorting the resulting array so it looks a bit better for the client developer.
1748 usort($categoriesinfo, "core_course_external::compare_categories_by_sortorder");
1750 return $categoriesinfo;
1754 * Sort categories array by path
1755 * private function: only used by get_categories
1757 * @param array $category1
1758 * @param array $category2
1759 * @return int result of strcmp
1760 * @since Moodle 2.3
1762 private static function compare_categories_by_path($category1, $category2) {
1763 return strcmp($category1->path, $category2->path);
1767 * Sort categories array by sortorder
1768 * private function: only used by get_categories
1770 * @param array $category1
1771 * @param array $category2
1772 * @return int result of strcmp
1773 * @since Moodle 2.3
1775 private static function compare_categories_by_sortorder($category1, $category2) {
1776 return strcmp($category1['sortorder'], $category2['sortorder']);
1780 * Returns description of method result value
1782 * @return external_description
1783 * @since Moodle 2.3
1785 public static function get_categories_returns() {
1786 return new external_multiple_structure(
1787 new external_single_structure(
1788 array(
1789 'id' => new external_value(PARAM_INT, 'category id'),
1790 'name' => new external_value(PARAM_TEXT, 'category name'),
1791 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1792 'description' => new external_value(PARAM_RAW, 'category description'),
1793 'descriptionformat' => new external_format_value('description'),
1794 'parent' => new external_value(PARAM_INT, 'parent category id'),
1795 'sortorder' => new external_value(PARAM_INT, 'category sorting order'),
1796 'coursecount' => new external_value(PARAM_INT, 'number of courses in this category'),
1797 'visible' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1798 'visibleold' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1799 'timemodified' => new external_value(PARAM_INT, 'timestamp', VALUE_OPTIONAL),
1800 'depth' => new external_value(PARAM_INT, 'category depth'),
1801 'path' => new external_value(PARAM_TEXT, 'category path'),
1802 'theme' => new external_value(PARAM_THEME, 'category theme', VALUE_OPTIONAL),
1803 ), 'List of categories'
1809 * Returns description of method parameters
1811 * @return external_function_parameters
1812 * @since Moodle 2.3
1814 public static function create_categories_parameters() {
1815 return new external_function_parameters(
1816 array(
1817 'categories' => new external_multiple_structure(
1818 new external_single_structure(
1819 array(
1820 'name' => new external_value(PARAM_TEXT, 'new category name'),
1821 'parent' => new external_value(PARAM_INT,
1822 'the parent category id inside which the new category will be created
1823 - set to 0 for a root category',
1824 VALUE_DEFAULT, 0),
1825 'idnumber' => new external_value(PARAM_RAW,
1826 'the new category idnumber', VALUE_OPTIONAL),
1827 'description' => new external_value(PARAM_RAW,
1828 'the new category description', VALUE_OPTIONAL),
1829 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
1830 'theme' => new external_value(PARAM_THEME,
1831 'the new category theme. This option must be enabled on moodle',
1832 VALUE_OPTIONAL),
1841 * Create categories
1843 * @param array $categories - see create_categories_parameters() for the array structure
1844 * @return array - see create_categories_returns() for the array structure
1845 * @since Moodle 2.3
1847 public static function create_categories($categories) {
1848 global $CFG, $DB;
1849 require_once($CFG->libdir . "/coursecatlib.php");
1851 $params = self::validate_parameters(self::create_categories_parameters(),
1852 array('categories' => $categories));
1854 $transaction = $DB->start_delegated_transaction();
1856 $createdcategories = array();
1857 foreach ($params['categories'] as $category) {
1858 if ($category['parent']) {
1859 if (!$DB->record_exists('course_categories', array('id' => $category['parent']))) {
1860 throw new moodle_exception('unknowcategory');
1862 $context = context_coursecat::instance($category['parent']);
1863 } else {
1864 $context = context_system::instance();
1866 self::validate_context($context);
1867 require_capability('moodle/category:manage', $context);
1869 // this will validate format and throw an exception if there are errors
1870 external_validate_format($category['descriptionformat']);
1872 $newcategory = coursecat::create($category);
1874 $createdcategories[] = array('id' => $newcategory->id, 'name' => $newcategory->name);
1877 $transaction->allow_commit();
1879 return $createdcategories;
1883 * Returns description of method parameters
1885 * @return external_function_parameters
1886 * @since Moodle 2.3
1888 public static function create_categories_returns() {
1889 return new external_multiple_structure(
1890 new external_single_structure(
1891 array(
1892 'id' => new external_value(PARAM_INT, 'new category id'),
1893 'name' => new external_value(PARAM_TEXT, 'new category name'),
1900 * Returns description of method parameters
1902 * @return external_function_parameters
1903 * @since Moodle 2.3
1905 public static function update_categories_parameters() {
1906 return new external_function_parameters(
1907 array(
1908 'categories' => new external_multiple_structure(
1909 new external_single_structure(
1910 array(
1911 'id' => new external_value(PARAM_INT, 'course id'),
1912 'name' => new external_value(PARAM_TEXT, 'category name', VALUE_OPTIONAL),
1913 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1914 'parent' => new external_value(PARAM_INT, 'parent category id', VALUE_OPTIONAL),
1915 'description' => new external_value(PARAM_RAW, 'category description', VALUE_OPTIONAL),
1916 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
1917 'theme' => new external_value(PARAM_THEME,
1918 'the category theme. This option must be enabled on moodle', VALUE_OPTIONAL),
1927 * Update categories
1929 * @param array $categories The list of categories to update
1930 * @return null
1931 * @since Moodle 2.3
1933 public static function update_categories($categories) {
1934 global $CFG, $DB;
1935 require_once($CFG->libdir . "/coursecatlib.php");
1937 // Validate parameters.
1938 $params = self::validate_parameters(self::update_categories_parameters(), array('categories' => $categories));
1940 $transaction = $DB->start_delegated_transaction();
1942 foreach ($params['categories'] as $cat) {
1943 $category = coursecat::get($cat['id']);
1945 $categorycontext = context_coursecat::instance($cat['id']);
1946 self::validate_context($categorycontext);
1947 require_capability('moodle/category:manage', $categorycontext);
1949 // this will throw an exception if descriptionformat is not valid
1950 external_validate_format($cat['descriptionformat']);
1952 $category->update($cat);
1955 $transaction->allow_commit();
1959 * Returns description of method result value
1961 * @return external_description
1962 * @since Moodle 2.3
1964 public static function update_categories_returns() {
1965 return null;
1969 * Returns description of method parameters
1971 * @return external_function_parameters
1972 * @since Moodle 2.3
1974 public static function delete_categories_parameters() {
1975 return new external_function_parameters(
1976 array(
1977 'categories' => new external_multiple_structure(
1978 new external_single_structure(
1979 array(
1980 'id' => new external_value(PARAM_INT, 'category id to delete'),
1981 'newparent' => new external_value(PARAM_INT,
1982 'the parent category to move the contents to, if specified', VALUE_OPTIONAL),
1983 'recursive' => new external_value(PARAM_BOOL, '1: recursively delete all contents inside this
1984 category, 0 (default): move contents to newparent or current parent category (except if parent is root)', VALUE_DEFAULT, 0)
1993 * Delete categories
1995 * @param array $categories A list of category ids
1996 * @return array
1997 * @since Moodle 2.3
1999 public static function delete_categories($categories) {
2000 global $CFG, $DB;
2001 require_once($CFG->dirroot . "/course/lib.php");
2002 require_once($CFG->libdir . "/coursecatlib.php");
2004 // Validate parameters.
2005 $params = self::validate_parameters(self::delete_categories_parameters(), array('categories' => $categories));
2007 $transaction = $DB->start_delegated_transaction();
2009 foreach ($params['categories'] as $category) {
2010 $deletecat = coursecat::get($category['id'], MUST_EXIST);
2011 $context = context_coursecat::instance($deletecat->id);
2012 require_capability('moodle/category:manage', $context);
2013 self::validate_context($context);
2014 self::validate_context(get_category_or_system_context($deletecat->parent));
2016 if ($category['recursive']) {
2017 // If recursive was specified, then we recursively delete the category's contents.
2018 if ($deletecat->can_delete_full()) {
2019 $deletecat->delete_full(false);
2020 } else {
2021 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2023 } else {
2024 // In this situation, we don't delete the category's contents, we either move it to newparent or parent.
2025 // If the parent is the root, moving is not supported (because a course must always be inside a category).
2026 // We must move to an existing category.
2027 if (!empty($category['newparent'])) {
2028 $newparentcat = coursecat::get($category['newparent']);
2029 } else {
2030 $newparentcat = coursecat::get($deletecat->parent);
2033 // This operation is not allowed. We must move contents to an existing category.
2034 if (!$newparentcat->id) {
2035 throw new moodle_exception('movecatcontentstoroot');
2038 self::validate_context(context_coursecat::instance($newparentcat->id));
2039 if ($deletecat->can_move_content_to($newparentcat->id)) {
2040 $deletecat->delete_move($newparentcat->id, false);
2041 } else {
2042 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2047 $transaction->allow_commit();
2051 * Returns description of method parameters
2053 * @return external_function_parameters
2054 * @since Moodle 2.3
2056 public static function delete_categories_returns() {
2057 return null;
2061 * Describes the parameters for delete_modules.
2063 * @return external_function_parameters
2064 * @since Moodle 2.5
2066 public static function delete_modules_parameters() {
2067 return new external_function_parameters (
2068 array(
2069 'cmids' => new external_multiple_structure(new external_value(PARAM_INT, 'course module ID',
2070 VALUE_REQUIRED, '', NULL_NOT_ALLOWED), 'Array of course module IDs'),
2076 * Deletes a list of provided module instances.
2078 * @param array $cmids the course module ids
2079 * @since Moodle 2.5
2081 public static function delete_modules($cmids) {
2082 global $CFG, $DB;
2084 // Require course file containing the course delete module function.
2085 require_once($CFG->dirroot . "/course/lib.php");
2087 // Clean the parameters.
2088 $params = self::validate_parameters(self::delete_modules_parameters(), array('cmids' => $cmids));
2090 // Keep track of the course ids we have performed a capability check on to avoid repeating.
2091 $arrcourseschecked = array();
2093 foreach ($params['cmids'] as $cmid) {
2094 // Get the course module.
2095 $cm = $DB->get_record('course_modules', array('id' => $cmid), '*', MUST_EXIST);
2097 // Check if we have not yet confirmed they have permission in this course.
2098 if (!in_array($cm->course, $arrcourseschecked)) {
2099 // Ensure the current user has required permission in this course.
2100 $context = context_course::instance($cm->course);
2101 self::validate_context($context);
2102 // Add to the array.
2103 $arrcourseschecked[] = $cm->course;
2106 // Ensure they can delete this module.
2107 $modcontext = context_module::instance($cm->id);
2108 require_capability('moodle/course:manageactivities', $modcontext);
2110 // Delete the module.
2111 course_delete_module($cm->id);
2116 * Describes the delete_modules return value.
2118 * @return external_single_structure
2119 * @since Moodle 2.5
2121 public static function delete_modules_returns() {
2122 return null;
2126 * Returns description of method parameters
2128 * @return external_function_parameters
2129 * @since Moodle 2.9
2131 public static function view_course_parameters() {
2132 return new external_function_parameters(
2133 array(
2134 'courseid' => new external_value(PARAM_INT, 'id of the course'),
2135 'sectionnumber' => new external_value(PARAM_INT, 'section number', VALUE_DEFAULT, 0)
2141 * Trigger the course viewed event.
2143 * @param int $courseid id of course
2144 * @param int $sectionnumber sectionnumber (0, 1, 2...)
2145 * @return array of warnings and status result
2146 * @since Moodle 2.9
2147 * @throws moodle_exception
2149 public static function view_course($courseid, $sectionnumber = 0) {
2150 global $CFG;
2151 require_once($CFG->dirroot . "/course/lib.php");
2153 $params = self::validate_parameters(self::view_course_parameters(),
2154 array(
2155 'courseid' => $courseid,
2156 'sectionnumber' => $sectionnumber
2159 $warnings = array();
2161 $course = get_course($params['courseid']);
2162 $context = context_course::instance($course->id);
2163 self::validate_context($context);
2165 if (!empty($params['sectionnumber'])) {
2167 // Get section details and check it exists.
2168 $modinfo = get_fast_modinfo($course);
2169 $coursesection = $modinfo->get_section_info($params['sectionnumber'], MUST_EXIST);
2171 // Check user is allowed to see it.
2172 if (!$coursesection->uservisible) {
2173 require_capability('moodle/course:viewhiddensections', $context);
2177 course_view($context, $params['sectionnumber']);
2179 $result = array();
2180 $result['status'] = true;
2181 $result['warnings'] = $warnings;
2182 return $result;
2186 * Returns description of method result value
2188 * @return external_description
2189 * @since Moodle 2.9
2191 public static function view_course_returns() {
2192 return new external_single_structure(
2193 array(
2194 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
2195 'warnings' => new external_warnings()
2201 * Returns description of method parameters
2203 * @return external_function_parameters
2204 * @since Moodle 3.0
2206 public static function search_courses_parameters() {
2207 return new external_function_parameters(
2208 array(
2209 'criterianame' => new external_value(PARAM_ALPHA, 'criteria name
2210 (search, modulelist (only admins), blocklist (only admins), tagid)'),
2211 'criteriavalue' => new external_value(PARAM_RAW, 'criteria value'),
2212 'page' => new external_value(PARAM_INT, 'page number (0 based)', VALUE_DEFAULT, 0),
2213 'perpage' => new external_value(PARAM_INT, 'items per page', VALUE_DEFAULT, 0),
2214 'requiredcapabilities' => new external_multiple_structure(
2215 new external_value(PARAM_CAPABILITY, 'Capability string used to filter courses by permission'),
2216 'Optional list of required capabilities (used to filter the list)', VALUE_DEFAULT, array()
2218 'limittoenrolled' => new external_value(PARAM_BOOL, 'limit to enrolled courses', VALUE_DEFAULT, 0),
2224 * Return the course information that is public (visible by every one)
2226 * @param course_in_list $course course in list object
2227 * @param stdClass $coursecontext course context object
2228 * @return array the course information
2229 * @since Moodle 3.2
2231 protected static function get_course_public_information(course_in_list $course, $coursecontext) {
2233 static $categoriescache = array();
2235 // Category information.
2236 if (!array_key_exists($course->category, $categoriescache)) {
2237 $categoriescache[$course->category] = coursecat::get($course->category, IGNORE_MISSING);
2239 $category = $categoriescache[$course->category];
2241 // Retrieve course overview used files.
2242 $files = array();
2243 foreach ($course->get_course_overviewfiles() as $file) {
2244 $fileurl = moodle_url::make_webservice_pluginfile_url($file->get_contextid(), $file->get_component(),
2245 $file->get_filearea(), null, $file->get_filepath(),
2246 $file->get_filename())->out(false);
2247 $files[] = array(
2248 'filename' => $file->get_filename(),
2249 'fileurl' => $fileurl,
2250 'filesize' => $file->get_filesize(),
2251 'filepath' => $file->get_filepath(),
2252 'mimetype' => $file->get_mimetype(),
2253 'timemodified' => $file->get_timemodified(),
2257 // Retrieve the course contacts,
2258 // we need here the users fullname since if we are not enrolled can be difficult to obtain them via other Web Services.
2259 $coursecontacts = array();
2260 foreach ($course->get_course_contacts() as $contact) {
2261 $coursecontacts[] = array(
2262 'id' => $contact['user']->id,
2263 'fullname' => $contact['username']
2267 // Allowed enrolment methods (maybe we can self-enrol).
2268 $enroltypes = array();
2269 $instances = enrol_get_instances($course->id, true);
2270 foreach ($instances as $instance) {
2271 $enroltypes[] = $instance->enrol;
2274 // Format summary.
2275 list($summary, $summaryformat) =
2276 external_format_text($course->summary, $course->summaryformat, $coursecontext->id, 'course', 'summary', null);
2278 $displayname = get_course_display_name_for_list($course);
2279 $coursereturns = array();
2280 $coursereturns['id'] = $course->id;
2281 $coursereturns['fullname'] = external_format_string($course->fullname, $coursecontext->id);
2282 $coursereturns['displayname'] = external_format_string($displayname, $coursecontext->id);
2283 $coursereturns['shortname'] = external_format_string($course->shortname, $coursecontext->id);
2284 $coursereturns['categoryid'] = $course->category;
2285 $coursereturns['categoryname'] = $category == null ? '' : $category->name;
2286 $coursereturns['summary'] = $summary;
2287 $coursereturns['summaryformat'] = $summaryformat;
2288 $coursereturns['summaryfiles'] = external_util::get_area_files($coursecontext->id, 'course', 'summary', false, false);
2289 $coursereturns['overviewfiles'] = $files;
2290 $coursereturns['contacts'] = $coursecontacts;
2291 $coursereturns['enrollmentmethods'] = $enroltypes;
2292 $coursereturns['sortorder'] = $course->sortorder;
2293 return $coursereturns;
2297 * Search courses following the specified criteria.
2299 * @param string $criterianame Criteria name (search, modulelist (only admins), blocklist (only admins), tagid)
2300 * @param string $criteriavalue Criteria value
2301 * @param int $page Page number (for pagination)
2302 * @param int $perpage Items per page
2303 * @param array $requiredcapabilities Optional list of required capabilities (used to filter the list).
2304 * @param int $limittoenrolled Limit to only enrolled courses
2305 * @return array of course objects and warnings
2306 * @since Moodle 3.0
2307 * @throws moodle_exception
2309 public static function search_courses($criterianame,
2310 $criteriavalue,
2311 $page=0,
2312 $perpage=0,
2313 $requiredcapabilities=array(),
2314 $limittoenrolled=0) {
2315 global $CFG;
2316 require_once($CFG->libdir . '/coursecatlib.php');
2318 $warnings = array();
2320 $parameters = array(
2321 'criterianame' => $criterianame,
2322 'criteriavalue' => $criteriavalue,
2323 'page' => $page,
2324 'perpage' => $perpage,
2325 'requiredcapabilities' => $requiredcapabilities
2327 $params = self::validate_parameters(self::search_courses_parameters(), $parameters);
2328 self::validate_context(context_system::instance());
2330 $allowedcriterianames = array('search', 'modulelist', 'blocklist', 'tagid');
2331 if (!in_array($params['criterianame'], $allowedcriterianames)) {
2332 throw new invalid_parameter_exception('Invalid value for criterianame parameter (value: '.$params['criterianame'].'),' .
2333 'allowed values are: '.implode(',', $allowedcriterianames));
2336 if ($params['criterianame'] == 'modulelist' or $params['criterianame'] == 'blocklist') {
2337 require_capability('moodle/site:config', context_system::instance());
2340 $paramtype = array(
2341 'search' => PARAM_RAW,
2342 'modulelist' => PARAM_PLUGIN,
2343 'blocklist' => PARAM_INT,
2344 'tagid' => PARAM_INT
2346 $params['criteriavalue'] = clean_param($params['criteriavalue'], $paramtype[$params['criterianame']]);
2348 // Prepare the search API options.
2349 $searchcriteria = array();
2350 $searchcriteria[$params['criterianame']] = $params['criteriavalue'];
2352 $options = array();
2353 if ($params['perpage'] != 0) {
2354 $offset = $params['page'] * $params['perpage'];
2355 $options = array('offset' => $offset, 'limit' => $params['perpage']);
2358 // Search the courses.
2359 $courses = coursecat::search_courses($searchcriteria, $options, $params['requiredcapabilities']);
2360 $totalcount = coursecat::search_courses_count($searchcriteria, $options, $params['requiredcapabilities']);
2362 if (!empty($limittoenrolled)) {
2363 // Get the courses where the current user has access.
2364 $enrolled = enrol_get_my_courses(array('id', 'cacherev'));
2367 $finalcourses = array();
2368 $categoriescache = array();
2370 foreach ($courses as $course) {
2371 if (!empty($limittoenrolled)) {
2372 // Filter out not enrolled courses.
2373 if (!isset($enrolled[$course->id])) {
2374 $totalcount--;
2375 continue;
2379 $coursecontext = context_course::instance($course->id);
2381 $finalcourses[] = self::get_course_public_information($course, $coursecontext);
2384 return array(
2385 'total' => $totalcount,
2386 'courses' => $finalcourses,
2387 'warnings' => $warnings
2392 * Returns a course structure definition
2394 * @param boolean $onlypublicdata set to true, to retrieve only fields viewable by anyone when the course is visible
2395 * @return array the course structure
2396 * @since Moodle 3.2
2398 protected static function get_course_structure($onlypublicdata = true) {
2399 $coursestructure = array(
2400 'id' => new external_value(PARAM_INT, 'course id'),
2401 'fullname' => new external_value(PARAM_TEXT, 'course full name'),
2402 'displayname' => new external_value(PARAM_TEXT, 'course display name'),
2403 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
2404 'categoryid' => new external_value(PARAM_INT, 'category id'),
2405 'categoryname' => new external_value(PARAM_TEXT, 'category name'),
2406 'sortorder' => new external_value(PARAM_INT, 'Sort order in the category', VALUE_OPTIONAL),
2407 'summary' => new external_value(PARAM_RAW, 'summary'),
2408 'summaryformat' => new external_format_value('summary'),
2409 'summaryfiles' => new external_files('summary files in the summary field', VALUE_OPTIONAL),
2410 'overviewfiles' => new external_files('additional overview files attached to this course'),
2411 'contacts' => new external_multiple_structure(
2412 new external_single_structure(
2413 array(
2414 'id' => new external_value(PARAM_INT, 'contact user id'),
2415 'fullname' => new external_value(PARAM_NOTAGS, 'contact user fullname'),
2418 'contact users'
2420 'enrollmentmethods' => new external_multiple_structure(
2421 new external_value(PARAM_PLUGIN, 'enrollment method'),
2422 'enrollment methods list'
2426 if (!$onlypublicdata) {
2427 $extra = array(
2428 'idnumber' => new external_value(PARAM_RAW, 'Id number', VALUE_OPTIONAL),
2429 'format' => new external_value(PARAM_PLUGIN, 'Course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
2430 'showgrades' => new external_value(PARAM_INT, '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
2431 'newsitems' => new external_value(PARAM_INT, 'Number of recent items appearing on the course page', VALUE_OPTIONAL),
2432 'startdate' => new external_value(PARAM_INT, 'Timestamp when the course start', VALUE_OPTIONAL),
2433 'enddate' => new external_value(PARAM_INT, 'Timestamp when the course end', VALUE_OPTIONAL),
2434 'maxbytes' => new external_value(PARAM_INT, 'Largest size of file that can be uploaded into', VALUE_OPTIONAL),
2435 'showreports' => new external_value(PARAM_INT, 'Are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
2436 'visible' => new external_value(PARAM_INT, '1: available to student, 0:not available', VALUE_OPTIONAL),
2437 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
2438 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
2439 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
2440 'enablecompletion' => new external_value(PARAM_INT, 'Completion enabled? 1: yes 0: no', VALUE_OPTIONAL),
2441 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
2442 'lang' => new external_value(PARAM_SAFEDIR, 'Forced course language', VALUE_OPTIONAL),
2443 'theme' => new external_value(PARAM_PLUGIN, 'Fame of the forced theme', VALUE_OPTIONAL),
2444 'marker' => new external_value(PARAM_INT, 'Current course marker', VALUE_OPTIONAL),
2445 'legacyfiles' => new external_value(PARAM_INT, 'If legacy files are enabled', VALUE_OPTIONAL),
2446 'calendartype' => new external_value(PARAM_PLUGIN, 'Calendar type', VALUE_OPTIONAL),
2447 'timecreated' => new external_value(PARAM_INT, 'Time when the course was created', VALUE_OPTIONAL),
2448 'timemodified' => new external_value(PARAM_INT, 'Last time the course was updated', VALUE_OPTIONAL),
2449 'requested' => new external_value(PARAM_INT, 'If is a requested course', VALUE_OPTIONAL),
2450 'cacherev' => new external_value(PARAM_INT, 'Cache revision number', VALUE_OPTIONAL),
2451 'filters' => new external_multiple_structure(
2452 new external_single_structure(
2453 array(
2454 'filter' => new external_value(PARAM_PLUGIN, 'Filter plugin name'),
2455 'localstate' => new external_value(PARAM_INT, 'Filter state: 1 for on, -1 for off, 0 if inherit'),
2456 'inheritedstate' => new external_value(PARAM_INT, '1 or 0 to use when localstate is set to inherit'),
2459 'Course filters', VALUE_OPTIONAL
2462 $coursestructure = array_merge($coursestructure, $extra);
2464 return new external_single_structure($coursestructure);
2468 * Returns description of method result value
2470 * @return external_description
2471 * @since Moodle 3.0
2473 public static function search_courses_returns() {
2474 return new external_single_structure(
2475 array(
2476 'total' => new external_value(PARAM_INT, 'total course count'),
2477 'courses' => new external_multiple_structure(self::get_course_structure(), 'course'),
2478 'warnings' => new external_warnings()
2484 * Returns description of method parameters
2486 * @return external_function_parameters
2487 * @since Moodle 3.0
2489 public static function get_course_module_parameters() {
2490 return new external_function_parameters(
2491 array(
2492 'cmid' => new external_value(PARAM_INT, 'The course module id')
2498 * Return information about a course module.
2500 * @param int $cmid the course module id
2501 * @return array of warnings and the course module
2502 * @since Moodle 3.0
2503 * @throws moodle_exception
2505 public static function get_course_module($cmid) {
2506 global $CFG, $DB;
2508 $params = self::validate_parameters(self::get_course_module_parameters(), array('cmid' => $cmid));
2509 $warnings = array();
2511 $cm = get_coursemodule_from_id(null, $params['cmid'], 0, true, MUST_EXIST);
2512 $context = context_module::instance($cm->id);
2513 self::validate_context($context);
2515 // If the user has permissions to manage the activity, return all the information.
2516 if (has_capability('moodle/course:manageactivities', $context)) {
2517 require_once($CFG->dirroot . '/course/modlib.php');
2518 require_once($CFG->libdir . '/gradelib.php');
2520 $info = $cm;
2521 // Get the extra information: grade, advanced grading and outcomes data.
2522 $course = get_course($cm->course);
2523 list($newcm, $newcontext, $module, $extrainfo, $cw) = get_moduleinfo_data($cm, $course);
2524 // Grades.
2525 $gradeinfo = array('grade', 'gradepass', 'gradecat');
2526 foreach ($gradeinfo as $gfield) {
2527 if (isset($extrainfo->{$gfield})) {
2528 $info->{$gfield} = $extrainfo->{$gfield};
2531 if (isset($extrainfo->grade) and $extrainfo->grade < 0) {
2532 $info->scale = $DB->get_field('scale', 'scale', array('id' => abs($extrainfo->grade)));
2534 // Advanced grading.
2535 if (isset($extrainfo->_advancedgradingdata)) {
2536 $info->advancedgrading = array();
2537 foreach ($extrainfo as $key => $val) {
2538 if (strpos($key, 'advancedgradingmethod_') === 0) {
2539 $info->advancedgrading[] = array(
2540 'area' => str_replace('advancedgradingmethod_', '', $key),
2541 'method' => $val
2546 // Outcomes.
2547 foreach ($extrainfo as $key => $val) {
2548 if (strpos($key, 'outcome_') === 0) {
2549 if (!isset($info->outcomes)) {
2550 $info->outcomes = array();
2552 $id = str_replace('outcome_', '', $key);
2553 $outcome = grade_outcome::fetch(array('id' => $id));
2554 $scaleitems = $outcome->load_scale();
2555 $info->outcomes[] = array(
2556 'id' => $id,
2557 'name' => external_format_string($outcome->get_name(), $context->id),
2558 'scale' => $scaleitems->scale
2562 } else {
2563 // Return information is safe to show to any user.
2564 $info = new stdClass();
2565 $info->id = $cm->id;
2566 $info->course = $cm->course;
2567 $info->module = $cm->module;
2568 $info->modname = $cm->modname;
2569 $info->instance = $cm->instance;
2570 $info->section = $cm->section;
2571 $info->sectionnum = $cm->sectionnum;
2572 $info->groupmode = $cm->groupmode;
2573 $info->groupingid = $cm->groupingid;
2574 $info->completion = $cm->completion;
2576 // Format name.
2577 $info->name = external_format_string($cm->name, $context->id);
2578 $result = array();
2579 $result['cm'] = $info;
2580 $result['warnings'] = $warnings;
2581 return $result;
2585 * Returns description of method result value
2587 * @return external_description
2588 * @since Moodle 3.0
2590 public static function get_course_module_returns() {
2591 return new external_single_structure(
2592 array(
2593 'cm' => new external_single_structure(
2594 array(
2595 'id' => new external_value(PARAM_INT, 'The course module id'),
2596 'course' => new external_value(PARAM_INT, 'The course id'),
2597 'module' => new external_value(PARAM_INT, 'The module type id'),
2598 'name' => new external_value(PARAM_RAW, 'The activity name'),
2599 'modname' => new external_value(PARAM_COMPONENT, 'The module component name (forum, assign, etc..)'),
2600 'instance' => new external_value(PARAM_INT, 'The activity instance id'),
2601 'section' => new external_value(PARAM_INT, 'The module section id'),
2602 'sectionnum' => new external_value(PARAM_INT, 'The module section number'),
2603 'groupmode' => new external_value(PARAM_INT, 'Group mode'),
2604 'groupingid' => new external_value(PARAM_INT, 'Grouping id'),
2605 'completion' => new external_value(PARAM_INT, 'If completion is enabled'),
2606 'idnumber' => new external_value(PARAM_RAW, 'Module id number', VALUE_OPTIONAL),
2607 'added' => new external_value(PARAM_INT, 'Time added', VALUE_OPTIONAL),
2608 'score' => new external_value(PARAM_INT, 'Score', VALUE_OPTIONAL),
2609 'indent' => new external_value(PARAM_INT, 'Indentation', VALUE_OPTIONAL),
2610 'visible' => new external_value(PARAM_INT, 'If visible', VALUE_OPTIONAL),
2611 'visibleoncoursepage' => new external_value(PARAM_INT, 'If visible on course page', VALUE_OPTIONAL),
2612 'visibleold' => new external_value(PARAM_INT, 'Visible old', VALUE_OPTIONAL),
2613 'completiongradeitemnumber' => new external_value(PARAM_INT, 'Completion grade item', VALUE_OPTIONAL),
2614 'completionview' => new external_value(PARAM_INT, 'Completion view setting', VALUE_OPTIONAL),
2615 'completionexpected' => new external_value(PARAM_INT, 'Completion time expected', VALUE_OPTIONAL),
2616 'showdescription' => new external_value(PARAM_INT, 'If the description is showed', VALUE_OPTIONAL),
2617 'availability' => new external_value(PARAM_RAW, 'Availability settings', VALUE_OPTIONAL),
2618 'grade' => new external_value(PARAM_FLOAT, 'Grade (max value or scale id)', VALUE_OPTIONAL),
2619 'scale' => new external_value(PARAM_TEXT, 'Scale items (if used)', VALUE_OPTIONAL),
2620 'gradepass' => new external_value(PARAM_RAW, 'Grade to pass (float)', VALUE_OPTIONAL),
2621 'gradecat' => new external_value(PARAM_INT, 'Grade category', VALUE_OPTIONAL),
2622 'advancedgrading' => new external_multiple_structure(
2623 new external_single_structure(
2624 array(
2625 'area' => new external_value(PARAM_AREA, 'Gradable area name'),
2626 'method' => new external_value(PARAM_COMPONENT, 'Grading method'),
2629 'Advanced grading settings', VALUE_OPTIONAL
2631 'outcomes' => new external_multiple_structure(
2632 new external_single_structure(
2633 array(
2634 'id' => new external_value(PARAM_ALPHANUMEXT, 'Outcome id'),
2635 'name' => new external_value(PARAM_TEXT, 'Outcome full name'),
2636 'scale' => new external_value(PARAM_TEXT, 'Scale items')
2639 'Outcomes information', VALUE_OPTIONAL
2643 'warnings' => new external_warnings()
2649 * Returns description of method parameters
2651 * @return external_function_parameters
2652 * @since Moodle 3.0
2654 public static function get_course_module_by_instance_parameters() {
2655 return new external_function_parameters(
2656 array(
2657 'module' => new external_value(PARAM_COMPONENT, 'The module name'),
2658 'instance' => new external_value(PARAM_INT, 'The module instance id')
2664 * Return information about a course module.
2666 * @param string $module the module name
2667 * @param int $instance the activity instance id
2668 * @return array of warnings and the course module
2669 * @since Moodle 3.0
2670 * @throws moodle_exception
2672 public static function get_course_module_by_instance($module, $instance) {
2674 $params = self::validate_parameters(self::get_course_module_by_instance_parameters(),
2675 array(
2676 'module' => $module,
2677 'instance' => $instance,
2680 $warnings = array();
2681 $cm = get_coursemodule_from_instance($params['module'], $params['instance'], 0, false, MUST_EXIST);
2683 return self::get_course_module($cm->id);
2687 * Returns description of method result value
2689 * @return external_description
2690 * @since Moodle 3.0
2692 public static function get_course_module_by_instance_returns() {
2693 return self::get_course_module_returns();
2697 * Returns description of method parameters
2699 * @deprecated since 3.3
2700 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
2701 * @return external_function_parameters
2702 * @since Moodle 3.2
2704 public static function get_activities_overview_parameters() {
2705 return new external_function_parameters(
2706 array(
2707 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2713 * Return activities overview for the given courses.
2715 * @deprecated since 3.3
2716 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
2717 * @param array $courseids a list of course ids
2718 * @return array of warnings and the activities overview
2719 * @since Moodle 3.2
2720 * @throws moodle_exception
2722 public static function get_activities_overview($courseids) {
2723 global $USER;
2725 // Parameter validation.
2726 $params = self::validate_parameters(self::get_activities_overview_parameters(), array('courseids' => $courseids));
2727 $courseoverviews = array();
2729 list($courses, $warnings) = external_util::validate_courses($params['courseids']);
2731 if (!empty($courses)) {
2732 // Add lastaccess to each course (required by print_overview function).
2733 // We need the complete user data, the ws server does not load a complete one.
2734 $user = get_complete_user_data('id', $USER->id);
2735 foreach ($courses as $course) {
2736 if (isset($user->lastcourseaccess[$course->id])) {
2737 $course->lastaccess = $user->lastcourseaccess[$course->id];
2738 } else {
2739 $course->lastaccess = 0;
2743 $overviews = array();
2744 if ($modules = get_plugin_list_with_function('mod', 'print_overview')) {
2745 foreach ($modules as $fname) {
2746 $fname($courses, $overviews);
2750 // Format output.
2751 foreach ($overviews as $courseid => $modules) {
2752 $courseoverviews[$courseid]['id'] = $courseid;
2753 $courseoverviews[$courseid]['overviews'] = array();
2755 foreach ($modules as $modname => $overviewtext) {
2756 $courseoverviews[$courseid]['overviews'][] = array(
2757 'module' => $modname,
2758 'overviewtext' => $overviewtext // This text doesn't need formatting.
2764 $result = array(
2765 'courses' => $courseoverviews,
2766 'warnings' => $warnings
2768 return $result;
2772 * Returns description of method result value
2774 * @deprecated since 3.3
2775 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
2776 * @return external_description
2777 * @since Moodle 3.2
2779 public static function get_activities_overview_returns() {
2780 return new external_single_structure(
2781 array(
2782 'courses' => new external_multiple_structure(
2783 new external_single_structure(
2784 array(
2785 'id' => new external_value(PARAM_INT, 'Course id'),
2786 'overviews' => new external_multiple_structure(
2787 new external_single_structure(
2788 array(
2789 'module' => new external_value(PARAM_PLUGIN, 'Module name'),
2790 'overviewtext' => new external_value(PARAM_RAW, 'Overview text'),
2795 ), 'List of courses'
2797 'warnings' => new external_warnings()
2803 * Marking the method as deprecated.
2805 * @return bool
2807 public static function get_activities_overview_is_deprecated() {
2808 return true;
2812 * Returns description of method parameters
2814 * @return external_function_parameters
2815 * @since Moodle 3.2
2817 public static function get_user_navigation_options_parameters() {
2818 return new external_function_parameters(
2819 array(
2820 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2826 * Return a list of navigation options in a set of courses that are avaialable or not for the current user.
2828 * @param array $courseids a list of course ids
2829 * @return array of warnings and the options availability
2830 * @since Moodle 3.2
2831 * @throws moodle_exception
2833 public static function get_user_navigation_options($courseids) {
2834 global $CFG;
2835 require_once($CFG->dirroot . '/course/lib.php');
2837 // Parameter validation.
2838 $params = self::validate_parameters(self::get_user_navigation_options_parameters(), array('courseids' => $courseids));
2839 $courseoptions = array();
2841 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
2843 if (!empty($courses)) {
2844 foreach ($courses as $course) {
2845 // Fix the context for the frontpage.
2846 if ($course->id == SITEID) {
2847 $course->context = context_system::instance();
2849 $navoptions = course_get_user_navigation_options($course->context, $course);
2850 $options = array();
2851 foreach ($navoptions as $name => $available) {
2852 $options[] = array(
2853 'name' => $name,
2854 'available' => $available,
2858 $courseoptions[] = array(
2859 'id' => $course->id,
2860 'options' => $options
2865 $result = array(
2866 'courses' => $courseoptions,
2867 'warnings' => $warnings
2869 return $result;
2873 * Returns description of method result value
2875 * @return external_description
2876 * @since Moodle 3.2
2878 public static function get_user_navigation_options_returns() {
2879 return new external_single_structure(
2880 array(
2881 'courses' => new external_multiple_structure(
2882 new external_single_structure(
2883 array(
2884 'id' => new external_value(PARAM_INT, 'Course id'),
2885 'options' => new external_multiple_structure(
2886 new external_single_structure(
2887 array(
2888 'name' => new external_value(PARAM_ALPHANUMEXT, 'Option name'),
2889 'available' => new external_value(PARAM_BOOL, 'Whether the option is available or not'),
2894 ), 'List of courses'
2896 'warnings' => new external_warnings()
2902 * Returns description of method parameters
2904 * @return external_function_parameters
2905 * @since Moodle 3.2
2907 public static function get_user_administration_options_parameters() {
2908 return new external_function_parameters(
2909 array(
2910 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2916 * Return a list of administration options in a set of courses that are available or not for the current user.
2918 * @param array $courseids a list of course ids
2919 * @return array of warnings and the options availability
2920 * @since Moodle 3.2
2921 * @throws moodle_exception
2923 public static function get_user_administration_options($courseids) {
2924 global $CFG;
2925 require_once($CFG->dirroot . '/course/lib.php');
2927 // Parameter validation.
2928 $params = self::validate_parameters(self::get_user_administration_options_parameters(), array('courseids' => $courseids));
2929 $courseoptions = array();
2931 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
2933 if (!empty($courses)) {
2934 foreach ($courses as $course) {
2935 $adminoptions = course_get_user_administration_options($course, $course->context);
2936 $options = array();
2937 foreach ($adminoptions as $name => $available) {
2938 $options[] = array(
2939 'name' => $name,
2940 'available' => $available,
2944 $courseoptions[] = array(
2945 'id' => $course->id,
2946 'options' => $options
2951 $result = array(
2952 'courses' => $courseoptions,
2953 'warnings' => $warnings
2955 return $result;
2959 * Returns description of method result value
2961 * @return external_description
2962 * @since Moodle 3.2
2964 public static function get_user_administration_options_returns() {
2965 return self::get_user_navigation_options_returns();
2969 * Returns description of method parameters
2971 * @return external_function_parameters
2972 * @since Moodle 3.2
2974 public static function get_courses_by_field_parameters() {
2975 return new external_function_parameters(
2976 array(
2977 'field' => new external_value(PARAM_ALPHA, 'The field to search can be left empty for all courses or:
2978 id: course id
2979 ids: comma separated course ids
2980 shortname: course short name
2981 idnumber: course id number
2982 category: category id the course belongs to
2983 ', VALUE_DEFAULT, ''),
2984 'value' => new external_value(PARAM_RAW, 'The value to match', VALUE_DEFAULT, '')
2991 * Get courses matching a specific field (id/s, shortname, idnumber, category)
2993 * @param string $field field name to search, or empty for all courses
2994 * @param string $value value to search
2995 * @return array list of courses and warnings
2996 * @throws invalid_parameter_exception
2997 * @since Moodle 3.2
2999 public static function get_courses_by_field($field = '', $value = '') {
3000 global $DB, $CFG;
3001 require_once($CFG->libdir . '/coursecatlib.php');
3002 require_once($CFG->libdir . '/filterlib.php');
3004 $params = self::validate_parameters(self::get_courses_by_field_parameters(),
3005 array(
3006 'field' => $field,
3007 'value' => $value,
3010 $warnings = array();
3012 if (empty($params['field'])) {
3013 $courses = $DB->get_records('course', null, 'id ASC');
3014 } else {
3015 switch ($params['field']) {
3016 case 'id':
3017 case 'category':
3018 $value = clean_param($params['value'], PARAM_INT);
3019 break;
3020 case 'ids':
3021 $value = clean_param($params['value'], PARAM_SEQUENCE);
3022 break;
3023 case 'shortname':
3024 $value = clean_param($params['value'], PARAM_TEXT);
3025 break;
3026 case 'idnumber':
3027 $value = clean_param($params['value'], PARAM_RAW);
3028 break;
3029 default:
3030 throw new invalid_parameter_exception('Invalid field name');
3033 if ($params['field'] === 'ids') {
3034 $courses = $DB->get_records_list('course', 'id', explode(',', $value), 'id ASC');
3035 } else {
3036 $courses = $DB->get_records('course', array($params['field'] => $value), 'id ASC');
3040 $coursesdata = array();
3041 foreach ($courses as $course) {
3042 $context = context_course::instance($course->id);
3043 $canupdatecourse = has_capability('moodle/course:update', $context);
3044 $canviewhiddencourses = has_capability('moodle/course:viewhiddencourses', $context);
3046 // Check if the course is visible in the site for the user.
3047 if (!$course->visible and !$canviewhiddencourses and !$canupdatecourse) {
3048 continue;
3050 // Get the public course information, even if we are not enrolled.
3051 $courseinlist = new course_in_list($course);
3052 $coursesdata[$course->id] = self::get_course_public_information($courseinlist, $context);
3054 // Now, check if we have access to the course.
3055 try {
3056 self::validate_context($context);
3057 } catch (Exception $e) {
3058 continue;
3060 // Return information for any user that can access the course.
3061 $coursefields = array('format', 'showgrades', 'newsitems', 'startdate', 'enddate', 'maxbytes', 'showreports', 'visible',
3062 'groupmode', 'groupmodeforce', 'defaultgroupingid', 'enablecompletion', 'completionnotify', 'lang', 'theme',
3063 'marker');
3065 // Course filters.
3066 $coursesdata[$course->id]['filters'] = filter_get_available_in_context($context);
3068 // Information for managers only.
3069 if ($canupdatecourse) {
3070 $managerfields = array('idnumber', 'legacyfiles', 'calendartype', 'timecreated', 'timemodified', 'requested',
3071 'cacherev');
3072 $coursefields = array_merge($coursefields, $managerfields);
3075 // Populate fields.
3076 foreach ($coursefields as $field) {
3077 $coursesdata[$course->id][$field] = $course->{$field};
3080 // Clean lang and auth fields for external functions (it may content uninstalled themes or language packs).
3081 if (isset($coursesdata[$course->id]['theme'])) {
3082 $coursesdata[$course->id]['theme'] = clean_param($coursesdata[$course->id]['theme'], PARAM_THEME);
3084 if (isset($coursesdata[$course->id]['lang'])) {
3085 $coursesdata[$course->id]['lang'] = clean_param($coursesdata[$course->id]['lang'], PARAM_LANG);
3089 return array(
3090 'courses' => $coursesdata,
3091 'warnings' => $warnings
3096 * Returns description of method result value
3098 * @return external_description
3099 * @since Moodle 3.2
3101 public static function get_courses_by_field_returns() {
3102 // Course structure, including not only public viewable fields.
3103 return new external_single_structure(
3104 array(
3105 'courses' => new external_multiple_structure(self::get_course_structure(false), 'Course'),
3106 'warnings' => new external_warnings()
3112 * Returns description of method parameters
3114 * @return external_function_parameters
3115 * @since Moodle 3.2
3117 public static function check_updates_parameters() {
3118 return new external_function_parameters(
3119 array(
3120 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3121 'tocheck' => new external_multiple_structure(
3122 new external_single_structure(
3123 array(
3124 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level for the file location.
3125 Only module supported right now.'),
3126 'id' => new external_value(PARAM_INT, 'Context instance id'),
3127 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3130 'Instances to check'
3132 'filter' => new external_multiple_structure(
3133 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3134 gradeitems, outcomes'),
3135 'Check only for updates in these areas', VALUE_DEFAULT, array()
3142 * Check if there is updates affecting the user for the given course and contexts.
3143 * Right now only modules are supported.
3144 * This WS calls mod_check_updates_since for each module to check if there is any update the user should we aware of.
3146 * @param int $courseid the list of modules to check
3147 * @param array $tocheck the list of modules to check
3148 * @param array $filter check only for updates in these areas
3149 * @return array list of updates and warnings
3150 * @throws moodle_exception
3151 * @since Moodle 3.2
3153 public static function check_updates($courseid, $tocheck, $filter = array()) {
3154 global $CFG, $DB;
3155 require_once($CFG->dirroot . "/course/lib.php");
3157 $params = self::validate_parameters(
3158 self::check_updates_parameters(),
3159 array(
3160 'courseid' => $courseid,
3161 'tocheck' => $tocheck,
3162 'filter' => $filter,
3166 $course = get_course($params['courseid']);
3167 $context = context_course::instance($course->id);
3168 self::validate_context($context);
3170 list($instances, $warnings) = course_check_updates($course, $params['tocheck'], $filter);
3172 $instancesformatted = array();
3173 foreach ($instances as $instance) {
3174 $updates = array();
3175 foreach ($instance['updates'] as $name => $data) {
3176 if (empty($data->updated)) {
3177 continue;
3179 $updatedata = array(
3180 'name' => $name,
3182 if (!empty($data->timeupdated)) {
3183 $updatedata['timeupdated'] = $data->timeupdated;
3185 if (!empty($data->itemids)) {
3186 $updatedata['itemids'] = $data->itemids;
3188 $updates[] = $updatedata;
3190 if (!empty($updates)) {
3191 $instancesformatted[] = array(
3192 'contextlevel' => $instance['contextlevel'],
3193 'id' => $instance['id'],
3194 'updates' => $updates
3199 return array(
3200 'instances' => $instancesformatted,
3201 'warnings' => $warnings
3206 * Returns description of method result value
3208 * @return external_description
3209 * @since Moodle 3.2
3211 public static function check_updates_returns() {
3212 return new external_single_structure(
3213 array(
3214 'instances' => new external_multiple_structure(
3215 new external_single_structure(
3216 array(
3217 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level'),
3218 'id' => new external_value(PARAM_INT, 'Instance id'),
3219 'updates' => new external_multiple_structure(
3220 new external_single_structure(
3221 array(
3222 'name' => new external_value(PARAM_ALPHANUMEXT, 'Name of the area updated.'),
3223 'timeupdated' => new external_value(PARAM_INT, 'Last time was updated', VALUE_OPTIONAL),
3224 'itemids' => new external_multiple_structure(
3225 new external_value(PARAM_INT, 'Instance id'),
3226 'The ids of the items updated',
3227 VALUE_OPTIONAL
3235 'warnings' => new external_warnings()
3241 * Returns description of method parameters
3243 * @return external_function_parameters
3244 * @since Moodle 3.3
3246 public static function get_updates_since_parameters() {
3247 return new external_function_parameters(
3248 array(
3249 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3250 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3251 'filter' => new external_multiple_structure(
3252 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3253 gradeitems, outcomes'),
3254 'Check only for updates in these areas', VALUE_DEFAULT, array()
3261 * Check if there are updates affecting the user for the given course since the given time stamp.
3263 * This function is a wrapper of self::check_updates for retrieving all the updates since a given time for all the activities.
3265 * @param int $courseid the list of modules to check
3266 * @param int $since check updates since this time stamp
3267 * @param array $filter check only for updates in these areas
3268 * @return array list of updates and warnings
3269 * @throws moodle_exception
3270 * @since Moodle 3.3
3272 public static function get_updates_since($courseid, $since, $filter = array()) {
3273 global $CFG, $DB;
3275 $params = self::validate_parameters(
3276 self::get_updates_since_parameters(),
3277 array(
3278 'courseid' => $courseid,
3279 'since' => $since,
3280 'filter' => $filter,
3284 $course = get_course($params['courseid']);
3285 $modinfo = get_fast_modinfo($course);
3286 $tocheck = array();
3288 // Retrieve all the visible course modules for the current user.
3289 $cms = $modinfo->get_cms();
3290 foreach ($cms as $cm) {
3291 if (!$cm->uservisible) {
3292 continue;
3294 $tocheck[] = array(
3295 'id' => $cm->id,
3296 'contextlevel' => 'module',
3297 'since' => $params['since'],
3301 return self::check_updates($course->id, $tocheck, $params['filter']);
3305 * Returns description of method result value
3307 * @return external_description
3308 * @since Moodle 3.3
3310 public static function get_updates_since_returns() {
3311 return self::check_updates_returns();
3315 * Parameters for function edit_module()
3317 * @since Moodle 3.3
3318 * @return external_function_parameters
3320 public static function edit_module_parameters() {
3321 return new external_function_parameters(
3322 array(
3323 'action' => new external_value(PARAM_ALPHA,
3324 'action: hide, show, stealth, duplicate, delete, moveleft, moveright, group...', VALUE_REQUIRED),
3325 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3326 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3331 * Performs one of the edit module actions and return new html for AJAX
3333 * Returns html to replace the current module html with, for example:
3334 * - empty string for "delete" action,
3335 * - two modules html for "duplicate" action
3336 * - updated module html for everything else
3338 * Throws exception if operation is not permitted/possible
3340 * @since Moodle 3.3
3341 * @param string $action
3342 * @param int $id
3343 * @param null|int $sectionreturn
3344 * @return string
3346 public static function edit_module($action, $id, $sectionreturn = null) {
3347 global $PAGE, $DB;
3348 // Validate and normalize parameters.
3349 $params = self::validate_parameters(self::edit_module_parameters(),
3350 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3351 $action = $params['action'];
3352 $id = $params['id'];
3353 $sectionreturn = $params['sectionreturn'];
3355 list($course, $cm) = get_course_and_cm_from_cmid($id);
3356 $modcontext = context_module::instance($cm->id);
3357 $coursecontext = context_course::instance($course->id);
3358 self::validate_context($modcontext);
3359 $courserenderer = $PAGE->get_renderer('core', 'course');
3360 $completioninfo = new completion_info($course);
3362 switch($action) {
3363 case 'hide':
3364 case 'show':
3365 case 'stealth':
3366 require_capability('moodle/course:activityvisibility', $modcontext);
3367 $visible = ($action === 'hide') ? 0 : 1;
3368 $visibleoncoursepage = ($action === 'stealth') ? 0 : 1;
3369 set_coursemodule_visible($id, $visible, $visibleoncoursepage);
3370 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3371 break;
3372 case 'duplicate':
3373 require_capability('moodle/course:manageactivities', $coursecontext);
3374 require_capability('moodle/backup:backuptargetimport', $coursecontext);
3375 require_capability('moodle/restore:restoretargetimport', $coursecontext);
3376 if (!course_allowed_module($course, $cm->modname)) {
3377 throw new moodle_exception('No permission to create that activity');
3379 if ($newcm = duplicate_module($course, $cm)) {
3380 $cm = get_fast_modinfo($course)->get_cm($id);
3381 $newcm = get_fast_modinfo($course)->get_cm($newcm->id);
3382 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn) .
3383 $courserenderer->course_section_cm_list_item($course, $completioninfo, $newcm, $sectionreturn);
3385 break;
3386 case 'groupsseparate':
3387 case 'groupsvisible':
3388 case 'groupsnone':
3389 require_capability('moodle/course:manageactivities', $modcontext);
3390 if ($action === 'groupsseparate') {
3391 $newgroupmode = SEPARATEGROUPS;
3392 } else if ($action === 'groupsvisible') {
3393 $newgroupmode = VISIBLEGROUPS;
3394 } else {
3395 $newgroupmode = NOGROUPS;
3397 if (set_coursemodule_groupmode($cm->id, $newgroupmode)) {
3398 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3400 break;
3401 case 'moveleft':
3402 case 'moveright':
3403 require_capability('moodle/course:manageactivities', $modcontext);
3404 $indent = $cm->indent + (($action === 'moveright') ? 1 : -1);
3405 if ($cm->indent >= 0) {
3406 $DB->update_record('course_modules', array('id' => $cm->id, 'indent' => $indent));
3407 rebuild_course_cache($cm->course);
3409 break;
3410 case 'delete':
3411 require_capability('moodle/course:manageactivities', $modcontext);
3412 course_delete_module($cm->id, true);
3413 return '';
3414 default:
3415 throw new coding_exception('Unrecognised action');
3418 $cm = get_fast_modinfo($course)->get_cm($id);
3419 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn);
3423 * Return structure for edit_module()
3425 * @since Moodle 3.3
3426 * @return external_description
3428 public static function edit_module_returns() {
3429 return new external_value(PARAM_RAW, 'html to replace the current module with');
3433 * Parameters for function get_module()
3435 * @since Moodle 3.3
3436 * @return external_function_parameters
3438 public static function get_module_parameters() {
3439 return new external_function_parameters(
3440 array(
3441 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3442 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3447 * Returns html for displaying one activity module on course page
3449 * @since Moodle 3.3
3450 * @param int $id
3451 * @param null|int $sectionreturn
3452 * @return string
3454 public static function get_module($id, $sectionreturn = null) {
3455 global $PAGE;
3456 // Validate and normalize parameters.
3457 $params = self::validate_parameters(self::get_module_parameters(),
3458 array('id' => $id, 'sectionreturn' => $sectionreturn));
3459 $id = $params['id'];
3460 $sectionreturn = $params['sectionreturn'];
3462 // Validate access to the course (note, this is html for the course view page, we don't validate access to the module).
3463 list($course, $cm) = get_course_and_cm_from_cmid($id);
3464 self::validate_context(context_course::instance($course->id));
3466 $courserenderer = $PAGE->get_renderer('core', 'course');
3467 $completioninfo = new completion_info($course);
3468 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn);
3472 * Return structure for edit_module()
3474 * @since Moodle 3.3
3475 * @return external_description
3477 public static function get_module_returns() {
3478 return new external_value(PARAM_RAW, 'html to replace the current module with');
3482 * Parameters for function edit_section()
3484 * @since Moodle 3.3
3485 * @return external_function_parameters
3487 public static function edit_section_parameters() {
3488 return new external_function_parameters(
3489 array(
3490 'action' => new external_value(PARAM_ALPHA, 'action: hide, show, stealth, setmarker, removemarker', VALUE_REQUIRED),
3491 'id' => new external_value(PARAM_INT, 'course section id', VALUE_REQUIRED),
3492 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3497 * Performs one of the edit section actions
3499 * @since Moodle 3.3
3500 * @param string $action
3501 * @param int $id section id
3502 * @param int $sectionreturn section to return to
3503 * @return string
3505 public static function edit_section($action, $id, $sectionreturn) {
3506 global $DB;
3507 // Validate and normalize parameters.
3508 $params = self::validate_parameters(self::edit_section_parameters(),
3509 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3510 $action = $params['action'];
3511 $id = $params['id'];
3512 $sr = $params['sectionreturn'];
3514 $section = $DB->get_record('course_sections', array('id' => $id), '*', MUST_EXIST);
3515 $coursecontext = context_course::instance($section->course);
3516 self::validate_context($coursecontext);
3518 $rv = course_get_format($section->course)->section_action($section, $action, $sectionreturn);
3519 if ($rv) {
3520 return json_encode($rv);
3521 } else {
3522 return null;
3527 * Return structure for edit_section()
3529 * @since Moodle 3.3
3530 * @return external_description
3532 public static function edit_section_returns() {
3533 return new external_value(PARAM_RAW, 'Additional data for javascript (JSON-encoded string)');