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();
164 //for each sections (first displayed to last displayed)
165 $modinfosections = $modinfo->get_sections();
166 foreach ($sections as $key => $section) {
168 if (!$section->uservisible
) {
172 // This becomes true when we are filtering and we found the value to filter with.
173 $sectionfound = false;
175 // Filter by section id.
176 if (!empty($filters['sectionid'])) {
177 if ($section->id
!= $filters['sectionid']) {
180 $sectionfound = true;
184 // Filter by section number. Note that 0 is a valid section number.
185 if (isset($filters['sectionnumber'])) {
186 if ($key != $filters['sectionnumber']) {
189 $sectionfound = true;
193 // reset $sectioncontents
194 $sectionvalues = array();
195 $sectionvalues['id'] = $section->id
;
196 $sectionvalues['name'] = get_section_name($course, $section);
197 $sectionvalues['visible'] = $section->visible
;
198 list($sectionvalues['summary'], $sectionvalues['summaryformat']) =
199 external_format_text($section->summary
, $section->summaryformat
,
200 $context->id
, 'course', 'section', $section->id
);
201 $sectioncontents = array();
203 //for each module of the section
204 if (empty($filters['excludemodules']) and !empty($modinfosections[$section->section
])) {
205 foreach ($modinfosections[$section->section
] as $cmid) {
206 $cm = $modinfo->cms
[$cmid];
208 // stop here if the module is not visible to the user
209 if (!$cm->uservisible
) {
213 // This becomes true when we are filtering and we found the value to filter with.
217 if (!empty($filters['cmid'])) {
218 if ($cmid != $filters['cmid']) {
225 // Filter by module name and id.
226 if (!empty($filters['modname'])) {
227 if ($cm->modname
!= $filters['modname']) {
229 } else if (!empty($filters['modid'])) {
230 if ($cm->instance
!= $filters['modid']) {
233 // Note that if we are only filtering by modname we don't break the loop.
241 //common info (for people being able to see the module or availability dates)
242 $module['id'] = $cm->id
;
243 $module['name'] = format_string($cm->name
, true);
244 $module['instance'] = $cm->instance
;
245 $module['modname'] = $cm->modname
;
246 $module['modplural'] = $cm->modplural
;
247 $module['modicon'] = $cm->get_icon_url()->out(false);
248 $module['indent'] = $cm->indent
;
250 $modcontext = context_module
::instance($cm->id
);
252 if (!empty($cm->showdescription
) or $cm->modname
== 'label') {
253 // We want to use the external format. However from reading get_formatted_content(), $cm->content format is always FORMAT_HTML.
254 list($module['description'], $descriptionformat) = external_format_text($cm->content
,
255 FORMAT_HTML
, $modcontext->id
, $cm->modname
, 'intro', $cm->id
);
260 if ($url) { //labels don't have url
261 $module['url'] = $url->out(false);
264 $canviewhidden = has_capability('moodle/course:viewhiddenactivities',
265 context_module
::instance($cm->id
));
266 //user that can view hidden module should know about the visibility
267 $module['visible'] = $cm->visible
;
269 // Availability date (also send to user who can see hidden module).
270 if ($CFG->enableavailability
&& ($canviewhidden ||
$canupdatecourse)) {
271 $module['availability'] = $cm->availability
;
274 $baseurl = 'webservice/pluginfile.php';
276 //call $modulename_export_contents
277 //(each module callback take care about checking the capabilities)
279 require_once($CFG->dirroot
. '/mod/' . $cm->modname
. '/lib.php');
280 $getcontentfunction = $cm->modname
.'_export_contents';
281 if (function_exists($getcontentfunction)) {
282 if (empty($filters['excludecontents']) and $contents = $getcontentfunction($cm, $baseurl)) {
283 $module['contents'] = $contents;
285 $module['contents'] = array();
289 //assign result to $sectioncontents
290 $sectioncontents[] = $module;
292 // If we just did a filtering, break the loop.
299 $sectionvalues['modules'] = $sectioncontents;
301 // assign result to $coursecontents
302 $coursecontents[] = $sectionvalues;
304 // Break the loop if we are filtering.
310 return $coursecontents;
314 * Returns description of method result value
316 * @return external_description
319 public static function get_course_contents_returns() {
320 return new external_multiple_structure(
321 new external_single_structure(
323 'id' => new external_value(PARAM_INT
, 'Section ID'),
324 'name' => new external_value(PARAM_TEXT
, 'Section name'),
325 'visible' => new external_value(PARAM_INT
, 'is the section visible', VALUE_OPTIONAL
),
326 'summary' => new external_value(PARAM_RAW
, 'Section description'),
327 'summaryformat' => new external_format_value('summary'),
328 'modules' => new external_multiple_structure(
329 new external_single_structure(
331 'id' => new external_value(PARAM_INT
, 'activity id'),
332 'url' => new external_value(PARAM_URL
, 'activity url', VALUE_OPTIONAL
),
333 'name' => new external_value(PARAM_RAW
, 'activity module name'),
334 'instance' => new external_value(PARAM_INT
, 'instance id', VALUE_OPTIONAL
),
335 'description' => new external_value(PARAM_RAW
, 'activity description', VALUE_OPTIONAL
),
336 'visible' => new external_value(PARAM_INT
, 'is the module visible', VALUE_OPTIONAL
),
337 'modicon' => new external_value(PARAM_URL
, 'activity icon url'),
338 'modname' => new external_value(PARAM_PLUGIN
, 'activity module type'),
339 'modplural' => new external_value(PARAM_TEXT
, 'activity module plural name'),
340 'availability' => new external_value(PARAM_RAW
, 'module availability settings', VALUE_OPTIONAL
),
341 'indent' => new external_value(PARAM_INT
, 'number of identation in the site'),
342 'contents' => new external_multiple_structure(
343 new external_single_structure(
346 'type'=> new external_value(PARAM_TEXT
, 'a file or a folder or external link'),
347 'filename'=> new external_value(PARAM_FILE
, 'filename'),
348 'filepath'=> new external_value(PARAM_PATH
, 'filepath'),
349 'filesize'=> new external_value(PARAM_INT
, 'filesize'),
350 'fileurl' => new external_value(PARAM_URL
, 'downloadable file url', VALUE_OPTIONAL
),
351 'content' => new external_value(PARAM_RAW
, 'Raw content, will be used when type is content', VALUE_OPTIONAL
),
352 'timecreated' => new external_value(PARAM_INT
, 'Time created'),
353 'timemodified' => new external_value(PARAM_INT
, 'Time modified'),
354 'sortorder' => new external_value(PARAM_INT
, 'Content sort order'),
356 // copyright related info
357 'userid' => new external_value(PARAM_INT
, 'User who added this content to moodle'),
358 'author' => new external_value(PARAM_TEXT
, 'Content owner'),
359 'license' => new external_value(PARAM_TEXT
, 'Content license'),
361 ), VALUE_DEFAULT
, array()
372 * Returns description of method parameters
374 * @return external_function_parameters
377 public static function get_courses_parameters() {
378 return new external_function_parameters(
379 array('options' => new external_single_structure(
380 array('ids' => new external_multiple_structure(
381 new external_value(PARAM_INT
, 'Course id')
382 , 'List of course id. If empty return all courses
383 except front page course.',
385 ), 'options - operator OR is used', VALUE_DEFAULT
, array())
393 * @param array $options It contains an array (list of ids)
397 public static function get_courses($options = array()) {
399 require_once($CFG->dirroot
. "/course/lib.php");
402 $params = self
::validate_parameters(self
::get_courses_parameters(),
403 array('options' => $options));
406 if (!array_key_exists('ids', $params['options'])
407 or empty($params['options']['ids'])) {
408 $courses = $DB->get_records('course');
410 $courses = $DB->get_records_list('course', 'id', $params['options']['ids']);
413 //create return value
414 $coursesinfo = array();
415 foreach ($courses as $course) {
417 // now security checks
418 $context = context_course
::instance($course->id
, IGNORE_MISSING
);
419 $courseformatoptions = course_get_format($course)->get_format_options();
421 self
::validate_context($context);
422 } catch (Exception
$e) {
423 $exceptionparam = new stdClass();
424 $exceptionparam->message
= $e->getMessage();
425 $exceptionparam->courseid
= $course->id
;
426 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
428 require_capability('moodle/course:view', $context);
430 $courseinfo = array();
431 $courseinfo['id'] = $course->id
;
432 $courseinfo['fullname'] = $course->fullname
;
433 $courseinfo['shortname'] = $course->shortname
;
434 $courseinfo['categoryid'] = $course->category
;
435 list($courseinfo['summary'], $courseinfo['summaryformat']) =
436 external_format_text($course->summary
, $course->summaryformat
, $context->id
, 'course', 'summary', 0);
437 $courseinfo['format'] = $course->format
;
438 $courseinfo['startdate'] = $course->startdate
;
439 if (array_key_exists('numsections', $courseformatoptions)) {
440 // For backward-compartibility
441 $courseinfo['numsections'] = $courseformatoptions['numsections'];
444 //some field should be returned only if the user has update permission
445 $courseadmin = has_capability('moodle/course:update', $context);
447 $courseinfo['categorysortorder'] = $course->sortorder
;
448 $courseinfo['idnumber'] = $course->idnumber
;
449 $courseinfo['showgrades'] = $course->showgrades
;
450 $courseinfo['showreports'] = $course->showreports
;
451 $courseinfo['newsitems'] = $course->newsitems
;
452 $courseinfo['visible'] = $course->visible
;
453 $courseinfo['maxbytes'] = $course->maxbytes
;
454 if (array_key_exists('hiddensections', $courseformatoptions)) {
455 // For backward-compartibility
456 $courseinfo['hiddensections'] = $courseformatoptions['hiddensections'];
458 $courseinfo['groupmode'] = $course->groupmode
;
459 $courseinfo['groupmodeforce'] = $course->groupmodeforce
;
460 $courseinfo['defaultgroupingid'] = $course->defaultgroupingid
;
461 $courseinfo['lang'] = $course->lang
;
462 $courseinfo['timecreated'] = $course->timecreated
;
463 $courseinfo['timemodified'] = $course->timemodified
;
464 $courseinfo['forcetheme'] = $course->theme
;
465 $courseinfo['enablecompletion'] = $course->enablecompletion
;
466 $courseinfo['completionnotify'] = $course->completionnotify
;
467 $courseinfo['courseformatoptions'] = array();
468 foreach ($courseformatoptions as $key => $value) {
469 $courseinfo['courseformatoptions'][] = array(
476 if ($courseadmin or $course->visible
477 or has_capability('moodle/course:viewhiddencourses', $context)) {
478 $coursesinfo[] = $courseinfo;
486 * Returns description of method result value
488 * @return external_description
491 public static function get_courses_returns() {
492 return new external_multiple_structure(
493 new external_single_structure(
495 'id' => new external_value(PARAM_INT
, 'course id'),
496 'shortname' => new external_value(PARAM_TEXT
, 'course short name'),
497 'categoryid' => new external_value(PARAM_INT
, 'category id'),
498 'categorysortorder' => new external_value(PARAM_INT
,
499 'sort order into the category', VALUE_OPTIONAL
),
500 'fullname' => new external_value(PARAM_TEXT
, 'full name'),
501 'idnumber' => new external_value(PARAM_RAW
, 'id number', VALUE_OPTIONAL
),
502 'summary' => new external_value(PARAM_RAW
, 'summary'),
503 'summaryformat' => new external_format_value('summary'),
504 'format' => new external_value(PARAM_PLUGIN
,
505 'course format: weeks, topics, social, site,..'),
506 'showgrades' => new external_value(PARAM_INT
,
507 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL
),
508 'newsitems' => new external_value(PARAM_INT
,
509 'number of recent items appearing on the course page', VALUE_OPTIONAL
),
510 'startdate' => new external_value(PARAM_INT
,
511 'timestamp when the course start'),
512 'numsections' => new external_value(PARAM_INT
,
513 '(deprecated, use courseformatoptions) number of weeks/topics',
515 'maxbytes' => new external_value(PARAM_INT
,
516 'largest size of file that can be uploaded into the course',
518 'showreports' => new external_value(PARAM_INT
,
519 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL
),
520 'visible' => new external_value(PARAM_INT
,
521 '1: available to student, 0:not available', VALUE_OPTIONAL
),
522 'hiddensections' => new external_value(PARAM_INT
,
523 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
525 'groupmode' => new external_value(PARAM_INT
, 'no group, separate, visible',
527 'groupmodeforce' => new external_value(PARAM_INT
, '1: yes, 0: no',
529 'defaultgroupingid' => new external_value(PARAM_INT
, 'default grouping id',
531 'timecreated' => new external_value(PARAM_INT
,
532 'timestamp when the course have been created', VALUE_OPTIONAL
),
533 'timemodified' => new external_value(PARAM_INT
,
534 'timestamp when the course have been modified', VALUE_OPTIONAL
),
535 'enablecompletion' => new external_value(PARAM_INT
,
536 'Enabled, control via completion and activity settings. Disbaled,
537 not shown in activity settings.',
539 'completionnotify' => new external_value(PARAM_INT
,
540 '1: yes 0: no', VALUE_OPTIONAL
),
541 'lang' => new external_value(PARAM_SAFEDIR
,
542 'forced course language', VALUE_OPTIONAL
),
543 'forcetheme' => new external_value(PARAM_PLUGIN
,
544 'name of the force theme', VALUE_OPTIONAL
),
545 'courseformatoptions' => new external_multiple_structure(
546 new external_single_structure(
547 array('name' => new external_value(PARAM_ALPHANUMEXT
, 'course format option name'),
548 'value' => new external_value(PARAM_RAW
, 'course format option value')
550 'additional options for particular course format', VALUE_OPTIONAL
558 * Returns description of method parameters
560 * @return external_function_parameters
563 public static function create_courses_parameters() {
564 $courseconfig = get_config('moodlecourse'); //needed for many default values
565 return new external_function_parameters(
567 'courses' => new external_multiple_structure(
568 new external_single_structure(
570 'fullname' => new external_value(PARAM_TEXT
, 'full name'),
571 'shortname' => new external_value(PARAM_TEXT
, 'course short name'),
572 'categoryid' => new external_value(PARAM_INT
, 'category id'),
573 'idnumber' => new external_value(PARAM_RAW
, 'id number', VALUE_OPTIONAL
),
574 'summary' => new external_value(PARAM_RAW
, 'summary', VALUE_OPTIONAL
),
575 'summaryformat' => new external_format_value('summary', VALUE_DEFAULT
),
576 'format' => new external_value(PARAM_PLUGIN
,
577 'course format: weeks, topics, social, site,..',
578 VALUE_DEFAULT
, $courseconfig->format
),
579 'showgrades' => new external_value(PARAM_INT
,
580 '1 if grades are shown, otherwise 0', VALUE_DEFAULT
,
581 $courseconfig->showgrades
),
582 'newsitems' => new external_value(PARAM_INT
,
583 'number of recent items appearing on the course page',
584 VALUE_DEFAULT
, $courseconfig->newsitems
),
585 'startdate' => new external_value(PARAM_INT
,
586 'timestamp when the course start', VALUE_OPTIONAL
),
587 'numsections' => new external_value(PARAM_INT
,
588 '(deprecated, use courseformatoptions) number of weeks/topics',
590 'maxbytes' => new external_value(PARAM_INT
,
591 'largest size of file that can be uploaded into the course',
592 VALUE_DEFAULT
, $courseconfig->maxbytes
),
593 'showreports' => new external_value(PARAM_INT
,
594 'are activity report shown (yes = 1, no =0)', VALUE_DEFAULT
,
595 $courseconfig->showreports
),
596 'visible' => new external_value(PARAM_INT
,
597 '1: available to student, 0:not available', VALUE_OPTIONAL
),
598 'hiddensections' => new external_value(PARAM_INT
,
599 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
601 'groupmode' => new external_value(PARAM_INT
, 'no group, separate, visible',
602 VALUE_DEFAULT
, $courseconfig->groupmode
),
603 'groupmodeforce' => new external_value(PARAM_INT
, '1: yes, 0: no',
604 VALUE_DEFAULT
, $courseconfig->groupmodeforce
),
605 'defaultgroupingid' => new external_value(PARAM_INT
, 'default grouping id',
607 'enablecompletion' => new external_value(PARAM_INT
,
608 'Enabled, control via completion and activity settings. Disabled,
609 not shown in activity settings.',
611 'completionnotify' => new external_value(PARAM_INT
,
612 '1: yes 0: no', VALUE_OPTIONAL
),
613 'lang' => new external_value(PARAM_SAFEDIR
,
614 'forced course language', VALUE_OPTIONAL
),
615 'forcetheme' => new external_value(PARAM_PLUGIN
,
616 'name of the force theme', VALUE_OPTIONAL
),
617 'courseformatoptions' => new external_multiple_structure(
618 new external_single_structure(
619 array('name' => new external_value(PARAM_ALPHANUMEXT
, 'course format option name'),
620 'value' => new external_value(PARAM_RAW
, 'course format option value')
622 'additional options for particular course format', VALUE_OPTIONAL
),
624 ), 'courses to create'
633 * @param array $courses
634 * @return array courses (id and shortname only)
637 public static function create_courses($courses) {
639 require_once($CFG->dirroot
. "/course/lib.php");
640 require_once($CFG->libdir
. '/completionlib.php');
642 $params = self
::validate_parameters(self
::create_courses_parameters(),
643 array('courses' => $courses));
645 $availablethemes = core_component
::get_plugin_list('theme');
646 $availablelangs = get_string_manager()->get_list_of_translations();
648 $transaction = $DB->start_delegated_transaction();
650 foreach ($params['courses'] as $course) {
652 // Ensure the current user is allowed to run this function
653 $context = context_coursecat
::instance($course['categoryid'], IGNORE_MISSING
);
655 self
::validate_context($context);
656 } catch (Exception
$e) {
657 $exceptionparam = new stdClass();
658 $exceptionparam->message
= $e->getMessage();
659 $exceptionparam->catid
= $course['categoryid'];
660 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
662 require_capability('moodle/course:create', $context);
664 // Make sure lang is valid
665 if (array_key_exists('lang', $course) and empty($availablelangs[$course['lang']])) {
666 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
669 // Make sure theme is valid
670 if (array_key_exists('forcetheme', $course)) {
671 if (!empty($CFG->allowcoursethemes
)) {
672 if (empty($availablethemes[$course['forcetheme']])) {
673 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
675 $course['theme'] = $course['forcetheme'];
680 //force visibility if ws user doesn't have the permission to set it
681 $category = $DB->get_record('course_categories', array('id' => $course['categoryid']));
682 if (!has_capability('moodle/course:visibility', $context)) {
683 $course['visible'] = $category->visible
;
686 //set default value for completion
687 $courseconfig = get_config('moodlecourse');
688 if (completion_info
::is_enabled_for_site()) {
689 if (!array_key_exists('enablecompletion', $course)) {
690 $course['enablecompletion'] = $courseconfig->enablecompletion
;
693 $course['enablecompletion'] = 0;
696 $course['category'] = $course['categoryid'];
699 $course['summaryformat'] = external_validate_format($course['summaryformat']);
701 if (!empty($course['courseformatoptions'])) {
702 foreach ($course['courseformatoptions'] as $option) {
703 $course[$option['name']] = $option['value'];
707 //Note: create_course() core function check shortname, idnumber, category
708 $course['id'] = create_course((object) $course)->id
;
710 $resultcourses[] = array('id' => $course['id'], 'shortname' => $course['shortname']);
713 $transaction->allow_commit();
715 return $resultcourses;
719 * Returns description of method result value
721 * @return external_description
724 public static function create_courses_returns() {
725 return new external_multiple_structure(
726 new external_single_structure(
728 'id' => new external_value(PARAM_INT
, 'course id'),
729 'shortname' => new external_value(PARAM_TEXT
, 'short name'),
738 * @return external_function_parameters
741 public static function update_courses_parameters() {
742 return new external_function_parameters(
744 'courses' => new external_multiple_structure(
745 new external_single_structure(
747 'id' => new external_value(PARAM_INT
, 'ID of the course'),
748 'fullname' => new external_value(PARAM_TEXT
, 'full name', VALUE_OPTIONAL
),
749 'shortname' => new external_value(PARAM_TEXT
, 'course short name', VALUE_OPTIONAL
),
750 'categoryid' => new external_value(PARAM_INT
, 'category id', VALUE_OPTIONAL
),
751 'idnumber' => new external_value(PARAM_RAW
, 'id number', VALUE_OPTIONAL
),
752 'summary' => new external_value(PARAM_RAW
, 'summary', VALUE_OPTIONAL
),
753 'summaryformat' => new external_format_value('summary', VALUE_OPTIONAL
),
754 'format' => new external_value(PARAM_PLUGIN
,
755 'course format: weeks, topics, social, site,..', VALUE_OPTIONAL
),
756 'showgrades' => new external_value(PARAM_INT
,
757 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL
),
758 'newsitems' => new external_value(PARAM_INT
,
759 'number of recent items appearing on the course page', VALUE_OPTIONAL
),
760 'startdate' => new external_value(PARAM_INT
,
761 'timestamp when the course start', VALUE_OPTIONAL
),
762 'numsections' => new external_value(PARAM_INT
,
763 '(deprecated, use courseformatoptions) number of weeks/topics', VALUE_OPTIONAL
),
764 'maxbytes' => new external_value(PARAM_INT
,
765 'largest size of file that can be uploaded into the course', VALUE_OPTIONAL
),
766 'showreports' => new external_value(PARAM_INT
,
767 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL
),
768 'visible' => new external_value(PARAM_INT
,
769 '1: available to student, 0:not available', VALUE_OPTIONAL
),
770 'hiddensections' => new external_value(PARAM_INT
,
771 '(deprecated, use courseformatoptions) How the hidden sections in the course are
772 displayed to students', VALUE_OPTIONAL
),
773 'groupmode' => new external_value(PARAM_INT
, 'no group, separate, visible', VALUE_OPTIONAL
),
774 'groupmodeforce' => new external_value(PARAM_INT
, '1: yes, 0: no', VALUE_OPTIONAL
),
775 'defaultgroupingid' => new external_value(PARAM_INT
, 'default grouping id', VALUE_OPTIONAL
),
776 'enablecompletion' => new external_value(PARAM_INT
,
777 'Enabled, control via completion and activity settings. Disabled,
778 not shown in activity settings.', VALUE_OPTIONAL
),
779 'completionnotify' => new external_value(PARAM_INT
, '1: yes 0: no', VALUE_OPTIONAL
),
780 'lang' => new external_value(PARAM_SAFEDIR
, 'forced course language', VALUE_OPTIONAL
),
781 'forcetheme' => new external_value(PARAM_PLUGIN
, 'name of the force theme', VALUE_OPTIONAL
),
782 'courseformatoptions' => new external_multiple_structure(
783 new external_single_structure(
784 array('name' => new external_value(PARAM_ALPHANUMEXT
, 'course format option name'),
785 'value' => new external_value(PARAM_RAW
, 'course format option value')
787 'additional options for particular course format', VALUE_OPTIONAL
),
789 ), 'courses to update'
798 * @param array $courses
801 public static function update_courses($courses) {
803 require_once($CFG->dirroot
. "/course/lib.php");
806 $params = self
::validate_parameters(self
::update_courses_parameters(),
807 array('courses' => $courses));
809 $availablethemes = core_component
::get_plugin_list('theme');
810 $availablelangs = get_string_manager()->get_list_of_translations();
812 foreach ($params['courses'] as $course) {
813 // Catch any exception while updating course and return as warning to user.
815 // Ensure the current user is allowed to run this function.
816 $context = context_course
::instance($course['id'], MUST_EXIST
);
817 self
::validate_context($context);
819 $oldcourse = course_get_format($course['id'])->get_course();
821 require_capability('moodle/course:update', $context);
823 // Check if user can change category.
824 if (array_key_exists('categoryid', $course) && ($oldcourse->category
!= $course['categoryid'])) {
825 require_capability('moodle/course:changecategory', $context);
826 $course['category'] = $course['categoryid'];
829 // Check if the user can change fullname.
830 if (array_key_exists('fullname', $course) && ($oldcourse->fullname
!= $course['fullname'])) {
831 require_capability('moodle/course:changefullname', $context);
834 // Check if the user can change shortname.
835 if (array_key_exists('shortname', $course) && ($oldcourse->shortname
!= $course['shortname'])) {
836 require_capability('moodle/course:changeshortname', $context);
839 // Check if the user can change the idnumber.
840 if (array_key_exists('idnumber', $course) && ($oldcourse->idnumber
!= $course['idnumber'])) {
841 require_capability('moodle/course:changeidnumber', $context);
844 // Check if user can change summary.
845 if (array_key_exists('summary', $course) && ($oldcourse->summary
!= $course['summary'])) {
846 require_capability('moodle/course:changesummary', $context);
850 if (array_key_exists('summaryformat', $course) && ($oldcourse->summaryformat
!= $course['summaryformat'])) {
851 require_capability('moodle/course:changesummary', $context);
852 $course['summaryformat'] = external_validate_format($course['summaryformat']);
855 // Check if user can change visibility.
856 if (array_key_exists('visible', $course) && ($oldcourse->visible
!= $course['visible'])) {
857 require_capability('moodle/course:visibility', $context);
860 // Make sure lang is valid.
861 if (array_key_exists('lang', $course) && empty($availablelangs[$course['lang']])) {
862 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
865 // Make sure theme is valid.
866 if (array_key_exists('forcetheme', $course)) {
867 if (!empty($CFG->allowcoursethemes
)) {
868 if (empty($availablethemes[$course['forcetheme']])) {
869 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
871 $course['theme'] = $course['forcetheme'];
876 // Make sure completion is enabled before setting it.
877 if (array_key_exists('enabledcompletion', $course) && !completion_info
::is_enabled_for_site()) {
878 $course['enabledcompletion'] = 0;
881 // Make sure maxbytes are less then CFG->maxbytes.
882 if (array_key_exists('maxbytes', $course)) {
883 $course['maxbytes'] = get_max_upload_file_size($CFG->maxbytes
, $course['maxbytes']);
886 if (!empty($course['courseformatoptions'])) {
887 foreach ($course['courseformatoptions'] as $option) {
888 if (isset($option['name']) && isset($option['value'])) {
889 $course[$option['name']] = $option['value'];
894 // Update course if user has all required capabilities.
895 update_course((object) $course);
896 } catch (Exception
$e) {
898 $warning['item'] = 'course';
899 $warning['itemid'] = $course['id'];
900 if ($e instanceof moodle_exception
) {
901 $warning['warningcode'] = $e->errorcode
;
903 $warning['warningcode'] = $e->getCode();
905 $warning['message'] = $e->getMessage();
906 $warnings[] = $warning;
911 $result['warnings'] = $warnings;
916 * Returns description of method result value
918 * @return external_description
921 public static function update_courses_returns() {
922 return new external_single_structure(
924 'warnings' => new external_warnings()
930 * Returns description of method parameters
932 * @return external_function_parameters
935 public static function delete_courses_parameters() {
936 return new external_function_parameters(
938 'courseids' => new external_multiple_structure(new external_value(PARAM_INT
, 'course ID')),
946 * @param array $courseids A list of course ids
949 public static function delete_courses($courseids) {
951 require_once($CFG->dirroot
."/course/lib.php");
953 // Parameter validation.
954 $params = self
::validate_parameters(self
::delete_courses_parameters(), array('courseids'=>$courseids));
958 foreach ($params['courseids'] as $courseid) {
959 $course = $DB->get_record('course', array('id' => $courseid));
961 if ($course === false) {
964 'itemid' => $courseid,
965 'warningcode' => 'unknowncourseidnumber',
966 'message' => 'Unknown course ID ' . $courseid
971 // Check if the context is valid.
972 $coursecontext = context_course
::instance($course->id
);
973 self
::validate_context($coursecontext);
975 // Check if the current user has permission.
976 if (!can_delete_course($courseid)) {
979 'itemid' => $courseid,
980 'warningcode' => 'cannotdeletecourse',
981 'message' => 'You do not have the permission to delete this course' . $courseid
986 if (delete_course($course, false) === false) {
989 'itemid' => $courseid,
990 'warningcode' => 'cannotdeletecategorycourse',
991 'message' => 'Course ' . $courseid . ' failed to be deleted'
997 fix_course_sortorder();
999 return array('warnings' => $warnings);
1003 * Returns description of method result value
1005 * @return external_description
1008 public static function delete_courses_returns() {
1009 return new external_single_structure(
1011 'warnings' => new external_warnings()
1017 * Returns description of method parameters
1019 * @return external_function_parameters
1022 public static function duplicate_course_parameters() {
1023 return new external_function_parameters(
1025 'courseid' => new external_value(PARAM_INT
, 'course to duplicate id'),
1026 'fullname' => new external_value(PARAM_TEXT
, 'duplicated course full name'),
1027 'shortname' => new external_value(PARAM_TEXT
, 'duplicated course short name'),
1028 'categoryid' => new external_value(PARAM_INT
, 'duplicated course category parent'),
1029 'visible' => new external_value(PARAM_INT
, 'duplicated course visible, default to yes', VALUE_DEFAULT
, 1),
1030 'options' => new external_multiple_structure(
1031 new external_single_structure(
1033 'name' => new external_value(PARAM_ALPHAEXT
, 'The backup option name:
1034 "activities" (int) Include course activites (default to 1 that is equal to yes),
1035 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1036 "filters" (int) Include course filters (default to 1 that is equal to yes),
1037 "users" (int) Include users (default to 0 that is equal to no),
1038 "role_assignments" (int) Include role assignments (default to 0 that is equal to no),
1039 "comments" (int) Include user comments (default to 0 that is equal to no),
1040 "userscompletion" (int) Include user course completion information (default to 0 that is equal to no),
1041 "logs" (int) Include course logs (default to 0 that is equal to no),
1042 "grade_histories" (int) Include histories (default to 0 that is equal to no)'
1044 'value' => new external_value(PARAM_RAW
, 'the value for the option 1 (yes) or 0 (no)'
1047 ), VALUE_DEFAULT
, array()
1054 * Duplicate a course
1056 * @param int $courseid
1057 * @param string $fullname Duplicated course fullname
1058 * @param string $shortname Duplicated course shortname
1059 * @param int $categoryid Duplicated course parent category id
1060 * @param int $visible Duplicated course availability
1061 * @param array $options List of backup options
1062 * @return array New course info
1065 public static function duplicate_course($courseid, $fullname, $shortname, $categoryid, $visible = 1, $options = array()) {
1066 global $CFG, $USER, $DB;
1067 require_once($CFG->dirroot
. '/backup/util/includes/backup_includes.php');
1068 require_once($CFG->dirroot
. '/backup/util/includes/restore_includes.php');
1070 // Parameter validation.
1071 $params = self
::validate_parameters(
1072 self
::duplicate_course_parameters(),
1074 'courseid' => $courseid,
1075 'fullname' => $fullname,
1076 'shortname' => $shortname,
1077 'categoryid' => $categoryid,
1078 'visible' => $visible,
1079 'options' => $options
1083 // Context validation.
1085 if (! ($course = $DB->get_record('course', array('id'=>$params['courseid'])))) {
1086 throw new moodle_exception('invalidcourseid', 'error');
1089 // Category where duplicated course is going to be created.
1090 $categorycontext = context_coursecat
::instance($params['categoryid']);
1091 self
::validate_context($categorycontext);
1093 // Course to be duplicated.
1094 $coursecontext = context_course
::instance($course->id
);
1095 self
::validate_context($coursecontext);
1097 $backupdefaults = array(
1102 'role_assignments' => 0,
1104 'userscompletion' => 0,
1106 'grade_histories' => 0
1109 $backupsettings = array();
1110 // Check for backup and restore options.
1111 if (!empty($params['options'])) {
1112 foreach ($params['options'] as $option) {
1114 // Strict check for a correct value (allways 1 or 0, true or false).
1115 $value = clean_param($option['value'], PARAM_INT
);
1117 if ($value !== 0 and $value !== 1) {
1118 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1121 if (!isset($backupdefaults[$option['name']])) {
1122 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1125 $backupsettings[$option['name']] = $value;
1129 // Capability checking.
1131 // The backup controller check for this currently, this may be redundant.
1132 require_capability('moodle/course:create', $categorycontext);
1133 require_capability('moodle/restore:restorecourse', $categorycontext);
1134 require_capability('moodle/backup:backupcourse', $coursecontext);
1136 if (!empty($backupsettings['users'])) {
1137 require_capability('moodle/backup:userinfo', $coursecontext);
1138 require_capability('moodle/restore:userinfo', $categorycontext);
1141 // Check if the shortname is used.
1142 if ($foundcourses = $DB->get_records('course', array('shortname'=>$shortname))) {
1143 foreach ($foundcourses as $foundcourse) {
1144 $foundcoursenames[] = $foundcourse->fullname
;
1147 $foundcoursenamestring = implode(',', $foundcoursenames);
1148 throw new moodle_exception('shortnametaken', '', '', $foundcoursenamestring);
1151 // Backup the course.
1153 $bc = new backup_controller(backup
::TYPE_1COURSE
, $course->id
, backup
::FORMAT_MOODLE
,
1154 backup
::INTERACTIVE_NO
, backup
::MODE_SAMESITE
, $USER->id
);
1156 foreach ($backupsettings as $name => $value) {
1157 $bc->get_plan()->get_setting($name)->set_value($value);
1160 $backupid = $bc->get_backupid();
1161 $backupbasepath = $bc->get_plan()->get_basepath();
1163 $bc->execute_plan();
1164 $results = $bc->get_results();
1165 $file = $results['backup_destination'];
1169 // Restore the backup immediately.
1171 // Check if we need to unzip the file because the backup temp dir does not contains backup files.
1172 if (!file_exists($backupbasepath . "/moodle_backup.xml")) {
1173 $file->extract_to_pathname(get_file_packer('application/vnd.moodle.backup'), $backupbasepath);
1176 // Create new course.
1177 $newcourseid = restore_dbops
::create_new_course($params['fullname'], $params['shortname'], $params['categoryid']);
1179 $rc = new restore_controller($backupid, $newcourseid,
1180 backup
::INTERACTIVE_NO
, backup
::MODE_SAMESITE
, $USER->id
, backup
::TARGET_NEW_COURSE
);
1182 foreach ($backupsettings as $name => $value) {
1183 $setting = $rc->get_plan()->get_setting($name);
1184 if ($setting->get_status() == backup_setting
::NOT_LOCKED
) {
1185 $setting->set_value($value);
1189 if (!$rc->execute_precheck()) {
1190 $precheckresults = $rc->get_precheck_results();
1191 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1192 if (empty($CFG->keeptempdirectoriesonbackup
)) {
1193 fulldelete($backupbasepath);
1198 foreach ($precheckresults['errors'] as $error) {
1199 $errorinfo .= $error;
1202 if (array_key_exists('warnings', $precheckresults)) {
1203 foreach ($precheckresults['warnings'] as $warning) {
1204 $errorinfo .= $warning;
1208 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1212 $rc->execute_plan();
1215 $course = $DB->get_record('course', array('id' => $newcourseid), '*', MUST_EXIST
);
1216 $course->fullname
= $params['fullname'];
1217 $course->shortname
= $params['shortname'];
1218 $course->visible
= $params['visible'];
1220 // Set shortname and fullname back.
1221 $DB->update_record('course', $course);
1223 if (empty($CFG->keeptempdirectoriesonbackup
)) {
1224 fulldelete($backupbasepath);
1227 // Delete the course backup file created by this WebService. Originally located in the course backups area.
1230 return array('id' => $course->id
, 'shortname' => $course->shortname
);
1234 * Returns description of method result value
1236 * @return external_description
1239 public static function duplicate_course_returns() {
1240 return new external_single_structure(
1242 'id' => new external_value(PARAM_INT
, 'course id'),
1243 'shortname' => new external_value(PARAM_TEXT
, 'short name'),
1249 * Returns description of method parameters for import_course
1251 * @return external_function_parameters
1254 public static function import_course_parameters() {
1255 return new external_function_parameters(
1257 'importfrom' => new external_value(PARAM_INT
, 'the id of the course we are importing from'),
1258 'importto' => new external_value(PARAM_INT
, 'the id of the course we are importing to'),
1259 'deletecontent' => new external_value(PARAM_INT
, 'whether to delete the course content where we are importing to (default to 0 = No)', VALUE_DEFAULT
, 0),
1260 'options' => new external_multiple_structure(
1261 new external_single_structure(
1263 'name' => new external_value(PARAM_ALPHA
, 'The backup option name:
1264 "activities" (int) Include course activites (default to 1 that is equal to yes),
1265 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1266 "filters" (int) Include course filters (default to 1 that is equal to yes)'
1268 'value' => new external_value(PARAM_RAW
, 'the value for the option 1 (yes) or 0 (no)'
1271 ), VALUE_DEFAULT
, array()
1280 * @param int $importfrom The id of the course we are importing from
1281 * @param int $importto The id of the course we are importing to
1282 * @param bool $deletecontent Whether to delete the course we are importing to content
1283 * @param array $options List of backup options
1287 public static function import_course($importfrom, $importto, $deletecontent = 0, $options = array()) {
1288 global $CFG, $USER, $DB;
1289 require_once($CFG->dirroot
. '/backup/util/includes/backup_includes.php');
1290 require_once($CFG->dirroot
. '/backup/util/includes/restore_includes.php');
1292 // Parameter validation.
1293 $params = self
::validate_parameters(
1294 self
::import_course_parameters(),
1296 'importfrom' => $importfrom,
1297 'importto' => $importto,
1298 'deletecontent' => $deletecontent,
1299 'options' => $options
1303 if ($params['deletecontent'] !== 0 and $params['deletecontent'] !== 1) {
1304 throw new moodle_exception('invalidextparam', 'webservice', '', $params['deletecontent']);
1307 // Context validation.
1309 if (! ($importfrom = $DB->get_record('course', array('id'=>$params['importfrom'])))) {
1310 throw new moodle_exception('invalidcourseid', 'error');
1313 if (! ($importto = $DB->get_record('course', array('id'=>$params['importto'])))) {
1314 throw new moodle_exception('invalidcourseid', 'error');
1317 $importfromcontext = context_course
::instance($importfrom->id
);
1318 self
::validate_context($importfromcontext);
1320 $importtocontext = context_course
::instance($importto->id
);
1321 self
::validate_context($importtocontext);
1323 $backupdefaults = array(
1329 $backupsettings = array();
1331 // Check for backup and restore options.
1332 if (!empty($params['options'])) {
1333 foreach ($params['options'] as $option) {
1335 // Strict check for a correct value (allways 1 or 0, true or false).
1336 $value = clean_param($option['value'], PARAM_INT
);
1338 if ($value !== 0 and $value !== 1) {
1339 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1342 if (!isset($backupdefaults[$option['name']])) {
1343 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1346 $backupsettings[$option['name']] = $value;
1350 // Capability checking.
1352 require_capability('moodle/backup:backuptargetimport', $importfromcontext);
1353 require_capability('moodle/restore:restoretargetimport', $importtocontext);
1355 $bc = new backup_controller(backup
::TYPE_1COURSE
, $importfrom->id
, backup
::FORMAT_MOODLE
,
1356 backup
::INTERACTIVE_NO
, backup
::MODE_IMPORT
, $USER->id
);
1358 foreach ($backupsettings as $name => $value) {
1359 $bc->get_plan()->get_setting($name)->set_value($value);
1362 $backupid = $bc->get_backupid();
1363 $backupbasepath = $bc->get_plan()->get_basepath();
1365 $bc->execute_plan();
1368 // Restore the backup immediately.
1370 // Check if we must delete the contents of the destination course.
1371 if ($params['deletecontent']) {
1372 $restoretarget = backup
::TARGET_EXISTING_DELETING
;
1374 $restoretarget = backup
::TARGET_EXISTING_ADDING
;
1377 $rc = new restore_controller($backupid, $importto->id
,
1378 backup
::INTERACTIVE_NO
, backup
::MODE_IMPORT
, $USER->id
, $restoretarget);
1380 foreach ($backupsettings as $name => $value) {
1381 $rc->get_plan()->get_setting($name)->set_value($value);
1384 if (!$rc->execute_precheck()) {
1385 $precheckresults = $rc->get_precheck_results();
1386 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1387 if (empty($CFG->keeptempdirectoriesonbackup
)) {
1388 fulldelete($backupbasepath);
1393 foreach ($precheckresults['errors'] as $error) {
1394 $errorinfo .= $error;
1397 if (array_key_exists('warnings', $precheckresults)) {
1398 foreach ($precheckresults['warnings'] as $warning) {
1399 $errorinfo .= $warning;
1403 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1406 if ($restoretarget == backup
::TARGET_EXISTING_DELETING
) {
1407 restore_dbops
::delete_course_content($importto->id
);
1411 $rc->execute_plan();
1414 if (empty($CFG->keeptempdirectoriesonbackup
)) {
1415 fulldelete($backupbasepath);
1422 * Returns description of method result value
1424 * @return external_description
1427 public static function import_course_returns() {
1432 * Returns description of method parameters
1434 * @return external_function_parameters
1437 public static function get_categories_parameters() {
1438 return new external_function_parameters(
1440 'criteria' => new external_multiple_structure(
1441 new external_single_structure(
1443 'key' => new external_value(PARAM_ALPHA
,
1444 'The category column to search, expected keys (value format) are:'.
1445 '"id" (int) the category id,'.
1446 '"name" (string) the category name,'.
1447 '"parent" (int) the parent category id,'.
1448 '"idnumber" (string) category idnumber'.
1449 ' - user must have \'moodle/category:manage\' to search on idnumber,'.
1450 '"visible" (int) whether the returned categories must be visible or hidden. If the key is not passed,
1451 then the function return all categories that the user can see.'.
1452 ' - user must have \'moodle/category:manage\' or \'moodle/category:viewhiddencategories\' to search on visible,'.
1453 '"theme" (string) only return the categories having this theme'.
1454 ' - user must have \'moodle/category:manage\' to search on theme'),
1455 'value' => new external_value(PARAM_RAW
, 'the value to match')
1457 ), 'criteria', VALUE_DEFAULT
, array()
1459 'addsubcategories' => new external_value(PARAM_BOOL
, 'return the sub categories infos
1460 (1 - default) otherwise only the category info (0)', VALUE_DEFAULT
, 1)
1468 * @param array $criteria Criteria to match the results
1469 * @param booln $addsubcategories obtain only the category (false) or its subcategories (true - default)
1470 * @return array list of categories
1473 public static function get_categories($criteria = array(), $addsubcategories = true) {
1475 require_once($CFG->dirroot
. "/course/lib.php");
1477 // Validate parameters.
1478 $params = self
::validate_parameters(self
::get_categories_parameters(),
1479 array('criteria' => $criteria, 'addsubcategories' => $addsubcategories));
1481 // Retrieve the categories.
1482 $categories = array();
1483 if (!empty($params['criteria'])) {
1485 $conditions = array();
1487 foreach ($params['criteria'] as $crit) {
1488 $key = trim($crit['key']);
1490 // Trying to avoid duplicate keys.
1491 if (!isset($conditions[$key])) {
1493 $context = context_system
::instance();
1497 $value = clean_param($crit['value'], PARAM_INT
);
1501 if (has_capability('moodle/category:manage', $context)) {
1502 $value = clean_param($crit['value'], PARAM_RAW
);
1504 // We must throw an exception.
1505 // Otherwise the dev client would think no idnumber exists.
1506 throw new moodle_exception('criteriaerror',
1507 'webservice', '', null,
1508 'You don\'t have the permissions to search on the "idnumber" field.');
1513 $value = clean_param($crit['value'], PARAM_TEXT
);
1517 $value = clean_param($crit['value'], PARAM_INT
);
1521 if (has_capability('moodle/category:manage', $context)
1522 or has_capability('moodle/category:viewhiddencategories',
1523 context_system
::instance())) {
1524 $value = clean_param($crit['value'], PARAM_INT
);
1526 throw new moodle_exception('criteriaerror',
1527 'webservice', '', null,
1528 'You don\'t have the permissions to search on the "visible" field.');
1533 if (has_capability('moodle/category:manage', $context)) {
1534 $value = clean_param($crit['value'], PARAM_THEME
);
1536 throw new moodle_exception('criteriaerror',
1537 'webservice', '', null,
1538 'You don\'t have the permissions to search on the "theme" field.');
1543 throw new moodle_exception('criteriaerror',
1544 'webservice', '', null,
1545 'You can not search on this criteria: ' . $key);
1548 if (isset($value)) {
1549 $conditions[$key] = $crit['value'];
1550 $wheres[] = $key . " = :" . $key;
1555 if (!empty($wheres)) {
1556 $wheres = implode(" AND ", $wheres);
1558 $categories = $DB->get_records_select('course_categories', $wheres, $conditions);
1560 // Retrieve its sub subcategories (all levels).
1561 if ($categories and !empty($params['addsubcategories'])) {
1562 $newcategories = array();
1564 // Check if we required visible/theme checks.
1565 $additionalselect = '';
1566 $additionalparams = array();
1567 if (isset($conditions['visible'])) {
1568 $additionalselect .= ' AND visible = :visible';
1569 $additionalparams['visible'] = $conditions['visible'];
1571 if (isset($conditions['theme'])) {
1572 $additionalselect .= ' AND theme= :theme';
1573 $additionalparams['theme'] = $conditions['theme'];
1576 foreach ($categories as $category) {
1577 $sqlselect = $DB->sql_like('path', ':path') . $additionalselect;
1578 $sqlparams = array('path' => $category->path
.'/%') +
$additionalparams; // It will NOT include the specified category.
1579 $subcategories = $DB->get_records_select('course_categories', $sqlselect, $sqlparams);
1580 $newcategories = $newcategories +
$subcategories; // Both arrays have integer as keys.
1582 $categories = $categories +
$newcategories;
1587 // Retrieve all categories in the database.
1588 $categories = $DB->get_records('course_categories');
1591 // The not returned categories. key => category id, value => reason of exclusion.
1592 $excludedcats = array();
1594 // The returned categories.
1595 $categoriesinfo = array();
1597 // We need to sort the categories by path.
1598 // The parent cats need to be checked by the algo first.
1599 usort($categories, "core_course_external::compare_categories_by_path");
1601 foreach ($categories as $category) {
1603 // Check if the category is a child of an excluded category, if yes exclude it too (excluded => do not return).
1604 $parents = explode('/', $category->path
);
1605 unset($parents[0]); // First key is always empty because path start with / => /1/2/4.
1606 foreach ($parents as $parentid) {
1607 // Note: when the parent exclusion was due to the context,
1608 // the sub category could still be returned.
1609 if (isset($excludedcats[$parentid]) and $excludedcats[$parentid] != 'context') {
1610 $excludedcats[$category->id
] = 'parent';
1614 // Check category depth is <= maxdepth (do not check for user who can manage categories).
1615 if ((!empty($CFG->maxcategorydepth
) && count($parents) > $CFG->maxcategorydepth
)
1616 and !has_capability('moodle/category:manage', $context)) {
1617 $excludedcats[$category->id
] = 'depth';
1620 // Check the user can use the category context.
1621 $context = context_coursecat
::instance($category->id
);
1623 self
::validate_context($context);
1624 } catch (Exception
$e) {
1625 $excludedcats[$category->id
] = 'context';
1627 // If it was the requested category then throw an exception.
1628 if (isset($params['categoryid']) && $category->id
== $params['categoryid']) {
1629 $exceptionparam = new stdClass();
1630 $exceptionparam->message
= $e->getMessage();
1631 $exceptionparam->catid
= $category->id
;
1632 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
1636 // Return the category information.
1637 if (!isset($excludedcats[$category->id
])) {
1639 // Final check to see if the category is visible to the user.
1640 if ($category->visible
1641 or has_capability('moodle/category:viewhiddencategories', context_system
::instance())
1642 or has_capability('moodle/category:manage', $context)) {
1644 $categoryinfo = array();
1645 $categoryinfo['id'] = $category->id
;
1646 $categoryinfo['name'] = $category->name
;
1647 list($categoryinfo['description'], $categoryinfo['descriptionformat']) =
1648 external_format_text($category->description
, $category->descriptionformat
,
1649 $context->id
, 'coursecat', 'description', null);
1650 $categoryinfo['parent'] = $category->parent
;
1651 $categoryinfo['sortorder'] = $category->sortorder
;
1652 $categoryinfo['coursecount'] = $category->coursecount
;
1653 $categoryinfo['depth'] = $category->depth
;
1654 $categoryinfo['path'] = $category->path
;
1656 // Some fields only returned for admin.
1657 if (has_capability('moodle/category:manage', $context)) {
1658 $categoryinfo['idnumber'] = $category->idnumber
;
1659 $categoryinfo['visible'] = $category->visible
;
1660 $categoryinfo['visibleold'] = $category->visibleold
;
1661 $categoryinfo['timemodified'] = $category->timemodified
;
1662 $categoryinfo['theme'] = $category->theme
;
1665 $categoriesinfo[] = $categoryinfo;
1667 $excludedcats[$category->id
] = 'visibility';
1672 // Sorting the resulting array so it looks a bit better for the client developer.
1673 usort($categoriesinfo, "core_course_external::compare_categories_by_sortorder");
1675 return $categoriesinfo;
1679 * Sort categories array by path
1680 * private function: only used by get_categories
1682 * @param array $category1
1683 * @param array $category2
1684 * @return int result of strcmp
1687 private static function compare_categories_by_path($category1, $category2) {
1688 return strcmp($category1->path
, $category2->path
);
1692 * Sort categories array by sortorder
1693 * private function: only used by get_categories
1695 * @param array $category1
1696 * @param array $category2
1697 * @return int result of strcmp
1700 private static function compare_categories_by_sortorder($category1, $category2) {
1701 return strcmp($category1['sortorder'], $category2['sortorder']);
1705 * Returns description of method result value
1707 * @return external_description
1710 public static function get_categories_returns() {
1711 return new external_multiple_structure(
1712 new external_single_structure(
1714 'id' => new external_value(PARAM_INT
, 'category id'),
1715 'name' => new external_value(PARAM_TEXT
, 'category name'),
1716 'idnumber' => new external_value(PARAM_RAW
, 'category id number', VALUE_OPTIONAL
),
1717 'description' => new external_value(PARAM_RAW
, 'category description'),
1718 'descriptionformat' => new external_format_value('description'),
1719 'parent' => new external_value(PARAM_INT
, 'parent category id'),
1720 'sortorder' => new external_value(PARAM_INT
, 'category sorting order'),
1721 'coursecount' => new external_value(PARAM_INT
, 'number of courses in this category'),
1722 'visible' => new external_value(PARAM_INT
, '1: available, 0:not available', VALUE_OPTIONAL
),
1723 'visibleold' => new external_value(PARAM_INT
, '1: available, 0:not available', VALUE_OPTIONAL
),
1724 'timemodified' => new external_value(PARAM_INT
, 'timestamp', VALUE_OPTIONAL
),
1725 'depth' => new external_value(PARAM_INT
, 'category depth'),
1726 'path' => new external_value(PARAM_TEXT
, 'category path'),
1727 'theme' => new external_value(PARAM_THEME
, 'category theme', VALUE_OPTIONAL
),
1728 ), 'List of categories'
1734 * Returns description of method parameters
1736 * @return external_function_parameters
1739 public static function create_categories_parameters() {
1740 return new external_function_parameters(
1742 'categories' => new external_multiple_structure(
1743 new external_single_structure(
1745 'name' => new external_value(PARAM_TEXT
, 'new category name'),
1746 'parent' => new external_value(PARAM_INT
,
1747 'the parent category id inside which the new category will be created
1748 - set to 0 for a root category',
1750 'idnumber' => new external_value(PARAM_RAW
,
1751 'the new category idnumber', VALUE_OPTIONAL
),
1752 'description' => new external_value(PARAM_RAW
,
1753 'the new category description', VALUE_OPTIONAL
),
1754 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT
),
1755 'theme' => new external_value(PARAM_THEME
,
1756 'the new category theme. This option must be enabled on moodle',
1768 * @param array $categories - see create_categories_parameters() for the array structure
1769 * @return array - see create_categories_returns() for the array structure
1772 public static function create_categories($categories) {
1774 require_once($CFG->libdir
. "/coursecatlib.php");
1776 $params = self
::validate_parameters(self
::create_categories_parameters(),
1777 array('categories' => $categories));
1779 $transaction = $DB->start_delegated_transaction();
1781 $createdcategories = array();
1782 foreach ($params['categories'] as $category) {
1783 if ($category['parent']) {
1784 if (!$DB->record_exists('course_categories', array('id' => $category['parent']))) {
1785 throw new moodle_exception('unknowcategory');
1787 $context = context_coursecat
::instance($category['parent']);
1789 $context = context_system
::instance();
1791 self
::validate_context($context);
1792 require_capability('moodle/category:manage', $context);
1794 // this will validate format and throw an exception if there are errors
1795 external_validate_format($category['descriptionformat']);
1797 $newcategory = coursecat
::create($category);
1799 $createdcategories[] = array('id' => $newcategory->id
, 'name' => $newcategory->name
);
1802 $transaction->allow_commit();
1804 return $createdcategories;
1808 * Returns description of method parameters
1810 * @return external_function_parameters
1813 public static function create_categories_returns() {
1814 return new external_multiple_structure(
1815 new external_single_structure(
1817 'id' => new external_value(PARAM_INT
, 'new category id'),
1818 'name' => new external_value(PARAM_TEXT
, 'new category name'),
1825 * Returns description of method parameters
1827 * @return external_function_parameters
1830 public static function update_categories_parameters() {
1831 return new external_function_parameters(
1833 'categories' => new external_multiple_structure(
1834 new external_single_structure(
1836 'id' => new external_value(PARAM_INT
, 'course id'),
1837 'name' => new external_value(PARAM_TEXT
, 'category name', VALUE_OPTIONAL
),
1838 'idnumber' => new external_value(PARAM_RAW
, 'category id number', VALUE_OPTIONAL
),
1839 'parent' => new external_value(PARAM_INT
, 'parent category id', VALUE_OPTIONAL
),
1840 'description' => new external_value(PARAM_RAW
, 'category description', VALUE_OPTIONAL
),
1841 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT
),
1842 'theme' => new external_value(PARAM_THEME
,
1843 'the category theme. This option must be enabled on moodle', VALUE_OPTIONAL
),
1854 * @param array $categories The list of categories to update
1858 public static function update_categories($categories) {
1860 require_once($CFG->libdir
. "/coursecatlib.php");
1862 // Validate parameters.
1863 $params = self
::validate_parameters(self
::update_categories_parameters(), array('categories' => $categories));
1865 $transaction = $DB->start_delegated_transaction();
1867 foreach ($params['categories'] as $cat) {
1868 $category = coursecat
::get($cat['id']);
1870 $categorycontext = context_coursecat
::instance($cat['id']);
1871 self
::validate_context($categorycontext);
1872 require_capability('moodle/category:manage', $categorycontext);
1874 // this will throw an exception if descriptionformat is not valid
1875 external_validate_format($cat['descriptionformat']);
1877 $category->update($cat);
1880 $transaction->allow_commit();
1884 * Returns description of method result value
1886 * @return external_description
1889 public static function update_categories_returns() {
1894 * Returns description of method parameters
1896 * @return external_function_parameters
1899 public static function delete_categories_parameters() {
1900 return new external_function_parameters(
1902 'categories' => new external_multiple_structure(
1903 new external_single_structure(
1905 'id' => new external_value(PARAM_INT
, 'category id to delete'),
1906 'newparent' => new external_value(PARAM_INT
,
1907 'the parent category to move the contents to, if specified', VALUE_OPTIONAL
),
1908 'recursive' => new external_value(PARAM_BOOL
, '1: recursively delete all contents inside this
1909 category, 0 (default): move contents to newparent or current parent category (except if parent is root)', VALUE_DEFAULT
, 0)
1920 * @param array $categories A list of category ids
1924 public static function delete_categories($categories) {
1926 require_once($CFG->dirroot
. "/course/lib.php");
1927 require_once($CFG->libdir
. "/coursecatlib.php");
1929 // Validate parameters.
1930 $params = self
::validate_parameters(self
::delete_categories_parameters(), array('categories' => $categories));
1932 $transaction = $DB->start_delegated_transaction();
1934 foreach ($params['categories'] as $category) {
1935 $deletecat = coursecat
::get($category['id'], MUST_EXIST
);
1936 $context = context_coursecat
::instance($deletecat->id
);
1937 require_capability('moodle/category:manage', $context);
1938 self
::validate_context($context);
1939 self
::validate_context(get_category_or_system_context($deletecat->parent
));
1941 if ($category['recursive']) {
1942 // If recursive was specified, then we recursively delete the category's contents.
1943 if ($deletecat->can_delete_full()) {
1944 $deletecat->delete_full(false);
1946 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
1949 // In this situation, we don't delete the category's contents, we either move it to newparent or parent.
1950 // If the parent is the root, moving is not supported (because a course must always be inside a category).
1951 // We must move to an existing category.
1952 if (!empty($category['newparent'])) {
1953 $newparentcat = coursecat
::get($category['newparent']);
1955 $newparentcat = coursecat
::get($deletecat->parent
);
1958 // This operation is not allowed. We must move contents to an existing category.
1959 if (!$newparentcat->id
) {
1960 throw new moodle_exception('movecatcontentstoroot');
1963 self
::validate_context(context_coursecat
::instance($newparentcat->id
));
1964 if ($deletecat->can_move_content_to($newparentcat->id
)) {
1965 $deletecat->delete_move($newparentcat->id
, false);
1967 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
1972 $transaction->allow_commit();
1976 * Returns description of method parameters
1978 * @return external_function_parameters
1981 public static function delete_categories_returns() {
1986 * Describes the parameters for delete_modules.
1988 * @return external_external_function_parameters
1991 public static function delete_modules_parameters() {
1992 return new external_function_parameters (
1994 'cmids' => new external_multiple_structure(new external_value(PARAM_INT
, 'course module ID',
1995 VALUE_REQUIRED
, '', NULL_NOT_ALLOWED
), 'Array of course module IDs'),
2001 * Deletes a list of provided module instances.
2003 * @param array $cmids the course module ids
2006 public static function delete_modules($cmids) {
2009 // Require course file containing the course delete module function.
2010 require_once($CFG->dirroot
. "/course/lib.php");
2012 // Clean the parameters.
2013 $params = self
::validate_parameters(self
::delete_modules_parameters(), array('cmids' => $cmids));
2015 // Keep track of the course ids we have performed a capability check on to avoid repeating.
2016 $arrcourseschecked = array();
2018 foreach ($params['cmids'] as $cmid) {
2019 // Get the course module.
2020 $cm = $DB->get_record('course_modules', array('id' => $cmid), '*', MUST_EXIST
);
2022 // Check if we have not yet confirmed they have permission in this course.
2023 if (!in_array($cm->course
, $arrcourseschecked)) {
2024 // Ensure the current user has required permission in this course.
2025 $context = context_course
::instance($cm->course
);
2026 self
::validate_context($context);
2027 // Add to the array.
2028 $arrcourseschecked[] = $cm->course
;
2031 // Ensure they can delete this module.
2032 $modcontext = context_module
::instance($cm->id
);
2033 require_capability('moodle/course:manageactivities', $modcontext);
2035 // Delete the module.
2036 course_delete_module($cm->id
);
2041 * Describes the delete_modules return value.
2043 * @return external_single_structure
2046 public static function delete_modules_returns() {
2051 * Returns description of method parameters
2053 * @return external_function_parameters
2056 public static function view_course_parameters() {
2057 return new external_function_parameters(
2059 'courseid' => new external_value(PARAM_INT
, 'id of the course'),
2060 'sectionnumber' => new external_value(PARAM_INT
, 'section number', VALUE_DEFAULT
, 0)
2066 * Simulate the view.php web interface page, logging events, completion, etc...
2068 * @param int $courseid id of course
2069 * @param int $sectionnumber sectionnumber (0, 1, 2...)
2070 * @return array of warnings and status result
2072 * @throws moodle_exception
2074 public static function view_course($courseid, $sectionnumber = 0) {
2076 require_once($CFG->dirroot
. "/course/lib.php");
2078 $params = self
::validate_parameters(self
::view_course_parameters(),
2080 'courseid' => $courseid,
2081 'sectionnumber' => $sectionnumber
2084 $warnings = array();
2086 $course = get_course($params['courseid']);
2087 $context = context_course
::instance($course->id
);
2088 self
::validate_context($context);
2090 if (!empty($params['sectionnumber'])) {
2092 // Get section details and check it exists.
2093 $modinfo = get_fast_modinfo($course);
2094 $coursesection = $modinfo->get_section_info($params['sectionnumber'], MUST_EXIST
);
2096 // Check user is allowed to see it.
2097 if (!$coursesection->uservisible
) {
2098 require_capability('moodle/course:viewhiddensections', $context);
2102 course_view($context, $params['sectionnumber']);
2105 $result['status'] = true;
2106 $result['warnings'] = $warnings;
2111 * Returns description of method result value
2113 * @return external_description
2116 public static function view_course_returns() {
2117 return new external_single_structure(
2119 'status' => new external_value(PARAM_BOOL
, 'status: true if success'),
2120 'warnings' => new external_warnings()
2128 * Deprecated course external functions
2130 * @package core_course
2131 * @copyright 2009 Petr Skodak
2132 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2134 * @deprecated Moodle 2.2 MDL-29106 - Please do not use this class any more.
2135 * @see core_course_external
2137 class moodle_course_external
extends external_api
{
2140 * Returns description of method parameters
2142 * @return external_function_parameters
2144 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
2145 * @see core_course_external::get_courses_parameters()
2147 public static function get_courses_parameters() {
2148 return core_course_external
::get_courses_parameters();
2154 * @param array $options
2157 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
2158 * @see core_course_external::get_courses()
2160 public static function get_courses($options) {
2161 return core_course_external
::get_courses($options);
2165 * Returns description of method result value
2167 * @return external_description
2169 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
2170 * @see core_course_external::get_courses_returns()
2172 public static function get_courses_returns() {
2173 return core_course_external
::get_courses_returns();
2177 * Marking the method as deprecated.
2181 public static function get_courses_is_deprecated() {
2186 * Returns description of method parameters
2188 * @return external_function_parameters
2190 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
2191 * @see core_course_external::create_courses_parameters()
2193 public static function create_courses_parameters() {
2194 return core_course_external
::create_courses_parameters();
2200 * @param array $courses
2201 * @return array courses (id and shortname only)
2203 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
2204 * @see core_course_external::create_courses()
2206 public static function create_courses($courses) {
2207 return core_course_external
::create_courses($courses);
2211 * Returns description of method result value
2213 * @return external_description
2215 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
2216 * @see core_course_external::create_courses_returns()
2218 public static function create_courses_returns() {
2219 return core_course_external
::create_courses_returns();
2223 * Marking the method as deprecated.
2227 public static function create_courses_is_deprecated() {