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