Differences Between: [Versions 400 and 401] [Versions 400 and 402] [Versions 400 and 403]
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 * Contains the base definition class for any course format plugin. 19 * 20 * @package core_courseformat 21 * @copyright 2020 Ferran Recio <ferran@moodle.com> 22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 23 */ 24 25 namespace core_courseformat; 26 27 use navigation_node; 28 use moodle_page; 29 use core_component; 30 use course_modinfo; 31 use html_writer; 32 use section_info; 33 use context_course; 34 use editsection_form; 35 use moodle_exception; 36 use coding_exception; 37 use moodle_url; 38 use lang_string; 39 use completion_info; 40 use external_api; 41 use stdClass; 42 use cache; 43 use core_courseformat\output\legacy_renderer; 44 45 /** 46 * Base class for course formats 47 * 48 * Each course format must declare class 49 * class format_FORMATNAME extends core_courseformat\base {} 50 * in file lib.php 51 * 52 * For each course just one instance of this class is created and it will always be returned by 53 * course_get_format($courseorid). Format may store it's specific course-dependent options in 54 * variables of this class. 55 * 56 * In rare cases instance of child class may be created just for format without course id 57 * i.e. to check if format supports AJAX. 58 * 59 * Also course formats may extend class section_info and overwrite 60 * course_format::build_section_cache() to return more information about sections. 61 * 62 * If you are upgrading from Moodle 2.3 start with copying the class format_legacy and renaming 63 * it to format_FORMATNAME, then move the code from your callback functions into 64 * appropriate functions of the class. 65 * 66 * @package core_courseformat 67 * @copyright 2012 Marina Glancy 68 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 69 */ 70 abstract class base { 71 /** @var int Id of the course in this instance (maybe 0) */ 72 protected $courseid; 73 /** @var string format used for this course. Please note that it can be different from 74 * course.format field if course referes to non-existing of disabled format */ 75 protected $format; 76 /** @var stdClass course data for course object, please use course_format::get_course() */ 77 protected $course = false; 78 /** @var array caches format options, please use course_format::get_format_options() */ 79 protected $formatoptions = array(); 80 /** @var int the section number in single section format, zero for multiple section formats. */ 81 protected $singlesection = 0; 82 /** @var course_modinfo the current course modinfo, please use course_format::get_modinfo() */ 83 private $modinfo = null; 84 /** @var array cached instances */ 85 private static $instances = array(); 86 /** @var array plugin name => class name. */ 87 private static $classesforformat = array('site' => 'site'); 88 89 /** 90 * Creates a new instance of class 91 * 92 * Please use course_get_format($courseorid) to get an instance of the format class 93 * 94 * @param string $format 95 * @param int $courseid 96 * @return course_format 97 */ 98 protected function __construct($format, $courseid) { 99 $this->format = $format; 100 $this->courseid = $courseid; 101 } 102 103 /** 104 * Validates that course format exists and enabled and returns either itself or default format 105 * 106 * @param string $format 107 * @return string 108 */ 109 protected static final function get_format_or_default($format) { 110 global $CFG; 111 require_once($CFG->dirroot . '/course/lib.php'); 112 113 if (array_key_exists($format, self::$classesforformat)) { 114 return self::$classesforformat[$format]; 115 } 116 117 $plugins = get_sorted_course_formats(); 118 foreach ($plugins as $plugin) { 119 self::$classesforformat[$plugin] = $plugin; 120 } 121 122 if (array_key_exists($format, self::$classesforformat)) { 123 return self::$classesforformat[$format]; 124 } 125 126 if (PHPUNIT_TEST && class_exists('format_' . $format)) { 127 // Allow unittests to use non-existing course formats. 128 return $format; 129 } 130 131 // Else return default format. 132 $defaultformat = get_config('moodlecourse', 'format'); 133 if (!in_array($defaultformat, $plugins)) { 134 // When default format is not set correctly, use the first available format. 135 $defaultformat = reset($plugins); 136 } 137 debugging('Format plugin format_'.$format.' is not found. Using default format_'.$defaultformat, DEBUG_DEVELOPER); 138 139 self::$classesforformat[$format] = $defaultformat; 140 return $defaultformat; 141 } 142 143 /** 144 * Get class name for the format. 145 * 146 * If course format xxx does not declare class format_xxx, format_legacy will be returned. 147 * This function also includes lib.php file from corresponding format plugin 148 * 149 * @param string $format 150 * @return string 151 */ 152 protected static final function get_class_name($format) { 153 global $CFG; 154 static $classnames = array('site' => 'format_site'); 155 if (!isset($classnames[$format])) { 156 $plugins = core_component::get_plugin_list('format'); 157 $usedformat = self::get_format_or_default($format); 158 if (isset($plugins[$usedformat]) && file_exists($plugins[$usedformat].'/lib.php')) { 159 require_once($plugins[$usedformat].'/lib.php'); 160 } 161 $classnames[$format] = 'format_'. $usedformat; 162 if (!class_exists($classnames[$format])) { 163 require_once($CFG->dirroot.'/course/format/formatlegacy.php'); 164 $classnames[$format] = 'format_legacy'; 165 } 166 } 167 return $classnames[$format]; 168 } 169 170 /** 171 * Returns an instance of the class 172 * 173 * @todo MDL-35727 use MUC for caching of instances, limit the number of cached instances 174 * 175 * @param int|stdClass $courseorid either course id or 176 * an object that has the property 'format' and may contain property 'id' 177 * @return course_format 178 */ 179 public static final function instance($courseorid) { 180 global $DB; 181 if (!is_object($courseorid)) { 182 $courseid = (int)$courseorid; 183 if ($courseid && isset(self::$instances[$courseid]) && count(self::$instances[$courseid]) == 1) { 184 $formats = array_keys(self::$instances[$courseid]); 185 $format = reset($formats); 186 } else { 187 $format = $DB->get_field('course', 'format', array('id' => $courseid), MUST_EXIST); 188 } 189 } else { 190 $format = $courseorid->format; 191 if (isset($courseorid->id)) { 192 $courseid = clean_param($courseorid->id, PARAM_INT); 193 } else { 194 $courseid = 0; 195 } 196 } 197 // Validate that format exists and enabled, use default otherwise. 198 $format = self::get_format_or_default($format); 199 if (!isset(self::$instances[$courseid][$format])) { 200 $classname = self::get_class_name($format); 201 self::$instances[$courseid][$format] = new $classname($format, $courseid); 202 } 203 return self::$instances[$courseid][$format]; 204 } 205 206 /** 207 * Resets cache for the course (or all caches) 208 * 209 * To be called from rebuild_course_cache() 210 * 211 * @param int $courseid 212 */ 213 public static final function reset_course_cache($courseid = 0) { 214 if ($courseid) { 215 if (isset(self::$instances[$courseid])) { 216 foreach (self::$instances[$courseid] as $format => $object) { 217 // In case somebody keeps the reference to course format object. 218 self::$instances[$courseid][$format]->course = false; 219 self::$instances[$courseid][$format]->formatoptions = array(); 220 self::$instances[$courseid][$format]->modinfo = null; 221 } 222 unset(self::$instances[$courseid]); 223 } 224 } else { 225 self::$instances = array(); 226 } 227 } 228 /** 229 * Reset the current user for all courses. 230 * 231 * The course format cache resets every time the course cache resets but 232 * also when the user changes their language, all course editors 233 * 234 * @return void 235 */ 236 public static function session_cache_reset_all(): void { 237 $statecache = cache::make('core', 'courseeditorstate'); 238 $statecache->purge(); 239 } 240 241 /** 242 * Reset the current user course format cache. 243 * 244 * The course format cache resets every time the course cache resets but 245 * also when the user changes their course format preference, complete 246 * an activity... 247 * 248 * @param stdClass $course the course object 249 * @return string the new statekey 250 */ 251 public static function session_cache_reset(stdClass $course): string { 252 $statecache = cache::make('core', 'courseeditorstate'); 253 $newkey = $course->cacherev . '_' . time(); 254 $statecache->set($course->id, $newkey); 255 return $newkey; 256 } 257 258 /** 259 * Return the current user course format cache key. 260 * 261 * The course format session cache can be used to cache the 262 * user course representation. The statekey will be reset when the 263 * the course state changes. For example when the course is edited, 264 * the user completes an activity or simply some course preference 265 * like collapsing a section happens. 266 * 267 * @param stdClass $course the course object 268 * @return string the current statekey 269 */ 270 public static function session_cache(stdClass $course): string { 271 $statecache = cache::make('core', 'courseeditorstate'); 272 $statekey = $statecache->get($course->id); 273 // Validate the statekey code. 274 if (preg_match('/^[0-9]+_[0-9]+$/', $statekey)) { 275 list($cacherev) = explode('_', $statekey); 276 if ($cacherev == $course->cacherev) { 277 return $statekey; 278 } 279 } 280 return self::session_cache_reset($course); 281 } 282 283 /** 284 * Returns the format name used by this course 285 * 286 * @return string 287 */ 288 public final function get_format() { 289 return $this->format; 290 } 291 292 /** 293 * Returns id of the course (0 if course is not specified) 294 * 295 * @return int 296 */ 297 public final function get_courseid() { 298 return $this->courseid; 299 } 300 301 /** 302 * Returns a record from course database table plus additional fields 303 * that course format defines 304 * 305 * @return stdClass 306 */ 307 public function get_course() { 308 global $DB; 309 if (!$this->courseid) { 310 return null; 311 } 312 if ($this->course === false) { 313 $this->course = get_course($this->courseid); 314 $options = $this->get_format_options(); 315 $dbcoursecolumns = null; 316 foreach ($options as $optionname => $optionvalue) { 317 if (isset($this->course->$optionname)) { 318 // Course format options must not have the same names as existing columns in db table "course". 319 if (!isset($dbcoursecolumns)) { 320 $dbcoursecolumns = $DB->get_columns('course'); 321 } 322 if (isset($dbcoursecolumns[$optionname])) { 323 debugging('The option name '.$optionname.' in course format '.$this->format. 324 ' is invalid because the field with the same name exists in {course} table', 325 DEBUG_DEVELOPER); 326 continue; 327 } 328 } 329 $this->course->$optionname = $optionvalue; 330 } 331 } 332 return $this->course; 333 } 334 335 /** 336 * Get the course display value for the current course. 337 * 338 * Formats extending topics or weeks will use coursedisplay as this setting name 339 * so they don't need to override the method. However, if the format uses a different 340 * display logic it must override this method to ensure the core renderers know 341 * if a COURSE_DISPLAY_MULTIPAGE or COURSE_DISPLAY_SINGLEPAGE is being used. 342 * 343 * @return int The current value (COURSE_DISPLAY_MULTIPAGE or COURSE_DISPLAY_SINGLEPAGE) 344 */ 345 public function get_course_display(): int { 346 return $this->get_course()->coursedisplay ?? COURSE_DISPLAY_SINGLEPAGE; 347 } 348 349 /** 350 * Return the current course modinfo. 351 * 352 * This method is used mainly by the output components to avoid unnecesary get_fast_modinfo calls. 353 * 354 * @return course_modinfo 355 */ 356 public function get_modinfo(): course_modinfo { 357 global $USER; 358 if ($this->modinfo === null) { 359 $this->modinfo = course_modinfo::instance($this->courseid, $USER->id); 360 } 361 return $this->modinfo; 362 } 363 364 /** 365 * Method used in the rendered and during backup instead of legacy 'numsections' 366 * 367 * Default renderer will treat sections with sectionnumber greater that the value returned by this 368 * method as "orphaned" and not display them on the course page unless in editing mode. 369 * Backup will store this value as 'numsections'. 370 * 371 * This method ensures that 3rd party course format plugins that still use 'numsections' continue to 372 * work but at the same time we no longer expect formats to have 'numsections' property. 373 * 374 * @return int 375 */ 376 public function get_last_section_number() { 377 $course = $this->get_course(); 378 if (isset($course->numsections)) { 379 return $course->numsections; 380 } 381 $modinfo = get_fast_modinfo($course); 382 $sections = $modinfo->get_section_info_all(); 383 return (int)max(array_keys($sections)); 384 } 385 386 /** 387 * Method used to get the maximum number of sections for this course format. 388 * @return int 389 */ 390 public function get_max_sections() { 391 $maxsections = get_config('moodlecourse', 'maxsections'); 392 if (!isset($maxsections) || !is_numeric($maxsections)) { 393 $maxsections = 52; 394 } 395 return $maxsections; 396 } 397 398 /** 399 * Returns true if the course has a front page. 400 * 401 * This function is called to determine if the course has a view page, whether or not 402 * it contains a listing of activities. It can be useful to set this to false when the course 403 * format has only one activity and ignores the course page. Or if there are multiple 404 * activities but no page to see the centralised information. 405 * 406 * Initially this was created to know if forms should add a button to return to the course page. 407 * So if 'Return to course' does not make sense in your format your should probably return false. 408 * 409 * @return boolean 410 * @since Moodle 2.6 411 */ 412 public function has_view_page() { 413 return true; 414 } 415 416 /** 417 * Generate the title for this section page. 418 * 419 * @return string the page title 420 */ 421 public function page_title(): string { 422 global $PAGE; 423 return $PAGE->title; 424 } 425 426 /** 427 * Returns true if this course format uses sections 428 * 429 * This function may be called without specifying the course id 430 * i.e. in course_format_uses_sections() 431 * 432 * Developers, note that if course format does use sections there should be defined a language 433 * string with the name 'sectionname' defining what the section relates to in the format, i.e. 434 * $string['sectionname'] = 'Topic'; 435 * or 436 * $string['sectionname'] = 'Week'; 437 * 438 * @return bool 439 */ 440 public function uses_sections() { 441 return false; 442 } 443 444 /** 445 * Returns true if this course format uses course index 446 * 447 * This function may be called without specifying the course id 448 * i.e. in course_index_drawer() 449 * 450 * @return bool 451 */ 452 public function uses_course_index() { 453 return false; 454 } 455 456 /** 457 * Returns true if this course format uses activity indentation. 458 * 459 * @return bool if the course format uses indentation. 460 */ 461 public function uses_indentation(): bool { 462 return true; 463 } 464 465 /** 466 * Returns a list of sections used in the course 467 * 468 * This is a shortcut to get_fast_modinfo()->get_section_info_all() 469 * @see get_fast_modinfo() 470 * @see course_modinfo::get_section_info_all() 471 * 472 * @return array of section_info objects 473 */ 474 public final function get_sections() { 475 if ($course = $this->get_course()) { 476 $modinfo = get_fast_modinfo($course); 477 return $modinfo->get_section_info_all(); 478 } 479 return array(); 480 } 481 482 /** 483 * Returns information about section used in course 484 * 485 * @param int|stdClass $section either section number (field course_section.section) or row from course_section table 486 * @param int $strictness 487 * @return section_info 488 */ 489 public final function get_section($section, $strictness = IGNORE_MISSING) { 490 if (is_object($section)) { 491 $sectionnum = $section->section; 492 } else { 493 $sectionnum = $section; 494 } 495 $sections = $this->get_sections(); 496 if (array_key_exists($sectionnum, $sections)) { 497 return $sections[$sectionnum]; 498 } 499 if ($strictness == MUST_EXIST) { 500 throw new moodle_exception('sectionnotexist'); 501 } 502 return null; 503 } 504 505 /** 506 * Returns the display name of the given section that the course prefers. 507 * 508 * @param int|stdClass $section Section object from database or just field course_sections.section 509 * @return Display name that the course format prefers, e.g. "Topic 2" 510 */ 511 public function get_section_name($section) { 512 if (is_object($section)) { 513 $sectionnum = $section->section; 514 } else { 515 $sectionnum = $section; 516 } 517 518 if (get_string_manager()->string_exists('sectionname', 'format_' . $this->format)) { 519 return get_string('sectionname', 'format_' . $this->format) . ' ' . $sectionnum; 520 } 521 522 // Return an empty string if there's no available section name string for the given format. 523 return ''; 524 } 525 526 /** 527 * Returns the default section using course_format's implementation of get_section_name. 528 * 529 * @param int|stdClass $section Section object from database or just field course_sections section 530 * @return string The default value for the section name based on the given course format. 531 */ 532 public function get_default_section_name($section) { 533 return self::get_section_name($section); 534 } 535 536 /** 537 * Returns the name for the highlighted section. 538 * 539 * @return string The name for the highlighted section based on the given course format. 540 */ 541 public function get_section_highlighted_name(): string { 542 return get_string('highlighted'); 543 } 544 545 /** 546 * Set if the current format instance will show multiple sections or an individual one. 547 * 548 * Some formats has the hability to swith from one section to multiple sections per page, 549 * this method replaces the old print_multiple_section_page and print_single_section_page. 550 * 551 * @param int $singlesection zero for all sections or a section number 552 */ 553 public function set_section_number(int $singlesection): void { 554 $this->singlesection = $singlesection; 555 } 556 557 /** 558 * Set if the current format instance will show multiple sections or an individual one. 559 * 560 * Some formats has the hability to swith from one section to multiple sections per page, 561 * output components will use this method to know if the current display is a single or 562 * multiple sections. 563 * 564 * @return int zero for all sections or the sectin number 565 */ 566 public function get_section_number(): int { 567 return $this->singlesection; 568 } 569 570 /** 571 * Return the format section preferences. 572 * 573 * @return array of preferences indexed by sectionid 574 */ 575 public function get_sections_preferences(): array { 576 global $USER; 577 578 $result = []; 579 580 $course = $this->get_course(); 581 $coursesectionscache = cache::make('core', 'coursesectionspreferences'); 582 583 $coursesections = $coursesectionscache->get($course->id); 584 if ($coursesections) { 585 return $coursesections; 586 } 587 588 $sectionpreferences = $this->get_sections_preferences_by_preference(); 589 590 foreach ($sectionpreferences as $preference => $sectionids) { 591 if (!empty($sectionids) && is_array($sectionids)) { 592 foreach ($sectionids as $sectionid) { 593 if (!isset($result[$sectionid])) { 594 $result[$sectionid] = new stdClass(); 595 } 596 $result[$sectionid]->$preference = true; 597 } 598 } 599 } 600 601 $coursesectionscache->set($course->id, $result); 602 return $result; 603 } 604 605 /** 606 * Return the format section preferences. 607 * 608 * @return array of preferences indexed by preference name 609 */ 610 public function get_sections_preferences_by_preference(): array { 611 global $USER; 612 $course = $this->get_course(); 613 try { 614 $sectionpreferences = (array) json_decode( 615 get_user_preferences('coursesectionspreferences_' . $course->id, null, $USER->id) 616 ); 617 if (empty($sectionpreferences)) { 618 $sectionpreferences = []; 619 } 620 } catch (\Throwable $e) { 621 $sectionpreferences = []; 622 } 623 return $sectionpreferences; 624 } 625 626 /** 627 * Return the format section preferences. 628 * 629 * @param string $preferencename preference name 630 * @param int[] $sectionids affected section ids 631 * 632 */ 633 public function set_sections_preference(string $preferencename, array $sectionids) { 634 global $USER; 635 $course = $this->get_course(); 636 $sectionpreferences = $this->get_sections_preferences_by_preference(); 637 $sectionpreferences[$preferencename] = $sectionids; 638 set_user_preference('coursesectionspreferences_' . $course->id, json_encode($sectionpreferences), $USER->id); 639 // Invalidate section preferences cache. 640 $coursesectionscache = cache::make('core', 'coursesectionspreferences'); 641 $coursesectionscache->delete($course->id); 642 } 643 644 /** 645 * Returns the information about the ajax support in the given source format 646 * 647 * The returned object's property (boolean)capable indicates that 648 * the course format supports Moodle course ajax features. 649 * 650 * @return stdClass 651 */ 652 public function supports_ajax() { 653 // No support by default. 654 $ajaxsupport = new stdClass(); 655 $ajaxsupport->capable = false; 656 return $ajaxsupport; 657 } 658 659 /** 660 * Returns true if this course format is compatible with content components. 661 * 662 * Using components means the content elements can watch the frontend course state and 663 * react to the changes. Formats with component compatibility can have more interactions 664 * without refreshing the page, like having drag and drop from the course index to reorder 665 * sections and activities. 666 * 667 * @return bool if the format is compatible with components. 668 */ 669 public function supports_components() { 670 return false; 671 } 672 673 674 /** 675 * Custom action after section has been moved in AJAX mode 676 * 677 * Used in course/rest.php 678 * 679 * @return array This will be passed in ajax respose 680 */ 681 public function ajax_section_move() { 682 return null; 683 } 684 685 /** 686 * The URL to use for the specified course (with section) 687 * 688 * Please note that course view page /course/view.php?id=COURSEID is hardcoded in many 689 * places in core and contributed modules. If course format wants to change the location 690 * of the view script, it is not enough to change just this function. Do not forget 691 * to add proper redirection. 692 * 693 * @param int|stdClass $section Section object from database or just field course_sections.section 694 * if null the course view page is returned 695 * @param array $options options for view URL. At the moment core uses: 696 * 'navigation' (bool) if true and section has no separate page, the function returns null 697 * 'sr' (int) used by multipage formats to specify to which section to return 698 * @return null|moodle_url 699 */ 700 public function get_view_url($section, $options = array()) { 701 global $CFG; 702 $course = $this->get_course(); 703 $url = new moodle_url('/course/view.php', array('id' => $course->id)); 704 705 if (array_key_exists('sr', $options)) { 706 $sectionno = $options['sr']; 707 } else if (is_object($section)) { 708 $sectionno = $section->section; 709 } else { 710 $sectionno = $section; 711 } 712 if (empty($CFG->linkcoursesections) && !empty($options['navigation']) && $sectionno !== null) { 713 // By default assume that sections are never displayed on separate pages. 714 return null; 715 } 716 if ($this->uses_sections() && $sectionno !== null) { 717 $url->set_anchor('section-'.$sectionno); 718 } 719 return $url; 720 } 721 722 /** 723 * Loads all of the course sections into the navigation 724 * 725 * This method is called from global_navigation::load_course_sections() 726 * 727 * By default the method global_navigation::load_generic_course_sections() is called 728 * 729 * When overwriting please note that navigationlib relies on using the correct values for 730 * arguments $type and $key in navigation_node::add() 731 * 732 * Example of code creating a section node: 733 * $sectionnode = $node->add($sectionname, $url, navigation_node::TYPE_SECTION, null, $section->id); 734 * $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH; 735 * 736 * Example of code creating an activity node: 737 * $activitynode = $sectionnode->add($activityname, $action, navigation_node::TYPE_ACTIVITY, null, $activity->id, $icon); 738 * if (global_navigation::module_extends_navigation($activity->modname)) { 739 * $activitynode->nodetype = navigation_node::NODETYPE_BRANCH; 740 * } else { 741 * $activitynode->nodetype = navigation_node::NODETYPE_LEAF; 742 * } 743 * 744 * Also note that if $navigation->includesectionnum is not null, the section with this relative 745 * number needs is expected to be loaded 746 * 747 * @param global_navigation $navigation 748 * @param navigation_node $node The course node within the navigation 749 */ 750 public function extend_course_navigation($navigation, navigation_node $node) { 751 if ($course = $this->get_course()) { 752 $navigation->load_generic_course_sections($course, $node); 753 } 754 return array(); 755 } 756 757 /** 758 * Returns the list of blocks to be automatically added for the newly created course 759 * 760 * @see blocks_add_default_course_blocks() 761 * 762 * @return array of default blocks, must contain two keys BLOCK_POS_LEFT and BLOCK_POS_RIGHT 763 * each of values is an array of block names (for left and right side columns) 764 */ 765 public function get_default_blocks() { 766 global $CFG; 767 if (isset($CFG->defaultblocks)) { 768 return blocks_parse_default_blocks_list($CFG->defaultblocks); 769 } 770 $blocknames = array( 771 BLOCK_POS_LEFT => array(), 772 BLOCK_POS_RIGHT => array() 773 ); 774 return $blocknames; 775 } 776 777 /** 778 * Returns the localised name of this course format plugin 779 * 780 * @return lang_string 781 */ 782 public final function get_format_name() { 783 return new lang_string('pluginname', 'format_'.$this->get_format()); 784 } 785 786 /** 787 * Definitions of the additional options that this course format uses for course 788 * 789 * This function may be called often, it should be as fast as possible. 790 * Avoid using get_string() method, use "new lang_string()" instead 791 * It is not recommended to use dynamic or course-dependant expressions here 792 * This function may be also called when course does not exist yet. 793 * 794 * Option names must be different from fields in the {course} talbe or any form elements on 795 * course edit form, it may even make sence to use special prefix for them. 796 * 797 * Each option must have the option name as a key and the array of properties as a value: 798 * 'default' - default value for this option (assumed null if not specified) 799 * 'type' - type of the option value (PARAM_INT, PARAM_RAW, etc.) 800 * 801 * Additional properties used by default implementation of 802 * course_format::create_edit_form_elements() (calls this method with $foreditform = true) 803 * 'label' - localised human-readable label for the edit form 804 * 'element_type' - type of the form element, default 'text' 805 * 'element_attributes' - additional attributes for the form element, these are 4th and further 806 * arguments in the moodleform::addElement() method 807 * 'help' - string for help button. Note that if 'help' value is 'myoption' then the string with 808 * the name 'myoption_help' must exist in the language file 809 * 'help_component' - language component to look for help string, by default this the component 810 * for this course format 811 * 812 * This is an interface for creating simple form elements. If format plugin wants to use other 813 * methods such as disableIf, it can be done by overriding create_edit_form_elements(). 814 * 815 * Course format options can be accessed as: 816 * $this->get_course()->OPTIONNAME (inside the format class) 817 * course_get_format($course)->get_course()->OPTIONNAME (outside of format class) 818 * 819 * All course options are returned by calling: 820 * $this->get_format_options(); 821 * 822 * @param bool $foreditform 823 * @return array of options 824 */ 825 public function course_format_options($foreditform = false) { 826 return array(); 827 } 828 829 /** 830 * Definitions of the additional options that this course format uses for section 831 * 832 * See course_format::course_format_options() for return array definition. 833 * 834 * Additionally section format options may have property 'cache' set to true 835 * if this option needs to be cached in get_fast_modinfo(). The 'cache' property 836 * is recommended to be set only for fields used in course_format::get_section_name(), 837 * course_format::extend_course_navigation() and course_format::get_view_url() 838 * 839 * For better performance cached options are recommended to have 'cachedefault' property 840 * Unlike 'default', 'cachedefault' should be static and not access get_config(). 841 * 842 * Regardless of value of 'cache' all options are accessed in the code as 843 * $sectioninfo->OPTIONNAME 844 * where $sectioninfo is instance of section_info, returned by 845 * get_fast_modinfo($course)->get_section_info($sectionnum) 846 * or get_fast_modinfo($course)->get_section_info_all() 847 * 848 * All format options for particular section are returned by calling: 849 * $this->get_format_options($section); 850 * 851 * @param bool $foreditform 852 * @return array 853 */ 854 public function section_format_options($foreditform = false) { 855 return array(); 856 } 857 858 /** 859 * Returns the format options stored for this course or course section 860 * 861 * When overriding please note that this function is called from rebuild_course_cache() 862 * and section_info object, therefore using of get_fast_modinfo() and/or any function that 863 * accesses it may lead to recursion. 864 * 865 * @param null|int|stdClass|section_info $section if null the course format options will be returned 866 * otherwise options for specified section will be returned. This can be either 867 * section object or relative section number (field course_sections.section) 868 * @return array 869 */ 870 public function get_format_options($section = null) { 871 global $DB; 872 if ($section === null) { 873 $options = $this->course_format_options(); 874 } else { 875 $options = $this->section_format_options(); 876 } 877 if (empty($options)) { 878 // There are no option for course/sections anyway, no need to go further. 879 return array(); 880 } 881 if ($section === null) { 882 // Course format options will be returned. 883 $sectionid = 0; 884 } else if ($this->courseid && isset($section->id)) { 885 // Course section format options will be returned. 886 $sectionid = $section->id; 887 } else if ($this->courseid && is_int($section) && 888 ($sectionobj = $DB->get_record('course_sections', 889 array('section' => $section, 'course' => $this->courseid), 'id'))) { 890 // Course section format options will be returned. 891 $sectionid = $sectionobj->id; 892 } else { 893 // Non-existing (yet) section was passed as an argument 894 // default format options for course section will be returned. 895 $sectionid = -1; 896 } 897 if (!array_key_exists($sectionid, $this->formatoptions)) { 898 $this->formatoptions[$sectionid] = array(); 899 // First fill with default values. 900 foreach ($options as $optionname => $optionparams) { 901 $this->formatoptions[$sectionid][$optionname] = null; 902 if (array_key_exists('default', $optionparams)) { 903 $this->formatoptions[$sectionid][$optionname] = $optionparams['default']; 904 } 905 } 906 if ($this->courseid && $sectionid !== -1) { 907 // Overwrite the default options values with those stored in course_format_options table 908 // nothing can be stored if we are interested in generic course ($this->courseid == 0) 909 // or generic section ($sectionid === 0). 910 $records = $DB->get_records('course_format_options', 911 array('courseid' => $this->courseid, 912 'format' => $this->format, 913 'sectionid' => $sectionid 914 ), '', 'id,name,value'); 915 $indexedrecords = []; 916 foreach ($records as $record) { 917 $indexedrecords[$record->name] = $record->value; 918 } 919 foreach ($options as $optionname => $option) { 920 contract_value($this->formatoptions[$sectionid], $indexedrecords, $option, $optionname); 921 } 922 } 923 } 924 return $this->formatoptions[$sectionid]; 925 } 926 927 /** 928 * Adds format options elements to the course/section edit form 929 * 930 * This function is called from course_edit_form::definition_after_data() 931 * 932 * @param MoodleQuickForm $mform form the elements are added to 933 * @param bool $forsection 'true' if this is a section edit form, 'false' if this is course edit form 934 * @return array array of references to the added form elements 935 */ 936 public function create_edit_form_elements(&$mform, $forsection = false) { 937 $elements = array(); 938 if ($forsection) { 939 $options = $this->section_format_options(true); 940 } else { 941 $options = $this->course_format_options(true); 942 } 943 foreach ($options as $optionname => $option) { 944 if (!isset($option['element_type'])) { 945 $option['element_type'] = 'text'; 946 } 947 $args = array($option['element_type'], $optionname, $option['label']); 948 if (!empty($option['element_attributes'])) { 949 $args = array_merge($args, $option['element_attributes']); 950 } 951 $elements[] = call_user_func_array(array($mform, 'addElement'), $args); 952 if (isset($option['help'])) { 953 $helpcomponent = 'format_'. $this->get_format(); 954 if (isset($option['help_component'])) { 955 $helpcomponent = $option['help_component']; 956 } 957 $mform->addHelpButton($optionname, $option['help'], $helpcomponent); 958 } 959 if (isset($option['type'])) { 960 $mform->setType($optionname, $option['type']); 961 } 962 if (isset($option['default']) && !array_key_exists($optionname, $mform->_defaultValues)) { 963 // Set defaults for the elements in the form. 964 // Since we call this method after set_data() make sure that we don't override what was already set. 965 $mform->setDefault($optionname, $option['default']); 966 } 967 } 968 969 if (!$forsection && empty($this->courseid)) { 970 // Check if course end date form field should be enabled by default. 971 // If a default date is provided to the form element, it is magically enabled by default in the 972 // MoodleQuickForm_date_time_selector class, otherwise it's disabled by default. 973 if (get_config('moodlecourse', 'courseenddateenabled')) { 974 // At this stage (this is called from definition_after_data) course data is already set as default. 975 // We can not overwrite what is in the database. 976 $mform->setDefault('enddate', $this->get_default_course_enddate($mform)); 977 } 978 } 979 980 return $elements; 981 } 982 983 /** 984 * Override if you need to perform some extra validation of the format options 985 * 986 * @param array $data array of ("fieldname"=>value) of submitted data 987 * @param array $files array of uploaded files "element_name"=>tmp_file_path 988 * @param array $errors errors already discovered in edit form validation 989 * @return array of "element_name"=>"error_description" if there are errors, 990 * or an empty array if everything is OK. 991 * Do not repeat errors from $errors param here 992 */ 993 public function edit_form_validation($data, $files, $errors) { 994 return array(); 995 } 996 997 /** 998 * Prepares values of course or section format options before storing them in DB 999 * 1000 * If an option has invalid value it is not returned 1001 * 1002 * @param array $rawdata associative array of the proposed course/section format options 1003 * @param int|null $sectionid null if it is course format option 1004 * @return array array of options that have valid values 1005 */ 1006 protected function validate_format_options(array $rawdata, int $sectionid = null) : array { 1007 if (!$sectionid) { 1008 $allformatoptions = $this->course_format_options(true); 1009 } else { 1010 $allformatoptions = $this->section_format_options(true); 1011 } 1012 $data = array_intersect_key($rawdata, $allformatoptions); 1013 foreach ($data as $key => $value) { 1014 $option = $allformatoptions[$key] + ['type' => PARAM_RAW, 'element_type' => null, 'element_attributes' => [[]]]; 1015 expand_value($data, $data, $option, $key); 1016 if ($option['element_type'] === 'select' && !array_key_exists($data[$key], $option['element_attributes'][0])) { 1017 // Value invalid for select element, skip. 1018 unset($data[$key]); 1019 } 1020 } 1021 return $data; 1022 } 1023 1024 /** 1025 * Validates format options for the course 1026 * 1027 * @param array $data data to insert/update 1028 * @return array array of options that have valid values 1029 */ 1030 public function validate_course_format_options(array $data) : array { 1031 return $this->validate_format_options($data); 1032 } 1033 1034 /** 1035 * Updates format options for a course or section 1036 * 1037 * If $data does not contain property with the option name, the option will not be updated 1038 * 1039 * @param stdClass|array $data return value from moodleform::get_data() or array with data 1040 * @param null|int $sectionid null if these are options for course or section id (course_sections.id) 1041 * if these are options for section 1042 * @return bool whether there were any changes to the options values 1043 */ 1044 protected function update_format_options($data, $sectionid = null) { 1045 global $DB; 1046 $data = $this->validate_format_options((array)$data, $sectionid); 1047 if (!$sectionid) { 1048 $allformatoptions = $this->course_format_options(); 1049 $sectionid = 0; 1050 } else { 1051 $allformatoptions = $this->section_format_options(); 1052 } 1053 if (empty($allformatoptions)) { 1054 // Nothing to update anyway. 1055 return false; 1056 } 1057 $defaultoptions = array(); 1058 $cached = array(); 1059 foreach ($allformatoptions as $key => $option) { 1060 $defaultoptions[$key] = null; 1061 if (array_key_exists('default', $option)) { 1062 $defaultoptions[$key] = $option['default']; 1063 } 1064 expand_value($defaultoptions, $defaultoptions, $option, $key); 1065 $cached[$key] = ($sectionid === 0 || !empty($option['cache'])); 1066 } 1067 $records = $DB->get_records('course_format_options', 1068 array('courseid' => $this->courseid, 1069 'format' => $this->format, 1070 'sectionid' => $sectionid 1071 ), '', 'name,id,value'); 1072 $changed = $needrebuild = false; 1073 foreach ($defaultoptions as $key => $value) { 1074 if (isset($records[$key])) { 1075 if (array_key_exists($key, $data) && $records[$key]->value !== $data[$key]) { 1076 $DB->set_field('course_format_options', 'value', 1077 $data[$key], array('id' => $records[$key]->id)); 1078 $changed = true; 1079 $needrebuild = $needrebuild || $cached[$key]; 1080 } 1081 } else { 1082 if (array_key_exists($key, $data) && $data[$key] !== $value) { 1083 $newvalue = $data[$key]; 1084 $changed = true; 1085 $needrebuild = $needrebuild || $cached[$key]; 1086 } else { 1087 $newvalue = $value; 1088 // We still insert entry in DB but there are no changes from user point of 1089 // view and no need to call rebuild_course_cache(). 1090 } 1091 $DB->insert_record('course_format_options', array( 1092 'courseid' => $this->courseid, 1093 'format' => $this->format, 1094 'sectionid' => $sectionid, 1095 'name' => $key, 1096 'value' => $newvalue 1097 )); 1098 } 1099 } 1100 if ($needrebuild) { 1101 if ($sectionid) { 1102 // Invalidate the section cache by given section id. 1103 course_modinfo::purge_course_section_cache_by_id($this->courseid, $sectionid); 1104 // Partial rebuild sections that have been invalidated. 1105 rebuild_course_cache($this->courseid, true, true); 1106 } else { 1107 // Full rebuild if sectionid is null. 1108 rebuild_course_cache($this->courseid); 1109 } 1110 } 1111 if ($changed) { 1112 // Reset internal caches. 1113 if (!$sectionid) { 1114 $this->course = false; 1115 } 1116 unset($this->formatoptions[$sectionid]); 1117 } 1118 return $changed; 1119 } 1120 1121 /** 1122 * Updates format options for a course 1123 * 1124 * If $data does not contain property with the option name, the option will not be updated 1125 * 1126 * @param stdClass|array $data return value from moodleform::get_data() or array with data 1127 * @param stdClass $oldcourse if this function is called from update_course() 1128 * this object contains information about the course before update 1129 * @return bool whether there were any changes to the options values 1130 */ 1131 public function update_course_format_options($data, $oldcourse = null) { 1132 return $this->update_format_options($data); 1133 } 1134 1135 /** 1136 * Updates format options for a section 1137 * 1138 * Section id is expected in $data->id (or $data['id']) 1139 * If $data does not contain property with the option name, the option will not be updated 1140 * 1141 * @param stdClass|array $data return value from moodleform::get_data() or array with data 1142 * @return bool whether there were any changes to the options values 1143 */ 1144 public function update_section_format_options($data) { 1145 $data = (array)$data; 1146 return $this->update_format_options($data, $data['id']); 1147 } 1148 1149 /** 1150 * Return an instance of moodleform to edit a specified section 1151 * 1152 * Default implementation returns instance of editsection_form that automatically adds 1153 * additional fields defined in course_format::section_format_options() 1154 * 1155 * Format plugins may extend editsection_form if they want to have custom edit section form. 1156 * 1157 * @param mixed $action the action attribute for the form. If empty defaults to auto detect the 1158 * current url. If a moodle_url object then outputs params as hidden variables. 1159 * @param array $customdata the array with custom data to be passed to the form 1160 * /course/editsection.php passes section_info object in 'cs' field 1161 * for filling availability fields 1162 * @return moodleform 1163 */ 1164 public function editsection_form($action, $customdata = array()) { 1165 global $CFG; 1166 require_once($CFG->dirroot. '/course/editsection_form.php'); 1167 if (!array_key_exists('course', $customdata)) { 1168 $customdata['course'] = $this->get_course(); 1169 } 1170 return new editsection_form($action, $customdata); 1171 } 1172 1173 /** 1174 * Allows course format to execute code on moodle_page::set_course() 1175 * 1176 * @param moodle_page $page instance of page calling set_course 1177 */ 1178 public function page_set_course(moodle_page $page) { 1179 } 1180 1181 /** 1182 * Allows course format to execute code on moodle_page::set_cm() 1183 * 1184 * Current module can be accessed as $page->cm (returns instance of cm_info) 1185 * 1186 * @param moodle_page $page instance of page calling set_cm 1187 */ 1188 public function page_set_cm(moodle_page $page) { 1189 } 1190 1191 /** 1192 * Course-specific information to be output on any course page (usually above navigation bar) 1193 * 1194 * Example of usage: 1195 * define 1196 * class format_FORMATNAME_XXX implements renderable {} 1197 * 1198 * create format renderer in course/format/FORMATNAME/renderer.php, define rendering function: 1199 * class format_FORMATNAME_renderer extends plugin_renderer_base { 1200 * protected function render_format_FORMATNAME_XXX(format_FORMATNAME_XXX $xxx) { 1201 * return html_writer::tag('div', 'This is my header/footer'); 1202 * } 1203 * } 1204 * 1205 * Return instance of format_FORMATNAME_XXX in this function, the appropriate method from 1206 * plugin renderer will be called 1207 * 1208 * @return null|renderable null for no output or object with data for plugin renderer 1209 */ 1210 public function course_header() { 1211 return null; 1212 } 1213 1214 /** 1215 * Course-specific information to be output on any course page (usually in the beginning of 1216 * standard footer) 1217 * 1218 * See course_format::course_header() for usage 1219 * 1220 * @return null|renderable null for no output or object with data for plugin renderer 1221 */ 1222 public function course_footer() { 1223 return null; 1224 } 1225 1226 /** 1227 * Course-specific information to be output immediately above content on any course page 1228 * 1229 * See course_format::course_header() for usage 1230 * 1231 * @return null|renderable null for no output or object with data for plugin renderer 1232 */ 1233 public function course_content_header() { 1234 return null; 1235 } 1236 1237 /** 1238 * Course-specific information to be output immediately below content on any course page 1239 * 1240 * See course_format::course_header() for usage 1241 * 1242 * @return null|renderable null for no output or object with data for plugin renderer 1243 */ 1244 public function course_content_footer() { 1245 return null; 1246 } 1247 1248 /** 1249 * Returns instance of page renderer used by this plugin 1250 * 1251 * @param moodle_page $page 1252 * @return renderer_base 1253 */ 1254 public function get_renderer(moodle_page $page) { 1255 try { 1256 $renderer = $page->get_renderer('format_'. $this->get_format()); 1257 } catch (moodle_exception $e) { 1258 $formatname = $this->get_format(); 1259 $expectedrenderername = 'format_'. $this->get_format() . '\output\renderer'; 1260 debugging( 1261 "The '{$formatname}' course format does not define the {$expectedrenderername} renderer class. This is required since Moodle 4.0.", 1262 DEBUG_DEVELOPER 1263 ); 1264 $renderer = new legacy_renderer($page, null); 1265 } 1266 1267 return $renderer; 1268 } 1269 1270 /** 1271 * Returns instance of output component used by this plugin 1272 * 1273 * @throws coding_exception if the format class does not extends the original core one. 1274 * @param string $outputname the element to render (section, activity...) 1275 * @return string the output component classname 1276 */ 1277 public function get_output_classname(string $outputname): string { 1278 // The core output class. 1279 $baseclass = "core_courseformat\\output\\local\\$outputname"; 1280 1281 // Look in this format and any parent formats before we get to the base one. 1282 $classes = array_merge([get_class($this)], class_parents($this)); 1283 foreach ($classes as $component) { 1284 if ($component === self::class) { 1285 break; 1286 } 1287 1288 // Because course formats are in the root namespace, there is no need to process the 1289 // class name - it is already a Frankenstyle component name beginning 'format_'. 1290 1291 // Check if there is a specific class in this format. 1292 $outputclass = "$component\\output\\courseformat\\$outputname"; 1293 if (class_exists($outputclass)) { 1294 // Check that the outputclass is a subclass of the base class. 1295 if (!is_subclass_of($outputclass, $baseclass)) { 1296 throw new coding_exception("The \"$outputclass\" must extend \"$baseclass\""); 1297 } 1298 return $outputclass; 1299 } 1300 } 1301 1302 return $baseclass; 1303 } 1304 1305 /** 1306 * Returns true if the specified section is current 1307 * 1308 * By default we analyze $course->marker 1309 * 1310 * @param int|stdClass|section_info $section 1311 * @return bool 1312 */ 1313 public function is_section_current($section) { 1314 if (is_object($section)) { 1315 $sectionnum = $section->section; 1316 } else { 1317 $sectionnum = $section; 1318 } 1319 return ($sectionnum && ($course = $this->get_course()) && $course->marker == $sectionnum); 1320 } 1321 1322 /** 1323 * Returns if an specific section is visible to the current user. 1324 * 1325 * Formats can overrride this method to implement any special section logic. 1326 * 1327 * @param section_info $section the section modinfo 1328 * @return bool; 1329 */ 1330 public function is_section_visible(section_info $section): bool { 1331 // Previous to Moodle 4.0 thas logic was hardcoded. To prevent errors in the contrib plugins 1332 // the default logic is the same required for topics and weeks format and still uses 1333 // a "hiddensections" format setting. 1334 $course = $this->get_course(); 1335 $hidesections = $course->hiddensections ?? true; 1336 // Show the section if the user is permitted to access it, OR if it's not available 1337 // but there is some available info text which explains the reason & should display, 1338 // OR it is hidden but the course has a setting to display hidden sections as unavailable. 1339 return $section->uservisible || 1340 ($section->visible && !$section->available && !empty($section->availableinfo)) || 1341 (!$section->visible && !$hidesections); 1342 } 1343 1344 /** 1345 * return true if the course editor must be displayed. 1346 * 1347 * @param array|null $capabilities array of capabilities a user needs to have to see edit controls in general. 1348 * If null or not specified, the user needs to have 'moodle/course:manageactivities' 1349 * @return bool true if edit controls must be displayed 1350 */ 1351 public function show_editor(?array $capabilities = ['moodle/course:manageactivities']): bool { 1352 global $PAGE; 1353 $course = $this->get_course(); 1354 $coursecontext = context_course::instance($course->id); 1355 if ($capabilities === null) { 1356 $capabilities = ['moodle/course:manageactivities']; 1357 } 1358 return $PAGE->user_is_editing() && has_all_capabilities($capabilities, $coursecontext); 1359 } 1360 1361 /** 1362 * Allows to specify for modinfo that section is not available even when it is visible and conditionally available. 1363 * 1364 * Note: affected user can be retrieved as: $section->modinfo->userid 1365 * 1366 * Course format plugins can override the method to change the properties $available and $availableinfo that were 1367 * calculated by conditional availability. 1368 * To make section unavailable set: 1369 * $available = false; 1370 * To make unavailable section completely hidden set: 1371 * $availableinfo = ''; 1372 * To make unavailable section visible with availability message set: 1373 * $availableinfo = get_string('sectionhidden', 'format_xxx'); 1374 * 1375 * @param section_info $section 1376 * @param bool $available the 'available' propery of the section_info as it was evaluated by conditional availability. 1377 * Can be changed by the method but 'false' can not be overridden by 'true'. 1378 * @param string $availableinfo the 'availableinfo' propery of the section_info as it was evaluated by conditional availability. 1379 * Can be changed by the method 1380 */ 1381 public function section_get_available_hook(section_info $section, &$available, &$availableinfo) { 1382 } 1383 1384 /** 1385 * Whether this format allows to delete sections 1386 * 1387 * If format supports deleting sections it is also recommended to define language string 1388 * 'deletesection' inside the format. 1389 * 1390 * Do not call this function directly, instead use course_can_delete_section() 1391 * 1392 * @param int|stdClass|section_info $section 1393 * @return bool 1394 */ 1395 public function can_delete_section($section) { 1396 return false; 1397 } 1398 1399 /** 1400 * Deletes a section 1401 * 1402 * Do not call this function directly, instead call course_delete_section() 1403 * 1404 * @param int|stdClass|section_info $section 1405 * @param bool $forcedeleteifnotempty if set to false section will not be deleted if it has modules in it. 1406 * @return bool whether section was deleted 1407 */ 1408 public function delete_section($section, $forcedeleteifnotempty = false) { 1409 global $DB; 1410 if (!$this->uses_sections()) { 1411 // Not possible to delete section if sections are not used. 1412 return false; 1413 } 1414 if (!is_object($section)) { 1415 $section = $DB->get_record('course_sections', array('course' => $this->get_courseid(), 'section' => $section), 1416 'id,section,sequence,summary'); 1417 } 1418 if (!$section || !$section->section) { 1419 // Not possible to delete 0-section. 1420 return false; 1421 } 1422 1423 if (!$forcedeleteifnotempty && (!empty($section->sequence) || !empty($section->summary))) { 1424 return false; 1425 } 1426 1427 $course = $this->get_course(); 1428 1429 // Remove the marker if it points to this section. 1430 if ($section->section == $course->marker) { 1431 course_set_marker($course->id, 0); 1432 } 1433 1434 $lastsection = $DB->get_field_sql('SELECT max(section) from {course_sections} 1435 WHERE course = ?', array($course->id)); 1436 1437 // Find out if we need to descrease the 'numsections' property later. 1438 $courseformathasnumsections = array_key_exists('numsections', 1439 $this->get_format_options()); 1440 $decreasenumsections = $courseformathasnumsections && ($section->section <= $course->numsections); 1441 1442 // Move the section to the end. 1443 move_section_to($course, $section->section, $lastsection, true); 1444 1445 // Delete all modules from the section. 1446 foreach (preg_split('/,/', $section->sequence, -1, PREG_SPLIT_NO_EMPTY) as $cmid) { 1447 course_delete_module($cmid); 1448 } 1449 1450 // Delete section and it's format options. 1451 $DB->delete_records('course_format_options', array('sectionid' => $section->id)); 1452 $DB->delete_records('course_sections', array('id' => $section->id)); 1453 // Invalidate the section cache by given section id. 1454 course_modinfo::purge_course_section_cache_by_id($course->id, $section->id); 1455 // Partial rebuild section cache that has been purged. 1456 rebuild_course_cache($course->id, true, true); 1457 1458 // Delete section summary files. 1459 $context = \context_course::instance($course->id); 1460 $fs = get_file_storage(); 1461 $fs->delete_area_files($context->id, 'course', 'section', $section->id); 1462 1463 // Descrease 'numsections' if needed. 1464 if ($decreasenumsections) { 1465 $this->update_course_format_options(array('numsections' => $course->numsections - 1)); 1466 } 1467 1468 return true; 1469 } 1470 1471 /** 1472 * Prepares the templateable object to display section name 1473 * 1474 * @param \section_info|\stdClass $section 1475 * @param bool $linkifneeded 1476 * @param bool $editable 1477 * @param null|lang_string|string $edithint 1478 * @param null|lang_string|string $editlabel 1479 * @return \core\output\inplace_editable 1480 */ 1481 public function inplace_editable_render_section_name($section, $linkifneeded = true, 1482 $editable = null, $edithint = null, $editlabel = null) { 1483 global $USER, $CFG; 1484 require_once($CFG->dirroot.'/course/lib.php'); 1485 1486 if ($editable === null) { 1487 $editable = !empty($USER->editing) && has_capability('moodle/course:update', 1488 context_course::instance($section->course)); 1489 } 1490 1491 $displayvalue = $title = get_section_name($section->course, $section); 1492 if ($linkifneeded) { 1493 // Display link under the section name if the course format setting is to display one section per page. 1494 $url = course_get_url($section->course, $section->section, array('navigation' => true)); 1495 if ($url) { 1496 $displayvalue = html_writer::link($url, $title); 1497 } 1498 $itemtype = 'sectionname'; 1499 } else { 1500 // If $linkifneeded==false, we never display the link (this is used when rendering the section header). 1501 // Itemtype 'sectionnamenl' (nl=no link) will tell the callback that link should not be rendered - 1502 // there is no other way callback can know where we display the section name. 1503 $itemtype = 'sectionnamenl'; 1504 } 1505 if (empty($edithint)) { 1506 $edithint = new lang_string('editsectionname'); 1507 } 1508 if (empty($editlabel)) { 1509 $editlabel = new lang_string('newsectionname', '', $title); 1510 } 1511 1512 return new \core\output\inplace_editable('format_' . $this->format, $itemtype, $section->id, $editable, 1513 $displayvalue, $section->name, $edithint, $editlabel); 1514 } 1515 1516 /** 1517 * Updates the value in the database and modifies this object respectively. 1518 * 1519 * ALWAYS check user permissions before performing an update! Throw exceptions if permissions are not sufficient 1520 * or value is not legit. 1521 * 1522 * @param stdClass $section 1523 * @param string $itemtype 1524 * @param mixed $newvalue 1525 * @return \core\output\inplace_editable 1526 */ 1527 public function inplace_editable_update_section_name($section, $itemtype, $newvalue) { 1528 if ($itemtype === 'sectionname' || $itemtype === 'sectionnamenl') { 1529 $context = context_course::instance($section->course); 1530 external_api::validate_context($context); 1531 require_capability('moodle/course:update', $context); 1532 1533 $newtitle = clean_param($newvalue, PARAM_TEXT); 1534 if (strval($section->name) !== strval($newtitle)) { 1535 course_update_section($section->course, $section, array('name' => $newtitle)); 1536 } 1537 return $this->inplace_editable_render_section_name($section, ($itemtype === 'sectionname'), true); 1538 } 1539 } 1540 1541 1542 /** 1543 * Returns the default end date value based on the start date. 1544 * 1545 * This is the default implementation for course formats, it is based on 1546 * moodlecourse/courseduration setting. Course formats like format_weeks for 1547 * example can overwrite this method and return a value based on their internal options. 1548 * 1549 * @param moodleform $mform 1550 * @param array $fieldnames The form - field names mapping. 1551 * @return int 1552 */ 1553 public function get_default_course_enddate($mform, $fieldnames = array()) { 1554 1555 if (empty($fieldnames)) { 1556 $fieldnames = array('startdate' => 'startdate'); 1557 } 1558 1559 $startdate = $this->get_form_start_date($mform, $fieldnames); 1560 $courseduration = intval(get_config('moodlecourse', 'courseduration')); 1561 if (!$courseduration) { 1562 // Default, it should be already set during upgrade though. 1563 $courseduration = YEARSECS; 1564 } 1565 1566 return $startdate + $courseduration; 1567 } 1568 1569 /** 1570 * Indicates whether the course format supports the creation of the Announcements forum. 1571 * 1572 * For course format plugin developers, please override this to return true if you want the Announcements forum 1573 * to be created upon course creation. 1574 * 1575 * @return bool 1576 */ 1577 public function supports_news() { 1578 // For backwards compatibility, check if default blocks include the news_items block. 1579 $defaultblocks = $this->get_default_blocks(); 1580 foreach ($defaultblocks as $blocks) { 1581 if (in_array('news_items', $blocks)) { 1582 return true; 1583 } 1584 } 1585 // Return false by default. 1586 return false; 1587 } 1588 1589 /** 1590 * Get the start date value from the course settings page form. 1591 * 1592 * @param moodleform $mform 1593 * @param array $fieldnames The form - field names mapping. 1594 * @return int 1595 */ 1596 protected function get_form_start_date($mform, $fieldnames) { 1597 $startdate = $mform->getElementValue($fieldnames['startdate']); 1598 return $mform->getElement($fieldnames['startdate'])->exportValue($startdate); 1599 } 1600 1601 /** 1602 * Returns whether this course format allows the activity to 1603 * have "triple visibility state" - visible always, hidden on course page but available, hidden. 1604 * 1605 * @param stdClass|cm_info $cm course module (may be null if we are displaying a form for adding a module) 1606 * @param stdClass|section_info $section section where this module is located or will be added to 1607 * @return bool 1608 */ 1609 public function allow_stealth_module_visibility($cm, $section) { 1610 return false; 1611 } 1612 1613 /** 1614 * Callback used in WS core_course_edit_section when teacher performs an AJAX action on a section (show/hide) 1615 * 1616 * Access to the course is already validated in the WS but the callback has to make sure 1617 * that particular action is allowed by checking capabilities 1618 * 1619 * Course formats should register 1620 * 1621 * @param stdClass|section_info $section 1622 * @param string $action 1623 * @param int $sr the section return 1624 * @return null|array|stdClass any data for the Javascript post-processor (must be json-encodeable) 1625 */ 1626 public function section_action($section, $action, $sr) { 1627 global $PAGE; 1628 if (!$this->uses_sections() || !$section->section) { 1629 // No section actions are allowed if course format does not support sections. 1630 // No actions are allowed on the 0-section by default (overwrite in course format if needed). 1631 throw new moodle_exception('sectionactionnotsupported', 'core', null, s($action)); 1632 } 1633 1634 $course = $this->get_course(); 1635 $coursecontext = context_course::instance($course->id); 1636 $modinfo = $this->get_modinfo(); 1637 $renderer = $this->get_renderer($PAGE); 1638 1639 if (!($section instanceof section_info)) { 1640 $section = $modinfo->get_section_info($section->section); 1641 } 1642 1643 if ($sr) { 1644 $this->set_section_number($sr); 1645 } 1646 1647 switch($action) { 1648 case 'hide': 1649 case 'show': 1650 require_capability('moodle/course:sectionvisibility', $coursecontext); 1651 $visible = ($action === 'hide') ? 0 : 1; 1652 course_update_section($course, $section, array('visible' => $visible)); 1653 break; 1654 case 'refresh': 1655 return [ 1656 'content' => $renderer->course_section_updated($this, $section), 1657 ]; 1658 default: 1659 throw new moodle_exception('sectionactionnotsupported', 'core', null, s($action)); 1660 } 1661 1662 return ['modules' => $this->get_section_modules_updated($section)]; 1663 } 1664 1665 /** 1666 * Return an array with all section modules content. 1667 * 1668 * This method is used in section_action method to generate the updated modules content 1669 * after a modinfo change. 1670 * 1671 * @param section_info $section the section 1672 * @return string[] the full modules content. 1673 */ 1674 protected function get_section_modules_updated(section_info $section): array { 1675 global $PAGE; 1676 1677 $modules = []; 1678 1679 if (!$this->uses_sections() || !$section->section) { 1680 return $modules; 1681 } 1682 1683 // Load the cmlist output from the updated modinfo. 1684 $renderer = $this->get_renderer($PAGE); 1685 $modinfo = $this->get_modinfo(); 1686 $coursesections = $modinfo->sections; 1687 if (array_key_exists($section->section, $coursesections)) { 1688 foreach ($coursesections[$section->section] as $cmid) { 1689 $cm = $modinfo->get_cm($cmid); 1690 $modules[] = $renderer->course_section_updated_cm_item($this, $section, $cm); 1691 } 1692 } 1693 return $modules; 1694 } 1695 1696 /** 1697 * Return the plugin config settings for external functions, 1698 * in some cases the configs will need formatting or be returned only if the current user has some capabilities enabled. 1699 * 1700 * @return array the list of configs 1701 * @since Moodle 3.5 1702 */ 1703 public function get_config_for_external() { 1704 return array(); 1705 } 1706 1707 /** 1708 * Course deletion hook. 1709 * 1710 * Format plugins can override this method to clean any format specific data and dependencies. 1711 * 1712 */ 1713 public function delete_format_data() { 1714 global $DB; 1715 $course = $this->get_course(); 1716 // By default, formats store some most display specifics in a user preference. 1717 $DB->delete_records('user_preferences', ['name' => 'coursesectionspreferences_' . $course->id]); 1718 } 1719 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body