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