Merge branch 'w40_MDL-41999_m26_userpw' of https://github.com/skodak/moodle
[moodle.git] / course / externallib.php
blob2d61c28cb86e7cf697122ac37cdb3c5a6d18b43e
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * External course API
21 * @package core_course
22 * @category external
23 * @copyright 2009 Petr Skodak
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') || die;
29 require_once("$CFG->libdir/externallib.php");
31 /**
32 * Course external functions
34 * @package core_course
35 * @category external
36 * @copyright 2011 Jerome Mouneyrac
37 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 * @since Moodle 2.2
40 class core_course_external extends external_api {
42 /**
43 * Returns description of method parameters
45 * @return external_function_parameters
46 * @since Moodle 2.2
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())
61 /**
62 * Get course contents
64 * @param int $courseid course id
65 * @param array $options These options are not used yet, might be used in later version
66 * @return array
67 * @since Moodle 2.2
69 public static function get_course_contents($courseid, $options = array()) {
70 global $CFG, $DB;
71 require_once($CFG->dirroot . "/course/lib.php");
73 //validate parameter
74 $params = self::validate_parameters(self::get_course_contents_parameters(),
75 array('courseid' => $courseid, 'options' => $options));
77 //retrieve the course
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));
83 } else {
84 require_once($CFG->dirroot . '/course/format/' . $course->format . '/lib.php');
87 // now security checks
88 $context = context_course::instance($course->id, IGNORE_MISSING);
89 try {
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)) {
106 //retrieve sections
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) {
115 continue;
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) {
135 continue;
138 $module = array();
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['modname'] = $cm->modname;
144 $module['modplural'] = $cm->modplural;
145 $module['modicon'] = $cm->get_icon_url()->out(false);
146 $module['indent'] = $cm->indent;
148 $modcontext = context_module::instance($cm->id);
150 if (!empty($cm->showdescription) or $cm->modname == 'label') {
151 // We want to use the external format. However from reading get_formatted_content(), get_content() format is always FORMAT_HTML.
152 list($module['description'], $descriptionformat) = external_format_text($cm->get_content(),
153 FORMAT_HTML, $modcontext->id, $cm->modname, 'intro', $cm->id);
156 //url of the module
157 $url = $cm->get_url();
158 if ($url) { //labels don't have url
159 $module['url'] = $cm->get_url()->out(false);
162 $canviewhidden = has_capability('moodle/course:viewhiddenactivities',
163 context_module::instance($cm->id));
164 //user that can view hidden module should know about the visibility
165 $module['visible'] = $cm->visible;
167 //availability date (also send to user who can see hidden module when the showavailabilyt is ON)
168 if ($canupdatecourse or ($CFG->enableavailability && $canviewhidden && $cm->showavailability)) {
169 $module['availablefrom'] = $cm->availablefrom;
170 $module['availableuntil'] = $cm->availableuntil;
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
203 * @since Moodle 2.2
205 public static function get_course_contents_returns() {
206 return new external_multiple_structure(
207 new external_single_structure(
208 array(
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(
216 array(
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 'description' => new external_value(PARAM_RAW, 'activity description', VALUE_OPTIONAL),
221 'visible' => new external_value(PARAM_INT, 'is the module visible', VALUE_OPTIONAL),
222 'modicon' => new external_value(PARAM_URL, 'activity icon url'),
223 'modname' => new external_value(PARAM_PLUGIN, 'activity module type'),
224 'modplural' => new external_value(PARAM_TEXT, 'activity module plural name'),
225 'availablefrom' => new external_value(PARAM_INT, 'module availability start date', VALUE_OPTIONAL),
226 'availableuntil' => new external_value(PARAM_INT, 'module availability en date', 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(
230 array(
231 // content info
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()
250 ), 'list of module'
258 * Returns description of method parameters
260 * @return external_function_parameters
261 * @since Moodle 2.3
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.',
270 VALUE_OPTIONAL)
271 ), 'options - operator OR is used', VALUE_DEFAULT, array())
277 * Get courses
279 * @param array $options It contains an array (list of ids)
280 * @return array
281 * @since Moodle 2.2
283 public static function get_courses($options = array()) {
284 global $CFG, $DB;
285 require_once($CFG->dirroot . "/course/lib.php");
287 //validate parameter
288 $params = self::validate_parameters(self::get_courses_parameters(),
289 array('options' => $options));
291 //retrieve courses
292 if (!array_key_exists('ids', $params['options'])
293 or empty($params['options']['ids'])) {
294 $courses = $DB->get_records('course');
295 } else {
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();
306 try {
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);
332 if ($courseadmin) {
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(
356 'name' => $key,
357 'value' => $value
362 if ($courseadmin or $course->visible
363 or has_capability('moodle/course:viewhiddencourses', $context)) {
364 $coursesinfo[] = $courseinfo;
368 return $coursesinfo;
372 * Returns description of method result value
374 * @return external_description
375 * @since Moodle 2.2
377 public static function get_courses_returns() {
378 return new external_multiple_structure(
379 new external_single_structure(
380 array(
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',
400 VALUE_OPTIONAL),
401 'maxbytes' => new external_value(PARAM_INT,
402 'largest size of file that can be uploaded into the course',
403 VALUE_OPTIONAL),
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',
410 VALUE_OPTIONAL),
411 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
412 VALUE_OPTIONAL),
413 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
414 VALUE_OPTIONAL),
415 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
416 VALUE_OPTIONAL),
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.',
424 VALUE_OPTIONAL),
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
438 ), 'course'
444 * Returns description of method parameters
446 * @return external_function_parameters
447 * @since Moodle 2.2
449 public static function create_courses_parameters() {
450 $courseconfig = get_config('moodlecourse'); //needed for many default values
451 return new external_function_parameters(
452 array(
453 'courses' => new external_multiple_structure(
454 new external_single_structure(
455 array(
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',
475 VALUE_OPTIONAL),
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',
486 VALUE_OPTIONAL),
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',
492 VALUE_DEFAULT, 0),
493 'enablecompletion' => new external_value(PARAM_INT,
494 'Enabled, control via completion and activity settings. Disabled,
495 not shown in activity settings.',
496 VALUE_OPTIONAL),
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'
517 * Create courses
519 * @param array $courses
520 * @return array courses (id and shortname only)
521 * @since Moodle 2.2
523 public static function create_courses($courses) {
524 global $CFG, $DB;
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);
540 try {
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');
560 } else {
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;
578 } else {
579 $course['enablecompletion'] = 0;
582 $course['category'] = $course['categoryid'];
584 // Summary format.
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
608 * @since Moodle 2.2
610 public static function create_courses_returns() {
611 return new external_multiple_structure(
612 new external_single_structure(
613 array(
614 'id' => new external_value(PARAM_INT, 'course id'),
615 'shortname' => new external_value(PARAM_TEXT, 'short name'),
622 * Update courses
624 * @return external_function_parameters
625 * @since Moodle 2.5
627 public static function update_courses_parameters() {
628 return new external_function_parameters(
629 array(
630 'courses' => new external_multiple_structure(
631 new external_single_structure(
632 array(
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'
682 * Update courses
684 * @param array $courses
685 * @since Moodle 2.5
687 public static function update_courses($courses) {
688 global $CFG, $DB;
689 require_once($CFG->dirroot . "/course/lib.php");
690 $warnings = array();
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.
700 try {
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);
735 // Summary format.
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');
756 } else {
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) {
783 $warning = array();
784 $warning['item'] = 'course';
785 $warning['itemid'] = $course['id'];
786 if ($e instanceof moodle_exception) {
787 $warning['warningcode'] = $e->errorcode;
788 } else {
789 $warning['warningcode'] = $e->getCode();
791 $warning['message'] = $e->getMessage();
792 $warnings[] = $warning;
796 $result = array();
797 $result['warnings'] = $warnings;
798 return $result;
802 * Returns description of method result value
804 * @return external_description
805 * @since Moodle 2.5
807 public static function update_courses_returns() {
808 return new external_single_structure(
809 array(
810 'warnings' => new external_warnings()
816 * Returns description of method parameters
818 * @return external_function_parameters
819 * @since Moodle 2.2
821 public static function delete_courses_parameters() {
822 return new external_function_parameters(
823 array(
824 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'course ID')),
830 * Delete courses
832 * @param array $courseids A list of course ids
833 * @since Moodle 2.2
835 public static function delete_courses($courseids) {
836 global $CFG, $DB;
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 throw new moodle_exception('cannotdeletecategorycourse', 'error',
854 '', format_string($course->fullname)." (id: $courseid)");
857 delete_course($course, false);
860 $transaction->allow_commit();
862 return null;
866 * Returns description of method result value
868 * @return external_description
869 * @since Moodle 2.2
871 public static function delete_courses_returns() {
872 return null;
876 * Returns description of method parameters
878 * @return external_function_parameters
879 * @since Moodle 2.3
881 public static function duplicate_course_parameters() {
882 return new external_function_parameters(
883 array(
884 'courseid' => new external_value(PARAM_INT, 'course to duplicate id'),
885 'fullname' => new external_value(PARAM_TEXT, 'duplicated course full name'),
886 'shortname' => new external_value(PARAM_TEXT, 'duplicated course short name'),
887 'categoryid' => new external_value(PARAM_INT, 'duplicated course category parent'),
888 'visible' => new external_value(PARAM_INT, 'duplicated course visible, default to yes', VALUE_DEFAULT, 1),
889 'options' => new external_multiple_structure(
890 new external_single_structure(
891 array(
892 'name' => new external_value(PARAM_ALPHAEXT, 'The backup option name:
893 "activities" (int) Include course activites (default to 1 that is equal to yes),
894 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
895 "filters" (int) Include course filters (default to 1 that is equal to yes),
896 "users" (int) Include users (default to 0 that is equal to no),
897 "role_assignments" (int) Include role assignments (default to 0 that is equal to no),
898 "comments" (int) Include user comments (default to 0 that is equal to no),
899 "userscompletion" (int) Include user course completion information (default to 0 that is equal to no),
900 "logs" (int) Include course logs (default to 0 that is equal to no),
901 "grade_histories" (int) Include histories (default to 0 that is equal to no)'
903 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
906 ), VALUE_DEFAULT, array()
913 * Duplicate a course
915 * @param int $courseid
916 * @param string $fullname Duplicated course fullname
917 * @param string $shortname Duplicated course shortname
918 * @param int $categoryid Duplicated course parent category id
919 * @param int $visible Duplicated course availability
920 * @param array $options List of backup options
921 * @return array New course info
922 * @since Moodle 2.3
924 public static function duplicate_course($courseid, $fullname, $shortname, $categoryid, $visible = 1, $options = array()) {
925 global $CFG, $USER, $DB;
926 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
927 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
929 // Parameter validation.
930 $params = self::validate_parameters(
931 self::duplicate_course_parameters(),
932 array(
933 'courseid' => $courseid,
934 'fullname' => $fullname,
935 'shortname' => $shortname,
936 'categoryid' => $categoryid,
937 'visible' => $visible,
938 'options' => $options
942 // Context validation.
944 if (! ($course = $DB->get_record('course', array('id'=>$params['courseid'])))) {
945 throw new moodle_exception('invalidcourseid', 'error');
948 // Category where duplicated course is going to be created.
949 $categorycontext = context_coursecat::instance($params['categoryid']);
950 self::validate_context($categorycontext);
952 // Course to be duplicated.
953 $coursecontext = context_course::instance($course->id);
954 self::validate_context($coursecontext);
956 $backupdefaults = array(
957 'activities' => 1,
958 'blocks' => 1,
959 'filters' => 1,
960 'users' => 0,
961 'role_assignments' => 0,
962 'comments' => 0,
963 'userscompletion' => 0,
964 'logs' => 0,
965 'grade_histories' => 0
968 $backupsettings = array();
969 // Check for backup and restore options.
970 if (!empty($params['options'])) {
971 foreach ($params['options'] as $option) {
973 // Strict check for a correct value (allways 1 or 0, true or false).
974 $value = clean_param($option['value'], PARAM_INT);
976 if ($value !== 0 and $value !== 1) {
977 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
980 if (!isset($backupdefaults[$option['name']])) {
981 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
984 $backupsettings[$option['name']] = $value;
988 // Capability checking.
990 // The backup controller check for this currently, this may be redundant.
991 require_capability('moodle/course:create', $categorycontext);
992 require_capability('moodle/restore:restorecourse', $categorycontext);
993 require_capability('moodle/backup:backupcourse', $coursecontext);
995 if (!empty($backupsettings['users'])) {
996 require_capability('moodle/backup:userinfo', $coursecontext);
997 require_capability('moodle/restore:userinfo', $categorycontext);
1000 // Check if the shortname is used.
1001 if ($foundcourses = $DB->get_records('course', array('shortname'=>$shortname))) {
1002 foreach ($foundcourses as $foundcourse) {
1003 $foundcoursenames[] = $foundcourse->fullname;
1006 $foundcoursenamestring = implode(',', $foundcoursenames);
1007 throw new moodle_exception('shortnametaken', '', '', $foundcoursenamestring);
1010 // Backup the course.
1012 $bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE,
1013 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id);
1015 foreach ($backupsettings as $name => $value) {
1016 $bc->get_plan()->get_setting($name)->set_value($value);
1019 $backupid = $bc->get_backupid();
1020 $backupbasepath = $bc->get_plan()->get_basepath();
1022 $bc->execute_plan();
1023 $results = $bc->get_results();
1024 $file = $results['backup_destination'];
1026 $bc->destroy();
1028 // Restore the backup immediately.
1030 // Check if we need to unzip the file because the backup temp dir does not contains backup files.
1031 if (!file_exists($backupbasepath . "/moodle_backup.xml")) {
1032 $file->extract_to_pathname(get_file_packer(), $backupbasepath);
1035 // Create new course.
1036 $newcourseid = restore_dbops::create_new_course($params['fullname'], $params['shortname'], $params['categoryid']);
1038 $rc = new restore_controller($backupid, $newcourseid,
1039 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id, backup::TARGET_NEW_COURSE);
1041 foreach ($backupsettings as $name => $value) {
1042 $setting = $rc->get_plan()->get_setting($name);
1043 if ($setting->get_status() == backup_setting::NOT_LOCKED) {
1044 $setting->set_value($value);
1048 if (!$rc->execute_precheck()) {
1049 $precheckresults = $rc->get_precheck_results();
1050 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1051 if (empty($CFG->keeptempdirectoriesonbackup)) {
1052 fulldelete($backupbasepath);
1055 $errorinfo = '';
1057 foreach ($precheckresults['errors'] as $error) {
1058 $errorinfo .= $error;
1061 if (array_key_exists('warnings', $precheckresults)) {
1062 foreach ($precheckresults['warnings'] as $warning) {
1063 $errorinfo .= $warning;
1067 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1071 $rc->execute_plan();
1072 $rc->destroy();
1074 $course = $DB->get_record('course', array('id' => $newcourseid), '*', MUST_EXIST);
1075 $course->fullname = $params['fullname'];
1076 $course->shortname = $params['shortname'];
1077 $course->visible = $params['visible'];
1079 // Set shortname and fullname back.
1080 $DB->update_record('course', $course);
1082 if (empty($CFG->keeptempdirectoriesonbackup)) {
1083 fulldelete($backupbasepath);
1086 // Delete the course backup file created by this WebService. Originally located in the course backups area.
1087 $file->delete();
1089 return array('id' => $course->id, 'shortname' => $course->shortname);
1093 * Returns description of method result value
1095 * @return external_description
1096 * @since Moodle 2.3
1098 public static function duplicate_course_returns() {
1099 return new external_single_structure(
1100 array(
1101 'id' => new external_value(PARAM_INT, 'course id'),
1102 'shortname' => new external_value(PARAM_TEXT, 'short name'),
1108 * Returns description of method parameters for import_course
1110 * @return external_function_parameters
1111 * @since Moodle 2.4
1113 public static function import_course_parameters() {
1114 return new external_function_parameters(
1115 array(
1116 'importfrom' => new external_value(PARAM_INT, 'the id of the course we are importing from'),
1117 'importto' => new external_value(PARAM_INT, 'the id of the course we are importing to'),
1118 'deletecontent' => new external_value(PARAM_INT, 'whether to delete the course content where we are importing to (default to 0 = No)', VALUE_DEFAULT, 0),
1119 'options' => new external_multiple_structure(
1120 new external_single_structure(
1121 array(
1122 'name' => new external_value(PARAM_ALPHA, 'The backup option name:
1123 "activities" (int) Include course activites (default to 1 that is equal to yes),
1124 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1125 "filters" (int) Include course filters (default to 1 that is equal to yes)'
1127 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1130 ), VALUE_DEFAULT, array()
1137 * Imports a course
1139 * @param int $importfrom The id of the course we are importing from
1140 * @param int $importto The id of the course we are importing to
1141 * @param bool $deletecontent Whether to delete the course we are importing to content
1142 * @param array $options List of backup options
1143 * @return null
1144 * @since Moodle 2.4
1146 public static function import_course($importfrom, $importto, $deletecontent = 0, $options = array()) {
1147 global $CFG, $USER, $DB;
1148 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1149 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1151 // Parameter validation.
1152 $params = self::validate_parameters(
1153 self::import_course_parameters(),
1154 array(
1155 'importfrom' => $importfrom,
1156 'importto' => $importto,
1157 'deletecontent' => $deletecontent,
1158 'options' => $options
1162 if ($params['deletecontent'] !== 0 and $params['deletecontent'] !== 1) {
1163 throw new moodle_exception('invalidextparam', 'webservice', '', $params['deletecontent']);
1166 // Context validation.
1168 if (! ($importfrom = $DB->get_record('course', array('id'=>$params['importfrom'])))) {
1169 throw new moodle_exception('invalidcourseid', 'error');
1172 if (! ($importto = $DB->get_record('course', array('id'=>$params['importto'])))) {
1173 throw new moodle_exception('invalidcourseid', 'error');
1176 $importfromcontext = context_course::instance($importfrom->id);
1177 self::validate_context($importfromcontext);
1179 $importtocontext = context_course::instance($importto->id);
1180 self::validate_context($importtocontext);
1182 $backupdefaults = array(
1183 'activities' => 1,
1184 'blocks' => 1,
1185 'filters' => 1
1188 $backupsettings = array();
1190 // Check for backup and restore options.
1191 if (!empty($params['options'])) {
1192 foreach ($params['options'] as $option) {
1194 // Strict check for a correct value (allways 1 or 0, true or false).
1195 $value = clean_param($option['value'], PARAM_INT);
1197 if ($value !== 0 and $value !== 1) {
1198 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1201 if (!isset($backupdefaults[$option['name']])) {
1202 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1205 $backupsettings[$option['name']] = $value;
1209 // Capability checking.
1211 require_capability('moodle/backup:backuptargetimport', $importfromcontext);
1212 require_capability('moodle/restore:restoretargetimport', $importtocontext);
1214 $bc = new backup_controller(backup::TYPE_1COURSE, $importfrom->id, backup::FORMAT_MOODLE,
1215 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
1217 foreach ($backupsettings as $name => $value) {
1218 $bc->get_plan()->get_setting($name)->set_value($value);
1221 $backupid = $bc->get_backupid();
1222 $backupbasepath = $bc->get_plan()->get_basepath();
1224 $bc->execute_plan();
1225 $bc->destroy();
1227 // Restore the backup immediately.
1229 // Check if we must delete the contents of the destination course.
1230 if ($params['deletecontent']) {
1231 $restoretarget = backup::TARGET_EXISTING_DELETING;
1232 } else {
1233 $restoretarget = backup::TARGET_EXISTING_ADDING;
1236 $rc = new restore_controller($backupid, $importto->id,
1237 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, $restoretarget);
1239 foreach ($backupsettings as $name => $value) {
1240 $rc->get_plan()->get_setting($name)->set_value($value);
1243 if (!$rc->execute_precheck()) {
1244 $precheckresults = $rc->get_precheck_results();
1245 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1246 if (empty($CFG->keeptempdirectoriesonbackup)) {
1247 fulldelete($backupbasepath);
1250 $errorinfo = '';
1252 foreach ($precheckresults['errors'] as $error) {
1253 $errorinfo .= $error;
1256 if (array_key_exists('warnings', $precheckresults)) {
1257 foreach ($precheckresults['warnings'] as $warning) {
1258 $errorinfo .= $warning;
1262 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1264 } else {
1265 if ($restoretarget == backup::TARGET_EXISTING_DELETING) {
1266 restore_dbops::delete_course_content($importto->id);
1270 $rc->execute_plan();
1271 $rc->destroy();
1273 if (empty($CFG->keeptempdirectoriesonbackup)) {
1274 fulldelete($backupbasepath);
1277 return null;
1281 * Returns description of method result value
1283 * @return external_description
1284 * @since Moodle 2.4
1286 public static function import_course_returns() {
1287 return null;
1291 * Returns description of method parameters
1293 * @return external_function_parameters
1294 * @since Moodle 2.3
1296 public static function get_categories_parameters() {
1297 return new external_function_parameters(
1298 array(
1299 'criteria' => new external_multiple_structure(
1300 new external_single_structure(
1301 array(
1302 'key' => new external_value(PARAM_ALPHA,
1303 'The category column to search, expected keys (value format) are:'.
1304 '"id" (int) the category id,'.
1305 '"name" (string) the category name,'.
1306 '"parent" (int) the parent category id,'.
1307 '"idnumber" (string) category idnumber'.
1308 ' - user must have \'moodle/category:manage\' to search on idnumber,'.
1309 '"visible" (int) whether the returned categories must be visible or hidden. If the key is not passed,
1310 then the function return all categories that the user can see.'.
1311 ' - user must have \'moodle/category:manage\' or \'moodle/category:viewhiddencategories\' to search on visible,'.
1312 '"theme" (string) only return the categories having this theme'.
1313 ' - user must have \'moodle/category:manage\' to search on theme'),
1314 'value' => new external_value(PARAM_RAW, 'the value to match')
1316 ), 'criteria', VALUE_DEFAULT, array()
1318 'addsubcategories' => new external_value(PARAM_BOOL, 'return the sub categories infos
1319 (1 - default) otherwise only the category info (0)', VALUE_DEFAULT, 1)
1325 * Get categories
1327 * @param array $criteria Criteria to match the results
1328 * @param booln $addsubcategories obtain only the category (false) or its subcategories (true - default)
1329 * @return array list of categories
1330 * @since Moodle 2.3
1332 public static function get_categories($criteria = array(), $addsubcategories = true) {
1333 global $CFG, $DB;
1334 require_once($CFG->dirroot . "/course/lib.php");
1336 // Validate parameters.
1337 $params = self::validate_parameters(self::get_categories_parameters(),
1338 array('criteria' => $criteria, 'addsubcategories' => $addsubcategories));
1340 // Retrieve the categories.
1341 $categories = array();
1342 if (!empty($params['criteria'])) {
1344 $conditions = array();
1345 $wheres = array();
1346 foreach ($params['criteria'] as $crit) {
1347 $key = trim($crit['key']);
1349 // Trying to avoid duplicate keys.
1350 if (!isset($conditions[$key])) {
1352 $context = context_system::instance();
1353 $value = null;
1354 switch ($key) {
1355 case 'id':
1356 $value = clean_param($crit['value'], PARAM_INT);
1357 break;
1359 case 'idnumber':
1360 if (has_capability('moodle/category:manage', $context)) {
1361 $value = clean_param($crit['value'], PARAM_RAW);
1362 } else {
1363 // We must throw an exception.
1364 // Otherwise the dev client would think no idnumber exists.
1365 throw new moodle_exception('criteriaerror',
1366 'webservice', '', null,
1367 'You don\'t have the permissions to search on the "idnumber" field.');
1369 break;
1371 case 'name':
1372 $value = clean_param($crit['value'], PARAM_TEXT);
1373 break;
1375 case 'parent':
1376 $value = clean_param($crit['value'], PARAM_INT);
1377 break;
1379 case 'visible':
1380 if (has_capability('moodle/category:manage', $context)
1381 or has_capability('moodle/category:viewhiddencategories',
1382 context_system::instance())) {
1383 $value = clean_param($crit['value'], PARAM_INT);
1384 } else {
1385 throw new moodle_exception('criteriaerror',
1386 'webservice', '', null,
1387 'You don\'t have the permissions to search on the "visible" field.');
1389 break;
1391 case 'theme':
1392 if (has_capability('moodle/category:manage', $context)) {
1393 $value = clean_param($crit['value'], PARAM_THEME);
1394 } else {
1395 throw new moodle_exception('criteriaerror',
1396 'webservice', '', null,
1397 'You don\'t have the permissions to search on the "theme" field.');
1399 break;
1401 default:
1402 throw new moodle_exception('criteriaerror',
1403 'webservice', '', null,
1404 'You can not search on this criteria: ' . $key);
1407 if (isset($value)) {
1408 $conditions[$key] = $crit['value'];
1409 $wheres[] = $key . " = :" . $key;
1414 if (!empty($wheres)) {
1415 $wheres = implode(" AND ", $wheres);
1417 $categories = $DB->get_records_select('course_categories', $wheres, $conditions);
1419 // Retrieve its sub subcategories (all levels).
1420 if ($categories and !empty($params['addsubcategories'])) {
1421 $newcategories = array();
1423 // Check if we required visible/theme checks.
1424 $additionalselect = '';
1425 $additionalparams = array();
1426 if (isset($conditions['visible'])) {
1427 $additionalselect .= ' AND visible = :visible';
1428 $additionalparams['visible'] = $conditions['visible'];
1430 if (isset($conditions['theme'])) {
1431 $additionalselect .= ' AND theme= :theme';
1432 $additionalparams['theme'] = $conditions['theme'];
1435 foreach ($categories as $category) {
1436 $sqlselect = $DB->sql_like('path', ':path') . $additionalselect;
1437 $sqlparams = array('path' => $category->path.'/%') + $additionalparams; // It will NOT include the specified category.
1438 $subcategories = $DB->get_records_select('course_categories', $sqlselect, $sqlparams);
1439 $newcategories = $newcategories + $subcategories; // Both arrays have integer as keys.
1441 $categories = $categories + $newcategories;
1445 } else {
1446 // Retrieve all categories in the database.
1447 $categories = $DB->get_records('course_categories');
1450 // The not returned categories. key => category id, value => reason of exclusion.
1451 $excludedcats = array();
1453 // The returned categories.
1454 $categoriesinfo = array();
1456 // We need to sort the categories by path.
1457 // The parent cats need to be checked by the algo first.
1458 usort($categories, "core_course_external::compare_categories_by_path");
1460 foreach ($categories as $category) {
1462 // Check if the category is a child of an excluded category, if yes exclude it too (excluded => do not return).
1463 $parents = explode('/', $category->path);
1464 unset($parents[0]); // First key is always empty because path start with / => /1/2/4.
1465 foreach ($parents as $parentid) {
1466 // Note: when the parent exclusion was due to the context,
1467 // the sub category could still be returned.
1468 if (isset($excludedcats[$parentid]) and $excludedcats[$parentid] != 'context') {
1469 $excludedcats[$category->id] = 'parent';
1473 // Check category depth is <= maxdepth (do not check for user who can manage categories).
1474 if ((!empty($CFG->maxcategorydepth) && count($parents) > $CFG->maxcategorydepth)
1475 and !has_capability('moodle/category:manage', $context)) {
1476 $excludedcats[$category->id] = 'depth';
1479 // Check the user can use the category context.
1480 $context = context_coursecat::instance($category->id);
1481 try {
1482 self::validate_context($context);
1483 } catch (Exception $e) {
1484 $excludedcats[$category->id] = 'context';
1486 // If it was the requested category then throw an exception.
1487 if (isset($params['categoryid']) && $category->id == $params['categoryid']) {
1488 $exceptionparam = new stdClass();
1489 $exceptionparam->message = $e->getMessage();
1490 $exceptionparam->catid = $category->id;
1491 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
1495 // Return the category information.
1496 if (!isset($excludedcats[$category->id])) {
1498 // Final check to see if the category is visible to the user.
1499 if ($category->visible
1500 or has_capability('moodle/category:viewhiddencategories', context_system::instance())
1501 or has_capability('moodle/category:manage', $context)) {
1503 $categoryinfo = array();
1504 $categoryinfo['id'] = $category->id;
1505 $categoryinfo['name'] = $category->name;
1506 list($categoryinfo['description'], $categoryinfo['descriptionformat']) =
1507 external_format_text($category->description, $category->descriptionformat,
1508 $context->id, 'coursecat', 'description', null);
1509 $categoryinfo['parent'] = $category->parent;
1510 $categoryinfo['sortorder'] = $category->sortorder;
1511 $categoryinfo['coursecount'] = $category->coursecount;
1512 $categoryinfo['depth'] = $category->depth;
1513 $categoryinfo['path'] = $category->path;
1515 // Some fields only returned for admin.
1516 if (has_capability('moodle/category:manage', $context)) {
1517 $categoryinfo['idnumber'] = $category->idnumber;
1518 $categoryinfo['visible'] = $category->visible;
1519 $categoryinfo['visibleold'] = $category->visibleold;
1520 $categoryinfo['timemodified'] = $category->timemodified;
1521 $categoryinfo['theme'] = $category->theme;
1524 $categoriesinfo[] = $categoryinfo;
1525 } else {
1526 $excludedcats[$category->id] = 'visibility';
1531 // Sorting the resulting array so it looks a bit better for the client developer.
1532 usort($categoriesinfo, "core_course_external::compare_categories_by_sortorder");
1534 return $categoriesinfo;
1538 * Sort categories array by path
1539 * private function: only used by get_categories
1541 * @param array $category1
1542 * @param array $category2
1543 * @return int result of strcmp
1544 * @since Moodle 2.3
1546 private static function compare_categories_by_path($category1, $category2) {
1547 return strcmp($category1->path, $category2->path);
1551 * Sort categories array by sortorder
1552 * private function: only used by get_categories
1554 * @param array $category1
1555 * @param array $category2
1556 * @return int result of strcmp
1557 * @since Moodle 2.3
1559 private static function compare_categories_by_sortorder($category1, $category2) {
1560 return strcmp($category1['sortorder'], $category2['sortorder']);
1564 * Returns description of method result value
1566 * @return external_description
1567 * @since Moodle 2.3
1569 public static function get_categories_returns() {
1570 return new external_multiple_structure(
1571 new external_single_structure(
1572 array(
1573 'id' => new external_value(PARAM_INT, 'category id'),
1574 'name' => new external_value(PARAM_TEXT, 'category name'),
1575 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1576 'description' => new external_value(PARAM_RAW, 'category description'),
1577 'descriptionformat' => new external_format_value('description'),
1578 'parent' => new external_value(PARAM_INT, 'parent category id'),
1579 'sortorder' => new external_value(PARAM_INT, 'category sorting order'),
1580 'coursecount' => new external_value(PARAM_INT, 'number of courses in this category'),
1581 'visible' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1582 'visibleold' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1583 'timemodified' => new external_value(PARAM_INT, 'timestamp', VALUE_OPTIONAL),
1584 'depth' => new external_value(PARAM_INT, 'category depth'),
1585 'path' => new external_value(PARAM_TEXT, 'category path'),
1586 'theme' => new external_value(PARAM_THEME, 'category theme', VALUE_OPTIONAL),
1587 ), 'List of categories'
1593 * Returns description of method parameters
1595 * @return external_function_parameters
1596 * @since Moodle 2.3
1598 public static function create_categories_parameters() {
1599 return new external_function_parameters(
1600 array(
1601 'categories' => new external_multiple_structure(
1602 new external_single_structure(
1603 array(
1604 'name' => new external_value(PARAM_TEXT, 'new category name'),
1605 'parent' => new external_value(PARAM_INT,
1606 'the parent category id inside which the new category will be created
1607 - set to 0 for a root category',
1608 VALUE_DEFAULT, 0),
1609 'idnumber' => new external_value(PARAM_RAW,
1610 'the new category idnumber', VALUE_OPTIONAL),
1611 'description' => new external_value(PARAM_RAW,
1612 'the new category description', VALUE_OPTIONAL),
1613 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
1614 'theme' => new external_value(PARAM_THEME,
1615 'the new category theme. This option must be enabled on moodle',
1616 VALUE_OPTIONAL),
1625 * Create categories
1627 * @param array $categories - see create_categories_parameters() for the array structure
1628 * @return array - see create_categories_returns() for the array structure
1629 * @since Moodle 2.3
1631 public static function create_categories($categories) {
1632 global $CFG, $DB;
1633 require_once($CFG->libdir . "/coursecatlib.php");
1635 $params = self::validate_parameters(self::create_categories_parameters(),
1636 array('categories' => $categories));
1638 $transaction = $DB->start_delegated_transaction();
1640 $createdcategories = array();
1641 foreach ($params['categories'] as $category) {
1642 if ($category['parent']) {
1643 if (!$DB->record_exists('course_categories', array('id' => $category['parent']))) {
1644 throw new moodle_exception('unknowcategory');
1646 $context = context_coursecat::instance($category['parent']);
1647 } else {
1648 $context = context_system::instance();
1650 self::validate_context($context);
1651 require_capability('moodle/category:manage', $context);
1653 // this will validate format and throw an exception if there are errors
1654 external_validate_format($category['descriptionformat']);
1656 $newcategory = coursecat::create($category);
1658 $createdcategories[] = array('id' => $newcategory->id, 'name' => $newcategory->name);
1661 $transaction->allow_commit();
1663 return $createdcategories;
1667 * Returns description of method parameters
1669 * @return external_function_parameters
1670 * @since Moodle 2.3
1672 public static function create_categories_returns() {
1673 return new external_multiple_structure(
1674 new external_single_structure(
1675 array(
1676 'id' => new external_value(PARAM_INT, 'new category id'),
1677 'name' => new external_value(PARAM_TEXT, 'new category name'),
1684 * Returns description of method parameters
1686 * @return external_function_parameters
1687 * @since Moodle 2.3
1689 public static function update_categories_parameters() {
1690 return new external_function_parameters(
1691 array(
1692 'categories' => new external_multiple_structure(
1693 new external_single_structure(
1694 array(
1695 'id' => new external_value(PARAM_INT, 'course id'),
1696 'name' => new external_value(PARAM_TEXT, 'category name', VALUE_OPTIONAL),
1697 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1698 'parent' => new external_value(PARAM_INT, 'parent category id', VALUE_OPTIONAL),
1699 'description' => new external_value(PARAM_RAW, 'category description', VALUE_OPTIONAL),
1700 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
1701 'theme' => new external_value(PARAM_THEME,
1702 'the category theme. This option must be enabled on moodle', VALUE_OPTIONAL),
1711 * Update categories
1713 * @param array $categories The list of categories to update
1714 * @return null
1715 * @since Moodle 2.3
1717 public static function update_categories($categories) {
1718 global $CFG, $DB;
1719 require_once($CFG->libdir . "/coursecatlib.php");
1721 // Validate parameters.
1722 $params = self::validate_parameters(self::update_categories_parameters(), array('categories' => $categories));
1724 $transaction = $DB->start_delegated_transaction();
1726 foreach ($params['categories'] as $cat) {
1727 $category = coursecat::get($cat['id']);
1729 $categorycontext = context_coursecat::instance($cat['id']);
1730 self::validate_context($categorycontext);
1731 require_capability('moodle/category:manage', $categorycontext);
1733 // this will throw an exception if descriptionformat is not valid
1734 external_validate_format($cat['descriptionformat']);
1736 $category->update($cat);
1739 $transaction->allow_commit();
1743 * Returns description of method result value
1745 * @return external_description
1746 * @since Moodle 2.3
1748 public static function update_categories_returns() {
1749 return null;
1753 * Returns description of method parameters
1755 * @return external_function_parameters
1756 * @since Moodle 2.3
1758 public static function delete_categories_parameters() {
1759 return new external_function_parameters(
1760 array(
1761 'categories' => new external_multiple_structure(
1762 new external_single_structure(
1763 array(
1764 'id' => new external_value(PARAM_INT, 'category id to delete'),
1765 'newparent' => new external_value(PARAM_INT,
1766 'the parent category to move the contents to, if specified', VALUE_OPTIONAL),
1767 'recursive' => new external_value(PARAM_BOOL, '1: recursively delete all contents inside this
1768 category, 0 (default): move contents to newparent or current parent category (except if parent is root)', VALUE_DEFAULT, 0)
1777 * Delete categories
1779 * @param array $categories A list of category ids
1780 * @return array
1781 * @since Moodle 2.3
1783 public static function delete_categories($categories) {
1784 global $CFG, $DB;
1785 require_once($CFG->dirroot . "/course/lib.php");
1786 require_once($CFG->libdir . "/coursecatlib.php");
1788 // Validate parameters.
1789 $params = self::validate_parameters(self::delete_categories_parameters(), array('categories' => $categories));
1791 $transaction = $DB->start_delegated_transaction();
1793 foreach ($params['categories'] as $category) {
1794 $deletecat = coursecat::get($category['id'], MUST_EXIST);
1795 $context = context_coursecat::instance($deletecat->id);
1796 require_capability('moodle/category:manage', $context);
1797 self::validate_context($context);
1798 self::validate_context(get_category_or_system_context($deletecat->parent));
1800 if ($category['recursive']) {
1801 // If recursive was specified, then we recursively delete the category's contents.
1802 if ($deletecat->can_delete_full()) {
1803 $deletecat->delete_full(false);
1804 } else {
1805 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
1807 } else {
1808 // In this situation, we don't delete the category's contents, we either move it to newparent or parent.
1809 // If the parent is the root, moving is not supported (because a course must always be inside a category).
1810 // We must move to an existing category.
1811 if (!empty($category['newparent'])) {
1812 $newparentcat = coursecat::get($category['newparent']);
1813 } else {
1814 $newparentcat = coursecat::get($deletecat->parent);
1817 // This operation is not allowed. We must move contents to an existing category.
1818 if (!$newparentcat->id) {
1819 throw new moodle_exception('movecatcontentstoroot');
1822 self::validate_context(context_coursecat::instance($newparentcat->id));
1823 if ($deletecat->can_move_content_to($newparentcat->id)) {
1824 $deletecat->delete_move($newparentcat->id, false);
1825 } else {
1826 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
1831 $transaction->allow_commit();
1835 * Returns description of method parameters
1837 * @return external_function_parameters
1838 * @since Moodle 2.3
1840 public static function delete_categories_returns() {
1841 return null;
1845 * Describes the parameters for delete_modules.
1847 * @return external_external_function_parameters
1848 * @since Moodle 2.5
1850 public static function delete_modules_parameters() {
1851 return new external_function_parameters (
1852 array(
1853 'cmids' => new external_multiple_structure(new external_value(PARAM_INT, 'course module ID',
1854 VALUE_REQUIRED, '', NULL_NOT_ALLOWED), 'Array of course module IDs'),
1860 * Deletes a list of provided module instances.
1862 * @param array $cmids the course module ids
1863 * @since Moodle 2.5
1865 public static function delete_modules($cmids) {
1866 global $CFG, $DB;
1868 // Require course file containing the course delete module function.
1869 require_once($CFG->dirroot . "/course/lib.php");
1871 // Clean the parameters.
1872 $params = self::validate_parameters(self::delete_modules_parameters(), array('cmids' => $cmids));
1874 // Keep track of the course ids we have performed a capability check on to avoid repeating.
1875 $arrcourseschecked = array();
1877 foreach ($params['cmids'] as $cmid) {
1878 // Get the course module.
1879 $cm = $DB->get_record('course_modules', array('id' => $cmid), '*', MUST_EXIST);
1881 // Check if we have not yet confirmed they have permission in this course.
1882 if (!in_array($cm->course, $arrcourseschecked)) {
1883 // Ensure the current user has required permission in this course.
1884 $context = context_course::instance($cm->course);
1885 self::validate_context($context);
1886 // Add to the array.
1887 $arrcourseschecked[] = $cm->course;
1890 // Ensure they can delete this module.
1891 $modcontext = context_module::instance($cm->id);
1892 require_capability('moodle/course:manageactivities', $modcontext);
1894 // Delete the module.
1895 course_delete_module($cm->id);
1900 * Describes the delete_modules return value.
1902 * @return external_single_structure
1903 * @since Moodle 2.5
1905 public static function delete_modules_returns() {
1906 return null;
1911 * Deprecated course external functions
1913 * @package core_course
1914 * @copyright 2009 Petr Skodak
1915 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1916 * @since Moodle 2.0
1917 * @deprecated Moodle 2.2 MDL-29106 - Please do not use this class any more.
1918 * @see core_course_external
1920 class moodle_course_external extends external_api {
1923 * Returns description of method parameters
1925 * @return external_function_parameters
1926 * @since Moodle 2.0
1927 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1928 * @see core_course_external::get_courses_parameters()
1930 public static function get_courses_parameters() {
1931 return core_course_external::get_courses_parameters();
1935 * Get courses
1937 * @param array $options
1938 * @return array
1939 * @since Moodle 2.0
1940 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1941 * @see core_course_external::get_courses()
1943 public static function get_courses($options) {
1944 return core_course_external::get_courses($options);
1948 * Returns description of method result value
1950 * @return external_description
1951 * @since Moodle 2.0
1952 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1953 * @see core_course_external::get_courses_returns()
1955 public static function get_courses_returns() {
1956 return core_course_external::get_courses_returns();
1960 * Returns description of method parameters
1962 * @return external_function_parameters
1963 * @since Moodle 2.0
1964 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1965 * @see core_course_external::create_courses_parameters()
1967 public static function create_courses_parameters() {
1968 return core_course_external::create_courses_parameters();
1972 * Create courses
1974 * @param array $courses
1975 * @return array courses (id and shortname only)
1976 * @since Moodle 2.0
1977 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1978 * @see core_course_external::create_courses()
1980 public static function create_courses($courses) {
1981 return core_course_external::create_courses($courses);
1985 * Returns description of method result value
1987 * @return external_description
1988 * @since Moodle 2.0
1989 * @deprecated Moodle 2.2 MDL-29106 - Please do not call this function any more.
1990 * @see core_course_external::create_courses_returns()
1992 public static function create_courses_returns() {
1993 return core_course_external::create_courses_returns();