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
48 public static function get_course_contents_parameters() {
49 return new external_function_parameters(
50 array('courseid' => new external_value(PARAM_INT
, 'course id'),
51 'options' => new external_multiple_structure (
52 new external_single_structure(
53 array('name' => new external_value(PARAM_ALPHANUM
, 'option name'),
54 'value' => new external_value(PARAM_RAW
, 'the value of the option, this param is personaly validated in the external function.')
56 ), 'Options, not used yet, might be used in later version', VALUE_DEFAULT
, array())
64 * @param int $courseid course id
65 * @param array $options These options are not used yet, might be used in later version
69 public static function get_course_contents($courseid, $options = array()) {
71 require_once($CFG->dirroot
. "/course/lib.php");
74 $params = self
::validate_parameters(self
::get_course_contents_parameters(),
75 array('courseid' => $courseid, 'options' => $options));
78 $course = $DB->get_record('course', array('id' => $params['courseid']), '*', MUST_EXIST
);
80 //check course format exist
81 if (!file_exists($CFG->dirroot
. '/course/format/' . $course->format
. '/lib.php')) {
82 throw new moodle_exception('cannotgetcoursecontents', 'webservice', '', null, get_string('courseformatnotfound', 'error', '', $course->format
));
84 require_once($CFG->dirroot
. '/course/format/' . $course->format
. '/lib.php');
87 // now security checks
88 $context = context_course
::instance($course->id
, IGNORE_MISSING
);
90 self
::validate_context($context);
91 } catch (Exception
$e) {
92 $exceptionparam = new stdClass();
93 $exceptionparam->message
= $e->getMessage();
94 $exceptionparam->courseid
= $course->id
;
95 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
98 $canupdatecourse = has_capability('moodle/course:update', $context);
100 //create return value
101 $coursecontents = array();
103 if ($canupdatecourse or $course->visible
104 or has_capability('moodle/course:viewhiddencourses', $context)) {
107 $modinfo = get_fast_modinfo($course);
108 $sections = $modinfo->get_section_info_all();
110 //for each sections (first displayed to last displayed)
111 $modinfosections = $modinfo->get_sections();
112 foreach ($sections as $key => $section) {
114 if (!$section->uservisible
) {
118 // reset $sectioncontents
119 $sectionvalues = array();
120 $sectionvalues['id'] = $section->id
;
121 $sectionvalues['name'] = get_section_name($course, $section);
122 $sectionvalues['visible'] = $section->visible
;
123 list($sectionvalues['summary'], $sectionvalues['summaryformat']) =
124 external_format_text($section->summary
, $section->summaryformat
,
125 $context->id
, 'course', 'section', $section->id
);
126 $sectioncontents = array();
128 //for each module of the section
129 if (!empty($modinfosections[$section->section
])) {
130 foreach ($modinfosections[$section->section
] as $cmid) {
131 $cm = $modinfo->cms
[$cmid];
133 // stop here if the module is not visible to the user
134 if (!$cm->uservisible
) {
140 //common info (for people being able to see the module or availability dates)
141 $module['id'] = $cm->id
;
142 $module['name'] = format_string($cm->name
, true);
143 $module['instance'] = $cm->instance
;
144 $module['modname'] = $cm->modname
;
145 $module['modplural'] = $cm->modplural
;
146 $module['modicon'] = $cm->get_icon_url()->out(false);
147 $module['indent'] = $cm->indent
;
149 $modcontext = context_module
::instance($cm->id
);
151 if (!empty($cm->showdescription
) or $cm->modname
== 'label') {
152 // We want to use the external format. However from reading get_formatted_content(), $cm->content format is always FORMAT_HTML.
153 list($module['description'], $descriptionformat) = external_format_text($cm->content
,
154 FORMAT_HTML
, $modcontext->id
, $cm->modname
, 'intro', $cm->id
);
159 if ($url) { //labels don't have url
160 $module['url'] = $url->out(false);
163 $canviewhidden = has_capability('moodle/course:viewhiddenactivities',
164 context_module
::instance($cm->id
));
165 //user that can view hidden module should know about the visibility
166 $module['visible'] = $cm->visible
;
168 // Availability date (also send to user who can see hidden module).
169 if ($CFG->enableavailability
&& ($canviewhidden ||
$canupdatecourse)) {
170 $module['availability'] = $cm->availability
;
173 $baseurl = 'webservice/pluginfile.php';
175 //call $modulename_export_contents
176 //(each module callback take care about checking the capabilities)
177 require_once($CFG->dirroot
. '/mod/' . $cm->modname
. '/lib.php');
178 $getcontentfunction = $cm->modname
.'_export_contents';
179 if (function_exists($getcontentfunction)) {
180 if ($contents = $getcontentfunction($cm, $baseurl)) {
181 $module['contents'] = $contents;
185 //assign result to $sectioncontents
186 $sectioncontents[] = $module;
190 $sectionvalues['modules'] = $sectioncontents;
192 // assign result to $coursecontents
193 $coursecontents[] = $sectionvalues;
196 return $coursecontents;
200 * Returns description of method result value
202 * @return external_description
205 public static function get_course_contents_returns() {
206 return new external_multiple_structure(
207 new external_single_structure(
209 'id' => new external_value(PARAM_INT
, 'Section ID'),
210 'name' => new external_value(PARAM_TEXT
, 'Section name'),
211 'visible' => new external_value(PARAM_INT
, 'is the section visible', VALUE_OPTIONAL
),
212 'summary' => new external_value(PARAM_RAW
, 'Section description'),
213 'summaryformat' => new external_format_value('summary'),
214 'modules' => new external_multiple_structure(
215 new external_single_structure(
217 'id' => new external_value(PARAM_INT
, 'activity id'),
218 'url' => new external_value(PARAM_URL
, 'activity url', VALUE_OPTIONAL
),
219 'name' => new external_value(PARAM_RAW
, 'activity module name'),
220 'instance' => new external_value(PARAM_INT
, 'instance id', VALUE_OPTIONAL
),
221 'description' => new external_value(PARAM_RAW
, 'activity description', VALUE_OPTIONAL
),
222 'visible' => new external_value(PARAM_INT
, 'is the module visible', VALUE_OPTIONAL
),
223 'modicon' => new external_value(PARAM_URL
, 'activity icon url'),
224 'modname' => new external_value(PARAM_PLUGIN
, 'activity module type'),
225 'modplural' => new external_value(PARAM_TEXT
, 'activity module plural name'),
226 'availability' => new external_value(PARAM_RAW
, 'module availability settings', VALUE_OPTIONAL
),
227 'indent' => new external_value(PARAM_INT
, 'number of identation in the site'),
228 'contents' => new external_multiple_structure(
229 new external_single_structure(
232 'type'=> new external_value(PARAM_TEXT
, 'a file or a folder or external link'),
233 'filename'=> new external_value(PARAM_FILE
, 'filename'),
234 'filepath'=> new external_value(PARAM_PATH
, 'filepath'),
235 'filesize'=> new external_value(PARAM_INT
, 'filesize'),
236 'fileurl' => new external_value(PARAM_URL
, 'downloadable file url', VALUE_OPTIONAL
),
237 'content' => new external_value(PARAM_RAW
, 'Raw content, will be used when type is content', VALUE_OPTIONAL
),
238 'timecreated' => new external_value(PARAM_INT
, 'Time created'),
239 'timemodified' => new external_value(PARAM_INT
, 'Time modified'),
240 'sortorder' => new external_value(PARAM_INT
, 'Content sort order'),
242 // copyright related info
243 'userid' => new external_value(PARAM_INT
, 'User who added this content to moodle'),
244 'author' => new external_value(PARAM_TEXT
, 'Content owner'),
245 'license' => new external_value(PARAM_TEXT
, 'Content license'),
247 ), VALUE_DEFAULT
, array()
258 * Returns description of method parameters
260 * @return external_function_parameters
263 public static function get_courses_parameters() {
264 return new external_function_parameters(
265 array('options' => new external_single_structure(
266 array('ids' => new external_multiple_structure(
267 new external_value(PARAM_INT
, 'Course id')
268 , 'List of course id. If empty return all courses
269 except front page course.',
271 ), 'options - operator OR is used', VALUE_DEFAULT
, array())
279 * @param array $options It contains an array (list of ids)
283 public static function get_courses($options = array()) {
285 require_once($CFG->dirroot
. "/course/lib.php");
288 $params = self
::validate_parameters(self
::get_courses_parameters(),
289 array('options' => $options));
292 if (!array_key_exists('ids', $params['options'])
293 or empty($params['options']['ids'])) {
294 $courses = $DB->get_records('course');
296 $courses = $DB->get_records_list('course', 'id', $params['options']['ids']);
299 //create return value
300 $coursesinfo = array();
301 foreach ($courses as $course) {
303 // now security checks
304 $context = context_course
::instance($course->id
, IGNORE_MISSING
);
305 $courseformatoptions = course_get_format($course)->get_format_options();
307 self
::validate_context($context);
308 } catch (Exception
$e) {
309 $exceptionparam = new stdClass();
310 $exceptionparam->message
= $e->getMessage();
311 $exceptionparam->courseid
= $course->id
;
312 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
314 require_capability('moodle/course:view', $context);
316 $courseinfo = array();
317 $courseinfo['id'] = $course->id
;
318 $courseinfo['fullname'] = $course->fullname
;
319 $courseinfo['shortname'] = $course->shortname
;
320 $courseinfo['categoryid'] = $course->category
;
321 list($courseinfo['summary'], $courseinfo['summaryformat']) =
322 external_format_text($course->summary
, $course->summaryformat
, $context->id
, 'course', 'summary', 0);
323 $courseinfo['format'] = $course->format
;
324 $courseinfo['startdate'] = $course->startdate
;
325 if (array_key_exists('numsections', $courseformatoptions)) {
326 // For backward-compartibility
327 $courseinfo['numsections'] = $courseformatoptions['numsections'];
330 //some field should be returned only if the user has update permission
331 $courseadmin = has_capability('moodle/course:update', $context);
333 $courseinfo['categorysortorder'] = $course->sortorder
;
334 $courseinfo['idnumber'] = $course->idnumber
;
335 $courseinfo['showgrades'] = $course->showgrades
;
336 $courseinfo['showreports'] = $course->showreports
;
337 $courseinfo['newsitems'] = $course->newsitems
;
338 $courseinfo['visible'] = $course->visible
;
339 $courseinfo['maxbytes'] = $course->maxbytes
;
340 if (array_key_exists('hiddensections', $courseformatoptions)) {
341 // For backward-compartibility
342 $courseinfo['hiddensections'] = $courseformatoptions['hiddensections'];
344 $courseinfo['groupmode'] = $course->groupmode
;
345 $courseinfo['groupmodeforce'] = $course->groupmodeforce
;
346 $courseinfo['defaultgroupingid'] = $course->defaultgroupingid
;
347 $courseinfo['lang'] = $course->lang
;
348 $courseinfo['timecreated'] = $course->timecreated
;
349 $courseinfo['timemodified'] = $course->timemodified
;
350 $courseinfo['forcetheme'] = $course->theme
;
351 $courseinfo['enablecompletion'] = $course->enablecompletion
;
352 $courseinfo['completionnotify'] = $course->completionnotify
;
353 $courseinfo['courseformatoptions'] = array();
354 foreach ($courseformatoptions as $key => $value) {
355 $courseinfo['courseformatoptions'][] = array(
362 if ($courseadmin or $course->visible
363 or has_capability('moodle/course:viewhiddencourses', $context)) {
364 $coursesinfo[] = $courseinfo;
372 * Returns description of method result value
374 * @return external_description
377 public static function get_courses_returns() {
378 return new external_multiple_structure(
379 new external_single_structure(
381 'id' => new external_value(PARAM_INT
, 'course id'),
382 'shortname' => new external_value(PARAM_TEXT
, 'course short name'),
383 'categoryid' => new external_value(PARAM_INT
, 'category id'),
384 'categorysortorder' => new external_value(PARAM_INT
,
385 'sort order into the category', VALUE_OPTIONAL
),
386 'fullname' => new external_value(PARAM_TEXT
, 'full name'),
387 'idnumber' => new external_value(PARAM_RAW
, 'id number', VALUE_OPTIONAL
),
388 'summary' => new external_value(PARAM_RAW
, 'summary'),
389 'summaryformat' => new external_format_value('summary'),
390 'format' => new external_value(PARAM_PLUGIN
,
391 'course format: weeks, topics, social, site,..'),
392 'showgrades' => new external_value(PARAM_INT
,
393 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL
),
394 'newsitems' => new external_value(PARAM_INT
,
395 'number of recent items appearing on the course page', VALUE_OPTIONAL
),
396 'startdate' => new external_value(PARAM_INT
,
397 'timestamp when the course start'),
398 'numsections' => new external_value(PARAM_INT
,
399 '(deprecated, use courseformatoptions) number of weeks/topics',
401 'maxbytes' => new external_value(PARAM_INT
,
402 'largest size of file that can be uploaded into the course',
404 'showreports' => new external_value(PARAM_INT
,
405 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL
),
406 'visible' => new external_value(PARAM_INT
,
407 '1: available to student, 0:not available', VALUE_OPTIONAL
),
408 'hiddensections' => new external_value(PARAM_INT
,
409 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
411 'groupmode' => new external_value(PARAM_INT
, 'no group, separate, visible',
413 'groupmodeforce' => new external_value(PARAM_INT
, '1: yes, 0: no',
415 'defaultgroupingid' => new external_value(PARAM_INT
, 'default grouping id',
417 'timecreated' => new external_value(PARAM_INT
,
418 'timestamp when the course have been created', VALUE_OPTIONAL
),
419 'timemodified' => new external_value(PARAM_INT
,
420 'timestamp when the course have been modified', VALUE_OPTIONAL
),
421 'enablecompletion' => new external_value(PARAM_INT
,
422 'Enabled, control via completion and activity settings. Disbaled,
423 not shown in activity settings.',
425 'completionnotify' => new external_value(PARAM_INT
,
426 '1: yes 0: no', VALUE_OPTIONAL
),
427 'lang' => new external_value(PARAM_SAFEDIR
,
428 'forced course language', VALUE_OPTIONAL
),
429 'forcetheme' => new external_value(PARAM_PLUGIN
,
430 'name of the force theme', VALUE_OPTIONAL
),
431 'courseformatoptions' => new external_multiple_structure(
432 new external_single_structure(
433 array('name' => new external_value(PARAM_ALPHANUMEXT
, 'course format option name'),
434 'value' => new external_value(PARAM_RAW
, 'course format option value')
436 'additional options for particular course format', VALUE_OPTIONAL
444 * Returns description of method parameters
446 * @return external_function_parameters
449 public static function create_courses_parameters() {
450 $courseconfig = get_config('moodlecourse'); //needed for many default values
451 return new external_function_parameters(
453 'courses' => new external_multiple_structure(
454 new external_single_structure(
456 'fullname' => new external_value(PARAM_TEXT
, 'full name'),
457 'shortname' => new external_value(PARAM_TEXT
, 'course short name'),
458 'categoryid' => new external_value(PARAM_INT
, 'category id'),
459 'idnumber' => new external_value(PARAM_RAW
, 'id number', VALUE_OPTIONAL
),
460 'summary' => new external_value(PARAM_RAW
, 'summary', VALUE_OPTIONAL
),
461 'summaryformat' => new external_format_value('summary', VALUE_DEFAULT
),
462 'format' => new external_value(PARAM_PLUGIN
,
463 'course format: weeks, topics, social, site,..',
464 VALUE_DEFAULT
, $courseconfig->format
),
465 'showgrades' => new external_value(PARAM_INT
,
466 '1 if grades are shown, otherwise 0', VALUE_DEFAULT
,
467 $courseconfig->showgrades
),
468 'newsitems' => new external_value(PARAM_INT
,
469 'number of recent items appearing on the course page',
470 VALUE_DEFAULT
, $courseconfig->newsitems
),
471 'startdate' => new external_value(PARAM_INT
,
472 'timestamp when the course start', VALUE_OPTIONAL
),
473 'numsections' => new external_value(PARAM_INT
,
474 '(deprecated, use courseformatoptions) number of weeks/topics',
476 'maxbytes' => new external_value(PARAM_INT
,
477 'largest size of file that can be uploaded into the course',
478 VALUE_DEFAULT
, $courseconfig->maxbytes
),
479 'showreports' => new external_value(PARAM_INT
,
480 'are activity report shown (yes = 1, no =0)', VALUE_DEFAULT
,
481 $courseconfig->showreports
),
482 'visible' => new external_value(PARAM_INT
,
483 '1: available to student, 0:not available', VALUE_OPTIONAL
),
484 'hiddensections' => new external_value(PARAM_INT
,
485 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
487 'groupmode' => new external_value(PARAM_INT
, 'no group, separate, visible',
488 VALUE_DEFAULT
, $courseconfig->groupmode
),
489 'groupmodeforce' => new external_value(PARAM_INT
, '1: yes, 0: no',
490 VALUE_DEFAULT
, $courseconfig->groupmodeforce
),
491 'defaultgroupingid' => new external_value(PARAM_INT
, 'default grouping id',
493 'enablecompletion' => new external_value(PARAM_INT
,
494 'Enabled, control via completion and activity settings. Disabled,
495 not shown in activity settings.',
497 'completionnotify' => new external_value(PARAM_INT
,
498 '1: yes 0: no', VALUE_OPTIONAL
),
499 'lang' => new external_value(PARAM_SAFEDIR
,
500 'forced course language', VALUE_OPTIONAL
),
501 'forcetheme' => new external_value(PARAM_PLUGIN
,
502 'name of the force theme', VALUE_OPTIONAL
),
503 'courseformatoptions' => new external_multiple_structure(
504 new external_single_structure(
505 array('name' => new external_value(PARAM_ALPHANUMEXT
, 'course format option name'),
506 'value' => new external_value(PARAM_RAW
, 'course format option value')
508 'additional options for particular course format', VALUE_OPTIONAL
),
510 ), 'courses to create'
519 * @param array $courses
520 * @return array courses (id and shortname only)
523 public static function create_courses($courses) {
525 require_once($CFG->dirroot
. "/course/lib.php");
526 require_once($CFG->libdir
. '/completionlib.php');
528 $params = self
::validate_parameters(self
::create_courses_parameters(),
529 array('courses' => $courses));
531 $availablethemes = core_component
::get_plugin_list('theme');
532 $availablelangs = get_string_manager()->get_list_of_translations();
534 $transaction = $DB->start_delegated_transaction();
536 foreach ($params['courses'] as $course) {
538 // Ensure the current user is allowed to run this function
539 $context = context_coursecat
::instance($course['categoryid'], IGNORE_MISSING
);
541 self
::validate_context($context);
542 } catch (Exception
$e) {
543 $exceptionparam = new stdClass();
544 $exceptionparam->message
= $e->getMessage();
545 $exceptionparam->catid
= $course['categoryid'];
546 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
548 require_capability('moodle/course:create', $context);
550 // Make sure lang is valid
551 if (array_key_exists('lang', $course) and empty($availablelangs[$course['lang']])) {
552 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
555 // Make sure theme is valid
556 if (array_key_exists('forcetheme', $course)) {
557 if (!empty($CFG->allowcoursethemes
)) {
558 if (empty($availablethemes[$course['forcetheme']])) {
559 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
561 $course['theme'] = $course['forcetheme'];
566 //force visibility if ws user doesn't have the permission to set it
567 $category = $DB->get_record('course_categories', array('id' => $course['categoryid']));
568 if (!has_capability('moodle/course:visibility', $context)) {
569 $course['visible'] = $category->visible
;
572 //set default value for completion
573 $courseconfig = get_config('moodlecourse');
574 if (completion_info
::is_enabled_for_site()) {
575 if (!array_key_exists('enablecompletion', $course)) {
576 $course['enablecompletion'] = $courseconfig->enablecompletion
;
579 $course['enablecompletion'] = 0;
582 $course['category'] = $course['categoryid'];
585 $course['summaryformat'] = external_validate_format($course['summaryformat']);
587 if (!empty($course['courseformatoptions'])) {
588 foreach ($course['courseformatoptions'] as $option) {
589 $course[$option['name']] = $option['value'];
593 //Note: create_course() core function check shortname, idnumber, category
594 $course['id'] = create_course((object) $course)->id
;
596 $resultcourses[] = array('id' => $course['id'], 'shortname' => $course['shortname']);
599 $transaction->allow_commit();
601 return $resultcourses;
605 * Returns description of method result value
607 * @return external_description
610 public static function create_courses_returns() {
611 return new external_multiple_structure(
612 new external_single_structure(
614 'id' => new external_value(PARAM_INT
, 'course id'),
615 'shortname' => new external_value(PARAM_TEXT
, 'short name'),
624 * @return external_function_parameters
627 public static function update_courses_parameters() {
628 return new external_function_parameters(
630 'courses' => new external_multiple_structure(
631 new external_single_structure(
633 'id' => new external_value(PARAM_INT
, 'ID of the course'),
634 'fullname' => new external_value(PARAM_TEXT
, 'full name', VALUE_OPTIONAL
),
635 'shortname' => new external_value(PARAM_TEXT
, 'course short name', VALUE_OPTIONAL
),
636 'categoryid' => new external_value(PARAM_INT
, 'category id', VALUE_OPTIONAL
),
637 'idnumber' => new external_value(PARAM_RAW
, 'id number', VALUE_OPTIONAL
),
638 'summary' => new external_value(PARAM_RAW
, 'summary', VALUE_OPTIONAL
),
639 'summaryformat' => new external_format_value('summary', VALUE_OPTIONAL
),
640 'format' => new external_value(PARAM_PLUGIN
,
641 'course format: weeks, topics, social, site,..', VALUE_OPTIONAL
),
642 'showgrades' => new external_value(PARAM_INT
,
643 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL
),
644 'newsitems' => new external_value(PARAM_INT
,
645 'number of recent items appearing on the course page', VALUE_OPTIONAL
),
646 'startdate' => new external_value(PARAM_INT
,
647 'timestamp when the course start', VALUE_OPTIONAL
),
648 'numsections' => new external_value(PARAM_INT
,
649 '(deprecated, use courseformatoptions) number of weeks/topics', VALUE_OPTIONAL
),
650 'maxbytes' => new external_value(PARAM_INT
,
651 'largest size of file that can be uploaded into the course', VALUE_OPTIONAL
),
652 'showreports' => new external_value(PARAM_INT
,
653 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL
),
654 'visible' => new external_value(PARAM_INT
,
655 '1: available to student, 0:not available', VALUE_OPTIONAL
),
656 'hiddensections' => new external_value(PARAM_INT
,
657 '(deprecated, use courseformatoptions) How the hidden sections in the course are
658 displayed to students', VALUE_OPTIONAL
),
659 'groupmode' => new external_value(PARAM_INT
, 'no group, separate, visible', VALUE_OPTIONAL
),
660 'groupmodeforce' => new external_value(PARAM_INT
, '1: yes, 0: no', VALUE_OPTIONAL
),
661 'defaultgroupingid' => new external_value(PARAM_INT
, 'default grouping id', VALUE_OPTIONAL
),
662 'enablecompletion' => new external_value(PARAM_INT
,
663 'Enabled, control via completion and activity settings. Disabled,
664 not shown in activity settings.', VALUE_OPTIONAL
),
665 'completionnotify' => new external_value(PARAM_INT
, '1: yes 0: no', VALUE_OPTIONAL
),
666 'lang' => new external_value(PARAM_SAFEDIR
, 'forced course language', VALUE_OPTIONAL
),
667 'forcetheme' => new external_value(PARAM_PLUGIN
, 'name of the force theme', VALUE_OPTIONAL
),
668 'courseformatoptions' => new external_multiple_structure(
669 new external_single_structure(
670 array('name' => new external_value(PARAM_ALPHANUMEXT
, 'course format option name'),
671 'value' => new external_value(PARAM_RAW
, 'course format option value')
673 'additional options for particular course format', VALUE_OPTIONAL
),
675 ), 'courses to update'
684 * @param array $courses
687 public static function update_courses($courses) {
689 require_once($CFG->dirroot
. "/course/lib.php");
692 $params = self
::validate_parameters(self
::update_courses_parameters(),
693 array('courses' => $courses));
695 $availablethemes = core_component
::get_plugin_list('theme');
696 $availablelangs = get_string_manager()->get_list_of_translations();
698 foreach ($params['courses'] as $course) {
699 // Catch any exception while updating course and return as warning to user.
701 // Ensure the current user is allowed to run this function.
702 $context = context_course
::instance($course['id'], MUST_EXIST
);
703 self
::validate_context($context);
705 $oldcourse = course_get_format($course['id'])->get_course();
707 require_capability('moodle/course:update', $context);
709 // Check if user can change category.
710 if (array_key_exists('categoryid', $course) && ($oldcourse->category
!= $course['categoryid'])) {
711 require_capability('moodle/course:changecategory', $context);
712 $course['category'] = $course['categoryid'];
715 // Check if the user can change fullname.
716 if (array_key_exists('fullname', $course) && ($oldcourse->fullname
!= $course['fullname'])) {
717 require_capability('moodle/course:changefullname', $context);
720 // Check if the user can change shortname.
721 if (array_key_exists('shortname', $course) && ($oldcourse->shortname
!= $course['shortname'])) {
722 require_capability('moodle/course:changeshortname', $context);
725 // Check if the user can change the idnumber.
726 if (array_key_exists('idnumber', $course) && ($oldcourse->idnumber
!= $course['idnumber'])) {
727 require_capability('moodle/course:changeidnumber', $context);
730 // Check if user can change summary.
731 if (array_key_exists('summary', $course) && ($oldcourse->summary
!= $course['summary'])) {
732 require_capability('moodle/course:changesummary', $context);
736 if (array_key_exists('summaryformat', $course) && ($oldcourse->summaryformat
!= $course['summaryformat'])) {
737 require_capability('moodle/course:changesummary', $context);
738 $course['summaryformat'] = external_validate_format($course['summaryformat']);
741 // Check if user can change visibility.
742 if (array_key_exists('visible', $course) && ($oldcourse->visible
!= $course['visible'])) {
743 require_capability('moodle/course:visibility', $context);
746 // Make sure lang is valid.
747 if (array_key_exists('lang', $course) && empty($availablelangs[$course['lang']])) {
748 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
751 // Make sure theme is valid.
752 if (array_key_exists('forcetheme', $course)) {
753 if (!empty($CFG->allowcoursethemes
)) {
754 if (empty($availablethemes[$course['forcetheme']])) {
755 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
757 $course['theme'] = $course['forcetheme'];
762 // Make sure completion is enabled before setting it.
763 if (array_key_exists('enabledcompletion', $course) && !completion_info
::is_enabled_for_site()) {
764 $course['enabledcompletion'] = 0;
767 // Make sure maxbytes are less then CFG->maxbytes.
768 if (array_key_exists('maxbytes', $course)) {
769 $course['maxbytes'] = get_max_upload_file_size($CFG->maxbytes
, $course['maxbytes']);
772 if (!empty($course['courseformatoptions'])) {
773 foreach ($course['courseformatoptions'] as $option) {
774 if (isset($option['name']) && isset($option['value'])) {
775 $course[$option['name']] = $option['value'];
780 // Update course if user has all required capabilities.
781 update_course((object) $course);
782 } catch (Exception
$e) {
784 $warning['item'] = 'course';
785 $warning['itemid'] = $course['id'];
786 if ($e instanceof moodle_exception
) {
787 $warning['warningcode'] = $e->errorcode
;
789 $warning['warningcode'] = $e->getCode();
791 $warning['message'] = $e->getMessage();
792 $warnings[] = $warning;
797 $result['warnings'] = $warnings;
802 * Returns description of method result value
804 * @return external_description
807 public static function update_courses_returns() {
808 return new external_single_structure(
810 'warnings' => new external_warnings()
816 * Returns description of method parameters
818 * @return external_function_parameters
821 public static function delete_courses_parameters() {
822 return new external_function_parameters(
824 'courseids' => new external_multiple_structure(new external_value(PARAM_INT
, 'course ID')),
832 * @param array $courseids A list of course ids
835 public static function delete_courses($courseids) {
837 require_once($CFG->dirroot
."/course/lib.php");
839 // Parameter validation.
840 $params = self
::validate_parameters(self
::delete_courses_parameters(), array('courseids'=>$courseids));
842 $transaction = $DB->start_delegated_transaction();
844 foreach ($params['courseids'] as $courseid) {
845 $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST
);
847 // Check if the context is valid.
848 $coursecontext = context_course
::instance($course->id
);
849 self
::validate_context($coursecontext);
851 // Check if the current user has enought permissions.
852 if (!can_delete_course($courseid)) {
853 fix_course_sortorder();
854 throw new moodle_exception('cannotdeletecategorycourse', 'error',
855 '', format_string($course->fullname
)." (id: $courseid)");
858 delete_course($course, false);
861 $transaction->allow_commit();
862 fix_course_sortorder();
868 * Returns description of method result value
870 * @return external_description
873 public static function delete_courses_returns() {
878 * Returns description of method parameters
880 * @return external_function_parameters
883 public static function duplicate_course_parameters() {
884 return new external_function_parameters(
886 'courseid' => new external_value(PARAM_INT
, 'course to duplicate id'),
887 'fullname' => new external_value(PARAM_TEXT
, 'duplicated course full name'),
888 'shortname' => new external_value(PARAM_TEXT
, 'duplicated course short name'),
889 'categoryid' => new external_value(PARAM_INT
, 'duplicated course category parent'),
890 'visible' => new external_value(PARAM_INT
, 'duplicated course visible, default to yes', VALUE_DEFAULT
, 1),
891 'options' => new external_multiple_structure(
892 new external_single_structure(
894 'name' => new external_value(PARAM_ALPHAEXT
, 'The backup option name:
895 "activities" (int) Include course activites (default to 1 that is equal to yes),
896 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
897 "filters" (int) Include course filters (default to 1 that is equal to yes),
898 "users" (int) Include users (default to 0 that is equal to no),
899 "role_assignments" (int) Include role assignments (default to 0 that is equal to no),
900 "comments" (int) Include user comments (default to 0 that is equal to no),
901 "userscompletion" (int) Include user course completion information (default to 0 that is equal to no),
902 "logs" (int) Include course logs (default to 0 that is equal to no),
903 "grade_histories" (int) Include histories (default to 0 that is equal to no)'
905 'value' => new external_value(PARAM_RAW
, 'the value for the option 1 (yes) or 0 (no)'
908 ), VALUE_DEFAULT
, array()
917 * @param int $courseid
918 * @param string $fullname Duplicated course fullname
919 * @param string $shortname Duplicated course shortname
920 * @param int $categoryid Duplicated course parent category id
921 * @param int $visible Duplicated course availability
922 * @param array $options List of backup options
923 * @return array New course info
926 public static function duplicate_course($courseid, $fullname, $shortname, $categoryid, $visible = 1, $options = array()) {
927 global $CFG, $USER, $DB;
928 require_once($CFG->dirroot
. '/backup/util/includes/backup_includes.php');
929 require_once($CFG->dirroot
. '/backup/util/includes/restore_includes.php');
931 // Parameter validation.
932 $params = self
::validate_parameters(
933 self
::duplicate_course_parameters(),
935 'courseid' => $courseid,
936 'fullname' => $fullname,
937 'shortname' => $shortname,
938 'categoryid' => $categoryid,
939 'visible' => $visible,
940 'options' => $options
944 // Context validation.
946 if (! ($course = $DB->get_record('course', array('id'=>$params['courseid'])))) {
947 throw new moodle_exception('invalidcourseid', 'error');
950 // Category where duplicated course is going to be created.
951 $categorycontext = context_coursecat
::instance($params['categoryid']);
952 self
::validate_context($categorycontext);
954 // Course to be duplicated.
955 $coursecontext = context_course
::instance($course->id
);
956 self
::validate_context($coursecontext);
958 $backupdefaults = array(
963 'role_assignments' => 0,
965 'userscompletion' => 0,
967 'grade_histories' => 0
970 $backupsettings = array();
971 // Check for backup and restore options.
972 if (!empty($params['options'])) {
973 foreach ($params['options'] as $option) {
975 // Strict check for a correct value (allways 1 or 0, true or false).
976 $value = clean_param($option['value'], PARAM_INT
);
978 if ($value !== 0 and $value !== 1) {
979 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
982 if (!isset($backupdefaults[$option['name']])) {
983 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
986 $backupsettings[$option['name']] = $value;
990 // Capability checking.
992 // The backup controller check for this currently, this may be redundant.
993 require_capability('moodle/course:create', $categorycontext);
994 require_capability('moodle/restore:restorecourse', $categorycontext);
995 require_capability('moodle/backup:backupcourse', $coursecontext);
997 if (!empty($backupsettings['users'])) {
998 require_capability('moodle/backup:userinfo', $coursecontext);
999 require_capability('moodle/restore:userinfo', $categorycontext);
1002 // Check if the shortname is used.
1003 if ($foundcourses = $DB->get_records('course', array('shortname'=>$shortname))) {
1004 foreach ($foundcourses as $foundcourse) {
1005 $foundcoursenames[] = $foundcourse->fullname
;
1008 $foundcoursenamestring = implode(',', $foundcoursenames);
1009 throw new moodle_exception('shortnametaken', '', '', $foundcoursenamestring);
1012 // Backup the course.
1014 $bc = new backup_controller(backup
::TYPE_1COURSE
, $course->id
, backup
::FORMAT_MOODLE
,
1015 backup
::INTERACTIVE_NO
, backup
::MODE_SAMESITE
, $USER->id
);
1017 foreach ($backupsettings as $name => $value) {
1018 $bc->get_plan()->get_setting($name)->set_value($value);
1021 $backupid = $bc->get_backupid();
1022 $backupbasepath = $bc->get_plan()->get_basepath();
1024 $bc->execute_plan();
1025 $results = $bc->get_results();
1026 $file = $results['backup_destination'];
1030 // Restore the backup immediately.
1032 // Check if we need to unzip the file because the backup temp dir does not contains backup files.
1033 if (!file_exists($backupbasepath . "/moodle_backup.xml")) {
1034 $file->extract_to_pathname(get_file_packer('application/vnd.moodle.backup'), $backupbasepath);
1037 // Create new course.
1038 $newcourseid = restore_dbops
::create_new_course($params['fullname'], $params['shortname'], $params['categoryid']);
1040 $rc = new restore_controller($backupid, $newcourseid,
1041 backup
::INTERACTIVE_NO
, backup
::MODE_SAMESITE
, $USER->id
, backup
::TARGET_NEW_COURSE
);
1043 foreach ($backupsettings as $name => $value) {
1044 $setting = $rc->get_plan()->get_setting($name);
1045 if ($setting->get_status() == backup_setting
::NOT_LOCKED
) {
1046 $setting->set_value($value);
1050 if (!$rc->execute_precheck()) {
1051 $precheckresults = $rc->get_precheck_results();
1052 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1053 if (empty($CFG->keeptempdirectoriesonbackup
)) {
1054 fulldelete($backupbasepath);
1059 foreach ($precheckresults['errors'] as $error) {
1060 $errorinfo .= $error;
1063 if (array_key_exists('warnings', $precheckresults)) {
1064 foreach ($precheckresults['warnings'] as $warning) {
1065 $errorinfo .= $warning;
1069 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1073 $rc->execute_plan();
1076 $course = $DB->get_record('course', array('id' => $newcourseid), '*', MUST_EXIST
);
1077 $course->fullname
= $params['fullname'];
1078 $course->shortname
= $params['shortname'];
1079 $course->visible
= $params['visible'];
1081 // Set shortname and fullname back.
1082 $DB->update_record('course', $course);
1084 if (empty($CFG->keeptempdirectoriesonbackup
)) {
1085 fulldelete($backupbasepath);
1088 // Delete the course backup file created by this WebService. Originally located in the course backups area.
1091 return array('id' => $course->id
, 'shortname' => $course->shortname
);
1095 * Returns description of method result value
1097 * @return external_description
1100 public static function duplicate_course_returns() {
1101 return new external_single_structure(
1103 'id' => new external_value(PARAM_INT
, 'course id'),
1104 'shortname' => new external_value(PARAM_TEXT
, 'short name'),
1110 * Returns description of method parameters for import_course
1112 * @return external_function_parameters
1115 public static function import_course_parameters() {
1116 return new external_function_parameters(
1118 'importfrom' => new external_value(PARAM_INT
, 'the id of the course we are importing from'),
1119 'importto' => new external_value(PARAM_INT
, 'the id of the course we are importing to'),
1120 'deletecontent' => new external_value(PARAM_INT
, 'whether to delete the course content where we are importing to (default to 0 = No)', VALUE_DEFAULT
, 0),
1121 'options' => new external_multiple_structure(
1122 new external_single_structure(
1124 'name' => new external_value(PARAM_ALPHA
, 'The backup option name:
1125 "activities" (int) Include course activites (default to 1 that is equal to yes),
1126 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1127 "filters" (int) Include course filters (default to 1 that is equal to yes)'
1129 'value' => new external_value(PARAM_RAW
, 'the value for the option 1 (yes) or 0 (no)'
1132 ), VALUE_DEFAULT
, array()
1141 * @param int $importfrom The id of the course we are importing from
1142 * @param int $importto The id of the course we are importing to
1143 * @param bool $deletecontent Whether to delete the course we are importing to content
1144 * @param array $options List of backup options
1148 public static function import_course($importfrom, $importto, $deletecontent = 0, $options = array()) {
1149 global $CFG, $USER, $DB;
1150 require_once($CFG->dirroot
. '/backup/util/includes/backup_includes.php');
1151 require_once($CFG->dirroot
. '/backup/util/includes/restore_includes.php');
1153 // Parameter validation.
1154 $params = self
::validate_parameters(
1155 self
::import_course_parameters(),
1157 'importfrom' => $importfrom,
1158 'importto' => $importto,
1159 'deletecontent' => $deletecontent,
1160 'options' => $options
1164 if ($params['deletecontent'] !== 0 and $params['deletecontent'] !== 1) {
1165 throw new moodle_exception('invalidextparam', 'webservice', '', $params['deletecontent']);
1168 // Context validation.
1170 if (! ($importfrom = $DB->get_record('course', array('id'=>$params['importfrom'])))) {
1171 throw new moodle_exception('invalidcourseid', 'error');
1174 if (! ($importto = $DB->get_record('course', array('id'=>$params['importto'])))) {
1175 throw new moodle_exception('invalidcourseid', 'error');
1178 $importfromcontext = context_course
::instance($importfrom->id
);
1179 self
::validate_context($importfromcontext);
1181 $importtocontext = context_course
::instance($importto->id
);
1182 self
::validate_context($importtocontext);
1184 $backupdefaults = array(
1190 $backupsettings = array();
1192 // Check for backup and restore options.
1193 if (!empty($params['options'])) {
1194 foreach ($params['options'] as $option) {
1196 // Strict check for a correct value (allways 1 or 0, true or false).
1197 $value = clean_param($option['value'], PARAM_INT
);
1199 if ($value !== 0 and $value !== 1) {
1200 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1203 if (!isset($backupdefaults[$option['name']])) {
1204 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1207 $backupsettings[$option['name']] = $value;
1211 // Capability checking.
1213 require_capability('moodle/backup:backuptargetimport', $importfromcontext);
1214 require_capability('moodle/restore:restoretargetimport', $importtocontext);
1216 $bc = new backup_controller(backup
::TYPE_1COURSE
, $importfrom->id
, backup
::FORMAT_MOODLE
,
1217 backup
::INTERACTIVE_NO
, backup
::MODE_IMPORT
, $USER->id
);
1219 foreach ($backupsettings as $name => $value) {
1220 $bc->get_plan()->get_setting($name)->set_value($value);
1223 $backupid = $bc->get_backupid();
1224 $backupbasepath = $bc->get_plan()->get_basepath();
1226 $bc->execute_plan();
1229 // Restore the backup immediately.
1231 // Check if we must delete the contents of the destination course.
1232 if ($params['deletecontent']) {
1233 $restoretarget = backup
::TARGET_EXISTING_DELETING
;
1235 $restoretarget = backup
::TARGET_EXISTING_ADDING
;
1238 $rc = new restore_controller($backupid, $importto->id
,
1239 backup
::INTERACTIVE_NO
, backup
::MODE_IMPORT
, $USER->id
, $restoretarget);
1241 foreach ($backupsettings as $name => $value) {
1242 $rc->get_plan()->get_setting($name)->set_value($value);
1245 if (!$rc->execute_precheck()) {
1246 $precheckresults = $rc->get_precheck_results();
1247 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1248 if (empty($CFG->keeptempdirectoriesonbackup
)) {
1249 fulldelete($backupbasepath);
1254 foreach ($precheckresults['errors'] as $error) {
1255 $errorinfo .= $error;
1258 if (array_key_exists('warnings', $precheckresults)) {
1259 foreach ($precheckresults['warnings'] as $warning) {
1260 $errorinfo .= $warning;
1264 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1267 if ($restoretarget == backup
::TARGET_EXISTING_DELETING
) {
1268 restore_dbops
::delete_course_content($importto->id
);
1272 $rc->execute_plan();
1275 if (empty($CFG->keeptempdirectoriesonbackup
)) {
1276 fulldelete($backupbasepath);
1283 * Returns description of method result value
1285 * @return external_description
1288 public static function import_course_returns() {
1293 * Returns description of method parameters
1295 * @return external_function_parameters
1298 public static function get_categories_parameters() {
1299 return new external_function_parameters(
1301 'criteria' => new external_multiple_structure(
1302 new external_single_structure(
1304 'key' => new external_value(PARAM_ALPHA
,
1305 'The category column to search, expected keys (value format) are:'.
1306 '"id" (int) the category id,'.
1307 '"name" (string) the category name,'.
1308 '"parent" (int) the parent category id,'.
1309 '"idnumber" (string) category idnumber'.
1310 ' - user must have \'moodle/category:manage\' to search on idnumber,'.
1311 '"visible" (int) whether the returned categories must be visible or hidden. If the key is not passed,
1312 then the function return all categories that the user can see.'.
1313 ' - user must have \'moodle/category:manage\' or \'moodle/category:viewhiddencategories\' to search on visible,'.
1314 '"theme" (string) only return the categories having this theme'.
1315 ' - user must have \'moodle/category:manage\' to search on theme'),
1316 'value' => new external_value(PARAM_RAW
, 'the value to match')
1318 ), 'criteria', VALUE_DEFAULT
, array()
1320 'addsubcategories' => new external_value(PARAM_BOOL
, 'return the sub categories infos
1321 (1 - default) otherwise only the category info (0)', VALUE_DEFAULT
, 1)
1329 * @param array $criteria Criteria to match the results
1330 * @param booln $addsubcategories obtain only the category (false) or its subcategories (true - default)
1331 * @return array list of categories
1334 public static function get_categories($criteria = array(), $addsubcategories = true) {
1336 require_once($CFG->dirroot
. "/course/lib.php");
1338 // Validate parameters.
1339 $params = self
::validate_parameters(self
::get_categories_parameters(),
1340 array('criteria' => $criteria, 'addsubcategories' => $addsubcategories));
1342 // Retrieve the categories.
1343 $categories = array();
1344 if (!empty($params['criteria'])) {
1346 $conditions = array();
1348 foreach ($params['criteria'] as $crit) {
1349 $key = trim($crit['key']);
1351 // Trying to avoid duplicate keys.
1352 if (!isset($conditions[$key])) {
1354 $context = context_system
::instance();
1358 $value = clean_param($crit['value'], PARAM_INT
);
1362 if (has_capability('moodle/category:manage', $context)) {
1363 $value = clean_param($crit['value'], PARAM_RAW
);
1365 // We must throw an exception.
1366 // Otherwise the dev client would think no idnumber exists.
1367 throw new moodle_exception('criteriaerror',
1368 'webservice', '', null,
1369 'You don\'t have the permissions to search on the "idnumber" field.');
1374 $value = clean_param($crit['value'], PARAM_TEXT
);
1378 $value = clean_param($crit['value'], PARAM_INT
);
1382 if (has_capability('moodle/category:manage', $context)
1383 or has_capability('moodle/category:viewhiddencategories',
1384 context_system
::instance())) {
1385 $value = clean_param($crit['value'], PARAM_INT
);
1387 throw new moodle_exception('criteriaerror',
1388 'webservice', '', null,
1389 'You don\'t have the permissions to search on the "visible" field.');
1394 if (has_capability('moodle/category:manage', $context)) {
1395 $value = clean_param($crit['value'], PARAM_THEME
);
1397 throw new moodle_exception('criteriaerror',
1398 'webservice', '', null,
1399 'You don\'t have the permissions to search on the "theme" field.');
1404 throw new moodle_exception('criteriaerror',
1405 'webservice', '', null,
1406 'You can not search on this criteria: ' . $key);
1409 if (isset($value)) {
1410 $conditions[$key] = $crit['value'];
1411 $wheres[] = $key . " = :" . $key;
1416 if (!empty($wheres)) {
1417 $wheres = implode(" AND ", $wheres);
1419 $categories = $DB->get_records_select('course_categories', $wheres, $conditions);
1421 // Retrieve its sub subcategories (all levels).
1422 if ($categories and !empty($params['addsubcategories'])) {
1423 $newcategories = array();
1425 // Check if we required visible/theme checks.
1426 $additionalselect = '';
1427 $additionalparams = array();
1428 if (isset($conditions['visible'])) {
1429 $additionalselect .= ' AND visible = :visible';
1430 $additionalparams['visible'] = $conditions['visible'];
1432 if (isset($conditions['theme'])) {
1433 $additionalselect .= ' AND theme= :theme';
1434 $additionalparams['theme'] = $conditions['theme'];
1437 foreach ($categories as $category) {
1438 $sqlselect = $DB->sql_like('path', ':path') . $additionalselect;
1439 $sqlparams = array('path' => $category->path
.'/%') +
$additionalparams; // It will NOT include the specified category.
1440 $subcategories = $DB->get_records_select('course_categories', $sqlselect, $sqlparams);
1441 $newcategories = $newcategories +
$subcategories; // Both arrays have integer as keys.
1443 $categories = $categories +
$newcategories;
1448 // Retrieve all categories in the database.
1449 $categories = $DB->get_records('course_categories');
1452 // The not returned categories. key => category id, value => reason of exclusion.
1453 $excludedcats = array();
1455 // The returned categories.
1456 $categoriesinfo = array();
1458 // We need to sort the categories by path.
1459 // The parent cats need to be checked by the algo first.
1460 usort($categories, "core_course_external::compare_categories_by_path");
1462 foreach ($categories as $category) {
1464 // Check if the category is a child of an excluded category, if yes exclude it too (excluded => do not return).
1465 $parents = explode('/', $category->path
);
1466 unset($parents[0]); // First key is always empty because path start with / => /1/2/4.
1467 foreach ($parents as $parentid) {
1468 // Note: when the parent exclusion was due to the context,
1469 // the sub category could still be returned.
1470 if (isset($excludedcats[$parentid]) and $excludedcats[$parentid] != 'context') {
1471 $excludedcats[$category->id
] = 'parent';
1475 // Check category depth is <= maxdepth (do not check for user who can manage categories).
1476 if ((!empty($CFG->maxcategorydepth
) && count($parents) > $CFG->maxcategorydepth
)
1477 and !has_capability('moodle/category:manage', $context)) {
1478 $excludedcats[$category->id
] = 'depth';
1481 // Check the user can use the category context.
1482 $context = context_coursecat
::instance($category->id
);
1484 self
::validate_context($context);
1485 } catch (Exception
$e) {
1486 $excludedcats[$category->id
] = 'context';
1488 // If it was the requested category then throw an exception.
1489 if (isset($params['categoryid']) && $category->id
== $params['categoryid']) {
1490 $exceptionparam = new stdClass();
1491 $exceptionparam->message
= $e->getMessage();
1492 $exceptionparam->catid
= $category->id
;
1493 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
1497 // Return the category information.
1498 if (!isset($excludedcats[$category->id
])) {
1500 // Final check to see if the category is visible to the user.
1501 if ($category->visible
1502 or has_capability('moodle/category:viewhiddencategories', context_system
::instance())
1503 or has_capability('moodle/category:manage', $context)) {
1505 $categoryinfo = array();
1506 $categoryinfo['id'] = $category->id
;
1507 $categoryinfo['name'] = $category->name
;
1508 list($categoryinfo['description'], $categoryinfo['descriptionformat']) =
1509 external_format_text($category->description
, $category->descriptionformat
,
1510 $context->id
, 'coursecat', 'description', null);
1511 $categoryinfo['parent'] = $category->parent
;
1512 $categoryinfo['sortorder'] = $category->sortorder
;
1513 $categoryinfo['coursecount'] = $category->coursecount
;
1514 $categoryinfo['depth'] = $category->depth
;
1515 $categoryinfo['path'] = $category->path
;
1517 // Some fields only returned for admin.
1518 if (has_capability('moodle/category:manage', $context)) {
1519 $categoryinfo['idnumber'] = $category->idnumber
;
1520 $categoryinfo['visible'] = $category->visible
;
1521 $categoryinfo['visibleold'] = $category->visibleold
;
1522 $categoryinfo['timemodified'] = $category->timemodified
;
1523 $categoryinfo['theme'] = $category->theme
;
1526 $categoriesinfo[] = $categoryinfo;
1528 $excludedcats[$category->id
] = 'visibility';
1533 // Sorting the resulting array so it looks a bit better for the client developer.
1534 usort($categoriesinfo, "core_course_external::compare_categories_by_sortorder");
1536 return $categoriesinfo;
1540 * Sort categories array by path
1541 * private function: only used by get_categories
1543 * @param array $category1
1544 * @param array $category2
1545 * @return int result of strcmp
1548 private static function compare_categories_by_path($category1, $category2) {
1549 return strcmp($category1->path
, $category2->path
);
1553 * Sort categories array by sortorder
1554 * private function: only used by get_categories
1556 * @param array $category1
1557 * @param array $category2
1558 * @return int result of strcmp
1561 private static function compare_categories_by_sortorder($category1, $category2) {
1562 return strcmp($category1['sortorder'], $category2['sortorder']);
1566 * Returns description of method result value
1568 * @return external_description
1571 public static function get_categories_returns() {
1572 return new external_multiple_structure(
1573 new external_single_structure(
1575 'id' => new external_value(PARAM_INT
, 'category id'),
1576 'name' => new external_value(PARAM_TEXT
, 'category name'),
1577 'idnumber' => new external_value(PARAM_RAW
, 'category id number', VALUE_OPTIONAL
),
1578 'description' => new external_value(PARAM_RAW
, 'category description'),
1579 'descriptionformat' => new external_format_value('description'),
1580 'parent' => new external_value(PARAM_INT
, 'parent category id'),
1581 'sortorder' => new external_value(PARAM_INT
, 'category sorting order'),
1582 'coursecount' => new external_value(PARAM_INT
, 'number of courses in this category'),
1583 'visible' => new external_value(PARAM_INT
, '1: available, 0:not available', VALUE_OPTIONAL
),
1584 'visibleold' => new external_value(PARAM_INT
, '1: available, 0:not available', VALUE_OPTIONAL
),
1585 'timemodified' => new external_value(PARAM_INT
, 'timestamp', VALUE_OPTIONAL
),
1586 'depth' => new external_value(PARAM_INT
, 'category depth'),
1587 'path' => new external_value(PARAM_TEXT
, 'category path'),
1588 'theme' => new external_value(PARAM_THEME
, 'category theme', VALUE_OPTIONAL
),
1589 ), 'List of categories'
1595 * Returns description of method parameters
1597 * @return external_function_parameters
1600 public static function create_categories_parameters() {
1601 return new external_function_parameters(
1603 'categories' => new external_multiple_structure(
1604 new external_single_structure(
1606 'name' => new external_value(PARAM_TEXT
, 'new category name'),
1607 'parent' => new external_value(PARAM_INT
,
1608 'the parent category id inside which the new category will be created
1609 - set to 0 for a root category',
1611 'idnumber' => new external_value(PARAM_RAW
,
1612 'the new category idnumber', VALUE_OPTIONAL
),
1613 'description' => new external_value(PARAM_RAW
,
1614 'the new category description', VALUE_OPTIONAL
),
1615 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT
),
1616 'theme' => new external_value(PARAM_THEME
,
1617 'the new category theme. This option must be enabled on moodle',
1629 * @param array $categories - see create_categories_parameters() for the array structure
1630 * @return array - see create_categories_returns() for the array structure
1633 public static function create_categories($categories) {
1635 require_once($CFG->libdir
. "/coursecatlib.php");
1637 $params = self
::validate_parameters(self
::create_categories_parameters(),
1638 array('categories' => $categories));
1640 $transaction = $DB->start_delegated_transaction();
1642 $createdcategories = array();
1643 foreach ($params['categories'] as $category) {
1644 if ($category['parent']) {
1645 if (!$DB->record_exists('course_categories', array('id' => $category['parent']))) {
1646 throw new moodle_exception('unknowcategory');
1648 $context = context_coursecat
::instance($category['parent']);
1650 $context = context_system
::instance();
1652 self
::validate_context($context);
1653 require_capability('moodle/category:manage', $context);
1655 // this will validate format and throw an exception if there are errors
1656 external_validate_format($category['descriptionformat']);
1658 $newcategory = coursecat
::create($category);
1660 $createdcategories[] = array('id' => $newcategory->id
, 'name' => $newcategory->name
);
1663 $transaction->allow_commit();
1665 return $createdcategories;
1669 * Returns description of method parameters
1671 * @return external_function_parameters
1674 public static function create_categories_returns() {
1675 return new external_multiple_structure(
1676 new external_single_structure(
1678 'id' => new external_value(PARAM_INT
, 'new category id'),
1679 'name' => new external_value(PARAM_TEXT
, 'new category name'),
1686 * Returns description of method parameters
1688 * @return external_function_parameters
1691 public static function update_categories_parameters() {
1692 return new external_function_parameters(
1694 'categories' => new external_multiple_structure(
1695 new external_single_structure(
1697 'id' => new external_value(PARAM_INT
, 'course id'),
1698 'name' => new external_value(PARAM_TEXT
, 'category name', VALUE_OPTIONAL
),
1699 'idnumber' => new external_value(PARAM_RAW
, 'category id number', VALUE_OPTIONAL
),
1700 'parent' => new external_value(PARAM_INT
, 'parent category id', VALUE_OPTIONAL
),
1701 'description' => new external_value(PARAM_RAW
, 'category description', VALUE_OPTIONAL
),
1702 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT
),
1703 'theme' => new external_value(PARAM_THEME
,
1704 'the category theme. This option must be enabled on moodle', VALUE_OPTIONAL
),
1715 * @param array $categories The list of categories to update
1719 public static function update_categories($categories) {
1721 require_once($CFG->libdir
. "/coursecatlib.php");
1723 // Validate parameters.
1724 $params = self
::validate_parameters(self
::update_categories_parameters(), array('categories' => $categories));
1726 $transaction = $DB->start_delegated_transaction();
1728 foreach ($params['categories'] as $cat) {
1729 $category = coursecat
::get($cat['id']);
1731 $categorycontext = context_coursecat
::instance($cat['id']);
1732 self
::validate_context($categorycontext);
1733 require_capability('moodle/category:manage', $categorycontext);
1735 // this will throw an exception if descriptionformat is not valid
1736 external_validate_format($cat['descriptionformat']);
1738 $category->update($cat);
1741 $transaction->allow_commit();
1745 * Returns description of method result value
1747 * @return external_description
1750 public static function update_categories_returns() {
1755 * Returns description of method parameters
1757 * @return external_function_parameters
1760 public static function delete_categories_parameters() {
1761 return new external_function_parameters(
1763 'categories' => new external_multiple_structure(
1764 new external_single_structure(
1766 'id' => new external_value(PARAM_INT
, 'category id to delete'),
1767 'newparent' => new external_value(PARAM_INT
,
1768 'the parent category to move the contents to, if specified', VALUE_OPTIONAL
),
1769 'recursive' => new external_value(PARAM_BOOL
, '1: recursively delete all contents inside this
1770 category, 0 (default): move contents to newparent or current parent category (except if parent is root)', VALUE_DEFAULT
, 0)
1781 * @param array $categories A list of category ids
1785 public static function delete_categories($categories) {
1787 require_once($CFG->dirroot
. "/course/lib.php");
1788 require_once($CFG->libdir
. "/coursecatlib.php");
1790 // Validate parameters.
1791 $params = self
::validate_parameters(self
::delete_categories_parameters(), array('categories' => $categories));
1793 $transaction = $DB->start_delegated_transaction();
1795 foreach ($params['categories'] as $category) {
1796 $deletecat = coursecat
::get($category['id'], MUST_EXIST
);
1797 $context = context_coursecat
::instance($deletecat->id
);
1798 require_capability('moodle/category:manage', $context);
1799 self
::validate_context($context);
1800 self
::validate_context(get_category_or_system_context($deletecat->parent
));
1802 if ($category['recursive']) {
1803 // If recursive was specified, then we recursively delete the category's contents.
1804 if ($deletecat->can_delete_full()) {
1805 $deletecat->delete_full(false);
1807 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
1810 // In this situation, we don't delete the category's contents, we either move it to newparent or parent.
1811 // If the parent is the root, moving is not supported (because a course must always be inside a category).
1812 // We must move to an existing category.
1813 if (!empty($category['newparent'])) {
1814 $newparentcat = coursecat
::get($category['newparent']);
1816 $newparentcat = coursecat
::get($deletecat->parent
);
1819 // This operation is not allowed. We must move contents to an existing category.
1820 if (!$newparentcat->id
) {
1821 throw new moodle_exception('movecatcontentstoroot');
1824 self
::validate_context(context_coursecat
::instance($newparentcat->id
));
1825 if ($deletecat->can_move_content_to($newparentcat->id
)) {
1826 $deletecat->delete_move($newparentcat->id
, false);
1828 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
1833 $transaction->allow_commit();
1837 * Returns description of method parameters
1839 * @return external_function_parameters
1842 public static function delete_categories_returns() {
1847 * Describes the parameters for delete_modules.
1849 * @return external_external_function_parameters
1852 public static function delete_modules_parameters() {
1853 return new external_function_parameters (
1855 'cmids' => new external_multiple_structure(new external_value(PARAM_INT
, 'course module ID',
1856 VALUE_REQUIRED
, '', NULL_NOT_ALLOWED
), 'Array of course module IDs'),
1862 * Deletes a list of provided module instances.
1864 * @param array $cmids the course module ids
1867 public static function delete_modules($cmids) {
1870 // Require course file containing the course delete module function.
1871 require_once($CFG->dirroot
. "/course/lib.php");
1873 // Clean the parameters.
1874 $params = self
::validate_parameters(self
::delete_modules_parameters(), array('cmids' => $cmids));
1876 // Keep track of the course ids we have performed a capability check on to avoid repeating.
1877 $arrcourseschecked = array();
1879 foreach ($params['cmids'] as $cmid) {
1880 // Get the course module.
1881 $cm = $DB->get_record('course_modules', array('id' => $cmid), '*', MUST_EXIST
);
1883 // Check if we have not yet confirmed they have permission in this course.
1884 if (!in_array($cm->course
, $arrcourseschecked)) {
1885 // Ensure the current user has required permission in this course.
1886 $context = context_course
::instance($cm->course
);
1887 self
::validate_context($context);
1888 // Add to the array.
1889 $arrcourseschecked[] = $cm->course
;
1892 // Ensure they can delete this module.
1893 $modcontext = context_module
::instance($cm->id
);
1894 require_capability('moodle/course:manageactivities', $modcontext);
1896 // Delete the module.
1897 course_delete_module($cm->id
);
1902 * Describes the delete_modules return value.
1904 * @return external_single_structure
1907 public static function delete_modules_returns() {
1913 * Deprecated course external functions
1915 * @package core_course
1916 * @copyright 2009 Petr Skodak
1917 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1919 * @deprecated Moodle 2.2 MDL-29106 - Please do not use this class any more.
1920 * @see core_course_external
1922 class moodle_course_external
extends external_api
{
1925 * Returns description of method parameters
1927 * @return external_function_parameters
1929 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1930 * @see core_course_external::get_courses_parameters()
1932 public static function get_courses_parameters() {
1933 return core_course_external
::get_courses_parameters();
1939 * @param array $options
1942 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1943 * @see core_course_external::get_courses()
1945 public static function get_courses($options) {
1946 return core_course_external
::get_courses($options);
1950 * Returns description of method result value
1952 * @return external_description
1954 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1955 * @see core_course_external::get_courses_returns()
1957 public static function get_courses_returns() {
1958 return core_course_external
::get_courses_returns();
1962 * Returns description of method parameters
1964 * @return external_function_parameters
1966 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1967 * @see core_course_external::create_courses_parameters()
1969 public static function create_courses_parameters() {
1970 return core_course_external
::create_courses_parameters();
1976 * @param array $courses
1977 * @return array courses (id and shortname only)
1979 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1980 * @see core_course_external::create_courses()
1982 public static function create_courses($courses) {
1983 return core_course_external
::create_courses($courses);
1987 * Returns description of method result value
1989 * @return external_description
1991 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1992 * @see core_course_external::create_courses_returns()
1994 public static function create_courses_returns() {
1995 return core_course_external
::create_courses_returns();