Merge branch 'MDL-60125-master' of git://github.com/andrewnicols/moodle
[moodle.git] / course / externallib.php
blob3919365b6ab1c53aa685382854139a683ae6a259
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 list($module['description'], $descriptionformat) = external_format_text($cm->content,
272 FORMAT_HTML, $modcontext->id, $cm->modname, 'intro', $cm->id);
275 //url of the module
276 $url = $cm->url;
277 if ($url) { //labels don't have url
278 $module['url'] = $url->out(false);
281 $canviewhidden = has_capability('moodle/course:viewhiddenactivities',
282 context_module::instance($cm->id));
283 //user that can view hidden module should know about the visibility
284 $module['visible'] = $cm->visible;
285 $module['visibleoncoursepage'] = $cm->visibleoncoursepage;
286 $module['uservisible'] = $cm->uservisible;
287 if (!empty($cm->availableinfo)) {
288 $module['availabilityinfo'] = \core_availability\info::format_info($cm->availableinfo, $course);
291 // Availability date (also send to user who can see hidden module).
292 if ($CFG->enableavailability && ($canviewhidden || $canupdatecourse)) {
293 $module['availability'] = $cm->availability;
296 // Return contents only if the user can access to the module.
297 if ($cm->uservisible) {
298 $baseurl = 'webservice/pluginfile.php';
300 // Call $modulename_export_contents (each module callback take care about checking the capabilities).
301 require_once($CFG->dirroot . '/mod/' . $cm->modname . '/lib.php');
302 $getcontentfunction = $cm->modname.'_export_contents';
303 if (function_exists($getcontentfunction)) {
304 if (empty($filters['excludecontents']) and $contents = $getcontentfunction($cm, $baseurl)) {
305 $module['contents'] = $contents;
306 } else {
307 $module['contents'] = array();
312 //assign result to $sectioncontents
313 $sectioncontents[] = $module;
315 // If we just did a filtering, break the loop.
316 if ($modfound) {
317 break;
322 $sectionvalues['modules'] = $sectioncontents;
324 // assign result to $coursecontents
325 $coursecontents[] = $sectionvalues;
327 // Break the loop if we are filtering.
328 if ($sectionfound) {
329 break;
333 return $coursecontents;
337 * Returns description of method result value
339 * @return external_description
340 * @since Moodle 2.2
342 public static function get_course_contents_returns() {
343 return new external_multiple_structure(
344 new external_single_structure(
345 array(
346 'id' => new external_value(PARAM_INT, 'Section ID'),
347 'name' => new external_value(PARAM_TEXT, 'Section name'),
348 'visible' => new external_value(PARAM_INT, 'is the section visible', VALUE_OPTIONAL),
349 'summary' => new external_value(PARAM_RAW, 'Section description'),
350 'summaryformat' => new external_format_value('summary'),
351 'section' => new external_value(PARAM_INT, 'Section number inside the course', VALUE_OPTIONAL),
352 'hiddenbynumsections' => new external_value(PARAM_INT, 'Whether is a section hidden in the course format',
353 VALUE_OPTIONAL),
354 'uservisible' => new external_value(PARAM_BOOL, 'Is the section visible for the user?', VALUE_OPTIONAL),
355 'availabilityinfo' => new external_value(PARAM_RAW, 'Availability information.', VALUE_OPTIONAL),
356 'modules' => new external_multiple_structure(
357 new external_single_structure(
358 array(
359 'id' => new external_value(PARAM_INT, 'activity id'),
360 'url' => new external_value(PARAM_URL, 'activity url', VALUE_OPTIONAL),
361 'name' => new external_value(PARAM_RAW, 'activity module name'),
362 'instance' => new external_value(PARAM_INT, 'instance id', VALUE_OPTIONAL),
363 'description' => new external_value(PARAM_RAW, 'activity description', VALUE_OPTIONAL),
364 'visible' => new external_value(PARAM_INT, 'is the module visible', VALUE_OPTIONAL),
365 'uservisible' => new external_value(PARAM_BOOL, 'Is the module visible for the user?',
366 VALUE_OPTIONAL),
367 'availabilityinfo' => new external_value(PARAM_RAW, 'Availability information.',
368 VALUE_OPTIONAL),
369 'visibleoncoursepage' => new external_value(PARAM_INT, 'is the module visible on course page',
370 VALUE_OPTIONAL),
371 'modicon' => new external_value(PARAM_URL, 'activity icon url'),
372 'modname' => new external_value(PARAM_PLUGIN, 'activity module type'),
373 'modplural' => new external_value(PARAM_TEXT, 'activity module plural name'),
374 'availability' => new external_value(PARAM_RAW, 'module availability settings', VALUE_OPTIONAL),
375 'indent' => new external_value(PARAM_INT, 'number of identation in the site'),
376 'contents' => new external_multiple_structure(
377 new external_single_structure(
378 array(
379 // content info
380 'type'=> new external_value(PARAM_TEXT, 'a file or a folder or external link'),
381 'filename'=> new external_value(PARAM_FILE, 'filename'),
382 'filepath'=> new external_value(PARAM_PATH, 'filepath'),
383 'filesize'=> new external_value(PARAM_INT, 'filesize'),
384 'fileurl' => new external_value(PARAM_URL, 'downloadable file url', VALUE_OPTIONAL),
385 'content' => new external_value(PARAM_RAW, 'Raw content, will be used when type is content', VALUE_OPTIONAL),
386 'timecreated' => new external_value(PARAM_INT, 'Time created'),
387 'timemodified' => new external_value(PARAM_INT, 'Time modified'),
388 'sortorder' => new external_value(PARAM_INT, 'Content sort order'),
389 'mimetype' => new external_value(PARAM_RAW, 'File mime type.', VALUE_OPTIONAL),
390 'isexternalfile' => new external_value(PARAM_BOOL, 'Whether is an external file.',
391 VALUE_OPTIONAL),
392 'repositorytype' => new external_value(PARAM_PLUGIN, 'The repository type for external files.',
393 VALUE_OPTIONAL),
395 // copyright related info
396 'userid' => new external_value(PARAM_INT, 'User who added this content to moodle'),
397 'author' => new external_value(PARAM_TEXT, 'Content owner'),
398 'license' => new external_value(PARAM_TEXT, 'Content license'),
400 ), VALUE_DEFAULT, array()
403 ), 'list of module'
411 * Returns description of method parameters
413 * @return external_function_parameters
414 * @since Moodle 2.3
416 public static function get_courses_parameters() {
417 return new external_function_parameters(
418 array('options' => new external_single_structure(
419 array('ids' => new external_multiple_structure(
420 new external_value(PARAM_INT, 'Course id')
421 , 'List of course id. If empty return all courses
422 except front page course.',
423 VALUE_OPTIONAL)
424 ), 'options - operator OR is used', VALUE_DEFAULT, array())
430 * Get courses
432 * @param array $options It contains an array (list of ids)
433 * @return array
434 * @since Moodle 2.2
436 public static function get_courses($options = array()) {
437 global $CFG, $DB;
438 require_once($CFG->dirroot . "/course/lib.php");
440 //validate parameter
441 $params = self::validate_parameters(self::get_courses_parameters(),
442 array('options' => $options));
444 //retrieve courses
445 if (!array_key_exists('ids', $params['options'])
446 or empty($params['options']['ids'])) {
447 $courses = $DB->get_records('course');
448 } else {
449 $courses = $DB->get_records_list('course', 'id', $params['options']['ids']);
452 //create return value
453 $coursesinfo = array();
454 foreach ($courses as $course) {
456 // now security checks
457 $context = context_course::instance($course->id, IGNORE_MISSING);
458 $courseformatoptions = course_get_format($course)->get_format_options();
459 try {
460 self::validate_context($context);
461 } catch (Exception $e) {
462 $exceptionparam = new stdClass();
463 $exceptionparam->message = $e->getMessage();
464 $exceptionparam->courseid = $course->id;
465 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
467 if ($course->id != SITEID) {
468 require_capability('moodle/course:view', $context);
471 $courseinfo = array();
472 $courseinfo['id'] = $course->id;
473 $courseinfo['fullname'] = external_format_string($course->fullname, $context->id);
474 $courseinfo['shortname'] = external_format_string($course->shortname, $context->id);
475 $courseinfo['displayname'] = external_format_string(get_course_display_name_for_list($course), $context->id);
476 $courseinfo['categoryid'] = $course->category;
477 list($courseinfo['summary'], $courseinfo['summaryformat']) =
478 external_format_text($course->summary, $course->summaryformat, $context->id, 'course', 'summary', 0);
479 $courseinfo['format'] = $course->format;
480 $courseinfo['startdate'] = $course->startdate;
481 $courseinfo['enddate'] = $course->enddate;
482 if (array_key_exists('numsections', $courseformatoptions)) {
483 // For backward-compartibility
484 $courseinfo['numsections'] = $courseformatoptions['numsections'];
487 //some field should be returned only if the user has update permission
488 $courseadmin = has_capability('moodle/course:update', $context);
489 if ($courseadmin) {
490 $courseinfo['categorysortorder'] = $course->sortorder;
491 $courseinfo['idnumber'] = $course->idnumber;
492 $courseinfo['showgrades'] = $course->showgrades;
493 $courseinfo['showreports'] = $course->showreports;
494 $courseinfo['newsitems'] = $course->newsitems;
495 $courseinfo['visible'] = $course->visible;
496 $courseinfo['maxbytes'] = $course->maxbytes;
497 if (array_key_exists('hiddensections', $courseformatoptions)) {
498 // For backward-compartibility
499 $courseinfo['hiddensections'] = $courseformatoptions['hiddensections'];
501 // Return numsections for backward-compatibility with clients who expect it.
502 $courseinfo['numsections'] = course_get_format($course)->get_last_section_number();
503 $courseinfo['groupmode'] = $course->groupmode;
504 $courseinfo['groupmodeforce'] = $course->groupmodeforce;
505 $courseinfo['defaultgroupingid'] = $course->defaultgroupingid;
506 $courseinfo['lang'] = $course->lang;
507 $courseinfo['timecreated'] = $course->timecreated;
508 $courseinfo['timemodified'] = $course->timemodified;
509 $courseinfo['forcetheme'] = $course->theme;
510 $courseinfo['enablecompletion'] = $course->enablecompletion;
511 $courseinfo['completionnotify'] = $course->completionnotify;
512 $courseinfo['courseformatoptions'] = array();
513 foreach ($courseformatoptions as $key => $value) {
514 $courseinfo['courseformatoptions'][] = array(
515 'name' => $key,
516 'value' => $value
521 if ($courseadmin or $course->visible
522 or has_capability('moodle/course:viewhiddencourses', $context)) {
523 $coursesinfo[] = $courseinfo;
527 return $coursesinfo;
531 * Returns description of method result value
533 * @return external_description
534 * @since Moodle 2.2
536 public static function get_courses_returns() {
537 return new external_multiple_structure(
538 new external_single_structure(
539 array(
540 'id' => new external_value(PARAM_INT, 'course id'),
541 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
542 'categoryid' => new external_value(PARAM_INT, 'category id'),
543 'categorysortorder' => new external_value(PARAM_INT,
544 'sort order into the category', VALUE_OPTIONAL),
545 'fullname' => new external_value(PARAM_TEXT, 'full name'),
546 'displayname' => new external_value(PARAM_TEXT, 'course display name'),
547 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
548 'summary' => new external_value(PARAM_RAW, 'summary'),
549 'summaryformat' => new external_format_value('summary'),
550 'format' => new external_value(PARAM_PLUGIN,
551 'course format: weeks, topics, social, site,..'),
552 'showgrades' => new external_value(PARAM_INT,
553 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
554 'newsitems' => new external_value(PARAM_INT,
555 'number of recent items appearing on the course page', VALUE_OPTIONAL),
556 'startdate' => new external_value(PARAM_INT,
557 'timestamp when the course start'),
558 'enddate' => new external_value(PARAM_INT,
559 'timestamp when the course end'),
560 'numsections' => new external_value(PARAM_INT,
561 '(deprecated, use courseformatoptions) number of weeks/topics',
562 VALUE_OPTIONAL),
563 'maxbytes' => new external_value(PARAM_INT,
564 'largest size of file that can be uploaded into the course',
565 VALUE_OPTIONAL),
566 'showreports' => new external_value(PARAM_INT,
567 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
568 'visible' => new external_value(PARAM_INT,
569 '1: available to student, 0:not available', VALUE_OPTIONAL),
570 'hiddensections' => new external_value(PARAM_INT,
571 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
572 VALUE_OPTIONAL),
573 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
574 VALUE_OPTIONAL),
575 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
576 VALUE_OPTIONAL),
577 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
578 VALUE_OPTIONAL),
579 'timecreated' => new external_value(PARAM_INT,
580 'timestamp when the course have been created', VALUE_OPTIONAL),
581 'timemodified' => new external_value(PARAM_INT,
582 'timestamp when the course have been modified', VALUE_OPTIONAL),
583 'enablecompletion' => new external_value(PARAM_INT,
584 'Enabled, control via completion and activity settings. Disbaled,
585 not shown in activity settings.',
586 VALUE_OPTIONAL),
587 'completionnotify' => new external_value(PARAM_INT,
588 '1: yes 0: no', VALUE_OPTIONAL),
589 'lang' => new external_value(PARAM_SAFEDIR,
590 'forced course language', VALUE_OPTIONAL),
591 'forcetheme' => new external_value(PARAM_PLUGIN,
592 'name of the force theme', VALUE_OPTIONAL),
593 'courseformatoptions' => new external_multiple_structure(
594 new external_single_structure(
595 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
596 'value' => new external_value(PARAM_RAW, 'course format option value')
598 'additional options for particular course format', VALUE_OPTIONAL
600 ), 'course'
606 * Returns description of method parameters
608 * @return external_function_parameters
609 * @since Moodle 2.2
611 public static function create_courses_parameters() {
612 $courseconfig = get_config('moodlecourse'); //needed for many default values
613 return new external_function_parameters(
614 array(
615 'courses' => new external_multiple_structure(
616 new external_single_structure(
617 array(
618 'fullname' => new external_value(PARAM_TEXT, 'full name'),
619 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
620 'categoryid' => new external_value(PARAM_INT, 'category id'),
621 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
622 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
623 'summaryformat' => new external_format_value('summary', VALUE_DEFAULT),
624 'format' => new external_value(PARAM_PLUGIN,
625 'course format: weeks, topics, social, site,..',
626 VALUE_DEFAULT, $courseconfig->format),
627 'showgrades' => new external_value(PARAM_INT,
628 '1 if grades are shown, otherwise 0', VALUE_DEFAULT,
629 $courseconfig->showgrades),
630 'newsitems' => new external_value(PARAM_INT,
631 'number of recent items appearing on the course page',
632 VALUE_DEFAULT, $courseconfig->newsitems),
633 'startdate' => new external_value(PARAM_INT,
634 'timestamp when the course start', VALUE_OPTIONAL),
635 'enddate' => new external_value(PARAM_INT,
636 'timestamp when the course end', VALUE_OPTIONAL),
637 'numsections' => new external_value(PARAM_INT,
638 '(deprecated, use courseformatoptions) number of weeks/topics',
639 VALUE_OPTIONAL),
640 'maxbytes' => new external_value(PARAM_INT,
641 'largest size of file that can be uploaded into the course',
642 VALUE_DEFAULT, $courseconfig->maxbytes),
643 'showreports' => new external_value(PARAM_INT,
644 'are activity report shown (yes = 1, no =0)', VALUE_DEFAULT,
645 $courseconfig->showreports),
646 'visible' => new external_value(PARAM_INT,
647 '1: available to student, 0:not available', VALUE_OPTIONAL),
648 'hiddensections' => new external_value(PARAM_INT,
649 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
650 VALUE_OPTIONAL),
651 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
652 VALUE_DEFAULT, $courseconfig->groupmode),
653 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
654 VALUE_DEFAULT, $courseconfig->groupmodeforce),
655 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
656 VALUE_DEFAULT, 0),
657 'enablecompletion' => new external_value(PARAM_INT,
658 'Enabled, control via completion and activity settings. Disabled,
659 not shown in activity settings.',
660 VALUE_OPTIONAL),
661 'completionnotify' => new external_value(PARAM_INT,
662 '1: yes 0: no', VALUE_OPTIONAL),
663 'lang' => new external_value(PARAM_SAFEDIR,
664 'forced course language', VALUE_OPTIONAL),
665 'forcetheme' => new external_value(PARAM_PLUGIN,
666 'name of the force theme', VALUE_OPTIONAL),
667 'courseformatoptions' => new external_multiple_structure(
668 new external_single_structure(
669 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
670 'value' => new external_value(PARAM_RAW, 'course format option value')
672 'additional options for particular course format', VALUE_OPTIONAL),
674 ), 'courses to create'
681 * Create courses
683 * @param array $courses
684 * @return array courses (id and shortname only)
685 * @since Moodle 2.2
687 public static function create_courses($courses) {
688 global $CFG, $DB;
689 require_once($CFG->dirroot . "/course/lib.php");
690 require_once($CFG->libdir . '/completionlib.php');
692 $params = self::validate_parameters(self::create_courses_parameters(),
693 array('courses' => $courses));
695 $availablethemes = core_component::get_plugin_list('theme');
696 $availablelangs = get_string_manager()->get_list_of_translations();
698 $transaction = $DB->start_delegated_transaction();
700 foreach ($params['courses'] as $course) {
702 // Ensure the current user is allowed to run this function
703 $context = context_coursecat::instance($course['categoryid'], IGNORE_MISSING);
704 try {
705 self::validate_context($context);
706 } catch (Exception $e) {
707 $exceptionparam = new stdClass();
708 $exceptionparam->message = $e->getMessage();
709 $exceptionparam->catid = $course['categoryid'];
710 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
712 require_capability('moodle/course:create', $context);
714 // Make sure lang is valid
715 if (array_key_exists('lang', $course) and empty($availablelangs[$course['lang']])) {
716 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
719 // Make sure theme is valid
720 if (array_key_exists('forcetheme', $course)) {
721 if (!empty($CFG->allowcoursethemes)) {
722 if (empty($availablethemes[$course['forcetheme']])) {
723 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
724 } else {
725 $course['theme'] = $course['forcetheme'];
730 //force visibility if ws user doesn't have the permission to set it
731 $category = $DB->get_record('course_categories', array('id' => $course['categoryid']));
732 if (!has_capability('moodle/course:visibility', $context)) {
733 $course['visible'] = $category->visible;
736 //set default value for completion
737 $courseconfig = get_config('moodlecourse');
738 if (completion_info::is_enabled_for_site()) {
739 if (!array_key_exists('enablecompletion', $course)) {
740 $course['enablecompletion'] = $courseconfig->enablecompletion;
742 } else {
743 $course['enablecompletion'] = 0;
746 $course['category'] = $course['categoryid'];
748 // Summary format.
749 $course['summaryformat'] = external_validate_format($course['summaryformat']);
751 if (!empty($course['courseformatoptions'])) {
752 foreach ($course['courseformatoptions'] as $option) {
753 $course[$option['name']] = $option['value'];
757 //Note: create_course() core function check shortname, idnumber, category
758 $course['id'] = create_course((object) $course)->id;
760 $resultcourses[] = array('id' => $course['id'], 'shortname' => $course['shortname']);
763 $transaction->allow_commit();
765 return $resultcourses;
769 * Returns description of method result value
771 * @return external_description
772 * @since Moodle 2.2
774 public static function create_courses_returns() {
775 return new external_multiple_structure(
776 new external_single_structure(
777 array(
778 'id' => new external_value(PARAM_INT, 'course id'),
779 'shortname' => new external_value(PARAM_TEXT, 'short name'),
786 * Update courses
788 * @return external_function_parameters
789 * @since Moodle 2.5
791 public static function update_courses_parameters() {
792 return new external_function_parameters(
793 array(
794 'courses' => new external_multiple_structure(
795 new external_single_structure(
796 array(
797 'id' => new external_value(PARAM_INT, 'ID of the course'),
798 'fullname' => new external_value(PARAM_TEXT, 'full name', VALUE_OPTIONAL),
799 'shortname' => new external_value(PARAM_TEXT, 'course short name', VALUE_OPTIONAL),
800 'categoryid' => new external_value(PARAM_INT, 'category id', VALUE_OPTIONAL),
801 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
802 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
803 'summaryformat' => new external_format_value('summary', VALUE_OPTIONAL),
804 'format' => new external_value(PARAM_PLUGIN,
805 'course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
806 'showgrades' => new external_value(PARAM_INT,
807 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
808 'newsitems' => new external_value(PARAM_INT,
809 'number of recent items appearing on the course page', VALUE_OPTIONAL),
810 'startdate' => new external_value(PARAM_INT,
811 'timestamp when the course start', VALUE_OPTIONAL),
812 'enddate' => new external_value(PARAM_INT,
813 'timestamp when the course end', VALUE_OPTIONAL),
814 'numsections' => new external_value(PARAM_INT,
815 '(deprecated, use courseformatoptions) number of weeks/topics', VALUE_OPTIONAL),
816 'maxbytes' => new external_value(PARAM_INT,
817 'largest size of file that can be uploaded into the course', VALUE_OPTIONAL),
818 'showreports' => new external_value(PARAM_INT,
819 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
820 'visible' => new external_value(PARAM_INT,
821 '1: available to student, 0:not available', VALUE_OPTIONAL),
822 'hiddensections' => new external_value(PARAM_INT,
823 '(deprecated, use courseformatoptions) How the hidden sections in the course are
824 displayed to students', VALUE_OPTIONAL),
825 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
826 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
827 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
828 'enablecompletion' => new external_value(PARAM_INT,
829 'Enabled, control via completion and activity settings. Disabled,
830 not shown in activity settings.', VALUE_OPTIONAL),
831 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
832 'lang' => new external_value(PARAM_SAFEDIR, 'forced course language', VALUE_OPTIONAL),
833 'forcetheme' => new external_value(PARAM_PLUGIN, 'name of the force theme', VALUE_OPTIONAL),
834 'courseformatoptions' => new external_multiple_structure(
835 new external_single_structure(
836 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
837 'value' => new external_value(PARAM_RAW, 'course format option value')
839 'additional options for particular course format', VALUE_OPTIONAL),
841 ), 'courses to update'
848 * Update courses
850 * @param array $courses
851 * @since Moodle 2.5
853 public static function update_courses($courses) {
854 global $CFG, $DB;
855 require_once($CFG->dirroot . "/course/lib.php");
856 $warnings = array();
858 $params = self::validate_parameters(self::update_courses_parameters(),
859 array('courses' => $courses));
861 $availablethemes = core_component::get_plugin_list('theme');
862 $availablelangs = get_string_manager()->get_list_of_translations();
864 foreach ($params['courses'] as $course) {
865 // Catch any exception while updating course and return as warning to user.
866 try {
867 // Ensure the current user is allowed to run this function.
868 $context = context_course::instance($course['id'], MUST_EXIST);
869 self::validate_context($context);
871 $oldcourse = course_get_format($course['id'])->get_course();
873 require_capability('moodle/course:update', $context);
875 // Check if user can change category.
876 if (array_key_exists('categoryid', $course) && ($oldcourse->category != $course['categoryid'])) {
877 require_capability('moodle/course:changecategory', $context);
878 $course['category'] = $course['categoryid'];
881 // Check if the user can change fullname.
882 if (array_key_exists('fullname', $course) && ($oldcourse->fullname != $course['fullname'])) {
883 require_capability('moodle/course:changefullname', $context);
886 // Check if the user can change shortname.
887 if (array_key_exists('shortname', $course) && ($oldcourse->shortname != $course['shortname'])) {
888 require_capability('moodle/course:changeshortname', $context);
891 // Check if the user can change the idnumber.
892 if (array_key_exists('idnumber', $course) && ($oldcourse->idnumber != $course['idnumber'])) {
893 require_capability('moodle/course:changeidnumber', $context);
896 // Check if user can change summary.
897 if (array_key_exists('summary', $course) && ($oldcourse->summary != $course['summary'])) {
898 require_capability('moodle/course:changesummary', $context);
901 // Summary format.
902 if (array_key_exists('summaryformat', $course) && ($oldcourse->summaryformat != $course['summaryformat'])) {
903 require_capability('moodle/course:changesummary', $context);
904 $course['summaryformat'] = external_validate_format($course['summaryformat']);
907 // Check if user can change visibility.
908 if (array_key_exists('visible', $course) && ($oldcourse->visible != $course['visible'])) {
909 require_capability('moodle/course:visibility', $context);
912 // Make sure lang is valid.
913 if (array_key_exists('lang', $course) && empty($availablelangs[$course['lang']])) {
914 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
917 // Make sure theme is valid.
918 if (array_key_exists('forcetheme', $course)) {
919 if (!empty($CFG->allowcoursethemes)) {
920 if (empty($availablethemes[$course['forcetheme']])) {
921 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
922 } else {
923 $course['theme'] = $course['forcetheme'];
928 // Make sure completion is enabled before setting it.
929 if (array_key_exists('enabledcompletion', $course) && !completion_info::is_enabled_for_site()) {
930 $course['enabledcompletion'] = 0;
933 // Make sure maxbytes are less then CFG->maxbytes.
934 if (array_key_exists('maxbytes', $course)) {
935 $course['maxbytes'] = get_max_upload_file_size($CFG->maxbytes, $course['maxbytes']);
938 if (!empty($course['courseformatoptions'])) {
939 foreach ($course['courseformatoptions'] as $option) {
940 if (isset($option['name']) && isset($option['value'])) {
941 $course[$option['name']] = $option['value'];
946 // Update course if user has all required capabilities.
947 update_course((object) $course);
948 } catch (Exception $e) {
949 $warning = array();
950 $warning['item'] = 'course';
951 $warning['itemid'] = $course['id'];
952 if ($e instanceof moodle_exception) {
953 $warning['warningcode'] = $e->errorcode;
954 } else {
955 $warning['warningcode'] = $e->getCode();
957 $warning['message'] = $e->getMessage();
958 $warnings[] = $warning;
962 $result = array();
963 $result['warnings'] = $warnings;
964 return $result;
968 * Returns description of method result value
970 * @return external_description
971 * @since Moodle 2.5
973 public static function update_courses_returns() {
974 return new external_single_structure(
975 array(
976 'warnings' => new external_warnings()
982 * Returns description of method parameters
984 * @return external_function_parameters
985 * @since Moodle 2.2
987 public static function delete_courses_parameters() {
988 return new external_function_parameters(
989 array(
990 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'course ID')),
996 * Delete courses
998 * @param array $courseids A list of course ids
999 * @since Moodle 2.2
1001 public static function delete_courses($courseids) {
1002 global $CFG, $DB;
1003 require_once($CFG->dirroot."/course/lib.php");
1005 // Parameter validation.
1006 $params = self::validate_parameters(self::delete_courses_parameters(), array('courseids'=>$courseids));
1008 $warnings = array();
1010 foreach ($params['courseids'] as $courseid) {
1011 $course = $DB->get_record('course', array('id' => $courseid));
1013 if ($course === false) {
1014 $warnings[] = array(
1015 'item' => 'course',
1016 'itemid' => $courseid,
1017 'warningcode' => 'unknowncourseidnumber',
1018 'message' => 'Unknown course ID ' . $courseid
1020 continue;
1023 // Check if the context is valid.
1024 $coursecontext = context_course::instance($course->id);
1025 self::validate_context($coursecontext);
1027 // Check if the current user has permission.
1028 if (!can_delete_course($courseid)) {
1029 $warnings[] = array(
1030 'item' => 'course',
1031 'itemid' => $courseid,
1032 'warningcode' => 'cannotdeletecourse',
1033 'message' => 'You do not have the permission to delete this course' . $courseid
1035 continue;
1038 if (delete_course($course, false) === false) {
1039 $warnings[] = array(
1040 'item' => 'course',
1041 'itemid' => $courseid,
1042 'warningcode' => 'cannotdeletecategorycourse',
1043 'message' => 'Course ' . $courseid . ' failed to be deleted'
1045 continue;
1049 fix_course_sortorder();
1051 return array('warnings' => $warnings);
1055 * Returns description of method result value
1057 * @return external_description
1058 * @since Moodle 2.2
1060 public static function delete_courses_returns() {
1061 return new external_single_structure(
1062 array(
1063 'warnings' => new external_warnings()
1069 * Returns description of method parameters
1071 * @return external_function_parameters
1072 * @since Moodle 2.3
1074 public static function duplicate_course_parameters() {
1075 return new external_function_parameters(
1076 array(
1077 'courseid' => new external_value(PARAM_INT, 'course to duplicate id'),
1078 'fullname' => new external_value(PARAM_TEXT, 'duplicated course full name'),
1079 'shortname' => new external_value(PARAM_TEXT, 'duplicated course short name'),
1080 'categoryid' => new external_value(PARAM_INT, 'duplicated course category parent'),
1081 'visible' => new external_value(PARAM_INT, 'duplicated course visible, default to yes', VALUE_DEFAULT, 1),
1082 'options' => new external_multiple_structure(
1083 new external_single_structure(
1084 array(
1085 'name' => new external_value(PARAM_ALPHAEXT, 'The backup option name:
1086 "activities" (int) Include course activites (default to 1 that is equal to yes),
1087 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1088 "filters" (int) Include course filters (default to 1 that is equal to yes),
1089 "users" (int) Include users (default to 0 that is equal to no),
1090 "enrolments" (int) Include enrolment methods (default to 1 - restore only with users),
1091 "role_assignments" (int) Include role assignments (default to 0 that is equal to no),
1092 "comments" (int) Include user comments (default to 0 that is equal to no),
1093 "userscompletion" (int) Include user course completion information (default to 0 that is equal to no),
1094 "logs" (int) Include course logs (default to 0 that is equal to no),
1095 "grade_histories" (int) Include histories (default to 0 that is equal to no)'
1097 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1100 ), VALUE_DEFAULT, array()
1107 * Duplicate a course
1109 * @param int $courseid
1110 * @param string $fullname Duplicated course fullname
1111 * @param string $shortname Duplicated course shortname
1112 * @param int $categoryid Duplicated course parent category id
1113 * @param int $visible Duplicated course availability
1114 * @param array $options List of backup options
1115 * @return array New course info
1116 * @since Moodle 2.3
1118 public static function duplicate_course($courseid, $fullname, $shortname, $categoryid, $visible = 1, $options = array()) {
1119 global $CFG, $USER, $DB;
1120 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1121 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1123 // Parameter validation.
1124 $params = self::validate_parameters(
1125 self::duplicate_course_parameters(),
1126 array(
1127 'courseid' => $courseid,
1128 'fullname' => $fullname,
1129 'shortname' => $shortname,
1130 'categoryid' => $categoryid,
1131 'visible' => $visible,
1132 'options' => $options
1136 // Context validation.
1138 if (! ($course = $DB->get_record('course', array('id'=>$params['courseid'])))) {
1139 throw new moodle_exception('invalidcourseid', 'error');
1142 // Category where duplicated course is going to be created.
1143 $categorycontext = context_coursecat::instance($params['categoryid']);
1144 self::validate_context($categorycontext);
1146 // Course to be duplicated.
1147 $coursecontext = context_course::instance($course->id);
1148 self::validate_context($coursecontext);
1150 $backupdefaults = array(
1151 'activities' => 1,
1152 'blocks' => 1,
1153 'filters' => 1,
1154 'users' => 0,
1155 'enrolments' => backup::ENROL_WITHUSERS,
1156 'role_assignments' => 0,
1157 'comments' => 0,
1158 'userscompletion' => 0,
1159 'logs' => 0,
1160 'grade_histories' => 0
1163 $backupsettings = array();
1164 // Check for backup and restore options.
1165 if (!empty($params['options'])) {
1166 foreach ($params['options'] as $option) {
1168 // Strict check for a correct value (allways 1 or 0, true or false).
1169 $value = clean_param($option['value'], PARAM_INT);
1171 if ($value !== 0 and $value !== 1) {
1172 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1175 if (!isset($backupdefaults[$option['name']])) {
1176 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1179 $backupsettings[$option['name']] = $value;
1183 // Capability checking.
1185 // The backup controller check for this currently, this may be redundant.
1186 require_capability('moodle/course:create', $categorycontext);
1187 require_capability('moodle/restore:restorecourse', $categorycontext);
1188 require_capability('moodle/backup:backupcourse', $coursecontext);
1190 if (!empty($backupsettings['users'])) {
1191 require_capability('moodle/backup:userinfo', $coursecontext);
1192 require_capability('moodle/restore:userinfo', $categorycontext);
1195 // Check if the shortname is used.
1196 if ($foundcourses = $DB->get_records('course', array('shortname'=>$shortname))) {
1197 foreach ($foundcourses as $foundcourse) {
1198 $foundcoursenames[] = $foundcourse->fullname;
1201 $foundcoursenamestring = implode(',', $foundcoursenames);
1202 throw new moodle_exception('shortnametaken', '', '', $foundcoursenamestring);
1205 // Backup the course.
1207 $bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE,
1208 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id);
1210 foreach ($backupsettings as $name => $value) {
1211 if ($setting = $bc->get_plan()->get_setting($name)) {
1212 $bc->get_plan()->get_setting($name)->set_value($value);
1216 $backupid = $bc->get_backupid();
1217 $backupbasepath = $bc->get_plan()->get_basepath();
1219 $bc->execute_plan();
1220 $results = $bc->get_results();
1221 $file = $results['backup_destination'];
1223 $bc->destroy();
1225 // Restore the backup immediately.
1227 // Check if we need to unzip the file because the backup temp dir does not contains backup files.
1228 if (!file_exists($backupbasepath . "/moodle_backup.xml")) {
1229 $file->extract_to_pathname(get_file_packer('application/vnd.moodle.backup'), $backupbasepath);
1232 // Create new course.
1233 $newcourseid = restore_dbops::create_new_course($params['fullname'], $params['shortname'], $params['categoryid']);
1235 $rc = new restore_controller($backupid, $newcourseid,
1236 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id, backup::TARGET_NEW_COURSE);
1238 foreach ($backupsettings as $name => $value) {
1239 $setting = $rc->get_plan()->get_setting($name);
1240 if ($setting->get_status() == backup_setting::NOT_LOCKED) {
1241 $setting->set_value($value);
1245 if (!$rc->execute_precheck()) {
1246 $precheckresults = $rc->get_precheck_results();
1247 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1248 if (empty($CFG->keeptempdirectoriesonbackup)) {
1249 fulldelete($backupbasepath);
1252 $errorinfo = '';
1254 foreach ($precheckresults['errors'] as $error) {
1255 $errorinfo .= $error;
1258 if (array_key_exists('warnings', $precheckresults)) {
1259 foreach ($precheckresults['warnings'] as $warning) {
1260 $errorinfo .= $warning;
1264 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1268 $rc->execute_plan();
1269 $rc->destroy();
1271 $course = $DB->get_record('course', array('id' => $newcourseid), '*', MUST_EXIST);
1272 $course->fullname = $params['fullname'];
1273 $course->shortname = $params['shortname'];
1274 $course->visible = $params['visible'];
1276 // Set shortname and fullname back.
1277 $DB->update_record('course', $course);
1279 if (empty($CFG->keeptempdirectoriesonbackup)) {
1280 fulldelete($backupbasepath);
1283 // Delete the course backup file created by this WebService. Originally located in the course backups area.
1284 $file->delete();
1286 return array('id' => $course->id, 'shortname' => $course->shortname);
1290 * Returns description of method result value
1292 * @return external_description
1293 * @since Moodle 2.3
1295 public static function duplicate_course_returns() {
1296 return new external_single_structure(
1297 array(
1298 'id' => new external_value(PARAM_INT, 'course id'),
1299 'shortname' => new external_value(PARAM_TEXT, 'short name'),
1305 * Returns description of method parameters for import_course
1307 * @return external_function_parameters
1308 * @since Moodle 2.4
1310 public static function import_course_parameters() {
1311 return new external_function_parameters(
1312 array(
1313 'importfrom' => new external_value(PARAM_INT, 'the id of the course we are importing from'),
1314 'importto' => new external_value(PARAM_INT, 'the id of the course we are importing to'),
1315 'deletecontent' => new external_value(PARAM_INT, 'whether to delete the course content where we are importing to (default to 0 = No)', VALUE_DEFAULT, 0),
1316 'options' => new external_multiple_structure(
1317 new external_single_structure(
1318 array(
1319 'name' => new external_value(PARAM_ALPHA, 'The backup option name:
1320 "activities" (int) Include course activites (default to 1 that is equal to yes),
1321 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1322 "filters" (int) Include course filters (default to 1 that is equal to yes)'
1324 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1327 ), VALUE_DEFAULT, array()
1334 * Imports a course
1336 * @param int $importfrom The id of the course we are importing from
1337 * @param int $importto The id of the course we are importing to
1338 * @param bool $deletecontent Whether to delete the course we are importing to content
1339 * @param array $options List of backup options
1340 * @return null
1341 * @since Moodle 2.4
1343 public static function import_course($importfrom, $importto, $deletecontent = 0, $options = array()) {
1344 global $CFG, $USER, $DB;
1345 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1346 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1348 // Parameter validation.
1349 $params = self::validate_parameters(
1350 self::import_course_parameters(),
1351 array(
1352 'importfrom' => $importfrom,
1353 'importto' => $importto,
1354 'deletecontent' => $deletecontent,
1355 'options' => $options
1359 if ($params['deletecontent'] !== 0 and $params['deletecontent'] !== 1) {
1360 throw new moodle_exception('invalidextparam', 'webservice', '', $params['deletecontent']);
1363 // Context validation.
1365 if (! ($importfrom = $DB->get_record('course', array('id'=>$params['importfrom'])))) {
1366 throw new moodle_exception('invalidcourseid', 'error');
1369 if (! ($importto = $DB->get_record('course', array('id'=>$params['importto'])))) {
1370 throw new moodle_exception('invalidcourseid', 'error');
1373 $importfromcontext = context_course::instance($importfrom->id);
1374 self::validate_context($importfromcontext);
1376 $importtocontext = context_course::instance($importto->id);
1377 self::validate_context($importtocontext);
1379 $backupdefaults = array(
1380 'activities' => 1,
1381 'blocks' => 1,
1382 'filters' => 1
1385 $backupsettings = array();
1387 // Check for backup and restore options.
1388 if (!empty($params['options'])) {
1389 foreach ($params['options'] as $option) {
1391 // Strict check for a correct value (allways 1 or 0, true or false).
1392 $value = clean_param($option['value'], PARAM_INT);
1394 if ($value !== 0 and $value !== 1) {
1395 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1398 if (!isset($backupdefaults[$option['name']])) {
1399 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1402 $backupsettings[$option['name']] = $value;
1406 // Capability checking.
1408 require_capability('moodle/backup:backuptargetimport', $importfromcontext);
1409 require_capability('moodle/restore:restoretargetimport', $importtocontext);
1411 $bc = new backup_controller(backup::TYPE_1COURSE, $importfrom->id, backup::FORMAT_MOODLE,
1412 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
1414 foreach ($backupsettings as $name => $value) {
1415 $bc->get_plan()->get_setting($name)->set_value($value);
1418 $backupid = $bc->get_backupid();
1419 $backupbasepath = $bc->get_plan()->get_basepath();
1421 $bc->execute_plan();
1422 $bc->destroy();
1424 // Restore the backup immediately.
1426 // Check if we must delete the contents of the destination course.
1427 if ($params['deletecontent']) {
1428 $restoretarget = backup::TARGET_EXISTING_DELETING;
1429 } else {
1430 $restoretarget = backup::TARGET_EXISTING_ADDING;
1433 $rc = new restore_controller($backupid, $importto->id,
1434 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, $restoretarget);
1436 foreach ($backupsettings as $name => $value) {
1437 $rc->get_plan()->get_setting($name)->set_value($value);
1440 if (!$rc->execute_precheck()) {
1441 $precheckresults = $rc->get_precheck_results();
1442 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1443 if (empty($CFG->keeptempdirectoriesonbackup)) {
1444 fulldelete($backupbasepath);
1447 $errorinfo = '';
1449 foreach ($precheckresults['errors'] as $error) {
1450 $errorinfo .= $error;
1453 if (array_key_exists('warnings', $precheckresults)) {
1454 foreach ($precheckresults['warnings'] as $warning) {
1455 $errorinfo .= $warning;
1459 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1461 } else {
1462 if ($restoretarget == backup::TARGET_EXISTING_DELETING) {
1463 restore_dbops::delete_course_content($importto->id);
1467 $rc->execute_plan();
1468 $rc->destroy();
1470 if (empty($CFG->keeptempdirectoriesonbackup)) {
1471 fulldelete($backupbasepath);
1474 return null;
1478 * Returns description of method result value
1480 * @return external_description
1481 * @since Moodle 2.4
1483 public static function import_course_returns() {
1484 return null;
1488 * Returns description of method parameters
1490 * @return external_function_parameters
1491 * @since Moodle 2.3
1493 public static function get_categories_parameters() {
1494 return new external_function_parameters(
1495 array(
1496 'criteria' => new external_multiple_structure(
1497 new external_single_structure(
1498 array(
1499 'key' => new external_value(PARAM_ALPHA,
1500 'The category column to search, expected keys (value format) are:'.
1501 '"id" (int) the category id,'.
1502 '"ids" (string) category ids separated by commas,'.
1503 '"name" (string) the category name,'.
1504 '"parent" (int) the parent category id,'.
1505 '"idnumber" (string) category idnumber'.
1506 ' - user must have \'moodle/category:manage\' to search on idnumber,'.
1507 '"visible" (int) whether the returned categories must be visible or hidden. If the key is not passed,
1508 then the function return all categories that the user can see.'.
1509 ' - user must have \'moodle/category:manage\' or \'moodle/category:viewhiddencategories\' to search on visible,'.
1510 '"theme" (string) only return the categories having this theme'.
1511 ' - user must have \'moodle/category:manage\' to search on theme'),
1512 'value' => new external_value(PARAM_RAW, 'the value to match')
1514 ), 'criteria', VALUE_DEFAULT, array()
1516 'addsubcategories' => new external_value(PARAM_BOOL, 'return the sub categories infos
1517 (1 - default) otherwise only the category info (0)', VALUE_DEFAULT, 1)
1523 * Get categories
1525 * @param array $criteria Criteria to match the results
1526 * @param booln $addsubcategories obtain only the category (false) or its subcategories (true - default)
1527 * @return array list of categories
1528 * @since Moodle 2.3
1530 public static function get_categories($criteria = array(), $addsubcategories = true) {
1531 global $CFG, $DB;
1532 require_once($CFG->dirroot . "/course/lib.php");
1534 // Validate parameters.
1535 $params = self::validate_parameters(self::get_categories_parameters(),
1536 array('criteria' => $criteria, 'addsubcategories' => $addsubcategories));
1538 // Retrieve the categories.
1539 $categories = array();
1540 if (!empty($params['criteria'])) {
1542 $conditions = array();
1543 $wheres = array();
1544 foreach ($params['criteria'] as $crit) {
1545 $key = trim($crit['key']);
1547 // Trying to avoid duplicate keys.
1548 if (!isset($conditions[$key])) {
1550 $context = context_system::instance();
1551 $value = null;
1552 switch ($key) {
1553 case 'id':
1554 $value = clean_param($crit['value'], PARAM_INT);
1555 $conditions[$key] = $value;
1556 $wheres[] = $key . " = :" . $key;
1557 break;
1559 case 'ids':
1560 $value = clean_param($crit['value'], PARAM_SEQUENCE);
1561 $ids = explode(',', $value);
1562 list($sqlids, $paramids) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED);
1563 $conditions = array_merge($conditions, $paramids);
1564 $wheres[] = 'id ' . $sqlids;
1565 break;
1567 case 'idnumber':
1568 if (has_capability('moodle/category:manage', $context)) {
1569 $value = clean_param($crit['value'], PARAM_RAW);
1570 $conditions[$key] = $value;
1571 $wheres[] = $key . " = :" . $key;
1572 } else {
1573 // We must throw an exception.
1574 // Otherwise the dev client would think no idnumber exists.
1575 throw new moodle_exception('criteriaerror',
1576 'webservice', '', null,
1577 'You don\'t have the permissions to search on the "idnumber" field.');
1579 break;
1581 case 'name':
1582 $value = clean_param($crit['value'], PARAM_TEXT);
1583 $conditions[$key] = $value;
1584 $wheres[] = $key . " = :" . $key;
1585 break;
1587 case 'parent':
1588 $value = clean_param($crit['value'], PARAM_INT);
1589 $conditions[$key] = $value;
1590 $wheres[] = $key . " = :" . $key;
1591 break;
1593 case 'visible':
1594 if (has_capability('moodle/category:manage', $context)
1595 or has_capability('moodle/category:viewhiddencategories',
1596 context_system::instance())) {
1597 $value = clean_param($crit['value'], PARAM_INT);
1598 $conditions[$key] = $value;
1599 $wheres[] = $key . " = :" . $key;
1600 } else {
1601 throw new moodle_exception('criteriaerror',
1602 'webservice', '', null,
1603 'You don\'t have the permissions to search on the "visible" field.');
1605 break;
1607 case 'theme':
1608 if (has_capability('moodle/category:manage', $context)) {
1609 $value = clean_param($crit['value'], PARAM_THEME);
1610 $conditions[$key] = $value;
1611 $wheres[] = $key . " = :" . $key;
1612 } else {
1613 throw new moodle_exception('criteriaerror',
1614 'webservice', '', null,
1615 'You don\'t have the permissions to search on the "theme" field.');
1617 break;
1619 default:
1620 throw new moodle_exception('criteriaerror',
1621 'webservice', '', null,
1622 'You can not search on this criteria: ' . $key);
1627 if (!empty($wheres)) {
1628 $wheres = implode(" AND ", $wheres);
1630 $categories = $DB->get_records_select('course_categories', $wheres, $conditions);
1632 // Retrieve its sub subcategories (all levels).
1633 if ($categories and !empty($params['addsubcategories'])) {
1634 $newcategories = array();
1636 // Check if we required visible/theme checks.
1637 $additionalselect = '';
1638 $additionalparams = array();
1639 if (isset($conditions['visible'])) {
1640 $additionalselect .= ' AND visible = :visible';
1641 $additionalparams['visible'] = $conditions['visible'];
1643 if (isset($conditions['theme'])) {
1644 $additionalselect .= ' AND theme= :theme';
1645 $additionalparams['theme'] = $conditions['theme'];
1648 foreach ($categories as $category) {
1649 $sqlselect = $DB->sql_like('path', ':path') . $additionalselect;
1650 $sqlparams = array('path' => $category->path.'/%') + $additionalparams; // It will NOT include the specified category.
1651 $subcategories = $DB->get_records_select('course_categories', $sqlselect, $sqlparams);
1652 $newcategories = $newcategories + $subcategories; // Both arrays have integer as keys.
1654 $categories = $categories + $newcategories;
1658 } else {
1659 // Retrieve all categories in the database.
1660 $categories = $DB->get_records('course_categories');
1663 // The not returned categories. key => category id, value => reason of exclusion.
1664 $excludedcats = array();
1666 // The returned categories.
1667 $categoriesinfo = array();
1669 // We need to sort the categories by path.
1670 // The parent cats need to be checked by the algo first.
1671 usort($categories, "core_course_external::compare_categories_by_path");
1673 foreach ($categories as $category) {
1675 // Check if the category is a child of an excluded category, if yes exclude it too (excluded => do not return).
1676 $parents = explode('/', $category->path);
1677 unset($parents[0]); // First key is always empty because path start with / => /1/2/4.
1678 foreach ($parents as $parentid) {
1679 // Note: when the parent exclusion was due to the context,
1680 // the sub category could still be returned.
1681 if (isset($excludedcats[$parentid]) and $excludedcats[$parentid] != 'context') {
1682 $excludedcats[$category->id] = 'parent';
1686 // Check the user can use the category context.
1687 $context = context_coursecat::instance($category->id);
1688 try {
1689 self::validate_context($context);
1690 } catch (Exception $e) {
1691 $excludedcats[$category->id] = 'context';
1693 // If it was the requested category then throw an exception.
1694 if (isset($params['categoryid']) && $category->id == $params['categoryid']) {
1695 $exceptionparam = new stdClass();
1696 $exceptionparam->message = $e->getMessage();
1697 $exceptionparam->catid = $category->id;
1698 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
1702 // Return the category information.
1703 if (!isset($excludedcats[$category->id])) {
1705 // Final check to see if the category is visible to the user.
1706 if ($category->visible
1707 or has_capability('moodle/category:viewhiddencategories', context_system::instance())
1708 or has_capability('moodle/category:manage', $context)) {
1710 $categoryinfo = array();
1711 $categoryinfo['id'] = $category->id;
1712 $categoryinfo['name'] = $category->name;
1713 list($categoryinfo['description'], $categoryinfo['descriptionformat']) =
1714 external_format_text($category->description, $category->descriptionformat,
1715 $context->id, 'coursecat', 'description', null);
1716 $categoryinfo['parent'] = $category->parent;
1717 $categoryinfo['sortorder'] = $category->sortorder;
1718 $categoryinfo['coursecount'] = $category->coursecount;
1719 $categoryinfo['depth'] = $category->depth;
1720 $categoryinfo['path'] = $category->path;
1722 // Some fields only returned for admin.
1723 if (has_capability('moodle/category:manage', $context)) {
1724 $categoryinfo['idnumber'] = $category->idnumber;
1725 $categoryinfo['visible'] = $category->visible;
1726 $categoryinfo['visibleold'] = $category->visibleold;
1727 $categoryinfo['timemodified'] = $category->timemodified;
1728 $categoryinfo['theme'] = $category->theme;
1731 $categoriesinfo[] = $categoryinfo;
1732 } else {
1733 $excludedcats[$category->id] = 'visibility';
1738 // Sorting the resulting array so it looks a bit better for the client developer.
1739 usort($categoriesinfo, "core_course_external::compare_categories_by_sortorder");
1741 return $categoriesinfo;
1745 * Sort categories array by path
1746 * private function: only used by get_categories
1748 * @param array $category1
1749 * @param array $category2
1750 * @return int result of strcmp
1751 * @since Moodle 2.3
1753 private static function compare_categories_by_path($category1, $category2) {
1754 return strcmp($category1->path, $category2->path);
1758 * Sort categories array by sortorder
1759 * private function: only used by get_categories
1761 * @param array $category1
1762 * @param array $category2
1763 * @return int result of strcmp
1764 * @since Moodle 2.3
1766 private static function compare_categories_by_sortorder($category1, $category2) {
1767 return strcmp($category1['sortorder'], $category2['sortorder']);
1771 * Returns description of method result value
1773 * @return external_description
1774 * @since Moodle 2.3
1776 public static function get_categories_returns() {
1777 return new external_multiple_structure(
1778 new external_single_structure(
1779 array(
1780 'id' => new external_value(PARAM_INT, 'category id'),
1781 'name' => new external_value(PARAM_TEXT, 'category name'),
1782 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1783 'description' => new external_value(PARAM_RAW, 'category description'),
1784 'descriptionformat' => new external_format_value('description'),
1785 'parent' => new external_value(PARAM_INT, 'parent category id'),
1786 'sortorder' => new external_value(PARAM_INT, 'category sorting order'),
1787 'coursecount' => new external_value(PARAM_INT, 'number of courses in this category'),
1788 'visible' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1789 'visibleold' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1790 'timemodified' => new external_value(PARAM_INT, 'timestamp', VALUE_OPTIONAL),
1791 'depth' => new external_value(PARAM_INT, 'category depth'),
1792 'path' => new external_value(PARAM_TEXT, 'category path'),
1793 'theme' => new external_value(PARAM_THEME, 'category theme', VALUE_OPTIONAL),
1794 ), 'List of categories'
1800 * Returns description of method parameters
1802 * @return external_function_parameters
1803 * @since Moodle 2.3
1805 public static function create_categories_parameters() {
1806 return new external_function_parameters(
1807 array(
1808 'categories' => new external_multiple_structure(
1809 new external_single_structure(
1810 array(
1811 'name' => new external_value(PARAM_TEXT, 'new category name'),
1812 'parent' => new external_value(PARAM_INT,
1813 'the parent category id inside which the new category will be created
1814 - set to 0 for a root category',
1815 VALUE_DEFAULT, 0),
1816 'idnumber' => new external_value(PARAM_RAW,
1817 'the new category idnumber', VALUE_OPTIONAL),
1818 'description' => new external_value(PARAM_RAW,
1819 'the new category description', VALUE_OPTIONAL),
1820 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
1821 'theme' => new external_value(PARAM_THEME,
1822 'the new category theme. This option must be enabled on moodle',
1823 VALUE_OPTIONAL),
1832 * Create categories
1834 * @param array $categories - see create_categories_parameters() for the array structure
1835 * @return array - see create_categories_returns() for the array structure
1836 * @since Moodle 2.3
1838 public static function create_categories($categories) {
1839 global $CFG, $DB;
1840 require_once($CFG->libdir . "/coursecatlib.php");
1842 $params = self::validate_parameters(self::create_categories_parameters(),
1843 array('categories' => $categories));
1845 $transaction = $DB->start_delegated_transaction();
1847 $createdcategories = array();
1848 foreach ($params['categories'] as $category) {
1849 if ($category['parent']) {
1850 if (!$DB->record_exists('course_categories', array('id' => $category['parent']))) {
1851 throw new moodle_exception('unknowcategory');
1853 $context = context_coursecat::instance($category['parent']);
1854 } else {
1855 $context = context_system::instance();
1857 self::validate_context($context);
1858 require_capability('moodle/category:manage', $context);
1860 // this will validate format and throw an exception if there are errors
1861 external_validate_format($category['descriptionformat']);
1863 $newcategory = coursecat::create($category);
1865 $createdcategories[] = array('id' => $newcategory->id, 'name' => $newcategory->name);
1868 $transaction->allow_commit();
1870 return $createdcategories;
1874 * Returns description of method parameters
1876 * @return external_function_parameters
1877 * @since Moodle 2.3
1879 public static function create_categories_returns() {
1880 return new external_multiple_structure(
1881 new external_single_structure(
1882 array(
1883 'id' => new external_value(PARAM_INT, 'new category id'),
1884 'name' => new external_value(PARAM_TEXT, 'new category name'),
1891 * Returns description of method parameters
1893 * @return external_function_parameters
1894 * @since Moodle 2.3
1896 public static function update_categories_parameters() {
1897 return new external_function_parameters(
1898 array(
1899 'categories' => new external_multiple_structure(
1900 new external_single_structure(
1901 array(
1902 'id' => new external_value(PARAM_INT, 'course id'),
1903 'name' => new external_value(PARAM_TEXT, 'category name', VALUE_OPTIONAL),
1904 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1905 'parent' => new external_value(PARAM_INT, 'parent category id', VALUE_OPTIONAL),
1906 'description' => new external_value(PARAM_RAW, 'category description', VALUE_OPTIONAL),
1907 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
1908 'theme' => new external_value(PARAM_THEME,
1909 'the category theme. This option must be enabled on moodle', VALUE_OPTIONAL),
1918 * Update categories
1920 * @param array $categories The list of categories to update
1921 * @return null
1922 * @since Moodle 2.3
1924 public static function update_categories($categories) {
1925 global $CFG, $DB;
1926 require_once($CFG->libdir . "/coursecatlib.php");
1928 // Validate parameters.
1929 $params = self::validate_parameters(self::update_categories_parameters(), array('categories' => $categories));
1931 $transaction = $DB->start_delegated_transaction();
1933 foreach ($params['categories'] as $cat) {
1934 $category = coursecat::get($cat['id']);
1936 $categorycontext = context_coursecat::instance($cat['id']);
1937 self::validate_context($categorycontext);
1938 require_capability('moodle/category:manage', $categorycontext);
1940 // this will throw an exception if descriptionformat is not valid
1941 external_validate_format($cat['descriptionformat']);
1943 $category->update($cat);
1946 $transaction->allow_commit();
1950 * Returns description of method result value
1952 * @return external_description
1953 * @since Moodle 2.3
1955 public static function update_categories_returns() {
1956 return null;
1960 * Returns description of method parameters
1962 * @return external_function_parameters
1963 * @since Moodle 2.3
1965 public static function delete_categories_parameters() {
1966 return new external_function_parameters(
1967 array(
1968 'categories' => new external_multiple_structure(
1969 new external_single_structure(
1970 array(
1971 'id' => new external_value(PARAM_INT, 'category id to delete'),
1972 'newparent' => new external_value(PARAM_INT,
1973 'the parent category to move the contents to, if specified', VALUE_OPTIONAL),
1974 'recursive' => new external_value(PARAM_BOOL, '1: recursively delete all contents inside this
1975 category, 0 (default): move contents to newparent or current parent category (except if parent is root)', VALUE_DEFAULT, 0)
1984 * Delete categories
1986 * @param array $categories A list of category ids
1987 * @return array
1988 * @since Moodle 2.3
1990 public static function delete_categories($categories) {
1991 global $CFG, $DB;
1992 require_once($CFG->dirroot . "/course/lib.php");
1993 require_once($CFG->libdir . "/coursecatlib.php");
1995 // Validate parameters.
1996 $params = self::validate_parameters(self::delete_categories_parameters(), array('categories' => $categories));
1998 $transaction = $DB->start_delegated_transaction();
2000 foreach ($params['categories'] as $category) {
2001 $deletecat = coursecat::get($category['id'], MUST_EXIST);
2002 $context = context_coursecat::instance($deletecat->id);
2003 require_capability('moodle/category:manage', $context);
2004 self::validate_context($context);
2005 self::validate_context(get_category_or_system_context($deletecat->parent));
2007 if ($category['recursive']) {
2008 // If recursive was specified, then we recursively delete the category's contents.
2009 if ($deletecat->can_delete_full()) {
2010 $deletecat->delete_full(false);
2011 } else {
2012 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2014 } else {
2015 // In this situation, we don't delete the category's contents, we either move it to newparent or parent.
2016 // If the parent is the root, moving is not supported (because a course must always be inside a category).
2017 // We must move to an existing category.
2018 if (!empty($category['newparent'])) {
2019 $newparentcat = coursecat::get($category['newparent']);
2020 } else {
2021 $newparentcat = coursecat::get($deletecat->parent);
2024 // This operation is not allowed. We must move contents to an existing category.
2025 if (!$newparentcat->id) {
2026 throw new moodle_exception('movecatcontentstoroot');
2029 self::validate_context(context_coursecat::instance($newparentcat->id));
2030 if ($deletecat->can_move_content_to($newparentcat->id)) {
2031 $deletecat->delete_move($newparentcat->id, false);
2032 } else {
2033 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2038 $transaction->allow_commit();
2042 * Returns description of method parameters
2044 * @return external_function_parameters
2045 * @since Moodle 2.3
2047 public static function delete_categories_returns() {
2048 return null;
2052 * Describes the parameters for delete_modules.
2054 * @return external_function_parameters
2055 * @since Moodle 2.5
2057 public static function delete_modules_parameters() {
2058 return new external_function_parameters (
2059 array(
2060 'cmids' => new external_multiple_structure(new external_value(PARAM_INT, 'course module ID',
2061 VALUE_REQUIRED, '', NULL_NOT_ALLOWED), 'Array of course module IDs'),
2067 * Deletes a list of provided module instances.
2069 * @param array $cmids the course module ids
2070 * @since Moodle 2.5
2072 public static function delete_modules($cmids) {
2073 global $CFG, $DB;
2075 // Require course file containing the course delete module function.
2076 require_once($CFG->dirroot . "/course/lib.php");
2078 // Clean the parameters.
2079 $params = self::validate_parameters(self::delete_modules_parameters(), array('cmids' => $cmids));
2081 // Keep track of the course ids we have performed a capability check on to avoid repeating.
2082 $arrcourseschecked = array();
2084 foreach ($params['cmids'] as $cmid) {
2085 // Get the course module.
2086 $cm = $DB->get_record('course_modules', array('id' => $cmid), '*', MUST_EXIST);
2088 // Check if we have not yet confirmed they have permission in this course.
2089 if (!in_array($cm->course, $arrcourseschecked)) {
2090 // Ensure the current user has required permission in this course.
2091 $context = context_course::instance($cm->course);
2092 self::validate_context($context);
2093 // Add to the array.
2094 $arrcourseschecked[] = $cm->course;
2097 // Ensure they can delete this module.
2098 $modcontext = context_module::instance($cm->id);
2099 require_capability('moodle/course:manageactivities', $modcontext);
2101 // Delete the module.
2102 course_delete_module($cm->id);
2107 * Describes the delete_modules return value.
2109 * @return external_single_structure
2110 * @since Moodle 2.5
2112 public static function delete_modules_returns() {
2113 return null;
2117 * Returns description of method parameters
2119 * @return external_function_parameters
2120 * @since Moodle 2.9
2122 public static function view_course_parameters() {
2123 return new external_function_parameters(
2124 array(
2125 'courseid' => new external_value(PARAM_INT, 'id of the course'),
2126 'sectionnumber' => new external_value(PARAM_INT, 'section number', VALUE_DEFAULT, 0)
2132 * Trigger the course viewed event.
2134 * @param int $courseid id of course
2135 * @param int $sectionnumber sectionnumber (0, 1, 2...)
2136 * @return array of warnings and status result
2137 * @since Moodle 2.9
2138 * @throws moodle_exception
2140 public static function view_course($courseid, $sectionnumber = 0) {
2141 global $CFG;
2142 require_once($CFG->dirroot . "/course/lib.php");
2144 $params = self::validate_parameters(self::view_course_parameters(),
2145 array(
2146 'courseid' => $courseid,
2147 'sectionnumber' => $sectionnumber
2150 $warnings = array();
2152 $course = get_course($params['courseid']);
2153 $context = context_course::instance($course->id);
2154 self::validate_context($context);
2156 if (!empty($params['sectionnumber'])) {
2158 // Get section details and check it exists.
2159 $modinfo = get_fast_modinfo($course);
2160 $coursesection = $modinfo->get_section_info($params['sectionnumber'], MUST_EXIST);
2162 // Check user is allowed to see it.
2163 if (!$coursesection->uservisible) {
2164 require_capability('moodle/course:viewhiddensections', $context);
2168 course_view($context, $params['sectionnumber']);
2170 $result = array();
2171 $result['status'] = true;
2172 $result['warnings'] = $warnings;
2173 return $result;
2177 * Returns description of method result value
2179 * @return external_description
2180 * @since Moodle 2.9
2182 public static function view_course_returns() {
2183 return new external_single_structure(
2184 array(
2185 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
2186 'warnings' => new external_warnings()
2192 * Returns description of method parameters
2194 * @return external_function_parameters
2195 * @since Moodle 3.0
2197 public static function search_courses_parameters() {
2198 return new external_function_parameters(
2199 array(
2200 'criterianame' => new external_value(PARAM_ALPHA, 'criteria name
2201 (search, modulelist (only admins), blocklist (only admins), tagid)'),
2202 'criteriavalue' => new external_value(PARAM_RAW, 'criteria value'),
2203 'page' => new external_value(PARAM_INT, 'page number (0 based)', VALUE_DEFAULT, 0),
2204 'perpage' => new external_value(PARAM_INT, 'items per page', VALUE_DEFAULT, 0),
2205 'requiredcapabilities' => new external_multiple_structure(
2206 new external_value(PARAM_CAPABILITY, 'Capability string used to filter courses by permission'),
2207 'Optional list of required capabilities (used to filter the list)', VALUE_DEFAULT, array()
2209 'limittoenrolled' => new external_value(PARAM_BOOL, 'limit to enrolled courses', VALUE_DEFAULT, 0),
2215 * Return the course information that is public (visible by every one)
2217 * @param course_in_list $course course in list object
2218 * @param stdClass $coursecontext course context object
2219 * @return array the course information
2220 * @since Moodle 3.2
2222 protected static function get_course_public_information(course_in_list $course, $coursecontext) {
2224 static $categoriescache = array();
2226 // Category information.
2227 if (!array_key_exists($course->category, $categoriescache)) {
2228 $categoriescache[$course->category] = coursecat::get($course->category, IGNORE_MISSING);
2230 $category = $categoriescache[$course->category];
2232 // Retrieve course overview used files.
2233 $files = array();
2234 foreach ($course->get_course_overviewfiles() as $file) {
2235 $fileurl = moodle_url::make_webservice_pluginfile_url($file->get_contextid(), $file->get_component(),
2236 $file->get_filearea(), null, $file->get_filepath(),
2237 $file->get_filename())->out(false);
2238 $files[] = array(
2239 'filename' => $file->get_filename(),
2240 'fileurl' => $fileurl,
2241 'filesize' => $file->get_filesize(),
2242 'filepath' => $file->get_filepath(),
2243 'mimetype' => $file->get_mimetype(),
2244 'timemodified' => $file->get_timemodified(),
2248 // Retrieve the course contacts,
2249 // we need here the users fullname since if we are not enrolled can be difficult to obtain them via other Web Services.
2250 $coursecontacts = array();
2251 foreach ($course->get_course_contacts() as $contact) {
2252 $coursecontacts[] = array(
2253 'id' => $contact['user']->id,
2254 'fullname' => $contact['username']
2258 // Allowed enrolment methods (maybe we can self-enrol).
2259 $enroltypes = array();
2260 $instances = enrol_get_instances($course->id, true);
2261 foreach ($instances as $instance) {
2262 $enroltypes[] = $instance->enrol;
2265 // Format summary.
2266 list($summary, $summaryformat) =
2267 external_format_text($course->summary, $course->summaryformat, $coursecontext->id, 'course', 'summary', null);
2269 $displayname = get_course_display_name_for_list($course);
2270 $coursereturns = array();
2271 $coursereturns['id'] = $course->id;
2272 $coursereturns['fullname'] = external_format_string($course->fullname, $coursecontext->id);
2273 $coursereturns['displayname'] = external_format_string($displayname, $coursecontext->id);
2274 $coursereturns['shortname'] = external_format_string($course->shortname, $coursecontext->id);
2275 $coursereturns['categoryid'] = $course->category;
2276 $coursereturns['categoryname'] = $category == null ? '' : $category->name;
2277 $coursereturns['summary'] = $summary;
2278 $coursereturns['summaryformat'] = $summaryformat;
2279 $coursereturns['summaryfiles'] = external_util::get_area_files($coursecontext->id, 'course', 'summary', false, false);
2280 $coursereturns['overviewfiles'] = $files;
2281 $coursereturns['contacts'] = $coursecontacts;
2282 $coursereturns['enrollmentmethods'] = $enroltypes;
2283 $coursereturns['sortorder'] = $course->sortorder;
2284 return $coursereturns;
2288 * Search courses following the specified criteria.
2290 * @param string $criterianame Criteria name (search, modulelist (only admins), blocklist (only admins), tagid)
2291 * @param string $criteriavalue Criteria value
2292 * @param int $page Page number (for pagination)
2293 * @param int $perpage Items per page
2294 * @param array $requiredcapabilities Optional list of required capabilities (used to filter the list).
2295 * @param int $limittoenrolled Limit to only enrolled courses
2296 * @return array of course objects and warnings
2297 * @since Moodle 3.0
2298 * @throws moodle_exception
2300 public static function search_courses($criterianame,
2301 $criteriavalue,
2302 $page=0,
2303 $perpage=0,
2304 $requiredcapabilities=array(),
2305 $limittoenrolled=0) {
2306 global $CFG;
2307 require_once($CFG->libdir . '/coursecatlib.php');
2309 $warnings = array();
2311 $parameters = array(
2312 'criterianame' => $criterianame,
2313 'criteriavalue' => $criteriavalue,
2314 'page' => $page,
2315 'perpage' => $perpage,
2316 'requiredcapabilities' => $requiredcapabilities
2318 $params = self::validate_parameters(self::search_courses_parameters(), $parameters);
2319 self::validate_context(context_system::instance());
2321 $allowedcriterianames = array('search', 'modulelist', 'blocklist', 'tagid');
2322 if (!in_array($params['criterianame'], $allowedcriterianames)) {
2323 throw new invalid_parameter_exception('Invalid value for criterianame parameter (value: '.$params['criterianame'].'),' .
2324 'allowed values are: '.implode(',', $allowedcriterianames));
2327 if ($params['criterianame'] == 'modulelist' or $params['criterianame'] == 'blocklist') {
2328 require_capability('moodle/site:config', context_system::instance());
2331 $paramtype = array(
2332 'search' => PARAM_RAW,
2333 'modulelist' => PARAM_PLUGIN,
2334 'blocklist' => PARAM_INT,
2335 'tagid' => PARAM_INT
2337 $params['criteriavalue'] = clean_param($params['criteriavalue'], $paramtype[$params['criterianame']]);
2339 // Prepare the search API options.
2340 $searchcriteria = array();
2341 $searchcriteria[$params['criterianame']] = $params['criteriavalue'];
2343 $options = array();
2344 if ($params['perpage'] != 0) {
2345 $offset = $params['page'] * $params['perpage'];
2346 $options = array('offset' => $offset, 'limit' => $params['perpage']);
2349 // Search the courses.
2350 $courses = coursecat::search_courses($searchcriteria, $options, $params['requiredcapabilities']);
2351 $totalcount = coursecat::search_courses_count($searchcriteria, $options, $params['requiredcapabilities']);
2353 if (!empty($limittoenrolled)) {
2354 // Get the courses where the current user has access.
2355 $enrolled = enrol_get_my_courses(array('id', 'cacherev'));
2358 $finalcourses = array();
2359 $categoriescache = array();
2361 foreach ($courses as $course) {
2362 if (!empty($limittoenrolled)) {
2363 // Filter out not enrolled courses.
2364 if (!isset($enrolled[$course->id])) {
2365 $totalcount--;
2366 continue;
2370 $coursecontext = context_course::instance($course->id);
2372 $finalcourses[] = self::get_course_public_information($course, $coursecontext);
2375 return array(
2376 'total' => $totalcount,
2377 'courses' => $finalcourses,
2378 'warnings' => $warnings
2383 * Returns a course structure definition
2385 * @param boolean $onlypublicdata set to true, to retrieve only fields viewable by anyone when the course is visible
2386 * @return array the course structure
2387 * @since Moodle 3.2
2389 protected static function get_course_structure($onlypublicdata = true) {
2390 $coursestructure = array(
2391 'id' => new external_value(PARAM_INT, 'course id'),
2392 'fullname' => new external_value(PARAM_TEXT, 'course full name'),
2393 'displayname' => new external_value(PARAM_TEXT, 'course display name'),
2394 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
2395 'categoryid' => new external_value(PARAM_INT, 'category id'),
2396 'categoryname' => new external_value(PARAM_TEXT, 'category name'),
2397 'sortorder' => new external_value(PARAM_INT, 'Sort order in the category', VALUE_OPTIONAL),
2398 'summary' => new external_value(PARAM_RAW, 'summary'),
2399 'summaryformat' => new external_format_value('summary'),
2400 'summaryfiles' => new external_files('summary files in the summary field', VALUE_OPTIONAL),
2401 'overviewfiles' => new external_files('additional overview files attached to this course'),
2402 'contacts' => new external_multiple_structure(
2403 new external_single_structure(
2404 array(
2405 'id' => new external_value(PARAM_INT, 'contact user id'),
2406 'fullname' => new external_value(PARAM_NOTAGS, 'contact user fullname'),
2409 'contact users'
2411 'enrollmentmethods' => new external_multiple_structure(
2412 new external_value(PARAM_PLUGIN, 'enrollment method'),
2413 'enrollment methods list'
2417 if (!$onlypublicdata) {
2418 $extra = array(
2419 'idnumber' => new external_value(PARAM_RAW, 'Id number', VALUE_OPTIONAL),
2420 'format' => new external_value(PARAM_PLUGIN, 'Course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
2421 'showgrades' => new external_value(PARAM_INT, '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
2422 'newsitems' => new external_value(PARAM_INT, 'Number of recent items appearing on the course page', VALUE_OPTIONAL),
2423 'startdate' => new external_value(PARAM_INT, 'Timestamp when the course start', VALUE_OPTIONAL),
2424 'enddate' => new external_value(PARAM_INT, 'Timestamp when the course end', VALUE_OPTIONAL),
2425 'maxbytes' => new external_value(PARAM_INT, 'Largest size of file that can be uploaded into', VALUE_OPTIONAL),
2426 'showreports' => new external_value(PARAM_INT, 'Are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
2427 'visible' => new external_value(PARAM_INT, '1: available to student, 0:not available', VALUE_OPTIONAL),
2428 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
2429 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
2430 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
2431 'enablecompletion' => new external_value(PARAM_INT, 'Completion enabled? 1: yes 0: no', VALUE_OPTIONAL),
2432 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
2433 'lang' => new external_value(PARAM_SAFEDIR, 'Forced course language', VALUE_OPTIONAL),
2434 'theme' => new external_value(PARAM_PLUGIN, 'Fame of the forced theme', VALUE_OPTIONAL),
2435 'marker' => new external_value(PARAM_INT, 'Current course marker', VALUE_OPTIONAL),
2436 'legacyfiles' => new external_value(PARAM_INT, 'If legacy files are enabled', VALUE_OPTIONAL),
2437 'calendartype' => new external_value(PARAM_PLUGIN, 'Calendar type', VALUE_OPTIONAL),
2438 'timecreated' => new external_value(PARAM_INT, 'Time when the course was created', VALUE_OPTIONAL),
2439 'timemodified' => new external_value(PARAM_INT, 'Last time the course was updated', VALUE_OPTIONAL),
2440 'requested' => new external_value(PARAM_INT, 'If is a requested course', VALUE_OPTIONAL),
2441 'cacherev' => new external_value(PARAM_INT, 'Cache revision number', VALUE_OPTIONAL),
2442 'filters' => new external_multiple_structure(
2443 new external_single_structure(
2444 array(
2445 'filter' => new external_value(PARAM_PLUGIN, 'Filter plugin name'),
2446 'localstate' => new external_value(PARAM_INT, 'Filter state: 1 for on, -1 for off, 0 if inherit'),
2447 'inheritedstate' => new external_value(PARAM_INT, '1 or 0 to use when localstate is set to inherit'),
2450 'Course filters', VALUE_OPTIONAL
2453 $coursestructure = array_merge($coursestructure, $extra);
2455 return new external_single_structure($coursestructure);
2459 * Returns description of method result value
2461 * @return external_description
2462 * @since Moodle 3.0
2464 public static function search_courses_returns() {
2465 return new external_single_structure(
2466 array(
2467 'total' => new external_value(PARAM_INT, 'total course count'),
2468 'courses' => new external_multiple_structure(self::get_course_structure(), 'course'),
2469 'warnings' => new external_warnings()
2475 * Returns description of method parameters
2477 * @return external_function_parameters
2478 * @since Moodle 3.0
2480 public static function get_course_module_parameters() {
2481 return new external_function_parameters(
2482 array(
2483 'cmid' => new external_value(PARAM_INT, 'The course module id')
2489 * Return information about a course module.
2491 * @param int $cmid the course module id
2492 * @return array of warnings and the course module
2493 * @since Moodle 3.0
2494 * @throws moodle_exception
2496 public static function get_course_module($cmid) {
2497 global $CFG, $DB;
2499 $params = self::validate_parameters(self::get_course_module_parameters(), array('cmid' => $cmid));
2500 $warnings = array();
2502 $cm = get_coursemodule_from_id(null, $params['cmid'], 0, true, MUST_EXIST);
2503 $context = context_module::instance($cm->id);
2504 self::validate_context($context);
2506 // If the user has permissions to manage the activity, return all the information.
2507 if (has_capability('moodle/course:manageactivities', $context)) {
2508 require_once($CFG->dirroot . '/course/modlib.php');
2509 require_once($CFG->libdir . '/gradelib.php');
2511 $info = $cm;
2512 // Get the extra information: grade, advanced grading and outcomes data.
2513 $course = get_course($cm->course);
2514 list($newcm, $newcontext, $module, $extrainfo, $cw) = get_moduleinfo_data($cm, $course);
2515 // Grades.
2516 $gradeinfo = array('grade', 'gradepass', 'gradecat');
2517 foreach ($gradeinfo as $gfield) {
2518 if (isset($extrainfo->{$gfield})) {
2519 $info->{$gfield} = $extrainfo->{$gfield};
2522 if (isset($extrainfo->grade) and $extrainfo->grade < 0) {
2523 $info->scale = $DB->get_field('scale', 'scale', array('id' => abs($extrainfo->grade)));
2525 // Advanced grading.
2526 if (isset($extrainfo->_advancedgradingdata)) {
2527 $info->advancedgrading = array();
2528 foreach ($extrainfo as $key => $val) {
2529 if (strpos($key, 'advancedgradingmethod_') === 0) {
2530 $info->advancedgrading[] = array(
2531 'area' => str_replace('advancedgradingmethod_', '', $key),
2532 'method' => $val
2537 // Outcomes.
2538 foreach ($extrainfo as $key => $val) {
2539 if (strpos($key, 'outcome_') === 0) {
2540 if (!isset($info->outcomes)) {
2541 $info->outcomes = array();
2543 $id = str_replace('outcome_', '', $key);
2544 $outcome = grade_outcome::fetch(array('id' => $id));
2545 $scaleitems = $outcome->load_scale();
2546 $info->outcomes[] = array(
2547 'id' => $id,
2548 'name' => external_format_string($outcome->get_name(), $context->id),
2549 'scale' => $scaleitems->scale
2553 } else {
2554 // Return information is safe to show to any user.
2555 $info = new stdClass();
2556 $info->id = $cm->id;
2557 $info->course = $cm->course;
2558 $info->module = $cm->module;
2559 $info->modname = $cm->modname;
2560 $info->instance = $cm->instance;
2561 $info->section = $cm->section;
2562 $info->sectionnum = $cm->sectionnum;
2563 $info->groupmode = $cm->groupmode;
2564 $info->groupingid = $cm->groupingid;
2565 $info->completion = $cm->completion;
2567 // Format name.
2568 $info->name = external_format_string($cm->name, $context->id);
2569 $result = array();
2570 $result['cm'] = $info;
2571 $result['warnings'] = $warnings;
2572 return $result;
2576 * Returns description of method result value
2578 * @return external_description
2579 * @since Moodle 3.0
2581 public static function get_course_module_returns() {
2582 return new external_single_structure(
2583 array(
2584 'cm' => new external_single_structure(
2585 array(
2586 'id' => new external_value(PARAM_INT, 'The course module id'),
2587 'course' => new external_value(PARAM_INT, 'The course id'),
2588 'module' => new external_value(PARAM_INT, 'The module type id'),
2589 'name' => new external_value(PARAM_RAW, 'The activity name'),
2590 'modname' => new external_value(PARAM_COMPONENT, 'The module component name (forum, assign, etc..)'),
2591 'instance' => new external_value(PARAM_INT, 'The activity instance id'),
2592 'section' => new external_value(PARAM_INT, 'The module section id'),
2593 'sectionnum' => new external_value(PARAM_INT, 'The module section number'),
2594 'groupmode' => new external_value(PARAM_INT, 'Group mode'),
2595 'groupingid' => new external_value(PARAM_INT, 'Grouping id'),
2596 'completion' => new external_value(PARAM_INT, 'If completion is enabled'),
2597 'idnumber' => new external_value(PARAM_RAW, 'Module id number', VALUE_OPTIONAL),
2598 'added' => new external_value(PARAM_INT, 'Time added', VALUE_OPTIONAL),
2599 'score' => new external_value(PARAM_INT, 'Score', VALUE_OPTIONAL),
2600 'indent' => new external_value(PARAM_INT, 'Indentation', VALUE_OPTIONAL),
2601 'visible' => new external_value(PARAM_INT, 'If visible', VALUE_OPTIONAL),
2602 'visibleoncoursepage' => new external_value(PARAM_INT, 'If visible on course page', VALUE_OPTIONAL),
2603 'visibleold' => new external_value(PARAM_INT, 'Visible old', VALUE_OPTIONAL),
2604 'completiongradeitemnumber' => new external_value(PARAM_INT, 'Completion grade item', VALUE_OPTIONAL),
2605 'completionview' => new external_value(PARAM_INT, 'Completion view setting', VALUE_OPTIONAL),
2606 'completionexpected' => new external_value(PARAM_INT, 'Completion time expected', VALUE_OPTIONAL),
2607 'showdescription' => new external_value(PARAM_INT, 'If the description is showed', VALUE_OPTIONAL),
2608 'availability' => new external_value(PARAM_RAW, 'Availability settings', VALUE_OPTIONAL),
2609 'grade' => new external_value(PARAM_FLOAT, 'Grade (max value or scale id)', VALUE_OPTIONAL),
2610 'scale' => new external_value(PARAM_TEXT, 'Scale items (if used)', VALUE_OPTIONAL),
2611 'gradepass' => new external_value(PARAM_RAW, 'Grade to pass (float)', VALUE_OPTIONAL),
2612 'gradecat' => new external_value(PARAM_INT, 'Grade category', VALUE_OPTIONAL),
2613 'advancedgrading' => new external_multiple_structure(
2614 new external_single_structure(
2615 array(
2616 'area' => new external_value(PARAM_AREA, 'Gradable area name'),
2617 'method' => new external_value(PARAM_COMPONENT, 'Grading method'),
2620 'Advanced grading settings', VALUE_OPTIONAL
2622 'outcomes' => new external_multiple_structure(
2623 new external_single_structure(
2624 array(
2625 'id' => new external_value(PARAM_ALPHANUMEXT, 'Outcome id'),
2626 'name' => new external_value(PARAM_TEXT, 'Outcome full name'),
2627 'scale' => new external_value(PARAM_TEXT, 'Scale items')
2630 'Outcomes information', VALUE_OPTIONAL
2634 'warnings' => new external_warnings()
2640 * Returns description of method parameters
2642 * @return external_function_parameters
2643 * @since Moodle 3.0
2645 public static function get_course_module_by_instance_parameters() {
2646 return new external_function_parameters(
2647 array(
2648 'module' => new external_value(PARAM_COMPONENT, 'The module name'),
2649 'instance' => new external_value(PARAM_INT, 'The module instance id')
2655 * Return information about a course module.
2657 * @param string $module the module name
2658 * @param int $instance the activity instance id
2659 * @return array of warnings and the course module
2660 * @since Moodle 3.0
2661 * @throws moodle_exception
2663 public static function get_course_module_by_instance($module, $instance) {
2665 $params = self::validate_parameters(self::get_course_module_by_instance_parameters(),
2666 array(
2667 'module' => $module,
2668 'instance' => $instance,
2671 $warnings = array();
2672 $cm = get_coursemodule_from_instance($params['module'], $params['instance'], 0, false, MUST_EXIST);
2674 return self::get_course_module($cm->id);
2678 * Returns description of method result value
2680 * @return external_description
2681 * @since Moodle 3.0
2683 public static function get_course_module_by_instance_returns() {
2684 return self::get_course_module_returns();
2688 * Returns description of method parameters
2690 * @deprecated since 3.3
2691 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
2692 * @return external_function_parameters
2693 * @since Moodle 3.2
2695 public static function get_activities_overview_parameters() {
2696 return new external_function_parameters(
2697 array(
2698 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2704 * Return activities overview for the given courses.
2706 * @deprecated since 3.3
2707 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
2708 * @param array $courseids a list of course ids
2709 * @return array of warnings and the activities overview
2710 * @since Moodle 3.2
2711 * @throws moodle_exception
2713 public static function get_activities_overview($courseids) {
2714 global $USER;
2716 // Parameter validation.
2717 $params = self::validate_parameters(self::get_activities_overview_parameters(), array('courseids' => $courseids));
2718 $courseoverviews = array();
2720 list($courses, $warnings) = external_util::validate_courses($params['courseids']);
2722 if (!empty($courses)) {
2723 // Add lastaccess to each course (required by print_overview function).
2724 // We need the complete user data, the ws server does not load a complete one.
2725 $user = get_complete_user_data('id', $USER->id);
2726 foreach ($courses as $course) {
2727 if (isset($user->lastcourseaccess[$course->id])) {
2728 $course->lastaccess = $user->lastcourseaccess[$course->id];
2729 } else {
2730 $course->lastaccess = 0;
2734 $overviews = array();
2735 if ($modules = get_plugin_list_with_function('mod', 'print_overview')) {
2736 foreach ($modules as $fname) {
2737 $fname($courses, $overviews);
2741 // Format output.
2742 foreach ($overviews as $courseid => $modules) {
2743 $courseoverviews[$courseid]['id'] = $courseid;
2744 $courseoverviews[$courseid]['overviews'] = array();
2746 foreach ($modules as $modname => $overviewtext) {
2747 $courseoverviews[$courseid]['overviews'][] = array(
2748 'module' => $modname,
2749 'overviewtext' => $overviewtext // This text doesn't need formatting.
2755 $result = array(
2756 'courses' => $courseoverviews,
2757 'warnings' => $warnings
2759 return $result;
2763 * Returns description of method result value
2765 * @deprecated since 3.3
2766 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
2767 * @return external_description
2768 * @since Moodle 3.2
2770 public static function get_activities_overview_returns() {
2771 return new external_single_structure(
2772 array(
2773 'courses' => new external_multiple_structure(
2774 new external_single_structure(
2775 array(
2776 'id' => new external_value(PARAM_INT, 'Course id'),
2777 'overviews' => new external_multiple_structure(
2778 new external_single_structure(
2779 array(
2780 'module' => new external_value(PARAM_PLUGIN, 'Module name'),
2781 'overviewtext' => new external_value(PARAM_RAW, 'Overview text'),
2786 ), 'List of courses'
2788 'warnings' => new external_warnings()
2794 * Marking the method as deprecated.
2796 * @return bool
2798 public static function get_activities_overview_is_deprecated() {
2799 return true;
2803 * Returns description of method parameters
2805 * @return external_function_parameters
2806 * @since Moodle 3.2
2808 public static function get_user_navigation_options_parameters() {
2809 return new external_function_parameters(
2810 array(
2811 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2817 * Return a list of navigation options in a set of courses that are avaialable or not for the current user.
2819 * @param array $courseids a list of course ids
2820 * @return array of warnings and the options availability
2821 * @since Moodle 3.2
2822 * @throws moodle_exception
2824 public static function get_user_navigation_options($courseids) {
2825 global $CFG;
2826 require_once($CFG->dirroot . '/course/lib.php');
2828 // Parameter validation.
2829 $params = self::validate_parameters(self::get_user_navigation_options_parameters(), array('courseids' => $courseids));
2830 $courseoptions = array();
2832 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
2834 if (!empty($courses)) {
2835 foreach ($courses as $course) {
2836 // Fix the context for the frontpage.
2837 if ($course->id == SITEID) {
2838 $course->context = context_system::instance();
2840 $navoptions = course_get_user_navigation_options($course->context, $course);
2841 $options = array();
2842 foreach ($navoptions as $name => $available) {
2843 $options[] = array(
2844 'name' => $name,
2845 'available' => $available,
2849 $courseoptions[] = array(
2850 'id' => $course->id,
2851 'options' => $options
2856 $result = array(
2857 'courses' => $courseoptions,
2858 'warnings' => $warnings
2860 return $result;
2864 * Returns description of method result value
2866 * @return external_description
2867 * @since Moodle 3.2
2869 public static function get_user_navigation_options_returns() {
2870 return new external_single_structure(
2871 array(
2872 'courses' => new external_multiple_structure(
2873 new external_single_structure(
2874 array(
2875 'id' => new external_value(PARAM_INT, 'Course id'),
2876 'options' => new external_multiple_structure(
2877 new external_single_structure(
2878 array(
2879 'name' => new external_value(PARAM_ALPHANUMEXT, 'Option name'),
2880 'available' => new external_value(PARAM_BOOL, 'Whether the option is available or not'),
2885 ), 'List of courses'
2887 'warnings' => new external_warnings()
2893 * Returns description of method parameters
2895 * @return external_function_parameters
2896 * @since Moodle 3.2
2898 public static function get_user_administration_options_parameters() {
2899 return new external_function_parameters(
2900 array(
2901 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2907 * Return a list of administration options in a set of courses that are available or not for the current user.
2909 * @param array $courseids a list of course ids
2910 * @return array of warnings and the options availability
2911 * @since Moodle 3.2
2912 * @throws moodle_exception
2914 public static function get_user_administration_options($courseids) {
2915 global $CFG;
2916 require_once($CFG->dirroot . '/course/lib.php');
2918 // Parameter validation.
2919 $params = self::validate_parameters(self::get_user_administration_options_parameters(), array('courseids' => $courseids));
2920 $courseoptions = array();
2922 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
2924 if (!empty($courses)) {
2925 foreach ($courses as $course) {
2926 $adminoptions = course_get_user_administration_options($course, $course->context);
2927 $options = array();
2928 foreach ($adminoptions as $name => $available) {
2929 $options[] = array(
2930 'name' => $name,
2931 'available' => $available,
2935 $courseoptions[] = array(
2936 'id' => $course->id,
2937 'options' => $options
2942 $result = array(
2943 'courses' => $courseoptions,
2944 'warnings' => $warnings
2946 return $result;
2950 * Returns description of method result value
2952 * @return external_description
2953 * @since Moodle 3.2
2955 public static function get_user_administration_options_returns() {
2956 return self::get_user_navigation_options_returns();
2960 * Returns description of method parameters
2962 * @return external_function_parameters
2963 * @since Moodle 3.2
2965 public static function get_courses_by_field_parameters() {
2966 return new external_function_parameters(
2967 array(
2968 'field' => new external_value(PARAM_ALPHA, 'The field to search can be left empty for all courses or:
2969 id: course id
2970 ids: comma separated course ids
2971 shortname: course short name
2972 idnumber: course id number
2973 category: category id the course belongs to
2974 ', VALUE_DEFAULT, ''),
2975 'value' => new external_value(PARAM_RAW, 'The value to match', VALUE_DEFAULT, '')
2982 * Get courses matching a specific field (id/s, shortname, idnumber, category)
2984 * @param string $field field name to search, or empty for all courses
2985 * @param string $value value to search
2986 * @return array list of courses and warnings
2987 * @throws invalid_parameter_exception
2988 * @since Moodle 3.2
2990 public static function get_courses_by_field($field = '', $value = '') {
2991 global $DB, $CFG;
2992 require_once($CFG->libdir . '/coursecatlib.php');
2993 require_once($CFG->libdir . '/filterlib.php');
2995 $params = self::validate_parameters(self::get_courses_by_field_parameters(),
2996 array(
2997 'field' => $field,
2998 'value' => $value,
3001 $warnings = array();
3003 if (empty($params['field'])) {
3004 $courses = $DB->get_records('course', null, 'id ASC');
3005 } else {
3006 switch ($params['field']) {
3007 case 'id':
3008 case 'category':
3009 $value = clean_param($params['value'], PARAM_INT);
3010 break;
3011 case 'ids':
3012 $value = clean_param($params['value'], PARAM_SEQUENCE);
3013 break;
3014 case 'shortname':
3015 $value = clean_param($params['value'], PARAM_TEXT);
3016 break;
3017 case 'idnumber':
3018 $value = clean_param($params['value'], PARAM_RAW);
3019 break;
3020 default:
3021 throw new invalid_parameter_exception('Invalid field name');
3024 if ($params['field'] === 'ids') {
3025 $courses = $DB->get_records_list('course', 'id', explode(',', $value), 'id ASC');
3026 } else {
3027 $courses = $DB->get_records('course', array($params['field'] => $value), 'id ASC');
3031 $coursesdata = array();
3032 foreach ($courses as $course) {
3033 $context = context_course::instance($course->id);
3034 $canupdatecourse = has_capability('moodle/course:update', $context);
3035 $canviewhiddencourses = has_capability('moodle/course:viewhiddencourses', $context);
3037 // Check if the course is visible in the site for the user.
3038 if (!$course->visible and !$canviewhiddencourses and !$canupdatecourse) {
3039 continue;
3041 // Get the public course information, even if we are not enrolled.
3042 $courseinlist = new course_in_list($course);
3043 $coursesdata[$course->id] = self::get_course_public_information($courseinlist, $context);
3045 // Now, check if we have access to the course.
3046 try {
3047 self::validate_context($context);
3048 } catch (Exception $e) {
3049 continue;
3051 // Return information for any user that can access the course.
3052 $coursefields = array('format', 'showgrades', 'newsitems', 'startdate', 'enddate', 'maxbytes', 'showreports', 'visible',
3053 'groupmode', 'groupmodeforce', 'defaultgroupingid', 'enablecompletion', 'completionnotify', 'lang', 'theme',
3054 'marker');
3056 // Course filters.
3057 $coursesdata[$course->id]['filters'] = filter_get_available_in_context($context);
3059 // Information for managers only.
3060 if ($canupdatecourse) {
3061 $managerfields = array('idnumber', 'legacyfiles', 'calendartype', 'timecreated', 'timemodified', 'requested',
3062 'cacherev');
3063 $coursefields = array_merge($coursefields, $managerfields);
3066 // Populate fields.
3067 foreach ($coursefields as $field) {
3068 $coursesdata[$course->id][$field] = $course->{$field};
3072 return array(
3073 'courses' => $coursesdata,
3074 'warnings' => $warnings
3079 * Returns description of method result value
3081 * @return external_description
3082 * @since Moodle 3.2
3084 public static function get_courses_by_field_returns() {
3085 // Course structure, including not only public viewable fields.
3086 return new external_single_structure(
3087 array(
3088 'courses' => new external_multiple_structure(self::get_course_structure(false), 'Course'),
3089 'warnings' => new external_warnings()
3095 * Returns description of method parameters
3097 * @return external_function_parameters
3098 * @since Moodle 3.2
3100 public static function check_updates_parameters() {
3101 return new external_function_parameters(
3102 array(
3103 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3104 'tocheck' => new external_multiple_structure(
3105 new external_single_structure(
3106 array(
3107 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level for the file location.
3108 Only module supported right now.'),
3109 'id' => new external_value(PARAM_INT, 'Context instance id'),
3110 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3113 'Instances to check'
3115 'filter' => new external_multiple_structure(
3116 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3117 gradeitems, outcomes'),
3118 'Check only for updates in these areas', VALUE_DEFAULT, array()
3125 * Check if there is updates affecting the user for the given course and contexts.
3126 * Right now only modules are supported.
3127 * This WS calls mod_check_updates_since for each module to check if there is any update the user should we aware of.
3129 * @param int $courseid the list of modules to check
3130 * @param array $tocheck the list of modules to check
3131 * @param array $filter check only for updates in these areas
3132 * @return array list of updates and warnings
3133 * @throws moodle_exception
3134 * @since Moodle 3.2
3136 public static function check_updates($courseid, $tocheck, $filter = array()) {
3137 global $CFG, $DB;
3139 $params = self::validate_parameters(
3140 self::check_updates_parameters(),
3141 array(
3142 'courseid' => $courseid,
3143 'tocheck' => $tocheck,
3144 'filter' => $filter,
3148 $course = get_course($params['courseid']);
3149 $context = context_course::instance($course->id);
3150 self::validate_context($context);
3152 list($instances, $warnings) = course_check_updates($course, $params['tocheck'], $filter);
3154 $instancesformatted = array();
3155 foreach ($instances as $instance) {
3156 $updates = array();
3157 foreach ($instance['updates'] as $name => $data) {
3158 if (empty($data->updated)) {
3159 continue;
3161 $updatedata = array(
3162 'name' => $name,
3164 if (!empty($data->timeupdated)) {
3165 $updatedata['timeupdated'] = $data->timeupdated;
3167 if (!empty($data->itemids)) {
3168 $updatedata['itemids'] = $data->itemids;
3170 $updates[] = $updatedata;
3172 if (!empty($updates)) {
3173 $instancesformatted[] = array(
3174 'contextlevel' => $instance['contextlevel'],
3175 'id' => $instance['id'],
3176 'updates' => $updates
3181 return array(
3182 'instances' => $instancesformatted,
3183 'warnings' => $warnings
3188 * Returns description of method result value
3190 * @return external_description
3191 * @since Moodle 3.2
3193 public static function check_updates_returns() {
3194 return new external_single_structure(
3195 array(
3196 'instances' => new external_multiple_structure(
3197 new external_single_structure(
3198 array(
3199 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level'),
3200 'id' => new external_value(PARAM_INT, 'Instance id'),
3201 'updates' => new external_multiple_structure(
3202 new external_single_structure(
3203 array(
3204 'name' => new external_value(PARAM_ALPHANUMEXT, 'Name of the area updated.'),
3205 'timeupdated' => new external_value(PARAM_INT, 'Last time was updated', VALUE_OPTIONAL),
3206 'itemids' => new external_multiple_structure(
3207 new external_value(PARAM_INT, 'Instance id'),
3208 'The ids of the items updated',
3209 VALUE_OPTIONAL
3217 'warnings' => new external_warnings()
3223 * Returns description of method parameters
3225 * @return external_function_parameters
3226 * @since Moodle 3.3
3228 public static function get_updates_since_parameters() {
3229 return new external_function_parameters(
3230 array(
3231 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3232 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3233 'filter' => new external_multiple_structure(
3234 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3235 gradeitems, outcomes'),
3236 'Check only for updates in these areas', VALUE_DEFAULT, array()
3243 * Check if there are updates affecting the user for the given course since the given time stamp.
3245 * This function is a wrapper of self::check_updates for retrieving all the updates since a given time for all the activities.
3247 * @param int $courseid the list of modules to check
3248 * @param int $since check updates since this time stamp
3249 * @param array $filter check only for updates in these areas
3250 * @return array list of updates and warnings
3251 * @throws moodle_exception
3252 * @since Moodle 3.3
3254 public static function get_updates_since($courseid, $since, $filter = array()) {
3255 global $CFG, $DB;
3257 $params = self::validate_parameters(
3258 self::get_updates_since_parameters(),
3259 array(
3260 'courseid' => $courseid,
3261 'since' => $since,
3262 'filter' => $filter,
3266 $course = get_course($params['courseid']);
3267 $modinfo = get_fast_modinfo($course);
3268 $tocheck = array();
3270 // Retrieve all the visible course modules for the current user.
3271 $cms = $modinfo->get_cms();
3272 foreach ($cms as $cm) {
3273 if (!$cm->uservisible) {
3274 continue;
3276 $tocheck[] = array(
3277 'id' => $cm->id,
3278 'contextlevel' => 'module',
3279 'since' => $params['since'],
3283 return self::check_updates($course->id, $tocheck, $params['filter']);
3287 * Returns description of method result value
3289 * @return external_description
3290 * @since Moodle 3.3
3292 public static function get_updates_since_returns() {
3293 return self::check_updates_returns();
3297 * Parameters for function edit_module()
3299 * @since Moodle 3.3
3300 * @return external_function_parameters
3302 public static function edit_module_parameters() {
3303 return new external_function_parameters(
3304 array(
3305 'action' => new external_value(PARAM_ALPHA,
3306 'action: hide, show, stealth, duplicate, delete, moveleft, moveright, group...', VALUE_REQUIRED),
3307 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3308 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3313 * Performs one of the edit module actions and return new html for AJAX
3315 * Returns html to replace the current module html with, for example:
3316 * - empty string for "delete" action,
3317 * - two modules html for "duplicate" action
3318 * - updated module html for everything else
3320 * Throws exception if operation is not permitted/possible
3322 * @since Moodle 3.3
3323 * @param string $action
3324 * @param int $id
3325 * @param null|int $sectionreturn
3326 * @return string
3328 public static function edit_module($action, $id, $sectionreturn = null) {
3329 global $PAGE, $DB;
3330 // Validate and normalize parameters.
3331 $params = self::validate_parameters(self::edit_module_parameters(),
3332 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3333 $action = $params['action'];
3334 $id = $params['id'];
3335 $sectionreturn = $params['sectionreturn'];
3337 list($course, $cm) = get_course_and_cm_from_cmid($id);
3338 $modcontext = context_module::instance($cm->id);
3339 $coursecontext = context_course::instance($course->id);
3340 self::validate_context($modcontext);
3341 $courserenderer = $PAGE->get_renderer('core', 'course');
3342 $completioninfo = new completion_info($course);
3344 switch($action) {
3345 case 'hide':
3346 case 'show':
3347 case 'stealth':
3348 require_capability('moodle/course:activityvisibility', $modcontext);
3349 $visible = ($action === 'hide') ? 0 : 1;
3350 $visibleoncoursepage = ($action === 'stealth') ? 0 : 1;
3351 set_coursemodule_visible($id, $visible, $visibleoncoursepage);
3352 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3353 break;
3354 case 'duplicate':
3355 require_capability('moodle/course:manageactivities', $coursecontext);
3356 require_capability('moodle/backup:backuptargetimport', $coursecontext);
3357 require_capability('moodle/restore:restoretargetimport', $coursecontext);
3358 if (!course_allowed_module($course, $cm->modname)) {
3359 throw new moodle_exception('No permission to create that activity');
3361 if ($newcm = duplicate_module($course, $cm)) {
3362 $cm = get_fast_modinfo($course)->get_cm($id);
3363 $newcm = get_fast_modinfo($course)->get_cm($newcm->id);
3364 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn) .
3365 $courserenderer->course_section_cm_list_item($course, $completioninfo, $newcm, $sectionreturn);
3367 break;
3368 case 'groupsseparate':
3369 case 'groupsvisible':
3370 case 'groupsnone':
3371 require_capability('moodle/course:manageactivities', $modcontext);
3372 if ($action === 'groupsseparate') {
3373 $newgroupmode = SEPARATEGROUPS;
3374 } else if ($action === 'groupsvisible') {
3375 $newgroupmode = VISIBLEGROUPS;
3376 } else {
3377 $newgroupmode = NOGROUPS;
3379 if (set_coursemodule_groupmode($cm->id, $newgroupmode)) {
3380 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3382 break;
3383 case 'moveleft':
3384 case 'moveright':
3385 require_capability('moodle/course:manageactivities', $modcontext);
3386 $indent = $cm->indent + (($action === 'moveright') ? 1 : -1);
3387 if ($cm->indent >= 0) {
3388 $DB->update_record('course_modules', array('id' => $cm->id, 'indent' => $indent));
3389 rebuild_course_cache($cm->course);
3391 break;
3392 case 'delete':
3393 require_capability('moodle/course:manageactivities', $modcontext);
3394 course_delete_module($cm->id, true);
3395 return '';
3396 default:
3397 throw new coding_exception('Unrecognised action');
3400 $cm = get_fast_modinfo($course)->get_cm($id);
3401 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn);
3405 * Return structure for edit_module()
3407 * @since Moodle 3.3
3408 * @return external_description
3410 public static function edit_module_returns() {
3411 return new external_value(PARAM_RAW, 'html to replace the current module with');
3415 * Parameters for function get_module()
3417 * @since Moodle 3.3
3418 * @return external_function_parameters
3420 public static function get_module_parameters() {
3421 return new external_function_parameters(
3422 array(
3423 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3424 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3429 * Returns html for displaying one activity module on course page
3431 * @since Moodle 3.3
3432 * @param int $id
3433 * @param null|int $sectionreturn
3434 * @return string
3436 public static function get_module($id, $sectionreturn = null) {
3437 global $PAGE;
3438 // Validate and normalize parameters.
3439 $params = self::validate_parameters(self::get_module_parameters(),
3440 array('id' => $id, 'sectionreturn' => $sectionreturn));
3441 $id = $params['id'];
3442 $sectionreturn = $params['sectionreturn'];
3444 // Validate access to the course (note, this is html for the course view page, we don't validate access to the module).
3445 list($course, $cm) = get_course_and_cm_from_cmid($id);
3446 self::validate_context(context_course::instance($course->id));
3448 $courserenderer = $PAGE->get_renderer('core', 'course');
3449 $completioninfo = new completion_info($course);
3450 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn);
3454 * Return structure for edit_module()
3456 * @since Moodle 3.3
3457 * @return external_description
3459 public static function get_module_returns() {
3460 return new external_value(PARAM_RAW, 'html to replace the current module with');
3464 * Parameters for function edit_section()
3466 * @since Moodle 3.3
3467 * @return external_function_parameters
3469 public static function edit_section_parameters() {
3470 return new external_function_parameters(
3471 array(
3472 'action' => new external_value(PARAM_ALPHA, 'action: hide, show, stealth, setmarker, removemarker', VALUE_REQUIRED),
3473 'id' => new external_value(PARAM_INT, 'course section id', VALUE_REQUIRED),
3474 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3479 * Performs one of the edit section actions
3481 * @since Moodle 3.3
3482 * @param string $action
3483 * @param int $id section id
3484 * @param int $sectionreturn section to return to
3485 * @return string
3487 public static function edit_section($action, $id, $sectionreturn) {
3488 global $DB;
3489 // Validate and normalize parameters.
3490 $params = self::validate_parameters(self::edit_section_parameters(),
3491 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3492 $action = $params['action'];
3493 $id = $params['id'];
3494 $sr = $params['sectionreturn'];
3496 $section = $DB->get_record('course_sections', array('id' => $id), '*', MUST_EXIST);
3497 $coursecontext = context_course::instance($section->course);
3498 self::validate_context($coursecontext);
3500 $rv = course_get_format($section->course)->section_action($section, $action, $sectionreturn);
3501 if ($rv) {
3502 return json_encode($rv);
3503 } else {
3504 return null;
3509 * Return structure for edit_section()
3511 * @since Moodle 3.3
3512 * @return external_description
3514 public static function edit_section_returns() {
3515 return new external_value(PARAM_RAW, 'Additional data for javascript (JSON-encoded string)');