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