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