forked from michael-milette/moodle-filter_filtercodes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfilter.php
2735 lines (2505 loc) · 133 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 - http://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 <http://www.gnu.org/licenses/>.
/**
* Main filter code for FilterCodes.
*
* @package filter_filtercodes
* @copyright 2017-2021 TNG Consulting Inc. - www.tngconsulting.ca
* @author Michael Milette
* @license http://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;
require_once($CFG->dirroot . '/course/renderer.php');
/**
* Extends the moodle_text_filter class to provide plain text support for new tags.
*
* @copyright 2017-2021 TNG Consulting Inc. - www.tngconsulting.ca
* @license http://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];
}
/**
* 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.
* @return string URL to the photo image file but with $1 for the size.
*/
private function getprofilepictureurl($user) {
if (isloggedin() && !isguestuser() && $user->picture > 0) {
$usercontext = context_user::instance($user->id, IGNORE_MISSING);
$url = moodle_url::make_pluginfile_url($usercontext->id, 'user', 'icon', null, '/', "f$1")
. '?rev=' . $user->picture;
} else {
// If the user does not have a profile picture, use the default faceless picture.
global $PAGE, $CFG;
$renderer = $PAGE->get_renderer('core');
if ($CFG->branch >= 33) {
$url = $renderer->image_url('u/f$1');
} else {
$url = $renderer->pix_url('u/f$1'); // Deprecated as of Moodle 3.3.
}
}
return str_replace('/f%24', '/f$', $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;
}
/**
* 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;
}
/**
* Render course cards for list of course ids.
*
* @param array $rcourseids Array of course ids.
* @return string HTML of course cars.
*/
private function rendercoursecards($rcourseids) {
global $OUTPUT, $PAGE;
$content = '';
$isadmin = (is_siteadmin() && !is_role_switched($PAGE->course->id));
foreach ($rcourseids as $courseid) {
$course = get_course($courseid);
// Skip this course if end-date is past or course is not visible, unless you are an admin.
if (!$isadmin && !empty($course->enddate) && $course->enddate < time() && empty($course->visible)) {
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 = '';
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]);
$content .= '
<div class="card shadow mr-4 mb-4 ml-1" 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">' . $course->get_formatted_name() . '</div>
</a>
</div>
';
}
return $content;
}
/**
* Main filter function called by Moodle.
*
* @param string $text Content to be filtered.
* @param array $options Moodle filter options. None are implemented in this plugin.
* @return string Content with filters applied.
*/
public function filter($text, array $options = []) {
global $CFG, $SITE, $PAGE, $USER, $DB;
if (strpos($text, '{') === false && strpos($text, '%7B') === false) {
return $text;
}
$replace = []; // Array of key/value filterobjects.
$changed = false; // Will be true if there were any changes.
// Handle escaped tags to be ignored.
// Determine if the option to {escape braces}] is enabled.
if (!empty(get_config('filter_filtercodes', 'escapebraces'))) {
// Temporarily escaped tags these with non-printable character. Will be re-adjusted after processing tags.
$escapedtags = (strpos($text, '[{') !== false && strpos($text, '}]') !== false);
if ($escapedtags) {
$text = str_replace('[{', chr(2), $text);
$text = str_replace('}]', chr(3), $text);
}
// Temporarily escaped tags these with non-printable character. Will be re-adjusted after processing tags.
$escapedtagsenc = (strpos($text, '[%7B') !== false && strpos($text, '%7D]') !== false);
if ($escapedtagsenc) {
$text = str_replace('[%7B', chr(4), $text);
$text = str_replace('%7D]', chr(5), $text);
}
} else {
$escapedtags = false;
$escapedtagsenc = false;
}
// START: Process tags that may end up containing other tags first.
// This tag: {form...}.
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]}. Global Custom tags as defined in plugin 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: {coursesummary}.
if (stripos($text, '{coursesummary}') !== false) {
$replace['/\{coursesummary\}/i'] = $PAGE->course->summary;
}
// This tag: {menuadmin}.
if (stripos($text, '{menuadmin}') !== false) {
$theme = $PAGE->theme->name;
$menu = '';
$menu .= '{ifminteacher}' . PHP_EOL;
$menu .= '{fa fa-wrench} {getstring}admin{/getstring}' . PHP_EOL;
$menu .= '{/ifminteacher}' . PHP_EOL;
$menu .= '{ifmincreator}' . PHP_EOL;
$menu .= '-{getstring}administrationsite{/getstring}|/admin/search.php' . PHP_EOL;
$menu .= '-{toggleeditingmenu}' . PHP_EOL;
$menu .= '-Learn Moodle|https://learn.moodle.org/" target="_blank' . PHP_EOL;
$menu .= '-Moodle Academy|https://moodle.academy/" target="_blank' . PHP_EOL;
$menu .= '-###' . PHP_EOL;
$menu .= '{/ifmincreator}' . PHP_EOL;
$menu .= '{ifminmanager}' . PHP_EOL;
$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' . PHP_EOL;
$menu .= '-{getstring}course{/getstring}: {getstring}new{/getstring}|/course/edit.php?category={coursecategoryid}&returnto=topcat' . PHP_EOL;
$menu .= '-{getstring}course{/getstring}: {getstring}searchcourses{/getstring}|/course/search.php' . PHP_EOL;
$menu .= '{/ifminmanager}' . PHP_EOL;
$menu .= '{ifminteacher}' . PHP_EOL;
$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;
$menu .= '{/ifminteacher}' . PHP_EOL;
$menu .= '{ifminmanager}' . PHP_EOL;
$menu .= '-{getstring}site{/getstring}: {getstring}reports{/getstring}|/admin/category.php?category=reports' . PHP_EOL;
$menu .= '{/ifminmanager}' . PHP_EOL;
$menu .= '{ifadmin}' . PHP_EOL;
$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;
$menu .= '{/ifadmin}' . PHP_EOL;
$replace['/\{menuadmin\}/i'] = $menu;
}
// This tag: {menudev}.
if (stripos($text, '{menudev}') !== false) {
$menu = '';
$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;
}
$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 .= '-MoodleDev docs|https://moodle.org/development|Moodle.org ({getstring}english{/getstring})' . PHP_EOL;
$menu .= '-MoodleDev 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 Academy|https://moodle.academy/|{getstring}english{/getstring}' . PHP_EOL;
$replace['/\{menudev\}/i'] = $menu;
}
// Apply all of the filtercodes so far.
$newtext = null;
if (count($replace) > 0) {
$newtext = preg_replace(array_keys($replace), array_values($replace), $text);
}
if (!is_null($newtext)) {
$text = $newtext;
$changed = true;
}
$replace = [];
// END: Process tags that may end up containing other tags first.
//
// FilterCodes extended (future feature).
//
if (file_exists(dirname(__FILE__) . '/filter-ext.php')) {
include(dirname(__FILE__) . '/filter-ext.php');
}
// Social field migrated from pre-Moodle 3.11 - for backwards compatibility.
if (stripos($text, '{webpage}') !== false) {
if ($CFG->branch >= 311) {
$text = str_replace('{webpage}', '{profile_field_webpage}', $text);
} else {
$replace['/\{webpage\}/i'] = isloggedin() && !isguestuser() ? $USER->url : '';
}
}
if (stripos($text, '{profile') !== false) {
// Tag: {profile_field_...}.
// Custom Profile Fields.
if (stripos($text, '{profile_field') !== false) {
$isuser = (isloggedin() && !isguestuser());
// Cached the defined custom profile fields and data.
static $profilefields;
static $profiledata;
if (!isset($profilefields)) {
$profilefields = $DB->get_records('user_info_field', null, '', 'id, datatype, shortname, visible, param3');
if ($isuser && !empty($profilefields)) {
$profiledata = $DB->get_records_menu('user_info_data', ['userid' => $USER->id], '', 'fieldid, data');
}
}
foreach ($profilefields as $field) {
// If the tag exists and is not set to "Not visible" in the custom profile field's settings.
if ($isuser
&& stripos($text, '{profile_field_' . $field->shortname . '}') !== false
&& $field->visible != '0') {
$data = isset($profiledata[$field->id]) ? trim($profiledata[$field->id]) : '' . PHP_EOL;
switch ($field->datatype) { // Format data for some field types.
case 'datetime':
// Include date and time or just date?
$datetimeformat = !empty($field->param3) ? 'strftimedaydatetime' : 'strftimedate';
$data = empty($data) ? '' : userdate($data, get_string($datetimeformat, 'langconfig'));
break;
case 'checkbox':
// 1 = Yes, 0 = No
$data = empty($data) ? get_string('no') : get_string('yes');
break;
}
$replace['/\{profile_field_' . $field->shortname . '\}/i'] = $data;
} else {
$replace['/\{profile_field_' . $field->shortname . '\}/i'] = '';
}
}
}
// Tag: {profilefullname}.
if (stripos($text, '{profilefullname}') !== false) {
$fullname = '';
if (isloggedin() && !isguestuser()) {
$fullname = get_string('fullnamedisplay', null, $USER);
if ($PAGE->pagelayout == 'mypublic' && $PAGE->pagetype == 'user-profile') {
$userid = optional_param('userid', optional_param('user',
optional_param('id', $USER->id, PARAM_INT), PARAM_INT), PARAM_INT);
if ($user = $DB->get_record('user', ['id' => $userid, 'deleted' => 0])) {
$fullname = get_string('fullnamedisplay', null, $user);
}
}
}
$replace['/\{profilefullname\}/i'] = $fullname;
unset($fullname);
}
}
// Substitutions.
$u = $USER;
if (!isloggedin() || isguestuser()) {
$u->firstname = get_string('defaultfirstname', 'filter_filtercodes');
$u->lastname = get_string('defaultsurname', 'filter_filtercodes');
}
$u->fullname = trim(get_string('fullnamedisplay', null, $u));
// Tag: {firstname}.
if (stripos($text, '{firstname}') !== false) {
$replace['/\{firstname\}/i'] = $u->firstname;
}
// Tag: {surname}.
if (stripos($text, '{surname}') !== false) {
$replace['/\{surname\}/i'] = $u->lastname;
}
// Tag: {lastname} (same as surname... just easier to remember).
if (stripos($text, '{lastname}') !== false) {
$replace['/\{lastname\}/i'] = $u->lastname;
}
// Tag: {fullname}.
if (stripos($text, '{fullname}') !== false) {
$replace['/\{fullname\}/i'] = $u->fullname;
}
// Tag: {alternatename}.
if (stripos($text, '{alternatename}') !== false) {
// If alternate name is empty, use firstname instead.
if (isloggedin() && !isguestuser() && !empty(trim($USER->alternatename))) {
$replace['/\{alternatename\}/i'] = $USER->alternatename;
} else {
$replace['/\{alternatename\}/i'] = $u->firstname;
}
}
// Tag: {email}.
if (stripos($text, '{email}') !== false) {
$replace['/\{email\}/i'] = isloggedin() && !isguestuser() ? $USER->email : '';
}
// Tag: {city}.
if (stripos($text, '{city}') !== false) {
$replace['/\{city\}/i'] = isloggedin() && !isguestuser() ? $USER->city : '';
}
// Tag: {country}.
if (stripos($text, '{country}') !== false) {
$replace['/\{country\}/i'] = isloggedin() && !isguestuser() && !empty($USER->country)
? get_string($USER->country, 'countries') : '';
}
// Tag: {timezone}.
if (stripos($text, '{timezone}') !== false) {
$replace['/\{timezone\}/i'] = isloggedin() && !isguestuser() && !empty($USER->timezone)
? core_date::get_localised_timezone($USER->timezone) : '';
}
// Tag: {preferredlanguage}.
if (stripos($text, '{preferredlanguage}') !== false) {
if (isloggedin() && !isguestuser()) {
if ('en' == $USER->lang) {
$langconfig = $CFG->dirroot . '/lang/en/langconfig.php';
} else {
$langconfig = $CFG->dataroot . '/lang/' . $USER->lang . '/langconfig.php';
}
// Ignore parents here for now.
$string = [];
include($langconfig);
if (!empty($string['thislanguage'])) {
$replace['/\{preferredlanguage\}/i'] = '<span lang="' . $string['iso6391'] . '">' . $string['thislanguage']
. '</span>';
} else { // This should never happen since the known user already exists.
$replace['/\{preferredlanguage\}/i'] = get_string('unknown', 'notes');
}
} else {
$replace['/\{preferredlanguage\}/i'] = '';
}
}
// Tag: {institution}.
if (stripos($text, '{institution}') !== false) {
$replace['/\{institution\}/i'] = isloggedin() && !isguestuser() ? $USER->institution : '';
}
// Tag: {department}.
if (stripos($text, '{department}') !== false) {
$replace['/\{department\}/i'] = isloggedin() && !isguestuser() ? $USER->department : '';
}
// Tag: {idnumber}.
if (stripos($text, '{idnumber}') !== false) {
$replace['/\{idnumber\}/i'] = isloggedin() && !isguestuser() ? $USER->idnumber : '';
}
// Tag: {firstaccessdate} or {firstaccessdate dateTimeFormat}.
if (stripos($text, '{firstaccessdate') !== false) {
if (isloggedin() && !isguestuser() && !empty($USER->firstaccess)) {
// Replace {firstaccessdate} tag with formatted date.
if (stripos($text, '{firstaccessdate}') !== false) {
$replace['/\{firstaccessdate\}/i'] = userdate($USER->firstaccess, get_string('strftimedatefullshort'));
}
// Replace {firstaccessdate dateTimeFormat} tag and parameters with formatted date.
if (stripos($text, '{firstaccessdate ') !== false) {
$newtext = preg_replace_callback('/\{firstaccessdate\s+(.+)\}/i',
function ($matches) use ($USER) {
// Hack to remove everything after the closing }, if it is still there.
// TODO: Improve regex above to support PHP strftime strings.
$matches[1] = strtok($matches[1], '}');
// Check if this is a built-in Moodle date/time format.
if (get_string_manager()->string_exists($matches[1], 'langconfig')) {
// It is! Get the strftime string.
$matches[1] = get_string($matches[1], 'langconfig');
}
return userdate($USER->firstaccess, $matches[1]);
},
$text
);
if ($newtext !== false) {
$text = $newtext;
$changed = true;
}
}
} else {
$replace['/\{firstaccessdate(.*)\}/i'] = get_string('never');
}
}
if (get_config('filter_filtercodes', 'enable_scrape')) { // Must be enabled in FilterCodes settings.
// Tag: {scrape url="" tag="" class="" id="" code=""}.
if (stripos($text, '{scrape ') !== false) {
// Replace {scrape} tag and parameters with retrieved content.
$newtext = preg_replace_callback('/\{scrape\s+(.*?)\}/i',
function ($matches) {
$scrape = '<' . substr($matches[0], 1, -1) . '/>';
$scrape = new SimpleXMLElement($scrape);
$url = (string) $scrape->attributes()->url;
$tag = (string) $scrape->attributes()->tag;
$class = (string) $scrape->attributes()->class;
$id = (string) $scrape->attributes()->id;
$code = (string) $scrape->attributes()->code;
if (empty($url)) {
return "SCRAPE error: Missing required URL parameter.";
}
return $this->scrapehtml($url, $tag, $class, $id, $code);
}, $text);
if ($newtext !== false) {
$text = $newtext;
$changed = true;
}
}
}
// Tag: {diskfreespace} - free space of Moodle application volume.
if (stripos($text, '{diskfreespace}') !== false) {
$bytes = @disk_free_space('.');
$replace['/\{diskfreespace\}/i'] = $this->humanbytes($bytes);
}
// Tag: {diskfreespacedata} - free space of Moodledata volume.
if (stripos($text, '{diskfreespacedata}') !== false) {
$bytes = @disk_free_space($CFG->dataroot);
$replace['/\{diskfreespacedata\}/i'] = $this->humanbytes($bytes);
}
// Any {user*} tags.
if (stripos($text, '{user') !== false || stripos($text, '%7Buser') !== false) {
// Tag: {username}.
if (stripos($text, '{username}') !== false) {
$replace['/\{username\}/i'] = isloggedin()
&& !isguestuser() ? $USER->username : get_string('defaultusername', 'filter_filtercodes');
}
// Tag: {userid}.
if (stripos($text, '{userid}') !== false) {
$replace['/\{userid\}/i'] = $USER->id;
}
// Alternative Tag: %7Buserid%7D (for encoded URLs).
if (stripos($text, '%7Buserid%7D') !== false) {
$replace['/%7Buserid%7D/i'] = $USER->id;
}
// These tags: {userpictureurl} and {userpictureimg}.
if (stripos($text, '{userpicture') !== false) {
// Tag: {userpictureurl size}. User photo URL.
// Sizes: 2 or sm (small), 1 or md (medium), 3 or lg (large).
if (stripos($text, '{userpictureurl ') !== false) {
$url = $this->getprofilepictureurl($USER);
// Substitute the $1 in URL with value of (\w+), making sure to substitute text versions into numbers.
$newtext = preg_replace_callback('/\{userpictureurl\s+(\w+)\}/i',
function ($matches) {
$sublist = ['sm' => '2', '2' => '2', 'md' => '1', '1' => '1', 'lg' => '3', '3' => '3'];
return '{userpictureurl ' . $sublist[$matches[1]] . '}';
}, $text);
if ($newtext !== false) {
$text = $newtext;
$changed = true;
}
$replace['/\{userpictureurl\s+(\w+)\}/i'] = $url;
}
// Tag: {userpictureimg size}. User photo URL wrapped in HTML image tag.
// Sizes: 2 or sm (small), 1 or md (medium), 3 or lg (large).
if (stripos($text, '{userpictureimg ') !== false) {
$url = $this->getprofilepictureurl($USER);
$tag = '<img src="' . $url . '" alt="' . $u->fullname . '" class="userpicture">';
// Will substitute the $1 in URL with value of (\w+).
$newtext = preg_replace_callback('/\{userpictureimg\s+(\w+)\}/i',
function ($matches) {
$sublist = ['sm' => '2', '2' => '2', 'md' => '1', '1' => '1', 'lg' => '3', '3' => '3'];
return '{userpictureimg ' . $sublist[$matches[1]] . '}';
}, $text);
if ($newtext !== false) {
$text = $newtext;
$changed = true;
}
$replace['/\{userpictureimg\s+(\w+)\}/i'] = $tag;
}
}
// Tag: {userdescription}.
if (stripos($text, '{userdescription}') !== false) {
if (isloggedin() && !isguestuser()) {
$user = $DB->get_record('user', ['id' => $USER->id], 'description', MUST_EXIST);
$replace['/\{userdescription\}/i'] = format_text($user->description, $USER->descriptionformat);
unset($user);
} else {
$replace['/\{userdescription\}/i'] = '';
}
}
// Tag: {usercount}.
if (stripos($text, '{usercount}') !== false) {
// Count total number of current users on the site.
// Exclude deleted users, admin and guest.
$cnt = $DB->count_records('user', ['deleted' => 0]) - 2;
$replace['/\{usercount\}/i'] = $cnt;
}
// Tag: {usersactive}.
if (stripos($text, '{usersactive}') !== false) {
// Count total number of current users on the site.
// Exclude deleted, suspended and unconfirmed users, admin and guest.
$cnt = $DB->count_records('user', ['deleted' => 0, 'suspended' => 0, 'confirmed' => 1]) - 2;
$replace['/\{usersactive\}/i'] = $cnt;
}
// Tag: {usersonline}.
if (stripos($text, '{usersonline}') !== false) {
$timetosee = 300; // Within last number of seconds (300 = 5 minutes).
if (isset($CFG->block_online_users_timetosee)) {
$timetosee = $CFG->block_online_users_timetosee * 60;
}
$now = time();
// Calculate if we are in separate groups.
$isseparategroups = ($PAGE->course->groupmode == SEPARATEGROUPS
&& $PAGE->course->groupmodeforce
&& !has_capability('moodle/site:accessallgroups', $PAGE->context));
// Get the user current group.
$thisgroup = $isseparategroups ? groups_get_course_group($PAGE->course) : null;
$onlineusers = new fetcher($thisgroup, $now, $timetosee, $PAGE->context,
$PAGE->context->contextlevel, $PAGE->course->id);
// Count online users.
$usersonline = $onlineusers->count_users();
$replace['/\{usersonline\}/i'] = $usersonline;
}
// Tag: {userscountrycount}.
if (stripos($text, '{userscountrycount}') !== false) {
$count = $DB->count_records_sql('SELECT COUNT(DISTINCT country) FROM {user} WHERE id > 2');
$replace['/\{userscountrycount\}/i'] = $count;
}
}
// Any {course*} or %7Bcourse*%7D tags.
if (stripos($text, '{course') !== false || stripos($text, '%7Bcourse') !== false) {
// Tag: {coursegradepercent} - Calculate and display current overall course grade as a percentage.
if (stripos($text, '{coursegradepercent}') !== false) {
require_once($CFG->libdir . '/gradelib.php');
require_once($CFG->dirroot . '/grade/querylib.php');
$gradeobj = grade_get_course_grade($USER->id, $PAGE->course->id);
if (!empty($grademax = floatval($gradeobj->item->grademax))) {
// Avoid divide by 0 error if no grades have been defined.
$grade = (int) ($gradeobj->grade / floatval($grademax) * 100) ?? 0;
} else {
$grade = 0;
}
$replace['/\{coursegradepercent\}/i'] = $grade;
}
// Custom Course Fields - First implemented in Moodle 3.7.
if ($CFG->branch >= 37) {
// Tag: {course_field_shortname}.
if (stripos($text, '{course_field_') !== false) {
// Cached the custom course field data.
static $coursefields;
if (!isset($coursefields)) {
$handler = core_course\customfield\course_handler::create();
$coursefields = $handler->export_instance_data_object($PAGE->course->id, true);
$fieldsvisible = $handler->export_instance_data_object($PAGE->course->id);
// Blank out the fields that should not be displayed.
foreach ($coursefields as $field => $value) {
if (empty($fieldsvisible->$field)) {
$coursefields->$field = '';
}
}
}
foreach ($coursefields as $field => $value) {
$shortname = strtolower($field);
// If the tag exists and it is not hidden in the custom course field's settings.
if (stripos($text, '{course_field_' . $shortname . '}') !== false) {
$replace['/\{course_field_' . $shortname . '\}/i'] = $value;
}
}
}
// Tag: {course_fields}.
if (stripos($text, '{course_fields}') !== false) {
// Display all custom course fields.
$customfields = '';
if ($PAGE->course instanceof stdClass) {
$thiscourse = new \core_course_list_element($PAGE->course);
}
if ($thiscourse->has_custom_fields()) {
$handler = \core_course\customfield\course_handler::create();
$customfields = $handler->display_custom_fields_data($thiscourse->get_custom_fields());
}