Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 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 the course format Weeks
19
 *
20
 * @since     Moodle 2.0
21
 * @package   format_weeks
22
 * @copyright 2009 Sam Hemelryk
23
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24
 */
25
 
26
defined('MOODLE_INTERNAL') || die();
27
require_once($CFG->dirroot. '/course/format/lib.php');
28
require_once($CFG->dirroot. '/course/lib.php');
29
 
30
/**
31
 * Main class for the Weeks course format
32
 *
33
 * @package    format_weeks
34
 * @copyright  2012 Marina Glancy
35
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36
 */
37
class format_weeks extends core_courseformat\base {
38
 
39
    /**
40
     * Returns true if this course format uses sections
41
     *
42
     * @return bool
43
     */
44
    public function uses_sections() {
45
        return true;
46
    }
47
 
48
    public function uses_course_index() {
49
        return true;
50
    }
51
 
52
    public function uses_indentation(): bool {
53
        return (get_config('format_weeks', 'indentation')) ? true : false;
54
    }
55
 
56
    /**
57
     * Generate the title for this section page
58
     * @return string the page title
59
     */
60
    public function page_title(): string {
61
        return get_string('sectionoutline');
62
    }
63
 
64
    /**
65
     * Returns the display name of the given section that the course prefers.
66
     *
67
     * @param int|stdClass $section Section object from database or just field section.section
68
     * @return string Display name that the course format prefers, e.g. "Topic 2"
69
     */
70
    public function get_section_name($section) {
71
        $section = $this->get_section($section);
72
        if ((string)$section->name !== '') {
73
            // Return the name the user set.
74
            return format_string($section->name, true, array('context' => context_course::instance($this->courseid)));
75
        } else {
76
            return $this->get_default_section_name($section);
77
        }
78
    }
79
 
80
    /**
81
     * Returns the default section name for the weekly course format.
82
     *
83
     * If the section number is 0, it will use the string with key = section0name from the course format's lang file.
84
     * Otherwise, the default format of "[start date] - [end date]" will be returned.
85
     *
86
     * @param stdClass $section Section object from database or just field course_sections section
87
     * @return string The default value for the section name.
88
     */
89
    public function get_default_section_name($section) {
90
        if ($section->section == 0) {
91
            // Return the general section.
92
            return get_string('section0name', 'format_weeks');
93
        } else {
94
            $dates = $this->get_section_dates($section);
95
 
96
            // We subtract 24 hours for display purposes.
97
            $dates->end = ($dates->end - 86400);
98
 
99
            $dateformat = get_string('strftimedateshort');
100
            $weekday = userdate($dates->start, $dateformat);
101
            $endweekday = userdate($dates->end, $dateformat);
102
            return $weekday.' - '.$endweekday;
103
        }
104
    }
105
 
106
    /**
107
     * Returns the name for the highlighted section.
108
     *
109
     * @return string The name for the highlighted section based on the given course format.
110
     */
111
    public function get_section_highlighted_name(): string {
112
        return get_string('currentsection', 'format_weeks');
113
    }
114
 
115
    /**
116
     * The URL to use for the specified course (with section)
117
     *
118
     * @param int|stdClass $section Section object from database or just field course_sections.section
119
     *     if omitted the course view page is returned
120
     * @param array $options options for view URL. At the moment core uses:
121
     *     'navigation' (bool) if true and section not empty, the function returns section page; otherwise, it returns course page.
122
     *     'sr' (int) used by course formats to specify to which section to return
123
     * @return null|moodle_url
124
     */
125
    public function get_view_url($section, $options = array()) {
126
        $course = $this->get_course();
127
        if (array_key_exists('sr', $options) && !is_null($options['sr'])) {
128
            $sectionno = $options['sr'];
129
        } else if (is_object($section)) {
130
            $sectionno = $section->section;
131
        } else {
132
            $sectionno = $section;
133
        }
134
        if ((!empty($options['navigation']) || array_key_exists('sr', $options)) && $sectionno !== null) {
135
            // Display section on separate page.
136
            $sectioninfo = $this->get_section($sectionno);
137
            return new moodle_url('/course/section.php', ['id' => $sectioninfo->id]);
138
        }
139
 
140
        return new moodle_url('/course/view.php', ['id' => $course->id]);
141
    }
142
 
143
    /**
144
     * Returns the information about the ajax support in the given source format
145
     *
146
     * The returned object's property (boolean)capable indicates that
147
     * the course format supports Moodle course ajax features.
148
     *
149
     * @return stdClass
150
     */
151
    public function supports_ajax() {
152
        $ajaxsupport = new stdClass();
153
        $ajaxsupport->capable = true;
154
        return $ajaxsupport;
155
    }
156
 
157
    public function supports_components() {
158
        return true;
159
    }
160
 
161
    /**
162
     * Loads all of the course sections into the navigation
163
     *
164
     * @param global_navigation $navigation
165
     * @param navigation_node $node The course node within the navigation
166
     */
167
    public function extend_course_navigation($navigation, navigation_node $node) {
168
        global $PAGE;
169
        // if section is specified in course/view.php, make sure it is expanded in navigation
170
        if ($navigation->includesectionnum === false) {
171
            $selectedsection = optional_param('section', null, PARAM_INT);
172
            if ($selectedsection !== null && (!defined('AJAX_SCRIPT') || AJAX_SCRIPT == '0') &&
173
                    $PAGE->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
174
                $navigation->includesectionnum = $selectedsection;
175
            }
176
        }
177
        parent::extend_course_navigation($navigation, $node);
178
 
179
        // We want to remove the general section if it is empty.
180
        $modinfo = get_fast_modinfo($this->get_course());
181
        $sections = $modinfo->get_sections();
182
        if (!isset($sections[0])) {
183
            // The general section is empty to find the navigation node for it we need to get its ID.
184
            $section = $modinfo->get_section_info(0);
185
            $generalsection = $node->get($section->id, navigation_node::TYPE_SECTION);
186
            if ($generalsection) {
187
                // We found the node - now remove it.
188
                $generalsection->remove();
189
            }
190
        }
191
    }
192
 
193
    /**
194
     * Custom action after section has been moved in AJAX mode
195
     *
196
     * Used in course/rest.php
197
     *
198
     * @return array This will be passed in ajax respose
199
     */
200
    function ajax_section_move() {
201
        global $PAGE;
202
        $titles = array();
203
        $current = -1;
204
        $course = $this->get_course();
205
        $modinfo = get_fast_modinfo($course);
206
        $renderer = $this->get_renderer($PAGE);
207
        if ($renderer && ($sections = $modinfo->get_section_info_all())) {
208
            foreach ($sections as $number => $section) {
209
                $titles[$number] = $renderer->section_title($section, $course);
210
                if ($this->is_section_current($section)) {
211
                    $current = $number;
212
                }
213
            }
214
        }
215
        return array('sectiontitles' => $titles, 'current' => $current, 'action' => 'move');
216
    }
217
 
218
    /**
219
     * Returns the list of blocks to be automatically added for the newly created course
220
     *
221
     * @return array of default blocks, must contain two keys BLOCK_POS_LEFT and BLOCK_POS_RIGHT
222
     *     each of values is an array of block names (for left and right side columns)
223
     */
224
    public function get_default_blocks() {
225
        return array(
226
            BLOCK_POS_LEFT => array(),
227
            BLOCK_POS_RIGHT => array()
228
        );
229
    }
230
 
231
    /**
232
     * Definitions of the additional options that this course format uses for course
233
     *
234
     * Weeks format uses the following options:
235
     * - coursedisplay
236
     * - hiddensections
237
     * - automaticenddate
238
     *
239
     * @param bool $foreditform
240
     * @return array of options
241
     */
242
    public function course_format_options($foreditform = false) {
243
        static $courseformatoptions = false;
244
        if ($courseformatoptions === false) {
245
            $courseconfig = get_config('moodlecourse');
246
            $courseformatoptions = array(
247
                'hiddensections' => array(
248
                    'default' => $courseconfig->hiddensections,
249
                    'type' => PARAM_INT,
250
                ),
251
                'coursedisplay' => array(
252
                    'default' => $courseconfig->coursedisplay ?? COURSE_DISPLAY_SINGLEPAGE,
253
                    'type' => PARAM_INT,
254
                ),
255
                'automaticenddate' => array(
256
                    'default' => 1,
257
                    'type' => PARAM_BOOL,
258
                ),
259
            );
260
        }
261
        if ($foreditform && !isset($courseformatoptions['coursedisplay']['label'])) {
262
            $courseformatoptionsedit = array(
263
                'hiddensections' => array(
264
                    'label' => new lang_string('hiddensections'),
265
                    'help' => 'hiddensections',
266
                    'help_component' => 'moodle',
267
                    'element_type' => 'select',
268
                    'element_attributes' => array(
269
                        array(
270
 
271
                            1 => new lang_string('hiddensectionsinvisible')
272
                        )
273
                    ),
274
                ),
275
                'coursedisplay' => array(
276
                    'label' => new lang_string('coursedisplay'),
277
                    'element_type' => 'select',
278
                    'element_attributes' => array(
279
                        array(
280
                            COURSE_DISPLAY_SINGLEPAGE => new lang_string('coursedisplay_single'),
281
                            COURSE_DISPLAY_MULTIPAGE => new lang_string('coursedisplay_multi')
282
                        )
283
                    ),
284
                    'help' => 'coursedisplay',
285
                    'help_component' => 'moodle',
286
                ),
287
                'automaticenddate' => array(
288
                    'label' => new lang_string('automaticenddate', 'format_weeks'),
289
                    'help' => 'automaticenddate',
290
                    'help_component' => 'format_weeks',
291
                    'element_type' => 'advcheckbox',
292
                )
293
            );
294
            $courseformatoptions = array_merge_recursive($courseformatoptions, $courseformatoptionsedit);
295
        }
296
        return $courseformatoptions;
297
    }
298
 
299
    /**
300
     * Adds format options elements to the course/section edit form.
301
     *
302
     * This function is called from {@link course_edit_form::definition_after_data()}.
303
     *
304
     * @param MoodleQuickForm $mform form the elements are added to.
305
     * @param bool $forsection 'true' if this is a section edit form, 'false' if this is course edit form.
306
     * @return array array of references to the added form elements.
307
     */
308
    public function create_edit_form_elements(&$mform, $forsection = false) {
309
        global $COURSE;
310
        $elements = parent::create_edit_form_elements($mform, $forsection);
311
 
312
        if (!$forsection && (empty($COURSE->id) || $COURSE->id == SITEID)) {
313
            // Add "numsections" element to the create course form - it will force new course to be prepopulated
314
            // with empty sections.
315
            // The "Number of sections" option is no longer available when editing course, instead teachers should
316
            // delete and add sections when needed.
317
            $courseconfig = get_config('moodlecourse');
318
            $max = (int)$courseconfig->maxsections;
319
            $element = $mform->addElement('select', 'numsections', get_string('numberweeks'), range(0, $max ?: 52));
320
            $mform->setType('numsections', PARAM_INT);
321
            if (is_null($mform->getElementValue('numsections'))) {
322
                $mform->setDefault('numsections', $courseconfig->numsections);
323
            }
324
            array_unshift($elements, $element);
325
        }
326
 
327
        // Re-order things.
328
        $mform->insertElementBefore($mform->removeElement('automaticenddate', false), 'idnumber');
329
        $mform->disabledIf('enddate', 'automaticenddate', 'checked');
330
        foreach ($elements as $key => $element) {
331
            if ($element->getName() == 'automaticenddate') {
332
                unset($elements[$key]);
333
            }
334
        }
335
 
336
        return $elements;
337
    }
338
 
339
    /**
340
     * Updates format options for a course
341
     *
342
     * In case if course format was changed to 'weeks', we try to copy options
343
     * 'coursedisplay', 'numsections' and 'hiddensections' from the previous format.
344
     * If previous course format did not have 'numsections' option, we populate it with the
345
     * current number of sections
346
     *
347
     * @param stdClass|array $data return value from {@link moodleform::get_data()} or array with data
348
     * @param stdClass $oldcourse if this function is called from {@link update_course()}
349
     *     this object contains information about the course before update
350
     * @return bool whether there were any changes to the options values
351
     */
352
    public function update_course_format_options($data, $oldcourse = null) {
353
        global $DB;
354
        $data = (array)$data;
355
        if ($oldcourse !== null) {
356
            $oldcourse = (array)$oldcourse;
357
            $options = $this->course_format_options();
358
            foreach ($options as $key => $unused) {
359
                if (!array_key_exists($key, $data)) {
360
                    if (array_key_exists($key, $oldcourse)) {
361
                        $data[$key] = $oldcourse[$key];
362
                    }
363
                }
364
            }
365
        }
366
        return $this->update_format_options($data);
367
    }
368
 
369
    /**
370
     * Return the start and end date of the passed section
371
     *
372
     * @param int|stdClass|section_info $section section to get the dates for
373
     * @param int $startdate Force course start date, useful when the course is not yet created
374
     * @return stdClass property start for startdate, property end for enddate
375
     */
376
    public function get_section_dates($section, $startdate = false) {
377
        global $USER;
378
 
379
        if ($startdate === false) {
380
            $course = $this->get_course();
381
            $userdates = course_get_course_dates_for_user_id($course, $USER->id);
382
            $startdate = $userdates['start'];
383
        }
384
 
385
        if (is_object($section)) {
386
            $sectionnum = $section->section;
387
        } else {
388
            $sectionnum = $section;
389
        }
390
 
391
        // Create a DateTime object for the start date.
392
        $startdateobj = new DateTime("@$startdate");
393
        $startdateobj->setTimezone(core_date::get_user_timezone_object());
394
 
395
        // Calculate the interval for one week.
396
        $oneweekinterval = new DateInterval('P7D');
397
 
398
        // Calculate the interval for the specified number of sections.
399
        for ($i = 1; $i < $sectionnum; $i++) {
400
            $startdateobj->add($oneweekinterval);
401
        }
402
 
403
        // Calculate the end date.
404
        $enddateobj = clone $startdateobj;
405
        $enddateobj->add($oneweekinterval);
406
 
407
        $dates = new stdClass();
408
        $dates->start = $startdateobj->getTimestamp();
409
        $dates->end = $enddateobj->getTimestamp();
410
 
411
        return $dates;
412
    }
413
 
414
    /**
415
     * Returns true if the specified week is current
416
     *
417
     * @param int|stdClass|section_info $section
418
     * @return bool
419
     */
420
    public function is_section_current($section) {
421
        if (is_object($section)) {
422
            $sectionnum = $section->section;
423
        } else {
424
            $sectionnum = $section;
425
        }
426
        if ($sectionnum < 1) {
427
            return false;
428
        }
429
        $timenow = time();
430
        $dates = $this->get_section_dates($section);
431
        return (($timenow >= $dates->start) && ($timenow < $dates->end));
432
    }
433
 
434
    /**
435
     * Whether this format allows to delete sections
436
     *
437
     * Do not call this function directly, instead use {@link course_can_delete_section()}
438
     *
439
     * @param int|stdClass|section_info $section
440
     * @return bool
441
     */
442
    public function can_delete_section($section) {
443
        return true;
444
    }
445
 
446
    /**
447
     * Returns the default end date for weeks course format.
448
     *
449
     * @param moodleform $mform
450
     * @param array $fieldnames The form - field names mapping.
451
     * @return int
452
     */
453
    public function get_default_course_enddate($mform, $fieldnames = array()) {
454
 
455
        if (empty($fieldnames['startdate'])) {
456
            $fieldnames['startdate'] = 'startdate';
457
        }
458
 
459
        if (empty($fieldnames['numsections'])) {
460
            $fieldnames['numsections'] = 'numsections';
461
        }
462
 
463
        $startdate = $this->get_form_start_date($mform, $fieldnames);
464
        if ($mform->elementExists($fieldnames['numsections'])) {
465
            $numsections = $mform->getElementValue($fieldnames['numsections']);
466
            $numsections = $mform->getElement($fieldnames['numsections'])->exportValue($numsections);
467
        } else if ($this->get_courseid()) {
468
            // For existing courses get the number of sections.
469
            $numsections = $this->get_last_section_number();
470
        } else {
471
            // Fallback to the default value for new courses.
472
            $numsections = get_config('moodlecourse', $fieldnames['numsections']);
473
        }
474
 
475
        // Final week's last day.
476
        $dates = $this->get_section_dates(intval($numsections), $startdate);
477
        return $dates->end;
478
    }
479
 
480
    /**
481
     * Indicates whether the course format supports the creation of a news forum.
482
     *
483
     * @return bool
484
     */
485
    public function supports_news() {
486
        return true;
487
    }
488
 
489
    /**
490
     * Returns whether this course format allows the activity to
491
     * have "triple visibility state" - visible always, hidden on course page but available, hidden.
492
     *
493
     * @param stdClass|cm_info $cm course module (may be null if we are displaying a form for adding a module)
494
     * @param stdClass|section_info $section section where this module is located or will be added to
495
     * @return bool
496
     */
497
    public function allow_stealth_module_visibility($cm, $section) {
498
        // Allow the third visibility state inside visible sections or in section 0.
499
        return !$section->section || $section->visible;
500
    }
501
 
502
    public function section_action($section, $action, $sr) {
503
        global $PAGE;
504
 
505
        // Call the parent method and return the new content for .section_availability element.
506
        $rv = parent::section_action($section, $action, $sr);
507
        $renderer = $PAGE->get_renderer('format_weeks');
508
 
509
        if (!($section instanceof section_info)) {
510
            $modinfo = course_modinfo::instance($this->courseid);
511
            $section = $modinfo->get_section_info($section->section);
512
        }
513
        $elementclass = $this->get_output_classname('content\\section\\availability');
514
        $availability = new $elementclass($this, $section);
515
 
516
        $rv['section_availability'] = $renderer->render($availability);
517
 
518
        return $rv;
519
    }
520
 
521
    /**
522
     * Updates the end date for a course in weeks format if option automaticenddate is set.
523
     *
524
     * This method is called from event observers and it can not use any modinfo or format caches because
525
     * events are triggered before the caches are reset.
526
     *
527
     * @param int $courseid
528
     */
529
    public static function update_end_date($courseid) {
530
        global $DB, $COURSE;
531
 
532
        // Use one DB query to retrieve necessary fields in course, value for automaticenddate and number of the last
533
        // section. This query will also validate that the course is indeed in 'weeks' format.
534
        $insql = "SELECT c.id, c.format, c.startdate, c.enddate, MAX(s.section) AS lastsection
535
                    FROM {course} c
536
                    JOIN {course_sections} s
537
                      ON s.course = c.id
538
                   WHERE c.format = :format
539
                     AND c.id = :courseid
540
                GROUP BY c.id, c.format, c.startdate, c.enddate";
541
        $sql = "SELECT co.id, co.format, co.startdate, co.enddate, co.lastsection, fo.value AS automaticenddate
542
                  FROM ($insql) co
543
             LEFT JOIN {course_format_options} fo
544
                    ON fo.courseid = co.id
545
                   AND fo.format = co.format
546
                   AND fo.name = :optionname
547
                   AND fo.sectionid = 0";
548
        $course = $DB->get_record_sql($sql,
549
            ['optionname' => 'automaticenddate', 'format' => 'weeks', 'courseid' => $courseid]);
550
 
551
        if (!$course) {
552
            // Looks like it is a course in a different format, nothing to do here.
553
            return;
554
        }
555
 
556
        // Create an instance of this class and mock the course object.
557
        $format = new format_weeks('weeks', $courseid);
558
        $format->course = $course;
559
 
560
        // If automaticenddate is not specified take the default value.
561
        if (!isset($course->automaticenddate)) {
562
            $defaults = $format->course_format_options();
563
            $course->automaticenddate = $defaults['automaticenddate']['default'];
564
        }
565
 
566
        // Check that the course format for setting an automatic date is set.
567
        if (!empty($course->automaticenddate)) {
568
            // Get the final week's last day.
569
            $dates = $format->get_section_dates((int)$course->lastsection);
570
 
571
            // Set the course end date.
572
            if ($course->enddate != $dates->end) {
573
                $DB->set_field('course', 'enddate', $dates->end, array('id' => $course->id));
574
                if (isset($COURSE->id) && $COURSE->id == $courseid) {
575
                    $COURSE->enddate = $dates->end;
576
                }
577
            }
578
        }
579
    }
580
 
581
    /**
582
     * Return the plugin configs for external functions.
583
     *
584
     * @return array the list of configuration settings
585
     * @since Moodle 3.5
586
     */
587
    public function get_config_for_external() {
588
        // Return everything (nothing to hide).
589
        $formatoptions = $this->get_format_options();
590
        $formatoptions['indentation'] = get_config('format_weeks', 'indentation');
591
        return $formatoptions;
592
    }
593
 
594
    /**
595
     * Get the required javascript files for the course format.
596
     *
597
     * @return array The list of javascript files required by the course format.
598
     */
599
    public function get_required_jsfiles(): array {
600
        return [];
601
    }
602
}
603
 
604
/**
605
 * Implements callback inplace_editable() allowing to edit values in-place
606
 *
607
 * @param string $itemtype
608
 * @param int $itemid
609
 * @param mixed $newvalue
610
 * @return \core\output\inplace_editable
611
 */
612
function format_weeks_inplace_editable($itemtype, $itemid, $newvalue) {
613
    global $DB, $CFG;
614
    require_once($CFG->dirroot . '/course/lib.php');
615
    if ($itemtype === 'sectionname' || $itemtype === 'sectionnamenl') {
616
        $section = $DB->get_record_sql(
617
            'SELECT s.* FROM {course_sections} s JOIN {course} c ON s.course = c.id WHERE s.id = ? AND c.format = ?',
618
            array($itemid, 'weeks'), MUST_EXIST);
619
        return course_get_format($section->course)->inplace_editable_update_section_name($section, $itemtype, $newvalue);
620
    }
621
}