Merge branch 'MDL-63583-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 use core_course\external\course_summary_exporter;
31 require_once("$CFG->libdir/externallib.php");
33 /**
34  * Course external functions
35  *
36  * @package    core_course
37  * @category   external
38  * @copyright  2011 Jerome Mouneyrac
39  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
40  * @since Moodle 2.2
41  */
42 class core_course_external extends external_api {
44     /**
45      * Returns description of method parameters
46      *
47      * @return external_function_parameters
48      * @since Moodle 2.9 Options available
49      * @since Moodle 2.2
50      */
51     public static function get_course_contents_parameters() {
52         return new external_function_parameters(
53                 array('courseid' => new external_value(PARAM_INT, 'course id'),
54                       'options' => new external_multiple_structure (
55                               new external_single_structure(
56                                 array(
57                                     'name' => new external_value(PARAM_ALPHANUM,
58                                                 'The expected keys (value format) are:
59                                                 excludemodules (bool) Do not return modules, return only the sections structure
60                                                 excludecontents (bool) Do not return module contents (i.e: files inside a resource)
61                                                 includestealthmodules (bool) Return stealth modules for students in a special
62                                                     section (with id -1)
63                                                 sectionid (int) Return only this section
64                                                 sectionnumber (int) Return only this section with number (order)
65                                                 cmid (int) Return only this module information (among the whole sections structure)
66                                                 modname (string) Return only modules with this name "label, forum, etc..."
67                                                 modid (int) Return only the module with this id (to be used with modname'),
68                                     'value' => new external_value(PARAM_RAW, 'the value of the option,
69                                                                     this param is personaly validated in the external function.')
70                               )
71                       ), 'Options, used since Moodle 2.9', VALUE_DEFAULT, array())
72                 )
73         );
74     }
76     /**
77      * Get course contents
78      *
79      * @param int $courseid course id
80      * @param array $options Options for filtering the results, used since Moodle 2.9
81      * @return array
82      * @since Moodle 2.9 Options available
83      * @since Moodle 2.2
84      */
85     public static function get_course_contents($courseid, $options = array()) {
86         global $CFG, $DB;
87         require_once($CFG->dirroot . "/course/lib.php");
89         //validate parameter
90         $params = self::validate_parameters(self::get_course_contents_parameters(),
91                         array('courseid' => $courseid, 'options' => $options));
93         $filters = array();
94         if (!empty($params['options'])) {
96             foreach ($params['options'] as $option) {
97                 $name = trim($option['name']);
98                 // Avoid duplicated options.
99                 if (!isset($filters[$name])) {
100                     switch ($name) {
101                         case 'excludemodules':
102                         case 'excludecontents':
103                         case 'includestealthmodules':
104                             $value = clean_param($option['value'], PARAM_BOOL);
105                             $filters[$name] = $value;
106                             break;
107                         case 'sectionid':
108                         case 'sectionnumber':
109                         case 'cmid':
110                         case 'modid':
111                             $value = clean_param($option['value'], PARAM_INT);
112                             if (is_numeric($value)) {
113                                 $filters[$name] = $value;
114                             } else {
115                                 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
116                             }
117                             break;
118                         case 'modname':
119                             $value = clean_param($option['value'], PARAM_PLUGIN);
120                             if ($value) {
121                                 $filters[$name] = $value;
122                             } else {
123                                 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
124                             }
125                             break;
126                         default:
127                             throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
128                     }
129                 }
130             }
131         }
133         //retrieve the course
134         $course = $DB->get_record('course', array('id' => $params['courseid']), '*', MUST_EXIST);
136         if ($course->id != SITEID) {
137             // Check course format exist.
138             if (!file_exists($CFG->dirroot . '/course/format/' . $course->format . '/lib.php')) {
139                 throw new moodle_exception('cannotgetcoursecontents', 'webservice', '', null,
140                                             get_string('courseformatnotfound', 'error', $course->format));
141             } else {
142                 require_once($CFG->dirroot . '/course/format/' . $course->format . '/lib.php');
143             }
144         }
146         // now security checks
147         $context = context_course::instance($course->id, IGNORE_MISSING);
148         try {
149             self::validate_context($context);
150         } catch (Exception $e) {
151             $exceptionparam = new stdClass();
152             $exceptionparam->message = $e->getMessage();
153             $exceptionparam->courseid = $course->id;
154             throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
155         }
157         $canupdatecourse = has_capability('moodle/course:update', $context);
159         //create return value
160         $coursecontents = array();
162         if ($canupdatecourse or $course->visible
163                 or has_capability('moodle/course:viewhiddencourses', $context)) {
165             //retrieve sections
166             $modinfo = get_fast_modinfo($course);
167             $sections = $modinfo->get_section_info_all();
168             $coursenumsections = course_get_format($course)->get_last_section_number();
169             $stealthmodules = array();   // Array to keep all the modules available but not visible in a course section/topic.
171             //for each sections (first displayed to last displayed)
172             $modinfosections = $modinfo->get_sections();
173             foreach ($sections as $key => $section) {
175                 // This becomes true when we are filtering and we found the value to filter with.
176                 $sectionfound = false;
178                 // Filter by section id.
179                 if (!empty($filters['sectionid'])) {
180                     if ($section->id != $filters['sectionid']) {
181                         continue;
182                     } else {
183                         $sectionfound = true;
184                     }
185                 }
187                 // Filter by section number. Note that 0 is a valid section number.
188                 if (isset($filters['sectionnumber'])) {
189                     if ($key != $filters['sectionnumber']) {
190                         continue;
191                     } else {
192                         $sectionfound = true;
193                     }
194                 }
196                 // reset $sectioncontents
197                 $sectionvalues = array();
198                 $sectionvalues['id'] = $section->id;
199                 $sectionvalues['name'] = get_section_name($course, $section);
200                 $sectionvalues['visible'] = $section->visible;
202                 $options = (object) array('noclean' => true);
203                 list($sectionvalues['summary'], $sectionvalues['summaryformat']) =
204                         external_format_text($section->summary, $section->summaryformat,
205                                 $context->id, 'course', 'section', $section->id, $options);
206                 $sectionvalues['section'] = $section->section;
207                 $sectionvalues['hiddenbynumsections'] = $section->section > $coursenumsections ? 1 : 0;
208                 $sectionvalues['uservisible'] = $section->uservisible;
209                 if (!empty($section->availableinfo)) {
210                     $sectionvalues['availabilityinfo'] = \core_availability\info::format_info($section->availableinfo, $course);
211                 }
213                 $sectioncontents = array();
215                 // For each module of the section.
216                 if (empty($filters['excludemodules']) and !empty($modinfosections[$section->section])) {
217                     foreach ($modinfosections[$section->section] as $cmid) {
218                         $cm = $modinfo->cms[$cmid];
220                         // Stop here if the module is not visible to the user on the course main page:
221                         // The user can't access the module and the user can't view the module on the course page.
222                         if (!$cm->uservisible && !$cm->is_visible_on_course_page()) {
223                             continue;
224                         }
226                         // This becomes true when we are filtering and we found the value to filter with.
227                         $modfound = false;
229                         // Filter by cmid.
230                         if (!empty($filters['cmid'])) {
231                             if ($cmid != $filters['cmid']) {
232                                 continue;
233                             } else {
234                                 $modfound = true;
235                             }
236                         }
238                         // Filter by module name and id.
239                         if (!empty($filters['modname'])) {
240                             if ($cm->modname != $filters['modname']) {
241                                 continue;
242                             } else if (!empty($filters['modid'])) {
243                                 if ($cm->instance != $filters['modid']) {
244                                     continue;
245                                 } else {
246                                     // Note that if we are only filtering by modname we don't break the loop.
247                                     $modfound = true;
248                                 }
249                             }
250                         }
252                         $module = array();
254                         $modcontext = context_module::instance($cm->id);
256                         //common info (for people being able to see the module or availability dates)
257                         $module['id'] = $cm->id;
258                         $module['name'] = external_format_string($cm->name, $modcontext->id);
259                         $module['instance'] = $cm->instance;
260                         $module['modname'] = $cm->modname;
261                         $module['modplural'] = $cm->modplural;
262                         $module['modicon'] = $cm->get_icon_url()->out(false);
263                         $module['indent'] = $cm->indent;
265                         if (!empty($cm->showdescription) or $cm->modname == 'label') {
266                             // We want to use the external format. However from reading get_formatted_content(), $cm->content format is always FORMAT_HTML.
267                             $options = array('noclean' => true);
268                             list($module['description'], $descriptionformat) = external_format_text($cm->content,
269                                 FORMAT_HTML, $modcontext->id, $cm->modname, 'intro', $cm->id, $options);
270                         }
272                         //url of the module
273                         $url = $cm->url;
274                         if ($url) { //labels don't have url
275                             $module['url'] = $url->out(false);
276                         }
278                         $canviewhidden = has_capability('moodle/course:viewhiddenactivities',
279                                             context_module::instance($cm->id));
280                         //user that can view hidden module should know about the visibility
281                         $module['visible'] = $cm->visible;
282                         $module['visibleoncoursepage'] = $cm->visibleoncoursepage;
283                         $module['uservisible'] = $cm->uservisible;
284                         if (!empty($cm->availableinfo)) {
285                             $module['availabilityinfo'] = \core_availability\info::format_info($cm->availableinfo, $course);
286                         }
288                         // Availability date (also send to user who can see hidden module).
289                         if ($CFG->enableavailability && ($canviewhidden || $canupdatecourse)) {
290                             $module['availability'] = $cm->availability;
291                         }
293                         // Return contents only if the user can access to the module.
294                         if ($cm->uservisible) {
295                             $baseurl = 'webservice/pluginfile.php';
297                             // Call $modulename_export_contents (each module callback take care about checking the capabilities).
298                             require_once($CFG->dirroot . '/mod/' . $cm->modname . '/lib.php');
299                             $getcontentfunction = $cm->modname.'_export_contents';
300                             if (function_exists($getcontentfunction)) {
301                                 if (empty($filters['excludecontents']) and $contents = $getcontentfunction($cm, $baseurl)) {
302                                     $module['contents'] = $contents;
303                                 } else {
304                                     $module['contents'] = array();
305                                 }
306                             }
307                         }
309                         // Assign result to $sectioncontents, there is an exception,
310                         // stealth activities in non-visible sections for students go to a special section.
311                         if (!empty($filters['includestealthmodules']) && !$section->uservisible && $cm->is_stealth()) {
312                             $stealthmodules[] = $module;
313                         } else {
314                             $sectioncontents[] = $module;
315                         }
317                         // If we just did a filtering, break the loop.
318                         if ($modfound) {
319                             break;
320                         }
322                     }
323                 }
324                 $sectionvalues['modules'] = $sectioncontents;
326                 // assign result to $coursecontents
327                 $coursecontents[$key] = $sectionvalues;
329                 // Break the loop if we are filtering.
330                 if ($sectionfound) {
331                     break;
332                 }
333             }
335             // Now that we have iterated over all the sections and activities, check the visibility.
336             // We didn't this before to be able to retrieve stealth activities.
337             foreach ($coursecontents as $sectionnumber => $sectioncontents) {
338                 $section = $sections[$sectionnumber];
339                 // Show the section if the user is permitted to access it, OR if it's not available
340                 // but there is some available info text which explains the reason & should display.
341                 $showsection = $section->uservisible ||
342                     ($section->visible && !$section->available &&
343                     !empty($section->availableinfo));
345                 if (!$showsection) {
346                     unset($coursecontents[$sectionnumber]);
347                     continue;
348                 }
350                 // Remove modules information if the section is not visible for the user.
351                 if (!$section->uservisible) {
352                     $coursecontents[$sectionnumber]['modules'] = array();
353                 }
354             }
356             // Include stealth modules in special section (without any info).
357             if (!empty($stealthmodules)) {
358                 $coursecontents[] = array(
359                     'id' => -1,
360                     'name' => '',
361                     'summary' => '',
362                     'summaryformat' => FORMAT_MOODLE,
363                     'modules' => $stealthmodules
364                 );
365             }
367         }
368         return $coursecontents;
369     }
371     /**
372      * Returns description of method result value
373      *
374      * @return external_description
375      * @since Moodle 2.2
376      */
377     public static function get_course_contents_returns() {
378         return new external_multiple_structure(
379             new external_single_structure(
380                 array(
381                     'id' => new external_value(PARAM_INT, 'Section ID'),
382                     'name' => new external_value(PARAM_TEXT, 'Section name'),
383                     'visible' => new external_value(PARAM_INT, 'is the section visible', VALUE_OPTIONAL),
384                     'summary' => new external_value(PARAM_RAW, 'Section description'),
385                     'summaryformat' => new external_format_value('summary'),
386                     'section' => new external_value(PARAM_INT, 'Section number inside the course', VALUE_OPTIONAL),
387                     'hiddenbynumsections' => new external_value(PARAM_INT, 'Whether is a section hidden in the course format',
388                                                                 VALUE_OPTIONAL),
389                     'uservisible' => new external_value(PARAM_BOOL, 'Is the section visible for the user?', VALUE_OPTIONAL),
390                     'availabilityinfo' => new external_value(PARAM_RAW, 'Availability information.', VALUE_OPTIONAL),
391                     'modules' => new external_multiple_structure(
392                             new external_single_structure(
393                                 array(
394                                     'id' => new external_value(PARAM_INT, 'activity id'),
395                                     'url' => new external_value(PARAM_URL, 'activity url', VALUE_OPTIONAL),
396                                     'name' => new external_value(PARAM_RAW, 'activity module name'),
397                                     'instance' => new external_value(PARAM_INT, 'instance id', VALUE_OPTIONAL),
398                                     'description' => new external_value(PARAM_RAW, 'activity description', VALUE_OPTIONAL),
399                                     'visible' => new external_value(PARAM_INT, 'is the module visible', VALUE_OPTIONAL),
400                                     'uservisible' => new external_value(PARAM_BOOL, 'Is the module visible for the user?',
401                                         VALUE_OPTIONAL),
402                                     'availabilityinfo' => new external_value(PARAM_RAW, 'Availability information.',
403                                         VALUE_OPTIONAL),
404                                     'visibleoncoursepage' => new external_value(PARAM_INT, 'is the module visible on course page',
405                                         VALUE_OPTIONAL),
406                                     'modicon' => new external_value(PARAM_URL, 'activity icon url'),
407                                     'modname' => new external_value(PARAM_PLUGIN, 'activity module type'),
408                                     'modplural' => new external_value(PARAM_TEXT, 'activity module plural name'),
409                                     'availability' => new external_value(PARAM_RAW, 'module availability settings', VALUE_OPTIONAL),
410                                     'indent' => new external_value(PARAM_INT, 'number of identation in the site'),
411                                     'contents' => new external_multiple_structure(
412                                           new external_single_structure(
413                                               array(
414                                                   // content info
415                                                   'type'=> new external_value(PARAM_TEXT, 'a file or a folder or external link'),
416                                                   'filename'=> new external_value(PARAM_FILE, 'filename'),
417                                                   'filepath'=> new external_value(PARAM_PATH, 'filepath'),
418                                                   'filesize'=> new external_value(PARAM_INT, 'filesize'),
419                                                   'fileurl' => new external_value(PARAM_URL, 'downloadable file url', VALUE_OPTIONAL),
420                                                   'content' => new external_value(PARAM_RAW, 'Raw content, will be used when type is content', VALUE_OPTIONAL),
421                                                   'timecreated' => new external_value(PARAM_INT, 'Time created'),
422                                                   'timemodified' => new external_value(PARAM_INT, 'Time modified'),
423                                                   'sortorder' => new external_value(PARAM_INT, 'Content sort order'),
424                                                   'mimetype' => new external_value(PARAM_RAW, 'File mime type.', VALUE_OPTIONAL),
425                                                   'isexternalfile' => new external_value(PARAM_BOOL, 'Whether is an external file.',
426                                                     VALUE_OPTIONAL),
427                                                   'repositorytype' => new external_value(PARAM_PLUGIN, 'The repository type for external files.',
428                                                     VALUE_OPTIONAL),
430                                                   // copyright related info
431                                                   'userid' => new external_value(PARAM_INT, 'User who added this content to moodle'),
432                                                   'author' => new external_value(PARAM_TEXT, 'Content owner'),
433                                                   'license' => new external_value(PARAM_TEXT, 'Content license'),
434                                               )
435                                           ), VALUE_DEFAULT, array()
436                                       )
437                                 )
438                             ), 'list of module'
439                     )
440                 )
441             )
442         );
443     }
445     /**
446      * Returns description of method parameters
447      *
448      * @return external_function_parameters
449      * @since Moodle 2.3
450      */
451     public static function get_courses_parameters() {
452         return new external_function_parameters(
453                 array('options' => new external_single_structure(
454                             array('ids' => new external_multiple_structure(
455                                         new external_value(PARAM_INT, 'Course id')
456                                         , 'List of course id. If empty return all courses
457                                             except front page course.',
458                                         VALUE_OPTIONAL)
459                             ), 'options - operator OR is used', VALUE_DEFAULT, array())
460                 )
461         );
462     }
464     /**
465      * Get courses
466      *
467      * @param array $options It contains an array (list of ids)
468      * @return array
469      * @since Moodle 2.2
470      */
471     public static function get_courses($options = array()) {
472         global $CFG, $DB;
473         require_once($CFG->dirroot . "/course/lib.php");
475         //validate parameter
476         $params = self::validate_parameters(self::get_courses_parameters(),
477                         array('options' => $options));
479         //retrieve courses
480         if (!array_key_exists('ids', $params['options'])
481                 or empty($params['options']['ids'])) {
482             $courses = $DB->get_records('course');
483         } else {
484             $courses = $DB->get_records_list('course', 'id', $params['options']['ids']);
485         }
487         //create return value
488         $coursesinfo = array();
489         foreach ($courses as $course) {
491             // now security checks
492             $context = context_course::instance($course->id, IGNORE_MISSING);
493             $courseformatoptions = course_get_format($course)->get_format_options();
494             try {
495                 self::validate_context($context);
496             } catch (Exception $e) {
497                 $exceptionparam = new stdClass();
498                 $exceptionparam->message = $e->getMessage();
499                 $exceptionparam->courseid = $course->id;
500                 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
501             }
502             if ($course->id != SITEID) {
503                 require_capability('moodle/course:view', $context);
504             }
506             $courseinfo = array();
507             $courseinfo['id'] = $course->id;
508             $courseinfo['fullname'] = external_format_string($course->fullname, $context->id);
509             $courseinfo['shortname'] = external_format_string($course->shortname, $context->id);
510             $courseinfo['displayname'] = external_format_string(get_course_display_name_for_list($course), $context->id);
511             $courseinfo['categoryid'] = $course->category;
512             list($courseinfo['summary'], $courseinfo['summaryformat']) =
513                 external_format_text($course->summary, $course->summaryformat, $context->id, 'course', 'summary', 0);
514             $courseinfo['format'] = $course->format;
515             $courseinfo['startdate'] = $course->startdate;
516             $courseinfo['enddate'] = $course->enddate;
517             if (array_key_exists('numsections', $courseformatoptions)) {
518                 // For backward-compartibility
519                 $courseinfo['numsections'] = $courseformatoptions['numsections'];
520             }
522             //some field should be returned only if the user has update permission
523             $courseadmin = has_capability('moodle/course:update', $context);
524             if ($courseadmin) {
525                 $courseinfo['categorysortorder'] = $course->sortorder;
526                 $courseinfo['idnumber'] = $course->idnumber;
527                 $courseinfo['showgrades'] = $course->showgrades;
528                 $courseinfo['showreports'] = $course->showreports;
529                 $courseinfo['newsitems'] = $course->newsitems;
530                 $courseinfo['visible'] = $course->visible;
531                 $courseinfo['maxbytes'] = $course->maxbytes;
532                 if (array_key_exists('hiddensections', $courseformatoptions)) {
533                     // For backward-compartibility
534                     $courseinfo['hiddensections'] = $courseformatoptions['hiddensections'];
535                 }
536                 // Return numsections for backward-compatibility with clients who expect it.
537                 $courseinfo['numsections'] = course_get_format($course)->get_last_section_number();
538                 $courseinfo['groupmode'] = $course->groupmode;
539                 $courseinfo['groupmodeforce'] = $course->groupmodeforce;
540                 $courseinfo['defaultgroupingid'] = $course->defaultgroupingid;
541                 $courseinfo['lang'] = clean_param($course->lang, PARAM_LANG);
542                 $courseinfo['timecreated'] = $course->timecreated;
543                 $courseinfo['timemodified'] = $course->timemodified;
544                 $courseinfo['forcetheme'] = clean_param($course->theme, PARAM_THEME);
545                 $courseinfo['enablecompletion'] = $course->enablecompletion;
546                 $courseinfo['completionnotify'] = $course->completionnotify;
547                 $courseinfo['courseformatoptions'] = array();
548                 foreach ($courseformatoptions as $key => $value) {
549                     $courseinfo['courseformatoptions'][] = array(
550                         'name' => $key,
551                         'value' => $value
552                     );
553                 }
554             }
556             if ($courseadmin or $course->visible
557                     or has_capability('moodle/course:viewhiddencourses', $context)) {
558                 $coursesinfo[] = $courseinfo;
559             }
560         }
562         return $coursesinfo;
563     }
565     /**
566      * Returns description of method result value
567      *
568      * @return external_description
569      * @since Moodle 2.2
570      */
571     public static function get_courses_returns() {
572         return new external_multiple_structure(
573                 new external_single_structure(
574                         array(
575                             'id' => new external_value(PARAM_INT, 'course id'),
576                             'shortname' => new external_value(PARAM_TEXT, 'course short name'),
577                             'categoryid' => new external_value(PARAM_INT, 'category id'),
578                             'categorysortorder' => new external_value(PARAM_INT,
579                                     'sort order into the category', VALUE_OPTIONAL),
580                             'fullname' => new external_value(PARAM_TEXT, 'full name'),
581                             'displayname' => new external_value(PARAM_TEXT, 'course display name'),
582                             'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
583                             'summary' => new external_value(PARAM_RAW, 'summary'),
584                             'summaryformat' => new external_format_value('summary'),
585                             'format' => new external_value(PARAM_PLUGIN,
586                                     'course format: weeks, topics, social, site,..'),
587                             'showgrades' => new external_value(PARAM_INT,
588                                     '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
589                             'newsitems' => new external_value(PARAM_INT,
590                                     'number of recent items appearing on the course page', VALUE_OPTIONAL),
591                             'startdate' => new external_value(PARAM_INT,
592                                     'timestamp when the course start'),
593                             'enddate' => new external_value(PARAM_INT,
594                                     'timestamp when the course end'),
595                             'numsections' => new external_value(PARAM_INT,
596                                     '(deprecated, use courseformatoptions) number of weeks/topics',
597                                     VALUE_OPTIONAL),
598                             'maxbytes' => new external_value(PARAM_INT,
599                                     'largest size of file that can be uploaded into the course',
600                                     VALUE_OPTIONAL),
601                             'showreports' => new external_value(PARAM_INT,
602                                     'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
603                             'visible' => new external_value(PARAM_INT,
604                                     '1: available to student, 0:not available', VALUE_OPTIONAL),
605                             'hiddensections' => new external_value(PARAM_INT,
606                                     '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
607                                     VALUE_OPTIONAL),
608                             'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
609                                     VALUE_OPTIONAL),
610                             'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
611                                     VALUE_OPTIONAL),
612                             'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
613                                     VALUE_OPTIONAL),
614                             'timecreated' => new external_value(PARAM_INT,
615                                     'timestamp when the course have been created', VALUE_OPTIONAL),
616                             'timemodified' => new external_value(PARAM_INT,
617                                     'timestamp when the course have been modified', VALUE_OPTIONAL),
618                             'enablecompletion' => new external_value(PARAM_INT,
619                                     'Enabled, control via completion and activity settings. Disbaled,
620                                         not shown in activity settings.',
621                                     VALUE_OPTIONAL),
622                             'completionnotify' => new external_value(PARAM_INT,
623                                     '1: yes 0: no', VALUE_OPTIONAL),
624                             'lang' => new external_value(PARAM_SAFEDIR,
625                                     'forced course language', VALUE_OPTIONAL),
626                             'forcetheme' => new external_value(PARAM_PLUGIN,
627                                     'name of the force theme', VALUE_OPTIONAL),
628                             'courseformatoptions' => new external_multiple_structure(
629                                 new external_single_structure(
630                                     array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
631                                         'value' => new external_value(PARAM_RAW, 'course format option value')
632                                 )),
633                                     'additional options for particular course format', VALUE_OPTIONAL
634                              ),
635                         ), 'course'
636                 )
637         );
638     }
640     /**
641      * Returns description of method parameters
642      *
643      * @return external_function_parameters
644      * @since Moodle 2.2
645      */
646     public static function create_courses_parameters() {
647         $courseconfig = get_config('moodlecourse'); //needed for many default values
648         return new external_function_parameters(
649             array(
650                 'courses' => new external_multiple_structure(
651                     new external_single_structure(
652                         array(
653                             'fullname' => new external_value(PARAM_TEXT, 'full name'),
654                             'shortname' => new external_value(PARAM_TEXT, 'course short name'),
655                             'categoryid' => new external_value(PARAM_INT, 'category id'),
656                             'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
657                             'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
658                             'summaryformat' => new external_format_value('summary', VALUE_DEFAULT),
659                             'format' => new external_value(PARAM_PLUGIN,
660                                     'course format: weeks, topics, social, site,..',
661                                     VALUE_DEFAULT, $courseconfig->format),
662                             'showgrades' => new external_value(PARAM_INT,
663                                     '1 if grades are shown, otherwise 0', VALUE_DEFAULT,
664                                     $courseconfig->showgrades),
665                             'newsitems' => new external_value(PARAM_INT,
666                                     'number of recent items appearing on the course page',
667                                     VALUE_DEFAULT, $courseconfig->newsitems),
668                             'startdate' => new external_value(PARAM_INT,
669                                     'timestamp when the course start', VALUE_OPTIONAL),
670                             'enddate' => new external_value(PARAM_INT,
671                                     'timestamp when the course end', VALUE_OPTIONAL),
672                             'numsections' => new external_value(PARAM_INT,
673                                     '(deprecated, use courseformatoptions) number of weeks/topics',
674                                     VALUE_OPTIONAL),
675                             'maxbytes' => new external_value(PARAM_INT,
676                                     'largest size of file that can be uploaded into the course',
677                                     VALUE_DEFAULT, $courseconfig->maxbytes),
678                             'showreports' => new external_value(PARAM_INT,
679                                     'are activity report shown (yes = 1, no =0)', VALUE_DEFAULT,
680                                     $courseconfig->showreports),
681                             'visible' => new external_value(PARAM_INT,
682                                     '1: available to student, 0:not available', VALUE_OPTIONAL),
683                             'hiddensections' => new external_value(PARAM_INT,
684                                     '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
685                                     VALUE_OPTIONAL),
686                             'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
687                                     VALUE_DEFAULT, $courseconfig->groupmode),
688                             'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
689                                     VALUE_DEFAULT, $courseconfig->groupmodeforce),
690                             'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
691                                     VALUE_DEFAULT, 0),
692                             'enablecompletion' => new external_value(PARAM_INT,
693                                     'Enabled, control via completion and activity settings. Disabled,
694                                         not shown in activity settings.',
695                                     VALUE_OPTIONAL),
696                             'completionnotify' => new external_value(PARAM_INT,
697                                     '1: yes 0: no', VALUE_OPTIONAL),
698                             'lang' => new external_value(PARAM_SAFEDIR,
699                                     'forced course language', VALUE_OPTIONAL),
700                             'forcetheme' => new external_value(PARAM_PLUGIN,
701                                     'name of the force theme', VALUE_OPTIONAL),
702                             'courseformatoptions' => new external_multiple_structure(
703                                 new external_single_structure(
704                                     array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
705                                         'value' => new external_value(PARAM_RAW, 'course format option value')
706                                 )),
707                                     'additional options for particular course format', VALUE_OPTIONAL),
708                         )
709                     ), 'courses to create'
710                 )
711             )
712         );
713     }
715     /**
716      * Create  courses
717      *
718      * @param array $courses
719      * @return array courses (id and shortname only)
720      * @since Moodle 2.2
721      */
722     public static function create_courses($courses) {
723         global $CFG, $DB;
724         require_once($CFG->dirroot . "/course/lib.php");
725         require_once($CFG->libdir . '/completionlib.php');
727         $params = self::validate_parameters(self::create_courses_parameters(),
728                         array('courses' => $courses));
730         $availablethemes = core_component::get_plugin_list('theme');
731         $availablelangs = get_string_manager()->get_list_of_translations();
733         $transaction = $DB->start_delegated_transaction();
735         foreach ($params['courses'] as $course) {
737             // Ensure the current user is allowed to run this function
738             $context = context_coursecat::instance($course['categoryid'], IGNORE_MISSING);
739             try {
740                 self::validate_context($context);
741             } catch (Exception $e) {
742                 $exceptionparam = new stdClass();
743                 $exceptionparam->message = $e->getMessage();
744                 $exceptionparam->catid = $course['categoryid'];
745                 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
746             }
747             require_capability('moodle/course:create', $context);
749             // Make sure lang is valid
750             if (array_key_exists('lang', $course)) {
751                 if (empty($availablelangs[$course['lang']])) {
752                     throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
753                 }
754                 if (!has_capability('moodle/course:setforcedlanguage', $context)) {
755                     unset($course['lang']);
756                 }
757             }
759             // Make sure theme is valid
760             if (array_key_exists('forcetheme', $course)) {
761                 if (!empty($CFG->allowcoursethemes)) {
762                     if (empty($availablethemes[$course['forcetheme']])) {
763                         throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
764                     } else {
765                         $course['theme'] = $course['forcetheme'];
766                     }
767                 }
768             }
770             //force visibility if ws user doesn't have the permission to set it
771             $category = $DB->get_record('course_categories', array('id' => $course['categoryid']));
772             if (!has_capability('moodle/course:visibility', $context)) {
773                 $course['visible'] = $category->visible;
774             }
776             //set default value for completion
777             $courseconfig = get_config('moodlecourse');
778             if (completion_info::is_enabled_for_site()) {
779                 if (!array_key_exists('enablecompletion', $course)) {
780                     $course['enablecompletion'] = $courseconfig->enablecompletion;
781                 }
782             } else {
783                 $course['enablecompletion'] = 0;
784             }
786             $course['category'] = $course['categoryid'];
788             // Summary format.
789             $course['summaryformat'] = external_validate_format($course['summaryformat']);
791             if (!empty($course['courseformatoptions'])) {
792                 foreach ($course['courseformatoptions'] as $option) {
793                     $course[$option['name']] = $option['value'];
794                 }
795             }
797             //Note: create_course() core function check shortname, idnumber, category
798             $course['id'] = create_course((object) $course)->id;
800             $resultcourses[] = array('id' => $course['id'], 'shortname' => $course['shortname']);
801         }
803         $transaction->allow_commit();
805         return $resultcourses;
806     }
808     /**
809      * Returns description of method result value
810      *
811      * @return external_description
812      * @since Moodle 2.2
813      */
814     public static function create_courses_returns() {
815         return new external_multiple_structure(
816             new external_single_structure(
817                 array(
818                     'id'       => new external_value(PARAM_INT, 'course id'),
819                     'shortname' => new external_value(PARAM_TEXT, 'short name'),
820                 )
821             )
822         );
823     }
825     /**
826      * Update courses
827      *
828      * @return external_function_parameters
829      * @since Moodle 2.5
830      */
831     public static function update_courses_parameters() {
832         return new external_function_parameters(
833             array(
834                 'courses' => new external_multiple_structure(
835                     new external_single_structure(
836                         array(
837                             'id' => new external_value(PARAM_INT, 'ID of the course'),
838                             'fullname' => new external_value(PARAM_TEXT, 'full name', VALUE_OPTIONAL),
839                             'shortname' => new external_value(PARAM_TEXT, 'course short name', VALUE_OPTIONAL),
840                             'categoryid' => new external_value(PARAM_INT, 'category id', VALUE_OPTIONAL),
841                             'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
842                             'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
843                             'summaryformat' => new external_format_value('summary', VALUE_OPTIONAL),
844                             'format' => new external_value(PARAM_PLUGIN,
845                                     'course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
846                             'showgrades' => new external_value(PARAM_INT,
847                                     '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
848                             'newsitems' => new external_value(PARAM_INT,
849                                     'number of recent items appearing on the course page', VALUE_OPTIONAL),
850                             'startdate' => new external_value(PARAM_INT,
851                                     'timestamp when the course start', VALUE_OPTIONAL),
852                             'enddate' => new external_value(PARAM_INT,
853                                     'timestamp when the course end', VALUE_OPTIONAL),
854                             'numsections' => new external_value(PARAM_INT,
855                                     '(deprecated, use courseformatoptions) number of weeks/topics', VALUE_OPTIONAL),
856                             'maxbytes' => new external_value(PARAM_INT,
857                                     'largest size of file that can be uploaded into the course', VALUE_OPTIONAL),
858                             'showreports' => new external_value(PARAM_INT,
859                                     'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
860                             'visible' => new external_value(PARAM_INT,
861                                     '1: available to student, 0:not available', VALUE_OPTIONAL),
862                             'hiddensections' => new external_value(PARAM_INT,
863                                     '(deprecated, use courseformatoptions) How the hidden sections in the course are
864                                         displayed to students', VALUE_OPTIONAL),
865                             'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
866                             'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
867                             'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
868                             'enablecompletion' => new external_value(PARAM_INT,
869                                     'Enabled, control via completion and activity settings. Disabled,
870                                         not shown in activity settings.', VALUE_OPTIONAL),
871                             'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
872                             'lang' => new external_value(PARAM_SAFEDIR, 'forced course language', VALUE_OPTIONAL),
873                             'forcetheme' => new external_value(PARAM_PLUGIN, 'name of the force theme', VALUE_OPTIONAL),
874                             'courseformatoptions' => new external_multiple_structure(
875                                 new external_single_structure(
876                                     array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
877                                         'value' => new external_value(PARAM_RAW, 'course format option value')
878                                 )),
879                                     'additional options for particular course format', VALUE_OPTIONAL),
880                         )
881                     ), 'courses to update'
882                 )
883             )
884         );
885     }
887     /**
888      * Update courses
889      *
890      * @param array $courses
891      * @since Moodle 2.5
892      */
893     public static function update_courses($courses) {
894         global $CFG, $DB;
895         require_once($CFG->dirroot . "/course/lib.php");
896         $warnings = array();
898         $params = self::validate_parameters(self::update_courses_parameters(),
899                         array('courses' => $courses));
901         $availablethemes = core_component::get_plugin_list('theme');
902         $availablelangs = get_string_manager()->get_list_of_translations();
904         foreach ($params['courses'] as $course) {
905             // Catch any exception while updating course and return as warning to user.
906             try {
907                 // Ensure the current user is allowed to run this function.
908                 $context = context_course::instance($course['id'], MUST_EXIST);
909                 self::validate_context($context);
911                 $oldcourse = course_get_format($course['id'])->get_course();
913                 require_capability('moodle/course:update', $context);
915                 // Check if user can change category.
916                 if (array_key_exists('categoryid', $course) && ($oldcourse->category != $course['categoryid'])) {
917                     require_capability('moodle/course:changecategory', $context);
918                     $course['category'] = $course['categoryid'];
919                 }
921                 // Check if the user can change fullname.
922                 if (array_key_exists('fullname', $course) && ($oldcourse->fullname != $course['fullname'])) {
923                     require_capability('moodle/course:changefullname', $context);
924                 }
926                 // Check if the user can change shortname.
927                 if (array_key_exists('shortname', $course) && ($oldcourse->shortname != $course['shortname'])) {
928                     require_capability('moodle/course:changeshortname', $context);
929                 }
931                 // Check if the user can change the idnumber.
932                 if (array_key_exists('idnumber', $course) && ($oldcourse->idnumber != $course['idnumber'])) {
933                     require_capability('moodle/course:changeidnumber', $context);
934                 }
936                 // Check if user can change summary.
937                 if (array_key_exists('summary', $course) && ($oldcourse->summary != $course['summary'])) {
938                     require_capability('moodle/course:changesummary', $context);
939                 }
941                 // Summary format.
942                 if (array_key_exists('summaryformat', $course) && ($oldcourse->summaryformat != $course['summaryformat'])) {
943                     require_capability('moodle/course:changesummary', $context);
944                     $course['summaryformat'] = external_validate_format($course['summaryformat']);
945                 }
947                 // Check if user can change visibility.
948                 if (array_key_exists('visible', $course) && ($oldcourse->visible != $course['visible'])) {
949                     require_capability('moodle/course:visibility', $context);
950                 }
952                 // Make sure lang is valid.
953                 if (array_key_exists('lang', $course) && ($oldcourse->lang != $course['lang'])) {
954                     require_capability('moodle/course:setforcedlanguage', $context);
955                     if (empty($availablelangs[$course['lang']])) {
956                         throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
957                     }
958                 }
960                 // Make sure theme is valid.
961                 if (array_key_exists('forcetheme', $course)) {
962                     if (!empty($CFG->allowcoursethemes)) {
963                         if (empty($availablethemes[$course['forcetheme']])) {
964                             throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
965                         } else {
966                             $course['theme'] = $course['forcetheme'];
967                         }
968                     }
969                 }
971                 // Make sure completion is enabled before setting it.
972                 if (array_key_exists('enabledcompletion', $course) && !completion_info::is_enabled_for_site()) {
973                     $course['enabledcompletion'] = 0;
974                 }
976                 // Make sure maxbytes are less then CFG->maxbytes.
977                 if (array_key_exists('maxbytes', $course)) {
978                     // We allow updates back to 0 max bytes, a special value denoting the course uses the site limit.
979                     // Otherwise, either use the size specified, or cap at the max size for the course.
980                     if ($course['maxbytes'] != 0) {
981                         $course['maxbytes'] = get_max_upload_file_size($CFG->maxbytes, $course['maxbytes']);
982                     }
983                 }
985                 if (!empty($course['courseformatoptions'])) {
986                     foreach ($course['courseformatoptions'] as $option) {
987                         if (isset($option['name']) && isset($option['value'])) {
988                             $course[$option['name']] = $option['value'];
989                         }
990                     }
991                 }
993                 // Update course if user has all required capabilities.
994                 update_course((object) $course);
995             } catch (Exception $e) {
996                 $warning = array();
997                 $warning['item'] = 'course';
998                 $warning['itemid'] = $course['id'];
999                 if ($e instanceof moodle_exception) {
1000                     $warning['warningcode'] = $e->errorcode;
1001                 } else {
1002                     $warning['warningcode'] = $e->getCode();
1003                 }
1004                 $warning['message'] = $e->getMessage();
1005                 $warnings[] = $warning;
1006             }
1007         }
1009         $result = array();
1010         $result['warnings'] = $warnings;
1011         return $result;
1012     }
1014     /**
1015      * Returns description of method result value
1016      *
1017      * @return external_description
1018      * @since Moodle 2.5
1019      */
1020     public static function update_courses_returns() {
1021         return new external_single_structure(
1022             array(
1023                 'warnings' => new external_warnings()
1024             )
1025         );
1026     }
1028     /**
1029      * Returns description of method parameters
1030      *
1031      * @return external_function_parameters
1032      * @since Moodle 2.2
1033      */
1034     public static function delete_courses_parameters() {
1035         return new external_function_parameters(
1036             array(
1037                 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'course ID')),
1038             )
1039         );
1040     }
1042     /**
1043      * Delete courses
1044      *
1045      * @param array $courseids A list of course ids
1046      * @since Moodle 2.2
1047      */
1048     public static function delete_courses($courseids) {
1049         global $CFG, $DB;
1050         require_once($CFG->dirroot."/course/lib.php");
1052         // Parameter validation.
1053         $params = self::validate_parameters(self::delete_courses_parameters(), array('courseids'=>$courseids));
1055         $warnings = array();
1057         foreach ($params['courseids'] as $courseid) {
1058             $course = $DB->get_record('course', array('id' => $courseid));
1060             if ($course === false) {
1061                 $warnings[] = array(
1062                                 'item' => 'course',
1063                                 'itemid' => $courseid,
1064                                 'warningcode' => 'unknowncourseidnumber',
1065                                 'message' => 'Unknown course ID ' . $courseid
1066                             );
1067                 continue;
1068             }
1070             // Check if the context is valid.
1071             $coursecontext = context_course::instance($course->id);
1072             self::validate_context($coursecontext);
1074             // Check if the current user has permission.
1075             if (!can_delete_course($courseid)) {
1076                 $warnings[] = array(
1077                                 'item' => 'course',
1078                                 'itemid' => $courseid,
1079                                 'warningcode' => 'cannotdeletecourse',
1080                                 'message' => 'You do not have the permission to delete this course' . $courseid
1081                             );
1082                 continue;
1083             }
1085             if (delete_course($course, false) === false) {
1086                 $warnings[] = array(
1087                                 'item' => 'course',
1088                                 'itemid' => $courseid,
1089                                 'warningcode' => 'cannotdeletecategorycourse',
1090                                 'message' => 'Course ' . $courseid . ' failed to be deleted'
1091                             );
1092                 continue;
1093             }
1094         }
1096         fix_course_sortorder();
1098         return array('warnings' => $warnings);
1099     }
1101     /**
1102      * Returns description of method result value
1103      *
1104      * @return external_description
1105      * @since Moodle 2.2
1106      */
1107     public static function delete_courses_returns() {
1108         return new external_single_structure(
1109             array(
1110                 'warnings' => new external_warnings()
1111             )
1112         );
1113     }
1115     /**
1116      * Returns description of method parameters
1117      *
1118      * @return external_function_parameters
1119      * @since Moodle 2.3
1120      */
1121     public static function duplicate_course_parameters() {
1122         return new external_function_parameters(
1123             array(
1124                 'courseid' => new external_value(PARAM_INT, 'course to duplicate id'),
1125                 'fullname' => new external_value(PARAM_TEXT, 'duplicated course full name'),
1126                 'shortname' => new external_value(PARAM_TEXT, 'duplicated course short name'),
1127                 'categoryid' => new external_value(PARAM_INT, 'duplicated course category parent'),
1128                 'visible' => new external_value(PARAM_INT, 'duplicated course visible, default to yes', VALUE_DEFAULT, 1),
1129                 'options' => new external_multiple_structure(
1130                     new external_single_structure(
1131                         array(
1132                                 'name' => new external_value(PARAM_ALPHAEXT, 'The backup option name:
1133                                             "activities" (int) Include course activites (default to 1 that is equal to yes),
1134                                             "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1135                                             "filters" (int) Include course filters  (default to 1 that is equal to yes),
1136                                             "users" (int) Include users (default to 0 that is equal to no),
1137                                             "enrolments" (int) Include enrolment methods (default to 1 - restore only with users),
1138                                             "role_assignments" (int) Include role assignments  (default to 0 that is equal to no),
1139                                             "comments" (int) Include user comments  (default to 0 that is equal to no),
1140                                             "userscompletion" (int) Include user course completion information  (default to 0 that is equal to no),
1141                                             "logs" (int) Include course logs  (default to 0 that is equal to no),
1142                                             "grade_histories" (int) Include histories  (default to 0 that is equal to no)'
1143                                             ),
1144                                 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1145                             )
1146                         )
1147                     ), VALUE_DEFAULT, array()
1148                 ),
1149             )
1150         );
1151     }
1153     /**
1154      * Duplicate a course
1155      *
1156      * @param int $courseid
1157      * @param string $fullname Duplicated course fullname
1158      * @param string $shortname Duplicated course shortname
1159      * @param int $categoryid Duplicated course parent category id
1160      * @param int $visible Duplicated course availability
1161      * @param array $options List of backup options
1162      * @return array New course info
1163      * @since Moodle 2.3
1164      */
1165     public static function duplicate_course($courseid, $fullname, $shortname, $categoryid, $visible = 1, $options = array()) {
1166         global $CFG, $USER, $DB;
1167         require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1168         require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1170         // Parameter validation.
1171         $params = self::validate_parameters(
1172                 self::duplicate_course_parameters(),
1173                 array(
1174                       'courseid' => $courseid,
1175                       'fullname' => $fullname,
1176                       'shortname' => $shortname,
1177                       'categoryid' => $categoryid,
1178                       'visible' => $visible,
1179                       'options' => $options
1180                 )
1181         );
1183         // Context validation.
1185         if (! ($course = $DB->get_record('course', array('id'=>$params['courseid'])))) {
1186             throw new moodle_exception('invalidcourseid', 'error');
1187         }
1189         // Category where duplicated course is going to be created.
1190         $categorycontext = context_coursecat::instance($params['categoryid']);
1191         self::validate_context($categorycontext);
1193         // Course to be duplicated.
1194         $coursecontext = context_course::instance($course->id);
1195         self::validate_context($coursecontext);
1197         $backupdefaults = array(
1198             'activities' => 1,
1199             'blocks' => 1,
1200             'filters' => 1,
1201             'users' => 0,
1202             'enrolments' => backup::ENROL_WITHUSERS,
1203             'role_assignments' => 0,
1204             'comments' => 0,
1205             'userscompletion' => 0,
1206             'logs' => 0,
1207             'grade_histories' => 0
1208         );
1210         $backupsettings = array();
1211         // Check for backup and restore options.
1212         if (!empty($params['options'])) {
1213             foreach ($params['options'] as $option) {
1215                 // Strict check for a correct value (allways 1 or 0, true or false).
1216                 $value = clean_param($option['value'], PARAM_INT);
1218                 if ($value !== 0 and $value !== 1) {
1219                     throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1220                 }
1222                 if (!isset($backupdefaults[$option['name']])) {
1223                     throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1224                 }
1226                 $backupsettings[$option['name']] = $value;
1227             }
1228         }
1230         // Capability checking.
1232         // The backup controller check for this currently, this may be redundant.
1233         require_capability('moodle/course:create', $categorycontext);
1234         require_capability('moodle/restore:restorecourse', $categorycontext);
1235         require_capability('moodle/backup:backupcourse', $coursecontext);
1237         if (!empty($backupsettings['users'])) {
1238             require_capability('moodle/backup:userinfo', $coursecontext);
1239             require_capability('moodle/restore:userinfo', $categorycontext);
1240         }
1242         // Check if the shortname is used.
1243         if ($foundcourses = $DB->get_records('course', array('shortname'=>$shortname))) {
1244             foreach ($foundcourses as $foundcourse) {
1245                 $foundcoursenames[] = $foundcourse->fullname;
1246             }
1248             $foundcoursenamestring = implode(',', $foundcoursenames);
1249             throw new moodle_exception('shortnametaken', '', '', $foundcoursenamestring);
1250         }
1252         // Backup the course.
1254         $bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE,
1255         backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id);
1257         foreach ($backupsettings as $name => $value) {
1258             if ($setting = $bc->get_plan()->get_setting($name)) {
1259                 $bc->get_plan()->get_setting($name)->set_value($value);
1260             }
1261         }
1263         $backupid       = $bc->get_backupid();
1264         $backupbasepath = $bc->get_plan()->get_basepath();
1266         $bc->execute_plan();
1267         $results = $bc->get_results();
1268         $file = $results['backup_destination'];
1270         $bc->destroy();
1272         // Restore the backup immediately.
1274         // Check if we need to unzip the file because the backup temp dir does not contains backup files.
1275         if (!file_exists($backupbasepath . "/moodle_backup.xml")) {
1276             $file->extract_to_pathname(get_file_packer('application/vnd.moodle.backup'), $backupbasepath);
1277         }
1279         // Create new course.
1280         $newcourseid = restore_dbops::create_new_course($params['fullname'], $params['shortname'], $params['categoryid']);
1282         $rc = new restore_controller($backupid, $newcourseid,
1283                 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id, backup::TARGET_NEW_COURSE);
1285         foreach ($backupsettings as $name => $value) {
1286             $setting = $rc->get_plan()->get_setting($name);
1287             if ($setting->get_status() == backup_setting::NOT_LOCKED) {
1288                 $setting->set_value($value);
1289             }
1290         }
1292         if (!$rc->execute_precheck()) {
1293             $precheckresults = $rc->get_precheck_results();
1294             if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1295                 if (empty($CFG->keeptempdirectoriesonbackup)) {
1296                     fulldelete($backupbasepath);
1297                 }
1299                 $errorinfo = '';
1301                 foreach ($precheckresults['errors'] as $error) {
1302                     $errorinfo .= $error;
1303                 }
1305                 if (array_key_exists('warnings', $precheckresults)) {
1306                     foreach ($precheckresults['warnings'] as $warning) {
1307                         $errorinfo .= $warning;
1308                     }
1309                 }
1311                 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1312             }
1313         }
1315         $rc->execute_plan();
1316         $rc->destroy();
1318         $course = $DB->get_record('course', array('id' => $newcourseid), '*', MUST_EXIST);
1319         $course->fullname = $params['fullname'];
1320         $course->shortname = $params['shortname'];
1321         $course->visible = $params['visible'];
1323         // Set shortname and fullname back.
1324         $DB->update_record('course', $course);
1326         if (empty($CFG->keeptempdirectoriesonbackup)) {
1327             fulldelete($backupbasepath);
1328         }
1330         // Delete the course backup file created by this WebService. Originally located in the course backups area.
1331         $file->delete();
1333         return array('id' => $course->id, 'shortname' => $course->shortname);
1334     }
1336     /**
1337      * Returns description of method result value
1338      *
1339      * @return external_description
1340      * @since Moodle 2.3
1341      */
1342     public static function duplicate_course_returns() {
1343         return new external_single_structure(
1344             array(
1345                 'id'       => new external_value(PARAM_INT, 'course id'),
1346                 'shortname' => new external_value(PARAM_TEXT, 'short name'),
1347             )
1348         );
1349     }
1351     /**
1352      * Returns description of method parameters for import_course
1353      *
1354      * @return external_function_parameters
1355      * @since Moodle 2.4
1356      */
1357     public static function import_course_parameters() {
1358         return new external_function_parameters(
1359             array(
1360                 'importfrom' => new external_value(PARAM_INT, 'the id of the course we are importing from'),
1361                 'importto' => new external_value(PARAM_INT, 'the id of the course we are importing to'),
1362                 'deletecontent' => new external_value(PARAM_INT, 'whether to delete the course content where we are importing to (default to 0 = No)', VALUE_DEFAULT, 0),
1363                 'options' => new external_multiple_structure(
1364                     new external_single_structure(
1365                         array(
1366                                 'name' => new external_value(PARAM_ALPHA, 'The backup option name:
1367                                             "activities" (int) Include course activites (default to 1 that is equal to yes),
1368                                             "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1369                                             "filters" (int) Include course filters  (default to 1 that is equal to yes)'
1370                                             ),
1371                                 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1372                             )
1373                         )
1374                     ), VALUE_DEFAULT, array()
1375                 ),
1376             )
1377         );
1378     }
1380     /**
1381      * Imports a course
1382      *
1383      * @param int $importfrom The id of the course we are importing from
1384      * @param int $importto The id of the course we are importing to
1385      * @param bool $deletecontent Whether to delete the course we are importing to content
1386      * @param array $options List of backup options
1387      * @return null
1388      * @since Moodle 2.4
1389      */
1390     public static function import_course($importfrom, $importto, $deletecontent = 0, $options = array()) {
1391         global $CFG, $USER, $DB;
1392         require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1393         require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1395         // Parameter validation.
1396         $params = self::validate_parameters(
1397             self::import_course_parameters(),
1398             array(
1399                 'importfrom' => $importfrom,
1400                 'importto' => $importto,
1401                 'deletecontent' => $deletecontent,
1402                 'options' => $options
1403             )
1404         );
1406         if ($params['deletecontent'] !== 0 and $params['deletecontent'] !== 1) {
1407             throw new moodle_exception('invalidextparam', 'webservice', '', $params['deletecontent']);
1408         }
1410         // Context validation.
1412         if (! ($importfrom = $DB->get_record('course', array('id'=>$params['importfrom'])))) {
1413             throw new moodle_exception('invalidcourseid', 'error');
1414         }
1416         if (! ($importto = $DB->get_record('course', array('id'=>$params['importto'])))) {
1417             throw new moodle_exception('invalidcourseid', 'error');
1418         }
1420         $importfromcontext = context_course::instance($importfrom->id);
1421         self::validate_context($importfromcontext);
1423         $importtocontext = context_course::instance($importto->id);
1424         self::validate_context($importtocontext);
1426         $backupdefaults = array(
1427             'activities' => 1,
1428             'blocks' => 1,
1429             'filters' => 1
1430         );
1432         $backupsettings = array();
1434         // Check for backup and restore options.
1435         if (!empty($params['options'])) {
1436             foreach ($params['options'] as $option) {
1438                 // Strict check for a correct value (allways 1 or 0, true or false).
1439                 $value = clean_param($option['value'], PARAM_INT);
1441                 if ($value !== 0 and $value !== 1) {
1442                     throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1443                 }
1445                 if (!isset($backupdefaults[$option['name']])) {
1446                     throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1447                 }
1449                 $backupsettings[$option['name']] = $value;
1450             }
1451         }
1453         // Capability checking.
1455         require_capability('moodle/backup:backuptargetimport', $importfromcontext);
1456         require_capability('moodle/restore:restoretargetimport', $importtocontext);
1458         $bc = new backup_controller(backup::TYPE_1COURSE, $importfrom->id, backup::FORMAT_MOODLE,
1459                 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
1461         foreach ($backupsettings as $name => $value) {
1462             $bc->get_plan()->get_setting($name)->set_value($value);
1463         }
1465         $backupid       = $bc->get_backupid();
1466         $backupbasepath = $bc->get_plan()->get_basepath();
1468         $bc->execute_plan();
1469         $bc->destroy();
1471         // Restore the backup immediately.
1473         // Check if we must delete the contents of the destination course.
1474         if ($params['deletecontent']) {
1475             $restoretarget = backup::TARGET_EXISTING_DELETING;
1476         } else {
1477             $restoretarget = backup::TARGET_EXISTING_ADDING;
1478         }
1480         $rc = new restore_controller($backupid, $importto->id,
1481                 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, $restoretarget);
1483         foreach ($backupsettings as $name => $value) {
1484             $rc->get_plan()->get_setting($name)->set_value($value);
1485         }
1487         if (!$rc->execute_precheck()) {
1488             $precheckresults = $rc->get_precheck_results();
1489             if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1490                 if (empty($CFG->keeptempdirectoriesonbackup)) {
1491                     fulldelete($backupbasepath);
1492                 }
1494                 $errorinfo = '';
1496                 foreach ($precheckresults['errors'] as $error) {
1497                     $errorinfo .= $error;
1498                 }
1500                 if (array_key_exists('warnings', $precheckresults)) {
1501                     foreach ($precheckresults['warnings'] as $warning) {
1502                         $errorinfo .= $warning;
1503                     }
1504                 }
1506                 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1507             }
1508         } else {
1509             if ($restoretarget == backup::TARGET_EXISTING_DELETING) {
1510                 restore_dbops::delete_course_content($importto->id);
1511             }
1512         }
1514         $rc->execute_plan();
1515         $rc->destroy();
1517         if (empty($CFG->keeptempdirectoriesonbackup)) {
1518             fulldelete($backupbasepath);
1519         }
1521         return null;
1522     }
1524     /**
1525      * Returns description of method result value
1526      *
1527      * @return external_description
1528      * @since Moodle 2.4
1529      */
1530     public static function import_course_returns() {
1531         return null;
1532     }
1534     /**
1535      * Returns description of method parameters
1536      *
1537      * @return external_function_parameters
1538      * @since Moodle 2.3
1539      */
1540     public static function get_categories_parameters() {
1541         return new external_function_parameters(
1542             array(
1543                 'criteria' => new external_multiple_structure(
1544                     new external_single_structure(
1545                         array(
1546                             'key' => new external_value(PARAM_ALPHA,
1547                                          'The category column to search, expected keys (value format) are:'.
1548                                          '"id" (int) the category id,'.
1549                                          '"ids" (string) category ids separated by commas,'.
1550                                          '"name" (string) the category name,'.
1551                                          '"parent" (int) the parent category id,'.
1552                                          '"idnumber" (string) category idnumber'.
1553                                          ' - user must have \'moodle/category:manage\' to search on idnumber,'.
1554                                          '"visible" (int) whether the returned categories must be visible or hidden. If the key is not passed,
1555                                              then the function return all categories that the user can see.'.
1556                                          ' - user must have \'moodle/category:manage\' or \'moodle/category:viewhiddencategories\' to search on visible,'.
1557                                          '"theme" (string) only return the categories having this theme'.
1558                                          ' - user must have \'moodle/category:manage\' to search on theme'),
1559                             'value' => new external_value(PARAM_RAW, 'the value to match')
1560                         )
1561                     ), 'criteria', VALUE_DEFAULT, array()
1562                 ),
1563                 'addsubcategories' => new external_value(PARAM_BOOL, 'return the sub categories infos
1564                                           (1 - default) otherwise only the category info (0)', VALUE_DEFAULT, 1)
1565             )
1566         );
1567     }
1569     /**
1570      * Get categories
1571      *
1572      * @param array $criteria Criteria to match the results
1573      * @param booln $addsubcategories obtain only the category (false) or its subcategories (true - default)
1574      * @return array list of categories
1575      * @since Moodle 2.3
1576      */
1577     public static function get_categories($criteria = array(), $addsubcategories = true) {
1578         global $CFG, $DB;
1579         require_once($CFG->dirroot . "/course/lib.php");
1581         // Validate parameters.
1582         $params = self::validate_parameters(self::get_categories_parameters(),
1583                 array('criteria' => $criteria, 'addsubcategories' => $addsubcategories));
1585         // Retrieve the categories.
1586         $categories = array();
1587         if (!empty($params['criteria'])) {
1589             $conditions = array();
1590             $wheres = array();
1591             foreach ($params['criteria'] as $crit) {
1592                 $key = trim($crit['key']);
1594                 // Trying to avoid duplicate keys.
1595                 if (!isset($conditions[$key])) {
1597                     $context = context_system::instance();
1598                     $value = null;
1599                     switch ($key) {
1600                         case 'id':
1601                             $value = clean_param($crit['value'], PARAM_INT);
1602                             $conditions[$key] = $value;
1603                             $wheres[] = $key . " = :" . $key;
1604                             break;
1606                         case 'ids':
1607                             $value = clean_param($crit['value'], PARAM_SEQUENCE);
1608                             $ids = explode(',', $value);
1609                             list($sqlids, $paramids) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED);
1610                             $conditions = array_merge($conditions, $paramids);
1611                             $wheres[] = 'id ' . $sqlids;
1612                             break;
1614                         case 'idnumber':
1615                             if (has_capability('moodle/category:manage', $context)) {
1616                                 $value = clean_param($crit['value'], PARAM_RAW);
1617                                 $conditions[$key] = $value;
1618                                 $wheres[] = $key . " = :" . $key;
1619                             } else {
1620                                 // We must throw an exception.
1621                                 // Otherwise the dev client would think no idnumber exists.
1622                                 throw new moodle_exception('criteriaerror',
1623                                         'webservice', '', null,
1624                                         'You don\'t have the permissions to search on the "idnumber" field.');
1625                             }
1626                             break;
1628                         case 'name':
1629                             $value = clean_param($crit['value'], PARAM_TEXT);
1630                             $conditions[$key] = $value;
1631                             $wheres[] = $key . " = :" . $key;
1632                             break;
1634                         case 'parent':
1635                             $value = clean_param($crit['value'], PARAM_INT);
1636                             $conditions[$key] = $value;
1637                             $wheres[] = $key . " = :" . $key;
1638                             break;
1640                         case 'visible':
1641                             if (has_capability('moodle/category:viewhiddencategories', $context)) {
1642                                 $value = clean_param($crit['value'], PARAM_INT);
1643                                 $conditions[$key] = $value;
1644                                 $wheres[] = $key . " = :" . $key;
1645                             } else {
1646                                 throw new moodle_exception('criteriaerror',
1647                                         'webservice', '', null,
1648                                         'You don\'t have the permissions to search on the "visible" field.');
1649                             }
1650                             break;
1652                         case 'theme':
1653                             if (has_capability('moodle/category:manage', $context)) {
1654                                 $value = clean_param($crit['value'], PARAM_THEME);
1655                                 $conditions[$key] = $value;
1656                                 $wheres[] = $key . " = :" . $key;
1657                             } else {
1658                                 throw new moodle_exception('criteriaerror',
1659                                         'webservice', '', null,
1660                                         'You don\'t have the permissions to search on the "theme" field.');
1661                             }
1662                             break;
1664                         default:
1665                             throw new moodle_exception('criteriaerror',
1666                                     'webservice', '', null,
1667                                     'You can not search on this criteria: ' . $key);
1668                     }
1669                 }
1670             }
1672             if (!empty($wheres)) {
1673                 $wheres = implode(" AND ", $wheres);
1675                 $categories = $DB->get_records_select('course_categories', $wheres, $conditions);
1677                 // Retrieve its sub subcategories (all levels).
1678                 if ($categories and !empty($params['addsubcategories'])) {
1679                     $newcategories = array();
1681                     // Check if we required visible/theme checks.
1682                     $additionalselect = '';
1683                     $additionalparams = array();
1684                     if (isset($conditions['visible'])) {
1685                         $additionalselect .= ' AND visible = :visible';
1686                         $additionalparams['visible'] = $conditions['visible'];
1687                     }
1688                     if (isset($conditions['theme'])) {
1689                         $additionalselect .= ' AND theme= :theme';
1690                         $additionalparams['theme'] = $conditions['theme'];
1691                     }
1693                     foreach ($categories as $category) {
1694                         $sqlselect = $DB->sql_like('path', ':path') . $additionalselect;
1695                         $sqlparams = array('path' => $category->path.'/%') + $additionalparams; // It will NOT include the specified category.
1696                         $subcategories = $DB->get_records_select('course_categories', $sqlselect, $sqlparams);
1697                         $newcategories = $newcategories + $subcategories;   // Both arrays have integer as keys.
1698                     }
1699                     $categories = $categories + $newcategories;
1700                 }
1701             }
1703         } else {
1704             // Retrieve all categories in the database.
1705             $categories = $DB->get_records('course_categories');
1706         }
1708         // The not returned categories. key => category id, value => reason of exclusion.
1709         $excludedcats = array();
1711         // The returned categories.
1712         $categoriesinfo = array();
1714         // We need to sort the categories by path.
1715         // The parent cats need to be checked by the algo first.
1716         usort($categories, "core_course_external::compare_categories_by_path");
1718         foreach ($categories as $category) {
1720             // Check if the category is a child of an excluded category, if yes exclude it too (excluded => do not return).
1721             $parents = explode('/', $category->path);
1722             unset($parents[0]); // First key is always empty because path start with / => /1/2/4.
1723             foreach ($parents as $parentid) {
1724                 // Note: when the parent exclusion was due to the context,
1725                 // the sub category could still be returned.
1726                 if (isset($excludedcats[$parentid]) and $excludedcats[$parentid] != 'context') {
1727                     $excludedcats[$category->id] = 'parent';
1728                 }
1729             }
1731             // Check the user can use the category context.
1732             $context = context_coursecat::instance($category->id);
1733             try {
1734                 self::validate_context($context);
1735             } catch (Exception $e) {
1736                 $excludedcats[$category->id] = 'context';
1738                 // If it was the requested category then throw an exception.
1739                 if (isset($params['categoryid']) && $category->id == $params['categoryid']) {
1740                     $exceptionparam = new stdClass();
1741                     $exceptionparam->message = $e->getMessage();
1742                     $exceptionparam->catid = $category->id;
1743                     throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
1744                 }
1745             }
1747             // Return the category information.
1748             if (!isset($excludedcats[$category->id])) {
1750                 // Final check to see if the category is visible to the user.
1751                 if ($category->visible or has_capability('moodle/category:viewhiddencategories', $context)) {
1753                     $categoryinfo = array();
1754                     $categoryinfo['id'] = $category->id;
1755                     $categoryinfo['name'] = external_format_string($category->name, $context);
1756                     list($categoryinfo['description'], $categoryinfo['descriptionformat']) =
1757                         external_format_text($category->description, $category->descriptionformat,
1758                                 $context->id, 'coursecat', 'description', null);
1759                     $categoryinfo['parent'] = $category->parent;
1760                     $categoryinfo['sortorder'] = $category->sortorder;
1761                     $categoryinfo['coursecount'] = $category->coursecount;
1762                     $categoryinfo['depth'] = $category->depth;
1763                     $categoryinfo['path'] = $category->path;
1765                     // Some fields only returned for admin.
1766                     if (has_capability('moodle/category:manage', $context)) {
1767                         $categoryinfo['idnumber'] = $category->idnumber;
1768                         $categoryinfo['visible'] = $category->visible;
1769                         $categoryinfo['visibleold'] = $category->visibleold;
1770                         $categoryinfo['timemodified'] = $category->timemodified;
1771                         $categoryinfo['theme'] = clean_param($category->theme, PARAM_THEME);
1772                     }
1774                     $categoriesinfo[] = $categoryinfo;
1775                 } else {
1776                     $excludedcats[$category->id] = 'visibility';
1777                 }
1778             }
1779         }
1781         // Sorting the resulting array so it looks a bit better for the client developer.
1782         usort($categoriesinfo, "core_course_external::compare_categories_by_sortorder");
1784         return $categoriesinfo;
1785     }
1787     /**
1788      * Sort categories array by path
1789      * private function: only used by get_categories
1790      *
1791      * @param array $category1
1792      * @param array $category2
1793      * @return int result of strcmp
1794      * @since Moodle 2.3
1795      */
1796     private static function compare_categories_by_path($category1, $category2) {
1797         return strcmp($category1->path, $category2->path);
1798     }
1800     /**
1801      * Sort categories array by sortorder
1802      * private function: only used by get_categories
1803      *
1804      * @param array $category1
1805      * @param array $category2
1806      * @return int result of strcmp
1807      * @since Moodle 2.3
1808      */
1809     private static function compare_categories_by_sortorder($category1, $category2) {
1810         return strcmp($category1['sortorder'], $category2['sortorder']);
1811     }
1813     /**
1814      * Returns description of method result value
1815      *
1816      * @return external_description
1817      * @since Moodle 2.3
1818      */
1819     public static function get_categories_returns() {
1820         return new external_multiple_structure(
1821             new external_single_structure(
1822                 array(
1823                     'id' => new external_value(PARAM_INT, 'category id'),
1824                     'name' => new external_value(PARAM_TEXT, 'category name'),
1825                     'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1826                     'description' => new external_value(PARAM_RAW, 'category description'),
1827                     'descriptionformat' => new external_format_value('description'),
1828                     'parent' => new external_value(PARAM_INT, 'parent category id'),
1829                     'sortorder' => new external_value(PARAM_INT, 'category sorting order'),
1830                     'coursecount' => new external_value(PARAM_INT, 'number of courses in this category'),
1831                     'visible' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1832                     'visibleold' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1833                     'timemodified' => new external_value(PARAM_INT, 'timestamp', VALUE_OPTIONAL),
1834                     'depth' => new external_value(PARAM_INT, 'category depth'),
1835                     'path' => new external_value(PARAM_TEXT, 'category path'),
1836                     'theme' => new external_value(PARAM_THEME, 'category theme', VALUE_OPTIONAL),
1837                 ), 'List of categories'
1838             )
1839         );
1840     }
1842     /**
1843      * Returns description of method parameters
1844      *
1845      * @return external_function_parameters
1846      * @since Moodle 2.3
1847      */
1848     public static function create_categories_parameters() {
1849         return new external_function_parameters(
1850             array(
1851                 'categories' => new external_multiple_structure(
1852                         new external_single_structure(
1853                             array(
1854                                 'name' => new external_value(PARAM_TEXT, 'new category name'),
1855                                 'parent' => new external_value(PARAM_INT,
1856                                         'the parent category id inside which the new category will be created
1857                                          - set to 0 for a root category',
1858                                         VALUE_DEFAULT, 0),
1859                                 'idnumber' => new external_value(PARAM_RAW,
1860                                         'the new category idnumber', VALUE_OPTIONAL),
1861                                 'description' => new external_value(PARAM_RAW,
1862                                         'the new category description', VALUE_OPTIONAL),
1863                                 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
1864                                 'theme' => new external_value(PARAM_THEME,
1865                                         'the new category theme. This option must be enabled on moodle',
1866                                         VALUE_OPTIONAL),
1867                         )
1868                     )
1869                 )
1870             )
1871         );
1872     }
1874     /**
1875      * Create categories
1876      *
1877      * @param array $categories - see create_categories_parameters() for the array structure
1878      * @return array - see create_categories_returns() for the array structure
1879      * @since Moodle 2.3
1880      */
1881     public static function create_categories($categories) {
1882         global $DB;
1884         $params = self::validate_parameters(self::create_categories_parameters(),
1885                         array('categories' => $categories));
1887         $transaction = $DB->start_delegated_transaction();
1889         $createdcategories = array();
1890         foreach ($params['categories'] as $category) {
1891             if ($category['parent']) {
1892                 if (!$DB->record_exists('course_categories', array('id' => $category['parent']))) {
1893                     throw new moodle_exception('unknowcategory');
1894                 }
1895                 $context = context_coursecat::instance($category['parent']);
1896             } else {
1897                 $context = context_system::instance();
1898             }
1899             self::validate_context($context);
1900             require_capability('moodle/category:manage', $context);
1902             // this will validate format and throw an exception if there are errors
1903             external_validate_format($category['descriptionformat']);
1905             $newcategory = core_course_category::create($category);
1906             $context = context_coursecat::instance($newcategory->id);
1908             $createdcategories[] = array(
1909                 'id' => $newcategory->id,
1910                 'name' => external_format_string($newcategory->name, $context),
1911             );
1912         }
1914         $transaction->allow_commit();
1916         return $createdcategories;
1917     }
1919     /**
1920      * Returns description of method parameters
1921      *
1922      * @return external_function_parameters
1923      * @since Moodle 2.3
1924      */
1925     public static function create_categories_returns() {
1926         return new external_multiple_structure(
1927             new external_single_structure(
1928                 array(
1929                     'id' => new external_value(PARAM_INT, 'new category id'),
1930                     'name' => new external_value(PARAM_TEXT, 'new category name'),
1931                 )
1932             )
1933         );
1934     }
1936     /**
1937      * Returns description of method parameters
1938      *
1939      * @return external_function_parameters
1940      * @since Moodle 2.3
1941      */
1942     public static function update_categories_parameters() {
1943         return new external_function_parameters(
1944             array(
1945                 'categories' => new external_multiple_structure(
1946                     new external_single_structure(
1947                         array(
1948                             'id'       => new external_value(PARAM_INT, 'course id'),
1949                             'name' => new external_value(PARAM_TEXT, 'category name', VALUE_OPTIONAL),
1950                             'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1951                             'parent' => new external_value(PARAM_INT, 'parent category id', VALUE_OPTIONAL),
1952                             'description' => new external_value(PARAM_RAW, 'category description', VALUE_OPTIONAL),
1953                             'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
1954                             'theme' => new external_value(PARAM_THEME,
1955                                     'the category theme. This option must be enabled on moodle', VALUE_OPTIONAL),
1956                         )
1957                     )
1958                 )
1959             )
1960         );
1961     }
1963     /**
1964      * Update categories
1965      *
1966      * @param array $categories The list of categories to update
1967      * @return null
1968      * @since Moodle 2.3
1969      */
1970     public static function update_categories($categories) {
1971         global $DB;
1973         // Validate parameters.
1974         $params = self::validate_parameters(self::update_categories_parameters(), array('categories' => $categories));
1976         $transaction = $DB->start_delegated_transaction();
1978         foreach ($params['categories'] as $cat) {
1979             $category = core_course_category::get($cat['id']);
1981             $categorycontext = context_coursecat::instance($cat['id']);
1982             self::validate_context($categorycontext);
1983             require_capability('moodle/category:manage', $categorycontext);
1985             // this will throw an exception if descriptionformat is not valid
1986             external_validate_format($cat['descriptionformat']);
1988             $category->update($cat);
1989         }
1991         $transaction->allow_commit();
1992     }
1994     /**
1995      * Returns description of method result value
1996      *
1997      * @return external_description
1998      * @since Moodle 2.3
1999      */
2000     public static function update_categories_returns() {
2001         return null;
2002     }
2004     /**
2005      * Returns description of method parameters
2006      *
2007      * @return external_function_parameters
2008      * @since Moodle 2.3
2009      */
2010     public static function delete_categories_parameters() {
2011         return new external_function_parameters(
2012             array(
2013                 'categories' => new external_multiple_structure(
2014                     new external_single_structure(
2015                         array(
2016                             'id' => new external_value(PARAM_INT, 'category id to delete'),
2017                             'newparent' => new external_value(PARAM_INT,
2018                                 'the parent category to move the contents to, if specified', VALUE_OPTIONAL),
2019                             'recursive' => new external_value(PARAM_BOOL, '1: recursively delete all contents inside this
2020                                 category, 0 (default): move contents to newparent or current parent category (except if parent is root)', VALUE_DEFAULT, 0)
2021                         )
2022                     )
2023                 )
2024             )
2025         );
2026     }
2028     /**
2029      * Delete categories
2030      *
2031      * @param array $categories A list of category ids
2032      * @return array
2033      * @since Moodle 2.3
2034      */
2035     public static function delete_categories($categories) {
2036         global $CFG, $DB;
2037         require_once($CFG->dirroot . "/course/lib.php");
2039         // Validate parameters.
2040         $params = self::validate_parameters(self::delete_categories_parameters(), array('categories' => $categories));
2042         $transaction = $DB->start_delegated_transaction();
2044         foreach ($params['categories'] as $category) {
2045             $deletecat = core_course_category::get($category['id'], MUST_EXIST);
2046             $context = context_coursecat::instance($deletecat->id);
2047             require_capability('moodle/category:manage', $context);
2048             self::validate_context($context);
2049             self::validate_context(get_category_or_system_context($deletecat->parent));
2051             if ($category['recursive']) {
2052                 // If recursive was specified, then we recursively delete the category's contents.
2053                 if ($deletecat->can_delete_full()) {
2054                     $deletecat->delete_full(false);
2055                 } else {
2056                     throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2057                 }
2058             } else {
2059                 // In this situation, we don't delete the category's contents, we either move it to newparent or parent.
2060                 // If the parent is the root, moving is not supported (because a course must always be inside a category).
2061                 // We must move to an existing category.
2062                 if (!empty($category['newparent'])) {
2063                     $newparentcat = core_course_category::get($category['newparent']);
2064                 } else {
2065                     $newparentcat = core_course_category::get($deletecat->parent);
2066                 }
2068                 // This operation is not allowed. We must move contents to an existing category.
2069                 if (!$newparentcat->id) {
2070                     throw new moodle_exception('movecatcontentstoroot');
2071                 }
2073                 self::validate_context(context_coursecat::instance($newparentcat->id));
2074                 if ($deletecat->can_move_content_to($newparentcat->id)) {
2075                     $deletecat->delete_move($newparentcat->id, false);
2076                 } else {
2077                     throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2078                 }
2079             }
2080         }
2082         $transaction->allow_commit();
2083     }
2085     /**
2086      * Returns description of method parameters
2087      *
2088      * @return external_function_parameters
2089      * @since Moodle 2.3
2090      */
2091     public static function delete_categories_returns() {
2092         return null;
2093     }
2095     /**
2096      * Describes the parameters for delete_modules.
2097      *
2098      * @return external_function_parameters
2099      * @since Moodle 2.5
2100      */
2101     public static function delete_modules_parameters() {
2102         return new external_function_parameters (
2103             array(
2104                 'cmids' => new external_multiple_structure(new external_value(PARAM_INT, 'course module ID',
2105                         VALUE_REQUIRED, '', NULL_NOT_ALLOWED), 'Array of course module IDs'),
2106             )
2107         );
2108     }
2110     /**
2111      * Deletes a list of provided module instances.
2112      *
2113      * @param array $cmids the course module ids
2114      * @since Moodle 2.5
2115      */
2116     public static function delete_modules($cmids) {
2117         global $CFG, $DB;
2119         // Require course file containing the course delete module function.
2120         require_once($CFG->dirroot . "/course/lib.php");
2122         // Clean the parameters.
2123         $params = self::validate_parameters(self::delete_modules_parameters(), array('cmids' => $cmids));
2125         // Keep track of the course ids we have performed a capability check on to avoid repeating.
2126         $arrcourseschecked = array();
2128         foreach ($params['cmids'] as $cmid) {
2129             // Get the course module.
2130             $cm = $DB->get_record('course_modules', array('id' => $cmid), '*', MUST_EXIST);
2132             // Check if we have not yet confirmed they have permission in this course.
2133             if (!in_array($cm->course, $arrcourseschecked)) {
2134                 // Ensure the current user has required permission in this course.
2135                 $context = context_course::instance($cm->course);
2136                 self::validate_context($context);
2137                 // Add to the array.
2138                 $arrcourseschecked[] = $cm->course;
2139             }
2141             // Ensure they can delete this module.
2142             $modcontext = context_module::instance($cm->id);
2143             require_capability('moodle/course:manageactivities', $modcontext);
2145             // Delete the module.
2146             course_delete_module($cm->id);
2147         }
2148     }
2150     /**
2151      * Describes the delete_modules return value.
2152      *
2153      * @return external_single_structure
2154      * @since Moodle 2.5
2155      */
2156     public static function delete_modules_returns() {
2157         return null;
2158     }
2160     /**
2161      * Returns description of method parameters
2162      *
2163      * @return external_function_parameters
2164      * @since Moodle 2.9
2165      */
2166     public static function view_course_parameters() {
2167         return new external_function_parameters(
2168             array(
2169                 'courseid' => new external_value(PARAM_INT, 'id of the course'),
2170                 'sectionnumber' => new external_value(PARAM_INT, 'section number', VALUE_DEFAULT, 0)
2171             )
2172         );
2173     }
2175     /**
2176      * Trigger the course viewed event.
2177      *
2178      * @param int $courseid id of course
2179      * @param int $sectionnumber sectionnumber (0, 1, 2...)
2180      * @return array of warnings and status result
2181      * @since Moodle 2.9
2182      * @throws moodle_exception
2183      */
2184     public static function view_course($courseid, $sectionnumber = 0) {
2185         global $CFG;
2186         require_once($CFG->dirroot . "/course/lib.php");
2188         $params = self::validate_parameters(self::view_course_parameters(),
2189                                             array(
2190                                                 'courseid' => $courseid,
2191                                                 'sectionnumber' => $sectionnumber
2192                                             ));
2194         $warnings = array();
2196         $course = get_course($params['courseid']);
2197         $context = context_course::instance($course->id);
2198         self::validate_context($context);
2200         if (!empty($params['sectionnumber'])) {
2202             // Get section details and check it exists.
2203             $modinfo = get_fast_modinfo($course);
2204             $coursesection = $modinfo->get_section_info($params['sectionnumber'], MUST_EXIST);
2206             // Check user is allowed to see it.
2207             if (!$coursesection->uservisible) {
2208                 require_capability('moodle/course:viewhiddensections', $context);
2209             }
2210         }
2212         course_view($context, $params['sectionnumber']);
2214         $result = array();
2215         $result['status'] = true;
2216         $result['warnings'] = $warnings;
2217         return $result;
2218     }
2220     /**
2221      * Returns description of method result value
2222      *
2223      * @return external_description
2224      * @since Moodle 2.9
2225      */
2226     public static function view_course_returns() {
2227         return new external_single_structure(
2228             array(
2229                 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
2230                 'warnings' => new external_warnings()
2231             )
2232         );
2233     }
2235     /**
2236      * Returns description of method parameters
2237      *
2238      * @return external_function_parameters
2239      * @since Moodle 3.0
2240      */
2241     public static function search_courses_parameters() {
2242         return new external_function_parameters(
2243             array(
2244                 'criterianame'  => new external_value(PARAM_ALPHA, 'criteria name
2245                                                         (search, modulelist (only admins), blocklist (only admins), tagid)'),
2246                 'criteriavalue' => new external_value(PARAM_RAW, 'criteria value'),
2247                 'page'          => new external_value(PARAM_INT, 'page number (0 based)', VALUE_DEFAULT, 0),
2248                 'perpage'       => new external_value(PARAM_INT, 'items per page', VALUE_DEFAULT, 0),
2249                 'requiredcapabilities' => new external_multiple_structure(
2250                     new external_value(PARAM_CAPABILITY, 'Capability string used to filter courses by permission'),
2251                     'Optional list of required capabilities (used to filter the list)', VALUE_DEFAULT, array()
2252                 ),
2253                 'limittoenrolled' => new external_value(PARAM_BOOL, 'limit to enrolled courses', VALUE_DEFAULT, 0),
2254             )
2255         );
2256     }
2258     /**
2259      * Return the course information that is public (visible by every one)
2260      *
2261      * @param  core_course_list_element $course        course in list object
2262      * @param  stdClass       $coursecontext course context object
2263      * @return array the course information
2264      * @since  Moodle 3.2
2265      */
2266     protected static function get_course_public_information(core_course_list_element $course, $coursecontext) {
2268         static $categoriescache = array();
2270         // Category information.
2271         if (!array_key_exists($course->category, $categoriescache)) {
2272             $categoriescache[$course->category] = core_course_category::get($course->category, IGNORE_MISSING);
2273         }
2274         $category = $categoriescache[$course->category];
2276         // Retrieve course overview used files.
2277         $files = array();
2278         foreach ($course->get_course_overviewfiles() as $file) {
2279             $fileurl = moodle_url::make_webservice_pluginfile_url($file->get_contextid(), $file->get_component(),
2280                                                                     $file->get_filearea(), null, $file->get_filepath(),
2281                                                                     $file->get_filename())->out(false);
2282             $files[] = array(
2283                 'filename' => $file->get_filename(),
2284                 'fileurl' => $fileurl,
2285                 'filesize' => $file->get_filesize(),
2286                 'filepath' => $file->get_filepath(),
2287                 'mimetype' => $file->get_mimetype(),
2288                 'timemodified' => $file->get_timemodified(),
2289             );
2290         }
2292         // Retrieve the course contacts,
2293         // we need here the users fullname since if we are not enrolled can be difficult to obtain them via other Web Services.
2294         $coursecontacts = array();
2295         foreach ($course->get_course_contacts() as $contact) {
2296              $coursecontacts[] = array(
2297                 'id' => $contact['user']->id,
2298                 'fullname' => $contact['username'],
2299                 'roles' => array_map(function($role){
2300                     return array('id' => $role->id, 'name' => $role->displayname);
2301                 }, $contact['roles']),
2302                 'role' => array('id' => $contact['role']->id, 'name' => $contact['role']->displayname),
2303                 'rolename' => $contact['rolename']
2304              );
2305         }
2307         // Allowed enrolment methods (maybe we can self-enrol).
2308         $enroltypes = array();
2309         $instances = enrol_get_instances($course->id, true);
2310         foreach ($instances as $instance) {
2311             $enroltypes[] = $instance->enrol;
2312         }
2314         // Format summary.
2315         list($summary, $summaryformat) =
2316             external_format_text($course->summary, $course->summaryformat, $coursecontext->id, 'course', 'summary', null);
2318         $categoryname = '';
2319         if (!empty($category)) {
2320             $categoryname = external_format_string($category->name, $category->get_context());
2321         }
2323         $displayname = get_course_display_name_for_list($course);
2324         $coursereturns = array();
2325         $coursereturns['id']                = $course->id;
2326         $coursereturns['fullname']          = external_format_string($course->fullname, $coursecontext->id);
2327         $coursereturns['displayname']       = external_format_string($displayname, $coursecontext->id);
2328         $coursereturns['shortname']         = external_format_string($course->shortname, $coursecontext->id);
2329         $coursereturns['categoryid']        = $course->category;
2330         $coursereturns['categoryname']      = $categoryname;
2331         $coursereturns['summary']           = $summary;
2332         $coursereturns['summaryformat']     = $summaryformat;
2333         $coursereturns['summaryfiles']      = external_util::get_area_files($coursecontext->id, 'course', 'summary', false, false);
2334         $coursereturns['overviewfiles']     = $files;
2335         $coursereturns['contacts']          = $coursecontacts;
2336         $coursereturns['enrollmentmethods'] = $enroltypes;
2337         $coursereturns['sortorder']         = $course->sortorder;
2338         return $coursereturns;
2339     }
2341     /**
2342      * Search courses following the specified criteria.
2343      *
2344      * @param string $criterianame  Criteria name (search, modulelist (only admins), blocklist (only admins), tagid)
2345      * @param string $criteriavalue Criteria value
2346      * @param int $page             Page number (for pagination)
2347      * @param int $perpage          Items per page
2348      * @param array $requiredcapabilities Optional list of required capabilities (used to filter the list).
2349      * @param int $limittoenrolled  Limit to only enrolled courses
2350      * @return array of course objects and warnings
2351      * @since Moodle 3.0
2352      * @throws moodle_exception
2353      */
2354     public static function search_courses($criterianame,
2355                                           $criteriavalue,
2356                                           $page=0,
2357                                           $perpage=0,
2358                                           $requiredcapabilities=array(),
2359                                           $limittoenrolled=0) {
2360         global $CFG;
2362         $warnings = array();
2364         $parameters = array(
2365             'criterianame'  => $criterianame,
2366             'criteriavalue' => $criteriavalue,
2367             'page'          => $page,
2368             'perpage'       => $perpage,
2369             'requiredcapabilities' => $requiredcapabilities
2370         );
2371         $params = self::validate_parameters(self::search_courses_parameters(), $parameters);
2372         self::validate_context(context_system::instance());
2374         $allowedcriterianames = array('search', 'modulelist', 'blocklist', 'tagid');
2375         if (!in_array($params['criterianame'], $allowedcriterianames)) {
2376             throw new invalid_parameter_exception('Invalid value for criterianame parameter (value: '.$params['criterianame'].'),' .
2377                 'allowed values are: '.implode(',', $allowedcriterianames));
2378         }
2380         if ($params['criterianame'] == 'modulelist' or $params['criterianame'] == 'blocklist') {
2381             require_capability('moodle/site:config', context_system::instance());
2382         }
2384         $paramtype = array(
2385             'search' => PARAM_RAW,
2386             'modulelist' => PARAM_PLUGIN,
2387             'blocklist' => PARAM_INT,
2388             'tagid' => PARAM_INT
2389         );
2390         $params['criteriavalue'] = clean_param($params['criteriavalue'], $paramtype[$params['criterianame']]);
2392         // Prepare the search API options.
2393         $searchcriteria = array();
2394         $searchcriteria[$params['criterianame']] = $params['criteriavalue'];
2396         $options = array();
2397         if ($params['perpage'] != 0) {
2398             $offset = $params['page'] * $params['perpage'];
2399             $options = array('offset' => $offset, 'limit' => $params['perpage']);
2400         }
2402         // Search the courses.
2403         $courses = core_course_category::search_courses($searchcriteria, $options, $params['requiredcapabilities']);
2404         $totalcount = core_course_category::search_courses_count($searchcriteria, $options, $params['requiredcapabilities']);
2406         if (!empty($limittoenrolled)) {
2407             // Get the courses where the current user has access.
2408             $enrolled = enrol_get_my_courses(array('id', 'cacherev'));
2409         }
2411         $finalcourses = array();
2412         $categoriescache = array();
2414         foreach ($courses as $course) {
2415             if (!empty($limittoenrolled)) {
2416                 // Filter out not enrolled courses.
2417                 if (!isset($enrolled[$course->id])) {
2418                     $totalcount--;
2419                     continue;
2420                 }
2421             }
2423             $coursecontext = context_course::instance($course->id);
2425             $finalcourses[] = self::get_course_public_information($course, $coursecontext);
2426         }
2428         return array(
2429             'total' => $totalcount,
2430             'courses' => $finalcourses,
2431             'warnings' => $warnings
2432         );
2433     }
2435     /**
2436      * Returns a course structure definition
2437      *
2438      * @param  boolean $onlypublicdata set to true, to retrieve only fields viewable by anyone when the course is visible
2439      * @return array the course structure
2440      * @since  Moodle 3.2
2441      */
2442     protected static function get_course_structure($onlypublicdata = true) {
2443         $coursestructure = array(
2444             'id' => new external_value(PARAM_INT, 'course id'),
2445             'fullname' => new external_value(PARAM_TEXT, 'course full name'),
2446             'displayname' => new external_value(PARAM_TEXT, 'course display name'),
2447             'shortname' => new external_value(PARAM_TEXT, 'course short name'),
2448             'categoryid' => new external_value(PARAM_INT, 'category id'),
2449             'categoryname' => new external_value(PARAM_TEXT, 'category name'),
2450             'sortorder' => new external_value(PARAM_INT, 'Sort order in the category', VALUE_OPTIONAL),
2451             'summary' => new external_value(PARAM_RAW, 'summary'),
2452             'summaryformat' => new external_format_value('summary'),
2453             'summaryfiles' => new external_files('summary files in the summary field', VALUE_OPTIONAL),
2454             'overviewfiles' => new external_files('additional overview files attached to this course'),
2455             'contacts' => new external_multiple_structure(
2456                 new external_single_structure(
2457                     array(
2458                         'id' => new external_value(PARAM_INT, 'contact user id'),
2459                         'fullname'  => new external_value(PARAM_NOTAGS, 'contact user fullname'),
2460                     )
2461                 ),
2462                 'contact users'
2463             ),
2464             'enrollmentmethods' => new external_multiple_structure(
2465                 new external_value(PARAM_PLUGIN, 'enrollment method'),
2466                 'enrollment methods list'
2467             ),
2468         );
2470         if (!$onlypublicdata) {
2471             $extra = array(
2472                 'idnumber' => new external_value(PARAM_RAW, 'Id number', VALUE_OPTIONAL),
2473                 'format' => new external_value(PARAM_PLUGIN, 'Course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
2474                 'showgrades' => new external_value(PARAM_INT, '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
2475                 'newsitems' => new external_value(PARAM_INT, 'Number of recent items appearing on the course page', VALUE_OPTIONAL),
2476                 'startdate' => new external_value(PARAM_INT, 'Timestamp when the course start', VALUE_OPTIONAL),
2477                 'enddate' => new external_value(PARAM_INT, 'Timestamp when the course end', VALUE_OPTIONAL),
2478                 'maxbytes' => new external_value(PARAM_INT, 'Largest size of file that can be uploaded into', VALUE_OPTIONAL),
2479                 'showreports' => new external_value(PARAM_INT, 'Are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
2480                 'visible' => new external_value(PARAM_INT, '1: available to student, 0:not available', VALUE_OPTIONAL),
2481                 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
2482                 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
2483                 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
2484                 'enablecompletion' => new external_value(PARAM_INT, 'Completion enabled? 1: yes 0: no', VALUE_OPTIONAL),
2485                 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
2486                 'lang' => new external_value(PARAM_SAFEDIR, 'Forced course language', VALUE_OPTIONAL),
2487                 'theme' => new external_value(PARAM_PLUGIN, 'Fame of the forced theme', VALUE_OPTIONAL),
2488                 'marker' => new external_value(PARAM_INT, 'Current course marker', VALUE_OPTIONAL),
2489                 'legacyfiles' => new external_value(PARAM_INT, 'If legacy files are enabled', VALUE_OPTIONAL),
2490                 'calendartype' => new external_value(PARAM_PLUGIN, 'Calendar type', VALUE_OPTIONAL),
2491                 'timecreated' => new external_value(PARAM_INT, 'Time when the course was created', VALUE_OPTIONAL),
2492                 'timemodified' => new external_value(PARAM_INT, 'Last time  the course was updated', VALUE_OPTIONAL),
2493                 'requested' => new external_value(PARAM_INT, 'If is a requested course', VALUE_OPTIONAL),
2494                 'cacherev' => new external_value(PARAM_INT, 'Cache revision number', VALUE_OPTIONAL),
2495                 'filters' => new external_multiple_structure(
2496                     new external_single_structure(
2497                         array(
2498                             'filter'  => new external_value(PARAM_PLUGIN, 'Filter plugin name'),
2499                             'localstate' => new external_value(PARAM_INT, 'Filter state: 1 for on, -1 for off, 0 if inherit'),
2500                             'inheritedstate' => new external_value(PARAM_INT, '1 or 0 to use when localstate is set to inherit'),
2501                         )
2502                     ),
2503                     'Course filters', VALUE_OPTIONAL
2504                 ),
2505                 'courseformatoptions' => new external_multiple_structure(
2506                     new external_single_structure(
2507                         array(
2508                             'name' => new external_value(PARAM_RAW, 'Course format option name.'),
2509                             'value' => new external_value(PARAM_RAW, 'Course format option value.'),
2510                         )
2511                     ),
2512                     'Additional options for particular course format.', VALUE_OPTIONAL
2513                 ),
2514             );
2515             $coursestructure = array_merge($coursestructure, $extra);
2516         }
2517         return new external_single_structure($coursestructure);
2518     }
2520     /**
2521      * Returns description of method result value
2522      *
2523      * @return external_description
2524      * @since Moodle 3.0
2525      */
2526     public static function search_courses_returns() {
2527         return new external_single_structure(
2528             array(
2529                 'total' => new external_value(PARAM_INT, 'total course count'),
2530                 'courses' => new external_multiple_structure(self::get_course_structure(), 'course'),
2531                 'warnings' => new external_warnings()
2532             )
2533         );
2534     }
2536     /**
2537      * Returns description of method parameters
2538      *
2539      * @return external_function_parameters
2540      * @since Moodle 3.0
2541      */
2542     public static function get_course_module_parameters() {
2543         return new external_function_parameters(
2544             array(
2545                 'cmid' => new external_value(PARAM_INT, 'The course module id')
2546             )
2547         );
2548     }
2550     /**
2551      * Return information about a course module.
2552      *
2553      * @param int $cmid the course module id
2554      * @return array of warnings and the course module
2555      * @since Moodle 3.0
2556      * @throws moodle_exception
2557      */
2558     public static function get_course_module($cmid) {
2559         global $CFG, $DB;
2561         $params = self::validate_parameters(self::get_course_module_parameters(), array('cmid' => $cmid));
2562         $warnings = array();
2564         $cm = get_coursemodule_from_id(null, $params['cmid'], 0, true, MUST_EXIST);
2565         $context = context_module::instance($cm->id);
2566         self::validate_context($context);
2568         // If the user has permissions to manage the activity, return all the information.
2569         if (has_capability('moodle/course:manageactivities', $context)) {
2570             require_once($CFG->dirroot . '/course/modlib.php');
2571             require_once($CFG->libdir . '/gradelib.php');
2573             $info = $cm;
2574             // Get the extra information: grade, advanced grading and outcomes data.
2575             $course = get_course($cm->course);
2576             list($newcm, $newcontext, $module, $extrainfo, $cw) = get_moduleinfo_data($cm, $course);
2577             // Grades.
2578             $gradeinfo = array('grade', 'gradepass', 'gradecat');
2579             foreach ($gradeinfo as $gfield) {
2580                 if (isset($extrainfo->{$gfield})) {
2581                     $info->{$gfield} = $extrainfo->{$gfield};
2582                 }
2583             }
2584             if (isset($extrainfo->grade) and $extrainfo->grade < 0) {
2585                 $info->scale = $DB->get_field('scale', 'scale', array('id' => abs($extrainfo->grade)));
2586             }
2587             // Advanced grading.
2588             if (isset($extrainfo->_advancedgradingdata)) {
2589                 $info->advancedgrading = array();
2590                 foreach ($extrainfo as $key => $val) {
2591                     if (strpos($key, 'advancedgradingmethod_') === 0) {
2592                         $info->advancedgrading[] = array(
2593                             'area' => str_replace('advancedgradingmethod_', '', $key),
2594                             'method' => $val
2595                         );
2596                     }
2597                 }
2598             }
2599             // Outcomes.
2600             foreach ($extrainfo as $key => $val) {
2601                 if (strpos($key, 'outcome_') === 0) {
2602                     if (!isset($info->outcomes)) {
2603                         $info->outcomes = array();
2604                     }
2605                     $id = str_replace('outcome_', '', $key);
2606                     $outcome = grade_outcome::fetch(array('id' => $id));
2607                     $scaleitems = $outcome->load_scale();
2608                     $info->outcomes[] = array(
2609                         'id' => $id,
2610                         'name' => external_format_string($outcome->get_name(), $context->id),
2611                         'scale' => $scaleitems->scale
2612                     );
2613                 }
2614             }
2615         } else {
2616             // Return information is safe to show to any user.
2617             $info = new stdClass();
2618             $info->id = $cm->id;
2619             $info->course = $cm->course;
2620             $info->module = $cm->module;
2621             $info->modname = $cm->modname;
2622             $info->instance = $cm->instance;
2623             $info->section = $cm->section;
2624             $info->sectionnum = $cm->sectionnum;
2625             $info->groupmode = $cm->groupmode;
2626             $info->groupingid = $cm->groupingid;
2627             $info->completion = $cm->completion;
2628         }
2629         // Format name.
2630         $info->name = external_format_string($cm->name, $context->id);
2631         $result = array();
2632         $result['cm'] = $info;
2633         $result['warnings'] = $warnings;
2634         return $result;
2635     }
2637     /**
2638      * Returns description of method result value
2639      *
2640      * @return external_description
2641      * @since Moodle 3.0
2642      */
2643     public static function get_course_module_returns() {
2644         return new external_single_structure(
2645             array(
2646                 'cm' => new external_single_structure(
2647                     array(
2648                         'id' => new external_value(PARAM_INT, 'The course module id'),
2649                         'course' => new external_value(PARAM_INT, 'The course id'),
2650                         'module' => new external_value(PARAM_INT, 'The module type id'),
2651                         'name' => new external_value(PARAM_RAW, 'The activity name'),
2652                         'modname' => new external_value(PARAM_COMPONENT, 'The module component name (forum, assign, etc..)'),
2653                         'instance' => new external_value(PARAM_INT, 'The activity instance id'),
2654                         'section' => new external_value(PARAM_INT, 'The module section id'),
2655                         'sectionnum' => new external_value(PARAM_INT, 'The module section number'),
2656                         'groupmode' => new external_value(PARAM_INT, 'Group mode'),
2657                         'groupingid' => new external_value(PARAM_INT, 'Grouping id'),
2658                         'completion' => new external_value(PARAM_INT, 'If completion is enabled'),
2659                         'idnumber' => new external_value(PARAM_RAW, 'Module id number', VALUE_OPTIONAL),
2660                         'added' => new external_value(PARAM_INT, 'Time added', VALUE_OPTIONAL),
2661                         'score' => new external_value(PARAM_INT, 'Score', VALUE_OPTIONAL),
2662                         'indent' => new external_value(PARAM_INT, 'Indentation', VALUE_OPTIONAL),
2663                         'visible' => new external_value(PARAM_INT, 'If visible', VALUE_OPTIONAL),
2664                         'visibleoncoursepage' => new external_value(PARAM_INT, 'If visible on course page', VALUE_OPTIONAL),
2665                         'visibleold' => new external_value(PARAM_INT, 'Visible old', VALUE_OPTIONAL),
2666                         'completiongradeitemnumber' => new external_value(PARAM_INT, 'Completion grade item', VALUE_OPTIONAL),
2667                         'completionview' => new external_value(PARAM_INT, 'Completion view setting', VALUE_OPTIONAL),
2668                         'completionexpected' => new external_value(PARAM_INT, 'Completion time expected', VALUE_OPTIONAL),
2669                         'showdescription' => new external_value(PARAM_INT, 'If the description is showed', VALUE_OPTIONAL),
2670                         'availability' => new external_value(PARAM_RAW, 'Availability settings', VALUE_OPTIONAL),
2671                         'grade' => new external_value(PARAM_FLOAT, 'Grade (max value or scale id)', VALUE_OPTIONAL),
2672                         'scale' => new external_value(PARAM_TEXT, 'Scale items (if used)', VALUE_OPTIONAL),
2673                         'gradepass' => new external_value(PARAM_RAW, 'Grade to pass (float)', VALUE_OPTIONAL),
2674                         'gradecat' => new external_value(PARAM_INT, 'Grade category', VALUE_OPTIONAL),
2675                         'advancedgrading' => new external_multiple_structure(
2676                             new external_single_structure(
2677                                 array(
2678                                     'area' => new external_value(PARAM_AREA, 'Gradable area name'),
2679                                     'method'  => new external_value(PARAM_COMPONENT, 'Grading method'),
2680                                 )
2681                             ),
2682                             'Advanced grading settings', VALUE_OPTIONAL
2683                         ),
2684                         'outcomes' => new external_multiple_structure(
2685                             new external_single_structure(
2686                                 array(
2687                                     'id' => new external_value(PARAM_ALPHANUMEXT, 'Outcome id'),
2688                                     'name'  => new external_value(PARAM_TEXT, 'Outcome full name'),
2689                                     'scale' => new external_value(PARAM_TEXT, 'Scale items')
2690                                 )
2691                             ),
2692                             'Outcomes information', VALUE_OPTIONAL
2693                         ),
2694                     )
2695                 ),
2696                 'warnings' => new external_warnings()
2697             )
2698         );
2699     }
2701     /**
2702      * Returns description of method parameters
2703      *
2704      * @return external_function_parameters
2705      * @since Moodle 3.0
2706      */
2707     public static function get_course_module_by_instance_parameters() {
2708         return new external_function_parameters(
2709             array(
2710                 'module' => new external_value(PARAM_COMPONENT, 'The module name'),
2711                 'instance' => new external_value(PARAM_INT, 'The module instance id')
2712             )
2713         );
2714     }
2716     /**
2717      * Return information about a course module.
2718      *
2719      * @param string $module the module name
2720      * @param int $instance the activity instance id
2721      * @return array of warnings and the course module
2722      * @since Moodle 3.0
2723      * @throws moodle_exception
2724      */
2725     public static function get_course_module_by_instance($module, $instance) {
2727         $params = self::validate_parameters(self::get_course_module_by_instance_parameters(),
2728                                             array(
2729                                                 'module' => $module,
2730                                                 'instance' => $instance,
2731                                             ));
2733         $warnings = array();
2734         $cm = get_coursemodule_from_instance($params['module'], $params['instance'], 0, false, MUST_EXIST);
2736         return self::get_course_module($cm->id);
2737     }
2739     /**
2740      * Returns description of method result value
2741      *
2742      * @return external_description
2743      * @since Moodle 3.0
2744      */
2745     public static function get_course_module_by_instance_returns() {
2746         return self::get_course_module_returns();
2747     }
2749     /**
2750      * Returns description of method parameters
2751      *
2752      * @deprecated since 3.3
2753      * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
2754      * @return external_function_parameters
2755      * @since Moodle 3.2
2756      */
2757     public static function get_activities_overview_parameters() {
2758         return new external_function_parameters(
2759             array(
2760                 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2761             )
2762         );
2763     }
2765     /**
2766      * Return activities overview for the given courses.
2767      *
2768      * @deprecated since 3.3
2769      * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
2770      * @param array $courseids a list of course ids
2771      * @return array of warnings and the activities overview
2772      * @since Moodle 3.2
2773      * @throws moodle_exception
2774      */
2775     public static function get_activities_overview($courseids) {
2776         global $USER;
2778         // Parameter validation.
2779         $params = self::validate_parameters(self::get_activities_overview_parameters(), array('courseids' => $courseids));
2780         $courseoverviews = array();
2782         list($courses, $warnings) = external_util::validate_courses($params['courseids']);
2784         if (!empty($courses)) {
2785             // Add lastaccess to each course (required by print_overview function).
2786             // We need the complete user data, the ws server does not load a complete one.
2787             $user = get_complete_user_data('id', $USER->id);
2788             foreach ($courses as $course) {
2789                 if (isset($user->lastcourseaccess[$course->id])) {
2790                     $course->lastaccess = $user->lastcourseaccess[$course->id];
2791                 } else {
2792                     $course->lastaccess = 0;
2793                 }
2794             }
2796             $overviews = array();
2797             if ($modules = get_plugin_list_with_function('mod', 'print_overview')) {
2798                 foreach ($modules as $fname) {
2799                     $fname($courses, $overviews);
2800                 }
2801             }
2803             // Format output.
2804             foreach ($overviews as $courseid => $modules) {
2805                 $courseoverviews[$courseid]['id'] = $courseid;
2806                 $courseoverviews[$courseid]['overviews'] = array();
2808                 foreach ($modules as $modname => $overviewtext) {
2809                     $courseoverviews[$courseid]['overviews'][] = array(
2810                         'module' => $modname,
2811                         'overviewtext' => $overviewtext // This text doesn't need formatting.
2812                     );
2813                 }
2814             }
2815         }
2817         $result = array(
2818             'courses' => $courseoverviews,
2819             'warnings' => $warnings
2820         );
2821         return $result;
2822     }
2824     /**
2825      * Returns description of method result value
2826      *
2827      * @deprecated since 3.3
2828      * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
2829      * @return external_description
2830      * @since Moodle 3.2
2831      */
2832     public static function get_activities_overview_returns() {
2833         return new external_single_structure(
2834             array(
2835                 'courses' => new external_multiple_structure(
2836                     new external_single_structure(
2837                         array(
2838                             'id' => new external_value(PARAM_INT, 'Course id'),
2839                             'overviews' => new external_multiple_structure(
2840                                 new external_single_structure(
2841                                     array(
2842                                         'module' => new external_value(PARAM_PLUGIN, 'Module name'),
2843                                         'overviewtext' => new external_value(PARAM_RAW, 'Overview text'),
2844                                     )
2845                                 )
2846                             )
2847                         )
2848                     ), 'List of courses'
2849                 ),
2850                 'warnings' => new external_warnings()
2851             )
2852         );
2853     }
2855     /**
2856      * Marking the method as deprecated.
2857      *
2858      * @return bool
2859      */
2860     public static function get_activities_overview_is_deprecated() {
2861         return true;
2862     }
2864     /**
2865      * Returns description of method parameters
2866      *
2867      * @return external_function_parameters
2868      * @since Moodle 3.2
2869      */
2870     public static function get_user_navigation_options_parameters() {
2871         return new external_function_parameters(
2872             array(
2873                 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2874             )
2875         );
2876     }
2878     /**
2879      * Return a list of navigation options in a set of courses that are avaialable or not for the current user.
2880      *
2881      * @param array $courseids a list of course ids
2882      * @return array of warnings and the options availability
2883      * @since Moodle 3.2
2884      * @throws moodle_exception
2885      */
2886     public static function get_user_navigation_options($courseids) {
2887         global $CFG;
2888         require_once($CFG->dirroot . '/course/lib.php');
2890         // Parameter validation.
2891         $params = self::validate_parameters(self::get_user_navigation_options_parameters(), array('courseids' => $courseids));
2892         $courseoptions = array();
2894         list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
2896         if (!empty($courses)) {
2897             foreach ($courses as $course) {
2898                 // Fix the context for the frontpage.
2899                 if ($course->id == SITEID) {
2900                     $course->context = context_system::instance();
2901                 }
2902                 $navoptions = course_get_user_navigation_options($course->context, $course);
2903                 $options = array();
2904                 foreach ($navoptions as $name => $available) {
2905                     $options[] = array(
2906                         'name' => $name,
2907                         'available' => $available,
2908                     );
2909                 }
2911                 $courseoptions[] = array(
2912                     'id' => $course->id,
2913                     'options' => $options
2914                 );
2915             }
2916         }
2918         $result = array(
2919             'courses' => $courseoptions,
2920             'warnings' => $warnings
2921         );
2922         return $result;
2923     }
2925     /**
2926      * Returns description of method result value
2927      *
2928      * @return external_description
2929      * @since Moodle 3.2
2930      */
2931     public static function get_user_navigation_options_returns() {
2932         return new external_single_structure(
2933             array(
2934                 'courses' => new external_multiple_structure(
2935                     new external_single_structure(
2936                         array(
2937                             'id' => new external_value(PARAM_INT, 'Course id'),
2938                             'options' => new external_multiple_structure(
2939                                 new external_single_structure(
2940                                     array(
2941                                         'name' => new external_value(PARAM_ALPHANUMEXT, 'Option name'),
2942                                         'available' => new external_value(PARAM_BOOL, 'Whether the option is available or not'),
2943                                     )
2944                                 )
2945                             )
2946                         )
2947                     ), 'List of courses'
2948                 ),
2949                 'warnings' => new external_warnings()
2950             )
2951         );
2952     }
2954     /**
2955      * Returns description of method parameters
2956      *
2957      * @return external_function_parameters
2958      * @since Moodle 3.2
2959      */
2960     public static function get_user_administration_options_parameters() {
2961         return new external_function_parameters(
2962             array(
2963                 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2964             )
2965         );
2966     }
2968     /**
2969      * Return a list of administration options in a set of courses that are available or not for the current user.
2970      *
2971      * @param array $courseids a list of course ids
2972      * @return array of warnings and the options availability
2973      * @since Moodle 3.2
2974      * @throws moodle_exception
2975      */
2976     public static function get_user_administration_options($courseids) {
2977         global $CFG;
2978         require_once($CFG->dirroot . '/course/lib.php');
2980         // Parameter validation.
2981         $params = self::validate_parameters(self::get_user_administration_options_parameters(), array('courseids' => $courseids));
2982         $courseoptions = array();
2984         list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true);
2986         if (!empty($courses)) {
2987             foreach ($courses as $course) {
2988                 $adminoptions = course_get_user_administration_options($course, $course->context);
2989                 $options = array();
2990                 foreach ($adminoptions as $name => $available) {
2991                     $options[] = array(
2992                         'name' => $name,
2993                         'available' => $available,
2994                     );
2995                 }
2997                 $courseoptions[] = array(
2998                     'id' => $course->id,
2999                     'options' => $options
3000                 );
3001             }
3002         }
3004         $result = array(
3005             'courses' => $courseoptions,
3006             'warnings' => $warnings
3007         );
3008         return $result;
3009     }
3011     /**
3012      * Returns description of method result value
3013      *
3014      * @return external_description
3015      * @since Moodle 3.2
3016      */
3017     public static function get_user_administration_options_returns() {
3018         return self::get_user_navigation_options_returns();
3019     }
3021     /**
3022      * Returns description of method parameters
3023      *
3024      * @return external_function_parameters
3025      * @since Moodle 3.2
3026      */
3027     public static function get_courses_by_field_parameters() {
3028         return new external_function_parameters(
3029             array(
3030                 'field' => new external_value(PARAM_ALPHA, 'The field to search can be left empty for all courses or:
3031                     id: course id
3032                     ids: comma separated course ids
3033                     shortname: course short name
3034                     idnumber: course id number
3035                     category: category id the course belongs to
3036                 ', VALUE_DEFAULT, ''),
3037                 'value' => new external_value(PARAM_RAW, 'The value to match', VALUE_DEFAULT, '')