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