MDL-58659 course: Add missing enddate field in get_courses_by_field
[moodle.git] / course / externallib.php
CommitLineData
8e7d3fe4 1<?php
8e7d3fe4
PS
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.
13//
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/>.
16
4615817d 17
8e7d3fe4 18/**
6bb31e40 19 * External course API
8e7d3fe4 20 *
4615817d
JM
21 * @package core_course
22 * @category external
23 * @copyright 2009 Petr Skodak
8e7d3fe4
PS
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 */
26
df997f84
PS
27defined('MOODLE_INTERNAL') || die;
28
8e7d3fe4
PS
29require_once("$CFG->libdir/externallib.php");
30
5d1017e1 31/**
4615817d
JM
32 * Course external functions
33 *
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
5d1017e1
JM
39 */
40class core_course_external extends external_api {
8e7d3fe4 41
ec0d6ea2
DC
42 /**
43 * Returns description of method parameters
4615817d 44 *
ec0d6ea2 45 * @return external_function_parameters
08b66e86 46 * @since Moodle 2.9 Options available
4615817d 47 * @since Moodle 2.2
ec0d6ea2
DC
48 */
49 public static function get_course_contents_parameters() {
50 return new external_function_parameters(
51 array('courseid' => new external_value(PARAM_INT, 'course id'),
52 'options' => new external_multiple_structure (
53 new external_single_structure(
08b66e86
JL
54 array(
55 'name' => new external_value(PARAM_ALPHANUM,
56 'The expected keys (value format) are:
57 excludemodules (bool) Do not return modules, return only the sections structure
58 excludecontents (bool) Do not return module contents (i.e: files inside a resource)
59 sectionid (int) Return only this section
60 sectionnumber (int) Return only this section with number (order)
61 cmid (int) Return only this module information (among the whole sections structure)
62 modname (string) Return only modules with this name "label, forum, etc..."
63 modid (int) Return only the module with this id (to be used with modname'),
64 'value' => new external_value(PARAM_RAW, 'the value of the option,
65 this param is personaly validated in the external function.')
ec0d6ea2 66 )
08b66e86 67 ), 'Options, used since Moodle 2.9', VALUE_DEFAULT, array())
ec0d6ea2
DC
68 )
69 );
70 }
71
72 /**
73 * Get course contents
4615817d
JM
74 *
75 * @param int $courseid course id
08b66e86 76 * @param array $options Options for filtering the results, used since Moodle 2.9
ec0d6ea2 77 * @return array
08b66e86 78 * @since Moodle 2.9 Options available
4615817d 79 * @since Moodle 2.2
ec0d6ea2 80 */
3297d575 81 public static function get_course_contents($courseid, $options = array()) {
ec0d6ea2
DC
82 global $CFG, $DB;
83 require_once($CFG->dirroot . "/course/lib.php");
84
85 //validate parameter
86 $params = self::validate_parameters(self::get_course_contents_parameters(),
87 array('courseid' => $courseid, 'options' => $options));
88
08b66e86
JL
89 $filters = array();
90 if (!empty($params['options'])) {
91
92 foreach ($params['options'] as $option) {
93 $name = trim($option['name']);
94 // Avoid duplicated options.
95 if (!isset($filters[$name])) {
96 switch ($name) {
97 case 'excludemodules':
98 case 'excludecontents':
99 $value = clean_param($option['value'], PARAM_BOOL);
100 $filters[$name] = $value;
101 break;
102 case 'sectionid':
103 case 'sectionnumber':
104 case 'cmid':
105 case 'modid':
106 $value = clean_param($option['value'], PARAM_INT);
107 if (is_numeric($value)) {
108 $filters[$name] = $value;
109 } else {
110 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
111 }
112 break;
113 case 'modname':
114 $value = clean_param($option['value'], PARAM_PLUGIN);
115 if ($value) {
116 $filters[$name] = $value;
117 } else {
118 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
119 }
120 break;
121 default:
122 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
123 }
124 }
125 }
126 }
127
ec0d6ea2
DC
128 //retrieve the course
129 $course = $DB->get_record('course', array('id' => $params['courseid']), '*', MUST_EXIST);
130
12da294e
JL
131 if ($course->id != SITEID) {
132 // Check course format exist.
133 if (!file_exists($CFG->dirroot . '/course/format/' . $course->format . '/lib.php')) {
134 throw new moodle_exception('cannotgetcoursecontents', 'webservice', '', null,
135 get_string('courseformatnotfound', 'error', $course->format));
136 } else {
137 require_once($CFG->dirroot . '/course/format/' . $course->format . '/lib.php');
138 }
ec0d6ea2
DC
139 }
140
141 // now security checks
1f364c87 142 $context = context_course::instance($course->id, IGNORE_MISSING);
ec0d6ea2
DC
143 try {
144 self::validate_context($context);
145 } catch (Exception $e) {
146 $exceptionparam = new stdClass();
147 $exceptionparam->message = $e->getMessage();
148 $exceptionparam->courseid = $course->id;
149 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
150 }
151
152 $canupdatecourse = has_capability('moodle/course:update', $context);
153
154 //create return value
155 $coursecontents = array();
156
157 if ($canupdatecourse or $course->visible
158 or has_capability('moodle/course:viewhiddencourses', $context)) {
159
160 //retrieve sections
161 $modinfo = get_fast_modinfo($course);
71a56e08 162 $sections = $modinfo->get_section_info_all();
89b909f6 163 $coursenumsections = course_get_format($course)->get_last_section_number();
ec0d6ea2
DC
164
165 //for each sections (first displayed to last displayed)
9f3cc17d 166 $modinfosections = $modinfo->get_sections();
ec0d6ea2
DC
167 foreach ($sections as $key => $section) {
168
71a56e08 169 if (!$section->uservisible) {
ec0d6ea2
DC
170 continue;
171 }
172
08b66e86
JL
173 // This becomes true when we are filtering and we found the value to filter with.
174 $sectionfound = false;
175
176 // Filter by section id.
177 if (!empty($filters['sectionid'])) {
178 if ($section->id != $filters['sectionid']) {
179 continue;
180 } else {
181 $sectionfound = true;
182 }
183 }
184
185 // Filter by section number. Note that 0 is a valid section number.
186 if (isset($filters['sectionnumber'])) {
187 if ($key != $filters['sectionnumber']) {
188 continue;
189 } else {
190 $sectionfound = true;
191 }
192 }
193
ec0d6ea2
DC
194 // reset $sectioncontents
195 $sectionvalues = array();
196 $sectionvalues['id'] = $section->id;
197 $sectionvalues['name'] = get_section_name($course, $section);
ec0d6ea2 198 $sectionvalues['visible'] = $section->visible;
6a1131e2
JL
199
200 $options = (object) array('noclean' => true);
93ce0e82
JM
201 list($sectionvalues['summary'], $sectionvalues['summaryformat']) =
202 external_format_text($section->summary, $section->summaryformat,
6a1131e2 203 $context->id, 'course', 'section', $section->id, $options);
9df9f1f0 204 $sectionvalues['section'] = $section->section;
82f5802a 205 $sectionvalues['hiddenbynumsections'] = $section->section > $coursenumsections ? 1 : 0;
ec0d6ea2
DC
206 $sectioncontents = array();
207
208 //for each module of the section
08b66e86 209 if (empty($filters['excludemodules']) and !empty($modinfosections[$section->section])) {
9f3cc17d
JM
210 foreach ($modinfosections[$section->section] as $cmid) {
211 $cm = $modinfo->cms[$cmid];
ec0d6ea2 212
9f3cc17d
JM
213 // stop here if the module is not visible to the user
214 if (!$cm->uservisible) {
215 continue;
216 }
ec0d6ea2 217
08b66e86
JL
218 // This becomes true when we are filtering and we found the value to filter with.
219 $modfound = false;
220
221 // Filter by cmid.
222 if (!empty($filters['cmid'])) {
223 if ($cmid != $filters['cmid']) {
224 continue;
225 } else {
226 $modfound = true;
227 }
228 }
229
230 // Filter by module name and id.
231 if (!empty($filters['modname'])) {
232 if ($cm->modname != $filters['modname']) {
233 continue;
234 } else if (!empty($filters['modid'])) {
235 if ($cm->instance != $filters['modid']) {
236 continue;
237 } else {
238 // Note that if we are only filtering by modname we don't break the loop.
239 $modfound = true;
240 }
241 }
242 }
243
9f3cc17d 244 $module = array();
ec0d6ea2 245
9748791b
JL
246 $modcontext = context_module::instance($cm->id);
247
9f3cc17d
JM
248 //common info (for people being able to see the module or availability dates)
249 $module['id'] = $cm->id;
9748791b 250 $module['name'] = external_format_string($cm->name, $modcontext->id);
d3549931 251 $module['instance'] = $cm->instance;
9f3cc17d
JM
252 $module['modname'] = $cm->modname;
253 $module['modplural'] = $cm->modplural;
254 $module['modicon'] = $cm->get_icon_url()->out(false);
255 $module['indent'] = $cm->indent;
ec0d6ea2 256
e7c5ee51 257 if (!empty($cm->showdescription) or $cm->modname == 'label') {
73ee2fda
DP
258 // We want to use the external format. However from reading get_formatted_content(), $cm->content format is always FORMAT_HTML.
259 list($module['description'], $descriptionformat) = external_format_text($cm->content,
e7c5ee51 260 FORMAT_HTML, $modcontext->id, $cm->modname, 'intro', $cm->id);
9f3cc17d 261 }
ec0d6ea2 262
9f3cc17d 263 //url of the module
73ee2fda 264 $url = $cm->url;
9f3cc17d 265 if ($url) { //labels don't have url
73ee2fda 266 $module['url'] = $url->out(false);
9f3cc17d 267 }
ec0d6ea2 268
9f3cc17d
JM
269 $canviewhidden = has_capability('moodle/course:viewhiddenactivities',
270 context_module::instance($cm->id));
271 //user that can view hidden module should know about the visibility
272 $module['visible'] = $cm->visible;
4529327a 273 $module['visibleoncoursepage'] = $cm->visibleoncoursepage;
ec0d6ea2 274
8d1f33e1 275 // Availability date (also send to user who can see hidden module).
276 if ($CFG->enableavailability && ($canviewhidden || $canupdatecourse)) {
277 $module['availability'] = $cm->availability;
9f3cc17d 278 }
ec0d6ea2 279
9f3cc17d 280 $baseurl = 'webservice/pluginfile.php';
ec0d6ea2 281
9f3cc17d
JM
282 //call $modulename_export_contents
283 //(each module callback take care about checking the capabilities)
08b66e86 284
9f3cc17d
JM
285 require_once($CFG->dirroot . '/mod/' . $cm->modname . '/lib.php');
286 $getcontentfunction = $cm->modname.'_export_contents';
287 if (function_exists($getcontentfunction)) {
08b66e86 288 if (empty($filters['excludecontents']) and $contents = $getcontentfunction($cm, $baseurl)) {
9f3cc17d 289 $module['contents'] = $contents;
08b66e86
JL
290 } else {
291 $module['contents'] = array();
9f3cc17d 292 }
ec0d6ea2 293 }
ec0d6ea2 294
9f3cc17d
JM
295 //assign result to $sectioncontents
296 $sectioncontents[] = $module;
ec0d6ea2 297
08b66e86
JL
298 // If we just did a filtering, break the loop.
299 if ($modfound) {
300 break;
301 }
302
9f3cc17d 303 }
ec0d6ea2
DC
304 }
305 $sectionvalues['modules'] = $sectioncontents;
306
307 // assign result to $coursecontents
308 $coursecontents[] = $sectionvalues;
08b66e86
JL
309
310 // Break the loop if we are filtering.
311 if ($sectionfound) {
312 break;
313 }
ec0d6ea2
DC
314 }
315 }
316 return $coursecontents;
317 }
318
319 /**
320 * Returns description of method result value
4615817d 321 *
ec0d6ea2 322 * @return external_description
4615817d 323 * @since Moodle 2.2
ec0d6ea2
DC
324 */
325 public static function get_course_contents_returns() {
326 return new external_multiple_structure(
327 new external_single_structure(
328 array(
329 'id' => new external_value(PARAM_INT, 'Section ID'),
330 'name' => new external_value(PARAM_TEXT, 'Section name'),
331 'visible' => new external_value(PARAM_INT, 'is the section visible', VALUE_OPTIONAL),
332 'summary' => new external_value(PARAM_RAW, 'Section description'),
93ce0e82 333 'summaryformat' => new external_format_value('summary'),
9df9f1f0 334 'section' => new external_value(PARAM_INT, 'Section number inside the course', VALUE_OPTIONAL),
82f5802a
JL
335 'hiddenbynumsections' => new external_value(PARAM_INT, 'Whether is a section hidden in the course format',
336 VALUE_OPTIONAL),
ec0d6ea2
DC
337 'modules' => new external_multiple_structure(
338 new external_single_structure(
339 array(
340 'id' => new external_value(PARAM_INT, 'activity id'),
341 'url' => new external_value(PARAM_URL, 'activity url', VALUE_OPTIONAL),
11d81936 342 'name' => new external_value(PARAM_RAW, 'activity module name'),
ca4154ce 343 'instance' => new external_value(PARAM_INT, 'instance id', VALUE_OPTIONAL),
ec0d6ea2
DC
344 'description' => new external_value(PARAM_RAW, 'activity description', VALUE_OPTIONAL),
345 'visible' => new external_value(PARAM_INT, 'is the module visible', VALUE_OPTIONAL),
4529327a
MG
346 'visibleoncoursepage' => new external_value(PARAM_INT, 'is the module visible on course page',
347 VALUE_OPTIONAL),
ec0d6ea2
DC
348 'modicon' => new external_value(PARAM_URL, 'activity icon url'),
349 'modname' => new external_value(PARAM_PLUGIN, 'activity module type'),
350 'modplural' => new external_value(PARAM_TEXT, 'activity module plural name'),
8d1f33e1 351 'availability' => new external_value(PARAM_RAW, 'module availability settings', VALUE_OPTIONAL),
ec0d6ea2
DC
352 'indent' => new external_value(PARAM_INT, 'number of identation in the site'),
353 'contents' => new external_multiple_structure(
354 new external_single_structure(
355 array(
356 // content info
357 'type'=> new external_value(PARAM_TEXT, 'a file or a folder or external link'),
358 'filename'=> new external_value(PARAM_FILE, 'filename'),
359 'filepath'=> new external_value(PARAM_PATH, 'filepath'),
360 'filesize'=> new external_value(PARAM_INT, 'filesize'),
361 'fileurl' => new external_value(PARAM_URL, 'downloadable file url', VALUE_OPTIONAL),
362 'content' => new external_value(PARAM_RAW, 'Raw content, will be used when type is content', VALUE_OPTIONAL),
363 'timecreated' => new external_value(PARAM_INT, 'Time created'),
364 'timemodified' => new external_value(PARAM_INT, 'Time modified'),
365 'sortorder' => new external_value(PARAM_INT, 'Content sort order'),
1104a9fa
JL
366 'mimetype' => new external_value(PARAM_RAW, 'File mime type.', VALUE_OPTIONAL),
367 'isexternalfile' => new external_value(PARAM_BOOL, 'Whether is an external file.',
368 VALUE_OPTIONAL),
369 'repositorytype' => new external_value(PARAM_PLUGIN, 'The repository type for external files.',
370 VALUE_OPTIONAL),
ec0d6ea2
DC
371
372 // copyright related info
373 'userid' => new external_value(PARAM_INT, 'User who added this content to moodle'),
374 'author' => new external_value(PARAM_TEXT, 'Content owner'),
375 'license' => new external_value(PARAM_TEXT, 'Content license'),
376 )
377 ), VALUE_DEFAULT, array()
378 )
379 )
380 ), 'list of module'
381 )
382 )
383 )
384 );
385 }
386
6bb31e40 387 /**
388 * Returns description of method parameters
4615817d 389 *
6bb31e40 390 * @return external_function_parameters
754c2dea 391 * @since Moodle 2.3
6bb31e40 392 */
393 public static function get_courses_parameters() {
394 return new external_function_parameters(
395 array('options' => new external_single_structure(
396 array('ids' => new external_multiple_structure(
397 new external_value(PARAM_INT, 'Course id')
398 , 'List of course id. If empty return all courses
399 except front page course.',
400 VALUE_OPTIONAL)
401 ), 'options - operator OR is used', VALUE_DEFAULT, array())
402 )
403 );
404 }
405
406 /**
407 * Get courses
4615817d
JM
408 *
409 * @param array $options It contains an array (list of ids)
6bb31e40 410 * @return array
4615817d 411 * @since Moodle 2.2
6bb31e40 412 */
3297d575 413 public static function get_courses($options = array()) {
6bb31e40 414 global $CFG, $DB;
415 require_once($CFG->dirroot . "/course/lib.php");
416
417 //validate parameter
418 $params = self::validate_parameters(self::get_courses_parameters(),
419 array('options' => $options));
420
421 //retrieve courses
12fc8acf 422 if (!array_key_exists('ids', $params['options'])
6bb31e40 423 or empty($params['options']['ids'])) {
424 $courses = $DB->get_records('course');
425 } else {
426 $courses = $DB->get_records_list('course', 'id', $params['options']['ids']);
427 }
428
429 //create return value
430 $coursesinfo = array();
431 foreach ($courses as $course) {
432
433 // now security checks
1f364c87 434 $context = context_course::instance($course->id, IGNORE_MISSING);
0e984d98 435 $courseformatoptions = course_get_format($course)->get_format_options();
6bb31e40 436 try {
437 self::validate_context($context);
438 } catch (Exception $e) {
439 $exceptionparam = new stdClass();
440 $exceptionparam->message = $e->getMessage();
441 $exceptionparam->courseid = $course->id;
96d3b93b 442 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
6bb31e40 443 }
a0cf7ee8
MG
444 if ($course->id != SITEID) {
445 require_capability('moodle/course:view', $context);
446 }
6bb31e40 447
448 $courseinfo = array();
449 $courseinfo['id'] = $course->id;
d889b587
JL
450 $courseinfo['fullname'] = external_format_string($course->fullname, $context->id);
451 $courseinfo['shortname'] = external_format_string($course->shortname, $context->id);
440b4c54 452 $courseinfo['displayname'] = external_format_string(get_course_display_name_for_list($course), $context->id);
6bb31e40 453 $courseinfo['categoryid'] = $course->category;
93ce0e82
JM
454 list($courseinfo['summary'], $courseinfo['summaryformat']) =
455 external_format_text($course->summary, $course->summaryformat, $context->id, 'course', 'summary', 0);
6bb31e40 456 $courseinfo['format'] = $course->format;
457 $courseinfo['startdate'] = $course->startdate;
fbcdb0d7 458 $courseinfo['enddate'] = $course->enddate;
0e984d98
MG
459 if (array_key_exists('numsections', $courseformatoptions)) {
460 // For backward-compartibility
461 $courseinfo['numsections'] = $courseformatoptions['numsections'];
462 }
6bb31e40 463
464 //some field should be returned only if the user has update permission
465 $courseadmin = has_capability('moodle/course:update', $context);
466 if ($courseadmin) {
467 $courseinfo['categorysortorder'] = $course->sortorder;
468 $courseinfo['idnumber'] = $course->idnumber;
469 $courseinfo['showgrades'] = $course->showgrades;
470 $courseinfo['showreports'] = $course->showreports;
471 $courseinfo['newsitems'] = $course->newsitems;
472 $courseinfo['visible'] = $course->visible;
473 $courseinfo['maxbytes'] = $course->maxbytes;
0e984d98
MG
474 if (array_key_exists('hiddensections', $courseformatoptions)) {
475 // For backward-compartibility
476 $courseinfo['hiddensections'] = $courseformatoptions['hiddensections'];
477 }
89b909f6
MG
478 // Return numsections for backward-compatibility with clients who expect it.
479 $courseinfo['numsections'] = course_get_format($course)->get_last_section_number();
6bb31e40 480 $courseinfo['groupmode'] = $course->groupmode;
481 $courseinfo['groupmodeforce'] = $course->groupmodeforce;
482 $courseinfo['defaultgroupingid'] = $course->defaultgroupingid;
483 $courseinfo['lang'] = $course->lang;
484 $courseinfo['timecreated'] = $course->timecreated;
485 $courseinfo['timemodified'] = $course->timemodified;
486 $courseinfo['forcetheme'] = $course->theme;
487 $courseinfo['enablecompletion'] = $course->enablecompletion;
6bb31e40 488 $courseinfo['completionnotify'] = $course->completionnotify;
8d8d4da4 489 $courseinfo['courseformatoptions'] = array();
0e984d98 490 foreach ($courseformatoptions as $key => $value) {
8d8d4da4
MG
491 $courseinfo['courseformatoptions'][] = array(
492 'name' => $key,
493 'value' => $value
0e984d98
MG
494 );
495 }
6bb31e40 496 }
497
498 if ($courseadmin or $course->visible
499 or has_capability('moodle/course:viewhiddencourses', $context)) {
500 $coursesinfo[] = $courseinfo;
501 }
502 }
503
504 return $coursesinfo;
505 }
506
507 /**
508 * Returns description of method result value
4615817d 509 *
6bb31e40 510 * @return external_description
4615817d 511 * @since Moodle 2.2
6bb31e40 512 */
513 public static function get_courses_returns() {
514 return new external_multiple_structure(
515 new external_single_structure(
516 array(
517 'id' => new external_value(PARAM_INT, 'course id'),
518 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
519 'categoryid' => new external_value(PARAM_INT, 'category id'),
520 'categorysortorder' => new external_value(PARAM_INT,
521 'sort order into the category', VALUE_OPTIONAL),
522 'fullname' => new external_value(PARAM_TEXT, 'full name'),
440b4c54 523 'displayname' => new external_value(PARAM_TEXT, 'course display name'),
6bb31e40 524 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
525 'summary' => new external_value(PARAM_RAW, 'summary'),
93ce0e82 526 'summaryformat' => new external_format_value('summary'),
aff24313 527 'format' => new external_value(PARAM_PLUGIN,
6bb31e40 528 'course format: weeks, topics, social, site,..'),
529 'showgrades' => new external_value(PARAM_INT,
530 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
531 'newsitems' => new external_value(PARAM_INT,
532 'number of recent items appearing on the course page', VALUE_OPTIONAL),
533 'startdate' => new external_value(PARAM_INT,
534 'timestamp when the course start'),
fbcdb0d7
DNA
535 'enddate' => new external_value(PARAM_INT,
536 'timestamp when the course end'),
0e984d98 537 'numsections' => new external_value(PARAM_INT,
8d8d4da4 538 '(deprecated, use courseformatoptions) number of weeks/topics',
0e984d98 539 VALUE_OPTIONAL),
6bb31e40 540 'maxbytes' => new external_value(PARAM_INT,
541 'largest size of file that can be uploaded into the course',
542 VALUE_OPTIONAL),
543 'showreports' => new external_value(PARAM_INT,
544 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
545 'visible' => new external_value(PARAM_INT,
546 '1: available to student, 0:not available', VALUE_OPTIONAL),
547 'hiddensections' => new external_value(PARAM_INT,
8d8d4da4 548 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
3ec163dd
EL
549 VALUE_OPTIONAL),
550 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
551 VALUE_OPTIONAL),
552 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
553 VALUE_OPTIONAL),
554 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
555 VALUE_OPTIONAL),
556 'timecreated' => new external_value(PARAM_INT,
557 'timestamp when the course have been created', VALUE_OPTIONAL),
558 'timemodified' => new external_value(PARAM_INT,
559 'timestamp when the course have been modified', VALUE_OPTIONAL),
560 'enablecompletion' => new external_value(PARAM_INT,
561 'Enabled, control via completion and activity settings. Disbaled,
562 not shown in activity settings.',
563 VALUE_OPTIONAL),
3ec163dd
EL
564 'completionnotify' => new external_value(PARAM_INT,
565 '1: yes 0: no', VALUE_OPTIONAL),
566 'lang' => new external_value(PARAM_SAFEDIR,
567 'forced course language', VALUE_OPTIONAL),
568 'forcetheme' => new external_value(PARAM_PLUGIN,
569 'name of the force theme', VALUE_OPTIONAL),
8d8d4da4 570 'courseformatoptions' => new external_multiple_structure(
0e984d98 571 new external_single_structure(
8d8d4da4
MG
572 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
573 'value' => new external_value(PARAM_RAW, 'course format option value')
0e984d98
MG
574 )),
575 'additional options for particular course format', VALUE_OPTIONAL
576 ),
3ec163dd 577 ), 'course'
479a5db1 578 )
479a5db1
FS
579 );
580 }
581
6bb31e40 582 /**
583 * Returns description of method parameters
4615817d 584 *
6bb31e40 585 * @return external_function_parameters
4615817d 586 * @since Moodle 2.2
6bb31e40 587 */
588 public static function create_courses_parameters() {
589 $courseconfig = get_config('moodlecourse'); //needed for many default values
590 return new external_function_parameters(
591 array(
592 'courses' => new external_multiple_structure(
593 new external_single_structure(
594 array(
595 'fullname' => new external_value(PARAM_TEXT, 'full name'),
596 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
597 'categoryid' => new external_value(PARAM_INT, 'category id'),
598 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
599 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
93ce0e82 600 'summaryformat' => new external_format_value('summary', VALUE_DEFAULT),
aff24313 601 'format' => new external_value(PARAM_PLUGIN,
6bb31e40 602 'course format: weeks, topics, social, site,..',
603 VALUE_DEFAULT, $courseconfig->format),
604 'showgrades' => new external_value(PARAM_INT,
605 '1 if grades are shown, otherwise 0', VALUE_DEFAULT,
606 $courseconfig->showgrades),
607 'newsitems' => new external_value(PARAM_INT,
608 'number of recent items appearing on the course page',
609 VALUE_DEFAULT, $courseconfig->newsitems),
610 'startdate' => new external_value(PARAM_INT,
611 'timestamp when the course start', VALUE_OPTIONAL),
fbcdb0d7
DNA
612 'enddate' => new external_value(PARAM_INT,
613 'timestamp when the course end', VALUE_OPTIONAL),
0e984d98 614 'numsections' => new external_value(PARAM_INT,
8d8d4da4 615 '(deprecated, use courseformatoptions) number of weeks/topics',
0e984d98 616 VALUE_OPTIONAL),
6bb31e40 617 'maxbytes' => new external_value(PARAM_INT,
618 'largest size of file that can be uploaded into the course',
619 VALUE_DEFAULT, $courseconfig->maxbytes),
620 'showreports' => new external_value(PARAM_INT,
621 'are activity report shown (yes = 1, no =0)', VALUE_DEFAULT,
622 $courseconfig->showreports),
623 'visible' => new external_value(PARAM_INT,
624 '1: available to student, 0:not available', VALUE_OPTIONAL),
625 'hiddensections' => new external_value(PARAM_INT,
8d8d4da4 626 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
0e984d98 627 VALUE_OPTIONAL),
6bb31e40 628 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
629 VALUE_DEFAULT, $courseconfig->groupmode),
630 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
631 VALUE_DEFAULT, $courseconfig->groupmodeforce),
632 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
633 VALUE_DEFAULT, 0),
634 'enablecompletion' => new external_value(PARAM_INT,
8a6b1193 635 'Enabled, control via completion and activity settings. Disabled,
6bb31e40 636 not shown in activity settings.',
637 VALUE_OPTIONAL),
6bb31e40 638 'completionnotify' => new external_value(PARAM_INT,
639 '1: yes 0: no', VALUE_OPTIONAL),
aff24313 640 'lang' => new external_value(PARAM_SAFEDIR,
6bb31e40 641 'forced course language', VALUE_OPTIONAL),
aff24313 642 'forcetheme' => new external_value(PARAM_PLUGIN,
6bb31e40 643 'name of the force theme', VALUE_OPTIONAL),
8d8d4da4 644 'courseformatoptions' => new external_multiple_structure(
0e984d98 645 new external_single_structure(
8d8d4da4
MG
646 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
647 'value' => new external_value(PARAM_RAW, 'course format option value')
0e984d98
MG
648 )),
649 'additional options for particular course format', VALUE_OPTIONAL),
6bb31e40 650 )
651 ), 'courses to create'
652 )
653 )
654 );
655 }
656
657 /**
658 * Create courses
4615817d 659 *
6bb31e40 660 * @param array $courses
661 * @return array courses (id and shortname only)
4615817d 662 * @since Moodle 2.2
6bb31e40 663 */
664 public static function create_courses($courses) {
665 global $CFG, $DB;
666 require_once($CFG->dirroot . "/course/lib.php");
667 require_once($CFG->libdir . '/completionlib.php');
668
6bb31e40 669 $params = self::validate_parameters(self::create_courses_parameters(),
670 array('courses' => $courses));
671
bd3b3bba 672 $availablethemes = core_component::get_plugin_list('theme');
6bb31e40 673 $availablelangs = get_string_manager()->get_list_of_translations();
674
675 $transaction = $DB->start_delegated_transaction();
676
677 foreach ($params['courses'] as $course) {
678
679 // Ensure the current user is allowed to run this function
1f364c87 680 $context = context_coursecat::instance($course['categoryid'], IGNORE_MISSING);
6bb31e40 681 try {
682 self::validate_context($context);
683 } catch (Exception $e) {
684 $exceptionparam = new stdClass();
685 $exceptionparam->message = $e->getMessage();
686 $exceptionparam->catid = $course['categoryid'];
96d3b93b 687 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
6bb31e40 688 }
689 require_capability('moodle/course:create', $context);
690
691 // Make sure lang is valid
12fc8acf 692 if (array_key_exists('lang', $course) and empty($availablelangs[$course['lang']])) {
96d3b93b 693 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
6bb31e40 694 }
695
696 // Make sure theme is valid
12fc8acf 697 if (array_key_exists('forcetheme', $course)) {
6bb31e40 698 if (!empty($CFG->allowcoursethemes)) {
699 if (empty($availablethemes[$course['forcetheme']])) {
96d3b93b 700 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
6bb31e40 701 } else {
702 $course['theme'] = $course['forcetheme'];
703 }
704 }
705 }
706
707 //force visibility if ws user doesn't have the permission to set it
708 $category = $DB->get_record('course_categories', array('id' => $course['categoryid']));
709 if (!has_capability('moodle/course:visibility', $context)) {
710 $course['visible'] = $category->visible;
711 }
712
713 //set default value for completion
8a6b1193 714 $courseconfig = get_config('moodlecourse');
6bb31e40 715 if (completion_info::is_enabled_for_site()) {
12fc8acf 716 if (!array_key_exists('enablecompletion', $course)) {
8a6b1193 717 $course['enablecompletion'] = $courseconfig->enablecompletion;
6bb31e40 718 }
6bb31e40 719 } else {
720 $course['enablecompletion'] = 0;
6bb31e40 721 }
722
723 $course['category'] = $course['categoryid'];
724
93ce0e82
JM
725 // Summary format.
726 $course['summaryformat'] = external_validate_format($course['summaryformat']);
727
8d8d4da4
MG
728 if (!empty($course['courseformatoptions'])) {
729 foreach ($course['courseformatoptions'] as $option) {
730 $course[$option['name']] = $option['value'];
0e984d98
MG
731 }
732 }
733
6bb31e40 734 //Note: create_course() core function check shortname, idnumber, category
735 $course['id'] = create_course((object) $course)->id;
736
737 $resultcourses[] = array('id' => $course['id'], 'shortname' => $course['shortname']);
738 }
739
740 $transaction->allow_commit();
741
742 return $resultcourses;
743 }
744
745 /**
746 * Returns description of method result value
4615817d 747 *
6bb31e40 748 * @return external_description
4615817d 749 * @since Moodle 2.2
6bb31e40 750 */
751 public static function create_courses_returns() {
752 return new external_multiple_structure(
753 new external_single_structure(
754 array(
755 'id' => new external_value(PARAM_INT, 'course id'),
756 'shortname' => new external_value(PARAM_TEXT, 'short name'),
757 )
758 )
759 );
760 }
761
791723c3
RT
762 /**
763 * Update courses
764 *
765 * @return external_function_parameters
766 * @since Moodle 2.5
767 */
768 public static function update_courses_parameters() {
769 return new external_function_parameters(
770 array(
771 'courses' => new external_multiple_structure(
772 new external_single_structure(
773 array(
774 'id' => new external_value(PARAM_INT, 'ID of the course'),
775 'fullname' => new external_value(PARAM_TEXT, 'full name', VALUE_OPTIONAL),
776 'shortname' => new external_value(PARAM_TEXT, 'course short name', VALUE_OPTIONAL),
777 'categoryid' => new external_value(PARAM_INT, 'category id', VALUE_OPTIONAL),
778 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
779 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
780 'summaryformat' => new external_format_value('summary', VALUE_OPTIONAL),
781 'format' => new external_value(PARAM_PLUGIN,
782 'course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
783 'showgrades' => new external_value(PARAM_INT,
784 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
785 'newsitems' => new external_value(PARAM_INT,
786 'number of recent items appearing on the course page', VALUE_OPTIONAL),
787 'startdate' => new external_value(PARAM_INT,
788 'timestamp when the course start', VALUE_OPTIONAL),
fbcdb0d7
DNA
789 'enddate' => new external_value(PARAM_INT,
790 'timestamp when the course end', VALUE_OPTIONAL),
791723c3
RT
791 'numsections' => new external_value(PARAM_INT,
792 '(deprecated, use courseformatoptions) number of weeks/topics', VALUE_OPTIONAL),
793 'maxbytes' => new external_value(PARAM_INT,
794 'largest size of file that can be uploaded into the course', VALUE_OPTIONAL),
795 'showreports' => new external_value(PARAM_INT,
796 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
797 'visible' => new external_value(PARAM_INT,
798 '1: available to student, 0:not available', VALUE_OPTIONAL),
799 'hiddensections' => new external_value(PARAM_INT,
e2adaaf7 800 '(deprecated, use courseformatoptions) How the hidden sections in the course are
791723c3
RT
801 displayed to students', VALUE_OPTIONAL),
802 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
803 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
804 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
805 'enablecompletion' => new external_value(PARAM_INT,
806 'Enabled, control via completion and activity settings. Disabled,
807 not shown in activity settings.', VALUE_OPTIONAL),
791723c3
RT
808 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
809 'lang' => new external_value(PARAM_SAFEDIR, 'forced course language', VALUE_OPTIONAL),
810 'forcetheme' => new external_value(PARAM_PLUGIN, 'name of the force theme', VALUE_OPTIONAL),
811 'courseformatoptions' => new external_multiple_structure(
812 new external_single_structure(
813 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
814 'value' => new external_value(PARAM_RAW, 'course format option value')
815 )),
816 'additional options for particular course format', VALUE_OPTIONAL),
817 )
818 ), 'courses to update'
819 )
820 )
821 );
822 }
823
824 /**
825 * Update courses
826 *
827 * @param array $courses
828 * @since Moodle 2.5
829 */
830 public static function update_courses($courses) {
831 global $CFG, $DB;
832 require_once($CFG->dirroot . "/course/lib.php");
833 $warnings = array();
834
835 $params = self::validate_parameters(self::update_courses_parameters(),
836 array('courses' => $courses));
837
bd3b3bba 838 $availablethemes = core_component::get_plugin_list('theme');
791723c3
RT
839 $availablelangs = get_string_manager()->get_list_of_translations();
840
841 foreach ($params['courses'] as $course) {
842 // Catch any exception while updating course and return as warning to user.
843 try {
844 // Ensure the current user is allowed to run this function.
845 $context = context_course::instance($course['id'], MUST_EXIST);
846 self::validate_context($context);
847
848 $oldcourse = course_get_format($course['id'])->get_course();
849
850 require_capability('moodle/course:update', $context);
851
852 // Check if user can change category.
853 if (array_key_exists('categoryid', $course) && ($oldcourse->category != $course['categoryid'])) {
854 require_capability('moodle/course:changecategory', $context);
855 $course['category'] = $course['categoryid'];
856 }
857
858 // Check if the user can change fullname.
859 if (array_key_exists('fullname', $course) && ($oldcourse->fullname != $course['fullname'])) {
860 require_capability('moodle/course:changefullname', $context);
861 }
862
5536a561 863 // Check if the user can change shortname.
791723c3
RT
864 if (array_key_exists('shortname', $course) && ($oldcourse->shortname != $course['shortname'])) {
865 require_capability('moodle/course:changeshortname', $context);
791723c3
RT
866 }
867
5536a561 868 // Check if the user can change the idnumber.
791723c3
RT
869 if (array_key_exists('idnumber', $course) && ($oldcourse->idnumber != $course['idnumber'])) {
870 require_capability('moodle/course:changeidnumber', $context);
791723c3
RT
871 }
872
873 // Check if user can change summary.
874 if (array_key_exists('summary', $course) && ($oldcourse->summary != $course['summary'])) {
875 require_capability('moodle/course:changesummary', $context);
876 }
877
878 // Summary format.
879 if (array_key_exists('summaryformat', $course) && ($oldcourse->summaryformat != $course['summaryformat'])) {
880 require_capability('moodle/course:changesummary', $context);
881 $course['summaryformat'] = external_validate_format($course['summaryformat']);
882 }
883
884 // Check if user can change visibility.
885 if (array_key_exists('visible', $course) && ($oldcourse->visible != $course['visible'])) {
886 require_capability('moodle/course:visibility', $context);
887 }
888
889 // Make sure lang is valid.
890 if (array_key_exists('lang', $course) && empty($availablelangs[$course['lang']])) {
891 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
892 }
893
894 // Make sure theme is valid.
895 if (array_key_exists('forcetheme', $course)) {
896 if (!empty($CFG->allowcoursethemes)) {
897 if (empty($availablethemes[$course['forcetheme']])) {
898 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
899 } else {
900 $course['theme'] = $course['forcetheme'];
901 }
902 }
903 }
904
905 // Make sure completion is enabled before setting it.
8819a836 906 if (array_key_exists('enabledcompletion', $course) && !completion_info::is_enabled_for_site()) {
791723c3 907 $course['enabledcompletion'] = 0;
791723c3
RT
908 }
909
910 // Make sure maxbytes are less then CFG->maxbytes.
911 if (array_key_exists('maxbytes', $course)) {
912 $course['maxbytes'] = get_max_upload_file_size($CFG->maxbytes, $course['maxbytes']);
913 }
914
915 if (!empty($course['courseformatoptions'])) {
916 foreach ($course['courseformatoptions'] as $option) {
917 if (isset($option['name']) && isset($option['value'])) {
918 $course[$option['name']] = $option['value'];
919 }
920 }
921 }
922
923 // Update course if user has all required capabilities.
924 update_course((object) $course);
925 } catch (Exception $e) {
926 $warning = array();
927 $warning['item'] = 'course';
928 $warning['itemid'] = $course['id'];
929 if ($e instanceof moodle_exception) {
930 $warning['warningcode'] = $e->errorcode;
931 } else {
932 $warning['warningcode'] = $e->getCode();
933 }
934 $warning['message'] = $e->getMessage();
935 $warnings[] = $warning;
936 }
937 }
938
939 $result = array();
940 $result['warnings'] = $warnings;
941 return $result;
942 }
943
944 /**
945 * Returns description of method result value
946 *
947 * @return external_description
948 * @since Moodle 2.5
949 */
950 public static function update_courses_returns() {
951 return new external_single_structure(
952 array(
953 'warnings' => new external_warnings()
954 )
955 );
956 }
957
63a85dc7
JL
958 /**
959 * Returns description of method parameters
3ec163dd 960 *
63a85dc7 961 * @return external_function_parameters
3ec163dd 962 * @since Moodle 2.2
63a85dc7
JL
963 */
964 public static function delete_courses_parameters() {
965 return new external_function_parameters(
966 array(
967 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'course ID')),
968 )
969 );
970 }
971
972 /**
973 * Delete courses
3ec163dd 974 *
63a85dc7 975 * @param array $courseids A list of course ids
3ec163dd 976 * @since Moodle 2.2
63a85dc7
JL
977 */
978 public static function delete_courses($courseids) {
979 global $CFG, $DB;
980 require_once($CFG->dirroot."/course/lib.php");
981
982 // Parameter validation.
983 $params = self::validate_parameters(self::delete_courses_parameters(), array('courseids'=>$courseids));
984
70f37963 985 $warnings = array();
63a85dc7
JL
986
987 foreach ($params['courseids'] as $courseid) {
70f37963
JH
988 $course = $DB->get_record('course', array('id' => $courseid));
989
990 if ($course === false) {
991 $warnings[] = array(
992 'item' => 'course',
993 'itemid' => $courseid,
994 'warningcode' => 'unknowncourseidnumber',
995 'message' => 'Unknown course ID ' . $courseid
996 );
997 continue;
998 }
63a85dc7
JL
999
1000 // Check if the context is valid.
1001 $coursecontext = context_course::instance($course->id);
1002 self::validate_context($coursecontext);
1003
70f37963 1004 // Check if the current user has permission.
63a85dc7 1005 if (!can_delete_course($courseid)) {
70f37963
JH
1006 $warnings[] = array(
1007 'item' => 'course',
1008 'itemid' => $courseid,
1009 'warningcode' => 'cannotdeletecourse',
1010 'message' => 'You do not have the permission to delete this course' . $courseid
1011 );
1012 continue;
63a85dc7
JL
1013 }
1014
70f37963
JH
1015 if (delete_course($course, false) === false) {
1016 $warnings[] = array(
1017 'item' => 'course',
1018 'itemid' => $courseid,
1019 'warningcode' => 'cannotdeletecategorycourse',
1020 'message' => 'Course ' . $courseid . ' failed to be deleted'
1021 );
1022 continue;
1023 }
63a85dc7
JL
1024 }
1025
70f37963 1026 fix_course_sortorder();
63a85dc7 1027
70f37963 1028 return array('warnings' => $warnings);
63a85dc7
JL
1029 }
1030
1031 /**
1032 * Returns description of method result value
3ec163dd 1033 *
63a85dc7 1034 * @return external_description
3ec163dd 1035 * @since Moodle 2.2
63a85dc7
JL
1036 */
1037 public static function delete_courses_returns() {
70f37963
JH
1038 return new external_single_structure(
1039 array(
1040 'warnings' => new external_warnings()
1041 )
1042 );
63a85dc7
JL
1043 }
1044
3dc1d76e
JL
1045 /**
1046 * Returns description of method parameters
1047 *
1048 * @return external_function_parameters
1049 * @since Moodle 2.3
1050 */
1051 public static function duplicate_course_parameters() {
1052 return new external_function_parameters(
1053 array(
1054 'courseid' => new external_value(PARAM_INT, 'course to duplicate id'),
1055 'fullname' => new external_value(PARAM_TEXT, 'duplicated course full name'),
1056 'shortname' => new external_value(PARAM_TEXT, 'duplicated course short name'),
1057 'categoryid' => new external_value(PARAM_INT, 'duplicated course category parent'),
1058 'visible' => new external_value(PARAM_INT, 'duplicated course visible, default to yes', VALUE_DEFAULT, 1),
1059 'options' => new external_multiple_structure(
1060 new external_single_structure(
1061 array(
3dfc29e1 1062 'name' => new external_value(PARAM_ALPHAEXT, 'The backup option name:
9aa84e91
JL
1063 "activities" (int) Include course activites (default to 1 that is equal to yes),
1064 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1065 "filters" (int) Include course filters (default to 1 that is equal to yes),
1066 "users" (int) Include users (default to 0 that is equal to no),
92253b15 1067 "enrolments" (int) Include enrolment methods (default to 1 - restore only with users),
9aa84e91 1068 "role_assignments" (int) Include role assignments (default to 0 that is equal to no),
9aa84e91 1069 "comments" (int) Include user comments (default to 0 that is equal to no),
7469c512 1070 "userscompletion" (int) Include user course completion information (default to 0 that is equal to no),
9aa84e91 1071 "logs" (int) Include course logs (default to 0 that is equal to no),
7469c512 1072 "grade_histories" (int) Include histories (default to 0 that is equal to no)'
9aa84e91
JL
1073 ),
1074 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1075 )
3dc1d76e
JL
1076 )
1077 ), VALUE_DEFAULT, array()
1078 ),
1079 )
1080 );
1081 }
1082
1083 /**
1084 * Duplicate a course
1085 *
1086 * @param int $courseid
1087 * @param string $fullname Duplicated course fullname
1088 * @param string $shortname Duplicated course shortname
1089 * @param int $categoryid Duplicated course parent category id
1090 * @param int $visible Duplicated course availability
1091 * @param array $options List of backup options
1092 * @return array New course info
1093 * @since Moodle 2.3
1094 */
3297d575 1095 public static function duplicate_course($courseid, $fullname, $shortname, $categoryid, $visible = 1, $options = array()) {
3dc1d76e
JL
1096 global $CFG, $USER, $DB;
1097 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1098 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1099
1100 // Parameter validation.
1101 $params = self::validate_parameters(
1102 self::duplicate_course_parameters(),
1103 array(
1104 'courseid' => $courseid,
1105 'fullname' => $fullname,
1106 'shortname' => $shortname,
1107 'categoryid' => $categoryid,
1108 'visible' => $visible,
1109 'options' => $options
1110 )
1111 );
1112
3ec163dd
EL
1113 // Context validation.
1114
1115 if (! ($course = $DB->get_record('course', array('id'=>$params['courseid'])))) {
19a86468 1116 throw new moodle_exception('invalidcourseid', 'error');
3ec163dd
EL
1117 }
1118
1119 // Category where duplicated course is going to be created.
1120 $categorycontext = context_coursecat::instance($params['categoryid']);
1121 self::validate_context($categorycontext);
1122
1123 // Course to be duplicated.
1124 $coursecontext = context_course::instance($course->id);
1125 self::validate_context($coursecontext);
1126
1127 $backupdefaults = array(
1128 'activities' => 1,
1129 'blocks' => 1,
1130 'filters' => 1,
1131 'users' => 0,
92253b15 1132 'enrolments' => backup::ENROL_WITHUSERS,
3ec163dd 1133 'role_assignments' => 0,
3ec163dd 1134 'comments' => 0,
7469c512 1135 'userscompletion' => 0,
3ec163dd 1136 'logs' => 0,
7469c512 1137 'grade_histories' => 0
3ec163dd
EL
1138 );
1139
1140 $backupsettings = array();
1141 // Check for backup and restore options.
1142 if (!empty($params['options'])) {
1143 foreach ($params['options'] as $option) {
1144
1145 // Strict check for a correct value (allways 1 or 0, true or false).
1146 $value = clean_param($option['value'], PARAM_INT);
1147
1148 if ($value !== 0 and $value !== 1) {
1149 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1150 }
1151
1152 if (!isset($backupdefaults[$option['name']])) {
1153 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1154 }
1155
1156 $backupsettings[$option['name']] = $value;
1157 }
1158 }
1159
1160 // Capability checking.
1161
1162 // The backup controller check for this currently, this may be redundant.
1163 require_capability('moodle/course:create', $categorycontext);
1164 require_capability('moodle/restore:restorecourse', $categorycontext);
1165 require_capability('moodle/backup:backupcourse', $coursecontext);
1166
1167 if (!empty($backupsettings['users'])) {
1168 require_capability('moodle/backup:userinfo', $coursecontext);
1169 require_capability('moodle/restore:userinfo', $categorycontext);
1170 }
1171
1172 // Check if the shortname is used.
1173 if ($foundcourses = $DB->get_records('course', array('shortname'=>$shortname))) {
1174 foreach ($foundcourses as $foundcourse) {
1175 $foundcoursenames[] = $foundcourse->fullname;
1176 }
1177
1178 $foundcoursenamestring = implode(',', $foundcoursenames);
1179 throw new moodle_exception('shortnametaken', '', '', $foundcoursenamestring);
1180 }
1181
1182 // Backup the course.
1183
1184 $bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE,
1185 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id);
1186
1187 foreach ($backupsettings as $name => $value) {
92253b15
MG
1188 if ($setting = $bc->get_plan()->get_setting($name)) {
1189 $bc->get_plan()->get_setting($name)->set_value($value);
1190 }
3ec163dd
EL
1191 }
1192
1193 $backupid = $bc->get_backupid();
1194 $backupbasepath = $bc->get_plan()->get_basepath();
1195
1196 $bc->execute_plan();
1197 $results = $bc->get_results();
1198 $file = $results['backup_destination'];
1199
1200 $bc->destroy();
1201
1202 // Restore the backup immediately.
1203
1204 // Check if we need to unzip the file because the backup temp dir does not contains backup files.
1205 if (!file_exists($backupbasepath . "/moodle_backup.xml")) {
00219425 1206 $file->extract_to_pathname(get_file_packer('application/vnd.moodle.backup'), $backupbasepath);
3ec163dd
EL
1207 }
1208
1209 // Create new course.
1210 $newcourseid = restore_dbops::create_new_course($params['fullname'], $params['shortname'], $params['categoryid']);
1211
1212 $rc = new restore_controller($backupid, $newcourseid,
1213 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id, backup::TARGET_NEW_COURSE);
1214
1215 foreach ($backupsettings as $name => $value) {
1216 $setting = $rc->get_plan()->get_setting($name);
1217 if ($setting->get_status() == backup_setting::NOT_LOCKED) {
1218 $setting->set_value($value);
1219 }
1220 }
1221
1222 if (!$rc->execute_precheck()) {
1223 $precheckresults = $rc->get_precheck_results();
1224 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1225 if (empty($CFG->keeptempdirectoriesonbackup)) {
1226 fulldelete($backupbasepath);
1227 }
1228
1229 $errorinfo = '';
1230
1231 foreach ($precheckresults['errors'] as $error) {
1232 $errorinfo .= $error;
1233 }
1234
1235 if (array_key_exists('warnings', $precheckresults)) {
1236 foreach ($precheckresults['warnings'] as $warning) {
1237 $errorinfo .= $warning;
1238 }
1239 }
1240
1241 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1242 }
1243 }
1244
1245 $rc->execute_plan();
1246 $rc->destroy();
1247
1248 $course = $DB->get_record('course', array('id' => $newcourseid), '*', MUST_EXIST);
1249 $course->fullname = $params['fullname'];
1250 $course->shortname = $params['shortname'];
1251 $course->visible = $params['visible'];
1252
1253 // Set shortname and fullname back.
1254 $DB->update_record('course', $course);
1255
1256 if (empty($CFG->keeptempdirectoriesonbackup)) {
1257 fulldelete($backupbasepath);
1258 }
1259
1260 // Delete the course backup file created by this WebService. Originally located in the course backups area.
1261 $file->delete();
1262
1263 return array('id' => $course->id, 'shortname' => $course->shortname);
1264 }
1265
1266 /**
1267 * Returns description of method result value
1268 *
1269 * @return external_description
1270 * @since Moodle 2.3
1271 */
1272 public static function duplicate_course_returns() {
1273 return new external_single_structure(
1274 array(
1275 'id' => new external_value(PARAM_INT, 'course id'),
1276 'shortname' => new external_value(PARAM_TEXT, 'short name'),
1277 )
1278 );
1279 }
1280
8430d87b 1281 /**
c1483c9c 1282 * Returns description of method parameters for import_course
8430d87b
JL
1283 *
1284 * @return external_function_parameters
c1483c9c 1285 * @since Moodle 2.4
8430d87b
JL
1286 */
1287 public static function import_course_parameters() {
1288 return new external_function_parameters(
1289 array(
1290 'importfrom' => new external_value(PARAM_INT, 'the id of the course we are importing from'),
1291 'importto' => new external_value(PARAM_INT, 'the id of the course we are importing to'),
1292 'deletecontent' => new external_value(PARAM_INT, 'whether to delete the course content where we are importing to (default to 0 = No)', VALUE_DEFAULT, 0),
1293 'options' => new external_multiple_structure(
1294 new external_single_structure(
1295 array(
1296 'name' => new external_value(PARAM_ALPHA, 'The backup option name:
1297 "activities" (int) Include course activites (default to 1 that is equal to yes),
1298 "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1299 "filters" (int) Include course filters (default to 1 that is equal to yes)'
1300 ),
1301 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1302 )
1303 )
1304 ), VALUE_DEFAULT, array()
1305 ),
1306 )
1307 );
1308 }
1309
1310 /**
1311 * Imports a course
1312 *
1313 * @param int $importfrom The id of the course we are importing from
1314 * @param int $importto The id of the course we are importing to
1315 * @param bool $deletecontent Whether to delete the course we are importing to content
1316 * @param array $options List of backup options
1317 * @return null
c1483c9c 1318 * @since Moodle 2.4
8430d87b 1319 */
b5bd42e8 1320 public static function import_course($importfrom, $importto, $deletecontent = 0, $options = array()) {
8430d87b
JL
1321 global $CFG, $USER, $DB;
1322 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1323 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1324
1325 // Parameter validation.
1326 $params = self::validate_parameters(
c1483c9c
SH
1327 self::import_course_parameters(),
1328 array(
1329 'importfrom' => $importfrom,
1330 'importto' => $importto,
1331 'deletecontent' => $deletecontent,
1332 'options' => $options
1333 )
8430d87b
JL
1334 );
1335
1336 if ($params['deletecontent'] !== 0 and $params['deletecontent'] !== 1) {
1b2f5493 1337 throw new moodle_exception('invalidextparam', 'webservice', '', $params['deletecontent']);
8430d87b
JL
1338 }
1339
1340 // Context validation.
1341
1342 if (! ($importfrom = $DB->get_record('course', array('id'=>$params['importfrom'])))) {
0b9a3d7a 1343 throw new moodle_exception('invalidcourseid', 'error');
8430d87b
JL
1344 }
1345
1346 if (! ($importto = $DB->get_record('course', array('id'=>$params['importto'])))) {
0b9a3d7a 1347 throw new moodle_exception('invalidcourseid', 'error');
8430d87b
JL
1348 }
1349
1350 $importfromcontext = context_course::instance($importfrom->id);
1351 self::validate_context($importfromcontext);
1352
1353 $importtocontext = context_course::instance($importto->id);
1354 self::validate_context($importtocontext);
1355
1356 $backupdefaults = array(
c1483c9c
SH
1357 'activities' => 1,
1358 'blocks' => 1,
1359 'filters' => 1
8430d87b
JL
1360 );
1361
1362 $backupsettings = array();
1363
1364 // Check for backup and restore options.
1365 if (!empty($params['options'])) {
1366 foreach ($params['options'] as $option) {
1367
1368 // Strict check for a correct value (allways 1 or 0, true or false).
1369 $value = clean_param($option['value'], PARAM_INT);
1370
1371 if ($value !== 0 and $value !== 1) {
1372 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1373 }
1374
1375 if (!isset($backupdefaults[$option['name']])) {
1376 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1377 }
1378
1379 $backupsettings[$option['name']] = $value;
1380 }
1381 }
1382
1383 // Capability checking.
1384
1385 require_capability('moodle/backup:backuptargetimport', $importfromcontext);
1386 require_capability('moodle/restore:restoretargetimport', $importtocontext);
1387
1388 $bc = new backup_controller(backup::TYPE_1COURSE, $importfrom->id, backup::FORMAT_MOODLE,
1389 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
1390
1391 foreach ($backupsettings as $name => $value) {
1392 $bc->get_plan()->get_setting($name)->set_value($value);
1393 }
1394
1395 $backupid = $bc->get_backupid();
1396 $backupbasepath = $bc->get_plan()->get_basepath();
1397
1398 $bc->execute_plan();
1399 $bc->destroy();
1400
1401 // Restore the backup immediately.
1402
1403 // Check if we must delete the contents of the destination course.
1404 if ($params['deletecontent']) {
1405 $restoretarget = backup::TARGET_EXISTING_DELETING;
1406 } else {
1407 $restoretarget = backup::TARGET_EXISTING_ADDING;
1408 }
1409
1410 $rc = new restore_controller($backupid, $importto->id,
1411 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, $restoretarget);
1412
1413 foreach ($backupsettings as $name => $value) {
1414 $rc->get_plan()->get_setting($name)->set_value($value);
1415 }
1416
1417 if (!$rc->execute_precheck()) {
1418 $precheckresults = $rc->get_precheck_results();
1419 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1420 if (empty($CFG->keeptempdirectoriesonbackup)) {
1421 fulldelete($backupbasepath);
1422 }
1423
1424 $errorinfo = '';
1425
1426 foreach ($precheckresults['errors'] as $error) {
1427 $errorinfo .= $error;
1428 }
1429
1430 if (array_key_exists('warnings', $precheckresults)) {
1431 foreach ($precheckresults['warnings'] as $warning) {
1432 $errorinfo .= $warning;
1433 }
1434 }
1435
1436 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1437 }
1438 } else {
1439 if ($restoretarget == backup::TARGET_EXISTING_DELETING) {
1440 restore_dbops::delete_course_content($importto->id);
1441 }
1442 }
1443
1444 $rc->execute_plan();
1445 $rc->destroy();
1446
1447 if (empty($CFG->keeptempdirectoriesonbackup)) {
1448 fulldelete($backupbasepath);
1449 }
1450
1451 return null;
1452 }
1453
1454 /**
1455 * Returns description of method result value
1456 *
1457 * @return external_description
c1483c9c 1458 * @since Moodle 2.4
8430d87b
JL
1459 */
1460 public static function import_course_returns() {
1461 return null;
1462 }
1463
3ec163dd
EL
1464 /**
1465 * Returns description of method parameters
1466 *
1467 * @return external_function_parameters
1468 * @since Moodle 2.3
1469 */
1470 public static function get_categories_parameters() {
1471 return new external_function_parameters(
1472 array(
1473 'criteria' => new external_multiple_structure(
1474 new external_single_structure(
1475 array(
1476 'key' => new external_value(PARAM_ALPHA,
1477 'The category column to search, expected keys (value format) are:'.
1478 '"id" (int) the category id,'.
c1da311a 1479 '"ids" (string) category ids separated by commas,'.
3ec163dd
EL
1480 '"name" (string) the category name,'.
1481 '"parent" (int) the parent category id,'.
1482 '"idnumber" (string) category idnumber'.
1483 ' - user must have \'moodle/category:manage\' to search on idnumber,'.
e6d1218a
JM
1484 '"visible" (int) whether the returned categories must be visible or hidden. If the key is not passed,
1485 then the function return all categories that the user can see.'.
3ec163dd 1486 ' - user must have \'moodle/category:manage\' or \'moodle/category:viewhiddencategories\' to search on visible,'.
e6d1218a 1487 '"theme" (string) only return the categories having this theme'.
3ec163dd
EL
1488 ' - user must have \'moodle/category:manage\' to search on theme'),
1489 'value' => new external_value(PARAM_RAW, 'the value to match')
1490 )
7a384506 1491 ), 'criteria', VALUE_DEFAULT, array()
3ec163dd
EL
1492 ),
1493 'addsubcategories' => new external_value(PARAM_BOOL, 'return the sub categories infos
1494 (1 - default) otherwise only the category info (0)', VALUE_DEFAULT, 1)
1495 )
1496 );
1497 }
1498
1499 /**
1500 * Get categories
1501 *
1502 * @param array $criteria Criteria to match the results
1503 * @param booln $addsubcategories obtain only the category (false) or its subcategories (true - default)
1504 * @return array list of categories
1505 * @since Moodle 2.3
1506 */
1507 public static function get_categories($criteria = array(), $addsubcategories = true) {
1508 global $CFG, $DB;
1509 require_once($CFG->dirroot . "/course/lib.php");
1510
1511 // Validate parameters.
1512 $params = self::validate_parameters(self::get_categories_parameters(),
1513 array('criteria' => $criteria, 'addsubcategories' => $addsubcategories));
1514
1515 // Retrieve the categories.
1516 $categories = array();
1517 if (!empty($params['criteria'])) {
1518
1519 $conditions = array();
1520 $wheres = array();
1521 foreach ($params['criteria'] as $crit) {
1522 $key = trim($crit['key']);
1523
1524 // Trying to avoid duplicate keys.
1525 if (!isset($conditions[$key])) {
3dc1d76e 1526
3ec163dd
EL
1527 $context = context_system::instance();
1528 $value = null;
1529 switch ($key) {
1530 case 'id':
1531 $value = clean_param($crit['value'], PARAM_INT);
c1da311a
JL
1532 $conditions[$key] = $value;
1533 $wheres[] = $key . " = :" . $key;
1534 break;
1535
1536 case 'ids':
1537 $value = clean_param($crit['value'], PARAM_SEQUENCE);
1538 $ids = explode(',', $value);
1539 list($sqlids, $paramids) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED);
1540 $conditions = array_merge($conditions, $paramids);
1541 $wheres[] = 'id ' . $sqlids;
3ec163dd 1542 break;
3dc1d76e 1543
3ec163dd
EL
1544 case 'idnumber':
1545 if (has_capability('moodle/category:manage', $context)) {
1546 $value = clean_param($crit['value'], PARAM_RAW);
c1da311a
JL
1547 $conditions[$key] = $value;
1548 $wheres[] = $key . " = :" . $key;
3ec163dd
EL
1549 } else {
1550 // We must throw an exception.
1551 // Otherwise the dev client would think no idnumber exists.
1552 throw new moodle_exception('criteriaerror',
1553 'webservice', '', null,
1554 'You don\'t have the permissions to search on the "idnumber" field.');
1555 }
1556 break;
3dc1d76e 1557
3ec163dd
EL
1558 case 'name':
1559 $value = clean_param($crit['value'], PARAM_TEXT);
c1da311a
JL
1560 $conditions[$key] = $value;
1561 $wheres[] = $key . " = :" . $key;
3ec163dd 1562 break;
3dc1d76e 1563
3ec163dd
EL
1564 case 'parent':
1565 $value = clean_param($crit['value'], PARAM_INT);
c1da311a
JL
1566 $conditions[$key] = $value;
1567 $wheres[] = $key . " = :" . $key;
3ec163dd 1568 break;
9aa84e91 1569
3ec163dd
EL
1570 case 'visible':
1571 if (has_capability('moodle/category:manage', $context)
1572 or has_capability('moodle/category:viewhiddencategories',
1573 context_system::instance())) {
1574 $value = clean_param($crit['value'], PARAM_INT);
c1da311a
JL
1575 $conditions[$key] = $value;
1576 $wheres[] = $key . " = :" . $key;
3ec163dd
EL
1577 } else {
1578 throw new moodle_exception('criteriaerror',
1579 'webservice', '', null,
1580 'You don\'t have the permissions to search on the "visible" field.');
1581 }
1582 break;
9aa84e91 1583
3ec163dd
EL
1584 case 'theme':
1585 if (has_capability('moodle/category:manage', $context)) {
1586 $value = clean_param($crit['value'], PARAM_THEME);
c1da311a
JL
1587 $conditions[$key] = $value;
1588 $wheres[] = $key . " = :" . $key;
3ec163dd
EL
1589 } else {
1590 throw new moodle_exception('criteriaerror',
1591 'webservice', '', null,
1592 'You don\'t have the permissions to search on the "theme" field.');
1593 }
1594 break;
9aa84e91 1595
3ec163dd
EL
1596 default:
1597 throw new moodle_exception('criteriaerror',
1598 'webservice', '', null,
1599 'You can not search on this criteria: ' . $key);
1600 }
9aa84e91 1601 }
9aa84e91 1602 }
9aa84e91 1603
3ec163dd
EL
1604 if (!empty($wheres)) {
1605 $wheres = implode(" AND ", $wheres);
3dc1d76e 1606
3ec163dd 1607 $categories = $DB->get_records_select('course_categories', $wheres, $conditions);
3dc1d76e 1608
3ec163dd
EL
1609 // Retrieve its sub subcategories (all levels).
1610 if ($categories and !empty($params['addsubcategories'])) {
1611 $newcategories = array();
9aa84e91 1612
e6d1218a
JM
1613 // Check if we required visible/theme checks.
1614 $additionalselect = '';
1615 $additionalparams = array();
1616 if (isset($conditions['visible'])) {
1617 $additionalselect .= ' AND visible = :visible';
1618 $additionalparams['visible'] = $conditions['visible'];
1619 }
1620 if (isset($conditions['theme'])) {
1621 $additionalselect .= ' AND theme= :theme';
1622 $additionalparams['theme'] = $conditions['theme'];
1623 }
1624
3ec163dd 1625 foreach ($categories as $category) {
e6d1218a
JM
1626 $sqlselect = $DB->sql_like('path', ':path') . $additionalselect;
1627 $sqlparams = array('path' => $category->path.'/%') + $additionalparams; // It will NOT include the specified category.
1628 $subcategories = $DB->get_records_select('course_categories', $sqlselect, $sqlparams);
3ec163dd
EL
1629 $newcategories = $newcategories + $subcategories; // Both arrays have integer as keys.
1630 }
1631 $categories = $categories + $newcategories;
1632 }
3dc1d76e
JL
1633 }
1634
3ec163dd
EL
1635 } else {
1636 // Retrieve all categories in the database.
1637 $categories = $DB->get_records('course_categories');
3dc1d76e
JL
1638 }
1639
3ec163dd
EL
1640 // The not returned categories. key => category id, value => reason of exclusion.
1641 $excludedcats = array();
3dc1d76e 1642
3ec163dd
EL
1643 // The returned categories.
1644 $categoriesinfo = array();
6c7d3e31 1645
3ec163dd
EL
1646 // We need to sort the categories by path.
1647 // The parent cats need to be checked by the algo first.
1648 usort($categories, "core_course_external::compare_categories_by_path");
3dc1d76e 1649
3ec163dd 1650 foreach ($categories as $category) {
3dc1d76e 1651
3ec163dd
EL
1652 // Check if the category is a child of an excluded category, if yes exclude it too (excluded => do not return).
1653 $parents = explode('/', $category->path);
1654 unset($parents[0]); // First key is always empty because path start with / => /1/2/4.
1655 foreach ($parents as $parentid) {
1656 // Note: when the parent exclusion was due to the context,
1657 // the sub category could still be returned.
1658 if (isset($excludedcats[$parentid]) and $excludedcats[$parentid] != 'context') {
1659 $excludedcats[$category->id] = 'parent';
1660 }
1661 }
9aa84e91 1662
3ec163dd
EL
1663 // Check the user can use the category context.
1664 $context = context_coursecat::instance($category->id);
1665 try {
1666 self::validate_context($context);
1667 } catch (Exception $e) {
1668 $excludedcats[$category->id] = 'context';
3dc1d76e 1669
3ec163dd
EL
1670 // If it was the requested category then throw an exception.
1671 if (isset($params['categoryid']) && $category->id == $params['categoryid']) {
1672 $exceptionparam = new stdClass();
1673 $exceptionparam->message = $e->getMessage();
1674 $exceptionparam->catid = $category->id;
1675 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
1676 }
9aa84e91 1677 }
3dc1d76e 1678
3ec163dd
EL
1679 // Return the category information.
1680 if (!isset($excludedcats[$category->id])) {
3dc1d76e 1681
3ec163dd
EL
1682 // Final check to see if the category is visible to the user.
1683 if ($category->visible
1684 or has_capability('moodle/category:viewhiddencategories', context_system::instance())
1685 or has_capability('moodle/category:manage', $context)) {
3dc1d76e 1686
3ec163dd
EL
1687 $categoryinfo = array();
1688 $categoryinfo['id'] = $category->id;
1689 $categoryinfo['name'] = $category->name;
93ce0e82
JM
1690 list($categoryinfo['description'], $categoryinfo['descriptionformat']) =
1691 external_format_text($category->description, $category->descriptionformat,
1692 $context->id, 'coursecat', 'description', null);
3ec163dd
EL
1693 $categoryinfo['parent'] = $category->parent;
1694 $categoryinfo['sortorder'] = $category->sortorder;
1695 $categoryinfo['coursecount'] = $category->coursecount;
1696 $categoryinfo['depth'] = $category->depth;
1697 $categoryinfo['path'] = $category->path;
3dc1d76e 1698
3ec163dd
EL
1699 // Some fields only returned for admin.
1700 if (has_capability('moodle/category:manage', $context)) {
1701 $categoryinfo['idnumber'] = $category->idnumber;
1702 $categoryinfo['visible'] = $category->visible;
1703 $categoryinfo['visibleold'] = $category->visibleold;
1704 $categoryinfo['timemodified'] = $category->timemodified;
1705 $categoryinfo['theme'] = $category->theme;
3dc1d76e 1706 }
3dc1d76e 1707
3ec163dd
EL
1708 $categoriesinfo[] = $categoryinfo;
1709 } else {
1710 $excludedcats[$category->id] = 'visibility';
1711 }
3dc1d76e
JL
1712 }
1713 }
1714
3ec163dd
EL
1715 // Sorting the resulting array so it looks a bit better for the client developer.
1716 usort($categoriesinfo, "core_course_external::compare_categories_by_sortorder");
3dc1d76e 1717
3ec163dd
EL
1718 return $categoriesinfo;
1719 }
3dc1d76e 1720
3ec163dd
EL
1721 /**
1722 * Sort categories array by path
1723 * private function: only used by get_categories
1724 *
1725 * @param array $category1
1726 * @param array $category2
1727 * @return int result of strcmp
1728 * @since Moodle 2.3
1729 */
1730 private static function compare_categories_by_path($category1, $category2) {
1731 return strcmp($category1->path, $category2->path);
1732 }
6c7d3e31 1733
3ec163dd
EL
1734 /**
1735 * Sort categories array by sortorder
1736 * private function: only used by get_categories
1737 *
1738 * @param array $category1
1739 * @param array $category2
1740 * @return int result of strcmp
1741 * @since Moodle 2.3
1742 */
1743 private static function compare_categories_by_sortorder($category1, $category2) {
1744 return strcmp($category1['sortorder'], $category2['sortorder']);
3dc1d76e
JL
1745 }
1746
1747 /**
1748 * Returns description of method result value
1749 *
1750 * @return external_description
1751 * @since Moodle 2.3
1752 */
3ec163dd
EL
1753 public static function get_categories_returns() {
1754 return new external_multiple_structure(
1755 new external_single_structure(
1756 array(
1757 'id' => new external_value(PARAM_INT, 'category id'),
1758 'name' => new external_value(PARAM_TEXT, 'category name'),
1759 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1760 'description' => new external_value(PARAM_RAW, 'category description'),
93ce0e82 1761 'descriptionformat' => new external_format_value('description'),
3ec163dd
EL
1762 'parent' => new external_value(PARAM_INT, 'parent category id'),
1763 'sortorder' => new external_value(PARAM_INT, 'category sorting order'),
1764 'coursecount' => new external_value(PARAM_INT, 'number of courses in this category'),
1765 'visible' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1766 'visibleold' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1767 'timemodified' => new external_value(PARAM_INT, 'timestamp', VALUE_OPTIONAL),
1768 'depth' => new external_value(PARAM_INT, 'category depth'),
1769 'path' => new external_value(PARAM_TEXT, 'category path'),
1770 'theme' => new external_value(PARAM_THEME, 'category theme', VALUE_OPTIONAL),
1771 ), 'List of categories'
3dc1d76e
JL
1772 )
1773 );
1774 }
1775
2f951d86
FS
1776 /**
1777 * Returns description of method parameters
3ec163dd 1778 *
2f951d86
FS
1779 * @return external_function_parameters
1780 * @since Moodle 2.3
1781 */
3ec163dd 1782 public static function create_categories_parameters() {
2f951d86
FS
1783 return new external_function_parameters(
1784 array(
1785 'categories' => new external_multiple_structure(
3ec163dd
EL
1786 new external_single_structure(
1787 array(
1788 'name' => new external_value(PARAM_TEXT, 'new category name'),
1789 'parent' => new external_value(PARAM_INT,
9615b623
JM
1790 'the parent category id inside which the new category will be created
1791 - set to 0 for a root category',
1792 VALUE_DEFAULT, 0),
3ec163dd
EL
1793 'idnumber' => new external_value(PARAM_RAW,
1794 'the new category idnumber', VALUE_OPTIONAL),
1795 'description' => new external_value(PARAM_RAW,
1796 'the new category description', VALUE_OPTIONAL),
93ce0e82 1797 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
3ec163dd
EL
1798 'theme' => new external_value(PARAM_THEME,
1799 'the new category theme. This option must be enabled on moodle',
1800 VALUE_OPTIONAL),
2f951d86
FS
1801 )
1802 )
1803 )
1804 )
1805 );
1806 }
1807
1808 /**
3ec163dd
EL
1809 * Create categories
1810 *
1811 * @param array $categories - see create_categories_parameters() for the array structure
1812 * @return array - see create_categories_returns() for the array structure
2f951d86
FS
1813 * @since Moodle 2.3
1814 */
3ec163dd 1815 public static function create_categories($categories) {
2f951d86 1816 global $CFG, $DB;
9bad61db 1817 require_once($CFG->libdir . "/coursecatlib.php");
2f951d86 1818
3ec163dd
EL
1819 $params = self::validate_parameters(self::create_categories_parameters(),
1820 array('categories' => $categories));
2f951d86 1821
3ec163dd
EL
1822 $transaction = $DB->start_delegated_transaction();
1823
1824 $createdcategories = array();
2f951d86 1825 foreach ($params['categories'] as $category) {
3ec163dd
EL
1826 if ($category['parent']) {
1827 if (!$DB->record_exists('course_categories', array('id' => $category['parent']))) {
1828 throw new moodle_exception('unknowcategory');
1829 }
1830 $context = context_coursecat::instance($category['parent']);
1831 } else {
1832 $context = context_system::instance();
2f951d86 1833 }
2f951d86 1834 self::validate_context($context);
3ec163dd 1835 require_capability('moodle/category:manage', $context);
2f951d86 1836
9bad61db
MG
1837 // this will validate format and throw an exception if there are errors
1838 external_validate_format($category['descriptionformat']);
3ec163dd 1839
9bad61db 1840 $newcategory = coursecat::create($category);
3ec163dd
EL
1841
1842 $createdcategories[] = array('id' => $newcategory->id, 'name' => $newcategory->name);
2f951d86
FS
1843 }
1844
3ec163dd
EL
1845 $transaction->allow_commit();
1846
1847 return $createdcategories;
2f951d86
FS
1848 }
1849
1850 /**
1851 * Returns description of method parameters
3ec163dd 1852 *
2f951d86
FS
1853 * @return external_function_parameters
1854 * @since Moodle 2.3
1855 */
3ec163dd
EL
1856 public static function create_categories_returns() {
1857 return new external_multiple_structure(
1858 new external_single_structure(
1859 array(
1860 'id' => new external_value(PARAM_INT, 'new category id'),
1861 'name' => new external_value(PARAM_TEXT, 'new category name'),
1862 )
1863 )
1864 );
2f951d86 1865 }
f2229c68
FS
1866
1867 /**
1868 * Returns description of method parameters
3ec163dd 1869 *
f2229c68
FS
1870 * @return external_function_parameters
1871 * @since Moodle 2.3
1872 */
1873 public static function update_categories_parameters() {
1874 return new external_function_parameters(
1875 array(
1876 'categories' => new external_multiple_structure(
1877 new external_single_structure(
1878 array(
1879 'id' => new external_value(PARAM_INT, 'course id'),
1880 'name' => new external_value(PARAM_TEXT, 'category name', VALUE_OPTIONAL),
1881 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1882 'parent' => new external_value(PARAM_INT, 'parent category id', VALUE_OPTIONAL),
1883 'description' => new external_value(PARAM_RAW, 'category description', VALUE_OPTIONAL),
93ce0e82 1884 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
f2229c68
FS
1885 'theme' => new external_value(PARAM_THEME,
1886 'the category theme. This option must be enabled on moodle', VALUE_OPTIONAL),
1887 )
1888 )
1889 )
1890 )
1891 );
1892 }
1893
1894 /**
1895 * Update categories
3ec163dd 1896 *
f2229c68
FS
1897 * @param array $categories The list of categories to update
1898 * @return null
1899 * @since Moodle 2.3
1900 */
1901 public static function update_categories($categories) {
1902 global $CFG, $DB;
6e1d1ee0 1903 require_once($CFG->libdir . "/coursecatlib.php");
f2229c68
FS
1904
1905 // Validate parameters.
1906 $params = self::validate_parameters(self::update_categories_parameters(), array('categories' => $categories));
1907
1908 $transaction = $DB->start_delegated_transaction();
1909
1910 foreach ($params['categories'] as $cat) {
9bad61db 1911 $category = coursecat::get($cat['id']);
f2229c68
FS
1912
1913 $categorycontext = context_coursecat::instance($cat['id']);
1914 self::validate_context($categorycontext);
1915 require_capability('moodle/category:manage', $categorycontext);
1916
9bad61db
MG
1917 // this will throw an exception if descriptionformat is not valid
1918 external_validate_format($cat['descriptionformat']);
1919
1920 $category->update($cat);
f2229c68
FS
1921 }
1922
1923 $transaction->allow_commit();
1924 }
1925
1926 /**
1927 * Returns description of method result value
3ec163dd 1928 *
f2229c68 1929 * @return external_description
3ec163dd 1930 * @since Moodle 2.3
f2229c68
FS
1931 */
1932 public static function update_categories_returns() {
1933 return null;
1934 }
3ec163dd
EL
1935
1936 /**
1937 * Returns description of method parameters
1938 *
1939 * @return external_function_parameters
1940 * @since Moodle 2.3
1941 */
1942 public static function delete_categories_parameters() {
1943 return new external_function_parameters(
1944 array(
1945 'categories' => new external_multiple_structure(
1946 new external_single_structure(
1947 array(
1948 'id' => new external_value(PARAM_INT, 'category id to delete'),
1949 'newparent' => new external_value(PARAM_INT,
1950 'the parent category to move the contents to, if specified', VALUE_OPTIONAL),
1951 'recursive' => new external_value(PARAM_BOOL, '1: recursively delete all contents inside this
1952 category, 0 (default): move contents to newparent or current parent category (except if parent is root)', VALUE_DEFAULT, 0)
1953 )
1954 )
1955 )
1956 )
1957 );
1958 }
1959
1960 /**
1961 * Delete categories
1962 *
1963 * @param array $categories A list of category ids
1964 * @return array
1965 * @since Moodle 2.3
1966 */
1967 public static function delete_categories($categories) {
1968 global $CFG, $DB;
1969 require_once($CFG->dirroot . "/course/lib.php");
deb65ced 1970 require_once($CFG->libdir . "/coursecatlib.php");
3ec163dd
EL
1971
1972 // Validate parameters.
1973 $params = self::validate_parameters(self::delete_categories_parameters(), array('categories' => $categories));
1974
f823158b
EL
1975 $transaction = $DB->start_delegated_transaction();
1976
3ec163dd 1977 foreach ($params['categories'] as $category) {
deb65ced 1978 $deletecat = coursecat::get($category['id'], MUST_EXIST);
3ec163dd
EL
1979 $context = context_coursecat::instance($deletecat->id);
1980 require_capability('moodle/category:manage', $context);
1981 self::validate_context($context);
1982 self::validate_context(get_category_or_system_context($deletecat->parent));
1983
1984 if ($category['recursive']) {
1985 // If recursive was specified, then we recursively delete the category's contents.
deb65ced
MG
1986 if ($deletecat->can_delete_full()) {
1987 $deletecat->delete_full(false);
1988 } else {
1989 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
1990 }
3ec163dd
EL
1991 } else {
1992 // In this situation, we don't delete the category's contents, we either move it to newparent or parent.
1993 // If the parent is the root, moving is not supported (because a course must always be inside a category).
1994 // We must move to an existing category.
1995 if (!empty($category['newparent'])) {
deb65ced 1996 $newparentcat = coursecat::get($category['newparent']);
3ec163dd 1997 } else {
deb65ced 1998 $newparentcat = coursecat::get($deletecat->parent);
3ec163dd
EL
1999 }
2000
2001 // This operation is not allowed. We must move contents to an existing category.
deb65ced 2002 if (!$newparentcat->id) {
3ec163dd
EL
2003 throw new moodle_exception('movecatcontentstoroot');
2004 }
2005
deb65ced
MG
2006 self::validate_context(context_coursecat::instance($newparentcat->id));
2007 if ($deletecat->can_move_content_to($newparentcat->id)) {
2008 $deletecat->delete_move($newparentcat->id, false);
2009 } else {
2010 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2011 }
3ec163dd
EL
2012 }
2013 }
2014
f823158b 2015 $transaction->allow_commit();
3ec163dd
EL
2016 }
2017
2018 /**
2019 * Returns description of method parameters
2020 *
2021 * @return external_function_parameters
2022 * @since Moodle 2.3
2023 */
2024 public static function delete_categories_returns() {
2025 return null;
2026 }
2027
79949c1b
MN
2028 /**
2029 * Describes the parameters for delete_modules.
2030 *
9db43c73 2031 * @return external_function_parameters
79949c1b
MN
2032 * @since Moodle 2.5
2033 */
2034 public static function delete_modules_parameters() {
2035 return new external_function_parameters (
2036 array(
2037 'cmids' => new external_multiple_structure(new external_value(PARAM_INT, 'course module ID',
2038 VALUE_REQUIRED, '', NULL_NOT_ALLOWED), 'Array of course module IDs'),
2039 )
2040 );
2041 }
2042
2043 /**
2044 * Deletes a list of provided module instances.
2045 *
2046 * @param array $cmids the course module ids
2047 * @since Moodle 2.5
2048 */
2049 public static function delete_modules($cmids) {
2050 global $CFG, $DB;
2051
2052 // Require course file containing the course delete module function.
2053 require_once($CFG->dirroot . "/course/lib.php");
2054
2055 // Clean the parameters.
2056 $params = self::validate_parameters(self::delete_modules_parameters(), array('cmids' => $cmids));
2057
2058 // Keep track of the course ids we have performed a capability check on to avoid repeating.
2059 $arrcourseschecked = array();
2060
2061 foreach ($params['cmids'] as $cmid) {
2062 // Get the course module.
2063 $cm = $DB->get_record('course_modules', array('id' => $cmid), '*', MUST_EXIST);
2064
2065 // Check if we have not yet confirmed they have permission in this course.
2066 if (!in_array($cm->course, $arrcourseschecked)) {
2067 // Ensure the current user has required permission in this course.
2068 $context = context_course::instance($cm->course);
2069 self::validate_context($context);
2070 // Add to the array.
2071 $arrcourseschecked[] = $cm->course;
2072 }
2073
2074 // Ensure they can delete this module.
2075 $modcontext = context_module::instance($cm->id);
2076 require_capability('moodle/course:manageactivities', $modcontext);
2077
2078 // Delete the module.
2079 course_delete_module($cm->id);
2080 }
2081 }
2082
2083 /**
2084 * Describes the delete_modules return value.
2085 *
2086 * @return external_single_structure
2087 * @since Moodle 2.5
2088 */
2089 public static function delete_modules_returns() {
2090 return null;
2091 }
7aed00d5
JL
2092
2093 /**
2094 * Returns description of method parameters
2095 *
2096 * @return external_function_parameters
2097 * @since Moodle 2.9
2098 */
2099 public static function view_course_parameters() {
2100 return new external_function_parameters(
2101 array(
2102 'courseid' => new external_value(PARAM_INT, 'id of the course'),
2103 'sectionnumber' => new external_value(PARAM_INT, 'section number', VALUE_DEFAULT, 0)
2104 )
2105 );
2106 }
2107
2108 /**
1c2b7882 2109 * Trigger the course viewed event.
7aed00d5
JL
2110 *
2111 * @param int $courseid id of course
2112 * @param int $sectionnumber sectionnumber (0, 1, 2...)
2113 * @return array of warnings and status result
2114 * @since Moodle 2.9
2115 * @throws moodle_exception
2116 */
2117 public static function view_course($courseid, $sectionnumber = 0) {
2118 global $CFG;
2119 require_once($CFG->dirroot . "/course/lib.php");
2120
2121 $params = self::validate_parameters(self::view_course_parameters(),
2122 array(
2123 'courseid' => $courseid,
2124 'sectionnumber' => $sectionnumber
2125 ));
2126
2127 $warnings = array();
2128
2129 $course = get_course($params['courseid']);
2130 $context = context_course::instance($course->id);
2131 self::validate_context($context);
2132
4dfef5e9
JL
2133 if (!empty($params['sectionnumber'])) {
2134
2135 // Get section details and check it exists.
2136 $modinfo = get_fast_modinfo($course);
2137 $coursesection = $modinfo->get_section_info($params['sectionnumber'], MUST_EXIST);
2138
2139 // Check user is allowed to see it.
2140 if (!$coursesection->uservisible) {
2141 require_capability('moodle/course:viewhiddensections', $context);
2142 }
2143 }
2144
7aed00d5
JL
2145 course_view($context, $params['sectionnumber']);
2146
2147 $result = array();
2148 $result['status'] = true;
2149 $result['warnings'] = $warnings;
2150 return $result;
2151 }
2152
2153 /**
2154 * Returns description of method result value
2155 *
2156 * @return external_description
2157 * @since Moodle 2.9
2158 */
2159 public static function view_course_returns() {
2160 return new external_single_structure(
2161 array(
2162 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
2163 'warnings' => new external_warnings()
2164 )
2165 );
2166 }
2167
740c354f
JL
2168 /**
2169 * Returns description of method parameters
2170 *
2171 * @return external_function_parameters
2172 * @since Moodle 3.0
2173 */
2174 public static function search_courses_parameters() {
2175 return new external_function_parameters(
2176 array(
2177 'criterianame' => new external_value(PARAM_ALPHA, 'criteria name
2178 (search, modulelist (only admins), blocklist (only admins), tagid)'),
2179 'criteriavalue' => new external_value(PARAM_RAW, 'criteria value'),
2180 'page' => new external_value(PARAM_INT, 'page number (0 based)', VALUE_DEFAULT, 0),
235ef57a
DW
2181 'perpage' => new external_value(PARAM_INT, 'items per page', VALUE_DEFAULT, 0),
2182 'requiredcapabilities' => new external_multiple_structure(
2183 new external_value(PARAM_CAPABILITY, 'Capability string used to filter courses by permission'),
72ac2aac 2184 'Optional list of required capabilities (used to filter the list)', VALUE_DEFAULT, array()
427e3cbc
EM
2185 ),
2186 'limittoenrolled' => new external_value(PARAM_BOOL, 'limit to enrolled courses', VALUE_DEFAULT, 0),
740c354f
JL
2187 )
2188 );
2189 }
2190
80adabef
JL
2191 /**
2192 * Return the course information that is public (visible by every one)
2193 *
2194 * @param course_in_list $course course in list object
2195 * @param stdClass $coursecontext course context object
2196 * @return array the course information
2197 * @since Moodle 3.2
2198 */
2199 protected static function get_course_public_information(course_in_list $course, $coursecontext) {
2200
2201 static $categoriescache = array();
2202
2203 // Category information.
2204 if (!array_key_exists($course->category, $categoriescache)) {
2205 $categoriescache[$course->category] = coursecat::get($course->category, IGNORE_MISSING);
2206 }
2207 $category = $categoriescache[$course->category];
2208
2209 // Retrieve course overview used files.
2210 $files = array();
2211 foreach ($course->get_course_overviewfiles() as $file) {
2212 $fileurl = moodle_url::make_webservice_pluginfile_url($file->get_contextid(), $file->get_component(),
2213 $file->get_filearea(), null, $file->get_filepath(),
2214 $file->get_filename())->out(false);
2215 $files[] = array(
2216 'filename' => $file->get_filename(),
2217 'fileurl' => $fileurl,
2218 'filesize' => $file->get_filesize(),
2219 'filepath' => $file->get_filepath(),
2220 'mimetype' => $file->get_mimetype(),
2221 'timemodified' => $file->get_timemodified(),
2222 );
2223 }
2224
2225 // Retrieve the course contacts,
2226 // we need here the users fullname since if we are not enrolled can be difficult to obtain them via other Web Services.
2227 $coursecontacts = array();
2228 foreach ($course->get_course_contacts() as $contact) {
2229 $coursecontacts[] = array(
2230 'id' => $contact['user']->id,
2231 'fullname' => $contact['username']
2232 );
2233 }
2234
2235 // Allowed enrolment methods (maybe we can self-enrol).
2236 $enroltypes = array();
2237 $instances = enrol_get_instances($course->id, true);
2238 foreach ($instances as $instance) {
2239 $enroltypes[] = $instance->enrol;
2240 }
2241
2242 // Format summary.
2243 list($summary, $summaryformat) =
2244 external_format_text($course->summary, $course->summaryformat, $coursecontext->id, 'course', 'summary', null);
2245
2246 $displayname = get_course_display_name_for_list($course);
2247 $coursereturns = array();
2248 $coursereturns['id'] = $course->id;
2249 $coursereturns['fullname'] = external_format_string($course->fullname, $coursecontext->id);
2250 $coursereturns['displayname'] = external_format_string($displayname, $coursecontext->id);
2251 $coursereturns['shortname'] = external_format_string($course->shortname, $coursecontext->id);
2252 $coursereturns['categoryid'] = $course->category;
2253 $coursereturns['categoryname'] = $category == null ? '' : $category->name;
2254 $coursereturns['summary'] = $summary;
2255 $coursereturns['summaryformat'] = $summaryformat;
2256 $coursereturns['summaryfiles'] = external_util::get_area_files($coursecontext->id, 'course', 'summary', false, false);
2257 $coursereturns['overviewfiles'] = $files;
2258 $coursereturns['contacts'] = $coursecontacts;
2259 $coursereturns['enrollmentmethods'] = $enroltypes;
fb41d2f0 2260 $coursereturns['sortorder'] = $course->sortorder;
80adabef
JL
2261 return $coursereturns;
2262 }
2263
740c354f
JL
2264 /**
2265 * Search courses following the specified criteria.
2266 *
2267 * @param string $criterianame Criteria name (search, modulelist (only admins), blocklist (only admins), tagid)
2268 * @param string $criteriavalue Criteria value
2269 * @param int $page Page number (for pagination)
2270 * @param int $perpage Items per page
235ef57a 2271 * @param array $requiredcapabilities Optional list of required capabilities (used to filter the list).
427e3cbc 2272 * @param int $limittoenrolled Limit to only enrolled courses
740c354f
JL
2273 * @return array of course objects and warnings
2274 * @since Moodle 3.0
2275 * @throws moodle_exception
2276 */
235ef57a
DW
2277 public static function search_courses($criterianame,
2278 $criteriavalue,
2279 $page=0,
2280 $perpage=0,
427e3cbc
EM
2281 $requiredcapabilities=array(),
2282 $limittoenrolled=0) {
740c354f
JL
2283 global $CFG;
2284 require_once($CFG->libdir . '/coursecatlib.php');
2285
2286 $warnings = array();
2287
2288 $parameters = array(
2289 'criterianame' => $criterianame,
2290 'criteriavalue' => $criteriavalue,
2291 'page' => $page,
235ef57a
DW
2292 'perpage' => $perpage,
2293 'requiredcapabilities' => $requiredcapabilities
740c354f
JL
2294 );
2295 $params = self::validate_parameters(self::search_courses_parameters(), $parameters);
1d014075 2296 self::validate_context(context_system::instance());
740c354f
JL
2297
2298 $allowedcriterianames = array('search', 'modulelist', 'blocklist', 'tagid');
2299 if (!in_array($params['criterianame'], $allowedcriterianames)) {
2300 throw new invalid_parameter_exception('Invalid value for criterianame parameter (value: '.$params['criterianame'].'),' .
2301 'allowed values are: '.implode(',', $allowedcriterianames));
2302 }
2303
2304 if ($params['criterianame'] == 'modulelist' or $params['criterianame'] == 'blocklist') {
2305 require_capability('moodle/site:config', context_system::instance());
2306 }
2307
2308 $paramtype = array(
2309 'search' => PARAM_RAW,
2310 'modulelist' => PARAM_PLUGIN,
2311 'blocklist' => PARAM_INT,
2312 'tagid' => PARAM_INT
2313 );
2314 $params['criteriavalue'] = clean_param($params['criteriavalue'], $paramtype[$params['criterianame']]);
2315
2316 // Prepare the search API options.
2317 $searchcriteria = array();
2318 $searchcriteria[$params['criterianame']] = $params['criteriavalue'];
2319
2320 $options = array();
2321 if ($params['perpage'] != 0) {
2322 $offset = $params['page'] * $params['perpage'];
2323 $options = array('offset' => $offset, 'limit' => $params['perpage']);
2324 }
2325
2326 // Search the courses.
235ef57a
DW
2327 $courses = coursecat::search_courses($searchcriteria, $options, $params['requiredcapabilities']);
2328 $totalcount = coursecat::search_courses_count($searchcriteria, $options, $params['requiredcapabilities']);
740c354f 2329
427e3cbc
EM
2330 if (!empty($limittoenrolled)) {
2331 // Get the courses where the current user has access.
2332 $enrolled = enrol_get_my_courses(array('id', 'cacherev'));
2333 }
2334
740c354f
JL
2335 $finalcourses = array();
2336 $categoriescache = array();
2337
2338 foreach ($courses as $course) {
427e3cbc
EM
2339 if (!empty($limittoenrolled)) {
2340 // Filter out not enrolled courses.
935ee1c6 2341 if (!isset($enrolled[$course->id])) {
427e3cbc
EM
2342 $totalcount--;
2343 continue;
2344 }
2345 }
740c354f
JL
2346
2347 $coursecontext = context_course::instance($course->id);
2348
80adabef 2349 $finalcourses[] = self::get_course_public_information($course, $coursecontext);
740c354f
JL
2350 }
2351
2352 return array(
2353 'total' => $totalcount,
2354 'courses' => $finalcourses,
2355 'warnings' => $warnings
2356 );
2357 }
2358
80adabef
JL
2359 /**
2360 * Returns a course structure definition
2361 *
2362 * @param boolean $onlypublicdata set to true, to retrieve only fields viewable by anyone when the course is visible
2363 * @return array the course structure
2364 * @since Moodle 3.2
2365 */
2366 protected static function get_course_structure($onlypublicdata = true) {
2367 $coursestructure = array(
2368 'id' => new external_value(PARAM_INT, 'course id'),
2369 'fullname' => new external_value(PARAM_TEXT, 'course full name'),
2370 'displayname' => new external_value(PARAM_TEXT, 'course display name'),
2371 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
2372 'categoryid' => new external_value(PARAM_INT, 'category id'),
2373 'categoryname' => new external_value(PARAM_TEXT, 'category name'),
fb41d2f0 2374 'sortorder' => new external_value(PARAM_INT, 'Sort order in the category', VALUE_OPTIONAL),
80adabef
JL
2375 'summary' => new external_value(PARAM_RAW, 'summary'),
2376 'summaryformat' => new external_format_value('summary'),
2377 'summaryfiles' => new external_files('summary files in the summary field', VALUE_OPTIONAL),
2378 'overviewfiles' => new external_files('additional overview files attached to this course'),
2379 'contacts' => new external_multiple_structure(
2380 new external_single_structure(
2381 array(
2382 'id' => new external_value(PARAM_INT, 'contact user id'),
2383 'fullname' => new external_value(PARAM_NOTAGS, 'contact user fullname'),
2384 )
2385 ),
2386 'contact users'
2387 ),
2388 'enrollmentmethods' => new external_multiple_structure(
2389 new external_value(PARAM_PLUGIN, 'enrollment method'),
2390 'enrollment methods list'
2391 ),
2392 );
2393
2394 if (!$onlypublicdata) {
2395 $extra = array(
2396 'idnumber' => new external_value(PARAM_RAW, 'Id number', VALUE_OPTIONAL),
2397 'format' => new external_value(PARAM_PLUGIN, 'Course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
2398 'showgrades' => new external_value(PARAM_INT, '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
2399 'newsitems' => new external_value(PARAM_INT, 'Number of recent items appearing on the course page', VALUE_OPTIONAL),
2400 'startdate' => new external_value(PARAM_INT, 'Timestamp when the course start', VALUE_OPTIONAL),
ef83fc2a 2401 'enddate' => new external_value(PARAM_INT, 'Timestamp when the course end', VALUE_OPTIONAL),
80adabef
JL
2402 'maxbytes' => new external_value(PARAM_INT, 'Largest size of file that can be uploaded into', VALUE_OPTIONAL),
2403 'showreports' => new external_value(PARAM_INT, 'Are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
2404 'visible' => new external_value(PARAM_INT, '1: available to student, 0:not available', VALUE_OPTIONAL),
2405 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
2406 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
2407 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
2408 'enablecompletion' => new external_value(PARAM_INT, 'Completion enabled? 1: yes 0: no', VALUE_OPTIONAL),
2409 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
2410 'lang' => new external_value(PARAM_SAFEDIR, 'Forced course language', VALUE_OPTIONAL),
2411 'theme' => new external_value(PARAM_PLUGIN, 'Fame of the forced theme', VALUE_OPTIONAL),
80adabef
JL
2412 'marker' => new external_value(PARAM_INT, 'Current course marker', VALUE_OPTIONAL),
2413 'legacyfiles' => new external_value(PARAM_INT, 'If legacy files are enabled', VALUE_OPTIONAL),
2414 'calendartype' => new external_value(PARAM_PLUGIN, 'Calendar type', VALUE_OPTIONAL),
2415 'timecreated' => new external_value(PARAM_INT, 'Time when the course was created', VALUE_OPTIONAL),
2416 'timemodified' => new external_value(PARAM_INT, 'Last time the course was updated', VALUE_OPTIONAL),
2417 'requested' => new external_value(PARAM_INT, 'If is a requested course', VALUE_OPTIONAL),
2418 'cacherev' => new external_value(PARAM_INT, 'Cache revision number', VALUE_OPTIONAL),
e45fc71e
JL
2419 'filters' => new external_multiple_structure(
2420 new external_single_structure(
2421 array(
2422 'filter' => new external_value(PARAM_PLUGIN, 'Filter plugin name'),
2423 'localstate' => new external_value(PARAM_INT, 'Filter state: 1 for on, -1 for off, 0 if inherit'),
2424 'inheritedstate' => new external_value(PARAM_INT, '1 or 0 to use when localstate is set to inherit'),
2425 )
2426 ),
2427 'Course filters', VALUE_OPTIONAL
2428 ),
80adabef
JL
2429 );
2430 $coursestructure = array_merge($coursestructure, $extra);
2431 }
2432 return new external_single_structure($coursestructure);
2433 }
2434
740c354f
JL
2435 /**
2436 * Returns description of method result value
2437 *
2438 * @return external_description
2439 * @since Moodle 3.0
2440 */
2441 public static function search_courses_returns() {
740c354f
JL
2442 return new external_single_structure(
2443 array(
2444 'total' => new external_value(PARAM_INT, 'total course count'),
80adabef 2445 'courses' => new external_multiple_structure(self::get_course_structure(), 'course'),
740c354f
JL
2446 'warnings' => new external_warnings()
2447 )
2448 );
2449 }
c5158499
JL
2450
2451 /**
2452 * Returns description of method parameters
2453 *
2454 * @return external_function_parameters
2455 * @since Moodle 3.0
2456 */
2457 public static function get_course_module_parameters() {
2458 return new external_function_parameters(
2459 array(
2460 'cmid' => new external_value(PARAM_INT, 'The course module id')
2461 )
2462 );
2463 }
2464
2465 /**
2466 * Return information about a course module.
2467 *
2468 * @param int $cmid the course module id
2469 * @return array of warnings and the course module
2470 * @since Moodle 3.0
2471 * @throws moodle_exception
2472 */
2473 public static function get_course_module($cmid) {
796876b0 2474 global $CFG, $DB;
c5158499 2475
796876b0 2476 $params = self::validate_parameters(self::get_course_module_parameters(), array('cmid' => $cmid));
c5158499
JL
2477 $warnings = array();
2478
2479 $cm = get_coursemodule_from_id(null, $params['cmid'], 0, true, MUST_EXIST);
2480 $context = context_module::instance($cm->id);
2481 self::validate_context($context);
2482
2483 // If the user has permissions to manage the activity, return all the information.
2484 if (has_capability('moodle/course:manageactivities', $context)) {
796876b0
JL
2485 require_once($CFG->dirroot . '/course/modlib.php');
2486 require_once($CFG->libdir . '/gradelib.php');
2487
c5158499 2488 $info = $cm;
796876b0
JL
2489 // Get the extra information: grade, advanced grading and outcomes data.
2490 $course = get_course($cm->course);
2491 list($newcm, $newcontext, $module, $extrainfo, $cw) = get_moduleinfo_data($cm, $course);
2492 // Grades.
2493 $gradeinfo = array('grade', 'gradepass', 'gradecat');
2494 foreach ($gradeinfo as $gfield) {
2495 if (isset($extrainfo->{$gfield})) {
2496 $info->{$gfield} = $extrainfo->{$gfield};
2497 }
2498 }
2499 if (isset($extrainfo->grade) and $extrainfo->grade < 0) {
2500 $info->scale = $DB->get_field('scale', 'scale', array('id' => abs($extrainfo->grade)));
2501 }
2502 // Advanced grading.
2503 if (isset($extrainfo->_advancedgradingdata)) {
2504 $info->advancedgrading = array();
2505 foreach ($extrainfo as $key => $val) {
2506 if (strpos($key, 'advancedgradingmethod_') === 0) {
2507 $info->advancedgrading[] = array(
2508 'area' => str_replace('advancedgradingmethod_', '', $key),
2509 'method' => $val
2510 );
2511 }
2512 }
2513 }
2514 // Outcomes.
2515 foreach ($extrainfo as $key => $val) {
2516 if (strpos($key, 'outcome_') === 0) {
2517 if (!isset($info->outcomes)) {
2518 $info->outcomes = array();
2519 }
2520 $id = str_replace('outcome_', '', $key);
28ff87be
PFO
2521 $outcome = grade_outcome::fetch(array('id' => $id));
2522 $scaleitems = $outcome->load_scale();
796876b0
JL
2523 $info->outcomes[] = array(
2524 'id' => $id,
28ff87be
PFO
2525 'name' => external_format_string($outcome->get_name(), $context->id),
2526 'scale' => $scaleitems->scale
796876b0
JL
2527 );
2528 }
2529 }
c5158499
JL
2530 } else {
2531 // Return information is safe to show to any user.
2532 $info = new stdClass();
2533 $info->id = $cm->id;
2534 $info->course = $cm->course;
2535 $info->module = $cm->module;
2536 $info->modname = $cm->modname;
2537 $info->instance = $cm->instance;
2538 $info->section = $cm->section;
2539 $info->sectionnum = $cm->sectionnum;
2540 $info->groupmode = $cm->groupmode;
2541 $info->groupingid = $cm->groupingid;
2542 $info->completion = $cm->completion;
2543 }
2544 // Format name.
9748791b 2545 $info->name = external_format_string($cm->name, $context->id);
c5158499
JL
2546 $result = array();
2547 $result['cm'] = $info;
2548 $result['warnings'] = $warnings;
2549 return $result;
2550 }
2551
2552 /**
2553 * Returns description of method result value
2554 *
2555 * @return external_description
2556 * @since Moodle 3.0
2557 */
2558 public static function get_course_module_returns() {
2559 return new external_single_structure(
2560 array(
2561 'cm' => new external_single_structure(
2562 array(
2563 'id' => new external_value(PARAM_INT, 'The course module id'),
2564 'course' => new external_value(PARAM_INT, 'The course id'),
2565 'module' => new external_value(PARAM_INT, 'The module type id'),
9748791b 2566 'name' => new external_value(PARAM_RAW, 'The activity name'),
c5158499
JL
2567 'modname' => new external_value(PARAM_COMPONENT, 'The module component name (forum, assign, etc..)'),
2568 'instance' => new external_value(PARAM_INT, 'The activity instance id'),
2569 'section' => new external_value(PARAM_INT, 'The module section id'),
2570 'sectionnum' => new external_value(PARAM_INT, 'The module section number'),
2571 'groupmode' => new external_value(PARAM_INT, 'Group mode'),
2572 'groupingid' => new external_value(PARAM_INT, 'Grouping id'),
2573 'completion' => new external_value(PARAM_INT, 'If completion is enabled'),
2574 'idnumber' => new external_value(PARAM_RAW, 'Module id number', VALUE_OPTIONAL),
2575 'added' => new external_value(PARAM_INT, 'Time added', VALUE_OPTIONAL),
2576 'score' => new external_value(PARAM_INT, 'Score', VALUE_OPTIONAL),
2577 'indent' => new external_value(PARAM_INT, 'Indentation', VALUE_OPTIONAL),
2578 'visible' => new external_value(PARAM_INT, 'If visible', VALUE_OPTIONAL),
4529327a 2579 'visibleoncoursepage' => new external_value(PARAM_INT, 'If visible on course page', VALUE_OPTIONAL),
c5158499
JL
2580 'visibleold' => new external_value(PARAM_INT, 'Visible old', VALUE_OPTIONAL),
2581 'completiongradeitemnumber' => new external_value(PARAM_INT, 'Completion grade item', VALUE_OPTIONAL),
2582 'completionview' => new external_value(PARAM_INT, 'Completion view setting', VALUE_OPTIONAL),
2583 'completionexpected' => new external_value(PARAM_INT, 'Completion time expected', VALUE_OPTIONAL),
2584 'showdescription' => new external_value(PARAM_INT, 'If the description is showed', VALUE_OPTIONAL),
2585 'availability' => new external_value(PARAM_RAW, 'Availability settings', VALUE_OPTIONAL),
796876b0
JL
2586 'grade' => new external_value(PARAM_INT, 'Grade (max value or scale id)', VALUE_OPTIONAL),
2587 'scale' => new external_value(PARAM_TEXT, 'Scale items (if used)', VALUE_OPTIONAL),
2588 'gradepass' => new external_value(PARAM_RAW, 'Grade to pass (float)', VALUE_OPTIONAL),
2589 'gradecat' => new external_value(PARAM_INT, 'Grade category', VALUE_OPTIONAL),
2590 'advancedgrading' => new external_multiple_structure(
2591 new external_single_structure(
2592 array(
2593 'area' => new external_value(PARAM_AREA, 'Gradable area name'),
2594 'method' => new external_value(PARAM_COMPONENT, 'Grading method'),
2595 )
2596 ),
2597 'Advanced grading settings', VALUE_OPTIONAL
2598 ),
2599 'outcomes' => new external_multiple_structure(
2600 new external_single_structure(
2601 array(
2602 'id' => new external_value(PARAM_ALPHANUMEXT, 'Outcome id'),
2603 'name' => new external_value(PARAM_TEXT, 'Outcome full name'),
28ff87be 2604 'scale' => new external_value(PARAM_TEXT, 'Scale items')
796876b0
JL
2605 )
2606 ),
2607 'Outcomes information', VALUE_OPTIONAL
2608 ),
c5158499
JL
2609 )
2610 ),
2611 'warnings' => new external_warnings()
2612 )
2613 );
2614 }
2615
13bb6819
JL
2616 /**
2617 * Returns description of method parameters
2618 *
2619 * @return external_function_parameters
2620 * @since Moodle 3.0
2621 */
2622 public static function get_course_module_by_instance_parameters() {
2623 return new external_function_parameters(
2624 array(
2625 'module' => new external_value(PARAM_COMPONENT, 'The module name'),
2626 'instance' => new external_value(PARAM_INT, 'The module instance id')
2627 )
2628 );
2629 }
2630
2631 /**
2632 * Return information about a course module.
2633 *
d30255a0
DM
2634 * @param string $module the module name
2635 * @param int $instance the activity instance id
13bb6819
JL
2636 * @return array of warnings and the course module
2637 * @since Moodle 3.0
2638 * @throws moodle_exception
2639 */
2640 public static function get_course_module_by_instance($module, $instance) {
2641
2642 $params = self::validate_parameters(self::get_course_module_by_instance_parameters(),
2643 array(
2644 'module' => $module,
2645 'instance' => $instance,
2646 ));
2647
2648 $warnings = array();
2649 $cm = get_coursemodule_from_instance($params['module'], $params['instance'], 0, false, MUST_EXIST);
2650
2651 return self::get_course_module($cm->id);
2652 }
2653
2654 /**
2655 * Returns description of method result value
2656 *
2657 * @return external_description
2658 * @since Moodle 3.0
2659 */
2660 public static function get_course_module_by_instance_returns() {
2661 return self::get_course_module_returns();
2662 }
2663
7c4e686f
JL
2664 /**
2665 * Returns description of method parameters
2666 *
e9dfeec9 2667 * @deprecated since 3.3
063b7ee6 2668 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
7c4e686f
JL
2669 * @return external_function_parameters
2670 * @since Moodle 3.2
2671 */
2672 public static function get_activities_overview_parameters() {
2673 return new external_function_parameters(
2674 array(
2675 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2676 )
2677 );
2678 }
2679
2680 /**
2681 * Return activities overview for the given courses.
2682 *
e9dfeec9 2683 * @deprecated since 3.3
063b7ee6 2684 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
7c4e686f
JL
2685 * @param array $courseids a list of course ids
2686 * @return array of warnings and the activities overview
2687 * @since Moodle 3.2
2688 * @throws moodle_exception
2689 */
2690 public static function get_activities_overview($courseids) {
2691 global $USER;
2692
2693 // Parameter validation.
2694 $params = self::validate_parameters(self::get_activities_overview_parameters(), array('courseids' => $courseids));
2695 $courseoverviews = array();
2696
2697 list($courses, $warnings) = external_util::validate_courses($params['courseids']);
2698
2699 if (!empty($courses)) {
2700 // Add lastaccess to each course (required by print_overview function).
2701 // We need the complete user data, the ws server does not load a complete one.
2702 $user = get_complete_user_data('id', $USER->id);
2703 foreach ($courses as $course) {
2704 if (isset($user->lastcourseaccess[$course->id])) {
2705 $course->lastaccess = $user->lastcourseaccess[$course->id];
2706 } else {
2707 $course->lastaccess = 0;
2708 }
2709 }
2710
2711 $overviews = array();
2712 if ($modules = get_plugin_list_with_function('mod', 'print_overview')) {
2713 foreach ($modules as $fname) {
2714 $fname($courses, $overviews);
2715 }
2716 }
2717
2718 // Format output.
2719 foreach ($overviews as $courseid => $modules) {
2720 $courseoverviews[$courseid]['id'] = $courseid;
2721 $courseoverviews[$courseid]['overviews'] = array();
2722
2723 foreach ($modules as $modname => $overviewtext) {
2724 $courseoverviews[$courseid]['overviews'][] = array(
2725 'module' => $modname,
2726 'overviewtext' => $overviewtext // This text doesn't need formatting.
2727 );
2728 }
2729 }
2730 }
2731
2732 $result = array(
2733 'courses' => $courseoverviews,
2734 'warnings' => $warnings
2735 );
2736 return $result;
2737 }
2738
2739 /**
2740 * Returns description of method result value
2741 *
e9dfeec9 2742 * @deprecated since 3.3
063b7ee6 2743 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
7c4e686f
JL
2744 * @return external_description
2745 * @since Moodle 3.2
2746 */
2747 public static function get_activities_overview_returns() {
2748 return new external_single_structure(
2749 array(
2750 'courses' => new external_multiple_structure(
2751 new external_single_structure(
2752 array(
2753 'id' => new external_value(PARAM_INT, 'Course id'),
2754 'overviews' => new external_multiple_structure(
2755 new external_single_structure(
2756 array(
2757 'module' => new external_value(PARAM_PLUGIN, 'Module name'),
2758 'overviewtext' => new external_value(PARAM_RAW, 'Overview text'),
2759 )
2760 )
2761 )
2762 )
2763 ), 'List of courses'
2764 ),
2765 'warnings' => new external_warnings()
2766 )
2767 );
2768 }
2769
e9dfeec9
MN
2770 /**
2771 * Marking the method as deprecated.
2772 *
2773 * @return bool
2774 */
2775 public static function get_activities_overview_is_deprecated() {
2776 return true;
2777 }
2778
c115ff6a
JL
2779 /**
2780 * Returns description of method parameters
2781 *
2782 * @return external_function_parameters
2783 * @since Moodle 3.2
2784 */
2785 public static function get_user_navigation_options_parameters() {
2786 return new external_function_parameters(
2787 array(
2788 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2789 )
2790 );
2791 }
2792
2793 /**
2794 * Return a list of navigation options in a set of courses that are avaialable or not for the current user.
2795 *
2796 * @param array $courseids a list of course ids
2797 * @return array of warnings and the options availability
2798 * @since Moodle 3.2
2799 * @throws moodle_exception
2800 */
2801 public static function get_user_navigation_options($courseids) {
2802 global $CFG;
2803 require_once($CFG->dirroot . '/course/lib.php');
2804
2805 // Parameter validation.
2806 $params = self::validate_parameters(self::get_user_navigation_options_parameters(), array('courseids' => $courseids));
2807 $courseoptions = array();
2808
2809 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
2810
2811 if (!empty($courses)) {
2812 foreach ($courses as $course) {
2813 // Fix the context for the frontpage.
2814 if ($course->id == SITEID) {
2815 $course->context = context_system::instance();
2816 }
2817 $navoptions = course_get_user_navigation_options($course->context, $course);
2818 $options = array();
2819 foreach ($navoptions as $name => $available) {
2820 $options[] = array(
2821 'name' => $name,
2822 'available' => $available,
2823 );
2824 }
2825
2826 $courseoptions[] = array(
2827 'id' => $course->id,
2828 'options' => $options
2829 );
2830 }
2831 }
2832
2833 $result = array(
2834 'courses' => $courseoptions,
2835 'warnings' => $warnings
2836 );
2837 return $result;
2838 }
2839
2840 /**
2841 * Returns description of method result value
2842 *
2843 * @return external_description
2844 * @since Moodle 3.2
2845 */
2846 public static function get_user_navigation_options_returns() {
2847 return new external_single_structure(
2848 array(
2849 'courses' => new external_multiple_structure(
2850 new external_single_structure(
2851 array(
2852 'id' => new external_value(PARAM_INT, 'Course id'),
2853 'options' => new external_multiple_structure(
2854 new external_single_structure(
2855 array(
2856 'name' => new external_value(PARAM_ALPHANUMEXT, 'Option name'),
2857 'available' => new external_value(PARAM_BOOL, 'Whether the option is available or not'),
2858 )
2859 )
2860 )
2861 )
2862 ), 'List of courses'
2863 ),
2864 'warnings' => new external_warnings()
2865 )
2866 );
2867 }
2868
b9050b10
JL
2869 /**
2870 * Returns description of method parameters
2871 *
2872 * @return external_function_parameters
2873 * @since Moodle 3.2
2874 */
2875 public static function get_user_administration_options_parameters() {
2876 return new external_function_parameters(
2877 array(
2878 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2879 )
2880 );
2881 }
2882
2883 /**
2884 * Return a list of administration options in a set of courses that are available or not for the current user.
2885 *
2886 * @param array $courseids a list of course ids
2887 * @return array of warnings and the options availability
2888 * @since Moodle 3.2
2889 * @throws moodle_exception
2890 */
2891 public static function get_user_administration_options($courseids) {
2892 global $CFG;
2893 require_once($CFG->dirroot . '/course/lib.php');
2894
2895 // Parameter validation.
2896 $params = self::validate_parameters(self::get_user_administration_options_parameters(), array('courseids' => $courseids));
2897 $courseoptions = array();
2898
2899 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
2900
2901 if (!empty($courses)) {
2902 foreach ($courses as $course) {
2903 $adminoptions = course_get_user_administration_options($course, $course->context);
2904 $options = array();
2905 foreach ($adminoptions as $name => $available) {
2906 $options[] = array(
2907 'name' => $name,
2908 'available' => $available,
2909 );
2910 }
2911
2912 $courseoptions[] = array(
2913 'id' => $course->id,
2914 'options' => $options
2915 );
2916 }
2917 }
2918
2919 $result = array(
2920 'courses' => $courseoptions,
2921 'warnings' => $warnings
2922 );
2923 return $result;
2924 }
2925
2926 /**
2927 * Returns description of method result value
2928 *
2929 * @return external_description
2930 * @since Moodle 3.2
2931 */
2932 public static function get_user_administration_options_returns() {
2933 return self::get_user_navigation_options_returns();
2934 }
80adabef
JL
2935
2936 /**
2937 * Returns description of method parameters
2938 *
2939 * @return external_function_parameters
2940 * @since Moodle 3.2
2941 */
2942 public static function get_courses_by_field_parameters() {
2943 return new external_function_parameters(
2944 array(
2945 'field' => new external_value(PARAM_ALPHA, 'The field to search can be left empty for all courses or:
2946 id: course id
2947 ids: comma separated course ids
2948 shortname: course short name
2949 idnumber: course id number
2950 category: category id the course belongs to
2951 ', VALUE_DEFAULT, ''),
2952 'value' => new external_value(PARAM_RAW, 'The value to match', VALUE_DEFAULT, '')
2953 )
2954 );
2955 }
2956
2957
2958 /**
2959 * Get courses matching a specific field (id/s, shortname, idnumber, category)
2960 *
2961 * @param string $field field name to search, or empty for all courses
2962 * @param string $value value to search
2963 * @return array list of courses and warnings
2964 * @throws invalid_parameter_exception
2965 * @since Moodle 3.2
2966 */
2967 public static function get_courses_by_field($field = '', $value = '') {
2968 global $DB, $CFG;
2969 require_once($CFG->libdir . '/coursecatlib.php');
e45fc71e 2970 require_once($CFG->libdir . '/filterlib.php');
80adabef
JL
2971
2972 $params = self::validate_parameters(self::get_courses_by_field_parameters(),
2973 array(
2974 'field' => $field,
2975 'value' => $value,
2976 )
2977 );
2978 $warnings = array();
2979
2980 if (empty($params['field'])) {
2981 $courses = $DB->get_records('course', null, 'id ASC');
2982 } else {
2983 switch ($params['field']) {
2984 case 'id':
2985 case 'category':
2986 $value = clean_param($params['value'], PARAM_INT);
2987 break;
2988 case 'ids':
2989 $value = clean_param($params['value'], PARAM_SEQUENCE);
2990 break;
2991 case 'shortname':
2992 $value = clean_param($params['value'], PARAM_TEXT);
2993 break;
2994 case 'idnumber':
2995 $value = clean_param($params['value'], PARAM_RAW);
2996 break;
2997 default:
2998 throw new invalid_parameter_exception('Invalid field name');
2999 }
3000
3001 if ($params['field'] === 'ids') {
3002 $courses = $DB->get_records_list('course', 'id', explode(',', $value), 'id ASC');
3003 } else {
3004 $courses = $DB->get_records('course', array($params['field'] => $value), 'id ASC');
3005 }
3006 }
3007
3008 $coursesdata = array();
3009 foreach ($courses as $course) {
3010 $context = context_course::instance($course->id);
3011 $canupdatecourse = has_capability('moodle/course:update', $context);
3012 $canviewhiddencourses = has_capability('moodle/course:viewhiddencourses', $context);
3013
3014 // Check if the course is visible in the site for the user.
3015 if (!$course->visible and !$canviewhiddencourses and !$canupdatecourse) {
3016 continue;
3017 }
3018 // Get the public course information, even if we are not enrolled.
3019 $courseinlist = new course_in_list($course);
3020 $coursesdata[$course->id] = self::get_course_public_information($courseinlist, $context);
3021
3022 // Now, check if we have access to the course.
3023 try {
3024 self::validate_context($context);
3025 } catch (Exception $e) {
3026 continue;
3027 }
3028 // Return information for any user that can access the course.
ef83fc2a 3029 $coursefields = array('format', 'showgrades', 'newsitems', 'startdate', 'enddate', 'maxbytes', 'showreports', 'visible',
80adabef 3030 'groupmode', 'groupmodeforce', 'defaultgroupingid', 'enablecompletion', 'completionnotify', 'lang', 'theme',
fb41d2f0 3031 'marker');
80adabef 3032
e45fc71e
JL
3033 // Course filters.
3034 $coursesdata[$course->id]['filters'] = filter_get_available_in_context($context);
3035
80adabef
JL
3036 // Information for managers only.
3037 if ($canupdatecourse) {
3038 $managerfields = array('idnumber', 'legacyfiles', 'calendartype', 'timecreated', 'timemodified', 'requested',
3039 'cacherev');
3040 $coursefields = array_merge($coursefields, $managerfields);
3041 }
3042
3043 // Populate fields.
3044 foreach ($coursefields as $field) {
3045 $coursesdata[$course->id][$field] = $course->{$field};
3046 }
3047 }
3048
3049 return array(
3050 'courses' => $coursesdata,
3051 'warnings' => $warnings
3052 );
3053 }
3054
3055 /**
3056 * Returns description of method result value
3057 *
3058 * @return external_description
3059 * @since Moodle 3.2
3060 */
3061 public static function get_courses_by_field_returns() {
3062 // Course structure, including not only public viewable fields.
3063 return new external_single_structure(
3064 array(
3065 'courses' => new external_multiple_structure(self::get_course_structure(false), 'Course'),
3066 'warnings' => new external_warnings()
3067 )
3068 );
3069 }
26659f62
JL
3070
3071 /**
3072 * Returns description of method parameters
3073 *
3074 * @return external_function_parameters
3075 * @since Moodle 3.2
3076 */
3077 public static function check_updates_parameters() {
3078 return new external_function_parameters(
3079 array(
3080 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3081 'tocheck' => new external_multiple_structure(
3082 new external_single_structure(
3083 array(
3084 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level for the file location.
3085 Only module supported right now.'),
3086 'id' => new external_value(PARAM_INT, 'Context instance id'),
3087 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3088 )
3089 ),
3090 'Instances to check'
3091 ),
3092 'filter' => new external_multiple_structure(
25adfbaa 3093 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
26659f62
JL
3094 gradeitems, outcomes'),
3095 'Check only for updates in these areas', VALUE_DEFAULT, array()
3096 )
3097 )
3098 );
3099 }
3100
3101 /**
3102 * Check if there is updates affecting the user for the given course and contexts.
3103 * Right now only modules are supported.
3104 * This WS calls mod_check_updates_since for each module to check if there is any update the user should we aware of.
26659f62
JL
3105 *
3106 * @param int $courseid the list of modules to check
3107 * @param array $tocheck the list of modules to check
3108 * @param array $filter check only for updates in these areas
3109 * @return array list of updates and warnings
3110 * @throws moodle_exception
3111 * @since Moodle 3.2
3112 */
3113 public static function check_updates($courseid, $tocheck, $filter = array()) {
3114 global $CFG, $DB;
3115
3116 $params = self::validate_parameters(
3117 self::check_updates_parameters(),
3118 array(
3119 'courseid' => $courseid,
3120 'tocheck' => $tocheck,
3121 'filter' => $filter,
3122 )
3123 );
3124
3125 $course = get_course($params['courseid']);
3126 $context = context_course::instance($course->id);
3127 self::validate_context($context);
3128
3129 list($instances, $warnings) = course_check_updates($course, $params['tocheck'], $filter);
3130
3131 $instancesformatted = array();
3132 foreach ($instances as $instance) {
3133 $updates = array();
25adfbaa
JL
3134 foreach ($instance['updates'] as $name => $data) {
3135 if (empty($data->updated)) {
3136 continue;
3137 }
3138 $updatedata = array(
26659f62 3139 'name' => $name,
25adfbaa
JL
3140 );
3141 if (!empty($data->timeupdated)) {
3142 $updatedata['timeupdated'] = $data->timeupdated;
3143 }
3144 if (!empty($data->itemids)) {
3145 $updatedata['itemids'] = $data->itemids;
3146 }
3147 $updates[] = $updatedata;
3148 }
3149 if (!empty($updates)) {
3150 $instancesformatted[] = array(
3151 'contextlevel' => $instance['contextlevel'],
3152 'id' => $instance['id'],
3153 'updates' => $updates
26659f62
JL
3154 );
3155 }
26659f62
JL
3156 }
3157
3158 return array(
3159 'instances' => $instancesformatted,
3160 'warnings' => $warnings
3161 );
3162 }
3163
3164 /**
3165 * Returns description of method result value
3166 *
3167 * @return external_description
3168 * @since Moodle 3.2
3169 */
3170 public static function check_updates_returns() {
3171 return new external_single_structure(
3172 array(
3173 'instances' => new external_multiple_structure(
3174 new external_single_structure(
3175 array(
3176 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level'),
3177 'id' => new external_value(PARAM_INT, 'Instance id'),
3178 'updates' => new external_multiple_structure(
3179 new external_single_structure(
3180 array(
3181 'name' => new external_value(PARAM_ALPHANUMEXT, 'Name of the area updated.'),
25adfbaa
JL
3182 'timeupdated' => new external_value(PARAM_INT, 'Last time was updated', VALUE_OPTIONAL),
3183 'itemids' => new external_multiple_structure(
3184 new external_value(PARAM_INT, 'Instance id'),
3185 'The ids of the items updated',
3186 VALUE_OPTIONAL
3187 )
26659f62
JL
3188 )
3189 )
3190 )
3191 )
3192 )
3193 ),
3194 'warnings' => new external_warnings()
3195 )
3196 );
3197 }
879a8f56
JL
3198
3199 /**
3200 * Returns description of method parameters
3201 *
3202 * @return external_function_parameters
3203 * @since Moodle 3.3
3204 */
3205 public static function get_updates_since_parameters() {
3206 return new external_function_parameters(
3207 array(
3208 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3209 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3210 'filter' => new external_multiple_structure(
3211 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3212 gradeitems, outcomes'),
3213 'Check only for updates in these areas', VALUE_DEFAULT, array()
3214 )
3215 )
3216 );
3217 }
3218
3219 /**
3220 * Check if there are updates affecting the user for the given course since the given time stamp.
3221 *
3222 * This function is a wrapper of self::check_updates for retrieving all the updates since a given time for all the activities.
3223 *
3224 * @param int $courseid the list of modules to check
3225 * @param int $since check updates since this time stamp
3226 * @param array $filter check only for updates in these areas
3227 * @return array list of updates and warnings
3228 * @throws moodle_exception
3229 * @since Moodle 3.3
3230 */
3231 public static function get_updates_since($courseid, $since, $filter = array()) {
3232 global $CFG, $DB;
3233
3234 $params = self::validate_parameters(
3235 self::get_updates_since_parameters(),
3236 array(
3237 'courseid' => $courseid,
3238 'since' => $since,
3239 'filter' => $filter,
3240 )
3241 );
3242
3243 $course = get_course($params['courseid']);
3244 $modinfo = get_fast_modinfo($course);
3245 $tocheck = array();
3246
3247 // Retrieve all the visible course modules for the current user.
3248 $cms = $modinfo->get_cms();
3249 foreach ($cms as $cm) {
3250 if (!$cm->uservisible) {
3251 continue;
3252 }
3253 $tocheck[] = array(
3254 'id' => $cm->id,
3255 'contextlevel' => 'module',
3256 'since' => $params['since'],
3257 );
3258 }
3259
3260 return self::check_updates($course->id, $tocheck, $params['filter']);
3261 }
3262
3263 /**
3264 * Returns description of method result value
3265 *
3266 * @return external_description
3267 * @since Moodle 3.3
3268 */
3269 public static function get_updates_since_returns() {
3270 return self::check_updates_returns();
3271 }
4529327a
MG
3272
3273 /**
3274 * Parameters for function edit_module()
3275 *
3276 * @since Moodle 3.3
3277 * @return external_function_parameters
3278 */
3279 public static function edit_module_parameters() {
3280 return new external_function_parameters(
3281 array(
3282 'action' => new external_value(PARAM_ALPHA,
3283 'action: hide, show, stealth, duplicate, delete, moveleft, moveright, group...', VALUE_REQUIRED),
3284 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3285 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3286 ));
3287 }
3288
3289 /**
3290 * Performs one of the edit module actions and return new html for AJAX
3291 *
3292 * Returns html to replace the current module html with, for example:
3293 * - empty string for "delete" action,
3294 * - two modules html for "duplicate" action
3295 * - updated module html for everything else
3296 *
3297 * Throws exception if operation is not permitted/possible
3298 *
3299 * @since Moodle 3.3
3300 * @param string $action
3301 * @param int $id
3302 * @param null|int $sectionreturn
3303 * @return string
3304 */
3305 public static function edit_module($action, $id, $sectionreturn = null) {
3306 global $PAGE, $DB;
3307 // Validate and normalize parameters.
3308 $params = self::validate_parameters(self::edit_module_parameters(),
3309 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3310 $action = $params['action'];
3311 $id = $params['id'];
3312 $sectionreturn = $params['sectionreturn'];
3313
3314 list($course, $cm) = get_course_and_cm_from_cmid($id);
3315 $modcontext = context_module::instance($cm->id);
3316 $coursecontext = context_course::instance($course->id);
3317 self::validate_context($modcontext);
3318 $courserenderer = $PAGE->get_renderer('core', 'course');
3319 $completioninfo = new completion_info($course);
3320
3321 switch($action) {
3322 case 'hide':
3323 case 'show':
3324 case 'stealth':
3325 require_capability('moodle/course:activityvisibility', $modcontext);
3326 $visible = ($action === 'hide') ? 0 : 1;
3327 $visibleoncoursepage = ($action === 'stealth') ? 0 : 1;
3328 set_coursemodule_visible($id, $visible, $visibleoncoursepage);
3329 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3330 break;
3331 case 'duplicate':
3332 require_capability('moodle/course:manageactivities', $coursecontext);
3333 require_capability('moodle/backup:backuptargetimport', $coursecontext);
3334 require_capability('moodle/restore:restoretargetimport', $coursecontext);
3335 if (!course_allowed_module($course, $cm->modname)) {
3336 throw new moodle_exception('No permission to create that activity');
3337 }
3338 if ($newcm = duplicate_module($course, $cm)) {
3339 $cm = get_fast_modinfo($course)->get_cm($id);
3340 $newcm = get_fast_modinfo($course)->get_cm($newcm->id);
3341 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn) .
3342 $courserenderer->course_section_cm_list_item($course, $completioninfo, $newcm, $sectionreturn);
3343 }
3344 break;
3345 case 'groupsseparate':
3346 case 'groupsvisible':
3347 case 'groupsnone':
3348 require_capability('moodle/course:manageactivities', $modcontext);
3349 if ($action === 'groupsseparate') {
3350 $newgroupmode = SEPARATEGROUPS;
3351 } else if ($action === 'groupsvisible') {
3352 $newgroupmode = VISIBLEGROUPS;
3353 } else {
3354 $newgroupmode = NOGROUPS;
3355 }
3356 if (set_coursemodule_groupmode($cm->id, $newgroupmode)) {
3357 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger();
3358 }
3359 break;
3360 case 'moveleft':
3361 case 'moveright':
3362 require_capability('moodle/course:manageactivities', $modcontext);
3363 $indent = $cm->indent + (($action === 'moveright') ? 1 : -1);
3364 if ($cm->indent >= 0) {
3365 $DB->update_record('course_modules', array('id' => $cm->id, 'indent' => $indent));
3366 rebuild_course_cache($cm->course);
3367 }
3368 break;
3369 case 'delete':
3370 require_capability('moodle/course:manageactivities', $modcontext);
3371 course_delete_module($cm->id, true);
3372 return '';
3373 default:
3374 throw new coding_exception('Unrecognised action');
3375 }
3376
3377 $cm = get_fast_modinfo($course)->get_cm($id);
3378 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn);
3379 }
3380
3381 /**
3382 * Return structure for edit_module()
3383 *
3384 * @since Moodle 3.3
3385 * @return external_description
3386 */
3387 public static function edit_module_returns() {
3388 return new external_value(PARAM_RAW, 'html to replace the current module with');
3389 }
3390
3391 /**
3392 * Parameters for function get_module()
3393 *
3394 * @since Moodle 3.3
3395 * @return external_function_parameters
3396 */
3397 public static function get_module_parameters() {
3398 return new external_function_parameters(
3399 array(
3400 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED),
3401 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3402 ));
3403 }
3404
3405 /**
3406 * Returns html for displaying one activity module on course page
3407 *
3408 * @since Moodle 3.3
3409 * @param int $id
3410 * @param null|int $sectionreturn
3411 * @return string
3412 */
3413 public static function get_module($id, $sectionreturn = null) {
3414 global $PAGE;
3415 // Validate and normalize parameters.
3416 $params = self::validate_parameters(self::get_module_parameters(),
3417 array('id' => $id, 'sectionreturn' => $sectionreturn));
3418 $id = $params['id'];
3419 $sectionreturn = $params['sectionreturn'];
3420
3421 // Validate access to the course (note, this is html for the course view page, we don't validate access to the module).
3422 list($course, $cm) = get_course_and_cm_from_cmid($id);
3423 self::validate_context(context_course::instance($course->id));
3424
3425 $courserenderer = $PAGE->get_renderer('core', 'course');
3426 $completioninfo = new completion_info($course);
3427 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn);
3428 }
3429
3430 /**
3431 * Return structure for edit_module()
3432 *
3433 * @since Moodle 3.3
3434 * @return external_description
3435 */
3436 public static function get_module_returns() {
3437 return new external_value(PARAM_RAW, 'html to replace the current module with');
3438 }
3439
3440 /**
3441 * Parameters for function edit_section()
3442 *
3443 * @since Moodle 3.3
3444 * @return external_function_parameters
3445 */
3446 public static function edit_section_parameters() {
3447 return new external_function_parameters(
3448 array(
3449 'action' => new external_value(PARAM_ALPHA, 'action: hide, show, stealth, setmarker, removemarker', VALUE_REQUIRED),
3450 'id' => new external_value(PARAM_INT, 'course section id', VALUE_REQUIRED),
3451 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null),
3452 ));
3453 }
3454
3455 /**
3456 * Performs one of the edit section actions
3457 *
3458 * @since Moodle 3.3
3459 * @param string $action
3460 * @param int $id section id
3461 * @param int $sectionreturn section to return to
3462 * @return string
3463 */
3464 public static function edit_section($action, $id, $sectionreturn) {
3465 global $DB;
3466 // Validate and normalize parameters.
3467 $params = self::validate_parameters(self::edit_section_parameters(),
3468 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn));
3469 $action = $params['action'];
3470 $id = $params['id'];
3471 $sr = $params['sectionreturn'];
3472
3473 $section = $DB->get_record('course_sections', array('id' => $id), '*', MUST_EXIST);
3474 $coursecontext = context_course::instance($section->course);
3475 self::validate_context($coursecontext);
3476
3477 $rv = course_get_format($section->course)->section_action($section, $action, $sectionreturn);
3478 if ($rv) {
3479 return json_encode($rv);
3480 } else {
3481 return null;
3482 }
3483 }
3484
3485 /**
3486 * Return structure for edit_section()
3487 *
3488 * @since Moodle 3.3
3489 * @return external_description
3490 */
3491 public static function edit_section_returns() {
3492 return new external_value(PARAM_RAW, 'Additional data for javascript (JSON-encoded string)');
3493 }
5d1017e1 3494}