MDL-65019 core: Return repository type for main file
[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                                 'valueused'     => core_availability\info::completion_value_used($course, $cm->id)
282                             );
283                         }
285                         if (!empty($cm->showdescription) or $cm->modname == 'label') {
286                             // We want to use the external format. However from reading get_formatted_content(), $cm->content format is always FORMAT_HTML.
287                             $options = array('noclean' => true);
288                             list($module['description'], $descriptionformat) = external_format_text($cm->content,
289                                 FORMAT_HTML, $modcontext->id, $cm->modname, 'intro', $cm->id, $options);
290                         }
292                         //url of the module
293                         $url = $cm->url;
294                         if ($url) { //labels don't have url
295                             $module['url'] = $url->out(false);
296                         }
298                         $canviewhidden = has_capability('moodle/course:viewhiddenactivities',
299                                             context_module::instance($cm->id));
300                         //user that can view hidden module should know about the visibility
301                         $module['visible'] = $cm->visible;
302                         $module['visibleoncoursepage'] = $cm->visibleoncoursepage;
303                         $module['uservisible'] = $cm->uservisible;
304                         if (!empty($cm->availableinfo)) {
305                             $module['availabilityinfo'] = \core_availability\info::format_info($cm->availableinfo, $course);
306                         }
308                         // Availability date (also send to user who can see hidden module).
309                         if ($CFG->enableavailability && ($canviewhidden || $canupdatecourse)) {
310                             $module['availability'] = $cm->availability;
311                         }
313                         // Return contents only if the user can access to the module.
314                         if ($cm->uservisible) {
315                             $baseurl = 'webservice/pluginfile.php';
317                             // Call $modulename_export_contents (each module callback take care about checking the capabilities).
318                             require_once($CFG->dirroot . '/mod/' . $cm->modname . '/lib.php');
319                             $getcontentfunction = $cm->modname.'_export_contents';
320                             if (function_exists($getcontentfunction)) {
321                                 $contents = $getcontentfunction($cm, $baseurl);
322                                 $module['contentsinfo'] = array(
323                                     'filescount' => count($contents),
324                                     'filessize' => 0,
325                                     'lastmodified' => 0,
326                                     'mimetypes' => array(),
327                                 );
328                                 foreach ($contents as $content) {
329                                     // Check repository file (only main file).
330                                     if (!isset($module['contentsinfo']['repositorytype'])) {
331                                         $module['contentsinfo']['repositorytype'] = isset($content['repositorytype']) ? $content['repositorytype'] : '';
332                                     }
333                                     if (isset($content['filesize'])) {
334                                         $module['contentsinfo']['filessize'] += $content['filesize'];
335                                     }
336                                     if (isset($content['timemodified']) &&
337                                             ($content['timemodified'] > $module['contentsinfo']['lastmodified'])) {
339                                         $module['contentsinfo']['lastmodified'] = $content['timemodified'];
340                                     }
341                                     if (isset($content['mimetype'])) {
342                                         $module['contentsinfo']['mimetypes'][$content['mimetype']] = $content['mimetype'];
343                                     }
344                                 }
346                                 if (empty($filters['excludecontents']) and !empty($contents)) {
347                                     $module['contents'] = $contents;
348                                 } else {
349                                     $module['contents'] = array();
350                                 }
351                             }
352                         }
354                         // Assign result to $sectioncontents, there is an exception,
355                         // stealth activities in non-visible sections for students go to a special section.
356                         if (!empty($filters['includestealthmodules']) && !$section->uservisible && $cm->is_stealth()) {
357                             $stealthmodules[] = $module;
358                         } else {
359                             $sectioncontents[] = $module;
360                         }
362                         // If we just did a filtering, break the loop.
363                         if ($modfound) {
364                             break;
365                         }
367                     }
368                 }
369                 $sectionvalues['modules'] = $sectioncontents;
371                 // assign result to $coursecontents
372                 $coursecontents[$key] = $sectionvalues;
374                 // Break the loop if we are filtering.
375                 if ($sectionfound) {
376                     break;
377                 }
378             }
380             // Now that we have iterated over all the sections and activities, check the visibility.
381             // We didn't this before to be able to retrieve stealth activities.
382             foreach ($coursecontents as $sectionnumber => $sectioncontents) {
383                 $section = $sections[$sectionnumber];
384                 // Show the section if the user is permitted to access it, OR if it's not available
385                 // but there is some available info text which explains the reason & should display.
386                 $showsection = $section->uservisible ||
387                     ($section->visible && !$section->available &&
388                     !empty($section->availableinfo));
390                 if (!$showsection) {
391                     unset($coursecontents[$sectionnumber]);
392                     continue;
393                 }
395                 // Remove modules information if the section is not visible for the user.
396                 if (!$section->uservisible) {
397                     $coursecontents[$sectionnumber]['modules'] = array();
398                 }
399             }
401             // Include stealth modules in special section (without any info).
402             if (!empty($stealthmodules)) {
403                 $coursecontents[] = array(
404                     'id' => -1,
405                     'name' => '',
406                     'summary' => '',
407                     'summaryformat' => FORMAT_MOODLE,
408                     'modules' => $stealthmodules
409                 );
410             }
412         }
413         return $coursecontents;
414     }
416     /**
417      * Returns description of method result value
418      *
419      * @return external_description
420      * @since Moodle 2.2
421      */
422     public static function get_course_contents_returns() {
423         return new external_multiple_structure(
424             new external_single_structure(
425                 array(
426                     'id' => new external_value(PARAM_INT, 'Section ID'),
427                     'name' => new external_value(PARAM_TEXT, 'Section name'),
428                     'visible' => new external_value(PARAM_INT, 'is the section visible', VALUE_OPTIONAL),
429                     'summary' => new external_value(PARAM_RAW, 'Section description'),
430                     'summaryformat' => new external_format_value('summary'),
431                     'section' => new external_value(PARAM_INT, 'Section number inside the course', VALUE_OPTIONAL),
432                     'hiddenbynumsections' => new external_value(PARAM_INT, 'Whether is a section hidden in the course format',
433                                                                 VALUE_OPTIONAL),
434                     'uservisible' => new external_value(PARAM_BOOL, 'Is the section visible for the user?', VALUE_OPTIONAL),
435                     'availabilityinfo' => new external_value(PARAM_RAW, 'Availability information.', VALUE_OPTIONAL),
436                     'modules' => new external_multiple_structure(
437                             new external_single_structure(
438                                 array(
439                                     'id' => new external_value(PARAM_INT, 'activity id'),
440                                     'url' => new external_value(PARAM_URL, 'activity url', VALUE_OPTIONAL),
441                                     'name' => new external_value(PARAM_RAW, 'activity module name'),
442                                     'instance' => new external_value(PARAM_INT, 'instance id', VALUE_OPTIONAL),
443                                     'description' => new external_value(PARAM_RAW, 'activity description', VALUE_OPTIONAL),
444                                     'visible' => new external_value(PARAM_INT, 'is the module visible', VALUE_OPTIONAL),
445                                     'uservisible' => new external_value(PARAM_BOOL, 'Is the module visible for the user?',
446                                         VALUE_OPTIONAL),
447                                     'availabilityinfo' => new external_value(PARAM_RAW, 'Availability information.',
448                                         VALUE_OPTIONAL),
449                                     'visibleoncoursepage' => new external_value(PARAM_INT, 'is the module visible on course page',
450                                         VALUE_OPTIONAL),
451                                     'modicon' => new external_value(PARAM_URL, 'activity icon url'),
452                                     'modname' => new external_value(PARAM_PLUGIN, 'activity module type'),
453                                     'modplural' => new external_value(PARAM_TEXT, 'activity module plural name'),
454                                     'availability' => new external_value(PARAM_RAW, 'module availability settings', VALUE_OPTIONAL),
455                                     'indent' => new external_value(PARAM_INT, 'number of identation in the site'),
456                                     'onclick' => new external_value(PARAM_RAW, 'Onclick action.', VALUE_OPTIONAL),
457                                     'afterlink' => new external_value(PARAM_RAW, 'After link info to be displayed.',
458                                         VALUE_OPTIONAL),
459                                     'customdata' => new external_value(PARAM_RAW, 'Custom data (JSON encoded).', VALUE_OPTIONAL),
460                                     'completion' => new external_value(PARAM_INT, 'Type of completion tracking:
461                                         0 means none, 1 manual, 2 automatic.', VALUE_OPTIONAL),
462                                     'completiondata' => new external_single_structure(
463                                         array(
464                                             'state' => new external_value(PARAM_INT, 'Completion state value:
465                                                 0 means incomplete, 1 complete, 2 complete pass, 3 complete fail'),
466                                             'timecompleted' => new external_value(PARAM_INT, 'Timestamp for completion status.'),
467                                             'overrideby' => new external_value(PARAM_INT, 'The user id who has overriden the
468                                                 status.'),
469                                             'valueused' => new external_value(PARAM_BOOL, 'Whether the completion status affects
470                                                 the availability of another activity.', VALUE_OPTIONAL),
471                                         ), 'Module completion data.', VALUE_OPTIONAL
472                                     ),
473                                     'contents' => new external_multiple_structure(
474                                           new external_single_structure(
475                                               array(
476                                                   // content info
477                                                   'type'=> new external_value(PARAM_TEXT, 'a file or a folder or external link'),
478                                                   'filename'=> new external_value(PARAM_FILE, 'filename'),
479                                                   'filepath'=> new external_value(PARAM_PATH, 'filepath'),
480                                                   'filesize'=> new external_value(PARAM_INT, 'filesize'),
481                                                   'fileurl' => new external_value(PARAM_URL, 'downloadable file url', VALUE_OPTIONAL),
482                                                   'content' => new external_value(PARAM_RAW, 'Raw content, will be used when type is content', VALUE_OPTIONAL),
483                                                   'timecreated' => new external_value(PARAM_INT, 'Time created'),
484                                                   'timemodified' => new external_value(PARAM_INT, 'Time modified'),
485                                                   'sortorder' => new external_value(PARAM_INT, 'Content sort order'),
486                                                   'mimetype' => new external_value(PARAM_RAW, 'File mime type.', VALUE_OPTIONAL),
487                                                   'isexternalfile' => new external_value(PARAM_BOOL, 'Whether is an external file.',
488                                                     VALUE_OPTIONAL),
489                                                   'repositorytype' => new external_value(PARAM_PLUGIN, 'The repository type for external files.',
490                                                     VALUE_OPTIONAL),
492                                                   // copyright related info
493                                                   'userid' => new external_value(PARAM_INT, 'User who added this content to moodle'),
494                                                   'author' => new external_value(PARAM_TEXT, 'Content owner'),
495                                                   'license' => new external_value(PARAM_TEXT, 'Content license'),
496                                               )
497                                           ), VALUE_DEFAULT, array()
498                                       ),
499                                     'contentsinfo' => new external_single_structure(
500                                         array(
501                                             'filescount' => new external_value(PARAM_INT, 'Total number of files.'),
502                                             'filessize' => new external_value(PARAM_INT, 'Total files size.'),
503                                             'lastmodified' => new external_value(PARAM_INT, 'Last time files were modified.'),
504                                             'mimetypes' => new external_multiple_structure(
505                                                 new external_value(PARAM_RAW, 'File mime type.'),
506                                                 'Files mime types.'
507                                             ),
508                                             'repositorytype' => new external_value(PARAM_PLUGIN, 'The repository type for
509                                                 the main file.', VALUE_OPTIONAL),
510                                         ), 'Contents summary information.', VALUE_OPTIONAL
511                                     ),
512                                 )
513                             ), 'list of module'
514                     )
515                 )
516             )
517         );
518     }
520     /**
521      * Returns description of method parameters
522      *
523      * @return external_function_parameters
524      * @since Moodle 2.3
525      */
526     public static function get_courses_parameters() {
527         return new external_function_parameters(
528                 array('options' => new external_single_structure(
529                             array('ids' => new external_multiple_structure(
530                                         new external_value(PARAM_INT, 'Course id')
531                                         , 'List of course id. If empty return all courses
532                                             except front page course.',
533                                         VALUE_OPTIONAL)
534                             ), 'options - operator OR is used', VALUE_DEFAULT, array())
535                 )
536         );
537     }
539     /**
540      * Get courses
541      *
542      * @param array $options It contains an array (list of ids)
543      * @return array
544      * @since Moodle 2.2
545      */
546     public static function get_courses($options = array()) {
547         global $CFG, $DB;
548         require_once($CFG->dirroot . "/course/lib.php");
550         //validate parameter
551         $params = self::validate_parameters(self::get_courses_parameters(),
552                         array('options' => $options));
554         //retrieve courses
555         if (!array_key_exists('ids', $params['options'])
556                 or empty($params['options']['ids'])) {
557             $courses = $DB->get_records('course');
558         } else {
559             $courses = $DB->get_records_list('course', 'id', $params['options']['ids']);
560         }
562         //create return value
563         $coursesinfo = array();
564         foreach ($courses as $course) {
566             // now security checks
567             $context = context_course::instance($course->id, IGNORE_MISSING);
568             $courseformatoptions = course_get_format($course)->get_format_options();
569             try {
570                 self::validate_context($context);
571             } catch (Exception $e) {
572                 $exceptionparam = new stdClass();
573                 $exceptionparam->message = $e->getMessage();
574                 $exceptionparam->courseid = $course->id;
575                 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
576             }
577             if ($course->id != SITEID) {
578                 require_capability('moodle/course:view', $context);
579             }
581             $courseinfo = array();
582             $courseinfo['id'] = $course->id;
583             $courseinfo['fullname'] = external_format_string($course->fullname, $context->id);
584             $courseinfo['shortname'] = external_format_string($course->shortname, $context->id);
585             $courseinfo['displayname'] = external_format_string(get_course_display_name_for_list($course), $context->id);
586             $courseinfo['categoryid'] = $course->category;
587             list($courseinfo['summary'], $courseinfo['summaryformat']) =
588                 external_format_text($course->summary, $course->summaryformat, $context->id, 'course', 'summary', 0);
589             $courseinfo['format'] = $course->format;
590             $courseinfo['startdate'] = $course->startdate;
591             $courseinfo['enddate'] = $course->enddate;
592             if (array_key_exists('numsections', $courseformatoptions)) {
593                 // For backward-compartibility
594                 $courseinfo['numsections'] = $courseformatoptions['numsections'];
595             }
597             $handler = core_course\customfield\course_handler::create();
598             if ($customfields = $handler->export_instance_data($course->id)) {
599                 $courseinfo['customfields'] = [];
600                 foreach ($customfields as $data) {
601                     $courseinfo['customfields'][] = [
602                         'type' => $data->get_type(),
603                         'value' => $data->get_value(),
604                         'name' => $data->get_name(),
605                         'shortname' => $data->get_shortname()
606                     ];
607                 }
608             }
610             //some field should be returned only if the user has update permission
611             $courseadmin = has_capability('moodle/course:update', $context);
612             if ($courseadmin) {
613                 $courseinfo['categorysortorder'] = $course->sortorder;
614                 $courseinfo['idnumber'] = $course->idnumber;
615                 $courseinfo['showgrades'] = $course->showgrades;
616                 $courseinfo['showreports'] = $course->showreports;
617                 $courseinfo['newsitems'] = $course->newsitems;
618                 $courseinfo['visible'] = $course->visible;
619                 $courseinfo['maxbytes'] = $course->maxbytes;
620                 if (array_key_exists('hiddensections', $courseformatoptions)) {
621                     // For backward-compartibility
622                     $courseinfo['hiddensections'] = $courseformatoptions['hiddensections'];
623                 }
624                 // Return numsections for backward-compatibility with clients who expect it.
625                 $courseinfo['numsections'] = course_get_format($course)->get_last_section_number();
626                 $courseinfo['groupmode'] = $course->groupmode;
627                 $courseinfo['groupmodeforce'] = $course->groupmodeforce;
628                 $courseinfo['defaultgroupingid'] = $course->defaultgroupingid;
629                 $courseinfo['lang'] = clean_param($course->lang, PARAM_LANG);
630                 $courseinfo['timecreated'] = $course->timecreated;
631                 $courseinfo['timemodified'] = $course->timemodified;
632                 $courseinfo['forcetheme'] = clean_param($course->theme, PARAM_THEME);
633                 $courseinfo['enablecompletion'] = $course->enablecompletion;
634                 $courseinfo['completionnotify'] = $course->completionnotify;
635                 $courseinfo['courseformatoptions'] = array();
636                 foreach ($courseformatoptions as $key => $value) {
637                     $courseinfo['courseformatoptions'][] = array(
638                         'name' => $key,
639                         'value' => $value
640                     );
641                 }
642             }
644             if ($courseadmin or $course->visible
645                     or has_capability('moodle/course:viewhiddencourses', $context)) {
646                 $coursesinfo[] = $courseinfo;
647             }
648         }
650         return $coursesinfo;
651     }
653     /**
654      * Returns description of method result value
655      *
656      * @return external_description
657      * @since Moodle 2.2
658      */
659     public static function get_courses_returns() {
660         return new external_multiple_structure(
661                 new external_single_structure(
662                         array(
663                             'id' => new external_value(PARAM_INT, 'course id'),
664                             'shortname' => new external_value(PARAM_TEXT, 'course short name'),
665                             'categoryid' => new external_value(PARAM_INT, 'category id'),
666                             'categorysortorder' => new external_value(PARAM_INT,
667                                     'sort order into the category', VALUE_OPTIONAL),
668                             'fullname' => new external_value(PARAM_TEXT, 'full name'),
669                             'displayname' => new external_value(PARAM_TEXT, 'course display name'),
670                             'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
671                             'summary' => new external_value(PARAM_RAW, 'summary'),
672                             'summaryformat' => new external_format_value('summary'),
673                             'format' => new external_value(PARAM_PLUGIN,
674                                     'course format: weeks, topics, social, site,..'),
675                             'showgrades' => new external_value(PARAM_INT,
676                                     '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
677                             'newsitems' => new external_value(PARAM_INT,
678                                     'number of recent items appearing on the course page', VALUE_OPTIONAL),
679                             'startdate' => new external_value(PARAM_INT,
680                                     'timestamp when the course start'),
681                             'enddate' => new external_value(PARAM_INT,
682                                     'timestamp when the course end'),
683                             'numsections' => new external_value(PARAM_INT,
684                                     '(deprecated, use courseformatoptions) number of weeks/topics',
685                                     VALUE_OPTIONAL),
686                             'maxbytes' => new external_value(PARAM_INT,
687                                     'largest size of file that can be uploaded into the course',
688                                     VALUE_OPTIONAL),
689                             'showreports' => new external_value(PARAM_INT,
690                                     'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
691                             'visible' => new external_value(PARAM_INT,
692                                     '1: available to student, 0:not available', VALUE_OPTIONAL),
693                             'hiddensections' => new external_value(PARAM_INT,
694                                     '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
695                                     VALUE_OPTIONAL),
696                             'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
697                                     VALUE_OPTIONAL),
698                             'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
699                                     VALUE_OPTIONAL),
700                             'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
701                                     VALUE_OPTIONAL),
702                             'timecreated' => new external_value(PARAM_INT,
703                                     'timestamp when the course have been created', VALUE_OPTIONAL),
704                             'timemodified' => new external_value(PARAM_INT,
705                                     'timestamp when the course have been modified', VALUE_OPTIONAL),
706                             'enablecompletion' => new external_value(PARAM_INT,
707                                     'Enabled, control via completion and activity settings. Disbaled,
708                                         not shown in activity settings.',
709                                     VALUE_OPTIONAL),
710                             'completionnotify' => new external_value(PARAM_INT,
711                                     '1: yes 0: no', VALUE_OPTIONAL),
712                             'lang' => new external_value(PARAM_SAFEDIR,
713                                     'forced course language', VALUE_OPTIONAL),
714                             'forcetheme' => new external_value(PARAM_PLUGIN,
715                                     'name of the force theme', VALUE_OPTIONAL),
716                             'courseformatoptions' => new external_multiple_structure(
717                                 new external_single_structure(
718                                     array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
719                                         'value' => new external_value(PARAM_RAW, 'course format option value')
720                                 )), 'additional options for particular course format', VALUE_OPTIONAL
721                              ),
722                             'customfields' => new external_multiple_structure(
723                                 new external_single_structure(
724                                     ['name' => new external_value(PARAM_TEXT, 'The name of the custom field'),
725                                      'shortname' => new external_value(PARAM_ALPHANUMEXT, 'The shortname of the custom field'),
726                                      'type'  => new external_value(PARAM_COMPONENT,
727                                          'The type of the custom field - text, checkbox...'),
728                                      'value' => new external_value(PARAM_RAW, 'The value of the custom field')]
729                                 ), 'Custom fields and associated values', VALUE_OPTIONAL),
730                         ), 'course'
731                 )
732         );
733     }
735     /**
736      * Returns description of method parameters
737      *
738      * @return external_function_parameters
739      * @since Moodle 2.2
740      */
741     public static function create_courses_parameters() {
742         $courseconfig = get_config('moodlecourse'); //needed for many default values
743         return new external_function_parameters(
744             array(
745                 'courses' => new external_multiple_structure(
746                     new external_single_structure(
747                         array(
748                             'fullname' => new external_value(PARAM_TEXT, 'full name'),
749                             'shortname' => new external_value(PARAM_TEXT, 'course short name'),
750                             'categoryid' => new external_value(PARAM_INT, 'category id'),
751                             'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
752                             'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
753                             'summaryformat' => new external_format_value('summary', VALUE_DEFAULT),
754                             'format' => new external_value(PARAM_PLUGIN,
755                                     'course format: weeks, topics, social, site,..',
756                                     VALUE_DEFAULT, $courseconfig->format),
757                             'showgrades' => new external_value(PARAM_INT,
758                                     '1 if grades are shown, otherwise 0', VALUE_DEFAULT,
759                                     $courseconfig->showgrades),
760                             'newsitems' => new external_value(PARAM_INT,
761                                     'number of recent items appearing on the course page',
762                                     VALUE_DEFAULT, $courseconfig->newsitems),
763                             'startdate' => new external_value(PARAM_INT,
764                                     'timestamp when the course start', VALUE_OPTIONAL),
765                             'enddate' => new external_value(PARAM_INT,
766                                     'timestamp when the course end', VALUE_OPTIONAL),
767                             'numsections' => new external_value(PARAM_INT,
768                                     '(deprecated, use courseformatoptions) number of weeks/topics',
769                                     VALUE_OPTIONAL),
770                             'maxbytes' => new external_value(PARAM_INT,
771                                     'largest size of file that can be uploaded into the course',
772                                     VALUE_DEFAULT, $courseconfig->maxbytes),
773                             'showreports' => new external_value(PARAM_INT,
774                                     'are activity report shown (yes = 1, no =0)', VALUE_DEFAULT,
775                                     $courseconfig->showreports),
776                             'visible' => new external_value(PARAM_INT,
777                                     '1: available to student, 0:not available', VALUE_OPTIONAL),
778                             'hiddensections' => new external_value(PARAM_INT,
779                                     '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
780                                     VALUE_OPTIONAL),
781                             'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
782                                     VALUE_DEFAULT, $courseconfig->groupmode),
783                             'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
784                                     VALUE_DEFAULT, $courseconfig->groupmodeforce),
785                             'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',
786                                     VALUE_DEFAULT, 0),
787                             'enablecompletion' => new external_value(PARAM_INT,
788                                     'Enabled, control via completion and activity settings. Disabled,
789                                         not shown in activity settings.',
790                                     VALUE_OPTIONAL),
791                             'completionnotify' => new external_value(PARAM_INT,
792                                     '1: yes 0: no', VALUE_OPTIONAL),
793                             'lang' => new external_value(PARAM_SAFEDIR,
794                                     'forced course language', VALUE_OPTIONAL),
795                             'forcetheme' => new external_value(PARAM_PLUGIN,
796                                     'name of the force theme', VALUE_OPTIONAL),
797                             'courseformatoptions' => new external_multiple_structure(
798                                 new external_single_structure(
799                                     array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
800                                         'value' => new external_value(PARAM_RAW, 'course format option value')
801                                 )),
802                                     'additional options for particular course format', VALUE_OPTIONAL),
803                             'customfields' => new external_multiple_structure(
804                                 new external_single_structure(
805                                     array(
806                                         'shortname'  => new external_value(PARAM_ALPHANUMEXT, 'The shortname of the custom field'),
807                                         'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
808                                 )), 'custom fields for the course', VALUE_OPTIONAL
809                             )
810                     )), 'courses to create'
811                 )
812             )
813         );
814     }
816     /**
817      * Create  courses
818      *
819      * @param array $courses
820      * @return array courses (id and shortname only)
821      * @since Moodle 2.2
822      */
823     public static function create_courses($courses) {
824         global $CFG, $DB;
825         require_once($CFG->dirroot . "/course/lib.php");
826         require_once($CFG->libdir . '/completionlib.php');
828         $params = self::validate_parameters(self::create_courses_parameters(),
829                         array('courses' => $courses));
831         $availablethemes = core_component::get_plugin_list('theme');
832         $availablelangs = get_string_manager()->get_list_of_translations();
834         $transaction = $DB->start_delegated_transaction();
836         foreach ($params['courses'] as $course) {
838             // Ensure the current user is allowed to run this function
839             $context = context_coursecat::instance($course['categoryid'], IGNORE_MISSING);
840             try {
841                 self::validate_context($context);
842             } catch (Exception $e) {
843                 $exceptionparam = new stdClass();
844                 $exceptionparam->message = $e->getMessage();
845                 $exceptionparam->catid = $course['categoryid'];
846                 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
847             }
848             require_capability('moodle/course:create', $context);
850             // Make sure lang is valid
851             if (array_key_exists('lang', $course)) {
852                 if (empty($availablelangs[$course['lang']])) {
853                     throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
854                 }
855                 if (!has_capability('moodle/course:setforcedlanguage', $context)) {
856                     unset($course['lang']);
857                 }
858             }
860             // Make sure theme is valid
861             if (array_key_exists('forcetheme', $course)) {
862                 if (!empty($CFG->allowcoursethemes)) {
863                     if (empty($availablethemes[$course['forcetheme']])) {
864                         throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
865                     } else {
866                         $course['theme'] = $course['forcetheme'];
867                     }
868                 }
869             }
871             //force visibility if ws user doesn't have the permission to set it
872             $category = $DB->get_record('course_categories', array('id' => $course['categoryid']));
873             if (!has_capability('moodle/course:visibility', $context)) {
874                 $course['visible'] = $category->visible;
875             }
877             //set default value for completion
878             $courseconfig = get_config('moodlecourse');
879             if (completion_info::is_enabled_for_site()) {
880                 if (!array_key_exists('enablecompletion', $course)) {
881                     $course['enablecompletion'] = $courseconfig->enablecompletion;
882                 }
883             } else {
884                 $course['enablecompletion'] = 0;
885             }
887             $course['category'] = $course['categoryid'];
889             // Summary format.
890             $course['summaryformat'] = external_validate_format($course['summaryformat']);
892             if (!empty($course['courseformatoptions'])) {
893                 foreach ($course['courseformatoptions'] as $option) {
894                     $course[$option['name']] = $option['value'];
895                 }
896             }
898             // Custom fields.
899             if (!empty($course['customfields'])) {
900                 foreach ($course['customfields'] as $field) {
901                     $course['customfield_'.$field['shortname']] = $field['value'];
902                 }
903             }
905             //Note: create_course() core function check shortname, idnumber, category
906             $course['id'] = create_course((object) $course)->id;
908             $resultcourses[] = array('id' => $course['id'], 'shortname' => $course['shortname']);
909         }
911         $transaction->allow_commit();
913         return $resultcourses;
914     }
916     /**
917      * Returns description of method result value
918      *
919      * @return external_description
920      * @since Moodle 2.2
921      */
922     public static function create_courses_returns() {
923         return new external_multiple_structure(
924             new external_single_structure(
925                 array(
926                     'id'       => new external_value(PARAM_INT, 'course id'),
927                     'shortname' => new external_value(PARAM_TEXT, 'short name'),
928                 )
929             )
930         );
931     }
933     /**
934      * Update courses
935      *
936      * @return external_function_parameters
937      * @since Moodle 2.5
938      */
939     public static function update_courses_parameters() {
940         return new external_function_parameters(
941             array(
942                 'courses' => new external_multiple_structure(
943                     new external_single_structure(
944                         array(
945                             'id' => new external_value(PARAM_INT, 'ID of the course'),
946                             'fullname' => new external_value(PARAM_TEXT, 'full name', VALUE_OPTIONAL),
947                             'shortname' => new external_value(PARAM_TEXT, 'course short name', VALUE_OPTIONAL),
948                             'categoryid' => new external_value(PARAM_INT, 'category id', VALUE_OPTIONAL),
949                             'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
950                             'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
951                             'summaryformat' => new external_format_value('summary', VALUE_OPTIONAL),
952                             'format' => new external_value(PARAM_PLUGIN,
953                                     'course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
954                             'showgrades' => new external_value(PARAM_INT,
955                                     '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
956                             'newsitems' => new external_value(PARAM_INT,
957                                     'number of recent items appearing on the course page', VALUE_OPTIONAL),
958                             'startdate' => new external_value(PARAM_INT,
959                                     'timestamp when the course start', VALUE_OPTIONAL),
960                             'enddate' => new external_value(PARAM_INT,
961                                     'timestamp when the course end', VALUE_OPTIONAL),
962                             'numsections' => new external_value(PARAM_INT,
963                                     '(deprecated, use courseformatoptions) number of weeks/topics', VALUE_OPTIONAL),
964                             'maxbytes' => new external_value(PARAM_INT,
965                                     'largest size of file that can be uploaded into the course', VALUE_OPTIONAL),
966                             'showreports' => new external_value(PARAM_INT,
967                                     'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
968                             'visible' => new external_value(PARAM_INT,
969                                     '1: available to student, 0:not available', VALUE_OPTIONAL),
970                             'hiddensections' => new external_value(PARAM_INT,
971                                     '(deprecated, use courseformatoptions) How the hidden sections in the course are
972                                         displayed to students', VALUE_OPTIONAL),
973                             'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
974                             'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
975                             'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
976                             'enablecompletion' => new external_value(PARAM_INT,
977                                     'Enabled, control via completion and activity settings. Disabled,
978                                         not shown in activity settings.', VALUE_OPTIONAL),
979                             'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
980                             'lang' => new external_value(PARAM_SAFEDIR, 'forced course language', VALUE_OPTIONAL),
981                             'forcetheme' => new external_value(PARAM_PLUGIN, 'name of the force theme', VALUE_OPTIONAL),
982                             'courseformatoptions' => new external_multiple_structure(
983                                 new external_single_structure(
984                                     array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'),
985                                         'value' => new external_value(PARAM_RAW, 'course format option value')
986                                 )), 'additional options for particular course format', VALUE_OPTIONAL),
987                             'customfields' => new external_multiple_structure(
988                                 new external_single_structure(
989                                     [
990                                         'shortname'  => new external_value(PARAM_ALPHANUMEXT, 'The shortname of the custom field'),
991                                         'value' => new external_value(PARAM_RAW, 'The value of the custom field')
992                                     ]
993                                 ), 'Custom fields', VALUE_OPTIONAL),
994                         )
995                     ), 'courses to update'
996                 )
997             )
998         );
999     }
1001     /**
1002      * Update courses
1003      *
1004      * @param array $courses
1005      * @since Moodle 2.5
1006      */
1007     public static function update_courses($courses) {
1008         global $CFG, $DB;
1009         require_once($CFG->dirroot . "/course/lib.php");
1010         $warnings = array();
1012         $params = self::validate_parameters(self::update_courses_parameters(),
1013                         array('courses' => $courses));
1015         $availablethemes = core_component::get_plugin_list('theme');
1016         $availablelangs = get_string_manager()->get_list_of_translations();
1018         foreach ($params['courses'] as $course) {
1019             // Catch any exception while updating course and return as warning to user.
1020             try {
1021                 // Ensure the current user is allowed to run this function.
1022                 $context = context_course::instance($course['id'], MUST_EXIST);
1023                 self::validate_context($context);
1025                 $oldcourse = course_get_format($course['id'])->get_course();
1027                 require_capability('moodle/course:update', $context);
1029                 // Check if user can change category.
1030                 if (array_key_exists('categoryid', $course) && ($oldcourse->category != $course['categoryid'])) {
1031                     require_capability('moodle/course:changecategory', $context);
1032                     $course['category'] = $course['categoryid'];
1033                 }
1035                 // Check if the user can change fullname.
1036                 if (array_key_exists('fullname', $course) && ($oldcourse->fullname != $course['fullname'])) {
1037                     require_capability('moodle/course:changefullname', $context);
1038                 }
1040                 // Check if the user can change shortname.
1041                 if (array_key_exists('shortname', $course) && ($oldcourse->shortname != $course['shortname'])) {
1042                     require_capability('moodle/course:changeshortname', $context);
1043                 }
1045                 // Check if the user can change the idnumber.
1046                 if (array_key_exists('idnumber', $course) && ($oldcourse->idnumber != $course['idnumber'])) {
1047                     require_capability('moodle/course:changeidnumber', $context);
1048                 }
1050                 // Check if user can change summary.
1051                 if (array_key_exists('summary', $course) && ($oldcourse->summary != $course['summary'])) {
1052                     require_capability('moodle/course:changesummary', $context);
1053                 }
1055                 // Summary format.
1056                 if (array_key_exists('summaryformat', $course) && ($oldcourse->summaryformat != $course['summaryformat'])) {
1057                     require_capability('moodle/course:changesummary', $context);
1058                     $course['summaryformat'] = external_validate_format($course['summaryformat']);
1059                 }
1061                 // Check if user can change visibility.
1062                 if (array_key_exists('visible', $course) && ($oldcourse->visible != $course['visible'])) {
1063                     require_capability('moodle/course:visibility', $context);
1064                 }
1066                 // Make sure lang is valid.
1067                 if (array_key_exists('lang', $course) && ($oldcourse->lang != $course['lang'])) {
1068                     require_capability('moodle/course:setforcedlanguage', $context);
1069                     if (empty($availablelangs[$course['lang']])) {
1070                         throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
1071                     }
1072                 }
1074                 // Make sure theme is valid.
1075                 if (array_key_exists('forcetheme', $course)) {
1076                     if (!empty($CFG->allowcoursethemes)) {
1077                         if (empty($availablethemes[$course['forcetheme']])) {
1078                             throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
1079                         } else {
1080                             $course['theme'] = $course['forcetheme'];
1081                         }
1082                     }
1083                 }
1085                 // Make sure completion is enabled before setting it.
1086                 if (array_key_exists('enabledcompletion', $course) && !completion_info::is_enabled_for_site()) {
1087                     $course['enabledcompletion'] = 0;
1088                 }
1090                 // Make sure maxbytes are less then CFG->maxbytes.
1091                 if (array_key_exists('maxbytes', $course)) {
1092                     // We allow updates back to 0 max bytes, a special value denoting the course uses the site limit.
1093                     // Otherwise, either use the size specified, or cap at the max size for the course.
1094                     if ($course['maxbytes'] != 0) {
1095                         $course['maxbytes'] = get_max_upload_file_size($CFG->maxbytes, $course['maxbytes']);
1096                     }
1097                 }
1099                 if (!empty($course['courseformatoptions'])) {
1100                     foreach ($course['courseformatoptions'] as $option) {
1101                         if (isset($option['name']) && isset($option['value'])) {
1102                             $course[$option['name']] = $option['value'];
1103                         }
1104                     }
1105                 }
1107                 // Prepare list of custom fields.
1108                 if (isset($course['customfields'])) {
1109                     foreach ($course['customfields'] as $field) {
1110                         $course['customfield_' . $field['shortname']] = $field['value'];
1111                     }
1112                 }
1114                 // Update course if user has all required capabilities.
1115                 update_course((object) $course);
1116             } catch (Exception $e) {
1117                 $warning = array();
1118                 $warning['item'] = 'course';
1119                 $warning['itemid'] = $course['id'];
1120                 if ($e instanceof moodle_exception) {
1121                     $warning['warningcode'] = $e->errorcode;
1122                 } else {
1123                     $warning['warningcode'] = $e->getCode();
1124                 }
1125                 $warning['message'] = $e->getMessage();
1126                 $warnings[] = $warning;
1127             }
1128         }
1130         $result = array();
1131         $result['warnings'] = $warnings;
1132         return $result;
1133     }
1135     /**
1136      * Returns description of method result value
1137      *
1138      * @return external_description
1139      * @since Moodle 2.5
1140      */
1141     public static function update_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.2
1154      */
1155     public static function delete_courses_parameters() {
1156         return new external_function_parameters(
1157             array(
1158                 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'course ID')),
1159             )
1160         );
1161     }
1163     /**
1164      * Delete courses
1165      *
1166      * @param array $courseids A list of course ids
1167      * @since Moodle 2.2
1168      */
1169     public static function delete_courses($courseids) {
1170         global $CFG, $DB;
1171         require_once($CFG->dirroot."/course/lib.php");
1173         // Parameter validation.
1174         $params = self::validate_parameters(self::delete_courses_parameters(), array('courseids'=>$courseids));
1176         $warnings = array();
1178         foreach ($params['courseids'] as $courseid) {
1179             $course = $DB->get_record('course', array('id' => $courseid));
1181             if ($course === false) {
1182                 $warnings[] = array(
1183                                 'item' => 'course',
1184                                 'itemid' => $courseid,
1185                                 'warningcode' => 'unknowncourseidnumber',
1186                                 'message' => 'Unknown course ID ' . $courseid
1187                             );
1188                 continue;
1189             }
1191             // Check if the context is valid.
1192             $coursecontext = context_course::instance($course->id);
1193             self::validate_context($coursecontext);
1195             // Check if the current user has permission.
1196             if (!can_delete_course($courseid)) {
1197                 $warnings[] = array(
1198                                 'item' => 'course',
1199                                 'itemid' => $courseid,
1200                                 'warningcode' => 'cannotdeletecourse',
1201                                 'message' => 'You do not have the permission to delete this course' . $courseid
1202                             );
1203                 continue;
1204             }
1206             if (delete_course($course, false) === false) {
1207                 $warnings[] = array(
1208                                 'item' => 'course',
1209                                 'itemid' => $courseid,
1210                                 'warningcode' => 'cannotdeletecategorycourse',
1211                                 'message' => 'Course ' . $courseid . ' failed to be deleted'
1212                             );
1213                 continue;
1214             }
1215         }
1217         fix_course_sortorder();
1219         return array('warnings' => $warnings);
1220     }
1222     /**
1223      * Returns description of method result value
1224      *
1225      * @return external_description
1226      * @since Moodle 2.2
1227      */
1228     public static function delete_courses_returns() {
1229         return new external_single_structure(
1230             array(
1231                 'warnings' => new external_warnings()
1232             )
1233         );
1234     }
1236     /**
1237      * Returns description of method parameters
1238      *
1239      * @return external_function_parameters
1240      * @since Moodle 2.3
1241      */
1242     public static function duplicate_course_parameters() {
1243         return new external_function_parameters(
1244             array(
1245                 'courseid' => new external_value(PARAM_INT, 'course to duplicate id'),
1246                 'fullname' => new external_value(PARAM_TEXT, 'duplicated course full name'),
1247                 'shortname' => new external_value(PARAM_TEXT, 'duplicated course short name'),
1248                 'categoryid' => new external_value(PARAM_INT, 'duplicated course category parent'),
1249                 'visible' => new external_value(PARAM_INT, 'duplicated course visible, default to yes', VALUE_DEFAULT, 1),
1250                 'options' => new external_multiple_structure(
1251                     new external_single_structure(
1252                         array(
1253                                 'name' => new external_value(PARAM_ALPHAEXT, 'The backup option name:
1254                                             "activities" (int) Include course activites (default to 1 that is equal to yes),
1255                                             "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1256                                             "filters" (int) Include course filters  (default to 1 that is equal to yes),
1257                                             "users" (int) Include users (default to 0 that is equal to no),
1258                                             "enrolments" (int) Include enrolment methods (default to 1 - restore only with users),
1259                                             "role_assignments" (int) Include role assignments  (default to 0 that is equal to no),
1260                                             "comments" (int) Include user comments  (default to 0 that is equal to no),
1261                                             "userscompletion" (int) Include user course completion information  (default to 0 that is equal to no),
1262                                             "logs" (int) Include course logs  (default to 0 that is equal to no),
1263                                             "grade_histories" (int) Include histories  (default to 0 that is equal to no)'
1264                                             ),
1265                                 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1266                             )
1267                         )
1268                     ), VALUE_DEFAULT, array()
1269                 ),
1270             )
1271         );
1272     }
1274     /**
1275      * Duplicate a course
1276      *
1277      * @param int $courseid
1278      * @param string $fullname Duplicated course fullname
1279      * @param string $shortname Duplicated course shortname
1280      * @param int $categoryid Duplicated course parent category id
1281      * @param int $visible Duplicated course availability
1282      * @param array $options List of backup options
1283      * @return array New course info
1284      * @since Moodle 2.3
1285      */
1286     public static function duplicate_course($courseid, $fullname, $shortname, $categoryid, $visible = 1, $options = array()) {
1287         global $CFG, $USER, $DB;
1288         require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1289         require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1291         // Parameter validation.
1292         $params = self::validate_parameters(
1293                 self::duplicate_course_parameters(),
1294                 array(
1295                       'courseid' => $courseid,
1296                       'fullname' => $fullname,
1297                       'shortname' => $shortname,
1298                       'categoryid' => $categoryid,
1299                       'visible' => $visible,
1300                       'options' => $options
1301                 )
1302         );
1304         // Context validation.
1306         if (! ($course = $DB->get_record('course', array('id'=>$params['courseid'])))) {
1307             throw new moodle_exception('invalidcourseid', 'error');
1308         }
1310         // Category where duplicated course is going to be created.
1311         $categorycontext = context_coursecat::instance($params['categoryid']);
1312         self::validate_context($categorycontext);
1314         // Course to be duplicated.
1315         $coursecontext = context_course::instance($course->id);
1316         self::validate_context($coursecontext);
1318         $backupdefaults = array(
1319             'activities' => 1,
1320             'blocks' => 1,
1321             'filters' => 1,
1322             'users' => 0,
1323             'enrolments' => backup::ENROL_WITHUSERS,
1324             'role_assignments' => 0,
1325             'comments' => 0,
1326             'userscompletion' => 0,
1327             'logs' => 0,
1328             'grade_histories' => 0
1329         );
1331         $backupsettings = array();
1332         // Check for backup and restore options.
1333         if (!empty($params['options'])) {
1334             foreach ($params['options'] as $option) {
1336                 // Strict check for a correct value (allways 1 or 0, true or false).
1337                 $value = clean_param($option['value'], PARAM_INT);
1339                 if ($value !== 0 and $value !== 1) {
1340                     throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1341                 }
1343                 if (!isset($backupdefaults[$option['name']])) {
1344                     throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1345                 }
1347                 $backupsettings[$option['name']] = $value;
1348             }
1349         }
1351         // Capability checking.
1353         // The backup controller check for this currently, this may be redundant.
1354         require_capability('moodle/course:create', $categorycontext);
1355         require_capability('moodle/restore:restorecourse', $categorycontext);
1356         require_capability('moodle/backup:backupcourse', $coursecontext);
1358         if (!empty($backupsettings['users'])) {
1359             require_capability('moodle/backup:userinfo', $coursecontext);
1360             require_capability('moodle/restore:userinfo', $categorycontext);
1361         }
1363         // Check if the shortname is used.
1364         if ($foundcourses = $DB->get_records('course', array('shortname'=>$shortname))) {
1365             foreach ($foundcourses as $foundcourse) {
1366                 $foundcoursenames[] = $foundcourse->fullname;
1367             }
1369             $foundcoursenamestring = implode(',', $foundcoursenames);
1370             throw new moodle_exception('shortnametaken', '', '', $foundcoursenamestring);
1371         }
1373         // Backup the course.
1375         $bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE,
1376         backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id);
1378         foreach ($backupsettings as $name => $value) {
1379             if ($setting = $bc->get_plan()->get_setting($name)) {
1380                 $bc->get_plan()->get_setting($name)->set_value($value);
1381             }
1382         }
1384         $backupid       = $bc->get_backupid();
1385         $backupbasepath = $bc->get_plan()->get_basepath();
1387         $bc->execute_plan();
1388         $results = $bc->get_results();
1389         $file = $results['backup_destination'];
1391         $bc->destroy();
1393         // Restore the backup immediately.
1395         // Check if we need to unzip the file because the backup temp dir does not contains backup files.
1396         if (!file_exists($backupbasepath . "/moodle_backup.xml")) {
1397             $file->extract_to_pathname(get_file_packer('application/vnd.moodle.backup'), $backupbasepath);
1398         }
1400         // Create new course.
1401         $newcourseid = restore_dbops::create_new_course($params['fullname'], $params['shortname'], $params['categoryid']);
1403         $rc = new restore_controller($backupid, $newcourseid,
1404                 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id, backup::TARGET_NEW_COURSE);
1406         foreach ($backupsettings as $name => $value) {
1407             $setting = $rc->get_plan()->get_setting($name);
1408             if ($setting->get_status() == backup_setting::NOT_LOCKED) {
1409                 $setting->set_value($value);
1410             }
1411         }
1413         if (!$rc->execute_precheck()) {
1414             $precheckresults = $rc->get_precheck_results();
1415             if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1416                 if (empty($CFG->keeptempdirectoriesonbackup)) {
1417                     fulldelete($backupbasepath);
1418                 }
1420                 $errorinfo = '';
1422                 foreach ($precheckresults['errors'] as $error) {
1423                     $errorinfo .= $error;
1424                 }
1426                 if (array_key_exists('warnings', $precheckresults)) {
1427                     foreach ($precheckresults['warnings'] as $warning) {
1428                         $errorinfo .= $warning;
1429                     }
1430                 }
1432                 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1433             }
1434         }
1436         $rc->execute_plan();
1437         $rc->destroy();
1439         $course = $DB->get_record('course', array('id' => $newcourseid), '*', MUST_EXIST);
1440         $course->fullname = $params['fullname'];
1441         $course->shortname = $params['shortname'];
1442         $course->visible = $params['visible'];
1444         // Set shortname and fullname back.
1445         $DB->update_record('course', $course);
1447         if (empty($CFG->keeptempdirectoriesonbackup)) {
1448             fulldelete($backupbasepath);
1449         }
1451         // Delete the course backup file created by this WebService. Originally located in the course backups area.
1452         $file->delete();
1454         return array('id' => $course->id, 'shortname' => $course->shortname);
1455     }
1457     /**
1458      * Returns description of method result value
1459      *
1460      * @return external_description
1461      * @since Moodle 2.3
1462      */
1463     public static function duplicate_course_returns() {
1464         return new external_single_structure(
1465             array(
1466                 'id'       => new external_value(PARAM_INT, 'course id'),
1467                 'shortname' => new external_value(PARAM_TEXT, 'short name'),
1468             )
1469         );
1470     }
1472     /**
1473      * Returns description of method parameters for import_course
1474      *
1475      * @return external_function_parameters
1476      * @since Moodle 2.4
1477      */
1478     public static function import_course_parameters() {
1479         return new external_function_parameters(
1480             array(
1481                 'importfrom' => new external_value(PARAM_INT, 'the id of the course we are importing from'),
1482                 'importto' => new external_value(PARAM_INT, 'the id of the course we are importing to'),
1483                 'deletecontent' => new external_value(PARAM_INT, 'whether to delete the course content where we are importing to (default to 0 = No)', VALUE_DEFAULT, 0),
1484                 'options' => new external_multiple_structure(
1485                     new external_single_structure(
1486                         array(
1487                                 'name' => new external_value(PARAM_ALPHA, 'The backup option name:
1488                                             "activities" (int) Include course activites (default to 1 that is equal to yes),
1489                                             "blocks" (int) Include course blocks (default to 1 that is equal to yes),
1490                                             "filters" (int) Include course filters  (default to 1 that is equal to yes)'
1491                                             ),
1492                                 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)'
1493                             )
1494                         )
1495                     ), VALUE_DEFAULT, array()
1496                 ),
1497             )
1498         );
1499     }
1501     /**
1502      * Imports a course
1503      *
1504      * @param int $importfrom The id of the course we are importing from
1505      * @param int $importto The id of the course we are importing to
1506      * @param bool $deletecontent Whether to delete the course we are importing to content
1507      * @param array $options List of backup options
1508      * @return null
1509      * @since Moodle 2.4
1510      */
1511     public static function import_course($importfrom, $importto, $deletecontent = 0, $options = array()) {
1512         global $CFG, $USER, $DB;
1513         require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
1514         require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
1516         // Parameter validation.
1517         $params = self::validate_parameters(
1518             self::import_course_parameters(),
1519             array(
1520                 'importfrom' => $importfrom,
1521                 'importto' => $importto,
1522                 'deletecontent' => $deletecontent,
1523                 'options' => $options
1524             )
1525         );
1527         if ($params['deletecontent'] !== 0 and $params['deletecontent'] !== 1) {
1528             throw new moodle_exception('invalidextparam', 'webservice', '', $params['deletecontent']);
1529         }
1531         // Context validation.
1533         if (! ($importfrom = $DB->get_record('course', array('id'=>$params['importfrom'])))) {
1534             throw new moodle_exception('invalidcourseid', 'error');
1535         }
1537         if (! ($importto = $DB->get_record('course', array('id'=>$params['importto'])))) {
1538             throw new moodle_exception('invalidcourseid', 'error');
1539         }
1541         $importfromcontext = context_course::instance($importfrom->id);
1542         self::validate_context($importfromcontext);
1544         $importtocontext = context_course::instance($importto->id);
1545         self::validate_context($importtocontext);
1547         $backupdefaults = array(
1548             'activities' => 1,
1549             'blocks' => 1,
1550             'filters' => 1
1551         );
1553         $backupsettings = array();
1555         // Check for backup and restore options.
1556         if (!empty($params['options'])) {
1557             foreach ($params['options'] as $option) {
1559                 // Strict check for a correct value (allways 1 or 0, true or false).
1560                 $value = clean_param($option['value'], PARAM_INT);
1562                 if ($value !== 0 and $value !== 1) {
1563                     throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1564                 }
1566                 if (!isset($backupdefaults[$option['name']])) {
1567                     throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']);
1568                 }
1570                 $backupsettings[$option['name']] = $value;
1571             }
1572         }
1574         // Capability checking.
1576         require_capability('moodle/backup:backuptargetimport', $importfromcontext);
1577         require_capability('moodle/restore:restoretargetimport', $importtocontext);
1579         $bc = new backup_controller(backup::TYPE_1COURSE, $importfrom->id, backup::FORMAT_MOODLE,
1580                 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
1582         foreach ($backupsettings as $name => $value) {
1583             $bc->get_plan()->get_setting($name)->set_value($value);
1584         }
1586         $backupid       = $bc->get_backupid();
1587         $backupbasepath = $bc->get_plan()->get_basepath();
1589         $bc->execute_plan();
1590         $bc->destroy();
1592         // Restore the backup immediately.
1594         // Check if we must delete the contents of the destination course.
1595         if ($params['deletecontent']) {
1596             $restoretarget = backup::TARGET_EXISTING_DELETING;
1597         } else {
1598             $restoretarget = backup::TARGET_EXISTING_ADDING;
1599         }
1601         $rc = new restore_controller($backupid, $importto->id,
1602                 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, $restoretarget);
1604         foreach ($backupsettings as $name => $value) {
1605             $rc->get_plan()->get_setting($name)->set_value($value);
1606         }
1608         if (!$rc->execute_precheck()) {
1609             $precheckresults = $rc->get_precheck_results();
1610             if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
1611                 if (empty($CFG->keeptempdirectoriesonbackup)) {
1612                     fulldelete($backupbasepath);
1613                 }
1615                 $errorinfo = '';
1617                 foreach ($precheckresults['errors'] as $error) {
1618                     $errorinfo .= $error;
1619                 }
1621                 if (array_key_exists('warnings', $precheckresults)) {
1622                     foreach ($precheckresults['warnings'] as $warning) {
1623                         $errorinfo .= $warning;
1624                     }
1625                 }
1627                 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo);
1628             }
1629         } else {
1630             if ($restoretarget == backup::TARGET_EXISTING_DELETING) {
1631                 restore_dbops::delete_course_content($importto->id);
1632             }
1633         }
1635         $rc->execute_plan();
1636         $rc->destroy();
1638         if (empty($CFG->keeptempdirectoriesonbackup)) {
1639             fulldelete($backupbasepath);
1640         }
1642         return null;
1643     }
1645     /**
1646      * Returns description of method result value
1647      *
1648      * @return external_description
1649      * @since Moodle 2.4
1650      */
1651     public static function import_course_returns() {
1652         return null;
1653     }
1655     /**
1656      * Returns description of method parameters
1657      *
1658      * @return external_function_parameters
1659      * @since Moodle 2.3
1660      */
1661     public static function get_categories_parameters() {
1662         return new external_function_parameters(
1663             array(
1664                 'criteria' => new external_multiple_structure(
1665                     new external_single_structure(
1666                         array(
1667                             'key' => new external_value(PARAM_ALPHA,
1668                                          'The category column to search, expected keys (value format) are:'.
1669                                          '"id" (int) the category id,'.
1670                                          '"ids" (string) category ids separated by commas,'.
1671                                          '"name" (string) the category name,'.
1672                                          '"parent" (int) the parent category id,'.
1673                                          '"idnumber" (string) category idnumber'.
1674                                          ' - user must have \'moodle/category:manage\' to search on idnumber,'.
1675                                          '"visible" (int) whether the returned categories must be visible or hidden. If the key is not passed,
1676                                              then the function return all categories that the user can see.'.
1677                                          ' - user must have \'moodle/category:manage\' or \'moodle/category:viewhiddencategories\' to search on visible,'.
1678                                          '"theme" (string) only return the categories having this theme'.
1679                                          ' - user must have \'moodle/category:manage\' to search on theme'),
1680                             'value' => new external_value(PARAM_RAW, 'the value to match')
1681                         )
1682                     ), 'criteria', VALUE_DEFAULT, array()
1683                 ),
1684                 'addsubcategories' => new external_value(PARAM_BOOL, 'return the sub categories infos
1685                                           (1 - default) otherwise only the category info (0)', VALUE_DEFAULT, 1)
1686             )
1687         );
1688     }
1690     /**
1691      * Get categories
1692      *
1693      * @param array $criteria Criteria to match the results
1694      * @param booln $addsubcategories obtain only the category (false) or its subcategories (true - default)
1695      * @return array list of categories
1696      * @since Moodle 2.3
1697      */
1698     public static function get_categories($criteria = array(), $addsubcategories = true) {
1699         global $CFG, $DB;
1700         require_once($CFG->dirroot . "/course/lib.php");
1702         // Validate parameters.
1703         $params = self::validate_parameters(self::get_categories_parameters(),
1704                 array('criteria' => $criteria, 'addsubcategories' => $addsubcategories));
1706         // Retrieve the categories.
1707         $categories = array();
1708         if (!empty($params['criteria'])) {
1710             $conditions = array();
1711             $wheres = array();
1712             foreach ($params['criteria'] as $crit) {
1713                 $key = trim($crit['key']);
1715                 // Trying to avoid duplicate keys.
1716                 if (!isset($conditions[$key])) {
1718                     $context = context_system::instance();
1719                     $value = null;
1720                     switch ($key) {
1721                         case 'id':
1722                             $value = clean_param($crit['value'], PARAM_INT);
1723                             $conditions[$key] = $value;
1724                             $wheres[] = $key . " = :" . $key;
1725                             break;
1727                         case 'ids':
1728                             $value = clean_param($crit['value'], PARAM_SEQUENCE);
1729                             $ids = explode(',', $value);
1730                             list($sqlids, $paramids) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED);
1731                             $conditions = array_merge($conditions, $paramids);
1732                             $wheres[] = 'id ' . $sqlids;
1733                             break;
1735                         case 'idnumber':
1736                             if (has_capability('moodle/category:manage', $context)) {
1737                                 $value = clean_param($crit['value'], PARAM_RAW);
1738                                 $conditions[$key] = $value;
1739                                 $wheres[] = $key . " = :" . $key;
1740                             } else {
1741                                 // We must throw an exception.
1742                                 // Otherwise the dev client would think no idnumber exists.
1743                                 throw new moodle_exception('criteriaerror',
1744                                         'webservice', '', null,
1745                                         'You don\'t have the permissions to search on the "idnumber" field.');
1746                             }
1747                             break;
1749                         case 'name':
1750                             $value = clean_param($crit['value'], PARAM_TEXT);
1751                             $conditions[$key] = $value;
1752                             $wheres[] = $key . " = :" . $key;
1753                             break;
1755                         case 'parent':
1756                             $value = clean_param($crit['value'], PARAM_INT);
1757                             $conditions[$key] = $value;
1758                             $wheres[] = $key . " = :" . $key;
1759                             break;
1761                         case 'visible':
1762                             if (has_capability('moodle/category:viewhiddencategories', $context)) {
1763                                 $value = clean_param($crit['value'], PARAM_INT);
1764                                 $conditions[$key] = $value;
1765                                 $wheres[] = $key . " = :" . $key;
1766                             } else {
1767                                 throw new moodle_exception('criteriaerror',
1768                                         'webservice', '', null,
1769                                         'You don\'t have the permissions to search on the "visible" field.');
1770                             }
1771                             break;
1773                         case 'theme':
1774                             if (has_capability('moodle/category:manage', $context)) {
1775                                 $value = clean_param($crit['value'], PARAM_THEME);
1776                                 $conditions[$key] = $value;
1777                                 $wheres[] = $key . " = :" . $key;
1778                             } else {
1779                                 throw new moodle_exception('criteriaerror',
1780                                         'webservice', '', null,
1781                                         'You don\'t have the permissions to search on the "theme" field.');
1782                             }
1783                             break;
1785                         default:
1786                             throw new moodle_exception('criteriaerror',
1787                                     'webservice', '', null,
1788                                     'You can not search on this criteria: ' . $key);
1789                     }
1790                 }
1791             }
1793             if (!empty($wheres)) {
1794                 $wheres = implode(" AND ", $wheres);
1796                 $categories = $DB->get_records_select('course_categories', $wheres, $conditions);
1798                 // Retrieve its sub subcategories (all levels).
1799                 if ($categories and !empty($params['addsubcategories'])) {
1800                     $newcategories = array();
1802                     // Check if we required visible/theme checks.
1803                     $additionalselect = '';
1804                     $additionalparams = array();
1805                     if (isset($conditions['visible'])) {
1806                         $additionalselect .= ' AND visible = :visible';
1807                         $additionalparams['visible'] = $conditions['visible'];
1808                     }
1809                     if (isset($conditions['theme'])) {
1810                         $additionalselect .= ' AND theme= :theme';
1811                         $additionalparams['theme'] = $conditions['theme'];
1812                     }
1814                     foreach ($categories as $category) {
1815                         $sqlselect = $DB->sql_like('path', ':path') . $additionalselect;
1816                         $sqlparams = array('path' => $category->path.'/%') + $additionalparams; // It will NOT include the specified category.
1817                         $subcategories = $DB->get_records_select('course_categories', $sqlselect, $sqlparams);
1818                         $newcategories = $newcategories + $subcategories;   // Both arrays have integer as keys.
1819                     }
1820                     $categories = $categories + $newcategories;
1821                 }
1822             }
1824         } else {
1825             // Retrieve all categories in the database.
1826             $categories = $DB->get_records('course_categories');
1827         }
1829         // The not returned categories. key => category id, value => reason of exclusion.
1830         $excludedcats = array();
1832         // The returned categories.
1833         $categoriesinfo = array();
1835         // We need to sort the categories by path.
1836         // The parent cats need to be checked by the algo first.
1837         usort($categories, "core_course_external::compare_categories_by_path");
1839         foreach ($categories as $category) {
1841             // Check if the category is a child of an excluded category, if yes exclude it too (excluded => do not return).
1842             $parents = explode('/', $category->path);
1843             unset($parents[0]); // First key is always empty because path start with / => /1/2/4.
1844             foreach ($parents as $parentid) {
1845                 // Note: when the parent exclusion was due to the context,
1846                 // the sub category could still be returned.
1847                 if (isset($excludedcats[$parentid]) and $excludedcats[$parentid] != 'context') {
1848                     $excludedcats[$category->id] = 'parent';
1849                 }
1850             }
1852             // Check the user can use the category context.
1853             $context = context_coursecat::instance($category->id);
1854             try {
1855                 self::validate_context($context);
1856             } catch (Exception $e) {
1857                 $excludedcats[$category->id] = 'context';
1859                 // If it was the requested category then throw an exception.
1860                 if (isset($params['categoryid']) && $category->id == $params['categoryid']) {
1861                     $exceptionparam = new stdClass();
1862                     $exceptionparam->message = $e->getMessage();
1863                     $exceptionparam->catid = $category->id;
1864                     throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
1865                 }
1866             }
1868             // Return the category information.
1869             if (!isset($excludedcats[$category->id])) {
1871                 // Final check to see if the category is visible to the user.
1872                 if ($category->visible or has_capability('moodle/category:viewhiddencategories', $context)) {
1874                     $categoryinfo = array();
1875                     $categoryinfo['id'] = $category->id;
1876                     $categoryinfo['name'] = external_format_string($category->name, $context);
1877                     list($categoryinfo['description'], $categoryinfo['descriptionformat']) =
1878                         external_format_text($category->description, $category->descriptionformat,
1879                                 $context->id, 'coursecat', 'description', null);
1880                     $categoryinfo['parent'] = $category->parent;
1881                     $categoryinfo['sortorder'] = $category->sortorder;
1882                     $categoryinfo['coursecount'] = $category->coursecount;
1883                     $categoryinfo['depth'] = $category->depth;
1884                     $categoryinfo['path'] = $category->path;
1886                     // Some fields only returned for admin.
1887                     if (has_capability('moodle/category:manage', $context)) {
1888                         $categoryinfo['idnumber'] = $category->idnumber;
1889                         $categoryinfo['visible'] = $category->visible;
1890                         $categoryinfo['visibleold'] = $category->visibleold;
1891                         $categoryinfo['timemodified'] = $category->timemodified;
1892                         $categoryinfo['theme'] = clean_param($category->theme, PARAM_THEME);
1893                     }
1895                     $categoriesinfo[] = $categoryinfo;
1896                 } else {
1897                     $excludedcats[$category->id] = 'visibility';
1898                 }
1899             }
1900         }
1902         // Sorting the resulting array so it looks a bit better for the client developer.
1903         usort($categoriesinfo, "core_course_external::compare_categories_by_sortorder");
1905         return $categoriesinfo;
1906     }
1908     /**
1909      * Sort categories array by path
1910      * private function: only used by get_categories
1911      *
1912      * @param array $category1
1913      * @param array $category2
1914      * @return int result of strcmp
1915      * @since Moodle 2.3
1916      */
1917     private static function compare_categories_by_path($category1, $category2) {
1918         return strcmp($category1->path, $category2->path);
1919     }
1921     /**
1922      * Sort categories array by sortorder
1923      * private function: only used by get_categories
1924      *
1925      * @param array $category1
1926      * @param array $category2
1927      * @return int result of strcmp
1928      * @since Moodle 2.3
1929      */
1930     private static function compare_categories_by_sortorder($category1, $category2) {
1931         return strcmp($category1['sortorder'], $category2['sortorder']);
1932     }
1934     /**
1935      * Returns description of method result value
1936      *
1937      * @return external_description
1938      * @since Moodle 2.3
1939      */
1940     public static function get_categories_returns() {
1941         return new external_multiple_structure(
1942             new external_single_structure(
1943                 array(
1944                     'id' => new external_value(PARAM_INT, 'category id'),
1945                     'name' => new external_value(PARAM_TEXT, 'category name'),
1946                     'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
1947                     'description' => new external_value(PARAM_RAW, 'category description'),
1948                     'descriptionformat' => new external_format_value('description'),
1949                     'parent' => new external_value(PARAM_INT, 'parent category id'),
1950                     'sortorder' => new external_value(PARAM_INT, 'category sorting order'),
1951                     'coursecount' => new external_value(PARAM_INT, 'number of courses in this category'),
1952                     'visible' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1953                     'visibleold' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL),
1954                     'timemodified' => new external_value(PARAM_INT, 'timestamp', VALUE_OPTIONAL),
1955                     'depth' => new external_value(PARAM_INT, 'category depth'),
1956                     'path' => new external_value(PARAM_TEXT, 'category path'),
1957                     'theme' => new external_value(PARAM_THEME, 'category theme', VALUE_OPTIONAL),
1958                 ), 'List of categories'
1959             )
1960         );
1961     }
1963     /**
1964      * Returns description of method parameters
1965      *
1966      * @return external_function_parameters
1967      * @since Moodle 2.3
1968      */
1969     public static function create_categories_parameters() {
1970         return new external_function_parameters(
1971             array(
1972                 'categories' => new external_multiple_structure(
1973                         new external_single_structure(
1974                             array(
1975                                 'name' => new external_value(PARAM_TEXT, 'new category name'),
1976                                 'parent' => new external_value(PARAM_INT,
1977                                         'the parent category id inside which the new category will be created
1978                                          - set to 0 for a root category',
1979                                         VALUE_DEFAULT, 0),
1980                                 'idnumber' => new external_value(PARAM_RAW,
1981                                         'the new category idnumber', VALUE_OPTIONAL),
1982                                 'description' => new external_value(PARAM_RAW,
1983                                         'the new category description', VALUE_OPTIONAL),
1984                                 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
1985                                 'theme' => new external_value(PARAM_THEME,
1986                                         'the new category theme. This option must be enabled on moodle',
1987                                         VALUE_OPTIONAL),
1988                         )
1989                     )
1990                 )
1991             )
1992         );
1993     }
1995     /**
1996      * Create categories
1997      *
1998      * @param array $categories - see create_categories_parameters() for the array structure
1999      * @return array - see create_categories_returns() for the array structure
2000      * @since Moodle 2.3
2001      */
2002     public static function create_categories($categories) {
2003         global $DB;
2005         $params = self::validate_parameters(self::create_categories_parameters(),
2006                         array('categories' => $categories));
2008         $transaction = $DB->start_delegated_transaction();
2010         $createdcategories = array();
2011         foreach ($params['categories'] as $category) {
2012             if ($category['parent']) {
2013                 if (!$DB->record_exists('course_categories', array('id' => $category['parent']))) {
2014                     throw new moodle_exception('unknowcategory');
2015                 }
2016                 $context = context_coursecat::instance($category['parent']);
2017             } else {
2018                 $context = context_system::instance();
2019             }
2020             self::validate_context($context);
2021             require_capability('moodle/category:manage', $context);
2023             // this will validate format and throw an exception if there are errors
2024             external_validate_format($category['descriptionformat']);
2026             $newcategory = core_course_category::create($category);
2027             $context = context_coursecat::instance($newcategory->id);
2029             $createdcategories[] = array(
2030                 'id' => $newcategory->id,
2031                 'name' => external_format_string($newcategory->name, $context),
2032             );
2033         }
2035         $transaction->allow_commit();
2037         return $createdcategories;
2038     }
2040     /**
2041      * Returns description of method parameters
2042      *
2043      * @return external_function_parameters
2044      * @since Moodle 2.3
2045      */
2046     public static function create_categories_returns() {
2047         return new external_multiple_structure(
2048             new external_single_structure(
2049                 array(
2050                     'id' => new external_value(PARAM_INT, 'new category id'),
2051                     'name' => new external_value(PARAM_TEXT, 'new category name'),
2052                 )
2053             )
2054         );
2055     }
2057     /**
2058      * Returns description of method parameters
2059      *
2060      * @return external_function_parameters
2061      * @since Moodle 2.3
2062      */
2063     public static function update_categories_parameters() {
2064         return new external_function_parameters(
2065             array(
2066                 'categories' => new external_multiple_structure(
2067                     new external_single_structure(
2068                         array(
2069                             'id'       => new external_value(PARAM_INT, 'course id'),
2070                             'name' => new external_value(PARAM_TEXT, 'category name', VALUE_OPTIONAL),
2071                             'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL),
2072                             'parent' => new external_value(PARAM_INT, 'parent category id', VALUE_OPTIONAL),
2073                             'description' => new external_value(PARAM_RAW, 'category description', VALUE_OPTIONAL),
2074                             'descriptionformat' => new external_format_value('description', VALUE_DEFAULT),
2075                             'theme' => new external_value(PARAM_THEME,
2076                                     'the category theme. This option must be enabled on moodle', VALUE_OPTIONAL),
2077                         )
2078                     )
2079                 )
2080             )
2081         );
2082     }
2084     /**
2085      * Update categories
2086      *
2087      * @param array $categories The list of categories to update
2088      * @return null
2089      * @since Moodle 2.3
2090      */
2091     public static function update_categories($categories) {
2092         global $DB;
2094         // Validate parameters.
2095         $params = self::validate_parameters(self::update_categories_parameters(), array('categories' => $categories));
2097         $transaction = $DB->start_delegated_transaction();
2099         foreach ($params['categories'] as $cat) {
2100             $category = core_course_category::get($cat['id']);
2102             $categorycontext = context_coursecat::instance($cat['id']);
2103             self::validate_context($categorycontext);
2104             require_capability('moodle/category:manage', $categorycontext);
2106             // this will throw an exception if descriptionformat is not valid
2107             external_validate_format($cat['descriptionformat']);
2109             $category->update($cat);
2110         }
2112         $transaction->allow_commit();
2113     }
2115     /**
2116      * Returns description of method result value
2117      *
2118      * @return external_description
2119      * @since Moodle 2.3
2120      */
2121     public static function update_categories_returns() {
2122         return null;
2123     }
2125     /**
2126      * Returns description of method parameters
2127      *
2128      * @return external_function_parameters
2129      * @since Moodle 2.3
2130      */
2131     public static function delete_categories_parameters() {
2132         return new external_function_parameters(
2133             array(
2134                 'categories' => new external_multiple_structure(
2135                     new external_single_structure(
2136                         array(
2137                             'id' => new external_value(PARAM_INT, 'category id to delete'),
2138                             'newparent' => new external_value(PARAM_INT,
2139                                 'the parent category to move the contents to, if specified', VALUE_OPTIONAL),
2140                             'recursive' => new external_value(PARAM_BOOL, '1: recursively delete all contents inside this
2141                                 category, 0 (default): move contents to newparent or current parent category (except if parent is root)', VALUE_DEFAULT, 0)
2142                         )
2143                     )
2144                 )
2145             )
2146         );
2147     }
2149     /**
2150      * Delete categories
2151      *
2152      * @param array $categories A list of category ids
2153      * @return array
2154      * @since Moodle 2.3
2155      */
2156     public static function delete_categories($categories) {
2157         global $CFG, $DB;
2158         require_once($CFG->dirroot . "/course/lib.php");
2160         // Validate parameters.
2161         $params = self::validate_parameters(self::delete_categories_parameters(), array('categories' => $categories));
2163         $transaction = $DB->start_delegated_transaction();
2165         foreach ($params['categories'] as $category) {
2166             $deletecat = core_course_category::get($category['id'], MUST_EXIST);
2167             $context = context_coursecat::instance($deletecat->id);
2168             require_capability('moodle/category:manage', $context);
2169             self::validate_context($context);
2170             self::validate_context(get_category_or_system_context($deletecat->parent));
2172             if ($category['recursive']) {
2173                 // If recursive was specified, then we recursively delete the category's contents.
2174                 if ($deletecat->can_delete_full()) {
2175                     $deletecat->delete_full(false);
2176                 } else {
2177                     throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2178                 }
2179             } else {
2180                 // In this situation, we don't delete the category's contents, we either move it to newparent or parent.
2181                 // If the parent is the root, moving is not supported (because a course must always be inside a category).
2182                 // We must move to an existing category.
2183                 if (!empty($category['newparent'])) {
2184                     $newparentcat = core_course_category::get($category['newparent']);
2185                 } else {
2186                     $newparentcat = core_course_category::get($deletecat->parent);
2187                 }
2189                 // This operation is not allowed. We must move contents to an existing category.
2190                 if (!$newparentcat->id) {
2191                     throw new moodle_exception('movecatcontentstoroot');
2192                 }
2194                 self::validate_context(context_coursecat::instance($newparentcat->id));
2195                 if ($deletecat->can_move_content_to($newparentcat->id)) {
2196                     $deletecat->delete_move($newparentcat->id, false);
2197                 } else {
2198                     throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name());
2199                 }
2200             }
2201         }
2203         $transaction->allow_commit();
2204     }
2206     /**
2207      * Returns description of method parameters
2208      *
2209      * @return external_function_parameters
2210      * @since Moodle 2.3
2211      */
2212     public static function delete_categories_returns() {
2213         return null;
2214     }
2216     /**
2217      * Describes the parameters for delete_modules.
2218      *
2219      * @return external_function_parameters
2220      * @since Moodle 2.5
2221      */
2222     public static function delete_modules_parameters() {
2223         return new external_function_parameters (
2224             array(
2225                 'cmids' => new external_multiple_structure(new external_value(PARAM_INT, 'course module ID',
2226                         VALUE_REQUIRED, '', NULL_NOT_ALLOWED), 'Array of course module IDs'),
2227             )
2228         );
2229     }
2231     /**
2232      * Deletes a list of provided module instances.
2233      *
2234      * @param array $cmids the course module ids
2235      * @since Moodle 2.5
2236      */
2237     public static function delete_modules($cmids) {
2238         global $CFG, $DB;
2240         // Require course file containing the course delete module function.
2241         require_once($CFG->dirroot . "/course/lib.php");
2243         // Clean the parameters.
2244         $params = self::validate_parameters(self::delete_modules_parameters(), array('cmids' => $cmids));
2246         // Keep track of the course ids we have performed a capability check on to avoid repeating.
2247         $arrcourseschecked = array();
2249         foreach ($params['cmids'] as $cmid) {
2250             // Get the course module.
2251             $cm = $DB->get_record('course_modules', array('id' => $cmid), '*', MUST_EXIST);
2253             // Check if we have not yet confirmed they have permission in this course.
2254             if (!in_array($cm->course, $arrcourseschecked)) {
2255                 // Ensure the current user has required permission in this course.
2256                 $context = context_course::instance($cm->course);
2257                 self::validate_context($context);
2258                 // Add to the array.
2259                 $arrcourseschecked[] = $cm->course;
2260             }
2262             // Ensure they can delete this module.
2263             $modcontext = context_module::instance($cm->id);
2264             require_capability('moodle/course:manageactivities', $modcontext);
2266             // Delete the module.
2267             course_delete_module($cm->id);
2268         }
2269     }
2271     /**
2272      * Describes the delete_modules return value.
2273      *
2274      * @return external_single_structure
2275      * @since Moodle 2.5
2276      */
2277     public static function delete_modules_returns() {
2278         return null;
2279     }
2281     /**
2282      * Returns description of method parameters
2283      *
2284      * @return external_function_parameters
2285      * @since Moodle 2.9
2286      */
2287     public static function view_course_parameters() {
2288         return new external_function_parameters(
2289             array(
2290                 'courseid' => new external_value(PARAM_INT, 'id of the course'),
2291                 'sectionnumber' => new external_value(PARAM_INT, 'section number', VALUE_DEFAULT, 0)
2292             )
2293         );
2294     }
2296     /**
2297      * Trigger the course viewed event.
2298      *
2299      * @param int $courseid id of course
2300      * @param int $sectionnumber sectionnumber (0, 1, 2...)
2301      * @return array of warnings and status result
2302      * @since Moodle 2.9
2303      * @throws moodle_exception
2304      */
2305     public static function view_course($courseid, $sectionnumber = 0) {
2306         global $CFG;
2307         require_once($CFG->dirroot . "/course/lib.php");
2309         $params = self::validate_parameters(self::view_course_parameters(),
2310                                             array(
2311                                                 'courseid' => $courseid,
2312                                                 'sectionnumber' => $sectionnumber
2313                                             ));
2315         $warnings = array();
2317         $course = get_course($params['courseid']);
2318         $context = context_course::instance($course->id);
2319         self::validate_context($context);
2321         if (!empty($params['sectionnumber'])) {
2323             // Get section details and check it exists.
2324             $modinfo = get_fast_modinfo($course);
2325             $coursesection = $modinfo->get_section_info($params['sectionnumber'], MUST_EXIST);
2327             // Check user is allowed to see it.
2328             if (!$coursesection->uservisible) {
2329                 require_capability('moodle/course:viewhiddensections', $context);
2330             }
2331         }
2333         course_view($context, $params['sectionnumber']);
2335         $result = array();
2336         $result['status'] = true;
2337         $result['warnings'] = $warnings;
2338         return $result;
2339     }
2341     /**
2342      * Returns description of method result value
2343      *
2344      * @return external_description
2345      * @since Moodle 2.9
2346      */
2347     public static function view_course_returns() {
2348         return new external_single_structure(
2349             array(
2350                 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
2351                 'warnings' => new external_warnings()
2352             )
2353         );
2354     }
2356     /**
2357      * Returns description of method parameters
2358      *
2359      * @return external_function_parameters
2360      * @since Moodle 3.0
2361      */
2362     public static function search_courses_parameters() {
2363         return new external_function_parameters(
2364             array(
2365                 'criterianame'  => new external_value(PARAM_ALPHA, 'criteria name
2366                                                         (search, modulelist (only admins), blocklist (only admins), tagid)'),
2367                 'criteriavalue' => new external_value(PARAM_RAW, 'criteria value'),
2368                 'page'          => new external_value(PARAM_INT, 'page number (0 based)', VALUE_DEFAULT, 0),
2369                 'perpage'       => new external_value(PARAM_INT, 'items per page', VALUE_DEFAULT, 0),
2370                 'requiredcapabilities' => new external_multiple_structure(
2371                     new external_value(PARAM_CAPABILITY, 'Capability string used to filter courses by permission'),
2372                     'Optional list of required capabilities (used to filter the list)', VALUE_DEFAULT, array()
2373                 ),
2374                 'limittoenrolled' => new external_value(PARAM_BOOL, 'limit to enrolled courses', VALUE_DEFAULT, 0),
2375             )
2376         );
2377     }
2379     /**
2380      * Return the course information that is public (visible by every one)
2381      *
2382      * @param  core_course_list_element $course        course in list object
2383      * @param  stdClass       $coursecontext course context object
2384      * @return array the course information
2385      * @since  Moodle 3.2
2386      */
2387     protected static function get_course_public_information(core_course_list_element $course, $coursecontext) {
2389         static $categoriescache = array();
2391         // Category information.
2392         if (!array_key_exists($course->category, $categoriescache)) {
2393             $categoriescache[$course->category] = core_course_category::get($course->category, IGNORE_MISSING);
2394         }
2395         $category = $categoriescache[$course->category];
2397         // Retrieve course overview used files.
2398         $files = array();
2399         foreach ($course->get_course_overviewfiles() as $file) {
2400             $fileurl = moodle_url::make_webservice_pluginfile_url($file->get_contextid(), $file->get_component(),
2401                                                                     $file->get_filearea(), null, $file->get_filepath(),
2402                                                                     $file->get_filename())->out(false);
2403             $files[] = array(
2404                 'filename' => $file->get_filename(),
2405                 'fileurl' => $fileurl,
2406                 'filesize' => $file->get_filesize(),
2407                 'filepath' => $file->get_filepath(),
2408                 'mimetype' => $file->get_mimetype(),
2409                 'timemodified' => $file->get_timemodified(),
2410             );
2411         }
2413         // Retrieve the course contacts,
2414         // we need here the users fullname since if we are not enrolled can be difficult to obtain them via other Web Services.
2415         $coursecontacts = array();
2416         foreach ($course->get_course_contacts() as $contact) {
2417              $coursecontacts[] = array(
2418                 'id' => $contact['user']->id,
2419                 'fullname' => $contact['username'],
2420                 'roles' => array_map(function($role){
2421                     return array('id' => $role->id, 'name' => $role->displayname);
2422                 }, $contact['roles']),
2423                 'role' => array('id' => $contact['role']->id, 'name' => $contact['role']->displayname),
2424                 'rolename' => $contact['rolename']
2425              );
2426         }
2428         // Allowed enrolment methods (maybe we can self-enrol).
2429         $enroltypes = array();
2430         $instances = enrol_get_instances($course->id, true);
2431         foreach ($instances as $instance) {
2432             $enroltypes[] = $instance->enrol;
2433         }
2435         // Format summary.
2436         list($summary, $summaryformat) =
2437             external_format_text($course->summary, $course->summaryformat, $coursecontext->id, 'course', 'summary', null);
2439         $categoryname = '';
2440         if (!empty($category)) {
2441             $categoryname = external_format_string($category->name, $category->get_context());
2442         }
2444         $displayname = get_course_display_name_for_list($course);
2445         $coursereturns = array();
2446         $coursereturns['id']                = $course->id;
2447         $coursereturns['fullname']          = external_format_string($course->fullname, $coursecontext->id);
2448         $coursereturns['displayname']       = external_format_string($displayname, $coursecontext->id);
2449         $coursereturns['shortname']         = external_format_string($course->shortname, $coursecontext->id);
2450         $coursereturns['categoryid']        = $course->category;
2451         $coursereturns['categoryname']      = $categoryname;
2452         $coursereturns['summary']           = $summary;
2453         $coursereturns['summaryformat']     = $summaryformat;
2454         $coursereturns['summaryfiles']      = external_util::get_area_files($coursecontext->id, 'course', 'summary', false, false);
2455         $coursereturns['overviewfiles']     = $files;
2456         $coursereturns['contacts']          = $coursecontacts;
2457         $coursereturns['enrollmentmethods'] = $enroltypes;
2458         $coursereturns['sortorder']         = $course->sortorder;
2459         return $coursereturns;
2460     }
2462     /**
2463      * Search courses following the specified criteria.
2464      *
2465      * @param string $criterianame  Criteria name (search, modulelist (only admins), blocklist (only admins), tagid)
2466      * @param string $criteriavalue Criteria value
2467      * @param int $page             Page number (for pagination)
2468      * @param int $perpage          Items per page
2469      * @param array $requiredcapabilities Optional list of required capabilities (used to filter the list).
2470      * @param int $limittoenrolled  Limit to only enrolled courses
2471      * @return array of course objects and warnings
2472      * @since Moodle 3.0
2473      * @throws moodle_exception
2474      */
2475     public static function search_courses($criterianame,
2476                                           $criteriavalue,
2477                                           $page=0,
2478                                           $perpage=0,
2479                                           $requiredcapabilities=array(),
2480                                           $limittoenrolled=0) {
2481         global $CFG;
2483         $warnings = array();
2485         $parameters = array(
2486             'criterianame'  => $criterianame,
2487             'criteriavalue' => $criteriavalue,
2488             'page'          => $page,
2489             'perpage'       => $perpage,
2490             'requiredcapabilities' => $requiredcapabilities
2491         );
2492         $params = self::validate_parameters(self::search_courses_parameters(), $parameters);
2493         self::validate_context(context_system::instance());
2495         $allowedcriterianames = array('search', 'modulelist', 'blocklist', 'tagid');
2496         if (!in_array($params['criterianame'], $allowedcriterianames)) {
2497             throw new invalid_parameter_exception('Invalid value for criterianame parameter (value: '.$params['criterianame'].'),' .
2498                 'allowed values are: '.implode(',', $allowedcriterianames));
2499         }
2501         if ($params['criterianame'] == 'modulelist' or $params['criterianame'] == 'blocklist') {
2502             require_capability('moodle/site:config', context_system::instance());
2503         }
2505         $paramtype = array(
2506             'search' => PARAM_RAW,
2507             'modulelist' => PARAM_PLUGIN,
2508             'blocklist' => PARAM_INT,
2509             'tagid' => PARAM_INT
2510         );
2511         $params['criteriavalue'] = clean_param($params['criteriavalue'], $paramtype[$params['criterianame']]);
2513         // Prepare the search API options.
2514         $searchcriteria = array();
2515         $searchcriteria[$params['criterianame']] = $params['criteriavalue'];
2517         $options = array();
2518         if ($params['perpage'] != 0) {
2519             $offset = $params['page'] * $params['perpage'];
2520             $options = array('offset' => $offset, 'limit' => $params['perpage']);
2521         }
2523         // Search the courses.
2524         $courses = core_course_category::search_courses($searchcriteria, $options, $params['requiredcapabilities']);
2525         $totalcount = core_course_category::search_courses_count($searchcriteria, $options, $params['requiredcapabilities']);
2527         if (!empty($limittoenrolled)) {
2528             // Get the courses where the current user has access.
2529             $enrolled = enrol_get_my_courses(array('id', 'cacherev'));
2530         }
2532         $finalcourses = array();
2533         $categoriescache = array();
2535         foreach ($courses as $course) {
2536             if (!empty($limittoenrolled)) {
2537                 // Filter out not enrolled courses.
2538                 if (!isset($enrolled[$course->id])) {
2539                     $totalcount--;
2540                     continue;
2541                 }
2542             }
2544             $coursecontext = context_course::instance($course->id);
2546             $finalcourses[] = self::get_course_public_information($course, $coursecontext);
2547         }
2549         return array(
2550             'total' => $totalcount,
2551             'courses' => $finalcourses,
2552             'warnings' => $warnings
2553         );
2554     }
2556     /**
2557      * Returns a course structure definition
2558      *
2559      * @param  boolean $onlypublicdata set to true, to retrieve only fields viewable by anyone when the course is visible
2560      * @return array the course structure
2561      * @since  Moodle 3.2
2562      */
2563     protected static function get_course_structure($onlypublicdata = true) {
2564         $coursestructure = array(
2565             'id' => new external_value(PARAM_INT, 'course id'),
2566             'fullname' => new external_value(PARAM_TEXT, 'course full name'),
2567             'displayname' => new external_value(PARAM_TEXT, 'course display name'),
2568             'shortname' => new external_value(PARAM_TEXT, 'course short name'),
2569             'categoryid' => new external_value(PARAM_INT, 'category id'),
2570             'categoryname' => new external_value(PARAM_TEXT, 'category name'),
2571             'sortorder' => new external_value(PARAM_INT, 'Sort order in the category', VALUE_OPTIONAL),
2572             'summary' => new external_value(PARAM_RAW, 'summary'),
2573             'summaryformat' => new external_format_value('summary'),
2574             'summaryfiles' => new external_files('summary files in the summary field', VALUE_OPTIONAL),
2575             'overviewfiles' => new external_files('additional overview files attached to this course'),
2576             'contacts' => new external_multiple_structure(
2577                 new external_single_structure(
2578                     array(
2579                         'id' => new external_value(PARAM_INT, 'contact user id'),
2580                         'fullname'  => new external_value(PARAM_NOTAGS, 'contact user fullname'),
2581                     )
2582                 ),
2583                 'contact users'
2584             ),
2585             'enrollmentmethods' => new external_multiple_structure(
2586                 new external_value(PARAM_PLUGIN, 'enrollment method'),
2587                 'enrollment methods list'
2588             ),
2589             'customfields' => new external_multiple_structure(
2590                 new external_single_structure(
2591                     array(
2592                         'name' => new external_value(PARAM_RAW, 'The name of the custom field'),
2593                         'shortname' => new external_value(PARAM_RAW,
2594                             'The shortname of the custom field - to be able to build the field class in the code'),
2595                         'type'  => new external_value(PARAM_ALPHANUMEXT,
2596                             'The type of the custom field - text field, checkbox...'),
2597                         'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
2598                     )
2599                 ), 'Custom fields', VALUE_OPTIONAL),
2600         );
2602         if (!$onlypublicdata) {
2603             $extra = array(
2604                 'idnumber' => new external_value(PARAM_RAW, 'Id number', VALUE_OPTIONAL),
2605                 'format' => new external_value(PARAM_PLUGIN, 'Course format: weeks, topics, social, site,..', VALUE_OPTIONAL),
2606                 'showgrades' => new external_value(PARAM_INT, '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
2607                 'newsitems' => new external_value(PARAM_INT, 'Number of recent items appearing on the course page', VALUE_OPTIONAL),
2608                 'startdate' => new external_value(PARAM_INT, 'Timestamp when the course start', VALUE_OPTIONAL),
2609                 'enddate' => new external_value(PARAM_INT, 'Timestamp when the course end', VALUE_OPTIONAL),
2610                 'maxbytes' => new external_value(PARAM_INT, 'Largest size of file that can be uploaded into', VALUE_OPTIONAL),
2611                 'showreports' => new external_value(PARAM_INT, 'Are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
2612                 'visible' => new external_value(PARAM_INT, '1: available to student, 0:not available', VALUE_OPTIONAL),
2613                 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
2614                 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
2615                 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
2616                 'enablecompletion' => new external_value(PARAM_INT, 'Completion enabled? 1: yes 0: no', VALUE_OPTIONAL),
2617                 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
2618                 'lang' => new external_value(PARAM_SAFEDIR, 'Forced course language', VALUE_OPTIONAL),
2619                 'theme' => new external_value(PARAM_PLUGIN, 'Fame of the forced theme', VALUE_OPTIONAL),
2620                 'marker' => new external_value(PARAM_INT, 'Current course marker', VALUE_OPTIONAL),
2621                 'legacyfiles' => new external_value(PARAM_INT, 'If legacy files are enabled', VALUE_OPTIONAL),
2622                 'calendartype' => new external_value(PARAM_PLUGIN, 'Calendar type', VALUE_OPTIONAL),
2623                 'timecreated' => new external_value(PARAM_INT, 'Time when the course was created', VALUE_OPTIONAL),
2624                 'timemodified' => new external_value(PARAM_INT, 'Last time  the course was updated', VALUE_OPTIONAL),
2625                 'requested' => new external_value(PARAM_INT, 'If is a requested course', VALUE_OPTIONAL),
2626                 'cacherev' => new external_value(PARAM_INT, 'Cache revision number', VALUE_OPTIONAL),
2627                 'filters' => new external_multiple_structure(
2628                     new external_single_structure(
2629                         array(
2630                             'filter'  => new external_value(PARAM_PLUGIN, 'Filter plugin name'),
2631                             'localstate' => new external_value(PARAM_INT, 'Filter state: 1 for on, -1 for off, 0 if inherit'),
2632                             'inheritedstate' => new external_value(PARAM_INT, '1 or 0 to use when localstate is set to inherit'),
2633                         )
2634                     ),
2635                     'Course filters', VALUE_OPTIONAL
2636                 ),
2637                 'courseformatoptions' => new external_multiple_structure(
2638                     new external_single_structure(
2639                         array(
2640                             'name' => new external_value(PARAM_RAW, 'Course format option name.'),
2641                             'value' => new external_value(PARAM_RAW, 'Course format option value.'),
2642                         )
2643                     ),
2644                     'Additional options for particular course format.', VALUE_OPTIONAL
2645                 ),
2646             );
2647             $coursestructure = array_merge($coursestructure, $extra);
2648         }
2649         return new external_single_structure($coursestructure);
2650     }
2652     /**
2653      * Returns description of method result value
2654      *
2655      * @return external_description
2656      * @since Moodle 3.0
2657      */
2658     public static function search_courses_returns() {
2659         return new external_single_structure(
2660             array(
2661                 'total' => new external_value(PARAM_INT, 'total course count'),
2662                 'courses' => new external_multiple_structure(self::get_course_structure(), 'course'),
2663                 'warnings' => new external_warnings()
2664             )
2665         );
2666     }
2668     /**
2669      * Returns description of method parameters
2670      *
2671      * @return external_function_parameters
2672      * @since Moodle 3.0
2673      */
2674     public static function get_course_module_parameters() {
2675         return new external_function_parameters(
2676             array(
2677                 'cmid' => new external_value(PARAM_INT, 'The course module id')
2678             )
2679         );
2680     }
2682     /**
2683      * Return information about a course module.
2684      *
2685      * @param int $cmid the course module id
2686      * @return array of warnings and the course module
2687      * @since Moodle 3.0
2688      * @throws moodle_exception
2689      */
2690     public static function get_course_module($cmid) {
2691         global $CFG, $DB;
2693         $params = self::validate_parameters(self::get_course_module_parameters(), array('cmid' => $cmid));
2694         $warnings = array();
2696         $cm = get_coursemodule_from_id(null, $params['cmid'], 0, true, MUST_EXIST);
2697         $context = context_module::instance($cm->id);
2698         self::validate_context($context);
2700         // If the user has permissions to manage the activity, return all the information.
2701         if (has_capability('moodle/course:manageactivities', $context)) {
2702             require_once($CFG->dirroot . '/course/modlib.php');
2703             require_once($CFG->libdir . '/gradelib.php');
2705             $info = $cm;
2706             // Get the extra information: grade, advanced grading and outcomes data.
2707             $course = get_course($cm->course);
2708             list($newcm, $newcontext, $module, $extrainfo, $cw) = get_moduleinfo_data($cm, $course);
2709             // Grades.
2710             $gradeinfo = array('grade', 'gradepass', 'gradecat');
2711             foreach ($gradeinfo as $gfield) {
2712                 if (isset($extrainfo->{$gfield})) {
2713                     $info->{$gfield} = $extrainfo->{$gfield};
2714                 }
2715             }
2716             if (isset($extrainfo->grade) and $extrainfo->grade < 0) {
2717                 $info->scale = $DB->get_field('scale', 'scale', array('id' => abs($extrainfo->grade)));
2718             }
2719             // Advanced grading.
2720             if (isset($extrainfo->_advancedgradingdata)) {
2721                 $info->advancedgrading = array();
2722                 foreach ($extrainfo as $key => $val) {
2723                     if (strpos($key, 'advancedgradingmethod_') === 0) {
2724                         $info->advancedgrading[] = array(
2725                             'area' => str_replace('advancedgradingmethod_', '', $key),
2726                             'method' => $val
2727                         );
2728                     }
2729                 }
2730             }
2731             // Outcomes.
2732             foreach ($extrainfo as $key => $val) {
2733                 if (strpos($key, 'outcome_') === 0) {
2734                     if (!isset($info->outcomes)) {
2735                         $info->outcomes = array();
2736                     }
2737                     $id = str_replace('outcome_', '', $key);
2738                     $outcome = grade_outcome::fetch(array('id' => $id));
2739                     $scaleitems = $outcome->load_scale();
2740                     $info->outcomes[] = array(
2741                         'id' => $id,
2742                         'name' => external_format_string($outcome->get_name(), $context->id),
2743                         'scale' => $scaleitems->scale
2744                     );
2745                 }
2746             }
2747         } else {
2748             // Return information is safe to show to any user.
2749             $info = new stdClass();
2750             $info->id = $cm->id;
2751             $info->course = $cm->course;
2752             $info->module = $cm->module;
2753             $info->modname = $cm->modname;
2754             $info->instance = $cm->instance;
2755             $info->section = $cm->section;
2756             $info->sectionnum = $cm->sectionnum;
2757             $info->groupmode = $cm->groupmode;
2758             $info->groupingid = $cm->groupingid;
2759             $info->completion = $cm->completion;
2760         }
2761         // Format name.
2762         $info->name = external_format_string($cm->name, $context->id);
2763         $result = array();
2764         $result['cm'] = $info;
2765         $result['warnings'] = $warnings;
2766         return $result;
2767     }
2769     /**
2770      * Returns description of method result value
2771      *
2772      * @return external_description
2773      * @since Moodle 3.0
2774      */
2775     public static function get_course_module_returns() {
2776         return new external_single_structure(
2777             array(
2778                 'cm' => new external_single_structure(
2779                     array(
2780                         'id' => new external_value(PARAM_INT, 'The course module id'),
2781                         'course' => new external_value(PARAM_INT, 'The course id'),
2782                         'module' => new external_value(PARAM_INT, 'The module type id'),
2783                         'name' => new external_value(PARAM_RAW, 'The activity name'),
2784                         'modname' => new external_value(PARAM_COMPONENT, 'The module component name (forum, assign, etc..)'),
2785                         'instance' => new external_value(PARAM_INT, 'The activity instance id'),
2786                         'section' => new external_value(PARAM_INT, 'The module section id'),
2787                         'sectionnum' => new external_value(PARAM_INT, 'The module section number'),
2788                         'groupmode' => new external_value(PARAM_INT, 'Group mode'),
2789                         'groupingid' => new external_value(PARAM_INT, 'Grouping id'),
2790                         'completion' => new external_value(PARAM_INT, 'If completion is enabled'),
2791                         'idnumber' => new external_value(PARAM_RAW, 'Module id number', VALUE_OPTIONAL),
2792                         'added' => new external_value(PARAM_INT, 'Time added', VALUE_OPTIONAL),
2793                         'score' => new external_value(PARAM_INT, 'Score', VALUE_OPTIONAL),
2794                         'indent' => new external_value(PARAM_INT, 'Indentation', VALUE_OPTIONAL),
2795                         'visible' => new external_value(PARAM_INT, 'If visible', VALUE_OPTIONAL),
2796                         'visibleoncoursepage' => new external_value(PARAM_INT, 'If visible on course page', VALUE_OPTIONAL),
2797                         'visibleold' => new external_value(PARAM_INT, 'Visible old', VALUE_OPTIONAL),
2798                         'completiongradeitemnumber' => new external_value(PARAM_INT, 'Completion grade item', VALUE_OPTIONAL),
2799                         'completionview' => new external_value(PARAM_INT, 'Completion view setting', VALUE_OPTIONAL),
2800                         'completionexpected' => new external_value(PARAM_INT, 'Completion time expected', VALUE_OPTIONAL),
2801                         'showdescription' => new external_value(PARAM_INT, 'If the description is showed', VALUE_OPTIONAL),
2802                         'availability' => new external_value(PARAM_RAW, 'Availability settings', VALUE_OPTIONAL),
2803                         'grade' => new external_value(PARAM_FLOAT, 'Grade (max value or scale id)', VALUE_OPTIONAL),
2804                         'scale' => new external_value(PARAM_TEXT, 'Scale items (if used)', VALUE_OPTIONAL),
2805                         'gradepass' => new external_value(PARAM_RAW, 'Grade to pass (float)', VALUE_OPTIONAL),
2806                         'gradecat' => new external_value(PARAM_INT, 'Grade category', VALUE_OPTIONAL),
2807                         'advancedgrading' => new external_multiple_structure(
2808                             new external_single_structure(
2809                                 array(
2810                                     'area' => new external_value(PARAM_AREA, 'Gradable area name'),
2811                                     'method'  => new external_value(PARAM_COMPONENT, 'Grading method'),
2812                                 )
2813                             ),
2814                             'Advanced grading settings', VALUE_OPTIONAL
2815                         ),
2816                         'outcomes' => new external_multiple_structure(
2817                             new external_single_structure(
2818                                 array(
2819                                     'id' => new external_value(PARAM_ALPHANUMEXT, 'Outcome id'),
2820                                     'name'  => new external_value(PARAM_TEXT, 'Outcome full name'),
2821                                     'scale' => new external_value(PARAM_TEXT, 'Scale items')
2822                                 )
2823                             ),
2824                             'Outcomes information', VALUE_OPTIONAL
2825                         ),
2826                     )
2827                 ),
2828                 'warnings' => new external_warnings()
2829             )
2830         );
2831     }
2833     /**
2834      * Returns description of method parameters
2835      *
2836      * @return external_function_parameters
2837      * @since Moodle 3.0
2838      */
2839     public static function get_course_module_by_instance_parameters() {
2840         return new external_function_parameters(
2841             array(
2842                 'module' => new external_value(PARAM_COMPONENT, 'The module name'),
2843                 'instance' => new external_value(PARAM_INT, 'The module instance id')
2844             )
2845         );
2846     }
2848     /**
2849      * Return information about a course module.
2850      *
2851      * @param string $module the module name
2852      * @param int $instance the activity instance id
2853      * @return array of warnings and the course module
2854      * @since Moodle 3.0
2855      * @throws moodle_exception
2856      */
2857     public static function get_course_module_by_instance($module, $instance) {
2859         $params = self::validate_parameters(self::get_course_module_by_instance_parameters(),
2860                                             array(
2861                                                 'module' => $module,
2862                                                 'instance' => $instance,
2863                                             ));
2865         $warnings = array();
2866         $cm = get_coursemodule_from_instance($params['module'], $params['instance'], 0, false, MUST_EXIST);
2868         return self::get_course_module($cm->id);
2869     }
2871     /**
2872      * Returns description of method result value
2873      *
2874      * @return external_description
2875      * @since Moodle 3.0
2876      */
2877     public static function get_course_module_by_instance_returns() {
2878         return self::get_course_module_returns();
2879     }
2881     /**
2882      * Returns description of method parameters
2883      *
2884      * @deprecated since 3.3
2885      * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
2886      * @return external_function_parameters
2887      * @since Moodle 3.2
2888      */
2889     public static function get_activities_overview_parameters() {
2890         return new external_function_parameters(
2891             array(
2892                 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')),
2893             )
2894         );
2895     }
2897     /**
2898      * Return activities overview for the given courses.
2899      *
2900      * @deprecated since 3.3
2901      * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
2902      * @param array $courseids a list of course ids
2903      * @return array of warnings and the activities overview
2904      * @since Moodle 3.2
2905      * @throws moodle_exception
2906      */
2907     public static function get_activities_overview($courseids) {
2908         global $USER;
2910         // Parameter validation.
2911         $params = self::validate_parameters(self::get_activities_overview_parameters(), array('courseids' => $courseids));
2912         $courseoverviews = array();
2914         list($courses, $warnings) = external_util::validate_courses($params['courseids']);
2916         if (!empty($courses)) {
2917             // Add lastaccess to each course (required by print_overview function).
2918             // We need the complete user data, the ws server does not load a complete one.
2919             $user = get_complete_user_data('id', $USER->id);
2920             foreach ($courses as $course) {
2921                 if (isset($user->lastcourseaccess[$course->id])) {
2922                     $course->lastaccess = $user->lastcourseaccess[$course->id];
2923                 } else {
2924                     $course->lastaccess = 0;
2925                 }
2926             }
2928             $overviews = array();
2929             if ($modules = get_plugin_list_with_function('mod', 'print_overview')) {
2930                 foreach ($modules as $fname) {
2931                     $fname($courses, $overviews);
2932                 }
2933             }
2935             // Format output.
2936             foreach ($overviews as $courseid => $modules) {
2937                 $courseoverviews[$courseid]['id'] = $courseid;
2938                 $courseoverviews[$courseid]['overviews'] = array();
2940                 foreach ($modules as $modname => $overviewtext) {
2941                     $courseoverviews[$courseid]['overviews'][] = array(
2942                         'module' => $modname,
2943                         'overviewtext' => $overviewtext // This text doesn't need formatting.
2944                     );
2945                 }
2946             }
2947         }
2949         $result = array(
2950             'courses' => $courseoverviews,
2951             'warnings' => $warnings
2952         );
2953         return $result;
2954     }
2956     /**
2957      * Returns description of method result value
2958      *
2959      * @deprecated since 3.3
2960      * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
2961      * @return external_description
2962      * @since Moodle 3.2
2963      */
2964     public static function get_activities_overview_returns() {
2965         return new external_single_structure(
2966             array(
2967                 'courses' => new external_multiple_structure(
2968                     new external_single_structure(
2969                         array(
2970                             'id' => new external_value(PARAM_INT, 'Course id'),
2971                             'overviews' => new external_multiple_structure(
2972                                 new external_single_structure(
2973                                     array(
2974                                         'module' => new external_value(PARAM_PLUGIN, 'Module name'),
2975                                         'overviewtext' => new external_value(PARAM_RAW, 'Overview text'),
2976                                     )
2977                                 )