Merge branch 'MDL-36056-master-enrolkeywhitespace' of git://github.com/mudrd8mz/moodle
[moodle.git] / course / format / lib.php
blob0e1e23eabb1be5746cfa36580d62a45277a6f854
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.
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/>.
17 /**
18 * Base class for course format plugins
20 * @package core_course
21 * @copyright 2012 Marina Glancy
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 defined('MOODLE_INTERNAL') || die;
27 /**
28 * Returns an instance of format class (extending format_base) for given course
30 * @param int|stdClass $courseorid either course id or
31 * an object that has the property 'format' and may contain property 'id'
32 * @return format_base
34 function course_get_format($courseorid) {
35 return format_base::instance($courseorid);
38 /**
39 * Base class for course formats
41 * Each course format must declare class
42 * class format_FORMATNAME extends format_base {}
43 * in file lib.php
45 * For each course just one instance of this class is created and it will always be returned by
46 * course_get_format($courseorid). Format may store it's specific course-dependent options in
47 * variables of this class.
49 * In rare cases instance of child class may be created just for format without course id
50 * i.e. to check if format supports AJAX.
52 * Also course formats may extend class section_info and overwrite
53 * format_base::build_section_cache() to return more information about sections.
55 * If you are upgrading from Moodle 2.3 start with copying the class format_legacy and renaming
56 * it to format_FORMATNAME, then move the code from your callback functions into
57 * appropriate functions of the class.
59 * @package core_course
60 * @copyright 2012 Marina Glancy
61 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
63 abstract class format_base {
64 /** @var int Id of the course in this instance (maybe 0) */
65 protected $courseid;
66 /** @var string format used for this course. Please note that it can be different from
67 * course.format field if course referes to non-existing of disabled format */
68 protected $format;
69 /** @var stdClass data for course object, please use {@link format_base::get_course()} */
70 protected $course = false;
71 /** @var array caches format options, please use {@link format_base::get_format_options()} */
72 protected $formatoptions = array();
73 /** @var array cached instances */
74 private static $instances = array();
75 /** @var array plugin name => class name. */
76 private static $classesforformat = array('site' => 'site');
78 /**
79 * Creates a new instance of class
81 * Please use {@link course_get_format($courseorid)} to get an instance of the format class
83 * @param string $format
84 * @param int $courseid
85 * @return format_base
87 protected function __construct($format, $courseid) {
88 $this->format = $format;
89 $this->courseid = $courseid;
92 /**
93 * Validates that course format exists and enabled and returns either itself or default format
95 * @param string $format
96 * @return string
98 protected static final function get_format_or_default($format) {
99 global $CFG;
100 require_once($CFG->dirroot . '/course/lib.php');
102 if (array_key_exists($format, self::$classesforformat)) {
103 return self::$classesforformat[$format];
106 $plugins = get_sorted_course_formats();
107 foreach ($plugins as $plugin) {
108 self::$classesforformat[$plugin] = $plugin;
111 if (array_key_exists($format, self::$classesforformat)) {
112 return self::$classesforformat[$format];
115 if (PHPUNIT_TEST && class_exists('format_' . $format)) {
116 // Allow unittests to use non-existing course formats.
117 return $format;
120 // Else return default format
121 $defaultformat = get_config('moodlecourse', 'format');
122 if (!in_array($defaultformat, $plugins)) {
123 // when default format is not set correctly, use the first available format
124 $defaultformat = reset($plugins);
126 debugging('Format plugin format_'.$format.' is not found. Using default format_'.$defaultformat, DEBUG_DEVELOPER);
128 self::$classesforformat[$format] = $defaultformat;
129 return $defaultformat;
133 * Get class name for the format
135 * If course format xxx does not declare class format_xxx, format_legacy will be returned.
136 * This function also includes lib.php file from corresponding format plugin
138 * @param string $format
139 * @return string
141 protected static final function get_class_name($format) {
142 global $CFG;
143 static $classnames = array('site' => 'format_site');
144 if (!isset($classnames[$format])) {
145 $plugins = core_component::get_plugin_list('format');
146 $usedformat = self::get_format_or_default($format);
147 if (isset($plugins[$usedformat]) && file_exists($plugins[$usedformat].'/lib.php')) {
148 require_once($plugins[$usedformat].'/lib.php');
150 $classnames[$format] = 'format_'. $usedformat;
151 if (!class_exists($classnames[$format])) {
152 require_once($CFG->dirroot.'/course/format/formatlegacy.php');
153 $classnames[$format] = 'format_legacy';
156 return $classnames[$format];
160 * Returns an instance of the class
162 * @todo MDL-35727 use MUC for caching of instances, limit the number of cached instances
164 * @param int|stdClass $courseorid either course id or
165 * an object that has the property 'format' and may contain property 'id'
166 * @return format_base
168 public static final function instance($courseorid) {
169 global $DB;
170 if (!is_object($courseorid)) {
171 $courseid = (int)$courseorid;
172 if ($courseid && isset(self::$instances[$courseid]) && count(self::$instances[$courseid]) == 1) {
173 $formats = array_keys(self::$instances[$courseid]);
174 $format = reset($formats);
175 } else {
176 $format = $DB->get_field('course', 'format', array('id' => $courseid), MUST_EXIST);
178 } else {
179 $format = $courseorid->format;
180 if (isset($courseorid->id)) {
181 $courseid = clean_param($courseorid->id, PARAM_INT);
182 } else {
183 $courseid = 0;
186 // validate that format exists and enabled, use default otherwise
187 $format = self::get_format_or_default($format);
188 if (!isset(self::$instances[$courseid][$format])) {
189 $classname = self::get_class_name($format);
190 self::$instances[$courseid][$format] = new $classname($format, $courseid);
192 return self::$instances[$courseid][$format];
196 * Resets cache for the course (or all caches)
197 * To be called from {@link rebuild_course_cache()}
199 * @param int $courseid
201 public static final function reset_course_cache($courseid = 0) {
202 if ($courseid) {
203 if (isset(self::$instances[$courseid])) {
204 foreach (self::$instances[$courseid] as $format => $object) {
205 // in case somebody keeps the reference to course format object
206 self::$instances[$courseid][$format]->course = false;
207 self::$instances[$courseid][$format]->formatoptions = array();
209 unset(self::$instances[$courseid]);
211 } else {
212 self::$instances = array();
217 * Returns the format name used by this course
219 * @return string
221 public final function get_format() {
222 return $this->format;
226 * Returns id of the course (0 if course is not specified)
228 * @return int
230 public final function get_courseid() {
231 return $this->courseid;
235 * Returns a record from course database table plus additional fields
236 * that course format defines
238 * @return stdClass
240 public function get_course() {
241 global $DB;
242 if (!$this->courseid) {
243 return null;
245 if ($this->course === false) {
246 $this->course = get_course($this->courseid);
247 $options = $this->get_format_options();
248 $dbcoursecolumns = null;
249 foreach ($options as $optionname => $optionvalue) {
250 if (isset($this->course->$optionname)) {
251 // Course format options must not have the same names as existing columns in db table "course".
252 if (!isset($dbcoursecolumns)) {
253 $dbcoursecolumns = $DB->get_columns('course');
255 if (isset($dbcoursecolumns[$optionname])) {
256 debugging('The option name '.$optionname.' in course format '.$this->format.
257 ' is invalid because the field with the same name exists in {course} table',
258 DEBUG_DEVELOPER);
259 continue;
262 $this->course->$optionname = $optionvalue;
265 return $this->course;
269 * Method used in the rendered and during backup instead of legacy 'numsections'
271 * Default renderer will treat sections with sectionnumber greater that the value returned by this
272 * method as "orphaned" and not display them on the course page unless in editing mode.
273 * Backup will store this value as 'numsections'.
275 * This method ensures that 3rd party course format plugins that still use 'numsections' continue to
276 * work but at the same time we no longer expect formats to have 'numsections' property.
278 * @return int
280 public function get_last_section_number() {
281 $course = $this->get_course();
282 if (isset($course->numsections)) {
283 return $course->numsections;
285 $modinfo = get_fast_modinfo($course);
286 $sections = $modinfo->get_section_info_all();
287 return (int)max(array_keys($sections));
291 * Returns true if the course has a front page.
293 * This function is called to determine if the course has a view page, whether or not
294 * it contains a listing of activities. It can be useful to set this to false when the course
295 * format has only one activity and ignores the course page. Or if there are multiple
296 * activities but no page to see the centralised information.
298 * Initially this was created to know if forms should add a button to return to the course page.
299 * So if 'Return to course' does not make sense in your format your should probably return false.
301 * @return boolean
302 * @since Moodle 2.6
304 public function has_view_page() {
305 return true;
309 * Returns true if this course format uses sections
311 * This function may be called without specifying the course id
312 * i.e. in {@link course_format_uses_sections()}
314 * Developers, note that if course format does use sections there should be defined a language
315 * string with the name 'sectionname' defining what the section relates to in the format, i.e.
316 * $string['sectionname'] = 'Topic';
317 * or
318 * $string['sectionname'] = 'Week';
320 * @return bool
322 public function uses_sections() {
323 return false;
327 * Returns a list of sections used in the course
329 * This is a shortcut to get_fast_modinfo()->get_section_info_all()
330 * @see get_fast_modinfo()
331 * @see course_modinfo::get_section_info_all()
333 * @return array of section_info objects
335 public final function get_sections() {
336 if ($course = $this->get_course()) {
337 $modinfo = get_fast_modinfo($course);
338 return $modinfo->get_section_info_all();
340 return array();
344 * Returns information about section used in course
346 * @param int|stdClass $section either section number (field course_section.section) or row from course_section table
347 * @param int $strictness
348 * @return section_info
350 public final function get_section($section, $strictness = IGNORE_MISSING) {
351 if (is_object($section)) {
352 $sectionnum = $section->section;
353 } else {
354 $sectionnum = $section;
356 $sections = $this->get_sections();
357 if (array_key_exists($sectionnum, $sections)) {
358 return $sections[$sectionnum];
360 if ($strictness == MUST_EXIST) {
361 throw new moodle_exception('sectionnotexist');
363 return null;
367 * Returns the display name of the given section that the course prefers.
369 * @param int|stdClass $section Section object from database or just field course_sections.section
370 * @return Display name that the course format prefers, e.g. "Topic 2"
372 public function get_section_name($section) {
373 if (is_object($section)) {
374 $sectionnum = $section->section;
375 } else {
376 $sectionnum = $section;
379 if (get_string_manager()->string_exists('sectionname', 'format_' . $this->format)) {
380 return get_string('sectionname', 'format_' . $this->format) . ' ' . $sectionnum;
383 // Return an empty string if there's no available section name string for the given format.
384 return '';
388 * Returns the default section using format_base's implementation of get_section_name.
390 * @param int|stdClass $section Section object from database or just field course_sections section
391 * @return string The default value for the section name based on the given course format.
393 public function get_default_section_name($section) {
394 return self::get_section_name($section);
398 * Returns the information about the ajax support in the given source format
400 * The returned object's property (boolean)capable indicates that
401 * the course format supports Moodle course ajax features.
403 * @return stdClass
405 public function supports_ajax() {
406 // no support by default
407 $ajaxsupport = new stdClass();
408 $ajaxsupport->capable = false;
409 return $ajaxsupport;
413 * Custom action after section has been moved in AJAX mode
415 * Used in course/rest.php
417 * @return array This will be passed in ajax respose
419 public function ajax_section_move() {
420 return null;
424 * The URL to use for the specified course (with section)
426 * Please note that course view page /course/view.php?id=COURSEID is hardcoded in many
427 * places in core and contributed modules. If course format wants to change the location
428 * of the view script, it is not enough to change just this function. Do not forget
429 * to add proper redirection.
431 * @param int|stdClass $section Section object from database or just field course_sections.section
432 * if null the course view page is returned
433 * @param array $options options for view URL. At the moment core uses:
434 * 'navigation' (bool) if true and section has no separate page, the function returns null
435 * 'sr' (int) used by multipage formats to specify to which section to return
436 * @return null|moodle_url
438 public function get_view_url($section, $options = array()) {
439 global $CFG;
440 $course = $this->get_course();
441 $url = new moodle_url('/course/view.php', array('id' => $course->id));
443 if (array_key_exists('sr', $options)) {
444 $sectionno = $options['sr'];
445 } else if (is_object($section)) {
446 $sectionno = $section->section;
447 } else {
448 $sectionno = $section;
450 if (empty($CFG->linkcoursesections) && !empty($options['navigation']) && $sectionno !== null) {
451 // by default assume that sections are never displayed on separate pages
452 return null;
454 if ($this->uses_sections() && $sectionno !== null) {
455 $url->set_anchor('section-'.$sectionno);
457 return $url;
461 * Loads all of the course sections into the navigation
463 * This method is called from {@link global_navigation::load_course_sections()}
465 * By default the method {@link global_navigation::load_generic_course_sections()} is called
467 * When overwriting please note that navigationlib relies on using the correct values for
468 * arguments $type and $key in {@link navigation_node::add()}
470 * Example of code creating a section node:
471 * $sectionnode = $node->add($sectionname, $url, navigation_node::TYPE_SECTION, null, $section->id);
472 * $sectionnode->nodetype = navigation_node::NODETYPE_BRANCH;
474 * Example of code creating an activity node:
475 * $activitynode = $sectionnode->add($activityname, $action, navigation_node::TYPE_ACTIVITY, null, $activity->id, $icon);
476 * if (global_navigation::module_extends_navigation($activity->modname)) {
477 * $activitynode->nodetype = navigation_node::NODETYPE_BRANCH;
478 * } else {
479 * $activitynode->nodetype = navigation_node::NODETYPE_LEAF;
482 * Also note that if $navigation->includesectionnum is not null, the section with this relative
483 * number needs is expected to be loaded
485 * @param global_navigation $navigation
486 * @param navigation_node $node The course node within the navigation
488 public function extend_course_navigation($navigation, navigation_node $node) {
489 if ($course = $this->get_course()) {
490 $navigation->load_generic_course_sections($course, $node);
492 return array();
496 * Returns the list of blocks to be automatically added for the newly created course
498 * @see blocks_add_default_course_blocks()
500 * @return array of default blocks, must contain two keys BLOCK_POS_LEFT and BLOCK_POS_RIGHT
501 * each of values is an array of block names (for left and right side columns)
503 public function get_default_blocks() {
504 global $CFG;
505 if (isset($CFG->defaultblocks)) {
506 return blocks_parse_default_blocks_list($CFG->defaultblocks);
508 $blocknames = array(
509 BLOCK_POS_LEFT => array(),
510 BLOCK_POS_RIGHT => array()
512 return $blocknames;
516 * Returns the localised name of this course format plugin
518 * @return lang_string
520 public final function get_format_name() {
521 return new lang_string('pluginname', 'format_'.$this->get_format());
525 * Definitions of the additional options that this course format uses for course
527 * This function may be called often, it should be as fast as possible.
528 * Avoid using get_string() method, use "new lang_string()" instead
529 * It is not recommended to use dynamic or course-dependant expressions here
530 * This function may be also called when course does not exist yet.
532 * Option names must be different from fields in the {course} talbe or any form elements on
533 * course edit form, it may even make sence to use special prefix for them.
535 * Each option must have the option name as a key and the array of properties as a value:
536 * 'default' - default value for this option (assumed null if not specified)
537 * 'type' - type of the option value (PARAM_INT, PARAM_RAW, etc.)
539 * Additional properties used by default implementation of
540 * {@link format_base::create_edit_form_elements()} (calls this method with $foreditform = true)
541 * 'label' - localised human-readable label for the edit form
542 * 'element_type' - type of the form element, default 'text'
543 * 'element_attributes' - additional attributes for the form element, these are 4th and further
544 * arguments in the moodleform::addElement() method
545 * 'help' - string for help button. Note that if 'help' value is 'myoption' then the string with
546 * the name 'myoption_help' must exist in the language file
547 * 'help_component' - language component to look for help string, by default this the component
548 * for this course format
550 * This is an interface for creating simple form elements. If format plugin wants to use other
551 * methods such as disableIf, it can be done by overriding create_edit_form_elements().
553 * Course format options can be accessed as:
554 * $this->get_course()->OPTIONNAME (inside the format class)
555 * course_get_format($course)->get_course()->OPTIONNAME (outside of format class)
557 * All course options are returned by calling:
558 * $this->get_format_options();
560 * @param bool $foreditform
561 * @return array of options
563 public function course_format_options($foreditform = false) {
564 return array();
568 * Definitions of the additional options that this course format uses for section
570 * See {@link format_base::course_format_options()} for return array definition.
572 * Additionally section format options may have property 'cache' set to true
573 * if this option needs to be cached in {@link get_fast_modinfo()}. The 'cache' property
574 * is recommended to be set only for fields used in {@link format_base::get_section_name()},
575 * {@link format_base::extend_course_navigation()} and {@link format_base::get_view_url()}
577 * For better performance cached options are recommended to have 'cachedefault' property
578 * Unlike 'default', 'cachedefault' should be static and not access get_config().
580 * Regardless of value of 'cache' all options are accessed in the code as
581 * $sectioninfo->OPTIONNAME
582 * where $sectioninfo is instance of section_info, returned by
583 * get_fast_modinfo($course)->get_section_info($sectionnum)
584 * or get_fast_modinfo($course)->get_section_info_all()
586 * All format options for particular section are returned by calling:
587 * $this->get_format_options($section);
589 * @param bool $foreditform
590 * @return array
592 public function section_format_options($foreditform = false) {
593 return array();
597 * Returns the format options stored for this course or course section
599 * When overriding please note that this function is called from rebuild_course_cache()
600 * and section_info object, therefore using of get_fast_modinfo() and/or any function that
601 * accesses it may lead to recursion.
603 * @param null|int|stdClass|section_info $section if null the course format options will be returned
604 * otherwise options for specified section will be returned. This can be either
605 * section object or relative section number (field course_sections.section)
606 * @return array
608 public function get_format_options($section = null) {
609 global $DB;
610 if ($section === null) {
611 $options = $this->course_format_options();
612 } else {
613 $options = $this->section_format_options();
615 if (empty($options)) {
616 // there are no option for course/sections anyway, no need to go further
617 return array();
619 if ($section === null) {
620 // course format options will be returned
621 $sectionid = 0;
622 } else if ($this->courseid && isset($section->id)) {
623 // course section format options will be returned
624 $sectionid = $section->id;
625 } else if ($this->courseid && is_int($section) &&
626 ($sectionobj = $DB->get_record('course_sections',
627 array('section' => $section, 'course' => $this->courseid), 'id'))) {
628 // course section format options will be returned
629 $sectionid = $sectionobj->id;
630 } else {
631 // non-existing (yet) section was passed as an argument
632 // default format options for course section will be returned
633 $sectionid = -1;
635 if (!array_key_exists($sectionid, $this->formatoptions)) {
636 $this->formatoptions[$sectionid] = array();
637 // first fill with default values
638 foreach ($options as $optionname => $optionparams) {
639 $this->formatoptions[$sectionid][$optionname] = null;
640 if (array_key_exists('default', $optionparams)) {
641 $this->formatoptions[$sectionid][$optionname] = $optionparams['default'];
644 if ($this->courseid && $sectionid !== -1) {
645 // overwrite the default options values with those stored in course_format_options table
646 // nothing can be stored if we are interested in generic course ($this->courseid == 0)
647 // or generic section ($sectionid === 0)
648 $records = $DB->get_records('course_format_options',
649 array('courseid' => $this->courseid,
650 'format' => $this->format,
651 'sectionid' => $sectionid
652 ), '', 'id,name,value');
653 foreach ($records as $record) {
654 if (array_key_exists($record->name, $this->formatoptions[$sectionid])) {
655 $value = $record->value;
656 if ($value !== null && isset($options[$record->name]['type'])) {
657 // this will convert string value to number if needed
658 $value = clean_param($value, $options[$record->name]['type']);
660 $this->formatoptions[$sectionid][$record->name] = $value;
665 return $this->formatoptions[$sectionid];
669 * Adds format options elements to the course/section edit form
671 * This function is called from {@link course_edit_form::definition_after_data()}
673 * @param MoodleQuickForm $mform form the elements are added to
674 * @param bool $forsection 'true' if this is a section edit form, 'false' if this is course edit form
675 * @return array array of references to the added form elements
677 public function create_edit_form_elements(&$mform, $forsection = false) {
678 $elements = array();
679 if ($forsection) {
680 $options = $this->section_format_options(true);
681 } else {
682 $options = $this->course_format_options(true);
684 foreach ($options as $optionname => $option) {
685 if (!isset($option['element_type'])) {
686 $option['element_type'] = 'text';
688 $args = array($option['element_type'], $optionname, $option['label']);
689 if (!empty($option['element_attributes'])) {
690 $args = array_merge($args, $option['element_attributes']);
692 $elements[] = call_user_func_array(array($mform, 'addElement'), $args);
693 if (isset($option['help'])) {
694 $helpcomponent = 'format_'. $this->get_format();
695 if (isset($option['help_component'])) {
696 $helpcomponent = $option['help_component'];
698 $mform->addHelpButton($optionname, $option['help'], $helpcomponent);
700 if (isset($option['type'])) {
701 $mform->setType($optionname, $option['type']);
703 if (isset($option['default']) && !array_key_exists($optionname, $mform->_defaultValues)) {
704 // Set defaults for the elements in the form.
705 // Since we call this method after set_data() make sure that we don't override what was already set.
706 $mform->setDefault($optionname, $option['default']);
710 if (!$forsection && empty($this->courseid)) {
711 // Check if course end date form field should be enabled by default.
712 // If a default date is provided to the form element, it is magically enabled by default in the
713 // MoodleQuickForm_date_time_selector class, otherwise it's disabled by default.
714 if (get_config('moodlecourse', 'courseenddateenabled')) {
715 // At this stage (this is called from definition_after_data) course data is already set as default.
716 // We can not overwrite what is in the database.
717 $mform->setDefault('enddate', $this->get_default_course_enddate($mform));
721 return $elements;
725 * Override if you need to perform some extra validation of the format options
727 * @param array $data array of ("fieldname"=>value) of submitted data
728 * @param array $files array of uploaded files "element_name"=>tmp_file_path
729 * @param array $errors errors already discovered in edit form validation
730 * @return array of "element_name"=>"error_description" if there are errors,
731 * or an empty array if everything is OK.
732 * Do not repeat errors from $errors param here
734 public function edit_form_validation($data, $files, $errors) {
735 return array();
739 * Updates format options for a course or section
741 * If $data does not contain property with the option name, the option will not be updated
743 * @param stdClass|array $data return value from {@link moodleform::get_data()} or array with data
744 * @param null|int null if these are options for course or section id (course_sections.id)
745 * if these are options for section
746 * @return bool whether there were any changes to the options values
748 protected function update_format_options($data, $sectionid = null) {
749 global $DB;
750 if (!$sectionid) {
751 $allformatoptions = $this->course_format_options();
752 $sectionid = 0;
753 } else {
754 $allformatoptions = $this->section_format_options();
756 if (empty($allformatoptions)) {
757 // nothing to update anyway
758 return false;
760 $defaultoptions = array();
761 $cached = array();
762 foreach ($allformatoptions as $key => $option) {
763 $defaultoptions[$key] = null;
764 if (array_key_exists('default', $option)) {
765 $defaultoptions[$key] = $option['default'];
767 $cached[$key] = ($sectionid === 0 || !empty($option['cache']));
769 $records = $DB->get_records('course_format_options',
770 array('courseid' => $this->courseid,
771 'format' => $this->format,
772 'sectionid' => $sectionid
773 ), '', 'name,id,value');
774 $changed = $needrebuild = false;
775 $data = (array)$data;
776 foreach ($defaultoptions as $key => $value) {
777 if (isset($records[$key])) {
778 if (array_key_exists($key, $data) && $records[$key]->value !== $data[$key]) {
779 $DB->set_field('course_format_options', 'value',
780 $data[$key], array('id' => $records[$key]->id));
781 $changed = true;
782 $needrebuild = $needrebuild || $cached[$key];
784 } else {
785 if (array_key_exists($key, $data) && $data[$key] !== $value) {
786 $newvalue = $data[$key];
787 $changed = true;
788 $needrebuild = $needrebuild || $cached[$key];
789 } else {
790 $newvalue = $value;
791 // we still insert entry in DB but there are no changes from user point of
792 // view and no need to call rebuild_course_cache()
794 $DB->insert_record('course_format_options', array(
795 'courseid' => $this->courseid,
796 'format' => $this->format,
797 'sectionid' => $sectionid,
798 'name' => $key,
799 'value' => $newvalue
803 if ($needrebuild) {
804 rebuild_course_cache($this->courseid, true);
806 if ($changed) {
807 // reset internal caches
808 if (!$sectionid) {
809 $this->course = false;
811 unset($this->formatoptions[$sectionid]);
813 return $changed;
817 * Updates format options for a course
819 * If $data does not contain property with the option name, the option will not be updated
821 * @param stdClass|array $data return value from {@link moodleform::get_data()} or array with data
822 * @param stdClass $oldcourse if this function is called from {@link update_course()}
823 * this object contains information about the course before update
824 * @return bool whether there were any changes to the options values
826 public function update_course_format_options($data, $oldcourse = null) {
827 return $this->update_format_options($data);
831 * Updates format options for a section
833 * Section id is expected in $data->id (or $data['id'])
834 * If $data does not contain property with the option name, the option will not be updated
836 * @param stdClass|array $data return value from {@link moodleform::get_data()} or array with data
837 * @return bool whether there were any changes to the options values
839 public function update_section_format_options($data) {
840 $data = (array)$data;
841 return $this->update_format_options($data, $data['id']);
845 * Return an instance of moodleform to edit a specified section
847 * Default implementation returns instance of editsection_form that automatically adds
848 * additional fields defined in {@link format_base::section_format_options()}
850 * Format plugins may extend editsection_form if they want to have custom edit section form.
852 * @param mixed $action the action attribute for the form. If empty defaults to auto detect the
853 * current url. If a moodle_url object then outputs params as hidden variables.
854 * @param array $customdata the array with custom data to be passed to the form
855 * /course/editsection.php passes section_info object in 'cs' field
856 * for filling availability fields
857 * @return moodleform
859 public function editsection_form($action, $customdata = array()) {
860 global $CFG;
861 require_once($CFG->dirroot. '/course/editsection_form.php');
862 $context = context_course::instance($this->courseid);
863 if (!array_key_exists('course', $customdata)) {
864 $customdata['course'] = $this->get_course();
866 return new editsection_form($action, $customdata);
870 * Allows course format to execute code on moodle_page::set_course()
872 * @param moodle_page $page instance of page calling set_course
874 public function page_set_course(moodle_page $page) {
878 * Allows course format to execute code on moodle_page::set_cm()
880 * Current module can be accessed as $page->cm (returns instance of cm_info)
882 * @param moodle_page $page instance of page calling set_cm
884 public function page_set_cm(moodle_page $page) {
888 * Course-specific information to be output on any course page (usually above navigation bar)
890 * Example of usage:
891 * define
892 * class format_FORMATNAME_XXX implements renderable {}
894 * create format renderer in course/format/FORMATNAME/renderer.php, define rendering function:
895 * class format_FORMATNAME_renderer extends plugin_renderer_base {
896 * protected function render_format_FORMATNAME_XXX(format_FORMATNAME_XXX $xxx) {
897 * return html_writer::tag('div', 'This is my header/footer');
901 * Return instance of format_FORMATNAME_XXX in this function, the appropriate method from
902 * plugin renderer will be called
904 * @return null|renderable null for no output or object with data for plugin renderer
906 public function course_header() {
907 return null;
911 * Course-specific information to be output on any course page (usually in the beginning of
912 * standard footer)
914 * See {@link format_base::course_header()} for usage
916 * @return null|renderable null for no output or object with data for plugin renderer
918 public function course_footer() {
919 return null;
923 * Course-specific information to be output immediately above content on any course page
925 * See {@link format_base::course_header()} for usage
927 * @return null|renderable null for no output or object with data for plugin renderer
929 public function course_content_header() {
930 return null;
934 * Course-specific information to be output immediately below content on any course page
936 * See {@link format_base::course_header()} for usage
938 * @return null|renderable null for no output or object with data for plugin renderer
940 public function course_content_footer() {
941 return null;
945 * Returns instance of page renderer used by this plugin
947 * @param moodle_page $page
948 * @return renderer_base
950 public function get_renderer(moodle_page $page) {
951 return $page->get_renderer('format_'. $this->get_format());
955 * Returns true if the specified section is current
957 * By default we analyze $course->marker
959 * @param int|stdClass|section_info $section
960 * @return bool
962 public function is_section_current($section) {
963 if (is_object($section)) {
964 $sectionnum = $section->section;
965 } else {
966 $sectionnum = $section;
968 return ($sectionnum && ($course = $this->get_course()) && $course->marker == $sectionnum);
972 * Allows to specify for modinfo that section is not available even when it is visible and conditionally available.
974 * Note: affected user can be retrieved as: $section->modinfo->userid
976 * Course format plugins can override the method to change the properties $available and $availableinfo that were
977 * calculated by conditional availability.
978 * To make section unavailable set:
979 * $available = false;
980 * To make unavailable section completely hidden set:
981 * $availableinfo = '';
982 * To make unavailable section visible with availability message set:
983 * $availableinfo = get_string('sectionhidden', 'format_xxx');
985 * @param section_info $section
986 * @param bool $available the 'available' propery of the section_info as it was evaluated by conditional availability.
987 * Can be changed by the method but 'false' can not be overridden by 'true'.
988 * @param string $availableinfo the 'availableinfo' propery of the section_info as it was evaluated by conditional availability.
989 * Can be changed by the method
991 public function section_get_available_hook(section_info $section, &$available, &$availableinfo) {
995 * Whether this format allows to delete sections
997 * If format supports deleting sections it is also recommended to define language string
998 * 'deletesection' inside the format.
1000 * Do not call this function directly, instead use {@link course_can_delete_section()}
1002 * @param int|stdClass|section_info $section
1003 * @return bool
1005 public function can_delete_section($section) {
1006 return false;
1010 * Deletes a section
1012 * Do not call this function directly, instead call {@link course_delete_section()}
1014 * @param int|stdClass|section_info $section
1015 * @param bool $forcedeleteifnotempty if set to false section will not be deleted if it has modules in it.
1016 * @return bool whether section was deleted
1018 public function delete_section($section, $forcedeleteifnotempty = false) {
1019 global $DB;
1020 if (!$this->uses_sections()) {
1021 // Not possible to delete section if sections are not used.
1022 return false;
1024 if (!is_object($section)) {
1025 $section = $DB->get_record('course_sections', array('course' => $this->get_courseid(), 'section' => $section),
1026 'id,section,sequence,summary');
1028 if (!$section || !$section->section) {
1029 // Not possible to delete 0-section.
1030 return false;
1033 if (!$forcedeleteifnotempty && (!empty($section->sequence) || !empty($section->summary))) {
1034 return false;
1037 $course = $this->get_course();
1039 // Remove the marker if it points to this section.
1040 if ($section->section == $course->marker) {
1041 course_set_marker($course->id, 0);
1044 $lastsection = $DB->get_field_sql('SELECT max(section) from {course_sections}
1045 WHERE course = ?', array($course->id));
1047 // Find out if we need to descrease the 'numsections' property later.
1048 $courseformathasnumsections = array_key_exists('numsections',
1049 $this->get_format_options());
1050 $decreasenumsections = $courseformathasnumsections && ($section->section <= $course->numsections);
1052 // Move the section to the end.
1053 move_section_to($course, $section->section, $lastsection, true);
1055 // Delete all modules from the section.
1056 foreach (preg_split('/,/', $section->sequence, -1, PREG_SPLIT_NO_EMPTY) as $cmid) {
1057 course_delete_module($cmid);
1060 // Delete section and it's format options.
1061 $DB->delete_records('course_format_options', array('sectionid' => $section->id));
1062 $DB->delete_records('course_sections', array('id' => $section->id));
1063 rebuild_course_cache($course->id, true);
1065 // Descrease 'numsections' if needed.
1066 if ($decreasenumsections) {
1067 $this->update_course_format_options(array('numsections' => $course->numsections - 1));
1070 return true;
1074 * Prepares the templateable object to display section name
1076 * @param \section_info|\stdClass $section
1077 * @param bool $linkifneeded
1078 * @param bool $editable
1079 * @param null|lang_string|string $edithint
1080 * @param null|lang_string|string $editlabel
1081 * @return \core\output\inplace_editable
1083 public function inplace_editable_render_section_name($section, $linkifneeded = true,
1084 $editable = null, $edithint = null, $editlabel = null) {
1085 global $USER, $CFG;
1086 require_once($CFG->dirroot.'/course/lib.php');
1088 if ($editable === null) {
1089 $editable = !empty($USER->editing) && has_capability('moodle/course:update',
1090 context_course::instance($section->course));
1093 $displayvalue = $title = get_section_name($section->course, $section);
1094 if ($linkifneeded) {
1095 // Display link under the section name if the course format setting is to display one section per page.
1096 $url = course_get_url($section->course, $section->section, array('navigation' => true));
1097 if ($url) {
1098 $displayvalue = html_writer::link($url, $title);
1100 $itemtype = 'sectionname';
1101 } else {
1102 // If $linkifneeded==false, we never display the link (this is used when rendering the section header).
1103 // Itemtype 'sectionnamenl' (nl=no link) will tell the callback that link should not be rendered -
1104 // there is no other way callback can know where we display the section name.
1105 $itemtype = 'sectionnamenl';
1107 if (empty($edithint)) {
1108 $edithint = new lang_string('editsectionname');
1110 if (empty($editlabel)) {
1111 $editlabel = new lang_string('newsectionname', '', $title);
1114 return new \core\output\inplace_editable('format_' . $this->format, $itemtype, $section->id, $editable,
1115 $displayvalue, $section->name, $edithint, $editlabel);
1119 * Updates the value in the database and modifies this object respectively.
1121 * ALWAYS check user permissions before performing an update! Throw exceptions if permissions are not sufficient
1122 * or value is not legit.
1124 * @param stdClass $section
1125 * @param string $itemtype
1126 * @param mixed $newvalue
1127 * @return \core\output\inplace_editable
1129 public function inplace_editable_update_section_name($section, $itemtype, $newvalue) {
1130 if ($itemtype === 'sectionname' || $itemtype === 'sectionnamenl') {
1131 $context = context_course::instance($section->course);
1132 external_api::validate_context($context);
1133 require_capability('moodle/course:update', $context);
1135 $newtitle = clean_param($newvalue, PARAM_TEXT);
1136 if (strval($section->name) !== strval($newtitle)) {
1137 course_update_section($section->course, $section, array('name' => $newtitle));
1139 return $this->inplace_editable_render_section_name($section, ($itemtype === 'sectionname'), true);
1145 * Returns the default end date value based on the start date.
1147 * This is the default implementation for course formats, it is based on
1148 * moodlecourse/courseduration setting. Course formats like format_weeks for
1149 * example can overwrite this method and return a value based on their internal options.
1151 * @param moodleform $mform
1152 * @param array $fieldnames The form - field names mapping.
1153 * @return int
1155 public function get_default_course_enddate($mform, $fieldnames = array()) {
1157 if (empty($fieldnames)) {
1158 $fieldnames = array('startdate' => 'startdate');
1161 $startdate = $this->get_form_start_date($mform, $fieldnames);
1162 $courseduration = intval(get_config('moodlecourse', 'courseduration'));
1163 if (!$courseduration) {
1164 // Default, it should be already set during upgrade though.
1165 $courseduration = YEARSECS;
1168 return $startdate + $courseduration;
1172 * Indicates whether the course format supports the creation of the Announcements forum.
1174 * For course format plugin developers, please override this to return true if you want the Announcements forum
1175 * to be created upon course creation.
1177 * @return bool
1179 public function supports_news() {
1180 // For backwards compatibility, check if default blocks include the news_items block.
1181 $defaultblocks = $this->get_default_blocks();
1182 foreach ($defaultblocks as $blocks) {
1183 if (in_array('news_items', $blocks)) {
1184 return true;
1187 // Return false by default.
1188 return false;
1192 * Get the start date value from the course settings page form.
1194 * @param moodleform $mform
1195 * @param array $fieldnames The form - field names mapping.
1196 * @return int
1198 protected function get_form_start_date($mform, $fieldnames) {
1199 $startdate = $mform->getElementValue($fieldnames['startdate']);
1200 return $mform->getElement($fieldnames['startdate'])->exportValue($startdate);
1204 * Returns whether this course format allows the activity to
1205 * have "triple visibility state" - visible always, hidden on course page but available, hidden.
1207 * @param stdClass|cm_info $cm course module (may be null if we are displaying a form for adding a module)
1208 * @param stdClass|section_info $section section where this module is located or will be added to
1209 * @return bool
1211 public function allow_stealth_module_visibility($cm, $section) {
1212 return false;
1216 * Callback used in WS core_course_edit_section when teacher performs an AJAX action on a section (show/hide)
1218 * Access to the course is already validated in the WS but the callback has to make sure
1219 * that particular action is allowed by checking capabilities
1221 * Course formats should register
1223 * @param stdClass|section_info $section
1224 * @param string $action
1225 * @param int $sr
1226 * @return null|array|stdClass any data for the Javascript post-processor (must be json-encodeable)
1228 public function section_action($section, $action, $sr) {
1229 global $PAGE;
1230 if (!$this->uses_sections() || !$section->section) {
1231 // No section actions are allowed if course format does not support sections.
1232 // No actions are allowed on the 0-section by default (overwrite in course format if needed).
1233 throw new moodle_exception('sectionactionnotsupported', 'core', null, s($action));
1236 $course = $this->get_course();
1237 $coursecontext = context_course::instance($course->id);
1238 switch($action) {
1239 case 'hide':
1240 case 'show':
1241 require_capability('moodle/course:sectionvisibility', $coursecontext);
1242 $visible = ($action === 'hide') ? 0 : 1;
1243 course_update_section($course, $section, array('visible' => $visible));
1244 break;
1245 default:
1246 throw new moodle_exception('sectionactionnotsupported', 'core', null, s($action));
1249 $modules = [];
1251 $modinfo = get_fast_modinfo($course);
1252 $coursesections = $modinfo->sections;
1253 if (array_key_exists($section->section, $coursesections)) {
1254 $courserenderer = $PAGE->get_renderer('core', 'course');
1255 $completioninfo = new completion_info($course);
1256 foreach ($coursesections[$section->section] as $cmid) {
1257 $cm = $modinfo->get_cm($cmid);
1258 $modules[] = $courserenderer->course_section_cm_list_item($course, $completioninfo, $cm, $sr);
1262 return ['modules' => $modules];
1267 * Pseudo course format used for the site main page
1269 * @package core_course
1270 * @copyright 2012 Marina Glancy
1271 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1273 class format_site extends format_base {
1276 * Returns the display name of the given section that the course prefers.
1278 * @param int|stdClass $section Section object from database or just field section.section
1279 * @return Display name that the course format prefers, e.g. "Topic 2"
1281 function get_section_name($section) {
1282 return get_string('site');
1286 * For this fake course referring to the whole site, the site homepage is always returned
1287 * regardless of arguments
1289 * @param int|stdClass $section
1290 * @param array $options
1291 * @return null|moodle_url
1293 public function get_view_url($section, $options = array()) {
1294 return new moodle_url('/', array('redirect' => 0));
1298 * Returns the list of blocks to be automatically added on the site frontpage when moodle is installed
1300 * @return array of default blocks, must contain two keys BLOCK_POS_LEFT and BLOCK_POS_RIGHT
1301 * each of values is an array of block names (for left and right side columns)
1303 public function get_default_blocks() {
1304 return blocks_get_default_site_course_blocks();
1308 * Definitions of the additional options that site uses
1310 * @param bool $foreditform
1311 * @return array of options
1313 public function course_format_options($foreditform = false) {
1314 static $courseformatoptions = false;
1315 if ($courseformatoptions === false) {
1316 $courseformatoptions = array(
1317 'numsections' => array(
1318 'default' => 1,
1319 'type' => PARAM_INT,
1323 return $courseformatoptions;
1327 * Returns whether this course format allows the activity to
1328 * have "triple visibility state" - visible always, hidden on course page but available, hidden.
1330 * @param stdClass|cm_info $cm course module (may be null if we are displaying a form for adding a module)
1331 * @param stdClass|section_info $section section where this module is located or will be added to
1332 * @return bool
1334 public function allow_stealth_module_visibility($cm, $section) {
1335 return true;