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