MDL-58035 lib: log when the expected theme cannot be initialised
[moodle.git] / course / externallib.php
blobc97800e3d54b5adc2d9476818ff6588964a9d4f7
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_course()->numsections;
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 $courseinfo['groupmode'] = $course->groupmode;
472 $courseinfo['groupmodeforce'] = $course->groupmodeforce;
473 $courseinfo['defaultgroupingid'] = $course->defaultgroupingid;
474 $courseinfo['lang'] = $course->lang;
475 $courseinfo['timecreated'] = $course->timecreated;
476 $courseinfo['timemodified'] = $course->timemodified;
477 $courseinfo['forcetheme'] = $course->theme;
478 $courseinfo['enablecompletion'] = $course->enablecompletion;
479 $courseinfo['completionnotify'] = $course->completionnotify;
480 $courseinfo['courseformatoptions'] = array();
481 foreach ($courseformatoptions as $key => $value) {
482 $courseinfo['courseformatoptions'][] = array(
483 'name' => $key,
484 'value' => $value
489 if ($courseadmin or $course->visible
490 or has_capability('moodle/course:viewhiddencourses', $context)) {
491 $coursesinfo[] = $courseinfo;
495 return $coursesinfo;
499 * Returns description of method result value
501 * @return external_description
502 * @since Moodle 2.2
504 public static function get_courses_returns() {
505 return new external_multiple_structure(
506 new external_single_structure(
507 array(
508 'id' => new external_value(PARAM_INT, 'course id'),
509 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
510 'categoryid' => new external_value(PARAM_INT, 'category id'),
511 'categorysortorder' => new external_value(PARAM_INT,
512 'sort order into the category', VALUE_OPTIONAL),
513 'fullname' => new external_value(PARAM_TEXT, 'full name'),
514 'displayname' => new external_value(PARAM_TEXT, 'course display name'),
515 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
516 'summary' => new external_value(PARAM_RAW, 'summary'),
517 'summaryformat' => new external_format_value('summary'),
518 'format' => new external_value(PARAM_PLUGIN,
519 'course format: weeks, topics, social, site,..'),
520 'showgrades' => new external_value(PARAM_INT,
521 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
522 'newsitems' => new external_value(PARAM_INT,
523 'number of recent items appearing on the course page', VALUE_OPTIONAL),
524 'startdate' => new external_value(PARAM_INT,
525 'timestamp when the course start'),
526 'enddate' => new external_value(PARAM_INT,
527 'timestamp when the course end'),
528 'numsections' => new external_value(PARAM_INT,
529 '(deprecated, use courseformatoptions) number of weeks/topics',
530 VALUE_OPTIONAL),
531 'maxbytes' => new external_value(PARAM_INT,
532 'largest size of file that can be uploaded into the course',
533 VALUE_OPTIONAL),
534 'showreports' => new external_value(PARAM_INT,
535 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
536 'visible' => new external_value(PARAM_INT,
537 '1: available to student, 0:not available', VALUE_OPTIONAL),
538 'hiddensections' => new external_value(PARAM_INT,
539 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
540 VALUE_OPTIONAL),
541 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
542 VALUE_OPTIONAL),
543 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
544 VALUE_OPTIONAL),
545 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
546 VALUE_OPTIONAL),
547 'timecreated' => new external_value(PARAM_INT,
548 'timestamp when the course have been created', VALUE_OPTIONAL),
549 'timemodified' => new external_value(PARAM_INT,
550 'timestamp when the course have been modified', VALUE_OPTIONAL),
551 'enablecompletion' => new external_value(PARAM_INT,
552 'Enabled, control via completion and activity settings. Disbaled,
553 not shown in activity settings.',
554 VALUE_OPTIONAL),
555 'completionnotify' => new external_value(PARAM_INT,
556 '1: yes 0: no', VALUE_OPTIONAL),
557 'lang' => new external_value(PARAM_SAFEDIR,
558 'forced course language', VALUE_OPTIONAL),
559 'forcetheme' => new external_value(PARAM_PLUGIN,
560 'name of the force theme', VALUE_OPTIONAL),
561 'courseformatoptions' => new external_multiple_structure(
562 new external_single_structure(
563 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
564 'value' => new external_value(PARAM_RAW, 'course format option value')
566 'additional options for particular course format', VALUE_OPTIONAL
568 ), 'course'
574 * Returns description of method parameters
576 * @return external_function_parameters
577 * @since Moodle 2.2
579 public static function create_courses_parameters() {
580 $courseconfig = get_config('moodlecourse'); //needed for many default values
581 return new external_function_parameters(
582 array(
583 'courses' => new external_multiple_structure(
584 new external_single_structure(
585 array(
586 'fullname' => new external_value(PARAM_TEXT, 'full name'),
587 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
588 'categoryid' => new external_value(PARAM_INT, 'category id'),
589 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
590 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
591 'summaryformat' => new external_format_value('summary', VALUE_DEFAULT),
592 'format' => new external_value(PARAM_PLUGIN,
593 'course format: weeks, topics, social, site,..',
594 VALUE_DEFAULT, $courseconfig->format),
595 'showgrades' => new external_value(PARAM_INT,
596 '1 if grades are shown, otherwise 0', VALUE_DEFAULT,
597 $courseconfig->showgrades),
598 'newsitems' => new external_value(PARAM_INT,
599 'number of recent items appearing on the course page',
600 VALUE_DEFAULT, $courseconfig->newsitems),
601 'startdate' => new external_value(PARAM_INT,
602 'timestamp when the course start', VALUE_OPTIONAL),
603 'enddate' => new external_value(PARAM_INT,
604 'timestamp when the course end', VALUE_OPTIONAL),
605 'numsections' => new external_value(PARAM_INT,
606 '(deprecated, use courseformatoptions) number of weeks/topics',
607 VALUE_OPTIONAL),
608 'maxbytes' => new external_value(PARAM_INT,
609 'largest size of file that can be uploaded into the course',
610 VALUE_DEFAULT, $courseconfig->maxbytes),
611 'showreports' => new external_value(PARAM_INT,
612 'are activity report shown (yes = 1, no =0)', VALUE_DEFAULT,
613 $courseconfig->showreports),
614 'visible' => new external_value(PARAM_INT,
615 '1: available to student, 0:not available', VALUE_OPTIONAL),
616 'hiddensections' => new external_value(PARAM_INT,
617 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
618 VALUE_OPTIONAL),
619 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
620 VALUE_DEFAULT, $courseconfig->groupmode),
621 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
622 VALUE_DEFAULT, $courseconfig->groupmodeforce),
623 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
624 VALUE_DEFAULT, 0),
625 'enablecompletion' => new external_value(PARAM_INT,
626 'Enabled, control via completion and activity settings. Disabled,
627 not shown in activity settings.',
628 VALUE_OPTIONAL),
629 'completionnotify' => new external_value(PARAM_INT,
630 '1: yes 0: no', VALUE_OPTIONAL),
631 'lang' => new external_value(PARAM_SAFEDIR,
632 'forced course language', VALUE_OPTIONAL),
633 'forcetheme' => new external_value(PARAM_PLUGIN,
634 'name of the force theme', VALUE_OPTIONAL),
635 'courseformatoptions' => new external_multiple_structure(
636 new external_single_structure(
637 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
638 'value' => new external_value(PARAM_RAW, 'course format option value')
640 'additional options for particular course format', VALUE_OPTIONAL),
642 ), 'courses to create'
649 * Create courses
651 * @param array $courses
652 * @return array courses (id and shortname only)
653 * @since Moodle 2.2
655 public static function create_courses($courses) {
656 global $CFG, $DB;
657 require_once($CFG->dirroot . "/course/lib.php");
658 require_once($CFG->libdir . '/completionlib.php');
660 $params = self::validate_parameters(self::create_courses_parameters(),
661 array('courses' => $courses));
663 $availablethemes = core_component::get_plugin_list('theme');
664 $availablelangs = get_string_manager()->get_list_of_translations();
666 $transaction = $DB->start_delegated_transaction();
668 foreach ($params['courses'] as $course) {
670 // Ensure the current user is allowed to run this function
671 $context = context_coursecat::instance($course['categoryid'], IGNORE_MISSING);
672 try {
673 self::validate_context($context);
674 } catch (Exception $e) {
675 $exceptionparam = new stdClass();
676 $exceptionparam->message = $e->getMessage();
677 $exceptionparam->catid = $course['categoryid'];
678 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
680 require_capability('moodle/course:create', $context);
682 // Make sure lang is valid
683 if (array_key_exists('lang', $course) and empty($availablelangs[$course['lang']])) {
684 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
687 // Make sure theme is valid
688 if (array_key_exists('forcetheme', $course)) {
689 if (!empty($CFG->allowcoursethemes)) {
690 if (empty($availablethemes[$course['forcetheme']])) {
691 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
692 } else {
693 $course['theme'] = $course['forcetheme'];
698 //force visibility if ws user doesn't have the permission to set it
699 $category = $DB->get_record('course_categories', array('id' => $course['categoryid']));
700 if (!has_capability('moodle/course:visibility', $context)) {
701 $course['visible'] = $category->visible;
704 //set default value for completion
705 $courseconfig = get_config('moodlecourse');
706 if (completion_info::is_enabled_for_site()) {
707 if (!array_key_exists('enablecompletion', $course)) {
708 $course['enablecompletion'] = $courseconfig->enablecompletion;
710 } else {
711 $course['enablecompletion'] = 0;
714 $course['category'] = $course['categoryid'];
716 // Summary format.
717 $course['summaryformat'] = external_validate_format($course['summaryformat']);
719 if (!empty($course['courseformatoptions'])) {
720 foreach ($course['courseformatoptions'] as $option) {
721 $course[$option['name']] = $option['value'];
725 //Note: create_course() core function check shortname, idnumber, category
726 $course['id'] = create_course((object) $course)->id;
728 $resultcourses[] = array('id' => $course['id'], 'shortname' => $course['shortname']);
731 $transaction->allow_commit();
733 return $resultcourses;
737 * Returns description of method result value
739 * @return external_description
740 * @since Moodle 2.2
742 public static function create_courses_returns() {
743 return new external_multiple_structure(
744 new external_single_structure(
745 array(
746 'id' => new external_value(PARAM_INT, 'course id'),
747 'shortname' => new external_value(PARAM_TEXT, 'short name'),
754 * Update courses
756 * @return external_function_parameters
757 * @since Moodle 2.5
759 public static function update_courses_parameters() {
760 return new external_function_parameters(
761 array(
762 'courses' => new external_multiple_structure(
763 new external_single_structure(
764 array(
765 'id' => new external_value(PARAM_INT, 'ID of the course'),
766 'fullname' => new external_value(PARAM_TEXT, 'full name', VALUE_OPTIONAL),
767 'shortname' => new external_value(PARAM_TEXT, 'course short name', VALUE_OPTIONAL),
768 'categoryid' => new external_value(PARAM_INT, 'category id', VALUE_OPTIONAL),
769 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
770 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
771 'summaryformat' => new external_format_value('summary', VALUE_OPTIONAL),
772 'format' => new external_value(PARAM_PLUGIN,
773 'course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
774 'showgrades' => new external_value(PARAM_INT,
775 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
776 'newsitems' => new external_value(PARAM_INT,
777 'number of recent items appearing on the course page', VALUE_OPTIONAL),
778 'startdate' => new external_value(PARAM_INT,
779 'timestamp when the course start', VALUE_OPTIONAL),
780 'enddate' => new external_value(PARAM_INT,
781 'timestamp when the course end', VALUE_OPTIONAL),
782 'numsections' => new external_value(PARAM_INT,
783 '(deprecated, use courseformatoptions) number of weeks/topics', VALUE_OPTIONAL),
784 'maxbytes' => new external_value(PARAM_INT,
785 'largest size of file that can be uploaded into the course', VALUE_OPTIONAL),
786 'showreports' => new external_value(PARAM_INT,
787 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
788 'visible' => new external_value(PARAM_INT,
789 '1: available to student, 0:not available', VALUE_OPTIONAL),
790 'hiddensections' => new external_value(PARAM_INT,
791 '(deprecated, use courseformatoptions) How the hidden sections in the course are
792 displayed to students', VALUE_OPTIONAL),
793 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
794 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
795 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
796 'enablecompletion' => new external_value(PARAM_INT,
797 'Enabled, control via completion and activity settings. Disabled,
798 not shown in activity settings.', VALUE_OPTIONAL),
799 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
800 'lang' => new external_value(PARAM_SAFEDIR, 'forced course language', VALUE_OPTIONAL),
801 'forcetheme' => new external_value(PARAM_PLUGIN, 'name of the force theme', VALUE_OPTIONAL),
802 'courseformatoptions' => new external_multiple_structure(
803 new external_single_structure(
804 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
805 'value' => new external_value(PARAM_RAW, 'course format option value')
807 'additional options for particular course format', VALUE_OPTIONAL),
809 ), 'courses to update'
816 * Update courses
818 * @param array $courses
819 * @since Moodle 2.5
821 public static function update_courses($courses) {
822 global $CFG, $DB;
823 require_once($CFG->dirroot . "/course/lib.php");
824 $warnings = array();
826 $params = self::validate_parameters(self::update_courses_parameters(),
827 array('courses' => $courses));
829 $availablethemes = core_component::get_plugin_list('theme');
830 $availablelangs = get_string_manager()->get_list_of_translations();
832 foreach ($params['courses'] as $course) {
833 // Catch any exception while updating course and return as warning to user.
834 try {
835 // Ensure the current user is allowed to run this function.
836 $context = context_course::instance($course['id'], MUST_EXIST);
837 self::validate_context($context);
839 $oldcourse = course_get_format($course['id'])->get_course();
841 require_capability('moodle/course:update', $context);
843 // Check if user can change category.
844 if (array_key_exists('categoryid', $course) && ($oldcourse->category != $course['categoryid'])) {
845 require_capability('moodle/course:changecategory', $context);
846 $course['category'] = $course['categoryid'];
849 // Check if the user can change fullname.
850 if (array_key_exists('fullname', $course) && ($oldcourse->fullname != $course['fullname'])) {
851 require_capability('moodle/course:changefullname', $context);
854 // Check if the user can change shortname.
855 if (array_key_exists('shortname', $course) && ($oldcourse->shortname != $course['shortname'])) {
856 require_capability('moodle/course:changeshortname', $context);
859 // Check if the user can change the idnumber.
860 if (array_key_exists('idnumber', $course) && ($oldcourse->idnumber != $course['idnumber'])) {
861 require_capability('moodle/course:changeidnumber', $context);
864 // Check if user can change summary.
865 if (array_key_exists('summary', $course) && ($oldcourse->summary != $course['summary'])) {
866 require_capability('moodle/course:changesummary', $context);
869 // Summary format.
870 if (array_key_exists('summaryformat', $course) && ($oldcourse->summaryformat != $course['summaryformat'])) {
871 require_capability('moodle/course:changesummary', $context);
872 $course['summaryformat'] = external_validate_format($course['summaryformat']);
875 // Check if user can change visibility.
876 if (array_key_exists('visible', $course) && ($oldcourse->visible != $course['visible'])) {
877 require_capability('moodle/course:visibility', $context);
880 // Make sure lang is valid.
881 if (array_key_exists('lang', $course) && empty($availablelangs[$course['lang']])) {
882 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
885 // Make sure theme is valid.
886 if (array_key_exists('forcetheme', $course)) {
887 if (!empty($CFG->allowcoursethemes)) {
888 if (empty($availablethemes[$course['forcetheme']])) {
889 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
890 } else {
891 $course['theme'] = $course['forcetheme'];
896 // Make sure completion is enabled before setting it.
897 if (array_key_exists('enabledcompletion', $course) && !completion_info::is_enabled_for_site()) {
898 $course['enabledcompletion'] = 0;
901 // Make sure maxbytes are less then CFG->maxbytes.
902 if (array_key_exists('maxbytes', $course)) {
903 $course['maxbytes'] = get_max_upload_file_size($CFG->maxbytes, $course['maxbytes']);
906 if (!empty($course['courseformatoptions'])) {
907 foreach ($course['courseformatoptions'] as $option) {
908 if (isset($option['name']) && isset($option['value'])) {
909 $course[$option['name']] = $option['value'];
914 // Update course if user has all required capabilities.
915 update_course((object) $course);
916 } catch (Exception $e) {
917 $warning = array();
918 $warning['item'] = 'course';
919 $warning['itemid'] = $course['id'];
920 if ($e instanceof moodle_exception) {
921 $warning['warningcode'] = $e->errorcode;
922 } else {
923 $warning['warningcode'] = $e->getCode();
925 $warning['message'] = $e->getMessage();
926 $warnings[] = $warning;
930 $result = array();
931 $result['warnings'] = $warnings;
932 return $result;
936 * Returns description of method result value
938 * @return external_description
939 * @since Moodle 2.5
941 public static function update_courses_returns() {
942 return new external_single_structure(
943 array(
944 'warnings' => new external_warnings()
950 * Returns description of method parameters
952 * @return external_function_parameters
953 * @since Moodle 2.2
955 public static function delete_courses_parameters() {
956 return new external_function_parameters(
957 array(
958 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'course ID')),
964 * Delete courses
966 * @param array $courseids A list of course ids
967 * @since Moodle 2.2
969 public static function delete_courses($courseids) {
970 global $CFG, $DB;
971 require_once($CFG->dirroot."/course/lib.php");
973 // Parameter validation.
974 $params = self::validate_parameters(self::delete_courses_parameters(), array('courseids'=>$courseids));
976 $warnings = array();
978 foreach ($params['courseids'] as $courseid) {
979 $course = $DB->get_record('course', array('id' => $courseid));
981 if ($course === false) {
982 $warnings[] = array(
983 'item' => 'course',
984 'itemid' => $courseid,
985 'warningcode' => 'unknowncourseidnumber',
986 'message' => 'Unknown course ID ' . $courseid
988 continue;
991 // Check if the context is valid.
992 $coursecontext = context_course::instance($course->id);
993 self::validate_context($coursecontext);
995 // Check if the current user has permission.
996 if (!can_delete_course($courseid)) {
997 $warnings[] = array(
998 'item' => 'course',
999 'itemid' => $courseid,
1000 'warningcode' => 'cannotdeletecourse',
1001 'message' => 'You do not have the permission to delete this course' . $courseid
1003 continue;
1006 if (delete_course($course, false) === false) {
1007 $warnings[] = array(
1008 'item' => 'course',
1009 'itemid' => $courseid,
1010 'warningcode' => 'cannotdeletecategorycourse',
1011 'message' => 'Course ' . $courseid . ' failed to be deleted'
1013 continue;
1017 fix_course_sortorder();
1019 return array('warnings' => $warnings);
1023 * Returns description of method result value
1025 * @return external_description
1026 * @since Moodle 2.2
1028 public static function delete_courses_returns() {
1029 return new external_single_structure(
1030 array(
1031 'warnings' => new external_warnings()
1037 * Returns description of method parameters
1039 * @return external_function_parameters
1040 * @since Moodle 2.3
1042 public static function duplicate_course_parameters() {
1043 return new external_function_parameters(
1044 array(
1045 'courseid' => new external_value(PARAM_INT, 'course to duplicate id'),
1046 'fullname' => new external_value(PARAM_TEXT, 'duplicated course full name'),
1047 'shortname' => new external_value(PARAM_TEXT, 'duplicated course short name'),
1048 'categoryid' => new external_value(PARAM_INT, 'duplicated course category parent'),
1049 'visible' => new external_value(PARAM_INT, 'duplicated course visible, default to yes', VALUE_DEFAULT, 1),
1050 'options' => new external_multiple_structure(
1051 new external_single_structure(
1052 array(
1053 'name' => new external_value(PARAM_ALPHAEXT, 'The backup option name:
1054 "activities" (int) Include course activites (default to 1 that is equal to yes),
1055 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1056 "filters" (int) Include course filters (default to 1 that is equal to yes),
1057 "users" (int) Include users (default to 0 that is equal to no),
1058 "role_assignments" (int) Include role assignments (default to 0 that is equal to no),
1059 "comments" (int) Include user comments (default to 0 that is equal to no),
1060 "userscompletion" (int) Include user course completion information (default to 0 that is equal to no),
1061 "logs" (int) Include course logs (default to 0 that is equal to no),
1062 "grade_histories" (int) Include histories (default to 0 that is equal to no)'
1064 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1067 ), VALUE_DEFAULT, array()
1074 * Duplicate a course
1076 * @param int $courseid
1077 * @param string $fullname Duplicated course fullname
1078 * @param string $shortname Duplicated course shortname
1079 * @param int $categoryid Duplicated course parent category id
1080 * @param int $visible Duplicated course availability
1081 * @param array $options List of backup options
1082 * @return array New course info
1083 * @since Moodle 2.3
1085 public static function duplicate_course($courseid, $fullname, $shortname, $categoryid, $visible = 1, $options = array()) {
1086 global $CFG, $USER, $DB;
1087 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1088 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1090 // Parameter validation.
1091 $params = self::validate_parameters(
1092 self::duplicate_course_parameters(),
1093 array(
1094 'courseid' => $courseid,
1095 'fullname' => $fullname,
1096 'shortname' => $shortname,
1097 'categoryid' => $categoryid,
1098 'visible' => $visible,
1099 'options' => $options
1103 // Context validation.
1105 if (! ($course = $DB->get_record('course', array('id'=>$params['courseid'])))) {
1106 throw new moodle_exception('invalidcourseid', 'error');
1109 // Category where duplicated course is going to be created.
1110 $categorycontext = context_coursecat::instance($params['categoryid']);
1111 self::validate_context($categorycontext);
1113 // Course to be duplicated.
1114 $coursecontext = context_course::instance($course->id);
1115 self::validate_context($coursecontext);
1117 $backupdefaults = array(
1118 'activities' => 1,
1119 'blocks' => 1,
1120 'filters' => 1,
1121 'users' => 0,
1122 'role_assignments' => 0,
1123 'comments' => 0,
1124 'userscompletion' => 0,
1125 'logs' => 0,
1126 'grade_histories' => 0
1129 $backupsettings = array();
1130 // Check for backup and restore options.
1131 if (!empty($params['options'])) {
1132 foreach ($params['options'] as $option) {
1134 // Strict check for a correct value (allways 1 or 0, true or false).
1135 $value = clean_param($option['value'], PARAM_INT);
1137 if ($value !== 0 and $value !== 1) {
1138 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1141 if (!isset($backupdefaults[$option['name']])) {
1142 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1145 $backupsettings[$option['name']] = $value;
1149 // Capability checking.
1151 // The backup controller check for this currently, this may be redundant.
1152 require_capability('moodle/course:create', $categorycontext);
1153 require_capability('moodle/restore:restorecourse', $categorycontext);
1154 require_capability('moodle/backup:backupcourse', $coursecontext);
1156 if (!empty($backupsettings['users'])) {
1157 require_capability('moodle/backup:userinfo', $coursecontext);
1158 require_capability('moodle/restore:userinfo', $categorycontext);
1161 // Check if the shortname is used.
1162 if ($foundcourses = $DB->get_records('course', array('shortname'=>$shortname))) {
1163 foreach ($foundcourses as $foundcourse) {
1164 $foundcoursenames[] = $foundcourse->fullname;
1167 $foundcoursenamestring = implode(',', $foundcoursenames);
1168 throw new moodle_exception('shortnametaken', '', '', $foundcoursenamestring);
1171 // Backup the course.
1173 $bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE,
1174 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id);
1176 foreach ($backupsettings as $name => $value) {
1177 $bc->get_plan()->get_setting($name)->set_value($value);
1180 $backupid = $bc->get_backupid();
1181 $backupbasepath = $bc->get_plan()->get_basepath();
1183 $bc->execute_plan();
1184 $results = $bc->get_results();
1185 $file = $results['backup_destination'];
1187 $bc->destroy();
1189 // Restore the backup immediately.
1191 // Check if we need to unzip the file because the backup temp dir does not contains backup files.
1192 if (!file_exists($backupbasepath . "/moodle_backup.xml")) {
1193 $file->extract_to_pathname(get_file_packer('application/vnd.moodle.backup'), $backupbasepath);
1196 // Create new course.
1197 $newcourseid = restore_dbops::create_new_course($params['fullname'], $params['shortname'], $params['categoryid']);
1199 $rc = new restore_controller($backupid, $newcourseid,
1200 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id, backup::TARGET_NEW_COURSE);
1202 foreach ($backupsettings as $name => $value) {
1203 $setting = $rc->get_plan()->get_setting($name);
1204 if ($setting->get_status() == backup_setting::NOT_LOCKED) {
1205 $setting->set_value($value);
1209 if (!$rc->execute_precheck()) {
1210 $precheckresults = $rc->get_precheck_results();
1211 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1212 if (empty($CFG->keeptempdirectoriesonbackup)) {
1213 fulldelete($backupbasepath);
1216 $errorinfo = '';
1218 foreach ($precheckresults['errors'] as $error) {
1219 $errorinfo .= $error;
1222 if (array_key_exists('warnings', $precheckresults)) {
1223 foreach ($precheckresults['warnings'] as $warning) {
1224 $errorinfo .= $warning;
1228 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1232 $rc->execute_plan();
1233 $rc->destroy();
1235 $course = $DB->get_record('course', array('id' => $newcourseid), '*', MUST_EXIST);
1236 $course->fullname = $params['fullname'];
1237 $course->shortname = $params['shortname'];
1238 $course->visible = $params['visible'];
1240 // Set shortname and fullname back.
1241 $DB->update_record('course', $course);
1243 if (empty($CFG->keeptempdirectoriesonbackup)) {
1244 fulldelete($backupbasepath);
1247 // Delete the course backup file created by this WebService. Originally located in the course backups area.
1248 $file->delete();
1250 return array('id' => $course->id, 'shortname' => $course->shortname);
1254 * Returns description of method result value
1256 * @return external_description
1257 * @since Moodle 2.3
1259 public static function duplicate_course_returns() {
1260 return new external_single_structure(
1261 array(
1262 'id' => new external_value(PARAM_INT, 'course id'),
1263 'shortname' => new external_value(PARAM_TEXT, 'short name'),
1269 * Returns description of method parameters for import_course
1271 * @return external_function_parameters
1272 * @since Moodle 2.4
1274 public static function import_course_parameters() {
1275 return new external_function_parameters(
1276 array(
1277 'importfrom' => new external_value(PARAM_INT, 'the id of the course we are importing from'),
1278 'importto' => new external_value(PARAM_INT, 'the id of the course we are importing to'),
1279 'deletecontent' => new external_value(PARAM_INT, 'whether to delete the course content where we are importing to (default to 0 = No)', VALUE_DEFAULT, 0),
1280 'options' => new external_multiple_structure(
1281 new external_single_structure(
1282 array(
1283 'name' => new external_value(PARAM_ALPHA, 'The backup option name:
1284 "activities" (int) Include course activites (default to 1 that is equal to yes),
1285 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1286 "filters" (int) Include course filters (default to 1 that is equal to yes)'
1288 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1291 ), VALUE_DEFAULT, array()
1298 * Imports a course
1300 * @param int $importfrom The id of the course we are importing from
1301 * @param int $importto The id of the course we are importing to
1302 * @param bool $deletecontent Whether to delete the course we are importing to content
1303 * @param array $options List of backup options
1304 * @return null
1305 * @since Moodle 2.4
1307 public static function import_course($importfrom, $importto, $deletecontent = 0, $options = array()) {
1308 global $CFG, $USER, $DB;
1309 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1310 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1312 // Parameter validation.
1313 $params = self::validate_parameters(
1314 self::import_course_parameters(),
1315 array(
1316 'importfrom' => $importfrom,
1317 'importto' => $importto,
1318 'deletecontent' => $deletecontent,
1319 'options' => $options
1323 if ($params['deletecontent'] !== 0 and $params['deletecontent'] !== 1) {
1324 throw new moodle_exception('invalidextparam', 'webservice', '', $params['deletecontent']);
1327 // Context validation.
1329 if (! ($importfrom = $DB->get_record('course', array('id'=>$params['importfrom'])))) {
1330 throw new moodle_exception('invalidcourseid', 'error');
1333 if (! ($importto = $DB->get_record('course', array('id'=>$params['importto'])))) {
1334 throw new moodle_exception('invalidcourseid', 'error');
1337 $importfromcontext = context_course::instance($importfrom->id);
1338 self::validate_context($importfromcontext);
1340 $importtocontext = context_course::instance($importto->id);
1341 self::validate_context($importtocontext);
1343 $backupdefaults = array(
1344 'activities' => 1,
1345 'blocks' => 1,
1346 'filters' => 1
1349 $backupsettings = array();
1351 // Check for backup and restore options.
1352 if (!empty($params['options'])) {
1353 foreach ($params['options'] as $option) {
1355 // Strict check for a correct value (allways 1 or 0, true or false).
1356 $value = clean_param($option['value'], PARAM_INT);
1358 if ($value !== 0 and $value !== 1) {
1359 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1362 if (!isset($backupdefaults[$option['name']])) {
1363 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1366 $backupsettings[$option['name']] = $value;
1370 // Capability checking.
1372 require_capability('moodle/backup:backuptargetimport', $importfromcontext);
1373 require_capability('moodle/restore:restoretargetimport', $importtocontext);
1375 $bc = new backup_controller(backup::TYPE_1COURSE, $importfrom->id, backup::FORMAT_MOODLE,
1376 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
1378 foreach ($backupsettings as $name => $value) {
1379 $bc->get_plan()->get_setting($name)->set_value($value);
1382 $backupid = $bc->get_backupid();
1383 $backupbasepath = $bc->get_plan()->get_basepath();
1385 $bc->execute_plan();
1386 $bc->destroy();
1388 // Restore the backup immediately.
1390 // Check if we must delete the contents of the destination course.
1391 if ($params['deletecontent']) {
1392 $restoretarget = backup::TARGET_EXISTING_DELETING;
1393 } else {
1394 $restoretarget = backup::TARGET_EXISTING_ADDING;
1397 $rc = new restore_controller($backupid, $importto->id,
1398 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, $restoretarget);
1400 foreach ($backupsettings as $name => $value) {
1401 $rc->get_plan()->get_setting($name)->set_value($value);
1404 if (!$rc->execute_precheck()) {
1405 $precheckresults = $rc->get_precheck_results();
1406 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1407 if (empty($CFG->keeptempdirectoriesonbackup)) {
1408 fulldelete($backupbasepath);
1411 $errorinfo = '';
1413 foreach ($precheckresults['errors'] as $error) {
1414 $errorinfo .= $error;
1417 if (array_key_exists('warnings', $precheckresults)) {
1418 foreach ($precheckresults['warnings'] as $warning) {
1419 $errorinfo .= $warning;
1423 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1425 } else {
1426 if ($restoretarget == backup::TARGET_EXISTING_DELETING) {
1427 restore_dbops::delete_course_content($importto->id);
1431 $rc->execute_plan();
1432 $rc->destroy();
1434 if (empty($CFG->keeptempdirectoriesonbackup)) {
1435 fulldelete($backupbasepath);
1438 return null;
1442 * Returns description of method result value
1444 * @return external_description
1445 * @since Moodle 2.4
1447 public static function import_course_returns() {
1448 return null;
1452 * Returns description of method parameters
1454 * @return external_function_parameters
1455 * @since Moodle 2.3
1457 public static function get_categories_parameters() {
1458 return new external_function_parameters(
1459 array(
1460 'criteria' => new external_multiple_structure(
1461 new external_single_structure(
1462 array(
1463 'key' => new external_value(PARAM_ALPHA,
1464 'The category column to search, expected keys (value format) are:'.
1465 '"id" (int) the category id,'.
1466 '"ids" (string) category ids separated by commas,'.
1467 '"name" (string) the category name,'.
1468 '"parent" (int) the parent category id,'.
1469 '"idnumber" (string) category idnumber'.
1470 ' - user must have \'moodle/category:manage\' to search on idnumber,'.
1471 '"visible" (int) whether the returned categories must be visible or hidden. If the key is not passed,
1472 then the function return all categories that the user can see.'.
1473 ' - user must have \'moodle/category:manage\' or \'moodle/category:viewhiddencategories\' to search on visible,'.
1474 '"theme" (string) only return the categories having this theme'.
1475 ' - user must have \'moodle/category:manage\' to search on theme'),
1476 'value' => new external_value(PARAM_RAW, 'the value to match')
1478 ), 'criteria', VALUE_DEFAULT, array()
1480 'addsubcategories' => new external_value(PARAM_BOOL, 'return the sub categories infos
1481 (1 - default) otherwise only the category info (0)', VALUE_DEFAULT, 1)
1487 * Get categories
1489 * @param array $criteria Criteria to match the results
1490 * @param booln $addsubcategories obtain only the category (false) or its subcategories (true - default)
1491 * @return array list of categories
1492 * @since Moodle 2.3
1494 public static function get_categories($criteria = array(), $addsubcategories = true) {
1495 global $CFG, $DB;
1496 require_once($CFG->dirroot . "/course/lib.php");
1498 // Validate parameters.
1499 $params = self::validate_parameters(self::get_categories_parameters(),
1500 array('criteria' => $criteria, 'addsubcategories' => $addsubcategories));
1502 // Retrieve the categories.
1503 $categories = array();
1504 if (!empty($params['criteria'])) {
1506 $conditions = array();
1507 $wheres = array();
1508 foreach ($params['criteria'] as $crit) {
1509 $key = trim($crit['key']);
1511 // Trying to avoid duplicate keys.
1512 if (!isset($conditions[$key])) {
1514 $context = context_system::instance();
1515 $value = null;
1516 switch ($key) {
1517 case 'id':
1518 $value = clean_param($crit['value'], PARAM_INT);
1519 $conditions[$key] = $value;
1520 $wheres[] = $key . " = :" . $key;
1521 break;
1523 case 'ids':
1524 $value = clean_param($crit['value'], PARAM_SEQUENCE);
1525 $ids = explode(',', $value);
1526 list($sqlids, $paramids) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED);
1527 $conditions = array_merge($conditions, $paramids);
1528 $wheres[] = 'id ' . $sqlids;
1529 break;
1531 case 'idnumber':
1532 if (has_capability('moodle/category:manage', $context)) {
1533 $value = clean_param($crit['value'], PARAM_RAW);
1534 $conditions[$key] = $value;
1535 $wheres[] = $key . " = :" . $key;
1536 } else {
1537 // We must throw an exception.
1538 // Otherwise the dev client would think no idnumber exists.
1539 throw new moodle_exception('criteriaerror',
1540 'webservice', '', null,
1541 'You don\'t have the permissions to search on the "idnumber" field.');
1543 break;
1545 case 'name':
1546 $value = clean_param($crit['value'], PARAM_TEXT);
1547 $conditions[$key] = $value;
1548 $wheres[] = $key . " = :" . $key;
1549 break;
1551 case 'parent':
1552 $value = clean_param($crit['value'], PARAM_INT);
1553 $conditions[$key] = $value;
1554 $wheres[] = $key . " = :" . $key;
1555 break;
1557 case 'visible':
1558 if (has_capability('moodle/category:manage', $context)
1559 or has_capability('moodle/category:viewhiddencategories',
1560 context_system::instance())) {
1561 $value = clean_param($crit['value'], PARAM_INT);
1562 $conditions[$key] = $value;
1563 $wheres[] = $key . " = :" . $key;
1564 } else {
1565 throw new moodle_exception('criteriaerror',
1566 'webservice', '', null,
1567 'You don\'t have the permissions to search on the "visible" field.');
1569 break;
1571 case 'theme':
1572 if (has_capability('moodle/category:manage', $context)) {
1573 $value = clean_param($crit['value'], PARAM_THEME);
1574 $conditions[$key] = $value;
1575 $wheres[] = $key . " = :" . $key;
1576 } else {
1577 throw new moodle_exception('criteriaerror',
1578 'webservice', '', null,
1579 'You don\'t have the permissions to search on the "theme" field.');
1581 break;
1583 default:
1584 throw new moodle_exception('criteriaerror',
1585 'webservice', '', null,
1586 'You can not search on this criteria: ' . $key);
1591 if (!empty($wheres)) {
1592 $wheres = implode(" AND ", $wheres);
1594 $categories = $DB->get_records_select('course_categories', $wheres, $conditions);
1596 // Retrieve its sub subcategories (all levels).
1597 if ($categories and !empty($params['addsubcategories'])) {
1598 $newcategories = array();
1600 // Check if we required visible/theme checks.
1601 $additionalselect = '';
1602 $additionalparams = array();
1603 if (isset($conditions['visible'])) {
1604 $additionalselect .= ' AND visible = :visible';
1605 $additionalparams['visible'] = $conditions['visible'];
1607 if (isset($conditions['theme'])) {
1608 $additionalselect .= ' AND theme= :theme';
1609 $additionalparams['theme'] = $conditions['theme'];
1612 foreach ($categories as $category) {
1613 $sqlselect = $DB->sql_like('path', ':path') . $additionalselect;
1614 $sqlparams = array('path' => $category->path.'/%') + $additionalparams; // It will NOT include the specified category.
1615 $subcategories = $DB->get_records_select('course_categories', $sqlselect, $sqlparams);
1616 $newcategories = $newcategories + $subcategories; // Both arrays have integer as keys.
1618 $categories = $categories + $newcategories;
1622 } else {
1623 // Retrieve all categories in the database.
1624 $categories = $DB->get_records('course_categories');
1627 // The not returned categories. key => category id, value => reason of exclusion.
1628 $excludedcats = array();
1630 // The returned categories.
1631 $categoriesinfo = array();
1633 // We need to sort the categories by path.
1634 // The parent cats need to be checked by the algo first.
1635 usort($categories, "core_course_external::compare_categories_by_path");
1637 foreach ($categories as $category) {
1639 // Check if the category is a child of an excluded category, if yes exclude it too (excluded => do not return).
1640 $parents = explode('/', $category->path);
1641 unset($parents[0]); // First key is always empty because path start with / => /1/2/4.
1642 foreach ($parents as $parentid) {
1643 // Note: when the parent exclusion was due to the context,
1644 // the sub category could still be returned.
1645 if (isset($excludedcats[$parentid]) and $excludedcats[$parentid] != 'context') {
1646 $excludedcats[$category->id] = 'parent';
1650 // Check the user can use the category context.
1651 $context = context_coursecat::instance($category->id);
1652 try {
1653 self::validate_context($context);
1654 } catch (Exception $e) {
1655 $excludedcats[$category->id] = 'context';
1657 // If it was the requested category then throw an exception.
1658 if (isset($params['categoryid']) && $category->id == $params['categoryid']) {
1659 $exceptionparam = new stdClass();
1660 $exceptionparam->message = $e->getMessage();
1661 $exceptionparam->catid = $category->id;
1662 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
1666 // Return the category information.
1667 if (!isset($excludedcats[$category->id])) {
1669 // Final check to see if the category is visible to the user.
1670 if ($category->visible
1671 or has_capability('moodle/category:viewhiddencategories', context_system::instance())
1672 or has_capability('moodle/category:manage', $context)) {
1674 $categoryinfo = array();
1675 $categoryinfo['id'] = $category->id;
1676 $categoryinfo['name'] = $category->name;
1677 list($categoryinfo['description'], $categoryinfo['descriptionformat']) =
1678 external_format_text($category->description, $category->descriptionformat,
1679 $context->id, 'coursecat', 'description', null);
1680 $categoryinfo['parent'] = $category->parent;
1681 $categoryinfo['sortorder'] = $category->sortorder;
1682 $categoryinfo['coursecount'] = $category->coursecount;
1683 $categoryinfo['depth'] = $category->depth;
1684 $categoryinfo['path'] = $category->path;
1686 // Some fields only returned for admin.
1687 if (has_capability('moodle/category:manage', $context)) {
1688 $categoryinfo['idnumber'] = $category->idnumber;
1689 $categoryinfo['visible'] = $category->visible;
1690 $categoryinfo['visibleold'] = $category->visibleold;
1691 $categoryinfo['timemodified'] = $category->timemodified;
1692 $categoryinfo['theme'] = $category->theme;
1695 $categoriesinfo[] = $categoryinfo;
1696 } else {
1697 $excludedcats[$category->id] = 'visibility';
1702 // Sorting the resulting array so it looks a bit better for the client developer.
1703 usort($categoriesinfo, "core_course_external::compare_categories_by_sortorder");
1705 return $categoriesinfo;
1709 * Sort categories array by path
1710 * private function: only used by get_categories
1712 * @param array $category1
1713 * @param array $category2
1714 * @return int result of strcmp
1715 * @since Moodle 2.3
1717 private static function compare_categories_by_path($category1, $category2) {
1718 return strcmp($category1->path, $category2->path);
1722 * Sort categories array by sortorder
1723 * private function: only used by get_categories
1725 * @param array $category1
1726 * @param array $category2
1727 * @return int result of strcmp
1728 * @since Moodle 2.3
1730 private static function compare_categories_by_sortorder($category1, $category2) {
1731 return strcmp($category1['sortorder'], $category2['sortorder']);
1735 * Returns description of method result value
1737 * @return external_description
1738 * @since Moodle 2.3
1740 public static function get_categories_returns() {
1741 return new external_multiple_structure(
1742 new external_single_structure(
1743 array(
1744 'id' => new external_value(PARAM_INT, 'category id'),
1745 'name' => new external_value(PARAM_TEXT, 'category name'),
1746 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1747 'description' => new external_value(PARAM_RAW, 'category description'),
1748 'descriptionformat' => new external_format_value('description'),
1749 'parent' => new external_value(PARAM_INT, 'parent category id'),
1750 'sortorder' => new external_value(PARAM_INT, 'category sorting order'),
1751 'coursecount' => new external_value(PARAM_INT, 'number of courses in this category'),
1752 'visible' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1753 'visibleold' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1754 'timemodified' => new external_value(PARAM_INT, 'timestamp', VALUE_OPTIONAL),
1755 'depth' => new external_value(PARAM_INT, 'category depth'),
1756 'path' => new external_value(PARAM_TEXT, 'category path'),
1757 'theme' => new external_value(PARAM_THEME, 'category theme', VALUE_OPTIONAL),
1758 ), 'List of categories'
1764 * Returns description of method parameters
1766 * @return external_function_parameters
1767 * @since Moodle 2.3
1769 public static function create_categories_parameters() {
1770 return new external_function_parameters(
1771 array(
1772 'categories' => new external_multiple_structure(
1773 new external_single_structure(
1774 array(
1775 'name' => new external_value(PARAM_TEXT, 'new category name'),
1776 'parent' => new external_value(PARAM_INT,
1777 'the parent category id inside which the new category will be created
1778 - set to 0 for a root category',
1779 VALUE_DEFAULT, 0),
1780 'idnumber' => new external_value(PARAM_RAW,
1781 'the new category idnumber', VALUE_OPTIONAL),
1782 'description' => new external_value(PARAM_RAW,
1783 'the new category description', VALUE_OPTIONAL),
1784 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
1785 'theme' => new external_value(PARAM_THEME,
1786 'the new category theme. This option must be enabled on moodle',
1787 VALUE_OPTIONAL),
1796 * Create categories
1798 * @param array $categories - see create_categories_parameters() for the array structure
1799 * @return array - see create_categories_returns() for the array structure
1800 * @since Moodle 2.3
1802 public static function create_categories($categories) {
1803 global $CFG, $DB;
1804 require_once($CFG->libdir . "/coursecatlib.php");
1806 $params = self::validate_parameters(self::create_categories_parameters(),
1807 array('categories' => $categories));
1809 $transaction = $DB->start_delegated_transaction();
1811 $createdcategories = array();
1812 foreach ($params['categories'] as $category) {
1813 if ($category['parent']) {
1814 if (!$DB->record_exists('course_categories', array('id' => $category['parent']))) {
1815 throw new moodle_exception('unknowcategory');
1817 $context = context_coursecat::instance($category['parent']);
1818 } else {
1819 $context = context_system::instance();
1821 self::validate_context($context);
1822 require_capability('moodle/category:manage', $context);
1824 // this will validate format and throw an exception if there are errors
1825 external_validate_format($category['descriptionformat']);
1827 $newcategory = coursecat::create($category);
1829 $createdcategories[] = array('id' => $newcategory->id, 'name' => $newcategory->name);
1832 $transaction->allow_commit();
1834 return $createdcategories;
1838 * Returns description of method parameters
1840 * @return external_function_parameters
1841 * @since Moodle 2.3
1843 public static function create_categories_returns() {
1844 return new external_multiple_structure(
1845 new external_single_structure(
1846 array(
1847 'id' => new external_value(PARAM_INT, 'new category id'),
1848 'name' => new external_value(PARAM_TEXT, 'new category name'),
1855 * Returns description of method parameters
1857 * @return external_function_parameters
1858 * @since Moodle 2.3
1860 public static function update_categories_parameters() {
1861 return new external_function_parameters(
1862 array(
1863 'categories' => new external_multiple_structure(
1864 new external_single_structure(
1865 array(
1866 'id' => new external_value(PARAM_INT, 'course id'),
1867 'name' => new external_value(PARAM_TEXT, 'category name', VALUE_OPTIONAL),
1868 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1869 'parent' => new external_value(PARAM_INT, 'parent category id', VALUE_OPTIONAL),
1870 'description' => new external_value(PARAM_RAW, 'category description', VALUE_OPTIONAL),
1871 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
1872 'theme' => new external_value(PARAM_THEME,
1873 'the category theme. This option must be enabled on moodle', VALUE_OPTIONAL),
1882 * Update categories
1884 * @param array $categories The list of categories to update
1885 * @return null
1886 * @since Moodle 2.3
1888 public static function update_categories($categories) {
1889 global $CFG, $DB;
1890 require_once($CFG->libdir . "/coursecatlib.php");
1892 // Validate parameters.
1893 $params = self::validate_parameters(self::update_categories_parameters(), array('categories' => $categories));
1895 $transaction = $DB->start_delegated_transaction();
1897 foreach ($params['categories'] as $cat) {
1898 $category = coursecat::get($cat['id']);
1900 $categorycontext = context_coursecat::instance($cat['id']);
1901 self::validate_context($categorycontext);
1902 require_capability('moodle/category:manage', $categorycontext);
1904 // this will throw an exception if descriptionformat is not valid
1905 external_validate_format($cat['descriptionformat']);
1907 $category->update($cat);
1910 $transaction->allow_commit();
1914 * Returns description of method result value
1916 * @return external_description
1917 * @since Moodle 2.3
1919 public static function update_categories_returns() {
1920 return null;
1924 * Returns description of method parameters
1926 * @return external_function_parameters
1927 * @since Moodle 2.3
1929 public static function delete_categories_parameters() {
1930 return new external_function_parameters(
1931 array(
1932 'categories' => new external_multiple_structure(
1933 new external_single_structure(
1934 array(
1935 'id' => new external_value(PARAM_INT, 'category id to delete'),
1936 'newparent' => new external_value(PARAM_INT,
1937 'the parent category to move the contents to, if specified', VALUE_OPTIONAL),
1938 'recursive' => new external_value(PARAM_BOOL, '1: recursively delete all contents inside this
1939 category, 0 (default): move contents to newparent or current parent category (except if parent is root)', VALUE_DEFAULT, 0)
1948 * Delete categories
1950 * @param array $categories A list of category ids
1951 * @return array
1952 * @since Moodle 2.3
1954 public static function delete_categories($categories) {
1955 global $CFG, $DB;
1956 require_once($CFG->dirroot . "/course/lib.php");
1957 require_once($CFG->libdir . "/coursecatlib.php");
1959 // Validate parameters.
1960 $params = self::validate_parameters(self::delete_categories_parameters(), array('categories' => $categories));
1962 $transaction = $DB->start_delegated_transaction();
1964 foreach ($params['categories'] as $category) {
1965 $deletecat = coursecat::get($category['id'], MUST_EXIST);
1966 $context = context_coursecat::instance($deletecat->id);
1967 require_capability('moodle/category:manage', $context);
1968 self::validate_context($context);
1969 self::validate_context(get_category_or_system_context($deletecat->parent));
1971 if ($category['recursive']) {
1972 // If recursive was specified, then we recursively delete the category's contents.
1973 if ($deletecat->can_delete_full()) {
1974 $deletecat->delete_full(false);
1975 } else {
1976 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
1978 } else {
1979 // In this situation, we don't delete the category's contents, we either move it to newparent or parent.
1980 // If the parent is the root, moving is not supported (because a course must always be inside a category).
1981 // We must move to an existing category.
1982 if (!empty($category['newparent'])) {
1983 $newparentcat = coursecat::get($category['newparent']);
1984 } else {
1985 $newparentcat = coursecat::get($deletecat->parent);
1988 // This operation is not allowed. We must move contents to an existing category.
1989 if (!$newparentcat->id) {
1990 throw new moodle_exception('movecatcontentstoroot');
1993 self::validate_context(context_coursecat::instance($newparentcat->id));
1994 if ($deletecat->can_move_content_to($newparentcat->id)) {
1995 $deletecat->delete_move($newparentcat->id, false);
1996 } else {
1997 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2002 $transaction->allow_commit();
2006 * Returns description of method parameters
2008 * @return external_function_parameters
2009 * @since Moodle 2.3
2011 public static function delete_categories_returns() {
2012 return null;
2016 * Describes the parameters for delete_modules.
2018 * @return external_function_parameters
2019 * @since Moodle 2.5
2021 public static function delete_modules_parameters() {
2022 return new external_function_parameters (
2023 array(
2024 'cmids' => new external_multiple_structure(new external_value(PARAM_INT, 'course module ID',
2025 VALUE_REQUIRED, '', NULL_NOT_ALLOWED), 'Array of course module IDs'),
2031 * Deletes a list of provided module instances.
2033 * @param array $cmids the course module ids
2034 * @since Moodle 2.5
2036 public static function delete_modules($cmids) {
2037 global $CFG, $DB;
2039 // Require course file containing the course delete module function.
2040 require_once($CFG->dirroot . "/course/lib.php");
2042 // Clean the parameters.
2043 $params = self::validate_parameters(self::delete_modules_parameters(), array('cmids' => $cmids));
2045 // Keep track of the course ids we have performed a capability check on to avoid repeating.
2046 $arrcourseschecked = array();
2048 foreach ($params['cmids'] as $cmid) {
2049 // Get the course module.
2050 $cm = $DB->get_record('course_modules', array('id' => $cmid), '*', MUST_EXIST);
2052 // Check if we have not yet confirmed they have permission in this course.
2053 if (!in_array($cm->course, $arrcourseschecked)) {
2054 // Ensure the current user has required permission in this course.
2055 $context = context_course::instance($cm->course);
2056 self::validate_context($context);
2057 // Add to the array.
2058 $arrcourseschecked[] = $cm->course;
2061 // Ensure they can delete this module.
2062 $modcontext = context_module::instance($cm->id);
2063 require_capability('moodle/course:manageactivities', $modcontext);
2065 // Delete the module.
2066 course_delete_module($cm->id);
2071 * Describes the delete_modules return value.
2073 * @return external_single_structure
2074 * @since Moodle 2.5
2076 public static function delete_modules_returns() {
2077 return null;
2081 * Returns description of method parameters
2083 * @return external_function_parameters
2084 * @since Moodle 2.9
2086 public static function view_course_parameters() {
2087 return new external_function_parameters(
2088 array(
2089 'courseid' => new external_value(PARAM_INT, 'id of the course'),
2090 'sectionnumber' => new external_value(PARAM_INT, 'section number', VALUE_DEFAULT, 0)
2096 * Trigger the course viewed event.
2098 * @param int $courseid id of course
2099 * @param int $sectionnumber sectionnumber (0, 1, 2...)
2100 * @return array of warnings and status result
2101 * @since Moodle 2.9
2102 * @throws moodle_exception
2104 public static function view_course($courseid, $sectionnumber = 0) {
2105 global $CFG;
2106 require_once($CFG->dirroot . "/course/lib.php");
2108 $params = self::validate_parameters(self::view_course_parameters(),
2109 array(
2110 'courseid' => $courseid,
2111 'sectionnumber' => $sectionnumber
2114 $warnings = array();
2116 $course = get_course($params['courseid']);
2117 $context = context_course::instance($course->id);
2118 self::validate_context($context);
2120 if (!empty($params['sectionnumber'])) {
2122 // Get section details and check it exists.
2123 $modinfo = get_fast_modinfo($course);
2124 $coursesection = $modinfo->get_section_info($params['sectionnumber'], MUST_EXIST);
2126 // Check user is allowed to see it.
2127 if (!$coursesection->uservisible) {
2128 require_capability('moodle/course:viewhiddensections', $context);
2132 course_view($context, $params['sectionnumber']);
2134 $result = array();
2135 $result['status'] = true;
2136 $result['warnings'] = $warnings;
2137 return $result;
2141 * Returns description of method result value
2143 * @return external_description
2144 * @since Moodle 2.9
2146 public static function view_course_returns() {
2147 return new external_single_structure(
2148 array(
2149 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
2150 'warnings' => new external_warnings()
2156 * Returns description of method parameters
2158 * @return external_function_parameters
2159 * @since Moodle 3.0
2161 public static function search_courses_parameters() {
2162 return new external_function_parameters(
2163 array(
2164 'criterianame' => new external_value(PARAM_ALPHA, 'criteria name
2165 (search, modulelist (only admins), blocklist (only admins), tagid)'),
2166 'criteriavalue' => new external_value(PARAM_RAW, 'criteria value'),
2167 'page' => new external_value(PARAM_INT, 'page number (0 based)', VALUE_DEFAULT, 0),
2168 'perpage' => new external_value(PARAM_INT, 'items per page', VALUE_DEFAULT, 0),
2169 'requiredcapabilities' => new external_multiple_structure(
2170 new external_value(PARAM_CAPABILITY, 'Capability string used to filter courses by permission'),
2171 'Optional list of required capabilities (used to filter the list)', VALUE_DEFAULT, array()
2173 'limittoenrolled' => new external_value(PARAM_BOOL, 'limit to enrolled courses', VALUE_DEFAULT, 0),
2179 * Return the course information that is public (visible by every one)
2181 * @param course_in_list $course course in list object
2182 * @param stdClass $coursecontext course context object
2183 * @return array the course information
2184 * @since Moodle 3.2
2186 protected static function get_course_public_information(course_in_list $course, $coursecontext) {
2188 static $categoriescache = array();
2190 // Category information.
2191 if (!array_key_exists($course->category, $categoriescache)) {
2192 $categoriescache[$course->category] = coursecat::get($course->category, IGNORE_MISSING);
2194 $category = $categoriescache[$course->category];
2196 // Retrieve course overview used files.
2197 $files = array();
2198 foreach ($course->get_course_overviewfiles() as $file) {
2199 $fileurl = moodle_url::make_webservice_pluginfile_url($file->get_contextid(), $file->get_component(),
2200 $file->get_filearea(), null, $file->get_filepath(),
2201 $file->get_filename())->out(false);
2202 $files[] = array(
2203 'filename' => $file->get_filename(),
2204 'fileurl' => $fileurl,
2205 'filesize' => $file->get_filesize(),
2206 'filepath' => $file->get_filepath(),
2207 'mimetype' => $file->get_mimetype(),
2208 'timemodified' => $file->get_timemodified(),
2212 // Retrieve the course contacts,
2213 // we need here the users fullname since if we are not enrolled can be difficult to obtain them via other Web Services.
2214 $coursecontacts = array();
2215 foreach ($course->get_course_contacts() as $contact) {
2216 $coursecontacts[] = array(
2217 'id' => $contact['user']->id,
2218 'fullname' => $contact['username']
2222 // Allowed enrolment methods (maybe we can self-enrol).
2223 $enroltypes = array();
2224 $instances = enrol_get_instances($course->id, true);
2225 foreach ($instances as $instance) {
2226 $enroltypes[] = $instance->enrol;
2229 // Format summary.
2230 list($summary, $summaryformat) =
2231 external_format_text($course->summary, $course->summaryformat, $coursecontext->id, 'course', 'summary', null);
2233 $displayname = get_course_display_name_for_list($course);
2234 $coursereturns = array();
2235 $coursereturns['id'] = $course->id;
2236 $coursereturns['fullname'] = external_format_string($course->fullname, $coursecontext->id);
2237 $coursereturns['displayname'] = external_format_string($displayname, $coursecontext->id);
2238 $coursereturns['shortname'] = external_format_string($course->shortname, $coursecontext->id);
2239 $coursereturns['categoryid'] = $course->category;
2240 $coursereturns['categoryname'] = $category == null ? '' : $category->name;
2241 $coursereturns['summary'] = $summary;
2242 $coursereturns['summaryformat'] = $summaryformat;
2243 $coursereturns['summaryfiles'] = external_util::get_area_files($coursecontext->id, 'course', 'summary', false, false);
2244 $coursereturns['overviewfiles'] = $files;
2245 $coursereturns['contacts'] = $coursecontacts;
2246 $coursereturns['enrollmentmethods'] = $enroltypes;
2247 return $coursereturns;
2251 * Search courses following the specified criteria.
2253 * @param string $criterianame Criteria name (search, modulelist (only admins), blocklist (only admins), tagid)
2254 * @param string $criteriavalue Criteria value
2255 * @param int $page Page number (for pagination)
2256 * @param int $perpage Items per page
2257 * @param array $requiredcapabilities Optional list of required capabilities (used to filter the list).
2258 * @param int $limittoenrolled Limit to only enrolled courses
2259 * @return array of course objects and warnings
2260 * @since Moodle 3.0
2261 * @throws moodle_exception
2263 public static function search_courses($criterianame,
2264 $criteriavalue,
2265 $page=0,
2266 $perpage=0,
2267 $requiredcapabilities=array(),
2268 $limittoenrolled=0) {
2269 global $CFG;
2270 require_once($CFG->libdir . '/coursecatlib.php');
2272 $warnings = array();
2274 $parameters = array(
2275 'criterianame' => $criterianame,
2276 'criteriavalue' => $criteriavalue,
2277 'page' => $page,
2278 'perpage' => $perpage,
2279 'requiredcapabilities' => $requiredcapabilities
2281 $params = self::validate_parameters(self::search_courses_parameters(), $parameters);
2282 self::validate_context(context_system::instance());
2284 $allowedcriterianames = array('search', 'modulelist', 'blocklist', 'tagid');
2285 if (!in_array($params['criterianame'], $allowedcriterianames)) {
2286 throw new invalid_parameter_exception('Invalid value for criterianame parameter (value: '.$params['criterianame'].'),' .
2287 'allowed values are: '.implode(',', $allowedcriterianames));
2290 if ($params['criterianame'] == 'modulelist' or $params['criterianame'] == 'blocklist') {
2291 require_capability('moodle/site:config', context_system::instance());
2294 $paramtype = array(
2295 'search' => PARAM_RAW,
2296 'modulelist' => PARAM_PLUGIN,
2297 'blocklist' => PARAM_INT,
2298 'tagid' => PARAM_INT
2300 $params['criteriavalue'] = clean_param($params['criteriavalue'], $paramtype[$params['criterianame']]);
2302 // Prepare the search API options.
2303 $searchcriteria = array();
2304 $searchcriteria[$params['criterianame']] = $params['criteriavalue'];
2306 $options = array();
2307 if ($params['perpage'] != 0) {
2308 $offset = $params['page'] * $params['perpage'];
2309 $options = array('offset' => $offset, 'limit' => $params['perpage']);
2312 // Search the courses.
2313 $courses = coursecat::search_courses($searchcriteria, $options, $params['requiredcapabilities']);
2314 $totalcount = coursecat::search_courses_count($searchcriteria, $options, $params['requiredcapabilities']);
2316 if (!empty($limittoenrolled)) {
2317 // Get the courses where the current user has access.
2318 $enrolled = enrol_get_my_courses(array('id', 'cacherev'));
2321 $finalcourses = array();
2322 $categoriescache = array();
2324 foreach ($courses as $course) {
2325 if (!empty($limittoenrolled)) {
2326 // Filter out not enrolled courses.
2327 if (!isset($enrolled[$course->id])) {
2328 $totalcount--;
2329 continue;
2333 $coursecontext = context_course::instance($course->id);
2335 $finalcourses[] = self::get_course_public_information($course, $coursecontext);
2338 return array(
2339 'total' => $totalcount,
2340 'courses' => $finalcourses,
2341 'warnings' => $warnings
2346 * Returns a course structure definition
2348 * @param boolean $onlypublicdata set to true, to retrieve only fields viewable by anyone when the course is visible
2349 * @return array the course structure
2350 * @since Moodle 3.2
2352 protected static function get_course_structure($onlypublicdata = true) {
2353 $coursestructure = array(
2354 'id' => new external_value(PARAM_INT, 'course id'),
2355 'fullname' => new external_value(PARAM_TEXT, 'course full name'),
2356 'displayname' => new external_value(PARAM_TEXT, 'course display name'),
2357 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
2358 'categoryid' => new external_value(PARAM_INT, 'category id'),
2359 'categoryname' => new external_value(PARAM_TEXT, 'category name'),
2360 'summary' => new external_value(PARAM_RAW, 'summary'),
2361 'summaryformat' => new external_format_value('summary'),
2362 'summaryfiles' => new external_files('summary files in the summary field', VALUE_OPTIONAL),
2363 'overviewfiles' => new external_files('additional overview files attached to this course'),
2364 'contacts' => new external_multiple_structure(
2365 new external_single_structure(
2366 array(
2367 'id' => new external_value(PARAM_INT, 'contact user id'),
2368 'fullname' => new external_value(PARAM_NOTAGS, 'contact user fullname'),
2371 'contact users'
2373 'enrollmentmethods' => new external_multiple_structure(
2374 new external_value(PARAM_PLUGIN, 'enrollment method'),
2375 'enrollment methods list'
2379 if (!$onlypublicdata) {
2380 $extra = array(
2381 'idnumber' => new external_value(PARAM_RAW, 'Id number', VALUE_OPTIONAL),
2382 'format' => new external_value(PARAM_PLUGIN, 'Course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
2383 'showgrades' => new external_value(PARAM_INT, '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
2384 'newsitems' => new external_value(PARAM_INT, 'Number of recent items appearing on the course page', VALUE_OPTIONAL),
2385 'startdate' => new external_value(PARAM_INT, 'Timestamp when the course start', VALUE_OPTIONAL),
2386 'maxbytes' => new external_value(PARAM_INT, 'Largest size of file that can be uploaded into', VALUE_OPTIONAL),
2387 'showreports' => new external_value(PARAM_INT, 'Are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
2388 'visible' => new external_value(PARAM_INT, '1: available to student, 0:not available', VALUE_OPTIONAL),
2389 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
2390 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
2391 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
2392 'enablecompletion' => new external_value(PARAM_INT, 'Completion enabled? 1: yes 0: no', VALUE_OPTIONAL),
2393 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
2394 'lang' => new external_value(PARAM_SAFEDIR, 'Forced course language', VALUE_OPTIONAL),
2395 'theme' => new external_value(PARAM_PLUGIN, 'Fame of the forced theme', VALUE_OPTIONAL),
2396 'sortorder' => new external_value(PARAM_INT, 'Sort order in the category', VALUE_OPTIONAL),
2397 'marker' => new external_value(PARAM_INT, 'Current course marker', VALUE_OPTIONAL),
2398 'legacyfiles' => new external_value(PARAM_INT, 'If legacy files are enabled', VALUE_OPTIONAL),
2399 'calendartype' => new external_value(PARAM_PLUGIN, 'Calendar type', VALUE_OPTIONAL),
2400 'timecreated' => new external_value(PARAM_INT, 'Time when the course was created', VALUE_OPTIONAL),
2401 'timemodified' => new external_value(PARAM_INT, 'Last time the course was updated', VALUE_OPTIONAL),
2402 'requested' => new external_value(PARAM_INT, 'If is a requested course', VALUE_OPTIONAL),
2403 'cacherev' => new external_value(PARAM_INT, 'Cache revision number', VALUE_OPTIONAL),
2404 'filters' => new external_multiple_structure(
2405 new external_single_structure(
2406 array(
2407 'filter' => new external_value(PARAM_PLUGIN, 'Filter plugin name'),
2408 'localstate' => new external_value(PARAM_INT, 'Filter state: 1 for on, -1 for off, 0 if inherit'),
2409 'inheritedstate' => new external_value(PARAM_INT, '1 or 0 to use when localstate is set to inherit'),
2412 'Course filters', VALUE_OPTIONAL
2415 $coursestructure = array_merge($coursestructure, $extra);
2417 return new external_single_structure($coursestructure);
2421 * Returns description of method result value
2423 * @return external_description
2424 * @since Moodle 3.0
2426 public static function search_courses_returns() {
2427 return new external_single_structure(
2428 array(
2429 'total' => new external_value(PARAM_INT, 'total course count'),
2430 'courses' => new external_multiple_structure(self::get_course_structure(), 'course'),
2431 'warnings' => new external_warnings()
2437 * Returns description of method parameters
2439 * @return external_function_parameters
2440 * @since Moodle 3.0
2442 public static function get_course_module_parameters() {
2443 return new external_function_parameters(
2444 array(
2445 'cmid' => new external_value(PARAM_INT, 'The course module id')
2451 * Return information about a course module.
2453 * @param int $cmid the course module id
2454 * @return array of warnings and the course module
2455 * @since Moodle 3.0
2456 * @throws moodle_exception
2458 public static function get_course_module($cmid) {
2459 global $CFG, $DB;
2461 $params = self::validate_parameters(self::get_course_module_parameters(), array('cmid' => $cmid));
2462 $warnings = array();
2464 $cm = get_coursemodule_from_id(null, $params['cmid'], 0, true, MUST_EXIST);
2465 $context = context_module::instance($cm->id);
2466 self::validate_context($context);
2468 // If the user has permissions to manage the activity, return all the information.
2469 if (has_capability('moodle/course:manageactivities', $context)) {
2470 require_once($CFG->dirroot . '/course/modlib.php');
2471 require_once($CFG->libdir . '/gradelib.php');
2473 $info = $cm;
2474 // Get the extra information: grade, advanced grading and outcomes data.
2475 $course = get_course($cm->course);
2476 list($newcm, $newcontext, $module, $extrainfo, $cw) = get_moduleinfo_data($cm, $course);
2477 // Grades.
2478 $gradeinfo = array('grade', 'gradepass', 'gradecat');
2479 foreach ($gradeinfo as $gfield) {
2480 if (isset($extrainfo->{$gfield})) {
2481 $info->{$gfield} = $extrainfo->{$gfield};
2484 if (isset($extrainfo->grade) and $extrainfo->grade < 0) {
2485 $info->scale = $DB->get_field('scale', 'scale', array('id' => abs($extrainfo->grade)));
2487 // Advanced grading.
2488 if (isset($extrainfo->_advancedgradingdata)) {
2489 $info->advancedgrading = array();
2490 foreach ($extrainfo as $key => $val) {
2491 if (strpos($key, 'advancedgradingmethod_') === 0) {
2492 $info->advancedgrading[] = array(
2493 'area' => str_replace('advancedgradingmethod_', '', $key),
2494 'method' => $val
2499 // Outcomes.
2500 foreach ($extrainfo as $key => $val) {
2501 if (strpos($key, 'outcome_') === 0) {
2502 if (!isset($info->outcomes)) {
2503 $info->outcomes = array();
2505 $id = str_replace('outcome_', '', $key);
2506 $outcome = grade_outcome::fetch(array('id' => $id));
2507 $scaleitems = $outcome->load_scale();
2508 $info->outcomes[] = array(
2509 'id' => $id,
2510 'name' => external_format_string($outcome->get_name(), $context->id),
2511 'scale' => $scaleitems->scale
2515 } else {
2516 // Return information is safe to show to any user.
2517 $info = new stdClass();
2518 $info->id = $cm->id;
2519 $info->course = $cm->course;
2520 $info->module = $cm->module;
2521 $info->modname = $cm->modname;
2522 $info->instance = $cm->instance;
2523 $info->section = $cm->section;
2524 $info->sectionnum = $cm->sectionnum;
2525 $info->groupmode = $cm->groupmode;
2526 $info->groupingid = $cm->groupingid;
2527 $info->completion = $cm->completion;
2529 // Format name.
2530 $info->name = external_format_string($cm->name, $context->id);
2531 $result = array();
2532 $result['cm'] = $info;
2533 $result['warnings'] = $warnings;
2534 return $result;
2538 * Returns description of method result value
2540 * @return external_description
2541 * @since Moodle 3.0
2543 public static function get_course_module_returns() {
2544 return new external_single_structure(
2545 array(
2546 'cm' => new external_single_structure(
2547 array(
2548 'id' => new external_value(PARAM_INT, 'The course module id'),
2549 'course' => new external_value(PARAM_INT, 'The course id'),
2550 'module' => new external_value(PARAM_INT, 'The module type id'),
2551 'name' => new external_value(PARAM_RAW, 'The activity name'),
2552 'modname' => new external_value(PARAM_COMPONENT, 'The module component name (forum, assign, etc..)'),
2553 'instance' => new external_value(PARAM_INT, 'The activity instance id'),
2554 'section' => new external_value(PARAM_INT, 'The module section id'),
2555 'sectionnum' => new external_value(PARAM_INT, 'The module section number'),
2556 'groupmode' => new external_value(PARAM_INT, 'Group mode'),
2557 'groupingid' => new external_value(PARAM_INT, 'Grouping id'),
2558 'completion' => new external_value(PARAM_INT, 'If completion is enabled'),
2559 'idnumber' => new external_value(PARAM_RAW, 'Module id number', VALUE_OPTIONAL),
2560 'added' => new external_value(PARAM_INT, 'Time added', VALUE_OPTIONAL),
2561 'score' => new external_value(PARAM_INT, 'Score', VALUE_OPTIONAL),
2562 'indent' => new external_value(PARAM_INT, 'Indentation', VALUE_OPTIONAL),
2563 'visible' => new external_value(PARAM_INT, 'If visible', VALUE_OPTIONAL),
2564 'visibleoncoursepage' => new external_value(PARAM_INT, 'If visible on course page', VALUE_OPTIONAL),
2565 'visibleold' => new external_value(PARAM_INT, 'Visible old', VALUE_OPTIONAL),
2566 'completiongradeitemnumber' => new external_value(PARAM_INT, 'Completion grade item', VALUE_OPTIONAL),
2567 'completionview' => new external_value(PARAM_INT, 'Completion view setting', VALUE_OPTIONAL),
2568 'completionexpected' => new external_value(PARAM_INT, 'Completion time expected', VALUE_OPTIONAL),
2569 'showdescription' => new external_value(PARAM_INT, 'If the description is showed', VALUE_OPTIONAL),
2570 'availability' => new external_value(PARAM_RAW, 'Availability settings', VALUE_OPTIONAL),
2571 'grade' => new external_value(PARAM_INT, 'Grade (max value or scale id)', VALUE_OPTIONAL),
2572 'scale' => new external_value(PARAM_TEXT, 'Scale items (if used)', VALUE_OPTIONAL),
2573 'gradepass' => new external_value(PARAM_RAW, 'Grade to pass (float)', VALUE_OPTIONAL),
2574 'gradecat' => new external_value(PARAM_INT, 'Grade category', VALUE_OPTIONAL),
2575 'advancedgrading' => new external_multiple_structure(
2576 new external_single_structure(
2577 array(
2578 'area' => new external_value(PARAM_AREA, 'Gradable area name'),
2579 'method' => new external_value(PARAM_COMPONENT, 'Grading method'),
2582 'Advanced grading settings', VALUE_OPTIONAL
2584 'outcomes' => new external_multiple_structure(
2585 new external_single_structure(
2586 array(
2587 'id' => new external_value(PARAM_ALPHANUMEXT, 'Outcome id'),
2588 'name' => new external_value(PARAM_TEXT, 'Outcome full name'),
2589 'scale' => new external_value(PARAM_TEXT, 'Scale items')
2592 'Outcomes information', VALUE_OPTIONAL
2596 'warnings' => new external_warnings()
2602 * Returns description of method parameters
2604 * @return external_function_parameters
2605 * @since Moodle 3.0
2607 public static function get_course_module_by_instance_parameters() {
2608 return new external_function_parameters(
2609 array(
2610 'module' => new external_value(PARAM_COMPONENT, 'The module name'),
2611 'instance' => new external_value(PARAM_INT, 'The module instance id')
2617 * Return information about a course module.
2619 * @param string $module the module name
2620 * @param int $instance the activity instance id
2621 * @return array of warnings and the course module
2622 * @since Moodle 3.0
2623 * @throws moodle_exception
2625 public static function get_course_module_by_instance($module, $instance) {
2627 $params = self::validate_parameters(self::get_course_module_by_instance_parameters(),
2628 array(
2629 'module' => $module,
2630 'instance' => $instance,
2633 $warnings = array();
2634 $cm = get_coursemodule_from_instance($params['module'], $params['instance'], 0, false, MUST_EXIST);
2636 return self::get_course_module($cm->id);
2640 * Returns description of method result value
2642 * @return external_description
2643 * @since Moodle 3.0
2645 public static function get_course_module_by_instance_returns() {
2646 return self::get_course_module_returns();
2650 * Returns description of method parameters
2652 * @return external_function_parameters
2653 * @since Moodle 3.2
2655 public static function get_activities_overview_parameters() {
2656 return new external_function_parameters(
2657 array(
2658 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2664 * Return activities overview for the given courses.
2666 * @param array $courseids a list of course ids
2667 * @return array of warnings and the activities overview
2668 * @since Moodle 3.2
2669 * @throws moodle_exception
2671 public static function get_activities_overview($courseids) {
2672 global $USER;
2674 // Parameter validation.
2675 $params = self::validate_parameters(self::get_activities_overview_parameters(), array('courseids' => $courseids));
2676 $courseoverviews = array();
2678 list($courses, $warnings) = external_util::validate_courses($params['courseids']);
2680 if (!empty($courses)) {
2681 // Add lastaccess to each course (required by print_overview function).
2682 // We need the complete user data, the ws server does not load a complete one.
2683 $user = get_complete_user_data('id', $USER->id);
2684 foreach ($courses as $course) {
2685 if (isset($user->lastcourseaccess[$course->id])) {
2686 $course->lastaccess = $user->lastcourseaccess[$course->id];
2687 } else {
2688 $course->lastaccess = 0;
2692 $overviews = array();
2693 if ($modules = get_plugin_list_with_function('mod', 'print_overview')) {
2694 foreach ($modules as $fname) {
2695 $fname($courses, $overviews);
2699 // Format output.
2700 foreach ($overviews as $courseid => $modules) {
2701 $courseoverviews[$courseid]['id'] = $courseid;
2702 $courseoverviews[$courseid]['overviews'] = array();
2704 foreach ($modules as $modname => $overviewtext) {
2705 $courseoverviews[$courseid]['overviews'][] = array(
2706 'module' => $modname,
2707 'overviewtext' => $overviewtext // This text doesn't need formatting.
2713 $result = array(
2714 'courses' => $courseoverviews,
2715 'warnings' => $warnings
2717 return $result;
2721 * Returns description of method result value
2723 * @return external_description
2724 * @since Moodle 3.2
2726 public static function get_activities_overview_returns() {
2727 return new external_single_structure(
2728 array(
2729 'courses' => new external_multiple_structure(
2730 new external_single_structure(
2731 array(
2732 'id' => new external_value(PARAM_INT, 'Course id'),
2733 'overviews' => new external_multiple_structure(
2734 new external_single_structure(
2735 array(
2736 'module' => new external_value(PARAM_PLUGIN, 'Module name'),
2737 'overviewtext' => new external_value(PARAM_RAW, 'Overview text'),
2742 ), 'List of courses'
2744 'warnings' => new external_warnings()
2750 * Returns description of method parameters
2752 * @return external_function_parameters
2753 * @since Moodle 3.2
2755 public static function get_user_navigation_options_parameters() {
2756 return new external_function_parameters(
2757 array(
2758 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2764 * Return a list of navigation options in a set of courses that are avaialable or not for the current user.
2766 * @param array $courseids a list of course ids
2767 * @return array of warnings and the options availability
2768 * @since Moodle 3.2
2769 * @throws moodle_exception
2771 public static function get_user_navigation_options($courseids) {
2772 global $CFG;
2773 require_once($CFG->dirroot . '/course/lib.php');
2775 // Parameter validation.
2776 $params = self::validate_parameters(self::get_user_navigation_options_parameters(), array('courseids' => $courseids));
2777 $courseoptions = array();
2779 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
2781 if (!empty($courses)) {
2782 foreach ($courses as $course) {
2783 // Fix the context for the frontpage.
2784 if ($course->id == SITEID) {
2785 $course->context = context_system::instance();
2787 $navoptions = course_get_user_navigation_options($course->context, $course);
2788 $options = array();
2789 foreach ($navoptions as $name => $available) {
2790 $options[] = array(
2791 'name' => $name,
2792 'available' => $available,
2796 $courseoptions[] = array(
2797 'id' => $course->id,
2798 'options' => $options
2803 $result = array(
2804 'courses' => $courseoptions,
2805 'warnings' => $warnings
2807 return $result;
2811 * Returns description of method result value
2813 * @return external_description
2814 * @since Moodle 3.2
2816 public static function get_user_navigation_options_returns() {
2817 return new external_single_structure(
2818 array(
2819 'courses' => new external_multiple_structure(
2820 new external_single_structure(
2821 array(
2822 'id' => new external_value(PARAM_INT, 'Course id'),
2823 'options' => new external_multiple_structure(
2824 new external_single_structure(
2825 array(
2826 'name' => new external_value(PARAM_ALPHANUMEXT, 'Option name'),
2827 'available' => new external_value(PARAM_BOOL, 'Whether the option is available or not'),
2832 ), 'List of courses'
2834 'warnings' => new external_warnings()
2840 * Returns description of method parameters
2842 * @return external_function_parameters
2843 * @since Moodle 3.2
2845 public static function get_user_administration_options_parameters() {
2846 return new external_function_parameters(
2847 array(
2848 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2854 * Return a list of administration options in a set of courses that are available or not for the current user.
2856 * @param array $courseids a list of course ids
2857 * @return array of warnings and the options availability
2858 * @since Moodle 3.2
2859 * @throws moodle_exception
2861 public static function get_user_administration_options($courseids) {
2862 global $CFG;
2863 require_once($CFG->dirroot . '/course/lib.php');
2865 // Parameter validation.
2866 $params = self::validate_parameters(self::get_user_administration_options_parameters(), array('courseids' => $courseids));
2867 $courseoptions = array();
2869 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
2871 if (!empty($courses)) {
2872 foreach ($courses as $course) {
2873 $adminoptions = course_get_user_administration_options($course, $course->context);
2874 $options = array();
2875 foreach ($adminoptions as $name => $available) {
2876 $options[] = array(
2877 'name' => $name,
2878 'available' => $available,
2882 $courseoptions[] = array(
2883 'id' => $course->id,
2884 'options' => $options
2889 $result = array(
2890 'courses' => $courseoptions,
2891 'warnings' => $warnings
2893 return $result;
2897 * Returns description of method result value
2899 * @return external_description
2900 * @since Moodle 3.2
2902 public static function get_user_administration_options_returns() {
2903 return self::get_user_navigation_options_returns();
2907 * Returns description of method parameters
2909 * @return external_function_parameters
2910 * @since Moodle 3.2
2912 public static function get_courses_by_field_parameters() {
2913 return new external_function_parameters(
2914 array(
2915 'field' => new external_value(PARAM_ALPHA, 'The field to search can be left empty for all courses or:
2916 id: course id
2917 ids: comma separated course ids
2918 shortname: course short name
2919 idnumber: course id number
2920 category: category id the course belongs to
2921 ', VALUE_DEFAULT, ''),
2922 'value' => new external_value(PARAM_RAW, 'The value to match', VALUE_DEFAULT, '')
2929 * Get courses matching a specific field (id/s, shortname, idnumber, category)
2931 * @param string $field field name to search, or empty for all courses
2932 * @param string $value value to search
2933 * @return array list of courses and warnings
2934 * @throws invalid_parameter_exception
2935 * @since Moodle 3.2
2937 public static function get_courses_by_field($field = '', $value = '') {
2938 global $DB, $CFG;
2939 require_once($CFG->libdir . '/coursecatlib.php');
2940 require_once($CFG->libdir . '/filterlib.php');
2942 $params = self::validate_parameters(self::get_courses_by_field_parameters(),
2943 array(
2944 'field' => $field,
2945 'value' => $value,
2948 $warnings = array();
2950 if (empty($params['field'])) {
2951 $courses = $DB->get_records('course', null, 'id ASC');
2952 } else {
2953 switch ($params['field']) {
2954 case 'id':
2955 case 'category':
2956 $value = clean_param($params['value'], PARAM_INT);
2957 break;
2958 case 'ids':
2959 $value = clean_param($params['value'], PARAM_SEQUENCE);
2960 break;
2961 case 'shortname':
2962 $value = clean_param($params['value'], PARAM_TEXT);
2963 break;
2964 case 'idnumber':
2965 $value = clean_param($params['value'], PARAM_RAW);
2966 break;
2967 default:
2968 throw new invalid_parameter_exception('Invalid field name');
2971 if ($params['field'] === 'ids') {
2972 $courses = $DB->get_records_list('course', 'id', explode(',', $value), 'id ASC');
2973 } else {
2974 $courses = $DB->get_records('course', array($params['field'] => $value), 'id ASC');
2978 $coursesdata = array();
2979 foreach ($courses as $course) {
2980 $context = context_course::instance($course->id);
2981 $canupdatecourse = has_capability('moodle/course:update', $context);
2982 $canviewhiddencourses = has_capability('moodle/course:viewhiddencourses', $context);
2984 // Check if the course is visible in the site for the user.
2985 if (!$course->visible and !$canviewhiddencourses and !$canupdatecourse) {
2986 continue;
2988 // Get the public course information, even if we are not enrolled.
2989 $courseinlist = new course_in_list($course);
2990 $coursesdata[$course->id] = self::get_course_public_information($courseinlist, $context);
2992 // Now, check if we have access to the course.
2993 try {
2994 self::validate_context($context);
2995 } catch (Exception $e) {
2996 continue;
2998 // Return information for any user that can access the course.
2999 $coursefields = array('format', 'showgrades', 'newsitems', 'startdate', 'maxbytes', 'showreports', 'visible',
3000 'groupmode', 'groupmodeforce', 'defaultgroupingid', 'enablecompletion', 'completionnotify', 'lang', 'theme',
3001 'sortorder', 'marker');
3003 // Course filters.
3004 $coursesdata[$course->id]['filters'] = filter_get_available_in_context($context);
3006 // Information for managers only.
3007 if ($canupdatecourse) {
3008 $managerfields = array('idnumber', 'legacyfiles', 'calendartype', 'timecreated', 'timemodified', 'requested',
3009 'cacherev');
3010 $coursefields = array_merge($coursefields, $managerfields);
3013 // Populate fields.
3014 foreach ($coursefields as $field) {
3015 $coursesdata[$course->id][$field] = $course->{$field};
3019 return array(
3020 'courses' => $coursesdata,
3021 'warnings' => $warnings
3026 * Returns description of method result value
3028 * @return external_description
3029 * @since Moodle 3.2
3031 public static function get_courses_by_field_returns() {
3032 // Course structure, including not only public viewable fields.
3033 return new external_single_structure(
3034 array(
3035 'courses' => new external_multiple_structure(self::get_course_structure(false), 'Course'),
3036 'warnings' => new external_warnings()
3042 * Returns description of method parameters
3044 * @return external_function_parameters
3045 * @since Moodle 3.2
3047 public static function check_updates_parameters() {
3048 return new external_function_parameters(
3049 array(
3050 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3051 'tocheck' => new external_multiple_structure(
3052 new external_single_structure(
3053 array(
3054 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level for the file location.
3055 Only module supported right now.'),
3056 'id' => new external_value(PARAM_INT, 'Context instance id'),
3057 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3060 'Instances to check'
3062 'filter' => new external_multiple_structure(
3063 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3064 gradeitems, outcomes'),
3065 'Check only for updates in these areas', VALUE_DEFAULT, array()
3072 * Check if there is updates affecting the user for the given course and contexts.
3073 * Right now only modules are supported.
3074 * This WS calls mod_check_updates_since for each module to check if there is any update the user should we aware of.
3076 * @param int $courseid the list of modules to check
3077 * @param array $tocheck the list of modules to check
3078 * @param array $filter check only for updates in these areas
3079 * @return array list of updates and warnings
3080 * @throws moodle_exception
3081 * @since Moodle 3.2
3083 public static function check_updates($courseid, $tocheck, $filter = array()) {
3084 global $CFG, $DB;
3086 $params = self::validate_parameters(
3087 self::check_updates_parameters(),
3088 array(
3089 'courseid' => $courseid,
3090 'tocheck' => $tocheck,
3091 'filter' => $filter,
3095 $course = get_course($params['courseid']);
3096 $context = context_course::instance($course->id);
3097 self::validate_context($context);
3099 list($instances, $warnings) = course_check_updates($course, $params['tocheck'], $filter);
3101 $instancesformatted = array();
3102 foreach ($instances as $instance) {
3103 $updates = array();
3104 foreach ($instance['updates'] as $name => $data) {
3105 if (empty($data->updated)) {
3106 continue;
3108 $updatedata = array(
3109 'name' => $name,
3111 if (!empty($data->timeupdated)) {
3112 $updatedata['timeupdated'] = $data->timeupdated;
3114 if (!empty($data->itemids)) {
3115 $updatedata['itemids'] = $data->itemids;
3117 $updates[] = $updatedata;
3119 if (!empty($updates)) {
3120 $instancesformatted[] = array(
3121 'contextlevel' => $instance['contextlevel'],
3122 'id' => $instance['id'],
3123 'updates' => $updates
3128 return array(
3129 'instances' => $instancesformatted,
3130 'warnings' => $warnings
3135 * Returns description of method result value
3137 * @return external_description
3138 * @since Moodle 3.2
3140 public static function check_updates_returns() {
3141 return new external_single_structure(
3142 array(
3143 'instances' => new external_multiple_structure(
3144 new external_single_structure(
3145 array(
3146 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level'),
3147 'id' => new external_value(PARAM_INT, 'Instance id'),
3148 'updates' => new external_multiple_structure(
3149 new external_single_structure(
3150 array(
3151 'name' => new external_value(PARAM_ALPHANUMEXT, 'Name of the area updated.'),
3152 'timeupdated' => new external_value(PARAM_INT, 'Last time was updated', VALUE_OPTIONAL),
3153 'itemids' => new external_multiple_structure(
3154 new external_value(PARAM_INT, 'Instance id'),
3155 'The ids of the items updated',
3156 VALUE_OPTIONAL
3164 'warnings' => new external_warnings()
3170 * Returns description of method parameters
3172 * @return external_function_parameters
3173 * @since Moodle 3.3
3175 public static function get_updates_since_parameters() {
3176 return new external_function_parameters(
3177 array(
3178 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3179 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3180 'filter' => new external_multiple_structure(
3181 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3182 gradeitems, outcomes'),
3183 'Check only for updates in these areas', VALUE_DEFAULT, array()
3190 * Check if there are updates affecting the user for the given course since the given time stamp.
3192 * This function is a wrapper of self::check_updates for retrieving all the updates since a given time for all the activities.
3194 * @param int $courseid the list of modules to check
3195 * @param int $since check updates since this time stamp
3196 * @param array $filter check only for updates in these areas
3197 * @return array list of updates and warnings
3198 * @throws moodle_exception
3199 * @since Moodle 3.3
3201 public static function get_updates_since($courseid, $since, $filter = array()) {
3202 global $CFG, $DB;
3204 $params = self::validate_parameters(
3205 self::get_updates_since_parameters(),
3206 array(
3207 'courseid' => $courseid,
3208 'since' => $since,
3209 'filter' => $filter,
3213 $course = get_course($params['courseid']);
3214 $modinfo = get_fast_modinfo($course);
3215 $tocheck = array();
3217 // Retrieve all the visible course modules for the current user.
3218 $cms = $modinfo->get_cms();
3219 foreach ($cms as $cm) {
3220 if (!$cm->uservisible) {
3221 continue;
3223 $tocheck[] = array(
3224 'id' => $cm->id,
3225 'contextlevel' => 'module',
3226 'since' => $params['since'],
3230 return self::check_updates($course->id, $tocheck, $params['filter']);
3234 * Returns description of method result value
3236 * @return external_description
3237 * @since Moodle 3.3
3239 public static function get_updates_since_returns() {
3240 return self::check_updates_returns();
3244 * Parameters for function edit_module()
3246 * @since Moodle 3.3
3247 * @return external_function_parameters
3249 public static function edit_module_parameters() {
3250 return new external_function_parameters(
3251 array(
3252 'action' => new external_value(PARAM_ALPHA,
3253 'action: hide, show, stealth, duplicate, delete, moveleft, moveright, group...', VALUE_REQUIRED),
3254 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3255 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3260 * Performs one of the edit module actions and return new html for AJAX
3262 * Returns html to replace the current module html with, for example:
3263 * - empty string for "delete" action,
3264 * - two modules html for "duplicate" action
3265 * - updated module html for everything else
3267 * Throws exception if operation is not permitted/possible
3269 * @since Moodle 3.3
3270 * @param string $action
3271 * @param int $id
3272 * @param null|int $sectionreturn
3273 * @return string
3275 public static function edit_module($action, $id, $sectionreturn = null) {
3276 global $PAGE, $DB;
3277 // Validate and normalize parameters.
3278 $params = self::validate_parameters(self::edit_module_parameters(),
3279 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3280 $action = $params['action'];
3281 $id = $params['id'];
3282 $sectionreturn = $params['sectionreturn'];
3284 list($course, $cm) = get_course_and_cm_from_cmid($id);
3285 $modcontext = context_module::instance($cm->id);
3286 $coursecontext = context_course::instance($course->id);
3287 self::validate_context($modcontext);
3288 $courserenderer = $PAGE->get_renderer('core', 'course');
3289 $completioninfo = new completion_info($course);
3291 switch($action) {
3292 case 'hide':
3293 case 'show':
3294 case 'stealth':
3295 require_capability('moodle/course:activityvisibility', $modcontext);
3296 $visible = ($action === 'hide') ? 0 : 1;
3297 $visibleoncoursepage = ($action === 'stealth') ? 0 : 1;
3298 set_coursemodule_visible($id, $visible, $visibleoncoursepage);
3299 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3300 break;
3301 case 'duplicate':
3302 require_capability('moodle/course:manageactivities', $coursecontext);
3303 require_capability('moodle/backup:backuptargetimport', $coursecontext);
3304 require_capability('moodle/restore:restoretargetimport', $coursecontext);
3305 if (!course_allowed_module($course, $cm->modname)) {
3306 throw new moodle_exception('No permission to create that activity');
3308 if ($newcm = duplicate_module($course, $cm)) {
3309 $cm = get_fast_modinfo($course)->get_cm($id);
3310 $newcm = get_fast_modinfo($course)->get_cm($newcm->id);
3311 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn) .
3312 $courserenderer->course_section_cm_list_item($course, $completioninfo, $newcm, $sectionreturn);
3314 break;
3315 case 'groupsseparate':
3316 case 'groupsvisible':
3317 case 'groupsnone':
3318 require_capability('moodle/course:manageactivities', $modcontext);
3319 if ($action === 'groupsseparate') {
3320 $newgroupmode = SEPARATEGROUPS;
3321 } else if ($action === 'groupsvisible') {
3322 $newgroupmode = VISIBLEGROUPS;
3323 } else {
3324 $newgroupmode = NOGROUPS;
3326 if (set_coursemodule_groupmode($cm->id, $newgroupmode)) {
3327 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3329 break;
3330 case 'moveleft':
3331 case 'moveright':
3332 require_capability('moodle/course:manageactivities', $modcontext);
3333 $indent = $cm->indent + (($action === 'moveright') ? 1 : -1);
3334 if ($cm->indent >= 0) {
3335 $DB->update_record('course_modules', array('id' => $cm->id, 'indent' => $indent));
3336 rebuild_course_cache($cm->course);
3338 break;
3339 case 'delete':
3340 require_capability('moodle/course:manageactivities', $modcontext);
3341 course_delete_module($cm->id, true);
3342 return '';
3343 default:
3344 throw new coding_exception('Unrecognised action');
3347 $cm = get_fast_modinfo($course)->get_cm($id);
3348 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn);
3352 * Return structure for edit_module()
3354 * @since Moodle 3.3
3355 * @return external_description
3357 public static function edit_module_returns() {
3358 return new external_value(PARAM_RAW, 'html to replace the current module with');
3362 * Parameters for function get_module()
3364 * @since Moodle 3.3
3365 * @return external_function_parameters
3367 public static function get_module_parameters() {
3368 return new external_function_parameters(
3369 array(
3370 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3371 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3376 * Returns html for displaying one activity module on course page
3378 * @since Moodle 3.3
3379 * @param int $id
3380 * @param null|int $sectionreturn
3381 * @return string
3383 public static function get_module($id, $sectionreturn = null) {
3384 global $PAGE;
3385 // Validate and normalize parameters.
3386 $params = self::validate_parameters(self::get_module_parameters(),
3387 array('id' => $id, 'sectionreturn' => $sectionreturn));
3388 $id = $params['id'];
3389 $sectionreturn = $params['sectionreturn'];
3391 // Validate access to the course (note, this is html for the course view page, we don't validate access to the module).
3392 list($course, $cm) = get_course_and_cm_from_cmid($id);
3393 self::validate_context(context_course::instance($course->id));
3395 $courserenderer = $PAGE->get_renderer('core', 'course');
3396 $completioninfo = new completion_info($course);
3397 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn);
3401 * Return structure for edit_module()
3403 * @since Moodle 3.3
3404 * @return external_description
3406 public static function get_module_returns() {
3407 return new external_value(PARAM_RAW, 'html to replace the current module with');
3411 * Parameters for function edit_section()
3413 * @since Moodle 3.3
3414 * @return external_function_parameters
3416 public static function edit_section_parameters() {
3417 return new external_function_parameters(
3418 array(
3419 'action' => new external_value(PARAM_ALPHA, 'action: hide, show, stealth, setmarker, removemarker', VALUE_REQUIRED),
3420 'id' => new external_value(PARAM_INT, 'course section id', VALUE_REQUIRED),
3421 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3426 * Performs one of the edit section actions
3428 * @since Moodle 3.3
3429 * @param string $action
3430 * @param int $id section id
3431 * @param int $sectionreturn section to return to
3432 * @return string
3434 public static function edit_section($action, $id, $sectionreturn) {
3435 global $DB;
3436 // Validate and normalize parameters.
3437 $params = self::validate_parameters(self::edit_section_parameters(),
3438 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3439 $action = $params['action'];
3440 $id = $params['id'];
3441 $sr = $params['sectionreturn'];
3443 $section = $DB->get_record('course_sections', array('id' => $id), '*', MUST_EXIST);
3444 $coursecontext = context_course::instance($section->course);
3445 self::validate_context($coursecontext);
3447 $rv = course_get_format($section->course)->section_action($section, $action, $sectionreturn);
3448 if ($rv) {
3449 return json_encode($rv);
3450 } else {
3451 return null;
3456 * Return structure for edit_section()
3458 * @since Moodle 3.3
3459 * @return external_description
3461 public static function edit_section_returns() {
3462 return new external_value(PARAM_RAW, 'Additional data for javascript (JSON-encoded string)');