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