Proyectos de Subversion Moodle

Rev

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