-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathfilter.php
4664 lines (4336 loc) · 229 KB
/
filter.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 FilterCodes for Moodle - https://moodle.org/
//
// FilterCodes 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.
//
// FilterCodes 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 <https://www.gnu.org/licenses/>.
/**
* Main filter code for FilterCodes.
*
* @package filter_filtercodes
* @copyright 2017-2023 TNG Consulting Inc. - www.tngconsulting.ca
* @author Michael Milette
* @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
use block_online_users\fetcher;
use core_table\local\filter\integer_filter;
use core_user\table\participants_filterset;
use core_user\table\participants_search;
use Endroid\QrCode\QrCode;
require_once($CFG->dirroot . '/course/renderer.php');
/**
* Extends the moodle_text_filter class to provide plain text support for new tags.
*
* @copyright 2017-2023 TNG Consulting Inc. - www.tngconsulting.ca
* @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class filter_filtercodes extends moodle_text_filter {
/** @var object $archetypes Object array of Moodle archetypes. */
public $archetypes = [];
/** @var array $customroles array of Roles key is shortname and value is the id */
private static $customroles = [];
/**
* @var array $customrolespermissions array of Roles key is shortname + context_id and the value is a boolean showing if
* user is allowed
*/
private static $customrolespermissions = [];
/**
* Constructor: Get the role IDs associated with each of the archetypes.
*/
public function __construct() {
// Note: This array must correspond to the one in function hasminarchetype.
$archetypelist = ['manager' => 1, 'coursecreator' => 2, 'editingteacher' => 3, 'teacher' => 4, 'student' => 5];
foreach ($archetypelist as $archetype => $level) {
$roleids = [];
// Build array of roles.
foreach (get_archetype_roles($archetype) as $role) {
$roleids[] = $role->id;
}
$this->archetypes[$archetype] = (object) ['level' => $level, 'roleids' => $roleids];
}
}
/**
* Determine if any of the user's roles includes specified archetype.
*
* @param string $archetype Name of archetype.
* @return boolean Does: true, Does not: false.
*/
private function hasarchetype($archetype) {
// If not logged in or is just a guestuser, definitely doesn't have the archetype we want.
if (!isloggedin() || isguestuser()) {
return false;
}
// Handle caching of results.
static $archetypes = [];
if (isset($archetypes[$archetype])) {
return $archetypes[$archetype];
}
global $USER, $PAGE;
$archetypes[$archetype] = false;
if (is_role_switched($PAGE->course->id)) { // Has switched roles.
$context = context_course::instance($PAGE->course->id);
$id = $USER->access['rsw'][$context->path];
$archetypes[$archetype] = in_array($id, $this->archetypes[$archetype]->roleids);
} else {
// For each of the roles associated with the archetype, check if the user has one of the roles.
foreach ($this->archetypes[$archetype]->roleids as $roleid) {
if (user_has_role_assignment($USER->id, $roleid, $PAGE->context->id)) {
$archetypes[$archetype] = true;
}
}
}
return $archetypes[$archetype];
}
/**
* Determine if the user only has a specified archetype amongst the user's role and no others.
* Example: Can be a student but not also be a teacher or manager.
*
* @param string $archetype Name of archetype.
* @return boolean Does: true, Does not: false.
*/
private function hasonlyarchetype($archetype) {
if ($this->hasarchetype($archetype)) {
$archetypes = array_keys($this->archetypes);
foreach ($archetypes as $archetypename) {
if ($archetypename != $archetype && $this->hasarchetype($archetypename)) {
return false;
}
}
global $PAGE;
if (is_role_switched($PAGE->course->id)) {
// Ignore site admin status if we have switched roles.
return true;
} else {
return is_siteadmin();
}
}
return false;
}
/**
* Determine if the user has the specified archetype or one with elevated capabilities.
* Example: Can be a teacher, course creator, manager or Administrator but not a student.
*
* @param string $minarchetype Name of archetype.
* @return boolean User meets minimum archetype requirement: true, does not: false.
*/
private function hasminarchetype($minarchetype) {
// Note: This array must start with one blank entry followed by the same list found in in __construct().
$archetypelist = ['', 'manager', 'coursecreator', 'editingteacher', 'teacher', 'student'];
// For each archetype level between the one specified and 'manager'.
for ($level = $this->archetypes[$minarchetype]->level; $level >= 1; $level--) {
// Check to see if any of the user's roles correspond to the archetype.
if ($this->hasarchetype($archetypelist[$level])) {
return true;
}
}
// Return true regardless of the archetype if we are an administrator and not in a switched role.
global $PAGE;
return !is_role_switched($PAGE->course->id) && is_siteadmin();
}
/**
* Checks if a user has a custom role or not within the current context.
*
* @param string $roleshortname The role's shortname.
* @param integer $contextid The context where the tag appears.
* @return boolean True if user has custom role, otherwise, false.
*/
private function hascustomrole($roleshortname, $contextid = 0) {
$keytocheck = $roleshortname . '-' . $contextid;
if (!isset(self::$customrolespermissions[$keytocheck])) {
global $USER, $DB;
if (!isset(self::$customroles[$roleshortname])) {
self::$customroles[$roleshortname] = $DB->get_field('role', 'id', ['shortname' => $roleshortname]);
}
$hasrole = false;
if (self::$customroles[$roleshortname]) {
$hasrole = user_has_role_assignment($USER->id, self::$customroles[$roleshortname], $contextid);
}
self::$customrolespermissions[$keytocheck] = $hasrole;
}
return self::$customrolespermissions[$keytocheck];
}
/**
* Determine if the specified user has the specified role anywhere in the system.
*
* @param string $roleshortname Role shortname.
* @param integer $userid The user's ID.
* @return boolean True if the user has the role, false if they do not.
*/
private function hasarole($roleshortname, $userid) {
// Cache list of user's roles.
static $list;
if (!isset($list)) {
// Not cached yet? We can take care of that.
$list = [];
if (isloggedin() && !isguestuser()) {
// We only track logged-in roles.
global $DB;
// Retrieve list of role names.
$rolenames = $DB->get_records('role');
// Retrieve list of my roles across all contexts.
$userroles = $DB->get_records('role_assignments', ['userid' => $userid]);
// For each of my roles, add the roll name to the list.
foreach ($userroles as $role) {
if (!empty($rolenames[$role->roleid]->shortname)) {
// There should always be a role name for each role id but you can't be too careful these days.
$list[] = $rolenames[$role->roleid]->shortname;
}
}
$list = array_unique($list);
if (is_siteadmin()) {
// Admin is not an actual role, but we can use our imagination for convenience.
$list[] = 'administrator';
}
}
}
return in_array(strtolower($roleshortname), $list);
}
/**
* Returns the URL of a blank Avatar as a square image.
*
* @param integer $size Width of desired image in pixels.
* @return MOODLE_URL URL to image of avatar image.
*/
private function getblankavatarurl($size) {
global $PAGE, $CFG;
$img = 'u/' . ($size > 100 ? 'f3' : ($size > 35 ? 'f1' : 'f2'));
$renderer = $PAGE->get_renderer('core');
if ($CFG->branch >= 33) {
$url = $renderer->image_url($img);
} else {
$url = $renderer->pix_url($img); // Deprecated as of Moodle 3.3.
}
return new moodle_url($url);
}
/**
* Retrieves the URL for the user's profile picture, if one is available.
*
* @param object $user The Moodle user object for which we want a photo.
* @param mixed $size Can be sm|md|lg or an integer 2|1|3 or an integer size in pixels > 3.
* @return string URL to the photo image file but with $1 for the size.
*/
private function getprofilepictureurl($user, $size = 'md') {
global $PAGE;
$sizes = ['sm' => 35, '2' => 35, 'md' => 100, '1' => 100, 'lg' => 512, '3' => 512];
if (empty($px = $sizes[$size])) {
$px = $size; // Size was specified in pixels.
}
$userpicture = new user_picture($user);
$userpicture->size = $px; // Size in pixels.
$url = $userpicture->get_url($PAGE);
return $url;
}
/**
* Determine if running on http or https. Same as Moodle's is_https() except that it is backwards compatible to Moodle 2.7.
*
* @return boolean true if protocol is https, false if http.
*/
private function ishttps() {
global $CFG;
if ($CFG->branch >= 28) {
$ishttps = is_https(); // Available as of Moodle 2.8.
} else {
$ishttps = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443);
}
return $ishttps;
}
/**
* Determine if access is from a web service.
*
* @return boolean true if a web service, false if web browser.
*/
private function iswebservice() {
global $ME;
// If this is a web service or the Moodle mobile app...
$isws = (WS_SERVER || (strpos($ME, "webservice/") !== false && optional_param('token', '', PARAM_ALPHANUM)));
return $isws;
}
/**
* Generates HTML code for a reCAPTCHA.
*
* @return string HTML Code for reCAPTCHA or blank if logged-in or Moodle reCAPTCHA is not configured.
*/
private function getrecaptcha() {
global $CFG;
// Is user not logged-in or logged-in as guest?
if (!isloggedin() || isguestuser()) {
// If Moodle reCAPTCHA configured.
if (!empty($CFG->recaptchaprivatekey) && !empty($CFG->recaptchapublickey)) {
// Yes? Generate reCAPTCHA.
if (file_exists($CFG->libdir . '/recaptchalib_v2.php')) {
// For reCAPTCHA 2.0.
require_once($CFG->libdir . '/recaptchalib_v2.php');
return recaptcha_get_challenge_html(RECAPTCHA_API_URL, $CFG->recaptchapublickey);
} else {
// For reCAPTCHA 1.0.
require_once($CFG->libdir . '/recaptchalib.php');
return recaptcha_get_html($CFG->recaptchapublickey, null, $this->ishttps());
}
} else if ($CFG->debugdisplay == 1) { // If debugging is set to DEVELOPER...
// Show indicator that {reCAPTCHA} tag is not required.
return 'Warning: The reCAPTCHA tag is not required here.';
}
}
// Logged-in as non-guest user (reCAPTCHA is not required) or Moodle reCAPTCHA not configured.
// Don't generate reCAPTCHA.
return '';
}
/**
* Scrape HTML (callback)
*
* Extract content from another web page.
* Example: Can be used to extract a shared privacy policy across your websites.
*
* @param string $url URL address of content source.
* @param string $tag HTML tag that contains the information we want to retrieve.
* @param string $class (optional) HTML tag class attribute we should match.
* @param string $id (optional) HTML tag id attribute we should match.
* @param string $code (optional) any URL encoded HTML code you want to insert after the retrieved content.
* @return string Extracted content+optional code. If content is unavailable, returns message to contact webmaster.
*/
private function scrapehtml($url, $tag = '', $class = '', $id = '', $code = '') {
// Retrieve content. If the URL fails, return a message.
$content = @file_get_contents($url);
if (empty($content)) {
return get_string('contentmissing', 'filter_filtercodes');
}
// Disable warnings.
$libxmlpreviousstate = libxml_use_internal_errors(true);
// Load content into DOM object.
$dom = new DOMDocument();
$dom->loadHTML($content);
// Clear suppressed warnings.
libxml_clear_errors();
libxml_use_internal_errors($libxmlpreviousstate);
// Scrape out the content we want. If not found, return everything.
$xpath = new DOMXPath($dom);
// If a tag was not specified.
if (empty($tag)) {
$tag .= '*'; // Match any tag.
}
$query = "//{$tag}";
// If a class was specified.
if (!empty($class)) {
$query .= "[@class=\"{$class}\"]";
}
// If an id was specified.
if (!empty($id)) {
$query .= "[@id=\"{$id}\"]";
}
$tag = $xpath->query($query);
$tag = $tag->item(0);
return $dom->saveXML($tag) . urldecode($code);
}
/**
* Convert a number of bytes (e.g. filesize) into human readable format.
*
* @param float $bytes Raw number of bytes.
* @return string Bytes in human readable format.
*/
private function humanbytes($bytes) {
if ($bytes === false || $bytes < 0 || is_null($bytes) || $bytes > 1.0E+26) {
// If invalid number of bytes, or value is more than about 84,703.29 Yottabyte (YB), assume it is infinite.
$str = '∞'; // Could not determine, assume infinite.
} else {
static $unit;
if (!isset($unit)) {
$units = ['sizeb', 'sizekb', 'sizemb', 'sizegb', 'sizetb', 'sizeeb', 'sizezb', 'sizeyb'];
$units = get_strings($units, 'filter_filtercodes');
$units = array_values((array) $units);
}
$base = 1024;
$factor = min((int) log($bytes, $base), count($units) - 1);
$precision = [0, 2, 2, 1, 1, 1, 1, 0];
$str = sprintf("%1.{$precision[$factor]}f", $bytes / pow($base, $factor)) . ' ' . $units[$factor];
}
return $str;
}
/**
* Correctly format a list as "A, B and C".
*
* @param array $list An array of numbers or strings.
* @return string The formatted string.
*/
private function formatlist($list) {
// Save and remove last item in list from array.
$last = array_pop($list);
if ($list) {
// Combine list using language list separator.
$list = implode(get_string('listsep', 'langconfig') . ' ', $list);
// Add last item separated by " and ".
$string = get_string('and', 'moodle', ['one' => $list, 'two' => $last]);
} else {
// Only one item in the list. No formatting required.
$string = $last;
}
return $string;
}
/**
* Convert string containg one or more attribute="value" pairs into an associative array.
*
* @param string $attrs One or more attribute="value" pairs.
* @return array Associative array of attributes and values.
*/
private function attribstoarray($attrs) {
$arr = [];
if (preg_match_all('/\s*(?:([a-z0-9-]+)\s*=\s*"([^"]*)")|(?:\s+([a-z0-9-]+)(?=\s*|>|\s+[a..z0-9]+))/i', $attrs, $matches)) {
// For each attribute in the string, add associated value to the array.
for ($i = 0; $i < count($matches[0]); $i++) {
if ($matches[3][$i]) {
$arr[$matches[3][$i]] = null;
} else {
$arr[$matches[1][$i]] = $matches[2][$i];
}
}
}
return $arr;
}
/**
* Render cards for provided category.
*
* @param object $category Category object.
* @param boolean $categoryshowpic Set to true to display a category image. False displays no image.
* @return string HTML rendering of category cars.
*/
private function rendercategorycard($category, $categoryshowpic) {
global $OUTPUT;
if (!$category->visible) {
$dimmed = 'opacity: 0.5;';
} else {
$dimmed = '';
}
if ($categoryshowpic) {
$imgurl = $OUTPUT->get_generated_image_for_id($category->id + 65535);
$html = '<li class="card shadow mr-4 mb-4 ml-0" style="min-width:290px;max-width:290px;' . $dimmed . '">
<a href="' . new moodle_url('/course/index.php', ['categoryid' => $category->id]);
$html .= '" class="text-white h-100">
<div class="card-img" style="background-image: url(' . $imgurl . ');height:100px;"></div>
<div class="card-img-overlay card-title pt-1 pr-3 pb-1 pl-3 m-0" '
. 'style="height:fit-content;top:auto;background-color:rgba(0,0,0,.4);color:#ffffff;'
. 'text-shadow:-1px -1px 0 #767676, 1px -1px 0 #767676, -1px 1px 0 #767676, 1px 1px 0 #767676">'
. $category->name . '</div>';
} else {
$html = '<li class="card shadow mr-4 mb-4 ml-0 fc-categorycard-' . $category->id .
'" style="min-width:350px;max-width:350px;' . $dimmed . '">' .
'<a href="' . new moodle_url('/course/index.php', ['categoryid' => $category->id]);
$html .= '" class="text-decoration-none h-100 p-4">' . $category->name;
}
$html .= '</a></li>' . PHP_EOL;
return $html;
}
/**
* Render course cards for list of course ids. Not visible for hidden courses or if it has expired.
*
* @param array $rcourseids Array of course ids.
* @param string $format orientation/layout of course cards.
* @return string HTML of course cars.
*/
private function rendercoursecards($rcourseids, $format = 'vertical') {
global $CFG, $OUTPUT, $PAGE, $SITE;
$content = '';
$isadmin = (is_siteadmin() && !is_role_switched($PAGE->course->id));
foreach ($rcourseids as $courseid) {
if ($courseid == $SITE->id) { // Skip site.
continue;
}
$course = get_course($courseid);
$context = context_course::instance($course->id);
// Course will be displayed if its visibility is set to Show AND (either has no end date OR a future end date).
$visible = ($course->visible && (empty($course->enddate) || time() < $course->enddate));
// Courses not visible will be still visible to site admins or users with viewhiddencourses capability.
if (!$visible && !($isadmin || has_capability('moodle/course:viewhiddencourses', $context))) {
// Skip if the course is not visible to user or course is the "site".
continue;
}
// Load image from course image. If none, generate a course image based on the course ID.
$context = context_course::instance($courseid);
if ($course instanceof stdClass) {
$course = new \core_course_list_element($course);
}
$coursefiles = $course->get_course_overviewfiles();
$imgurl = '';
if ($CFG->branch >= 311) {
$imgurl = \core_course\external\course_summary_exporter::get_course_image($course);
} else { // Previous to Moodle 3.11.
foreach ($coursefiles as $file) {
if ($isimage = $file->is_valid_image()) {
// The file_encode_url() function is deprecated as per MDL-31071 but still in wide use.
$imgurl = file_encode_url("/pluginfile.php", '/' . $file->get_contextid() . '/'
. $file->get_component() . '/' . $file->get_filearea() . $file->get_filepath()
. $file->get_filename(), !$isimage);
$imgurl = new moodle_url($imgurl);
break;
}
}
}
if (empty($imgurl)) {
$imgurl = $OUTPUT->get_generated_image_for_id($courseid);
}
$courseurl = new moodle_url('/course/view.php', ['id' => $courseid]);
switch ($format) {
case 'vertical':
$content .= '
<div class="card shadow mr-4 mb-4 ml-1 fc-coursecard-card" style="min-width:300px;max-width:300px;">
<a href="' . $courseurl . '" class="text-normal h-100">
<div class="card-img-top" style="background-image:url(' . $imgurl
. ');height:100px;max-width:300px;padding-top:50%;background-size:cover;'
. 'background-repeat:no-repeat;background-position:center;"></div>
<div class="card-title pt-1 pr-3 pb-1 pl-3 m-0"><span class="sr-only">' . get_string('course') . ': </span>'
. $course->get_formatted_name() . '</div>
</a>
</div>
';
break;
case 'horizontal':
global $DB;
$category = $DB->get_record('course_categories', ['id' => $course->category]);
$category = $category->name;
$summary = $course->summary == null ? '' : $course->summary;
$summary = substr($summary, -4) == '<br>' ? substr($summary, 0, strlen($summary) - 4) : $summary;
$content .= '
<div class="card mb-3 fc-coursecard-list">
<div class="row no-gutter">
<div class="col-md-4">
<a href="' . $courseurl . '" aria-hidden="true" tabindex="-1">
<img src="' . $imgurl . '" class="card-img" alt="">
</a>
</div>
<div class="col-md-8">
<div class="card-body">
<p class="card-text text-category" style="float:right">
<small class="text-muted"><span class="sr-only">'
. get_string('category') . ': </span>' . $category .
'</small>
</p>
<h3 class="card-title">
<a href="' . $courseurl . '" class="text-normal h-100">
<span class="sr-only">' . get_string('course') . ': </span>'
. $course->get_formatted_name() .
'</a>
</h3>
<div class="card-text text-summary"><span class="sr-only">'
. get_string('summary') . ': </span>' . $summary .
'</div>
</div>
</div>
</div>
</div>
';
break;
case 'table':
global $DB;
$category = $DB->get_record('course_categories', ['id' => $course->category]);
$category = $category->name;
$course->summary == null ? '' : $course->summary;
$summary = substr($summary, -4) == '<br>' ? substr($summary, 0, strlen($summary) - 4) : $summary;
$content .= '
<tr class="fc-coursecard-table">
<td class="text-coursename"><a href="' . $courseurl . '">' . $course->get_formatted_name() . '</a></td>
<td class="text-coursecategory">' . $category . '</td>
<td class="text-coursename" style="white-space:normal;">' . $summary . '</td>
</tr>
';
break;
}
}
return $content;
}
/**
* Get course card including format, header and footer.
*
* @param string $format card format.
* @return object $cards->format, $cards->header, $cards->footer
*/
private function getcoursecardinfo($format = null) {
static $cards;
if (is_object($cards)) {
return $cards;
}
$cards = new stdClass();
if (empty($format)) {
$cards->format = get_config('filter_filtercodes', 'coursecardsformat');
} else {
$cards->format = $format;
}
switch ($cards->format) {
case 'table':
$cards->header = '
<table class="table table-hover table-responsive">
<thead>
<tr>
<th scope="col">' . get_string('course') . '</th>
<th scope="col">' . get_string('category') . '</th>
<th scope="col">' . get_string('description') . '</th>
</tr>
</thead>
<tbody>
';
$cards->footer = '
</tbody>
</table>';
break;
case 'horizontal':
$cards->header = '<div class="d-flex"><div>';
$cards->footer = '</div></div>';
break;
default:
$cards->format = 'vertical';
$cards->header = '<div class="card-deck mr-0">';
$cards->footer = '</div>';
}
return $cards;
}
/**
* Generate a user link of a specified type if logged-in.
*
* @param string $clinktype Type of link to generate. Options include: email, message, profile, phone1.
* @param object $user A user object.
* @param string $name The name to be displayed.
*
* @return string Generated link.
*/
private function userlink($clinktype, $user, $name) {
if (!isloggedin() || isguestuser()) {
$clinktype = ''; // No link, only name.
}
switch ($clinktype) {
case 'email':
$link = '<a href="mailto:' . $user->email . '">' . $name . '</a>';
break;
case 'message':
$link = '<a href="' . new moodle_url('/message/index.php', ['id' => $user->id]) . '">' . $name . '</a>';
break;
case 'profile':
$link = '<a href="' . new moodle_url('/user/profile.php', ['id' => $user->id]) . '">' . $name . '</a>';
break;
case 'phone1':
if (!empty($user->phone1)) {
$link = '<a href="tel:' . $user->phone1 . '">' . $name . '</a>';
} else {
$link = $name;
}
break;
default:
$link = $name;
}
return $link;
}
/**
* Generate base64 encoded data img of QR Code.
*
* @param string $text Text to be encoded.
* @param string $label Label to display below QR code.
* @return string Base64 encoded data image.
*/
private function qrcode($text, $label = '') {
if (empty($text)) {
return '';
}
global $CFG;
require_once($CFG->dirroot . '/filter/filtercodes/thirdparty/QrCode/src/QrCode.php');
$code = new QrCode();
$code->setText($text);
$code->setErrorCorrection('high');
$code->setPadding(0);
$code->setSize(480);
$code->setLabelFontSize(16);
$code->setLabel($label);
$src = 'data:image/png;base64,' . base64_encode($code->get('png'));
return $src;
}
/**
* Course completion progress percentage.
*
* @return int completion progress percentage
*/
private function completionprogress() {
static $progresspercent;
if (!isset($progresspercent)) {
global $PAGE;
$course = $PAGE->course;
$progresspercent = -1; // Disabled: -1.
if (
$course->enablecompletion == 1
&& isloggedin()
&& !isguestuser()
&& context_system::instance() != 'page-site-index'
) {
$progresspercent = (int) \core_completion\progress::get_course_progress_percentage($course);
}
}
return $progresspercent;
}
/**
* Generator Tags
*
* This function processes tags that generate content that could potentially include additional tags.
*
* @param string $text The unprocessed text. Passed by refernce.
* @return boolean True of there are more tags to be processed, otherwise false.
*/
private function generatortags(&$text) {
global $CFG, $PAGE, $DB;
$replace = []; // Array of key/value filterobjects.
// Tag: {menuadmin}.
// Description: Displays a menu of useful links for site administrators when added to the custom menu.
// Parameters: None.
if (stripos($text, '{menuadmin}') !== false) {
$theme = $PAGE->theme->name;
$menu = '';
if ($this->hasminarchetype('editingteacher')) {
$menu .= '{fa fa-wrench} {getstring}admin{/getstring}' . PHP_EOL;
}
if ($this->hasminarchetype('coursecreator')) { // If a course creator or above.
$menu .= '-{getstring}administrationsite{/getstring}|/admin/search.php' . PHP_EOL;
$menu .= '-{toggleeditingmenu}' . PHP_EOL;
$menu .= '-Moodle Academy|https://moodle.academy/' . PHP_EOL;
$menu .= '-###' . PHP_EOL;
}
if ($this->hasminarchetype('manager')) { // If a manager or above.
$menu .= '-{getstring}user{/getstring}: {getstring:admin}usermanagement{/getstring}|/admin/user.php' . PHP_EOL;
$menu .= '{ifminsitemanager}' . PHP_EOL;
$menu .= '-{getstring}user{/getstring}: {getstring:mnet}profilefields{/getstring}|/user/profile/index.php' .
PHP_EOL;
$menu .= '-###' . PHP_EOL;
$menu .= '{/ifminsitemanager}' . PHP_EOL;
$menu .= '-{getstring}course{/getstring}: {getstring:admin}coursemgmt{/getstring}|/course/management.php' .
'?categoryid={categoryid}' . PHP_EOL;
$menu .= '-{getstring}course{/getstring}: {getstring}new{/getstring}|/course/edit.php' .
'?category={categoryid}&returnto=topcat' . PHP_EOL;
$menu .= '-{getstring}course{/getstring}: {getstring}searchcourses{/getstring}|/course/search.php' . PHP_EOL;
}
if ($this->hasminarchetype('editingteacher')) {
$menu .= '-{getstring}course{/getstring}: {getstring}restore{/getstring}|/backup/restorefile.php' .
'?contextid={coursecontextid}' . PHP_EOL;
$menu .= '{ifincourse}' . PHP_EOL;
$menu .= '-{getstring}course{/getstring}: {getstring}backup{/getstring}|/backup/backup.php?id={courseid}' .
PHP_EOL;
$menu .= '-{getstring}course{/getstring}: {getstring}participants{/getstring}|/user/index.php?id={courseid}' .
PHP_EOL;
$menu .= '-{getstring}course{/getstring}: {getstring:badges}badges{/getstring}|/badges/index.php' .
'?type={courseid}' . PHP_EOL;
$menu .= '-{getstring}course{/getstring}: {getstring}reports{/getstring}|/course/admin.php' .
'?courseid={courseid}#linkcoursereports' . PHP_EOL;
$menu .= '-{getstring}course{/getstring}: {getstring:enrol}enrolmentinstances{/getstring}|/enrol/instances.php' .
'?id={courseid}' . PHP_EOL;
$menu .= '-{getstring}course{/getstring}: {getstring}reset{/getstring}|/course/reset.php?id={courseid}' . PHP_EOL;
$menu .= '-Course: Layoutit|https://www.layoutit.com/build" target="popup" ' .
'onclick="window.open(\'https://www.layoutit.com/build\',\'popup\',\'width=1340,height=700\');' .
' return false;|Bootstrap Page Builder' . PHP_EOL;
$menu .= '{/ifincourse}' . PHP_EOL;
$menu .= '-###' . PHP_EOL;
}
if ($this->hasminarchetype('manager')) { // If a manager or above.
$menu .= '-{getstring}site{/getstring}: {getstring}reports{/getstring}|/admin/category.php?category=reports' .
PHP_EOL;
}
if (is_siteadmin() && !is_role_switched($PAGE->course->id)) { // If an administrator.
$menu .= '-{getstring}site{/getstring}: {getstring:admin}additionalhtml{/getstring}|/admin/settings.php' .
'?section=additionalhtml' . PHP_EOL;
$menu .= '-{getstring}site{/getstring}: {getstring:admin}frontpage{/getstring}|/admin/settings.php' .
'?section=frontpagesettings|Including site name' . PHP_EOL;
$menu .= '-{getstring}site{/getstring}: {getstring:admin}plugins{/getstring}|/admin/search.php#linkmodules' .
PHP_EOL;
$menu .= '-{getstring}site{/getstring}: {getstring:admin}supportcontact{/getstring}|/admin/settings.php' .
'?section=supportcontact' . PHP_EOL;
$menu .= '-{getstring}site{/getstring}: {getstring:admin}themesettings{/getstring}|/admin/settings.php' .
'?section=themesettings|Including custom menus, designer mode, theme in URL' . PHP_EOL;
if (file_exists($CFG->dirroot . '/theme/' . $theme . '/settings.php')) {
$menu .= '-{getstring}site{/getstring}: {getstring:admin}currenttheme{/getstring}|/admin/settings.php' .
'?section=themesetting' . $theme . PHP_EOL;
}
$menu .= '-{getstring}site{/getstring}: {getstring}notifications{/getstring} ({getstring}admin{/getstring})' .
'|/admin/index.php' . PHP_EOL;
}
$replace['/\{menuadmin\}/i'] = $menu;
}
// Tag: {menudev}.
// Description: Displays a menu of useful links for site administrators when added to the custom menu.
// Parameters: None.
if (stripos($text, '{menudev}') !== false) {
$menu = '';
if (is_siteadmin() && !is_role_switched($PAGE->course->id)) { // If a site administrator.
$menu .= '-{getstring:tool_installaddon}installaddons{/getstring}|/admin/tool/installaddon' . PHP_EOL;
$menu .= '-###' . PHP_EOL;
$menu .= '-{getstring:admin}debugging{/getstring}|/admin/settings.php?section=debugging' . PHP_EOL;
$menu .= '-{getstring:admin}purgecachespage{/getstring}|/admin/purgecaches.php' . PHP_EOL;
$menu .= '-###' . PHP_EOL;
if (file_exists(dirname(__FILE__) . '/../../local/adminer/index.php')) {
$menu .= '-{getstring:local_adminer}pluginname{/getstring}|/local/adminer' . PHP_EOL;
}
if (file_exists(dirname(__FILE__) . '/../../local/codechecker/index.php')) {
$menu .= '-{getstring:local_codechecker}pluginname{/getstring}|/local/codechecker' . PHP_EOL;
}
if (file_exists(dirname(__FILE__) . '/../../local/moodlecheck/index.php')) {
$menu .= '-{getstring:local_moodlecheck}pluginname{/getstring}|/local/moodlecheck' . PHP_EOL;
}
if (file_exists(dirname(__FILE__) . '/../../admin/tool/pluginskel/index.php')) {
$menu .= '-{getstring:tool_pluginskel}pluginname{/getstring}|/admin/tool/pluginskel' . PHP_EOL;
}
if (file_exists(dirname(__FILE__) . '/../../local/tinyfilemanager/index.php')) {
$menu .= '-{getstring:local_tinyfilemanager}pluginname{/getstring}|/local/tinyfilemanager' . PHP_EOL;
}
$menu .= '-{getstring}phpinfo{/getstring}|/admin/phpinfo.php' . PHP_EOL;
$menu .= '-###' . PHP_EOL;
$menu .= '-{getstring:filter_filtercodes}pagebuilder{/getstring}|'
. '{getstring:filter_filtercodes}pagebuilderlink{/getstring}"'
. ' target="popup" onclick="window.open(\'{getstring:filter_filtercodes}pagebuilderlink{/getstring}\''
. ',\'popup\',\'width=1340,height=700\'); return false;' . PHP_EOL;
$menu .= '-{getstring:filter_filtercodes}photoeditor{/getstring}|'
. '{getstring:filter_filtercodes}photoeditorlink{/getstring}"'
. ' target="popup" onclick="window.open(\'{getstring:filter_filtercodes}photoeditorlink{/getstring}\''
. ',\'popup\',\'width=1340,height=700\'); return false;' . PHP_EOL;
$menu .= '-{getstring:filter_filtercodes}screenrec{/getstring}|'
. '{getstring:filter_filtercodes}screenreclink{/getstring}"'
. ' target="popup" onclick="window.open(\'{getstring:filter_filtercodes}screenreclink{/getstring}\''
. ',\'popup\',\'width=1340,height=700\'); return false;' . PHP_EOL;
$menu .= '-###' . PHP_EOL;
$menu .= '-Dev docs|https://moodle.org/development|Moodle.org ({getstring}english{/getstring})' . PHP_EOL;
$menu .= '-Dev forum|https://moodle.org/mod/forum/view.php?id=55|Moodle.org ({getstring}english{/getstring})' .
PHP_EOL;
$menu .= '-Tracker|https://tracker.moodle.org/|Moodle.org ({getstring}english{/getstring})' . PHP_EOL;
$menu .= '-AMOS|https://lang.moodle.org/|Moodle.org ({getstring}english{/getstring})' . PHP_EOL;
$menu .= '-WCAG 2.1|https://www.w3.org/WAI/WCAG21/quickref/|W3C ({getstring}english{/getstring})' . PHP_EOL;
$menu .= '-###' . PHP_EOL;
$menu .= '-DevTuts|https://www.youtube.com/watch?v=UY_pcs4HdDM|{getstring}english{/getstring}' . PHP_EOL;
$menu .= '-Moodle Development School|https://moodledev.moodle.school/|{getstring}english{/getstring}' . PHP_EOL;
$menu .= '-Moodle Dev Academy|https://moodle.academy/course/index.php?categoryid=4|{getstring}english{/getstring}' .
PHP_EOL;
}
$replace['/\{menudev\}/i'] = $menu;
}
// Tag: {menuthemes}.
// Description: Theme switcher for custom menu. Only for administrators. Not available after POST. Allow Theme Changes on URL must be enabled.
// Parameters: None.
if (stripos($text, '{menuthemes}') !== false) {
$menu = '';
if (is_siteadmin() && empty($_POST)) { // If a site administrator.
if (get_config('core', 'allowthemechangeonurl')) {
$url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http")
. "://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
$url .= (strpos($url, '?') ? '&' : '?');
$themeslist = core_component::get_plugin_list('theme');
$menu = '';
foreach ($themeslist as $theme => $themedir) {
$themename = ucfirst(get_string('pluginname', 'theme_' . $theme));
$menu .= '-' . $themename . '|' . $url . 'theme=' . $theme . PHP_EOL;
}
if (!empty($menu)) {
$menu = 'Themes' . PHP_EOL . $menu;
}
}
}
$replace['/\{menuthemes\}/i'] = $menu;
}
// Check if any {course*} or %7Bcourse*%7D tags. Note: There is another course tags section further down.
$coursetagsexist = (stripos($text, '{course') !== false || stripos($text, '%7Bcourse') !== false);
if ($coursetagsexist) {
// Tag: {coursesummary} or {coursesummary courseid}.
// Description: Course summary as defined in the course settings.
// Optional parameters: Course id. Default is to use the current course, or site summary if not in a course.
if (stripos($text, '{coursesummary') !== false) {
if (stripos($text, '{coursesummary}') !== false) {
// No course ID specified.
$coursecontext = context_course::instance($PAGE->course->id);
$PAGE->course->summary == null ? '' : $PAGE->course->summary;
$replace['/\{coursesummary\}/i'] = format_text(
$PAGE->course->summary,
FORMAT_HTML,
['context' => $coursecontext]
);
}
if (stripos($text, '{coursesummary ') !== false) {
// Course ID was specified.
preg_match_all('/\{coursesummary ([0-9]+)\}/', $text, $matches);
// Eliminate course IDs.
$courseids = array_unique($matches[1]);
$coursecontext = context_course::instance($PAGE->course->id);
foreach ($courseids as $id) {
$course = $DB->get_record('course', ['id' => $id]);
if (!empty($course)) {
$course->summary == null ? '' : $course->summary;
$replace['/\{coursesummary ' . $course->id . '\}/isuU'] = format_text(
$course->summary,
FORMAT_HTML,
['context' => $coursecontext]
);
}
}
unset($matches, $course, $courseids, $id);
}
}
}
// Tag: {formquickquestion}
// Tag: {formcheckin}
// Tag: {formcontactus}
// Tag: {formcourserequest}
// Tag: {formsupport}
// Tag: {formsesskey}
//
// Description: Tags used to generate pre-define forms for use with ContactForm plugin.
// Parameters: None.
if (stripos($text, '{form') !== false) {
$pre = '<form action="{wwwcontactform}" method="post" class="cf ';
$post = '</form>';
$options = ['noclean' => true, 'para' => false, 'newlines' => false];
// These require that you already be logged-in.
foreach (['formquickquestion', 'formcheckin'] as $form) {
if (stripos($text, '{' . $form . '}') !== false) {
if (isloggedin() && !isguestuser()) {
$formcode = get_string($form, 'filter_filtercodes');
$replace['/\{' . $form . '\}/i'] = $pre . $form . '">' . get_string($form, 'filter_filtercodes') . $post;
} else {
$replace['/\{' . $form . '\}/i'] = '';
}
}
}
// These work regardless of whether you are logged-in or not.
foreach (['formcontactus', 'formcourserequest', 'formsupport'] as $form) {
if (stripos($text, '{' . $form . '}') !== false) {
$formcode = get_string($form, 'filter_filtercodes');
$replace['/\{' . $form . '\}/i'] = $pre . $form . '">' . $formcode . $post;
} else {
$replace['/\{' . $form . '\}/i'] = '';
}
}
// Tag: {formsesskey}.
if (stripos($text, '{formsesskey}') !== false) {
$replace['/\{formsesskey\}/i'] = '<input type="hidden" id="sesskey" name="sesskey" value="">';
$replace['/\{formsesskey\}/i'] .= '<script>document.getElementById(\'sesskey\').value = M.cfg.sesskey;</script>';
}
}
// Tag: {global_[custom]}.
// Description: Global Custom tags as defined in plugin settings.
// Parameters: custom: Name of custom global tag from FilterCodes settings.
if (stripos($text, '{global_') !== false) {
// Get total number of defined global block tags.
$globaltagcount = get_config('filter_filtercodes', 'globaltagcount');
for ($i = 1; $i <= $globaltagcount; $i++) {
// Get name of tag.
$tag = get_config('filter_filtercodes', 'globalname' . $i);
// If defined and tag exists in the content.
if (!empty($tag) && stripos($text, '{global_' . $tag . '}') !== false) {
// Replace the tag with new content.
$content = get_config('filter_filtercodes', 'globalcontent' . $i);
$replace['/\{global_' . $tag . '\}/i'] = $content;
}
}
unset($i);
unset($globaltagcount);
unset($tag);
unset($content);
}
// Tag: {teamcards}.
// Description: Displays a series of card for each contact on the site. Configurable in FilterCodes settings.
// Note: Included selected roles in Site Administration > Appearance > Course > Course Contacts.
// Parameters: None.
if (stripos($text, '{teamcards}') !== false) {