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 * This file contains main class for Topics course format.
19 *
20 * @since     Moodle 2.0
21 * @package   format_topics
22 * @copyright 2009 Sam Hemelryk
23 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 */
25
26defined('MOODLE_INTERNAL') || die();
27require_once($CFG->dirroot. '/course/format/lib.php');
28
29use core\output\inplace_editable;
30
31/**
32 * Main class for the Topics course format.
33 *
34 * @package    format_topics
35 * @copyright  2012 Marina Glancy
36 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37 */
38class format_topics extends format_base {
39
40    /**
41     * Returns true if this course format uses sections.
42     *
43     * @return bool
44     */
45    public function uses_sections() {
46        return true;
47    }
48
49    /**
50     * Returns the display name of the given section that the course prefers.
51     *
52     * Use section name is specified by user. Otherwise use default ("Topic #").
53     *
54     * @param int|stdClass $section Section object from database or just field section.section
55     * @return string Display name that the course format prefers, e.g. "Topic 2"
56     */
57    public function get_section_name($section) {
58        $section = $this->get_section($section);
59        if ((string)$section->name !== '') {
60            return format_string($section->name, true,
61                ['context' => context_course::instance($this->courseid)]);
62        } else {
63            return $this->get_default_section_name($section);
64        }
65    }
66
67    /**
68     * Returns the default section name for the topics course format.
69     *
70     * If the section number is 0, it will use the string with key = section0name from the course format's lang file.
71     * If the section number is not 0, the base implementation of format_base::get_default_section_name which uses
72     * the string with the key = 'sectionname' from the course format's lang file + the section number will be used.
73     *
74     * @param stdClass $section Section object from database or just field course_sections section
75     * @return string The default value for the section name.
76     */
77    public function get_default_section_name($section) {
78        if ($section->section == 0) {
79            // Return the general section.
80            return get_string('section0name', 'format_topics');
81        } else {
82            // Use format_base::get_default_section_name implementation which
83            // will display the section name in "Topic n" format.
84            return parent::get_default_section_name($section);
85        }
86    }
87
88    /**
89     * The URL to use for the specified course (with section).
90     *
91     * @param int|stdClass $section Section object from database or just field course_sections.section
92     *     if omitted the course view page is returned
93     * @param array $options options for view URL. At the moment core uses:
94     *     'navigation' (bool) if true and section has no separate page, the function returns null
95     *     'sr' (int) used by multipage formats to specify to which section to return
96     * @return null|moodle_url
97     */
98    public function get_view_url($section, $options = []) {
99        global $CFG;
100        $course = $this->get_course();
101        $url = new moodle_url('/course/view.php', ['id' => $course->id]);
102
103        $sr = null;
104        if (array_key_exists('sr', $options)) {
105            $sr = $options['sr'];
106        }
107        if (is_object($section)) {
108            $sectionno = $section->section;
109        } else {
110            $sectionno = $section;
111        }
112        if ($sectionno !== null) {
113            if ($sr !== null) {
114                if ($sr) {
115                    $usercoursedisplay = COURSE_DISPLAY_MULTIPAGE;
116                    $sectionno = $sr;
117                } else {
118                    $usercoursedisplay = COURSE_DISPLAY_SINGLEPAGE;
119                }
120            } else {
121                $usercoursedisplay = $course->coursedisplay;
122            }
123            if ($sectionno != 0 && $usercoursedisplay == COURSE_DISPLAY_MULTIPAGE) {
124                $url->param('section', $sectionno);
125            } else {
126                if (empty($CFG->linkcoursesections) && !empty($options['navigation'])) {
127                    return null;
128                }
129                $url->set_anchor('section-'.$sectionno);
130            }
131        }
132        return $url;
133    }
134
135    /**
136     * Returns the information about the ajax support in the given source format.
137     *
138     * The returned object's property (boolean)capable indicates that
139     * the course format supports Moodle course ajax features.
140     *
141     * @return stdClass
142     */
143    public function supports_ajax() {
144        $ajaxsupport = new stdClass();
145        $ajaxsupport->capable = true;
146        return $ajaxsupport;
147    }
148
149    /**
150     * Loads all of the course sections into the navigation.
151     *
152     * @param global_navigation $navigation
153     * @param navigation_node $node The course node within the navigation
154     * @return void
155     */
156    public function extend_course_navigation($navigation, navigation_node $node) {
157        global $PAGE;
158        // If section is specified in course/view.php, make sure it is expanded in navigation.
159        if ($navigation->includesectionnum === false) {
160            $selectedsection = optional_param('section', null, PARAM_INT);
161            if ($selectedsection !== null && (!defined('AJAX_SCRIPT') || AJAX_SCRIPT == '0') &&
162                    $PAGE->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
163                $navigation->includesectionnum = $selectedsection;
164            }
165        }
166
167        // Check if there are callbacks to extend course navigation.
168        parent::extend_course_navigation($navigation, $node);
169
170        // We want to remove the general section if it is empty.
171        $modinfo = get_fast_modinfo($this->get_course());
172        $sections = $modinfo->get_sections();
173        if (!isset($sections[0])) {
174            // The general section is empty to find the navigation node for it we need to get its ID.
175            $section = $modinfo->get_section_info(0);
176            $generalsection = $node->get($section->id, navigation_node::TYPE_SECTION);
177            if ($generalsection) {
178                // We found the node - now remove it.
179                $generalsection->remove();
180            }
181        }
182    }
183
184    /**
185     * Custom action after section has been moved in AJAX mode.
186     *
187     * Used in course/rest.php
188     *
189     * @return array This will be passed in ajax respose
190     */
191    public function ajax_section_move() {
192        global $PAGE;
193        $titles = [];
194        $course = $this->get_course();
195        $modinfo = get_fast_modinfo($course);
196        $renderer = $this->get_renderer($PAGE);
197        if ($renderer && ($sections = $modinfo->get_section_info_all())) {
198            foreach ($sections as $number => $section) {
199                $titles[$number] = $renderer->section_title($section, $course);
200            }
201        }
202        return ['sectiontitles' => $titles, 'action' => 'move'];
203    }
204
205    /**
206     * Returns the list of blocks to be automatically added for the newly created course.
207     *
208     * @return array of default blocks, must contain two keys BLOCK_POS_LEFT and BLOCK_POS_RIGHT
209     *     each of values is an array of block names (for left and right side columns)
210     */
211    public function get_default_blocks() {
212        return [
213            BLOCK_POS_LEFT => [],
214            BLOCK_POS_RIGHT => [],
215        ];
216    }
217
218    /**
219     * Definitions of the additional options that this course format uses for course.
220     *
221     * Topics format uses the following options:
222     * - coursedisplay
223     * - hiddensections
224     *
225     * @param bool $foreditform
226     * @return array of options
227     */
228    public function course_format_options($foreditform = false) {
229        static $courseformatoptions = false;
230        if ($courseformatoptions === false) {
231            $courseconfig = get_config('moodlecourse');
232            $courseformatoptions = [
233                'hiddensections' => [
234                    'default' => $courseconfig->hiddensections,
235                    'type' => PARAM_INT,
236                ],
237                'coursedisplay' => [
238                    'default' => $courseconfig->coursedisplay,
239                    'type' => PARAM_INT,
240                ],
241            ];
242        }
243        if ($foreditform && !isset($courseformatoptions['coursedisplay']['label'])) {
244            $courseformatoptionsedit = [
245                'hiddensections' => [
246                    'label' => new lang_string('hiddensections'),
247                    'help' => 'hiddensections',
248                    'help_component' => 'moodle',
249                    'element_type' => 'select',
250                    'element_attributes' => [
251                        [
252                            0 => new lang_string('hiddensectionscollapsed'),
253                            1 => new lang_string('hiddensectionsinvisible')
254                        ],
255                    ],
256                ],
257                'coursedisplay' => [
258                    'label' => new lang_string('coursedisplay'),
259                    'element_type' => 'select',
260                    'element_attributes' => [
261                        [
262                            COURSE_DISPLAY_SINGLEPAGE => new lang_string('coursedisplay_single'),
263                            COURSE_DISPLAY_MULTIPAGE => new lang_string('coursedisplay_multi'),
264                        ],
265                    ],
266                    'help' => 'coursedisplay',
267                    'help_component' => 'moodle',
268                ],
269            ];
270            $courseformatoptions = array_merge_recursive($courseformatoptions, $courseformatoptionsedit);
271        }
272        return $courseformatoptions;
273    }
274
275    /**
276     * Adds format options elements to the course/section edit form.
277     *
278     * This function is called from {@link course_edit_form::definition_after_data()}.
279     *
280     * @param MoodleQuickForm $mform form the elements are added to.
281     * @param bool $forsection 'true' if this is a section edit form, 'false' if this is course edit form.
282     * @return array array of references to the added form elements.
283     */
284    public function create_edit_form_elements(&$mform, $forsection = false) {
285        global $COURSE;
286        $elements = parent::create_edit_form_elements($mform, $forsection);
287
288        if (!$forsection && (empty($COURSE->id) || $COURSE->id == SITEID)) {
289            // Add "numsections" element to the create course form - it will force new course to be prepopulated
290            // with empty sections.
291            // The "Number of sections" option is no longer available when editing course, instead teachers should
292            // delete and add sections when needed.
293            $courseconfig = get_config('moodlecourse');
294            $max = (int)$courseconfig->maxsections;
295            $element = $mform->addElement('select', 'numsections', get_string('numberweeks'), range(0, $max ?: 52));
296            $mform->setType('numsections', PARAM_INT);
297            if (is_null($mform->getElementValue('numsections'))) {
298                $mform->setDefault('numsections', $courseconfig->numsections);
299            }
300            array_unshift($elements, $element);
301        }
302
303        return $elements;
304    }
305
306    /**
307     * Updates format options for a course.
308     *
309     * In case if course format was changed to 'topics', we try to copy options
310     * 'coursedisplay' and 'hiddensections' from the previous format.
311     *
312     * @param stdClass|array $data return value from {@link moodleform::get_data()} or array with data
313     * @param stdClass $oldcourse if this function is called from {@link update_course()}
314     *     this object contains information about the course before update
315     * @return bool whether there were any changes to the options values
316     */
317    public function update_course_format_options($data, $oldcourse = null) {
318        $data = (array)$data;
319        if ($oldcourse !== null) {
320            $oldcourse = (array)$oldcourse;
321            $options = $this->course_format_options();
322            foreach ($options as $key => $unused) {
323                if (!array_key_exists($key, $data)) {
324                    if (array_key_exists($key, $oldcourse)) {
325                        $data[$key] = $oldcourse[$key];
326                    }
327                }
328            }
329        }
330        return $this->update_format_options($data);
331    }
332
333    /**
334     * Whether this format allows to delete sections.
335     *
336     * Do not call this function directly, instead use {@link course_can_delete_section()}
337     *
338     * @param int|stdClass|section_info $section
339     * @return bool
340     */
341    public function can_delete_section($section) {
342        return true;
343    }
344
345    /**
346     * Prepares the templateable object to display section name.
347     *
348     * @param \section_info|\stdClass $section
349     * @param bool $linkifneeded
350     * @param bool $editable
351     * @param null|lang_string|string $edithint
352     * @param null|lang_string|string $editlabel
353     * @return inplace_editable
354     */
355    public function inplace_editable_render_section_name($section, $linkifneeded = true,
356            $editable = null, $edithint = null, $editlabel = null) {
357        if (empty($edithint)) {
358            $edithint = new lang_string('editsectionname', 'format_topics');
359        }
360        if (empty($editlabel)) {
361            $title = get_section_name($section->course, $section);
362            $editlabel = new lang_string('newsectionname', 'format_topics', $title);
363        }
364        return parent::inplace_editable_render_section_name($section, $linkifneeded, $editable, $edithint, $editlabel);
365    }
366
367    /**
368     * Indicates whether the course format supports the creation of a news forum.
369     *
370     * @return bool
371     */
372    public function supports_news() {
373        return true;
374    }
375
376    /**
377     * Returns whether this course format allows the activity to
378     * have "triple visibility state" - visible always, hidden on course page but available, hidden.
379     *
380     * @param stdClass|cm_info $cm course module (may be null if we are displaying a form for adding a module)
381     * @param stdClass|section_info $section section where this module is located or will be added to
382     * @return bool
383     */
384    public function allow_stealth_module_visibility($cm, $section) {
385        // Allow the third visibility state inside visible sections or in section 0.
386        return !$section->section || $section->visible;
387    }
388
389    /**
390     * Callback used in WS core_course_edit_section when teacher performs an AJAX action on a section (show/hide).
391     *
392     * Access to the course is already validated in the WS but the callback has to make sure
393     * that particular action is allowed by checking capabilities
394     *
395     * Course formats should register.
396     *
397     * @param section_info|stdClass $section
398     * @param string $action
399     * @param int $sr
400     * @return null|array any data for the Javascript post-processor (must be json-encodeable)
401     */
402    public function section_action($section, $action, $sr) {
403        global $PAGE;
404
405        if ($section->section && ($action === 'setmarker' || $action === 'removemarker')) {
406            // Format 'topics' allows to set and remove markers in addition to common section actions.
407            require_capability('moodle/course:setcurrentsection', context_course::instance($this->courseid));
408            course_set_marker($this->courseid, ($action === 'setmarker') ? $section->section : 0);
409            return null;
410        }
411
412        // For show/hide actions call the parent method and return the new content for .section_availability element.
413        $rv = parent::section_action($section, $action, $sr);
414        $renderer = $PAGE->get_renderer('format_topics');
415        $rv['section_availability'] = $renderer->section_availability($this->get_section($section));
416        return $rv;
417    }
418
419    /**
420     * Return the plugin configs for external functions.
421     *
422     * @return array the list of configuration settings
423     * @since Moodle 3.5
424     */
425    public function get_config_for_external() {
426        // Return everything (nothing to hide).
427        return $this->get_format_options();
428    }
429}
430
431/**
432 * Implements callback inplace_editable() allowing to edit values in-place.
433 *
434 * @param string $itemtype
435 * @param int $itemid
436 * @param mixed $newvalue
437 * @return inplace_editable
438 */
439function format_topics_inplace_editable($itemtype, $itemid, $newvalue) {
440    global $DB, $CFG;
441    require_once($CFG->dirroot . '/course/lib.php');
442    if ($itemtype === 'sectionname' || $itemtype === 'sectionnamenl') {
443        $section = $DB->get_record_sql(
444            'SELECT s.* FROM {course_sections} s JOIN {course} c ON s.course = c.id WHERE s.id = ? AND c.format = ?',
445            [$itemid, 'topics'], MUST_EXIST);
446        return course_get_format($section->course)->inplace_editable_update_section_name($section, $itemtype, $newvalue);
447    }
448}
449