Proyectos de Subversion Moodle

Rev

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