Merge branch 'wip-MDL-57769-master' of https://github.com/marinaglancy/moodle
[moodle.git] / course / externallib.php
blob01deee981ec79ede9c9c37db35a40c958a4f527a
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 if (!$section->uservisible) {
170 continue;
173 // This becomes true when we are filtering and we found the value to filter with.
174 $sectionfound = false;
176 // Filter by section id.
177 if (!empty($filters['sectionid'])) {
178 if ($section->id != $filters['sectionid']) {
179 continue;
180 } else {
181 $sectionfound = true;
185 // Filter by section number. Note that 0 is a valid section number.
186 if (isset($filters['sectionnumber'])) {
187 if ($key != $filters['sectionnumber']) {
188 continue;
189 } else {
190 $sectionfound = true;
194 // reset $sectioncontents
195 $sectionvalues = array();
196 $sectionvalues['id'] = $section->id;
197 $sectionvalues['name'] = get_section_name($course, $section);
198 $sectionvalues['visible'] = $section->visible;
200 $options = (object) array('noclean' => true);
201 list($sectionvalues['summary'], $sectionvalues['summaryformat']) =
202 external_format_text($section->summary, $section->summaryformat,
203 $context->id, 'course', 'section', $section->id, $options);
204 $sectionvalues['section'] = $section->section;
205 $sectionvalues['hiddenbynumsections'] = $section->section > $coursenumsections ? 1 : 0;
206 $sectioncontents = array();
208 //for each module of the section
209 if (empty($filters['excludemodules']) and !empty($modinfosections[$section->section])) {
210 foreach ($modinfosections[$section->section] as $cmid) {
211 $cm = $modinfo->cms[$cmid];
213 // stop here if the module is not visible to the user
214 if (!$cm->uservisible) {
215 continue;
218 // This becomes true when we are filtering and we found the value to filter with.
219 $modfound = false;
221 // Filter by cmid.
222 if (!empty($filters['cmid'])) {
223 if ($cmid != $filters['cmid']) {
224 continue;
225 } else {
226 $modfound = true;
230 // Filter by module name and id.
231 if (!empty($filters['modname'])) {
232 if ($cm->modname != $filters['modname']) {
233 continue;
234 } else if (!empty($filters['modid'])) {
235 if ($cm->instance != $filters['modid']) {
236 continue;
237 } else {
238 // Note that if we are only filtering by modname we don't break the loop.
239 $modfound = true;
244 $module = array();
246 $modcontext = context_module::instance($cm->id);
248 //common info (for people being able to see the module or availability dates)
249 $module['id'] = $cm->id;
250 $module['name'] = external_format_string($cm->name, $modcontext->id);
251 $module['instance'] = $cm->instance;
252 $module['modname'] = $cm->modname;
253 $module['modplural'] = $cm->modplural;
254 $module['modicon'] = $cm->get_icon_url()->out(false);
255 $module['indent'] = $cm->indent;
257 if (!empty($cm->showdescription) or $cm->modname == 'label') {
258 // We want to use the external format. However from reading get_formatted_content(), $cm->content format is always FORMAT_HTML.
259 list($module['description'], $descriptionformat) = external_format_text($cm->content,
260 FORMAT_HTML, $modcontext->id, $cm->modname, 'intro', $cm->id);
263 //url of the module
264 $url = $cm->url;
265 if ($url) { //labels don't have url
266 $module['url'] = $url->out(false);
269 $canviewhidden = has_capability('moodle/course:viewhiddenactivities',
270 context_module::instance($cm->id));
271 //user that can view hidden module should know about the visibility
272 $module['visible'] = $cm->visible;
273 $module['visibleoncoursepage'] = $cm->visibleoncoursepage;
275 // Availability date (also send to user who can see hidden module).
276 if ($CFG->enableavailability && ($canviewhidden || $canupdatecourse)) {
277 $module['availability'] = $cm->availability;
280 $baseurl = 'webservice/pluginfile.php';
282 //call $modulename_export_contents
283 //(each module callback take care about checking the capabilities)
285 require_once($CFG->dirroot . '/mod/' . $cm->modname . '/lib.php');
286 $getcontentfunction = $cm->modname.'_export_contents';
287 if (function_exists($getcontentfunction)) {
288 if (empty($filters['excludecontents']) and $contents = $getcontentfunction($cm, $baseurl)) {
289 $module['contents'] = $contents;
290 } else {
291 $module['contents'] = array();
295 //assign result to $sectioncontents
296 $sectioncontents[] = $module;
298 // If we just did a filtering, break the loop.
299 if ($modfound) {
300 break;
305 $sectionvalues['modules'] = $sectioncontents;
307 // assign result to $coursecontents
308 $coursecontents[] = $sectionvalues;
310 // Break the loop if we are filtering.
311 if ($sectionfound) {
312 break;
316 return $coursecontents;
320 * Returns description of method result value
322 * @return external_description
323 * @since Moodle 2.2
325 public static function get_course_contents_returns() {
326 return new external_multiple_structure(
327 new external_single_structure(
328 array(
329 'id' => new external_value(PARAM_INT, 'Section ID'),
330 'name' => new external_value(PARAM_TEXT, 'Section name'),
331 'visible' => new external_value(PARAM_INT, 'is the section visible', VALUE_OPTIONAL),
332 'summary' => new external_value(PARAM_RAW, 'Section description'),
333 'summaryformat' => new external_format_value('summary'),
334 'section' => new external_value(PARAM_INT, 'Section number inside the course', VALUE_OPTIONAL),
335 'hiddenbynumsections' => new external_value(PARAM_INT, 'Whether is a section hidden in the course format',
336 VALUE_OPTIONAL),
337 'modules' => new external_multiple_structure(
338 new external_single_structure(
339 array(
340 'id' => new external_value(PARAM_INT, 'activity id'),
341 'url' => new external_value(PARAM_URL, 'activity url', VALUE_OPTIONAL),
342 'name' => new external_value(PARAM_RAW, 'activity module name'),
343 'instance' => new external_value(PARAM_INT, 'instance id', VALUE_OPTIONAL),
344 'description' => new external_value(PARAM_RAW, 'activity description', VALUE_OPTIONAL),
345 'visible' => new external_value(PARAM_INT, 'is the module visible', VALUE_OPTIONAL),
346 'visibleoncoursepage' => new external_value(PARAM_INT, 'is the module visible on course page',
347 VALUE_OPTIONAL),
348 'modicon' => new external_value(PARAM_URL, 'activity icon url'),
349 'modname' => new external_value(PARAM_PLUGIN, 'activity module type'),
350 'modplural' => new external_value(PARAM_TEXT, 'activity module plural name'),
351 'availability' => new external_value(PARAM_RAW, 'module availability settings', VALUE_OPTIONAL),
352 'indent' => new external_value(PARAM_INT, 'number of identation in the site'),
353 'contents' => new external_multiple_structure(
354 new external_single_structure(
355 array(
356 // content info
357 'type'=> new external_value(PARAM_TEXT, 'a file or a folder or external link'),
358 'filename'=> new external_value(PARAM_FILE, 'filename'),
359 'filepath'=> new external_value(PARAM_PATH, 'filepath'),
360 'filesize'=> new external_value(PARAM_INT, 'filesize'),
361 'fileurl' => new external_value(PARAM_URL, 'downloadable file url', VALUE_OPTIONAL),
362 'content' => new external_value(PARAM_RAW, 'Raw content, will be used when type is content', VALUE_OPTIONAL),
363 'timecreated' => new external_value(PARAM_INT, 'Time created'),
364 'timemodified' => new external_value(PARAM_INT, 'Time modified'),
365 'sortorder' => new external_value(PARAM_INT, 'Content sort order'),
367 // copyright related info
368 'userid' => new external_value(PARAM_INT, 'User who added this content to moodle'),
369 'author' => new external_value(PARAM_TEXT, 'Content owner'),
370 'license' => new external_value(PARAM_TEXT, 'Content license'),
372 ), VALUE_DEFAULT, array()
375 ), 'list of module'
383 * Returns description of method parameters
385 * @return external_function_parameters
386 * @since Moodle 2.3
388 public static function get_courses_parameters() {
389 return new external_function_parameters(
390 array('options' => new external_single_structure(
391 array('ids' => new external_multiple_structure(
392 new external_value(PARAM_INT, 'Course id')
393 , 'List of course id. If empty return all courses
394 except front page course.',
395 VALUE_OPTIONAL)
396 ), 'options - operator OR is used', VALUE_DEFAULT, array())
402 * Get courses
404 * @param array $options It contains an array (list of ids)
405 * @return array
406 * @since Moodle 2.2
408 public static function get_courses($options = array()) {
409 global $CFG, $DB;
410 require_once($CFG->dirroot . "/course/lib.php");
412 //validate parameter
413 $params = self::validate_parameters(self::get_courses_parameters(),
414 array('options' => $options));
416 //retrieve courses
417 if (!array_key_exists('ids', $params['options'])
418 or empty($params['options']['ids'])) {
419 $courses = $DB->get_records('course');
420 } else {
421 $courses = $DB->get_records_list('course', 'id', $params['options']['ids']);
424 //create return value
425 $coursesinfo = array();
426 foreach ($courses as $course) {
428 // now security checks
429 $context = context_course::instance($course->id, IGNORE_MISSING);
430 $courseformatoptions = course_get_format($course)->get_format_options();
431 try {
432 self::validate_context($context);
433 } catch (Exception $e) {
434 $exceptionparam = new stdClass();
435 $exceptionparam->message = $e->getMessage();
436 $exceptionparam->courseid = $course->id;
437 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
439 require_capability('moodle/course:view', $context);
441 $courseinfo = array();
442 $courseinfo['id'] = $course->id;
443 $courseinfo['fullname'] = external_format_string($course->fullname, $context->id);
444 $courseinfo['shortname'] = external_format_string($course->shortname, $context->id);
445 $courseinfo['displayname'] = external_format_string(get_course_display_name_for_list($course), $context->id);
446 $courseinfo['categoryid'] = $course->category;
447 list($courseinfo['summary'], $courseinfo['summaryformat']) =
448 external_format_text($course->summary, $course->summaryformat, $context->id, 'course', 'summary', 0);
449 $courseinfo['format'] = $course->format;
450 $courseinfo['startdate'] = $course->startdate;
451 $courseinfo['enddate'] = $course->enddate;
452 if (array_key_exists('numsections', $courseformatoptions)) {
453 // For backward-compartibility
454 $courseinfo['numsections'] = $courseformatoptions['numsections'];
457 //some field should be returned only if the user has update permission
458 $courseadmin = has_capability('moodle/course:update', $context);
459 if ($courseadmin) {
460 $courseinfo['categorysortorder'] = $course->sortorder;
461 $courseinfo['idnumber'] = $course->idnumber;
462 $courseinfo['showgrades'] = $course->showgrades;
463 $courseinfo['showreports'] = $course->showreports;
464 $courseinfo['newsitems'] = $course->newsitems;
465 $courseinfo['visible'] = $course->visible;
466 $courseinfo['maxbytes'] = $course->maxbytes;
467 if (array_key_exists('hiddensections', $courseformatoptions)) {
468 // For backward-compartibility
469 $courseinfo['hiddensections'] = $courseformatoptions['hiddensections'];
471 // Return numsections for backward-compatibility with clients who expect it.
472 $courseinfo['numsections'] = course_get_format($course)->get_last_section_number();
473 $courseinfo['groupmode'] = $course->groupmode;
474 $courseinfo['groupmodeforce'] = $course->groupmodeforce;
475 $courseinfo['defaultgroupingid'] = $course->defaultgroupingid;
476 $courseinfo['lang'] = $course->lang;
477 $courseinfo['timecreated'] = $course->timecreated;
478 $courseinfo['timemodified'] = $course->timemodified;
479 $courseinfo['forcetheme'] = $course->theme;
480 $courseinfo['enablecompletion'] = $course->enablecompletion;
481 $courseinfo['completionnotify'] = $course->completionnotify;
482 $courseinfo['courseformatoptions'] = array();
483 foreach ($courseformatoptions as $key => $value) {
484 $courseinfo['courseformatoptions'][] = array(
485 'name' => $key,
486 'value' => $value
491 if ($courseadmin or $course->visible
492 or has_capability('moodle/course:viewhiddencourses', $context)) {
493 $coursesinfo[] = $courseinfo;
497 return $coursesinfo;
501 * Returns description of method result value
503 * @return external_description
504 * @since Moodle 2.2
506 public static function get_courses_returns() {
507 return new external_multiple_structure(
508 new external_single_structure(
509 array(
510 'id' => new external_value(PARAM_INT, 'course id'),
511 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
512 'categoryid' => new external_value(PARAM_INT, 'category id'),
513 'categorysortorder' => new external_value(PARAM_INT,
514 'sort order into the category', VALUE_OPTIONAL),
515 'fullname' => new external_value(PARAM_TEXT, 'full name'),
516 'displayname' => new external_value(PARAM_TEXT, 'course display name'),
517 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
518 'summary' => new external_value(PARAM_RAW, 'summary'),
519 'summaryformat' => new external_format_value('summary'),
520 'format' => new external_value(PARAM_PLUGIN,
521 'course format: weeks, topics, social, site,..'),
522 'showgrades' => new external_value(PARAM_INT,
523 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
524 'newsitems' => new external_value(PARAM_INT,
525 'number of recent items appearing on the course page', VALUE_OPTIONAL),
526 'startdate' => new external_value(PARAM_INT,
527 'timestamp when the course start'),
528 'enddate' => new external_value(PARAM_INT,
529 'timestamp when the course end'),
530 'numsections' => new external_value(PARAM_INT,
531 '(deprecated, use courseformatoptions) number of weeks/topics',
532 VALUE_OPTIONAL),
533 'maxbytes' => new external_value(PARAM_INT,
534 'largest size of file that can be uploaded into the course',
535 VALUE_OPTIONAL),
536 'showreports' => new external_value(PARAM_INT,
537 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
538 'visible' => new external_value(PARAM_INT,
539 '1: available to student, 0:not available', VALUE_OPTIONAL),
540 'hiddensections' => new external_value(PARAM_INT,
541 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
542 VALUE_OPTIONAL),
543 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
544 VALUE_OPTIONAL),
545 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
546 VALUE_OPTIONAL),
547 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
548 VALUE_OPTIONAL),
549 'timecreated' => new external_value(PARAM_INT,
550 'timestamp when the course have been created', VALUE_OPTIONAL),
551 'timemodified' => new external_value(PARAM_INT,
552 'timestamp when the course have been modified', VALUE_OPTIONAL),
553 'enablecompletion' => new external_value(PARAM_INT,
554 'Enabled, control via completion and activity settings. Disbaled,
555 not shown in activity settings.',
556 VALUE_OPTIONAL),
557 'completionnotify' => new external_value(PARAM_INT,
558 '1: yes 0: no', VALUE_OPTIONAL),
559 'lang' => new external_value(PARAM_SAFEDIR,
560 'forced course language', VALUE_OPTIONAL),
561 'forcetheme' => new external_value(PARAM_PLUGIN,
562 'name of the force theme', VALUE_OPTIONAL),
563 'courseformatoptions' => new external_multiple_structure(
564 new external_single_structure(
565 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
566 'value' => new external_value(PARAM_RAW, 'course format option value')
568 'additional options for particular course format', VALUE_OPTIONAL
570 ), 'course'
576 * Returns description of method parameters
578 * @return external_function_parameters
579 * @since Moodle 2.2
581 public static function create_courses_parameters() {
582 $courseconfig = get_config('moodlecourse'); //needed for many default values
583 return new external_function_parameters(
584 array(
585 'courses' => new external_multiple_structure(
586 new external_single_structure(
587 array(
588 'fullname' => new external_value(PARAM_TEXT, 'full name'),
589 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
590 'categoryid' => new external_value(PARAM_INT, 'category id'),
591 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
592 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
593 'summaryformat' => new external_format_value('summary', VALUE_DEFAULT),
594 'format' => new external_value(PARAM_PLUGIN,
595 'course format: weeks, topics, social, site,..',
596 VALUE_DEFAULT, $courseconfig->format),
597 'showgrades' => new external_value(PARAM_INT,
598 '1 if grades are shown, otherwise 0', VALUE_DEFAULT,
599 $courseconfig->showgrades),
600 'newsitems' => new external_value(PARAM_INT,
601 'number of recent items appearing on the course page',
602 VALUE_DEFAULT, $courseconfig->newsitems),
603 'startdate' => new external_value(PARAM_INT,
604 'timestamp when the course start', VALUE_OPTIONAL),
605 'enddate' => new external_value(PARAM_INT,
606 'timestamp when the course end', VALUE_OPTIONAL),
607 'numsections' => new external_value(PARAM_INT,
608 '(deprecated, use courseformatoptions) number of weeks/topics',
609 VALUE_OPTIONAL),
610 'maxbytes' => new external_value(PARAM_INT,
611 'largest size of file that can be uploaded into the course',
612 VALUE_DEFAULT, $courseconfig->maxbytes),
613 'showreports' => new external_value(PARAM_INT,
614 'are activity report shown (yes = 1, no =0)', VALUE_DEFAULT,
615 $courseconfig->showreports),
616 'visible' => new external_value(PARAM_INT,
617 '1: available to student, 0:not available', VALUE_OPTIONAL),
618 'hiddensections' => new external_value(PARAM_INT,
619 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
620 VALUE_OPTIONAL),
621 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
622 VALUE_DEFAULT, $courseconfig->groupmode),
623 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
624 VALUE_DEFAULT, $courseconfig->groupmodeforce),
625 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
626 VALUE_DEFAULT, 0),
627 'enablecompletion' => new external_value(PARAM_INT,
628 'Enabled, control via completion and activity settings. Disabled,
629 not shown in activity settings.',
630 VALUE_OPTIONAL),
631 'completionnotify' => new external_value(PARAM_INT,
632 '1: yes 0: no', VALUE_OPTIONAL),
633 'lang' => new external_value(PARAM_SAFEDIR,
634 'forced course language', VALUE_OPTIONAL),
635 'forcetheme' => new external_value(PARAM_PLUGIN,
636 'name of the force theme', VALUE_OPTIONAL),
637 'courseformatoptions' => new external_multiple_structure(
638 new external_single_structure(
639 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
640 'value' => new external_value(PARAM_RAW, 'course format option value')
642 'additional options for particular course format', VALUE_OPTIONAL),
644 ), 'courses to create'
651 * Create courses
653 * @param array $courses
654 * @return array courses (id and shortname only)
655 * @since Moodle 2.2
657 public static function create_courses($courses) {
658 global $CFG, $DB;
659 require_once($CFG->dirroot . "/course/lib.php");
660 require_once($CFG->libdir . '/completionlib.php');
662 $params = self::validate_parameters(self::create_courses_parameters(),
663 array('courses' => $courses));
665 $availablethemes = core_component::get_plugin_list('theme');
666 $availablelangs = get_string_manager()->get_list_of_translations();
668 $transaction = $DB->start_delegated_transaction();
670 foreach ($params['courses'] as $course) {
672 // Ensure the current user is allowed to run this function
673 $context = context_coursecat::instance($course['categoryid'], IGNORE_MISSING);
674 try {
675 self::validate_context($context);
676 } catch (Exception $e) {
677 $exceptionparam = new stdClass();
678 $exceptionparam->message = $e->getMessage();
679 $exceptionparam->catid = $course['categoryid'];
680 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
682 require_capability('moodle/course:create', $context);
684 // Make sure lang is valid
685 if (array_key_exists('lang', $course) and empty($availablelangs[$course['lang']])) {
686 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
689 // Make sure theme is valid
690 if (array_key_exists('forcetheme', $course)) {
691 if (!empty($CFG->allowcoursethemes)) {
692 if (empty($availablethemes[$course['forcetheme']])) {
693 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
694 } else {
695 $course['theme'] = $course['forcetheme'];
700 //force visibility if ws user doesn't have the permission to set it
701 $category = $DB->get_record('course_categories', array('id' => $course['categoryid']));
702 if (!has_capability('moodle/course:visibility', $context)) {
703 $course['visible'] = $category->visible;
706 //set default value for completion
707 $courseconfig = get_config('moodlecourse');
708 if (completion_info::is_enabled_for_site()) {
709 if (!array_key_exists('enablecompletion', $course)) {
710 $course['enablecompletion'] = $courseconfig->enablecompletion;
712 } else {
713 $course['enablecompletion'] = 0;
716 $course['category'] = $course['categoryid'];
718 // Summary format.
719 $course['summaryformat'] = external_validate_format($course['summaryformat']);
721 if (!empty($course['courseformatoptions'])) {
722 foreach ($course['courseformatoptions'] as $option) {
723 $course[$option['name']] = $option['value'];
727 //Note: create_course() core function check shortname, idnumber, category
728 $course['id'] = create_course((object) $course)->id;
730 $resultcourses[] = array('id' => $course['id'], 'shortname' => $course['shortname']);
733 $transaction->allow_commit();
735 return $resultcourses;
739 * Returns description of method result value
741 * @return external_description
742 * @since Moodle 2.2
744 public static function create_courses_returns() {
745 return new external_multiple_structure(
746 new external_single_structure(
747 array(
748 'id' => new external_value(PARAM_INT, 'course id'),
749 'shortname' => new external_value(PARAM_TEXT, 'short name'),
756 * Update courses
758 * @return external_function_parameters
759 * @since Moodle 2.5
761 public static function update_courses_parameters() {
762 return new external_function_parameters(
763 array(
764 'courses' => new external_multiple_structure(
765 new external_single_structure(
766 array(
767 'id' => new external_value(PARAM_INT, 'ID of the course'),
768 'fullname' => new external_value(PARAM_TEXT, 'full name', VALUE_OPTIONAL),
769 'shortname' => new external_value(PARAM_TEXT, 'course short name', VALUE_OPTIONAL),
770 'categoryid' => new external_value(PARAM_INT, 'category id', VALUE_OPTIONAL),
771 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
772 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
773 'summaryformat' => new external_format_value('summary', VALUE_OPTIONAL),
774 'format' => new external_value(PARAM_PLUGIN,
775 'course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
776 'showgrades' => new external_value(PARAM_INT,
777 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
778 'newsitems' => new external_value(PARAM_INT,
779 'number of recent items appearing on the course page', VALUE_OPTIONAL),
780 'startdate' => new external_value(PARAM_INT,
781 'timestamp when the course start', VALUE_OPTIONAL),
782 'enddate' => new external_value(PARAM_INT,
783 'timestamp when the course end', VALUE_OPTIONAL),
784 'numsections' => new external_value(PARAM_INT,
785 '(deprecated, use courseformatoptions) number of weeks/topics', VALUE_OPTIONAL),
786 'maxbytes' => new external_value(PARAM_INT,
787 'largest size of file that can be uploaded into the course', VALUE_OPTIONAL),
788 'showreports' => new external_value(PARAM_INT,
789 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
790 'visible' => new external_value(PARAM_INT,
791 '1: available to student, 0:not available', VALUE_OPTIONAL),
792 'hiddensections' => new external_value(PARAM_INT,
793 '(deprecated, use courseformatoptions) How the hidden sections in the course are
794 displayed to students', VALUE_OPTIONAL),
795 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
796 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
797 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
798 'enablecompletion' => new external_value(PARAM_INT,
799 'Enabled, control via completion and activity settings. Disabled,
800 not shown in activity settings.', VALUE_OPTIONAL),
801 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
802 'lang' => new external_value(PARAM_SAFEDIR, 'forced course language', VALUE_OPTIONAL),
803 'forcetheme' => new external_value(PARAM_PLUGIN, 'name of the force theme', VALUE_OPTIONAL),
804 'courseformatoptions' => new external_multiple_structure(
805 new external_single_structure(
806 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
807 'value' => new external_value(PARAM_RAW, 'course format option value')
809 'additional options for particular course format', VALUE_OPTIONAL),
811 ), 'courses to update'
818 * Update courses
820 * @param array $courses
821 * @since Moodle 2.5
823 public static function update_courses($courses) {
824 global $CFG, $DB;
825 require_once($CFG->dirroot . "/course/lib.php");
826 $warnings = array();
828 $params = self::validate_parameters(self::update_courses_parameters(),
829 array('courses' => $courses));
831 $availablethemes = core_component::get_plugin_list('theme');
832 $availablelangs = get_string_manager()->get_list_of_translations();
834 foreach ($params['courses'] as $course) {
835 // Catch any exception while updating course and return as warning to user.
836 try {
837 // Ensure the current user is allowed to run this function.
838 $context = context_course::instance($course['id'], MUST_EXIST);
839 self::validate_context($context);
841 $oldcourse = course_get_format($course['id'])->get_course();
843 require_capability('moodle/course:update', $context);
845 // Check if user can change category.
846 if (array_key_exists('categoryid', $course) && ($oldcourse->category != $course['categoryid'])) {
847 require_capability('moodle/course:changecategory', $context);
848 $course['category'] = $course['categoryid'];
851 // Check if the user can change fullname.
852 if (array_key_exists('fullname', $course) && ($oldcourse->fullname != $course['fullname'])) {
853 require_capability('moodle/course:changefullname', $context);
856 // Check if the user can change shortname.
857 if (array_key_exists('shortname', $course) && ($oldcourse->shortname != $course['shortname'])) {
858 require_capability('moodle/course:changeshortname', $context);
861 // Check if the user can change the idnumber.
862 if (array_key_exists('idnumber', $course) && ($oldcourse->idnumber != $course['idnumber'])) {
863 require_capability('moodle/course:changeidnumber', $context);
866 // Check if user can change summary.
867 if (array_key_exists('summary', $course) && ($oldcourse->summary != $course['summary'])) {
868 require_capability('moodle/course:changesummary', $context);
871 // Summary format.
872 if (array_key_exists('summaryformat', $course) && ($oldcourse->summaryformat != $course['summaryformat'])) {
873 require_capability('moodle/course:changesummary', $context);
874 $course['summaryformat'] = external_validate_format($course['summaryformat']);
877 // Check if user can change visibility.
878 if (array_key_exists('visible', $course) && ($oldcourse->visible != $course['visible'])) {
879 require_capability('moodle/course:visibility', $context);
882 // Make sure lang is valid.
883 if (array_key_exists('lang', $course) && empty($availablelangs[$course['lang']])) {
884 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
887 // Make sure theme is valid.
888 if (array_key_exists('forcetheme', $course)) {
889 if (!empty($CFG->allowcoursethemes)) {
890 if (empty($availablethemes[$course['forcetheme']])) {
891 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
892 } else {
893 $course['theme'] = $course['forcetheme'];
898 // Make sure completion is enabled before setting it.
899 if (array_key_exists('enabledcompletion', $course) && !completion_info::is_enabled_for_site()) {
900 $course['enabledcompletion'] = 0;
903 // Make sure maxbytes are less then CFG->maxbytes.
904 if (array_key_exists('maxbytes', $course)) {
905 $course['maxbytes'] = get_max_upload_file_size($CFG->maxbytes, $course['maxbytes']);
908 if (!empty($course['courseformatoptions'])) {
909 foreach ($course['courseformatoptions'] as $option) {
910 if (isset($option['name']) && isset($option['value'])) {
911 $course[$option['name']] = $option['value'];
916 // Update course if user has all required capabilities.
917 update_course((object) $course);
918 } catch (Exception $e) {
919 $warning = array();
920 $warning['item'] = 'course';
921 $warning['itemid'] = $course['id'];
922 if ($e instanceof moodle_exception) {
923 $warning['warningcode'] = $e->errorcode;
924 } else {
925 $warning['warningcode'] = $e->getCode();
927 $warning['message'] = $e->getMessage();
928 $warnings[] = $warning;
932 $result = array();
933 $result['warnings'] = $warnings;
934 return $result;
938 * Returns description of method result value
940 * @return external_description
941 * @since Moodle 2.5
943 public static function update_courses_returns() {
944 return new external_single_structure(
945 array(
946 'warnings' => new external_warnings()
952 * Returns description of method parameters
954 * @return external_function_parameters
955 * @since Moodle 2.2
957 public static function delete_courses_parameters() {
958 return new external_function_parameters(
959 array(
960 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'course ID')),
966 * Delete courses
968 * @param array $courseids A list of course ids
969 * @since Moodle 2.2
971 public static function delete_courses($courseids) {
972 global $CFG, $DB;
973 require_once($CFG->dirroot."/course/lib.php");
975 // Parameter validation.
976 $params = self::validate_parameters(self::delete_courses_parameters(), array('courseids'=>$courseids));
978 $warnings = array();
980 foreach ($params['courseids'] as $courseid) {
981 $course = $DB->get_record('course', array('id' => $courseid));
983 if ($course === false) {
984 $warnings[] = array(
985 'item' => 'course',
986 'itemid' => $courseid,
987 'warningcode' => 'unknowncourseidnumber',
988 'message' => 'Unknown course ID ' . $courseid
990 continue;
993 // Check if the context is valid.
994 $coursecontext = context_course::instance($course->id);
995 self::validate_context($coursecontext);
997 // Check if the current user has permission.
998 if (!can_delete_course($courseid)) {
999 $warnings[] = array(
1000 'item' => 'course',
1001 'itemid' => $courseid,
1002 'warningcode' => 'cannotdeletecourse',
1003 'message' => 'You do not have the permission to delete this course' . $courseid
1005 continue;
1008 if (delete_course($course, false) === false) {
1009 $warnings[] = array(
1010 'item' => 'course',
1011 'itemid' => $courseid,
1012 'warningcode' => 'cannotdeletecategorycourse',
1013 'message' => 'Course ' . $courseid . ' failed to be deleted'
1015 continue;
1019 fix_course_sortorder();
1021 return array('warnings' => $warnings);
1025 * Returns description of method result value
1027 * @return external_description
1028 * @since Moodle 2.2
1030 public static function delete_courses_returns() {
1031 return new external_single_structure(
1032 array(
1033 'warnings' => new external_warnings()
1039 * Returns description of method parameters
1041 * @return external_function_parameters
1042 * @since Moodle 2.3
1044 public static function duplicate_course_parameters() {
1045 return new external_function_parameters(
1046 array(
1047 'courseid' => new external_value(PARAM_INT, 'course to duplicate id'),
1048 'fullname' => new external_value(PARAM_TEXT, 'duplicated course full name'),
1049 'shortname' => new external_value(PARAM_TEXT, 'duplicated course short name'),
1050 'categoryid' => new external_value(PARAM_INT, 'duplicated course category parent'),
1051 'visible' => new external_value(PARAM_INT, 'duplicated course visible, default to yes', VALUE_DEFAULT, 1),
1052 'options' => new external_multiple_structure(
1053 new external_single_structure(
1054 array(
1055 'name' => new external_value(PARAM_ALPHAEXT, 'The backup option name:
1056 "activities" (int) Include course activites (default to 1 that is equal to yes),
1057 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1058 "filters" (int) Include course filters (default to 1 that is equal to yes),
1059 "users" (int) Include users (default to 0 that is equal to no),
1060 "enrolments" (int) Include enrolment methods (default to 1 - restore only with users),
1061 "role_assignments" (int) Include role assignments (default to 0 that is equal to no),
1062 "comments" (int) Include user comments (default to 0 that is equal to no),
1063 "userscompletion" (int) Include user course completion information (default to 0 that is equal to no),
1064 "logs" (int) Include course logs (default to 0 that is equal to no),
1065 "grade_histories" (int) Include histories (default to 0 that is equal to no)'
1067 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1070 ), VALUE_DEFAULT, array()
1077 * Duplicate a course
1079 * @param int $courseid
1080 * @param string $fullname Duplicated course fullname
1081 * @param string $shortname Duplicated course shortname
1082 * @param int $categoryid Duplicated course parent category id
1083 * @param int $visible Duplicated course availability
1084 * @param array $options List of backup options
1085 * @return array New course info
1086 * @since Moodle 2.3
1088 public static function duplicate_course($courseid, $fullname, $shortname, $categoryid, $visible = 1, $options = array()) {
1089 global $CFG, $USER, $DB;
1090 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1091 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1093 // Parameter validation.
1094 $params = self::validate_parameters(
1095 self::duplicate_course_parameters(),
1096 array(
1097 'courseid' => $courseid,
1098 'fullname' => $fullname,
1099 'shortname' => $shortname,
1100 'categoryid' => $categoryid,
1101 'visible' => $visible,
1102 'options' => $options
1106 // Context validation.
1108 if (! ($course = $DB->get_record('course', array('id'=>$params['courseid'])))) {
1109 throw new moodle_exception('invalidcourseid', 'error');
1112 // Category where duplicated course is going to be created.
1113 $categorycontext = context_coursecat::instance($params['categoryid']);
1114 self::validate_context($categorycontext);
1116 // Course to be duplicated.
1117 $coursecontext = context_course::instance($course->id);
1118 self::validate_context($coursecontext);
1120 $backupdefaults = array(
1121 'activities' => 1,
1122 'blocks' => 1,
1123 'filters' => 1,
1124 'users' => 0,
1125 'enrolments' => backup::ENROL_WITHUSERS,
1126 'role_assignments' => 0,
1127 'comments' => 0,
1128 'userscompletion' => 0,
1129 'logs' => 0,
1130 'grade_histories' => 0
1133 $backupsettings = array();
1134 // Check for backup and restore options.
1135 if (!empty($params['options'])) {
1136 foreach ($params['options'] as $option) {
1138 // Strict check for a correct value (allways 1 or 0, true or false).
1139 $value = clean_param($option['value'], PARAM_INT);
1141 if ($value !== 0 and $value !== 1) {
1142 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1145 if (!isset($backupdefaults[$option['name']])) {
1146 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1149 $backupsettings[$option['name']] = $value;
1153 // Capability checking.
1155 // The backup controller check for this currently, this may be redundant.
1156 require_capability('moodle/course:create', $categorycontext);
1157 require_capability('moodle/restore:restorecourse', $categorycontext);
1158 require_capability('moodle/backup:backupcourse', $coursecontext);
1160 if (!empty($backupsettings['users'])) {
1161 require_capability('moodle/backup:userinfo', $coursecontext);
1162 require_capability('moodle/restore:userinfo', $categorycontext);
1165 // Check if the shortname is used.
1166 if ($foundcourses = $DB->get_records('course', array('shortname'=>$shortname))) {
1167 foreach ($foundcourses as $foundcourse) {
1168 $foundcoursenames[] = $foundcourse->fullname;
1171 $foundcoursenamestring = implode(',', $foundcoursenames);
1172 throw new moodle_exception('shortnametaken', '', '', $foundcoursenamestring);
1175 // Backup the course.
1177 $bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE,
1178 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id);
1180 foreach ($backupsettings as $name => $value) {
1181 if ($setting = $bc->get_plan()->get_setting($name)) {
1182 $bc->get_plan()->get_setting($name)->set_value($value);
1186 $backupid = $bc->get_backupid();
1187 $backupbasepath = $bc->get_plan()->get_basepath();
1189 $bc->execute_plan();
1190 $results = $bc->get_results();
1191 $file = $results['backup_destination'];
1193 $bc->destroy();
1195 // Restore the backup immediately.
1197 // Check if we need to unzip the file because the backup temp dir does not contains backup files.
1198 if (!file_exists($backupbasepath . "/moodle_backup.xml")) {
1199 $file->extract_to_pathname(get_file_packer('application/vnd.moodle.backup'), $backupbasepath);
1202 // Create new course.
1203 $newcourseid = restore_dbops::create_new_course($params['fullname'], $params['shortname'], $params['categoryid']);
1205 $rc = new restore_controller($backupid, $newcourseid,
1206 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id, backup::TARGET_NEW_COURSE);
1208 foreach ($backupsettings as $name => $value) {
1209 $setting = $rc->get_plan()->get_setting($name);
1210 if ($setting->get_status() == backup_setting::NOT_LOCKED) {
1211 $setting->set_value($value);
1215 if (!$rc->execute_precheck()) {
1216 $precheckresults = $rc->get_precheck_results();
1217 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1218 if (empty($CFG->keeptempdirectoriesonbackup)) {
1219 fulldelete($backupbasepath);
1222 $errorinfo = '';
1224 foreach ($precheckresults['errors'] as $error) {
1225 $errorinfo .= $error;
1228 if (array_key_exists('warnings', $precheckresults)) {
1229 foreach ($precheckresults['warnings'] as $warning) {
1230 $errorinfo .= $warning;
1234 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1238 $rc->execute_plan();
1239 $rc->destroy();
1241 $course = $DB->get_record('course', array('id' => $newcourseid), '*', MUST_EXIST);
1242 $course->fullname = $params['fullname'];
1243 $course->shortname = $params['shortname'];
1244 $course->visible = $params['visible'];
1246 // Set shortname and fullname back.
1247 $DB->update_record('course', $course);
1249 if (empty($CFG->keeptempdirectoriesonbackup)) {
1250 fulldelete($backupbasepath);
1253 // Delete the course backup file created by this WebService. Originally located in the course backups area.
1254 $file->delete();
1256 return array('id' => $course->id, 'shortname' => $course->shortname);
1260 * Returns description of method result value
1262 * @return external_description
1263 * @since Moodle 2.3
1265 public static function duplicate_course_returns() {
1266 return new external_single_structure(
1267 array(
1268 'id' => new external_value(PARAM_INT, 'course id'),
1269 'shortname' => new external_value(PARAM_TEXT, 'short name'),
1275 * Returns description of method parameters for import_course
1277 * @return external_function_parameters
1278 * @since Moodle 2.4
1280 public static function import_course_parameters() {
1281 return new external_function_parameters(
1282 array(
1283 'importfrom' => new external_value(PARAM_INT, 'the id of the course we are importing from'),
1284 'importto' => new external_value(PARAM_INT, 'the id of the course we are importing to'),
1285 'deletecontent' => new external_value(PARAM_INT, 'whether to delete the course content where we are importing to (default to 0 = No)', VALUE_DEFAULT, 0),
1286 'options' => new external_multiple_structure(
1287 new external_single_structure(
1288 array(
1289 'name' => new external_value(PARAM_ALPHA, 'The backup option name:
1290 "activities" (int) Include course activites (default to 1 that is equal to yes),
1291 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1292 "filters" (int) Include course filters (default to 1 that is equal to yes)'
1294 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1297 ), VALUE_DEFAULT, array()
1304 * Imports a course
1306 * @param int $importfrom The id of the course we are importing from
1307 * @param int $importto The id of the course we are importing to
1308 * @param bool $deletecontent Whether to delete the course we are importing to content
1309 * @param array $options List of backup options
1310 * @return null
1311 * @since Moodle 2.4
1313 public static function import_course($importfrom, $importto, $deletecontent = 0, $options = array()) {
1314 global $CFG, $USER, $DB;
1315 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1316 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1318 // Parameter validation.
1319 $params = self::validate_parameters(
1320 self::import_course_parameters(),
1321 array(
1322 'importfrom' => $importfrom,
1323 'importto' => $importto,
1324 'deletecontent' => $deletecontent,
1325 'options' => $options
1329 if ($params['deletecontent'] !== 0 and $params['deletecontent'] !== 1) {
1330 throw new moodle_exception('invalidextparam', 'webservice', '', $params['deletecontent']);
1333 // Context validation.
1335 if (! ($importfrom = $DB->get_record('course', array('id'=>$params['importfrom'])))) {
1336 throw new moodle_exception('invalidcourseid', 'error');
1339 if (! ($importto = $DB->get_record('course', array('id'=>$params['importto'])))) {
1340 throw new moodle_exception('invalidcourseid', 'error');
1343 $importfromcontext = context_course::instance($importfrom->id);
1344 self::validate_context($importfromcontext);
1346 $importtocontext = context_course::instance($importto->id);
1347 self::validate_context($importtocontext);
1349 $backupdefaults = array(
1350 'activities' => 1,
1351 'blocks' => 1,
1352 'filters' => 1
1355 $backupsettings = array();
1357 // Check for backup and restore options.
1358 if (!empty($params['options'])) {
1359 foreach ($params['options'] as $option) {
1361 // Strict check for a correct value (allways 1 or 0, true or false).
1362 $value = clean_param($option['value'], PARAM_INT);
1364 if ($value !== 0 and $value !== 1) {
1365 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1368 if (!isset($backupdefaults[$option['name']])) {
1369 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1372 $backupsettings[$option['name']] = $value;
1376 // Capability checking.
1378 require_capability('moodle/backup:backuptargetimport', $importfromcontext);
1379 require_capability('moodle/restore:restoretargetimport', $importtocontext);
1381 $bc = new backup_controller(backup::TYPE_1COURSE, $importfrom->id, backup::FORMAT_MOODLE,
1382 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
1384 foreach ($backupsettings as $name => $value) {
1385 $bc->get_plan()->get_setting($name)->set_value($value);
1388 $backupid = $bc->get_backupid();
1389 $backupbasepath = $bc->get_plan()->get_basepath();
1391 $bc->execute_plan();
1392 $bc->destroy();
1394 // Restore the backup immediately.
1396 // Check if we must delete the contents of the destination course.
1397 if ($params['deletecontent']) {
1398 $restoretarget = backup::TARGET_EXISTING_DELETING;
1399 } else {
1400 $restoretarget = backup::TARGET_EXISTING_ADDING;
1403 $rc = new restore_controller($backupid, $importto->id,
1404 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, $restoretarget);
1406 foreach ($backupsettings as $name => $value) {
1407 $rc->get_plan()->get_setting($name)->set_value($value);
1410 if (!$rc->execute_precheck()) {
1411 $precheckresults = $rc->get_precheck_results();
1412 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1413 if (empty($CFG->keeptempdirectoriesonbackup)) {
1414 fulldelete($backupbasepath);
1417 $errorinfo = '';
1419 foreach ($precheckresults['errors'] as $error) {
1420 $errorinfo .= $error;
1423 if (array_key_exists('warnings', $precheckresults)) {
1424 foreach ($precheckresults['warnings'] as $warning) {
1425 $errorinfo .= $warning;
1429 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1431 } else {
1432 if ($restoretarget == backup::TARGET_EXISTING_DELETING) {
1433 restore_dbops::delete_course_content($importto->id);
1437 $rc->execute_plan();
1438 $rc->destroy();
1440 if (empty($CFG->keeptempdirectoriesonbackup)) {
1441 fulldelete($backupbasepath);
1444 return null;
1448 * Returns description of method result value
1450 * @return external_description
1451 * @since Moodle 2.4
1453 public static function import_course_returns() {
1454 return null;
1458 * Returns description of method parameters
1460 * @return external_function_parameters
1461 * @since Moodle 2.3
1463 public static function get_categories_parameters() {
1464 return new external_function_parameters(
1465 array(
1466 'criteria' => new external_multiple_structure(
1467 new external_single_structure(
1468 array(
1469 'key' => new external_value(PARAM_ALPHA,
1470 'The category column to search, expected keys (value format) are:'.
1471 '"id" (int) the category id,'.
1472 '"ids" (string) category ids separated by commas,'.
1473 '"name" (string) the category name,'.
1474 '"parent" (int) the parent category id,'.
1475 '"idnumber" (string) category idnumber'.
1476 ' - user must have \'moodle/category:manage\' to search on idnumber,'.
1477 '"visible" (int) whether the returned categories must be visible or hidden. If the key is not passed,
1478 then the function return all categories that the user can see.'.
1479 ' - user must have \'moodle/category:manage\' or \'moodle/category:viewhiddencategories\' to search on visible,'.
1480 '"theme" (string) only return the categories having this theme'.
1481 ' - user must have \'moodle/category:manage\' to search on theme'),
1482 'value' => new external_value(PARAM_RAW, 'the value to match')
1484 ), 'criteria', VALUE_DEFAULT, array()
1486 'addsubcategories' => new external_value(PARAM_BOOL, 'return the sub categories infos
1487 (1 - default) otherwise only the category info (0)', VALUE_DEFAULT, 1)
1493 * Get categories
1495 * @param array $criteria Criteria to match the results
1496 * @param booln $addsubcategories obtain only the category (false) or its subcategories (true - default)
1497 * @return array list of categories
1498 * @since Moodle 2.3
1500 public static function get_categories($criteria = array(), $addsubcategories = true) {
1501 global $CFG, $DB;
1502 require_once($CFG->dirroot . "/course/lib.php");
1504 // Validate parameters.
1505 $params = self::validate_parameters(self::get_categories_parameters(),
1506 array('criteria' => $criteria, 'addsubcategories' => $addsubcategories));
1508 // Retrieve the categories.
1509 $categories = array();
1510 if (!empty($params['criteria'])) {
1512 $conditions = array();
1513 $wheres = array();
1514 foreach ($params['criteria'] as $crit) {
1515 $key = trim($crit['key']);
1517 // Trying to avoid duplicate keys.
1518 if (!isset($conditions[$key])) {
1520 $context = context_system::instance();
1521 $value = null;
1522 switch ($key) {
1523 case 'id':
1524 $value = clean_param($crit['value'], PARAM_INT);
1525 $conditions[$key] = $value;
1526 $wheres[] = $key . " = :" . $key;
1527 break;
1529 case 'ids':
1530 $value = clean_param($crit['value'], PARAM_SEQUENCE);
1531 $ids = explode(',', $value);
1532 list($sqlids, $paramids) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED);
1533 $conditions = array_merge($conditions, $paramids);
1534 $wheres[] = 'id ' . $sqlids;
1535 break;
1537 case 'idnumber':
1538 if (has_capability('moodle/category:manage', $context)) {
1539 $value = clean_param($crit['value'], PARAM_RAW);
1540 $conditions[$key] = $value;
1541 $wheres[] = $key . " = :" . $key;
1542 } else {
1543 // We must throw an exception.
1544 // Otherwise the dev client would think no idnumber exists.
1545 throw new moodle_exception('criteriaerror',
1546 'webservice', '', null,
1547 'You don\'t have the permissions to search on the "idnumber" field.');
1549 break;
1551 case 'name':
1552 $value = clean_param($crit['value'], PARAM_TEXT);
1553 $conditions[$key] = $value;
1554 $wheres[] = $key . " = :" . $key;
1555 break;
1557 case 'parent':
1558 $value = clean_param($crit['value'], PARAM_INT);
1559 $conditions[$key] = $value;
1560 $wheres[] = $key . " = :" . $key;
1561 break;
1563 case 'visible':
1564 if (has_capability('moodle/category:manage', $context)
1565 or has_capability('moodle/category:viewhiddencategories',
1566 context_system::instance())) {
1567 $value = clean_param($crit['value'], PARAM_INT);
1568 $conditions[$key] = $value;
1569 $wheres[] = $key . " = :" . $key;
1570 } else {
1571 throw new moodle_exception('criteriaerror',
1572 'webservice', '', null,
1573 'You don\'t have the permissions to search on the "visible" field.');
1575 break;
1577 case 'theme':
1578 if (has_capability('moodle/category:manage', $context)) {
1579 $value = clean_param($crit['value'], PARAM_THEME);
1580 $conditions[$key] = $value;
1581 $wheres[] = $key . " = :" . $key;
1582 } else {
1583 throw new moodle_exception('criteriaerror',
1584 'webservice', '', null,
1585 'You don\'t have the permissions to search on the "theme" field.');
1587 break;
1589 default:
1590 throw new moodle_exception('criteriaerror',
1591 'webservice', '', null,
1592 'You can not search on this criteria: ' . $key);
1597 if (!empty($wheres)) {
1598 $wheres = implode(" AND ", $wheres);
1600 $categories = $DB->get_records_select('course_categories', $wheres, $conditions);
1602 // Retrieve its sub subcategories (all levels).
1603 if ($categories and !empty($params['addsubcategories'])) {
1604 $newcategories = array();
1606 // Check if we required visible/theme checks.
1607 $additionalselect = '';
1608 $additionalparams = array();
1609 if (isset($conditions['visible'])) {
1610 $additionalselect .= ' AND visible = :visible';
1611 $additionalparams['visible'] = $conditions['visible'];
1613 if (isset($conditions['theme'])) {
1614 $additionalselect .= ' AND theme= :theme';
1615 $additionalparams['theme'] = $conditions['theme'];
1618 foreach ($categories as $category) {
1619 $sqlselect = $DB->sql_like('path', ':path') . $additionalselect;
1620 $sqlparams = array('path' => $category->path.'/%') + $additionalparams; // It will NOT include the specified category.
1621 $subcategories = $DB->get_records_select('course_categories', $sqlselect, $sqlparams);
1622 $newcategories = $newcategories + $subcategories; // Both arrays have integer as keys.
1624 $categories = $categories + $newcategories;
1628 } else {
1629 // Retrieve all categories in the database.
1630 $categories = $DB->get_records('course_categories');
1633 // The not returned categories. key => category id, value => reason of exclusion.
1634 $excludedcats = array();
1636 // The returned categories.
1637 $categoriesinfo = array();
1639 // We need to sort the categories by path.
1640 // The parent cats need to be checked by the algo first.
1641 usort($categories, "core_course_external::compare_categories_by_path");
1643 foreach ($categories as $category) {
1645 // Check if the category is a child of an excluded category, if yes exclude it too (excluded => do not return).
1646 $parents = explode('/', $category->path);
1647 unset($parents[0]); // First key is always empty because path start with / => /1/2/4.
1648 foreach ($parents as $parentid) {
1649 // Note: when the parent exclusion was due to the context,
1650 // the sub category could still be returned.
1651 if (isset($excludedcats[$parentid]) and $excludedcats[$parentid] != 'context') {
1652 $excludedcats[$category->id] = 'parent';
1656 // Check the user can use the category context.
1657 $context = context_coursecat::instance($category->id);
1658 try {
1659 self::validate_context($context);
1660 } catch (Exception $e) {
1661 $excludedcats[$category->id] = 'context';
1663 // If it was the requested category then throw an exception.
1664 if (isset($params['categoryid']) && $category->id == $params['categoryid']) {
1665 $exceptionparam = new stdClass();
1666 $exceptionparam->message = $e->getMessage();
1667 $exceptionparam->catid = $category->id;
1668 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
1672 // Return the category information.
1673 if (!isset($excludedcats[$category->id])) {
1675 // Final check to see if the category is visible to the user.
1676 if ($category->visible
1677 or has_capability('moodle/category:viewhiddencategories', context_system::instance())
1678 or has_capability('moodle/category:manage', $context)) {
1680 $categoryinfo = array();
1681 $categoryinfo['id'] = $category->id;
1682 $categoryinfo['name'] = $category->name;
1683 list($categoryinfo['description'], $categoryinfo['descriptionformat']) =
1684 external_format_text($category->description, $category->descriptionformat,
1685 $context->id, 'coursecat', 'description', null);
1686 $categoryinfo['parent'] = $category->parent;
1687 $categoryinfo['sortorder'] = $category->sortorder;
1688 $categoryinfo['coursecount'] = $category->coursecount;
1689 $categoryinfo['depth'] = $category->depth;
1690 $categoryinfo['path'] = $category->path;
1692 // Some fields only returned for admin.
1693 if (has_capability('moodle/category:manage', $context)) {
1694 $categoryinfo['idnumber'] = $category->idnumber;
1695 $categoryinfo['visible'] = $category->visible;
1696 $categoryinfo['visibleold'] = $category->visibleold;
1697 $categoryinfo['timemodified'] = $category->timemodified;
1698 $categoryinfo['theme'] = $category->theme;
1701 $categoriesinfo[] = $categoryinfo;
1702 } else {
1703 $excludedcats[$category->id] = 'visibility';
1708 // Sorting the resulting array so it looks a bit better for the client developer.
1709 usort($categoriesinfo, "core_course_external::compare_categories_by_sortorder");
1711 return $categoriesinfo;
1715 * Sort categories array by path
1716 * private function: only used by get_categories
1718 * @param array $category1
1719 * @param array $category2
1720 * @return int result of strcmp
1721 * @since Moodle 2.3
1723 private static function compare_categories_by_path($category1, $category2) {
1724 return strcmp($category1->path, $category2->path);
1728 * Sort categories array by sortorder
1729 * private function: only used by get_categories
1731 * @param array $category1
1732 * @param array $category2
1733 * @return int result of strcmp
1734 * @since Moodle 2.3
1736 private static function compare_categories_by_sortorder($category1, $category2) {
1737 return strcmp($category1['sortorder'], $category2['sortorder']);
1741 * Returns description of method result value
1743 * @return external_description
1744 * @since Moodle 2.3
1746 public static function get_categories_returns() {
1747 return new external_multiple_structure(
1748 new external_single_structure(
1749 array(
1750 'id' => new external_value(PARAM_INT, 'category id'),
1751 'name' => new external_value(PARAM_TEXT, 'category name'),
1752 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1753 'description' => new external_value(PARAM_RAW, 'category description'),
1754 'descriptionformat' => new external_format_value('description'),
1755 'parent' => new external_value(PARAM_INT, 'parent category id'),
1756 'sortorder' => new external_value(PARAM_INT, 'category sorting order'),
1757 'coursecount' => new external_value(PARAM_INT, 'number of courses in this category'),
1758 'visible' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1759 'visibleold' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1760 'timemodified' => new external_value(PARAM_INT, 'timestamp', VALUE_OPTIONAL),
1761 'depth' => new external_value(PARAM_INT, 'category depth'),
1762 'path' => new external_value(PARAM_TEXT, 'category path'),
1763 'theme' => new external_value(PARAM_THEME, 'category theme', VALUE_OPTIONAL),
1764 ), 'List of categories'
1770 * Returns description of method parameters
1772 * @return external_function_parameters
1773 * @since Moodle 2.3
1775 public static function create_categories_parameters() {
1776 return new external_function_parameters(
1777 array(
1778 'categories' => new external_multiple_structure(
1779 new external_single_structure(
1780 array(
1781 'name' => new external_value(PARAM_TEXT, 'new category name'),
1782 'parent' => new external_value(PARAM_INT,
1783 'the parent category id inside which the new category will be created
1784 - set to 0 for a root category',
1785 VALUE_DEFAULT, 0),
1786 'idnumber' => new external_value(PARAM_RAW,
1787 'the new category idnumber', VALUE_OPTIONAL),
1788 'description' => new external_value(PARAM_RAW,
1789 'the new category description', VALUE_OPTIONAL),
1790 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
1791 'theme' => new external_value(PARAM_THEME,
1792 'the new category theme. This option must be enabled on moodle',
1793 VALUE_OPTIONAL),
1802 * Create categories
1804 * @param array $categories - see create_categories_parameters() for the array structure
1805 * @return array - see create_categories_returns() for the array structure
1806 * @since Moodle 2.3
1808 public static function create_categories($categories) {
1809 global $CFG, $DB;
1810 require_once($CFG->libdir . "/coursecatlib.php");
1812 $params = self::validate_parameters(self::create_categories_parameters(),
1813 array('categories' => $categories));
1815 $transaction = $DB->start_delegated_transaction();
1817 $createdcategories = array();
1818 foreach ($params['categories'] as $category) {
1819 if ($category['parent']) {
1820 if (!$DB->record_exists('course_categories', array('id' => $category['parent']))) {
1821 throw new moodle_exception('unknowcategory');
1823 $context = context_coursecat::instance($category['parent']);
1824 } else {
1825 $context = context_system::instance();
1827 self::validate_context($context);
1828 require_capability('moodle/category:manage', $context);
1830 // this will validate format and throw an exception if there are errors
1831 external_validate_format($category['descriptionformat']);
1833 $newcategory = coursecat::create($category);
1835 $createdcategories[] = array('id' => $newcategory->id, 'name' => $newcategory->name);
1838 $transaction->allow_commit();
1840 return $createdcategories;
1844 * Returns description of method parameters
1846 * @return external_function_parameters
1847 * @since Moodle 2.3
1849 public static function create_categories_returns() {
1850 return new external_multiple_structure(
1851 new external_single_structure(
1852 array(
1853 'id' => new external_value(PARAM_INT, 'new category id'),
1854 'name' => new external_value(PARAM_TEXT, 'new category name'),
1861 * Returns description of method parameters
1863 * @return external_function_parameters
1864 * @since Moodle 2.3
1866 public static function update_categories_parameters() {
1867 return new external_function_parameters(
1868 array(
1869 'categories' => new external_multiple_structure(
1870 new external_single_structure(
1871 array(
1872 'id' => new external_value(PARAM_INT, 'course id'),
1873 'name' => new external_value(PARAM_TEXT, 'category name', VALUE_OPTIONAL),
1874 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1875 'parent' => new external_value(PARAM_INT, 'parent category id', VALUE_OPTIONAL),
1876 'description' => new external_value(PARAM_RAW, 'category description', VALUE_OPTIONAL),
1877 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
1878 'theme' => new external_value(PARAM_THEME,
1879 'the category theme. This option must be enabled on moodle', VALUE_OPTIONAL),
1888 * Update categories
1890 * @param array $categories The list of categories to update
1891 * @return null
1892 * @since Moodle 2.3
1894 public static function update_categories($categories) {
1895 global $CFG, $DB;
1896 require_once($CFG->libdir . "/coursecatlib.php");
1898 // Validate parameters.
1899 $params = self::validate_parameters(self::update_categories_parameters(), array('categories' => $categories));
1901 $transaction = $DB->start_delegated_transaction();
1903 foreach ($params['categories'] as $cat) {
1904 $category = coursecat::get($cat['id']);
1906 $categorycontext = context_coursecat::instance($cat['id']);
1907 self::validate_context($categorycontext);
1908 require_capability('moodle/category:manage', $categorycontext);
1910 // this will throw an exception if descriptionformat is not valid
1911 external_validate_format($cat['descriptionformat']);
1913 $category->update($cat);
1916 $transaction->allow_commit();
1920 * Returns description of method result value
1922 * @return external_description
1923 * @since Moodle 2.3
1925 public static function update_categories_returns() {
1926 return null;
1930 * Returns description of method parameters
1932 * @return external_function_parameters
1933 * @since Moodle 2.3
1935 public static function delete_categories_parameters() {
1936 return new external_function_parameters(
1937 array(
1938 'categories' => new external_multiple_structure(
1939 new external_single_structure(
1940 array(
1941 'id' => new external_value(PARAM_INT, 'category id to delete'),
1942 'newparent' => new external_value(PARAM_INT,
1943 'the parent category to move the contents to, if specified', VALUE_OPTIONAL),
1944 'recursive' => new external_value(PARAM_BOOL, '1: recursively delete all contents inside this
1945 category, 0 (default): move contents to newparent or current parent category (except if parent is root)', VALUE_DEFAULT, 0)
1954 * Delete categories
1956 * @param array $categories A list of category ids
1957 * @return array
1958 * @since Moodle 2.3
1960 public static function delete_categories($categories) {
1961 global $CFG, $DB;
1962 require_once($CFG->dirroot . "/course/lib.php");
1963 require_once($CFG->libdir . "/coursecatlib.php");
1965 // Validate parameters.
1966 $params = self::validate_parameters(self::delete_categories_parameters(), array('categories' => $categories));
1968 $transaction = $DB->start_delegated_transaction();
1970 foreach ($params['categories'] as $category) {
1971 $deletecat = coursecat::get($category['id'], MUST_EXIST);
1972 $context = context_coursecat::instance($deletecat->id);
1973 require_capability('moodle/category:manage', $context);
1974 self::validate_context($context);
1975 self::validate_context(get_category_or_system_context($deletecat->parent));
1977 if ($category['recursive']) {
1978 // If recursive was specified, then we recursively delete the category's contents.
1979 if ($deletecat->can_delete_full()) {
1980 $deletecat->delete_full(false);
1981 } else {
1982 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
1984 } else {
1985 // In this situation, we don't delete the category's contents, we either move it to newparent or parent.
1986 // If the parent is the root, moving is not supported (because a course must always be inside a category).
1987 // We must move to an existing category.
1988 if (!empty($category['newparent'])) {
1989 $newparentcat = coursecat::get($category['newparent']);
1990 } else {
1991 $newparentcat = coursecat::get($deletecat->parent);
1994 // This operation is not allowed. We must move contents to an existing category.
1995 if (!$newparentcat->id) {
1996 throw new moodle_exception('movecatcontentstoroot');
1999 self::validate_context(context_coursecat::instance($newparentcat->id));
2000 if ($deletecat->can_move_content_to($newparentcat->id)) {
2001 $deletecat->delete_move($newparentcat->id, false);
2002 } else {
2003 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2008 $transaction->allow_commit();
2012 * Returns description of method parameters
2014 * @return external_function_parameters
2015 * @since Moodle 2.3
2017 public static function delete_categories_returns() {
2018 return null;
2022 * Describes the parameters for delete_modules.
2024 * @return external_function_parameters
2025 * @since Moodle 2.5
2027 public static function delete_modules_parameters() {
2028 return new external_function_parameters (
2029 array(
2030 'cmids' => new external_multiple_structure(new external_value(PARAM_INT, 'course module ID',
2031 VALUE_REQUIRED, '', NULL_NOT_ALLOWED), 'Array of course module IDs'),
2037 * Deletes a list of provided module instances.
2039 * @param array $cmids the course module ids
2040 * @since Moodle 2.5
2042 public static function delete_modules($cmids) {
2043 global $CFG, $DB;
2045 // Require course file containing the course delete module function.
2046 require_once($CFG->dirroot . "/course/lib.php");
2048 // Clean the parameters.
2049 $params = self::validate_parameters(self::delete_modules_parameters(), array('cmids' => $cmids));
2051 // Keep track of the course ids we have performed a capability check on to avoid repeating.
2052 $arrcourseschecked = array();
2054 foreach ($params['cmids'] as $cmid) {
2055 // Get the course module.
2056 $cm = $DB->get_record('course_modules', array('id' => $cmid), '*', MUST_EXIST);
2058 // Check if we have not yet confirmed they have permission in this course.
2059 if (!in_array($cm->course, $arrcourseschecked)) {
2060 // Ensure the current user has required permission in this course.
2061 $context = context_course::instance($cm->course);
2062 self::validate_context($context);
2063 // Add to the array.
2064 $arrcourseschecked[] = $cm->course;
2067 // Ensure they can delete this module.
2068 $modcontext = context_module::instance($cm->id);
2069 require_capability('moodle/course:manageactivities', $modcontext);
2071 // Delete the module.
2072 course_delete_module($cm->id);
2077 * Describes the delete_modules return value.
2079 * @return external_single_structure
2080 * @since Moodle 2.5
2082 public static function delete_modules_returns() {
2083 return null;
2087 * Returns description of method parameters
2089 * @return external_function_parameters
2090 * @since Moodle 2.9
2092 public static function view_course_parameters() {
2093 return new external_function_parameters(
2094 array(
2095 'courseid' => new external_value(PARAM_INT, 'id of the course'),
2096 'sectionnumber' => new external_value(PARAM_INT, 'section number', VALUE_DEFAULT, 0)
2102 * Trigger the course viewed event.
2104 * @param int $courseid id of course
2105 * @param int $sectionnumber sectionnumber (0, 1, 2...)
2106 * @return array of warnings and status result
2107 * @since Moodle 2.9
2108 * @throws moodle_exception
2110 public static function view_course($courseid, $sectionnumber = 0) {
2111 global $CFG;
2112 require_once($CFG->dirroot . "/course/lib.php");
2114 $params = self::validate_parameters(self::view_course_parameters(),
2115 array(
2116 'courseid' => $courseid,
2117 'sectionnumber' => $sectionnumber
2120 $warnings = array();
2122 $course = get_course($params['courseid']);
2123 $context = context_course::instance($course->id);
2124 self::validate_context($context);
2126 if (!empty($params['sectionnumber'])) {
2128 // Get section details and check it exists.
2129 $modinfo = get_fast_modinfo($course);
2130 $coursesection = $modinfo->get_section_info($params['sectionnumber'], MUST_EXIST);
2132 // Check user is allowed to see it.
2133 if (!$coursesection->uservisible) {
2134 require_capability('moodle/course:viewhiddensections', $context);
2138 course_view($context, $params['sectionnumber']);
2140 $result = array();
2141 $result['status'] = true;
2142 $result['warnings'] = $warnings;
2143 return $result;
2147 * Returns description of method result value
2149 * @return external_description
2150 * @since Moodle 2.9
2152 public static function view_course_returns() {
2153 return new external_single_structure(
2154 array(
2155 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
2156 'warnings' => new external_warnings()
2162 * Returns description of method parameters
2164 * @return external_function_parameters
2165 * @since Moodle 3.0
2167 public static function search_courses_parameters() {
2168 return new external_function_parameters(
2169 array(
2170 'criterianame' => new external_value(PARAM_ALPHA, 'criteria name
2171 (search, modulelist (only admins), blocklist (only admins), tagid)'),
2172 'criteriavalue' => new external_value(PARAM_RAW, 'criteria value'),
2173 'page' => new external_value(PARAM_INT, 'page number (0 based)', VALUE_DEFAULT, 0),
2174 'perpage' => new external_value(PARAM_INT, 'items per page', VALUE_DEFAULT, 0),
2175 'requiredcapabilities' => new external_multiple_structure(
2176 new external_value(PARAM_CAPABILITY, 'Capability string used to filter courses by permission'),
2177 'Optional list of required capabilities (used to filter the list)', VALUE_DEFAULT, array()
2179 'limittoenrolled' => new external_value(PARAM_BOOL, 'limit to enrolled courses', VALUE_DEFAULT, 0),
2185 * Return the course information that is public (visible by every one)
2187 * @param course_in_list $course course in list object
2188 * @param stdClass $coursecontext course context object
2189 * @return array the course information
2190 * @since Moodle 3.2
2192 protected static function get_course_public_information(course_in_list $course, $coursecontext) {
2194 static $categoriescache = array();
2196 // Category information.
2197 if (!array_key_exists($course->category, $categoriescache)) {
2198 $categoriescache[$course->category] = coursecat::get($course->category, IGNORE_MISSING);
2200 $category = $categoriescache[$course->category];
2202 // Retrieve course overview used files.
2203 $files = array();
2204 foreach ($course->get_course_overviewfiles() as $file) {
2205 $fileurl = moodle_url::make_webservice_pluginfile_url($file->get_contextid(), $file->get_component(),
2206 $file->get_filearea(), null, $file->get_filepath(),
2207 $file->get_filename())->out(false);
2208 $files[] = array(
2209 'filename' => $file->get_filename(),
2210 'fileurl' => $fileurl,
2211 'filesize' => $file->get_filesize(),
2212 'filepath' => $file->get_filepath(),
2213 'mimetype' => $file->get_mimetype(),
2214 'timemodified' => $file->get_timemodified(),
2218 // Retrieve the course contacts,
2219 // we need here the users fullname since if we are not enrolled can be difficult to obtain them via other Web Services.
2220 $coursecontacts = array();
2221 foreach ($course->get_course_contacts() as $contact) {
2222 $coursecontacts[] = array(
2223 'id' => $contact['user']->id,
2224 'fullname' => $contact['username']
2228 // Allowed enrolment methods (maybe we can self-enrol).
2229 $enroltypes = array();
2230 $instances = enrol_get_instances($course->id, true);
2231 foreach ($instances as $instance) {
2232 $enroltypes[] = $instance->enrol;
2235 // Format summary.
2236 list($summary, $summaryformat) =
2237 external_format_text($course->summary, $course->summaryformat, $coursecontext->id, 'course', 'summary', null);
2239 $displayname = get_course_display_name_for_list($course);
2240 $coursereturns = array();
2241 $coursereturns['id'] = $course->id;
2242 $coursereturns['fullname'] = external_format_string($course->fullname, $coursecontext->id);
2243 $coursereturns['displayname'] = external_format_string($displayname, $coursecontext->id);
2244 $coursereturns['shortname'] = external_format_string($course->shortname, $coursecontext->id);
2245 $coursereturns['categoryid'] = $course->category;
2246 $coursereturns['categoryname'] = $category == null ? '' : $category->name;
2247 $coursereturns['summary'] = $summary;
2248 $coursereturns['summaryformat'] = $summaryformat;
2249 $coursereturns['summaryfiles'] = external_util::get_area_files($coursecontext->id, 'course', 'summary', false, false);
2250 $coursereturns['overviewfiles'] = $files;
2251 $coursereturns['contacts'] = $coursecontacts;
2252 $coursereturns['enrollmentmethods'] = $enroltypes;
2253 $coursereturns['sortorder'] = $course->sortorder;
2254 return $coursereturns;
2258 * Search courses following the specified criteria.
2260 * @param string $criterianame Criteria name (search, modulelist (only admins), blocklist (only admins), tagid)
2261 * @param string $criteriavalue Criteria value
2262 * @param int $page Page number (for pagination)
2263 * @param int $perpage Items per page
2264 * @param array $requiredcapabilities Optional list of required capabilities (used to filter the list).
2265 * @param int $limittoenrolled Limit to only enrolled courses
2266 * @return array of course objects and warnings
2267 * @since Moodle 3.0
2268 * @throws moodle_exception
2270 public static function search_courses($criterianame,
2271 $criteriavalue,
2272 $page=0,
2273 $perpage=0,
2274 $requiredcapabilities=array(),
2275 $limittoenrolled=0) {
2276 global $CFG;
2277 require_once($CFG->libdir . '/coursecatlib.php');
2279 $warnings = array();
2281 $parameters = array(
2282 'criterianame' => $criterianame,
2283 'criteriavalue' => $criteriavalue,
2284 'page' => $page,
2285 'perpage' => $perpage,
2286 'requiredcapabilities' => $requiredcapabilities
2288 $params = self::validate_parameters(self::search_courses_parameters(), $parameters);
2289 self::validate_context(context_system::instance());
2291 $allowedcriterianames = array('search', 'modulelist', 'blocklist', 'tagid');
2292 if (!in_array($params['criterianame'], $allowedcriterianames)) {
2293 throw new invalid_parameter_exception('Invalid value for criterianame parameter (value: '.$params['criterianame'].'),' .
2294 'allowed values are: '.implode(',', $allowedcriterianames));
2297 if ($params['criterianame'] == 'modulelist' or $params['criterianame'] == 'blocklist') {
2298 require_capability('moodle/site:config', context_system::instance());
2301 $paramtype = array(
2302 'search' => PARAM_RAW,
2303 'modulelist' => PARAM_PLUGIN,
2304 'blocklist' => PARAM_INT,
2305 'tagid' => PARAM_INT
2307 $params['criteriavalue'] = clean_param($params['criteriavalue'], $paramtype[$params['criterianame']]);
2309 // Prepare the search API options.
2310 $searchcriteria = array();
2311 $searchcriteria[$params['criterianame']] = $params['criteriavalue'];
2313 $options = array();
2314 if ($params['perpage'] != 0) {
2315 $offset = $params['page'] * $params['perpage'];
2316 $options = array('offset' => $offset, 'limit' => $params['perpage']);
2319 // Search the courses.
2320 $courses = coursecat::search_courses($searchcriteria, $options, $params['requiredcapabilities']);
2321 $totalcount = coursecat::search_courses_count($searchcriteria, $options, $params['requiredcapabilities']);
2323 if (!empty($limittoenrolled)) {
2324 // Get the courses where the current user has access.
2325 $enrolled = enrol_get_my_courses(array('id', 'cacherev'));
2328 $finalcourses = array();
2329 $categoriescache = array();
2331 foreach ($courses as $course) {
2332 if (!empty($limittoenrolled)) {
2333 // Filter out not enrolled courses.
2334 if (!isset($enrolled[$course->id])) {
2335 $totalcount--;
2336 continue;
2340 $coursecontext = context_course::instance($course->id);
2342 $finalcourses[] = self::get_course_public_information($course, $coursecontext);
2345 return array(
2346 'total' => $totalcount,
2347 'courses' => $finalcourses,
2348 'warnings' => $warnings
2353 * Returns a course structure definition
2355 * @param boolean $onlypublicdata set to true, to retrieve only fields viewable by anyone when the course is visible
2356 * @return array the course structure
2357 * @since Moodle 3.2
2359 protected static function get_course_structure($onlypublicdata = true) {
2360 $coursestructure = array(
2361 'id' => new external_value(PARAM_INT, 'course id'),
2362 'fullname' => new external_value(PARAM_TEXT, 'course full name'),
2363 'displayname' => new external_value(PARAM_TEXT, 'course display name'),
2364 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
2365 'categoryid' => new external_value(PARAM_INT, 'category id'),
2366 'categoryname' => new external_value(PARAM_TEXT, 'category name'),
2367 'sortorder' => new external_value(PARAM_INT, 'Sort order in the category', VALUE_OPTIONAL),
2368 'summary' => new external_value(PARAM_RAW, 'summary'),
2369 'summaryformat' => new external_format_value('summary'),
2370 'summaryfiles' => new external_files('summary files in the summary field', VALUE_OPTIONAL),
2371 'overviewfiles' => new external_files('additional overview files attached to this course'),
2372 'contacts' => new external_multiple_structure(
2373 new external_single_structure(
2374 array(
2375 'id' => new external_value(PARAM_INT, 'contact user id'),
2376 'fullname' => new external_value(PARAM_NOTAGS, 'contact user fullname'),
2379 'contact users'
2381 'enrollmentmethods' => new external_multiple_structure(
2382 new external_value(PARAM_PLUGIN, 'enrollment method'),
2383 'enrollment methods list'
2387 if (!$onlypublicdata) {
2388 $extra = array(
2389 'idnumber' => new external_value(PARAM_RAW, 'Id number', VALUE_OPTIONAL),
2390 'format' => new external_value(PARAM_PLUGIN, 'Course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
2391 'showgrades' => new external_value(PARAM_INT, '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
2392 'newsitems' => new external_value(PARAM_INT, 'Number of recent items appearing on the course page', VALUE_OPTIONAL),
2393 'startdate' => new external_value(PARAM_INT, 'Timestamp when the course start', VALUE_OPTIONAL),
2394 'maxbytes' => new external_value(PARAM_INT, 'Largest size of file that can be uploaded into', VALUE_OPTIONAL),
2395 'showreports' => new external_value(PARAM_INT, 'Are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
2396 'visible' => new external_value(PARAM_INT, '1: available to student, 0:not available', VALUE_OPTIONAL),
2397 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
2398 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
2399 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
2400 'enablecompletion' => new external_value(PARAM_INT, 'Completion enabled? 1: yes 0: no', VALUE_OPTIONAL),
2401 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
2402 'lang' => new external_value(PARAM_SAFEDIR, 'Forced course language', VALUE_OPTIONAL),
2403 'theme' => new external_value(PARAM_PLUGIN, 'Fame of the forced theme', VALUE_OPTIONAL),
2404 'marker' => new external_value(PARAM_INT, 'Current course marker', VALUE_OPTIONAL),
2405 'legacyfiles' => new external_value(PARAM_INT, 'If legacy files are enabled', VALUE_OPTIONAL),
2406 'calendartype' => new external_value(PARAM_PLUGIN, 'Calendar type', VALUE_OPTIONAL),
2407 'timecreated' => new external_value(PARAM_INT, 'Time when the course was created', VALUE_OPTIONAL),
2408 'timemodified' => new external_value(PARAM_INT, 'Last time the course was updated', VALUE_OPTIONAL),
2409 'requested' => new external_value(PARAM_INT, 'If is a requested course', VALUE_OPTIONAL),
2410 'cacherev' => new external_value(PARAM_INT, 'Cache revision number', VALUE_OPTIONAL),
2411 'filters' => new external_multiple_structure(
2412 new external_single_structure(
2413 array(
2414 'filter' => new external_value(PARAM_PLUGIN, 'Filter plugin name'),
2415 'localstate' => new external_value(PARAM_INT, 'Filter state: 1 for on, -1 for off, 0 if inherit'),
2416 'inheritedstate' => new external_value(PARAM_INT, '1 or 0 to use when localstate is set to inherit'),
2419 'Course filters', VALUE_OPTIONAL
2422 $coursestructure = array_merge($coursestructure, $extra);
2424 return new external_single_structure($coursestructure);
2428 * Returns description of method result value
2430 * @return external_description
2431 * @since Moodle 3.0
2433 public static function search_courses_returns() {
2434 return new external_single_structure(
2435 array(
2436 'total' => new external_value(PARAM_INT, 'total course count'),
2437 'courses' => new external_multiple_structure(self::get_course_structure(), 'course'),
2438 'warnings' => new external_warnings()
2444 * Returns description of method parameters
2446 * @return external_function_parameters
2447 * @since Moodle 3.0
2449 public static function get_course_module_parameters() {
2450 return new external_function_parameters(
2451 array(
2452 'cmid' => new external_value(PARAM_INT, 'The course module id')
2458 * Return information about a course module.
2460 * @param int $cmid the course module id
2461 * @return array of warnings and the course module
2462 * @since Moodle 3.0
2463 * @throws moodle_exception
2465 public static function get_course_module($cmid) {
2466 global $CFG, $DB;
2468 $params = self::validate_parameters(self::get_course_module_parameters(), array('cmid' => $cmid));
2469 $warnings = array();
2471 $cm = get_coursemodule_from_id(null, $params['cmid'], 0, true, MUST_EXIST);
2472 $context = context_module::instance($cm->id);
2473 self::validate_context($context);
2475 // If the user has permissions to manage the activity, return all the information.
2476 if (has_capability('moodle/course:manageactivities', $context)) {
2477 require_once($CFG->dirroot . '/course/modlib.php');
2478 require_once($CFG->libdir . '/gradelib.php');
2480 $info = $cm;
2481 // Get the extra information: grade, advanced grading and outcomes data.
2482 $course = get_course($cm->course);
2483 list($newcm, $newcontext, $module, $extrainfo, $cw) = get_moduleinfo_data($cm, $course);
2484 // Grades.
2485 $gradeinfo = array('grade', 'gradepass', 'gradecat');
2486 foreach ($gradeinfo as $gfield) {
2487 if (isset($extrainfo->{$gfield})) {
2488 $info->{$gfield} = $extrainfo->{$gfield};
2491 if (isset($extrainfo->grade) and $extrainfo->grade < 0) {
2492 $info->scale = $DB->get_field('scale', 'scale', array('id' => abs($extrainfo->grade)));
2494 // Advanced grading.
2495 if (isset($extrainfo->_advancedgradingdata)) {
2496 $info->advancedgrading = array();
2497 foreach ($extrainfo as $key => $val) {
2498 if (strpos($key, 'advancedgradingmethod_') === 0) {
2499 $info->advancedgrading[] = array(
2500 'area' => str_replace('advancedgradingmethod_', '', $key),
2501 'method' => $val
2506 // Outcomes.
2507 foreach ($extrainfo as $key => $val) {
2508 if (strpos($key, 'outcome_') === 0) {
2509 if (!isset($info->outcomes)) {
2510 $info->outcomes = array();
2512 $id = str_replace('outcome_', '', $key);
2513 $outcome = grade_outcome::fetch(array('id' => $id));
2514 $scaleitems = $outcome->load_scale();
2515 $info->outcomes[] = array(
2516 'id' => $id,
2517 'name' => external_format_string($outcome->get_name(), $context->id),
2518 'scale' => $scaleitems->scale
2522 } else {
2523 // Return information is safe to show to any user.
2524 $info = new stdClass();
2525 $info->id = $cm->id;
2526 $info->course = $cm->course;
2527 $info->module = $cm->module;
2528 $info->modname = $cm->modname;
2529 $info->instance = $cm->instance;
2530 $info->section = $cm->section;
2531 $info->sectionnum = $cm->sectionnum;
2532 $info->groupmode = $cm->groupmode;
2533 $info->groupingid = $cm->groupingid;
2534 $info->completion = $cm->completion;
2536 // Format name.
2537 $info->name = external_format_string($cm->name, $context->id);
2538 $result = array();
2539 $result['cm'] = $info;
2540 $result['warnings'] = $warnings;
2541 return $result;
2545 * Returns description of method result value
2547 * @return external_description
2548 * @since Moodle 3.0
2550 public static function get_course_module_returns() {
2551 return new external_single_structure(
2552 array(
2553 'cm' => new external_single_structure(
2554 array(
2555 'id' => new external_value(PARAM_INT, 'The course module id'),
2556 'course' => new external_value(PARAM_INT, 'The course id'),
2557 'module' => new external_value(PARAM_INT, 'The module type id'),
2558 'name' => new external_value(PARAM_RAW, 'The activity name'),
2559 'modname' => new external_value(PARAM_COMPONENT, 'The module component name (forum, assign, etc..)'),
2560 'instance' => new external_value(PARAM_INT, 'The activity instance id'),
2561 'section' => new external_value(PARAM_INT, 'The module section id'),
2562 'sectionnum' => new external_value(PARAM_INT, 'The module section number'),
2563 'groupmode' => new external_value(PARAM_INT, 'Group mode'),
2564 'groupingid' => new external_value(PARAM_INT, 'Grouping id'),
2565 'completion' => new external_value(PARAM_INT, 'If completion is enabled'),
2566 'idnumber' => new external_value(PARAM_RAW, 'Module id number', VALUE_OPTIONAL),
2567 'added' => new external_value(PARAM_INT, 'Time added', VALUE_OPTIONAL),
2568 'score' => new external_value(PARAM_INT, 'Score', VALUE_OPTIONAL),
2569 'indent' => new external_value(PARAM_INT, 'Indentation', VALUE_OPTIONAL),
2570 'visible' => new external_value(PARAM_INT, 'If visible', VALUE_OPTIONAL),
2571 'visibleoncoursepage' => new external_value(PARAM_INT, 'If visible on course page', VALUE_OPTIONAL),
2572 'visibleold' => new external_value(PARAM_INT, 'Visible old', VALUE_OPTIONAL),
2573 'completiongradeitemnumber' => new external_value(PARAM_INT, 'Completion grade item', VALUE_OPTIONAL),
2574 'completionview' => new external_value(PARAM_INT, 'Completion view setting', VALUE_OPTIONAL),
2575 'completionexpected' => new external_value(PARAM_INT, 'Completion time expected', VALUE_OPTIONAL),
2576 'showdescription' => new external_value(PARAM_INT, 'If the description is showed', VALUE_OPTIONAL),
2577 'availability' => new external_value(PARAM_RAW, 'Availability settings', VALUE_OPTIONAL),
2578 'grade' => new external_value(PARAM_INT, 'Grade (max value or scale id)', VALUE_OPTIONAL),
2579 'scale' => new external_value(PARAM_TEXT, 'Scale items (if used)', VALUE_OPTIONAL),
2580 'gradepass' => new external_value(PARAM_RAW, 'Grade to pass (float)', VALUE_OPTIONAL),
2581 'gradecat' => new external_value(PARAM_INT, 'Grade category', VALUE_OPTIONAL),
2582 'advancedgrading' => new external_multiple_structure(
2583 new external_single_structure(
2584 array(
2585 'area' => new external_value(PARAM_AREA, 'Gradable area name'),
2586 'method' => new external_value(PARAM_COMPONENT, 'Grading method'),
2589 'Advanced grading settings', VALUE_OPTIONAL
2591 'outcomes' => new external_multiple_structure(
2592 new external_single_structure(
2593 array(
2594 'id' => new external_value(PARAM_ALPHANUMEXT, 'Outcome id'),
2595 'name' => new external_value(PARAM_TEXT, 'Outcome full name'),
2596 'scale' => new external_value(PARAM_TEXT, 'Scale items')
2599 'Outcomes information', VALUE_OPTIONAL
2603 'warnings' => new external_warnings()
2609 * Returns description of method parameters
2611 * @return external_function_parameters
2612 * @since Moodle 3.0
2614 public static function get_course_module_by_instance_parameters() {
2615 return new external_function_parameters(
2616 array(
2617 'module' => new external_value(PARAM_COMPONENT, 'The module name'),
2618 'instance' => new external_value(PARAM_INT, 'The module instance id')
2624 * Return information about a course module.
2626 * @param string $module the module name
2627 * @param int $instance the activity instance id
2628 * @return array of warnings and the course module
2629 * @since Moodle 3.0
2630 * @throws moodle_exception
2632 public static function get_course_module_by_instance($module, $instance) {
2634 $params = self::validate_parameters(self::get_course_module_by_instance_parameters(),
2635 array(
2636 'module' => $module,
2637 'instance' => $instance,
2640 $warnings = array();
2641 $cm = get_coursemodule_from_instance($params['module'], $params['instance'], 0, false, MUST_EXIST);
2643 return self::get_course_module($cm->id);
2647 * Returns description of method result value
2649 * @return external_description
2650 * @since Moodle 3.0
2652 public static function get_course_module_by_instance_returns() {
2653 return self::get_course_module_returns();
2657 * Returns description of method parameters
2659 * @deprecated since 3.3
2661 * @return external_function_parameters
2662 * @since Moodle 3.2
2664 public static function get_activities_overview_parameters() {
2665 return new external_function_parameters(
2666 array(
2667 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2673 * Return activities overview for the given courses.
2675 * @deprecated since 3.3
2677 * @param array $courseids a list of course ids
2678 * @return array of warnings and the activities overview
2679 * @since Moodle 3.2
2680 * @throws moodle_exception
2682 public static function get_activities_overview($courseids) {
2683 global $USER;
2685 // Parameter validation.
2686 $params = self::validate_parameters(self::get_activities_overview_parameters(), array('courseids' => $courseids));
2687 $courseoverviews = array();
2689 list($courses, $warnings) = external_util::validate_courses($params['courseids']);
2691 if (!empty($courses)) {
2692 // Add lastaccess to each course (required by print_overview function).
2693 // We need the complete user data, the ws server does not load a complete one.
2694 $user = get_complete_user_data('id', $USER->id);
2695 foreach ($courses as $course) {
2696 if (isset($user->lastcourseaccess[$course->id])) {
2697 $course->lastaccess = $user->lastcourseaccess[$course->id];
2698 } else {
2699 $course->lastaccess = 0;
2703 $overviews = array();
2704 if ($modules = get_plugin_list_with_function('mod', 'print_overview')) {
2705 foreach ($modules as $fname) {
2706 $fname($courses, $overviews);
2710 // Format output.
2711 foreach ($overviews as $courseid => $modules) {
2712 $courseoverviews[$courseid]['id'] = $courseid;
2713 $courseoverviews[$courseid]['overviews'] = array();
2715 foreach ($modules as $modname => $overviewtext) {
2716 $courseoverviews[$courseid]['overviews'][] = array(
2717 'module' => $modname,
2718 'overviewtext' => $overviewtext // This text doesn't need formatting.
2724 $result = array(
2725 'courses' => $courseoverviews,
2726 'warnings' => $warnings
2728 return $result;
2732 * Returns description of method result value
2734 * @deprecated since 3.3
2736 * @return external_description
2737 * @since Moodle 3.2
2739 public static function get_activities_overview_returns() {
2740 return new external_single_structure(
2741 array(
2742 'courses' => new external_multiple_structure(
2743 new external_single_structure(
2744 array(
2745 'id' => new external_value(PARAM_INT, 'Course id'),
2746 'overviews' => new external_multiple_structure(
2747 new external_single_structure(
2748 array(
2749 'module' => new external_value(PARAM_PLUGIN, 'Module name'),
2750 'overviewtext' => new external_value(PARAM_RAW, 'Overview text'),
2755 ), 'List of courses'
2757 'warnings' => new external_warnings()
2763 * Marking the method as deprecated.
2765 * @return bool
2767 public static function get_activities_overview_is_deprecated() {
2768 return true;
2772 * Returns description of method parameters
2774 * @return external_function_parameters
2775 * @since Moodle 3.2
2777 public static function get_user_navigation_options_parameters() {
2778 return new external_function_parameters(
2779 array(
2780 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2786 * Return a list of navigation options in a set of courses that are avaialable or not for the current user.
2788 * @param array $courseids a list of course ids
2789 * @return array of warnings and the options availability
2790 * @since Moodle 3.2
2791 * @throws moodle_exception
2793 public static function get_user_navigation_options($courseids) {
2794 global $CFG;
2795 require_once($CFG->dirroot . '/course/lib.php');
2797 // Parameter validation.
2798 $params = self::validate_parameters(self::get_user_navigation_options_parameters(), array('courseids' => $courseids));
2799 $courseoptions = array();
2801 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
2803 if (!empty($courses)) {
2804 foreach ($courses as $course) {
2805 // Fix the context for the frontpage.
2806 if ($course->id == SITEID) {
2807 $course->context = context_system::instance();
2809 $navoptions = course_get_user_navigation_options($course->context, $course);
2810 $options = array();
2811 foreach ($navoptions as $name => $available) {
2812 $options[] = array(
2813 'name' => $name,
2814 'available' => $available,
2818 $courseoptions[] = array(
2819 'id' => $course->id,
2820 'options' => $options
2825 $result = array(
2826 'courses' => $courseoptions,
2827 'warnings' => $warnings
2829 return $result;
2833 * Returns description of method result value
2835 * @return external_description
2836 * @since Moodle 3.2
2838 public static function get_user_navigation_options_returns() {
2839 return new external_single_structure(
2840 array(
2841 'courses' => new external_multiple_structure(
2842 new external_single_structure(
2843 array(
2844 'id' => new external_value(PARAM_INT, 'Course id'),
2845 'options' => new external_multiple_structure(
2846 new external_single_structure(
2847 array(
2848 'name' => new external_value(PARAM_ALPHANUMEXT, 'Option name'),
2849 'available' => new external_value(PARAM_BOOL, 'Whether the option is available or not'),
2854 ), 'List of courses'
2856 'warnings' => new external_warnings()
2862 * Returns description of method parameters
2864 * @return external_function_parameters
2865 * @since Moodle 3.2
2867 public static function get_user_administration_options_parameters() {
2868 return new external_function_parameters(
2869 array(
2870 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2876 * Return a list of administration options in a set of courses that are available or not for the current user.
2878 * @param array $courseids a list of course ids
2879 * @return array of warnings and the options availability
2880 * @since Moodle 3.2
2881 * @throws moodle_exception
2883 public static function get_user_administration_options($courseids) {
2884 global $CFG;
2885 require_once($CFG->dirroot . '/course/lib.php');
2887 // Parameter validation.
2888 $params = self::validate_parameters(self::get_user_administration_options_parameters(), array('courseids' => $courseids));
2889 $courseoptions = array();
2891 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
2893 if (!empty($courses)) {
2894 foreach ($courses as $course) {
2895 $adminoptions = course_get_user_administration_options($course, $course->context);
2896 $options = array();
2897 foreach ($adminoptions as $name => $available) {
2898 $options[] = array(
2899 'name' => $name,
2900 'available' => $available,
2904 $courseoptions[] = array(
2905 'id' => $course->id,
2906 'options' => $options
2911 $result = array(
2912 'courses' => $courseoptions,
2913 'warnings' => $warnings
2915 return $result;
2919 * Returns description of method result value
2921 * @return external_description
2922 * @since Moodle 3.2
2924 public static function get_user_administration_options_returns() {
2925 return self::get_user_navigation_options_returns();
2929 * Returns description of method parameters
2931 * @return external_function_parameters
2932 * @since Moodle 3.2
2934 public static function get_courses_by_field_parameters() {
2935 return new external_function_parameters(
2936 array(
2937 'field' => new external_value(PARAM_ALPHA, 'The field to search can be left empty for all courses or:
2938 id: course id
2939 ids: comma separated course ids
2940 shortname: course short name
2941 idnumber: course id number
2942 category: category id the course belongs to
2943 ', VALUE_DEFAULT, ''),
2944 'value' => new external_value(PARAM_RAW, 'The value to match', VALUE_DEFAULT, '')
2951 * Get courses matching a specific field (id/s, shortname, idnumber, category)
2953 * @param string $field field name to search, or empty for all courses
2954 * @param string $value value to search
2955 * @return array list of courses and warnings
2956 * @throws invalid_parameter_exception
2957 * @since Moodle 3.2
2959 public static function get_courses_by_field($field = '', $value = '') {
2960 global $DB, $CFG;
2961 require_once($CFG->libdir . '/coursecatlib.php');
2962 require_once($CFG->libdir . '/filterlib.php');
2964 $params = self::validate_parameters(self::get_courses_by_field_parameters(),
2965 array(
2966 'field' => $field,
2967 'value' => $value,
2970 $warnings = array();
2972 if (empty($params['field'])) {
2973 $courses = $DB->get_records('course', null, 'id ASC');
2974 } else {
2975 switch ($params['field']) {
2976 case 'id':
2977 case 'category':
2978 $value = clean_param($params['value'], PARAM_INT);
2979 break;
2980 case 'ids':
2981 $value = clean_param($params['value'], PARAM_SEQUENCE);
2982 break;
2983 case 'shortname':
2984 $value = clean_param($params['value'], PARAM_TEXT);
2985 break;
2986 case 'idnumber':
2987 $value = clean_param($params['value'], PARAM_RAW);
2988 break;
2989 default:
2990 throw new invalid_parameter_exception('Invalid field name');
2993 if ($params['field'] === 'ids') {
2994 $courses = $DB->get_records_list('course', 'id', explode(',', $value), 'id ASC');
2995 } else {
2996 $courses = $DB->get_records('course', array($params['field'] => $value), 'id ASC');
3000 $coursesdata = array();
3001 foreach ($courses as $course) {
3002 $context = context_course::instance($course->id);
3003 $canupdatecourse = has_capability('moodle/course:update', $context);
3004 $canviewhiddencourses = has_capability('moodle/course:viewhiddencourses', $context);
3006 // Check if the course is visible in the site for the user.
3007 if (!$course->visible and !$canviewhiddencourses and !$canupdatecourse) {
3008 continue;
3010 // Get the public course information, even if we are not enrolled.
3011 $courseinlist = new course_in_list($course);
3012 $coursesdata[$course->id] = self::get_course_public_information($courseinlist, $context);
3014 // Now, check if we have access to the course.
3015 try {
3016 self::validate_context($context);
3017 } catch (Exception $e) {
3018 continue;
3020 // Return information for any user that can access the course.
3021 $coursefields = array('format', 'showgrades', 'newsitems', 'startdate', 'maxbytes', 'showreports', 'visible',
3022 'groupmode', 'groupmodeforce', 'defaultgroupingid', 'enablecompletion', 'completionnotify', 'lang', 'theme',
3023 'marker');
3025 // Course filters.
3026 $coursesdata[$course->id]['filters'] = filter_get_available_in_context($context);
3028 // Information for managers only.
3029 if ($canupdatecourse) {
3030 $managerfields = array('idnumber', 'legacyfiles', 'calendartype', 'timecreated', 'timemodified', 'requested',
3031 'cacherev');
3032 $coursefields = array_merge($coursefields, $managerfields);
3035 // Populate fields.
3036 foreach ($coursefields as $field) {
3037 $coursesdata[$course->id][$field] = $course->{$field};
3041 return array(
3042 'courses' => $coursesdata,
3043 'warnings' => $warnings
3048 * Returns description of method result value
3050 * @return external_description
3051 * @since Moodle 3.2
3053 public static function get_courses_by_field_returns() {
3054 // Course structure, including not only public viewable fields.
3055 return new external_single_structure(
3056 array(
3057 'courses' => new external_multiple_structure(self::get_course_structure(false), 'Course'),
3058 'warnings' => new external_warnings()
3064 * Returns description of method parameters
3066 * @return external_function_parameters
3067 * @since Moodle 3.2
3069 public static function check_updates_parameters() {
3070 return new external_function_parameters(
3071 array(
3072 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3073 'tocheck' => new external_multiple_structure(
3074 new external_single_structure(
3075 array(
3076 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level for the file location.
3077 Only module supported right now.'),
3078 'id' => new external_value(PARAM_INT, 'Context instance id'),
3079 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3082 'Instances to check'
3084 'filter' => new external_multiple_structure(
3085 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3086 gradeitems, outcomes'),
3087 'Check only for updates in these areas', VALUE_DEFAULT, array()
3094 * Check if there is updates affecting the user for the given course and contexts.
3095 * Right now only modules are supported.
3096 * This WS calls mod_check_updates_since for each module to check if there is any update the user should we aware of.
3098 * @param int $courseid the list of modules to check
3099 * @param array $tocheck the list of modules to check
3100 * @param array $filter check only for updates in these areas
3101 * @return array list of updates and warnings
3102 * @throws moodle_exception
3103 * @since Moodle 3.2
3105 public static function check_updates($courseid, $tocheck, $filter = array()) {
3106 global $CFG, $DB;
3108 $params = self::validate_parameters(
3109 self::check_updates_parameters(),
3110 array(
3111 'courseid' => $courseid,
3112 'tocheck' => $tocheck,
3113 'filter' => $filter,
3117 $course = get_course($params['courseid']);
3118 $context = context_course::instance($course->id);
3119 self::validate_context($context);
3121 list($instances, $warnings) = course_check_updates($course, $params['tocheck'], $filter);
3123 $instancesformatted = array();
3124 foreach ($instances as $instance) {
3125 $updates = array();
3126 foreach ($instance['updates'] as $name => $data) {
3127 if (empty($data->updated)) {
3128 continue;
3130 $updatedata = array(
3131 'name' => $name,
3133 if (!empty($data->timeupdated)) {
3134 $updatedata['timeupdated'] = $data->timeupdated;
3136 if (!empty($data->itemids)) {
3137 $updatedata['itemids'] = $data->itemids;
3139 $updates[] = $updatedata;
3141 if (!empty($updates)) {
3142 $instancesformatted[] = array(
3143 'contextlevel' => $instance['contextlevel'],
3144 'id' => $instance['id'],
3145 'updates' => $updates
3150 return array(
3151 'instances' => $instancesformatted,
3152 'warnings' => $warnings
3157 * Returns description of method result value
3159 * @return external_description
3160 * @since Moodle 3.2
3162 public static function check_updates_returns() {
3163 return new external_single_structure(
3164 array(
3165 'instances' => new external_multiple_structure(
3166 new external_single_structure(
3167 array(
3168 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level'),
3169 'id' => new external_value(PARAM_INT, 'Instance id'),
3170 'updates' => new external_multiple_structure(
3171 new external_single_structure(
3172 array(
3173 'name' => new external_value(PARAM_ALPHANUMEXT, 'Name of the area updated.'),
3174 'timeupdated' => new external_value(PARAM_INT, 'Last time was updated', VALUE_OPTIONAL),
3175 'itemids' => new external_multiple_structure(
3176 new external_value(PARAM_INT, 'Instance id'),
3177 'The ids of the items updated',
3178 VALUE_OPTIONAL
3186 'warnings' => new external_warnings()
3192 * Returns description of method parameters
3194 * @return external_function_parameters
3195 * @since Moodle 3.3
3197 public static function get_updates_since_parameters() {
3198 return new external_function_parameters(
3199 array(
3200 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3201 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3202 'filter' => new external_multiple_structure(
3203 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3204 gradeitems, outcomes'),
3205 'Check only for updates in these areas', VALUE_DEFAULT, array()
3212 * Check if there are updates affecting the user for the given course since the given time stamp.
3214 * This function is a wrapper of self::check_updates for retrieving all the updates since a given time for all the activities.
3216 * @param int $courseid the list of modules to check
3217 * @param int $since check updates since this time stamp
3218 * @param array $filter check only for updates in these areas
3219 * @return array list of updates and warnings
3220 * @throws moodle_exception
3221 * @since Moodle 3.3
3223 public static function get_updates_since($courseid, $since, $filter = array()) {
3224 global $CFG, $DB;
3226 $params = self::validate_parameters(
3227 self::get_updates_since_parameters(),
3228 array(
3229 'courseid' => $courseid,
3230 'since' => $since,
3231 'filter' => $filter,
3235 $course = get_course($params['courseid']);
3236 $modinfo = get_fast_modinfo($course);
3237 $tocheck = array();
3239 // Retrieve all the visible course modules for the current user.
3240 $cms = $modinfo->get_cms();
3241 foreach ($cms as $cm) {
3242 if (!$cm->uservisible) {
3243 continue;
3245 $tocheck[] = array(
3246 'id' => $cm->id,
3247 'contextlevel' => 'module',
3248 'since' => $params['since'],
3252 return self::check_updates($course->id, $tocheck, $params['filter']);
3256 * Returns description of method result value
3258 * @return external_description
3259 * @since Moodle 3.3
3261 public static function get_updates_since_returns() {
3262 return self::check_updates_returns();
3266 * Parameters for function edit_module()
3268 * @since Moodle 3.3
3269 * @return external_function_parameters
3271 public static function edit_module_parameters() {
3272 return new external_function_parameters(
3273 array(
3274 'action' => new external_value(PARAM_ALPHA,
3275 'action: hide, show, stealth, duplicate, delete, moveleft, moveright, group...', VALUE_REQUIRED),
3276 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3277 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3282 * Performs one of the edit module actions and return new html for AJAX
3284 * Returns html to replace the current module html with, for example:
3285 * - empty string for "delete" action,
3286 * - two modules html for "duplicate" action
3287 * - updated module html for everything else
3289 * Throws exception if operation is not permitted/possible
3291 * @since Moodle 3.3
3292 * @param string $action
3293 * @param int $id
3294 * @param null|int $sectionreturn
3295 * @return string
3297 public static function edit_module($action, $id, $sectionreturn = null) {
3298 global $PAGE, $DB;
3299 // Validate and normalize parameters.
3300 $params = self::validate_parameters(self::edit_module_parameters(),
3301 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3302 $action = $params['action'];
3303 $id = $params['id'];
3304 $sectionreturn = $params['sectionreturn'];
3306 list($course, $cm) = get_course_and_cm_from_cmid($id);
3307 $modcontext = context_module::instance($cm->id);
3308 $coursecontext = context_course::instance($course->id);
3309 self::validate_context($modcontext);
3310 $courserenderer = $PAGE->get_renderer('core', 'course');
3311 $completioninfo = new completion_info($course);
3313 switch($action) {
3314 case 'hide':
3315 case 'show':
3316 case 'stealth':
3317 require_capability('moodle/course:activityvisibility', $modcontext);
3318 $visible = ($action === 'hide') ? 0 : 1;
3319 $visibleoncoursepage = ($action === 'stealth') ? 0 : 1;
3320 set_coursemodule_visible($id, $visible, $visibleoncoursepage);
3321 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3322 break;
3323 case 'duplicate':
3324 require_capability('moodle/course:manageactivities', $coursecontext);
3325 require_capability('moodle/backup:backuptargetimport', $coursecontext);
3326 require_capability('moodle/restore:restoretargetimport', $coursecontext);
3327 if (!course_allowed_module($course, $cm->modname)) {
3328 throw new moodle_exception('No permission to create that activity');
3330 if ($newcm = duplicate_module($course, $cm)) {
3331 $cm = get_fast_modinfo($course)->get_cm($id);
3332 $newcm = get_fast_modinfo($course)->get_cm($newcm->id);
3333 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn) .
3334 $courserenderer->course_section_cm_list_item($course, $completioninfo, $newcm, $sectionreturn);
3336 break;
3337 case 'groupsseparate':
3338 case 'groupsvisible':
3339 case 'groupsnone':
3340 require_capability('moodle/course:manageactivities', $modcontext);
3341 if ($action === 'groupsseparate') {
3342 $newgroupmode = SEPARATEGROUPS;
3343 } else if ($action === 'groupsvisible') {
3344 $newgroupmode = VISIBLEGROUPS;
3345 } else {
3346 $newgroupmode = NOGROUPS;
3348 if (set_coursemodule_groupmode($cm->id, $newgroupmode)) {
3349 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3351 break;
3352 case 'moveleft':
3353 case 'moveright':
3354 require_capability('moodle/course:manageactivities', $modcontext);
3355 $indent = $cm->indent + (($action === 'moveright') ? 1 : -1);
3356 if ($cm->indent >= 0) {
3357 $DB->update_record('course_modules', array('id' => $cm->id, 'indent' => $indent));
3358 rebuild_course_cache($cm->course);
3360 break;
3361 case 'delete':
3362 require_capability('moodle/course:manageactivities', $modcontext);
3363 course_delete_module($cm->id, true);
3364 return '';
3365 default:
3366 throw new coding_exception('Unrecognised action');
3369 $cm = get_fast_modinfo($course)->get_cm($id);
3370 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn);
3374 * Return structure for edit_module()
3376 * @since Moodle 3.3
3377 * @return external_description
3379 public static function edit_module_returns() {
3380 return new external_value(PARAM_RAW, 'html to replace the current module with');
3384 * Parameters for function get_module()
3386 * @since Moodle 3.3
3387 * @return external_function_parameters
3389 public static function get_module_parameters() {
3390 return new external_function_parameters(
3391 array(
3392 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3393 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3398 * Returns html for displaying one activity module on course page
3400 * @since Moodle 3.3
3401 * @param int $id
3402 * @param null|int $sectionreturn
3403 * @return string
3405 public static function get_module($id, $sectionreturn = null) {
3406 global $PAGE;
3407 // Validate and normalize parameters.
3408 $params = self::validate_parameters(self::get_module_parameters(),
3409 array('id' => $id, 'sectionreturn' => $sectionreturn));
3410 $id = $params['id'];
3411 $sectionreturn = $params['sectionreturn'];
3413 // Validate access to the course (note, this is html for the course view page, we don't validate access to the module).
3414 list($course, $cm) = get_course_and_cm_from_cmid($id);
3415 self::validate_context(context_course::instance($course->id));
3417 $courserenderer = $PAGE->get_renderer('core', 'course');
3418 $completioninfo = new completion_info($course);
3419 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn);
3423 * Return structure for edit_module()
3425 * @since Moodle 3.3
3426 * @return external_description
3428 public static function get_module_returns() {
3429 return new external_value(PARAM_RAW, 'html to replace the current module with');
3433 * Parameters for function edit_section()
3435 * @since Moodle 3.3
3436 * @return external_function_parameters
3438 public static function edit_section_parameters() {
3439 return new external_function_parameters(
3440 array(
3441 'action' => new external_value(PARAM_ALPHA, 'action: hide, show, stealth, setmarker, removemarker', VALUE_REQUIRED),
3442 'id' => new external_value(PARAM_INT, 'course section id', VALUE_REQUIRED),
3443 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3448 * Performs one of the edit section actions
3450 * @since Moodle 3.3
3451 * @param string $action
3452 * @param int $id section id
3453 * @param int $sectionreturn section to return to
3454 * @return string
3456 public static function edit_section($action, $id, $sectionreturn) {
3457 global $DB;
3458 // Validate and normalize parameters.
3459 $params = self::validate_parameters(self::edit_section_parameters(),
3460 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3461 $action = $params['action'];
3462 $id = $params['id'];
3463 $sr = $params['sectionreturn'];
3465 $section = $DB->get_record('course_sections', array('id' => $id), '*', MUST_EXIST);
3466 $coursecontext = context_course::instance($section->course);
3467 self::validate_context($coursecontext);
3469 $rv = course_get_format($section->course)->section_action($section, $action, $sectionreturn);
3470 if ($rv) {
3471 return json_encode($rv);
3472 } else {
3473 return null;
3478 * Return structure for edit_section()
3480 * @since Moodle 3.3
3481 * @return external_description
3483 public static function edit_section_returns() {
3484 return new external_value(PARAM_RAW, 'Additional data for javascript (JSON-encoded string)');