Merge branch 'MDL-61691-33' of https://github.com/snake/moodle into MOODLE_33_STABLE
[moodle.git] / course / externallib.php
blob2542a4dc61249d6ae6d275d61acc9595eb0474c7
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * External course API
21 * @package core_course
22 * @category external
23 * @copyright 2009 Petr Skodak
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') || die;
29 require_once("$CFG->libdir/externallib.php");
31 /**
32 * Course external functions
34 * @package core_course
35 * @category external
36 * @copyright 2011 Jerome Mouneyrac
37 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 * @since Moodle 2.2
40 class core_course_external extends external_api {
42 /**
43 * Returns description of method parameters
45 * @return external_function_parameters
46 * @since Moodle 2.9 Options available
47 * @since Moodle 2.2
49 public static function get_course_contents_parameters() {
50 return new external_function_parameters(
51 array('courseid' => new external_value(PARAM_INT, 'course id'),
52 'options' => new external_multiple_structure (
53 new external_single_structure(
54 array(
55 'name' => new external_value(PARAM_ALPHANUM,
56 'The expected keys (value format) are:
57 excludemodules (bool) Do not return modules, return only the sections structure
58 excludecontents (bool) Do not return module contents (i.e: files inside a resource)
59 sectionid (int) Return only this section
60 sectionnumber (int) Return only this section with number (order)
61 cmid (int) Return only this module information (among the whole sections structure)
62 modname (string) Return only modules with this name "label, forum, etc..."
63 modid (int) Return only the module with this id (to be used with modname'),
64 'value' => new external_value(PARAM_RAW, 'the value of the option,
65 this param is personaly validated in the external function.')
67 ), 'Options, used since Moodle 2.9', VALUE_DEFAULT, array())
72 /**
73 * Get course contents
75 * @param int $courseid course id
76 * @param array $options Options for filtering the results, used since Moodle 2.9
77 * @return array
78 * @since Moodle 2.9 Options available
79 * @since Moodle 2.2
81 public static function get_course_contents($courseid, $options = array()) {
82 global $CFG, $DB;
83 require_once($CFG->dirroot . "/course/lib.php");
85 //validate parameter
86 $params = self::validate_parameters(self::get_course_contents_parameters(),
87 array('courseid' => $courseid, 'options' => $options));
89 $filters = array();
90 if (!empty($params['options'])) {
92 foreach ($params['options'] as $option) {
93 $name = trim($option['name']);
94 // Avoid duplicated options.
95 if (!isset($filters[$name])) {
96 switch ($name) {
97 case 'excludemodules':
98 case 'excludecontents':
99 $value = clean_param($option['value'], PARAM_BOOL);
100 $filters[$name] = $value;
101 break;
102 case 'sectionid':
103 case 'sectionnumber':
104 case 'cmid':
105 case 'modid':
106 $value = clean_param($option['value'], PARAM_INT);
107 if (is_numeric($value)) {
108 $filters[$name] = $value;
109 } else {
110 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
112 break;
113 case 'modname':
114 $value = clean_param($option['value'], PARAM_PLUGIN);
115 if ($value) {
116 $filters[$name] = $value;
117 } else {
118 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
120 break;
121 default:
122 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
128 //retrieve the course
129 $course = $DB->get_record('course', array('id' => $params['courseid']), '*', MUST_EXIST);
131 if ($course->id != SITEID) {
132 // Check course format exist.
133 if (!file_exists($CFG->dirroot . '/course/format/' . $course->format . '/lib.php')) {
134 throw new moodle_exception('cannotgetcoursecontents', 'webservice', '', null,
135 get_string('courseformatnotfound', 'error', $course->format));
136 } else {
137 require_once($CFG->dirroot . '/course/format/' . $course->format . '/lib.php');
141 // now security checks
142 $context = context_course::instance($course->id, IGNORE_MISSING);
143 try {
144 self::validate_context($context);
145 } catch (Exception $e) {
146 $exceptionparam = new stdClass();
147 $exceptionparam->message = $e->getMessage();
148 $exceptionparam->courseid = $course->id;
149 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
152 $canupdatecourse = has_capability('moodle/course:update', $context);
154 //create return value
155 $coursecontents = array();
157 if ($canupdatecourse or $course->visible
158 or has_capability('moodle/course:viewhiddencourses', $context)) {
160 //retrieve sections
161 $modinfo = get_fast_modinfo($course);
162 $sections = $modinfo->get_section_info_all();
163 $coursenumsections = course_get_format($course)->get_last_section_number();
165 //for each sections (first displayed to last displayed)
166 $modinfosections = $modinfo->get_sections();
167 foreach ($sections as $key => $section) {
169 // Show the section if the user is permitted to access it, OR if it's not available
170 // but there is some available info text which explains the reason & should display.
171 $showsection = $section->uservisible ||
172 ($section->visible && !$section->available &&
173 !empty($section->availableinfo));
175 if (!$showsection) {
176 continue;
179 // This becomes true when we are filtering and we found the value to filter with.
180 $sectionfound = false;
182 // Filter by section id.
183 if (!empty($filters['sectionid'])) {
184 if ($section->id != $filters['sectionid']) {
185 continue;
186 } else {
187 $sectionfound = true;
191 // Filter by section number. Note that 0 is a valid section number.
192 if (isset($filters['sectionnumber'])) {
193 if ($key != $filters['sectionnumber']) {
194 continue;
195 } else {
196 $sectionfound = true;
200 // reset $sectioncontents
201 $sectionvalues = array();
202 $sectionvalues['id'] = $section->id;
203 $sectionvalues['name'] = get_section_name($course, $section);
204 $sectionvalues['visible'] = $section->visible;
206 $options = (object) array('noclean' => true);
207 list($sectionvalues['summary'], $sectionvalues['summaryformat']) =
208 external_format_text($section->summary, $section->summaryformat,
209 $context->id, 'course', 'section', $section->id, $options);
210 $sectionvalues['section'] = $section->section;
211 $sectionvalues['hiddenbynumsections'] = $section->section > $coursenumsections ? 1 : 0;
212 $sectionvalues['uservisible'] = $section->uservisible;
213 if (!empty($section->availableinfo)) {
214 $sectionvalues['availabilityinfo'] = \core_availability\info::format_info($section->availableinfo, $course);
217 $sectioncontents = array();
219 // For each module of the section (if it is visible).
220 if ($section->uservisible and empty($filters['excludemodules']) and !empty($modinfosections[$section->section])) {
221 foreach ($modinfosections[$section->section] as $cmid) {
222 $cm = $modinfo->cms[$cmid];
224 // Stop here if the module is not visible to the user on the course main page:
225 // The user can't access the module and the user can't view the module on the course page.
226 if (!$cm->uservisible && !$cm->is_visible_on_course_page()) {
227 continue;
230 // This becomes true when we are filtering and we found the value to filter with.
231 $modfound = false;
233 // Filter by cmid.
234 if (!empty($filters['cmid'])) {
235 if ($cmid != $filters['cmid']) {
236 continue;
237 } else {
238 $modfound = true;
242 // Filter by module name and id.
243 if (!empty($filters['modname'])) {
244 if ($cm->modname != $filters['modname']) {
245 continue;
246 } else if (!empty($filters['modid'])) {
247 if ($cm->instance != $filters['modid']) {
248 continue;
249 } else {
250 // Note that if we are only filtering by modname we don't break the loop.
251 $modfound = true;
256 $module = array();
258 $modcontext = context_module::instance($cm->id);
260 //common info (for people being able to see the module or availability dates)
261 $module['id'] = $cm->id;
262 $module['name'] = external_format_string($cm->name, $modcontext->id);
263 $module['instance'] = $cm->instance;
264 $module['modname'] = $cm->modname;
265 $module['modplural'] = $cm->modplural;
266 $module['modicon'] = $cm->get_icon_url()->out(false);
267 $module['indent'] = $cm->indent;
269 if (!empty($cm->showdescription) or $cm->modname == 'label') {
270 // We want to use the external format. However from reading get_formatted_content(), $cm->content format is always FORMAT_HTML.
271 $options = array('noclean' => true);
272 list($module['description'], $descriptionformat) = external_format_text($cm->content,
273 FORMAT_HTML, $modcontext->id, $cm->modname, 'intro', $cm->id, $options);
276 //url of the module
277 $url = $cm->url;
278 if ($url) { //labels don't have url
279 $module['url'] = $url->out(false);
282 $canviewhidden = has_capability('moodle/course:viewhiddenactivities',
283 context_module::instance($cm->id));
284 //user that can view hidden module should know about the visibility
285 $module['visible'] = $cm->visible;
286 $module['visibleoncoursepage'] = $cm->visibleoncoursepage;
287 $module['uservisible'] = $cm->uservisible;
288 if (!empty($cm->availableinfo)) {
289 $module['availabilityinfo'] = \core_availability\info::format_info($cm->availableinfo, $course);
292 // Availability date (also send to user who can see hidden module).
293 if ($CFG->enableavailability && ($canviewhidden || $canupdatecourse)) {
294 $module['availability'] = $cm->availability;
297 // Return contents only if the user can access to the module.
298 if ($cm->uservisible) {
299 $baseurl = 'webservice/pluginfile.php';
301 // Call $modulename_export_contents (each module callback take care about checking the capabilities).
302 require_once($CFG->dirroot . '/mod/' . $cm->modname . '/lib.php');
303 $getcontentfunction = $cm->modname.'_export_contents';
304 if (function_exists($getcontentfunction)) {
305 if (empty($filters['excludecontents']) and $contents = $getcontentfunction($cm, $baseurl)) {
306 $module['contents'] = $contents;
307 } else {
308 $module['contents'] = array();
313 //assign result to $sectioncontents
314 $sectioncontents[] = $module;
316 // If we just did a filtering, break the loop.
317 if ($modfound) {
318 break;
323 $sectionvalues['modules'] = $sectioncontents;
325 // assign result to $coursecontents
326 $coursecontents[] = $sectionvalues;
328 // Break the loop if we are filtering.
329 if ($sectionfound) {
330 break;
334 return $coursecontents;
338 * Returns description of method result value
340 * @return external_description
341 * @since Moodle 2.2
343 public static function get_course_contents_returns() {
344 return new external_multiple_structure(
345 new external_single_structure(
346 array(
347 'id' => new external_value(PARAM_INT, 'Section ID'),
348 'name' => new external_value(PARAM_TEXT, 'Section name'),
349 'visible' => new external_value(PARAM_INT, 'is the section visible', VALUE_OPTIONAL),
350 'summary' => new external_value(PARAM_RAW, 'Section description'),
351 'summaryformat' => new external_format_value('summary'),
352 'section' => new external_value(PARAM_INT, 'Section number inside the course', VALUE_OPTIONAL),
353 'hiddenbynumsections' => new external_value(PARAM_INT, 'Whether is a section hidden in the course format',
354 VALUE_OPTIONAL),
355 'uservisible' => new external_value(PARAM_BOOL, 'Is the section visible for the user?', VALUE_OPTIONAL),
356 'availabilityinfo' => new external_value(PARAM_RAW, 'Availability information.', VALUE_OPTIONAL),
357 'modules' => new external_multiple_structure(
358 new external_single_structure(
359 array(
360 'id' => new external_value(PARAM_INT, 'activity id'),
361 'url' => new external_value(PARAM_URL, 'activity url', VALUE_OPTIONAL),
362 'name' => new external_value(PARAM_RAW, 'activity module name'),
363 'instance' => new external_value(PARAM_INT, 'instance id', VALUE_OPTIONAL),
364 'description' => new external_value(PARAM_RAW, 'activity description', VALUE_OPTIONAL),
365 'visible' => new external_value(PARAM_INT, 'is the module visible', VALUE_OPTIONAL),
366 'uservisible' => new external_value(PARAM_BOOL, 'Is the module visible for the user?',
367 VALUE_OPTIONAL),
368 'availabilityinfo' => new external_value(PARAM_RAW, 'Availability information.',
369 VALUE_OPTIONAL),
370 'visibleoncoursepage' => new external_value(PARAM_INT, 'is the module visible on course page',
371 VALUE_OPTIONAL),
372 'modicon' => new external_value(PARAM_URL, 'activity icon url'),
373 'modname' => new external_value(PARAM_PLUGIN, 'activity module type'),
374 'modplural' => new external_value(PARAM_TEXT, 'activity module plural name'),
375 'availability' => new external_value(PARAM_RAW, 'module availability settings', VALUE_OPTIONAL),
376 'indent' => new external_value(PARAM_INT, 'number of identation in the site'),
377 'contents' => new external_multiple_structure(
378 new external_single_structure(
379 array(
380 // content info
381 'type'=> new external_value(PARAM_TEXT, 'a file or a folder or external link'),
382 'filename'=> new external_value(PARAM_FILE, 'filename'),
383 'filepath'=> new external_value(PARAM_PATH, 'filepath'),
384 'filesize'=> new external_value(PARAM_INT, 'filesize'),
385 'fileurl' => new external_value(PARAM_URL, 'downloadable file url', VALUE_OPTIONAL),
386 'content' => new external_value(PARAM_RAW, 'Raw content, will be used when type is content', VALUE_OPTIONAL),
387 'timecreated' => new external_value(PARAM_INT, 'Time created'),
388 'timemodified' => new external_value(PARAM_INT, 'Time modified'),
389 'sortorder' => new external_value(PARAM_INT, 'Content sort order'),
390 'mimetype' => new external_value(PARAM_RAW, 'File mime type.', VALUE_OPTIONAL),
391 'isexternalfile' => new external_value(PARAM_BOOL, 'Whether is an external file.',
392 VALUE_OPTIONAL),
393 'repositorytype' => new external_value(PARAM_PLUGIN, 'The repository type for external files.',
394 VALUE_OPTIONAL),
396 // copyright related info
397 'userid' => new external_value(PARAM_INT, 'User who added this content to moodle'),
398 'author' => new external_value(PARAM_TEXT, 'Content owner'),
399 'license' => new external_value(PARAM_TEXT, 'Content license'),
401 ), VALUE_DEFAULT, array()
404 ), 'list of module'
412 * Returns description of method parameters
414 * @return external_function_parameters
415 * @since Moodle 2.3
417 public static function get_courses_parameters() {
418 return new external_function_parameters(
419 array('options' => new external_single_structure(
420 array('ids' => new external_multiple_structure(
421 new external_value(PARAM_INT, 'Course id')
422 , 'List of course id. If empty return all courses
423 except front page course.',
424 VALUE_OPTIONAL)
425 ), 'options - operator OR is used', VALUE_DEFAULT, array())
431 * Get courses
433 * @param array $options It contains an array (list of ids)
434 * @return array
435 * @since Moodle 2.2
437 public static function get_courses($options = array()) {
438 global $CFG, $DB;
439 require_once($CFG->dirroot . "/course/lib.php");
441 //validate parameter
442 $params = self::validate_parameters(self::get_courses_parameters(),
443 array('options' => $options));
445 //retrieve courses
446 if (!array_key_exists('ids', $params['options'])
447 or empty($params['options']['ids'])) {
448 $courses = $DB->get_records('course');
449 } else {
450 $courses = $DB->get_records_list('course', 'id', $params['options']['ids']);
453 //create return value
454 $coursesinfo = array();
455 foreach ($courses as $course) {
457 // now security checks
458 $context = context_course::instance($course->id, IGNORE_MISSING);
459 $courseformatoptions = course_get_format($course)->get_format_options();
460 try {
461 self::validate_context($context);
462 } catch (Exception $e) {
463 $exceptionparam = new stdClass();
464 $exceptionparam->message = $e->getMessage();
465 $exceptionparam->courseid = $course->id;
466 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
468 if ($course->id != SITEID) {
469 require_capability('moodle/course:view', $context);
472 $courseinfo = array();
473 $courseinfo['id'] = $course->id;
474 $courseinfo['fullname'] = external_format_string($course->fullname, $context->id);
475 $courseinfo['shortname'] = external_format_string($course->shortname, $context->id);
476 $courseinfo['displayname'] = external_format_string(get_course_display_name_for_list($course), $context->id);
477 $courseinfo['categoryid'] = $course->category;
478 list($courseinfo['summary'], $courseinfo['summaryformat']) =
479 external_format_text($course->summary, $course->summaryformat, $context->id, 'course', 'summary', 0);
480 $courseinfo['format'] = $course->format;
481 $courseinfo['startdate'] = $course->startdate;
482 $courseinfo['enddate'] = $course->enddate;
483 if (array_key_exists('numsections', $courseformatoptions)) {
484 // For backward-compartibility
485 $courseinfo['numsections'] = $courseformatoptions['numsections'];
488 //some field should be returned only if the user has update permission
489 $courseadmin = has_capability('moodle/course:update', $context);
490 if ($courseadmin) {
491 $courseinfo['categorysortorder'] = $course->sortorder;
492 $courseinfo['idnumber'] = $course->idnumber;
493 $courseinfo['showgrades'] = $course->showgrades;
494 $courseinfo['showreports'] = $course->showreports;
495 $courseinfo['newsitems'] = $course->newsitems;
496 $courseinfo['visible'] = $course->visible;
497 $courseinfo['maxbytes'] = $course->maxbytes;
498 if (array_key_exists('hiddensections', $courseformatoptions)) {
499 // For backward-compartibility
500 $courseinfo['hiddensections'] = $courseformatoptions['hiddensections'];
502 // Return numsections for backward-compatibility with clients who expect it.
503 $courseinfo['numsections'] = course_get_format($course)->get_last_section_number();
504 $courseinfo['groupmode'] = $course->groupmode;
505 $courseinfo['groupmodeforce'] = $course->groupmodeforce;
506 $courseinfo['defaultgroupingid'] = $course->defaultgroupingid;
507 $courseinfo['lang'] = clean_param($course->lang, PARAM_LANG);
508 $courseinfo['timecreated'] = $course->timecreated;
509 $courseinfo['timemodified'] = $course->timemodified;
510 $courseinfo['forcetheme'] = clean_param($course->theme, PARAM_THEME);
511 $courseinfo['enablecompletion'] = $course->enablecompletion;
512 $courseinfo['completionnotify'] = $course->completionnotify;
513 $courseinfo['courseformatoptions'] = array();
514 foreach ($courseformatoptions as $key => $value) {
515 $courseinfo['courseformatoptions'][] = array(
516 'name' => $key,
517 'value' => $value
522 if ($courseadmin or $course->visible
523 or has_capability('moodle/course:viewhiddencourses', $context)) {
524 $coursesinfo[] = $courseinfo;
528 return $coursesinfo;
532 * Returns description of method result value
534 * @return external_description
535 * @since Moodle 2.2
537 public static function get_courses_returns() {
538 return new external_multiple_structure(
539 new external_single_structure(
540 array(
541 'id' => new external_value(PARAM_INT, 'course id'),
542 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
543 'categoryid' => new external_value(PARAM_INT, 'category id'),
544 'categorysortorder' => new external_value(PARAM_INT,
545 'sort order into the category', VALUE_OPTIONAL),
546 'fullname' => new external_value(PARAM_TEXT, 'full name'),
547 'displayname' => new external_value(PARAM_TEXT, 'course display name'),
548 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
549 'summary' => new external_value(PARAM_RAW, 'summary'),
550 'summaryformat' => new external_format_value('summary'),
551 'format' => new external_value(PARAM_PLUGIN,
552 'course format: weeks, topics, social, site,..'),
553 'showgrades' => new external_value(PARAM_INT,
554 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
555 'newsitems' => new external_value(PARAM_INT,
556 'number of recent items appearing on the course page', VALUE_OPTIONAL),
557 'startdate' => new external_value(PARAM_INT,
558 'timestamp when the course start'),
559 'enddate' => new external_value(PARAM_INT,
560 'timestamp when the course end'),
561 'numsections' => new external_value(PARAM_INT,
562 '(deprecated, use courseformatoptions) number of weeks/topics',
563 VALUE_OPTIONAL),
564 'maxbytes' => new external_value(PARAM_INT,
565 'largest size of file that can be uploaded into the course',
566 VALUE_OPTIONAL),
567 'showreports' => new external_value(PARAM_INT,
568 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
569 'visible' => new external_value(PARAM_INT,
570 '1: available to student, 0:not available', VALUE_OPTIONAL),
571 'hiddensections' => new external_value(PARAM_INT,
572 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
573 VALUE_OPTIONAL),
574 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
575 VALUE_OPTIONAL),
576 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
577 VALUE_OPTIONAL),
578 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
579 VALUE_OPTIONAL),
580 'timecreated' => new external_value(PARAM_INT,
581 'timestamp when the course have been created', VALUE_OPTIONAL),
582 'timemodified' => new external_value(PARAM_INT,
583 'timestamp when the course have been modified', VALUE_OPTIONAL),
584 'enablecompletion' => new external_value(PARAM_INT,
585 'Enabled, control via completion and activity settings. Disbaled,
586 not shown in activity settings.',
587 VALUE_OPTIONAL),
588 'completionnotify' => new external_value(PARAM_INT,
589 '1: yes 0: no', VALUE_OPTIONAL),
590 'lang' => new external_value(PARAM_SAFEDIR,
591 'forced course language', VALUE_OPTIONAL),
592 'forcetheme' => new external_value(PARAM_PLUGIN,
593 'name of the force theme', VALUE_OPTIONAL),
594 'courseformatoptions' => new external_multiple_structure(
595 new external_single_structure(
596 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
597 'value' => new external_value(PARAM_RAW, 'course format option value')
599 'additional options for particular course format', VALUE_OPTIONAL
601 ), 'course'
607 * Returns description of method parameters
609 * @return external_function_parameters
610 * @since Moodle 2.2
612 public static function create_courses_parameters() {
613 $courseconfig = get_config('moodlecourse'); //needed for many default values
614 return new external_function_parameters(
615 array(
616 'courses' => new external_multiple_structure(
617 new external_single_structure(
618 array(
619 'fullname' => new external_value(PARAM_TEXT, 'full name'),
620 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
621 'categoryid' => new external_value(PARAM_INT, 'category id'),
622 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
623 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
624 'summaryformat' => new external_format_value('summary', VALUE_DEFAULT),
625 'format' => new external_value(PARAM_PLUGIN,
626 'course format: weeks, topics, social, site,..',
627 VALUE_DEFAULT, $courseconfig->format),
628 'showgrades' => new external_value(PARAM_INT,
629 '1 if grades are shown, otherwise 0', VALUE_DEFAULT,
630 $courseconfig->showgrades),
631 'newsitems' => new external_value(PARAM_INT,
632 'number of recent items appearing on the course page',
633 VALUE_DEFAULT, $courseconfig->newsitems),
634 'startdate' => new external_value(PARAM_INT,
635 'timestamp when the course start', VALUE_OPTIONAL),
636 'enddate' => new external_value(PARAM_INT,
637 'timestamp when the course end', VALUE_OPTIONAL),
638 'numsections' => new external_value(PARAM_INT,
639 '(deprecated, use courseformatoptions) number of weeks/topics',
640 VALUE_OPTIONAL),
641 'maxbytes' => new external_value(PARAM_INT,
642 'largest size of file that can be uploaded into the course',
643 VALUE_DEFAULT, $courseconfig->maxbytes),
644 'showreports' => new external_value(PARAM_INT,
645 'are activity report shown (yes = 1, no =0)', VALUE_DEFAULT,
646 $courseconfig->showreports),
647 'visible' => new external_value(PARAM_INT,
648 '1: available to student, 0:not available', VALUE_OPTIONAL),
649 'hiddensections' => new external_value(PARAM_INT,
650 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
651 VALUE_OPTIONAL),
652 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
653 VALUE_DEFAULT, $courseconfig->groupmode),
654 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
655 VALUE_DEFAULT, $courseconfig->groupmodeforce),
656 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
657 VALUE_DEFAULT, 0),
658 'enablecompletion' => new external_value(PARAM_INT,
659 'Enabled, control via completion and activity settings. Disabled,
660 not shown in activity settings.',
661 VALUE_OPTIONAL),
662 'completionnotify' => new external_value(PARAM_INT,
663 '1: yes 0: no', VALUE_OPTIONAL),
664 'lang' => new external_value(PARAM_SAFEDIR,
665 'forced course language', VALUE_OPTIONAL),
666 'forcetheme' => new external_value(PARAM_PLUGIN,
667 'name of the force theme', VALUE_OPTIONAL),
668 'courseformatoptions' => new external_multiple_structure(
669 new external_single_structure(
670 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
671 'value' => new external_value(PARAM_RAW, 'course format option value')
673 'additional options for particular course format', VALUE_OPTIONAL),
675 ), 'courses to create'
682 * Create courses
684 * @param array $courses
685 * @return array courses (id and shortname only)
686 * @since Moodle 2.2
688 public static function create_courses($courses) {
689 global $CFG, $DB;
690 require_once($CFG->dirroot . "/course/lib.php");
691 require_once($CFG->libdir . '/completionlib.php');
693 $params = self::validate_parameters(self::create_courses_parameters(),
694 array('courses' => $courses));
696 $availablethemes = core_component::get_plugin_list('theme');
697 $availablelangs = get_string_manager()->get_list_of_translations();
699 $transaction = $DB->start_delegated_transaction();
701 foreach ($params['courses'] as $course) {
703 // Ensure the current user is allowed to run this function
704 $context = context_coursecat::instance($course['categoryid'], IGNORE_MISSING);
705 try {
706 self::validate_context($context);
707 } catch (Exception $e) {
708 $exceptionparam = new stdClass();
709 $exceptionparam->message = $e->getMessage();
710 $exceptionparam->catid = $course['categoryid'];
711 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
713 require_capability('moodle/course:create', $context);
715 // Make sure lang is valid
716 if (array_key_exists('lang', $course) and empty($availablelangs[$course['lang']])) {
717 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
720 // Make sure theme is valid
721 if (array_key_exists('forcetheme', $course)) {
722 if (!empty($CFG->allowcoursethemes)) {
723 if (empty($availablethemes[$course['forcetheme']])) {
724 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
725 } else {
726 $course['theme'] = $course['forcetheme'];
731 //force visibility if ws user doesn't have the permission to set it
732 $category = $DB->get_record('course_categories', array('id' => $course['categoryid']));
733 if (!has_capability('moodle/course:visibility', $context)) {
734 $course['visible'] = $category->visible;
737 //set default value for completion
738 $courseconfig = get_config('moodlecourse');
739 if (completion_info::is_enabled_for_site()) {
740 if (!array_key_exists('enablecompletion', $course)) {
741 $course['enablecompletion'] = $courseconfig->enablecompletion;
743 } else {
744 $course['enablecompletion'] = 0;
747 $course['category'] = $course['categoryid'];
749 // Summary format.
750 $course['summaryformat'] = external_validate_format($course['summaryformat']);
752 if (!empty($course['courseformatoptions'])) {
753 foreach ($course['courseformatoptions'] as $option) {
754 $course[$option['name']] = $option['value'];
758 //Note: create_course() core function check shortname, idnumber, category
759 $course['id'] = create_course((object) $course)->id;
761 $resultcourses[] = array('id' => $course['id'], 'shortname' => $course['shortname']);
764 $transaction->allow_commit();
766 return $resultcourses;
770 * Returns description of method result value
772 * @return external_description
773 * @since Moodle 2.2
775 public static function create_courses_returns() {
776 return new external_multiple_structure(
777 new external_single_structure(
778 array(
779 'id' => new external_value(PARAM_INT, 'course id'),
780 'shortname' => new external_value(PARAM_TEXT, 'short name'),
787 * Update courses
789 * @return external_function_parameters
790 * @since Moodle 2.5
792 public static function update_courses_parameters() {
793 return new external_function_parameters(
794 array(
795 'courses' => new external_multiple_structure(
796 new external_single_structure(
797 array(
798 'id' => new external_value(PARAM_INT, 'ID of the course'),
799 'fullname' => new external_value(PARAM_TEXT, 'full name', VALUE_OPTIONAL),
800 'shortname' => new external_value(PARAM_TEXT, 'course short name', VALUE_OPTIONAL),
801 'categoryid' => new external_value(PARAM_INT, 'category id', VALUE_OPTIONAL),
802 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
803 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
804 'summaryformat' => new external_format_value('summary', VALUE_OPTIONAL),
805 'format' => new external_value(PARAM_PLUGIN,
806 'course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
807 'showgrades' => new external_value(PARAM_INT,
808 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
809 'newsitems' => new external_value(PARAM_INT,
810 'number of recent items appearing on the course page', VALUE_OPTIONAL),
811 'startdate' => new external_value(PARAM_INT,
812 'timestamp when the course start', VALUE_OPTIONAL),
813 'enddate' => new external_value(PARAM_INT,
814 'timestamp when the course end', VALUE_OPTIONAL),
815 'numsections' => new external_value(PARAM_INT,
816 '(deprecated, use courseformatoptions) number of weeks/topics', VALUE_OPTIONAL),
817 'maxbytes' => new external_value(PARAM_INT,
818 'largest size of file that can be uploaded into the course', VALUE_OPTIONAL),
819 'showreports' => new external_value(PARAM_INT,
820 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
821 'visible' => new external_value(PARAM_INT,
822 '1: available to student, 0:not available', VALUE_OPTIONAL),
823 'hiddensections' => new external_value(PARAM_INT,
824 '(deprecated, use courseformatoptions) How the hidden sections in the course are
825 displayed to students', VALUE_OPTIONAL),
826 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
827 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
828 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
829 'enablecompletion' => new external_value(PARAM_INT,
830 'Enabled, control via completion and activity settings. Disabled,
831 not shown in activity settings.', VALUE_OPTIONAL),
832 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
833 'lang' => new external_value(PARAM_SAFEDIR, 'forced course language', VALUE_OPTIONAL),
834 'forcetheme' => new external_value(PARAM_PLUGIN, 'name of the force theme', VALUE_OPTIONAL),
835 'courseformatoptions' => new external_multiple_structure(
836 new external_single_structure(
837 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
838 'value' => new external_value(PARAM_RAW, 'course format option value')
840 'additional options for particular course format', VALUE_OPTIONAL),
842 ), 'courses to update'
849 * Update courses
851 * @param array $courses
852 * @since Moodle 2.5
854 public static function update_courses($courses) {
855 global $CFG, $DB;
856 require_once($CFG->dirroot . "/course/lib.php");
857 $warnings = array();
859 $params = self::validate_parameters(self::update_courses_parameters(),
860 array('courses' => $courses));
862 $availablethemes = core_component::get_plugin_list('theme');
863 $availablelangs = get_string_manager()->get_list_of_translations();
865 foreach ($params['courses'] as $course) {
866 // Catch any exception while updating course and return as warning to user.
867 try {
868 // Ensure the current user is allowed to run this function.
869 $context = context_course::instance($course['id'], MUST_EXIST);
870 self::validate_context($context);
872 $oldcourse = course_get_format($course['id'])->get_course();
874 require_capability('moodle/course:update', $context);
876 // Check if user can change category.
877 if (array_key_exists('categoryid', $course) && ($oldcourse->category != $course['categoryid'])) {
878 require_capability('moodle/course:changecategory', $context);
879 $course['category'] = $course['categoryid'];
882 // Check if the user can change fullname.
883 if (array_key_exists('fullname', $course) && ($oldcourse->fullname != $course['fullname'])) {
884 require_capability('moodle/course:changefullname', $context);
887 // Check if the user can change shortname.
888 if (array_key_exists('shortname', $course) && ($oldcourse->shortname != $course['shortname'])) {
889 require_capability('moodle/course:changeshortname', $context);
892 // Check if the user can change the idnumber.
893 if (array_key_exists('idnumber', $course) && ($oldcourse->idnumber != $course['idnumber'])) {
894 require_capability('moodle/course:changeidnumber', $context);
897 // Check if user can change summary.
898 if (array_key_exists('summary', $course) && ($oldcourse->summary != $course['summary'])) {
899 require_capability('moodle/course:changesummary', $context);
902 // Summary format.
903 if (array_key_exists('summaryformat', $course) && ($oldcourse->summaryformat != $course['summaryformat'])) {
904 require_capability('moodle/course:changesummary', $context);
905 $course['summaryformat'] = external_validate_format($course['summaryformat']);
908 // Check if user can change visibility.
909 if (array_key_exists('visible', $course) && ($oldcourse->visible != $course['visible'])) {
910 require_capability('moodle/course:visibility', $context);
913 // Make sure lang is valid.
914 if (array_key_exists('lang', $course) && empty($availablelangs[$course['lang']])) {
915 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
918 // Make sure theme is valid.
919 if (array_key_exists('forcetheme', $course)) {
920 if (!empty($CFG->allowcoursethemes)) {
921 if (empty($availablethemes[$course['forcetheme']])) {
922 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
923 } else {
924 $course['theme'] = $course['forcetheme'];
929 // Make sure completion is enabled before setting it.
930 if (array_key_exists('enabledcompletion', $course) && !completion_info::is_enabled_for_site()) {
931 $course['enabledcompletion'] = 0;
934 // Make sure maxbytes are less then CFG->maxbytes.
935 if (array_key_exists('maxbytes', $course)) {
936 $course['maxbytes'] = get_max_upload_file_size($CFG->maxbytes, $course['maxbytes']);
939 if (!empty($course['courseformatoptions'])) {
940 foreach ($course['courseformatoptions'] as $option) {
941 if (isset($option['name']) && isset($option['value'])) {
942 $course[$option['name']] = $option['value'];
947 // Update course if user has all required capabilities.
948 update_course((object) $course);
949 } catch (Exception $e) {
950 $warning = array();
951 $warning['item'] = 'course';
952 $warning['itemid'] = $course['id'];
953 if ($e instanceof moodle_exception) {
954 $warning['warningcode'] = $e->errorcode;
955 } else {
956 $warning['warningcode'] = $e->getCode();
958 $warning['message'] = $e->getMessage();
959 $warnings[] = $warning;
963 $result = array();
964 $result['warnings'] = $warnings;
965 return $result;
969 * Returns description of method result value
971 * @return external_description
972 * @since Moodle 2.5
974 public static function update_courses_returns() {
975 return new external_single_structure(
976 array(
977 'warnings' => new external_warnings()
983 * Returns description of method parameters
985 * @return external_function_parameters
986 * @since Moodle 2.2
988 public static function delete_courses_parameters() {
989 return new external_function_parameters(
990 array(
991 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'course ID')),
997 * Delete courses
999 * @param array $courseids A list of course ids
1000 * @since Moodle 2.2
1002 public static function delete_courses($courseids) {
1003 global $CFG, $DB;
1004 require_once($CFG->dirroot."/course/lib.php");
1006 // Parameter validation.
1007 $params = self::validate_parameters(self::delete_courses_parameters(), array('courseids'=>$courseids));
1009 $warnings = array();
1011 foreach ($params['courseids'] as $courseid) {
1012 $course = $DB->get_record('course', array('id' => $courseid));
1014 if ($course === false) {
1015 $warnings[] = array(
1016 'item' => 'course',
1017 'itemid' => $courseid,
1018 'warningcode' => 'unknowncourseidnumber',
1019 'message' => 'Unknown course ID ' . $courseid
1021 continue;
1024 // Check if the context is valid.
1025 $coursecontext = context_course::instance($course->id);
1026 self::validate_context($coursecontext);
1028 // Check if the current user has permission.
1029 if (!can_delete_course($courseid)) {
1030 $warnings[] = array(
1031 'item' => 'course',
1032 'itemid' => $courseid,
1033 'warningcode' => 'cannotdeletecourse',
1034 'message' => 'You do not have the permission to delete this course' . $courseid
1036 continue;
1039 if (delete_course($course, false) === false) {
1040 $warnings[] = array(
1041 'item' => 'course',
1042 'itemid' => $courseid,
1043 'warningcode' => 'cannotdeletecategorycourse',
1044 'message' => 'Course ' . $courseid . ' failed to be deleted'
1046 continue;
1050 fix_course_sortorder();
1052 return array('warnings' => $warnings);
1056 * Returns description of method result value
1058 * @return external_description
1059 * @since Moodle 2.2
1061 public static function delete_courses_returns() {
1062 return new external_single_structure(
1063 array(
1064 'warnings' => new external_warnings()
1070 * Returns description of method parameters
1072 * @return external_function_parameters
1073 * @since Moodle 2.3
1075 public static function duplicate_course_parameters() {
1076 return new external_function_parameters(
1077 array(
1078 'courseid' => new external_value(PARAM_INT, 'course to duplicate id'),
1079 'fullname' => new external_value(PARAM_TEXT, 'duplicated course full name'),
1080 'shortname' => new external_value(PARAM_TEXT, 'duplicated course short name'),
1081 'categoryid' => new external_value(PARAM_INT, 'duplicated course category parent'),
1082 'visible' => new external_value(PARAM_INT, 'duplicated course visible, default to yes', VALUE_DEFAULT, 1),
1083 'options' => new external_multiple_structure(
1084 new external_single_structure(
1085 array(
1086 'name' => new external_value(PARAM_ALPHAEXT, 'The backup option name:
1087 "activities" (int) Include course activites (default to 1 that is equal to yes),
1088 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1089 "filters" (int) Include course filters (default to 1 that is equal to yes),
1090 "users" (int) Include users (default to 0 that is equal to no),
1091 "enrolments" (int) Include enrolment methods (default to 1 - restore only with users),
1092 "role_assignments" (int) Include role assignments (default to 0 that is equal to no),
1093 "comments" (int) Include user comments (default to 0 that is equal to no),
1094 "userscompletion" (int) Include user course completion information (default to 0 that is equal to no),
1095 "logs" (int) Include course logs (default to 0 that is equal to no),
1096 "grade_histories" (int) Include histories (default to 0 that is equal to no)'
1098 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1101 ), VALUE_DEFAULT, array()
1108 * Duplicate a course
1110 * @param int $courseid
1111 * @param string $fullname Duplicated course fullname
1112 * @param string $shortname Duplicated course shortname
1113 * @param int $categoryid Duplicated course parent category id
1114 * @param int $visible Duplicated course availability
1115 * @param array $options List of backup options
1116 * @return array New course info
1117 * @since Moodle 2.3
1119 public static function duplicate_course($courseid, $fullname, $shortname, $categoryid, $visible = 1, $options = array()) {
1120 global $CFG, $USER, $DB;
1121 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1122 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1124 // Parameter validation.
1125 $params = self::validate_parameters(
1126 self::duplicate_course_parameters(),
1127 array(
1128 'courseid' => $courseid,
1129 'fullname' => $fullname,
1130 'shortname' => $shortname,
1131 'categoryid' => $categoryid,
1132 'visible' => $visible,
1133 'options' => $options
1137 // Context validation.
1139 if (! ($course = $DB->get_record('course', array('id'=>$params['courseid'])))) {
1140 throw new moodle_exception('invalidcourseid', 'error');
1143 // Category where duplicated course is going to be created.
1144 $categorycontext = context_coursecat::instance($params['categoryid']);
1145 self::validate_context($categorycontext);
1147 // Course to be duplicated.
1148 $coursecontext = context_course::instance($course->id);
1149 self::validate_context($coursecontext);
1151 $backupdefaults = array(
1152 'activities' => 1,
1153 'blocks' => 1,
1154 'filters' => 1,
1155 'users' => 0,
1156 'enrolments' => backup::ENROL_WITHUSERS,
1157 'role_assignments' => 0,
1158 'comments' => 0,
1159 'userscompletion' => 0,
1160 'logs' => 0,
1161 'grade_histories' => 0
1164 $backupsettings = array();
1165 // Check for backup and restore options.
1166 if (!empty($params['options'])) {
1167 foreach ($params['options'] as $option) {
1169 // Strict check for a correct value (allways 1 or 0, true or false).
1170 $value = clean_param($option['value'], PARAM_INT);
1172 if ($value !== 0 and $value !== 1) {
1173 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1176 if (!isset($backupdefaults[$option['name']])) {
1177 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1180 $backupsettings[$option['name']] = $value;
1184 // Capability checking.
1186 // The backup controller check for this currently, this may be redundant.
1187 require_capability('moodle/course:create', $categorycontext);
1188 require_capability('moodle/restore:restorecourse', $categorycontext);
1189 require_capability('moodle/backup:backupcourse', $coursecontext);
1191 if (!empty($backupsettings['users'])) {
1192 require_capability('moodle/backup:userinfo', $coursecontext);
1193 require_capability('moodle/restore:userinfo', $categorycontext);
1196 // Check if the shortname is used.
1197 if ($foundcourses = $DB->get_records('course', array('shortname'=>$shortname))) {
1198 foreach ($foundcourses as $foundcourse) {
1199 $foundcoursenames[] = $foundcourse->fullname;
1202 $foundcoursenamestring = implode(',', $foundcoursenames);
1203 throw new moodle_exception('shortnametaken', '', '', $foundcoursenamestring);
1206 // Backup the course.
1208 $bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE,
1209 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id);
1211 foreach ($backupsettings as $name => $value) {
1212 if ($setting = $bc->get_plan()->get_setting($name)) {
1213 $bc->get_plan()->get_setting($name)->set_value($value);
1217 $backupid = $bc->get_backupid();
1218 $backupbasepath = $bc->get_plan()->get_basepath();
1220 $bc->execute_plan();
1221 $results = $bc->get_results();
1222 $file = $results['backup_destination'];
1224 $bc->destroy();
1226 // Restore the backup immediately.
1228 // Check if we need to unzip the file because the backup temp dir does not contains backup files.
1229 if (!file_exists($backupbasepath . "/moodle_backup.xml")) {
1230 $file->extract_to_pathname(get_file_packer('application/vnd.moodle.backup'), $backupbasepath);
1233 // Create new course.
1234 $newcourseid = restore_dbops::create_new_course($params['fullname'], $params['shortname'], $params['categoryid']);
1236 $rc = new restore_controller($backupid, $newcourseid,
1237 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id, backup::TARGET_NEW_COURSE);
1239 foreach ($backupsettings as $name => $value) {
1240 $setting = $rc->get_plan()->get_setting($name);
1241 if ($setting->get_status() == backup_setting::NOT_LOCKED) {
1242 $setting->set_value($value);
1246 if (!$rc->execute_precheck()) {
1247 $precheckresults = $rc->get_precheck_results();
1248 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1249 if (empty($CFG->keeptempdirectoriesonbackup)) {
1250 fulldelete($backupbasepath);
1253 $errorinfo = '';
1255 foreach ($precheckresults['errors'] as $error) {
1256 $errorinfo .= $error;
1259 if (array_key_exists('warnings', $precheckresults)) {
1260 foreach ($precheckresults['warnings'] as $warning) {
1261 $errorinfo .= $warning;
1265 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1269 $rc->execute_plan();
1270 $rc->destroy();
1272 $course = $DB->get_record('course', array('id' => $newcourseid), '*', MUST_EXIST);
1273 $course->fullname = $params['fullname'];
1274 $course->shortname = $params['shortname'];
1275 $course->visible = $params['visible'];
1277 // Set shortname and fullname back.
1278 $DB->update_record('course', $course);
1280 if (empty($CFG->keeptempdirectoriesonbackup)) {
1281 fulldelete($backupbasepath);
1284 // Delete the course backup file created by this WebService. Originally located in the course backups area.
1285 $file->delete();
1287 return array('id' => $course->id, 'shortname' => $course->shortname);
1291 * Returns description of method result value
1293 * @return external_description
1294 * @since Moodle 2.3
1296 public static function duplicate_course_returns() {
1297 return new external_single_structure(
1298 array(
1299 'id' => new external_value(PARAM_INT, 'course id'),
1300 'shortname' => new external_value(PARAM_TEXT, 'short name'),
1306 * Returns description of method parameters for import_course
1308 * @return external_function_parameters
1309 * @since Moodle 2.4
1311 public static function import_course_parameters() {
1312 return new external_function_parameters(
1313 array(
1314 'importfrom' => new external_value(PARAM_INT, 'the id of the course we are importing from'),
1315 'importto' => new external_value(PARAM_INT, 'the id of the course we are importing to'),
1316 'deletecontent' => new external_value(PARAM_INT, 'whether to delete the course content where we are importing to (default to 0 = No)', VALUE_DEFAULT, 0),
1317 'options' => new external_multiple_structure(
1318 new external_single_structure(
1319 array(
1320 'name' => new external_value(PARAM_ALPHA, 'The backup option name:
1321 "activities" (int) Include course activites (default to 1 that is equal to yes),
1322 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1323 "filters" (int) Include course filters (default to 1 that is equal to yes)'
1325 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1328 ), VALUE_DEFAULT, array()
1335 * Imports a course
1337 * @param int $importfrom The id of the course we are importing from
1338 * @param int $importto The id of the course we are importing to
1339 * @param bool $deletecontent Whether to delete the course we are importing to content
1340 * @param array $options List of backup options
1341 * @return null
1342 * @since Moodle 2.4
1344 public static function import_course($importfrom, $importto, $deletecontent = 0, $options = array()) {
1345 global $CFG, $USER, $DB;
1346 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1347 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1349 // Parameter validation.
1350 $params = self::validate_parameters(
1351 self::import_course_parameters(),
1352 array(
1353 'importfrom' => $importfrom,
1354 'importto' => $importto,
1355 'deletecontent' => $deletecontent,
1356 'options' => $options
1360 if ($params['deletecontent'] !== 0 and $params['deletecontent'] !== 1) {
1361 throw new moodle_exception('invalidextparam', 'webservice', '', $params['deletecontent']);
1364 // Context validation.
1366 if (! ($importfrom = $DB->get_record('course', array('id'=>$params['importfrom'])))) {
1367 throw new moodle_exception('invalidcourseid', 'error');
1370 if (! ($importto = $DB->get_record('course', array('id'=>$params['importto'])))) {
1371 throw new moodle_exception('invalidcourseid', 'error');
1374 $importfromcontext = context_course::instance($importfrom->id);
1375 self::validate_context($importfromcontext);
1377 $importtocontext = context_course::instance($importto->id);
1378 self::validate_context($importtocontext);
1380 $backupdefaults = array(
1381 'activities' => 1,
1382 'blocks' => 1,
1383 'filters' => 1
1386 $backupsettings = array();
1388 // Check for backup and restore options.
1389 if (!empty($params['options'])) {
1390 foreach ($params['options'] as $option) {
1392 // Strict check for a correct value (allways 1 or 0, true or false).
1393 $value = clean_param($option['value'], PARAM_INT);
1395 if ($value !== 0 and $value !== 1) {
1396 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1399 if (!isset($backupdefaults[$option['name']])) {
1400 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1403 $backupsettings[$option['name']] = $value;
1407 // Capability checking.
1409 require_capability('moodle/backup:backuptargetimport', $importfromcontext);
1410 require_capability('moodle/restore:restoretargetimport', $importtocontext);
1412 $bc = new backup_controller(backup::TYPE_1COURSE, $importfrom->id, backup::FORMAT_MOODLE,
1413 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
1415 foreach ($backupsettings as $name => $value) {
1416 $bc->get_plan()->get_setting($name)->set_value($value);
1419 $backupid = $bc->get_backupid();
1420 $backupbasepath = $bc->get_plan()->get_basepath();
1422 $bc->execute_plan();
1423 $bc->destroy();
1425 // Restore the backup immediately.
1427 // Check if we must delete the contents of the destination course.
1428 if ($params['deletecontent']) {
1429 $restoretarget = backup::TARGET_EXISTING_DELETING;
1430 } else {
1431 $restoretarget = backup::TARGET_EXISTING_ADDING;
1434 $rc = new restore_controller($backupid, $importto->id,
1435 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, $restoretarget);
1437 foreach ($backupsettings as $name => $value) {
1438 $rc->get_plan()->get_setting($name)->set_value($value);
1441 if (!$rc->execute_precheck()) {
1442 $precheckresults = $rc->get_precheck_results();
1443 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1444 if (empty($CFG->keeptempdirectoriesonbackup)) {
1445 fulldelete($backupbasepath);
1448 $errorinfo = '';
1450 foreach ($precheckresults['errors'] as $error) {
1451 $errorinfo .= $error;
1454 if (array_key_exists('warnings', $precheckresults)) {
1455 foreach ($precheckresults['warnings'] as $warning) {
1456 $errorinfo .= $warning;
1460 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1462 } else {
1463 if ($restoretarget == backup::TARGET_EXISTING_DELETING) {
1464 restore_dbops::delete_course_content($importto->id);
1468 $rc->execute_plan();
1469 $rc->destroy();
1471 if (empty($CFG->keeptempdirectoriesonbackup)) {
1472 fulldelete($backupbasepath);
1475 return null;
1479 * Returns description of method result value
1481 * @return external_description
1482 * @since Moodle 2.4
1484 public static function import_course_returns() {
1485 return null;
1489 * Returns description of method parameters
1491 * @return external_function_parameters
1492 * @since Moodle 2.3
1494 public static function get_categories_parameters() {
1495 return new external_function_parameters(
1496 array(
1497 'criteria' => new external_multiple_structure(
1498 new external_single_structure(
1499 array(
1500 'key' => new external_value(PARAM_ALPHA,
1501 'The category column to search, expected keys (value format) are:'.
1502 '"id" (int) the category id,'.
1503 '"ids" (string) category ids separated by commas,'.
1504 '"name" (string) the category name,'.
1505 '"parent" (int) the parent category id,'.
1506 '"idnumber" (string) category idnumber'.
1507 ' - user must have \'moodle/category:manage\' to search on idnumber,'.
1508 '"visible" (int) whether the returned categories must be visible or hidden. If the key is not passed,
1509 then the function return all categories that the user can see.'.
1510 ' - user must have \'moodle/category:manage\' or \'moodle/category:viewhiddencategories\' to search on visible,'.
1511 '"theme" (string) only return the categories having this theme'.
1512 ' - user must have \'moodle/category:manage\' to search on theme'),
1513 'value' => new external_value(PARAM_RAW, 'the value to match')
1515 ), 'criteria', VALUE_DEFAULT, array()
1517 'addsubcategories' => new external_value(PARAM_BOOL, 'return the sub categories infos
1518 (1 - default) otherwise only the category info (0)', VALUE_DEFAULT, 1)
1524 * Get categories
1526 * @param array $criteria Criteria to match the results
1527 * @param booln $addsubcategories obtain only the category (false) or its subcategories (true - default)
1528 * @return array list of categories
1529 * @since Moodle 2.3
1531 public static function get_categories($criteria = array(), $addsubcategories = true) {
1532 global $CFG, $DB;
1533 require_once($CFG->dirroot . "/course/lib.php");
1535 // Validate parameters.
1536 $params = self::validate_parameters(self::get_categories_parameters(),
1537 array('criteria' => $criteria, 'addsubcategories' => $addsubcategories));
1539 // Retrieve the categories.
1540 $categories = array();
1541 if (!empty($params['criteria'])) {
1543 $conditions = array();
1544 $wheres = array();
1545 foreach ($params['criteria'] as $crit) {
1546 $key = trim($crit['key']);
1548 // Trying to avoid duplicate keys.
1549 if (!isset($conditions[$key])) {
1551 $context = context_system::instance();
1552 $value = null;
1553 switch ($key) {
1554 case 'id':
1555 $value = clean_param($crit['value'], PARAM_INT);
1556 $conditions[$key] = $value;
1557 $wheres[] = $key . " = :" . $key;
1558 break;
1560 case 'ids':
1561 $value = clean_param($crit['value'], PARAM_SEQUENCE);
1562 $ids = explode(',', $value);
1563 list($sqlids, $paramids) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED);
1564 $conditions = array_merge($conditions, $paramids);
1565 $wheres[] = 'id ' . $sqlids;
1566 break;
1568 case 'idnumber':
1569 if (has_capability('moodle/category:manage', $context)) {
1570 $value = clean_param($crit['value'], PARAM_RAW);
1571 $conditions[$key] = $value;
1572 $wheres[] = $key . " = :" . $key;
1573 } else {
1574 // We must throw an exception.
1575 // Otherwise the dev client would think no idnumber exists.
1576 throw new moodle_exception('criteriaerror',
1577 'webservice', '', null,
1578 'You don\'t have the permissions to search on the "idnumber" field.');
1580 break;
1582 case 'name':
1583 $value = clean_param($crit['value'], PARAM_TEXT);
1584 $conditions[$key] = $value;
1585 $wheres[] = $key . " = :" . $key;
1586 break;
1588 case 'parent':
1589 $value = clean_param($crit['value'], PARAM_INT);
1590 $conditions[$key] = $value;
1591 $wheres[] = $key . " = :" . $key;
1592 break;
1594 case 'visible':
1595 if (has_capability('moodle/category:manage', $context)
1596 or has_capability('moodle/category:viewhiddencategories',
1597 context_system::instance())) {
1598 $value = clean_param($crit['value'], PARAM_INT);
1599 $conditions[$key] = $value;
1600 $wheres[] = $key . " = :" . $key;
1601 } else {
1602 throw new moodle_exception('criteriaerror',
1603 'webservice', '', null,
1604 'You don\'t have the permissions to search on the "visible" field.');
1606 break;
1608 case 'theme':
1609 if (has_capability('moodle/category:manage', $context)) {
1610 $value = clean_param($crit['value'], PARAM_THEME);
1611 $conditions[$key] = $value;
1612 $wheres[] = $key . " = :" . $key;
1613 } else {
1614 throw new moodle_exception('criteriaerror',
1615 'webservice', '', null,
1616 'You don\'t have the permissions to search on the "theme" field.');
1618 break;
1620 default:
1621 throw new moodle_exception('criteriaerror',
1622 'webservice', '', null,
1623 'You can not search on this criteria: ' . $key);
1628 if (!empty($wheres)) {
1629 $wheres = implode(" AND ", $wheres);
1631 $categories = $DB->get_records_select('course_categories', $wheres, $conditions);
1633 // Retrieve its sub subcategories (all levels).
1634 if ($categories and !empty($params['addsubcategories'])) {
1635 $newcategories = array();
1637 // Check if we required visible/theme checks.
1638 $additionalselect = '';
1639 $additionalparams = array();
1640 if (isset($conditions['visible'])) {
1641 $additionalselect .= ' AND visible = :visible';
1642 $additionalparams['visible'] = $conditions['visible'];
1644 if (isset($conditions['theme'])) {
1645 $additionalselect .= ' AND theme= :theme';
1646 $additionalparams['theme'] = $conditions['theme'];
1649 foreach ($categories as $category) {
1650 $sqlselect = $DB->sql_like('path', ':path') . $additionalselect;
1651 $sqlparams = array('path' => $category->path.'/%') + $additionalparams; // It will NOT include the specified category.
1652 $subcategories = $DB->get_records_select('course_categories', $sqlselect, $sqlparams);
1653 $newcategories = $newcategories + $subcategories; // Both arrays have integer as keys.
1655 $categories = $categories + $newcategories;
1659 } else {
1660 // Retrieve all categories in the database.
1661 $categories = $DB->get_records('course_categories');
1664 // The not returned categories. key => category id, value => reason of exclusion.
1665 $excludedcats = array();
1667 // The returned categories.
1668 $categoriesinfo = array();
1670 // We need to sort the categories by path.
1671 // The parent cats need to be checked by the algo first.
1672 usort($categories, "core_course_external::compare_categories_by_path");
1674 foreach ($categories as $category) {
1676 // Check if the category is a child of an excluded category, if yes exclude it too (excluded => do not return).
1677 $parents = explode('/', $category->path);
1678 unset($parents[0]); // First key is always empty because path start with / => /1/2/4.
1679 foreach ($parents as $parentid) {
1680 // Note: when the parent exclusion was due to the context,
1681 // the sub category could still be returned.
1682 if (isset($excludedcats[$parentid]) and $excludedcats[$parentid] != 'context') {
1683 $excludedcats[$category->id] = 'parent';
1687 // Check the user can use the category context.
1688 $context = context_coursecat::instance($category->id);
1689 try {
1690 self::validate_context($context);
1691 } catch (Exception $e) {
1692 $excludedcats[$category->id] = 'context';
1694 // If it was the requested category then throw an exception.
1695 if (isset($params['categoryid']) && $category->id == $params['categoryid']) {
1696 $exceptionparam = new stdClass();
1697 $exceptionparam->message = $e->getMessage();
1698 $exceptionparam->catid = $category->id;
1699 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
1703 // Return the category information.
1704 if (!isset($excludedcats[$category->id])) {
1706 // Final check to see if the category is visible to the user.
1707 if ($category->visible
1708 or has_capability('moodle/category:viewhiddencategories', context_system::instance())
1709 or has_capability('moodle/category:manage', $context)) {
1711 $categoryinfo = array();
1712 $categoryinfo['id'] = $category->id;
1713 $categoryinfo['name'] = $category->name;
1714 list($categoryinfo['description'], $categoryinfo['descriptionformat']) =
1715 external_format_text($category->description, $category->descriptionformat,
1716 $context->id, 'coursecat', 'description', null);
1717 $categoryinfo['parent'] = $category->parent;
1718 $categoryinfo['sortorder'] = $category->sortorder;
1719 $categoryinfo['coursecount'] = $category->coursecount;
1720 $categoryinfo['depth'] = $category->depth;
1721 $categoryinfo['path'] = $category->path;
1723 // Some fields only returned for admin.
1724 if (has_capability('moodle/category:manage', $context)) {
1725 $categoryinfo['idnumber'] = $category->idnumber;
1726 $categoryinfo['visible'] = $category->visible;
1727 $categoryinfo['visibleold'] = $category->visibleold;
1728 $categoryinfo['timemodified'] = $category->timemodified;
1729 $categoryinfo['theme'] = clean_param($category->theme, PARAM_THEME);
1732 $categoriesinfo[] = $categoryinfo;
1733 } else {
1734 $excludedcats[$category->id] = 'visibility';
1739 // Sorting the resulting array so it looks a bit better for the client developer.
1740 usort($categoriesinfo, "core_course_external::compare_categories_by_sortorder");
1742 return $categoriesinfo;
1746 * Sort categories array by path
1747 * private function: only used by get_categories
1749 * @param array $category1
1750 * @param array $category2
1751 * @return int result of strcmp
1752 * @since Moodle 2.3
1754 private static function compare_categories_by_path($category1, $category2) {
1755 return strcmp($category1->path, $category2->path);
1759 * Sort categories array by sortorder
1760 * private function: only used by get_categories
1762 * @param array $category1
1763 * @param array $category2
1764 * @return int result of strcmp
1765 * @since Moodle 2.3
1767 private static function compare_categories_by_sortorder($category1, $category2) {
1768 return strcmp($category1['sortorder'], $category2['sortorder']);
1772 * Returns description of method result value
1774 * @return external_description
1775 * @since Moodle 2.3
1777 public static function get_categories_returns() {
1778 return new external_multiple_structure(
1779 new external_single_structure(
1780 array(
1781 'id' => new external_value(PARAM_INT, 'category id'),
1782 'name' => new external_value(PARAM_TEXT, 'category name'),
1783 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1784 'description' => new external_value(PARAM_RAW, 'category description'),
1785 'descriptionformat' => new external_format_value('description'),
1786 'parent' => new external_value(PARAM_INT, 'parent category id'),
1787 'sortorder' => new external_value(PARAM_INT, 'category sorting order'),
1788 'coursecount' => new external_value(PARAM_INT, 'number of courses in this category'),
1789 'visible' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1790 'visibleold' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1791 'timemodified' => new external_value(PARAM_INT, 'timestamp', VALUE_OPTIONAL),
1792 'depth' => new external_value(PARAM_INT, 'category depth'),
1793 'path' => new external_value(PARAM_TEXT, 'category path'),
1794 'theme' => new external_value(PARAM_THEME, 'category theme', VALUE_OPTIONAL),
1795 ), 'List of categories'
1801 * Returns description of method parameters
1803 * @return external_function_parameters
1804 * @since Moodle 2.3
1806 public static function create_categories_parameters() {
1807 return new external_function_parameters(
1808 array(
1809 'categories' => new external_multiple_structure(
1810 new external_single_structure(
1811 array(
1812 'name' => new external_value(PARAM_TEXT, 'new category name'),
1813 'parent' => new external_value(PARAM_INT,
1814 'the parent category id inside which the new category will be created
1815 - set to 0 for a root category',
1816 VALUE_DEFAULT, 0),
1817 'idnumber' => new external_value(PARAM_RAW,
1818 'the new category idnumber', VALUE_OPTIONAL),
1819 'description' => new external_value(PARAM_RAW,
1820 'the new category description', VALUE_OPTIONAL),
1821 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
1822 'theme' => new external_value(PARAM_THEME,
1823 'the new category theme. This option must be enabled on moodle',
1824 VALUE_OPTIONAL),
1833 * Create categories
1835 * @param array $categories - see create_categories_parameters() for the array structure
1836 * @return array - see create_categories_returns() for the array structure
1837 * @since Moodle 2.3
1839 public static function create_categories($categories) {
1840 global $CFG, $DB;
1841 require_once($CFG->libdir . "/coursecatlib.php");
1843 $params = self::validate_parameters(self::create_categories_parameters(),
1844 array('categories' => $categories));
1846 $transaction = $DB->start_delegated_transaction();
1848 $createdcategories = array();
1849 foreach ($params['categories'] as $category) {
1850 if ($category['parent']) {
1851 if (!$DB->record_exists('course_categories', array('id' => $category['parent']))) {
1852 throw new moodle_exception('unknowcategory');
1854 $context = context_coursecat::instance($category['parent']);
1855 } else {
1856 $context = context_system::instance();
1858 self::validate_context($context);
1859 require_capability('moodle/category:manage', $context);
1861 // this will validate format and throw an exception if there are errors
1862 external_validate_format($category['descriptionformat']);
1864 $newcategory = coursecat::create($category);
1866 $createdcategories[] = array('id' => $newcategory->id, 'name' => $newcategory->name);
1869 $transaction->allow_commit();
1871 return $createdcategories;
1875 * Returns description of method parameters
1877 * @return external_function_parameters
1878 * @since Moodle 2.3
1880 public static function create_categories_returns() {
1881 return new external_multiple_structure(
1882 new external_single_structure(
1883 array(
1884 'id' => new external_value(PARAM_INT, 'new category id'),
1885 'name' => new external_value(PARAM_TEXT, 'new category name'),
1892 * Returns description of method parameters
1894 * @return external_function_parameters
1895 * @since Moodle 2.3
1897 public static function update_categories_parameters() {
1898 return new external_function_parameters(
1899 array(
1900 'categories' => new external_multiple_structure(
1901 new external_single_structure(
1902 array(
1903 'id' => new external_value(PARAM_INT, 'course id'),
1904 'name' => new external_value(PARAM_TEXT, 'category name', VALUE_OPTIONAL),
1905 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1906 'parent' => new external_value(PARAM_INT, 'parent category id', VALUE_OPTIONAL),
1907 'description' => new external_value(PARAM_RAW, 'category description', VALUE_OPTIONAL),
1908 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
1909 'theme' => new external_value(PARAM_THEME,
1910 'the category theme. This option must be enabled on moodle', VALUE_OPTIONAL),
1919 * Update categories
1921 * @param array $categories The list of categories to update
1922 * @return null
1923 * @since Moodle 2.3
1925 public static function update_categories($categories) {
1926 global $CFG, $DB;
1927 require_once($CFG->libdir . "/coursecatlib.php");
1929 // Validate parameters.
1930 $params = self::validate_parameters(self::update_categories_parameters(), array('categories' => $categories));
1932 $transaction = $DB->start_delegated_transaction();
1934 foreach ($params['categories'] as $cat) {
1935 $category = coursecat::get($cat['id']);
1937 $categorycontext = context_coursecat::instance($cat['id']);
1938 self::validate_context($categorycontext);
1939 require_capability('moodle/category:manage', $categorycontext);
1941 // this will throw an exception if descriptionformat is not valid
1942 external_validate_format($cat['descriptionformat']);
1944 $category->update($cat);
1947 $transaction->allow_commit();
1951 * Returns description of method result value
1953 * @return external_description
1954 * @since Moodle 2.3
1956 public static function update_categories_returns() {
1957 return null;
1961 * Returns description of method parameters
1963 * @return external_function_parameters
1964 * @since Moodle 2.3
1966 public static function delete_categories_parameters() {
1967 return new external_function_parameters(
1968 array(
1969 'categories' => new external_multiple_structure(
1970 new external_single_structure(
1971 array(
1972 'id' => new external_value(PARAM_INT, 'category id to delete'),
1973 'newparent' => new external_value(PARAM_INT,
1974 'the parent category to move the contents to, if specified', VALUE_OPTIONAL),
1975 'recursive' => new external_value(PARAM_BOOL, '1: recursively delete all contents inside this
1976 category, 0 (default): move contents to newparent or current parent category (except if parent is root)', VALUE_DEFAULT, 0)
1985 * Delete categories
1987 * @param array $categories A list of category ids
1988 * @return array
1989 * @since Moodle 2.3
1991 public static function delete_categories($categories) {
1992 global $CFG, $DB;
1993 require_once($CFG->dirroot . "/course/lib.php");
1994 require_once($CFG->libdir . "/coursecatlib.php");
1996 // Validate parameters.
1997 $params = self::validate_parameters(self::delete_categories_parameters(), array('categories' => $categories));
1999 $transaction = $DB->start_delegated_transaction();
2001 foreach ($params['categories'] as $category) {
2002 $deletecat = coursecat::get($category['id'], MUST_EXIST);
2003 $context = context_coursecat::instance($deletecat->id);
2004 require_capability('moodle/category:manage', $context);
2005 self::validate_context($context);
2006 self::validate_context(get_category_or_system_context($deletecat->parent));
2008 if ($category['recursive']) {
2009 // If recursive was specified, then we recursively delete the category's contents.
2010 if ($deletecat->can_delete_full()) {
2011 $deletecat->delete_full(false);
2012 } else {
2013 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2015 } else {
2016 // In this situation, we don't delete the category's contents, we either move it to newparent or parent.
2017 // If the parent is the root, moving is not supported (because a course must always be inside a category).
2018 // We must move to an existing category.
2019 if (!empty($category['newparent'])) {
2020 $newparentcat = coursecat::get($category['newparent']);
2021 } else {
2022 $newparentcat = coursecat::get($deletecat->parent);
2025 // This operation is not allowed. We must move contents to an existing category.
2026 if (!$newparentcat->id) {
2027 throw new moodle_exception('movecatcontentstoroot');
2030 self::validate_context(context_coursecat::instance($newparentcat->id));
2031 if ($deletecat->can_move_content_to($newparentcat->id)) {
2032 $deletecat->delete_move($newparentcat->id, false);
2033 } else {
2034 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2039 $transaction->allow_commit();
2043 * Returns description of method parameters
2045 * @return external_function_parameters
2046 * @since Moodle 2.3
2048 public static function delete_categories_returns() {
2049 return null;
2053 * Describes the parameters for delete_modules.
2055 * @return external_function_parameters
2056 * @since Moodle 2.5
2058 public static function delete_modules_parameters() {
2059 return new external_function_parameters (
2060 array(
2061 'cmids' => new external_multiple_structure(new external_value(PARAM_INT, 'course module ID',
2062 VALUE_REQUIRED, '', NULL_NOT_ALLOWED), 'Array of course module IDs'),
2068 * Deletes a list of provided module instances.
2070 * @param array $cmids the course module ids
2071 * @since Moodle 2.5
2073 public static function delete_modules($cmids) {
2074 global $CFG, $DB;
2076 // Require course file containing the course delete module function.
2077 require_once($CFG->dirroot . "/course/lib.php");
2079 // Clean the parameters.
2080 $params = self::validate_parameters(self::delete_modules_parameters(), array('cmids' => $cmids));
2082 // Keep track of the course ids we have performed a capability check on to avoid repeating.
2083 $arrcourseschecked = array();
2085 foreach ($params['cmids'] as $cmid) {
2086 // Get the course module.
2087 $cm = $DB->get_record('course_modules', array('id' => $cmid), '*', MUST_EXIST);
2089 // Check if we have not yet confirmed they have permission in this course.
2090 if (!in_array($cm->course, $arrcourseschecked)) {
2091 // Ensure the current user has required permission in this course.
2092 $context = context_course::instance($cm->course);
2093 self::validate_context($context);
2094 // Add to the array.
2095 $arrcourseschecked[] = $cm->course;
2098 // Ensure they can delete this module.
2099 $modcontext = context_module::instance($cm->id);
2100 require_capability('moodle/course:manageactivities', $modcontext);
2102 // Delete the module.
2103 course_delete_module($cm->id);
2108 * Describes the delete_modules return value.
2110 * @return external_single_structure
2111 * @since Moodle 2.5
2113 public static function delete_modules_returns() {
2114 return null;
2118 * Returns description of method parameters
2120 * @return external_function_parameters
2121 * @since Moodle 2.9
2123 public static function view_course_parameters() {
2124 return new external_function_parameters(
2125 array(
2126 'courseid' => new external_value(PARAM_INT, 'id of the course'),
2127 'sectionnumber' => new external_value(PARAM_INT, 'section number', VALUE_DEFAULT, 0)
2133 * Trigger the course viewed event.
2135 * @param int $courseid id of course
2136 * @param int $sectionnumber sectionnumber (0, 1, 2...)
2137 * @return array of warnings and status result
2138 * @since Moodle 2.9
2139 * @throws moodle_exception
2141 public static function view_course($courseid, $sectionnumber = 0) {
2142 global $CFG;
2143 require_once($CFG->dirroot . "/course/lib.php");
2145 $params = self::validate_parameters(self::view_course_parameters(),
2146 array(
2147 'courseid' => $courseid,
2148 'sectionnumber' => $sectionnumber
2151 $warnings = array();
2153 $course = get_course($params['courseid']);
2154 $context = context_course::instance($course->id);
2155 self::validate_context($context);
2157 if (!empty($params['sectionnumber'])) {
2159 // Get section details and check it exists.
2160 $modinfo = get_fast_modinfo($course);
2161 $coursesection = $modinfo->get_section_info($params['sectionnumber'], MUST_EXIST);
2163 // Check user is allowed to see it.
2164 if (!$coursesection->uservisible) {
2165 require_capability('moodle/course:viewhiddensections', $context);
2169 course_view($context, $params['sectionnumber']);
2171 $result = array();
2172 $result['status'] = true;
2173 $result['warnings'] = $warnings;
2174 return $result;
2178 * Returns description of method result value
2180 * @return external_description
2181 * @since Moodle 2.9
2183 public static function view_course_returns() {
2184 return new external_single_structure(
2185 array(
2186 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
2187 'warnings' => new external_warnings()
2193 * Returns description of method parameters
2195 * @return external_function_parameters
2196 * @since Moodle 3.0
2198 public static function search_courses_parameters() {
2199 return new external_function_parameters(
2200 array(
2201 'criterianame' => new external_value(PARAM_ALPHA, 'criteria name
2202 (search, modulelist (only admins), blocklist (only admins), tagid)'),
2203 'criteriavalue' => new external_value(PARAM_RAW, 'criteria value'),
2204 'page' => new external_value(PARAM_INT, 'page number (0 based)', VALUE_DEFAULT, 0),
2205 'perpage' => new external_value(PARAM_INT, 'items per page', VALUE_DEFAULT, 0),
2206 'requiredcapabilities' => new external_multiple_structure(
2207 new external_value(PARAM_CAPABILITY, 'Capability string used to filter courses by permission'),
2208 'Optional list of required capabilities (used to filter the list)', VALUE_DEFAULT, array()
2210 'limittoenrolled' => new external_value(PARAM_BOOL, 'limit to enrolled courses', VALUE_DEFAULT, 0),
2216 * Return the course information that is public (visible by every one)
2218 * @param course_in_list $course course in list object
2219 * @param stdClass $coursecontext course context object
2220 * @return array the course information
2221 * @since Moodle 3.2
2223 protected static function get_course_public_information(course_in_list $course, $coursecontext) {
2225 static $categoriescache = array();
2227 // Category information.
2228 if (!array_key_exists($course->category, $categoriescache)) {
2229 $categoriescache[$course->category] = coursecat::get($course->category, IGNORE_MISSING);
2231 $category = $categoriescache[$course->category];
2233 // Retrieve course overview used files.
2234 $files = array();
2235 foreach ($course->get_course_overviewfiles() as $file) {
2236 $fileurl = moodle_url::make_webservice_pluginfile_url($file->get_contextid(), $file->get_component(),
2237 $file->get_filearea(), null, $file->get_filepath(),
2238 $file->get_filename())->out(false);
2239 $files[] = array(
2240 'filename' => $file->get_filename(),
2241 'fileurl' => $fileurl,
2242 'filesize' => $file->get_filesize(),
2243 'filepath' => $file->get_filepath(),
2244 'mimetype' => $file->get_mimetype(),
2245 'timemodified' => $file->get_timemodified(),
2249 // Retrieve the course contacts,
2250 // we need here the users fullname since if we are not enrolled can be difficult to obtain them via other Web Services.
2251 $coursecontacts = array();
2252 foreach ($course->get_course_contacts() as $contact) {
2253 $coursecontacts[] = array(
2254 'id' => $contact['user']->id,
2255 'fullname' => $contact['username']
2259 // Allowed enrolment methods (maybe we can self-enrol).
2260 $enroltypes = array();
2261 $instances = enrol_get_instances($course->id, true);
2262 foreach ($instances as $instance) {
2263 $enroltypes[] = $instance->enrol;
2266 // Format summary.
2267 list($summary, $summaryformat) =
2268 external_format_text($course->summary, $course->summaryformat, $coursecontext->id, 'course', 'summary', null);
2270 $displayname = get_course_display_name_for_list($course);
2271 $coursereturns = array();
2272 $coursereturns['id'] = $course->id;
2273 $coursereturns['fullname'] = external_format_string($course->fullname, $coursecontext->id);
2274 $coursereturns['displayname'] = external_format_string($displayname, $coursecontext->id);
2275 $coursereturns['shortname'] = external_format_string($course->shortname, $coursecontext->id);
2276 $coursereturns['categoryid'] = $course->category;
2277 $coursereturns['categoryname'] = $category == null ? '' : $category->name;
2278 $coursereturns['summary'] = $summary;
2279 $coursereturns['summaryformat'] = $summaryformat;
2280 $coursereturns['summaryfiles'] = external_util::get_area_files($coursecontext->id, 'course', 'summary', false, false);
2281 $coursereturns['overviewfiles'] = $files;
2282 $coursereturns['contacts'] = $coursecontacts;
2283 $coursereturns['enrollmentmethods'] = $enroltypes;
2284 $coursereturns['sortorder'] = $course->sortorder;
2285 return $coursereturns;
2289 * Search courses following the specified criteria.
2291 * @param string $criterianame Criteria name (search, modulelist (only admins), blocklist (only admins), tagid)
2292 * @param string $criteriavalue Criteria value
2293 * @param int $page Page number (for pagination)
2294 * @param int $perpage Items per page
2295 * @param array $requiredcapabilities Optional list of required capabilities (used to filter the list).
2296 * @param int $limittoenrolled Limit to only enrolled courses
2297 * @return array of course objects and warnings
2298 * @since Moodle 3.0
2299 * @throws moodle_exception
2301 public static function search_courses($criterianame,
2302 $criteriavalue,
2303 $page=0,
2304 $perpage=0,
2305 $requiredcapabilities=array(),
2306 $limittoenrolled=0) {
2307 global $CFG;
2308 require_once($CFG->libdir . '/coursecatlib.php');
2310 $warnings = array();
2312 $parameters = array(
2313 'criterianame' => $criterianame,
2314 'criteriavalue' => $criteriavalue,
2315 'page' => $page,
2316 'perpage' => $perpage,
2317 'requiredcapabilities' => $requiredcapabilities
2319 $params = self::validate_parameters(self::search_courses_parameters(), $parameters);
2320 self::validate_context(context_system::instance());
2322 $allowedcriterianames = array('search', 'modulelist', 'blocklist', 'tagid');
2323 if (!in_array($params['criterianame'], $allowedcriterianames)) {
2324 throw new invalid_parameter_exception('Invalid value for criterianame parameter (value: '.$params['criterianame'].'),' .
2325 'allowed values are: '.implode(',', $allowedcriterianames));
2328 if ($params['criterianame'] == 'modulelist' or $params['criterianame'] == 'blocklist') {
2329 require_capability('moodle/site:config', context_system::instance());
2332 $paramtype = array(
2333 'search' => PARAM_RAW,
2334 'modulelist' => PARAM_PLUGIN,
2335 'blocklist' => PARAM_INT,
2336 'tagid' => PARAM_INT
2338 $params['criteriavalue'] = clean_param($params['criteriavalue'], $paramtype[$params['criterianame']]);
2340 // Prepare the search API options.
2341 $searchcriteria = array();
2342 $searchcriteria[$params['criterianame']] = $params['criteriavalue'];
2344 $options = array();
2345 if ($params['perpage'] != 0) {
2346 $offset = $params['page'] * $params['perpage'];
2347 $options = array('offset' => $offset, 'limit' => $params['perpage']);
2350 // Search the courses.
2351 $courses = coursecat::search_courses($searchcriteria, $options, $params['requiredcapabilities']);
2352 $totalcount = coursecat::search_courses_count($searchcriteria, $options, $params['requiredcapabilities']);
2354 if (!empty($limittoenrolled)) {
2355 // Get the courses where the current user has access.
2356 $enrolled = enrol_get_my_courses(array('id', 'cacherev'));
2359 $finalcourses = array();
2360 $categoriescache = array();
2362 foreach ($courses as $course) {
2363 if (!empty($limittoenrolled)) {
2364 // Filter out not enrolled courses.
2365 if (!isset($enrolled[$course->id])) {
2366 $totalcount--;
2367 continue;
2371 $coursecontext = context_course::instance($course->id);
2373 $finalcourses[] = self::get_course_public_information($course, $coursecontext);
2376 return array(
2377 'total' => $totalcount,
2378 'courses' => $finalcourses,
2379 'warnings' => $warnings
2384 * Returns a course structure definition
2386 * @param boolean $onlypublicdata set to true, to retrieve only fields viewable by anyone when the course is visible
2387 * @return array the course structure
2388 * @since Moodle 3.2
2390 protected static function get_course_structure($onlypublicdata = true) {
2391 $coursestructure = array(
2392 'id' => new external_value(PARAM_INT, 'course id'),
2393 'fullname' => new external_value(PARAM_TEXT, 'course full name'),
2394 'displayname' => new external_value(PARAM_TEXT, 'course display name'),
2395 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
2396 'categoryid' => new external_value(PARAM_INT, 'category id'),
2397 'categoryname' => new external_value(PARAM_TEXT, 'category name'),
2398 'sortorder' => new external_value(PARAM_INT, 'Sort order in the category', VALUE_OPTIONAL),
2399 'summary' => new external_value(PARAM_RAW, 'summary'),
2400 'summaryformat' => new external_format_value('summary'),
2401 'summaryfiles' => new external_files('summary files in the summary field', VALUE_OPTIONAL),
2402 'overviewfiles' => new external_files('additional overview files attached to this course'),
2403 'contacts' => new external_multiple_structure(
2404 new external_single_structure(
2405 array(
2406 'id' => new external_value(PARAM_INT, 'contact user id'),
2407 'fullname' => new external_value(PARAM_NOTAGS, 'contact user fullname'),
2410 'contact users'
2412 'enrollmentmethods' => new external_multiple_structure(
2413 new external_value(PARAM_PLUGIN, 'enrollment method'),
2414 'enrollment methods list'
2418 if (!$onlypublicdata) {
2419 $extra = array(
2420 'idnumber' => new external_value(PARAM_RAW, 'Id number', VALUE_OPTIONAL),
2421 'format' => new external_value(PARAM_PLUGIN, 'Course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
2422 'showgrades' => new external_value(PARAM_INT, '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
2423 'newsitems' => new external_value(PARAM_INT, 'Number of recent items appearing on the course page', VALUE_OPTIONAL),
2424 'startdate' => new external_value(PARAM_INT, 'Timestamp when the course start', VALUE_OPTIONAL),
2425 'enddate' => new external_value(PARAM_INT, 'Timestamp when the course end', VALUE_OPTIONAL),
2426 'maxbytes' => new external_value(PARAM_INT, 'Largest size of file that can be uploaded into', VALUE_OPTIONAL),
2427 'showreports' => new external_value(PARAM_INT, 'Are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
2428 'visible' => new external_value(PARAM_INT, '1: available to student, 0:not available', VALUE_OPTIONAL),
2429 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
2430 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
2431 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
2432 'enablecompletion' => new external_value(PARAM_INT, 'Completion enabled? 1: yes 0: no', VALUE_OPTIONAL),
2433 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
2434 'lang' => new external_value(PARAM_SAFEDIR, 'Forced course language', VALUE_OPTIONAL),
2435 'theme' => new external_value(PARAM_PLUGIN, 'Fame of the forced theme', VALUE_OPTIONAL),
2436 'marker' => new external_value(PARAM_INT, 'Current course marker', VALUE_OPTIONAL),
2437 'legacyfiles' => new external_value(PARAM_INT, 'If legacy files are enabled', VALUE_OPTIONAL),
2438 'calendartype' => new external_value(PARAM_PLUGIN, 'Calendar type', VALUE_OPTIONAL),
2439 'timecreated' => new external_value(PARAM_INT, 'Time when the course was created', VALUE_OPTIONAL),
2440 'timemodified' => new external_value(PARAM_INT, 'Last time the course was updated', VALUE_OPTIONAL),
2441 'requested' => new external_value(PARAM_INT, 'If is a requested course', VALUE_OPTIONAL),
2442 'cacherev' => new external_value(PARAM_INT, 'Cache revision number', VALUE_OPTIONAL),
2443 'filters' => new external_multiple_structure(
2444 new external_single_structure(
2445 array(
2446 'filter' => new external_value(PARAM_PLUGIN, 'Filter plugin name'),
2447 'localstate' => new external_value(PARAM_INT, 'Filter state: 1 for on, -1 for off, 0 if inherit'),
2448 'inheritedstate' => new external_value(PARAM_INT, '1 or 0 to use when localstate is set to inherit'),
2451 'Course filters', VALUE_OPTIONAL
2454 $coursestructure = array_merge($coursestructure, $extra);
2456 return new external_single_structure($coursestructure);
2460 * Returns description of method result value
2462 * @return external_description
2463 * @since Moodle 3.0
2465 public static function search_courses_returns() {
2466 return new external_single_structure(
2467 array(
2468 'total' => new external_value(PARAM_INT, 'total course count'),
2469 'courses' => new external_multiple_structure(self::get_course_structure(), 'course'),
2470 'warnings' => new external_warnings()
2476 * Returns description of method parameters
2478 * @return external_function_parameters
2479 * @since Moodle 3.0
2481 public static function get_course_module_parameters() {
2482 return new external_function_parameters(
2483 array(
2484 'cmid' => new external_value(PARAM_INT, 'The course module id')
2490 * Return information about a course module.
2492 * @param int $cmid the course module id
2493 * @return array of warnings and the course module
2494 * @since Moodle 3.0
2495 * @throws moodle_exception
2497 public static function get_course_module($cmid) {
2498 global $CFG, $DB;
2500 $params = self::validate_parameters(self::get_course_module_parameters(), array('cmid' => $cmid));
2501 $warnings = array();
2503 $cm = get_coursemodule_from_id(null, $params['cmid'], 0, true, MUST_EXIST);
2504 $context = context_module::instance($cm->id);
2505 self::validate_context($context);
2507 // If the user has permissions to manage the activity, return all the information.
2508 if (has_capability('moodle/course:manageactivities', $context)) {
2509 require_once($CFG->dirroot . '/course/modlib.php');
2510 require_once($CFG->libdir . '/gradelib.php');
2512 $info = $cm;
2513 // Get the extra information: grade, advanced grading and outcomes data.
2514 $course = get_course($cm->course);
2515 list($newcm, $newcontext, $module, $extrainfo, $cw) = get_moduleinfo_data($cm, $course);
2516 // Grades.
2517 $gradeinfo = array('grade', 'gradepass', 'gradecat');
2518 foreach ($gradeinfo as $gfield) {
2519 if (isset($extrainfo->{$gfield})) {
2520 $info->{$gfield} = $extrainfo->{$gfield};
2523 if (isset($extrainfo->grade) and $extrainfo->grade < 0) {
2524 $info->scale = $DB->get_field('scale', 'scale', array('id' => abs($extrainfo->grade)));
2526 // Advanced grading.
2527 if (isset($extrainfo->_advancedgradingdata)) {
2528 $info->advancedgrading = array();
2529 foreach ($extrainfo as $key => $val) {
2530 if (strpos($key, 'advancedgradingmethod_') === 0) {
2531 $info->advancedgrading[] = array(
2532 'area' => str_replace('advancedgradingmethod_', '', $key),
2533 'method' => $val
2538 // Outcomes.
2539 foreach ($extrainfo as $key => $val) {
2540 if (strpos($key, 'outcome_') === 0) {
2541 if (!isset($info->outcomes)) {
2542 $info->outcomes = array();
2544 $id = str_replace('outcome_', '', $key);
2545 $outcome = grade_outcome::fetch(array('id' => $id));
2546 $scaleitems = $outcome->load_scale();
2547 $info->outcomes[] = array(
2548 'id' => $id,
2549 'name' => external_format_string($outcome->get_name(), $context->id),
2550 'scale' => $scaleitems->scale
2554 } else {
2555 // Return information is safe to show to any user.
2556 $info = new stdClass();
2557 $info->id = $cm->id;
2558 $info->course = $cm->course;
2559 $info->module = $cm->module;
2560 $info->modname = $cm->modname;
2561 $info->instance = $cm->instance;
2562 $info->section = $cm->section;
2563 $info->sectionnum = $cm->sectionnum;
2564 $info->groupmode = $cm->groupmode;
2565 $info->groupingid = $cm->groupingid;
2566 $info->completion = $cm->completion;
2568 // Format name.
2569 $info->name = external_format_string($cm->name, $context->id);
2570 $result = array();
2571 $result['cm'] = $info;
2572 $result['warnings'] = $warnings;
2573 return $result;
2577 * Returns description of method result value
2579 * @return external_description
2580 * @since Moodle 3.0
2582 public static function get_course_module_returns() {
2583 return new external_single_structure(
2584 array(
2585 'cm' => new external_single_structure(
2586 array(
2587 'id' => new external_value(PARAM_INT, 'The course module id'),
2588 'course' => new external_value(PARAM_INT, 'The course id'),
2589 'module' => new external_value(PARAM_INT, 'The module type id'),
2590 'name' => new external_value(PARAM_RAW, 'The activity name'),
2591 'modname' => new external_value(PARAM_COMPONENT, 'The module component name (forum, assign, etc..)'),
2592 'instance' => new external_value(PARAM_INT, 'The activity instance id'),
2593 'section' => new external_value(PARAM_INT, 'The module section id'),
2594 'sectionnum' => new external_value(PARAM_INT, 'The module section number'),
2595 'groupmode' => new external_value(PARAM_INT, 'Group mode'),
2596 'groupingid' => new external_value(PARAM_INT, 'Grouping id'),
2597 'completion' => new external_value(PARAM_INT, 'If completion is enabled'),
2598 'idnumber' => new external_value(PARAM_RAW, 'Module id number', VALUE_OPTIONAL),
2599 'added' => new external_value(PARAM_INT, 'Time added', VALUE_OPTIONAL),
2600 'score' => new external_value(PARAM_INT, 'Score', VALUE_OPTIONAL),
2601 'indent' => new external_value(PARAM_INT, 'Indentation', VALUE_OPTIONAL),
2602 'visible' => new external_value(PARAM_INT, 'If visible', VALUE_OPTIONAL),
2603 'visibleoncoursepage' => new external_value(PARAM_INT, 'If visible on course page', VALUE_OPTIONAL),
2604 'visibleold' => new external_value(PARAM_INT, 'Visible old', VALUE_OPTIONAL),
2605 'completiongradeitemnumber' => new external_value(PARAM_INT, 'Completion grade item', VALUE_OPTIONAL),
2606 'completionview' => new external_value(PARAM_INT, 'Completion view setting', VALUE_OPTIONAL),
2607 'completionexpected' => new external_value(PARAM_INT, 'Completion time expected', VALUE_OPTIONAL),
2608 'showdescription' => new external_value(PARAM_INT, 'If the description is showed', VALUE_OPTIONAL),
2609 'availability' => new external_value(PARAM_RAW, 'Availability settings', VALUE_OPTIONAL),
2610 'grade' => new external_value(PARAM_INT, 'Grade (max value or scale id)', VALUE_OPTIONAL),
2611 'scale' => new external_value(PARAM_TEXT, 'Scale items (if used)', VALUE_OPTIONAL),
2612 'gradepass' => new external_value(PARAM_RAW, 'Grade to pass (float)', VALUE_OPTIONAL),
2613 'gradecat' => new external_value(PARAM_INT, 'Grade category', VALUE_OPTIONAL),
2614 'advancedgrading' => new external_multiple_structure(
2615 new external_single_structure(
2616 array(
2617 'area' => new external_value(PARAM_AREA, 'Gradable area name'),
2618 'method' => new external_value(PARAM_COMPONENT, 'Grading method'),
2621 'Advanced grading settings', VALUE_OPTIONAL
2623 'outcomes' => new external_multiple_structure(
2624 new external_single_structure(
2625 array(
2626 'id' => new external_value(PARAM_ALPHANUMEXT, 'Outcome id'),
2627 'name' => new external_value(PARAM_TEXT, 'Outcome full name'),
2628 'scale' => new external_value(PARAM_TEXT, 'Scale items')
2631 'Outcomes information', VALUE_OPTIONAL
2635 'warnings' => new external_warnings()
2641 * Returns description of method parameters
2643 * @return external_function_parameters
2644 * @since Moodle 3.0
2646 public static function get_course_module_by_instance_parameters() {
2647 return new external_function_parameters(
2648 array(
2649 'module' => new external_value(PARAM_COMPONENT, 'The module name'),
2650 'instance' => new external_value(PARAM_INT, 'The module instance id')
2656 * Return information about a course module.
2658 * @param string $module the module name
2659 * @param int $instance the activity instance id
2660 * @return array of warnings and the course module
2661 * @since Moodle 3.0
2662 * @throws moodle_exception
2664 public static function get_course_module_by_instance($module, $instance) {
2666 $params = self::validate_parameters(self::get_course_module_by_instance_parameters(),
2667 array(
2668 'module' => $module,
2669 'instance' => $instance,
2672 $warnings = array();
2673 $cm = get_coursemodule_from_instance($params['module'], $params['instance'], 0, false, MUST_EXIST);
2675 return self::get_course_module($cm->id);
2679 * Returns description of method result value
2681 * @return external_description
2682 * @since Moodle 3.0
2684 public static function get_course_module_by_instance_returns() {
2685 return self::get_course_module_returns();
2689 * Returns description of method parameters
2691 * @deprecated since 3.3
2692 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
2693 * @return external_function_parameters
2694 * @since Moodle 3.2
2696 public static function get_activities_overview_parameters() {
2697 return new external_function_parameters(
2698 array(
2699 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2705 * Return activities overview for the given courses.
2707 * @deprecated since 3.3
2708 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
2709 * @param array $courseids a list of course ids
2710 * @return array of warnings and the activities overview
2711 * @since Moodle 3.2
2712 * @throws moodle_exception
2714 public static function get_activities_overview($courseids) {
2715 global $USER;
2717 // Parameter validation.
2718 $params = self::validate_parameters(self::get_activities_overview_parameters(), array('courseids' => $courseids));
2719 $courseoverviews = array();
2721 list($courses, $warnings) = external_util::validate_courses($params['courseids']);
2723 if (!empty($courses)) {
2724 // Add lastaccess to each course (required by print_overview function).
2725 // We need the complete user data, the ws server does not load a complete one.
2726 $user = get_complete_user_data('id', $USER->id);
2727 foreach ($courses as $course) {
2728 if (isset($user->lastcourseaccess[$course->id])) {
2729 $course->lastaccess = $user->lastcourseaccess[$course->id];
2730 } else {
2731 $course->lastaccess = 0;
2735 $overviews = array();
2736 if ($modules = get_plugin_list_with_function('mod', 'print_overview')) {
2737 foreach ($modules as $fname) {
2738 $fname($courses, $overviews);
2742 // Format output.
2743 foreach ($overviews as $courseid => $modules) {
2744 $courseoverviews[$courseid]['id'] = $courseid;
2745 $courseoverviews[$courseid]['overviews'] = array();
2747 foreach ($modules as $modname => $overviewtext) {
2748 $courseoverviews[$courseid]['overviews'][] = array(
2749 'module' => $modname,
2750 'overviewtext' => $overviewtext // This text doesn't need formatting.
2756 $result = array(
2757 'courses' => $courseoverviews,
2758 'warnings' => $warnings
2760 return $result;
2764 * Returns description of method result value
2766 * @deprecated since 3.3
2767 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
2768 * @return external_description
2769 * @since Moodle 3.2
2771 public static function get_activities_overview_returns() {
2772 return new external_single_structure(
2773 array(
2774 'courses' => new external_multiple_structure(
2775 new external_single_structure(
2776 array(
2777 'id' => new external_value(PARAM_INT, 'Course id'),
2778 'overviews' => new external_multiple_structure(
2779 new external_single_structure(
2780 array(
2781 'module' => new external_value(PARAM_PLUGIN, 'Module name'),
2782 'overviewtext' => new external_value(PARAM_RAW, 'Overview text'),
2787 ), 'List of courses'
2789 'warnings' => new external_warnings()
2795 * Marking the method as deprecated.
2797 * @return bool
2799 public static function get_activities_overview_is_deprecated() {
2800 return true;
2804 * Returns description of method parameters
2806 * @return external_function_parameters
2807 * @since Moodle 3.2
2809 public static function get_user_navigation_options_parameters() {
2810 return new external_function_parameters(
2811 array(
2812 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2818 * Return a list of navigation options in a set of courses that are avaialable or not for the current user.
2820 * @param array $courseids a list of course ids
2821 * @return array of warnings and the options availability
2822 * @since Moodle 3.2
2823 * @throws moodle_exception
2825 public static function get_user_navigation_options($courseids) {
2826 global $CFG;
2827 require_once($CFG->dirroot . '/course/lib.php');
2829 // Parameter validation.
2830 $params = self::validate_parameters(self::get_user_navigation_options_parameters(), array('courseids' => $courseids));
2831 $courseoptions = array();
2833 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
2835 if (!empty($courses)) {
2836 foreach ($courses as $course) {
2837 // Fix the context for the frontpage.
2838 if ($course->id == SITEID) {
2839 $course->context = context_system::instance();
2841 $navoptions = course_get_user_navigation_options($course->context, $course);
2842 $options = array();
2843 foreach ($navoptions as $name => $available) {
2844 $options[] = array(
2845 'name' => $name,
2846 'available' => $available,
2850 $courseoptions[] = array(
2851 'id' => $course->id,
2852 'options' => $options
2857 $result = array(
2858 'courses' => $courseoptions,
2859 'warnings' => $warnings
2861 return $result;
2865 * Returns description of method result value
2867 * @return external_description
2868 * @since Moodle 3.2
2870 public static function get_user_navigation_options_returns() {
2871 return new external_single_structure(
2872 array(
2873 'courses' => new external_multiple_structure(
2874 new external_single_structure(
2875 array(
2876 'id' => new external_value(PARAM_INT, 'Course id'),
2877 'options' => new external_multiple_structure(
2878 new external_single_structure(
2879 array(
2880 'name' => new external_value(PARAM_ALPHANUMEXT, 'Option name'),
2881 'available' => new external_value(PARAM_BOOL, 'Whether the option is available or not'),
2886 ), 'List of courses'
2888 'warnings' => new external_warnings()
2894 * Returns description of method parameters
2896 * @return external_function_parameters
2897 * @since Moodle 3.2
2899 public static function get_user_administration_options_parameters() {
2900 return new external_function_parameters(
2901 array(
2902 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2908 * Return a list of administration options in a set of courses that are available or not for the current user.
2910 * @param array $courseids a list of course ids
2911 * @return array of warnings and the options availability
2912 * @since Moodle 3.2
2913 * @throws moodle_exception
2915 public static function get_user_administration_options($courseids) {
2916 global $CFG;
2917 require_once($CFG->dirroot . '/course/lib.php');
2919 // Parameter validation.
2920 $params = self::validate_parameters(self::get_user_administration_options_parameters(), array('courseids' => $courseids));
2921 $courseoptions = array();
2923 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
2925 if (!empty($courses)) {
2926 foreach ($courses as $course) {
2927 $adminoptions = course_get_user_administration_options($course, $course->context);
2928 $options = array();
2929 foreach ($adminoptions as $name => $available) {
2930 $options[] = array(
2931 'name' => $name,
2932 'available' => $available,
2936 $courseoptions[] = array(
2937 'id' => $course->id,
2938 'options' => $options
2943 $result = array(
2944 'courses' => $courseoptions,
2945 'warnings' => $warnings
2947 return $result;
2951 * Returns description of method result value
2953 * @return external_description
2954 * @since Moodle 3.2
2956 public static function get_user_administration_options_returns() {
2957 return self::get_user_navigation_options_returns();
2961 * Returns description of method parameters
2963 * @return external_function_parameters
2964 * @since Moodle 3.2
2966 public static function get_courses_by_field_parameters() {
2967 return new external_function_parameters(
2968 array(
2969 'field' => new external_value(PARAM_ALPHA, 'The field to search can be left empty for all courses or:
2970 id: course id
2971 ids: comma separated course ids
2972 shortname: course short name
2973 idnumber: course id number
2974 category: category id the course belongs to
2975 ', VALUE_DEFAULT, ''),
2976 'value' => new external_value(PARAM_RAW, 'The value to match', VALUE_DEFAULT, '')
2983 * Get courses matching a specific field (id/s, shortname, idnumber, category)
2985 * @param string $field field name to search, or empty for all courses
2986 * @param string $value value to search
2987 * @return array list of courses and warnings
2988 * @throws invalid_parameter_exception
2989 * @since Moodle 3.2
2991 public static function get_courses_by_field($field = '', $value = '') {
2992 global $DB, $CFG;
2993 require_once($CFG->libdir . '/coursecatlib.php');
2994 require_once($CFG->libdir . '/filterlib.php');
2996 $params = self::validate_parameters(self::get_courses_by_field_parameters(),
2997 array(
2998 'field' => $field,
2999 'value' => $value,
3002 $warnings = array();
3004 if (empty($params['field'])) {
3005 $courses = $DB->get_records('course', null, 'id ASC');
3006 } else {
3007 switch ($params['field']) {
3008 case 'id':
3009 case 'category':
3010 $value = clean_param($params['value'], PARAM_INT);
3011 break;
3012 case 'ids':
3013 $value = clean_param($params['value'], PARAM_SEQUENCE);
3014 break;
3015 case 'shortname':
3016 $value = clean_param($params['value'], PARAM_TEXT);
3017 break;
3018 case 'idnumber':
3019 $value = clean_param($params['value'], PARAM_RAW);
3020 break;
3021 default:
3022 throw new invalid_parameter_exception('Invalid field name');
3025 if ($params['field'] === 'ids') {
3026 $courses = $DB->get_records_list('course', 'id', explode(',', $value), 'id ASC');
3027 } else {
3028 $courses = $DB->get_records('course', array($params['field'] => $value), 'id ASC');
3032 $coursesdata = array();
3033 foreach ($courses as $course) {
3034 $context = context_course::instance($course->id);
3035 $canupdatecourse = has_capability('moodle/course:update', $context);
3036 $canviewhiddencourses = has_capability('moodle/course:viewhiddencourses', $context);
3038 // Check if the course is visible in the site for the user.
3039 if (!$course->visible and !$canviewhiddencourses and !$canupdatecourse) {
3040 continue;
3042 // Get the public course information, even if we are not enrolled.
3043 $courseinlist = new course_in_list($course);
3044 $coursesdata[$course->id] = self::get_course_public_information($courseinlist, $context);
3046 // Now, check if we have access to the course.
3047 try {
3048 self::validate_context($context);
3049 } catch (Exception $e) {
3050 continue;
3052 // Return information for any user that can access the course.
3053 $coursefields = array('format', 'showgrades', 'newsitems', 'startdate', 'enddate', 'maxbytes', 'showreports', 'visible',
3054 'groupmode', 'groupmodeforce', 'defaultgroupingid', 'enablecompletion', 'completionnotify', 'lang', 'theme',
3055 'marker');
3057 // Course filters.
3058 $coursesdata[$course->id]['filters'] = filter_get_available_in_context($context);
3060 // Information for managers only.
3061 if ($canupdatecourse) {
3062 $managerfields = array('idnumber', 'legacyfiles', 'calendartype', 'timecreated', 'timemodified', 'requested',
3063 'cacherev');
3064 $coursefields = array_merge($coursefields, $managerfields);
3067 // Populate fields.
3068 foreach ($coursefields as $field) {
3069 $coursesdata[$course->id][$field] = $course->{$field};
3072 // Clean lang and auth fields for external functions (it may content uninstalled themes or language packs).
3073 if (isset($coursesdata[$course->id]['theme'])) {
3074 $coursesdata[$course->id]['theme'] = clean_param($coursesdata[$course->id]['theme'], PARAM_THEME);
3076 if (isset($coursesdata[$course->id]['lang'])) {
3077 $coursesdata[$course->id]['lang'] = clean_param($coursesdata[$course->id]['lang'], PARAM_LANG);
3081 return array(
3082 'courses' => $coursesdata,
3083 'warnings' => $warnings
3088 * Returns description of method result value
3090 * @return external_description
3091 * @since Moodle 3.2
3093 public static function get_courses_by_field_returns() {
3094 // Course structure, including not only public viewable fields.
3095 return new external_single_structure(
3096 array(
3097 'courses' => new external_multiple_structure(self::get_course_structure(false), 'Course'),
3098 'warnings' => new external_warnings()
3104 * Returns description of method parameters
3106 * @return external_function_parameters
3107 * @since Moodle 3.2
3109 public static function check_updates_parameters() {
3110 return new external_function_parameters(
3111 array(
3112 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3113 'tocheck' => new external_multiple_structure(
3114 new external_single_structure(
3115 array(
3116 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level for the file location.
3117 Only module supported right now.'),
3118 'id' => new external_value(PARAM_INT, 'Context instance id'),
3119 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3122 'Instances to check'
3124 'filter' => new external_multiple_structure(
3125 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3126 gradeitems, outcomes'),
3127 'Check only for updates in these areas', VALUE_DEFAULT, array()
3134 * Check if there is updates affecting the user for the given course and contexts.
3135 * Right now only modules are supported.
3136 * This WS calls mod_check_updates_since for each module to check if there is any update the user should we aware of.
3138 * @param int $courseid the list of modules to check
3139 * @param array $tocheck the list of modules to check
3140 * @param array $filter check only for updates in these areas
3141 * @return array list of updates and warnings
3142 * @throws moodle_exception
3143 * @since Moodle 3.2
3145 public static function check_updates($courseid, $tocheck, $filter = array()) {
3146 global $CFG, $DB;
3147 require_once($CFG->dirroot . "/course/lib.php");
3149 $params = self::validate_parameters(
3150 self::check_updates_parameters(),
3151 array(
3152 'courseid' => $courseid,
3153 'tocheck' => $tocheck,
3154 'filter' => $filter,
3158 $course = get_course($params['courseid']);
3159 $context = context_course::instance($course->id);
3160 self::validate_context($context);
3162 list($instances, $warnings) = course_check_updates($course, $params['tocheck'], $filter);
3164 $instancesformatted = array();
3165 foreach ($instances as $instance) {
3166 $updates = array();
3167 foreach ($instance['updates'] as $name => $data) {
3168 if (empty($data->updated)) {
3169 continue;
3171 $updatedata = array(
3172 'name' => $name,
3174 if (!empty($data->timeupdated)) {
3175 $updatedata['timeupdated'] = $data->timeupdated;
3177 if (!empty($data->itemids)) {
3178 $updatedata['itemids'] = $data->itemids;
3180 $updates[] = $updatedata;
3182 if (!empty($updates)) {
3183 $instancesformatted[] = array(
3184 'contextlevel' => $instance['contextlevel'],
3185 'id' => $instance['id'],
3186 'updates' => $updates
3191 return array(
3192 'instances' => $instancesformatted,
3193 'warnings' => $warnings
3198 * Returns description of method result value
3200 * @return external_description
3201 * @since Moodle 3.2
3203 public static function check_updates_returns() {
3204 return new external_single_structure(
3205 array(
3206 'instances' => new external_multiple_structure(
3207 new external_single_structure(
3208 array(
3209 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level'),
3210 'id' => new external_value(PARAM_INT, 'Instance id'),
3211 'updates' => new external_multiple_structure(
3212 new external_single_structure(
3213 array(
3214 'name' => new external_value(PARAM_ALPHANUMEXT, 'Name of the area updated.'),
3215 'timeupdated' => new external_value(PARAM_INT, 'Last time was updated', VALUE_OPTIONAL),
3216 'itemids' => new external_multiple_structure(
3217 new external_value(PARAM_INT, 'Instance id'),
3218 'The ids of the items updated',
3219 VALUE_OPTIONAL
3227 'warnings' => new external_warnings()
3233 * Returns description of method parameters
3235 * @return external_function_parameters
3236 * @since Moodle 3.3
3238 public static function get_updates_since_parameters() {
3239 return new external_function_parameters(
3240 array(
3241 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3242 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3243 'filter' => new external_multiple_structure(
3244 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3245 gradeitems, outcomes'),
3246 'Check only for updates in these areas', VALUE_DEFAULT, array()
3253 * Check if there are updates affecting the user for the given course since the given time stamp.
3255 * This function is a wrapper of self::check_updates for retrieving all the updates since a given time for all the activities.
3257 * @param int $courseid the list of modules to check
3258 * @param int $since check updates since this time stamp
3259 * @param array $filter check only for updates in these areas
3260 * @return array list of updates and warnings
3261 * @throws moodle_exception
3262 * @since Moodle 3.3
3264 public static function get_updates_since($courseid, $since, $filter = array()) {
3265 global $CFG, $DB;
3267 $params = self::validate_parameters(
3268 self::get_updates_since_parameters(),
3269 array(
3270 'courseid' => $courseid,
3271 'since' => $since,
3272 'filter' => $filter,
3276 $course = get_course($params['courseid']);
3277 $modinfo = get_fast_modinfo($course);
3278 $tocheck = array();
3280 // Retrieve all the visible course modules for the current user.
3281 $cms = $modinfo->get_cms();
3282 foreach ($cms as $cm) {
3283 if (!$cm->uservisible) {
3284 continue;
3286 $tocheck[] = array(
3287 'id' => $cm->id,
3288 'contextlevel' => 'module',
3289 'since' => $params['since'],
3293 return self::check_updates($course->id, $tocheck, $params['filter']);
3297 * Returns description of method result value
3299 * @return external_description
3300 * @since Moodle 3.3
3302 public static function get_updates_since_returns() {
3303 return self::check_updates_returns();
3307 * Parameters for function edit_module()
3309 * @since Moodle 3.3
3310 * @return external_function_parameters
3312 public static function edit_module_parameters() {
3313 return new external_function_parameters(
3314 array(
3315 'action' => new external_value(PARAM_ALPHA,
3316 'action: hide, show, stealth, duplicate, delete, moveleft, moveright, group...', VALUE_REQUIRED),
3317 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3318 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3323 * Performs one of the edit module actions and return new html for AJAX
3325 * Returns html to replace the current module html with, for example:
3326 * - empty string for "delete" action,
3327 * - two modules html for "duplicate" action
3328 * - updated module html for everything else
3330 * Throws exception if operation is not permitted/possible
3332 * @since Moodle 3.3
3333 * @param string $action
3334 * @param int $id
3335 * @param null|int $sectionreturn
3336 * @return string
3338 public static function edit_module($action, $id, $sectionreturn = null) {
3339 global $PAGE, $DB;
3340 // Validate and normalize parameters.
3341 $params = self::validate_parameters(self::edit_module_parameters(),
3342 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3343 $action = $params['action'];
3344 $id = $params['id'];
3345 $sectionreturn = $params['sectionreturn'];
3347 list($course, $cm) = get_course_and_cm_from_cmid($id);
3348 $modcontext = context_module::instance($cm->id);
3349 $coursecontext = context_course::instance($course->id);
3350 self::validate_context($modcontext);
3351 $courserenderer = $PAGE->get_renderer('core', 'course');
3352 $completioninfo = new completion_info($course);
3354 switch($action) {
3355 case 'hide':
3356 case 'show':
3357 case 'stealth':
3358 require_capability('moodle/course:activityvisibility', $modcontext);
3359 $visible = ($action === 'hide') ? 0 : 1;
3360 $visibleoncoursepage = ($action === 'stealth') ? 0 : 1;
3361 set_coursemodule_visible($id, $visible, $visibleoncoursepage);
3362 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3363 break;
3364 case 'duplicate':
3365 require_capability('moodle/course:manageactivities', $coursecontext);
3366 require_capability('moodle/backup:backuptargetimport', $coursecontext);
3367 require_capability('moodle/restore:restoretargetimport', $coursecontext);
3368 if (!course_allowed_module($course, $cm->modname)) {
3369 throw new moodle_exception('No permission to create that activity');
3371 if ($newcm = duplicate_module($course, $cm)) {
3372 $cm = get_fast_modinfo($course)->get_cm($id);
3373 $newcm = get_fast_modinfo($course)->get_cm($newcm->id);
3374 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn) .
3375 $courserenderer->course_section_cm_list_item($course, $completioninfo, $newcm, $sectionreturn);
3377 break;
3378 case 'groupsseparate':
3379 case 'groupsvisible':
3380 case 'groupsnone':
3381 require_capability('moodle/course:manageactivities', $modcontext);
3382 if ($action === 'groupsseparate') {
3383 $newgroupmode = SEPARATEGROUPS;
3384 } else if ($action === 'groupsvisible') {
3385 $newgroupmode = VISIBLEGROUPS;
3386 } else {
3387 $newgroupmode = NOGROUPS;
3389 if (set_coursemodule_groupmode($cm->id, $newgroupmode)) {
3390 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3392 break;
3393 case 'moveleft':
3394 case 'moveright':
3395 require_capability('moodle/course:manageactivities', $modcontext);
3396 $indent = $cm->indent + (($action === 'moveright') ? 1 : -1);
3397 if ($cm->indent >= 0) {
3398 $DB->update_record('course_modules', array('id' => $cm->id, 'indent' => $indent));
3399 rebuild_course_cache($cm->course);
3401 break;
3402 case 'delete':
3403 require_capability('moodle/course:manageactivities', $modcontext);
3404 course_delete_module($cm->id, true);
3405 return '';
3406 default:
3407 throw new coding_exception('Unrecognised action');
3410 $cm = get_fast_modinfo($course)->get_cm($id);
3411 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn);
3415 * Return structure for edit_module()
3417 * @since Moodle 3.3
3418 * @return external_description
3420 public static function edit_module_returns() {
3421 return new external_value(PARAM_RAW, 'html to replace the current module with');
3425 * Parameters for function get_module()
3427 * @since Moodle 3.3
3428 * @return external_function_parameters
3430 public static function get_module_parameters() {
3431 return new external_function_parameters(
3432 array(
3433 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3434 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3439 * Returns html for displaying one activity module on course page
3441 * @since Moodle 3.3
3442 * @param int $id
3443 * @param null|int $sectionreturn
3444 * @return string
3446 public static function get_module($id, $sectionreturn = null) {
3447 global $PAGE;
3448 // Validate and normalize parameters.
3449 $params = self::validate_parameters(self::get_module_parameters(),
3450 array('id' => $id, 'sectionreturn' => $sectionreturn));
3451 $id = $params['id'];
3452 $sectionreturn = $params['sectionreturn'];
3454 // Validate access to the course (note, this is html for the course view page, we don't validate access to the module).
3455 list($course, $cm) = get_course_and_cm_from_cmid($id);
3456 self::validate_context(context_course::instance($course->id));
3458 $courserenderer = $PAGE->get_renderer('core', 'course');
3459 $completioninfo = new completion_info($course);
3460 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn);
3464 * Return structure for edit_module()
3466 * @since Moodle 3.3
3467 * @return external_description
3469 public static function get_module_returns() {
3470 return new external_value(PARAM_RAW, 'html to replace the current module with');
3474 * Parameters for function edit_section()
3476 * @since Moodle 3.3
3477 * @return external_function_parameters
3479 public static function edit_section_parameters() {
3480 return new external_function_parameters(
3481 array(
3482 'action' => new external_value(PARAM_ALPHA, 'action: hide, show, stealth, setmarker, removemarker', VALUE_REQUIRED),
3483 'id' => new external_value(PARAM_INT, 'course section id', VALUE_REQUIRED),
3484 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3489 * Performs one of the edit section actions
3491 * @since Moodle 3.3
3492 * @param string $action
3493 * @param int $id section id
3494 * @param int $sectionreturn section to return to
3495 * @return string
3497 public static function edit_section($action, $id, $sectionreturn) {
3498 global $DB;
3499 // Validate and normalize parameters.
3500 $params = self::validate_parameters(self::edit_section_parameters(),
3501 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3502 $action = $params['action'];
3503 $id = $params['id'];
3504 $sr = $params['sectionreturn'];
3506 $section = $DB->get_record('course_sections', array('id' => $id), '*', MUST_EXIST);
3507 $coursecontext = context_course::instance($section->course);
3508 self::validate_context($coursecontext);
3510 $rv = course_get_format($section->course)->section_action($section, $action, $sectionreturn);
3511 if ($rv) {
3512 return json_encode($rv);
3513 } else {
3514 return null;
3519 * Return structure for edit_section()
3521 * @since Moodle 3.3
3522 * @return external_description
3524 public static function edit_section_returns() {
3525 return new external_value(PARAM_RAW, 'Additional data for javascript (JSON-encoded string)');