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
 * Theme functions.
19
 *
20
 * @package   theme_monocolor
21
 * @copyright 2022 - 2023 Marcin Czaja (https://rosea.io)
22
 * @license   Commercial https://themeforest.net/licenses
23
 */
24
 
25
/**
26
 * Get theme setting
27
 *
28
 * @param string $setting
29
 * @param bool $format
30
 * @return string
31
 */
32
function theme_monocolor_get_setting($setting, $format = false) {
33
    $theme = theme_config::load('monocolor');
34
 
35
    if (empty($theme->settings->$setting)) {
36
        return false;
37
    }
38
 
39
    if (!$format) {
40
        return $theme->settings->$setting;
41
    }
42
 
43
    if ($format === 'format_text') {
44
        return format_text($theme->settings->$setting, FORMAT_PLAIN);
45
    }
46
 
47
    if ($format === 'format_html') {
48
        return format_text($theme->settings->$setting, FORMAT_HTML, array('trusted' => true, 'noclean' => true));
49
    }
50
 
51
    return format_string($theme->settings->$setting);
52
}
53
 
54
/**
55
 * Post process the CSS tree.
56
 *
57
 * @param string $tree The CSS tree.
58
 * @param theme_config $theme The theme config object.
59
 */
60
function theme_monocolor_css_tree_post_processor($tree, $theme) {
61
    debugging('theme_monocolor_css_tree_post_processor() is deprecated. Required' .
62
        'prefixes for Bootstrap are now in theme/monocolor/scss/moodle/prefixes.scss');
63
    $prefixer = new theme_monocolor\autoprefixer($tree);
64
    $prefixer->prefix();
65
}
66
 
67
/**
68
 * Get the current user preferences that are available
69
 *
70
 * @return array[]
71
 */
72
function theme_monocolor_user_preferences(): array {
73
    return [
74
        'drawer-open-block' => [
75
            'type' => PARAM_BOOL,
76
            'null' => NULL_NOT_ALLOWED,
77
            'default' => false,
78
            'permissioncallback' => [core_user::class, 'is_current_user'],
79
        ],
80
        'drawer-open-index' => [
81
            'type' => PARAM_BOOL,
82
            'null' => NULL_NOT_ALLOWED,
83
            'default' => true,
84
            'permissioncallback' => [core_user::class, 'is_current_user'],
85
        ],
86
        'darkmode-on' => [
87
            'type' => PARAM_BOOL,
88
            'null' => NULL_NOT_ALLOWED,
89
            'default' => false,
90
            'permissioncallback' => [core_user::class, 'is_current_user'],
91
        ],
92
        'sidepre-open' => [
93
            'type' => PARAM_BOOL,
94
            'null' => NULL_NOT_ALLOWED,
95
            'default' => true,
96
            'permissioncallback' => [core_user::class, 'is_current_user'],
97
        ],
98
    ];
99
}
100
 
101
/**
102
 * Inject additional SCSS.
103
 *
104
 * @param theme_config $theme The theme config object.
105
 * @return string
106
 */
107
function theme_monocolor_get_extra_scss($theme) {
108
    $content = '';
109
 
110
    // Sets the login background image.
111
    // Check login layout, only layout #1 has background image.
112
    $loginlayout = theme_monocolor_get_setting('setloginlayout');
113
    $loginlayoutimg = false;
114
 
115
    if ($loginlayout == 1 || $loginlayout == 4 || $loginlayout == 5) {
116
        $loginlayoutimg = true;
117
    }
118
    if ($loginlayout == 2 || $loginlayout == 3) {
119
        $loginlayoutimg = false;
120
    } else {
121
        $loginlayoutimg = false;
122
    }
123
 
124
    $loginbackgroundimageurl = $theme->setting_file_url('loginbg', 'loginbg');
125
    if ($loginlayout == 1) {
126
        if (!empty($loginbackgroundimageurl)) {
127
            $content .= 'body.path-login { ';
128
            $content .= "background-image: url('$loginbackgroundimageurl'); background-size: cover;";
129
            $content .= ' }';
130
        }
131
    }
132
 
133
    $forcefwvideo = theme_monocolor_get_setting('forcefwvideo');
134
    if ($forcefwvideo == 1) {
135
        $content .= '.mediaplugin.mediaplugin_videojs div[style*="max-width"] {margin-left:auto;margin-right:auto;
136
            width: 100%; max-width: 100% !important;}';
137
        $content .= '.mediaplugin div {max-width:100%!important;}';
138
    }
139
 
140
    // Always return the background image with the scss when we have it.
141
    return !empty($theme->settings->scss) ? $theme->settings->scss . ' ' . $content : $content;
142
}
143
 
144
/**
145
 * Serves any files associated with the theme settings.
146
 *
147
 * @param stdClass $course
148
 * @param stdClass $cm
149
 * @param context $context
150
 * @param string $filearea
151
 * @param array $args
152
 * @param bool $forcedownload
153
 * @param array $options
154
 * @return bool
155
 */
156
function theme_monocolor_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options = array()) {
157
    if ($context->contextlevel == CONTEXT_SYSTEM) {
158
        $theme = theme_config::load('monocolor');
159
        // By default, theme files must be cache-able by both browsers and proxies.
160
        if (!array_key_exists('cacheability', $options)) {
161
            $options['cacheability'] = 'public';
162
        }
163
        if ($filearea === 'hvp') {
164
            return theme_monocolor_serve_hvp_css($args[1], $theme);
165
        }
166
        if ($filearea === 'favicon') {
167
            return $theme->setting_file_serve('favicon', $args, $forcedownload, $options);
168
        } else if ($filearea === 'logo') {
169
            return $theme->setting_file_serve('logo', $args, $forcedownload, $options);
170
        } else if ($filearea === 'loginbg') {
171
            return $theme->setting_file_serve('loginbg', $args, $forcedownload, $options);
172
        } else if ($filearea === 'customloginlogo') {
173
            return $theme->setting_file_serve('customloginlogo', $args, $forcedownload, $options);
174
        } else if ($filearea === 'customlogo') {
175
            return $theme->setting_file_serve('customlogo', $args, $forcedownload, $options);
176
        } else if ($filearea === 'customdmlogo') {
177
            return $theme->setting_file_serve('customdmlogo', $args, $forcedownload, $options);
178
        } else if ($filearea === 'customsidebarlogo') {
179
            return $theme->setting_file_serve('customsidebarlogo', $args, $forcedownload, $options);
180
        } else if ($filearea === 'customsidebardmlogo') {
181
            return $theme->setting_file_serve('customsidebardmlogo', $args, $forcedownload, $options);
182
        } else if ($filearea === 'monocolorsettingsimgs') {
183
            return $theme->setting_file_serve('monocolorsettingsimgs', $args, $forcedownload, $options);
184
        } else if (preg_match("/^block1slideimg[1-9][0-9]?$/", $filearea) !== false) {
185
            return $theme->setting_file_serve($filearea, $args, $forcedownload, $options);
186
        } else if (preg_match("/^block5itemimg[1-9][0-9]?$/", $filearea) !== false) {
187
            return $theme->setting_file_serve($filearea, $args, $forcedownload, $options);
188
        } else if ($filearea === 'block2videoposter') {
189
            return $theme->setting_file_serve('block2videoposter', $args, $forcedownload, $options);
190
        } else if ($filearea === 'block2img') {
191
            return $theme->setting_file_serve('block2img', $args, $forcedownload, $options);
192
        } else if ($filearea === 'block2videomp4') {
193
            return $theme->setting_file_serve('block2videomp4', $args, $forcedownload, $options);
194
        } else if ($filearea === 'block2videowebm') {
195
            return $theme->setting_file_serve('block2videowebm', $args, $forcedownload, $options);
196
        } else if ($filearea === 'footerbgimg') {
197
            return $theme->setting_file_serve('footerbgimg', $args, $forcedownload, $options);
198
        } else {
199
            send_file_not_found();
200
        }
201
    }
202
}
203
 
204
/**
205
 * Get the URL of files from theme settings.
206
 *
207
 * @param $setting
208
 * @param $filearea
209
 * @param $theme
210
 * @return array|false|string|string[]|null
211
 * @throws dml_exception
212
 */
213
function theme_monocolor_setting_file_url($setting, $filearea, $theme) {
214
    global $CFG;
215
 
216
    $component = 'theme_monocolor';
217
    $itemid = 0;
218
    $filepath = $theme->settings->$filearea;
219
 
220
    if (empty($filepath)) {
221
        return false;
222
    }
223
    $syscontext = context_system::instance();
224
 
225
    $url = moodle_url::make_file_url("$CFG->wwwroot/pluginfile.php", "/$syscontext->id/$component/$filearea/$itemid" . $filepath);
226
 
227
    // Now this is tricky because the we can not hardcode http or https here, lets use the relative link.
228
    // Note: unfortunately moodle_url does not support //urls yet.
229
 
230
    $url = preg_replace('|^https?://|i', '//', $url->out(false));
231
 
232
    return $url;
233
}
234
 
235
/**
236
 * Returns the main SCSS content.
237
 *
238
 * @param theme_config $theme The theme config object.
239
 * @return string
240
 */
241
function theme_monocolor_get_main_scss_content($theme) {
242
    global $CFG;
243
 
244
    $scss = '';
245
    $filename = !empty($theme->settings->preset) ? $theme->settings->preset : null;
246
    $fs = get_file_storage();
247
 
248
    $context = context_system::instance();
249
    if ($filename == 'default.scss') {
250
        $scss .= file_get_contents($CFG->dirroot . '/theme/monocolor/scss/preset/default.scss');
251
    } else if ($filename == 'plain.scss') {
252
        $scss .= file_get_contents($CFG->dirroot . '/theme/monocolor/scss/preset/plain.scss');
253
    } else if ($filename && ($presetfile = $fs->get_file($context->id, 'theme_monocolor', 'preset', 0, '/', $filename))) {
254
        $scss .= $presetfile->get_content();
255
    } else {
256
        // Safety fallback - maybe new installs etc.
257
        $scss .= file_get_contents($CFG->dirroot . '/theme/monocolor/scss/preset/default.scss');
258
    }
259
 
260
    return $scss;
261
}
262
 
263
/**
264
 * Get compiled css.
265
 *
266
 * @return string compiled css
267
 */
268
function theme_monocolor_get_precompiled_css() {
269
    global $CFG;
270
    return file_get_contents($CFG->dirroot . '/theme/monocolor/style/moodle.css');
271
}
272
 
273
/**
274
 * Get SCSS to prepend.
275
 *
276
 * @param theme_config $theme The theme config object.
277
 * @return array
278
 */
279
function theme_monocolor_get_pre_scss($theme) {
280
    global $CFG;
281
 
282
    $scss = '';
283
    $configurable = [
284
        // Config key => [variableName, ...].
285
        'colorloginbgtext' => ['colorloginbgtext'],
286
        // Blocks.
287
        'block1sliderwrapperbg' => ['block1-wrapper-bg'],
288
        'block2wrapperbg' => ['block2-wrapper-bg'],
289
        'block3wrapperbg' => ['block3-wrapper-bg'],
290
        'block4sliderwrapperbg' => ['block4-wrapper-bg'],
291
        // Customization.
292
        'fontweightheadings' => ['headings-font-weight'],
293
        'fontbody' => ['font-family-base'],
294
        'fontweightregular' => ['font-weight-normal'],
295
        'fontweightmedium' => ['font-weight-medium'],
296
        'fontweightbold' => ['font-weight-bold'],
297
        'fontheadings' => ['fontheadings'],
298
        'coursedescwidth' => ['coursedescwidth'],
299
        'incoursedescwidth' => ['incoursedescwidth'],
300
        // Text.
301
        'colorbody' => ['body-color'],
302
        'colorbodysecondary' => ['body-color-secondary'],
303
        'colorbodylight' => ['body-color-light'],
304
        'colorlink' => ['link-color'],
305
        'colorlinkhover' => ['link-color-hover'],
306
        // Grays.
307
        'white' => ['white'],
308
        'black' => ['black'],
309
        'colorgray100' => ['gray-100'],
310
        'colorgray200' => ['gray-200'],
311
        'colorgray300' => ['gray-300'],
312
        'colorgray400' => ['gray-400'],
313
        'colorgray500' => ['gray-500'],
314
        'colorgray600' => ['gray-600'],
315
        'colorgray700' => ['gray-700'],
316
        'colorgray800' => ['gray-800'],
317
        'colorgray900' => ['gray-900'],
318
        // Primary.
319
        'colorprimary100' => ['primary-color-100'],
320
        'colorprimary200' => ['primary-color-200'],
321
        'colorprimary300' => ['primary-color-300'],
322
        'colorprimary400' => ['primary-color-400'],
323
        'colorprimary500' => ['primary-color-500'],
324
        'colorprimary600' => ['primary-color-600'],
325
        'colorprimary700' => ['primary-color-700'],
326
        'colorprimary800' => ['primary-color-800'],
327
        'colorprimary900' => ['primary-color-900'],
328
        // Others.
329
        'colorbodybg' => ['body-bg'],
330
        'colorborder' => ['border-color'],
331
        // Topbar.
332
        'topbarheight' => ['navbar-height'],
333
        'colortopbarbg' => ['topbar-bg'],
334
        'colortopbartext' => ['topbar-text'],
335
        'colortopbarlink' => ['topbar-link'],
336
        'colortopbarlinkhover' => ['topbar-link-hover'],
337
        'colortopbarbtn' => ['topbar-btn'],
338
        'colortopbarbtntext' => ['topbar-btn-text'],
339
        'colortopbarbtnhover' => ['topbar-btn-hover'],
340
        'colortopbarbtnhovertext' => ['topbar-btn-hover-text'],
341
        // Buttons.
342
        'btnborderradius' => ['btn-border-radius'],
343
        // Sidebar.
344
        'colordrawerbg' => ['drawer-bg'],
345
        'colordrawertext' => ['drawer-text'],
346
        'colordrawernavcontainer' => ['drawer-nav-container'],
347
        'colordrawernavbtntext' => ['drawer-nav-btn-text'],
348
        'colordrawernavbtnicon' => ['drawer-nav-btn-icon'],
349
        'colordrawernavbtntexth' => ['drawer-nav-btn-text-hover'],
350
        'colordrawernavbtniconh' => ['drawer-nav-btn-icon-hover'],
351
        'colordrawernavbtnbgh' => ['drawer-nav-btn-bg-hover'],
352
        'colordrawernavbtntextlight' => ['drawer-nav-btn-text-light'],
353
        'colordrawerscrollbar' => ['drawer-scroll-bg-track'],
354
        'colordrawerlink' => ['drawer-link'],
355
        'colordrawerlinkh' => ['drawer-link-h'],
356
        'colordrawernavboxbg' => ['drawer-nav-box-bg'],
357
        'colordrawernavbtnicon' => ['drawer-nav-btn-icon'],
358
        // Footer.
359
        'colorfooterbg' => ['footer-bg'],
360
        'colorfooterborder' => ['footer-border'],
361
        'colorfootertext' => ['footer-text-color'],
362
        'colorfooterlink' => ['footer-link-color'],
363
        'colorfooterlinkhover' => ['footer-link-color-hover'],
364
        'colorcoursecardmask' => ['course-card-mask-color'],
365
        'showcolorcoursecardmask' => ['showcolorcoursecardmask'],
366
        // Headings.
367
        'colorheadings' => ['headings-color'],
368
        'colorgradientheading1' => ['headings-gradient-color-1'],
369
        'colorgradientheading2' => ['headings-gradient-color-2'],
370
        // Login.
371
        'loginbgcolor' => ['login-bgcolor'],
372
        // Icon Colors.
373
        'iconadministration' => ['icon-color-administraion'],
374
        'iconassessment' => ['icon-color-assessment'],
375
        'iconcolleboration' => ['icon-color-collaboration'],
376
        'iconcommunication' => ['icon-color-communication'],
377
        'iconcontent' => ['icon-color-content'],
378
        'iconinterface' => ['icon-color-interface'],
379
        // Dark mode.
380
        'dmcolorgray100' => ['dm-gray-100'],
381
        'dmcolorgray200' => ['dm-gray-200'],
382
        'dmcolorgray300' => ['dm-gray-300'],
383
        'dmcolorgray400' => ['dm-gray-400'],
384
        'dmcolorgray500' => ['dm-gray-500'],
385
        'dmcolorgray600' => ['dm-gray-600'],
386
        'dmcolorgray700' => ['dm-gray-700'],
387
        'dmcolorgray800' => ['dm-gray-800'],
388
        'dmcolorgray900' => ['dm-gray-900'],
389
        'dmcolorbody' => ['dm-body-color'],
390
        'dmcolorbodysecondary' => ['dm-body-color-secondary'],
391
        'dmcolorbodylight' => ['dm-body-color-light'],
392
        'dmcolorlink' => ['dm-link-color'],
393
        'dmcolorlinkhover' => ['dm-link-hover-color'],
394
        'dmcolorheadings' => ['dm-headings-color'],
395
        'dmcolorgradientheading1' => ['dm-headings-gradient-color-1'],
396
        'dmcolorgradientheading2' => ['dm-headings-gradient-color-2']
397
    ];
398
 
399
    // Prepend variables first.
400
    foreach ($configurable as $configkey => $targets) {
401
        $value = isset($theme->settings->{$configkey}) ? $theme->settings->{$configkey} : null;
402
        if (empty($value)) {
403
            continue;
404
        }
405
        array_map(function ($target) use (&$scss, $value) {
406
            $scss .= '$' . $target . ': ' . $value . ";\n";
407
        }, (array) $targets);
408
    }
409
 
410
    // Prepend pre-scss.
411
    if (!empty($theme->settings->scsspre)) {
412
        $scss .= $theme->settings->scsspre;
413
    }
414
 
415
    return $scss;
416
}
417
 
418
/**
419
 * Build the guest access hint HTML code.
420
 *
421
 * @param int $courseid The course ID.
422
 * @return string.
423
 */
424
function theme_monocolor_get_course_guest_access_hint($courseid) {
425
    global $CFG;
426
    require_once($CFG->dirroot . '/enrol/self/lib.php');
427
 
428
    $html = '';
429
    $instances = enrol_get_instances($courseid, true);
430
    $plugins = enrol_get_plugins(true);
431
    foreach ($instances as $instance) {
432
        if (!isset($plugins[$instance->enrol])) {
433
            continue;
434
        }
435
        $plugin = $plugins[$instance->enrol];
436
        if ($plugin->show_enrolme_link($instance)) {
437
            $html = html_writer::tag('div', get_string(
438
                'showhintcourseguestaccesslink',
439
                'theme_monocolor',
440
                array('url' => $CFG->wwwroot . '/enrol/index.php?id=' . $courseid)
441
            ));
442
            break;
443
        }
444
    }
445
 
446
    return $html;
447
}
448
 
449
/**
450
 * Build the course page information banners HTML code.
451
 * This function evaluates and composes all information banners which may appear on a course page below the full header.
452
 *
453
 * @return string.
454
 */
455
function theme_monocolor_get_course_information_banners() {
456
    global $CFG, $COURSE, $PAGE, $USER, $OUTPUT;
457
 
458
    // Require user library.
459
    require_once($CFG->dirroot . '/user/lib.php');
460
 
461
    // Initialize HTML code.
462
    $html = '';
463
 
464
    // Check if user is admin, teacher or editing teacher.
465
    if (
466
        user_has_role_assignment($USER->id, '1') ||
467
        user_has_role_assignment($USER->id, '2') ||
468
        user_has_role_assignment($USER->id, '3') ||
469
        user_has_role_assignment($USER->id, '4')
470
    ) {
471
        $allowtoshowhint = true;
472
    } else {
473
        $allowtoshowhint = false;
474
    }
475
 
476
    // If the setting showhintcoursehidden is set and the visibility of the course is hidden and
477
    // a hint for the visibility will be shown.
478
    if (
479
        get_config('theme_monocolor', 'showhintcoursehidden') == 1
480
        && $allowtoshowhint == true
481
        && $PAGE->has_set_url()
482
        && $PAGE->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)
483
        && $COURSE->visible == false
484
    ) {
485
 
486
        // Prepare template context.
487
        $templatecontext = array('courseid' => $COURSE->id);
488
 
489
        // If the user has the capability to change the course settings, an additional link to the course settings is shown.
490
        if (has_capability('moodle/course:update', context_course::instance($COURSE->id))) {
491
            $templatecontext['showcoursesettingslink'] = true;
492
        } else {
493
            $templatecontext['showcoursesettingslink'] = false;
494
        }
495
 
496
        // Render template and add it to HTML code.
497
        $html .= $OUTPUT->render_from_template('theme_monocolor/course-hint-hidden', $templatecontext);
498
    }
499
 
500
    // If the setting showhintcourseguestaccess is set and the user is accessing the course with guest access,
501
    // a hint for users is shown.
502
    // We also check that the user did not switch the role. This is a special case for roles that can fully access the course
503
    // without being enrolled. A role switch would show the guest access hint additionally in that case and this is not
504
    // intended.
505
    if (
506
        get_config('theme_monocolor', 'showhintcourseguestaccess') == 1
507
        && is_guest(\context_course::instance($COURSE->id), $USER->id)
508
        && $PAGE->has_set_url()
509
        && $PAGE->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)
510
        && !is_role_switched($COURSE->id)
511
    ) {
512
 
513
        // Require self enrolment library.
514
        require_once($CFG->dirroot . '/enrol/self/lib.php');
515
 
516
        // Prepare template context.
517
        $templatecontext = array(
518
            'courseid' => $COURSE->id,
519
            'role' => role_get_name(get_guest_role())
520
        );
521
 
522
        // Search for an available self enrolment link in this course.
523
        $templatecontext['showselfenrollink'] = false;
524
        $instances = enrol_get_instances($COURSE->id, true);
525
        $plugins = enrol_get_plugins(true);
526
        foreach ($instances as $instance) {
527
            // If the enrolment plugin isn't enabled currently, skip it.
528
            if (!isset($plugins[$instance->enrol])) {
529
                continue;
530
            }
531
 
532
            // Remember the enrolment plugin.
533
            $plugin = $plugins[$instance->enrol];
534
 
535
            // If there is a self enrolment link.
536
            if ($plugin->show_enrolme_link($instance)) {
537
                $templatecontext['showselfenrollink'] = true;
538
                break;
539
            }
540
        }
541
 
542
        // Render template and add it to HTML code.
543
        $html .= $OUTPUT->render_from_template('theme_monocolor/course-hint-guestaccess', $templatecontext);
544
    }
545
 
546
    // If the setting showhintcourseselfenrol is set, a hint for users is shown that the course allows unrestricted self
547
    // enrolment. This hint is only shown if the course is visible, the self enrolment is visible and if the user has the
548
    // capability "theme/space:viewhintcourseselfenrol".
549
    if (
550
        get_config('theme_monocolor', 'showhintcourseselfenrol') == 1
551
        && $allowtoshowhint == true
552
        && $PAGE->has_set_url()
553
        && $PAGE->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)
554
        && $COURSE->visible == true
555
    ) {
556
 
557
        // Get the active enrol instances for this course.
558
        $enrolinstances = enrol_get_instances($COURSE->id, true);
559
 
560
        // Prepare to remember when self enrolment is / will be possible.
561
        $selfenrolmentpossiblecurrently = false;
562
        $selfenrolmentpossiblefuture = false;
563
        foreach ($enrolinstances as $instance) {
564
            // Check if unrestricted self enrolment is possible currently or in the future.
565
            $now = (new \DateTime("now", \core_date::get_server_timezone_object()))->getTimestamp();
566
            if (
567
                $instance->enrol == 'self' && empty($instance->password) && $instance->customint6 == 1 &&
568
                (empty($instance->enrolenddate) || $instance->enrolenddate > $now)
569
            ) {
570
 
571
                // Build enrol instance object with all necessary information for rendering the note later.
572
                $instanceobject = new stdClass();
573
 
574
                // Remember instance name.
575
                if (empty($instance->name)) {
576
                    $instanceobject->name = get_string('pluginname', 'enrol_self') .
577
                        " (" . get_string('defaultcoursestudent', 'core') . ")";
578
                } else {
579
                    $instanceobject->name = $instance->name;
580
                }
581
 
582
                // Remember type of unrestrictedness.
583
                if (empty($instance->enrolenddate) && empty($instance->enrolstartdate)) {
584
                    $instanceobject->unrestrictedness = 'unlimited';
585
                    $selfenrolmentpossiblecurrently = true;
586
                } else if (
587
                    empty($instance->enrolstartdate) &&
588
                    !empty($instance->enrolenddate) && $instance->enrolenddate > $now
589
                ) {
590
                    $instanceobject->unrestrictedness = 'until';
591
                    $selfenrolmentpossiblecurrently = true;
592
                } else if (
593
                    empty($instance->enrolenddate) &&
594
                    !empty($instance->enrolstartdate) && $instance->enrolstartdate > $now
595
                ) {
596
                    $instanceobject->unrestrictedness = 'from';
597
                    $selfenrolmentpossiblefuture = true;
598
                } else if (
599
                    empty($instance->enrolenddate) &&
600
                    !empty($instance->enrolstartdate) && $instance->enrolstartdate <= $now
601
                ) {
602
                    $instanceobject->unrestrictedness = 'since';
603
                    $selfenrolmentpossiblecurrently = true;
604
                } else if (
605
                    !empty($instance->enrolstartdate) && $instance->enrolstartdate > $now &&
606
                    !empty($instance->enrolenddate) && $instance->enrolenddate > $now
607
                ) {
608
                    $instanceobject->unrestrictedness = 'fromuntil';
609
                    $selfenrolmentpossiblefuture = true;
610
                } else if (
611
                    !empty($instance->enrolstartdate) && $instance->enrolstartdate <= $now &&
612
                    !empty($instance->enrolenddate) && $instance->enrolenddate > $now
613
                ) {
614
                    $instanceobject->unrestrictedness = 'sinceuntil';
615
                    $selfenrolmentpossiblecurrently = true;
616
                } else {
617
                    // This should not happen, thus continue to next instance.
618
                    continue;
619
                }
620
 
621
                // Remember enrol start date.
622
                if (!empty($instance->enrolstartdate)) {
623
                    $instanceobject->startdate = $instance->enrolstartdate;
624
                } else {
625
                    $instanceobject->startdate = null;
626
                }
627
 
628
                // Remember enrol end date.
629
                if (!empty($instance->enrolenddate)) {
630
                    $instanceobject->enddate = $instance->enrolenddate;
631
                } else {
632
                    $instanceobject->enddate = null;
633
                }
634
 
635
                // Remember this instance.
636
                $selfenrolinstances[$instance->id] = $instanceobject;
637
            }
638
        }
639
 
640
        // If there is at least one unrestricted enrolment instance,
641
        // show the hint with information about each unrestricted active self enrolment in the course.
642
        if (
643
            !empty($selfenrolinstances) &&
644
            ($selfenrolmentpossiblecurrently == true || $selfenrolmentpossiblefuture == true)
645
        ) {
646
 
647
            // Prepare template context.
648
            $templatecontext = array();
649
 
650
            // Add the start of the hint t the template context
651
            // depending on the fact if enrolment is already possible currently or will be in the future.
652
            if ($selfenrolmentpossiblecurrently == true) {
653
                $templatecontext['selfenrolhintstart'] = get_string('showhintcourseselfenrolstartcurrently', 'theme_monocolor');
654
            } else if ($selfenrolmentpossiblefuture == true) {
655
                $templatecontext['selfenrolhintstart'] = get_string('showhintcourseselfenrolstartfuture', 'theme_monocolor');
656
            }
657
 
658
            // Iterate over all enrolment instances to output the details.
659
            foreach ($selfenrolinstances as $selfenrolinstanceid => $selfenrolinstanceobject) {
660
                // If the user has the capability to config self enrolments, enrich the instance name with the settings link.
661
                if (has_capability('enrol/self:config', \context_course::instance($COURSE->id))) {
662
                    $url = new moodle_url('/enrol/editinstance.php', array(
663
                        'courseid' => $COURSE->id,
664
                        'id' => $selfenrolinstanceid, 'type' => 'self'
665
                    ));
666
                    $selfenrolinstanceobject->name = html_writer::link($url, $selfenrolinstanceobject->name);
667
                }
668
 
669
                // Add the enrolment instance information to the template context depending on the instance configuration.
670
                if ($selfenrolinstanceobject->unrestrictedness == 'unlimited') {
671
                    $templatecontext['selfenrolinstances'][] = get_string(
672
                        'showhintcourseselfenrolunlimited',
673
                        'theme_monocolor',
674
                        array('name' => $selfenrolinstanceobject->name)
675
                    );
676
                } else if ($selfenrolinstanceobject->unrestrictedness == 'until') {
677
                    $templatecontext['selfenrolinstances'][] = get_string(
678
                        'showhintcourseselfenroluntil',
679
                        'theme_monocolor',
680
                        array(
681
                            'name' => $selfenrolinstanceobject->name,
682
                            'until' => userdate($selfenrolinstanceobject->enddate)
683
                        )
684
                    );
685
                } else if ($selfenrolinstanceobject->unrestrictedness == 'from') {
686
                    $templatecontext['selfenrolinstances'][] = get_string(
687
                        'showhintcourseselfenrolfrom',
688
                        'theme_monocolor',
689
                        array(
690
                            'name' => $selfenrolinstanceobject->name,
691
                            'from' => userdate($selfenrolinstanceobject->startdate)
692
                        )
693
                    );
694
                } else if ($selfenrolinstanceobject->unrestrictedness == 'since') {
695
                    $templatecontext['selfenrolinstances'][] = get_string(
696
                        'showhintcourseselfenrolsince',
697
                        'theme_monocolor',
698
                        array(
699
                            'name' => $selfenrolinstanceobject->name,
700
                            'since' => userdate($selfenrolinstanceobject->startdate)
701
                        )
702
                    );
703
                } else if ($selfenrolinstanceobject->unrestrictedness == 'fromuntil') {
704
                    $templatecontext['selfenrolinstances'][] = get_string(
705
                        'showhintcourseselfenrolfromuntil',
706
                        'theme_monocolor',
707
                        array(
708
                            'name' => $selfenrolinstanceobject->name,
709
                            'until' => userdate($selfenrolinstanceobject->enddate),
710
                            'from' => userdate($selfenrolinstanceobject->startdate)
711
                        )
712
                    );
713
                } else if ($selfenrolinstanceobject->unrestrictedness == 'sinceuntil') {
714
                    $templatecontext['selfenrolinstances'][] = get_string(
715
                        'showhintcourseselfenrolsinceuntil',
716
                        'theme_monocolor',
717
                        array(
718
                            'name' => $selfenrolinstanceobject->name,
719
                            'until' => userdate($selfenrolinstanceobject->enddate),
720
                            'since' => userdate($selfenrolinstanceobject->startdate)
721
                        )
722
                    );
723
                }
724
            }
725
 
726
            // If the user has the capability to config self enrolments, add the call for action to the template context.
727
            if (has_capability('enrol/self:config', \context_course::instance($COURSE->id))) {
728
                $templatecontext['calltoaction'] = true;
729
            } else {
730
                $templatecontext['calltoaction'] = false;
731
            }
732
 
733
            // Render template and add it to HTML code.
734
            $html .= $OUTPUT->render_from_template('theme_monocolor/course-hint-selfenrol', $templatecontext);
735
        }
736
    }
737
 
738
    // If the setting showswitchedroleincourse is set and the user has switched his role,
739
    // a hint for the role switch will be shown.
740
    if (
741
        get_config('theme_monocolor', 'showswitchedroleincourse') == 1
742
        && is_role_switched($COURSE->id)
743
    ) {
744
 
745
        // Get the role name switched to.
746
        $opts = \user_get_user_navigation_info($USER, $PAGE);
747
        $role = $opts->metadata['rolename'];
748
 
749
        // Get the URL to switch back (normal role).
750
        $url = new moodle_url(
751
            '/course/switchrole.php',
752
            array(
753
                'id' => $COURSE->id,
754
                'sesskey' => sesskey(),
755
                'switchrole' => 0,
756
                'returnurl' => $PAGE->url->out_as_local_url(false)
757
            )
758
        );
759
 
760
        // Prepare template context.
761
        $templatecontext = array(
762
            'role' => $role,
763
            'url' => $url->out()
764
        );
765
 
766
        // Render template and add it to HTML code.
767
        $html .= $OUTPUT->render_from_template('theme_monocolor/course-hint-switchedrole', $templatecontext);
768
    }
769
 
770
    // Return HTML code.
771
    return $html;
772
}
773
 
774
/**
775
 * Serves the H5P Custom CSS.
776
 *
777
 * @param string $filename The filename.
778
 * @param theme_config $theme The theme config object.
779
 *
780
 * @throws dml_exception
781
 */
782
function theme_monocolor_serve_hvp_css($filename, $theme) {
783
    global $CFG, $PAGE;
784
 
785
    require_once($CFG->dirroot . '/lib/configonlylib.php'); // For min_enable_zlib_compression.
786
 
787
    $PAGE->set_context(context_system::instance());
788
    $themename = $theme->name;
789
 
790
    $settings = new \theme_monocolor\util\theme_settings();
791
    $content = $settings->hvpcss;
792
 
793
    $md5content = md5($content);
794
    $md5stored = get_config('theme_monocolor', 'hvpccssmd5');
795
    if ((empty($md5stored)) || ($md5stored != $md5content)) {
796
        // Content changed, so the last modified time needs to change.
797
        set_config('hvpccssmd5', $md5content, $themename);
798
        $lastmodified = time();
799
        set_config('hvpccsslm', $lastmodified, $themename);
800
    } else {
801
        $lastmodified = get_config($themename, 'hvpccsslm');
802
        if (empty($lastmodified)) {
803
            $lastmodified = time();
804
        }
805
    }
806
 
807
    // Sixty days only - the revision may get incremented quite often.
808
    $lifetime = 60 * 60 * 24 * 60;
809
 
810
    header('HTTP/1.1 200 OK');
811
 
812
    header('Etag: "' . $md5content . '"');
813
    header('Content-Disposition: inline; filename="' . $filename . '"');
814
    header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $lastmodified) . ' GMT');
815
    header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $lifetime) . ' GMT');
816
    header('Pragma: ');
817
    header('Cache-Control: public, max-age=' . $lifetime);
818
    header('Accept-Ranges: none');
819
    header('Content-Type: text/css; charset=utf-8');
820
    if (!min_enable_zlib_compression()) {
821
        header('Content-Length: ' . strlen($content));
822
    }
823
 
824
    echo $content;
825
 
826
    die;
827
}
828
 
829
/**
830
 * Return the files from the customfonts file area as templatecontext structure.
831
 * It was designed to compose the files for the settings-customfonts-filelist.mustache template.
832
 * This function always loads the files from the filearea which is not really performant.
833
 * Thus, you have to take care where and how often you use it (or add some caching).
834
 *
835
 * @return array|null
836
 * @throws coding_exception
837
 * @throws dml_exception
838
 * Credits: Boost_Union
839
 */
840
function theme_monocolor_get_customfonts_templatecontext() {
841
    global $OUTPUT;
842
 
843
    // Static variable to remember the files for subsequent calls of this function.
844
    static $filesforcontext = null;
845
 
846
    if ($filesforcontext == null) {
847
        // Get the system context.
848
        $systemcontext = \context_system::instance();
849
 
850
        // Get filearea.
851
        $fs = get_file_storage();
852
 
853
        // Get all files from filearea.
854
        $files = $fs->get_area_files($systemcontext->id, 'theme_monocolor', 'fontfiles', false, 'itemid', false);
855
 
856
        // Get the webfonts extensions list.
857
        $webfonts = theme_monocolor_get_webfonts_extensions();
858
 
859
        // Iterate over the files.
860
        $filesforcontext = [];
861
        foreach ($files as $af) {
862
            // Get the filename.
863
            $filename = $af->get_filename();
864
 
865
            // Check if the file is really a font file (as we can't really rely on the upload restriction in settings.php)
866
            // according to its file suffix (as the filetype might not have a known mimetype).
867
            // If it isn't a font file, skip it.
868
            $filenamesuffix = pathinfo($filename, PATHINFO_EXTENSION);
869
            if (!in_array('.'.$filenamesuffix, $webfonts)) {
870
                continue;
871
            }
872
 
873
            // Otherwise, fill the templatecontext of the file list.
874
            $urlpersistent = new moodle_url('/pluginfile.php/1/theme_monocolor/fontfiles/0/'.$filename);
875
            $filesforcontext[] = ['filename' => $filename,
876
                    'fileurlpersistent' => $urlpersistent->out(), ];
877
        }
878
    }
879
 
880
    return $filesforcontext;
881
}
882
 
883
/**
884
 * Helper function which returns an array of accepted webfonts extensions (including the dots).
885
 *
886
 * @return array
887
 * Credits: Boost_Union
888
 */
889
function theme_monocolor_get_webfonts_extensions() {
890
    return ['.eot', '.otf', '.svg', '.ttf', '.woff', '.woff2'];
891
}
892
 
893
/**
894
 * Helper function which makes sure that all webfont file types are registered in the system.
895
 * The webfont file types need to be registered in the system, otherwise the admin settings filepicker wouldn't allow restricting
896
 * the uploadable file types to webfonts only.
897
 *
898
 * Please note: If custom filetypes are defined in config.php, registering additional filetypes is not possible
899
 * due to a restriction in the set_custom_types() function in Moodle core. In this case, this function does not
900
 * register anything and will return false.
901
 *
902
 * @return boolean true if the filetypes were registered, false if not.
903
 * @throws coding_exception
904
 * Credits: Boost_Union
905
 */
906
function theme_monocolor_register_webfonts_filetypes() {
907
    global $CFG;
908
 
909
    // If customfiletypes are set in config.php or PHP tests are running, we can't do anything.
910
    if (array_key_exists('customfiletypes', $CFG->config_php_settings) || PHPUNIT_TEST) {
911
        return false;
912
    }
913
 
914
    // Our array of webfont file types to register.
915
    // As we want to keep things simple, we do not set a particular icon for these file types.
916
    // Likewise, we do not set any type groups or use descriptions from the language pack.
917
    $webfonts = [
918
            'eot' => [
919
                    'extension' => 'eot',
920
                    'mimetype' => 'application/vnd.ms-fontobject',
921
                    'coreicon' => 'unknown',
922
            ],
923
            'otf' => [
924
                    'extension' => 'otf',
925
                    'mimetype' => 'font/otf',
926
                    'coreicon' => 'unknown',
927
            ],
928
            'svg' => [
929
                    'extension' => 'svg',
930
                    'mimetype' => 'image/svg+xml',
931
                    'coreicon' => 'unknown',
932
            ],
933
            'ttf' => [
934
                    'extension' => 'ttf',
935
                    'mimetype' => 'font/ttf',
936
                    'coreicon' => 'unknown',
937
            ],
938
            'woff' => [
939
                    'extension' => 'woff',
940
                    'mimetype' => 'font/woff',
941
                    'coreicon' => 'unknown',
942
            ],
943
            'woff2' => [
944
                    'extension' => 'woff2',
945
                    'mimetype' => 'font/woff2',
946
                    'coreicon' => 'unknown',
947
            ],
948
    ];
949
 
950
    // First, get the list of currently registered file types.
951
    $currenttypes = core_filetypes::get_types();
952
 
953
    // Iterate over the webfonts file types.
954
    foreach ($webfonts as $f) {
955
        // If the file type is already registered, skip it.
956
        if (array_key_exists($f['extension'], $currenttypes)) {
957
            continue;
958
        }
959
 
960
        // Otherwise, register the file type.
961
        core_filetypes::add_type($f['extension'], $f['mimetype'], $f['coreicon']);
962
    }
963
 
964
    return true;
965
}