Proyectos de Subversion Moodle

Rev

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