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