-
Notifications
You must be signed in to change notification settings - Fork 58
/
locallib.php
2414 lines (2062 loc) · 96.9 KB
/
locallib.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Theme Boost Union - Local library
*
* @package theme_boost_union
* @copyright 2022 Alexander Bias, lern.link GmbH <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
use core\di;
use core\hook\manager as hook_manager;
/**
* Build the course related hints HTML code.
* This function evaluates and composes all course related hints which may appear on a course page below the course header.
*
* @copyright 2022 Alexander Bias, lern.link GmbH <[email protected]>
* @copyright based on code from theme_boost_campus by Kathrin Osswald.
*
* @return string.
*/
function theme_boost_union_get_course_related_hints() {
global $CFG, $COURSE, $PAGE, $USER, $OUTPUT;
// Require user library.
require_once($CFG->dirroot.'/user/lib.php');
// Initialize HTML code.
$html = '';
// If the setting showhintcoursehidden is set and the visibility of the course is hidden
// a hint for the visibility will be shown.
if (get_config('theme_boost_union', 'showhintcoursehidden') == THEME_BOOST_UNION_SETTING_SELECT_YES
&& has_capability('theme/boost_union:viewhintinhiddencourse', \context_course::instance($COURSE->id))
&& $PAGE->has_set_url()
&& $COURSE->visible == false) {
// Initialize hint text.
$hintcoursehiddentext = '';
// The general hint will only be shown when the course is viewed.
if ($PAGE->url->compare(new core\url('/course/view.php'), URL_MATCH_BASE)) {
// Use the default hint text for hidden courses.
$hintcoursehiddentext = get_string('showhintcoursehiddengeneral', 'theme_boost_union');
}
// If the setting showhintcoursehiddennotifications is set too and we view a forum (e.g. announcement) within a hidden
// course a hint will be shown that no notifications via forums will be sent out to students.
if (get_config('theme_boost_union', 'showhintforumnotifications') == THEME_BOOST_UNION_SETTING_SELECT_YES
&& ($PAGE->url->compare(new core\url('/mod/forum/view.php'), URL_MATCH_BASE) ||
$PAGE->url->compare(new core\url('/mod/forum/discuss.php'), URL_MATCH_BASE) ||
$PAGE->url->compare(new core\url('/mod/forum/post.php'), URL_MATCH_BASE))) {
// Use the specialized hint text for hidden courses on forum pages.
$hintcoursehiddentext = get_string('showhintforumnotifications', 'theme_boost_union');
}
// If we show any kind of hint for the hidden course, construct the hints HTML item via mustache.
if ($hintcoursehiddentext) {
// Prepare the templates context.
$templatecontext = [
'courseid' => $COURSE->id,
'hintcoursehiddentext' => $hintcoursehiddentext,
// If the user has the capability to change the course settings, an additional link to the course settings is shown.
'showcoursesettingslink' => has_capability('moodle/course:update', context_course::instance($COURSE->id)),
];
// Render template and add it to HTML code.
$html .= $OUTPUT->render_from_template('theme_boost_union/course-hint-hidden', $templatecontext);
}
}
// If the setting showhintcourseguestaccess is set and the user is accessing the course with guest access,
// a hint for users is shown.
// We also check that the user did not switch the role. This is a special case for roles that can fully access the course
// without being enrolled. A role switch would show the guest access hint additionally in that case and this is not
// intended.
if (get_config('theme_boost_union', 'showhintcourseguestaccess') == THEME_BOOST_UNION_SETTING_SELECT_YES
&& is_guest(\context_course::instance($COURSE->id), $USER->id)
&& $PAGE->has_set_url()
&& $PAGE->url->compare(new core\url('/course/view.php'), URL_MATCH_BASE)
&& !is_role_switched($COURSE->id)) {
// Require self enrolment library.
require_once($CFG->dirroot . '/enrol/self/lib.php');
// Prepare template context.
$templatecontext = ['courseid' => $COURSE->id,
'role' => role_get_name(get_guest_role()), ];
// Search for an available self enrolment link in this course.
$templatecontext['showselfenrollink'] = false;
$instances = enrol_get_instances($COURSE->id, true);
$plugins = enrol_get_plugins(true);
foreach ($instances as $instance) {
// If the enrolment plugin isn't enabled currently, skip it.
if (!isset($plugins[$instance->enrol])) {
continue;
}
// Remember the enrolment plugin.
$plugin = $plugins[$instance->enrol];
// If there is a self enrolment link.
if ($plugin->show_enrolme_link($instance)) {
$templatecontext['showselfenrollink'] = true;
break;
}
}
// Render template and add it to HTML code.
$html .= $OUTPUT->render_from_template('theme_boost_union/course-hint-guestaccess', $templatecontext);
}
// If the setting showhintcourseselfenrol is set, a hint for users is shown that the course allows unrestricted self
// enrolment. This hint is only shown if the course is visible, the self enrolment is visible and if the user has the
// capability "theme/boost_union:viewhintcourseselfenrol".
if (get_config('theme_boost_union', 'showhintcourseselfenrol') == THEME_BOOST_UNION_SETTING_SELECT_YES
&& has_capability('theme/boost_union:viewhintcourseselfenrol', \context_course::instance($COURSE->id))
&& $PAGE->has_set_url()
&& $PAGE->url->compare(new core\url('/course/view.php'), URL_MATCH_BASE)
&& $COURSE->visible == true) {
// Get the active enrol instances for this course.
$enrolinstances = enrol_get_instances($COURSE->id, true);
// Prepare to remember when self enrolment is / will be possible.
$selfenrolmentpossiblecurrently = false;
$selfenrolmentpossiblefuture = false;
foreach ($enrolinstances as $instance) {
// Check if unrestricted self enrolment is possible currently or in the future.
$now = (new \DateTime("now", \core_date::get_server_timezone_object()))->getTimestamp();
if ($instance->enrol == 'self' && empty($instance->password) && $instance->customint6 == 1 &&
(empty($instance->enrolenddate) || $instance->enrolenddate > $now)) {
// Build enrol instance object with all necessary information for rendering the note later.
$instanceobject = new stdClass();
// Remember instance name.
if (empty($instance->name)) {
$instanceobject->name = get_string('pluginname', 'enrol_self') .
" (" . get_string('defaultcoursestudent', 'core') . ")";
} else {
$instanceobject->name = $instance->name;
}
// Remember type of unrestrictedness.
if (empty($instance->enrolenddate) && empty($instance->enrolstartdate)) {
$instanceobject->unrestrictedness = 'unlimited';
$selfenrolmentpossiblecurrently = true;
} else if (empty($instance->enrolstartdate) &&
!empty($instance->enrolenddate) && $instance->enrolenddate > $now) {
$instanceobject->unrestrictedness = 'until';
$selfenrolmentpossiblecurrently = true;
} else if (empty($instance->enrolenddate) &&
!empty($instance->enrolstartdate) && $instance->enrolstartdate > $now) {
$instanceobject->unrestrictedness = 'from';
$selfenrolmentpossiblefuture = true;
} else if (empty($instance->enrolenddate) &&
!empty($instance->enrolstartdate) && $instance->enrolstartdate <= $now) {
$instanceobject->unrestrictedness = 'since';
$selfenrolmentpossiblecurrently = true;
} else if (!empty($instance->enrolstartdate) && $instance->enrolstartdate > $now &&
!empty($instance->enrolenddate) && $instance->enrolenddate > $now) {
$instanceobject->unrestrictedness = 'fromuntil';
$selfenrolmentpossiblefuture = true;
} else if (!empty($instance->enrolstartdate) && $instance->enrolstartdate <= $now &&
!empty($instance->enrolenddate) && $instance->enrolenddate > $now) {
$instanceobject->unrestrictedness = 'sinceuntil';
$selfenrolmentpossiblecurrently = true;
} else {
// This should not happen, thus continue to next instance.
continue;
}
// Remember enrol start date.
if (!empty($instance->enrolstartdate)) {
$instanceobject->startdate = $instance->enrolstartdate;
} else {
$instanceobject->startdate = null;
}
// Remember enrol end date.
if (!empty($instance->enrolenddate)) {
$instanceobject->enddate = $instance->enrolenddate;
} else {
$instanceobject->enddate = null;
}
// Remember this instance.
$selfenrolinstances[$instance->id] = $instanceobject;
}
}
// If there is at least one unrestricted enrolment instance,
// show the hint with information about each unrestricted active self enrolment in the course.
if (!empty($selfenrolinstances) &&
($selfenrolmentpossiblecurrently == true || $selfenrolmentpossiblefuture == true)) {
// Prepare template context.
$templatecontext = [];
// Add the start of the hint t the template context
// depending on the fact if enrolment is already possible currently or will be in the future.
if ($selfenrolmentpossiblecurrently == true) {
$templatecontext['selfenrolhintstart'] = get_string('showhintcourseselfenrolstartcurrently', 'theme_boost_union');
} else if ($selfenrolmentpossiblefuture == true) {
$templatecontext['selfenrolhintstart'] = get_string('showhintcourseselfenrolstartfuture', 'theme_boost_union');
}
// Iterate over all enrolment instances to output the details.
foreach ($selfenrolinstances as $selfenrolinstanceid => $selfenrolinstanceobject) {
// If the user has the capability to config self enrolments, enrich the instance name with the settings link.
if (has_capability('enrol/self:config', \context_course::instance($COURSE->id))) {
$url = new core\url('/enrol/editinstance.php', ['courseid' => $COURSE->id,
'id' => $selfenrolinstanceid, 'type' => 'self', ]);
$selfenrolinstanceobject->name = core\output\html_writer::link($url, $selfenrolinstanceobject->name);
}
// Add the enrolment instance information to the template context depending on the instance configuration.
if ($selfenrolinstanceobject->unrestrictedness == 'unlimited') {
$templatecontext['selfenrolinstances'][] = get_string('showhintcourseselfenrolunlimited', 'theme_boost_union',
['name' => $selfenrolinstanceobject->name]);
} else if ($selfenrolinstanceobject->unrestrictedness == 'until') {
$templatecontext['selfenrolinstances'][] = get_string('showhintcourseselfenroluntil', 'theme_boost_union',
['name' => $selfenrolinstanceobject->name,
'until' => userdate($selfenrolinstanceobject->enddate), ]);
} else if ($selfenrolinstanceobject->unrestrictedness == 'from') {
$templatecontext['selfenrolinstances'][] = get_string('showhintcourseselfenrolfrom', 'theme_boost_union',
['name' => $selfenrolinstanceobject->name,
'from' => userdate($selfenrolinstanceobject->startdate), ]);
} else if ($selfenrolinstanceobject->unrestrictedness == 'since') {
$templatecontext['selfenrolinstances'][] = get_string('showhintcourseselfenrolsince', 'theme_boost_union',
['name' => $selfenrolinstanceobject->name,
'since' => userdate($selfenrolinstanceobject->startdate), ]);
} else if ($selfenrolinstanceobject->unrestrictedness == 'fromuntil') {
$templatecontext['selfenrolinstances'][] = get_string('showhintcourseselfenrolfromuntil', 'theme_boost_union',
['name' => $selfenrolinstanceobject->name,
'until' => userdate($selfenrolinstanceobject->enddate),
'from' => userdate($selfenrolinstanceobject->startdate), ]);
} else if ($selfenrolinstanceobject->unrestrictedness == 'sinceuntil') {
$templatecontext['selfenrolinstances'][] = get_string('showhintcourseselfenrolsinceuntil', 'theme_boost_union',
['name' => $selfenrolinstanceobject->name,
'until' => userdate($selfenrolinstanceobject->enddate),
'since' => userdate($selfenrolinstanceobject->startdate), ]);
}
}
// If the user has the capability to config self enrolments, add the call for action to the template context.
if (has_capability('enrol/self:config', \context_course::instance($COURSE->id))) {
$templatecontext['calltoaction'] = true;
} else {
$templatecontext['calltoaction'] = false;
}
// Render template and add it to HTML code.
$html .= $OUTPUT->render_from_template('theme_boost_union/course-hint-selfenrol', $templatecontext);
}
}
// If the setting showswitchedroleincourse is set and the user has switched his role,
// a hint for the role switch will be shown.
if (get_config('theme_boost_union', 'showswitchedroleincourse') === THEME_BOOST_UNION_SETTING_SELECT_YES
&& is_role_switched($COURSE->id) ) {
// Get the role name switched to.
$opts = \user_get_user_navigation_info($USER, $PAGE);
$role = $opts->metadata['rolename'];
// Get the URL to switch back (normal role).
$url = new core\url('/course/switchrole.php',
['id' => $COURSE->id,
'sesskey' => sesskey(),
'switchrole' => 0,
'returnurl' => $PAGE->url->out_as_local_url(false), ]);
// Prepare template context.
$templatecontext = ['role' => $role,
'url' => $url->out(), ];
// Render template and add it to HTML code.
$html .= $OUTPUT->render_from_template('theme_boost_union/course-hint-switchedrole', $templatecontext);
}
// Return HTML code.
return $html;
}
/**
* Build the link to a static page.
*
* @param string $page The static page's identifier.
* @return string.
*/
function theme_boost_union_get_staticpage_link($page) {
// Compose the URL object.
$url = new core\url('/theme/boost_union/pages/'.$page.'.php');
// Return the string representation of the URL.
return $url->out();
}
/**
* Build the page title of a static page.
*
* @param string $page The static page's identifier.
* @return string.
*/
function theme_boost_union_get_staticpage_pagetitle($page) {
// Get the configured page title.
$pagetitleconfig = format_string(get_config('theme_boost_union', $page.'pagetitle'), true,
['context' => \context_system::instance()]);
// If there is a string configured.
if ($pagetitleconfig) {
// Return this setting.
return $pagetitleconfig;
// Otherwise.
} else {
// Return the default string.
return get_string($page.'pagetitledefault', 'theme_boost_union');
}
}
/**
* Helper function to check if a given info banner should be shown on this page.
* This function checks
* a) if the banner is enabled at all
* b) if the banner has any content (i.e. is not empty)
* b) if the banner is configured to be shown on the given page
* c) if the banner is configured to be shown now (in case it is a time-based banner)
*
* @copyright 2022 Alexander Bias, lern.link GmbH <[email protected]>
* @copyright based on code from theme_boost_campus by Kathrin Osswald.
*
* @param int $bannerno The counting number of the info banner.
*
* @return boolean.
*/
function theme_boost_union_infobanner_is_shown_on_page($bannerno) {
global $PAGE;
// Get theme config.
$config = get_config('theme_boost_union');
// If the info banner is enabled.
$enabledsettingname = 'infobanner'.$bannerno.'enabled';
if ($config->{$enabledsettingname} == THEME_BOOST_UNION_SETTING_SELECT_YES) {
// If the info banner has any content.
$contentsettingname = 'infobanner'.$bannerno.'content';
if (!empty($config->{$contentsettingname})) {
// If the info banner should be shown on this page.
$pagessettingname = 'infobanner'.$bannerno.'pages';
$showonpage = false;
$pages = explode(',', $config->{$pagessettingname});
foreach ($pages as $page) {
if ($PAGE->pagelayout == $page) {
$showonpage = true;
break;
}
}
if ($showonpage == true) {
// If this is a time-based-banner.
$modesettingname = 'infobanner'.$bannerno.'mode';
if ($config->{$modesettingname} == THEME_BOOST_UNION_SETTING_INFOBANNERMODE_TIMEBASED) {
$startsettingname = 'infobanner'.$bannerno.'start';
$endsettingname = 'infobanner'.$bannerno.'end';
// Check if time settings are empty and try to convert the time strings to a unix timestamp.
if (empty($config->{$startsettingname})) {
$startempty = true;
$start = 0;
} else {
$startempty = false;
$start = $config->{$startsettingname};
}
if (empty($config->{$endsettingname})) {
$endempty = true;
$end = 0;
} else {
$endempty = false;
$end = $config->{$endsettingname};
}
// The banner is shown if
// a) now is between start and end time OR
// b) start is not set but end is not reached yet OR
// c) end is not set, but start lies in the past OR
// d) no dates are set, so there's no time restriction.
$now = time();
if (($now >= $start && $now <= $end ||
($now <= $end && $startempty) ||
($now >= $start && $endempty) ||
($startempty && $endempty))) {
return true;
}
// Otherwise this is a perpetual banner.
} else {
// If the banner was not dismissed by the user.
if (get_user_preferences('theme_boost_union_infobanner'.$bannerno.'_dismissed') != true) {
return true;
}
}
}
}
}
// Apparently, the banner should not be shown on this page.
return false;
}
/**
* Helper function to compare either infobanner or tiles or slides orders.
*
* @param int $a The first value
* @param int $b The second value
*
* @return boolean.
*/
function theme_boost_union_compare_order($a, $b) {
// If the same 'order' attribute is given to both items.
if ($a->order == $b->order) {
// We have to compare the 'no' attribute.
// This way, we make sure that the item which is presented first in the admin settings is still placed first in the
// ordered list even if the same order is configured.
return ($a->no < $b->no) ? -1 : 1;
}
// Otherwise, compare both items based on their 'order' attribute.
return ($a->order < $b->order) ? -1 : 1;
}
/**
* Helper function to reset the visibility of a given info banner.
*
* @param int $no The number of the info banner.
*
* @return bool True if everything went fine, false if at least one user couldn't be resetted.
*/
function theme_boost_union_infobanner_reset_visibility($no) {
global $DB;
// Clean the no parameter, just to be sure as we will use it within a user preference label (hence in a SQL query).
$no = clean_param($no, PARAM_INT);
// Get all users that have dismissed the info banner once and therefore the user preference.
$whereclause = 'name = :name AND value = :value';
$params = ['name' => 'theme_boost_union_infobanner'.$no.'_dismissed', 'value' => '1'];
$users = $DB->get_records_select('user_preferences', $whereclause, $params, '', 'userid');
// Initialize variable for feedback messages.
$somethingwentwrong = false;
// Store coding exception.
$codingexception[] = [];
foreach ($users as $user) {
try {
unset_user_preference('theme_boost_union_infobanner'.$no.'_dismissed', $user->userid);
} catch (coding_exception $e) {
$somethingwentwrong = true;
}
}
if (!$somethingwentwrong) {
return true;
} else {
return false;
}
}
/**
* Get the random number for displaying the background image on the login page randomly.
*
* @return int|null
* @throws coding_exception
* @throws dml_exception
*/
function theme_boost_union_get_random_loginbackgroundimage_number() {
// Static variable.
static $number = null;
if ($number == null) {
// Get all files for loginbackgroundimages.
$files = theme_boost_union_get_loginbackgroundimage_files();
// Get count of array elements.
$filecount = count($files);
// We only return a number if images are uploaded to the loginbackgroundimage file area.
if ($filecount > 0) {
// If Behat tests are running.
if (defined('BEHAT_SITE_RUNNING')) {
// Select the last image (to make Behat tests work).
$number = $filecount;
} else {
// Generate random number.
$number = rand(1, $filecount);
}
}
}
return $number;
}
/**
* Get a random class for body tag for the background image of the login page.
*
* @return string
*/
function theme_boost_union_get_random_loginbackgroundimage_class() {
// Get the static random number.
$number = theme_boost_union_get_random_loginbackgroundimage_number();
// Only create the class name with the random number if there is a number (=files uploaded to the file area).
if ($number != null) {
return 'loginbackgroundimage'.$number;
} else {
return '';
}
}
/**
* Return the files from the loginbackgroundimage file area.
* This function always loads the files from the filearea which is not really performant.
* However, we accept this at the moment as it is only invoked on the login page.
*
* @return array|null
* @throws coding_exception
* @throws dml_exception
*/
function theme_boost_union_get_loginbackgroundimage_files() {
// Static variable to remember the files for subsequent calls of this function.
static $files = null;
if ($files == null) {
// Get the system context.
$systemcontext = \context_system::instance();
// Get filearea.
$fs = get_file_storage();
// Get all files from filearea.
$files = $fs->get_area_files($systemcontext->id, 'theme_boost_union', 'loginbackgroundimage',
false, 'itemid', false);
}
return $files;
}
/**
*
* Get the advertisement tile's background image URL from the filearea 'tilebackgroundimage'.tileno.
*
* Note:
* Calling this function for each tile separately is maybe not performant. Originally it was planed to put
* all files in one filearea. However, at the time of development
* https://github.com/moodle/moodle/blob/master/lib/outputlib.php#L2062
* did not support itemids in setting-files of themes.
*
* @param int $tileno The tile number.
* @return string|null
*/
function theme_boost_union_get_urloftilebackgroundimage($tileno) {
// If the tile number is apparently not valid, return.
// Note: We just check the tile's number, we do not check if the tile is enabled or not.
if ($tileno < 0 || $tileno > THEME_BOOST_UNION_SETTING_ADVERTISEMENTTILES_COUNT) {
return null;
}
// Get the background image config for this tile.
$bgconfig = get_config('theme_boost_union', 'tile'.$tileno.'backgroundimage');
// If a background image is configured.
if (!empty($bgconfig)) {
// Get the system context.
$systemcontext = context_system::instance();
// Get filearea.
$fs = get_file_storage();
// Get all files from filearea.
$files = $fs->get_area_files($systemcontext->id, 'theme_boost_union', 'tilebackgroundimage'.$tileno,
false, 'itemid', false);
// Just pick the first file - we are sure that there is just one file.
$file = reset($files);
// Build and return the image URL.
return core\url::make_pluginfile_url($file->get_contextid(), $file->get_component(), $file->get_filearea(),
$file->get_itemid(), $file->get_filepath(), $file->get_filename());
}
// As no image was found, return null.
return null;
}
/**
* Get the slider's background image URL from the filearea 'slidebackgroundimage'.tileno.
*
* Note:
* Calling this function for each slide separately is maybe not performant. Originally it was planed to put
* all files in one filearea. However, at the time of development
* https://github.com/moodle/moodle/blob/master/lib/outputlib.php#L2062
* did not support itemids in setting-files of themes.
*
* @param int $slideno The slide number.
* @return string|null
*/
function theme_boost_union_get_urlofslidebackgroundimage($slideno) {
// If the slide number is apparently not valid, return.
// Note: We just check the slide's number, we do not check if the slide is enabled or not.
if ($slideno < 0 || $slideno > THEME_BOOST_UNION_SETTING_SLIDES_COUNT) {
return null;
}
// Get the background image config for this slide.
$bgconfig = get_config('theme_boost_union', 'slide'.$slideno.'backgroundimage');
// If a background image is configured.
if (!empty($bgconfig)) {
// Get the system context.
$systemcontext = context_system::instance();
// Get filearea.
$fs = get_file_storage();
// Get all files from filearea.
$files = $fs->get_area_files($systemcontext->id, 'theme_boost_union', 'slidebackgroundimage'.$slideno,
false, 'itemid', false);
// Just pick the first file - we are sure that there is just one file.
$file = reset($files);
// Build and return the image URL.
return core\url::make_pluginfile_url($file->get_contextid(), $file->get_component(), $file->get_filearea(),
$file->get_itemid(), $file->get_filepath(), $file->get_filename());
}
// As no image was found, return null.
return null;
}
/**
* Add background images from setting 'loginbackgroundimage' to SCSS.
*
* @return string
*/
function theme_boost_union_get_loginbackgroundimage_scss() {
// Initialize variables.
$count = 0;
$scss = '';
// Get all files from filearea.
$files = theme_boost_union_get_loginbackgroundimage_files();
// Add URL of uploaded images to equivalent class.
foreach ($files as $file) {
$count++;
// Get url from file.
$url = core\url::make_pluginfile_url($file->get_contextid(), $file->get_component(), $file->get_filearea(),
$file->get_itemid(), $file->get_filepath(), $file->get_filename());
// Add this url to the body class loginbackgroundimage[n] as a background image.
$scss .= 'body.pagelayout-login.loginbackgroundimage'.$count.' {';
$scss .= 'background-image: url("'.$url.'");';
$scss .= '}';
}
return $scss;
}
/**
* Get the text that should be displayed for the randomly displayed background image on the login page.
*
* @return array (of two strings, holding the text and the text color)
* @throws coding_exception
* @throws dml_exception
*/
function theme_boost_union_get_loginbackgroundimage_text() {
// Get the random number.
$number = theme_boost_union_get_random_loginbackgroundimage_number();
// Only search for the text if there's a background image.
if ($number != null) {
// Get the files from the filearea loginbackgroundimage.
$files = theme_boost_union_get_loginbackgroundimage_files();
// Get the file for the selected random number.
$file = array_slice($files, ($number - 1), 1, false);
// Get the filename.
$filename = array_pop($file)->get_filename();
// Get the config for loginbackgroundimagetext and make an array out of the lines.
$lines = explode("\n", get_config('theme_boost_union', 'loginbackgroundimagetext'));
// Process the lines.
foreach ($lines as $line) {
$settings = explode("|", $line);
// If the line does not have three items, skip it.
if (count($settings) != 3) {
continue;
}
// Compare the filenames for a match.
if (strcmp($filename, trim($settings[0])) == 0) {
// Trim the second parameter as we need it more than once.
$settings[2] = trim($settings[2]);
// If the color value is not acceptable, replace it with dark.
if ($settings[2] != 'dark' && $settings[2] != 'light') {
$settings[2] = 'dark';
}
// Return the text + text color that belongs to the randomly selected image.
return [format_string(trim($settings[1])), $settings[2]];
}
}
}
return '';
}
/**
* Return the files from the additionalresources file area as templatecontext structure.
* It was designed to compose the files for the settings-additionalresources-filelist.mustache template.
* This function always loads the files from the filearea which is not really performant.
* Thus, you have to take care where and how often you use it (or add some caching).
*
* @return array|null
* @throws coding_exception
* @throws dml_exception
*/
function theme_boost_union_get_additionalresources_templatecontext() {
global $OUTPUT;
// Static variable to remember the files for subsequent calls of this function.
static $filesforcontext = null;
if ($filesforcontext == null) {
// Get the system context.
$systemcontext = \context_system::instance();
// Get filearea.
$fs = get_file_storage();
// Get all files from filearea.
$files = $fs->get_area_files($systemcontext->id, 'theme_boost_union', 'additionalresources', false, 'itemid', false);
// Iterate over the files and fill the templatecontext of the file list.
$filesforcontext = [];
foreach ($files as $af) {
$urlpersistent = new core\url('/pluginfile.php/1/theme_boost_union/additionalresources/0/'.$af->get_filename());
$urlrevisioned = new core\url('/pluginfile.php/1/theme_boost_union/additionalresources/'.theme_get_revision().
'/'.$af->get_filename());
$filesforcontext[] = ['filename' => $af->get_filename(),
'filetype' => $af->get_mimetype(),
'filesize' => display_size($af->get_filesize()),
'fileicon' => $OUTPUT->image_icon(file_file_icon($af), get_mimetype_description($af)),
'fileurlpersistent' => $urlpersistent->out(),
'fileurlrevisioned' => $urlrevisioned->out(), ];
}
}
return $filesforcontext;
}
/**
* Return the files from the customfonts file area as templatecontext structure.
* It was designed to compose the files for the settings-customfonts-filelist.mustache template.
* This function always loads the files from the filearea which is not really performant.
* Thus, you have to take care where and how often you use it (or add some caching).
*
* @return array|null
* @throws coding_exception
* @throws dml_exception
*/
function theme_boost_union_get_customfonts_templatecontext() {
global $OUTPUT;
// Static variable to remember the files for subsequent calls of this function.
static $filesforcontext = null;
if ($filesforcontext == null) {
// Get the system context.
$systemcontext = \context_system::instance();
// Get filearea.
$fs = get_file_storage();
// Get all files from filearea.
$files = $fs->get_area_files($systemcontext->id, 'theme_boost_union', 'customfonts', false, 'itemid', false);
// Get the webfonts extensions list.
$webfonts = theme_boost_union_get_webfonts_extensions();
// Iterate over the files.
$filesforcontext = [];
foreach ($files as $af) {
// Get the filename.
$filename = $af->get_filename();
// Check if the file is really a font file (as we can't really rely on the upload restriction in settings.php)
// according to its file suffix (as the filetype might not have a known mimetype).
// If it isn't a font file, skip it.
$filenamesuffix = pathinfo($filename, PATHINFO_EXTENSION);
if (!in_array('.'.$filenamesuffix, $webfonts)) {
continue;
}
// Otherwise, fill the templatecontext of the file list.
$urlpersistent = new core\url('/pluginfile.php/1/theme_boost_union/customfonts/0/'.$filename);
$filesforcontext[] = ['filename' => $filename,
'fileurlpersistent' => $urlpersistent->out(), ];
}
}
return $filesforcontext;
}
/**
* Helper function which returns an array of accepted webfonts extensions (including the dots).
*
* @return array
*/
function theme_boost_union_get_webfonts_extensions() {
return ['.eot', '.otf', '.svg', '.ttf', '.woff', '.woff2'];
}
/**
* Helper function which makes sure that all webfont file types are registered in the system.
* The webfont file types need to be registered in the system, otherwise the admin settings filepicker wouldn't allow restricting
* the uploadable file types to webfonts only.
*
* Please note: If custom filetypes are defined in config.php, registering additional filetypes is not possible
* due to a restriction in the set_custom_types() function in Moodle core. In this case, this function does not
* register anything and will return false.
*
* @return boolean true if the filetypes were registered, false if not.
* @throws coding_exception
*/
function theme_boost_union_register_webfonts_filetypes() {
global $CFG;
// If customfiletypes are set in config.php or PHP tests are running, we can't do anything.
if (array_key_exists('customfiletypes', $CFG->config_php_settings) || PHPUNIT_TEST) {
return false;
}
// Our array of webfont file types to register.
// As we want to keep things simple, we do not set a particular icon for these file types.
// Likewise, we do not set any type groups or use descriptions from the language pack.
$webfonts = [
'eot' => [
'extension' => 'eot',
'mimetype' => 'application/vnd.ms-fontobject',
'coreicon' => 'unknown',
],
'otf' => [
'extension' => 'otf',
'mimetype' => 'font/otf',
'coreicon' => 'unknown',
],
'svg' => [
'extension' => 'svg',
'mimetype' => 'image/svg+xml',
'coreicon' => 'unknown',
],
'ttf' => [
'extension' => 'ttf',
'mimetype' => 'font/ttf',
'coreicon' => 'unknown',
],
'woff' => [
'extension' => 'woff',
'mimetype' => 'font/woff',
'coreicon' => 'unknown',
],
'woff2' => [
'extension' => 'woff2',
'mimetype' => 'font/woff2',
'coreicon' => 'unknown',
],
];
// First, get the list of currently registered file types.
$currenttypes = core_filetypes::get_types();
// Iterate over the webfonts file types.
foreach ($webfonts as $f) {
// If the file type is already registered, skip it.
if (array_key_exists($f['extension'], $currenttypes)) {
continue;
}
// Otherwise, register the file type.
core_filetypes::add_type($f['extension'], $f['mimetype'], $f['coreicon']);
}
return true;
}
/**
* Helper function to render a preview of a HTML email to be shown on the theme settings page.
*
* If E-Mails have been branded, an E-Mail preview will be returned as string.
* Otherwise, null will be returned.
*
* @return string|null
*/
function theme_boost_union_get_emailbrandinghtmlpreview() {
global $OUTPUT;
// Get branding snippets.
$htmlprefix = get_string('templateemailhtmlprefix', 'theme_boost_union');
$htmlsuffix = get_string('templateemailhtmlsuffix', 'theme_boost_union');
// If no snippet was customized, return null.
if (trim($htmlprefix) == '' && trim($htmlsuffix) == '') {
return null;
}
// Otherwise, compose mail text.
$mailtemplatecontext = ['body' => get_string('emailbrandinghtmldemobody', 'theme_boost_union')];
$mail = $OUTPUT->render_from_template('core/email_html', $mailtemplatecontext);
// And compose mail preview.
$previewtemplatecontext = ['mail' => $mail, 'type' => 'Html', 'monospace' => false];
$preview = $OUTPUT->render_from_template('theme_boost_union/emailpreview', $previewtemplatecontext);
return $preview;
}
/**
* Helper function to render a preview of a plaintext email to be shown on the theme settings page.
*
* If E-Mails have been branded, an E-Mail preview will be returned as string.
* Otherwise, null will be returned.
*
* @return string|null
*/
function theme_boost_union_get_emailbrandingtextpreview() {
global $OUTPUT;
// Get branding snippets.
$textprefix = get_string('templateemailtextprefix', 'theme_boost_union');
$textsuffix = get_string('templateemailtextsuffix', 'theme_boost_union');
// If no snippet was customized, return null.
if (trim($textprefix) == '' && trim($textsuffix) == '') {
return null;
}
// Otherwise, compose mail text.
$mailtemplatecontext = ['body' => get_string('emailbrandingtextdemobody', 'theme_boost_union')];
$mail = nl2br($OUTPUT->render_from_template('core/email_text', $mailtemplatecontext));
// And compose mail preview.
$previewtemplatecontext = ['mail' => $mail, 'type' => 'Text', 'monospace' => true];
$preview = $OUTPUT->render_from_template('theme_boost_union/emailpreview', $previewtemplatecontext);
return $preview;
}
/**
* Helper function to compose the title of an external admin page.
* This is adopted from /admin/settings.php and done to make sure that the external admin pages look as similar as possible
* to the standard admin pages.
*
* @param string $pagename The page's name.
*
* @return string
*/
function theme_boost_union_get_externaladminpage_title($pagename) {
global $SITE;
$title = $SITE->shortname.': ';
$title .= get_string('administration', 'core').': ';
$title .= get_string('appearance', 'core').': ';
$title .= get_string('themes', 'core').': ';
$title .= get_string('pluginname', 'theme_boost_union').': ';
$title .= $pagename;
return $title;
}
/**
* Helper function to compose the heading of an external admin page.