2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
21 * @package core_course
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");
32 * Course external functions
34 * @package core_course
36 * @copyright 2011 Jerome Mouneyrac
37 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
40 class core_course_external extends external_api {
43 * Returns description of method parameters
45 * @return external_function_parameters
46 * @since Moodle 2.9 Options available
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(
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())
75 * @param int $courseid course id
76 * @param array $options Options for filtering the results, used since Moodle 2.9
78 * @since Moodle 2.9 Options available
81 public static function get_course_contents($courseid, $options = array()) {
83 require_once($CFG->dirroot . "/course/lib.php");
86 $params = self::validate_parameters(self::get_course_contents_parameters(),
87 array('courseid' => $courseid, 'options' => $options));
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])) {
97 case 'excludemodules':
98 case 'excludecontents':
99 $value = clean_param($option['value'], PARAM_BOOL);
100 $filters[$name] = $value;
103 case 'sectionnumber':
106 $value = clean_param($option['value'], PARAM_INT);
107 if (is_numeric($value)) {
108 $filters[$name] = $value;
110 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
114 $value = clean_param($option['value'], PARAM_PLUGIN);
116 $filters[$name] = $value;
118 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
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));
137 require_once($CFG->dirroot . '/course/format/' . $course->format . '/lib.php');
141 // now security checks
142 $context = context_course::instance($course->id, IGNORE_MISSING);
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)) {
161 $modinfo = get_fast_modinfo($course);
162 $sections = $modinfo->get_section_info_all();
163 $coursenumsections = course_get_format($course)->get_last_section_number();
165 //for each sections (first displayed to last displayed)
166 $modinfosections = $modinfo->get_sections();
167 foreach ($sections as $key => $section) {
169 if (!$section->uservisible) {
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']) {
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']) {
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) {
218 // This becomes true when we are filtering and we found the value to filter with.
222 if (!empty($filters['cmid'])) {
223 if ($cmid != $filters['cmid']) {
230 // Filter by module name and id.
231 if (!empty($filters['modname'])) {
232 if ($cm->modname != $filters['modname']) {
234 } else if (!empty($filters['modid'])) {
235 if ($cm->instance != $filters['modid']) {
238 // Note that if we are only filtering by modname we don't break the loop.
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);
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;
291 $module['contents'] = array();
295 //assign result to $sectioncontents
296 $sectioncontents[] = $module;
298 // If we just did a filtering, break the loop.
305 $sectionvalues['modules'] = $sectioncontents;
307 // assign result to $coursecontents
308 $coursecontents[] = $sectionvalues;
310 // Break the loop if we are filtering.
316 return $coursecontents;
320 * Returns description of method result value
322 * @return external_description
325 public static function get_course_contents_returns() {
326 return new external_multiple_structure(
327 new external_single_structure(
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',
337 'modules' => new external_multiple_structure(
338 new external_single_structure(
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',
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(
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'),
366 'mimetype' => new external_value(PARAM_RAW, 'File mime type.', VALUE_OPTIONAL),
367 'isexternalfile' => new external_value(PARAM_BOOL, 'Whether is an external file.',
369 'repositorytype' => new external_value(PARAM_PLUGIN, 'The repository type for external files.',
372 // copyright related info
373 'userid' => new external_value(PARAM_INT, 'User who added this content to moodle'),
374 'author' => new external_value(PARAM_TEXT, 'Content owner'),
375 'license' => new external_value(PARAM_TEXT, 'Content license'),
377 ), VALUE_DEFAULT, array()
388 * Returns description of method parameters
390 * @return external_function_parameters
393 public static function get_courses_parameters() {
394 return new external_function_parameters(
395 array('options' => new external_single_structure(
396 array('ids' => new external_multiple_structure(
397 new external_value(PARAM_INT, 'Course id')
398 , 'List of course id. If empty return all courses
399 except front page course.',
401 ), 'options - operator OR is used', VALUE_DEFAULT, array())
409 * @param array $options It contains an array (list of ids)
413 public static function get_courses($options = array()) {
415 require_once($CFG->dirroot . "/course/lib.php");
418 $params = self::validate_parameters(self::get_courses_parameters(),
419 array('options' => $options));
422 if (!array_key_exists('ids', $params['options'])
423 or empty($params['options']['ids'])) {
424 $courses = $DB->get_records('course');
426 $courses = $DB->get_records_list('course', 'id', $params['options']['ids']);
429 //create return value
430 $coursesinfo = array();
431 foreach ($courses as $course) {
433 // now security checks
434 $context = context_course::instance($course->id, IGNORE_MISSING);
435 $courseformatoptions = course_get_format($course)->get_format_options();
437 self::validate_context($context);
438 } catch (Exception $e) {
439 $exceptionparam = new stdClass();
440 $exceptionparam->message = $e->getMessage();
441 $exceptionparam->courseid = $course->id;
442 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
444 require_capability('moodle/course:view', $context);
446 $courseinfo = array();
447 $courseinfo['id'] = $course->id;
448 $courseinfo['fullname'] = external_format_string($course->fullname, $context->id);
449 $courseinfo['shortname'] = external_format_string($course->shortname, $context->id);
450 $courseinfo['displayname'] = external_format_string(get_course_display_name_for_list($course), $context->id);
451 $courseinfo['categoryid'] = $course->category;
452 list($courseinfo['summary'], $courseinfo['summaryformat']) =
453 external_format_text($course->summary, $course->summaryformat, $context->id, 'course', 'summary', 0);
454 $courseinfo['format'] = $course->format;
455 $courseinfo['startdate'] = $course->startdate;
456 $courseinfo['enddate'] = $course->enddate;
457 if (array_key_exists('numsections', $courseformatoptions)) {
458 // For backward-compartibility
459 $courseinfo['numsections'] = $courseformatoptions['numsections'];
462 //some field should be returned only if the user has update permission
463 $courseadmin = has_capability('moodle/course:update', $context);
465 $courseinfo['categorysortorder'] = $course->sortorder;
466 $courseinfo['idnumber'] = $course->idnumber;
467 $courseinfo['showgrades'] = $course->showgrades;
468 $courseinfo['showreports'] = $course->showreports;
469 $courseinfo['newsitems'] = $course->newsitems;
470 $courseinfo['visible'] = $course->visible;
471 $courseinfo['maxbytes'] = $course->maxbytes;
472 if (array_key_exists('hiddensections', $courseformatoptions)) {
473 // For backward-compartibility
474 $courseinfo['hiddensections'] = $courseformatoptions['hiddensections'];
476 // Return numsections for backward-compatibility with clients who expect it.
477 $courseinfo['numsections'] = course_get_format($course)->get_last_section_number();
478 $courseinfo['groupmode'] = $course->groupmode;
479 $courseinfo['groupmodeforce'] = $course->groupmodeforce;
480 $courseinfo['defaultgroupingid'] = $course->defaultgroupingid;
481 $courseinfo['lang'] = $course->lang;
482 $courseinfo['timecreated'] = $course->timecreated;
483 $courseinfo['timemodified'] = $course->timemodified;
484 $courseinfo['forcetheme'] = $course->theme;
485 $courseinfo['enablecompletion'] = $course->enablecompletion;
486 $courseinfo['completionnotify'] = $course->completionnotify;
487 $courseinfo['courseformatoptions'] = array();
488 foreach ($courseformatoptions as $key => $value) {
489 $courseinfo['courseformatoptions'][] = array(
496 if ($courseadmin or $course->visible
497 or has_capability('moodle/course:viewhiddencourses', $context)) {
498 $coursesinfo[] = $courseinfo;
506 * Returns description of method result value
508 * @return external_description
511 public static function get_courses_returns() {
512 return new external_multiple_structure(
513 new external_single_structure(
515 'id' => new external_value(PARAM_INT, 'course id'),
516 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
517 'categoryid' => new external_value(PARAM_INT, 'category id'),
518 'categorysortorder' => new external_value(PARAM_INT,
519 'sort order into the category', VALUE_OPTIONAL),
520 'fullname' => new external_value(PARAM_TEXT, 'full name'),
521 'displayname' => new external_value(PARAM_TEXT, 'course display name'),
522 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
523 'summary' => new external_value(PARAM_RAW, 'summary'),
524 'summaryformat' => new external_format_value('summary'),
525 'format' => new external_value(PARAM_PLUGIN,
526 'course format: weeks, topics, social, site,..'),
527 'showgrades' => new external_value(PARAM_INT,
528 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
529 'newsitems' => new external_value(PARAM_INT,
530 'number of recent items appearing on the course page', VALUE_OPTIONAL),
531 'startdate' => new external_value(PARAM_INT,
532 'timestamp when the course start'),
533 'enddate' => new external_value(PARAM_INT,
534 'timestamp when the course end'),
535 'numsections' => new external_value(PARAM_INT,
536 '(deprecated, use courseformatoptions) number of weeks/topics',
538 'maxbytes' => new external_value(PARAM_INT,
539 'largest size of file that can be uploaded into the course',
541 'showreports' => new external_value(PARAM_INT,
542 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
543 'visible' => new external_value(PARAM_INT,
544 '1: available to student, 0:not available', VALUE_OPTIONAL),
545 'hiddensections' => new external_value(PARAM_INT,
546 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
548 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
550 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
552 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
554 'timecreated' => new external_value(PARAM_INT,
555 'timestamp when the course have been created', VALUE_OPTIONAL),
556 'timemodified' => new external_value(PARAM_INT,
557 'timestamp when the course have been modified', VALUE_OPTIONAL),
558 'enablecompletion' => new external_value(PARAM_INT,
559 'Enabled, control via completion and activity settings. Disbaled,
560 not shown in activity settings.',
562 'completionnotify' => new external_value(PARAM_INT,
563 '1: yes 0: no', VALUE_OPTIONAL),
564 'lang' => new external_value(PARAM_SAFEDIR,
565 'forced course language', VALUE_OPTIONAL),
566 'forcetheme' => new external_value(PARAM_PLUGIN,
567 'name of the force theme', VALUE_OPTIONAL),
568 'courseformatoptions' => new external_multiple_structure(
569 new external_single_structure(
570 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
571 'value' => new external_value(PARAM_RAW, 'course format option value')
573 'additional options for particular course format', VALUE_OPTIONAL
581 * Returns description of method parameters
583 * @return external_function_parameters
586 public static function create_courses_parameters() {
587 $courseconfig = get_config('moodlecourse'); //needed for many default values
588 return new external_function_parameters(
590 'courses' => new external_multiple_structure(
591 new external_single_structure(
593 'fullname' => new external_value(PARAM_TEXT, 'full name'),
594 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
595 'categoryid' => new external_value(PARAM_INT, 'category id'),
596 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
597 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
598 'summaryformat' => new external_format_value('summary', VALUE_DEFAULT),
599 'format' => new external_value(PARAM_PLUGIN,
600 'course format: weeks, topics, social, site,..',
601 VALUE_DEFAULT, $courseconfig->format),
602 'showgrades' => new external_value(PARAM_INT,
603 '1 if grades are shown, otherwise 0', VALUE_DEFAULT,
604 $courseconfig->showgrades),
605 'newsitems' => new external_value(PARAM_INT,
606 'number of recent items appearing on the course page',
607 VALUE_DEFAULT, $courseconfig->newsitems),
608 'startdate' => new external_value(PARAM_INT,
609 'timestamp when the course start', VALUE_OPTIONAL),
610 'enddate' => new external_value(PARAM_INT,
611 'timestamp when the course end', VALUE_OPTIONAL),
612 'numsections' => new external_value(PARAM_INT,
613 '(deprecated, use courseformatoptions) number of weeks/topics',
615 'maxbytes' => new external_value(PARAM_INT,
616 'largest size of file that can be uploaded into the course',
617 VALUE_DEFAULT, $courseconfig->maxbytes),
618 'showreports' => new external_value(PARAM_INT,
619 'are activity report shown (yes = 1, no =0)', VALUE_DEFAULT,
620 $courseconfig->showreports),
621 'visible' => new external_value(PARAM_INT,
622 '1: available to student, 0:not available', VALUE_OPTIONAL),
623 'hiddensections' => new external_value(PARAM_INT,
624 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
626 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
627 VALUE_DEFAULT, $courseconfig->groupmode),
628 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
629 VALUE_DEFAULT, $courseconfig->groupmodeforce),
630 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
632 'enablecompletion' => new external_value(PARAM_INT,
633 'Enabled, control via completion and activity settings. Disabled,
634 not shown in activity settings.',
636 'completionnotify' => new external_value(PARAM_INT,
637 '1: yes 0: no', VALUE_OPTIONAL),
638 'lang' => new external_value(PARAM_SAFEDIR,
639 'forced course language', VALUE_OPTIONAL),
640 'forcetheme' => new external_value(PARAM_PLUGIN,
641 'name of the force theme', VALUE_OPTIONAL),
642 'courseformatoptions' => new external_multiple_structure(
643 new external_single_structure(
644 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
645 'value' => new external_value(PARAM_RAW, 'course format option value')
647 'additional options for particular course format', VALUE_OPTIONAL),
649 ), 'courses to create'
658 * @param array $courses
659 * @return array courses (id and shortname only)
662 public static function create_courses($courses) {
664 require_once($CFG->dirroot . "/course/lib.php");
665 require_once($CFG->libdir . '/completionlib.php');
667 $params = self::validate_parameters(self::create_courses_parameters(),
668 array('courses' => $courses));
670 $availablethemes = core_component::get_plugin_list('theme');
671 $availablelangs = get_string_manager()->get_list_of_translations();
673 $transaction = $DB->start_delegated_transaction();
675 foreach ($params['courses'] as $course) {
677 // Ensure the current user is allowed to run this function
678 $context = context_coursecat::instance($course['categoryid'], IGNORE_MISSING);
680 self::validate_context($context);
681 } catch (Exception $e) {
682 $exceptionparam = new stdClass();
683 $exceptionparam->message = $e->getMessage();
684 $exceptionparam->catid = $course['categoryid'];
685 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
687 require_capability('moodle/course:create', $context);
689 // Make sure lang is valid
690 if (array_key_exists('lang', $course) and empty($availablelangs[$course['lang']])) {
691 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
694 // Make sure theme is valid
695 if (array_key_exists('forcetheme', $course)) {
696 if (!empty($CFG->allowcoursethemes)) {
697 if (empty($availablethemes[$course['forcetheme']])) {
698 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
700 $course['theme'] = $course['forcetheme'];
705 //force visibility if ws user doesn't have the permission to set it
706 $category = $DB->get_record('course_categories', array('id' => $course['categoryid']));
707 if (!has_capability('moodle/course:visibility', $context)) {
708 $course['visible'] = $category->visible;
711 //set default value for completion
712 $courseconfig = get_config('moodlecourse');
713 if (completion_info::is_enabled_for_site()) {
714 if (!array_key_exists('enablecompletion', $course)) {
715 $course['enablecompletion'] = $courseconfig->enablecompletion;
718 $course['enablecompletion'] = 0;
721 $course['category'] = $course['categoryid'];
724 $course['summaryformat'] = external_validate_format($course['summaryformat']);
726 if (!empty($course['courseformatoptions'])) {
727 foreach ($course['courseformatoptions'] as $option) {
728 $course[$option['name']] = $option['value'];
732 //Note: create_course() core function check shortname, idnumber, category
733 $course['id'] = create_course((object) $course)->id;
735 $resultcourses[] = array('id' => $course['id'], 'shortname' => $course['shortname']);
738 $transaction->allow_commit();
740 return $resultcourses;
744 * Returns description of method result value
746 * @return external_description
749 public static function create_courses_returns() {
750 return new external_multiple_structure(
751 new external_single_structure(
753 'id' => new external_value(PARAM_INT, 'course id'),
754 'shortname' => new external_value(PARAM_TEXT, 'short name'),
763 * @return external_function_parameters
766 public static function update_courses_parameters() {
767 return new external_function_parameters(
769 'courses' => new external_multiple_structure(
770 new external_single_structure(
772 'id' => new external_value(PARAM_INT, 'ID of the course'),
773 'fullname' => new external_value(PARAM_TEXT, 'full name', VALUE_OPTIONAL),
774 'shortname' => new external_value(PARAM_TEXT, 'course short name', VALUE_OPTIONAL),
775 'categoryid' => new external_value(PARAM_INT, 'category id', VALUE_OPTIONAL),
776 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
777 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
778 'summaryformat' => new external_format_value('summary', VALUE_OPTIONAL),
779 'format' => new external_value(PARAM_PLUGIN,
780 'course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
781 'showgrades' => new external_value(PARAM_INT,
782 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
783 'newsitems' => new external_value(PARAM_INT,
784 'number of recent items appearing on the course page', VALUE_OPTIONAL),
785 'startdate' => new external_value(PARAM_INT,
786 'timestamp when the course start', VALUE_OPTIONAL),
787 'enddate' => new external_value(PARAM_INT,
788 'timestamp when the course end', VALUE_OPTIONAL),
789 'numsections' => new external_value(PARAM_INT,
790 '(deprecated, use courseformatoptions) number of weeks/topics', VALUE_OPTIONAL),
791 'maxbytes' => new external_value(PARAM_INT,
792 'largest size of file that can be uploaded into the course', VALUE_OPTIONAL),
793 'showreports' => new external_value(PARAM_INT,
794 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
795 'visible' => new external_value(PARAM_INT,
796 '1: available to student, 0:not available', VALUE_OPTIONAL),
797 'hiddensections' => new external_value(PARAM_INT,
798 '(deprecated, use courseformatoptions) How the hidden sections in the course are
799 displayed to students', VALUE_OPTIONAL),
800 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
801 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
802 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
803 'enablecompletion' => new external_value(PARAM_INT,
804 'Enabled, control via completion and activity settings. Disabled,
805 not shown in activity settings.', VALUE_OPTIONAL),
806 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
807 'lang' => new external_value(PARAM_SAFEDIR, 'forced course language', VALUE_OPTIONAL),
808 'forcetheme' => new external_value(PARAM_PLUGIN, 'name of the force theme', VALUE_OPTIONAL),
809 'courseformatoptions' => new external_multiple_structure(
810 new external_single_structure(
811 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
812 'value' => new external_value(PARAM_RAW, 'course format option value')
814 'additional options for particular course format', VALUE_OPTIONAL),
816 ), 'courses to update'
825 * @param array $courses
828 public static function update_courses($courses) {
830 require_once($CFG->dirroot . "/course/lib.php");
833 $params = self::validate_parameters(self::update_courses_parameters(),
834 array('courses' => $courses));
836 $availablethemes = core_component::get_plugin_list('theme');
837 $availablelangs = get_string_manager()->get_list_of_translations();
839 foreach ($params['courses'] as $course) {
840 // Catch any exception while updating course and return as warning to user.
842 // Ensure the current user is allowed to run this function.
843 $context = context_course::instance($course['id'], MUST_EXIST);
844 self::validate_context($context);
846 $oldcourse = course_get_format($course['id'])->get_course();
848 require_capability('moodle/course:update', $context);
850 // Check if user can change category.
851 if (array_key_exists('categoryid', $course) && ($oldcourse->category != $course['categoryid'])) {
852 require_capability('moodle/course:changecategory', $context);
853 $course['category'] = $course['categoryid'];
856 // Check if the user can change fullname.
857 if (array_key_exists('fullname', $course) && ($oldcourse->fullname != $course['fullname'])) {
858 require_capability('moodle/course:changefullname', $context);
861 // Check if the user can change shortname.
862 if (array_key_exists('shortname', $course) && ($oldcourse->shortname != $course['shortname'])) {
863 require_capability('moodle/course:changeshortname', $context);
866 // Check if the user can change the idnumber.
867 if (array_key_exists('idnumber', $course) && ($oldcourse->idnumber != $course['idnumber'])) {
868 require_capability('moodle/course:changeidnumber', $context);
871 // Check if user can change summary.
872 if (array_key_exists('summary', $course) && ($oldcourse->summary != $course['summary'])) {
873 require_capability('moodle/course:changesummary', $context);
877 if (array_key_exists('summaryformat', $course) && ($oldcourse->summaryformat != $course['summaryformat'])) {
878 require_capability('moodle/course:changesummary', $context);
879 $course['summaryformat'] = external_validate_format($course['summaryformat']);
882 // Check if user can change visibility.
883 if (array_key_exists('visible', $course) && ($oldcourse->visible != $course['visible'])) {
884 require_capability('moodle/course:visibility', $context);
887 // Make sure lang is valid.
888 if (array_key_exists('lang', $course) && empty($availablelangs[$course['lang']])) {
889 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
892 // Make sure theme is valid.
893 if (array_key_exists('forcetheme', $course)) {
894 if (!empty($CFG->allowcoursethemes)) {
895 if (empty($availablethemes[$course['forcetheme']])) {
896 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
898 $course['theme'] = $course['forcetheme'];
903 // Make sure completion is enabled before setting it.
904 if (array_key_exists('enabledcompletion', $course) && !completion_info::is_enabled_for_site()) {
905 $course['enabledcompletion'] = 0;
908 // Make sure maxbytes are less then CFG->maxbytes.
909 if (array_key_exists('maxbytes', $course)) {
910 $course['maxbytes'] = get_max_upload_file_size($CFG->maxbytes, $course['maxbytes']);
913 if (!empty($course['courseformatoptions'])) {
914 foreach ($course['courseformatoptions'] as $option) {
915 if (isset($option['name']) && isset($option['value'])) {
916 $course[$option['name']] = $option['value'];
921 // Update course if user has all required capabilities.
922 update_course((object) $course);
923 } catch (Exception $e) {
925 $warning['item'] = 'course';
926 $warning['itemid'] = $course['id'];
927 if ($e instanceof moodle_exception) {
928 $warning['warningcode'] = $e->errorcode;
930 $warning['warningcode'] = $e->getCode();
932 $warning['message'] = $e->getMessage();
933 $warnings[] = $warning;
938 $result['warnings'] = $warnings;
943 * Returns description of method result value
945 * @return external_description
948 public static function update_courses_returns() {
949 return new external_single_structure(
951 'warnings' => new external_warnings()
957 * Returns description of method parameters
959 * @return external_function_parameters
962 public static function delete_courses_parameters() {
963 return new external_function_parameters(
965 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'course ID')),
973 * @param array $courseids A list of course ids
976 public static function delete_courses($courseids) {
978 require_once($CFG->dirroot."/course/lib.php");
980 // Parameter validation.
981 $params = self::validate_parameters(self::delete_courses_parameters(), array('courseids'=>$courseids));
985 foreach ($params['courseids'] as $courseid) {
986 $course = $DB->get_record('course', array('id' => $courseid));
988 if ($course === false) {
991 'itemid' => $courseid,
992 'warningcode' => 'unknowncourseidnumber',
993 'message' => 'Unknown course ID ' . $courseid
998 // Check if the context is valid.
999 $coursecontext = context_course::instance($course->id);
1000 self::validate_context($coursecontext);
1002 // Check if the current user has permission.
1003 if (!can_delete_course($courseid)) {
1004 $warnings[] = array(
1006 'itemid' => $courseid,
1007 'warningcode' => 'cannotdeletecourse',
1008 'message' => 'You do not have the permission to delete this course' . $courseid
1013 if (delete_course($course, false) === false) {
1014 $warnings[] = array(
1016 'itemid' => $courseid,
1017 'warningcode' => 'cannotdeletecategorycourse',
1018 'message' => 'Course ' . $courseid . ' failed to be deleted'
1024 fix_course_sortorder();
1026 return array('warnings' => $warnings);
1030 * Returns description of method result value
1032 * @return external_description
1035 public static function delete_courses_returns() {
1036 return new external_single_structure(
1038 'warnings' => new external_warnings()
1044 * Returns description of method parameters
1046 * @return external_function_parameters
1049 public static function duplicate_course_parameters() {
1050 return new external_function_parameters(
1052 'courseid' => new external_value(PARAM_INT, 'course to duplicate id'),
1053 'fullname' => new external_value(PARAM_TEXT, 'duplicated course full name'),
1054 'shortname' => new external_value(PARAM_TEXT, 'duplicated course short name'),
1055 'categoryid' => new external_value(PARAM_INT, 'duplicated course category parent'),
1056 'visible' => new external_value(PARAM_INT, 'duplicated course visible, default to yes', VALUE_DEFAULT, 1),
1057 'options' => new external_multiple_structure(
1058 new external_single_structure(
1060 'name' => new external_value(PARAM_ALPHAEXT, 'The backup option name:
1061 "activities" (int) Include course activites (default to 1 that is equal to yes),
1062 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1063 "filters" (int) Include course filters (default to 1 that is equal to yes),
1064 "users" (int) Include users (default to 0 that is equal to no),
1065 "enrolments" (int) Include enrolment methods (default to 1 - restore only with users),
1066 "role_assignments" (int) Include role assignments (default to 0 that is equal to no),
1067 "comments" (int) Include user comments (default to 0 that is equal to no),
1068 "userscompletion" (int) Include user course completion information (default to 0 that is equal to no),
1069 "logs" (int) Include course logs (default to 0 that is equal to no),
1070 "grade_histories" (int) Include histories (default to 0 that is equal to no)'
1072 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1075 ), VALUE_DEFAULT, array()
1082 * Duplicate a course
1084 * @param int $courseid
1085 * @param string $fullname Duplicated course fullname
1086 * @param string $shortname Duplicated course shortname
1087 * @param int $categoryid Duplicated course parent category id
1088 * @param int $visible Duplicated course availability
1089 * @param array $options List of backup options
1090 * @return array New course info
1093 public static function duplicate_course($courseid, $fullname, $shortname, $categoryid, $visible = 1, $options = array()) {
1094 global $CFG, $USER, $DB;
1095 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1096 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1098 // Parameter validation.
1099 $params = self::validate_parameters(
1100 self::duplicate_course_parameters(),
1102 'courseid' => $courseid,
1103 'fullname' => $fullname,
1104 'shortname' => $shortname,
1105 'categoryid' => $categoryid,
1106 'visible' => $visible,
1107 'options' => $options
1111 // Context validation.
1113 if (! ($course = $DB->get_record('course', array('id'=>$params['courseid'])))) {
1114 throw new moodle_exception('invalidcourseid', 'error');
1117 // Category where duplicated course is going to be created.
1118 $categorycontext = context_coursecat::instance($params['categoryid']);
1119 self::validate_context($categorycontext);
1121 // Course to be duplicated.
1122 $coursecontext = context_course::instance($course->id);
1123 self::validate_context($coursecontext);
1125 $backupdefaults = array(
1130 'enrolments' => backup::ENROL_WITHUSERS,
1131 'role_assignments' => 0,
1133 'userscompletion' => 0,
1135 'grade_histories' => 0
1138 $backupsettings = array();
1139 // Check for backup and restore options.
1140 if (!empty($params['options'])) {
1141 foreach ($params['options'] as $option) {
1143 // Strict check for a correct value (allways 1 or 0, true or false).
1144 $value = clean_param($option['value'], PARAM_INT);
1146 if ($value !== 0 and $value !== 1) {
1147 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1150 if (!isset($backupdefaults[$option['name']])) {
1151 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1154 $backupsettings[$option['name']] = $value;
1158 // Capability checking.
1160 // The backup controller check for this currently, this may be redundant.
1161 require_capability('moodle/course:create', $categorycontext);
1162 require_capability('moodle/restore:restorecourse', $categorycontext);
1163 require_capability('moodle/backup:backupcourse', $coursecontext);
1165 if (!empty($backupsettings['users'])) {
1166 require_capability('moodle/backup:userinfo', $coursecontext);
1167 require_capability('moodle/restore:userinfo', $categorycontext);
1170 // Check if the shortname is used.
1171 if ($foundcourses = $DB->get_records('course', array('shortname'=>$shortname))) {
1172 foreach ($foundcourses as $foundcourse) {
1173 $foundcoursenames[] = $foundcourse->fullname;
1176 $foundcoursenamestring = implode(',', $foundcoursenames);
1177 throw new moodle_exception('shortnametaken', '', '', $foundcoursenamestring);
1180 // Backup the course.
1182 $bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE,
1183 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id);
1185 foreach ($backupsettings as $name => $value) {
1186 if ($setting = $bc->get_plan()->get_setting($name)) {
1187 $bc->get_plan()->get_setting($name)->set_value($value);
1191 $backupid = $bc->get_backupid();
1192 $backupbasepath = $bc->get_plan()->get_basepath();
1194 $bc->execute_plan();
1195 $results = $bc->get_results();
1196 $file = $results['backup_destination'];
1200 // Restore the backup immediately.
1202 // Check if we need to unzip the file because the backup temp dir does not contains backup files.
1203 if (!file_exists($backupbasepath . "/moodle_backup.xml")) {
1204 $file->extract_to_pathname(get_file_packer('application/vnd.moodle.backup'), $backupbasepath);
1207 // Create new course.
1208 $newcourseid = restore_dbops::create_new_course($params['fullname'], $params['shortname'], $params['categoryid']);
1210 $rc = new restore_controller($backupid, $newcourseid,
1211 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id, backup::TARGET_NEW_COURSE);
1213 foreach ($backupsettings as $name => $value) {
1214 $setting = $rc->get_plan()->get_setting($name);
1215 if ($setting->get_status() == backup_setting::NOT_LOCKED) {
1216 $setting->set_value($value);
1220 if (!$rc->execute_precheck()) {
1221 $precheckresults = $rc->get_precheck_results();
1222 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1223 if (empty($CFG->keeptempdirectoriesonbackup)) {
1224 fulldelete($backupbasepath);
1229 foreach ($precheckresults['errors'] as $error) {
1230 $errorinfo .= $error;
1233 if (array_key_exists('warnings', $precheckresults)) {
1234 foreach ($precheckresults['warnings'] as $warning) {
1235 $errorinfo .= $warning;
1239 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1243 $rc->execute_plan();
1246 $course = $DB->get_record('course', array('id' => $newcourseid), '*', MUST_EXIST);
1247 $course->fullname = $params['fullname'];
1248 $course->shortname = $params['shortname'];
1249 $course->visible = $params['visible'];
1251 // Set shortname and fullname back.
1252 $DB->update_record('course', $course);
1254 if (empty($CFG->keeptempdirectoriesonbackup)) {
1255 fulldelete($backupbasepath);
1258 // Delete the course backup file created by this WebService. Originally located in the course backups area.
1261 return array('id' => $course->id, 'shortname' => $course->shortname);
1265 * Returns description of method result value
1267 * @return external_description
1270 public static function duplicate_course_returns() {
1271 return new external_single_structure(
1273 'id' => new external_value(PARAM_INT, 'course id'),
1274 'shortname' => new external_value(PARAM_TEXT, 'short name'),
1280 * Returns description of method parameters for import_course
1282 * @return external_function_parameters
1285 public static function import_course_parameters() {
1286 return new external_function_parameters(
1288 'importfrom' => new external_value(PARAM_INT, 'the id of the course we are importing from'),
1289 'importto' => new external_value(PARAM_INT, 'the id of the course we are importing to'),
1290 'deletecontent' => new external_value(PARAM_INT, 'whether to delete the course content where we are importing to (default to 0 = No)', VALUE_DEFAULT, 0),
1291 'options' => new external_multiple_structure(
1292 new external_single_structure(
1294 'name' => new external_value(PARAM_ALPHA, 'The backup option name:
1295 "activities" (int) Include course activites (default to 1 that is equal to yes),
1296 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1297 "filters" (int) Include course filters (default to 1 that is equal to yes)'
1299 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1302 ), VALUE_DEFAULT, array()
1311 * @param int $importfrom The id of the course we are importing from
1312 * @param int $importto The id of the course we are importing to
1313 * @param bool $deletecontent Whether to delete the course we are importing to content
1314 * @param array $options List of backup options
1318 public static function import_course($importfrom, $importto, $deletecontent = 0, $options = array()) {
1319 global $CFG, $USER, $DB;
1320 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1321 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1323 // Parameter validation.
1324 $params = self::validate_parameters(
1325 self::import_course_parameters(),
1327 'importfrom' => $importfrom,
1328 'importto' => $importto,
1329 'deletecontent' => $deletecontent,
1330 'options' => $options
1334 if ($params['deletecontent'] !== 0 and $params['deletecontent'] !== 1) {
1335 throw new moodle_exception('invalidextparam', 'webservice', '', $params['deletecontent']);
1338 // Context validation.
1340 if (! ($importfrom = $DB->get_record('course', array('id'=>$params['importfrom'])))) {
1341 throw new moodle_exception('invalidcourseid', 'error');
1344 if (! ($importto = $DB->get_record('course', array('id'=>$params['importto'])))) {
1345 throw new moodle_exception('invalidcourseid', 'error');
1348 $importfromcontext = context_course::instance($importfrom->id);
1349 self::validate_context($importfromcontext);
1351 $importtocontext = context_course::instance($importto->id);
1352 self::validate_context($importtocontext);
1354 $backupdefaults = array(
1360 $backupsettings = array();
1362 // Check for backup and restore options.
1363 if (!empty($params['options'])) {
1364 foreach ($params['options'] as $option) {
1366 // Strict check for a correct value (allways 1 or 0, true or false).
1367 $value = clean_param($option['value'], PARAM_INT);
1369 if ($value !== 0 and $value !== 1) {
1370 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1373 if (!isset($backupdefaults[$option['name']])) {
1374 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1377 $backupsettings[$option['name']] = $value;
1381 // Capability checking.
1383 require_capability('moodle/backup:backuptargetimport', $importfromcontext);
1384 require_capability('moodle/restore:restoretargetimport', $importtocontext);
1386 $bc = new backup_controller(backup::TYPE_1COURSE, $importfrom->id, backup::FORMAT_MOODLE,
1387 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
1389 foreach ($backupsettings as $name => $value) {
1390 $bc->get_plan()->get_setting($name)->set_value($value);
1393 $backupid = $bc->get_backupid();
1394 $backupbasepath = $bc->get_plan()->get_basepath();
1396 $bc->execute_plan();
1399 // Restore the backup immediately.
1401 // Check if we must delete the contents of the destination course.
1402 if ($params['deletecontent']) {
1403 $restoretarget = backup::TARGET_EXISTING_DELETING;
1405 $restoretarget = backup::TARGET_EXISTING_ADDING;
1408 $rc = new restore_controller($backupid, $importto->id,
1409 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, $restoretarget);
1411 foreach ($backupsettings as $name => $value) {
1412 $rc->get_plan()->get_setting($name)->set_value($value);
1415 if (!$rc->execute_precheck()) {
1416 $precheckresults = $rc->get_precheck_results();
1417 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1418 if (empty($CFG->keeptempdirectoriesonbackup)) {
1419 fulldelete($backupbasepath);
1424 foreach ($precheckresults['errors'] as $error) {
1425 $errorinfo .= $error;
1428 if (array_key_exists('warnings', $precheckresults)) {
1429 foreach ($precheckresults['warnings'] as $warning) {
1430 $errorinfo .= $warning;
1434 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1437 if ($restoretarget == backup::TARGET_EXISTING_DELETING) {
1438 restore_dbops::delete_course_content($importto->id);
1442 $rc->execute_plan();
1445 if (empty($CFG->keeptempdirectoriesonbackup)) {
1446 fulldelete($backupbasepath);
1453 * Returns description of method result value
1455 * @return external_description
1458 public static function import_course_returns() {
1463 * Returns description of method parameters
1465 * @return external_function_parameters
1468 public static function get_categories_parameters() {
1469 return new external_function_parameters(
1471 'criteria' => new external_multiple_structure(
1472 new external_single_structure(
1474 'key' => new external_value(PARAM_ALPHA,
1475 'The category column to search, expected keys (value format) are:'.
1476 '"id" (int) the category id,'.
1477 '"ids" (string) category ids separated by commas,'.
1478 '"name" (string) the category name,'.
1479 '"parent" (int) the parent category id,'.
1480 '"idnumber" (string) category idnumber'.
1481 ' - user must have \'moodle/category:manage\' to search on idnumber,'.
1482 '"visible" (int) whether the returned categories must be visible or hidden. If the key is not passed,
1483 then the function return all categories that the user can see.'.
1484 ' - user must have \'moodle/category:manage\' or \'moodle/category:viewhiddencategories\' to search on visible,'.
1485 '"theme" (string) only return the categories having this theme'.
1486 ' - user must have \'moodle/category:manage\' to search on theme'),
1487 'value' => new external_value(PARAM_RAW, 'the value to match')
1489 ), 'criteria', VALUE_DEFAULT, array()
1491 'addsubcategories' => new external_value(PARAM_BOOL, 'return the sub categories infos
1492 (1 - default) otherwise only the category info (0)', VALUE_DEFAULT, 1)
1500 * @param array $criteria Criteria to match the results
1501 * @param booln $addsubcategories obtain only the category (false) or its subcategories (true - default)
1502 * @return array list of categories
1505 public static function get_categories($criteria = array(), $addsubcategories = true) {
1507 require_once($CFG->dirroot . "/course/lib.php");
1509 // Validate parameters.
1510 $params = self::validate_parameters(self::get_categories_parameters(),
1511 array('criteria' => $criteria, 'addsubcategories' => $addsubcategories));
1513 // Retrieve the categories.
1514 $categories = array();
1515 if (!empty($params['criteria'])) {
1517 $conditions = array();
1519 foreach ($params['criteria'] as $crit) {
1520 $key = trim($crit['key']);
1522 // Trying to avoid duplicate keys.
1523 if (!isset($conditions[$key])) {
1525 $context = context_system::instance();
1529 $value = clean_param($crit['value'], PARAM_INT);
1530 $conditions[$key] = $value;
1531 $wheres[] = $key . " = :" . $key;
1535 $value = clean_param($crit['value'], PARAM_SEQUENCE);
1536 $ids = explode(',', $value);
1537 list($sqlids, $paramids) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED);
1538 $conditions = array_merge($conditions, $paramids);
1539 $wheres[] = 'id ' . $sqlids;
1543 if (has_capability('moodle/category:manage', $context)) {
1544 $value = clean_param($crit['value'], PARAM_RAW);
1545 $conditions[$key] = $value;
1546 $wheres[] = $key . " = :" . $key;
1548 // We must throw an exception.
1549 // Otherwise the dev client would think no idnumber exists.
1550 throw new moodle_exception('criteriaerror',
1551 'webservice', '', null,
1552 'You don\'t have the permissions to search on the "idnumber" field.');
1557 $value = clean_param($crit['value'], PARAM_TEXT);
1558 $conditions[$key] = $value;
1559 $wheres[] = $key . " = :" . $key;
1563 $value = clean_param($crit['value'], PARAM_INT);
1564 $conditions[$key] = $value;
1565 $wheres[] = $key . " = :" . $key;
1569 if (has_capability('moodle/category:manage', $context)
1570 or has_capability('moodle/category:viewhiddencategories',
1571 context_system::instance())) {
1572 $value = clean_param($crit['value'], PARAM_INT);
1573 $conditions[$key] = $value;
1574 $wheres[] = $key . " = :" . $key;
1576 throw new moodle_exception('criteriaerror',
1577 'webservice', '', null,
1578 'You don\'t have the permissions to search on the "visible" field.');
1583 if (has_capability('moodle/category:manage', $context)) {
1584 $value = clean_param($crit['value'], PARAM_THEME);
1585 $conditions[$key] = $value;
1586 $wheres[] = $key . " = :" . $key;
1588 throw new moodle_exception('criteriaerror',
1589 'webservice', '', null,
1590 'You don\'t have the permissions to search on the "theme" field.');
1595 throw new moodle_exception('criteriaerror',
1596 'webservice', '', null,
1597 'You can not search on this criteria: ' . $key);
1602 if (!empty($wheres)) {
1603 $wheres = implode(" AND ", $wheres);
1605 $categories = $DB->get_records_select('course_categories', $wheres, $conditions);
1607 // Retrieve its sub subcategories (all levels).
1608 if ($categories and !empty($params['addsubcategories'])) {
1609 $newcategories = array();
1611 // Check if we required visible/theme checks.
1612 $additionalselect = '';
1613 $additionalparams = array();
1614 if (isset($conditions['visible'])) {
1615 $additionalselect .= ' AND visible = :visible';
1616 $additionalparams['visible'] = $conditions['visible'];
1618 if (isset($conditions['theme'])) {
1619 $additionalselect .= ' AND theme= :theme';
1620 $additionalparams['theme'] = $conditions['theme'];
1623 foreach ($categories as $category) {
1624 $sqlselect = $DB->sql_like('path', ':path') . $additionalselect;
1625 $sqlparams = array('path' => $category->path.'/%') + $additionalparams; // It will NOT include the specified category.
1626 $subcategories = $DB->get_records_select('course_categories', $sqlselect, $sqlparams);
1627 $newcategories = $newcategories + $subcategories; // Both arrays have integer as keys.
1629 $categories = $categories + $newcategories;
1634 // Retrieve all categories in the database.
1635 $categories = $DB->get_records('course_categories');
1638 // The not returned categories. key => category id, value => reason of exclusion.
1639 $excludedcats = array();
1641 // The returned categories.
1642 $categoriesinfo = array();
1644 // We need to sort the categories by path.
1645 // The parent cats need to be checked by the algo first.
1646 usort($categories, "core_course_external::compare_categories_by_path");
1648 foreach ($categories as $category) {
1650 // Check if the category is a child of an excluded category, if yes exclude it too (excluded => do not return).
1651 $parents = explode('/', $category->path);
1652 unset($parents[0]); // First key is always empty because path start with / => /1/2/4.
1653 foreach ($parents as $parentid) {
1654 // Note: when the parent exclusion was due to the context,
1655 // the sub category could still be returned.
1656 if (isset($excludedcats[$parentid]) and $excludedcats[$parentid] != 'context') {
1657 $excludedcats[$category->id] = 'parent';
1661 // Check the user can use the category context.
1662 $context = context_coursecat::instance($category->id);
1664 self::validate_context($context);
1665 } catch (Exception $e) {
1666 $excludedcats[$category->id] = 'context';
1668 // If it was the requested category then throw an exception.
1669 if (isset($params['categoryid']) && $category->id == $params['categoryid']) {
1670 $exceptionparam = new stdClass();
1671 $exceptionparam->message = $e->getMessage();
1672 $exceptionparam->catid = $category->id;
1673 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
1677 // Return the category information.
1678 if (!isset($excludedcats[$category->id])) {
1680 // Final check to see if the category is visible to the user.
1681 if ($category->visible
1682 or has_capability('moodle/category:viewhiddencategories', context_system::instance())
1683 or has_capability('moodle/category:manage', $context)) {
1685 $categoryinfo = array();
1686 $categoryinfo['id'] = $category->id;
1687 $categoryinfo['name'] = $category->name;
1688 list($categoryinfo['description'], $categoryinfo['descriptionformat']) =
1689 external_format_text($category->description, $category->descriptionformat,
1690 $context->id, 'coursecat', 'description', null);
1691 $categoryinfo['parent'] = $category->parent;
1692 $categoryinfo['sortorder'] = $category->sortorder;
1693 $categoryinfo['coursecount'] = $category->coursecount;
1694 $categoryinfo['depth'] = $category->depth;
1695 $categoryinfo['path'] = $category->path;
1697 // Some fields only returned for admin.
1698 if (has_capability('moodle/category:manage', $context)) {
1699 $categoryinfo['idnumber'] = $category->idnumber;
1700 $categoryinfo['visible'] = $category->visible;
1701 $categoryinfo['visibleold'] = $category->visibleold;
1702 $categoryinfo['timemodified'] = $category->timemodified;
1703 $categoryinfo['theme'] = $category->theme;
1706 $categoriesinfo[] = $categoryinfo;
1708 $excludedcats[$category->id] = 'visibility';
1713 // Sorting the resulting array so it looks a bit better for the client developer.
1714 usort($categoriesinfo, "core_course_external::compare_categories_by_sortorder");
1716 return $categoriesinfo;
1720 * Sort categories array by path
1721 * private function: only used by get_categories
1723 * @param array $category1
1724 * @param array $category2
1725 * @return int result of strcmp
1728 private static function compare_categories_by_path($category1, $category2) {
1729 return strcmp($category1->path, $category2->path);
1733 * Sort categories array by sortorder
1734 * private function: only used by get_categories
1736 * @param array $category1
1737 * @param array $category2
1738 * @return int result of strcmp
1741 private static function compare_categories_by_sortorder($category1, $category2) {
1742 return strcmp($category1['sortorder'], $category2['sortorder']);
1746 * Returns description of method result value
1748 * @return external_description
1751 public static function get_categories_returns() {
1752 return new external_multiple_structure(
1753 new external_single_structure(
1755 'id' => new external_value(PARAM_INT, 'category id'),
1756 'name' => new external_value(PARAM_TEXT, 'category name'),
1757 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1758 'description' => new external_value(PARAM_RAW, 'category description'),
1759 'descriptionformat' => new external_format_value('description'),
1760 'parent' => new external_value(PARAM_INT, 'parent category id'),
1761 'sortorder' => new external_value(PARAM_INT, 'category sorting order'),
1762 'coursecount' => new external_value(PARAM_INT, 'number of courses in this category'),
1763 'visible' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1764 'visibleold' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1765 'timemodified' => new external_value(PARAM_INT, 'timestamp', VALUE_OPTIONAL),
1766 'depth' => new external_value(PARAM_INT, 'category depth'),
1767 'path' => new external_value(PARAM_TEXT, 'category path'),
1768 'theme' => new external_value(PARAM_THEME, 'category theme', VALUE_OPTIONAL),
1769 ), 'List of categories'
1775 * Returns description of method parameters
1777 * @return external_function_parameters
1780 public static function create_categories_parameters() {
1781 return new external_function_parameters(
1783 'categories' => new external_multiple_structure(
1784 new external_single_structure(
1786 'name' => new external_value(PARAM_TEXT, 'new category name'),
1787 'parent' => new external_value(PARAM_INT,
1788 'the parent category id inside which the new category will be created
1789 - set to 0 for a root category',
1791 'idnumber' => new external_value(PARAM_RAW,
1792 'the new category idnumber', VALUE_OPTIONAL),
1793 'description' => new external_value(PARAM_RAW,
1794 'the new category description', VALUE_OPTIONAL),
1795 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
1796 'theme' => new external_value(PARAM_THEME,
1797 'the new category theme. This option must be enabled on moodle',
1809 * @param array $categories - see create_categories_parameters() for the array structure
1810 * @return array - see create_categories_returns() for the array structure
1813 public static function create_categories($categories) {
1815 require_once($CFG->libdir . "/coursecatlib.php");
1817 $params = self::validate_parameters(self::create_categories_parameters(),
1818 array('categories' => $categories));
1820 $transaction = $DB->start_delegated_transaction();
1822 $createdcategories = array();
1823 foreach ($params['categories'] as $category) {
1824 if ($category['parent']) {
1825 if (!$DB->record_exists('course_categories', array('id' => $category['parent']))) {
1826 throw new moodle_exception('unknowcategory');
1828 $context = context_coursecat::instance($category['parent']);
1830 $context = context_system::instance();
1832 self::validate_context($context);
1833 require_capability('moodle/category:manage', $context);
1835 // this will validate format and throw an exception if there are errors
1836 external_validate_format($category['descriptionformat']);
1838 $newcategory = coursecat::create($category);
1840 $createdcategories[] = array('id' => $newcategory->id, 'name' => $newcategory->name);
1843 $transaction->allow_commit();
1845 return $createdcategories;
1849 * Returns description of method parameters
1851 * @return external_function_parameters
1854 public static function create_categories_returns() {
1855 return new external_multiple_structure(
1856 new external_single_structure(
1858 'id' => new external_value(PARAM_INT, 'new category id'),
1859 'name' => new external_value(PARAM_TEXT, 'new category name'),
1866 * Returns description of method parameters
1868 * @return external_function_parameters
1871 public static function update_categories_parameters() {
1872 return new external_function_parameters(
1874 'categories' => new external_multiple_structure(
1875 new external_single_structure(
1877 'id' => new external_value(PARAM_INT, 'course id'),
1878 'name' => new external_value(PARAM_TEXT, 'category name', VALUE_OPTIONAL),
1879 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1880 'parent' => new external_value(PARAM_INT, 'parent category id', VALUE_OPTIONAL),
1881 'description' => new external_value(PARAM_RAW, 'category description', VALUE_OPTIONAL),
1882 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
1883 'theme' => new external_value(PARAM_THEME,
1884 'the category theme. This option must be enabled on moodle', VALUE_OPTIONAL),
1895 * @param array $categories The list of categories to update
1899 public static function update_categories($categories) {
1901 require_once($CFG->libdir . "/coursecatlib.php");
1903 // Validate parameters.
1904 $params = self::validate_parameters(self::update_categories_parameters(), array('categories' => $categories));
1906 $transaction = $DB->start_delegated_transaction();
1908 foreach ($params['categories'] as $cat) {
1909 $category = coursecat::get($cat['id']);
1911 $categorycontext = context_coursecat::instance($cat['id']);
1912 self::validate_context($categorycontext);
1913 require_capability('moodle/category:manage', $categorycontext);
1915 // this will throw an exception if descriptionformat is not valid
1916 external_validate_format($cat['descriptionformat']);
1918 $category->update($cat);
1921 $transaction->allow_commit();
1925 * Returns description of method result value
1927 * @return external_description
1930 public static function update_categories_returns() {
1935 * Returns description of method parameters
1937 * @return external_function_parameters
1940 public static function delete_categories_parameters() {
1941 return new external_function_parameters(
1943 'categories' => new external_multiple_structure(
1944 new external_single_structure(
1946 'id' => new external_value(PARAM_INT, 'category id to delete'),
1947 'newparent' => new external_value(PARAM_INT,
1948 'the parent category to move the contents to, if specified', VALUE_OPTIONAL),
1949 'recursive' => new external_value(PARAM_BOOL, '1: recursively delete all contents inside this
1950 category, 0 (default): move contents to newparent or current parent category (except if parent is root)', VALUE_DEFAULT, 0)
1961 * @param array $categories A list of category ids
1965 public static function delete_categories($categories) {
1967 require_once($CFG->dirroot . "/course/lib.php");
1968 require_once($CFG->libdir . "/coursecatlib.php");
1970 // Validate parameters.
1971 $params = self::validate_parameters(self::delete_categories_parameters(), array('categories' => $categories));
1973 $transaction = $DB->start_delegated_transaction();
1975 foreach ($params['categories'] as $category) {
1976 $deletecat = coursecat::get($category['id'], MUST_EXIST);
1977 $context = context_coursecat::instance($deletecat->id);
1978 require_capability('moodle/category:manage', $context);
1979 self::validate_context($context);
1980 self::validate_context(get_category_or_system_context($deletecat->parent));
1982 if ($category['recursive']) {
1983 // If recursive was specified, then we recursively delete the category's contents.
1984 if ($deletecat->can_delete_full()) {
1985 $deletecat->delete_full(false);
1987 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
1990 // In this situation, we don't delete the category's contents, we either move it to newparent or parent.
1991 // If the parent is the root, moving is not supported (because a course must always be inside a category).
1992 // We must move to an existing category.
1993 if (!empty($category['newparent'])) {
1994 $newparentcat = coursecat::get($category['newparent']);
1996 $newparentcat = coursecat::get($deletecat->parent);
1999 // This operation is not allowed. We must move contents to an existing category.
2000 if (!$newparentcat->id) {
2001 throw new moodle_exception('movecatcontentstoroot');
2004 self::validate_context(context_coursecat::instance($newparentcat->id));
2005 if ($deletecat->can_move_content_to($newparentcat->id)) {
2006 $deletecat->delete_move($newparentcat->id, false);
2008 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2013 $transaction->allow_commit();
2017 * Returns description of method parameters
2019 * @return external_function_parameters
2022 public static function delete_categories_returns() {
2027 * Describes the parameters for delete_modules.
2029 * @return external_function_parameters
2032 public static function delete_modules_parameters() {
2033 return new external_function_parameters (
2035 'cmids' => new external_multiple_structure(new external_value(PARAM_INT, 'course module ID',
2036 VALUE_REQUIRED, '', NULL_NOT_ALLOWED), 'Array of course module IDs'),
2042 * Deletes a list of provided module instances.
2044 * @param array $cmids the course module ids
2047 public static function delete_modules($cmids) {
2050 // Require course file containing the course delete module function.
2051 require_once($CFG->dirroot . "/course/lib.php");
2053 // Clean the parameters.
2054 $params = self::validate_parameters(self::delete_modules_parameters(), array('cmids' => $cmids));
2056 // Keep track of the course ids we have performed a capability check on to avoid repeating.
2057 $arrcourseschecked = array();
2059 foreach ($params['cmids'] as $cmid) {
2060 // Get the course module.
2061 $cm = $DB->get_record('course_modules', array('id' => $cmid), '*', MUST_EXIST);
2063 // Check if we have not yet confirmed they have permission in this course.
2064 if (!in_array($cm->course, $arrcourseschecked)) {
2065 // Ensure the current user has required permission in this course.
2066 $context = context_course::instance($cm->course);
2067 self::validate_context($context);
2068 // Add to the array.
2069 $arrcourseschecked[] = $cm->course;
2072 // Ensure they can delete this module.
2073 $modcontext = context_module::instance($cm->id);
2074 require_capability('moodle/course:manageactivities', $modcontext);
2076 // Delete the module.
2077 course_delete_module($cm->id);
2082 * Describes the delete_modules return value.
2084 * @return external_single_structure
2087 public static function delete_modules_returns() {
2092 * Returns description of method parameters
2094 * @return external_function_parameters
2097 public static function view_course_parameters() {
2098 return new external_function_parameters(
2100 'courseid' => new external_value(PARAM_INT, 'id of the course'),
2101 'sectionnumber' => new external_value(PARAM_INT, 'section number', VALUE_DEFAULT, 0)
2107 * Trigger the course viewed event.
2109 * @param int $courseid id of course
2110 * @param int $sectionnumber sectionnumber (0, 1, 2...)
2111 * @return array of warnings and status result
2113 * @throws moodle_exception
2115 public static function view_course($courseid, $sectionnumber = 0) {
2117 require_once($CFG->dirroot . "/course/lib.php");
2119 $params = self::validate_parameters(self::view_course_parameters(),
2121 'courseid' => $courseid,
2122 'sectionnumber' => $sectionnumber
2125 $warnings = array();
2127 $course = get_course($params['courseid']);
2128 $context = context_course::instance($course->id);
2129 self::validate_context($context);
2131 if (!empty($params['sectionnumber'])) {
2133 // Get section details and check it exists.
2134 $modinfo = get_fast_modinfo($course);
2135 $coursesection = $modinfo->get_section_info($params['sectionnumber'], MUST_EXIST);
2137 // Check user is allowed to see it.
2138 if (!$coursesection->uservisible) {
2139 require_capability('moodle/course:viewhiddensections', $context);
2143 course_view($context, $params['sectionnumber']);
2146 $result['status'] = true;
2147 $result['warnings'] = $warnings;
2152 * Returns description of method result value
2154 * @return external_description
2157 public static function view_course_returns() {
2158 return new external_single_structure(
2160 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
2161 'warnings' => new external_warnings()
2167 * Returns description of method parameters
2169 * @return external_function_parameters
2172 public static function search_courses_parameters() {
2173 return new external_function_parameters(
2175 'criterianame' => new external_value(PARAM_ALPHA, 'criteria name
2176 (search, modulelist (only admins), blocklist (only admins), tagid)'),
2177 'criteriavalue' => new external_value(PARAM_RAW, 'criteria value'),
2178 'page' => new external_value(PARAM_INT, 'page number (0 based)', VALUE_DEFAULT, 0),
2179 'perpage' => new external_value(PARAM_INT, 'items per page', VALUE_DEFAULT, 0),
2180 'requiredcapabilities' => new external_multiple_structure(
2181 new external_value(PARAM_CAPABILITY, 'Capability string used to filter courses by permission'),
2182 'Optional list of required capabilities (used to filter the list)', VALUE_DEFAULT, array()
2184 'limittoenrolled' => new external_value(PARAM_BOOL, 'limit to enrolled courses', VALUE_DEFAULT, 0),
2190 * Return the course information that is public (visible by every one)
2192 * @param course_in_list $course course in list object
2193 * @param stdClass $coursecontext course context object
2194 * @return array the course information
2197 protected static function get_course_public_information(course_in_list $course, $coursecontext) {
2199 static $categoriescache = array();
2201 // Category information.
2202 if (!array_key_exists($course->category, $categoriescache)) {
2203 $categoriescache[$course->category] = coursecat::get($course->category, IGNORE_MISSING);
2205 $category = $categoriescache[$course->category];
2207 // Retrieve course overview used files.
2209 foreach ($course->get_course_overviewfiles() as $file) {
2210 $fileurl = moodle_url::make_webservice_pluginfile_url($file->get_contextid(), $file->get_component(),
2211 $file->get_filearea(), null, $file->get_filepath(),
2212 $file->get_filename())->out(false);
2214 'filename' => $file->get_filename(),
2215 'fileurl' => $fileurl,
2216 'filesize' => $file->get_filesize(),
2217 'filepath' => $file->get_filepath(),
2218 'mimetype' => $file->get_mimetype(),
2219 'timemodified' => $file->get_timemodified(),
2223 // Retrieve the course contacts,
2224 // we need here the users fullname since if we are not enrolled can be difficult to obtain them via other Web Services.
2225 $coursecontacts = array();
2226 foreach ($course->get_course_contacts() as $contact) {
2227 $coursecontacts[] = array(
2228 'id' => $contact['user']->id,
2229 'fullname' => $contact['username']
2233 // Allowed enrolment methods (maybe we can self-enrol).
2234 $enroltypes = array();
2235 $instances = enrol_get_instances($course->id, true);
2236 foreach ($instances as $instance) {
2237 $enroltypes[] = $instance->enrol;
2241 list($summary, $summaryformat) =
2242 external_format_text($course->summary, $course->summaryformat, $coursecontext->id, 'course', 'summary', null);
2244 $displayname = get_course_display_name_for_list($course);
2245 $coursereturns = array();
2246 $coursereturns['id'] = $course->id;
2247 $coursereturns['fullname'] = external_format_string($course->fullname, $coursecontext->id);
2248 $coursereturns['displayname'] = external_format_string($displayname, $coursecontext->id);
2249 $coursereturns['shortname'] = external_format_string($course->shortname, $coursecontext->id);
2250 $coursereturns['categoryid'] = $course->category;
2251 $coursereturns['categoryname'] = $category == null ? '' : $category->name;
2252 $coursereturns['summary'] = $summary;
2253 $coursereturns['summaryformat'] = $summaryformat;
2254 $coursereturns['summaryfiles'] = external_util::get_area_files($coursecontext->id, 'course', 'summary', false, false);
2255 $coursereturns['overviewfiles'] = $files;
2256 $coursereturns['contacts'] = $coursecontacts;
2257 $coursereturns['enrollmentmethods'] = $enroltypes;
2258 $coursereturns['sortorder'] = $course->sortorder;
2259 return $coursereturns;
2263 * Search courses following the specified criteria.
2265 * @param string $criterianame Criteria name (search, modulelist (only admins), blocklist (only admins), tagid)
2266 * @param string $criteriavalue Criteria value
2267 * @param int $page Page number (for pagination)
2268 * @param int $perpage Items per page
2269 * @param array $requiredcapabilities Optional list of required capabilities (used to filter the list).
2270 * @param int $limittoenrolled Limit to only enrolled courses
2271 * @return array of course objects and warnings
2273 * @throws moodle_exception
2275 public static function search_courses($criterianame,
2279 $requiredcapabilities=array(),
2280 $limittoenrolled=0) {
2282 require_once($CFG->libdir . '/coursecatlib.php');
2284 $warnings = array();
2286 $parameters = array(
2287 'criterianame' => $criterianame,
2288 'criteriavalue' => $criteriavalue,
2290 'perpage' => $perpage,
2291 'requiredcapabilities' => $requiredcapabilities
2293 $params = self::validate_parameters(self::search_courses_parameters(), $parameters);
2294 self::validate_context(context_system::instance());
2296 $allowedcriterianames = array('search', 'modulelist', 'blocklist', 'tagid');
2297 if (!in_array($params['criterianame'], $allowedcriterianames)) {
2298 throw new invalid_parameter_exception('Invalid value for criterianame parameter (value: '.$params['criterianame'].'),' .
2299 'allowed values are: '.implode(',', $allowedcriterianames));
2302 if ($params['criterianame'] == 'modulelist' or $params['criterianame'] == 'blocklist') {
2303 require_capability('moodle/site:config', context_system::instance());
2307 'search' => PARAM_RAW,
2308 'modulelist' => PARAM_PLUGIN,
2309 'blocklist' => PARAM_INT,
2310 'tagid' => PARAM_INT
2312 $params['criteriavalue'] = clean_param($params['criteriavalue'], $paramtype[$params['criterianame']]);
2314 // Prepare the search API options.
2315 $searchcriteria = array();
2316 $searchcriteria[$params['criterianame']] = $params['criteriavalue'];
2319 if ($params['perpage'] != 0) {
2320 $offset = $params['page'] * $params['perpage'];
2321 $options = array('offset' => $offset, 'limit' => $params['perpage']);
2324 // Search the courses.
2325 $courses = coursecat::search_courses($searchcriteria, $options, $params['requiredcapabilities']);
2326 $totalcount = coursecat::search_courses_count($searchcriteria, $options, $params['requiredcapabilities']);
2328 if (!empty($limittoenrolled)) {
2329 // Get the courses where the current user has access.
2330 $enrolled = enrol_get_my_courses(array('id', 'cacherev'));
2333 $finalcourses = array();
2334 $categoriescache = array();
2336 foreach ($courses as $course) {
2337 if (!empty($limittoenrolled)) {
2338 // Filter out not enrolled courses.
2339 if (!isset($enrolled[$course->id])) {
2345 $coursecontext = context_course::instance($course->id);
2347 $finalcourses[] = self::get_course_public_information($course, $coursecontext);
2351 'total' => $totalcount,
2352 'courses' => $finalcourses,
2353 'warnings' => $warnings
2358 * Returns a course structure definition
2360 * @param boolean $onlypublicdata set to true, to retrieve only fields viewable by anyone when the course is visible
2361 * @return array the course structure
2364 protected static function get_course_structure($onlypublicdata = true) {
2365 $coursestructure = array(
2366 'id' => new external_value(PARAM_INT, 'course id'),
2367 'fullname' => new external_value(PARAM_TEXT, 'course full name'),
2368 'displayname' => new external_value(PARAM_TEXT, 'course display name'),
2369 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
2370 'categoryid' => new external_value(PARAM_INT, 'category id'),
2371 'categoryname' => new external_value(PARAM_TEXT, 'category name'),
2372 'sortorder' => new external_value(PARAM_INT, 'Sort order in the category', VALUE_OPTIONAL),
2373 'summary' => new external_value(PARAM_RAW, 'summary'),
2374 'summaryformat' => new external_format_value('summary'),
2375 'summaryfiles' => new external_files('summary files in the summary field', VALUE_OPTIONAL),
2376 'overviewfiles' => new external_files('additional overview files attached to this course'),
2377 'contacts' => new external_multiple_structure(
2378 new external_single_structure(
2380 'id' => new external_value(PARAM_INT, 'contact user id'),
2381 'fullname' => new external_value(PARAM_NOTAGS, 'contact user fullname'),
2386 'enrollmentmethods' => new external_multiple_structure(
2387 new external_value(PARAM_PLUGIN, 'enrollment method'),
2388 'enrollment methods list'
2392 if (!$onlypublicdata) {
2394 'idnumber' => new external_value(PARAM_RAW, 'Id number', VALUE_OPTIONAL),
2395 'format' => new external_value(PARAM_PLUGIN, 'Course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
2396 'showgrades' => new external_value(PARAM_INT, '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
2397 'newsitems' => new external_value(PARAM_INT, 'Number of recent items appearing on the course page', VALUE_OPTIONAL),
2398 'startdate' => new external_value(PARAM_INT, 'Timestamp when the course start', VALUE_OPTIONAL),
2399 'maxbytes' => new external_value(PARAM_INT, 'Largest size of file that can be uploaded into', VALUE_OPTIONAL),
2400 'showreports' => new external_value(PARAM_INT, 'Are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
2401 'visible' => new external_value(PARAM_INT, '1: available to student, 0:not available', VALUE_OPTIONAL),
2402 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
2403 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
2404 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
2405 'enablecompletion' => new external_value(PARAM_INT, 'Completion enabled? 1: yes 0: no', VALUE_OPTIONAL),
2406 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
2407 'lang' => new external_value(PARAM_SAFEDIR, 'Forced course language', VALUE_OPTIONAL),
2408 'theme' => new external_value(PARAM_PLUGIN, 'Fame of the forced theme', VALUE_OPTIONAL),
2409 'marker' => new external_value(PARAM_INT, 'Current course marker', VALUE_OPTIONAL),
2410 'legacyfiles' => new external_value(PARAM_INT, 'If legacy files are enabled', VALUE_OPTIONAL),
2411 'calendartype' => new external_value(PARAM_PLUGIN, 'Calendar type', VALUE_OPTIONAL),
2412 'timecreated' => new external_value(PARAM_INT, 'Time when the course was created', VALUE_OPTIONAL),
2413 'timemodified' => new external_value(PARAM_INT, 'Last time the course was updated', VALUE_OPTIONAL),
2414 'requested' => new external_value(PARAM_INT, 'If is a requested course', VALUE_OPTIONAL),
2415 'cacherev' => new external_value(PARAM_INT, 'Cache revision number', VALUE_OPTIONAL),
2416 'filters' => new external_multiple_structure(
2417 new external_single_structure(
2419 'filter' => new external_value(PARAM_PLUGIN, 'Filter plugin name'),
2420 'localstate' => new external_value(PARAM_INT, 'Filter state: 1 for on, -1 for off, 0 if inherit'),
2421 'inheritedstate' => new external_value(PARAM_INT, '1 or 0 to use when localstate is set to inherit'),
2424 'Course filters', VALUE_OPTIONAL
2427 $coursestructure = array_merge($coursestructure, $extra);
2429 return new external_single_structure($coursestructure);
2433 * Returns description of method result value
2435 * @return external_description
2438 public static function search_courses_returns() {
2439 return new external_single_structure(
2441 'total' => new external_value(PARAM_INT, 'total course count'),
2442 'courses' => new external_multiple_structure(self::get_course_structure(), 'course'),
2443 'warnings' => new external_warnings()
2449 * Returns description of method parameters
2451 * @return external_function_parameters
2454 public static function get_course_module_parameters() {
2455 return new external_function_parameters(
2457 'cmid' => new external_value(PARAM_INT, 'The course module id')
2463 * Return information about a course module.
2465 * @param int $cmid the course module id
2466 * @return array of warnings and the course module
2468 * @throws moodle_exception
2470 public static function get_course_module($cmid) {
2473 $params = self::validate_parameters(self::get_course_module_parameters(), array('cmid' => $cmid));
2474 $warnings = array();
2476 $cm = get_coursemodule_from_id(null, $params['cmid'], 0, true, MUST_EXIST);
2477 $context = context_module::instance($cm->id);
2478 self::validate_context($context);
2480 // If the user has permissions to manage the activity, return all the information.
2481 if (has_capability('moodle/course:manageactivities', $context)) {
2482 require_once($CFG->dirroot . '/course/modlib.php');
2483 require_once($CFG->libdir . '/gradelib.php');
2486 // Get the extra information: grade, advanced grading and outcomes data.
2487 $course = get_course($cm->course);
2488 list($newcm, $newcontext, $module, $extrainfo, $cw) = get_moduleinfo_data($cm, $course);
2490 $gradeinfo = array('grade', 'gradepass', 'gradecat');
2491 foreach ($gradeinfo as $gfield) {
2492 if (isset($extrainfo->{$gfield})) {
2493 $info->{$gfield} = $extrainfo->{$gfield};
2496 if (isset($extrainfo->grade) and $extrainfo->grade < 0) {
2497 $info->scale = $DB->get_field('scale', 'scale', array('id' => abs($extrainfo->grade)));
2499 // Advanced grading.
2500 if (isset($extrainfo->_advancedgradingdata)) {
2501 $info->advancedgrading = array();
2502 foreach ($extrainfo as $key => $val) {
2503 if (strpos($key, 'advancedgradingmethod_') === 0) {
2504 $info->advancedgrading[] = array(
2505 'area' => str_replace('advancedgradingmethod_', '', $key),
2512 foreach ($extrainfo as $key => $val) {
2513 if (strpos($key, 'outcome_') === 0) {
2514 if (!isset($info->outcomes)) {
2515 $info->outcomes = array();
2517 $id = str_replace('outcome_', '', $key);
2518 $outcome = grade_outcome::fetch(array('id' => $id));
2519 $scaleitems = $outcome->load_scale();
2520 $info->outcomes[] = array(
2522 'name' => external_format_string($outcome->get_name(), $context->id),
2523 'scale' => $scaleitems->scale
2528 // Return information is safe to show to any user.
2529 $info = new stdClass();
2530 $info->id = $cm->id;
2531 $info->course = $cm->course;
2532 $info->module = $cm->module;
2533 $info->modname = $cm->modname;
2534 $info->instance = $cm->instance;
2535 $info->section = $cm->section;
2536 $info->sectionnum = $cm->sectionnum;
2537 $info->groupmode = $cm->groupmode;
2538 $info->groupingid = $cm->groupingid;
2539 $info->completion = $cm->completion;
2542 $info->name = external_format_string($cm->name, $context->id);
2544 $result['cm'] = $info;
2545 $result['warnings'] = $warnings;
2550 * Returns description of method result value
2552 * @return external_description
2555 public static function get_course_module_returns() {
2556 return new external_single_structure(
2558 'cm' => new external_single_structure(
2560 'id' => new external_value(PARAM_INT, 'The course module id'),
2561 'course' => new external_value(PARAM_INT, 'The course id'),
2562 'module' => new external_value(PARAM_INT, 'The module type id'),
2563 'name' => new external_value(PARAM_RAW, 'The activity name'),
2564 'modname' => new external_value(PARAM_COMPONENT, 'The module component name (forum, assign, etc..)'),
2565 'instance' => new external_value(PARAM_INT, 'The activity instance id'),
2566 'section' => new external_value(PARAM_INT, 'The module section id'),
2567 'sectionnum' => new external_value(PARAM_INT, 'The module section number'),
2568 'groupmode' => new external_value(PARAM_INT, 'Group mode'),
2569 'groupingid' => new external_value(PARAM_INT, 'Grouping id'),
2570 'completion' => new external_value(PARAM_INT, 'If completion is enabled'),
2571 'idnumber' => new external_value(PARAM_RAW, 'Module id number', VALUE_OPTIONAL),
2572 'added' => new external_value(PARAM_INT, 'Time added', VALUE_OPTIONAL),
2573 'score' => new external_value(PARAM_INT, 'Score', VALUE_OPTIONAL),
2574 'indent' => new external_value(PARAM_INT, 'Indentation', VALUE_OPTIONAL),
2575 'visible' => new external_value(PARAM_INT, 'If visible', VALUE_OPTIONAL),
2576 'visibleoncoursepage' => new external_value(PARAM_INT, 'If visible on course page', VALUE_OPTIONAL),
2577 'visibleold' => new external_value(PARAM_INT, 'Visible old', VALUE_OPTIONAL),
2578 'completiongradeitemnumber' => new external_value(PARAM_INT, 'Completion grade item', VALUE_OPTIONAL),
2579 'completionview' => new external_value(PARAM_INT, 'Completion view setting', VALUE_OPTIONAL),
2580 'completionexpected' => new external_value(PARAM_INT, 'Completion time expected', VALUE_OPTIONAL),
2581 'showdescription' => new external_value(PARAM_INT, 'If the description is showed', VALUE_OPTIONAL),
2582 'availability' => new external_value(PARAM_RAW, 'Availability settings', VALUE_OPTIONAL),
2583 'grade' => new external_value(PARAM_INT, 'Grade (max value or scale id)', VALUE_OPTIONAL),
2584 'scale' => new external_value(PARAM_TEXT, 'Scale items (if used)', VALUE_OPTIONAL),
2585 'gradepass' => new external_value(PARAM_RAW, 'Grade to pass (float)', VALUE_OPTIONAL),
2586 'gradecat' => new external_value(PARAM_INT, 'Grade category', VALUE_OPTIONAL),
2587 'advancedgrading' => new external_multiple_structure(
2588 new external_single_structure(
2590 'area' => new external_value(PARAM_AREA, 'Gradable area name'),
2591 'method' => new external_value(PARAM_COMPONENT, 'Grading method'),
2594 'Advanced grading settings', VALUE_OPTIONAL
2596 'outcomes' => new external_multiple_structure(
2597 new external_single_structure(
2599 'id' => new external_value(PARAM_ALPHANUMEXT, 'Outcome id'),
2600 'name' => new external_value(PARAM_TEXT, 'Outcome full name'),
2601 'scale' => new external_value(PARAM_TEXT, 'Scale items')
2604 'Outcomes information', VALUE_OPTIONAL
2608 'warnings' => new external_warnings()
2614 * Returns description of method parameters
2616 * @return external_function_parameters
2619 public static function get_course_module_by_instance_parameters() {
2620 return new external_function_parameters(
2622 'module' => new external_value(PARAM_COMPONENT, 'The module name'),
2623 'instance' => new external_value(PARAM_INT, 'The module instance id')
2629 * Return information about a course module.
2631 * @param string $module the module name
2632 * @param int $instance the activity instance id
2633 * @return array of warnings and the course module
2635 * @throws moodle_exception
2637 public static function get_course_module_by_instance($module, $instance) {
2639 $params = self::validate_parameters(self::get_course_module_by_instance_parameters(),
2641 'module' => $module,
2642 'instance' => $instance,
2645 $warnings = array();
2646 $cm = get_coursemodule_from_instance($params['module'], $params['instance'], 0, false, MUST_EXIST);
2648 return self::get_course_module($cm->id);
2652 * Returns description of method result value
2654 * @return external_description
2657 public static function get_course_module_by_instance_returns() {
2658 return self::get_course_module_returns();
2662 * Returns description of method parameters
2664 * @deprecated since 3.3
2666 * @return external_function_parameters
2669 public static function get_activities_overview_parameters() {
2670 return new external_function_parameters(
2672 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2678 * Return activities overview for the given courses.
2680 * @deprecated since 3.3
2682 * @param array $courseids a list of course ids
2683 * @return array of warnings and the activities overview
2685 * @throws moodle_exception
2687 public static function get_activities_overview($courseids) {
2690 // Parameter validation.
2691 $params = self::validate_parameters(self::get_activities_overview_parameters(), array('courseids' => $courseids));
2692 $courseoverviews = array();
2694 list($courses, $warnings) = external_util::validate_courses($params['courseids']);
2696 if (!empty($courses)) {
2697 // Add lastaccess to each course (required by print_overview function).
2698 // We need the complete user data, the ws server does not load a complete one.
2699 $user = get_complete_user_data('id', $USER->id);
2700 foreach ($courses as $course) {
2701 if (isset($user->lastcourseaccess[$course->id])) {
2702 $course->lastaccess = $user->lastcourseaccess[$course->id];
2704 $course->lastaccess = 0;
2708 $overviews = array();
2709 if ($modules = get_plugin_list_with_function('mod', 'print_overview')) {
2710 foreach ($modules as $fname) {
2711 $fname($courses, $overviews);
2716 foreach ($overviews as $courseid => $modules) {
2717 $courseoverviews[$courseid]['id'] = $courseid;
2718 $courseoverviews[$courseid]['overviews'] = array();
2720 foreach ($modules as $modname => $overviewtext) {
2721 $courseoverviews[$courseid]['overviews'][] = array(
2722 'module' => $modname,
2723 'overviewtext' => $overviewtext // This text doesn't need formatting.
2730 'courses' => $courseoverviews,
2731 'warnings' => $warnings
2737 * Returns description of method result value
2739 * @deprecated since 3.3
2741 * @return external_description
2744 public static function get_activities_overview_returns() {
2745 return new external_single_structure(
2747 'courses' => new external_multiple_structure(
2748 new external_single_structure(
2750 'id' => new external_value(PARAM_INT, 'Course id'),
2751 'overviews' => new external_multiple_structure(
2752 new external_single_structure(
2754 'module' => new external_value(PARAM_PLUGIN, 'Module name'),
2755 'overviewtext' => new external_value(PARAM_RAW, 'Overview text'),
2760 ), 'List of courses'
2762 'warnings' => new external_warnings()
2768 * Marking the method as deprecated.
2772 public static function get_activities_overview_is_deprecated() {
2777 * Returns description of method parameters
2779 * @return external_function_parameters
2782 public static function get_user_navigation_options_parameters() {
2783 return new external_function_parameters(
2785 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2791 * Return a list of navigation options in a set of courses that are avaialable or not for the current user.
2793 * @param array $courseids a list of course ids
2794 * @return array of warnings and the options availability
2796 * @throws moodle_exception
2798 public static function get_user_navigation_options($courseids) {
2800 require_once($CFG->dirroot . '/course/lib.php');
2802 // Parameter validation.
2803 $params = self::validate_parameters(self::get_user_navigation_options_parameters(), array('courseids' => $courseids));
2804 $courseoptions = array();
2806 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
2808 if (!empty($courses)) {
2809 foreach ($courses as $course) {
2810 // Fix the context for the frontpage.
2811 if ($course->id == SITEID) {
2812 $course->context = context_system::instance();
2814 $navoptions = course_get_user_navigation_options($course->context, $course);
2816 foreach ($navoptions as $name => $available) {
2819 'available' => $available,
2823 $courseoptions[] = array(
2824 'id' => $course->id,
2825 'options' => $options
2831 'courses' => $courseoptions,
2832 'warnings' => $warnings
2838 * Returns description of method result value
2840 * @return external_description
2843 public static function get_user_navigation_options_returns() {
2844 return new external_single_structure(
2846 'courses' => new external_multiple_structure(
2847 new external_single_structure(
2849 'id' => new external_value(PARAM_INT, 'Course id'),
2850 'options' => new external_multiple_structure(
2851 new external_single_structure(
2853 'name' => new external_value(PARAM_ALPHANUMEXT, 'Option name'),
2854 'available' => new external_value(PARAM_BOOL, 'Whether the option is available or not'),
2859 ), 'List of courses'
2861 'warnings' => new external_warnings()
2867 * Returns description of method parameters
2869 * @return external_function_parameters
2872 public static function get_user_administration_options_parameters() {
2873 return new external_function_parameters(
2875 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2881 * Return a list of administration options in a set of courses that are available or not for the current user.
2883 * @param array $courseids a list of course ids
2884 * @return array of warnings and the options availability
2886 * @throws moodle_exception
2888 public static function get_user_administration_options($courseids) {
2890 require_once($CFG->dirroot . '/course/lib.php');
2892 // Parameter validation.
2893 $params = self::validate_parameters(self::get_user_administration_options_parameters(), array('courseids' => $courseids));
2894 $courseoptions = array();
2896 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
2898 if (!empty($courses)) {
2899 foreach ($courses as $course) {
2900 $adminoptions = course_get_user_administration_options($course, $course->context);
2902 foreach ($adminoptions as $name => $available) {
2905 'available' => $available,
2909 $courseoptions[] = array(
2910 'id' => $course->id,
2911 'options' => $options
2917 'courses' => $courseoptions,
2918 'warnings' => $warnings
2924 * Returns description of method result value
2926 * @return external_description
2929 public static function get_user_administration_options_returns() {
2930 return self::get_user_navigation_options_returns();
2934 * Returns description of method parameters
2936 * @return external_function_parameters
2939 public static function get_courses_by_field_parameters() {
2940 return new external_function_parameters(
2942 'field' => new external_value(PARAM_ALPHA, 'The field to search can be left empty for all courses or:
2944 ids: comma separated course ids
2945 shortname: course short name
2946 idnumber: course id number
2947 category: category id the course belongs to
2948 ', VALUE_DEFAULT, ''),
2949 'value' => new external_value(PARAM_RAW, 'The value to match', VALUE_DEFAULT, '')
2956 * Get courses matching a specific field (id/s, shortname, idnumber, category)
2958 * @param string $field field name to search, or empty for all courses
2959 * @param string $value value to search
2960 * @return array list of courses and warnings
2961 * @throws invalid_parameter_exception
2964 public static function get_courses_by_field($field = '', $value = '') {
2966 require_once($CFG->libdir . '/coursecatlib.php');
2967 require_once($CFG->libdir . '/filterlib.php');
2969 $params = self::validate_parameters(self::get_courses_by_field_parameters(),
2975 $warnings = array();
2977 if (empty($params['field'])) {
2978 $courses = $DB->get_records('course', null, 'id ASC');
2980 switch ($params['field']) {
2983 $value = clean_param($params['value'], PARAM_INT);
2986 $value = clean_param($params['value'], PARAM_SEQUENCE);
2989 $value = clean_param($params['value'], PARAM_TEXT);
2992 $value = clean_param($params['value'], PARAM_RAW);
2995 throw new invalid_parameter_exception('Invalid field name');
2998 if ($params['field'] === 'ids') {
2999 $courses = $DB->get_records_list('course', 'id', explode(',', $value), 'id ASC');
3001 $courses = $DB->get_records('course', array($params['field'] => $value), 'id ASC');
3005 $coursesdata = array();
3006 foreach ($courses as $course) {
3007 $context = context_course::instance($course->id);
3008 $canupdatecourse = has_capability('moodle/course:update', $context);
3009 $canviewhiddencourses = has_capability('moodle/course:viewhiddencourses', $context);
3011 // Check if the course is visible in the site for the user.
3012 if (!$course->visible and !$canviewhiddencourses and !$canupdatecourse) {
3015 // Get the public course information, even if we are not enrolled.
3016 $courseinlist = new course_in_list($course);
3017 $coursesdata[$course->id] = self::get_course_public_information($courseinlist, $context);
3019 // Now, check if we have access to the course.
3021 self::validate_context($context);
3022 } catch (Exception $e) {
3025 // Return information for any user that can access the course.
3026 $coursefields = array('format', 'showgrades', 'newsitems', 'startdate', 'maxbytes', 'showreports', 'visible',
3027 'groupmode', 'groupmodeforce', 'defaultgroupingid', 'enablecompletion', 'completionnotify', 'lang', 'theme',
3031 $coursesdata[$course->id]['filters'] = filter_get_available_in_context($context);
3033 // Information for managers only.
3034 if ($canupdatecourse) {
3035 $managerfields = array('idnumber', 'legacyfiles', 'calendartype', 'timecreated', 'timemodified', 'requested',
3037 $coursefields = array_merge($coursefields, $managerfields);
3041 foreach ($coursefields as $field) {
3042 $coursesdata[$course->id][$field] = $course->{$field};
3047 'courses' => $coursesdata,
3048 'warnings' => $warnings
3053 * Returns description of method result value
3055 * @return external_description
3058 public static function get_courses_by_field_returns() {
3059 // Course structure, including not only public viewable fields.
3060 return new external_single_structure(