Differences Between: [Versions 310 and 311] [Versions 310 and 400] [Versions 310 and 401] [Versions 310 and 402] [Versions 310 and 403] [Versions 39 and 310]
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/>. 16 17 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 */ 26 27 defined('MOODLE_INTERNAL') || die; 28 29 use core_course\external\course_summary_exporter; 30 31 require_once("$CFG->libdir/externallib.php"); 32 require_once (__DIR__ . "/lib.php"); 33 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 { 44 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 } 76 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'); 90 91 //validate parameter 92 $params = self::validate_parameters(self::get_course_contents_parameters(), 93 array('courseid' => $courseid, 'options' => $options)); 94 95 $filters = array(); 96 if (!empty($params['options'])) { 97 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 } 134 135 //retrieve the course 136 $course = $DB->get_record('course', array('id' => $params['courseid']), '*', MUST_EXIST); 137 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 } 147 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 } 158 159 $canupdatecourse = has_capability('moodle/course:update', $context); 160 161 //create return value 162 $coursecontents = array(); 163 164 if ($canupdatecourse or $course->visible 165 or has_capability('moodle/course:viewhiddencourses', $context)) { 166 167 //retrieve sections 168 $modinfo = get_fast_modinfo($course); 169 $sections = $modinfo->get_section_info_all(); 170 $courseformat = course_get_format($course); 171 $coursenumsections = $courseformat->get_last_section_number(); 172 $stealthmodules = array(); // Array to keep all the modules available but not visible in a course section/topic. 173 174 $completioninfo = new completion_info($course); 175 176 //for each sections (first displayed to last displayed) 177 $modinfosections = $modinfo->get_sections(); 178 foreach ($sections as $key => $section) { 179 180 // This becomes true when we are filtering and we found the value to filter with. 181 $sectionfound = false; 182 183 // Filter by section id. 184 if (!empty($filters['sectionid'])) { 185 if ($section->id != $filters['sectionid']) { 186 continue; 187 } else { 188 $sectionfound = true; 189 } 190 } 191 192 // Filter by section number. Note that 0 is a valid section number. 193 if (isset($filters['sectionnumber'])) { 194 if ($key != $filters['sectionnumber']) { 195 continue; 196 } else { 197 $sectionfound = true; 198 } 199 } 200 201 // reset $sectioncontents 202 $sectionvalues = array(); 203 $sectionvalues['id'] = $section->id; 204 $sectionvalues['name'] = get_section_name($course, $section); 205 $sectionvalues['visible'] = $section->visible; 206 207 $options = (object) array('noclean' => true); 208 list($sectionvalues['summary'], $sectionvalues['summaryformat']) = 209 external_format_text($section->summary, $section->summaryformat, 210 $context->id, 'course', 'section', $section->id, $options); 211 $sectionvalues['section'] = $section->section; 212 $sectionvalues['hiddenbynumsections'] = $section->section > $coursenumsections ? 1 : 0; 213 $sectionvalues['uservisible'] = $section->uservisible; 214 if (!empty($section->availableinfo)) { 215 $sectionvalues['availabilityinfo'] = \core_availability\info::format_info($section->availableinfo, $course); 216 } 217 218 $sectioncontents = array(); 219 220 // For each module of the section. 221 if (empty($filters['excludemodules']) and !empty($modinfosections[$section->section])) { 222 foreach ($modinfosections[$section->section] as $cmid) { 223 $cm = $modinfo->cms[$cmid]; 224 225 // Stop here if the module is not visible to the user on the course main page: 226 // The user can't access the module and the user can't view the module on the course page. 227 if (!$cm->uservisible && !$cm->is_visible_on_course_page()) { 228 continue; 229 } 230 231 // This becomes true when we are filtering and we found the value to filter with. 232 $modfound = false; 233 234 // Filter by cmid. 235 if (!empty($filters['cmid'])) { 236 if ($cmid != $filters['cmid']) { 237 continue; 238 } else { 239 $modfound = true; 240 } 241 } 242 243 // Filter by module name and id. 244 if (!empty($filters['modname'])) { 245 if ($cm->modname != $filters['modname']) { 246 continue; 247 } else if (!empty($filters['modid'])) { 248 if ($cm->instance != $filters['modid']) { 249 continue; 250 } else { 251 // Note that if we are only filtering by modname we don't break the loop. 252 $modfound = true; 253 } 254 } 255 } 256 257 $module = array(); 258 259 $modcontext = context_module::instance($cm->id); 260 261 //common info (for people being able to see the module or availability dates) 262 $module['id'] = $cm->id; 263 $module['name'] = external_format_string($cm->name, $modcontext->id); 264 $module['instance'] = $cm->instance; 265 $module['contextid'] = $modcontext->id; 266 $module['modname'] = (string) $cm->modname; 267 $module['modplural'] = (string) $cm->modplural; 268 $module['modicon'] = $cm->get_icon_url()->out(false); 269 $module['indent'] = $cm->indent; 270 $module['onclick'] = $cm->onclick; 271 $module['afterlink'] = $cm->afterlink; 272 $module['customdata'] = json_encode($cm->customdata); 273 $module['completion'] = $cm->completion; 274 $module['noviewlink'] = plugin_supports('mod', $cm->modname, FEATURE_NO_VIEW_LINK, false); 275 276 // Check module completion. 277 $completion = $completioninfo->is_enabled($cm); 278 if ($completion != COMPLETION_DISABLED) { 279 $completiondata = $completioninfo->get_data($cm, true); 280 $module['completiondata'] = array( 281 'state' => $completiondata->completionstate, 282 'timecompleted' => $completiondata->timemodified, 283 'overrideby' => $completiondata->overrideby, 284 'valueused' => core_availability\info::completion_value_used($course, $cm->id) 285 ); 286 } 287 288 if (!empty($cm->showdescription) or $module['noviewlink']) { 289 // We want to use the external format. However from reading get_formatted_content(), $cm->content format is always FORMAT_HTML. 290 $options = array('noclean' => true); 291 list($module['description'], $descriptionformat) = external_format_text($cm->content, 292 FORMAT_HTML, $modcontext->id, $cm->modname, 'intro', $cm->id, $options); 293 } 294 295 //url of the module 296 $url = $cm->url; 297 if ($url) { //labels don't have url 298 $module['url'] = $url->out(false); 299 } 300 301 $canviewhidden = has_capability('moodle/course:viewhiddenactivities', 302 context_module::instance($cm->id)); 303 //user that can view hidden module should know about the visibility 304 $module['visible'] = $cm->visible; 305 $module['visibleoncoursepage'] = $cm->visibleoncoursepage; 306 $module['uservisible'] = $cm->uservisible; 307 if (!empty($cm->availableinfo)) { 308 $module['availabilityinfo'] = \core_availability\info::format_info($cm->availableinfo, $course); 309 } 310 311 // Availability date (also send to user who can see hidden module). 312 if ($CFG->enableavailability && ($canviewhidden || $canupdatecourse)) { 313 $module['availability'] = $cm->availability; 314 } 315 316 // Return contents only if the user can access to the module. 317 if ($cm->uservisible) { 318 $baseurl = 'webservice/pluginfile.php'; 319 320 // Call $modulename_export_contents (each module callback take care about checking the capabilities). 321 require_once($CFG->dirroot . '/mod/' . $cm->modname . '/lib.php'); 322 $getcontentfunction = $cm->modname.'_export_contents'; 323 if (function_exists($getcontentfunction)) { 324 $contents = $getcontentfunction($cm, $baseurl); 325 $module['contentsinfo'] = array( 326 'filescount' => count($contents), 327 'filessize' => 0, 328 'lastmodified' => 0, 329 'mimetypes' => array(), 330 ); 331 foreach ($contents as $content) { 332 // Check repository file (only main file). 333 if (!isset($module['contentsinfo']['repositorytype'])) { 334 $module['contentsinfo']['repositorytype'] = 335 isset($content['repositorytype']) ? $content['repositorytype'] : ''; 336 } 337 if (isset($content['filesize'])) { 338 $module['contentsinfo']['filessize'] += $content['filesize']; 339 } 340 if (isset($content['timemodified']) && 341 ($content['timemodified'] > $module['contentsinfo']['lastmodified'])) { 342 343 $module['contentsinfo']['lastmodified'] = $content['timemodified']; 344 } 345 if (isset($content['mimetype'])) { 346 $module['contentsinfo']['mimetypes'][$content['mimetype']] = $content['mimetype']; 347 } 348 } 349 350 if (empty($filters['excludecontents']) and !empty($contents)) { 351 $module['contents'] = $contents; 352 } else { 353 $module['contents'] = array(); 354 } 355 } 356 } 357 358 // Assign result to $sectioncontents, there is an exception, 359 // stealth activities in non-visible sections for students go to a special section. 360 if (!empty($filters['includestealthmodules']) && !$section->uservisible && $cm->is_stealth()) { 361 $stealthmodules[] = $module; 362 } else { 363 $sectioncontents[] = $module; 364 } 365 366 // If we just did a filtering, break the loop. 367 if ($modfound) { 368 break; 369 } 370 371 } 372 } 373 $sectionvalues['modules'] = $sectioncontents; 374 375 // assign result to $coursecontents 376 $coursecontents[$key] = $sectionvalues; 377 378 // Break the loop if we are filtering. 379 if ($sectionfound) { 380 break; 381 } 382 } 383 384 // Now that we have iterated over all the sections and activities, check the visibility. 385 // We didn't this before to be able to retrieve stealth activities. 386 foreach ($coursecontents as $sectionnumber => $sectioncontents) { 387 $section = $sections[$sectionnumber]; 388 // Show the section if the user is permitted to access it OR 389 // if it's not available but there is some available info text which explains the reason & should display OR 390 // the course is configured to show hidden sections name. 391 $showsection = $section->uservisible || 392 ($section->visible && !$section->available && !empty($section->availableinfo)) || 393 (!$section->visible && empty($courseformat->get_course()->hiddensections)); 394 395 if (!$showsection) { 396 unset($coursecontents[$sectionnumber]); 397 continue; 398 } 399 400 // Remove section and modules information if the section is not visible for the user. 401 if (!$section->uservisible) { 402 $coursecontents[$sectionnumber]['modules'] = array(); 403 // Remove summary information if the section is completely hidden only, 404 // even if the section is not user visible, the summary is always displayed among the availability information. 405 if (!$section->visible) { 406 $coursecontents[$sectionnumber]['summary'] = ''; 407 } 408 } 409 } 410 411 // Include stealth modules in special section (without any info). 412 if (!empty($stealthmodules)) { 413 $coursecontents[] = array( 414 'id' => -1, 415 'name' => '', 416 'summary' => '', 417 'summaryformat' => FORMAT_MOODLE, 418 'modules' => $stealthmodules 419 ); 420 } 421 422 } 423 return $coursecontents; 424 } 425 426 /** 427 * Returns description of method result value 428 * 429 * @return external_description 430 * @since Moodle 2.2 431 */ 432 public static function get_course_contents_returns() { 433 return new external_multiple_structure( 434 new external_single_structure( 435 array( 436 'id' => new external_value(PARAM_INT, 'Section ID'), 437 'name' => new external_value(PARAM_RAW, 'Section name'), 438 'visible' => new external_value(PARAM_INT, 'is the section visible', VALUE_OPTIONAL), 439 'summary' => new external_value(PARAM_RAW, 'Section description'), 440 'summaryformat' => new external_format_value('summary'), 441 'section' => new external_value(PARAM_INT, 'Section number inside the course', VALUE_OPTIONAL), 442 'hiddenbynumsections' => new external_value(PARAM_INT, 'Whether is a section hidden in the course format', 443 VALUE_OPTIONAL), 444 'uservisible' => new external_value(PARAM_BOOL, 'Is the section visible for the user?', VALUE_OPTIONAL), 445 'availabilityinfo' => new external_value(PARAM_RAW, 'Availability information.', VALUE_OPTIONAL), 446 'modules' => new external_multiple_structure( 447 new external_single_structure( 448 array( 449 'id' => new external_value(PARAM_INT, 'activity id'), 450 'url' => new external_value(PARAM_URL, 'activity url', VALUE_OPTIONAL), 451 'name' => new external_value(PARAM_RAW, 'activity module name'), 452 'instance' => new external_value(PARAM_INT, 'instance id', VALUE_OPTIONAL), 453 'contextid' => new external_value(PARAM_INT, 'Activity context id.', VALUE_OPTIONAL), 454 'description' => new external_value(PARAM_RAW, 'activity description', VALUE_OPTIONAL), 455 'visible' => new external_value(PARAM_INT, 'is the module visible', VALUE_OPTIONAL), 456 'uservisible' => new external_value(PARAM_BOOL, 'Is the module visible for the user?', 457 VALUE_OPTIONAL), 458 'availabilityinfo' => new external_value(PARAM_RAW, 'Availability information.', 459 VALUE_OPTIONAL), 460 'visibleoncoursepage' => new external_value(PARAM_INT, 'is the module visible on course page', 461 VALUE_OPTIONAL), 462 'modicon' => new external_value(PARAM_URL, 'activity icon url'), 463 'modname' => new external_value(PARAM_PLUGIN, 'activity module type'), 464 'modplural' => new external_value(PARAM_TEXT, 'activity module plural name'), 465 'availability' => new external_value(PARAM_RAW, 'module availability settings', VALUE_OPTIONAL), 466 'indent' => new external_value(PARAM_INT, 'number of identation in the site'), 467 'onclick' => new external_value(PARAM_RAW, 'Onclick action.', VALUE_OPTIONAL), 468 'afterlink' => new external_value(PARAM_RAW, 'After link info to be displayed.', 469 VALUE_OPTIONAL), 470 'customdata' => new external_value(PARAM_RAW, 'Custom data (JSON encoded).', VALUE_OPTIONAL), 471 'noviewlink' => new external_value(PARAM_BOOL, 'Whether the module has no view page', 472 VALUE_OPTIONAL), 473 'completion' => new external_value(PARAM_INT, 'Type of completion tracking: 474 0 means none, 1 manual, 2 automatic.', VALUE_OPTIONAL), 475 'completiondata' => new external_single_structure( 476 array( 477 'state' => new external_value(PARAM_INT, 'Completion state value: 478 0 means incomplete, 1 complete, 2 complete pass, 3 complete fail'), 479 'timecompleted' => new external_value(PARAM_INT, 'Timestamp for completion status.'), 480 'overrideby' => new external_value(PARAM_INT, 'The user id who has overriden the 481 status.'), 482 'valueused' => new external_value(PARAM_BOOL, 'Whether the completion status affects 483 the availability of another activity.', VALUE_OPTIONAL), 484 ), 'Module completion data.', VALUE_OPTIONAL 485 ), 486 'contents' => new external_multiple_structure( 487 new external_single_structure( 488 array( 489 // content info 490 'type'=> new external_value(PARAM_TEXT, 'a file or a folder or external link'), 491 'filename'=> new external_value(PARAM_FILE, 'filename'), 492 'filepath'=> new external_value(PARAM_PATH, 'filepath'), 493 'filesize'=> new external_value(PARAM_INT, 'filesize'), 494 'fileurl' => new external_value(PARAM_URL, 'downloadable file url', VALUE_OPTIONAL), 495 'content' => new external_value(PARAM_RAW, 'Raw content, will be used when type is content', VALUE_OPTIONAL), 496 'timecreated' => new external_value(PARAM_INT, 'Time created'), 497 'timemodified' => new external_value(PARAM_INT, 'Time modified'), 498 'sortorder' => new external_value(PARAM_INT, 'Content sort order'), 499 'mimetype' => new external_value(PARAM_RAW, 'File mime type.', VALUE_OPTIONAL), 500 'isexternalfile' => new external_value(PARAM_BOOL, 'Whether is an external file.', 501 VALUE_OPTIONAL), 502 'repositorytype' => new external_value(PARAM_PLUGIN, 'The repository type for external files.', 503 VALUE_OPTIONAL), 504 505 // copyright related info 506 'userid' => new external_value(PARAM_INT, 'User who added this content to moodle'), 507 'author' => new external_value(PARAM_TEXT, 'Content owner'), 508 'license' => new external_value(PARAM_TEXT, 'Content license'), 509 'tags' => new external_multiple_structure( 510 \core_tag\external\tag_item_exporter::get_read_structure(), 'Tags', 511 VALUE_OPTIONAL 512 ), 513 ) 514 ), VALUE_DEFAULT, array() 515 ), 516 'contentsinfo' => new external_single_structure( 517 array( 518 'filescount' => new external_value(PARAM_INT, 'Total number of files.'), 519 'filessize' => new external_value(PARAM_INT, 'Total files size.'), 520 'lastmodified' => new external_value(PARAM_INT, 'Last time files were modified.'), 521 'mimetypes' => new external_multiple_structure( 522 new external_value(PARAM_RAW, 'File mime type.'), 523 'Files mime types.' 524 ), 525 'repositorytype' => new external_value(PARAM_PLUGIN, 'The repository type for 526 the main file.', VALUE_OPTIONAL), 527 ), 'Contents summary information.', VALUE_OPTIONAL 528 ), 529 ) 530 ), 'list of module' 531 ) 532 ) 533 ) 534 ); 535 } 536 537 /** 538 * Returns description of method parameters 539 * 540 * @return external_function_parameters 541 * @since Moodle 2.3 542 */ 543 public static function get_courses_parameters() { 544 return new external_function_parameters( 545 array('options' => new external_single_structure( 546 array('ids' => new external_multiple_structure( 547 new external_value(PARAM_INT, 'Course id') 548 , 'List of course id. If empty return all courses 549 except front page course.', 550 VALUE_OPTIONAL) 551 ), 'options - operator OR is used', VALUE_DEFAULT, array()) 552 ) 553 ); 554 } 555 556 /** 557 * Get courses 558 * 559 * @param array $options It contains an array (list of ids) 560 * @return array 561 * @since Moodle 2.2 562 */ 563 public static function get_courses($options = array()) { 564 global $CFG, $DB; 565 require_once($CFG->dirroot . "/course/lib.php"); 566 567 //validate parameter 568 $params = self::validate_parameters(self::get_courses_parameters(), 569 array('options' => $options)); 570 571 //retrieve courses 572 if (!array_key_exists('ids', $params['options']) 573 or empty($params['options']['ids'])) { 574 $courses = $DB->get_records('course'); 575 } else { 576 $courses = $DB->get_records_list('course', 'id', $params['options']['ids']); 577 } 578 579 //create return value 580 $coursesinfo = array(); 581 foreach ($courses as $course) { 582 583 // now security checks 584 $context = context_course::instance($course->id, IGNORE_MISSING); 585 $courseformatoptions = course_get_format($course)->get_format_options(); 586 try { 587 self::validate_context($context); 588 } catch (Exception $e) { 589 $exceptionparam = new stdClass(); 590 $exceptionparam->message = $e->getMessage(); 591 $exceptionparam->courseid = $course->id; 592 throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam); 593 } 594 if ($course->id != SITEID) { 595 require_capability('moodle/course:view', $context); 596 } 597 598 $courseinfo = array(); 599 $courseinfo['id'] = $course->id; 600 $courseinfo['fullname'] = external_format_string($course->fullname, $context->id); 601 $courseinfo['shortname'] = external_format_string($course->shortname, $context->id); 602 $courseinfo['displayname'] = external_format_string(get_course_display_name_for_list($course), $context->id); 603 $courseinfo['categoryid'] = $course->category; 604 list($courseinfo['summary'], $courseinfo['summaryformat']) = 605 external_format_text($course->summary, $course->summaryformat, $context->id, 'course', 'summary', 0); 606 $courseinfo['format'] = $course->format; 607 $courseinfo['startdate'] = $course->startdate; 608 $courseinfo['enddate'] = $course->enddate; 609 if (array_key_exists('numsections', $courseformatoptions)) { 610 // For backward-compartibility 611 $courseinfo['numsections'] = $courseformatoptions['numsections']; 612 } 613 614 $handler = core_course\customfield\course_handler::create(); 615 if ($customfields = $handler->export_instance_data($course->id)) { 616 $courseinfo['customfields'] = []; 617 foreach ($customfields as $data) { 618 $courseinfo['customfields'][] = [ 619 'type' => $data->get_type(), 620 'value' => $data->get_value(), 621 'valueraw' => $data->get_data_controller()->get_value(), 622 'name' => $data->get_name(), 623 'shortname' => $data->get_shortname() 624 ]; 625 } 626 } 627 628 //some field should be returned only if the user has update permission 629 $courseadmin = has_capability('moodle/course:update', $context); 630 if ($courseadmin) { 631 $courseinfo['categorysortorder'] = $course->sortorder; 632 $courseinfo['idnumber'] = $course->idnumber; 633 $courseinfo['showgrades'] = $course->showgrades; 634 $courseinfo['showreports'] = $course->showreports; 635 $courseinfo['newsitems'] = $course->newsitems; 636 $courseinfo['visible'] = $course->visible; 637 $courseinfo['maxbytes'] = $course->maxbytes; 638 if (array_key_exists('hiddensections', $courseformatoptions)) { 639 // For backward-compartibility 640 $courseinfo['hiddensections'] = $courseformatoptions['hiddensections']; 641 } 642 // Return numsections for backward-compatibility with clients who expect it. 643 $courseinfo['numsections'] = course_get_format($course)->get_last_section_number(); 644 $courseinfo['groupmode'] = $course->groupmode; 645 $courseinfo['groupmodeforce'] = $course->groupmodeforce; 646 $courseinfo['defaultgroupingid'] = $course->defaultgroupingid; 647 $courseinfo['lang'] = clean_param($course->lang, PARAM_LANG); 648 $courseinfo['timecreated'] = $course->timecreated; 649 $courseinfo['timemodified'] = $course->timemodified; 650 $courseinfo['forcetheme'] = clean_param($course->theme, PARAM_THEME); 651 $courseinfo['enablecompletion'] = $course->enablecompletion; 652 $courseinfo['completionnotify'] = $course->completionnotify; 653 $courseinfo['courseformatoptions'] = array(); 654 foreach ($courseformatoptions as $key => $value) { 655 $courseinfo['courseformatoptions'][] = array( 656 'name' => $key, 657 'value' => $value 658 ); 659 } 660 } 661 662 if ($courseadmin or $course->visible 663 or has_capability('moodle/course:viewhiddencourses', $context)) { 664 $coursesinfo[] = $courseinfo; 665 } 666 } 667 668 return $coursesinfo; 669 } 670 671 /** 672 * Returns description of method result value 673 * 674 * @return external_description 675 * @since Moodle 2.2 676 */ 677 public static function get_courses_returns() { 678 return new external_multiple_structure( 679 new external_single_structure( 680 array( 681 'id' => new external_value(PARAM_INT, 'course id'), 682 'shortname' => new external_value(PARAM_RAW, 'course short name'), 683 'categoryid' => new external_value(PARAM_INT, 'category id'), 684 'categorysortorder' => new external_value(PARAM_INT, 685 'sort order into the category', VALUE_OPTIONAL), 686 'fullname' => new external_value(PARAM_RAW, 'full name'), 687 'displayname' => new external_value(PARAM_RAW, 'course display name'), 688 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL), 689 'summary' => new external_value(PARAM_RAW, 'summary'), 690 'summaryformat' => new external_format_value('summary'), 691 'format' => new external_value(PARAM_PLUGIN, 692 'course format: weeks, topics, social, site,..'), 693 'showgrades' => new external_value(PARAM_INT, 694 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL), 695 'newsitems' => new external_value(PARAM_INT, 696 'number of recent items appearing on the course page', VALUE_OPTIONAL), 697 'startdate' => new external_value(PARAM_INT, 698 'timestamp when the course start'), 699 'enddate' => new external_value(PARAM_INT, 700 'timestamp when the course end'), 701 'numsections' => new external_value(PARAM_INT, 702 '(deprecated, use courseformatoptions) number of weeks/topics', 703 VALUE_OPTIONAL), 704 'maxbytes' => new external_value(PARAM_INT, 705 'largest size of file that can be uploaded into the course', 706 VALUE_OPTIONAL), 707 'showreports' => new external_value(PARAM_INT, 708 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL), 709 'visible' => new external_value(PARAM_INT, 710 '1: available to student, 0:not available', VALUE_OPTIONAL), 711 'hiddensections' => new external_value(PARAM_INT, 712 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students', 713 VALUE_OPTIONAL), 714 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', 715 VALUE_OPTIONAL), 716 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', 717 VALUE_OPTIONAL), 718 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', 719 VALUE_OPTIONAL), 720 'timecreated' => new external_value(PARAM_INT, 721 'timestamp when the course have been created', VALUE_OPTIONAL), 722 'timemodified' => new external_value(PARAM_INT, 723 'timestamp when the course have been modified', VALUE_OPTIONAL), 724 'enablecompletion' => new external_value(PARAM_INT, 725 'Enabled, control via completion and activity settings. Disbaled, 726 not shown in activity settings.', 727 VALUE_OPTIONAL), 728 'completionnotify' => new external_value(PARAM_INT, 729 '1: yes 0: no', VALUE_OPTIONAL), 730 'lang' => new external_value(PARAM_SAFEDIR, 731 'forced course language', VALUE_OPTIONAL), 732 'forcetheme' => new external_value(PARAM_PLUGIN, 733 'name of the force theme', VALUE_OPTIONAL), 734 'courseformatoptions' => new external_multiple_structure( 735 new external_single_structure( 736 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'), 737 'value' => new external_value(PARAM_RAW, 'course format option value') 738 )), 'additional options for particular course format', VALUE_OPTIONAL 739 ), 740 'customfields' => new external_multiple_structure( 741 new external_single_structure( 742 ['name' => new external_value(PARAM_RAW, 'The name of the custom field'), 743 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'The shortname of the custom field'), 744 'type' => new external_value(PARAM_COMPONENT, 745 'The type of the custom field - text, checkbox...'), 746 'valueraw' => new external_value(PARAM_RAW, 'The raw value of the custom field'), 747 'value' => new external_value(PARAM_RAW, 'The value of the custom field')] 748 ), 'Custom fields and associated values', VALUE_OPTIONAL), 749 ), 'course' 750 ) 751 ); 752 } 753 754 /** 755 * Returns description of method parameters 756 * 757 * @return external_function_parameters 758 * @since Moodle 2.2 759 */ 760 public static function create_courses_parameters() { 761 $courseconfig = get_config('moodlecourse'); //needed for many default values 762 return new external_function_parameters( 763 array( 764 'courses' => new external_multiple_structure( 765 new external_single_structure( 766 array( 767 'fullname' => new external_value(PARAM_TEXT, 'full name'), 768 'shortname' => new external_value(PARAM_TEXT, 'course short name'), 769 'categoryid' => new external_value(PARAM_INT, 'category id'), 770 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL), 771 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL), 772 'summaryformat' => new external_format_value('summary', VALUE_DEFAULT), 773 'format' => new external_value(PARAM_PLUGIN, 774 'course format: weeks, topics, social, site,..', 775 VALUE_DEFAULT, $courseconfig->format), 776 'showgrades' => new external_value(PARAM_INT, 777 '1 if grades are shown, otherwise 0', VALUE_DEFAULT, 778 $courseconfig->showgrades), 779 'newsitems' => new external_value(PARAM_INT, 780 'number of recent items appearing on the course page', 781 VALUE_DEFAULT, $courseconfig->newsitems), 782 'startdate' => new external_value(PARAM_INT, 783 'timestamp when the course start', VALUE_OPTIONAL), 784 'enddate' => new external_value(PARAM_INT, 785 'timestamp when the course end', VALUE_OPTIONAL), 786 'numsections' => new external_value(PARAM_INT, 787 '(deprecated, use courseformatoptions) number of weeks/topics', 788 VALUE_OPTIONAL), 789 'maxbytes' => new external_value(PARAM_INT, 790 'largest size of file that can be uploaded into the course', 791 VALUE_DEFAULT, $courseconfig->maxbytes), 792 'showreports' => new external_value(PARAM_INT, 793 'are activity report shown (yes = 1, no =0)', VALUE_DEFAULT, 794 $courseconfig->showreports), 795 'visible' => new external_value(PARAM_INT, 796 '1: available to student, 0:not available', VALUE_OPTIONAL), 797 'hiddensections' => new external_value(PARAM_INT, 798 '(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students', 799 VALUE_OPTIONAL), 800 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', 801 VALUE_DEFAULT, $courseconfig->groupmode), 802 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', 803 VALUE_DEFAULT, $courseconfig->groupmodeforce), 804 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', 805 VALUE_DEFAULT, 0), 806 'enablecompletion' => new external_value(PARAM_INT, 807 'Enabled, control via completion and activity settings. Disabled, 808 not shown in activity settings.', 809 VALUE_OPTIONAL), 810 'completionnotify' => new external_value(PARAM_INT, 811 '1: yes 0: no', VALUE_OPTIONAL), 812 'lang' => new external_value(PARAM_SAFEDIR, 813 'forced course language', VALUE_OPTIONAL), 814 'forcetheme' => new external_value(PARAM_PLUGIN, 815 'name of the force theme', VALUE_OPTIONAL), 816 'courseformatoptions' => new external_multiple_structure( 817 new external_single_structure( 818 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'), 819 'value' => new external_value(PARAM_RAW, 'course format option value') 820 )), 821 'additional options for particular course format', VALUE_OPTIONAL), 822 'customfields' => new external_multiple_structure( 823 new external_single_structure( 824 array( 825 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'The shortname of the custom field'), 826 'value' => new external_value(PARAM_RAW, 'The value of the custom field'), 827 )), 'custom fields for the course', VALUE_OPTIONAL 828 ) 829 )), 'courses to create' 830 ) 831 ) 832 ); 833 } 834 835 /** 836 * Create courses 837 * 838 * @param array $courses 839 * @return array courses (id and shortname only) 840 * @since Moodle 2.2 841 */ 842 public static function create_courses($courses) { 843 global $CFG, $DB; 844 require_once($CFG->dirroot . "/course/lib.php"); 845 require_once($CFG->libdir . '/completionlib.php'); 846 847 $params = self::validate_parameters(self::create_courses_parameters(), 848 array('courses' => $courses)); 849 850 $availablethemes = core_component::get_plugin_list('theme'); 851 $availablelangs = get_string_manager()->get_list_of_translations(); 852 853 $transaction = $DB->start_delegated_transaction(); 854 855 foreach ($params['courses'] as $course) { 856 857 // Ensure the current user is allowed to run this function 858 $context = context_coursecat::instance($course['categoryid'], IGNORE_MISSING); 859 try { 860 self::validate_context($context); 861 } catch (Exception $e) { 862 $exceptionparam = new stdClass(); 863 $exceptionparam->message = $e->getMessage(); 864 $exceptionparam->catid = $course['categoryid']; 865 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam); 866 } 867 require_capability('moodle/course:create', $context); 868 869 // Fullname and short name are required to be non-empty. 870 if (trim($course['fullname']) === '') { 871 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'fullname'); 872 } else if (trim($course['shortname']) === '') { 873 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'shortname'); 874 } 875 876 // Make sure lang is valid 877 if (array_key_exists('lang', $course)) { 878 if (empty($availablelangs[$course['lang']])) { 879 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang'); 880 } 881 if (!has_capability('moodle/course:setforcedlanguage', $context)) { 882 unset($course['lang']); 883 } 884 } 885 886 // Make sure theme is valid 887 if (array_key_exists('forcetheme', $course)) { 888 if (!empty($CFG->allowcoursethemes)) { 889 if (empty($availablethemes[$course['forcetheme']])) { 890 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme'); 891 } else { 892 $course['theme'] = $course['forcetheme']; 893 } 894 } 895 } 896 897 //force visibility if ws user doesn't have the permission to set it 898 $category = $DB->get_record('course_categories', array('id' => $course['categoryid'])); 899 if (!has_capability('moodle/course:visibility', $context)) { 900 $course['visible'] = $category->visible; 901 } 902 903 //set default value for completion 904 $courseconfig = get_config('moodlecourse'); 905 if (completion_info::is_enabled_for_site()) { 906 if (!array_key_exists('enablecompletion', $course)) { 907 $course['enablecompletion'] = $courseconfig->enablecompletion; 908 } 909 } else { 910 $course['enablecompletion'] = 0; 911 } 912 913 $course['category'] = $course['categoryid']; 914 915 // Summary format. 916 $course['summaryformat'] = external_validate_format($course['summaryformat']); 917 918 if (!empty($course['courseformatoptions'])) { 919 foreach ($course['courseformatoptions'] as $option) { 920 $course[$option['name']] = $option['value']; 921 } 922 } 923 924 // Custom fields. 925 if (!empty($course['customfields'])) { 926 foreach ($course['customfields'] as $field) { 927 $course['customfield_'.$field['shortname']] = $field['value']; 928 } 929 } 930 931 //Note: create_course() core function check shortname, idnumber, category 932 $course['id'] = create_course((object) $course)->id; 933 934 $resultcourses[] = array('id' => $course['id'], 'shortname' => $course['shortname']); 935 } 936 937 $transaction->allow_commit(); 938 939 return $resultcourses; 940 } 941 942 /** 943 * Returns description of method result value 944 * 945 * @return external_description 946 * @since Moodle 2.2 947 */ 948 public static function create_courses_returns() { 949 return new external_multiple_structure( 950 new external_single_structure( 951 array( 952 'id' => new external_value(PARAM_INT, 'course id'), 953 'shortname' => new external_value(PARAM_RAW, 'short name'), 954 ) 955 ) 956 ); 957 } 958 959 /** 960 * Update courses 961 * 962 * @return external_function_parameters 963 * @since Moodle 2.5 964 */ 965 public static function update_courses_parameters() { 966 return new external_function_parameters( 967 array( 968 'courses' => new external_multiple_structure( 969 new external_single_structure( 970 array( 971 'id' => new external_value(PARAM_INT, 'ID of the course'), 972 'fullname' => new external_value(PARAM_TEXT, 'full name', VALUE_OPTIONAL), 973 'shortname' => new external_value(PARAM_TEXT, 'course short name', VALUE_OPTIONAL), 974 'categoryid' => new external_value(PARAM_INT, 'category id', VALUE_OPTIONAL), 975 'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL), 976 'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL), 977 'summaryformat' => new external_format_value('summary', VALUE_OPTIONAL), 978 'format' => new external_value(PARAM_PLUGIN, 979 'course format: weeks, topics, social, site,..', VALUE_OPTIONAL), 980 'showgrades' => new external_value(PARAM_INT, 981 '1 if grades are shown, otherwise 0', VALUE_OPTIONAL), 982 'newsitems' => new external_value(PARAM_INT, 983 'number of recent items appearing on the course page', VALUE_OPTIONAL), 984 'startdate' => new external_value(PARAM_INT, 985 'timestamp when the course start', VALUE_OPTIONAL), 986 'enddate' => new external_value(PARAM_INT, 987 'timestamp when the course end', VALUE_OPTIONAL), 988 'numsections' => new external_value(PARAM_INT, 989 '(deprecated, use courseformatoptions) number of weeks/topics', VALUE_OPTIONAL), 990 'maxbytes' => new external_value(PARAM_INT, 991 'largest size of file that can be uploaded into the course', VALUE_OPTIONAL), 992 'showreports' => new external_value(PARAM_INT, 993 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL), 994 'visible' => new external_value(PARAM_INT, 995 '1: available to student, 0:not available', VALUE_OPTIONAL), 996 'hiddensections' => new external_value(PARAM_INT, 997 '(deprecated, use courseformatoptions) How the hidden sections in the course are 998 displayed to students', VALUE_OPTIONAL), 999 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL), 1000 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL), 1001 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL), 1002 'enablecompletion' => new external_value(PARAM_INT, 1003 'Enabled, control via completion and activity settings. Disabled, 1004 not shown in activity settings.', VALUE_OPTIONAL), 1005 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL), 1006 'lang' => new external_value(PARAM_SAFEDIR, 'forced course language', VALUE_OPTIONAL), 1007 'forcetheme' => new external_value(PARAM_PLUGIN, 'name of the force theme', VALUE_OPTIONAL), 1008 'courseformatoptions' => new external_multiple_structure( 1009 new external_single_structure( 1010 array('name' => new external_value(PARAM_ALPHANUMEXT, 'course format option name'), 1011 'value' => new external_value(PARAM_RAW, 'course format option value') 1012 )), 'additional options for particular course format', VALUE_OPTIONAL), 1013 'customfields' => new external_multiple_structure( 1014 new external_single_structure( 1015 [ 1016 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'The shortname of the custom field'), 1017 'value' => new external_value(PARAM_RAW, 'The value of the custom field') 1018 ] 1019 ), 'Custom fields', VALUE_OPTIONAL), 1020 ) 1021 ), 'courses to update' 1022 ) 1023 ) 1024 ); 1025 } 1026 1027 /** 1028 * Update courses 1029 * 1030 * @param array $courses 1031 * @since Moodle 2.5 1032 */ 1033 public static function update_courses($courses) { 1034 global $CFG, $DB; 1035 require_once($CFG->dirroot . "/course/lib.php"); 1036 $warnings = array(); 1037 1038 $params = self::validate_parameters(self::update_courses_parameters(), 1039 array('courses' => $courses)); 1040 1041 $availablethemes = core_component::get_plugin_list('theme'); 1042 $availablelangs = get_string_manager()->get_list_of_translations(); 1043 1044 foreach ($params['courses'] as $course) { 1045 // Catch any exception while updating course and return as warning to user. 1046 try { 1047 // Ensure the current user is allowed to run this function. 1048 $context = context_course::instance($course['id'], MUST_EXIST); 1049 self::validate_context($context); 1050 1051 $oldcourse = course_get_format($course['id'])->get_course(); 1052 1053 require_capability('moodle/course:update', $context); 1054 1055 // Check if user can change category. 1056 if (array_key_exists('categoryid', $course) && ($oldcourse->category != $course['categoryid'])) { 1057 require_capability('moodle/course:changecategory', $context); 1058 $course['category'] = $course['categoryid']; 1059 } 1060 1061 // Check if the user can change fullname, and the new value is non-empty. 1062 if (array_key_exists('fullname', $course) && ($oldcourse->fullname != $course['fullname'])) { 1063 require_capability('moodle/course:changefullname', $context); 1064 if (trim($course['fullname']) === '') { 1065 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'fullname'); 1066 } 1067 } 1068 1069 // Check if the user can change shortname, and the new value is non-empty. 1070 if (array_key_exists('shortname', $course) && ($oldcourse->shortname != $course['shortname'])) { 1071 require_capability('moodle/course:changeshortname', $context); 1072 if (trim($course['shortname']) === '') { 1073 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'shortname'); 1074 } 1075 } 1076 1077 // Check if the user can change the idnumber. 1078 if (array_key_exists('idnumber', $course) && ($oldcourse->idnumber != $course['idnumber'])) { 1079 require_capability('moodle/course:changeidnumber', $context); 1080 } 1081 1082 // Check if user can change summary. 1083 if (array_key_exists('summary', $course) && ($oldcourse->summary != $course['summary'])) { 1084 require_capability('moodle/course:changesummary', $context); 1085 } 1086 1087 // Summary format. 1088 if (array_key_exists('summaryformat', $course) && ($oldcourse->summaryformat != $course['summaryformat'])) { 1089 require_capability('moodle/course:changesummary', $context); 1090 $course['summaryformat'] = external_validate_format($course['summaryformat']); 1091 } 1092 1093 // Check if user can change visibility. 1094 if (array_key_exists('visible', $course) && ($oldcourse->visible != $course['visible'])) { 1095 require_capability('moodle/course:visibility', $context); 1096 } 1097 1098 // Make sure lang is valid. 1099 if (array_key_exists('lang', $course) && ($oldcourse->lang != $course['lang'])) { 1100 require_capability('moodle/course:setforcedlanguage', $context); 1101 if (empty($availablelangs[$course['lang']])) { 1102 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang'); 1103 } 1104 } 1105 1106 // Make sure theme is valid. 1107 if (array_key_exists('forcetheme', $course)) { 1108 if (!empty($CFG->allowcoursethemes)) { 1109 if (empty($availablethemes[$course['forcetheme']])) { 1110 throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme'); 1111 } else { 1112 $course['theme'] = $course['forcetheme']; 1113 } 1114 } 1115 } 1116 1117 // Make sure completion is enabled before setting it. 1118 if (array_key_exists('enabledcompletion', $course) && !completion_info::is_enabled_for_site()) { 1119 $course['enabledcompletion'] = 0; 1120 } 1121 1122 // Make sure maxbytes are less then CFG->maxbytes. 1123 if (array_key_exists('maxbytes', $course)) { 1124 // We allow updates back to 0 max bytes, a special value denoting the course uses the site limit. 1125 // Otherwise, either use the size specified, or cap at the max size for the course. 1126 if ($course['maxbytes'] != 0) { 1127 $course['maxbytes'] = get_max_upload_file_size($CFG->maxbytes, $course['maxbytes']); 1128 } 1129 } 1130 1131 if (!empty($course['courseformatoptions'])) { 1132 foreach ($course['courseformatoptions'] as $option) { 1133 if (isset($option['name']) && isset($option['value'])) { 1134 $course[$option['name']] = $option['value']; 1135 } 1136 } 1137 } 1138 1139 // Prepare list of custom fields. 1140 if (isset($course['customfields'])) { 1141 foreach ($course['customfields'] as $field) { 1142 $course['customfield_' . $field['shortname']] = $field['value']; 1143 } 1144 } 1145 1146 // Update course if user has all required capabilities. 1147 update_course((object) $course); 1148 } catch (Exception $e) { 1149 $warning = array(); 1150 $warning['item'] = 'course'; 1151 $warning['itemid'] = $course['id']; 1152 if ($e instanceof moodle_exception) { 1153 $warning['warningcode'] = $e->errorcode; 1154 } else { 1155 $warning['warningcode'] = $e->getCode(); 1156 } 1157 $warning['message'] = $e->getMessage(); 1158 $warnings[] = $warning; 1159 } 1160 } 1161 1162 $result = array(); 1163 $result['warnings'] = $warnings; 1164 return $result; 1165 } 1166 1167 /** 1168 * Returns description of method result value 1169 * 1170 * @return external_description 1171 * @since Moodle 2.5 1172 */ 1173 public static function update_courses_returns() { 1174 return new external_single_structure( 1175 array( 1176 'warnings' => new external_warnings() 1177 ) 1178 ); 1179 } 1180 1181 /** 1182 * Returns description of method parameters 1183 * 1184 * @return external_function_parameters 1185 * @since Moodle 2.2 1186 */ 1187 public static function delete_courses_parameters() { 1188 return new external_function_parameters( 1189 array( 1190 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'course ID')), 1191 ) 1192 ); 1193 } 1194 1195 /** 1196 * Delete courses 1197 * 1198 * @param array $courseids A list of course ids 1199 * @since Moodle 2.2 1200 */ 1201 public static function delete_courses($courseids) { 1202 global $CFG, $DB; 1203 require_once($CFG->dirroot."/course/lib.php"); 1204 1205 // Parameter validation. 1206 $params = self::validate_parameters(self::delete_courses_parameters(), array('courseids'=>$courseids)); 1207 1208 $warnings = array(); 1209 1210 foreach ($params['courseids'] as $courseid) { 1211 $course = $DB->get_record('course', array('id' => $courseid)); 1212 1213 if ($course === false) { 1214 $warnings[] = array( 1215 'item' => 'course', 1216 'itemid' => $courseid, 1217 'warningcode' => 'unknowncourseidnumber', 1218 'message' => 'Unknown course ID ' . $courseid 1219 ); 1220 continue; 1221 } 1222 1223 // Check if the context is valid. 1224 $coursecontext = context_course::instance($course->id); 1225 self::validate_context($coursecontext); 1226 1227 // Check if the current user has permission. 1228 if (!can_delete_course($courseid)) { 1229 $warnings[] = array( 1230 'item' => 'course', 1231 'itemid' => $courseid, 1232 'warningcode' => 'cannotdeletecourse', 1233 'message' => 'You do not have the permission to delete this course' . $courseid 1234 ); 1235 continue; 1236 } 1237 1238 if (delete_course($course, false) === false) { 1239 $warnings[] = array( 1240 'item' => 'course', 1241 'itemid' => $courseid, 1242 'warningcode' => 'cannotdeletecategorycourse', 1243 'message' => 'Course ' . $courseid . ' failed to be deleted' 1244 ); 1245 continue; 1246 } 1247 } 1248 1249 fix_course_sortorder(); 1250 1251 return array('warnings' => $warnings); 1252 } 1253 1254 /** 1255 * Returns description of method result value 1256 * 1257 * @return external_description 1258 * @since Moodle 2.2 1259 */ 1260 public static function delete_courses_returns() { 1261 return new external_single_structure( 1262 array( 1263 'warnings' => new external_warnings() 1264 ) 1265 ); 1266 } 1267 1268 /** 1269 * Returns description of method parameters 1270 * 1271 * @return external_function_parameters 1272 * @since Moodle 2.3 1273 */ 1274 public static function duplicate_course_parameters() { 1275 return new external_function_parameters( 1276 array( 1277 'courseid' => new external_value(PARAM_INT, 'course to duplicate id'), 1278 'fullname' => new external_value(PARAM_TEXT, 'duplicated course full name'), 1279 'shortname' => new external_value(PARAM_TEXT, 'duplicated course short name'), 1280 'categoryid' => new external_value(PARAM_INT, 'duplicated course category parent'), 1281 'visible' => new external_value(PARAM_INT, 'duplicated course visible, default to yes', VALUE_DEFAULT, 1), 1282 'options' => new external_multiple_structure( 1283 new external_single_structure( 1284 array( 1285 'name' => new external_value(PARAM_ALPHAEXT, 'The backup option name: 1286 "activities" (int) Include course activites (default to 1 that is equal to yes), 1287 "blocks" (int) Include course blocks (default to 1 that is equal to yes), 1288 "filters" (int) Include course filters (default to 1 that is equal to yes), 1289 "users" (int) Include users (default to 0 that is equal to no), 1290 "enrolments" (int) Include enrolment methods (default to 1 - restore only with users), 1291 "role_assignments" (int) Include role assignments (default to 0 that is equal to no), 1292 "comments" (int) Include user comments (default to 0 that is equal to no), 1293 "userscompletion" (int) Include user course completion information (default to 0 that is equal to no), 1294 "logs" (int) Include course logs (default to 0 that is equal to no), 1295 "grade_histories" (int) Include histories (default to 0 that is equal to no)' 1296 ), 1297 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)' 1298 ) 1299 ) 1300 ), VALUE_DEFAULT, array() 1301 ), 1302 ) 1303 ); 1304 } 1305 1306 /** 1307 * Duplicate a course 1308 * 1309 * @param int $courseid 1310 * @param string $fullname Duplicated course fullname 1311 * @param string $shortname Duplicated course shortname 1312 * @param int $categoryid Duplicated course parent category id 1313 * @param int $visible Duplicated course availability 1314 * @param array $options List of backup options 1315 * @return array New course info 1316 * @since Moodle 2.3 1317 */ 1318 public static function duplicate_course($courseid, $fullname, $shortname, $categoryid, $visible = 1, $options = array()) { 1319 global $CFG, $USER, $DB; 1320 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php'); 1321 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php'); 1322 1323 // Parameter validation. 1324 $params = self::validate_parameters( 1325 self::duplicate_course_parameters(), 1326 array( 1327 'courseid' => $courseid, 1328 'fullname' => $fullname, 1329 'shortname' => $shortname, 1330 'categoryid' => $categoryid, 1331 'visible' => $visible, 1332 'options' => $options 1333 ) 1334 ); 1335 1336 // Context validation. 1337 1338 if (! ($course = $DB->get_record('course', array('id'=>$params['courseid'])))) { 1339 throw new moodle_exception('invalidcourseid', 'error'); 1340 } 1341 1342 // Category where duplicated course is going to be created. 1343 $categorycontext = context_coursecat::instance($params['categoryid']); 1344 self::validate_context($categorycontext); 1345 1346 // Course to be duplicated. 1347 $coursecontext = context_course::instance($course->id); 1348 self::validate_context($coursecontext); 1349 1350 $backupdefaults = array( 1351 'activities' => 1, 1352 'blocks' => 1, 1353 'filters' => 1, 1354 'users' => 0, 1355 'enrolments' => backup::ENROL_WITHUSERS, 1356 'role_assignments' => 0, 1357 'comments' => 0, 1358 'userscompletion' => 0, 1359 'logs' => 0, 1360 'grade_histories' => 0 1361 ); 1362 1363 $backupsettings = array(); 1364 // Check for backup and restore options. 1365 if (!empty($params['options'])) { 1366 foreach ($params['options'] as $option) { 1367 1368 // Strict check for a correct value (allways 1 or 0, true or false). 1369 $value = clean_param($option['value'], PARAM_INT); 1370 1371 if ($value !== 0 and $value !== 1) { 1372 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']); 1373 } 1374 1375 if (!isset($backupdefaults[$option['name']])) { 1376 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']); 1377 } 1378 1379 $backupsettings[$option['name']] = $value; 1380 } 1381 } 1382 1383 // Capability checking. 1384 1385 // The backup controller check for this currently, this may be redundant. 1386 require_capability('moodle/course:create', $categorycontext); 1387 require_capability('moodle/restore:restorecourse', $categorycontext); 1388 require_capability('moodle/backup:backupcourse', $coursecontext); 1389 1390 if (!empty($backupsettings['users'])) { 1391 require_capability('moodle/backup:userinfo', $coursecontext); 1392 require_capability('moodle/restore:userinfo', $categorycontext); 1393 } 1394 1395 // Check if the shortname is used. 1396 if ($foundcourses = $DB->get_records('course', array('shortname'=>$shortname))) { 1397 foreach ($foundcourses as $foundcourse) { 1398 $foundcoursenames[] = $foundcourse->fullname; 1399 } 1400 1401 $foundcoursenamestring = implode(',', $foundcoursenames); 1402 throw new moodle_exception('shortnametaken', '', '', $foundcoursenamestring); 1403 } 1404 1405 // Backup the course. 1406 1407 $bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE, 1408 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id); 1409 1410 foreach ($backupsettings as $name => $value) { 1411 if ($setting = $bc->get_plan()->get_setting($name)) { 1412 $bc->get_plan()->get_setting($name)->set_value($value); 1413 } 1414 } 1415 1416 $backupid = $bc->get_backupid(); 1417 $backupbasepath = $bc->get_plan()->get_basepath(); 1418 1419 $bc->execute_plan(); 1420 $results = $bc->get_results(); 1421 $file = $results['backup_destination']; 1422 1423 $bc->destroy(); 1424 1425 // Restore the backup immediately. 1426 1427 // Check if we need to unzip the file because the backup temp dir does not contains backup files. 1428 if (!file_exists($backupbasepath . "/moodle_backup.xml")) { 1429 $file->extract_to_pathname(get_file_packer('application/vnd.moodle.backup'), $backupbasepath); 1430 } 1431 1432 // Create new course. 1433 $newcourseid = restore_dbops::create_new_course($params['fullname'], $params['shortname'], $params['categoryid']); 1434 1435 $rc = new restore_controller($backupid, $newcourseid, 1436 backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $USER->id, backup::TARGET_NEW_COURSE); 1437 1438 foreach ($backupsettings as $name => $value) { 1439 $setting = $rc->get_plan()->get_setting($name); 1440 if ($setting->get_status() == backup_setting::NOT_LOCKED) { 1441 $setting->set_value($value); 1442 } 1443 } 1444 1445 if (!$rc->execute_precheck()) { 1446 $precheckresults = $rc->get_precheck_results(); 1447 if (is_array($precheckresults) && !empty($precheckresults['errors'])) { 1448 if (empty($CFG->keeptempdirectoriesonbackup)) { 1449 fulldelete($backupbasepath); 1450 } 1451 1452 $errorinfo = ''; 1453 1454 foreach ($precheckresults['errors'] as $error) { 1455 $errorinfo .= $error; 1456 } 1457 1458 if (array_key_exists('warnings', $precheckresults)) { 1459 foreach ($precheckresults['warnings'] as $warning) { 1460 $errorinfo .= $warning; 1461 } 1462 } 1463 1464 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo); 1465 } 1466 } 1467 1468 $rc->execute_plan(); 1469 $rc->destroy(); 1470 1471 $course = $DB->get_record('course', array('id' => $newcourseid), '*', MUST_EXIST); 1472 $course->fullname = $params['fullname']; 1473 $course->shortname = $params['shortname']; 1474 $course->visible = $params['visible']; 1475 1476 // Set shortname and fullname back. 1477 $DB->update_record('course', $course); 1478 1479 if (empty($CFG->keeptempdirectoriesonbackup)) { 1480 fulldelete($backupbasepath); 1481 } 1482 1483 // Delete the course backup file created by this WebService. Originally located in the course backups area. 1484 $file->delete(); 1485 1486 return array('id' => $course->id, 'shortname' => $course->shortname); 1487 } 1488 1489 /** 1490 * Returns description of method result value 1491 * 1492 * @return external_description 1493 * @since Moodle 2.3 1494 */ 1495 public static function duplicate_course_returns() { 1496 return new external_single_structure( 1497 array( 1498 'id' => new external_value(PARAM_INT, 'course id'), 1499 'shortname' => new external_value(PARAM_RAW, 'short name'), 1500 ) 1501 ); 1502 } 1503 1504 /** 1505 * Returns description of method parameters for import_course 1506 * 1507 * @return external_function_parameters 1508 * @since Moodle 2.4 1509 */ 1510 public static function import_course_parameters() { 1511 return new external_function_parameters( 1512 array( 1513 'importfrom' => new external_value(PARAM_INT, 'the id of the course we are importing from'), 1514 'importto' => new external_value(PARAM_INT, 'the id of the course we are importing to'), 1515 'deletecontent' => new external_value(PARAM_INT, 'whether to delete the course content where we are importing to (default to 0 = No)', VALUE_DEFAULT, 0), 1516 'options' => new external_multiple_structure( 1517 new external_single_structure( 1518 array( 1519 'name' => new external_value(PARAM_ALPHA, 'The backup option name: 1520 "activities" (int) Include course activites (default to 1 that is equal to yes), 1521 "blocks" (int) Include course blocks (default to 1 that is equal to yes), 1522 "filters" (int) Include course filters (default to 1 that is equal to yes)' 1523 ), 1524 'value' => new external_value(PARAM_RAW, 'the value for the option 1 (yes) or 0 (no)' 1525 ) 1526 ) 1527 ), VALUE_DEFAULT, array() 1528 ), 1529 ) 1530 ); 1531 } 1532 1533 /** 1534 * Imports a course 1535 * 1536 * @param int $importfrom The id of the course we are importing from 1537 * @param int $importto The id of the course we are importing to 1538 * @param bool $deletecontent Whether to delete the course we are importing to content 1539 * @param array $options List of backup options 1540 * @return null 1541 * @since Moodle 2.4 1542 */ 1543 public static function import_course($importfrom, $importto, $deletecontent = 0, $options = array()) { 1544 global $CFG, $USER, $DB; 1545 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php'); 1546 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php'); 1547 1548 // Parameter validation. 1549 $params = self::validate_parameters( 1550 self::import_course_parameters(), 1551 array( 1552 'importfrom' => $importfrom, 1553 'importto' => $importto, 1554 'deletecontent' => $deletecontent, 1555 'options' => $options 1556 ) 1557 ); 1558 1559 if ($params['deletecontent'] !== 0 and $params['deletecontent'] !== 1) { 1560 throw new moodle_exception('invalidextparam', 'webservice', '', $params['deletecontent']); 1561 } 1562 1563 // Context validation. 1564 1565 if (! ($importfrom = $DB->get_record('course', array('id'=>$params['importfrom'])))) { 1566 throw new moodle_exception('invalidcourseid', 'error'); 1567 } 1568 1569 if (! ($importto = $DB->get_record('course', array('id'=>$params['importto'])))) { 1570 throw new moodle_exception('invalidcourseid', 'error'); 1571 } 1572 1573 $importfromcontext = context_course::instance($importfrom->id); 1574 self::validate_context($importfromcontext); 1575 1576 $importtocontext = context_course::instance($importto->id); 1577 self::validate_context($importtocontext); 1578 1579 $backupdefaults = array( 1580 'activities' => 1, 1581 'blocks' => 1, 1582 'filters' => 1 1583 ); 1584 1585 $backupsettings = array(); 1586 1587 // Check for backup and restore options. 1588 if (!empty($params['options'])) { 1589 foreach ($params['options'] as $option) { 1590 1591 // Strict check for a correct value (allways 1 or 0, true or false). 1592 $value = clean_param($option['value'], PARAM_INT); 1593 1594 if ($value !== 0 and $value !== 1) { 1595 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']); 1596 } 1597 1598 if (!isset($backupdefaults[$option['name']])) { 1599 throw new moodle_exception('invalidextparam', 'webservice', '', $option['name']); 1600 } 1601 1602 $backupsettings[$option['name']] = $value; 1603 } 1604 } 1605 1606 // Capability checking. 1607 1608 require_capability('moodle/backup:backuptargetimport', $importfromcontext); 1609 require_capability('moodle/restore:restoretargetimport', $importtocontext); 1610 1611 $bc = new backup_controller(backup::TYPE_1COURSE, $importfrom->id, backup::FORMAT_MOODLE, 1612 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id); 1613 1614 foreach ($backupsettings as $name => $value) { 1615 $bc->get_plan()->get_setting($name)->set_value($value); 1616 } 1617 1618 $backupid = $bc->get_backupid(); 1619 $backupbasepath = $bc->get_plan()->get_basepath(); 1620 1621 $bc->execute_plan(); 1622 $bc->destroy(); 1623 1624 // Restore the backup immediately. 1625 1626 // Check if we must delete the contents of the destination course. 1627 if ($params['deletecontent']) { 1628 $restoretarget = backup::TARGET_EXISTING_DELETING; 1629 } else { 1630 $restoretarget = backup::TARGET_EXISTING_ADDING; 1631 } 1632 1633 $rc = new restore_controller($backupid, $importto->id, 1634 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, $restoretarget); 1635 1636 foreach ($backupsettings as $name => $value) { 1637 $rc->get_plan()->get_setting($name)->set_value($value); 1638 } 1639 1640 if (!$rc->execute_precheck()) { 1641 $precheckresults = $rc->get_precheck_results(); 1642 if (is_array($precheckresults) && !empty($precheckresults['errors'])) { 1643 if (empty($CFG->keeptempdirectoriesonbackup)) { 1644 fulldelete($backupbasepath); 1645 } 1646 1647 $errorinfo = ''; 1648 1649 foreach ($precheckresults['errors'] as $error) { 1650 $errorinfo .= $error; 1651 } 1652 1653 if (array_key_exists('warnings', $precheckresults)) { 1654 foreach ($precheckresults['warnings'] as $warning) { 1655 $errorinfo .= $warning; 1656 } 1657 } 1658 1659 throw new moodle_exception('backupprecheckerrors', 'webservice', '', $errorinfo); 1660 } 1661 } else { 1662 if ($restoretarget == backup::TARGET_EXISTING_DELETING) { 1663 restore_dbops::delete_course_content($importto->id); 1664 } 1665 } 1666 1667 $rc->execute_plan(); 1668 $rc->destroy(); 1669 1670 if (empty($CFG->keeptempdirectoriesonbackup)) { 1671 fulldelete($backupbasepath); 1672 } 1673 1674 return null; 1675 } 1676 1677 /** 1678 * Returns description of method result value 1679 * 1680 * @return external_description 1681 * @since Moodle 2.4 1682 */ 1683 public static function import_course_returns() { 1684 return null; 1685 } 1686 1687 /** 1688 * Returns description of method parameters 1689 * 1690 * @return external_function_parameters 1691 * @since Moodle 2.3 1692 */ 1693 public static function get_categories_parameters() { 1694 return new external_function_parameters( 1695 array( 1696 'criteria' => new external_multiple_structure( 1697 new external_single_structure( 1698 array( 1699 'key' => new external_value(PARAM_ALPHA, 1700 'The category column to search, expected keys (value format) are:'. 1701 '"id" (int) the category id,'. 1702 '"ids" (string) category ids separated by commas,'. 1703 '"name" (string) the category name,'. 1704 '"parent" (int) the parent category id,'. 1705 '"idnumber" (string) category idnumber'. 1706 ' - user must have \'moodle/category:manage\' to search on idnumber,'. 1707 '"visible" (int) whether the returned categories must be visible or hidden. If the key is not passed, 1708 then the function return all categories that the user can see.'. 1709 ' - user must have \'moodle/category:manage\' or \'moodle/category:viewhiddencategories\' to search on visible,'. 1710 '"theme" (string) only return the categories having this theme'. 1711 ' - user must have \'moodle/category:manage\' to search on theme'), 1712 'value' => new external_value(PARAM_RAW, 'the value to match') 1713 ) 1714 ), 'criteria', VALUE_DEFAULT, array() 1715 ), 1716 'addsubcategories' => new external_value(PARAM_BOOL, 'return the sub categories infos 1717 (1 - default) otherwise only the category info (0)', VALUE_DEFAULT, 1) 1718 ) 1719 ); 1720 } 1721 1722 /** 1723 * Get categories 1724 * 1725 * @param array $criteria Criteria to match the results 1726 * @param booln $addsubcategories obtain only the category (false) or its subcategories (true - default) 1727 * @return array list of categories 1728 * @since Moodle 2.3 1729 */ 1730 public static function get_categories($criteria = array(), $addsubcategories = true) { 1731 global $CFG, $DB; 1732 require_once($CFG->dirroot . "/course/lib.php"); 1733 1734 // Validate parameters. 1735 $params = self::validate_parameters(self::get_categories_parameters(), 1736 array('criteria' => $criteria, 'addsubcategories' => $addsubcategories)); 1737 1738 // Retrieve the categories. 1739 $categories = array(); 1740 if (!empty($params['criteria'])) { 1741 1742 $conditions = array(); 1743 $wheres = array(); 1744 foreach ($params['criteria'] as $crit) { 1745 $key = trim($crit['key']); 1746 1747 // Trying to avoid duplicate keys. 1748 if (!isset($conditions[$key])) { 1749 1750 $context = context_system::instance(); 1751 $value = null; 1752 switch ($key) { 1753 case 'id': 1754 $value = clean_param($crit['value'], PARAM_INT); 1755 $conditions[$key] = $value; 1756 $wheres[] = $key . " = :" . $key; 1757 break; 1758 1759 case 'ids': 1760 $value = clean_param($crit['value'], PARAM_SEQUENCE); 1761 $ids = explode(',', $value); 1762 list($sqlids, $paramids) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED); 1763 $conditions = array_merge($conditions, $paramids); 1764 $wheres[] = 'id ' . $sqlids; 1765 break; 1766 1767 case 'idnumber': 1768 if (has_capability('moodle/category:manage', $context)) { 1769 $value = clean_param($crit['value'], PARAM_RAW); 1770 $conditions[$key] = $value; 1771 $wheres[] = $key . " = :" . $key; 1772 } else { 1773 // We must throw an exception. 1774 // Otherwise the dev client would think no idnumber exists. 1775 throw new moodle_exception('criteriaerror', 1776 'webservice', '', null, 1777 'You don\'t have the permissions to search on the "idnumber" field.'); 1778 } 1779 break; 1780 1781 case 'name': 1782 $value = clean_param($crit['value'], PARAM_TEXT); 1783 $conditions[$key] = $value; 1784 $wheres[] = $key . " = :" . $key; 1785 break; 1786 1787 case 'parent': 1788 $value = clean_param($crit['value'], PARAM_INT); 1789 $conditions[$key] = $value; 1790 $wheres[] = $key . " = :" . $key; 1791 break; 1792 1793 case 'visible': 1794 if (has_capability('moodle/category:viewhiddencategories', $context)) { 1795 $value = clean_param($crit['value'], PARAM_INT); 1796 $conditions[$key] = $value; 1797 $wheres[] = $key . " = :" . $key; 1798 } else { 1799 throw new moodle_exception('criteriaerror', 1800 'webservice', '', null, 1801 'You don\'t have the permissions to search on the "visible" field.'); 1802 } 1803 break; 1804 1805 case 'theme': 1806 if (has_capability('moodle/category:manage', $context)) { 1807 $value = clean_param($crit['value'], PARAM_THEME); 1808 $conditions[$key] = $value; 1809 $wheres[] = $key . " = :" . $key; 1810 } else { 1811 throw new moodle_exception('criteriaerror', 1812 'webservice', '', null, 1813 'You don\'t have the permissions to search on the "theme" field.'); 1814 } 1815 break; 1816 1817 default: 1818 throw new moodle_exception('criteriaerror', 1819 'webservice', '', null, 1820 'You can not search on this criteria: ' . $key); 1821 } 1822 } 1823 } 1824 1825 if (!empty($wheres)) { 1826 $wheres = implode(" AND ", $wheres); 1827 1828 $categories = $DB->get_records_select('course_categories', $wheres, $conditions); 1829 1830 // Retrieve its sub subcategories (all levels). 1831 if ($categories and !empty($params['addsubcategories'])) { 1832 $newcategories = array(); 1833 1834 // Check if we required visible/theme checks. 1835 $additionalselect = ''; 1836 $additionalparams = array(); 1837 if (isset($conditions['visible'])) { 1838 $additionalselect .= ' AND visible = :visible'; 1839 $additionalparams['visible'] = $conditions['visible']; 1840 } 1841 if (isset($conditions['theme'])) { 1842 $additionalselect .= ' AND theme= :theme'; 1843 $additionalparams['theme'] = $conditions['theme']; 1844 } 1845 1846 foreach ($categories as $category) { 1847 $sqlselect = $DB->sql_like('path', ':path') . $additionalselect; 1848 $sqlparams = array('path' => $category->path.'/%') + $additionalparams; // It will NOT include the specified category. 1849 $subcategories = $DB->get_records_select('course_categories', $sqlselect, $sqlparams); 1850 $newcategories = $newcategories + $subcategories; // Both arrays have integer as keys. 1851 } 1852 $categories = $categories + $newcategories; 1853 } 1854 } 1855 1856 } else { 1857 // Retrieve all categories in the database. 1858 $categories = $DB->get_records('course_categories'); 1859 } 1860 1861 // The not returned categories. key => category id, value => reason of exclusion. 1862 $excludedcats = array(); 1863 1864 // The returned categories. 1865 $categoriesinfo = array(); 1866 1867 // We need to sort the categories by path. 1868 // The parent cats need to be checked by the algo first. 1869 usort($categories, "core_course_external::compare_categories_by_path"); 1870 1871 foreach ($categories as $category) { 1872 1873 // Check if the category is a child of an excluded category, if yes exclude it too (excluded => do not return). 1874 $parents = explode('/', $category->path); 1875 unset($parents[0]); // First key is always empty because path start with / => /1/2/4. 1876 foreach ($parents as $parentid) { 1877 // Note: when the parent exclusion was due to the context, 1878 // the sub category could still be returned. 1879 if (isset($excludedcats[$parentid]) and $excludedcats[$parentid] != 'context') { 1880 $excludedcats[$category->id] = 'parent'; 1881 } 1882 } 1883 1884 // Check the user can use the category context. 1885 $context = context_coursecat::instance($category->id); 1886 try { 1887 self::validate_context($context); 1888 } catch (Exception $e) { 1889 $excludedcats[$category->id] = 'context'; 1890 1891 // If it was the requested category then throw an exception. 1892 if (isset($params['categoryid']) && $category->id == $params['categoryid']) { 1893 $exceptionparam = new stdClass(); 1894 $exceptionparam->message = $e->getMessage(); 1895 $exceptionparam->catid = $category->id; 1896 throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam); 1897 } 1898 } 1899 1900 // Return the category information. 1901 if (!isset($excludedcats[$category->id])) { 1902 1903 // Final check to see if the category is visible to the user. 1904 if (core_course_category::can_view_category($category)) { 1905 1906 $categoryinfo = array(); 1907 $categoryinfo['id'] = $category->id; 1908 $categoryinfo['name'] = external_format_string($category->name, $context); 1909 list($categoryinfo['description'], $categoryinfo['descriptionformat']) = 1910 external_format_text($category->description, $category->descriptionformat, 1911 $context->id, 'coursecat', 'description', null); 1912 $categoryinfo['parent'] = $category->parent; 1913 $categoryinfo['sortorder'] = $category->sortorder; 1914 $categoryinfo['coursecount'] = $category->coursecount; 1915 $categoryinfo['depth'] = $category->depth; 1916 $categoryinfo['path'] = $category->path; 1917 1918 // Some fields only returned for admin. 1919 if (has_capability('moodle/category:manage', $context)) { 1920 $categoryinfo['idnumber'] = $category->idnumber; 1921 $categoryinfo['visible'] = $category->visible; 1922 $categoryinfo['visibleold'] = $category->visibleold; 1923 $categoryinfo['timemodified'] = $category->timemodified; 1924 $categoryinfo['theme'] = clean_param($category->theme, PARAM_THEME); 1925 } 1926 1927 $categoriesinfo[] = $categoryinfo; 1928 } else { 1929 $excludedcats[$category->id] = 'visibility'; 1930 } 1931 } 1932 } 1933 1934 // Sorting the resulting array so it looks a bit better for the client developer. 1935 usort($categoriesinfo, "core_course_external::compare_categories_by_sortorder"); 1936 1937 return $categoriesinfo; 1938 } 1939 1940 /** 1941 * Sort categories array by path 1942 * private function: only used by get_categories 1943 * 1944 * @param array $category1 1945 * @param array $category2 1946 * @return int result of strcmp 1947 * @since Moodle 2.3 1948 */ 1949 private static function compare_categories_by_path($category1, $category2) { 1950 return strcmp($category1->path, $category2->path); 1951 } 1952 1953 /** 1954 * Sort categories array by sortorder 1955 * private function: only used by get_categories 1956 * 1957 * @param array $category1 1958 * @param array $category2 1959 * @return int result of strcmp 1960 * @since Moodle 2.3 1961 */ 1962 private static function compare_categories_by_sortorder($category1, $category2) { 1963 return strcmp($category1['sortorder'], $category2['sortorder']); 1964 } 1965 1966 /** 1967 * Returns description of method result value 1968 * 1969 * @return external_description 1970 * @since Moodle 2.3 1971 */ 1972 public static function get_categories_returns() { 1973 return new external_multiple_structure( 1974 new external_single_structure( 1975 array( 1976 'id' => new external_value(PARAM_INT, 'category id'), 1977 'name' => new external_value(PARAM_RAW, 'category name'), 1978 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL), 1979 'description' => new external_value(PARAM_RAW, 'category description'), 1980 'descriptionformat' => new external_format_value('description'), 1981 'parent' => new external_value(PARAM_INT, 'parent category id'), 1982 'sortorder' => new external_value(PARAM_INT, 'category sorting order'), 1983 'coursecount' => new external_value(PARAM_INT, 'number of courses in this category'), 1984 'visible' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL), 1985 'visibleold' => new external_value(PARAM_INT, '1: available, 0:not available', VALUE_OPTIONAL), 1986 'timemodified' => new external_value(PARAM_INT, 'timestamp', VALUE_OPTIONAL), 1987 'depth' => new external_value(PARAM_INT, 'category depth'), 1988 'path' => new external_value(PARAM_TEXT, 'category path'), 1989 'theme' => new external_value(PARAM_THEME, 'category theme', VALUE_OPTIONAL), 1990 ), 'List of categories' 1991 ) 1992 ); 1993 } 1994 1995 /** 1996 * Returns description of method parameters 1997 * 1998 * @return external_function_parameters 1999 * @since Moodle 2.3 2000 */ 2001 public static function create_categories_parameters() { 2002 return new external_function_parameters( 2003 array( 2004 'categories' => new external_multiple_structure( 2005 new external_single_structure( 2006 array( 2007 'name' => new external_value(PARAM_TEXT, 'new category name'), 2008 'parent' => new external_value(PARAM_INT, 2009 'the parent category id inside which the new category will be created 2010 - set to 0 for a root category', 2011 VALUE_DEFAULT, 0), 2012 'idnumber' => new external_value(PARAM_RAW, 2013 'the new category idnumber', VALUE_OPTIONAL), 2014 'description' => new external_value(PARAM_RAW, 2015 'the new category description', VALUE_OPTIONAL), 2016 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT), 2017 'theme' => new external_value(PARAM_THEME, 2018 'the new category theme. This option must be enabled on moodle', 2019 VALUE_OPTIONAL), 2020 ) 2021 ) 2022 ) 2023 ) 2024 ); 2025 } 2026 2027 /** 2028 * Create categories 2029 * 2030 * @param array $categories - see create_categories_parameters() for the array structure 2031 * @return array - see create_categories_returns() for the array structure 2032 * @since Moodle 2.3 2033 */ 2034 public static function create_categories($categories) { 2035 global $DB; 2036 2037 $params = self::validate_parameters(self::create_categories_parameters(), 2038 array('categories' => $categories)); 2039 2040 $transaction = $DB->start_delegated_transaction(); 2041 2042 $createdcategories = array(); 2043 foreach ($params['categories'] as $category) { 2044 if ($category['parent']) { 2045 if (!$DB->record_exists('course_categories', array('id' => $category['parent']))) { 2046 throw new moodle_exception('unknowcategory'); 2047 } 2048 $context = context_coursecat::instance($category['parent']); 2049 } else { 2050 $context = context_system::instance(); 2051 } 2052 self::validate_context($context); 2053 require_capability('moodle/category:manage', $context); 2054 2055 // this will validate format and throw an exception if there are errors 2056 external_validate_format($category['descriptionformat']); 2057 2058 $newcategory = core_course_category::create($category); 2059 $context = context_coursecat::instance($newcategory->id); 2060 2061 $createdcategories[] = array( 2062 'id' => $newcategory->id, 2063 'name' => external_format_string($newcategory->name, $context), 2064 ); 2065 } 2066 2067 $transaction->allow_commit(); 2068 2069 return $createdcategories; 2070 } 2071 2072 /** 2073 * Returns description of method parameters 2074 * 2075 * @return external_function_parameters 2076 * @since Moodle 2.3 2077 */ 2078 public static function create_categories_returns() { 2079 return new external_multiple_structure( 2080 new external_single_structure( 2081 array( 2082 'id' => new external_value(PARAM_INT, 'new category id'), 2083 'name' => new external_value(PARAM_RAW, 'new category name'), 2084 ) 2085 ) 2086 ); 2087 } 2088 2089 /** 2090 * Returns description of method parameters 2091 * 2092 * @return external_function_parameters 2093 * @since Moodle 2.3 2094 */ 2095 public static function update_categories_parameters() { 2096 return new external_function_parameters( 2097 array( 2098 'categories' => new external_multiple_structure( 2099 new external_single_structure( 2100 array( 2101 'id' => new external_value(PARAM_INT, 'course id'), 2102 'name' => new external_value(PARAM_TEXT, 'category name', VALUE_OPTIONAL), 2103 'idnumber' => new external_value(PARAM_RAW, 'category id number', VALUE_OPTIONAL), 2104 'parent' => new external_value(PARAM_INT, 'parent category id', VALUE_OPTIONAL), 2105 'description' => new external_value(PARAM_RAW, 'category description', VALUE_OPTIONAL), 2106 'descriptionformat' => new external_format_value('description', VALUE_DEFAULT), 2107 'theme' => new external_value(PARAM_THEME, 2108 'the category theme. This option must be enabled on moodle', VALUE_OPTIONAL), 2109 ) 2110 ) 2111 ) 2112 ) 2113 ); 2114 } 2115 2116 /** 2117 * Update categories 2118 * 2119 * @param array $categories The list of categories to update 2120 * @return null 2121 * @since Moodle 2.3 2122 */ 2123 public static function update_categories($categories) { 2124 global $DB; 2125 2126 // Validate parameters. 2127 $params = self::validate_parameters(self::update_categories_parameters(), array('categories' => $categories)); 2128 2129 $transaction = $DB->start_delegated_transaction(); 2130 2131 foreach ($params['categories'] as $cat) { 2132 $category = core_course_category::get($cat['id']); 2133 2134 $categorycontext = context_coursecat::instance($cat['id']); 2135 self::validate_context($categorycontext); 2136 require_capability('moodle/category:manage', $categorycontext); 2137 2138 // this will throw an exception if descriptionformat is not valid 2139 external_validate_format($cat['descriptionformat']); 2140 2141 $category->update($cat); 2142 } 2143 2144 $transaction->allow_commit(); 2145 } 2146 2147 /** 2148 * Returns description of method result value 2149 * 2150 * @return external_description 2151 * @since Moodle 2.3 2152 */ 2153 public static function update_categories_returns() { 2154 return null; 2155 } 2156 2157 /** 2158 * Returns description of method parameters 2159 * 2160 * @return external_function_parameters 2161 * @since Moodle 2.3 2162 */ 2163 public static function delete_categories_parameters() { 2164 return new external_function_parameters( 2165 array( 2166 'categories' => new external_multiple_structure( 2167 new external_single_structure( 2168 array( 2169 'id' => new external_value(PARAM_INT, 'category id to delete'), 2170 'newparent' => new external_value(PARAM_INT, 2171 'the parent category to move the contents to, if specified', VALUE_OPTIONAL), 2172 'recursive' => new external_value(PARAM_BOOL, '1: recursively delete all contents inside this 2173 category, 0 (default): move contents to newparent or current parent category (except if parent is root)', VALUE_DEFAULT, 0) 2174 ) 2175 ) 2176 ) 2177 ) 2178 ); 2179 } 2180 2181 /** 2182 * Delete categories 2183 * 2184 * @param array $categories A list of category ids 2185 * @return array 2186 * @since Moodle 2.3 2187 */ 2188 public static function delete_categories($categories) { 2189 global $CFG, $DB; 2190 require_once($CFG->dirroot . "/course/lib.php"); 2191 2192 // Validate parameters. 2193 $params = self::validate_parameters(self::delete_categories_parameters(), array('categories' => $categories)); 2194 2195 $transaction = $DB->start_delegated_transaction(); 2196 2197 foreach ($params['categories'] as $category) { 2198 $deletecat = core_course_category::get($category['id'], MUST_EXIST); 2199 $context = context_coursecat::instance($deletecat->id); 2200 require_capability('moodle/category:manage', $context); 2201 self::validate_context($context); 2202 self::validate_context(get_category_or_system_context($deletecat->parent)); 2203 2204 if ($category['recursive']) { 2205 // If recursive was specified, then we recursively delete the category's contents. 2206 if ($deletecat->can_delete_full()) { 2207 $deletecat->delete_full(false); 2208 } else { 2209 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name()); 2210 } 2211 } else { 2212 // In this situation, we don't delete the category's contents, we either move it to newparent or parent. 2213 // If the parent is the root, moving is not supported (because a course must always be inside a category). 2214 // We must move to an existing category. 2215 if (!empty($category['newparent'])) { 2216 $newparentcat = core_course_category::get($category['newparent']); 2217 } else { 2218 $newparentcat = core_course_category::get($deletecat->parent); 2219 } 2220 2221 // This operation is not allowed. We must move contents to an existing category. 2222 if (!$newparentcat->id) { 2223 throw new moodle_exception('movecatcontentstoroot'); 2224 } 2225 2226 self::validate_context(context_coursecat::instance($newparentcat->id)); 2227 if ($deletecat->can_move_content_to($newparentcat->id)) { 2228 $deletecat->delete_move($newparentcat->id, false); 2229 } else { 2230 throw new moodle_exception('youcannotdeletecategory', '', '', $deletecat->get_formatted_name()); 2231 } 2232 } 2233 } 2234 2235 $transaction->allow_commit(); 2236 } 2237 2238 /** 2239 * Returns description of method parameters 2240 * 2241 * @return external_function_parameters 2242 * @since Moodle 2.3 2243 */ 2244 public static function delete_categories_returns() { 2245 return null; 2246 } 2247 2248 /** 2249 * Describes the parameters for delete_modules. 2250 * 2251 * @return external_function_parameters 2252 * @since Moodle 2.5 2253 */ 2254 public static function delete_modules_parameters() { 2255 return new external_function_parameters ( 2256 array( 2257 'cmids' => new external_multiple_structure(new external_value(PARAM_INT, 'course module ID', 2258 VALUE_REQUIRED, '', NULL_NOT_ALLOWED), 'Array of course module IDs'), 2259 ) 2260 ); 2261 } 2262 2263 /** 2264 * Deletes a list of provided module instances. 2265 * 2266 * @param array $cmids the course module ids 2267 * @since Moodle 2.5 2268 */ 2269 public static function delete_modules($cmids) { 2270 global $CFG, $DB; 2271 2272 // Require course file containing the course delete module function. 2273 require_once($CFG->dirroot . "/course/lib.php"); 2274 2275 // Clean the parameters. 2276 $params = self::validate_parameters(self::delete_modules_parameters(), array('cmids' => $cmids)); 2277 2278 // Keep track of the course ids we have performed a capability check on to avoid repeating. 2279 $arrcourseschecked = array(); 2280 2281 foreach ($params['cmids'] as $cmid) { 2282 // Get the course module. 2283 $cm = $DB->get_record('course_modules', array('id' => $cmid), '*', MUST_EXIST); 2284 2285 // Check if we have not yet confirmed they have permission in this course. 2286 if (!in_array($cm->course, $arrcourseschecked)) { 2287 // Ensure the current user has required permission in this course. 2288 $context = context_course::instance($cm->course); 2289 self::validate_context($context); 2290 // Add to the array. 2291 $arrcourseschecked[] = $cm->course; 2292 } 2293 2294 // Ensure they can delete this module. 2295 $modcontext = context_module::instance($cm->id); 2296 require_capability('moodle/course:manageactivities', $modcontext); 2297 2298 // Delete the module. 2299 course_delete_module($cm->id); 2300 } 2301 } 2302 2303 /** 2304 * Describes the delete_modules return value. 2305 * 2306 * @return external_single_structure 2307 * @since Moodle 2.5 2308 */ 2309 public static function delete_modules_returns() { 2310 return null; 2311 } 2312 2313 /** 2314 * Returns description of method parameters 2315 * 2316 * @return external_function_parameters 2317 * @since Moodle 2.9 2318 */ 2319 public static function view_course_parameters() { 2320 return new external_function_parameters( 2321 array( 2322 'courseid' => new external_value(PARAM_INT, 'id of the course'), 2323 'sectionnumber' => new external_value(PARAM_INT, 'section number', VALUE_DEFAULT, 0) 2324 ) 2325 ); 2326 } 2327 2328 /** 2329 * Trigger the course viewed event. 2330 * 2331 * @param int $courseid id of course 2332 * @param int $sectionnumber sectionnumber (0, 1, 2...) 2333 * @return array of warnings and status result 2334 * @since Moodle 2.9 2335 * @throws moodle_exception 2336 */ 2337 public static function view_course($courseid, $sectionnumber = 0) { 2338 global $CFG; 2339 require_once($CFG->dirroot . "/course/lib.php"); 2340 2341 $params = self::validate_parameters(self::view_course_parameters(), 2342 array( 2343 'courseid' => $courseid, 2344 'sectionnumber' => $sectionnumber 2345 )); 2346 2347 $warnings = array(); 2348 2349 $course = get_course($params['courseid']); 2350 $context = context_course::instance($course->id); 2351 self::validate_context($context); 2352 2353 if (!empty($params['sectionnumber'])) { 2354 2355 // Get section details and check it exists. 2356 $modinfo = get_fast_modinfo($course); 2357 $coursesection = $modinfo->get_section_info($params['sectionnumber'], MUST_EXIST); 2358 2359 // Check user is allowed to see it. 2360 if (!$coursesection->uservisible) { 2361 require_capability('moodle/course:viewhiddensections', $context); 2362 } 2363 } 2364 2365 course_view($context, $params['sectionnumber']); 2366 2367 $result = array(); 2368 $result['status'] = true; 2369 $result['warnings'] = $warnings; 2370 return $result; 2371 } 2372 2373 /** 2374 * Returns description of method result value 2375 * 2376 * @return external_description 2377 * @since Moodle 2.9 2378 */ 2379 public static function view_course_returns() { 2380 return new external_single_structure( 2381 array( 2382 'status' => new external_value(PARAM_BOOL, 'status: true if success'), 2383 'warnings' => new external_warnings() 2384 ) 2385 ); 2386 } 2387 2388 /** 2389 * Returns description of method parameters 2390 * 2391 * @return external_function_parameters 2392 * @since Moodle 3.0 2393 */ 2394 public static function search_courses_parameters() { 2395 return new external_function_parameters( 2396 array( 2397 'criterianame' => new external_value(PARAM_ALPHA, 'criteria name 2398 (search, modulelist (only admins), blocklist (only admins), tagid)'), 2399 'criteriavalue' => new external_value(PARAM_RAW, 'criteria value'), 2400 'page' => new external_value(PARAM_INT, 'page number (0 based)', VALUE_DEFAULT, 0), 2401 'perpage' => new external_value(PARAM_INT, 'items per page', VALUE_DEFAULT, 0), 2402 'requiredcapabilities' => new external_multiple_structure( 2403 new external_value(PARAM_CAPABILITY, 'Capability string used to filter courses by permission'), 2404 'Optional list of required capabilities (used to filter the list)', VALUE_DEFAULT, array() 2405 ), 2406 'limittoenrolled' => new external_value(PARAM_BOOL, 'limit to enrolled courses', VALUE_DEFAULT, 0), 2407 'onlywithcompletion' => new external_value(PARAM_BOOL, 'limit to courses where completion is enabled', 2408 VALUE_DEFAULT, 0), 2409 ) 2410 ); 2411 } 2412 2413 /** 2414 * Return the course information that is public (visible by every one) 2415 * 2416 * @param core_course_list_element $course course in list object 2417 * @param stdClass $coursecontext course context object 2418 * @return array the course information 2419 * @since Moodle 3.2 2420 */ 2421 protected static function get_course_public_information(core_course_list_element $course, $coursecontext) { 2422 2423 static $categoriescache = array(); 2424 2425 // Category information. 2426 if (!array_key_exists($course->category, $categoriescache)) { 2427 $categoriescache[$course->category] = core_course_category::get($course->category, IGNORE_MISSING); 2428 } 2429 $category = $categoriescache[$course->category]; 2430 2431 // Retrieve course overview used files. 2432 $files = array(); 2433 foreach ($course->get_course_overviewfiles() as $file) { 2434 $fileurl = moodle_url::make_webservice_pluginfile_url($file->get_contextid(), $file->get_component(), 2435 $file->get_filearea(), null, $file->get_filepath(), 2436 $file->get_filename())->out(false); 2437 $files[] = array( 2438 'filename' => $file->get_filename(), 2439 'fileurl' => $fileurl, 2440 'filesize' => $file->get_filesize(), 2441 'filepath' => $file->get_filepath(), 2442 'mimetype' => $file->get_mimetype(), 2443 'timemodified' => $file->get_timemodified(), 2444 ); 2445 } 2446 2447 // Retrieve the course contacts, 2448 // we need here the users fullname since if we are not enrolled can be difficult to obtain them via other Web Services. 2449 $coursecontacts = array(); 2450 foreach ($course->get_course_contacts() as $contact) { 2451 $coursecontacts[] = array( 2452 'id' => $contact['user']->id, 2453 'fullname' => $contact['username'], 2454 'roles' => array_map(function($role){ 2455 return array('id' => $role->id, 'name' => $role->displayname); 2456 }, $contact['roles']), 2457 'role' => array('id' => $contact['role']->id, 'name' => $contact['role']->displayname), 2458 'rolename' => $contact['rolename'] 2459 ); 2460 } 2461 2462 // Allowed enrolment methods (maybe we can self-enrol). 2463 $enroltypes = array(); 2464 $instances = enrol_get_instances($course->id, true); 2465 foreach ($instances as $instance) { 2466 $enroltypes[] = $instance->enrol; 2467 } 2468 2469 // Format summary. 2470 list($summary, $summaryformat) = 2471 external_format_text($course->summary, $course->summaryformat, $coursecontext->id, 'course', 'summary', null); 2472 2473 $categoryname = ''; 2474 if (!empty($category)) { 2475 $categoryname = external_format_string($category->name, $category->get_context()); 2476 } 2477 2478 $displayname = get_course_display_name_for_list($course); 2479 $coursereturns = array(); 2480 $coursereturns['id'] = $course->id; 2481 $coursereturns['fullname'] = external_format_string($course->fullname, $coursecontext->id); 2482 $coursereturns['displayname'] = external_format_string($displayname, $coursecontext->id); 2483 $coursereturns['shortname'] = external_format_string($course->shortname, $coursecontext->id); 2484 $coursereturns['categoryid'] = $course->category; 2485 $coursereturns['categoryname'] = $categoryname; 2486 $coursereturns['summary'] = $summary; 2487 $coursereturns['summaryformat'] = $summaryformat; 2488 $coursereturns['summaryfiles'] = external_util::get_area_files($coursecontext->id, 'course', 'summary', false, false); 2489 $coursereturns['overviewfiles'] = $files; 2490 $coursereturns['contacts'] = $coursecontacts; 2491 $coursereturns['enrollmentmethods'] = $enroltypes; 2492 $coursereturns['sortorder'] = $course->sortorder; 2493 2494 $handler = core_course\customfield\course_handler::create(); 2495 if ($customfields = $handler->export_instance_data($course->id)) { 2496 $coursereturns['customfields'] = []; 2497 foreach ($customfields as $data) { 2498 $coursereturns['customfields'][] = [ 2499 'type' => $data->get_type(), 2500 'value' => $data->get_value(), 2501 'valueraw' => $data->get_data_controller()->get_value(), 2502 'name' => $data->get_name(), 2503 'shortname' => $data->get_shortname() 2504 ]; 2505 } 2506 } 2507 2508 return $coursereturns; 2509 } 2510 2511 /** 2512 * Search courses following the specified criteria. 2513 * 2514 * @param string $criterianame Criteria name (search, modulelist (only admins), blocklist (only admins), tagid) 2515 * @param string $criteriavalue Criteria value 2516 * @param int $page Page number (for pagination) 2517 * @param int $perpage Items per page 2518 * @param array $requiredcapabilities Optional list of required capabilities (used to filter the list). 2519 * @param int $limittoenrolled Limit to only enrolled courses 2520 * @param int onlywithcompletion Limit to only courses where completion is enabled 2521 * @return array of course objects and warnings 2522 * @since Moodle 3.0 2523 * @throws moodle_exception 2524 */ 2525 public static function search_courses($criterianame, 2526 $criteriavalue, 2527 $page=0, 2528 $perpage=0, 2529 $requiredcapabilities=array(), 2530 $limittoenrolled=0, 2531 $onlywithcompletion=0) { 2532 global $CFG; 2533 2534 $warnings = array(); 2535 2536 $parameters = array( 2537 'criterianame' => $criterianame, 2538 'criteriavalue' => $criteriavalue, 2539 'page' => $page, 2540 'perpage' => $perpage, 2541 'requiredcapabilities' => $requiredcapabilities, 2542 'limittoenrolled' => $limittoenrolled, 2543 'onlywithcompletion' => $onlywithcompletion 2544 ); 2545 $params = self::validate_parameters(self::search_courses_parameters(), $parameters); 2546 self::validate_context(context_system::instance()); 2547 2548 $allowedcriterianames = array('search', 'modulelist', 'blocklist', 'tagid'); 2549 if (!in_array($params['criterianame'], $allowedcriterianames)) { 2550 throw new invalid_parameter_exception('Invalid value for criterianame parameter (value: '.$params['criterianame'].'),' . 2551 'allowed values are: '.implode(',', $allowedcriterianames)); 2552 } 2553 2554 if ($params['criterianame'] == 'modulelist' or $params['criterianame'] == 'blocklist') { 2555 require_capability('moodle/site:config', context_system::instance()); 2556 } 2557 2558 $paramtype = array( 2559 'search' => PARAM_RAW, 2560 'modulelist' => PARAM_PLUGIN, 2561 'blocklist' => PARAM_INT, 2562 'tagid' => PARAM_INT 2563 ); 2564 $params['criteriavalue'] = clean_param($params['criteriavalue'], $paramtype[$params['criterianame']]); 2565 2566 // Prepare the search API options. 2567 $searchcriteria = array(); 2568 $searchcriteria[$params['criterianame']] = $params['criteriavalue']; 2569 if ($params['onlywithcompletion']) { 2570 $searchcriteria['onlywithcompletion'] = true; 2571 } 2572 2573 $options = array(); 2574 if ($params['perpage'] != 0) { 2575 $offset = $params['page'] * $params['perpage']; 2576 $options = array('offset' => $offset, 'limit' => $params['perpage']); 2577 } 2578 2579 // Search the courses. 2580 $courses = core_course_category::search_courses($searchcriteria, $options, $params['requiredcapabilities']); 2581 $totalcount = core_course_category::search_courses_count($searchcriteria, $options, $params['requiredcapabilities']); 2582 2583 if (!empty($limittoenrolled)) { 2584 // Get the courses where the current user has access. 2585 $enrolled = enrol_get_my_courses(array('id', 'cacherev')); 2586 } 2587 2588 $finalcourses = array(); 2589 $categoriescache = array(); 2590 2591 foreach ($courses as $course) { 2592 if (!empty($limittoenrolled)) { 2593 // Filter out not enrolled courses. 2594 if (!isset($enrolled[$course->id])) { 2595 $totalcount--; 2596 continue; 2597 } 2598 } 2599 2600 $coursecontext = context_course::instance($course->id); 2601 2602 $finalcourses[] = self::get_course_public_information($course, $coursecontext); 2603 } 2604 2605 return array( 2606 'total' => $totalcount, 2607 'courses' => $finalcourses, 2608 'warnings' => $warnings 2609 ); 2610 } 2611 2612 /** 2613 * Returns a course structure definition 2614 * 2615 * @param boolean $onlypublicdata set to true, to retrieve only fields viewable by anyone when the course is visible 2616 * @return array the course structure 2617 * @since Moodle 3.2 2618 */ 2619 protected static function get_course_structure($onlypublicdata = true) { 2620 $coursestructure = array( 2621 'id' => new external_value(PARAM_INT, 'course id'), 2622 'fullname' => new external_value(PARAM_RAW, 'course full name'), 2623 'displayname' => new external_value(PARAM_RAW, 'course display name'), 2624 'shortname' => new external_value(PARAM_RAW, 'course short name'), 2625 'categoryid' => new external_value(PARAM_INT, 'category id'), 2626 'categoryname' => new external_value(PARAM_RAW, 'category name'), 2627 'sortorder' => new external_value(PARAM_INT, 'Sort order in the category', VALUE_OPTIONAL), 2628 'summary' => new external_value(PARAM_RAW, 'summary'), 2629 'summaryformat' => new external_format_value('summary'), 2630 'summaryfiles' => new external_files('summary files in the summary field', VALUE_OPTIONAL), 2631 'overviewfiles' => new external_files('additional overview files attached to this course'), 2632 'contacts' => new external_multiple_structure( 2633 new external_single_structure( 2634 array( 2635 'id' => new external_value(PARAM_INT, 'contact user id'), 2636 'fullname' => new external_value(PARAM_NOTAGS, 'contact user fullname'), 2637 ) 2638 ), 2639 'contact users' 2640 ), 2641 'enrollmentmethods' => new external_multiple_structure( 2642 new external_value(PARAM_PLUGIN, 'enrollment method'), 2643 'enrollment methods list' 2644 ), 2645 'customfields' => new external_multiple_structure( 2646 new external_single_structure( 2647 array( 2648 'name' => new external_value(PARAM_RAW, 'The name of the custom field'), 2649 'shortname' => new external_value(PARAM_RAW, 2650 'The shortname of the custom field - to be able to build the field class in the code'), 2651 'type' => new external_value(PARAM_ALPHANUMEXT, 2652 'The type of the custom field - text field, checkbox...'), 2653 'valueraw' => new external_value(PARAM_RAW, 'The raw value of the custom field'), 2654 'value' => new external_value(PARAM_RAW, 'The value of the custom field'), 2655 ) 2656 ), 'Custom fields', VALUE_OPTIONAL), 2657 ); 2658 2659 if (!$onlypublicdata) { 2660 $extra = array( 2661 'idnumber' => new external_value(PARAM_RAW, 'Id number', VALUE_OPTIONAL), 2662 'format' => new external_value(PARAM_PLUGIN, 'Course format: weeks, topics, social, site,..', VALUE_OPTIONAL), 2663 'showgrades' => new external_value(PARAM_INT, '1 if grades are shown, otherwise 0', VALUE_OPTIONAL), 2664 'newsitems' => new external_value(PARAM_INT, 'Number of recent items appearing on the course page', VALUE_OPTIONAL), 2665 'startdate' => new external_value(PARAM_INT, 'Timestamp when the course start', VALUE_OPTIONAL), 2666 'enddate' => new external_value(PARAM_INT, 'Timestamp when the course end', VALUE_OPTIONAL), 2667 'maxbytes' => new external_value(PARAM_INT, 'Largest size of file that can be uploaded into', VALUE_OPTIONAL), 2668 'showreports' => new external_value(PARAM_INT, 'Are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL), 2669 'visible' => new external_value(PARAM_INT, '1: available to student, 0:not available', VALUE_OPTIONAL), 2670 'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL), 2671 'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL), 2672 'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL), 2673 'enablecompletion' => new external_value(PARAM_INT, 'Completion enabled? 1: yes 0: no', VALUE_OPTIONAL), 2674 'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL), 2675 'lang' => new external_value(PARAM_SAFEDIR, 'Forced course language', VALUE_OPTIONAL), 2676 'theme' => new external_value(PARAM_PLUGIN, 'Fame of the forced theme', VALUE_OPTIONAL), 2677 'marker' => new external_value(PARAM_INT, 'Current course marker', VALUE_OPTIONAL), 2678 'legacyfiles' => new external_value(PARAM_INT, 'If legacy files are enabled', VALUE_OPTIONAL), 2679 'calendartype' => new external_value(PARAM_PLUGIN, 'Calendar type', VALUE_OPTIONAL), 2680 'timecreated' => new external_value(PARAM_INT, 'Time when the course was created', VALUE_OPTIONAL), 2681 'timemodified' => new external_value(PARAM_INT, 'Last time the course was updated', VALUE_OPTIONAL), 2682 'requested' => new external_value(PARAM_INT, 'If is a requested course', VALUE_OPTIONAL), 2683 'cacherev' => new external_value(PARAM_INT, 'Cache revision number', VALUE_OPTIONAL), 2684 'filters' => new external_multiple_structure( 2685 new external_single_structure( 2686 array( 2687 'filter' => new external_value(PARAM_PLUGIN, 'Filter plugin name'), 2688 'localstate' => new external_value(PARAM_INT, 'Filter state: 1 for on, -1 for off, 0 if inherit'), 2689 'inheritedstate' => new external_value(PARAM_INT, '1 or 0 to use when localstate is set to inherit'), 2690 ) 2691 ), 2692 'Course filters', VALUE_OPTIONAL 2693 ), 2694 'courseformatoptions' => new external_multiple_structure( 2695 new external_single_structure( 2696 array( 2697 'name' => new external_value(PARAM_RAW, 'Course format option name.'), 2698 'value' => new external_value(PARAM_RAW, 'Course format option value.'), 2699 ) 2700 ), 2701 'Additional options for particular course format.', VALUE_OPTIONAL 2702 ), 2703 ); 2704 $coursestructure = array_merge($coursestructure, $extra); 2705 } 2706 return new external_single_structure($coursestructure); 2707 } 2708 2709 /** 2710 * Returns description of method result value 2711 * 2712 * @return external_description 2713 * @since Moodle 3.0 2714 */ 2715 public static function search_courses_returns() { 2716 return new external_single_structure( 2717 array( 2718 'total' => new external_value(PARAM_INT, 'total course count'), 2719 'courses' => new external_multiple_structure(self::get_course_structure(), 'course'), 2720 'warnings' => new external_warnings() 2721 ) 2722 ); 2723 } 2724 2725 /** 2726 * Returns description of method parameters 2727 * 2728 * @return external_function_parameters 2729 * @since Moodle 3.0 2730 */ 2731 public static function get_course_module_parameters() { 2732 return new external_function_parameters( 2733 array( 2734 'cmid' => new external_value(PARAM_INT, 'The course module id') 2735 ) 2736 ); 2737 } 2738 2739 /** 2740 * Return information about a course module. 2741 * 2742 * @param int $cmid the course module id 2743 * @return array of warnings and the course module 2744 * @since Moodle 3.0 2745 * @throws moodle_exception 2746 */ 2747 public static function get_course_module($cmid) { 2748 global $CFG, $DB; 2749 2750 $params = self::validate_parameters(self::get_course_module_parameters(), array('cmid' => $cmid)); 2751 $warnings = array(); 2752 2753 $cm = get_coursemodule_from_id(null, $params['cmid'], 0, true, MUST_EXIST); 2754 $context = context_module::instance($cm->id); 2755 self::validate_context($context); 2756 2757 // If the user has permissions to manage the activity, return all the information. 2758 if (has_capability('moodle/course:manageactivities', $context)) { 2759 require_once($CFG->dirroot . '/course/modlib.php'); 2760 require_once($CFG->libdir . '/gradelib.php'); 2761 2762 $info = $cm; 2763 // Get the extra information: grade, advanced grading and outcomes data. 2764 $course = get_course($cm->course); 2765 list($newcm, $newcontext, $module, $extrainfo, $cw) = get_moduleinfo_data($cm, $course); 2766 // Grades. 2767 $gradeinfo = array('grade', 'gradepass', 'gradecat'); 2768 foreach ($gradeinfo as $gfield) { 2769 if (isset($extrainfo->{$gfield})) { 2770 $info->{$gfield} = $extrainfo->{$gfield}; 2771 } 2772 } 2773 if (isset($extrainfo->grade) and $extrainfo->grade < 0) { 2774 $info->scale = $DB->get_field('scale', 'scale', array('id' => abs($extrainfo->grade))); 2775 } 2776 // Advanced grading. 2777 if (isset($extrainfo->_advancedgradingdata)) { 2778 $info->advancedgrading = array(); 2779 foreach ($extrainfo as $key => $val) { 2780 if (strpos($key, 'advancedgradingmethod_') === 0) { 2781 $info->advancedgrading[] = array( 2782 'area' => str_replace('advancedgradingmethod_', '', $key), 2783 'method' => $val 2784 ); 2785 } 2786 } 2787 } 2788 // Outcomes. 2789 foreach ($extrainfo as $key => $val) { 2790 if (strpos($key, 'outcome_') === 0) { 2791 if (!isset($info->outcomes)) { 2792 $info->outcomes = array(); 2793 } 2794 $id = str_replace('outcome_', '', $key); 2795 $outcome = grade_outcome::fetch(array('id' => $id)); 2796 $scaleitems = $outcome->load_scale(); 2797 $info->outcomes[] = array( 2798 'id' => $id, 2799 'name' => external_format_string($outcome->get_name(), $context->id), 2800 'scale' => $scaleitems->scale 2801 ); 2802 } 2803 } 2804 } else { 2805 // Return information is safe to show to any user. 2806 $info = new stdClass(); 2807 $info->id = $cm->id; 2808 $info->course = $cm->course; 2809 $info->module = $cm->module; 2810 $info->modname = $cm->modname; 2811 $info->instance = $cm->instance; 2812 $info->section = $cm->section; 2813 $info->sectionnum = $cm->sectionnum; 2814 $info->groupmode = $cm->groupmode; 2815 $info->groupingid = $cm->groupingid; 2816 $info->completion = $cm->completion; 2817 } 2818 // Format name. 2819 $info->name = external_format_string($cm->name, $context->id); 2820 $result = array(); 2821 $result['cm'] = $info; 2822 $result['warnings'] = $warnings; 2823 return $result; 2824 } 2825 2826 /** 2827 * Returns description of method result value 2828 * 2829 * @return external_description 2830 * @since Moodle 3.0 2831 */ 2832 public static function get_course_module_returns() { 2833 return new external_single_structure( 2834 array( 2835 'cm' => new external_single_structure( 2836 array( 2837 'id' => new external_value(PARAM_INT, 'The course module id'), 2838 'course' => new external_value(PARAM_INT, 'The course id'), 2839 'module' => new external_value(PARAM_INT, 'The module type id'), 2840 'name' => new external_value(PARAM_RAW, 'The activity name'), 2841 'modname' => new external_value(PARAM_COMPONENT, 'The module component name (forum, assign, etc..)'), 2842 'instance' => new external_value(PARAM_INT, 'The activity instance id'), 2843 'section' => new external_value(PARAM_INT, 'The module section id'), 2844 'sectionnum' => new external_value(PARAM_INT, 'The module section number'), 2845 'groupmode' => new external_value(PARAM_INT, 'Group mode'), 2846 'groupingid' => new external_value(PARAM_INT, 'Grouping id'), 2847 'completion' => new external_value(PARAM_INT, 'If completion is enabled'), 2848 'idnumber' => new external_value(PARAM_RAW, 'Module id number', VALUE_OPTIONAL), 2849 'added' => new external_value(PARAM_INT, 'Time added', VALUE_OPTIONAL), 2850 'score' => new external_value(PARAM_INT, 'Score', VALUE_OPTIONAL), 2851 'indent' => new external_value(PARAM_INT, 'Indentation', VALUE_OPTIONAL), 2852 'visible' => new external_value(PARAM_INT, 'If visible', VALUE_OPTIONAL), 2853 'visibleoncoursepage' => new external_value(PARAM_INT, 'If visible on course page', VALUE_OPTIONAL), 2854 'visibleold' => new external_value(PARAM_INT, 'Visible old', VALUE_OPTIONAL), 2855 'completiongradeitemnumber' => new external_value(PARAM_INT, 'Completion grade item', VALUE_OPTIONAL), 2856 'completionview' => new external_value(PARAM_INT, 'Completion view setting', VALUE_OPTIONAL), 2857 'completionexpected' => new external_value(PARAM_INT, 'Completion time expected', VALUE_OPTIONAL), 2858 'showdescription' => new external_value(PARAM_INT, 'If the description is showed', VALUE_OPTIONAL), 2859 'availability' => new external_value(PARAM_RAW, 'Availability settings', VALUE_OPTIONAL), 2860 'grade' => new external_value(PARAM_FLOAT, 'Grade (max value or scale id)', VALUE_OPTIONAL), 2861 'scale' => new external_value(PARAM_TEXT, 'Scale items (if used)', VALUE_OPTIONAL), 2862 'gradepass' => new external_value(PARAM_RAW, 'Grade to pass (float)', VALUE_OPTIONAL), 2863 'gradecat' => new external_value(PARAM_INT, 'Grade category', VALUE_OPTIONAL), 2864 'advancedgrading' => new external_multiple_structure( 2865 new external_single_structure( 2866 array( 2867 'area' => new external_value(PARAM_AREA, 'Gradable area name'), 2868 'method' => new external_value(PARAM_COMPONENT, 'Grading method'), 2869 ) 2870 ), 2871 'Advanced grading settings', VALUE_OPTIONAL 2872 ), 2873 'outcomes' => new external_multiple_structure( 2874 new external_single_structure( 2875 array( 2876 'id' => new external_value(PARAM_ALPHANUMEXT, 'Outcome id'), 2877 'name' => new external_value(PARAM_RAW, 'Outcome full name'), 2878 'scale' => new external_value(PARAM_TEXT, 'Scale items') 2879 ) 2880 ), 2881 'Outcomes information', VALUE_OPTIONAL 2882 ), 2883 ) 2884 ), 2885 'warnings' => new external_warnings() 2886 ) 2887 ); 2888 } 2889 2890 /** 2891 * Returns description of method parameters 2892 * 2893 * @return external_function_parameters 2894 * @since Moodle 3.0 2895 */ 2896 public static function get_course_module_by_instance_parameters() { 2897 return new external_function_parameters( 2898 array( 2899 'module' => new external_value(PARAM_COMPONENT, 'The module name'), 2900 'instance' => new external_value(PARAM_INT, 'The module instance id') 2901 ) 2902 ); 2903 } 2904 2905 /** 2906 * Return information about a course module. 2907 * 2908 * @param string $module the module name 2909 * @param int $instance the activity instance id 2910 * @return array of warnings and the course module 2911 * @since Moodle 3.0 2912 * @throws moodle_exception 2913 */ 2914 public static function get_course_module_by_instance($module, $instance) { 2915 2916 $params = self::validate_parameters(self::get_course_module_by_instance_parameters(), 2917 array( 2918 'module' => $module, 2919 'instance' => $instance, 2920 )); 2921 2922 $warnings = array(); 2923 $cm = get_coursemodule_from_instance($params['module'], $params['instance'], 0, false, MUST_EXIST); 2924 2925 return self::get_course_module($cm->id); 2926 } 2927 2928 /** 2929 * Returns description of method result value 2930 * 2931 * @return external_description 2932 * @since Moodle 3.0 2933 */ 2934 public static function get_course_module_by_instance_returns() { 2935 return self::get_course_module_returns(); 2936 } 2937 2938 /** 2939 * Returns description of method parameters 2940 * 2941 * @return external_function_parameters 2942 * @since Moodle 3.2 2943 */ 2944 public static function get_user_navigation_options_parameters() { 2945 return new external_function_parameters( 2946 array( 2947 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')), 2948 ) 2949 ); 2950 } 2951 2952 /** 2953 * Return a list of navigation options in a set of courses that are avaialable or not for the current user. 2954 * 2955 * @param array $courseids a list of course ids 2956 * @return array of warnings and the options availability 2957 * @since Moodle 3.2 2958 * @throws moodle_exception 2959 */ 2960 public static function get_user_navigation_options($courseids) { 2961 global $CFG; 2962 require_once($CFG->dirroot . '/course/lib.php'); 2963 2964 // Parameter validation. 2965 $params = self::validate_parameters(self::get_user_navigation_options_parameters(), array('courseids' => $courseids)); 2966 $courseoptions = array(); 2967 2968 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true); 2969 2970 if (!empty($courses)) { 2971 foreach ($courses as $course) { 2972 // Fix the context for the frontpage. 2973 if ($course->id == SITEID) { 2974 $course->context = context_system::instance(); 2975 } 2976 $navoptions = course_get_user_navigation_options($course->context, $course); 2977 $options = array(); 2978 foreach ($navoptions as $name => $available) { 2979 $options[] = array( 2980 'name' => $name, 2981 'available' => $available, 2982 ); 2983 } 2984 2985 $courseoptions[] = array( 2986 'id' => $course->id, 2987 'options' => $options 2988 ); 2989 } 2990 } 2991 2992 $result = array( 2993 'courses' => $courseoptions, 2994 'warnings' => $warnings 2995 ); 2996 return $result; 2997 } 2998 2999 /** 3000 * Returns description of method result value 3001 * 3002 * @return external_description 3003 * @since Moodle 3.2 3004 */ 3005 public static function get_user_navigation_options_returns() { 3006 return new external_single_structure( 3007 array( 3008 'courses' => new external_multiple_structure( 3009 new external_single_structure( 3010 array( 3011 'id' => new external_value(PARAM_INT, 'Course id'), 3012 'options' => new external_multiple_structure( 3013 new external_single_structure( 3014 array( 3015 'name' => new external_value(PARAM_ALPHANUMEXT, 'Option name'), 3016 'available' => new external_value(PARAM_BOOL, 'Whether the option is available or not'), 3017 ) 3018 ) 3019 ) 3020 ) 3021 ), 'List of courses' 3022 ), 3023 'warnings' => new external_warnings() 3024 ) 3025 ); 3026 } 3027 3028 /** 3029 * Returns description of method parameters 3030 * 3031 * @return external_function_parameters 3032 * @since Moodle 3.2 3033 */ 3034 public static function get_user_administration_options_parameters() { 3035 return new external_function_parameters( 3036 array( 3037 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'Course id.')), 3038 ) 3039 ); 3040 } 3041 3042 /** 3043 * Return a list of administration options in a set of courses that are available or not for the current user. 3044 * 3045 * @param array $courseids a list of course ids 3046 * @return array of warnings and the options availability 3047 * @since Moodle 3.2 3048 * @throws moodle_exception 3049 */ 3050 public static function get_user_administration_options($courseids) { 3051 global $CFG; 3052 require_once($CFG->dirroot . '/course/lib.php'); 3053 3054 // Parameter validation. 3055 $params = self::validate_parameters(self::get_user_administration_options_parameters(), array('courseids' => $courseids)); 3056 $courseoptions = array(); 3057 3058 list($courses, $warnings) = external_util::validate_courses($params['courseids'], array(), true); 3059 3060 if (!empty($courses)) { 3061 foreach ($courses as $course) { 3062 $adminoptions = course_get_user_administration_options($course, $course->context); 3063 $options = array(); 3064 foreach ($adminoptions as $name => $available) { 3065 $options[] = array( 3066 'name' => $name, 3067 'available' => $available, 3068 ); 3069 } 3070 3071 $courseoptions[] = array( 3072 'id' => $course->id, 3073 'options' => $options 3074 ); 3075 } 3076 } 3077 3078 $result = array( 3079 'courses' => $courseoptions, 3080 'warnings' => $warnings 3081 ); 3082 return $result; 3083 } 3084 3085 /** 3086 * Returns description of method result value 3087 * 3088 * @return external_description 3089 * @since Moodle 3.2 3090 */ 3091 public static function get_user_administration_options_returns() { 3092 return self::get_user_navigation_options_returns(); 3093 } 3094 3095 /** 3096 * Returns description of method parameters 3097 * 3098 * @return external_function_parameters 3099 * @since Moodle 3.2 3100 */ 3101 public static function get_courses_by_field_parameters() { 3102 return new external_function_parameters( 3103 array( 3104 'field' => new external_value(PARAM_ALPHA, 'The field to search can be left empty for all courses or: 3105 id: course id 3106 ids: comma separated course ids 3107 shortname: course short name 3108 idnumber: course id number 3109 category: category id the course belongs to 3110 ', VALUE_DEFAULT, ''), 3111 'value' => new external_value(PARAM_RAW, 'The value to match', VALUE_DEFAULT, '') 3112 ) 3113 ); 3114 } 3115 3116 3117 /** 3118 * Get courses matching a specific field (id/s, shortname, idnumber, category) 3119 * 3120 * @param string $field field name to search, or empty for all courses 3121 * @param string $value value to search 3122 * @return array list of courses and warnings 3123 * @throws invalid_parameter_exception 3124 * @since Moodle 3.2 3125 */ 3126 public static function get_courses_by_field($field = '', $value = '') { 3127 global $DB, $CFG; 3128 require_once($CFG->dirroot . '/course/lib.php'); 3129 require_once($CFG->libdir . '/filterlib.php'); 3130 3131 $params = self::validate_parameters(self::get_courses_by_field_parameters(), 3132 array( 3133 'field' => $field, 3134 'value' => $value, 3135 ) 3136 ); 3137 $warnings = array(); 3138 3139 if (empty($params['field'])) { 3140 $courses = $DB->get_records('course', null, 'id ASC'); 3141 } else { 3142 switch ($params['field']) { 3143 case 'id': 3144 case 'category': 3145 $value = clean_param($params['value'], PARAM_INT); 3146 break; 3147 case 'ids': 3148 $value = clean_param($params['value'], PARAM_SEQUENCE); 3149 break; 3150 case 'shortname': 3151 $value = clean_param($params['value'], PARAM_TEXT); 3152 break; 3153 case 'idnumber': 3154 $value = clean_param($params['value'], PARAM_RAW); 3155 break; 3156 default: 3157 throw new invalid_parameter_exception('Invalid field name'); 3158 } 3159 3160 if ($params['field'] === 'ids') { 3161 // Preload categories to avoid loading one at a time. 3162 $courseids = explode(',', $value); 3163 list ($listsql, $listparams) = $DB->get_in_or_equal($courseids); 3164 $categoryids = $DB->get_fieldset_sql(" 3165 SELECT DISTINCT cc.id 3166 FROM {course} c 3167 JOIN {course_categories} cc ON cc.id = c.category 3168 WHERE c.id $listsql", $listparams); 3169 core_course_category::get_many($categoryids); 3170 3171 // Load and validate all courses. This is called because it loads the courses 3172 // more efficiently. 3173 list ($courses, $warnings) = external_util::validate_courses($courseids, [], 3174 false, true); 3175 } else { 3176 $courses = $DB->get_records('course', array($params['field'] => $value), 'id ASC'); 3177 } 3178 } 3179 3180 $coursesdata = array(); 3181 foreach ($courses as $course) { 3182 $context = context_course::instance($course->id); 3183 $canupdatecourse = has_capability('moodle/course:update', $context); 3184 $canviewhiddencourses = has_capability('moodle/course:viewhiddencourses', $context); 3185 3186 // Check if the course is visible in the site for the user. 3187 if (!$course->visible and !$canviewhiddencourses and !$canupdatecourse) { 3188 continue; 3189 } 3190 // Get the public course information, even if we are not enrolled. 3191 $courseinlist = new core_course_list_element($course); 3192 3193 // Now, check if we have access to the course, unless it was already checked. 3194 try { 3195 if (empty($course->contextvalidated)) { 3196 self::validate_context($context); 3197 } 3198 } catch (Exception $e) { 3199 // User can not access the course, check if they can see the public information about the course and return it. 3200 if (core_course_category::can_view_course_info($course)) { 3201 $coursesdata[$course->id] = self::get_course_public_information($courseinlist, $context); 3202 } 3203 continue; 3204 } 3205 $coursesdata[$course->id] = self::get_course_public_information($courseinlist, $context); 3206 // Return information for any user that can access the course. 3207 $coursefields = array('format', 'showgrades', 'newsitems', 'startdate', 'enddate', 'maxbytes', 'showreports', 'visible', 3208 'groupmode', 'groupmodeforce', 'defaultgroupingid', 'enablecompletion', 'completionnotify', 'lang', 'theme', 3209 'marker'); 3210 3211 // Course filters. 3212 $coursesdata[$course->id]['filters'] = filter_get_available_in_context($context); 3213 3214 // Information for managers only. 3215 if ($canupdatecourse) { 3216 $managerfields = array('idnumber', 'legacyfiles', 'calendartype', 'timecreated', 'timemodified', 'requested', 3217 'cacherev'); 3218 $coursefields = array_merge($coursefields, $managerfields); 3219 } 3220 3221 // Populate fields. 3222 foreach ($coursefields as $field) { 3223 $coursesdata[$course->id][$field] = $course->{$field}; 3224 } 3225 3226 // Clean lang and auth fields for external functions (it may content uninstalled themes or language packs). 3227 if (isset($coursesdata[$course->id]['theme'])) { 3228 $coursesdata[$course->id]['theme'] = clean_param($coursesdata[$course->id]['theme'], PARAM_THEME); 3229 } 3230 if (isset($coursesdata[$course->id]['lang'])) { 3231 $coursesdata[$course->id]['lang'] = clean_param($coursesdata[$course->id]['lang'], PARAM_LANG); 3232 } 3233 3234 $courseformatoptions = course_get_format($course)->get_config_for_external(); 3235 foreach ($courseformatoptions as $key => $value) { 3236 $coursesdata[$course->id]['courseformatoptions'][] = array( 3237 'name' => $key, 3238 'value' => $value 3239 ); 3240 } 3241 } 3242 3243 return array( 3244 'courses' => $coursesdata, 3245 'warnings' => $warnings 3246 ); 3247 } 3248 3249 /** 3250 * Returns description of method result value 3251 * 3252 * @return external_description 3253 * @since Moodle 3.2 3254 */ 3255 public static function get_courses_by_field_returns() { 3256 // Course structure, including not only public viewable fields. 3257 return new external_single_structure( 3258 array( 3259 'courses' => new external_multiple_structure(self::get_course_structure(false), 'Course'), 3260 'warnings' => new external_warnings() 3261 ) 3262 ); 3263 } 3264 3265 /** 3266 * Returns description of method parameters 3267 * 3268 * @return external_function_parameters 3269 * @since Moodle 3.2 3270 */ 3271 public static function check_updates_parameters() { 3272 return new external_function_parameters( 3273 array( 3274 'courseid' => new external_value(PARAM_INT, 'Course id to check'), 3275 'tocheck' => new external_multiple_structure( 3276 new external_single_structure( 3277 array( 3278 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level for the file location. 3279 Only module supported right now.'), 3280 'id' => new external_value(PARAM_INT, 'Context instance id'), 3281 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'), 3282 ) 3283 ), 3284 'Instances to check' 3285 ), 3286 'filter' => new external_multiple_structure( 3287 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments, 3288 gradeitems, outcomes'), 3289 'Check only for updates in these areas', VALUE_DEFAULT, array() 3290 ) 3291 ) 3292 ); 3293 } 3294 3295 /** 3296 * Check if there is updates affecting the user for the given course and contexts. 3297 * Right now only modules are supported. 3298 * This WS calls mod_check_updates_since for each module to check if there is any update the user should we aware of. 3299 * 3300 * @param int $courseid the list of modules to check 3301 * @param array $tocheck the list of modules to check 3302 * @param array $filter check only for updates in these areas 3303 * @return array list of updates and warnings 3304 * @throws moodle_exception 3305 * @since Moodle 3.2 3306 */ 3307 public static function check_updates($courseid, $tocheck, $filter = array()) { 3308 global $CFG, $DB; 3309 require_once($CFG->dirroot . "/course/lib.php"); 3310 3311 $params = self::validate_parameters( 3312 self::check_updates_parameters(), 3313 array( 3314 'courseid' => $courseid, 3315 'tocheck' => $tocheck, 3316 'filter' => $filter, 3317 ) 3318 ); 3319 3320 $course = get_course($params['courseid']); 3321 $context = context_course::instance($course->id); 3322 self::validate_context($context); 3323 3324 list($instances, $warnings) = course_check_updates($course, $params['tocheck'], $filter); 3325 3326 $instancesformatted = array(); 3327 foreach ($instances as $instance) { 3328 $updates = array(); 3329 foreach ($instance['updates'] as $name => $data) { 3330 if (empty($data->updated)) { 3331 continue; 3332 } 3333 $updatedata = array( 3334 'name' => $name, 3335 ); 3336 if (!empty($data->timeupdated)) { 3337 $updatedata['timeupdated'] = $data->timeupdated; 3338 } 3339 if (!empty($data->itemids)) { 3340 $updatedata['itemids'] = $data->itemids; 3341 } 3342 $updates[] = $updatedata; 3343 } 3344 if (!empty($updates)) { 3345 $instancesformatted[] = array( 3346 'contextlevel' => $instance['contextlevel'], 3347 'id' => $instance['id'], 3348 'updates' => $updates 3349 ); 3350 } 3351 } 3352 3353 return array( 3354 'instances' => $instancesformatted, 3355 'warnings' => $warnings 3356 ); 3357 } 3358 3359 /** 3360 * Returns description of method result value 3361 * 3362 * @return external_description 3363 * @since Moodle 3.2 3364 */ 3365 public static function check_updates_returns() { 3366 return new external_single_structure( 3367 array( 3368 'instances' => new external_multiple_structure( 3369 new external_single_structure( 3370 array( 3371 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level'), 3372 'id' => new external_value(PARAM_INT, 'Instance id'), 3373 'updates' => new external_multiple_structure( 3374 new external_single_structure( 3375 array( 3376 'name' => new external_value(PARAM_ALPHANUMEXT, 'Name of the area updated.'), 3377 'timeupdated' => new external_value(PARAM_INT, 'Last time was updated', VALUE_OPTIONAL), 3378 'itemids' => new external_multiple_structure( 3379 new external_value(PARAM_INT, 'Instance id'), 3380 'The ids of the items updated', 3381 VALUE_OPTIONAL 3382 ) 3383 ) 3384 ) 3385 ) 3386 ) 3387 ) 3388 ), 3389 'warnings' => new external_warnings() 3390 ) 3391 ); 3392 } 3393 3394 /** 3395 * Returns description of method parameters 3396 * 3397 * @return external_function_parameters 3398 * @since Moodle 3.3 3399 */ 3400 public static function get_updates_since_parameters() { 3401 return new external_function_parameters( 3402 array( 3403 'courseid' => new external_value(PARAM_INT, 'Course id to check'), 3404 'since' => new external_value(PARAM_INT, 'Check updates since this time stamp'), 3405 'filter' => new external_multiple_structure( 3406 new external_value(PARAM_ALPHANUM, 'Area name: configuration, fileareas, completion, ratings, comments, 3407 gradeitems, outcomes'), 3408 'Check only for updates in these areas', VALUE_DEFAULT, array() 3409 ) 3410 ) 3411 ); 3412 } 3413 3414 /** 3415 * Check if there are updates affecting the user for the given course since the given time stamp. 3416 * 3417 * This function is a wrapper of self::check_updates for retrieving all the updates since a given time for all the activities. 3418 * 3419 * @param int $courseid the list of modules to check 3420 * @param int $since check updates since this time stamp 3421 * @param array $filter check only for updates in these areas 3422 * @return array list of updates and warnings 3423 * @throws moodle_exception 3424 * @since Moodle 3.3 3425 */ 3426 public static function get_updates_since($courseid, $since, $filter = array()) { 3427 global $CFG, $DB; 3428 3429 $params = self::validate_parameters( 3430 self::get_updates_since_parameters(), 3431 array( 3432 'courseid' => $courseid, 3433 'since' => $since, 3434 'filter' => $filter, 3435 ) 3436 ); 3437 3438 $course = get_course($params['courseid']); 3439 $modinfo = get_fast_modinfo($course); 3440 $tocheck = array(); 3441 3442 // Retrieve all the visible course modules for the current user. 3443 $cms = $modinfo->get_cms(); 3444 foreach ($cms as $cm) { 3445 if (!$cm->uservisible) { 3446 continue; 3447 } 3448 $tocheck[] = array( 3449 'id' => $cm->id, 3450 'contextlevel' => 'module', 3451 'since' => $params['since'], 3452 ); 3453 } 3454 3455 return self::check_updates($course->id, $tocheck, $params['filter']); 3456 } 3457 3458 /** 3459 * Returns description of method result value 3460 * 3461 * @return external_description 3462 * @since Moodle 3.3 3463 */ 3464 public static function get_updates_since_returns() { 3465 return self::check_updates_returns(); 3466 } 3467 3468 /** 3469 * Parameters for function edit_module() 3470 * 3471 * @since Moodle 3.3 3472 * @return external_function_parameters 3473 */ 3474 public static function edit_module_parameters() { 3475 return new external_function_parameters( 3476 array( 3477 'action' => new external_value(PARAM_ALPHA, 3478 'action: hide, show, stealth, duplicate, delete, moveleft, moveright, group...', VALUE_REQUIRED), 3479 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED), 3480 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null), 3481 )); 3482 } 3483 3484 /** 3485 * Performs one of the edit module actions and return new html for AJAX 3486 * 3487 * Returns html to replace the current module html with, for example: 3488 * - empty string for "delete" action, 3489 * - two modules html for "duplicate" action 3490 * - updated module html for everything else 3491 * 3492 * Throws exception if operation is not permitted/possible 3493 * 3494 * @since Moodle 3.3 3495 * @param string $action 3496 * @param int $id 3497 * @param null|int $sectionreturn 3498 * @return string 3499 */ 3500 public static function edit_module($action, $id, $sectionreturn = null) { 3501 global $PAGE, $DB; 3502 // Validate and normalize parameters. 3503 $params = self::validate_parameters(self::edit_module_parameters(), 3504 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn)); 3505 $action = $params['action']; 3506 $id = $params['id']; 3507 $sectionreturn = $params['sectionreturn']; 3508 3509 // Set of permissions an editing user may have. 3510 $contextarray = [ 3511 'moodle/course:update', 3512 'moodle/course:manageactivities', 3513 'moodle/course:activityvisibility', 3514 'moodle/course:sectionvisibility', 3515 'moodle/course:movesections', 3516 'moodle/course:setcurrentsection', 3517 ]; 3518 $PAGE->set_other_editing_capability($contextarray); 3519 3520 list($course, $cm) = get_course_and_cm_from_cmid($id); 3521 $modcontext = context_module::instance($cm->id); 3522 $coursecontext = context_course::instance($course->id); 3523 self::validate_context($modcontext); 3524 $courserenderer = $PAGE->get_renderer('core', 'course'); 3525 $completioninfo = new completion_info($course); 3526 3527 switch($action) { 3528 case 'hide': 3529 case 'show': 3530 case 'stealth': 3531 require_capability('moodle/course:activityvisibility', $modcontext); 3532 $visible = ($action === 'hide') ? 0 : 1; 3533 $visibleoncoursepage = ($action === 'stealth') ? 0 : 1; 3534 set_coursemodule_visible($id, $visible, $visibleoncoursepage); 3535 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger(); 3536 break; 3537 case 'duplicate': 3538 require_capability('moodle/course:manageactivities', $coursecontext); 3539 require_capability('moodle/backup:backuptargetimport', $coursecontext); 3540 require_capability('moodle/restore:restoretargetimport', $coursecontext); 3541 if (!course_allowed_module($course, $cm->modname)) { 3542 throw new moodle_exception('No permission to create that activity'); 3543 } 3544 if ($newcm = duplicate_module($course, $cm)) { 3545 $cm = get_fast_modinfo($course)->get_cm($id); 3546 $newcm = get_fast_modinfo($course)->get_cm($newcm->id); 3547 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn) . 3548 $courserenderer->course_section_cm_list_item($course, $completioninfo, $newcm, $sectionreturn); 3549 } 3550 break; 3551 case 'groupsseparate': 3552 case 'groupsvisible': 3553 case 'groupsnone': 3554 require_capability('moodle/course:manageactivities', $modcontext); 3555 if ($action === 'groupsseparate') { 3556 $newgroupmode = SEPARATEGROUPS; 3557 } else if ($action === 'groupsvisible') { 3558 $newgroupmode = VISIBLEGROUPS; 3559 } else { 3560 $newgroupmode = NOGROUPS; 3561 } 3562 if (set_coursemodule_groupmode($cm->id, $newgroupmode)) { 3563 \core\event\course_module_updated::create_from_cm($cm, $modcontext)->trigger(); 3564 } 3565 break; 3566 case 'moveleft': 3567 case 'moveright': 3568 require_capability('moodle/course:manageactivities', $modcontext); 3569 $indent = $cm->indent + (($action === 'moveright') ? 1 : -1); 3570 if ($cm->indent >= 0) { 3571 $DB->update_record('course_modules', array('id' => $cm->id, 'indent' => $indent)); 3572 rebuild_course_cache($cm->course); 3573 } 3574 break; 3575 case 'delete': 3576 require_capability('moodle/course:manageactivities', $modcontext); 3577 course_delete_module($cm->id, true); 3578 return ''; 3579 default: 3580 throw new coding_exception('Unrecognised action'); 3581 } 3582 3583 $cm = get_fast_modinfo($course)->get_cm($id); 3584 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn); 3585 } 3586 3587 /** 3588 * Return structure for edit_module() 3589 * 3590 * @since Moodle 3.3 3591 * @return external_description 3592 */ 3593 public static function edit_module_returns() { 3594 return new external_value(PARAM_RAW, 'html to replace the current module with'); 3595 } 3596 3597 /** 3598 * Parameters for function get_module() 3599 * 3600 * @since Moodle 3.3 3601 * @return external_function_parameters 3602 */ 3603 public static function get_module_parameters() { 3604 return new external_function_parameters( 3605 array( 3606 'id' => new external_value(PARAM_INT, 'course module id', VALUE_REQUIRED), 3607 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null), 3608 )); 3609 } 3610 3611 /** 3612 * Returns html for displaying one activity module on course page 3613 * 3614 * @since Moodle 3.3 3615 * @param int $id 3616 * @param null|int $sectionreturn 3617 * @return string 3618 */ 3619 public static function get_module($id, $sectionreturn = null) { 3620 global $PAGE; 3621 // Validate and normalize parameters. 3622 $params = self::validate_parameters(self::get_module_parameters(), 3623 array('id' => $id, 'sectionreturn' => $sectionreturn)); 3624 $id = $params['id']; 3625 $sectionreturn = $params['sectionreturn']; 3626 3627 // Set of permissions an editing user may have. 3628 $contextarray = [ 3629 'moodle/course:update', 3630 'moodle/course:manageactivities', 3631 'moodle/course:activityvisibility', 3632 'moodle/course:sectionvisibility', 3633 'moodle/course:movesections', 3634 'moodle/course:setcurrentsection', 3635 ]; 3636 $PAGE->set_other_editing_capability($contextarray); 3637 3638 // Validate access to the course (note, this is html for the course view page, we don't validate access to the module). 3639 list($course, $cm) = get_course_and_cm_from_cmid($id); 3640 self::validate_context(context_course::instance($course->id)); 3641 3642 $courserenderer = $PAGE->get_renderer('core', 'course'); 3643 $completioninfo = new completion_info($course); 3644 return $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sectionreturn); 3645 } 3646 3647 /** 3648 * Return structure for get_module() 3649 * 3650 * @since Moodle 3.3 3651 * @return external_description 3652 */ 3653 public static function get_module_returns() { 3654 return new external_value(PARAM_RAW, 'html to replace the current module with'); 3655 } 3656 3657 /** 3658 * Parameters for function edit_section() 3659 * 3660 * @since Moodle 3.3 3661 * @return external_function_parameters 3662 */ 3663 public static function edit_section_parameters() { 3664 return new external_function_parameters( 3665 array( 3666 'action' => new external_value(PARAM_ALPHA, 'action: hide, show, stealth, setmarker, removemarker', VALUE_REQUIRED), 3667 'id' => new external_value(PARAM_INT, 'course section id', VALUE_REQUIRED), 3668 'sectionreturn' => new external_value(PARAM_INT, 'section to return to', VALUE_DEFAULT, null), 3669 )); 3670 } 3671 3672 /** 3673 * Performs one of the edit section actions 3674 * 3675 * @since Moodle 3.3 3676 * @param string $action 3677 * @param int $id section id 3678 * @param int $sectionreturn section to return to 3679 * @return string 3680 */ 3681 public static function edit_section($action, $id, $sectionreturn) { 3682 global $DB; 3683 // Validate and normalize parameters. 3684 $params = self::validate_parameters(self::edit_section_parameters(), 3685 array('action' => $action, 'id' => $id, 'sectionreturn' => $sectionreturn)); 3686 $action = $params['action']; 3687 $id = $params['id']; 3688 $sr = $params['sectionreturn']; 3689 3690 $section = $DB->get_record('course_sections', array('id' => $id), '*', MUST_EXIST); 3691 $coursecontext = context_course::instance($section->course); 3692 self::validate_context($coursecontext); 3693 3694 $rv = course_get_format($section->course)->section_action($section, $action, $sectionreturn); 3695 if ($rv) { 3696 return json_encode($rv); 3697 } else { 3698 return null; 3699 } 3700 } 3701 3702 /** 3703 * Return structure for edit_section() 3704 * 3705 * @since Moodle 3.3 3706 * @return external_description 3707 */ 3708 public static function edit_section_returns() { 3709 return new external_value(PARAM_RAW, 'Additional data for javascript (JSON-encoded string)'); 3710 } 3711 3712 /** 3713 * Returns description of method parameters 3714 * 3715 * @return external_function_parameters 3716 */ 3717 public static function get_enrolled_courses_by_timeline_classification_parameters() { 3718 return new external_function_parameters( 3719 array( 3720 'classification' => new external_value(PARAM_ALPHA, 'future, inprogress, or past'), 3721 'limit' => new external_value(PARAM_INT, 'Result set limit', VALUE_DEFAULT, 0), 3722 'offset' => new external_value(PARAM_INT, 'Result set offset', VALUE_DEFAULT, 0), 3723 'sort' => new external_value(PARAM_TEXT, 'Sort string', VALUE_DEFAULT, null), 3724 'customfieldname' => new external_value(PARAM_ALPHANUMEXT, 'Used when classification = customfield', 3725 VALUE_DEFAULT, null), 3726 'customfieldvalue' => new external_value(PARAM_RAW, 'Used when classification = customfield', 3727 VALUE_DEFAULT, null), 3728 ) 3729 ); 3730 } 3731 3732 /** 3733 * Get courses matching the given timeline classification. 3734 * 3735 * NOTE: The offset applies to the unfiltered full set of courses before the classification 3736 * filtering is done. 3737 * E.g. 3738 * If the user is enrolled in 5 courses: 3739 * c1, c2, c3, c4, and c5 3740 * And c4 and c5 are 'future' courses 3741 * 3742 * If a request comes in for future courses with an offset of 1 it will mean that 3743 * c1 is skipped (because the offset applies *before* the classification filtering) 3744 * and c4 and c5 will be return. 3745 * 3746 * @param string $classification past, inprogress, or future 3747 * @param int $limit Result set limit 3748 * @param int $offset Offset the full course set before timeline classification is applied 3749 * @param string $sort SQL sort string for results 3750 * @param string $customfieldname 3751 * @param string $customfieldvalue 3752 * @return array list of courses and warnings 3753 * @throws invalid_parameter_exception 3754 */ 3755 public static function get_enrolled_courses_by_timeline_classification( 3756 string $classification, 3757 int $limit = 0, 3758 int $offset = 0, 3759 string $sort = null, 3760 string $customfieldname = null, 3761 string $customfieldvalue = null 3762 ) { 3763 global $CFG, $PAGE, $USER; 3764 require_once($CFG->dirroot . '/course/lib.php'); 3765 3766 $params = self::validate_parameters(self::get_enrolled_courses_by_timeline_classification_parameters(), 3767 array( 3768 'classification' => $classification, 3769 'limit' => $limit, 3770 'offset' => $offset, 3771 'sort' => $sort, 3772 'customfieldvalue' => $customfieldvalue, 3773 ) 3774 ); 3775 3776 $classification = $params['classification']; 3777 $limit = $params['limit']; 3778 $offset = $params['offset']; 3779 $sort = $params['sort']; 3780 $customfieldvalue = $params['customfieldvalue']; 3781 3782 switch($classification) { 3783 case COURSE_TIMELINE_ALLINCLUDINGHIDDEN: 3784 break; 3785 case COURSE_TIMELINE_ALL: 3786 break; 3787 case COURSE_TIMELINE_PAST: 3788 break; 3789 case COURSE_TIMELINE_INPROGRESS: 3790 break; 3791 case COURSE_TIMELINE_FUTURE: 3792 break; 3793 case COURSE_FAVOURITES: 3794 break; 3795 case COURSE_TIMELINE_HIDDEN: 3796 break; 3797 case COURSE_CUSTOMFIELD: 3798 break; 3799 default: 3800 throw new invalid_parameter_exception('Invalid classification'); 3801 } 3802 3803 self::validate_context(context_user::instance($USER->id)); 3804 3805 $requiredproperties = course_summary_exporter::define_properties(); 3806 $fields = join(',', array_keys($requiredproperties)); 3807 $hiddencourses = get_hidden_courses_on_timeline(); 3808 $courses = []; 3809 3810 // If the timeline requires really all courses, get really all courses. 3811 if ($classification == COURSE_TIMELINE_ALLINCLUDINGHIDDEN) { 3812 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields, COURSE_DB_QUERY_LIMIT); 3813 3814 // Otherwise if the timeline requires the hidden courses then restrict the result to only $hiddencourses. 3815 } else if ($classification == COURSE_TIMELINE_HIDDEN) { 3816 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields, 3817 COURSE_DB_QUERY_LIMIT, $hiddencourses); 3818 3819 // Otherwise get the requested courses and exclude the hidden courses. 3820 } else { 3821 $courses = course_get_enrolled_courses_for_logged_in_user(0, $offset, $sort, $fields, 3822 COURSE_DB_QUERY_LIMIT, [], $hiddencourses); 3823 } 3824 3825 $favouritecourseids = []; 3826 $ufservice = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($USER->id)); 3827 $favourites = $ufservice->find_favourites_by_type('core_course', 'courses'); 3828 3829 if ($favourites) { 3830 $favouritecourseids = array_map( 3831 function($favourite) { 3832 return $favourite->itemid; 3833 }, $favourites); 3834 } 3835 3836 if ($classification == COURSE_FAVOURITES) { 3837 list($filteredcourses, $processedcount) = course_filter_courses_by_favourites( 3838 $courses, 3839 $favouritecourseids, 3840 $limit 3841 ); 3842 } else if ($classification == COURSE_CUSTOMFIELD) { 3843 list($filteredcourses, $processedcount) = course_filter_courses_by_customfield( 3844 $courses, 3845 $customfieldname, 3846 $customfieldvalue, 3847 $limit 3848 ); 3849 } else { 3850 list($filteredcourses, $processedcount) = course_filter_courses_by_timeline_classification( 3851 $courses, 3852 $classification, 3853 $limit 3854 ); 3855 } 3856 3857 $renderer = $PAGE->get_renderer('core'); 3858 $formattedcourses = array_map(function($course) use ($renderer, $favouritecourseids) { 3859 context_helper::preload_from_record($course); 3860 $context = context_course::instance($course->id); 3861 $isfavourite = false; 3862 if (in_array($course->id, $favouritecourseids)) { 3863 $isfavourite = true; 3864 } 3865 $exporter = new course_summary_exporter($course, ['context' => $context, 'isfavourite' => $isfavourite]); 3866 return $exporter->export($renderer); 3867 }, $filteredcourses); 3868 3869 return [ 3870 'courses' => $formattedcourses, 3871 'nextoffset' => $offset + $processedcount 3872 ]; 3873 } 3874 3875 /** 3876 * Returns description of method result value 3877 * 3878 * @return external_description 3879 */ 3880 public static function get_enrolled_courses_by_timeline_classification_returns() { 3881 return new external_single_structure( 3882 array( 3883 'courses' => new external_multiple_structure(course_summary_exporter::get_read_structure(), 'Course'), 3884 'nextoffset' => new external_value(PARAM_INT, 'Offset for the next request') 3885 ) 3886 ); 3887 } 3888 3889 /** 3890 * Returns description of method parameters 3891 * 3892 * @return external_function_parameters 3893 */ 3894 public static function set_favourite_courses_parameters() { 3895 return new external_function_parameters( 3896 array( 3897 'courses' => new external_multiple_structure( 3898 new external_single_structure( 3899 array( 3900 'id' => new external_value(PARAM_INT, 'course ID'), 3901 'favourite' => new external_value(PARAM_BOOL, 'favourite status') 3902 ) 3903 ) 3904 ) 3905 ) 3906 ); 3907 } 3908 3909 /** 3910 * Set the course favourite status for an array of courses. 3911 * 3912 * @param array $courses List with course id's and favourite status. 3913 * @return array Array with an array of favourite courses. 3914 */ 3915 public static function set_favourite_courses( 3916 array $courses 3917 ) { 3918 global $USER; 3919 3920 $params = self::validate_parameters(self::set_favourite_courses_parameters(), 3921 array( 3922 'courses' => $courses 3923 ) 3924 ); 3925 3926 $warnings = []; 3927 3928 $ufservice = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($USER->id)); 3929 3930 foreach ($params['courses'] as $course) { 3931 3932 $warning = []; 3933 3934 $favouriteexists = $ufservice->favourite_exists('core_course', 'courses', $course['id'], 3935 \context_course::instance($course['id'])); 3936 3937 if ($course['favourite']) { 3938 if (!$favouriteexists) { 3939 try { 3940 $ufservice->create_favourite('core_course', 'courses', $course['id'], 3941 \context_course::instance($course['id'])); 3942 } catch (Exception $e) { 3943 $warning['courseid'] = $course['id']; 3944 if ($e instanceof moodle_exception) { 3945 $warning['warningcode'] = $e->errorcode; 3946 } else { 3947 $warning['warningcode'] = $e->getCode(); 3948 } 3949 $warning['message'] = $e->getMessage(); 3950 $warnings[] = $warning; 3951 $warnings[] = $warning; 3952 } 3953 } else { 3954 $warning['courseid'] = $course['id']; 3955 $warning['warningcode'] = 'coursealreadyfavourited'; 3956 $warning['message'] = 'Course already favourited'; 3957 $warnings[] = $warning; 3958 } 3959 } else { 3960 if ($favouriteexists) { 3961 try { 3962 $ufservice->delete_favourite('core_course', 'courses', $course['id'], 3963 \context_course::instance($course['id'])); 3964 } catch (Exception $e) { 3965 $warning['courseid'] = $course['id']; 3966 if ($e instanceof moodle_exception) { 3967 $warning['warningcode'] = $e->errorcode; 3968 } else { 3969 $warning['warningcode'] = $e->getCode(); 3970 } 3971 $warning['message'] = $e->getMessage(); 3972 $warnings[] = $warning; 3973 $warnings[] = $warning; 3974 } 3975 } else { 3976 $warning['courseid'] = $course['id']; 3977 $warning['warningcode'] = 'cannotdeletefavourite'; 3978 $warning['message'] = 'Could not delete favourite status for course'; 3979 $warnings[] = $warning; 3980 } 3981 } 3982 } 3983 3984 return [ 3985 'warnings' => $warnings 3986 ]; 3987 } 3988 3989 /** 3990 * Returns description of method result value 3991 * 3992 * @return external_description 3993 */ 3994 public static function set_favourite_courses_returns() { 3995 return new external_single_structure( 3996 array( 3997 'warnings' => new external_warnings() 3998 ) 3999 ); 4000 } 4001 4002 /** 4003 * Returns description of method parameters 4004 * 4005 * @return external_function_parameters 4006 * @since Moodle 3.6 4007 */ 4008 public static function get_recent_courses_parameters() { 4009 return new external_function_parameters( 4010 array( 4011 'userid' => new external_value(PARAM_INT, 'id of the user, default to current user', VALUE_DEFAULT, 0), 4012 'limit' => new external_value(PARAM_INT, 'result set limit', VALUE_DEFAULT, 0), 4013 'offset' => new external_value(PARAM_INT, 'Result set offset', VALUE_DEFAULT, 0), 4014 'sort' => new external_value(PARAM_TEXT, 'Sort string', VALUE_DEFAULT, null) 4015 ) 4016 ); 4017 } 4018 4019 /** 4020 * Get last accessed courses adding additional course information like images. 4021 * 4022 * @param int $userid User id from which the courses will be obtained 4023 * @param int $limit Restrict result set to this amount 4024 * @param int $offset Skip this number of records from the start of the result set 4025 * @param string|null $sort SQL string for sorting 4026 * @return array List of courses 4027 * @throws invalid_parameter_exception 4028 */ 4029 public static function get_recent_courses(int $userid = 0, int $limit = 0, int $offset = 0, string $sort = null) { 4030 global $USER, $PAGE; 4031 4032 if (empty($userid)) { 4033 $userid = $USER->id; 4034 } 4035 4036 $params = self::validate_parameters(self::get_recent_courses_parameters(), 4037 array( 4038 'userid' => $userid, 4039 'limit' => $limit, 4040 'offset' => $offset, 4041 'sort' => $sort 4042 ) 4043 ); 4044 4045 $userid = $params['userid']; 4046 $limit = $params['limit']; 4047 $offset = $params['offset']; 4048 $sort = $params['sort']; 4049 4050 $usercontext = context_user::instance($userid); 4051 4052 self::validate_context($usercontext); 4053 4054 if ($userid != $USER->id and !has_capability('moodle/user:viewdetails', $usercontext)) { 4055 return array(); 4056 } 4057 4058 $courses = course_get_recent_courses($userid, $limit, $offset, $sort); 4059 4060 $renderer = $PAGE->get_renderer('core'); 4061 4062 $recentcourses = array_map(function($course) use ($renderer) { 4063 context_helper::preload_from_record($course); 4064 $context = context_course::instance($course->id); 4065 $isfavourite = !empty($course->component); 4066 $exporter = new course_summary_exporter($course, ['context' => $context, 'isfavourite' => $isfavourite]); 4067 return $exporter->export($renderer); 4068 }, $courses); 4069 4070 return $recentcourses; 4071 } 4072 4073 /** 4074 * Returns description of method result value 4075 * 4076 * @return external_description 4077 * @since Moodle 3.6 4078 */ 4079 public static function get_recent_courses_returns() { 4080 return new external_multiple_structure(course_summary_exporter::get_read_structure(), 'Courses'); 4081 } 4082 4083 /** 4084 * Returns description of method parameters 4085 * 4086 * @return external_function_parameters 4087 */ 4088 public static function get_enrolled_users_by_cmid_parameters() { 4089 return new external_function_parameters([ 4090 'cmid' => new external_value(PARAM_INT, 'id of the course module', VALUE_REQUIRED), 4091 'groupid' => new external_value(PARAM_INT, 'id of the group', VALUE_DEFAULT, 0), 4092 ]); 4093 } 4094 4095 /** 4096 * Get all users in a course for a given cmid. 4097 * 4098 * @param int $cmid Course Module id from which the users will be obtained 4099 * @param int $groupid Group id from which the users will be obtained 4100 * @return array List of users 4101 * @throws invalid_parameter_exception 4102 */ 4103 public static function get_enrolled_users_by_cmid(int $cmid, int $groupid = 0) { 4104 global $PAGE; 4105 $warnings = []; 4106 4107 [ 4108 'cmid' => $cmid, 4109 'groupid' => $groupid, 4110 ] = self::validate_parameters(self::get_enrolled_users_by_cmid_parameters(), [ 4111 'cmid' => $cmid, 4112 'groupid' => $groupid, 4113 ]); 4114 4115 list($course, $cm) = get_course_and_cm_from_cmid($cmid); 4116 $coursecontext = context_course::instance($course->id); 4117 self::validate_context($coursecontext); 4118 4119 $enrolledusers = get_enrolled_users($coursecontext, '', $groupid); 4120 4121 $users = array_map(function ($user) use ($PAGE) { 4122 $user->fullname = fullname($user); 4123 $userpicture = new user_picture($user); 4124 $userpicture->size = 1; 4125 $user->profileimage = $userpicture->get_url($PAGE)->out(false); 4126 return $user; 4127 }, $enrolledusers); 4128 sort($users); 4129 4130 return [ 4131 'users' => $users, 4132 'warnings' => $warnings, 4133 ]; 4134 } 4135 4136 /** 4137 * Returns description of method result value 4138 * 4139 * @return external_description 4140 */ 4141 public static function get_enrolled_users_by_cmid_returns() { 4142 return new external_single_structure([ 4143 'users' => new external_multiple_structure(self::user_description()), 4144 'warnings' => new external_warnings(), 4145 ]); 4146 } 4147 4148 /** 4149 * Create user return value description. 4150 * 4151 * @return external_description 4152 */ 4153 public static function user_description() { 4154 $userfields = array( 4155 'id' => new external_value(core_user::get_property_type('id'), 'ID of the user'), 4156 'profileimage' => new external_value(PARAM_URL, 'The location of the users larger image', VALUE_OPTIONAL), 4157 'fullname' => new external_value(PARAM_TEXT, 'The full name of the user', VALUE_OPTIONAL), 4158 'firstname' => new external_value( 4159 core_user::get_property_type('firstname'), 4160 'The first name(s) of the user', 4161 VALUE_OPTIONAL), 4162 'lastname' => new external_value( 4163 core_user::get_property_type('lastname'), 4164 'The family name of the user', 4165 VALUE_OPTIONAL), 4166 ); 4167 return new external_single_structure($userfields); 4168 } 4169 4170 /** 4171 * Returns description of method parameters. 4172 * 4173 * @return external_function_parameters 4174 */ 4175 public static function add_content_item_to_user_favourites_parameters() { 4176 return new external_function_parameters([ 4177 'componentname' => new external_value(PARAM_TEXT, 4178 'frankenstyle name of the component to which the content item belongs', VALUE_REQUIRED), 4179 'contentitemid' => new external_value(PARAM_INT, 'id of the content item', VALUE_REQUIRED, '', NULL_NOT_ALLOWED) 4180 ]); 4181 } 4182 4183 /** 4184 * Add a content item to a user's favourites. 4185 * 4186 * @param string $componentname the name of the component from which this content item originates. 4187 * @param int $contentitemid the id of the content item. 4188 * @return stdClass the exporter content item. 4189 */ 4190 public static function add_content_item_to_user_favourites(string $componentname, int $contentitemid) { 4191 global $USER; 4192 4193 [ 4194 'componentname' => $componentname, 4195 'contentitemid' => $contentitemid, 4196 ] = self::validate_parameters(self::add_content_item_to_user_favourites_parameters(), 4197 [ 4198 'componentname' => $componentname, 4199 'contentitemid' => $contentitemid, 4200 ] 4201 ); 4202 4203 self::validate_context(context_user::instance($USER->id)); 4204 4205 $contentitemservice = \core_course\local\factory\content_item_service_factory::get_content_item_service(); 4206 4207 return $contentitemservice->add_to_user_favourites($USER, $componentname, $contentitemid); 4208 } 4209 4210 /** 4211 * Returns description of method result value. 4212 * 4213 * @return external_description 4214 */ 4215 public static function add_content_item_to_user_favourites_returns() { 4216 return \core_course\local\exporters\course_content_item_exporter::get_read_structure(); 4217 } 4218 4219 /** 4220 * Returns description of method parameters. 4221 * 4222 * @return external_function_parameters 4223 */ 4224 public static function remove_content_item_from_user_favourites_parameters() { 4225 return new external_function_parameters([ 4226 'componentname' => new external_value(PARAM_TEXT, 4227 'frankenstyle name of the component to which the content item belongs', VALUE_REQUIRED), 4228 'contentitemid' => new external_value(PARAM_INT, 'id of the content item', VALUE_REQUIRED, '', NULL_NOT_ALLOWED), 4229 ]); 4230 } 4231 4232 /** 4233 * Remove a content item from a user's favourites. 4234 * 4235 * @param string $componentname the name of the component from which this content item originates. 4236 * @param int $contentitemid the id of the content item. 4237 * @return stdClass the exported content item. 4238 */ 4239 public static function remove_content_item_from_user_favourites(string $componentname, int $contentitemid) { 4240 global $USER; 4241 4242 [ 4243 'componentname' => $componentname, 4244 'contentitemid' => $contentitemid, 4245 ] = self::validate_parameters(self::remove_content_item_from_user_favourites_parameters(), 4246 [ 4247 'componentname' => $componentname, 4248 'contentitemid' => $contentitemid, 4249 ] 4250 ); 4251 4252 self::validate_context(context_user::instance($USER->id)); 4253 4254 $contentitemservice = \core_course\local\factory\content_item_service_factory::get_content_item_service(); 4255 4256 return $contentitemservice->remove_from_user_favourites($USER, $componentname, $contentitemid); 4257 } 4258 4259 /** 4260 * Returns description of method result value. 4261 * 4262 * @return external_description 4263 */ 4264 public static function remove_content_item_from_user_favourites_returns() { 4265 return \core_course\local\exporters\course_content_item_exporter::get_read_structure(); 4266 } 4267 4268 /** 4269 * Returns description of method result value 4270 * 4271 * @return external_description 4272 */ 4273 public static function get_course_content_items_returns() { 4274 return new external_single_structure([ 4275 'content_items' => new external_multiple_structure( 4276 \core_course\local\exporters\course_content_item_exporter::get_read_structure() 4277 ), 4278 ]); 4279 } 4280 4281 /** 4282 * Returns description of method parameters 4283 * 4284 * @return external_function_parameters 4285 */ 4286 public static function get_course_content_items_parameters() { 4287 return new external_function_parameters([ 4288 'courseid' => new external_value(PARAM_INT, 'ID of the course', VALUE_REQUIRED), 4289 ]); 4290 } 4291 4292 /** 4293 * Given a course ID fetch all accessible modules for that course 4294 * 4295 * @param int $courseid The course we want to fetch the modules for 4296 * @return array Contains array of modules and their metadata 4297 */ 4298 public static function get_course_content_items(int $courseid) { 4299 global $USER; 4300 4301 [ 4302 'courseid' => $courseid, 4303 ] = self::validate_parameters(self::get_course_content_items_parameters(), [ 4304 'courseid' => $courseid, 4305 ]); 4306 4307 $coursecontext = context_course::instance($courseid); 4308 self::validate_context($coursecontext); 4309 $course = get_course($courseid); 4310 4311 $contentitemservice = \core_course\local\factory\content_item_service_factory::get_content_item_service(); 4312 4313 $contentitems = $contentitemservice->get_content_items_for_user_in_course($USER, $course); 4314 return ['content_items' => $contentitems]; 4315 } 4316 4317 /** 4318 * Returns description of method parameters. 4319 * 4320 * @return external_function_parameters 4321 */ 4322 public static function toggle_activity_recommendation_parameters() { 4323 return new external_function_parameters([ 4324 'area' => new external_value(PARAM_TEXT, 'The favourite area (itemtype)', VALUE_REQUIRED), 4325 'id' => new external_value(PARAM_INT, 'id of the activity or whatever', VALUE_REQUIRED), 4326 ]); 4327 } 4328 4329 /** 4330 * Update the recommendation for an activity item. 4331 * 4332 * @param string $area identifier for this activity. 4333 * @param int $id Associated id. This is needed in conjunction with the area to find the recommendation. 4334 * @return array some warnings or something. 4335 */ 4336 public static function toggle_activity_recommendation(string $area, int $id): array { 4337 ['area' => $area, 'id' => $id] = self::validate_parameters(self::toggle_activity_recommendation_parameters(), 4338 ['area' => $area, 'id' => $id]); 4339 4340 $context = context_system::instance(); 4341 self::validate_context($context); 4342 4343 require_capability('moodle/course:recommendactivity', $context); 4344 4345 $manager = \core_course\local\factory\content_item_service_factory::get_content_item_service(); 4346 4347 $status = $manager->toggle_recommendation($area, $id); 4348 return ['id' => $id, 'area' => $area, 'status' => $status]; 4349 } 4350 4351 /** 4352 * Returns warnings. 4353 * 4354 * @return external_description 4355 */ 4356 public static function toggle_activity_recommendation_returns() { 4357 return new external_single_structure( 4358 [ 4359 'id' => new external_value(PARAM_INT, 'id of the activity or whatever'), 4360 'area' => new external_value(PARAM_TEXT, 'The favourite area (itemtype)'), 4361 'status' => new external_value(PARAM_BOOL, 'If created or deleted'), 4362 ] 4363 ); 4364 } 4365 4366 /** 4367 * Returns description of method parameters 4368 * 4369 * @return external_function_parameters 4370 */ 4371 public static function get_activity_chooser_footer_parameters() { 4372 return new external_function_parameters([ 4373 'courseid' => new external_value(PARAM_INT, 'ID of the course', VALUE_REQUIRED), 4374 'sectionid' => new external_value(PARAM_INT, 'ID of the section', VALUE_REQUIRED), 4375 ]); 4376 } 4377 4378 /** 4379 * Given a course ID we need to build up a footre for the chooser. 4380 * 4381 * @param int $courseid The course we want to fetch the modules for 4382 * @param int $sectionid The section we want to fetch the modules for 4383 * @return array 4384 */ 4385 public static function get_activity_chooser_footer(int $courseid, int $sectionid) { 4386 [ 4387 'courseid' => $courseid, 4388 'sectionid' => $sectionid, 4389 ] = self::validate_parameters(self::get_activity_chooser_footer_parameters(), [ 4390 'courseid' => $courseid, 4391 'sectionid' => $sectionid, 4392 ]); 4393 4394 $coursecontext = context_course::instance($courseid); 4395 self::validate_context($coursecontext); 4396 4397 $activeplugin = get_config('core', 'activitychooseractivefooter'); 4398 4399 if ($activeplugin !== COURSE_CHOOSER_FOOTER_NONE) { 4400 $footerdata = component_callback($activeplugin, 'custom_chooser_footer', [$courseid, $sectionid]); 4401 return [ 4402 'footer' => true, 4403 'customfooterjs' => $footerdata->get_footer_js_file(), 4404 'customfootertemplate' => $footerdata->get_footer_template(), 4405 'customcarouseltemplate' => $footerdata->get_carousel_template(), 4406 ]; 4407 } else { 4408 return [ 4409 'footer' => false, 4410 ]; 4411 } 4412 } 4413 4414 /** 4415 * Returns description of method result value 4416 * 4417 * @return external_description 4418 */ 4419 public static function get_activity_chooser_footer_returns() { 4420 return new external_single_structure( 4421 [ 4422 'footer' => new external_value(PARAM_BOOL, 'Is a footer being return by this request?', VALUE_REQUIRED), 4423 'customfooterjs' => new external_value(PARAM_RAW, 'The path to the plugin JS file', VALUE_OPTIONAL), 4424 'customfootertemplate' => new external_value(PARAM_RAW, 'The prerendered footer', VALUE_OPTIONAL), 4425 'customcarouseltemplate' => new external_value(PARAM_RAW, 'Either "" or the prerendered carousel page', 4426 VALUE_OPTIONAL), 4427 ] 4428 ); 4429 } 4430 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body