Merge branch 'MDL-57629-master' of git://github.com/jleyva/moodle
[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();
163             $coursenumsections = course_get_format($course)->get_course()->numsections;
165             //for each sections (first displayed to last displayed)
166             $modinfosections = $modinfo->get_sections();
167             foreach ($sections as $key => $section) {
169                 if (!$section->uservisible) {
170                     continue;
171                 }
173                 // This becomes true when we are filtering and we found the value to filter with.
174                 $sectionfound = false;
176                 // Filter by section id.
177                 if (!empty($filters['sectionid'])) {
178                     if ($section->id != $filters['sectionid']) {
179                         continue;
180                     } else {
181                         $sectionfound = true;
182                     }
183                 }
185                 // Filter by section number. Note that 0 is a valid section number.
186                 if (isset($filters['sectionnumber'])) {
187                     if ($key != $filters['sectionnumber']) {
188                         continue;
189                     } else {
190                         $sectionfound = true;
191                     }
192                 }
194                 // reset $sectioncontents
195                 $sectionvalues = array();
196                 $sectionvalues['id'] = $section->id;
197                 $sectionvalues['name'] = get_section_name($course, $section);
198                 $sectionvalues['visible'] = $section->visible;
200                 $options = (object) array('noclean' => true);
201                 list($sectionvalues['summary'], $sectionvalues['summaryformat']) =
202                         external_format_text($section->summary, $section->summaryformat,
203                                 $context->id, 'course', 'section', $section->id, $options);
204                 $sectionvalues['section'] = $section->section;
205                 $sectionvalues['hiddenbynumsections'] = $section->section > $coursenumsections ? 1 : 0;
206                 $sectioncontents = array();
208                 //for each module of the section
209                 if (empty($filters['excludemodules']) and !empty($modinfosections[$section->section])) {
210                     foreach ($modinfosections[$section->section] as $cmid) {
211                         $cm = $modinfo->cms[$cmid];
213                         // stop here if the module is not visible to the user
214                         if (!$cm->uservisible) {
215                             continue;
216                         }
218                         // This becomes true when we are filtering and we found the value to filter with.
219                         $modfound = false;
221                         // Filter by cmid.
222                         if (!empty($filters['cmid'])) {
223                             if ($cmid != $filters['cmid']) {
224                                 continue;
225                             } else {
226                                 $modfound = true;
227                             }
228                         }
230                         // Filter by module name and id.
231                         if (!empty($filters['modname'])) {
232                             if ($cm->modname != $filters['modname']) {
233                                 continue;
234                             } else if (!empty($filters['modid'])) {
235                                 if ($cm->instance != $filters['modid']) {
236                                     continue;
237                                 } else {
238                                     // Note that if we are only filtering by modname we don't break the loop.
239                                     $modfound = true;
240                                 }
241                             }
242                         }
244                         $module = array();
246                         $modcontext = context_module::instance($cm->id);
248                         //common info (for people being able to see the module or availability dates)
249                         $module['id'] = $cm->id;
250                         $module['name'] = external_format_string($cm->name, $modcontext->id);
251                         $module['instance'] = $cm->instance;
252                         $module['modname'] = $cm->modname;
253                         $module['modplural'] = $cm->modplural;
254                         $module['modicon'] = $cm->get_icon_url()->out(false);
255                         $module['indent'] = $cm->indent;
257                         if (!empty($cm->showdescription) or $cm->modname == 'label') {
258                             // We want to use the external format. However from reading get_formatted_content(), $cm->content format is always FORMAT_HTML.
259                             list($module['description'], $descriptionformat) = external_format_text($cm->content,
260                                 FORMAT_HTML, $modcontext->id, $cm->modname, 'intro', $cm->id);
261                         }
263                         //url of the module
264                         $url = $cm->url;
265                         if ($url) { //labels don't have url
266                             $module['url'] = $url->out(false);
267                         }
269                         $canviewhidden = has_capability('moodle/course:viewhiddenactivities',
270                                             context_module::instance($cm->id));
271                         //user that can view hidden module should know about the visibility
272                         $module['visible'] = $cm->visible;
274                         // Availability date (also send to user who can see hidden module).
275                         if ($CFG->enableavailability && ($canviewhidden || $canupdatecourse)) {
276                             $module['availability'] = $cm->availability;
277                         }
279                         $baseurl = 'webservice/pluginfile.php';
281                         //call $modulename_export_contents
282                         //(each module callback take care about checking the capabilities)
284                         require_once($CFG->dirroot . '/mod/' . $cm->modname . '/lib.php');
285                         $getcontentfunction = $cm->modname.'_export_contents';
286                         if (function_exists($getcontentfunction)) {
287                             if (empty($filters['excludecontents']) and $contents = $getcontentfunction($cm, $baseurl)) {
288                                 $module['contents'] = $contents;
289                             } else {
290                                 $module['contents'] = array();
291                             }
292                         }
294                         //assign result to $sectioncontents
295                         $sectioncontents[] = $module;
297                         // If we just did a filtering, break the loop.
298                         if ($modfound) {
299                             break;
300                         }
302                     }
303                 }
304                 $sectionvalues['modules'] = $sectioncontents;
306                 // assign result to $coursecontents
307                 $coursecontents[] = $sectionvalues;
309                 // Break the loop if we are filtering.
310                 if ($sectionfound) {
311                     break;
312                 }
313             }
314         }
315         return $coursecontents;
316     }
318     /**
319      * Returns description of method result value
320      *
321      * @return external_description
322      * @since Moodle 2.2
323      */
324     public static function get_course_contents_returns() {
325         return new external_multiple_structure(
326             new external_single_structure(
327                 array(
328                     'id' => new external_value(PARAM_INT, 'Section ID'),
329                     'name' => new external_value(PARAM_TEXT, 'Section name'),
330                     'visible' => new external_value(PARAM_INT, 'is the section visible', VALUE_OPTIONAL),
331                     'summary' => new external_value(PARAM_RAW, 'Section description'),
332                     'summaryformat' => new external_format_value('summary'),
333                     'section' => new external_value(PARAM_INT, 'Section number inside the course', VALUE_OPTIONAL),
334                     'hiddenbynumsections' => new external_value(PARAM_INT, 'Whether is a section hidden in the course format',
335                                                                 VALUE_OPTIONAL),
336                     'modules' => new external_multiple_structure(
337                             new external_single_structure(
338                                 array(
339                                     'id' => new external_value(PARAM_INT, 'activity id'),
340                                     'url' => new external_value(PARAM_URL, 'activity url', VALUE_OPTIONAL),
341                                     'name' => new external_value(PARAM_RAW, 'activity module name'),
342                                     'instance' => new external_value(PARAM_INT, 'instance id', VALUE_OPTIONAL),
343                                     'description' => new external_value(PARAM_RAW, 'activity description', VALUE_OPTIONAL),
344                                     'visible' => new external_value(PARAM_INT, 'is the module visible', VALUE_OPTIONAL),
345                                     'modicon' => new external_value(PARAM_URL, 'activity icon url'),
346                                     'modname' => new external_value(PARAM_PLUGIN, 'activity module type'),
347                                     'modplural' => new external_value(PARAM_TEXT, 'activity module plural name'),
348                                     'availability' => new external_value(PARAM_RAW, 'module availability settings', VALUE_OPTIONAL),
349                                     'indent' => new external_value(PARAM_INT, 'number of identation in the site'),
350                                     'contents' => new external_multiple_structure(
351                                           new external_single_structure(
352                                               array(
353                                                   // content info
354                                                   'type'=> new external_value(PARAM_TEXT, 'a file or a folder or external link'),
355                                                   'filename'=> new external_value(PARAM_FILE, 'filename'),
356                                                   'filepath'=> new external_value(PARAM_PATH, 'filepath'),
357                                                   'filesize'=> new external_value(PARAM_INT, 'filesize'),
358                                                   'fileurl' => new external_value(PARAM_URL, 'downloadable file url', VALUE_OPTIONAL),
359                                                   'content' => new external_value(PARAM_RAW, 'Raw content, will be used when type is content', VALUE_OPTIONAL),
360                                                   'timecreated' => new external_value(PARAM_INT, 'Time created'),
361                                                   'timemodified' => new external_value(PARAM_INT, 'Time modified'),
362                                                   'sortorder' => new external_value(PARAM_INT, 'Content sort order'),
364                                                   // copyright related info
365                                                   'userid' => new external_value(PARAM_INT, 'User who added this content to moodle'),
366                                                   'author' => new external_value(PARAM_TEXT, 'Content owner'),
367                                                   'license' => new external_value(PARAM_TEXT, 'Content license'),
368                                               )
369                                           ), VALUE_DEFAULT, array()
370                                       )
371                                 )
372                             ), 'list of module'
373                     )
374                 )
375             )
376         );
377     }
379     /**
380      * Returns description of method parameters
381      *
382      * @return external_function_parameters
383      * @since Moodle 2.3
384      */
385     public static function get_courses_parameters() {
386         return new external_function_parameters(
387                 array('options' => new external_single_structure(
388                             array('ids' => new external_multiple_structure(
389                                         new external_value(PARAM_INT, 'Course id')
390                                         , 'List of course id. If empty return all courses
391                                             except front page course.',
392                                         VALUE_OPTIONAL)
393                             ), 'options - operator OR is used', VALUE_DEFAULT, array())
394                 )
395         );
396     }
398     /**
399      * Get courses
400      *
401      * @param array $options It contains an array (list of ids)
402      * @return array
403      * @since Moodle 2.2
404      */
405     public static function get_courses($options = array()) {
406         global $CFG, $DB;
407         require_once($CFG->dirroot . "/course/lib.php");
409         //validate parameter
410         $params = self::validate_parameters(self::get_courses_parameters(),
411                         array('options' => $options));
413         //retrieve courses
414         if (!array_key_exists('ids', $params['options'])
415                 or empty($params['options']['ids'])) {
416             $courses = $DB->get_records('course');
417         } else {
418             $courses = $DB->get_records_list('course', 'id', $params['options']['ids']);
419         }
421         //create return value
422         $coursesinfo = array();
423         foreach ($courses as $course) {
425             // now security checks
426             $context = context_course::instance($course->id, IGNORE_MISSING);
427             $courseformatoptions = course_get_format($course)->get_format_options();
428             try {
429                 self::validate_context($context);
430             } catch (Exception $e) {
431                 $exceptionparam = new stdClass();
432                 $exceptionparam->message = $e->getMessage();
433                 $exceptionparam->courseid = $course->id;
434                 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
435             }
436             require_capability('moodle/course:view', $context);
438             $courseinfo = array();
439             $courseinfo['id'] = $course->id;
440             $courseinfo['fullname'] = external_format_string($course->fullname, $context->id);
441             $courseinfo['shortname'] = external_format_string($course->shortname, $context->id);
442             $courseinfo['displayname'] = external_format_string(get_course_display_name_for_list($course), $context->id);
443             $courseinfo['categoryid'] = $course->category;
444             list($courseinfo['summary'], $courseinfo['summaryformat']) =
445                 external_format_text($course->summary, $course->summaryformat, $context->id, 'course', 'summary', 0);
446             $courseinfo['format'] = $course->format;
447             $courseinfo['startdate'] = $course->startdate;
448             $courseinfo['enddate'] = $course->enddate;
449             if (array_key_exists('numsections', $courseformatoptions)) {
450                 // For backward-compartibility
451                 $courseinfo['numsections'] = $courseformatoptions['numsections'];
452             }
454             //some field should be returned only if the user has update permission
455             $courseadmin = has_capability('moodle/course:update', $context);
456             if ($courseadmin) {
457                 $courseinfo['categorysortorder'] = $course->sortorder;
458                 $courseinfo['idnumber'] = $course->idnumber;
459                 $courseinfo['showgrades'] = $course->showgrades;
460                 $courseinfo['showreports'] = $course->showreports;
461                 $courseinfo['newsitems'] = $course->newsitems;
462                 $courseinfo['visible'] = $course->visible;
463                 $courseinfo['maxbytes'] = $course->maxbytes;
464                 if (array_key_exists('hiddensections', $courseformatoptions)) {
465                     // For backward-compartibility
466                     $courseinfo['hiddensections'] = $courseformatoptions['hiddensections'];
467                 }
468                 $courseinfo['groupmode'] = $course->groupmode;
469                 $courseinfo['groupmodeforce'] = $course->groupmodeforce;
470                 $courseinfo['defaultgroupingid'] = $course->defaultgroupingid;
471                 $courseinfo['lang'] = $course->lang;
472                 $courseinfo['timecreated'] = $course->timecreated;
473                 $courseinfo['timemodified'] = $course->timemodified;
474                 $courseinfo['forcetheme'] = $course->theme;
475                 $courseinfo['enablecompletion'] = $course->enablecompletion;
476                 $courseinfo['completionnotify'] = $course->completionnotify;
477                 $courseinfo['courseformatoptions'] = array();
478                 foreach ($courseformatoptions as $key => $value) {
479                     $courseinfo['courseformatoptions'][] = array(
480                         'name' => $key,
481                         'value' => $value
482                     );
483                 }
484             }
486             if ($courseadmin or $course->visible
487                     or has_capability('moodle/course:viewhiddencourses', $context)) {
488                 $coursesinfo[] = $courseinfo;
489             }
490         }
492         return $coursesinfo;
493     }
495     /**
496      * Returns description of method result value
497      *
498      * @return external_description
499      * @since Moodle 2.2
500      */
501     public static function get_courses_returns() {
502         return new external_multiple_structure(
503                 new external_single_structure(
504                         array(
505                             'id' => new external_value(PARAM_INT, 'course id'),
506                             'shortname' => new external_value(PARAM_TEXT, 'course short name'),
507                             'categoryid' => new external_value(PARAM_INT, 'category id'),
508                             'categorysortorder' => new external_value(PARAM_INT,
509                                     'sort order into the category', VALUE_OPTIONAL),
510                             'fullname' => new external_value(PARAM_TEXT, 'full name'),
511                             'displayname' => new external_value(PARAM_TEXT, 'course display name'),
512                             'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
513                             'summary' => new external_value(PARAM_RAW, 'summary'),
514                             'summaryformat' => new external_format_value('summary'),
515                             'format' => new external_value(PARAM_PLUGIN,
516                                     'course format: weeks, topics, social, site,..'),
517                             'showgrades' => new external_value(PARAM_INT,
518                                     '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
519                             'newsitems' => new external_value(PARAM_INT,
520                                     'number of recent items appearing on the course page', VALUE_OPTIONAL),
521                             'startdate' => new external_value(PARAM_INT,
522                                     'timestamp when the course start'),
523                             'enddate' => new external_value(PARAM_INT,
524                                     'timestamp when the course end'),
525                             'numsections' => new external_value(PARAM_INT,
526                                     '(deprecated, use courseformatoptions) number of weeks/topics',
527                                     VALUE_OPTIONAL),
528                             'maxbytes' => new external_value(PARAM_INT,
529                                     'largest size of file that can be uploaded into the course',
530                                     VALUE_OPTIONAL),
531                             'showreports' => new external_value(PARAM_INT,
532                                     'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
533                             'visible' => new external_value(PARAM_INT,
534                                     '1: available to student, 0:not available', VALUE_OPTIONAL),
535                             'hiddensections' => new external_value(PARAM_INT,
536                                     '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
537                                     VALUE_OPTIONAL),
538                             'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
539                                     VALUE_OPTIONAL),
540                             'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
541                                     VALUE_OPTIONAL),
542                             'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
543                                     VALUE_OPTIONAL),
544                             'timecreated' => new external_value(PARAM_INT,
545                                     'timestamp when the course have been created', VALUE_OPTIONAL),
546                             'timemodified' => new external_value(PARAM_INT,
547                                     'timestamp when the course have been modified', VALUE_OPTIONAL),
548                             'enablecompletion' => new external_value(PARAM_INT,
549                                     'Enabled, control via completion and activity settings. Disbaled,
550                                         not shown in activity settings.',
551                                     VALUE_OPTIONAL),
552                             'completionnotify' => new external_value(PARAM_INT,
553                                     '1: yes 0: no', VALUE_OPTIONAL),
554                             'lang' => new external_value(PARAM_SAFEDIR,
555                                     'forced course language', VALUE_OPTIONAL),
556                             'forcetheme' => new external_value(PARAM_PLUGIN,
557                                     'name of the force theme', VALUE_OPTIONAL),
558                             'courseformatoptions' => new external_multiple_structure(
559                                 new external_single_structure(
560                                     array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
561                                         'value' => new external_value(PARAM_RAW, 'course format option value')
562                                 )),
563                                     'additional options for particular course format', VALUE_OPTIONAL
564                              ),
565                         ), 'course'
566                 )
567         );
568     }
570     /**
571      * Returns description of method parameters
572      *
573      * @return external_function_parameters
574      * @since Moodle 2.2
575      */
576     public static function create_courses_parameters() {
577         $courseconfig = get_config('moodlecourse'); //needed for many default values
578         return new external_function_parameters(
579             array(
580                 'courses' => new external_multiple_structure(
581                     new external_single_structure(
582                         array(
583                             'fullname' => new external_value(PARAM_TEXT, 'full name'),
584                             'shortname' => new external_value(PARAM_TEXT, 'course short name'),
585                             'categoryid' => new external_value(PARAM_INT, 'category id'),
586                             'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
587                             'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
588                             'summaryformat' => new external_format_value('summary', VALUE_DEFAULT),
589                             'format' => new external_value(PARAM_PLUGIN,
590                                     'course format: weeks, topics, social, site,..',
591                                     VALUE_DEFAULT, $courseconfig->format),
592                             'showgrades' => new external_value(PARAM_INT,
593                                     '1 if grades are shown, otherwise 0', VALUE_DEFAULT,
594                                     $courseconfig->showgrades),
595                             'newsitems' => new external_value(PARAM_INT,
596                                     'number of recent items appearing on the course page',
597                                     VALUE_DEFAULT, $courseconfig->newsitems),
598                             'startdate' => new external_value(PARAM_INT,
599                                     'timestamp when the course start', VALUE_OPTIONAL),
600                             'enddate' => new external_value(PARAM_INT,
601                                     'timestamp when the course end', VALUE_OPTIONAL),
602                             'numsections' => new external_value(PARAM_INT,
603                                     '(deprecated, use courseformatoptions) number of weeks/topics',
604                                     VALUE_OPTIONAL),
605                             'maxbytes' => new external_value(PARAM_INT,
606                                     'largest size of file that can be uploaded into the course',
607                                     VALUE_DEFAULT, $courseconfig->maxbytes),
608                             'showreports' => new external_value(PARAM_INT,
609                                     'are activity report shown (yes = 1, no =0)', VALUE_DEFAULT,
610                                     $courseconfig->showreports),
611                             'visible' => new external_value(PARAM_INT,
612                                     '1: available to student, 0:not available', VALUE_OPTIONAL),
613                             'hiddensections' => new external_value(PARAM_INT,
614                                     '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
615                                     VALUE_OPTIONAL),
616                             'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
617                                     VALUE_DEFAULT, $courseconfig->groupmode),
618                             'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
619                                     VALUE_DEFAULT, $courseconfig->groupmodeforce),
620                             'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
621                                     VALUE_DEFAULT, 0),
622                             'enablecompletion' => new external_value(PARAM_INT,
623                                     'Enabled, control via completion and activity settings. Disabled,
624                                         not shown in activity settings.',
625                                     VALUE_OPTIONAL),
626                             'completionnotify' => new external_value(PARAM_INT,
627                                     '1: yes 0: no', VALUE_OPTIONAL),
628                             'lang' => new external_value(PARAM_SAFEDIR,
629                                     'forced course language', VALUE_OPTIONAL),
630                             'forcetheme' => new external_value(PARAM_PLUGIN,
631                                     'name of the force theme', VALUE_OPTIONAL),
632                             'courseformatoptions' => new external_multiple_structure(
633                                 new external_single_structure(
634                                     array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
635                                         'value' => new external_value(PARAM_RAW, 'course format option value')
636                                 )),
637                                     'additional options for particular course format', VALUE_OPTIONAL),
638                         )
639                     ), 'courses to create'
640                 )
641             )
642         );
643     }
645     /**
646      * Create  courses
647      *
648      * @param array $courses
649      * @return array courses (id and shortname only)
650      * @since Moodle 2.2
651      */
652     public static function create_courses($courses) {
653         global $CFG, $DB;
654         require_once($CFG->dirroot . "/course/lib.php");
655         require_once($CFG->libdir . '/completionlib.php');
657         $params = self::validate_parameters(self::create_courses_parameters(),
658                         array('courses' => $courses));
660         $availablethemes = core_component::get_plugin_list('theme');
661         $availablelangs = get_string_manager()->get_list_of_translations();
663         $transaction = $DB->start_delegated_transaction();
665         foreach ($params['courses'] as $course) {
667             // Ensure the current user is allowed to run this function
668             $context = context_coursecat::instance($course['categoryid'], IGNORE_MISSING);
669             try {
670                 self::validate_context($context);
671             } catch (Exception $e) {
672                 $exceptionparam = new stdClass();
673                 $exceptionparam->message = $e->getMessage();
674                 $exceptionparam->catid = $course['categoryid'];
675                 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
676             }
677             require_capability('moodle/course:create', $context);
679             // Make sure lang is valid
680             if (array_key_exists('lang', $course) and empty($availablelangs[$course['lang']])) {
681                 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
682             }
684             // Make sure theme is valid
685             if (array_key_exists('forcetheme', $course)) {
686                 if (!empty($CFG->allowcoursethemes)) {
687                     if (empty($availablethemes[$course['forcetheme']])) {
688                         throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
689                     } else {
690                         $course['theme'] = $course['forcetheme'];
691                     }
692                 }
693             }
695             //force visibility if ws user doesn't have the permission to set it
696             $category = $DB->get_record('course_categories', array('id' => $course['categoryid']));
697             if (!has_capability('moodle/course:visibility', $context)) {
698                 $course['visible'] = $category->visible;
699             }
701             //set default value for completion
702             $courseconfig = get_config('moodlecourse');
703             if (completion_info::is_enabled_for_site()) {
704                 if (!array_key_exists('enablecompletion', $course)) {
705                     $course['enablecompletion'] = $courseconfig->enablecompletion;
706                 }
707             } else {
708                 $course['enablecompletion'] = 0;
709             }
711             $course['category'] = $course['categoryid'];
713             // Summary format.
714             $course['summaryformat'] = external_validate_format($course['summaryformat']);
716             if (!empty($course['courseformatoptions'])) {
717                 foreach ($course['courseformatoptions'] as $option) {
718                     $course[$option['name']] = $option['value'];
719                 }
720             }
722             //Note: create_course() core function check shortname, idnumber, category
723             $course['id'] = create_course((object) $course)->id;
725             $resultcourses[] = array('id' => $course['id'], 'shortname' => $course['shortname']);
726         }
728         $transaction->allow_commit();
730         return $resultcourses;
731     }
733     /**
734      * Returns description of method result value
735      *
736      * @return external_description
737      * @since Moodle 2.2
738      */
739     public static function create_courses_returns() {
740         return new external_multiple_structure(
741             new external_single_structure(
742                 array(
743                     'id'       => new external_value(PARAM_INT, 'course id'),
744                     'shortname' => new external_value(PARAM_TEXT, 'short name'),
745                 )
746             )
747         );
748     }
750     /**
751      * Update courses
752      *
753      * @return external_function_parameters
754      * @since Moodle 2.5
755      */
756     public static function update_courses_parameters() {
757         return new external_function_parameters(
758             array(
759                 'courses' => new external_multiple_structure(
760                     new external_single_structure(
761                         array(
762                             'id' => new external_value(PARAM_INT, 'ID of the course'),
763                             'fullname' => new external_value(PARAM_TEXT, 'full name', VALUE_OPTIONAL),
764                             'shortname' => new external_value(PARAM_TEXT, 'course short name', VALUE_OPTIONAL),
765                             'categoryid' => new external_value(PARAM_INT, 'category id', VALUE_OPTIONAL),
766                             'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
767                             'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
768                             'summaryformat' => new external_format_value('summary', VALUE_OPTIONAL),
769                             'format' => new external_value(PARAM_PLUGIN,
770                                     'course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
771                             'showgrades' => new external_value(PARAM_INT,
772                                     '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
773                             'newsitems' => new external_value(PARAM_INT,
774                                     'number of recent items appearing on the course page', VALUE_OPTIONAL),
775                             'startdate' => new external_value(PARAM_INT,
776                                     'timestamp when the course start', VALUE_OPTIONAL),
777                             'enddate' => new external_value(PARAM_INT,
778                                     'timestamp when the course end', VALUE_OPTIONAL),
779                             'numsections' => new external_value(PARAM_INT,
780                                     '(deprecated, use courseformatoptions) number of weeks/topics', VALUE_OPTIONAL),
781                             'maxbytes' => new external_value(PARAM_INT,
782                                     'largest size of file that can be uploaded into the course', VALUE_OPTIONAL),
783                             'showreports' => new external_value(PARAM_INT,
784                                     'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
785                             'visible' => new external_value(PARAM_INT,
786                                     '1: available to student, 0:not available', VALUE_OPTIONAL),
787                             'hiddensections' => new external_value(PARAM_INT,
788                                     '(deprecated, use courseformatoptions) How the hidden sections in the course are
789                                         displayed to students', VALUE_OPTIONAL),
790                             'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
791                             'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
792                             'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
793                             'enablecompletion' => new external_value(PARAM_INT,
794                                     'Enabled, control via completion and activity settings. Disabled,
795                                         not shown in activity settings.', VALUE_OPTIONAL),
796                             'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
797                             'lang' => new external_value(PARAM_SAFEDIR, 'forced course language', VALUE_OPTIONAL),
798                             'forcetheme' => new external_value(PARAM_PLUGIN, 'name of the force theme', VALUE_OPTIONAL),
799                             'courseformatoptions' => new external_multiple_structure(
800                                 new external_single_structure(
801                                     array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
802                                         'value' => new external_value(PARAM_RAW, 'course format option value')
803                                 )),
804                                     'additional options for particular course format', VALUE_OPTIONAL),
805                         )
806                     ), 'courses to update'
807                 )
808             )
809         );
810     }
812     /**
813      * Update courses
814      *
815      * @param array $courses
816      * @since Moodle 2.5
817      */
818     public static function update_courses($courses) {
819         global $CFG, $DB;
820         require_once($CFG->dirroot . "/course/lib.php");
821         $warnings = array();
823         $params = self::validate_parameters(self::update_courses_parameters(),
824                         array('courses' => $courses));
826         $availablethemes = core_component::get_plugin_list('theme');
827         $availablelangs = get_string_manager()->get_list_of_translations();
829         foreach ($params['courses'] as $course) {
830             // Catch any exception while updating course and return as warning to user.
831             try {
832                 // Ensure the current user is allowed to run this function.
833                 $context = context_course::instance($course['id'], MUST_EXIST);
834                 self::validate_context($context);
836                 $oldcourse = course_get_format($course['id'])->get_course();
838                 require_capability('moodle/course:update', $context);
840                 // Check if user can change category.
841                 if (array_key_exists('categoryid', $course) && ($oldcourse->category != $course['categoryid'])) {
842                     require_capability('moodle/course:changecategory', $context);
843                     $course['category'] = $course['categoryid'];
844                 }
846                 // Check if the user can change fullname.
847                 if (array_key_exists('fullname', $course) && ($oldcourse->fullname != $course['fullname'])) {
848                     require_capability('moodle/course:changefullname', $context);
849                 }
851                 // Check if the user can change shortname.
852                 if (array_key_exists('shortname', $course) && ($oldcourse->shortname != $course['shortname'])) {
853                     require_capability('moodle/course:changeshortname', $context);
854                 }
856                 // Check if the user can change the idnumber.
857                 if (array_key_exists('idnumber', $course) && ($oldcourse->idnumber != $course['idnumber'])) {
858                     require_capability('moodle/course:changeidnumber', $context);
859                 }
861                 // Check if user can change summary.
862                 if (array_key_exists('summary', $course) && ($oldcourse->summary != $course['summary'])) {
863                     require_capability('moodle/course:changesummary', $context);
864                 }
866                 // Summary format.
867                 if (array_key_exists('summaryformat', $course) && ($oldcourse->summaryformat != $course['summaryformat'])) {
868                     require_capability('moodle/course:changesummary', $context);
869                     $course['summaryformat'] = external_validate_format($course['summaryformat']);
870                 }
872                 // Check if user can change visibility.
873                 if (array_key_exists('visible', $course) && ($oldcourse->visible != $course['visible'])) {
874                     require_capability('moodle/course:visibility', $context);
875                 }
877                 // Make sure lang is valid.
878                 if (array_key_exists('lang', $course) && empty($availablelangs[$course['lang']])) {
879                     throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
880                 }
882                 // Make sure theme is valid.
883                 if (array_key_exists('forcetheme', $course)) {
884                     if (!empty($CFG->allowcoursethemes)) {
885                         if (empty($availablethemes[$course['forcetheme']])) {
886                             throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
887                         } else {
888                             $course['theme'] = $course['forcetheme'];
889                         }
890                     }
891                 }
893                 // Make sure completion is enabled before setting it.
894                 if (array_key_exists('enabledcompletion', $course) && !completion_info::is_enabled_for_site()) {
895                     $course['enabledcompletion'] = 0;
896                 }
898                 // Make sure maxbytes are less then CFG->maxbytes.
899                 if (array_key_exists('maxbytes', $course)) {
900                     $course['maxbytes'] = get_max_upload_file_size($CFG->maxbytes, $course['maxbytes']);
901                 }
903                 if (!empty($course['courseformatoptions'])) {
904                     foreach ($course['courseformatoptions'] as $option) {
905                         if (isset($option['name']) && isset($option['value'])) {
906                             $course[$option['name']] = $option['value'];
907                         }
908                     }
909                 }
911                 // Update course if user has all required capabilities.
912                 update_course((object) $course);
913             } catch (Exception $e) {
914                 $warning = array();
915                 $warning['item'] = 'course';
916                 $warning['itemid'] = $course['id'];
917                 if ($e instanceof moodle_exception) {
918                     $warning['warningcode'] = $e->errorcode;
919                 } else {
920                     $warning['warningcode'] = $e->getCode();
921                 }
922                 $warning['message'] = $e->getMessage();
923                 $warnings[] = $warning;
924             }
925         }
927         $result = array();
928         $result['warnings'] = $warnings;
929         return $result;
930     }
932     /**
933      * Returns description of method result value
934      *
935      * @return external_description
936      * @since Moodle 2.5
937      */
938     public static function update_courses_returns() {
939         return new external_single_structure(
940             array(
941                 'warnings' => new external_warnings()
942             )
943         );
944     }
946     /**
947      * Returns description of method parameters
948      *
949      * @return external_function_parameters
950      * @since Moodle 2.2
951      */
952     public static function delete_courses_parameters() {
953         return new external_function_parameters(
954             array(
955                 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'course ID')),
956             )
957         );
958     }
960     /**
961      * Delete courses
962      *
963      * @param array $courseids A list of course ids
964      * @since Moodle 2.2
965      */
966     public static function delete_courses($courseids) {
967         global $CFG, $DB;
968         require_once($CFG->dirroot."/course/lib.php");
970         // Parameter validation.
971         $params = self::validate_parameters(self::delete_courses_parameters(), array('courseids'=>$courseids));
973         $warnings = array();
975         foreach ($params['courseids'] as $courseid) {
976             $course = $DB->get_record('course', array('id' => $courseid));
978             if ($course === false) {
979                 $warnings[] = array(
980                                 'item' => 'course',
981                                 'itemid' => $courseid,
982                                 'warningcode' => 'unknowncourseidnumber',
983                                 'message' => 'Unknown course ID ' . $courseid
984                             );
985                 continue;
986             }
988             // Check if the context is valid.
989             $coursecontext = context_course::instance($course->id);
990             self::validate_context($coursecontext);
992             // Check if the current user has permission.
993             if (!can_delete_course($courseid)) {
994                 $warnings[] = array(
995                                 'item' => 'course',
996                                 'itemid' => $courseid,
997                                 'warningcode' => 'cannotdeletecourse',
998                                 'message' => 'You do not have the permission to delete this course' . $courseid
999                             );
1000                 continue;
1001             }
1003             if (delete_course($course, false) === false) {
1004                 $warnings[] = array(
1005                                 'item' => 'course',
1006                                 'itemid' => $courseid,
1007                                 'warningcode' => 'cannotdeletecategorycourse',
1008                                 'message' => 'Course ' . $courseid . ' failed to be deleted'
1009                             );
1010                 continue;
1011             }
1012         }
1014         fix_course_sortorder();
1016         return array('warnings' => $warnings);
1017     }
1019     /**
1020      * Returns description of method result value
1021      *
1022      * @return external_description
1023      * @since Moodle 2.2
1024      */
1025     public static function delete_courses_returns() {
1026         return new external_single_structure(
1027             array(
1028                 'warnings' => new external_warnings()
1029             )
1030         );
1031     }
1033     /**
1034      * Returns description of method parameters
1035      *
1036      * @return external_function_parameters
1037      * @since Moodle 2.3
1038      */
1039     public static function duplicate_course_parameters() {
1040         return new external_function_parameters(
1041             array(
1042                 'courseid' => new external_value(PARAM_INT, 'course to duplicate id'),
1043                 'fullname' => new external_value(PARAM_TEXT, 'duplicated course full name'),
1044                 'shortname' => new external_value(PARAM_TEXT, 'duplicated course short name'),
1045                 'categoryid' => new external_value(PARAM_INT, 'duplicated course category parent'),
1046                 'visible' => new external_value(PARAM_INT, 'duplicated course visible, default to yes', VALUE_DEFAULT, 1),
1047                 'options' => new external_multiple_structure(
1048                     new external_single_structure(
1049                         array(
1050                                 'name' => new external_value(PARAM_ALPHAEXT, 'The backup option name:
1051                                             "activities" (int) Include course activites (default to 1 that is equal to yes),
1052                                             "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1053                                             "filters" (int) Include course filters  (default to 1 that is equal to yes),
1054                                             "users" (int) Include users (default to 0 that is equal to no),
1055                                             "role_assignments" (int) Include role assignments  (default to 0 that is equal to no),
1056                                             "comments" (int) Include user comments  (default to 0 that is equal to no),
1057                                             "userscompletion" (int) Include user course completion information  (default to 0 that is equal to no),
1058                                             "logs" (int) Include course logs  (default to 0 that is equal to no),
1059                                             "grade_histories" (int) Include histories  (default to 0 that is equal to no)'
1060                                             ),
1061                                 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1062                             )
1063                         )
1064                     ), VALUE_DEFAULT, array()
1065                 ),
1066             )
1067         );
1068     }
1070     /**
1071      * Duplicate a course
1072      *
1073      * @param int $courseid
1074      * @param string $fullname Duplicated course fullname
1075      * @param string $shortname Duplicated course shortname
1076      * @param int $categoryid Duplicated course parent category id
1077      * @param int $visible Duplicated course availability
1078      * @param array $options List of backup options
1079      * @return array New course info
1080      * @since Moodle 2.3
1081      */
1082     public static function duplicate_course($courseid, $fullname, $shortname, $categoryid, $visible = 1, $options = array()) {
1083         global $CFG, $USER, $DB;
1084         require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1085         require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1087         // Parameter validation.
1088         $params = self::validate_parameters(
1089                 self::duplicate_course_parameters(),
1090                 array(
1091                       'courseid' => $courseid,
1092                       'fullname' => $fullname,
1093                       'shortname' => $shortname,
1094                       'categoryid' => $categoryid,
1095                       'visible' => $visible,
1096                       'options' => $options
1097                 )
1098         );
1100         // Context validation.
1102         if (! ($course = $DB->get_record('course', array('id'=>$params['courseid'])))) {
1103             throw new moodle_exception('invalidcourseid', 'error');
1104         }
1106         // Category where duplicated course is going to be created.
1107         $categorycontext = context_coursecat::instance($params['categoryid']);
1108         self::validate_context($categorycontext);
1110         // Course to be duplicated.
1111         $coursecontext = context_course::instance($course->id);
1112         self::validate_context($coursecontext);
1114         $backupdefaults = array(
1115             'activities' => 1,
1116             'blocks' => 1,
1117             'filters' => 1,
1118             'users' => 0,
1119             'role_assignments' => 0,
1120             'comments' => 0,
1121             'userscompletion' => 0,
1122             'logs' => 0,
1123             'grade_histories' => 0
1124         );
1126         $backupsettings = array();
1127         // Check for backup and restore options.
1128         if (!empty($params['options'])) {
1129             foreach ($params['options'] as $option) {
1131                 // Strict check for a correct value (allways 1 or 0, true or false).
1132                 $value = clean_param($option['value'], PARAM_INT);
1134                 if ($value !== 0 and $value !== 1) {
1135                     throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1136                 }
1138                 if (!isset($backupdefaults[$option['name']])) {
1139                     throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1140                 }
1142                 $backupsettings[$option['name']] = $value;
1143             }
1144         }
1146         // Capability checking.
1148         // The backup controller check for this currently, this may be redundant.
1149         require_capability('moodle/course:create', $categorycontext);
1150         require_capability('moodle/restore:restorecourse', $categorycontext);
1151         require_capability('moodle/backup:backupcourse', $coursecontext);
1153         if (!empty($backupsettings['users'])) {
1154             require_capability('moodle/backup:userinfo', $coursecontext);
1155             require_capability('moodle/restore:userinfo', $categorycontext);
1156         }
1158         // Check if the shortname is used.
1159         if ($foundcourses = $DB->get_records('course', array('shortname'=>$shortname))) {
1160             foreach ($foundcourses as $foundcourse) {
1161                 $foundcoursenames[] = $foundcourse->fullname;
1162             }
1164             $foundcoursenamestring = implode(',', $foundcoursenames);
1165             throw new moodle_exception('shortnametaken', '', '', $foundcoursenamestring);
1166         }
1168         // Backup the course.
1170         $bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE,
1171         backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id);
1173         foreach ($backupsettings as $name => $value) {
1174             $bc->get_plan()->get_setting($name)->set_value($value);
1175         }
1177         $backupid       = $bc->get_backupid();
1178         $backupbasepath = $bc->get_plan()->get_basepath();
1180         $bc->execute_plan();
1181         $results = $bc->get_results();
1182         $file = $results['backup_destination'];
1184         $bc->destroy();
1186         // Restore the backup immediately.
1188         // Check if we need to unzip the file because the backup temp dir does not contains backup files.
1189         if (!file_exists($backupbasepath . "/moodle_backup.xml")) {
1190             $file->extract_to_pathname(get_file_packer('application/vnd.moodle.backup'), $backupbasepath);
1191         }
1193         // Create new course.
1194         $newcourseid = restore_dbops::create_new_course($params['fullname'], $params['shortname'], $params['categoryid']);
1196         $rc = new restore_controller($backupid, $newcourseid,
1197                 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id, backup::TARGET_NEW_COURSE);
1199         foreach ($backupsettings as $name => $value) {
1200             $setting = $rc->get_plan()->get_setting($name);
1201             if ($setting->get_status() == backup_setting::NOT_LOCKED) {
1202                 $setting->set_value($value);
1203             }
1204         }
1206         if (!$rc->execute_precheck()) {
1207             $precheckresults = $rc->get_precheck_results();
1208             if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1209                 if (empty($CFG->keeptempdirectoriesonbackup)) {
1210                     fulldelete($backupbasepath);
1211                 }
1213                 $errorinfo = '';
1215                 foreach ($precheckresults['errors'] as $error) {
1216                     $errorinfo .= $error;
1217                 }
1219                 if (array_key_exists('warnings', $precheckresults)) {
1220                     foreach ($precheckresults['warnings'] as $warning) {
1221                         $errorinfo .= $warning;
1222                     }
1223                 }
1225                 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1226             }
1227         }
1229         $rc->execute_plan();
1230         $rc->destroy();
1232         $course = $DB->get_record('course', array('id' => $newcourseid), '*', MUST_EXIST);
1233         $course->fullname = $params['fullname'];
1234         $course->shortname = $params['shortname'];
1235         $course->visible = $params['visible'];
1237         // Set shortname and fullname back.
1238         $DB->update_record('course', $course);
1240         if (empty($CFG->keeptempdirectoriesonbackup)) {
1241             fulldelete($backupbasepath);
1242         }
1244         // Delete the course backup file created by this WebService. Originally located in the course backups area.
1245         $file->delete();
1247         return array('id' => $course->id, 'shortname' => $course->shortname);
1248     }
1250     /**
1251      * Returns description of method result value
1252      *
1253      * @return external_description
1254      * @since Moodle 2.3
1255      */
1256     public static function duplicate_course_returns() {
1257         return new external_single_structure(
1258             array(
1259                 'id'       => new external_value(PARAM_INT, 'course id'),
1260                 'shortname' => new external_value(PARAM_TEXT, 'short name'),
1261             )
1262         );
1263     }
1265     /**
1266      * Returns description of method parameters for import_course
1267      *
1268      * @return external_function_parameters
1269      * @since Moodle 2.4
1270      */
1271     public static function import_course_parameters() {
1272         return new external_function_parameters(
1273             array(
1274                 'importfrom' => new external_value(PARAM_INT, 'the id of the course we are importing from'),
1275                 'importto' => new external_value(PARAM_INT, 'the id of the course we are importing to'),
1276                 'deletecontent' => new external_value(PARAM_INT, 'whether to delete the course content where we are importing to (default to 0 = No)', VALUE_DEFAULT, 0),
1277                 'options' => new external_multiple_structure(
1278                     new external_single_structure(
1279                         array(
1280                                 'name' => new external_value(PARAM_ALPHA, 'The backup option name:
1281                                             "activities" (int) Include course activites (default to 1 that is equal to yes),
1282                                             "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1283                                             "filters" (int) Include course filters  (default to 1 that is equal to yes)'
1284                                             ),
1285                                 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1286                             )
1287                         )
1288                     ), VALUE_DEFAULT, array()
1289                 ),
1290             )
1291         );
1292     }
1294     /**
1295      * Imports a course
1296      *
1297      * @param int $importfrom The id of the course we are importing from
1298      * @param int $importto The id of the course we are importing to
1299      * @param bool $deletecontent Whether to delete the course we are importing to content
1300      * @param array $options List of backup options
1301      * @return null
1302      * @since Moodle 2.4
1303      */
1304     public static function import_course($importfrom, $importto, $deletecontent = 0, $options = array()) {
1305         global $CFG, $USER, $DB;
1306         require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1307         require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1309         // Parameter validation.
1310         $params = self::validate_parameters(
1311             self::import_course_parameters(),
1312             array(
1313                 'importfrom' => $importfrom,
1314                 'importto' => $importto,
1315                 'deletecontent' => $deletecontent,
1316                 'options' => $options
1317             )
1318         );
1320         if ($params['deletecontent'] !== 0 and $params['deletecontent'] !== 1) {
1321             throw new moodle_exception('invalidextparam', 'webservice', '', $params['deletecontent']);
1322         }
1324         // Context validation.
1326         if (! ($importfrom = $DB->get_record('course', array('id'=>$params['importfrom'])))) {
1327             throw new moodle_exception('invalidcourseid', 'error');
1328         }
1330         if (! ($importto = $DB->get_record('course', array('id'=>$params['importto'])))) {
1331             throw new moodle_exception('invalidcourseid', 'error');
1332         }
1334         $importfromcontext = context_course::instance($importfrom->id);
1335         self::validate_context($importfromcontext);
1337         $importtocontext = context_course::instance($importto->id);
1338         self::validate_context($importtocontext);
1340         $backupdefaults = array(
1341             'activities' => 1,
1342             'blocks' => 1,
1343             'filters' => 1
1344         );
1346         $backupsettings = array();
1348         // Check for backup and restore options.
1349         if (!empty($params['options'])) {
1350             foreach ($params['options'] as $option) {
1352                 // Strict check for a correct value (allways 1 or 0, true or false).
1353                 $value = clean_param($option['value'], PARAM_INT);
1355                 if ($value !== 0 and $value !== 1) {
1356                     throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1357                 }
1359                 if (!isset($backupdefaults[$option['name']])) {
1360                     throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1361                 }
1363                 $backupsettings[$option['name']] = $value;
1364             }
1365         }
1367         // Capability checking.
1369         require_capability('moodle/backup:backuptargetimport', $importfromcontext);
1370         require_capability('moodle/restore:restoretargetimport', $importtocontext);
1372         $bc = new backup_controller(backup::TYPE_1COURSE, $importfrom->id, backup::FORMAT_MOODLE,
1373                 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
1375         foreach ($backupsettings as $name => $value) {
1376             $bc->get_plan()->get_setting($name)->set_value($value);
1377         }
1379         $backupid       = $bc->get_backupid();
1380         $backupbasepath = $bc->get_plan()->get_basepath();
1382         $bc->execute_plan();
1383         $bc->destroy();
1385         // Restore the backup immediately.
1387         // Check if we must delete the contents of the destination course.
1388         if ($params['deletecontent']) {
1389             $restoretarget = backup::TARGET_EXISTING_DELETING;
1390         } else {
1391             $restoretarget = backup::TARGET_EXISTING_ADDING;
1392         }
1394         $rc = new restore_controller($backupid, $importto->id,
1395                 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, $restoretarget);
1397         foreach ($backupsettings as $name => $value) {
1398             $rc->get_plan()->get_setting($name)->set_value($value);
1399         }
1401         if (!$rc->execute_precheck()) {
1402             $precheckresults = $rc->get_precheck_results();
1403             if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1404                 if (empty($CFG->keeptempdirectoriesonbackup)) {
1405                     fulldelete($backupbasepath);
1406                 }
1408                 $errorinfo = '';
1410                 foreach ($precheckresults['errors'] as $error) {
1411                     $errorinfo .= $error;
1412                 }
1414                 if (array_key_exists('warnings', $precheckresults)) {
1415                     foreach ($precheckresults['warnings'] as $warning) {
1416                         $errorinfo .= $warning;
1417                     }
1418                 }
1420                 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1421             }
1422         } else {
1423             if ($restoretarget == backup::TARGET_EXISTING_DELETING) {
1424                 restore_dbops::delete_course_content($importto->id);
1425             }
1426         }
1428         $rc->execute_plan();
1429         $rc->destroy();
1431         if (empty($CFG->keeptempdirectoriesonbackup)) {
1432             fulldelete($backupbasepath);
1433         }
1435         return null;
1436     }
1438     /**
1439      * Returns description of method result value
1440      *
1441      * @return external_description
1442      * @since Moodle 2.4
1443      */
1444     public static function import_course_returns() {
1445         return null;
1446     }
1448     /**
1449      * Returns description of method parameters
1450      *
1451      * @return external_function_parameters
1452      * @since Moodle 2.3
1453      */
1454     public static function get_categories_parameters() {
1455         return new external_function_parameters(
1456             array(
1457                 'criteria' => new external_multiple_structure(
1458                     new external_single_structure(
1459                         array(
1460                             'key' => new external_value(PARAM_ALPHA,
1461                                          'The category column to search, expected keys (value format) are:'.
1462                                          '"id" (int) the category id,'.
1463                                          '"ids" (string) category ids separated by commas,'.
1464                                          '"name" (string) the category name,'.
1465                                          '"parent" (int) the parent category id,'.
1466                                          '"idnumber" (string) category idnumber'.
1467                                          ' - user must have \'moodle/category:manage\' to search on idnumber,'.
1468                                          '"visible" (int) whether the returned categories must be visible or hidden. If the key is not passed,
1469                                              then the function return all categories that the user can see.'.
1470                                          ' - user must have \'moodle/category:manage\' or \'moodle/category:viewhiddencategories\' to search on visible,'.
1471                                          '"theme" (string) only return the categories having this theme'.
1472                                          ' - user must have \'moodle/category:manage\' to search on theme'),
1473                             'value' => new external_value(PARAM_RAW, 'the value to match')
1474                         )
1475                     ), 'criteria', VALUE_DEFAULT, array()
1476                 ),
1477                 'addsubcategories' => new external_value(PARAM_BOOL, 'return the sub categories infos
1478                                           (1 - default) otherwise only the category info (0)', VALUE_DEFAULT, 1)
1479             )
1480         );
1481     }
1483     /**
1484      * Get categories
1485      *
1486      * @param array $criteria Criteria to match the results
1487      * @param booln $addsubcategories obtain only the category (false) or its subcategories (true - default)
1488      * @return array list of categories
1489      * @since Moodle 2.3
1490      */
1491     public static function get_categories($criteria = array(), $addsubcategories = true) {
1492         global $CFG, $DB;
1493         require_once($CFG->dirroot . "/course/lib.php");
1495         // Validate parameters.
1496         $params = self::validate_parameters(self::get_categories_parameters(),
1497                 array('criteria' => $criteria, 'addsubcategories' => $addsubcategories));
1499         // Retrieve the categories.
1500         $categories = array();
1501         if (!empty($params['criteria'])) {
1503             $conditions = array();
1504             $wheres = array();
1505             foreach ($params['criteria'] as $crit) {
1506                 $key = trim($crit['key']);
1508                 // Trying to avoid duplicate keys.
1509                 if (!isset($conditions[$key])) {
1511                     $context = context_system::instance();
1512                     $value = null;
1513                     switch ($key) {
1514                         case 'id':
1515                             $value = clean_param($crit['value'], PARAM_INT);
1516                             $conditions[$key] = $value;
1517                             $wheres[] = $key . " = :" . $key;
1518                             break;
1520                         case 'ids':
1521                             $value = clean_param($crit['value'], PARAM_SEQUENCE);
1522                             $ids = explode(',', $value);
1523                             list($sqlids, $paramids) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED);
1524                             $conditions = array_merge($conditions, $paramids);
1525                             $wheres[] = 'id ' . $sqlids;
1526                             break;
1528                         case 'idnumber':
1529                             if (has_capability('moodle/category:manage', $context)) {
1530                                 $value = clean_param($crit['value'], PARAM_RAW);
1531                                 $conditions[$key] = $value;
1532                                 $wheres[] = $key . " = :" . $key;
1533                             } else {
1534                                 // We must throw an exception.
1535                                 // Otherwise the dev client would think no idnumber exists.
1536                                 throw new moodle_exception('criteriaerror',
1537                                         'webservice', '', null,
1538                                         'You don\'t have the permissions to search on the "idnumber" field.');
1539                             }
1540                             break;
1542                         case 'name':
1543                             $value = clean_param($crit['value'], PARAM_TEXT);
1544                             $conditions[$key] = $value;
1545                             $wheres[] = $key . " = :" . $key;
1546                             break;
1548                         case 'parent':
1549                             $value = clean_param($crit['value'], PARAM_INT);
1550                             $conditions[$key] = $value;
1551                             $wheres[] = $key . " = :" . $key;
1552                             break;
1554                         case 'visible':
1555                             if (has_capability('moodle/category:manage', $context)
1556                                 or has_capability('moodle/category:viewhiddencategories',
1557                                         context_system::instance())) {
1558                                 $value = clean_param($crit['value'], PARAM_INT);
1559                                 $conditions[$key] = $value;
1560                                 $wheres[] = $key . " = :" . $key;
1561                             } else {
1562                                 throw new moodle_exception('criteriaerror',
1563                                         'webservice', '', null,
1564                                         'You don\'t have the permissions to search on the "visible" field.');
1565                             }
1566                             break;
1568                         case 'theme':
1569                             if (has_capability('moodle/category:manage', $context)) {
1570                                 $value = clean_param($crit['value'], PARAM_THEME);
1571                                 $conditions[$key] = $value;
1572                                 $wheres[] = $key . " = :" . $key;
1573                             } else {
1574                                 throw new moodle_exception('criteriaerror',
1575                                         'webservice', '', null,
1576                                         'You don\'t have the permissions to search on the "theme" field.');
1577                             }
1578                             break;
1580                         default:
1581                             throw new moodle_exception('criteriaerror',
1582                                     'webservice', '', null,
1583                                     'You can not search on this criteria: ' . $key);
1584                     }
1585                 }
1586             }
1588             if (!empty($wheres)) {
1589                 $wheres = implode(" AND ", $wheres);
1591                 $categories = $DB->get_records_select('course_categories', $wheres, $conditions);
1593                 // Retrieve its sub subcategories (all levels).
1594                 if ($categories and !empty($params['addsubcategories'])) {
1595                     $newcategories = array();
1597                     // Check if we required visible/theme checks.
1598                     $additionalselect = '';
1599                     $additionalparams = array();
1600                     if (isset($conditions['visible'])) {
1601                         $additionalselect .= ' AND visible = :visible';
1602                         $additionalparams['visible'] = $conditions['visible'];
1603                     }
1604                     if (isset($conditions['theme'])) {
1605                         $additionalselect .= ' AND theme= :theme';
1606                         $additionalparams['theme'] = $conditions['theme'];
1607                     }
1609                     foreach ($categories as $category) {
1610                         $sqlselect = $DB->sql_like('path', ':path') . $additionalselect;
1611                         $sqlparams = array('path' => $category->path.'/%') + $additionalparams; // It will NOT include the specified category.
1612                         $subcategories = $DB->get_records_select('course_categories', $sqlselect, $sqlparams);
1613                         $newcategories = $newcategories + $subcategories;   // Both arrays have integer as keys.
1614                     }
1615                     $categories = $categories + $newcategories;
1616                 }
1617             }
1619         } else {
1620             // Retrieve all categories in the database.
1621             $categories = $DB->get_records('course_categories');
1622         }
1624         // The not returned categories. key => category id, value => reason of exclusion.
1625         $excludedcats = array();
1627         // The returned categories.
1628         $categoriesinfo = array();
1630         // We need to sort the categories by path.
1631         // The parent cats need to be checked by the algo first.
1632         usort($categories, "core_course_external::compare_categories_by_path");
1634         foreach ($categories as $category) {
1636             // Check if the category is a child of an excluded category, if yes exclude it too (excluded => do not return).
1637             $parents = explode('/', $category->path);
1638             unset($parents[0]); // First key is always empty because path start with / => /1/2/4.
1639             foreach ($parents as $parentid) {
1640                 // Note: when the parent exclusion was due to the context,
1641                 // the sub category could still be returned.
1642                 if (isset($excludedcats[$parentid]) and $excludedcats[$parentid] != 'context') {
1643                     $excludedcats[$category->id] = 'parent';
1644                 }
1645             }
1647             // Check the user can use the category context.
1648             $context = context_coursecat::instance($category->id);
1649             try {
1650                 self::validate_context($context);
1651             } catch (Exception $e) {
1652                 $excludedcats[$category->id] = 'context';
1654                 // If it was the requested category then throw an exception.
1655                 if (isset($params['categoryid']) && $category->id == $params['categoryid']) {
1656                     $exceptionparam = new stdClass();
1657                     $exceptionparam->message = $e->getMessage();
1658                     $exceptionparam->catid = $category->id;
1659                     throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
1660                 }
1661             }
1663             // Return the category information.
1664             if (!isset($excludedcats[$category->id])) {
1666                 // Final check to see if the category is visible to the user.
1667                 if ($category->visible
1668                         or has_capability('moodle/category:viewhiddencategories', context_system::instance())
1669                         or has_capability('moodle/category:manage', $context)) {
1671                     $categoryinfo = array();
1672                     $categoryinfo['id'] = $category->id;
1673                     $categoryinfo['name'] = $category->name;
1674                     list($categoryinfo['description'], $categoryinfo['descriptionformat']) =
1675                         external_format_text($category->description, $category->descriptionformat,
1676                                 $context->id, 'coursecat', 'description', null);
1677                     $categoryinfo['parent'] = $category->parent;
1678                     $categoryinfo['sortorder'] = $category->sortorder;
1679                     $categoryinfo['coursecount'] = $category->coursecount;
1680                     $categoryinfo['depth'] = $category->depth;
1681                     $categoryinfo['path'] = $category->path;
1683                     // Some fields only returned for admin.
1684                     if (has_capability('moodle/category:manage', $context)) {
1685                         $categoryinfo['idnumber'] = $category->idnumber;
1686                         $categoryinfo['visible'] = $category->visible;
1687                         $categoryinfo['visibleold'] = $category->visibleold;
1688                         $categoryinfo['timemodified'] = $category->timemodified;
1689                         $categoryinfo['theme'] = $category->theme;
1690                     }
1692                     $categoriesinfo[] = $categoryinfo;
1693                 } else {
1694                     $excludedcats[$category->id] = 'visibility';
1695                 }
1696             }
1697         }
1699         // Sorting the resulting array so it looks a bit better for the client developer.
1700         usort($categoriesinfo, "core_course_external::compare_categories_by_sortorder");
1702         return $categoriesinfo;
1703     }
1705     /**
1706      * Sort categories array by path
1707      * private function: only used by get_categories
1708      *
1709      * @param array $category1
1710      * @param array $category2
1711      * @return int result of strcmp
1712      * @since Moodle 2.3
1713      */
1714     private static function compare_categories_by_path($category1, $category2) {
1715         return strcmp($category1->path, $category2->path);
1716     }
1718     /**
1719      * Sort categories array by sortorder
1720      * private function: only used by get_categories
1721      *
1722      * @param array $category1
1723      * @param array $category2
1724      * @return int result of strcmp
1725      * @since Moodle 2.3
1726      */
1727     private static function compare_categories_by_sortorder($category1, $category2) {
1728         return strcmp($category1['sortorder'], $category2['sortorder']);
1729     }
1731     /**
1732      * Returns description of method result value
1733      *
1734      * @return external_description
1735      * @since Moodle 2.3
1736      */
1737     public static function get_categories_returns() {
1738         return new external_multiple_structure(
1739             new external_single_structure(
1740                 array(
1741                     'id' => new external_value(PARAM_INT, 'category id'),
1742                     'name' => new external_value(PARAM_TEXT, 'category name'),
1743                     'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1744                     'description' => new external_value(PARAM_RAW, 'category description'),
1745                     'descriptionformat' => new external_format_value('description'),
1746                     'parent' => new external_value(PARAM_INT, 'parent category id'),
1747                     'sortorder' => new external_value(PARAM_INT, 'category sorting order'),
1748                     'coursecount' => new external_value(PARAM_INT, 'number of courses in this category'),
1749                     'visible' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1750                     'visibleold' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1751                     'timemodified' => new external_value(PARAM_INT, 'timestamp', VALUE_OPTIONAL),
1752                     'depth' => new external_value(PARAM_INT, 'category depth'),
1753                     'path' => new external_value(PARAM_TEXT, 'category path'),
1754                     'theme' => new external_value(PARAM_THEME, 'category theme', VALUE_OPTIONAL),
1755                 ), 'List of categories'
1756             )
1757         );
1758     }
1760     /**
1761      * Returns description of method parameters
1762      *
1763      * @return external_function_parameters
1764      * @since Moodle 2.3
1765      */
1766     public static function create_categories_parameters() {
1767         return new external_function_parameters(
1768             array(
1769                 'categories' => new external_multiple_structure(
1770                         new external_single_structure(
1771                             array(
1772                                 'name' => new external_value(PARAM_TEXT, 'new category name'),
1773                                 'parent' => new external_value(PARAM_INT,
1774                                         'the parent category id inside which the new category will be created
1775                                          - set to 0 for a root category',
1776                                         VALUE_DEFAULT, 0),
1777                                 'idnumber' => new external_value(PARAM_RAW,
1778                                         'the new category idnumber', VALUE_OPTIONAL),
1779                                 'description' => new external_value(PARAM_RAW,
1780                                         'the new category description', VALUE_OPTIONAL),
1781                                 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
1782                                 'theme' => new external_value(PARAM_THEME,
1783                                         'the new category theme. This option must be enabled on moodle',
1784                                         VALUE_OPTIONAL),
1785                         )
1786                     )
1787                 )
1788             )
1789         );
1790     }
1792     /**
1793      * Create categories
1794      *
1795      * @param array $categories - see create_categories_parameters() for the array structure
1796      * @return array - see create_categories_returns() for the array structure
1797      * @since Moodle 2.3
1798      */
1799     public static function create_categories($categories) {
1800         global $CFG, $DB;
1801         require_once($CFG->libdir . "/coursecatlib.php");
1803         $params = self::validate_parameters(self::create_categories_parameters(),
1804                         array('categories' => $categories));
1806         $transaction = $DB->start_delegated_transaction();
1808         $createdcategories = array();
1809         foreach ($params['categories'] as $category) {
1810             if ($category['parent']) {
1811                 if (!$DB->record_exists('course_categories', array('id' => $category['parent']))) {
1812                     throw new moodle_exception('unknowcategory');
1813                 }
1814                 $context = context_coursecat::instance($category['parent']);
1815             } else {
1816                 $context = context_system::instance();
1817             }
1818             self::validate_context($context);
1819             require_capability('moodle/category:manage', $context);
1821             // this will validate format and throw an exception if there are errors
1822             external_validate_format($category['descriptionformat']);
1824             $newcategory = coursecat::create($category);
1826             $createdcategories[] = array('id' => $newcategory->id, 'name' => $newcategory->name);
1827         }
1829         $transaction->allow_commit();
1831         return $createdcategories;
1832     }
1834     /**
1835      * Returns description of method parameters
1836      *
1837      * @return external_function_parameters
1838      * @since Moodle 2.3
1839      */
1840     public static function create_categories_returns() {
1841         return new external_multiple_structure(
1842             new external_single_structure(
1843                 array(
1844                     'id' => new external_value(PARAM_INT, 'new category id'),
1845                     'name' => new external_value(PARAM_TEXT, 'new category name'),
1846                 )
1847             )
1848         );
1849     }
1851     /**
1852      * Returns description of method parameters
1853      *
1854      * @return external_function_parameters
1855      * @since Moodle 2.3
1856      */
1857     public static function update_categories_parameters() {
1858         return new external_function_parameters(
1859             array(
1860                 'categories' => new external_multiple_structure(
1861                     new external_single_structure(
1862                         array(
1863                             'id'       => new external_value(PARAM_INT, 'course id'),
1864                             'name' => new external_value(PARAM_TEXT, 'category name', VALUE_OPTIONAL),
1865                             'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1866                             'parent' => new external_value(PARAM_INT, 'parent category id', VALUE_OPTIONAL),
1867                             'description' => new external_value(PARAM_RAW, 'category description', VALUE_OPTIONAL),
1868                             'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
1869                             'theme' => new external_value(PARAM_THEME,
1870                                     'the category theme. This option must be enabled on moodle', VALUE_OPTIONAL),
1871                         )
1872                     )
1873                 )
1874             )
1875         );
1876     }
1878     /**
1879      * Update categories
1880      *
1881      * @param array $categories The list of categories to update
1882      * @return null
1883      * @since Moodle 2.3
1884      */
1885     public static function update_categories($categories) {
1886         global $CFG, $DB;
1887         require_once($CFG->libdir . "/coursecatlib.php");
1889         // Validate parameters.
1890         $params = self::validate_parameters(self::update_categories_parameters(), array('categories' => $categories));
1892         $transaction = $DB->start_delegated_transaction();
1894         foreach ($params['categories'] as $cat) {
1895             $category = coursecat::get($cat['id']);
1897             $categorycontext = context_coursecat::instance($cat['id']);
1898             self::validate_context($categorycontext);
1899             require_capability('moodle/category:manage', $categorycontext);
1901             // this will throw an exception if descriptionformat is not valid
1902             external_validate_format($cat['descriptionformat']);
1904             $category->update($cat);
1905         }
1907         $transaction->allow_commit();
1908     }
1910     /**
1911      * Returns description of method result value
1912      *
1913      * @return external_description
1914      * @since Moodle 2.3
1915      */
1916     public static function update_categories_returns() {
1917         return null;
1918     }
1920     /**
1921      * Returns description of method parameters
1922      *
1923      * @return external_function_parameters
1924      * @since Moodle 2.3
1925      */
1926     public static function delete_categories_parameters() {
1927         return new external_function_parameters(
1928             array(
1929                 'categories' => new external_multiple_structure(
1930                     new external_single_structure(
1931                         array(
1932                             'id' => new external_value(PARAM_INT, 'category id to delete'),
1933                             'newparent' => new external_value(PARAM_INT,
1934                                 'the parent category to move the contents to, if specified', VALUE_OPTIONAL),
1935                             'recursive' => new external_value(PARAM_BOOL, '1: recursively delete all contents inside this
1936                                 category, 0 (default): move contents to newparent or current parent category (except if parent is root)', VALUE_DEFAULT, 0)
1937                         )
1938                     )
1939                 )
1940             )
1941         );
1942     }
1944     /**
1945      * Delete categories
1946      *
1947      * @param array $categories A list of category ids
1948      * @return array
1949      * @since Moodle 2.3
1950      */
1951     public static function delete_categories($categories) {
1952         global $CFG, $DB;
1953         require_once($CFG->dirroot . "/course/lib.php");
1954         require_once($CFG->libdir . "/coursecatlib.php");
1956         // Validate parameters.
1957         $params = self::validate_parameters(self::delete_categories_parameters(), array('categories' => $categories));
1959         $transaction = $DB->start_delegated_transaction();
1961         foreach ($params['categories'] as $category) {
1962             $deletecat = coursecat::get($category['id'], MUST_EXIST);
1963             $context = context_coursecat::instance($deletecat->id);
1964             require_capability('moodle/category:manage', $context);
1965             self::validate_context($context);
1966             self::validate_context(get_category_or_system_context($deletecat->parent));
1968             if ($category['recursive']) {
1969                 // If recursive was specified, then we recursively delete the category's contents.
1970                 if ($deletecat->can_delete_full()) {
1971                     $deletecat->delete_full(false);
1972                 } else {
1973                     throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
1974                 }
1975             } else {
1976                 // In this situation, we don't delete the category's contents, we either move it to newparent or parent.
1977                 // If the parent is the root, moving is not supported (because a course must always be inside a category).
1978                 // We must move to an existing category.
1979                 if (!empty($category['newparent'])) {
1980                     $newparentcat = coursecat::get($category['newparent']);
1981                 } else {
1982                     $newparentcat = coursecat::get($deletecat->parent);
1983                 }
1985                 // This operation is not allowed. We must move contents to an existing category.
1986                 if (!$newparentcat->id) {
1987                     throw new moodle_exception('movecatcontentstoroot');
1988                 }
1990                 self::validate_context(context_coursecat::instance($newparentcat->id));
1991                 if ($deletecat->can_move_content_to($newparentcat->id)) {
1992                     $deletecat->delete_move($newparentcat->id, false);
1993                 } else {
1994                     throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
1995                 }
1996             }
1997         }
1999         $transaction->allow_commit();
2000     }
2002     /**
2003      * Returns description of method parameters
2004      *
2005      * @return external_function_parameters
2006      * @since Moodle 2.3
2007      */
2008     public static function delete_categories_returns() {
2009         return null;
2010     }
2012     /**
2013      * Describes the parameters for delete_modules.
2014      *
2015      * @return external_function_parameters
2016      * @since Moodle 2.5
2017      */
2018     public static function delete_modules_parameters() {
2019         return new external_function_parameters (
2020             array(
2021                 'cmids' => new external_multiple_structure(new external_value(PARAM_INT, 'course module ID',
2022                         VALUE_REQUIRED, '', NULL_NOT_ALLOWED), 'Array of course module IDs'),
2023             )
2024         );
2025     }
2027     /**
2028      * Deletes a list of provided module instances.
2029      *
2030      * @param array $cmids the course module ids
2031      * @since Moodle 2.5
2032      */
2033     public static function delete_modules($cmids) {
2034         global $CFG, $DB;
2036         // Require course file containing the course delete module function.
2037         require_once($CFG->dirroot . "/course/lib.php");
2039         // Clean the parameters.
2040         $params = self::validate_parameters(self::delete_modules_parameters(), array('cmids' => $cmids));
2042         // Keep track of the course ids we have performed a capability check on to avoid repeating.
2043         $arrcourseschecked = array();
2045         foreach ($params['cmids'] as $cmid) {
2046             // Get the course module.
2047             $cm = $DB->get_record('course_modules', array('id' => $cmid), '*', MUST_EXIST);
2049             // Check if we have not yet confirmed they have permission in this course.
2050             if (!in_array($cm->course, $arrcourseschecked)) {
2051                 // Ensure the current user has required permission in this course.
2052                 $context = context_course::instance($cm->course);
2053                 self::validate_context($context);
2054                 // Add to the array.
2055                 $arrcourseschecked[] = $cm->course;
2056             }
2058             // Ensure they can delete this module.
2059             $modcontext = context_module::instance($cm->id);
2060             require_capability('moodle/course:manageactivities', $modcontext);
2062             // Delete the module.
2063             course_delete_module($cm->id);
2064         }
2065     }
2067     /**
2068      * Describes the delete_modules return value.
2069      *
2070      * @return external_single_structure
2071      * @since Moodle 2.5
2072      */
2073     public static function delete_modules_returns() {
2074         return null;
2075     }
2077     /**
2078      * Returns description of method parameters
2079      *
2080      * @return external_function_parameters
2081      * @since Moodle 2.9
2082      */
2083     public static function view_course_parameters() {
2084         return new external_function_parameters(
2085             array(
2086                 'courseid' => new external_value(PARAM_INT, 'id of the course'),
2087                 'sectionnumber' => new external_value(PARAM_INT, 'section number', VALUE_DEFAULT, 0)
2088             )
2089         );
2090     }
2092     /**
2093      * Trigger the course viewed event.
2094      *
2095      * @param int $courseid id of course
2096      * @param int $sectionnumber sectionnumber (0, 1, 2...)
2097      * @return array of warnings and status result
2098      * @since Moodle 2.9
2099      * @throws moodle_exception
2100      */
2101     public static function view_course($courseid, $sectionnumber = 0) {
2102         global $CFG;
2103         require_once($CFG->dirroot . "/course/lib.php");
2105         $params = self::validate_parameters(self::view_course_parameters(),
2106                                             array(
2107                                                 'courseid' => $courseid,
2108                                                 'sectionnumber' => $sectionnumber
2109                                             ));
2111         $warnings = array();
2113         $course = get_course($params['courseid']);
2114         $context = context_course::instance($course->id);
2115         self::validate_context($context);
2117         if (!empty($params['sectionnumber'])) {
2119             // Get section details and check it exists.
2120             $modinfo = get_fast_modinfo($course);
2121             $coursesection = $modinfo->get_section_info($params['sectionnumber'], MUST_EXIST);
2123             // Check user is allowed to see it.
2124             if (!$coursesection->uservisible) {
2125                 require_capability('moodle/course:viewhiddensections', $context);
2126             }
2127         }
2129         course_view($context, $params['sectionnumber']);
2131         $result = array();
2132         $result['status'] = true;
2133         $result['warnings'] = $warnings;
2134         return $result;
2135     }
2137     /**
2138      * Returns description of method result value
2139      *
2140      * @return external_description
2141      * @since Moodle 2.9
2142      */
2143     public static function view_course_returns() {
2144         return new external_single_structure(
2145             array(
2146                 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
2147                 'warnings' => new external_warnings()
2148             )
2149         );
2150     }
2152     /**
2153      * Returns description of method parameters
2154      *
2155      * @return external_function_parameters
2156      * @since Moodle 3.0
2157      */
2158     public static function search_courses_parameters() {
2159         return new external_function_parameters(
2160             array(
2161                 'criterianame'  => new external_value(PARAM_ALPHA, 'criteria name
2162                                                         (search, modulelist (only admins), blocklist (only admins), tagid)'),
2163                 'criteriavalue' => new external_value(PARAM_RAW, 'criteria value'),
2164                 'page'          => new external_value(PARAM_INT, 'page number (0 based)', VALUE_DEFAULT, 0),
2165                 'perpage'       => new external_value(PARAM_INT, 'items per page', VALUE_DEFAULT, 0),
2166                 'requiredcapabilities' => new external_multiple_structure(
2167                     new external_value(PARAM_CAPABILITY, 'Capability string used to filter courses by permission'),
2168                     'Optional list of required capabilities (used to filter the list)', VALUE_DEFAULT, array()
2169                 ),
2170                 'limittoenrolled' => new external_value(PARAM_BOOL, 'limit to enrolled courses', VALUE_DEFAULT, 0),
2171             )
2172         );
2173     }
2175     /**
2176      * Return the course information that is public (visible by every one)
2177      *
2178      * @param  course_in_list $course        course in list object
2179      * @param  stdClass       $coursecontext course context object
2180      * @return array the course information
2181      * @since  Moodle 3.2
2182      */
2183     protected static function get_course_public_information(course_in_list $course, $coursecontext) {
2185         static $categoriescache = array();
2187         // Category information.
2188         if (!array_key_exists($course->category, $categoriescache)) {
2189             $categoriescache[$course->category] = coursecat::get($course->category, IGNORE_MISSING);
2190         }
2191         $category = $categoriescache[$course->category];
2193         // Retrieve course overview used files.
2194         $files = array();
2195         foreach ($course->get_course_overviewfiles() as $file) {
2196             $fileurl = moodle_url::make_webservice_pluginfile_url($file->get_contextid(), $file->get_component(),
2197                                                                     $file->get_filearea(), null, $file->get_filepath(),
2198                                                                     $file->get_filename())->out(false);
2199             $files[] = array(
2200                 'filename' => $file->get_filename(),
2201                 'fileurl' => $fileurl,
2202                 'filesize' => $file->get_filesize(),
2203                 'filepath' => $file->get_filepath(),
2204                 'mimetype' => $file->get_mimetype(),
2205                 'timemodified' => $file->get_timemodified(),
2206             );
2207         }
2209         // Retrieve the course contacts,
2210         // we need here the users fullname since if we are not enrolled can be difficult to obtain them via other Web Services.
2211         $coursecontacts = array();
2212         foreach ($course->get_course_contacts() as $contact) {
2213              $coursecontacts[] = array(
2214                 'id' => $contact['user']->id,
2215                 'fullname' => $contact['username']
2216             );
2217         }
2219         // Allowed enrolment methods (maybe we can self-enrol).
2220         $enroltypes = array();
2221         $instances = enrol_get_instances($course->id, true);
2222         foreach ($instances as $instance) {
2223             $enroltypes[] = $instance->enrol;
2224         }
2226         // Format summary.
2227         list($summary, $summaryformat) =
2228             external_format_text($course->summary, $course->summaryformat, $coursecontext->id, 'course', 'summary', null);
2230         $displayname = get_course_display_name_for_list($course);
2231         $coursereturns = array();
2232         $coursereturns['id']                = $course->id;
2233         $coursereturns['fullname']          = external_format_string($course->fullname, $coursecontext->id);
2234         $coursereturns['displayname']       = external_format_string($displayname, $coursecontext->id);
2235         $coursereturns['shortname']         = external_format_string($course->shortname, $coursecontext->id);
2236         $coursereturns['categoryid']        = $course->category;
2237         $coursereturns['categoryname']      = $category == null ? '' : $category->name;
2238         $coursereturns['summary']           = $summary;
2239         $coursereturns['summaryformat']     = $summaryformat;
2240         $coursereturns['summaryfiles']      = external_util::get_area_files($coursecontext->id, 'course', 'summary', false, false);
2241         $coursereturns['overviewfiles']     = $files;
2242         $coursereturns['contacts']          = $coursecontacts;
2243         $coursereturns['enrollmentmethods'] = $enroltypes;
2244         return $coursereturns;
2245     }
2247     /**
2248      * Search courses following the specified criteria.
2249      *
2250      * @param string $criterianame  Criteria name (search, modulelist (only admins), blocklist (only admins), tagid)
2251      * @param string $criteriavalue Criteria value
2252      * @param int $page             Page number (for pagination)
2253      * @param int $perpage          Items per page
2254      * @param array $requiredcapabilities Optional list of required capabilities (used to filter the list).
2255      * @param int $limittoenrolled  Limit to only enrolled courses
2256      * @return array of course objects and warnings
2257      * @since Moodle 3.0
2258      * @throws moodle_exception
2259      */
2260     public static function search_courses($criterianame,
2261                                           $criteriavalue,
2262                                           $page=0,
2263                                           $perpage=0,
2264                                           $requiredcapabilities=array(),
2265                                           $limittoenrolled=0) {
2266         global $CFG;
2267         require_once($CFG->libdir . '/coursecatlib.php');
2269         $warnings = array();
2271         $parameters = array(
2272             'criterianame'  => $criterianame,
2273             'criteriavalue' => $criteriavalue,
2274             'page'          => $page,
2275             'perpage'       => $perpage,
2276             'requiredcapabilities' => $requiredcapabilities
2277         );
2278         $params = self::validate_parameters(self::search_courses_parameters(), $parameters);
2279         self::validate_context(context_system::instance());
2281         $allowedcriterianames = array('search', 'modulelist', 'blocklist', 'tagid');
2282         if (!in_array($params['criterianame'], $allowedcriterianames)) {
2283             throw new invalid_parameter_exception('Invalid value for criterianame parameter (value: '.$params['criterianame'].'),' .
2284                 'allowed values are: '.implode(',', $allowedcriterianames));
2285         }
2287         if ($params['criterianame'] == 'modulelist' or $params['criterianame'] == 'blocklist') {
2288             require_capability('moodle/site:config', context_system::instance());
2289         }
2291         $paramtype = array(
2292             'search' => PARAM_RAW,
2293             'modulelist' => PARAM_PLUGIN,
2294             'blocklist' => PARAM_INT,
2295             'tagid' => PARAM_INT
2296         );
2297         $params['criteriavalue'] = clean_param($params['criteriavalue'], $paramtype[$params['criterianame']]);
2299         // Prepare the search API options.
2300         $searchcriteria = array();
2301         $searchcriteria[$params['criterianame']] = $params['criteriavalue'];
2303         $options = array();
2304         if ($params['perpage'] != 0) {
2305             $offset = $params['page'] * $params['perpage'];
2306             $options = array('offset' => $offset, 'limit' => $params['perpage']);
2307         }
2309         // Search the courses.
2310         $courses = coursecat::search_courses($searchcriteria, $options, $params['requiredcapabilities']);
2311         $totalcount = coursecat::search_courses_count($searchcriteria, $options, $params['requiredcapabilities']);
2313         if (!empty($limittoenrolled)) {
2314             // Get the courses where the current user has access.
2315             $enrolled = enrol_get_my_courses(array('id', 'cacherev'));
2316         }
2318         $finalcourses = array();
2319         $categoriescache = array();
2321         foreach ($courses as $course) {
2322             if (!empty($limittoenrolled)) {
2323                 // Filter out not enrolled courses.
2324                 if (!isset($enrolled[$course->id])) {
2325                     $totalcount--;
2326                     continue;
2327                 }
2328             }
2330             $coursecontext = context_course::instance($course->id);
2332             $finalcourses[] = self::get_course_public_information($course, $coursecontext);
2333         }
2335         return array(
2336             'total' => $totalcount,
2337             'courses' => $finalcourses,
2338             'warnings' => $warnings
2339         );
2340     }
2342     /**
2343      * Returns a course structure definition
2344      *
2345      * @param  boolean $onlypublicdata set to true, to retrieve only fields viewable by anyone when the course is visible
2346      * @return array the course structure
2347      * @since  Moodle 3.2
2348      */
2349     protected static function get_course_structure($onlypublicdata = true) {
2350         $coursestructure = array(
2351             'id' => new external_value(PARAM_INT, 'course id'),
2352             'fullname' => new external_value(PARAM_TEXT, 'course full name'),
2353             'displayname' => new external_value(PARAM_TEXT, 'course display name'),
2354             'shortname' => new external_value(PARAM_TEXT, 'course short name'),
2355             'categoryid' => new external_value(PARAM_INT, 'category id'),
2356             'categoryname' => new external_value(PARAM_TEXT, 'category name'),
2357             'summary' => new external_value(PARAM_RAW, 'summary'),
2358             'summaryformat' => new external_format_value('summary'),
2359             'summaryfiles' => new external_files('summary files in the summary field', VALUE_OPTIONAL),
2360             'overviewfiles' => new external_files('additional overview files attached to this course'),
2361             'contacts' => new external_multiple_structure(
2362                 new external_single_structure(
2363                     array(
2364                         'id' => new external_value(PARAM_INT, 'contact user id'),
2365                         'fullname'  => new external_value(PARAM_NOTAGS, 'contact user fullname'),
2366                     )
2367                 ),
2368                 'contact users'
2369             ),
2370             'enrollmentmethods' => new external_multiple_structure(
2371                 new external_value(PARAM_PLUGIN, 'enrollment method'),
2372                 'enrollment methods list'
2373             ),
2374         );
2376         if (!$onlypublicdata) {
2377             $extra = array(
2378                 'idnumber' => new external_value(PARAM_RAW, 'Id number', VALUE_OPTIONAL),
2379                 'format' => new external_value(PARAM_PLUGIN, 'Course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
2380                 'showgrades' => new external_value(PARAM_INT, '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
2381                 'newsitems' => new external_value(PARAM_INT, 'Number of recent items appearing on the course page', VALUE_OPTIONAL),
2382                 'startdate' => new external_value(PARAM_INT, 'Timestamp when the course start', VALUE_OPTIONAL),
2383                 'maxbytes' => new external_value(PARAM_INT, 'Largest size of file that can be uploaded into', VALUE_OPTIONAL),
2384                 'showreports' => new external_value(PARAM_INT, 'Are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
2385                 'visible' => new external_value(PARAM_INT, '1: available to student, 0:not available', VALUE_OPTIONAL),
2386                 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
2387                 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
2388                 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
2389                 'enablecompletion' => new external_value(PARAM_INT, 'Completion enabled? 1: yes 0: no', VALUE_OPTIONAL),
2390                 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
2391                 'lang' => new external_value(PARAM_SAFEDIR, 'Forced course language', VALUE_OPTIONAL),
2392                 'theme' => new external_value(PARAM_PLUGIN, 'Fame of the forced theme', VALUE_OPTIONAL),
2393                 'sortorder' => new external_value(PARAM_INT, 'Sort order in the category', VALUE_OPTIONAL),
2394                 'marker' => new external_value(PARAM_INT, 'Current course marker', VALUE_OPTIONAL),
2395                 'legacyfiles' => new external_value(PARAM_INT, 'If legacy files are enabled', VALUE_OPTIONAL),
2396                 'calendartype' => new external_value(PARAM_PLUGIN, 'Calendar type', VALUE_OPTIONAL),
2397                 'timecreated' => new external_value(PARAM_INT, 'Time when the course was created', VALUE_OPTIONAL),
2398                 'timemodified' => new external_value(PARAM_INT, 'Last time  the course was updated', VALUE_OPTIONAL),
2399                 'requested' => new external_value(PARAM_INT, 'If is a requested course', VALUE_OPTIONAL),
2400                 'cacherev' => new external_value(PARAM_INT, 'Cache revision number', VALUE_OPTIONAL),
2401                 'filters' => new external_multiple_structure(
2402                     new external_single_structure(
2403                         array(
2404                             'filter'  => new external_value(PARAM_PLUGIN, 'Filter plugin name'),
2405                             'localstate' => new external_value(PARAM_INT, 'Filter state: 1 for on, -1 for off, 0 if inherit'),
2406                             'inheritedstate' => new external_value(PARAM_INT, '1 or 0 to use when localstate is set to inherit'),
2407                         )
2408                     ),
2409                     'Course filters', VALUE_OPTIONAL
2410                 ),
2411             );
2412             $coursestructure = array_merge($coursestructure, $extra);
2413         }
2414         return new external_single_structure($coursestructure);
2415     }
2417     /**
2418      * Returns description of method result value
2419      *
2420      * @return external_description
2421      * @since Moodle 3.0
2422      */
2423     public static function search_courses_returns() {
2424         return new external_single_structure(
2425             array(
2426                 'total' => new external_value(PARAM_INT, 'total course count'),
2427                 'courses' => new external_multiple_structure(self::get_course_structure(), 'course'),
2428                 'warnings' => new external_warnings()
2429             )
2430         );
2431     }
2433     /**
2434      * Returns description of method parameters
2435      *
2436      * @return external_function_parameters
2437      * @since Moodle 3.0
2438      */
2439     public static function get_course_module_parameters() {
2440         return new external_function_parameters(
2441             array(
2442                 'cmid' => new external_value(PARAM_INT, 'The course module id')
2443             )
2444         );
2445     }
2447     /**
2448      * Return information about a course module.
2449      *
2450      * @param int $cmid the course module id
2451      * @return array of warnings and the course module
2452      * @since Moodle 3.0
2453      * @throws moodle_exception
2454      */
2455     public static function get_course_module($cmid) {
2456         global $CFG, $DB;
2458         $params = self::validate_parameters(self::get_course_module_parameters(), array('cmid' => $cmid));
2459         $warnings = array();
2461         $cm = get_coursemodule_from_id(null, $params['cmid'], 0, true, MUST_EXIST);
2462         $context = context_module::instance($cm->id);
2463         self::validate_context($context);
2465         // If the user has permissions to manage the activity, return all the information.
2466         if (has_capability('moodle/course:manageactivities', $context)) {
2467             require_once($CFG->dirroot . '/course/modlib.php');
2468             require_once($CFG->libdir . '/gradelib.php');
2470             $info = $cm;
2471             // Get the extra information: grade, advanced grading and outcomes data.
2472             $course = get_course($cm->course);
2473             list($newcm, $newcontext, $module, $extrainfo, $cw) = get_moduleinfo_data($cm, $course);
2474             // Grades.
2475             $gradeinfo = array('grade', 'gradepass', 'gradecat');
2476             foreach ($gradeinfo as $gfield) {
2477                 if (isset($extrainfo->{$gfield})) {
2478                     $info->{$gfield} = $extrainfo->{$gfield};
2479                 }
2480             }
2481             if (isset($extrainfo->grade) and $extrainfo->grade < 0) {
2482                 $info->scale = $DB->get_field('scale', 'scale', array('id' => abs($extrainfo->grade)));
2483             }
2484             // Advanced grading.
2485             if (isset($extrainfo->_advancedgradingdata)) {
2486                 $info->advancedgrading = array();
2487                 foreach ($extrainfo as $key => $val) {
2488                     if (strpos($key, 'advancedgradingmethod_') === 0) {
2489                         $info->advancedgrading[] = array(
2490                             'area' => str_replace('advancedgradingmethod_', '', $key),
2491                             'method' => $val
2492                         );
2493                     }
2494                 }
2495             }
2496             // Outcomes.
2497             foreach ($extrainfo as $key => $val) {
2498                 if (strpos($key, 'outcome_') === 0) {
2499                     if (!isset($info->outcomes)) {
2500                         $info->outcomes = array();
2501                     }
2502                     $id = str_replace('outcome_', '', $key);
2503                     $outcome = grade_outcome::fetch(array('id' => $id));
2504                     $scaleitems = $outcome->load_scale();
2505                     $info->outcomes[] = array(
2506                         'id' => $id,
2507                         'name' => external_format_string($outcome->get_name(), $context->id),
2508                         'scale' => $scaleitems->scale
2509                     );
2510                 }
2511             }
2512         } else {
2513             // Return information is safe to show to any user.
2514             $info = new stdClass();
2515             $info->id = $cm->id;
2516             $info->course = $cm->course;
2517             $info->module = $cm->module;
2518             $info->modname = $cm->modname;
2519             $info->instance = $cm->instance;
2520             $info->section = $cm->section;
2521             $info->sectionnum = $cm->sectionnum;
2522             $info->groupmode = $cm->groupmode;
2523             $info->groupingid = $cm->groupingid;
2524             $info->completion = $cm->completion;
2525         }
2526         // Format name.
2527         $info->name = external_format_string($cm->name, $context->id);
2528         $result = array();
2529         $result['cm'] = $info;
2530         $result['warnings'] = $warnings;
2531         return $result;
2532     }
2534     /**
2535      * Returns description of method result value
2536      *
2537      * @return external_description
2538      * @since Moodle 3.0
2539      */
2540     public static function get_course_module_returns() {
2541         return new external_single_structure(
2542             array(
2543                 'cm' => new external_single_structure(
2544                     array(
2545                         'id' => new external_value(PARAM_INT, 'The course module id'),
2546                         'course' => new external_value(PARAM_INT, 'The course id'),
2547                         'module' => new external_value(PARAM_INT, 'The module type id'),
2548                         'name' => new external_value(PARAM_RAW, 'The activity name'),
2549                         'modname' => new external_value(PARAM_COMPONENT, 'The module component name (forum, assign, etc..)'),
2550                         'instance' => new external_value(PARAM_INT, 'The activity instance id'),
2551                         'section' => new external_value(PARAM_INT, 'The module section id'),
2552                         'sectionnum' => new external_value(PARAM_INT, 'The module section number'),
2553                         'groupmode' => new external_value(PARAM_INT, 'Group mode'),
2554                         'groupingid' => new external_value(PARAM_INT, 'Grouping id'),
2555                         'completion' => new external_value(PARAM_INT, 'If completion is enabled'),
2556                         'idnumber' => new external_value(PARAM_RAW, 'Module id number', VALUE_OPTIONAL),
2557                         'added' => new external_value(PARAM_INT, 'Time added', VALUE_OPTIONAL),
2558                         'score' => new external_value(PARAM_INT, 'Score', VALUE_OPTIONAL),
2559                         'indent' => new external_value(PARAM_INT, 'Indentation', VALUE_OPTIONAL),
2560                         'visible' => new external_value(PARAM_INT, 'If visible', VALUE_OPTIONAL),
2561                         'visibleold' => new external_value(PARAM_INT, 'Visible old', VALUE_OPTIONAL),
2562                         'completiongradeitemnumber' => new external_value(PARAM_INT, 'Completion grade item', VALUE_OPTIONAL),
2563                         'completionview' => new external_value(PARAM_INT, 'Completion view setting', VALUE_OPTIONAL),
2564                         'completionexpected' => new external_value(PARAM_INT, 'Completion time expected', VALUE_OPTIONAL),
2565                         'showdescription' => new external_value(PARAM_INT, 'If the description is showed', VALUE_OPTIONAL),
2566                         'availability' => new external_value(PARAM_RAW, 'Availability settings', VALUE_OPTIONAL),
2567                         'grade' => new external_value(PARAM_INT, 'Grade (max value or scale id)', VALUE_OPTIONAL),
2568                         'scale' => new external_value(PARAM_TEXT, 'Scale items (if used)', VALUE_OPTIONAL),
2569                         'gradepass' => new external_value(PARAM_RAW, 'Grade to pass (float)', VALUE_OPTIONAL),
2570                         'gradecat' => new external_value(PARAM_INT, 'Grade category', VALUE_OPTIONAL),
2571                         'advancedgrading' => new external_multiple_structure(
2572                             new external_single_structure(
2573                                 array(
2574                                     'area' => new external_value(PARAM_AREA, 'Gradable area name'),
2575                                     'method'  => new external_value(PARAM_COMPONENT, 'Grading method'),
2576                                 )
2577                             ),
2578                             'Advanced grading settings', VALUE_OPTIONAL
2579                         ),
2580                         'outcomes' => new external_multiple_structure(
2581                             new external_single_structure(
2582                                 array(
2583                                     'id' => new external_value(PARAM_ALPHANUMEXT, 'Outcome id'),
2584                                     'name'  => new external_value(PARAM_TEXT, 'Outcome full name'),
2585                                     'scale' => new external_value(PARAM_TEXT, 'Scale items')
2586                                 )
2587                             ),
2588                             'Outcomes information', VALUE_OPTIONAL
2589                         ),
2590                     )
2591                 ),
2592                 'warnings' => new external_warnings()
2593             )
2594         );
2595     }
2597     /**
2598      * Returns description of method parameters
2599      *
2600      * @return external_function_parameters
2601      * @since Moodle 3.0
2602      */
2603     public static function get_course_module_by_instance_parameters() {
2604         return new external_function_parameters(
2605             array(
2606                 'module' => new external_value(PARAM_COMPONENT, 'The module name'),
2607                 'instance' => new external_value(PARAM_INT, 'The module instance id')
2608             )
2609         );
2610     }
2612     /**
2613      * Return information about a course module.
2614      *
2615      * @param string $module the module name
2616      * @param int $instance the activity instance id
2617      * @return array of warnings and the course module
2618      * @since Moodle 3.0
2619      * @throws moodle_exception
2620      */
2621     public static function get_course_module_by_instance($module, $instance) {
2623         $params = self::validate_parameters(self::get_course_module_by_instance_parameters(),
2624                                             array(
2625                                                 'module' => $module,
2626                                                 'instance' => $instance,
2627                                             ));
2629         $warnings = array();
2630         $cm = get_coursemodule_from_instance($params['module'], $params['instance'], 0, false, MUST_EXIST);
2632         return self::get_course_module($cm->id);
2633     }
2635     /**
2636      * Returns description of method result value
2637      *
2638      * @return external_description
2639      * @since Moodle 3.0
2640      */
2641     public static function get_course_module_by_instance_returns() {
2642         return self::get_course_module_returns();
2643     }
2645     /**
2646      * Returns description of method parameters
2647      *
2648      * @return external_function_parameters
2649      * @since Moodle 3.2
2650      */
2651     public static function get_activities_overview_parameters() {
2652         return new external_function_parameters(
2653             array(
2654                 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2655             )
2656         );
2657     }
2659     /**
2660      * Return activities overview for the given courses.
2661      *
2662      * @param array $courseids a list of course ids
2663      * @return array of warnings and the activities overview
2664      * @since Moodle 3.2
2665      * @throws moodle_exception
2666      */
2667     public static function get_activities_overview($courseids) {
2668         global $USER;
2670         // Parameter validation.
2671         $params = self::validate_parameters(self::get_activities_overview_parameters(), array('courseids' => $courseids));
2672         $courseoverviews = array();
2674         list($courses, $warnings) = external_util::validate_courses($params['courseids']);
2676         if (!empty($courses)) {
2677             // Add lastaccess to each course (required by print_overview function).
2678             // We need the complete user data, the ws server does not load a complete one.
2679             $user = get_complete_user_data('id', $USER->id);
2680             foreach ($courses as $course) {
2681                 if (isset($user->lastcourseaccess[$course->id])) {
2682                     $course->lastaccess = $user->lastcourseaccess[$course->id];
2683                 } else {
2684                     $course->lastaccess = 0;
2685                 }
2686             }
2688             $overviews = array();
2689             if ($modules = get_plugin_list_with_function('mod', 'print_overview')) {
2690                 foreach ($modules as $fname) {
2691                     $fname($courses, $overviews);
2692                 }
2693             }
2695             // Format output.
2696             foreach ($overviews as $courseid => $modules) {
2697                 $courseoverviews[$courseid]['id'] = $courseid;
2698                 $courseoverviews[$courseid]['overviews'] = array();
2700                 foreach ($modules as $modname => $overviewtext) {
2701                     $courseoverviews[$courseid]['overviews'][] = array(
2702                         'module' => $modname,
2703                         'overviewtext' => $overviewtext // This text doesn't need formatting.
2704                     );
2705                 }
2706             }
2707         }
2709         $result = array(
2710             'courses' => $courseoverviews,
2711             'warnings' => $warnings
2712         );
2713         return $result;
2714     }
2716     /**
2717      * Returns description of method result value
2718      *
2719      * @return external_description
2720      * @since Moodle 3.2
2721      */
2722     public static function get_activities_overview_returns() {
2723         return new external_single_structure(
2724             array(
2725                 'courses' => new external_multiple_structure(
2726                     new external_single_structure(
2727                         array(
2728                             'id' => new external_value(PARAM_INT, 'Course id'),
2729                             'overviews' => new external_multiple_structure(
2730                                 new external_single_structure(
2731                                     array(
2732                                         'module' => new external_value(PARAM_PLUGIN, 'Module name'),
2733                                         'overviewtext' => new external_value(PARAM_RAW, 'Overview text'),
2734                                     )
2735                                 )
2736                             )
2737                         )
2738                     ), 'List of courses'
2739                 ),
2740                 'warnings' => new external_warnings()
2741             )
2742         );
2743     }
2745     /**
2746      * Returns description of method parameters
2747      *
2748      * @return external_function_parameters
2749      * @since Moodle 3.2
2750      */
2751     public static function get_user_navigation_options_parameters() {
2752         return new external_function_parameters(
2753             array(
2754                 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2755             )
2756         );
2757     }
2759     /**
2760      * Return a list of navigation options in a set of courses that are avaialable or not for the current user.
2761      *
2762      * @param array $courseids a list of course ids
2763      * @return array of warnings and the options availability
2764      * @since Moodle 3.2
2765      * @throws moodle_exception
2766      */
2767     public static function get_user_navigation_options($courseids) {
2768         global $CFG;
2769         require_once($CFG->dirroot . '/course/lib.php');
2771         // Parameter validation.
2772         $params = self::validate_parameters(self::get_user_navigation_options_parameters(), array('courseids' => $courseids));
2773         $courseoptions = array();
2775         list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
2777         if (!empty($courses)) {
2778             foreach ($courses as $course) {
2779                 // Fix the context for the frontpage.
2780                 if ($course->id == SITEID) {
2781                     $course->context = context_system::instance();
2782                 }
2783                 $navoptions = course_get_user_navigation_options($course->context, $course);
2784                 $options = array();
2785                 foreach ($navoptions as $name => $available) {
2786                     $options[] = array(
2787                         'name' => $name,
2788                         'available' => $available,
2789                     );
2790                 }
2792                 $courseoptions[] = array(
2793                     'id' => $course->id,
2794                     'options' => $options
2795                 );
2796             }
2797         }
2799         $result = array(
2800             'courses' => $courseoptions,
2801             'warnings' => $warnings
2802         );
2803         return $result;
2804     }
2806     /**
2807      * Returns description of method result value
2808      *
2809      * @return external_description
2810      * @since Moodle 3.2
2811      */
2812     public static function get_user_navigation_options_returns() {
2813         return new external_single_structure(
2814             array(
2815                 'courses' => new external_multiple_structure(
2816                     new external_single_structure(
2817                         array(
2818                             'id' => new external_value(PARAM_INT, 'Course id'),
2819                             'options' => new external_multiple_structure(
2820                                 new external_single_structure(
2821                                     array(
2822                                         'name' => new external_value(PARAM_ALPHANUMEXT, 'Option name'),
2823                                         'available' => new external_value(PARAM_BOOL, 'Whether the option is available or not'),
2824                                     )
2825                                 )
2826                             )
2827                         )
2828                     ), 'List of courses'
2829                 ),
2830                 'warnings' => new external_warnings()
2831             )
2832         );
2833     }
2835     /**
2836      * Returns description of method parameters
2837      *
2838      * @return external_function_parameters
2839      * @since Moodle 3.2
2840      */
2841     public static function get_user_administration_options_parameters() {
2842         return new external_function_parameters(
2843             array(
2844                 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2845             )
2846         );
2847     }
2849     /**
2850      * Return a list of administration options in a set of courses that are available or not for the current user.
2851      *
2852      * @param array $courseids a list of course ids
2853      * @return array of warnings and the options availability
2854      * @since Moodle 3.2
2855      * @throws moodle_exception
2856      */
2857     public static function get_user_administration_options($courseids) {
2858         global $CFG;
2859         require_once($CFG->dirroot . '/course/lib.php');
2861         // Parameter validation.
2862         $params = self::validate_parameters(self::get_user_administration_options_parameters(), array('courseids' => $courseids));
2863         $courseoptions = array();
2865         list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
2867         if (!empty($courses)) {
2868             foreach ($courses as $course) {
2869                 $adminoptions = course_get_user_administration_options($course, $course->context);
2870                 $options = array();
2871                 foreach ($adminoptions as $name => $available) {
2872                     $options[] = array(
2873                         'name' => $name,
2874                         'available' => $available,
2875                     );
2876                 }
2878                 $courseoptions[] = array(
2879                     'id' => $course->id,
2880                     'options' => $options
2881                 );
2882             }
2883         }
2885         $result = array(
2886             'courses' => $courseoptions,
2887             'warnings' => $warnings
2888         );
2889         return $result;
2890     }
2892     /**
2893      * Returns description of method result value
2894      *
2895      * @return external_description
2896      * @since Moodle 3.2
2897      */
2898     public static function get_user_administration_options_returns() {
2899         return self::get_user_navigation_options_returns();
2900     }
2902     /**
2903      * Returns description of method parameters
2904      *
2905      * @return external_function_parameters
2906      * @since Moodle 3.2
2907      */
2908     public static function get_courses_by_field_parameters() {
2909         return new external_function_parameters(
2910             array(
2911                 'field' => new external_value(PARAM_ALPHA, 'The field to search can be left empty for all courses or:
2912                     id: course id
2913                     ids: comma separated course ids
2914                     shortname: course short name
2915                     idnumber: course id number
2916                     category: category id the course belongs to
2917                 ', VALUE_DEFAULT, ''),
2918                 'value' => new external_value(PARAM_RAW, 'The value to match', VALUE_DEFAULT, '')
2919             )
2920         );
2921     }
2924     /**
2925      * Get courses matching a specific field (id/s, shortname, idnumber, category)
2926      *
2927      * @param  string $field field name to search, or empty for all courses
2928      * @param  string $value value to search
2929      * @return array list of courses and warnings
2930      * @throws  invalid_parameter_exception
2931      * @since Moodle 3.2
2932      */
2933     public static function get_courses_by_field($field = '', $value = '') {
2934         global $DB, $CFG;
2935         require_once($CFG->libdir . '/coursecatlib.php');
2936         require_once($CFG->libdir . '/filterlib.php');
2938         $params = self::validate_parameters(self::get_courses_by_field_parameters(),
2939             array(
2940                 'field' => $field,
2941                 'value' => $value,
2942             )
2943         );
2944         $warnings = array();
2946         if (empty($params['field'])) {
2947             $courses = $DB->get_records('course', null, 'id ASC');
2948         } else {
2949             switch ($params['field']) {
2950                 case 'id':
2951                 case 'category':
2952                     $value = clean_param($params['value'], PARAM_INT);
2953                     break;
2954                 case 'ids':
2955                     $value = clean_param($params['value'], PARAM_SEQUENCE);
2956                     break;
2957                 case 'shortname':
2958                     $value = clean_param($params['value'], PARAM_TEXT);
2959                     break;
2960                 case 'idnumber':
2961                     $value = clean_param($params['value'], PARAM_RAW);
2962                     break;
2963                 default:
2964                     throw new invalid_parameter_exception('Invalid field name');
2965             }
2967             if ($params['field'] === 'ids') {
2968                 $courses = $DB->get_records_list('course', 'id', explode(',', $value), 'id ASC');
2969             } else {
2970                 $courses = $DB->get_records('course', array($params['field'] => $value), 'id ASC');
2971             }
2972         }
2974         $coursesdata = array();
2975         foreach ($courses as $course) {
2976             $context = context_course::instance($course->id);
2977             $canupdatecourse = has_capability('moodle/course:update', $context);
2978             $canviewhiddencourses = has_capability('moodle/course:viewhiddencourses', $context);
2980             // Check if the course is visible in the site for the user.
2981             if (!$course->visible and !$canviewhiddencourses and !$canupdatecourse) {
2982                 continue;
2983             }
2984             // Get the public course information, even if we are not enrolled.
2985             $courseinlist = new course_in_list($course);
2986             $coursesdata[$course->id] = self::get_course_public_information($courseinlist, $context);
2988             // Now, check if we have access to the course.
2989             try {
2990                 self::validate_context($context);
2991             } catch (Exception $e) {
2992                 continue;
2993             }
2994             // Return information for any user that can access the course.
2995             $coursefields = array('format', 'showgrades', 'newsitems', 'startdate', 'maxbytes', 'showreports', 'visible',
2996                 'groupmode', 'groupmodeforce', 'defaultgroupingid', 'enablecompletion', 'completionnotify', 'lang', 'theme',
2997                 'sortorder', 'marker');
2999             // Course filters.
3000             $coursesdata[$course->id]['filters'] = filter_get_available_in_context($context);
3002             // Information for managers only.
3003             if ($canupdatecourse) {
3004                 $managerfields = array('idnumber', 'legacyfiles', 'calendartype', 'timecreated', 'timemodified', 'requested',
3005                     'cacherev');
3006                 $coursefields = array_merge($coursefields, $managerfields);
3007             }
3009             // Populate fields.
3010             foreach ($coursefields as $field) {
3011                 $coursesdata[$course->id][$field] = $course->{$field};
3012             }
3013         }
3015         return array(
3016             'courses' => $coursesdata,
3017             'warnings' => $warnings
3018         );
3019     }
3021     /**
3022      * Returns description of method result value
3023      *
3024      * @return external_description
3025      * @since Moodle 3.2
3026      */
3027     public static function get_courses_by_field_returns() {
3028         // Course structure, including not only public viewable fields.
3029         return new external_single_structure(
3030             array(
3031                 'courses' => new external_multiple_structure(self::get_course_structure(false), 'Course'),
3032                 'warnings' => new external_warnings()
3033             )
3034         );
3035     }
3037     /**
3038      * Returns description of method parameters
3039      *
3040      * @return external_function_parameters
3041      * @since Moodle 3.2
3042      */
3043     public static function check_updates_parameters() {
3044         return new external_function_parameters(
3045             array(
3046                 'courseid' => new external_value(PARAM_INT, 'Course id to check'),
3047                 'tocheck' => new external_multiple_structure(
3048                     new external_single_structure(
3049                         array(
3050                             'contextlevel' => new external_value(PARAM_ALPHA, 'The context level for the file location.
3051                                                                                 Only module supported right now.'),
3052                             'id' => new external_value(PARAM_INT, 'Context instance id'),
3053                             'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'),
3054                         )
3055                     ),
3056                     'Instances to check'
3057                 ),
3058                 'filter' => new external_multiple_structure(
3059                     new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments,
3060                                                         gradeitems, outcomes'),
3061                     'Check only for updates in these areas', VALUE_DEFAULT, array()
3062             &nbs