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