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_course()->numsections
;
165 //for each sections (first displayed to last displayed)
166 $modinfosections = $modinfo->get_sections();
167 foreach ($sections as $key => $section) {
169 if (!$section->uservisible
) {
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'),
367 // copyright related info
368 'userid' => new external_value(PARAM_INT
, 'User who added this content to moodle'),
369 'author' => new external_value(PARAM_TEXT
, 'Content owner'),
370 'license' => new external_value(PARAM_TEXT
, 'Content license'),
372 ), VALUE_DEFAULT
, array()
383 * Returns description of method parameters
385 * @return external_function_parameters
388 public static function get_courses_parameters() {
389 return new external_function_parameters(
390 array('options' => new external_single_structure(
391 array('ids' => new external_multiple_structure(
392 new external_value(PARAM_INT
, 'Course id')
393 , 'List of course id. If empty return all courses
394 except front page course.',
396 ), 'options - operator OR is used', VALUE_DEFAULT
, array())
404 * @param array $options It contains an array (list of ids)
408 public static function get_courses($options = array()) {
410 require_once($CFG->dirroot
. "/course/lib.php");
413 $params = self
::validate_parameters(self
::get_courses_parameters(),
414 array('options' => $options));
417 if (!array_key_exists('ids', $params['options'])
418 or empty($params['options']['ids'])) {
419 $courses = $DB->get_records('course');
421 $courses = $DB->get_records_list('course', 'id', $params['options']['ids']);
424 //create return value
425 $coursesinfo = array();
426 foreach ($courses as $course) {
428 // now security checks
429 $context = context_course
::instance($course->id
, IGNORE_MISSING
);
430 $courseformatoptions = course_get_format($course)->get_format_options();
432 self
::validate_context($context);
433 } catch (Exception
$e) {
434 $exceptionparam = new stdClass();
435 $exceptionparam->message
= $e->getMessage();
436 $exceptionparam->courseid
= $course->id
;
437 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
439 require_capability('moodle/course:view', $context);
441 $courseinfo = array();
442 $courseinfo['id'] = $course->id
;
443 $courseinfo['fullname'] = external_format_string($course->fullname
, $context->id
);
444 $courseinfo['shortname'] = external_format_string($course->shortname
, $context->id
);
445 $courseinfo['displayname'] = external_format_string(get_course_display_name_for_list($course), $context->id
);
446 $courseinfo['categoryid'] = $course->category
;
447 list($courseinfo['summary'], $courseinfo['summaryformat']) =
448 external_format_text($course->summary
, $course->summaryformat
, $context->id
, 'course', 'summary', 0);
449 $courseinfo['format'] = $course->format
;
450 $courseinfo['startdate'] = $course->startdate
;
451 $courseinfo['enddate'] = $course->enddate
;
452 if (array_key_exists('numsections', $courseformatoptions)) {
453 // For backward-compartibility
454 $courseinfo['numsections'] = $courseformatoptions['numsections'];
457 //some field should be returned only if the user has update permission
458 $courseadmin = has_capability('moodle/course:update', $context);
460 $courseinfo['categorysortorder'] = $course->sortorder
;
461 $courseinfo['idnumber'] = $course->idnumber
;
462 $courseinfo['showgrades'] = $course->showgrades
;
463 $courseinfo['showreports'] = $course->showreports
;
464 $courseinfo['newsitems'] = $course->newsitems
;
465 $courseinfo['visible'] = $course->visible
;
466 $courseinfo['maxbytes'] = $course->maxbytes
;
467 if (array_key_exists('hiddensections', $courseformatoptions)) {
468 // For backward-compartibility
469 $courseinfo['hiddensections'] = $courseformatoptions['hiddensections'];
471 $courseinfo['groupmode'] = $course->groupmode
;
472 $courseinfo['groupmodeforce'] = $course->groupmodeforce
;
473 $courseinfo['defaultgroupingid'] = $course->defaultgroupingid
;
474 $courseinfo['lang'] = $course->lang
;
475 $courseinfo['timecreated'] = $course->timecreated
;
476 $courseinfo['timemodified'] = $course->timemodified
;
477 $courseinfo['forcetheme'] = $course->theme
;
478 $courseinfo['enablecompletion'] = $course->enablecompletion
;
479 $courseinfo['completionnotify'] = $course->completionnotify
;
480 $courseinfo['courseformatoptions'] = array();
481 foreach ($courseformatoptions as $key => $value) {
482 $courseinfo['courseformatoptions'][] = array(
489 if ($courseadmin or $course->visible
490 or has_capability('moodle/course:viewhiddencourses', $context)) {
491 $coursesinfo[] = $courseinfo;
499 * Returns description of method result value
501 * @return external_description
504 public static function get_courses_returns() {
505 return new external_multiple_structure(
506 new external_single_structure(
508 'id' => new external_value(PARAM_INT
, 'course id'),
509 'shortname' => new external_value(PARAM_TEXT
, 'course short name'),
510 'categoryid' => new external_value(PARAM_INT
, 'category id'),
511 'categorysortorder' => new external_value(PARAM_INT
,
512 'sort order into the category', VALUE_OPTIONAL
),
513 'fullname' => new external_value(PARAM_TEXT
, 'full name'),
514 'displayname' => new external_value(PARAM_TEXT
, 'course display name'),
515 'idnumber' => new external_value(PARAM_RAW
, 'id number', VALUE_OPTIONAL
),
516 'summary' => new external_value(PARAM_RAW
, 'summary'),
517 'summaryformat' => new external_format_value('summary'),
518 'format' => new external_value(PARAM_PLUGIN
,
519 'course format: weeks, topics, social, site,..'),
520 'showgrades' => new external_value(PARAM_INT
,
521 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL
),
522 'newsitems' => new external_value(PARAM_INT
,
523 'number of recent items appearing on the course page', VALUE_OPTIONAL
),
524 'startdate' => new external_value(PARAM_INT
,
525 'timestamp when the course start'),
526 'enddate' => new external_value(PARAM_INT
,
527 'timestamp when the course end'),
528 'numsections' => new external_value(PARAM_INT
,
529 '(deprecated, use courseformatoptions) number of weeks/topics',
531 'maxbytes' => new external_value(PARAM_INT
,
532 'largest size of file that can be uploaded into the course',
534 'showreports' => new external_value(PARAM_INT
,
535 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL
),
536 'visible' => new external_value(PARAM_INT
,
537 '1: available to student, 0:not available', VALUE_OPTIONAL
),
538 'hiddensections' => new external_value(PARAM_INT
,
539 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
541 'groupmode' => new external_value(PARAM_INT
, 'no group, separate, visible',
543 'groupmodeforce' => new external_value(PARAM_INT
, '1: yes, 0: no',
545 'defaultgroupingid' => new external_value(PARAM_INT
, 'default grouping id',
547 'timecreated' => new external_value(PARAM_INT
,
548 'timestamp when the course have been created', VALUE_OPTIONAL
),
549 'timemodified' => new external_value(PARAM_INT
,
550 'timestamp when the course have been modified', VALUE_OPTIONAL
),
551 'enablecompletion' => new external_value(PARAM_INT
,
552 'Enabled, control via completion and activity settings. Disbaled,
553 not shown in activity settings.',
555 'completionnotify' => new external_value(PARAM_INT
,
556 '1: yes 0: no', VALUE_OPTIONAL
),
557 'lang' => new external_value(PARAM_SAFEDIR
,
558 'forced course language', VALUE_OPTIONAL
),
559 'forcetheme' => new external_value(PARAM_PLUGIN
,
560 'name of the force theme', VALUE_OPTIONAL
),
561 'courseformatoptions' => new external_multiple_structure(
562 new external_single_structure(
563 array('name' => new external_value(PARAM_ALPHANUMEXT
, 'course format option name'),
564 'value' => new external_value(PARAM_RAW
, 'course format option value')
566 'additional options for particular course format', VALUE_OPTIONAL
574 * Returns description of method parameters
576 * @return external_function_parameters
579 public static function create_courses_parameters() {
580 $courseconfig = get_config('moodlecourse'); //needed for many default values
581 return new external_function_parameters(
583 'courses' => new external_multiple_structure(
584 new external_single_structure(
586 'fullname' => new external_value(PARAM_TEXT
, 'full name'),
587 'shortname' => new external_value(PARAM_TEXT
, 'course short name'),
588 'categoryid' => new external_value(PARAM_INT
, 'category id'),
589 'idnumber' => new external_value(PARAM_RAW
, 'id number', VALUE_OPTIONAL
),
590 'summary' => new external_value(PARAM_RAW
, 'summary', VALUE_OPTIONAL
),
591 'summaryformat' => new external_format_value('summary', VALUE_DEFAULT
),
592 'format' => new external_value(PARAM_PLUGIN
,
593 'course format: weeks, topics, social, site,..',
594 VALUE_DEFAULT
, $courseconfig->format
),
595 'showgrades' => new external_value(PARAM_INT
,
596 '1 if grades are shown, otherwise 0', VALUE_DEFAULT
,
597 $courseconfig->showgrades
),
598 'newsitems' => new external_value(PARAM_INT
,
599 'number of recent items appearing on the course page',
600 VALUE_DEFAULT
, $courseconfig->newsitems
),
601 'startdate' => new external_value(PARAM_INT
,
602 'timestamp when the course start', VALUE_OPTIONAL
),
603 'enddate' => new external_value(PARAM_INT
,
604 'timestamp when the course end', VALUE_OPTIONAL
),
605 'numsections' => new external_value(PARAM_INT
,
606 '(deprecated, use courseformatoptions) number of weeks/topics',
608 'maxbytes' => new external_value(PARAM_INT
,
609 'largest size of file that can be uploaded into the course',
610 VALUE_DEFAULT
, $courseconfig->maxbytes
),
611 'showreports' => new external_value(PARAM_INT
,
612 'are activity report shown (yes = 1, no =0)', VALUE_DEFAULT
,
613 $courseconfig->showreports
),
614 'visible' => new external_value(PARAM_INT
,
615 '1: available to student, 0:not available', VALUE_OPTIONAL
),
616 'hiddensections' => new external_value(PARAM_INT
,
617 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
619 'groupmode' => new external_value(PARAM_INT
, 'no group, separate, visible',
620 VALUE_DEFAULT
, $courseconfig->groupmode
),
621 'groupmodeforce' => new external_value(PARAM_INT
, '1: yes, 0: no',
622 VALUE_DEFAULT
, $courseconfig->groupmodeforce
),
623 'defaultgroupingid' => new external_value(PARAM_INT
, 'default grouping id',
625 'enablecompletion' => new external_value(PARAM_INT
,
626 'Enabled, control via completion and activity settings. Disabled,
627 not shown in activity settings.',
629 'completionnotify' => new external_value(PARAM_INT
,
630 '1: yes 0: no', VALUE_OPTIONAL
),
631 'lang' => new external_value(PARAM_SAFEDIR
,
632 'forced course language', VALUE_OPTIONAL
),
633 'forcetheme' => new external_value(PARAM_PLUGIN
,
634 'name of the force theme', VALUE_OPTIONAL
),
635 'courseformatoptions' => new external_multiple_structure(
636 new external_single_structure(
637 array('name' => new external_value(PARAM_ALPHANUMEXT
, 'course format option name'),
638 'value' => new external_value(PARAM_RAW
, 'course format option value')
640 'additional options for particular course format', VALUE_OPTIONAL
),
642 ), 'courses to create'
651 * @param array $courses
652 * @return array courses (id and shortname only)
655 public static function create_courses($courses) {
657 require_once($CFG->dirroot
. "/course/lib.php");
658 require_once($CFG->libdir
. '/completionlib.php');
660 $params = self
::validate_parameters(self
::create_courses_parameters(),
661 array('courses' => $courses));
663 $availablethemes = core_component
::get_plugin_list('theme');
664 $availablelangs = get_string_manager()->get_list_of_translations();
666 $transaction = $DB->start_delegated_transaction();
668 foreach ($params['courses'] as $course) {
670 // Ensure the current user is allowed to run this function
671 $context = context_coursecat
::instance($course['categoryid'], IGNORE_MISSING
);
673 self
::validate_context($context);
674 } catch (Exception
$e) {
675 $exceptionparam = new stdClass();
676 $exceptionparam->message
= $e->getMessage();
677 $exceptionparam->catid
= $course['categoryid'];
678 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
680 require_capability('moodle/course:create', $context);
682 // Make sure lang is valid
683 if (array_key_exists('lang', $course) and empty($availablelangs[$course['lang']])) {
684 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
687 // Make sure theme is valid
688 if (array_key_exists('forcetheme', $course)) {
689 if (!empty($CFG->allowcoursethemes
)) {
690 if (empty($availablethemes[$course['forcetheme']])) {
691 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
693 $course['theme'] = $course['forcetheme'];
698 //force visibility if ws user doesn't have the permission to set it
699 $category = $DB->get_record('course_categories', array('id' => $course['categoryid']));
700 if (!has_capability('moodle/course:visibility', $context)) {
701 $course['visible'] = $category->visible
;
704 //set default value for completion
705 $courseconfig = get_config('moodlecourse');
706 if (completion_info
::is_enabled_for_site()) {
707 if (!array_key_exists('enablecompletion', $course)) {
708 $course['enablecompletion'] = $courseconfig->enablecompletion
;
711 $course['enablecompletion'] = 0;
714 $course['category'] = $course['categoryid'];
717 $course['summaryformat'] = external_validate_format($course['summaryformat']);
719 if (!empty($course['courseformatoptions'])) {
720 foreach ($course['courseformatoptions'] as $option) {
721 $course[$option['name']] = $option['value'];
725 //Note: create_course() core function check shortname, idnumber, category
726 $course['id'] = create_course((object) $course)->id
;
728 $resultcourses[] = array('id' => $course['id'], 'shortname' => $course['shortname']);
731 $transaction->allow_commit();
733 return $resultcourses;
737 * Returns description of method result value
739 * @return external_description
742 public static function create_courses_returns() {
743 return new external_multiple_structure(
744 new external_single_structure(
746 'id' => new external_value(PARAM_INT
, 'course id'),
747 'shortname' => new external_value(PARAM_TEXT
, 'short name'),
756 * @return external_function_parameters
759 public static function update_courses_parameters() {
760 return new external_function_parameters(
762 'courses' => new external_multiple_structure(
763 new external_single_structure(
765 'id' => new external_value(PARAM_INT
, 'ID of the course'),
766 'fullname' => new external_value(PARAM_TEXT
, 'full name', VALUE_OPTIONAL
),
767 'shortname' => new external_value(PARAM_TEXT
, 'course short name', VALUE_OPTIONAL
),
768 'categoryid' => new external_value(PARAM_INT
, 'category id', VALUE_OPTIONAL
),
769 'idnumber' => new external_value(PARAM_RAW
, 'id number', VALUE_OPTIONAL
),
770 'summary' => new external_value(PARAM_RAW
, 'summary', VALUE_OPTIONAL
),
771 'summaryformat' => new external_format_value('summary', VALUE_OPTIONAL
),
772 'format' => new external_value(PARAM_PLUGIN
,
773 'course format: weeks, topics, social, site,..', VALUE_OPTIONAL
),
774 'showgrades' => new external_value(PARAM_INT
,
775 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL
),
776 'newsitems' => new external_value(PARAM_INT
,
777 'number of recent items appearing on the course page', VALUE_OPTIONAL
),
778 'startdate' => new external_value(PARAM_INT
,
779 'timestamp when the course start', VALUE_OPTIONAL
),
780 'enddate' => new external_value(PARAM_INT
,
781 'timestamp when the course end', VALUE_OPTIONAL
),
782 'numsections' => new external_value(PARAM_INT
,
783 '(deprecated, use courseformatoptions) number of weeks/topics', VALUE_OPTIONAL
),
784 'maxbytes' => new external_value(PARAM_INT
,
785 'largest size of file that can be uploaded into the course', VALUE_OPTIONAL
),
786 'showreports' => new external_value(PARAM_INT
,
787 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL
),
788 'visible' => new external_value(PARAM_INT
,
789 '1: available to student, 0:not available', VALUE_OPTIONAL
),
790 'hiddensections' => new external_value(PARAM_INT
,
791 '(deprecated, use courseformatoptions) How the hidden sections in the course are
792 displayed to students', VALUE_OPTIONAL
),
793 'groupmode' => new external_value(PARAM_INT
, 'no group, separate, visible', VALUE_OPTIONAL
),
794 'groupmodeforce' => new external_value(PARAM_INT
, '1: yes, 0: no', VALUE_OPTIONAL
),
795 'defaultgroupingid' => new external_value(PARAM_INT
, 'default grouping id', VALUE_OPTIONAL
),
796 'enablecompletion' => new external_value(PARAM_INT
,
797 'Enabled, control via completion and activity settings. Disabled,
798 not shown in activity settings.', VALUE_OPTIONAL
),
799 'completionnotify' => new external_value(PARAM_INT
, '1: yes 0: no', VALUE_OPTIONAL
),
800 'lang' => new external_value(PARAM_SAFEDIR
, 'forced course language', VALUE_OPTIONAL
),
801 'forcetheme' => new external_value(PARAM_PLUGIN
, 'name of the force theme', VALUE_OPTIONAL
),
802 'courseformatoptions' => new external_multiple_structure(
803 new external_single_structure(
804 array('name' => new external_value(PARAM_ALPHANUMEXT
, 'course format option name'),
805 'value' => new external_value(PARAM_RAW
, 'course format option value')
807 'additional options for particular course format', VALUE_OPTIONAL
),
809 ), 'courses to update'
818 * @param array $courses
821 public static function update_courses($courses) {
823 require_once($CFG->dirroot
. "/course/lib.php");
826 $params = self
::validate_parameters(self
::update_courses_parameters(),
827 array('courses' => $courses));
829 $availablethemes = core_component
::get_plugin_list('theme');
830 $availablelangs = get_string_manager()->get_list_of_translations();
832 foreach ($params['courses'] as $course) {
833 // Catch any exception while updating course and return as warning to user.
835 // Ensure the current user is allowed to run this function.
836 $context = context_course
::instance($course['id'], MUST_EXIST
);
837 self
::validate_context($context);
839 $oldcourse = course_get_format($course['id'])->get_course();
841 require_capability('moodle/course:update', $context);
843 // Check if user can change category.
844 if (array_key_exists('categoryid', $course) && ($oldcourse->category
!= $course['categoryid'])) {
845 require_capability('moodle/course:changecategory', $context);
846 $course['category'] = $course['categoryid'];
849 // Check if the user can change fullname.
850 if (array_key_exists('fullname', $course) && ($oldcourse->fullname
!= $course['fullname'])) {
851 require_capability('moodle/course:changefullname', $context);
854 // Check if the user can change shortname.
855 if (array_key_exists('shortname', $course) && ($oldcourse->shortname
!= $course['shortname'])) {
856 require_capability('moodle/course:changeshortname', $context);
859 // Check if the user can change the idnumber.
860 if (array_key_exists('idnumber', $course) && ($oldcourse->idnumber
!= $course['idnumber'])) {
861 require_capability('moodle/course:changeidnumber', $context);
864 // Check if user can change summary.
865 if (array_key_exists('summary', $course) && ($oldcourse->summary
!= $course['summary'])) {
866 require_capability('moodle/course:changesummary', $context);
870 if (array_key_exists('summaryformat', $course) && ($oldcourse->summaryformat
!= $course['summaryformat'])) {
871 require_capability('moodle/course:changesummary', $context);
872 $course['summaryformat'] = external_validate_format($course['summaryformat']);
875 // Check if user can change visibility.
876 if (array_key_exists('visible', $course) && ($oldcourse->visible
!= $course['visible'])) {
877 require_capability('moodle/course:visibility', $context);
880 // Make sure lang is valid.
881 if (array_key_exists('lang', $course) && empty($availablelangs[$course['lang']])) {
882 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
885 // Make sure theme is valid.
886 if (array_key_exists('forcetheme', $course)) {
887 if (!empty($CFG->allowcoursethemes
)) {
888 if (empty($availablethemes[$course['forcetheme']])) {
889 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
891 $course['theme'] = $course['forcetheme'];
896 // Make sure completion is enabled before setting it.
897 if (array_key_exists('enabledcompletion', $course) && !completion_info
::is_enabled_for_site()) {
898 $course['enabledcompletion'] = 0;
901 // Make sure maxbytes are less then CFG->maxbytes.
902 if (array_key_exists('maxbytes', $course)) {
903 $course['maxbytes'] = get_max_upload_file_size($CFG->maxbytes
, $course['maxbytes']);
906 if (!empty($course['courseformatoptions'])) {
907 foreach ($course['courseformatoptions'] as $option) {
908 if (isset($option['name']) && isset($option['value'])) {
909 $course[$option['name']] = $option['value'];
914 // Update course if user has all required capabilities.
915 update_course((object) $course);
916 } catch (Exception
$e) {
918 $warning['item'] = 'course';
919 $warning['itemid'] = $course['id'];
920 if ($e instanceof moodle_exception
) {
921 $warning['warningcode'] = $e->errorcode
;
923 $warning['warningcode'] = $e->getCode();
925 $warning['message'] = $e->getMessage();
926 $warnings[] = $warning;
931 $result['warnings'] = $warnings;
936 * Returns description of method result value
938 * @return external_description
941 public static function update_courses_returns() {
942 return new external_single_structure(
944 'warnings' => new external_warnings()
950 * Returns description of method parameters
952 * @return external_function_parameters
955 public static function delete_courses_parameters() {
956 return new external_function_parameters(
958 'courseids' => new external_multiple_structure(new external_value(PARAM_INT
, 'course ID')),
966 * @param array $courseids A list of course ids
969 public static function delete_courses($courseids) {
971 require_once($CFG->dirroot
."/course/lib.php");
973 // Parameter validation.
974 $params = self
::validate_parameters(self
::delete_courses_parameters(), array('courseids'=>$courseids));
978 foreach ($params['courseids'] as $courseid) {
979 $course = $DB->get_record('course', array('id' => $courseid));
981 if ($course === false) {
984 'itemid' => $courseid,
985 'warningcode' => 'unknowncourseidnumber',
986 'message' => 'Unknown course ID ' . $courseid
991 // Check if the context is valid.
992 $coursecontext = context_course
::instance($course->id
);
993 self
::validate_context($coursecontext);
995 // Check if the current user has permission.
996 if (!can_delete_course($courseid)) {
999 'itemid' => $courseid,
1000 'warningcode' => 'cannotdeletecourse',
1001 'message' => 'You do not have the permission to delete this course' . $courseid
1006 if (delete_course($course, false) === false) {
1007 $warnings[] = array(
1009 'itemid' => $courseid,
1010 'warningcode' => 'cannotdeletecategorycourse',
1011 'message' => 'Course ' . $courseid . ' failed to be deleted'
1017 fix_course_sortorder();
1019 return array('warnings' => $warnings);
1023 * Returns description of method result value
1025 * @return external_description
1028 public static function delete_courses_returns() {
1029 return new external_single_structure(
1031 'warnings' => new external_warnings()
1037 * Returns description of method parameters
1039 * @return external_function_parameters
1042 public static function duplicate_course_parameters() {
1043 return new external_function_parameters(
1045 'courseid' => new external_value(PARAM_INT
, 'course to duplicate id'),
1046 'fullname' => new external_value(PARAM_TEXT
, 'duplicated course full name'),
1047 'shortname' => new external_value(PARAM_TEXT
, 'duplicated course short name'),
1048 'categoryid' => new external_value(PARAM_INT
, 'duplicated course category parent'),
1049 'visible' => new external_value(PARAM_INT
, 'duplicated course visible, default to yes', VALUE_DEFAULT
, 1),
1050 'options' => new external_multiple_structure(
1051 new external_single_structure(
1053 'name' => new external_value(PARAM_ALPHAEXT
, 'The backup option name:
1054 "activities" (int) Include course activites (default to 1 that is equal to yes),
1055 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1056 "filters" (int) Include course filters (default to 1 that is equal to yes),
1057 "users" (int) Include users (default to 0 that is equal to no),
1058 "enrolments" (int) Include enrolment methods (default to 1 - restore only with users),
1059 "role_assignments" (int) Include role assignments (default to 0 that is equal to no),
1060 "comments" (int) Include user comments (default to 0 that is equal to no),
1061 "userscompletion" (int) Include user course completion information (default to 0 that is equal to no),
1062 "logs" (int) Include course logs (default to 0 that is equal to no),
1063 "grade_histories" (int) Include histories (default to 0 that is equal to no)'
1065 'value' => new external_value(PARAM_RAW
, 'the value for the option 1 (yes) or 0 (no)'
1068 ), VALUE_DEFAULT
, array()
1075 * Duplicate a course
1077 * @param int $courseid
1078 * @param string $fullname Duplicated course fullname
1079 * @param string $shortname Duplicated course shortname
1080 * @param int $categoryid Duplicated course parent category id
1081 * @param int $visible Duplicated course availability
1082 * @param array $options List of backup options
1083 * @return array New course info
1086 public static function duplicate_course($courseid, $fullname, $shortname, $categoryid, $visible = 1, $options = array()) {
1087 global $CFG, $USER, $DB;
1088 require_once($CFG->dirroot
. '/backup/util/includes/backup_includes.php');
1089 require_once($CFG->dirroot
. '/backup/util/includes/restore_includes.php');
1091 // Parameter validation.
1092 $params = self
::validate_parameters(
1093 self
::duplicate_course_parameters(),
1095 'courseid' => $courseid,
1096 'fullname' => $fullname,
1097 'shortname' => $shortname,
1098 'categoryid' => $categoryid,
1099 'visible' => $visible,
1100 'options' => $options
1104 // Context validation.
1106 if (! ($course = $DB->get_record('course', array('id'=>$params['courseid'])))) {
1107 throw new moodle_exception('invalidcourseid', 'error');
1110 // Category where duplicated course is going to be created.
1111 $categorycontext = context_coursecat
::instance($params['categoryid']);
1112 self
::validate_context($categorycontext);
1114 // Course to be duplicated.
1115 $coursecontext = context_course
::instance($course->id
);
1116 self
::validate_context($coursecontext);
1118 $backupdefaults = array(
1123 'enrolments' => backup
::ENROL_WITHUSERS
,
1124 'role_assignments' => 0,
1126 'userscompletion' => 0,
1128 'grade_histories' => 0
1131 $backupsettings = array();
1132 // Check for backup and restore options.
1133 if (!empty($params['options'])) {
1134 foreach ($params['options'] as $option) {
1136 // Strict check for a correct value (allways 1 or 0, true or false).
1137 $value = clean_param($option['value'], PARAM_INT
);
1139 if ($value !== 0 and $value !== 1) {
1140 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1143 if (!isset($backupdefaults[$option['name']])) {
1144 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1147 $backupsettings[$option['name']] = $value;
1151 // Capability checking.
1153 // The backup controller check for this currently, this may be redundant.
1154 require_capability('moodle/course:create', $categorycontext);
1155 require_capability('moodle/restore:restorecourse', $categorycontext);
1156 require_capability('moodle/backup:backupcourse', $coursecontext);
1158 if (!empty($backupsettings['users'])) {
1159 require_capability('moodle/backup:userinfo', $coursecontext);
1160 require_capability('moodle/restore:userinfo', $categorycontext);
1163 // Check if the shortname is used.
1164 if ($foundcourses = $DB->get_records('course', array('shortname'=>$shortname))) {
1165 foreach ($foundcourses as $foundcourse) {
1166 $foundcoursenames[] = $foundcourse->fullname
;
1169 $foundcoursenamestring = implode(',', $foundcoursenames);
1170 throw new moodle_exception('shortnametaken', '', '', $foundcoursenamestring);
1173 // Backup the course.
1175 $bc = new backup_controller(backup
::TYPE_1COURSE
, $course->id
, backup
::FORMAT_MOODLE
,
1176 backup
::INTERACTIVE_NO
, backup
::MODE_SAMESITE
, $USER->id
);
1178 foreach ($backupsettings as $name => $value) {
1179 if ($setting = $bc->get_plan()->get_setting($name)) {
1180 $bc->get_plan()->get_setting($name)->set_value($value);
1184 $backupid = $bc->get_backupid();
1185 $backupbasepath = $bc->get_plan()->get_basepath();
1187 $bc->execute_plan();
1188 $results = $bc->get_results();
1189 $file = $results['backup_destination'];
1193 // Restore the backup immediately.
1195 // Check if we need to unzip the file because the backup temp dir does not contains backup files.
1196 if (!file_exists($backupbasepath . "/moodle_backup.xml")) {
1197 $file->extract_to_pathname(get_file_packer('application/vnd.moodle.backup'), $backupbasepath);
1200 // Create new course.
1201 $newcourseid = restore_dbops
::create_new_course($params['fullname'], $params['shortname'], $params['categoryid']);
1203 $rc = new restore_controller($backupid, $newcourseid,
1204 backup
::INTERACTIVE_NO
, backup
::MODE_SAMESITE
, $USER->id
, backup
::TARGET_NEW_COURSE
);
1206 foreach ($backupsettings as $name => $value) {
1207 $setting = $rc->get_plan()->get_setting($name);
1208 if ($setting->get_status() == backup_setting
::NOT_LOCKED
) {
1209 $setting->set_value($value);
1213 if (!$rc->execute_precheck()) {
1214 $precheckresults = $rc->get_precheck_results();
1215 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1216 if (empty($CFG->keeptempdirectoriesonbackup
)) {
1217 fulldelete($backupbasepath);
1222 foreach ($precheckresults['errors'] as $error) {
1223 $errorinfo .= $error;
1226 if (array_key_exists('warnings', $precheckresults)) {
1227 foreach ($precheckresults['warnings'] as $warning) {
1228 $errorinfo .= $warning;
1232 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1236 $rc->execute_plan();
1239 $course = $DB->get_record('course', array('id' => $newcourseid), '*', MUST_EXIST
);
1240 $course->fullname
= $params['fullname'];
1241 $course->shortname
= $params['shortname'];
1242 $course->visible
= $params['visible'];
1244 // Set shortname and fullname back.
1245 $DB->update_record('course', $course);
1247 if (empty($CFG->keeptempdirectoriesonbackup
)) {
1248 fulldelete($backupbasepath);
1251 // Delete the course backup file created by this WebService. Originally located in the course backups area.
1254 return array('id' => $course->id
, 'shortname' => $course->shortname
);
1258 * Returns description of method result value
1260 * @return external_description
1263 public static function duplicate_course_returns() {
1264 return new external_single_structure(
1266 'id' => new external_value(PARAM_INT
, 'course id'),
1267 'shortname' => new external_value(PARAM_TEXT
, 'short name'),
1273 * Returns description of method parameters for import_course
1275 * @return external_function_parameters
1278 public static function import_course_parameters() {
1279 return new external_function_parameters(
1281 'importfrom' => new external_value(PARAM_INT
, 'the id of the course we are importing from'),
1282 'importto' => new external_value(PARAM_INT
, 'the id of the course we are importing to'),
1283 'deletecontent' => new external_value(PARAM_INT
, 'whether to delete the course content where we are importing to (default to 0 = No)', VALUE_DEFAULT
, 0),
1284 'options' => new external_multiple_structure(
1285 new external_single_structure(
1287 'name' => new external_value(PARAM_ALPHA
, 'The backup option name:
1288 "activities" (int) Include course activites (default to 1 that is equal to yes),
1289 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1290 "filters" (int) Include course filters (default to 1 that is equal to yes)'
1292 'value' => new external_value(PARAM_RAW
, 'the value for the option 1 (yes) or 0 (no)'
1295 ), VALUE_DEFAULT
, array()
1304 * @param int $importfrom The id of the course we are importing from
1305 * @param int $importto The id of the course we are importing to
1306 * @param bool $deletecontent Whether to delete the course we are importing to content
1307 * @param array $options List of backup options
1311 public static function import_course($importfrom, $importto, $deletecontent = 0, $options = array()) {
1312 global $CFG, $USER, $DB;
1313 require_once($CFG->dirroot
. '/backup/util/includes/backup_includes.php');
1314 require_once($CFG->dirroot
. '/backup/util/includes/restore_includes.php');
1316 // Parameter validation.
1317 $params = self
::validate_parameters(
1318 self
::import_course_parameters(),
1320 'importfrom' => $importfrom,
1321 'importto' => $importto,
1322 'deletecontent' => $deletecontent,
1323 'options' => $options
1327 if ($params['deletecontent'] !== 0 and $params['deletecontent'] !== 1) {
1328 throw new moodle_exception('invalidextparam', 'webservice', '', $params['deletecontent']);
1331 // Context validation.
1333 if (! ($importfrom = $DB->get_record('course', array('id'=>$params['importfrom'])))) {
1334 throw new moodle_exception('invalidcourseid', 'error');
1337 if (! ($importto = $DB->get_record('course', array('id'=>$params['importto'])))) {
1338 throw new moodle_exception('invalidcourseid', 'error');
1341 $importfromcontext = context_course
::instance($importfrom->id
);
1342 self
::validate_context($importfromcontext);
1344 $importtocontext = context_course
::instance($importto->id
);
1345 self
::validate_context($importtocontext);
1347 $backupdefaults = array(
1353 $backupsettings = array();
1355 // Check for backup and restore options.
1356 if (!empty($params['options'])) {
1357 foreach ($params['options'] as $option) {
1359 // Strict check for a correct value (allways 1 or 0, true or false).
1360 $value = clean_param($option['value'], PARAM_INT
);
1362 if ($value !== 0 and $value !== 1) {
1363 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1366 if (!isset($backupdefaults[$option['name']])) {
1367 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1370 $backupsettings[$option['name']] = $value;
1374 // Capability checking.
1376 require_capability('moodle/backup:backuptargetimport', $importfromcontext);
1377 require_capability('moodle/restore:restoretargetimport', $importtocontext);
1379 $bc = new backup_controller(backup
::TYPE_1COURSE
, $importfrom->id
, backup
::FORMAT_MOODLE
,
1380 backup
::INTERACTIVE_NO
, backup
::MODE_IMPORT
, $USER->id
);
1382 foreach ($backupsettings as $name => $value) {
1383 $bc->get_plan()->get_setting($name)->set_value($value);
1386 $backupid = $bc->get_backupid();
1387 $backupbasepath = $bc->get_plan()->get_basepath();
1389 $bc->execute_plan();
1392 // Restore the backup immediately.
1394 // Check if we must delete the contents of the destination course.
1395 if ($params['deletecontent']) {
1396 $restoretarget = backup
::TARGET_EXISTING_DELETING
;
1398 $restoretarget = backup
::TARGET_EXISTING_ADDING
;
1401 $rc = new restore_controller($backupid, $importto->id
,
1402 backup
::INTERACTIVE_NO
, backup
::MODE_IMPORT
, $USER->id
, $restoretarget);
1404 foreach ($backupsettings as $name => $value) {
1405 $rc->get_plan()->get_setting($name)->set_value($value);
1408 if (!$rc->execute_precheck()) {
1409 $precheckresults = $rc->get_precheck_results();
1410 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1411 if (empty($CFG->keeptempdirectoriesonbackup
)) {
1412 fulldelete($backupbasepath);
1417 foreach ($precheckresults['errors'] as $error) {
1418 $errorinfo .= $error;
1421 if (array_key_exists('warnings', $precheckresults)) {
1422 foreach ($precheckresults['warnings'] as $warning) {
1423 $errorinfo .= $warning;
1427 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1430 if ($restoretarget == backup
::TARGET_EXISTING_DELETING
) {
1431 restore_dbops
::delete_course_content($importto->id
);
1435 $rc->execute_plan();
1438 if (empty($CFG->keeptempdirectoriesonbackup
)) {
1439 fulldelete($backupbasepath);
1446 * Returns description of method result value
1448 * @return external_description
1451 public static function import_course_returns() {
1456 * Returns description of method parameters
1458 * @return external_function_parameters
1461 public static function get_categories_parameters() {
1462 return new external_function_parameters(
1464 'criteria' => new external_multiple_structure(
1465 new external_single_structure(
1467 'key' => new external_value(PARAM_ALPHA
,
1468 'The category column to search, expected keys (value format) are:'.
1469 '"id" (int) the category id,'.
1470 '"ids" (string) category ids separated by commas,'.
1471 '"name" (string) the category name,'.
1472 '"parent" (int) the parent category id,'.
1473 '"idnumber" (string) category idnumber'.
1474 ' - user must have \'moodle/category:manage\' to search on idnumber,'.
1475 '"visible" (int) whether the returned categories must be visible or hidden. If the key is not passed,
1476 then the function return all categories that the user can see.'.
1477 ' - user must have \'moodle/category:manage\' or \'moodle/category:viewhiddencategories\' to search on visible,'.
1478 '"theme" (string) only return the categories having this theme'.
1479 ' - user must have \'moodle/category:manage\' to search on theme'),
1480 'value' => new external_value(PARAM_RAW
, 'the value to match')
1482 ), 'criteria', VALUE_DEFAULT
, array()
1484 'addsubcategories' => new external_value(PARAM_BOOL
, 'return the sub categories infos
1485 (1 - default) otherwise only the category info (0)', VALUE_DEFAULT
, 1)
1493 * @param array $criteria Criteria to match the results
1494 * @param booln $addsubcategories obtain only the category (false) or its subcategories (true - default)
1495 * @return array list of categories
1498 public static function get_categories($criteria = array(), $addsubcategories = true) {
1500 require_once($CFG->dirroot
. "/course/lib.php");
1502 // Validate parameters.
1503 $params = self
::validate_parameters(self
::get_categories_parameters(),
1504 array('criteria' => $criteria, 'addsubcategories' => $addsubcategories));
1506 // Retrieve the categories.
1507 $categories = array();
1508 if (!empty($params['criteria'])) {
1510 $conditions = array();
1512 foreach ($params['criteria'] as $crit) {
1513 $key = trim($crit['key']);
1515 // Trying to avoid duplicate keys.
1516 if (!isset($conditions[$key])) {
1518 $context = context_system
::instance();
1522 $value = clean_param($crit['value'], PARAM_INT
);
1523 $conditions[$key] = $value;
1524 $wheres[] = $key . " = :" . $key;
1528 $value = clean_param($crit['value'], PARAM_SEQUENCE
);
1529 $ids = explode(',', $value);
1530 list($sqlids, $paramids) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED
);
1531 $conditions = array_merge($conditions, $paramids);
1532 $wheres[] = 'id ' . $sqlids;
1536 if (has_capability('moodle/category:manage', $context)) {
1537 $value = clean_param($crit['value'], PARAM_RAW
);
1538 $conditions[$key] = $value;
1539 $wheres[] = $key . " = :" . $key;
1541 // We must throw an exception.
1542 // Otherwise the dev client would think no idnumber exists.
1543 throw new moodle_exception('criteriaerror',
1544 'webservice', '', null,
1545 'You don\'t have the permissions to search on the "idnumber" field.');
1550 $value = clean_param($crit['value'], PARAM_TEXT
);
1551 $conditions[$key] = $value;
1552 $wheres[] = $key . " = :" . $key;
1556 $value = clean_param($crit['value'], PARAM_INT
);
1557 $conditions[$key] = $value;
1558 $wheres[] = $key . " = :" . $key;
1562 if (has_capability('moodle/category:manage', $context)
1563 or has_capability('moodle/category:viewhiddencategories',
1564 context_system
::instance())) {
1565 $value = clean_param($crit['value'], PARAM_INT
);
1566 $conditions[$key] = $value;
1567 $wheres[] = $key . " = :" . $key;
1569 throw new moodle_exception('criteriaerror',
1570 'webservice', '', null,
1571 'You don\'t have the permissions to search on the "visible" field.');
1576 if (has_capability('moodle/category:manage', $context)) {
1577 $value = clean_param($crit['value'], PARAM_THEME
);
1578 $conditions[$key] = $value;
1579 $wheres[] = $key . " = :" . $key;
1581 throw new moodle_exception('criteriaerror',
1582 'webservice', '', null,
1583 'You don\'t have the permissions to search on the "theme" field.');
1588 throw new moodle_exception('criteriaerror',
1589 'webservice', '', null,
1590 'You can not search on this criteria: ' . $key);
1595 if (!empty($wheres)) {
1596 $wheres = implode(" AND ", $wheres);
1598 $categories = $DB->get_records_select('course_categories', $wheres, $conditions);
1600 // Retrieve its sub subcategories (all levels).
1601 if ($categories and !empty($params['addsubcategories'])) {
1602 $newcategories = array();
1604 // Check if we required visible/theme checks.
1605 $additionalselect = '';
1606 $additionalparams = array();
1607 if (isset($conditions['visible'])) {
1608 $additionalselect .= ' AND visible = :visible';
1609 $additionalparams['visible'] = $conditions['visible'];
1611 if (isset($conditions['theme'])) {
1612 $additionalselect .= ' AND theme= :theme';
1613 $additionalparams['theme'] = $conditions['theme'];
1616 foreach ($categories as $category) {
1617 $sqlselect = $DB->sql_like('path', ':path') . $additionalselect;
1618 $sqlparams = array('path' => $category->path
.'/%') +
$additionalparams; // It will NOT include the specified category.
1619 $subcategories = $DB->get_records_select('course_categories', $sqlselect, $sqlparams);
1620 $newcategories = $newcategories +
$subcategories; // Both arrays have integer as keys.
1622 $categories = $categories +
$newcategories;
1627 // Retrieve all categories in the database.
1628 $categories = $DB->get_records('course_categories');
1631 // The not returned categories. key => category id, value => reason of exclusion.
1632 $excludedcats = array();
1634 // The returned categories.
1635 $categoriesinfo = array();
1637 // We need to sort the categories by path.
1638 // The parent cats need to be checked by the algo first.
1639 usort($categories, "core_course_external::compare_categories_by_path");
1641 foreach ($categories as $category) {
1643 // Check if the category is a child of an excluded category, if yes exclude it too (excluded => do not return).
1644 $parents = explode('/', $category->path
);
1645 unset($parents[0]); // First key is always empty because path start with / => /1/2/4.
1646 foreach ($parents as $parentid) {
1647 // Note: when the parent exclusion was due to the context,
1648 // the sub category could still be returned.
1649 if (isset($excludedcats[$parentid]) and $excludedcats[$parentid] != 'context') {
1650 $excludedcats[$category->id
] = 'parent';
1654 // Check the user can use the category context.
1655 $context = context_coursecat
::instance($category->id
);
1657 self
::validate_context($context);
1658 } catch (Exception
$e) {
1659 $excludedcats[$category->id
] = 'context';
1661 // If it was the requested category then throw an exception.
1662 if (isset($params['categoryid']) && $category->id
== $params['categoryid']) {
1663 $exceptionparam = new stdClass();
1664 $exceptionparam->message
= $e->getMessage();
1665 $exceptionparam->catid
= $category->id
;
1666 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
1670 // Return the category information.
1671 if (!isset($excludedcats[$category->id
])) {
1673 // Final check to see if the category is visible to the user.
1674 if ($category->visible
1675 or has_capability('moodle/category:viewhiddencategories', context_system
::instance())
1676 or has_capability('moodle/category:manage', $context)) {
1678 $categoryinfo = array();
1679 $categoryinfo['id'] = $category->id
;
1680 $categoryinfo['name'] = $category->name
;
1681 list($categoryinfo['description'], $categoryinfo['descriptionformat']) =
1682 external_format_text($category->description
, $category->descriptionformat
,
1683 $context->id
, 'coursecat', 'description', null);
1684 $categoryinfo['parent'] = $category->parent
;
1685 $categoryinfo['sortorder'] = $category->sortorder
;
1686 $categoryinfo['coursecount'] = $category->coursecount
;
1687 $categoryinfo['depth'] = $category->depth
;
1688 $categoryinfo['path'] = $category->path
;
1690 // Some fields only returned for admin.
1691 if (has_capability('moodle/category:manage', $context)) {
1692 $categoryinfo['idnumber'] = $category->idnumber
;
1693 $categoryinfo['visible'] = $category->visible
;
1694 $categoryinfo['visibleold'] = $category->visibleold
;
1695 $categoryinfo['timemodified'] = $category->timemodified
;
1696 $categoryinfo['theme'] = $category->theme
;
1699 $categoriesinfo[] = $categoryinfo;
1701 $excludedcats[$category->id
] = 'visibility';
1706 // Sorting the resulting array so it looks a bit better for the client developer.
1707 usort($categoriesinfo, "core_course_external::compare_categories_by_sortorder");
1709 return $categoriesinfo;
1713 * Sort categories array by path
1714 * private function: only used by get_categories
1716 * @param array $category1
1717 * @param array $category2
1718 * @return int result of strcmp
1721 private static function compare_categories_by_path($category1, $category2) {
1722 return strcmp($category1->path
, $category2->path
);
1726 * Sort categories array by sortorder
1727 * private function: only used by get_categories
1729 * @param array $category1
1730 * @param array $category2
1731 * @return int result of strcmp
1734 private static function compare_categories_by_sortorder($category1, $category2) {
1735 return strcmp($category1['sortorder'], $category2['sortorder']);
1739 * Returns description of method result value
1741 * @return external_description
1744 public static function get_categories_returns() {
1745 return new external_multiple_structure(
1746 new external_single_structure(
1748 'id' => new external_value(PARAM_INT
, 'category id'),
1749 'name' => new external_value(PARAM_TEXT
, 'category name'),
1750 'idnumber' => new external_value(PARAM_RAW
, 'category id number', VALUE_OPTIONAL
),
1751 'description' => new external_value(PARAM_RAW
, 'category description'),
1752 'descriptionformat' => new external_format_value('description'),
1753 'parent' => new external_value(PARAM_INT
, 'parent category id'),
1754 'sortorder' => new external_value(PARAM_INT
, 'category sorting order'),
1755 'coursecount' => new external_value(PARAM_INT
, 'number of courses in this category'),
1756 'visible' => new external_value(PARAM_INT
, '1: available, 0:not available', VALUE_OPTIONAL
),
1757 'visibleold' => new external_value(PARAM_INT
, '1: available, 0:not available', VALUE_OPTIONAL
),
1758 'timemodified' => new external_value(PARAM_INT
, 'timestamp', VALUE_OPTIONAL
),
1759 'depth' => new external_value(PARAM_INT
, 'category depth'),
1760 'path' => new external_value(PARAM_TEXT
, 'category path'),
1761 'theme' => new external_value(PARAM_THEME
, 'category theme', VALUE_OPTIONAL
),
1762 ), 'List of categories'
1768 * Returns description of method parameters
1770 * @return external_function_parameters
1773 public static function create_categories_parameters() {
1774 return new external_function_parameters(
1776 'categories' => new external_multiple_structure(
1777 new external_single_structure(
1779 'name' => new external_value(PARAM_TEXT
, 'new category name'),
1780 'parent' => new external_value(PARAM_INT
,
1781 'the parent category id inside which the new category will be created
1782 - set to 0 for a root category',
1784 'idnumber' => new external_value(PARAM_RAW
,
1785 'the new category idnumber', VALUE_OPTIONAL
),
1786 'description' => new external_value(PARAM_RAW
,
1787 'the new category description', VALUE_OPTIONAL
),
1788 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT
),
1789 'theme' => new external_value(PARAM_THEME
,
1790 'the new category theme. This option must be enabled on moodle',
1802 * @param array $categories - see create_categories_parameters() for the array structure
1803 * @return array - see create_categories_returns() for the array structure
1806 public static function create_categories($categories) {
1808 require_once($CFG->libdir
. "/coursecatlib.php");
1810 $params = self
::validate_parameters(self
::create_categories_parameters(),
1811 array('categories' => $categories));
1813 $transaction = $DB->start_delegated_transaction();
1815 $createdcategories = array();
1816 foreach ($params['categories'] as $category) {
1817 if ($category['parent']) {
1818 if (!$DB->record_exists('course_categories', array('id' => $category['parent']))) {
1819 throw new moodle_exception('unknowcategory');
1821 $context = context_coursecat
::instance($category['parent']);
1823 $context = context_system
::instance();
1825 self
::validate_context($context);
1826 require_capability('moodle/category:manage', $context);
1828 // this will validate format and throw an exception if there are errors
1829 external_validate_format($category['descriptionformat']);
1831 $newcategory = coursecat
::create($category);
1833 $createdcategories[] = array('id' => $newcategory->id
, 'name' => $newcategory->name
);
1836 $transaction->allow_commit();
1838 return $createdcategories;
1842 * Returns description of method parameters
1844 * @return external_function_parameters
1847 public static function create_categories_returns() {
1848 return new external_multiple_structure(
1849 new external_single_structure(
1851 'id' => new external_value(PARAM_INT
, 'new category id'),
1852 'name' => new external_value(PARAM_TEXT
, 'new category name'),
1859 * Returns description of method parameters
1861 * @return external_function_parameters
1864 public static function update_categories_parameters() {
1865 return new external_function_parameters(
1867 'categories' => new external_multiple_structure(
1868 new external_single_structure(
1870 'id' => new external_value(PARAM_INT
, 'course id'),
1871 'name' => new external_value(PARAM_TEXT
, 'category name', VALUE_OPTIONAL
),
1872 'idnumber' => new external_value(PARAM_RAW
, 'category id number', VALUE_OPTIONAL
),
1873 'parent' => new external_value(PARAM_INT
, 'parent category id', VALUE_OPTIONAL
),
1874 'description' => new external_value(PARAM_RAW
, 'category description', VALUE_OPTIONAL
),
1875 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT
),
1876 'theme' => new external_value(PARAM_THEME
,
1877 'the category theme. This option must be enabled on moodle', VALUE_OPTIONAL
),
1888 * @param array $categories The list of categories to update
1892 public static function update_categories($categories) {
1894 require_once($CFG->libdir
. "/coursecatlib.php");
1896 // Validate parameters.
1897 $params = self
::validate_parameters(self
::update_categories_parameters(), array('categories' => $categories));
1899 $transaction = $DB->start_delegated_transaction();
1901 foreach ($params['categories'] as $cat) {
1902 $category = coursecat
::get($cat['id']);
1904 $categorycontext = context_coursecat
::instance($cat['id']);
1905 self
::validate_context($categorycontext);
1906 require_capability('moodle/category:manage', $categorycontext);
1908 // this will throw an exception if descriptionformat is not valid
1909 external_validate_format($cat['descriptionformat']);
1911 $category->update($cat);
1914 $transaction->allow_commit();
1918 * Returns description of method result value
1920 * @return external_description
1923 public static function update_categories_returns() {
1928 * Returns description of method parameters
1930 * @return external_function_parameters
1933 public static function delete_categories_parameters() {
1934 return new external_function_parameters(
1936 'categories' => new external_multiple_structure(
1937 new external_single_structure(
1939 'id' => new external_value(PARAM_INT
, 'category id to delete'),
1940 'newparent' => new external_value(PARAM_INT
,
1941 'the parent category to move the contents to, if specified', VALUE_OPTIONAL
),
1942 'recursive' => new external_value(PARAM_BOOL
, '1: recursively delete all contents inside this
1943 category, 0 (default): move contents to newparent or current parent category (except if parent is root)', VALUE_DEFAULT
, 0)
1954 * @param array $categories A list of category ids
1958 public static function delete_categories($categories) {
1960 require_once($CFG->dirroot
. "/course/lib.php");
1961 require_once($CFG->libdir
. "/coursecatlib.php");
1963 // Validate parameters.
1964 $params = self
::validate_parameters(self
::delete_categories_parameters(), array('categories' => $categories));
1966 $transaction = $DB->start_delegated_transaction();
1968 foreach ($params['categories'] as $category) {
1969 $deletecat = coursecat
::get($category['id'], MUST_EXIST
);
1970 $context = context_coursecat
::instance($deletecat->id
);
1971 require_capability('moodle/category:manage', $context);
1972 self
::validate_context($context);
1973 self
::validate_context(get_category_or_system_context($deletecat->parent
));
1975 if ($category['recursive']) {
1976 // If recursive was specified, then we recursively delete the category's contents.
1977 if ($deletecat->can_delete_full()) {
1978 $deletecat->delete_full(false);
1980 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
1983 // In this situation, we don't delete the category's contents, we either move it to newparent or parent.
1984 // If the parent is the root, moving is not supported (because a course must always be inside a category).
1985 // We must move to an existing category.
1986 if (!empty($category['newparent'])) {
1987 $newparentcat = coursecat
::get($category['newparent']);
1989 $newparentcat = coursecat
::get($deletecat->parent
);
1992 // This operation is not allowed. We must move contents to an existing category.
1993 if (!$newparentcat->id
) {
1994 throw new moodle_exception('movecatcontentstoroot');
1997 self
::validate_context(context_coursecat
::instance($newparentcat->id
));
1998 if ($deletecat->can_move_content_to($newparentcat->id
)) {
1999 $deletecat->delete_move($newparentcat->id
, false);
2001 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2006 $transaction->allow_commit();
2010 * Returns description of method parameters
2012 * @return external_function_parameters
2015 public static function delete_categories_returns() {
2020 * Describes the parameters for delete_modules.
2022 * @return external_function_parameters
2025 public static function delete_modules_parameters() {
2026 return new external_function_parameters (
2028 'cmids' => new external_multiple_structure(new external_value(PARAM_INT
, 'course module ID',
2029 VALUE_REQUIRED
, '', NULL_NOT_ALLOWED
), 'Array of course module IDs'),
2035 * Deletes a list of provided module instances.
2037 * @param array $cmids the course module ids
2040 public static function delete_modules($cmids) {
2043 // Require course file containing the course delete module function.
2044 require_once($CFG->dirroot
. "/course/lib.php");
2046 // Clean the parameters.
2047 $params = self
::validate_parameters(self
::delete_modules_parameters(), array('cmids' => $cmids));
2049 // Keep track of the course ids we have performed a capability check on to avoid repeating.
2050 $arrcourseschecked = array();
2052 foreach ($params['cmids'] as $cmid) {
2053 // Get the course module.
2054 $cm = $DB->get_record('course_modules', array('id' => $cmid), '*', MUST_EXIST
);
2056 // Check if we have not yet confirmed they have permission in this course.
2057 if (!in_array($cm->course
, $arrcourseschecked)) {
2058 // Ensure the current user has required permission in this course.
2059 $context = context_course
::instance($cm->course
);
2060 self
::validate_context($context);
2061 // Add to the array.
2062 $arrcourseschecked[] = $cm->course
;
2065 // Ensure they can delete this module.
2066 $modcontext = context_module
::instance($cm->id
);
2067 require_capability('moodle/course:manageactivities', $modcontext);
2069 // Delete the module.
2070 course_delete_module($cm->id
);
2075 * Describes the delete_modules return value.
2077 * @return external_single_structure
2080 public static function delete_modules_returns() {
2085 * Returns description of method parameters
2087 * @return external_function_parameters
2090 public static function view_course_parameters() {
2091 return new external_function_parameters(
2093 'courseid' => new external_value(PARAM_INT
, 'id of the course'),
2094 'sectionnumber' => new external_value(PARAM_INT
, 'section number', VALUE_DEFAULT
, 0)
2100 * Trigger the course viewed event.
2102 * @param int $courseid id of course
2103 * @param int $sectionnumber sectionnumber (0, 1, 2...)
2104 * @return array of warnings and status result
2106 * @throws moodle_exception
2108 public static function view_course($courseid, $sectionnumber = 0) {
2110 require_once($CFG->dirroot
. "/course/lib.php");
2112 $params = self
::validate_parameters(self
::view_course_parameters(),
2114 'courseid' => $courseid,
2115 'sectionnumber' => $sectionnumber
2118 $warnings = array();
2120 $course = get_course($params['courseid']);
2121 $context = context_course
::instance($course->id
);
2122 self
::validate_context($context);
2124 if (!empty($params['sectionnumber'])) {
2126 // Get section details and check it exists.
2127 $modinfo = get_fast_modinfo($course);
2128 $coursesection = $modinfo->get_section_info($params['sectionnumber'], MUST_EXIST
);
2130 // Check user is allowed to see it.
2131 if (!$coursesection->uservisible
) {
2132 require_capability('moodle/course:viewhiddensections', $context);
2136 course_view($context, $params['sectionnumber']);
2139 $result['status'] = true;
2140 $result['warnings'] = $warnings;
2145 * Returns description of method result value
2147 * @return external_description
2150 public static function view_course_returns() {
2151 return new external_single_structure(
2153 'status' => new external_value(PARAM_BOOL
, 'status: true if success'),
2154 'warnings' => new external_warnings()
2160 * Returns description of method parameters
2162 * @return external_function_parameters
2165 public static function search_courses_parameters() {
2166 return new external_function_parameters(
2168 'criterianame' => new external_value(PARAM_ALPHA
, 'criteria name
2169 (search, modulelist (only admins), blocklist (only admins), tagid)'),
2170 'criteriavalue' => new external_value(PARAM_RAW
, 'criteria value'),
2171 'page' => new external_value(PARAM_INT
, 'page number (0 based)', VALUE_DEFAULT
, 0),
2172 'perpage' => new external_value(PARAM_INT
, 'items per page', VALUE_DEFAULT
, 0),
2173 'requiredcapabilities' => new external_multiple_structure(
2174 new external_value(PARAM_CAPABILITY
, 'Capability string used to filter courses by permission'),
2175 'Optional list of required capabilities (used to filter the list)', VALUE_DEFAULT
, array()
2177 'limittoenrolled' => new external_value(PARAM_BOOL
, 'limit to enrolled courses', VALUE_DEFAULT
, 0),
2183 * Return the course information that is public (visible by every one)
2185 * @param course_in_list $course course in list object
2186 * @param stdClass $coursecontext course context object
2187 * @return array the course information
2190 protected static function get_course_public_information(course_in_list
$course, $coursecontext) {
2192 static $categoriescache = array();
2194 // Category information.
2195 if (!array_key_exists($course->category
, $categoriescache)) {
2196 $categoriescache[$course->category
] = coursecat
::get($course->category
, IGNORE_MISSING
);
2198 $category = $categoriescache[$course->category
];
2200 // Retrieve course overview used files.
2202 foreach ($course->get_course_overviewfiles() as $file) {
2203 $fileurl = moodle_url
::make_webservice_pluginfile_url($file->get_contextid(), $file->get_component(),
2204 $file->get_filearea(), null, $file->get_filepath(),
2205 $file->get_filename())->out(false);
2207 'filename' => $file->get_filename(),
2208 'fileurl' => $fileurl,
2209 'filesize' => $file->get_filesize(),
2210 'filepath' => $file->get_filepath(),
2211 'mimetype' => $file->get_mimetype(),
2212 'timemodified' => $file->get_timemodified(),
2216 // Retrieve the course contacts,
2217 // we need here the users fullname since if we are not enrolled can be difficult to obtain them via other Web Services.
2218 $coursecontacts = array();
2219 foreach ($course->get_course_contacts() as $contact) {
2220 $coursecontacts[] = array(
2221 'id' => $contact['user']->id
,
2222 'fullname' => $contact['username']
2226 // Allowed enrolment methods (maybe we can self-enrol).
2227 $enroltypes = array();
2228 $instances = enrol_get_instances($course->id
, true);
2229 foreach ($instances as $instance) {
2230 $enroltypes[] = $instance->enrol
;
2234 list($summary, $summaryformat) =
2235 external_format_text($course->summary
, $course->summaryformat
, $coursecontext->id
, 'course', 'summary', null);
2237 $displayname = get_course_display_name_for_list($course);
2238 $coursereturns = array();
2239 $coursereturns['id'] = $course->id
;
2240 $coursereturns['fullname'] = external_format_string($course->fullname
, $coursecontext->id
);
2241 $coursereturns['displayname'] = external_format_string($displayname, $coursecontext->id
);
2242 $coursereturns['shortname'] = external_format_string($course->shortname
, $coursecontext->id
);
2243 $coursereturns['categoryid'] = $course->category
;
2244 $coursereturns['categoryname'] = $category == null ?
'' : $category->name
;
2245 $coursereturns['summary'] = $summary;
2246 $coursereturns['summaryformat'] = $summaryformat;
2247 $coursereturns['summaryfiles'] = external_util
::get_area_files($coursecontext->id
, 'course', 'summary', false, false);
2248 $coursereturns['overviewfiles'] = $files;
2249 $coursereturns['contacts'] = $coursecontacts;
2250 $coursereturns['enrollmentmethods'] = $enroltypes;
2251 $coursereturns['sortorder'] = $course->sortorder
;
2252 return $coursereturns;
2256 * Search courses following the specified criteria.
2258 * @param string $criterianame Criteria name (search, modulelist (only admins), blocklist (only admins), tagid)
2259 * @param string $criteriavalue Criteria value
2260 * @param int $page Page number (for pagination)
2261 * @param int $perpage Items per page
2262 * @param array $requiredcapabilities Optional list of required capabilities (used to filter the list).
2263 * @param int $limittoenrolled Limit to only enrolled courses
2264 * @return array of course objects and warnings
2266 * @throws moodle_exception
2268 public static function search_courses($criterianame,
2272 $requiredcapabilities=array(),
2273 $limittoenrolled=0) {
2275 require_once($CFG->libdir
. '/coursecatlib.php');
2277 $warnings = array();
2279 $parameters = array(
2280 'criterianame' => $criterianame,
2281 'criteriavalue' => $criteriavalue,
2283 'perpage' => $perpage,
2284 'requiredcapabilities' => $requiredcapabilities
2286 $params = self
::validate_parameters(self
::search_courses_parameters(), $parameters);
2287 self
::validate_context(context_system
::instance());
2289 $allowedcriterianames = array('search', 'modulelist', 'blocklist', 'tagid');
2290 if (!in_array($params['criterianame'], $allowedcriterianames)) {
2291 throw new invalid_parameter_exception('Invalid value for criterianame parameter (value: '.$params['criterianame'].'),' .
2292 'allowed values are: '.implode(',', $allowedcriterianames));
2295 if ($params['criterianame'] == 'modulelist' or $params['criterianame'] == 'blocklist') {
2296 require_capability('moodle/site:config', context_system
::instance());
2300 'search' => PARAM_RAW
,
2301 'modulelist' => PARAM_PLUGIN
,
2302 'blocklist' => PARAM_INT
,
2303 'tagid' => PARAM_INT
2305 $params['criteriavalue'] = clean_param($params['criteriavalue'], $paramtype[$params['criterianame']]);
2307 // Prepare the search API options.
2308 $searchcriteria = array();
2309 $searchcriteria[$params['criterianame']] = $params['criteriavalue'];
2312 if ($params['perpage'] != 0) {
2313 $offset = $params['page'] * $params['perpage'];
2314 $options = array('offset' => $offset, 'limit' => $params['perpage']);
2317 // Search the courses.
2318 $courses = coursecat
::search_courses($searchcriteria, $options, $params['requiredcapabilities']);
2319 $totalcount = coursecat
::search_courses_count($searchcriteria, $options, $params['requiredcapabilities']);
2321 if (!empty($limittoenrolled)) {
2322 // Get the courses where the current user has access.
2323 $enrolled = enrol_get_my_courses(array('id', 'cacherev'));
2326 $finalcourses = array();
2327 $categoriescache = array();
2329 foreach ($courses as $course) {
2330 if (!empty($limittoenrolled)) {
2331 // Filter out not enrolled courses.
2332 if (!isset($enrolled[$course->id
])) {
2338 $coursecontext = context_course
::instance($course->id
);
2340 $finalcourses[] = self
::get_course_public_information($course, $coursecontext);
2344 'total' => $totalcount,
2345 'courses' => $finalcourses,
2346 'warnings' => $warnings
2351 * Returns a course structure definition
2353 * @param boolean $onlypublicdata set to true, to retrieve only fields viewable by anyone when the course is visible
2354 * @return array the course structure
2357 protected static function get_course_structure($onlypublicdata = true) {
2358 $coursestructure = array(
2359 'id' => new external_value(PARAM_INT
, 'course id'),
2360 'fullname' => new external_value(PARAM_TEXT
, 'course full name'),
2361 'displayname' => new external_value(PARAM_TEXT
, 'course display name'),
2362 'shortname' => new external_value(PARAM_TEXT
, 'course short name'),
2363 'categoryid' => new external_value(PARAM_INT
, 'category id'),
2364 'categoryname' => new external_value(PARAM_TEXT
, 'category name'),
2365 'sortorder' => new external_value(PARAM_INT
, 'Sort order in the category', VALUE_OPTIONAL
),
2366 'summary' => new external_value(PARAM_RAW
, 'summary'),
2367 'summaryformat' => new external_format_value('summary'),
2368 'summaryfiles' => new external_files('summary files in the summary field', VALUE_OPTIONAL
),
2369 'overviewfiles' => new external_files('additional overview files attached to this course'),
2370 'contacts' => new external_multiple_structure(
2371 new external_single_structure(
2373 'id' => new external_value(PARAM_INT
, 'contact user id'),
2374 'fullname' => new external_value(PARAM_NOTAGS
, 'contact user fullname'),
2379 'enrollmentmethods' => new external_multiple_structure(
2380 new external_value(PARAM_PLUGIN
, 'enrollment method'),
2381 'enrollment methods list'
2385 if (!$onlypublicdata) {
2387 'idnumber' => new external_value(PARAM_RAW
, 'Id number', VALUE_OPTIONAL
),
2388 'format' => new external_value(PARAM_PLUGIN
, 'Course format: weeks, topics, social, site,..', VALUE_OPTIONAL
),
2389 'showgrades' => new external_value(PARAM_INT
, '1 if grades are shown, otherwise 0', VALUE_OPTIONAL
),
2390 'newsitems' => new external_value(PARAM_INT
, 'Number of recent items appearing on the course page', VALUE_OPTIONAL
),
2391 'startdate' => new external_value(PARAM_INT
, 'Timestamp when the course start', VALUE_OPTIONAL
),
2392 'maxbytes' => new external_value(PARAM_INT
, 'Largest size of file that can be uploaded into', VALUE_OPTIONAL
),
2393 'showreports' => new external_value(PARAM_INT
, 'Are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL
),
2394 'visible' => new external_value(PARAM_INT
, '1: available to student, 0:not available', VALUE_OPTIONAL
),
2395 'groupmode' => new external_value(PARAM_INT
, 'no group, separate, visible', VALUE_OPTIONAL
),
2396 'groupmodeforce' => new external_value(PARAM_INT
, '1: yes, 0: no', VALUE_OPTIONAL
),
2397 'defaultgroupingid' => new external_value(PARAM_INT
, 'default grouping id', VALUE_OPTIONAL
),
2398 'enablecompletion' => new external_value(PARAM_INT
, 'Completion enabled? 1: yes 0: no', VALUE_OPTIONAL
),
2399 'completionnotify' => new external_value(PARAM_INT
, '1: yes 0: no', VALUE_OPTIONAL
),
2400 'lang' => new external_value(PARAM_SAFEDIR
, 'Forced course language', VALUE_OPTIONAL
),
2401 'theme' => new external_value(PARAM_PLUGIN
, 'Fame of the forced theme', VALUE_OPTIONAL
),
2402 'marker' => new external_value(PARAM_INT
, 'Current course marker', VALUE_OPTIONAL
),
2403 'legacyfiles' => new external_value(PARAM_INT
, 'If legacy files are enabled', VALUE_OPTIONAL
),
2404 'calendartype' => new external_value(PARAM_PLUGIN
, 'Calendar type', VALUE_OPTIONAL
),
2405 'timecreated' => new external_value(PARAM_INT
, 'Time when the course was created', VALUE_OPTIONAL
),
2406 'timemodified' => new external_value(PARAM_INT
, 'Last time the course was updated', VALUE_OPTIONAL
),
2407 'requested' => new external_value(PARAM_INT
, 'If is a requested course', VALUE_OPTIONAL
),
2408 'cacherev' => new external_value(PARAM_INT
, 'Cache revision number', VALUE_OPTIONAL
),
2409 'filters' => new external_multiple_structure(
2410 new external_single_structure(
2412 'filter' => new external_value(PARAM_PLUGIN
, 'Filter plugin name'),
2413 'localstate' => new external_value(PARAM_INT
, 'Filter state: 1 for on, -1 for off, 0 if inherit'),
2414 'inheritedstate' => new external_value(PARAM_INT
, '1 or 0 to use when localstate is set to inherit'),
2417 'Course filters', VALUE_OPTIONAL
2420 $coursestructure = array_merge($coursestructure, $extra);
2422 return new external_single_structure($coursestructure);
2426 * Returns description of method result value
2428 * @return external_description
2431 public static function search_courses_returns() {
2432 return new external_single_structure(
2434 'total' => new external_value(PARAM_INT
, 'total course count'),
2435 'courses' => new external_multiple_structure(self
::get_course_structure(), 'course'),
2436 'warnings' => new external_warnings()
2442 * Returns description of method parameters
2444 * @return external_function_parameters
2447 public static function get_course_module_parameters() {
2448 return new external_function_parameters(
2450 'cmid' => new external_value(PARAM_INT
, 'The course module id')
2456 * Return information about a course module.
2458 * @param int $cmid the course module id
2459 * @return array of warnings and the course module
2461 * @throws moodle_exception
2463 public static function get_course_module($cmid) {
2466 $params = self
::validate_parameters(self
::get_course_module_parameters(), array('cmid' => $cmid));
2467 $warnings = array();
2469 $cm = get_coursemodule_from_id(null, $params['cmid'], 0, true, MUST_EXIST
);
2470 $context = context_module
::instance($cm->id
);
2471 self
::validate_context($context);
2473 // If the user has permissions to manage the activity, return all the information.
2474 if (has_capability('moodle/course:manageactivities', $context)) {
2475 require_once($CFG->dirroot
. '/course/modlib.php');
2476 require_once($CFG->libdir
. '/gradelib.php');
2479 // Get the extra information: grade, advanced grading and outcomes data.
2480 $course = get_course($cm->course
);
2481 list($newcm, $newcontext, $module, $extrainfo, $cw) = get_moduleinfo_data($cm, $course);
2483 $gradeinfo = array('grade', 'gradepass', 'gradecat');
2484 foreach ($gradeinfo as $gfield) {
2485 if (isset($extrainfo->{$gfield})) {
2486 $info->{$gfield} = $extrainfo->{$gfield};
2489 if (isset($extrainfo->grade
) and $extrainfo->grade
< 0) {
2490 $info->scale
= $DB->get_field('scale', 'scale', array('id' => abs($extrainfo->grade
)));
2492 // Advanced grading.
2493 if (isset($extrainfo->_advancedgradingdata
)) {
2494 $info->advancedgrading
= array();
2495 foreach ($extrainfo as $key => $val) {
2496 if (strpos($key, 'advancedgradingmethod_') === 0) {
2497 $info->advancedgrading
[] = array(
2498 'area' => str_replace('advancedgradingmethod_', '', $key),
2505 foreach ($extrainfo as $key => $val) {
2506 if (strpos($key, 'outcome_') === 0) {
2507 if (!isset($info->outcomes
)) {
2508 $info->outcomes
= array();
2510 $id = str_replace('outcome_', '', $key);
2511 $outcome = grade_outcome
::fetch(array('id' => $id));
2512 $scaleitems = $outcome->load_scale();
2513 $info->outcomes
[] = array(
2515 'name' => external_format_string($outcome->get_name(), $context->id
),
2516 'scale' => $scaleitems->scale
2521 // Return information is safe to show to any user.
2522 $info = new stdClass();
2523 $info->id
= $cm->id
;
2524 $info->course
= $cm->course
;
2525 $info->module
= $cm->module
;
2526 $info->modname
= $cm->modname
;
2527 $info->instance
= $cm->instance
;
2528 $info->section
= $cm->section
;
2529 $info->sectionnum
= $cm->sectionnum
;
2530 $info->groupmode
= $cm->groupmode
;
2531 $info->groupingid
= $cm->groupingid
;
2532 $info->completion
= $cm->completion
;
2535 $info->name
= external_format_string($cm->name
, $context->id
);
2537 $result['cm'] = $info;
2538 $result['warnings'] = $warnings;
2543 * Returns description of method result value
2545 * @return external_description
2548 public static function get_course_module_returns() {
2549 return new external_single_structure(
2551 'cm' => new external_single_structure(
2553 'id' => new external_value(PARAM_INT
, 'The course module id'),
2554 'course' => new external_value(PARAM_INT
, 'The course id'),
2555 'module' => new external_value(PARAM_INT
, 'The module type id'),
2556 'name' => new external_value(PARAM_RAW
, 'The activity name'),
2557 'modname' => new external_value(PARAM_COMPONENT
, 'The module component name (forum, assign, etc..)'),
2558 'instance' => new external_value(PARAM_INT
, 'The activity instance id'),
2559 'section' => new external_value(PARAM_INT
, 'The module section id'),
2560 'sectionnum' => new external_value(PARAM_INT
, 'The module section number'),
2561 'groupmode' => new external_value(PARAM_INT
, 'Group mode'),
2562 'groupingid' => new external_value(PARAM_INT
, 'Grouping id'),
2563 'completion' => new external_value(PARAM_INT
, 'If completion is enabled'),
2564 'idnumber' => new external_value(PARAM_RAW
, 'Module id number', VALUE_OPTIONAL
),
2565 'added' => new external_value(PARAM_INT
, 'Time added', VALUE_OPTIONAL
),
2566 'score' => new external_value(PARAM_INT
, 'Score', VALUE_OPTIONAL
),
2567 'indent' => new external_value(PARAM_INT
, 'Indentation', VALUE_OPTIONAL
),
2568 'visible' => new external_value(PARAM_INT
, 'If visible', VALUE_OPTIONAL
),
2569 'visibleoncoursepage' => new external_value(PARAM_INT
, 'If visible on course page', VALUE_OPTIONAL
),
2570 'visibleold' => new external_value(PARAM_INT
, 'Visible old', VALUE_OPTIONAL
),
2571 'completiongradeitemnumber' => new external_value(PARAM_INT
, 'Completion grade item', VALUE_OPTIONAL
),
2572 'completionview' => new external_value(PARAM_INT
, 'Completion view setting', VALUE_OPTIONAL
),
2573 'completionexpected' => new external_value(PARAM_INT
, 'Completion time expected', VALUE_OPTIONAL
),
2574 'showdescription' => new external_value(PARAM_INT
, 'If the description is showed', VALUE_OPTIONAL
),
2575 'availability' => new external_value(PARAM_RAW
, 'Availability settings', VALUE_OPTIONAL
),
2576 'grade' => new external_value(PARAM_INT
, 'Grade (max value or scale id)', VALUE_OPTIONAL
),
2577 'scale' => new external_value(PARAM_TEXT
, 'Scale items (if used)', VALUE_OPTIONAL
),
2578 'gradepass' => new external_value(PARAM_RAW
, 'Grade to pass (float)', VALUE_OPTIONAL
),
2579 'gradecat' => new external_value(PARAM_INT
, 'Grade category', VALUE_OPTIONAL
),
2580 'advancedgrading' => new external_multiple_structure(
2581 new external_single_structure(
2583 'area' => new external_value(PARAM_AREA
, 'Gradable area name'),
2584 'method' => new external_value(PARAM_COMPONENT
, 'Grading method'),
2587 'Advanced grading settings', VALUE_OPTIONAL
2589 'outcomes' => new external_multiple_structure(
2590 new external_single_structure(
2592 'id' => new external_value(PARAM_ALPHANUMEXT
, 'Outcome id'),
2593 'name' => new external_value(PARAM_TEXT
, 'Outcome full name'),
2594 'scale' => new external_value(PARAM_TEXT
, 'Scale items')
2597 'Outcomes information', VALUE_OPTIONAL
2601 'warnings' => new external_warnings()
2607 * Returns description of method parameters
2609 * @return external_function_parameters
2612 public static function get_course_module_by_instance_parameters() {
2613 return new external_function_parameters(
2615 'module' => new external_value(PARAM_COMPONENT
, 'The module name'),
2616 'instance' => new external_value(PARAM_INT
, 'The module instance id')
2622 * Return information about a course module.
2624 * @param string $module the module name
2625 * @param int $instance the activity instance id
2626 * @return array of warnings and the course module
2628 * @throws moodle_exception
2630 public static function get_course_module_by_instance($module, $instance) {
2632 $params = self
::validate_parameters(self
::get_course_module_by_instance_parameters(),
2634 'module' => $module,
2635 'instance' => $instance,
2638 $warnings = array();
2639 $cm = get_coursemodule_from_instance($params['module'], $params['instance'], 0, false, MUST_EXIST
);
2641 return self
::get_course_module($cm->id
);
2645 * Returns description of method result value
2647 * @return external_description
2650 public static function get_course_module_by_instance_returns() {
2651 return self
::get_course_module_returns();
2655 * Returns description of method parameters
2657 * @return external_function_parameters
2660 public static function get_activities_overview_parameters() {
2661 return new external_function_parameters(
2663 'courseids' => new external_multiple_structure(new external_value(PARAM_INT
, 'Course id.')),
2669 * Return activities overview for the given courses.
2671 * @param array $courseids a list of course ids
2672 * @return array of warnings and the activities overview
2674 * @throws moodle_exception
2676 public static function get_activities_overview($courseids) {
2679 // Parameter validation.
2680 $params = self
::validate_parameters(self
::get_activities_overview_parameters(), array('courseids' => $courseids));
2681 $courseoverviews = array();
2683 list($courses, $warnings) = external_util
::validate_courses($params['courseids']);
2685 if (!empty($courses)) {
2686 // Add lastaccess to each course (required by print_overview function).
2687 // We need the complete user data, the ws server does not load a complete one.
2688 $user = get_complete_user_data('id', $USER->id
);
2689 foreach ($courses as $course) {
2690 if (isset($user->lastcourseaccess
[$course->id
])) {
2691 $course->lastaccess
= $user->lastcourseaccess
[$course->id
];
2693 $course->lastaccess
= 0;
2697 $overviews = array();
2698 if ($modules = get_plugin_list_with_function('mod', 'print_overview')) {
2699 foreach ($modules as $fname) {
2700 $fname($courses, $overviews);
2705 foreach ($overviews as $courseid => $modules) {
2706 $courseoverviews[$courseid]['id'] = $courseid;
2707 $courseoverviews[$courseid]['overviews'] = array();
2709 foreach ($modules as $modname => $overviewtext) {
2710 $courseoverviews[$courseid]['overviews'][] = array(
2711 'module' => $modname,
2712 'overviewtext' => $overviewtext // This text doesn't need formatting.
2719 'courses' => $courseoverviews,
2720 'warnings' => $warnings
2726 * Returns description of method result value
2728 * @return external_description
2731 public static function get_activities_overview_returns() {
2732 return new external_single_structure(
2734 'courses' => new external_multiple_structure(
2735 new external_single_structure(
2737 'id' => new external_value(PARAM_INT
, 'Course id'),
2738 'overviews' => new external_multiple_structure(
2739 new external_single_structure(
2741 'module' => new external_value(PARAM_PLUGIN
, 'Module name'),
2742 'overviewtext' => new external_value(PARAM_RAW
, 'Overview text'),
2747 ), 'List of courses'
2749 'warnings' => new external_warnings()
2755 * Returns description of method parameters
2757 * @return external_function_parameters
2760 public static function get_user_navigation_options_parameters() {
2761 return new external_function_parameters(
2763 'courseids' => new external_multiple_structure(new external_value(PARAM_INT
, 'Course id.')),
2769 * Return a list of navigation options in a set of courses that are avaialable or not for the current user.
2771 * @param array $courseids a list of course ids
2772 * @return array of warnings and the options availability
2774 * @throws moodle_exception
2776 public static function get_user_navigation_options($courseids) {
2778 require_once($CFG->dirroot
. '/course/lib.php');
2780 // Parameter validation.
2781 $params = self
::validate_parameters(self
::get_user_navigation_options_parameters(), array('courseids' => $courseids));
2782 $courseoptions = array();
2784 list($courses, $warnings) = external_util
::validate_courses($params['courseids'], array(), true);
2786 if (!empty($courses)) {
2787 foreach ($courses as $course) {
2788 // Fix the context for the frontpage.
2789 if ($course->id
== SITEID
) {
2790 $course->context
= context_system
::instance();
2792 $navoptions = course_get_user_navigation_options($course->context
, $course);
2794 foreach ($navoptions as $name => $available) {
2797 'available' => $available,
2801 $courseoptions[] = array(
2802 'id' => $course->id
,
2803 'options' => $options
2809 'courses' => $courseoptions,
2810 'warnings' => $warnings
2816 * Returns description of method result value
2818 * @return external_description
2821 public static function get_user_navigation_options_returns() {
2822 return new external_single_structure(
2824 'courses' => new external_multiple_structure(
2825 new external_single_structure(
2827 'id' => new external_value(PARAM_INT
, 'Course id'),
2828 'options' => new external_multiple_structure(
2829 new external_single_structure(
2831 'name' => new external_value(PARAM_ALPHANUMEXT
, 'Option name'),
2832 'available' => new external_value(PARAM_BOOL
, 'Whether the option is available or not'),
2837 ), 'List of courses'
2839 'warnings' => new external_warnings()
2845 * Returns description of method parameters
2847 * @return external_function_parameters
2850 public static function get_user_administration_options_parameters() {
2851 return new external_function_parameters(
2853 'courseids' => new external_multiple_structure(new external_value(PARAM_INT
, 'Course id.')),
2859 * Return a list of administration options in a set of courses that are available or not for the current user.
2861 * @param array $courseids a list of course ids
2862 * @return array of warnings and the options availability
2864 * @throws moodle_exception
2866 public static function get_user_administration_options($courseids) {
2868 require_once($CFG->dirroot
. '/course/lib.php');
2870 // Parameter validation.
2871 $params = self
::validate_parameters(self
::get_user_administration_options_parameters(), array('courseids' => $courseids));
2872 $courseoptions = array();
2874 list($courses, $warnings) = external_util
::validate_courses($params['courseids'], array(), true);
2876 if (!empty($courses)) {
2877 foreach ($courses as $course) {
2878 $adminoptions = course_get_user_administration_options($course, $course->context
);
2880 foreach ($adminoptions as $name => $available) {
2883 'available' => $available,
2887 $courseoptions[] = array(
2888 'id' => $course->id
,
2889 'options' => $options
2895 'courses' => $courseoptions,
2896 'warnings' => $warnings
2902 * Returns description of method result value
2904 * @return external_description
2907 public static function get_user_administration_options_returns() {
2908 return self
::get_user_navigation_options_returns();
2912 * Returns description of method parameters
2914 * @return external_function_parameters
2917 public static function get_courses_by_field_parameters() {
2918 return new external_function_parameters(
2920 'field' => new external_value(PARAM_ALPHA
, 'The field to search can be left empty for all courses or:
2922 ids: comma separated course ids
2923 shortname: course short name
2924 idnumber: course id number
2925 category: category id the course belongs to
2926 ', VALUE_DEFAULT
, ''),
2927 'value' => new external_value(PARAM_RAW
, 'The value to match', VALUE_DEFAULT
, '')
2934 * Get courses matching a specific field (id/s, shortname, idnumber, category)
2936 * @param string $field field name to search, or empty for all courses
2937 * @param string $value value to search
2938 * @return array list of courses and warnings
2939 * @throws invalid_parameter_exception
2942 public static function get_courses_by_field($field = '', $value = '') {
2944 require_once($CFG->libdir
. '/coursecatlib.php');
2945 require_once($CFG->libdir
. '/filterlib.php');
2947 $params = self
::validate_parameters(self
::get_courses_by_field_parameters(),
2953 $warnings = array();
2955 if (empty($params['field'])) {
2956 $courses = $DB->get_records('course', null, 'id ASC');
2958 switch ($params['field']) {
2961 $value = clean_param($params['value'], PARAM_INT
);
2964 $value = clean_param($params['value'], PARAM_SEQUENCE
);
2967 $value = clean_param($params['value'], PARAM_TEXT
);
2970 $value = clean_param($params['value'], PARAM_RAW
);
2973 throw new invalid_parameter_exception('Invalid field name');
2976 if ($params['field'] === 'ids') {
2977 $courses = $DB->get_records_list('course', 'id', explode(',', $value), 'id ASC');
2979 $courses = $DB->get_records('course', array($params['field'] => $value), 'id ASC');
2983 $coursesdata = array();
2984 foreach ($courses as $course) {
2985 $context = context_course
::instance($course->id
);
2986 $canupdatecourse = has_capability('moodle/course:update', $context);
2987 $canviewhiddencourses = has_capability('moodle/course:viewhiddencourses', $context);
2989 // Check if the course is visible in the site for the user.
2990 if (!$course->visible
and !$canviewhiddencourses and !$canupdatecourse) {
2993 // Get the public course information, even if we are not enrolled.
2994 $courseinlist = new course_in_list($course);
2995 $coursesdata[$course->id
] = self
::get_course_public_information($courseinlist, $context);
2997 // Now, check if we have access to the course.
2999 self
::validate_context($context);
3000 } catch (Exception
$e) {
3003 // Return information for any user that can access the course.
3004 $coursefields = array('format', 'showgrades', 'newsitems', 'startdate', 'maxbytes', 'showreports', 'visible',
3005 'groupmode', 'groupmodeforce', 'defaultgroupingid', 'enablecompletion', 'completionnotify', 'lang', 'theme',
3009 $coursesdata[$course->id
]['filters'] = filter_get_available_in_context($context);
3011 // Information for managers only.
3012 if ($canupdatecourse) {
3013 $managerfields = array('idnumber', 'legacyfiles', 'calendartype', 'timecreated', 'timemodified', 'requested',
3015 $coursefields = array_merge($coursefields, $managerfields);
3019 foreach ($coursefields as $field) {
3020 $coursesdata[$course->id
][$field] = $course->{$field};
3025 'courses' => $coursesdata,
3026 'warnings' => $warnings
3031 * Returns description of method result value
3033 * @return external_description
3036 public static function get_courses_by_field_returns() {
3037 // Course structure, including not only public viewable fields.
3038 return new external_single_structure(
3040 'courses' => new external_multiple_structure(self
::get_course_structure(false), 'Course'),
3041 'warnings' => new external_warnings()
3047 * Returns description of method parameters
3049 * @return external_function_parameters
3052 public static function check_updates_parameters() {
3053 return new external_function_parameters(
3055 'courseid' => new external_value(PARAM_INT
, 'Course id to check'),
3056 'tocheck' => new external_multiple_structure(
3057 new external_single_structure(
3059 'contextlevel' => new external_value(PARAM_ALPHA
, 'The context level for the file location.
3060 Only module supported right now.'),
3061 'id' => new external_value(PARAM_INT
, 'Context instance id'),
3062 'since' => new external_value(PARAM_INT
, 'Check updates since this time stamp'),
3065 'Instances to check'
3067 'filter' => new external_multiple_structure(
3068 new external_value(PARAM_ALPHANUM
, 'Area name: configuration, fileareas, completion, ratings, comments,
3069 gradeitems, outcomes'),
3070 'Check only for updates in these areas', VALUE_DEFAULT
, array()
3077 * Check if there is updates affecting the user for the given course and contexts.
3078 * Right now only modules are supported.
3079 * This WS calls mod_check_updates_since for each module to check if there is any update the user should we aware of.
3081 * @param int $courseid the list of modules to check
3082 * @param array $tocheck the list of modules to check
3083 * @param array $filter check only for updates in these areas
3084 * @return array list of updates and warnings
3085 * @throws moodle_exception
3088 public static function check_updates($courseid, $tocheck, $filter = array()) {
3091 $params = self
::validate_parameters(
3092 self
::check_updates_parameters(),
3094 'courseid' => $courseid,
3095 'tocheck' => $tocheck,
3096 'filter' => $filter,
3100 $course = get_course($params['courseid']);
3101 $context = context_course
::instance($course->id
);
3102 self
::validate_context($context);
3104 list($instances, $warnings) = course_check_updates($course, $params['tocheck'], $filter);
3106 $instancesformatted = array();
3107 foreach ($instances as $instance) {
3109 foreach ($instance['updates'] as $name => $data) {
3110 if (empty($data->updated
)) {
3113 $updatedata = array(
3116 if (!empty($data->timeupdated
)) {
3117 $updatedata['timeupdated'] = $data->timeupdated
;
3119 if (!empty($data->itemids
)) {
3120 $updatedata['itemids'] = $data->itemids
;
3122 $updates[] = $updatedata;
3124 if (!empty($updates)) {
3125 $instancesformatted[] = array(
3126 'contextlevel' => $instance['contextlevel'],
3127 'id' => $instance['id'],
3128 'updates' => $updates
3134 'instances' => $instancesformatted,
3135 'warnings' => $warnings
3140 * Returns description of method result value
3142 * @return external_description
3145 public static function check_updates_returns() {
3146 return new external_single_structure(
3148 'instances' => new external_multiple_structure(
3149 new external_single_structure(
3151 'contextlevel' => new external_value(PARAM_ALPHA
, 'The context level'),
3152 'id' => new external_value(PARAM_INT
, 'Instance id'),
3153 'updates' => new external_multiple_structure(
3154 new external_single_structure(
3156 'name' => new external_value(PARAM_ALPHANUMEXT
, 'Name of the area updated.'),
3157 'timeupdated' => new external_value(PARAM_INT
, 'Last time was updated', VALUE_OPTIONAL
),
3158 'itemids' => new external_multiple_structure(
3159 new external_value(PARAM_INT
, 'Instance id'),
3160 'The ids of the items updated',
3169 'warnings' => new external_warnings()
3175 * Returns description of method parameters
3177 * @return external_function_parameters
3180 public static function get_updates_since_parameters() {
3181 return new external_function_parameters(
3183 'courseid' => new external_value(PARAM_INT
, 'Course id to check'),
3184 'since' => new external_value(PARAM_INT
, 'Check updates since this time stamp'),
3185 'filter' => new external_multiple_structure(
3186 new external_value(PARAM_ALPHANUM
, 'Area name: configuration, fileareas, completion, ratings, comments,
3187 gradeitems, outcomes'),
3188 'Check only for updates in these areas', VALUE_DEFAULT
, array()
3195 * Check if there are updates affecting the user for the given course since the given time stamp.
3197 * This function is a wrapper of self::check_updates for retrieving all the updates since a given time for all the activities.
3199 * @param int $courseid the list of modules to check
3200 * @param int $since check updates since this time stamp
3201 * @param array $filter check only for updates in these areas
3202 * @return array list of updates and warnings
3203 * @throws moodle_exception
3206 public static function get_updates_since($courseid, $since, $filter = array()) {
3209 $params = self
::validate_parameters(
3210 self
::get_updates_since_parameters(),
3212 'courseid' => $courseid,
3214 'filter' => $filter,
3218 $course = get_course($params['courseid']);
3219 $modinfo = get_fast_modinfo($course);
3222 // Retrieve all the visible course modules for the current user.
3223 $cms = $modinfo->get_cms();
3224 foreach ($cms as $cm) {
3225 if (!$cm->uservisible
) {
3230 'contextlevel' => 'module',
3231 'since' => $params['since'],
3235 return self
::check_updates($course->id
, $tocheck, $params['filter']);
3239 * Returns description of method result value
3241 * @return external_description
3244 public static function get_updates_since_returns() {
3245 return self
::check_updates_returns();
3249 * Parameters for function edit_module()
3252 * @return external_function_parameters
3254 public static function edit_module_parameters() {
3255 return new external_function_parameters(
3257 'action' => new external_value(PARAM_ALPHA
,
3258 'action: hide, show, stealth, duplicate, delete, moveleft, moveright, group...', VALUE_REQUIRED
),
3259 'id' => new external_value(PARAM_INT
, 'course module id', VALUE_REQUIRED
),
3260 'sectionreturn' => new external_value(PARAM_INT
, 'section to return to', VALUE_DEFAULT
, null),
3265 * Performs one of the edit module actions and return new html for AJAX
3267 * Returns html to replace the current module html with, for example:
3268 * - empty string for "delete" action,
3269 * - two modules html for "duplicate" action
3270 * - updated module html for everything else
3272 * Throws exception if operation is not permitted/possible
3275 * @param string $action
3277 * @param null|int $sectionreturn
3280 public static function edit_module($action, $id, $sectionreturn = null) {
3282 // Validate and normalize parameters.
3283 $params = self
::validate_parameters(self
::edit_module_parameters(),
3284 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3285 $action = $params['action'];
3286 $id = $params['id'];
3287 $sectionreturn = $params['sectionreturn'];
3289 list($course, $cm) = get_course_and_cm_from_cmid($id);
3290 $modcontext = context_module
::instance($cm->id
);
3291 $coursecontext = context_course
::instance($course->id
);
3292 self
::validate_context($modcontext);
3293 $courserenderer = $PAGE->get_renderer('core', 'course');
3294 $completioninfo = new completion_info($course);
3300 require_capability('moodle/course:activityvisibility', $modcontext);
3301 $visible = ($action === 'hide') ?
0 : 1;
3302 $visibleoncoursepage = ($action === 'stealth') ?
0 : 1;
3303 set_coursemodule_visible($id, $visible, $visibleoncoursepage);
3304 \core\event\course_module_updated
::create_from_cm($cm, $modcontext)->trigger();
3307 require_capability('moodle/course:manageactivities', $coursecontext);
3308 require_capability('moodle/backup:backuptargetimport', $coursecontext);
3309 require_capability('moodle/restore:restoretargetimport', $coursecontext);
3310 if (!course_allowed_module($course, $cm->modname
)) {
3311 throw new moodle_exception('No permission to create that activity');
3313 if ($newcm = duplicate_module($course, $cm)) {
3314 $cm = get_fast_modinfo($course)->get_cm($id);
3315 $newcm = get_fast_modinfo($course)->get_cm($newcm->id
);
3316 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn) .
3317 $courserenderer->course_section_cm_list_item($course, $completioninfo, $newcm, $sectionreturn);
3320 case 'groupsseparate':
3321 case 'groupsvisible':
3323 require_capability('moodle/course:manageactivities', $modcontext);
3324 if ($action === 'groupsseparate') {
3325 $newgroupmode = SEPARATEGROUPS
;
3326 } else if ($action === 'groupsvisible') {
3327 $newgroupmode = VISIBLEGROUPS
;
3329 $newgroupmode = NOGROUPS
;
3331 if (set_coursemodule_groupmode($cm->id
, $newgroupmode)) {
3332 \core\event\course_module_updated
::create_from_cm($cm, $modcontext)->trigger();
3337 require_capability('moodle/course:manageactivities', $modcontext);
3338 $indent = $cm->indent +
(($action === 'moveright') ?
1 : -1);
3339 if ($cm->indent
>= 0) {
3340 $DB->update_record('course_modules', array('id' => $cm->id
, 'indent' => $indent));
3341 rebuild_course_cache($cm->course
);
3345 require_capability('moodle/course:manageactivities', $modcontext);
3346 course_delete_module($cm->id
, true);
3349 throw new coding_exception('Unrecognised action');
3352 $cm = get_fast_modinfo($course)->get_cm($id);
3353 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn);
3357 * Return structure for edit_module()
3360 * @return external_description
3362 public static function edit_module_returns() {
3363 return new external_value(PARAM_RAW
, 'html to replace the current module with');
3367 * Parameters for function get_module()
3370 * @return external_function_parameters
3372 public static function get_module_parameters() {
3373 return new external_function_parameters(
3375 'id' => new external_value(PARAM_INT
, 'course module id', VALUE_REQUIRED
),
3376 'sectionreturn' => new external_value(PARAM_INT
, 'section to return to', VALUE_DEFAULT
, null),
3381 * Returns html for displaying one activity module on course page
3385 * @param null|int $sectionreturn
3388 public static function get_module($id, $sectionreturn = null) {
3390 // Validate and normalize parameters.
3391 $params = self
::validate_parameters(self
::get_module_parameters(),
3392 array('id' => $id, 'sectionreturn' => $sectionreturn));
3393 $id = $params['id'];
3394 $sectionreturn = $params['sectionreturn'];
3396 // Validate access to the course (note, this is html for the course view page, we don't validate access to the module).
3397 list($course, $cm) = get_course_and_cm_from_cmid($id);
3398 self
::validate_context(context_course
::instance($course->id
));
3400 $courserenderer = $PAGE->get_renderer('core', 'course');
3401 $completioninfo = new completion_info($course);
3402 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn);
3406 * Return structure for edit_module()
3409 * @return external_description
3411 public static function get_module_returns() {
3412 return new external_value(PARAM_RAW
, 'html to replace the current module with');
3416 * Parameters for function edit_section()
3419 * @return external_function_parameters
3421 public static function edit_section_parameters() {
3422 return new external_function_parameters(
3424 'action' => new external_value(PARAM_ALPHA
, 'action: hide, show, stealth, setmarker, removemarker', VALUE_REQUIRED
),
3425 'id' => new external_value(PARAM_INT
, 'course section id', VALUE_REQUIRED
),
3426 'sectionreturn' => new external_value(PARAM_INT
, 'section to return to', VALUE_DEFAULT
, null),
3431 * Performs one of the edit section actions
3434 * @param string $action
3435 * @param int $id section id
3436 * @param int $sectionreturn section to return to
3439 public static function edit_section($action, $id, $sectionreturn) {
3441 // Validate and normalize parameters.
3442 $params = self
::validate_parameters(self
::edit_section_parameters(),
3443 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3444 $action = $params['action'];
3445 $id = $params['id'];
3446 $sr = $params['sectionreturn'];
3448 $section = $DB->get_record('course_sections', array('id' => $id), '*', MUST_EXIST
);
3449 $coursecontext = context_course
::instance($section->course
);
3450 self
::validate_context($coursecontext);
3452 $rv = course_get_format($section->course
)->section_action($section, $action, $sectionreturn);
3454 return json_encode($rv);
3461 * Return structure for edit_section()
3464 * @return external_description
3466 public static function edit_section_returns() {
3467 return new external_value(PARAM_RAW
, 'Additional data for javascript (JSON-encoded string)');