forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
filterlib.php
1445 lines (1289 loc) · 52.7 KB
/
filterlib.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/>.
/**
* Library functions for managing text filter plugins.
*
* @package core
* @subpackage filter
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
/** The states a filter can be in, stored in the filter_active table. */
define('TEXTFILTER_ON', 1);
/** The states a filter can be in, stored in the filter_active table. */
define('TEXTFILTER_INHERIT', 0);
/** The states a filter can be in, stored in the filter_active table. */
define('TEXTFILTER_OFF', -1);
/** The states a filter can be in, stored in the filter_active table. */
define('TEXTFILTER_DISABLED', -9999);
/**
* Define one exclusive separator that we'll use in the temp saved tags
* keys. It must be something rare enough to avoid having matches with
* filterobjects. MDL-18165
*/
define('TEXTFILTER_EXCL_SEPARATOR', '-%-');
/**
* Class to manage the filtering of strings. It is intended that this class is
* only used by weblib.php. Client code should probably be using the
* format_text and format_string functions.
*
* This class is a singleton.
*
* @package core
* @subpackage filter
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class filter_manager {
/**
* @var array This list of active filters, by context, for filtering content.
* An array contextid => array of filter objects.
*/
protected $textfilters = array();
/**
* @var array This list of active filters, by context, for filtering strings.
* An array contextid => array of filter objects.
*/
protected $stringfilters = array();
/** @var array Exploded version of $CFG->stringfilters. */
protected $stringfilternames = array();
/** @var object Holds the singleton instance. */
protected static $singletoninstance;
protected function __construct() {
$this->stringfilternames = filter_get_string_filters();
}
/**
* @return filter_manager the singleton instance.
*/
public static function instance() {
global $CFG;
if (is_null(self::$singletoninstance)) {
if (!empty($CFG->perfdebug)) {
self::$singletoninstance = new performance_measuring_filter_manager();
} else {
self::$singletoninstance = new self();
}
}
return self::$singletoninstance;
}
/**
* Load all the filters required by this context.
*
* @param object $context
*/
protected function load_filters($context) {
$filters = filter_get_active_in_context($context);
$this->textfilters[$context->id] = array();
$this->stringfilters[$context->id] = array();
foreach ($filters as $filtername => $localconfig) {
$filter = $this->make_filter_object($filtername, $context, $localconfig);
if (is_null($filter)) {
continue;
}
$this->textfilters[$context->id][] = $filter;
if (in_array($filtername, $this->stringfilternames)) {
$this->stringfilters[$context->id][] = $filter;
}
}
}
/**
* Factory method for creating a filter
*
* @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
* @param object $context context object.
* @param array $localconfig array of local configuration variables for this filter.
* @return object moodle_text_filter The filter, or null, if this type of filter is
* not recognised or could not be created.
*/
protected function make_filter_object($filtername, $context, $localconfig) {
global $CFG;
$path = $CFG->dirroot .'/'. $filtername .'/filter.php';
if (!is_readable($path)) {
return null;
}
include_once($path);
$filterclassname = 'filter_' . basename($filtername);
if (class_exists($filterclassname)) {
return new $filterclassname($context, $localconfig);
}
// TODO: deprecated since 2.2, will be out in 2.3, see MDL-29996
$legacyfunctionname = basename($filtername) . '_filter';
if (function_exists($legacyfunctionname)) {
return new legacy_filter($legacyfunctionname, $context, $localconfig);
}
return null;
}
/**
* @todo Document this function
* @param string $text
* @param array $filterchain
* @param array $options options passed to the filters
* @return string $text
*/
protected function apply_filter_chain($text, $filterchain, array $options = array()) {
foreach ($filterchain as $filter) {
$text = $filter->filter($text, $options);
}
return $text;
}
/**
* @todo Document this function
* @param object $context
* @return object A text filter
*/
protected function get_text_filters($context) {
if (!isset($this->textfilters[$context->id])) {
$this->load_filters($context);
}
return $this->textfilters[$context->id];
}
/**
* @todo Document this function
* @param object $context
* @return object A string filter
*/
protected function get_string_filters($context) {
if (!isset($this->stringfilters[$context->id])) {
$this->load_filters($context);
}
return $this->stringfilters[$context->id];
}
/**
* Filter some text
*
* @param string $text The text to filter
* @param object $context
* @param array $options options passed to the filters
* @return string resulting text
*/
public function filter_text($text, $context, array $options = array()) {
$text = $this->apply_filter_chain($text, $this->get_text_filters($context), $options);
/// <nolink> tags removed for XHTML compatibility
$text = str_replace(array('<nolink>', '</nolink>'), '', $text);
return $text;
}
/**
* Filter a piece of string
*
* @param string $string The text to filter
* @param object $context
* @return string resulting string
*/
public function filter_string($string, $context) {
return $this->apply_filter_chain($string, $this->get_string_filters($context));
}
/**
* @todo Document this function
* @param object $context
* @return object A string filter
*/
public function text_filtering_hash($context) {
$filters = $this->get_text_filters($context);
$hashes = array();
foreach ($filters as $filter) {
$hashes[] = $filter->hash();
}
return implode('-', $hashes);
}
}
/**
* Filter manager subclass that does nothing. Having this simplifies the logic
* of format_text, etc.
*
* @todo Document this class
*
* @package core
* @subpackage filter
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class null_filter_manager {
/**
* @return string
*/
public function filter_text($text, $context, $options) {
return $text;
}
/**
* @return string
*/
public function filter_string($string, $context) {
return $string;
}
/**
* @return string
*/
public function text_filtering_hash() {
return '';
}
}
/**
* Filter manager subclass that tacks how much work it does.
*
* @todo Document this class
*
* @package core
* @subpackage filter
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class performance_measuring_filter_manager extends filter_manager {
/** @var int */
protected $filterscreated = 0;
protected $textsfiltered = 0;
protected $stringsfiltered = 0;
/**
* @param string $filtername
* @param object $context
* @param mixed $localconfig
* @return mixed
*/
protected function make_filter_object($filtername, $context, $localconfig) {
$this->filterscreated++;
return parent::make_filter_object($filtername, $context, $localconfig);
}
/**
* @param string $text
* @param object $context
* @param array $options options passed to the filters
* @return mixed
*/
public function filter_text($text, $context, array $options = array()) {
$this->textsfiltered++;
return parent::filter_text($text, $context, $options);
}
/**
* @param string $string
* @param object $context
* @return mixed
*/
public function filter_string($string, $context) {
$this->stringsfiltered++;
return parent::filter_string($string, $context);
}
/**
* @return array
*/
public function get_performance_summary() {
return array(array(
'contextswithfilters' => count($this->textfilters),
'filterscreated' => $this->filterscreated,
'textsfiltered' => $this->textsfiltered,
'stringsfiltered' => $this->stringsfiltered,
), array(
'contextswithfilters' => 'Contexts for which filters were loaded',
'filterscreated' => 'Filters created',
'textsfiltered' => 'Pieces of content filtered',
'stringsfiltered' => 'Strings filtered',
));
}
}
/**
* Base class for text filters. You just need to override this class and
* implement the filter method.
*
* @package core
* @subpackage filter
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
abstract class moodle_text_filter {
/** @var object The context we are in. */
protected $context;
/** @var array Any local configuration for this filter in this context. */
protected $localconfig;
/**
* Set any context-specific configuration for this filter.
* @param object $context The current course id.
* @param object $context The current context.
* @param array $config Any context-specific configuration for this filter.
*/
public function __construct($context, array $localconfig) {
$this->context = $context;
$this->localconfig = $localconfig;
}
/**
* @return string The class name of the current class
*/
public function hash() {
return __CLASS__;
}
/**
* Override this function to actually implement the filtering.
*
* @param $text some HTML content.
* @param array $options options passed to the filters
* @return the HTML content after the filtering has been applied.
*/
public abstract function filter($text, array $options = array());
}
/**
* moodle_text_filter implementation that encapsulates an old-style filter that
* only defines a function, not a class.
*
* @deprecated since 2.2, see MDL-29995
* @todo will be out in 2.3, see MDL-29996
* @package core
* @subpackage filter
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class legacy_filter extends moodle_text_filter {
/** @var string */
protected $filterfunction;
protected $courseid;
/**
* Set any context-specific configuration for this filter.
*
* @param string $filterfunction
* @param object $context The current context.
* @param array $config Any context-specific configuration for this filter.
*/
public function __construct($filterfunction, $context, array $localconfig) {
parent::__construct($context, $localconfig);
$this->filterfunction = $filterfunction;
$this->courseid = get_courseid_from_context($this->context);
}
/**
* @param string $text
* @param array $options options - not supported for legacy filters
* @return mixed
*/
public function filter($text, array $options = array()) {
if ($this->courseid) {
// old filters are called only when inside courses
return call_user_func($this->filterfunction, $this->courseid, $text);
} else {
return $text;
}
}
}
/**
* This is just a little object to define a phrase and some instructions
* for how to process it. Filters can create an array of these to pass
* to the filter_phrases function below.
*
* @package core
* @subpackage filter
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
**/
class filterobject {
/** @var string */
var $phrase;
var $hreftagbegin;
var $hreftagend;
/** @var bool */
var $casesensitive;
var $fullmatch;
/** @var mixed */
var $replacementphrase;
var $work_phrase;
var $work_hreftagbegin;
var $work_hreftagend;
var $work_casesensitive;
var $work_fullmatch;
var $work_replacementphrase;
/** @var bool */
var $work_calculated;
/**
* A constructor just because I like constructing
*
* @param string $phrase
* @param string $hreftagbegin
* @param string $hreftagend
* @param bool $casesensitive
* @param bool $fullmatch
* @param mixed $replacementphrase
*/
function filterobject($phrase, $hreftagbegin = '<span class="highlight">',
$hreftagend = '</span>',
$casesensitive = false,
$fullmatch = false,
$replacementphrase = NULL) {
$this->phrase = $phrase;
$this->hreftagbegin = $hreftagbegin;
$this->hreftagend = $hreftagend;
$this->casesensitive = $casesensitive;
$this->fullmatch = $fullmatch;
$this->replacementphrase= $replacementphrase;
$this->work_calculated = false;
}
}
/**
* Look up the name of this filter in the most appropriate location.
* If $filterlocation = 'mod' then does get_string('filtername', $filter);
* else if $filterlocation = 'filter' then does get_string('filtername', 'filter_' . $filter);
* with a fallback to get_string('filtername', $filter) for backwards compatibility.
* These are the only two options supported at the moment.
*
* @param string $filter the folder name where the filter lives.
* @return string the human-readable name for this filter.
*/
function filter_get_name($filter) {
// TODO: should we be using pluginname here instead? , see MDL-29998
list($type, $filter) = explode('/', $filter);
switch ($type) {
case 'filter':
$strfiltername = get_string('filtername', 'filter_' . $filter);
if (substr($strfiltername, 0, 2) != '[[') {
// found a valid string.
return $strfiltername;
}
// Fall through to try the legacy location.
// TODO: deprecated since 2.2, will be out in 2.3, see MDL-29996
case 'mod':
$strfiltername = get_string('filtername', $filter);
if (substr($strfiltername, 0, 2) == '[[') {
$strfiltername .= ' (' . $type . '/' . $filter . ')';
}
return $strfiltername;
default:
throw new coding_exception('Unknown filter type ' . $type);
}
}
/**
* Get the names of all the filters installed in this Moodle.
*
* @global object
* @return array path => filter name from the appropriate lang file. e.g.
* array('mod/glossary' => 'Glossary Auto-linking', 'filter/tex' => 'TeX Notation');
* sorted in alphabetical order of name.
*/
function filter_get_all_installed() {
global $CFG;
$filternames = array();
// TODO: deprecated since 2.2, will be out in 2.3, see MDL-29996
$filterlocations = array('mod', 'filter');
foreach ($filterlocations as $filterlocation) {
// TODO: move get_list_of_plugins() to get_plugin_list()
$filters = get_list_of_plugins($filterlocation);
foreach ($filters as $filter) {
// MDL-29994 - Ignore mod/data and mod/glossary filters forever, this will be out in 2.3
if ($filterlocation == 'mod' && ($filter == 'data' || $filter == 'glossary')) {
continue;
}
$path = $filterlocation . '/' . $filter;
if (is_readable($CFG->dirroot . '/' . $path . '/filter.php')) {
$strfiltername = filter_get_name($path);
$filternames[$path] = $strfiltername;
}
}
}
collatorlib::asort($filternames);
return $filternames;
}
/**
* Set the global activated state for a text filter.
*
* @global object
* @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
* @param integer $state One of the values TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_DISABLED.
* @param integer $sortorder (optional) a position in the sortorder to place this filter.
* If not given defaults to:
* No change in order if we are updating an existing record, and not changing to or from TEXTFILTER_DISABLED.
* Just after the last currently active filter when adding an unknown filter
* in state TEXTFILTER_ON or TEXTFILTER_OFF, or enabling/disabling an existing filter.
* Just after the very last filter when adding an unknown filter in state TEXTFILTER_DISABLED
*/
function filter_set_global_state($filter, $state, $sortorder = false) {
global $DB;
// Check requested state is valid.
if (!in_array($state, array(TEXTFILTER_ON, TEXTFILTER_OFF, TEXTFILTER_DISABLED))) {
throw new coding_exception("Illegal option '$state' passed to filter_set_global_state. " .
"Must be one of TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_DISABLED.");
}
// Check sortorder is valid.
if ($sortorder !== false) {
if ($sortorder < 1 || $sortorder > $DB->get_field('filter_active', 'MAX(sortorder)', array()) + 1) {
throw new coding_exception("Invalid sort order passed to filter_set_global_state.");
}
}
// See if there is an existing record.
$syscontext = get_context_instance(CONTEXT_SYSTEM);
$rec = $DB->get_record('filter_active', array('filter' => $filter, 'contextid' => $syscontext->id));
if (empty($rec)) {
$insert = true;
$rec = new stdClass;
$rec->filter = $filter;
$rec->contextid = $syscontext->id;
} else {
$insert = false;
if ($sortorder === false && !($rec->active == TEXTFILTER_DISABLED xor $state == TEXTFILTER_DISABLED)) {
$sortorder = $rec->sortorder;
}
}
// Automatic sort order.
if ($sortorder === false) {
if ($state == TEXTFILTER_DISABLED && $insert) {
$prevmaxsortorder = $DB->get_field('filter_active', 'MAX(sortorder)', array());
} else {
$prevmaxsortorder = $DB->get_field_select('filter_active', 'MAX(sortorder)', 'active <> ?', array(TEXTFILTER_DISABLED));
}
if (empty($prevmaxsortorder)) {
$sortorder = 1;
} else {
$sortorder = $prevmaxsortorder + 1;
if (!$insert && $state == TEXTFILTER_DISABLED) {
$sortorder = $prevmaxsortorder;
}
}
}
// Move any existing records out of the way of the sortorder.
if ($insert) {
$DB->execute('UPDATE {filter_active} SET sortorder = sortorder + 1 WHERE sortorder >= ?', array($sortorder));
} else if ($sortorder != $rec->sortorder) {
$sparesortorder = $DB->get_field('filter_active', 'MIN(sortorder)', array()) - 1;
$DB->set_field('filter_active', 'sortorder', $sparesortorder, array('filter' => $filter, 'contextid' => $syscontext->id));
if ($sortorder < $rec->sortorder) {
$DB->execute('UPDATE {filter_active} SET sortorder = sortorder + 1 WHERE sortorder >= ? AND sortorder < ?',
array($sortorder, $rec->sortorder));
} else if ($sortorder > $rec->sortorder) {
$DB->execute('UPDATE {filter_active} SET sortorder = sortorder - 1 WHERE sortorder <= ? AND sortorder > ?',
array($sortorder, $rec->sortorder));
}
}
// Insert/update the new record.
$rec->active = $state;
$rec->sortorder = $sortorder;
if ($insert) {
$DB->insert_record('filter_active', $rec);
} else {
$DB->update_record('filter_active', $rec);
}
}
/**
* @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
* @return boolean is this filter allowed to be used on this site. That is, the
* admin has set the global 'active' setting to On, or Off, but available.
*/
function filter_is_enabled($filter) {
return array_key_exists($filter, filter_get_globally_enabled());
}
/**
* Return a list of all the filters that may be in use somewhere.
*
* @staticvar array $enabledfilters
* @return array where the keys and values are both the filter name, like 'filter/tex'.
*/
function filter_get_globally_enabled() {
static $enabledfilters = null;
if (is_null($enabledfilters)) {
$filters = filter_get_global_states();
$enabledfilters = array();
foreach ($filters as $filter => $filerinfo) {
if ($filerinfo->active != TEXTFILTER_DISABLED) {
$enabledfilters[$filter] = $filter;
}
}
}
return $enabledfilters;
}
/**
* Return the names of the filters that should also be applied to strings
* (when they are enabled).
*
* @global object
* @return array where the keys and values are both the filter name, like 'filter/tex'.
*/
function filter_get_string_filters() {
global $CFG;
$stringfilters = array();
if (!empty($CFG->filterall) && !empty($CFG->stringfilters)) {
$stringfilters = explode(',', $CFG->stringfilters);
$stringfilters = array_combine($stringfilters, $stringfilters);
}
return $stringfilters;
}
/**
* Sets whether a particular active filter should be applied to all strings by
* format_string, or just used by format_text.
*
* @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
* @param boolean $applytostrings if true, this filter will apply to format_string
* and format_text, when it is enabled.
*/
function filter_set_applies_to_strings($filter, $applytostrings) {
$stringfilters = filter_get_string_filters();
$numstringfilters = count($stringfilters);
if ($applytostrings) {
$stringfilters[$filter] = $filter;
} else {
unset($stringfilters[$filter]);
}
if (count($stringfilters) != $numstringfilters) {
set_config('stringfilters', implode(',', $stringfilters));
set_config('filterall', !empty($stringfilters));
}
}
/**
* Set the local activated state for a text filter.
*
* @global object
* @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
* @param integer $contextid The id of the context to get the local config for.
* @param integer $state One of the values TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_INHERIT.
* @return void
*/
function filter_set_local_state($filter, $contextid, $state) {
global $DB;
// Check requested state is valid.
if (!in_array($state, array(TEXTFILTER_ON, TEXTFILTER_OFF, TEXTFILTER_INHERIT))) {
throw new coding_exception("Illegal option '$state' passed to filter_set_local_state. " .
"Must be one of TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_INHERIT.");
}
if ($contextid == get_context_instance(CONTEXT_SYSTEM)->id) {
throw new coding_exception('You cannot use filter_set_local_state ' .
'with $contextid equal to the system context id.');
}
if ($state == TEXTFILTER_INHERIT) {
$DB->delete_records('filter_active', array('filter' => $filter, 'contextid' => $contextid));
return;
}
$rec = $DB->get_record('filter_active', array('filter' => $filter, 'contextid' => $contextid));
$insert = false;
if (empty($rec)) {
$insert = true;
$rec = new stdClass;
$rec->filter = $filter;
$rec->contextid = $contextid;
}
$rec->active = $state;
if ($insert) {
$DB->insert_record('filter_active', $rec);
} else {
$DB->update_record('filter_active', $rec);
}
}
/**
* Set a particular local config variable for a filter in a context.
*
* @global object
* @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
* @param integer $contextid The id of the context to get the local config for.
* @param string $name the setting name.
* @param string $value the corresponding value.
*/
function filter_set_local_config($filter, $contextid, $name, $value) {
global $DB;
$rec = $DB->get_record('filter_config', array('filter' => $filter, 'contextid' => $contextid, 'name' => $name));
$insert = false;
if (empty($rec)) {
$insert = true;
$rec = new stdClass;
$rec->filter = $filter;
$rec->contextid = $contextid;
$rec->name = $name;
}
$rec->value = $value;
if ($insert) {
$DB->insert_record('filter_config', $rec);
} else {
$DB->update_record('filter_config', $rec);
}
}
/**
* Remove a particular local config variable for a filter in a context.
*
* @global object
* @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
* @param integer $contextid The id of the context to get the local config for.
* @param string $name the setting name.
*/
function filter_unset_local_config($filter, $contextid, $name) {
global $DB;
$DB->delete_records('filter_config', array('filter' => $filter, 'contextid' => $contextid, 'name' => $name));
}
/**
* Get local config variables for a filter in a context. Normally (when your
* filter is running) you don't need to call this, becuase the config is fetched
* for you automatically. You only need this, for example, when you are getting
* the config so you can show the user an editing from.
*
* @global object
* @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
* @param integer $contextid The ID of the context to get the local config for.
* @return array of name => value pairs.
*/
function filter_get_local_config($filter, $contextid) {
global $DB;
return $DB->get_records_menu('filter_config', array('filter' => $filter, 'contextid' => $contextid), '', 'name,value');
}
/**
* This function is for use by backup. Gets all the filter information specific
* to one context.
*
* @global object
* @param int $contextid
* @return array Array with two elements. The first element is an array of objects with
* fields filter and active. These come from the filter_active table. The
* second element is an array of objects with fields filter, name and value
* from the filter_config table.
*/
function filter_get_all_local_settings($contextid) {
global $DB;
$context = get_context_instance(CONTEXT_SYSTEM);
return array(
$DB->get_records('filter_active', array('contextid' => $contextid), 'filter', 'filter,active'),
$DB->get_records('filter_config', array('contextid' => $contextid), 'filter,name', 'filter,name,value'),
);
}
/**
* Get the list of active filters, in the order that they should be used
* for a particular context, along with any local configuration variables.
*
* @global object
* @param object $context a context
* @return array an array where the keys are the filter names, for example
* 'filter/tex' or 'mod/glossary' and the values are any local
* configuration for that filter, as an array of name => value pairs
* from the filter_config table. In a lot of cases, this will be an
* empty array. So, an example return value for this function might be
* array('filter/tex' => array(), 'mod/glossary' => array('glossaryid', 123))
*/
function filter_get_active_in_context($context) {
global $DB, $FILTERLIB_PRIVATE;
// Use cache (this is a within-request cache only) if available. See
// function filter_preload_activities.
if (isset($FILTERLIB_PRIVATE->active) &&
array_key_exists($context->id, $FILTERLIB_PRIVATE->active)) {
return $FILTERLIB_PRIVATE->active[$context->id];
}
$contextids = str_replace('/', ',', trim($context->path, '/'));
// The following SQL is tricky. It is explained on
// http://docs.moodle.org/dev/Filter_enable/disable_by_context
$sql = "SELECT active.filter, fc.name, fc.value
FROM (SELECT f.filter, MAX(f.sortorder) AS sortorder
FROM {filter_active} f
JOIN {context} ctx ON f.contextid = ctx.id
WHERE ctx.id IN ($contextids)
GROUP BY filter
HAVING MAX(f.active * " . $DB->sql_cast_2signed('ctx.depth') .
") > -MIN(f.active * " . $DB->sql_cast_2signed('ctx.depth') . ")
) active
LEFT JOIN {filter_config} fc ON fc.filter = active.filter AND fc.contextid = $context->id
ORDER BY active.sortorder";
$rs = $DB->get_recordset_sql($sql);
// Masssage the data into the specified format to return.
$filters = array();
foreach ($rs as $row) {
if (!isset($filters[$row->filter])) {
$filters[$row->filter] = array();
}
if (!is_null($row->name)) {
$filters[$row->filter][$row->name] = $row->value;
}
}
$rs->close();
return $filters;
}
/**
* Preloads the list of active filters for all activities (modules) on the course
* using two database queries.
* @param course_modinfo $modinfo Course object from get_fast_modinfo
*/
function filter_preload_activities(course_modinfo $modinfo) {
global $DB, $FILTERLIB_PRIVATE;
// Don't repeat preload
if (!isset($FILTERLIB_PRIVATE->preloaded)) {
$FILTERLIB_PRIVATE->preloaded = array();
}
if (!empty($FILTERLIB_PRIVATE->preloaded[$modinfo->get_course_id()])) {
return;
}
$FILTERLIB_PRIVATE->preloaded[$modinfo->get_course_id()] = true;
// Get contexts for all CMs
$cmcontexts = array();
$cmcontextids = array();
foreach ($modinfo->get_cms() as $cm) {
$modulecontext = get_context_instance(CONTEXT_MODULE, $cm->id);
$cmcontextids[] = $modulecontext->id;
$cmcontexts[] = $modulecontext;
}
// Get course context and all other parents...
$coursecontext = get_context_instance(CONTEXT_COURSE, $modinfo->get_course_id());
$parentcontextids = explode('/', substr($coursecontext->path, 1));
$allcontextids = array_merge($cmcontextids, $parentcontextids);
// Get all filter_active rows relating to all these contexts
list ($sql, $params) = $DB->get_in_or_equal($allcontextids);
$filteractives = $DB->get_records_select('filter_active', "contextid $sql", $params);
// Get all filter_config only for the cm contexts
list ($sql, $params) = $DB->get_in_or_equal($cmcontextids);
$filterconfigs = $DB->get_records_select('filter_config', "contextid $sql", $params);
// Note: I was a bit surprised that filter_config only works for the
// most specific context (i.e. it does not need to be checked for course
// context if we only care about CMs) however basede on code in
// filter_get_active_in_context, this does seem to be correct.
// Build course default active list. Initially this will be an array of
// filter name => active score (where an active score >0 means it's active)
$courseactive = array();
// Also build list of filter_active rows below course level, by contextid
$remainingactives = array();
// Array lists filters that are banned at top level
$banned = array();
// Add any active filters in parent contexts to the array
foreach ($filteractives as $row) {
$depth = array_search($row->contextid, $parentcontextids);
if ($depth !== false) {
// Find entry
if (!array_key_exists($row->filter, $courseactive)) {
$courseactive[$row->filter] = 0;
}
// This maths copes with reading rows in any order. Turning on/off
// at site level counts 1, at next level down 4, at next level 9,
// then 16, etc. This means the deepest level always wins, except
// against the -9999 at top level.
$courseactive[$row->filter] +=
($depth + 1) * ($depth + 1) * $row->active;
if ($row->active == TEXTFILTER_DISABLED) {
$banned[$row->filter] = true;
}
} else {
// Build list of other rows indexed by contextid
if (!array_key_exists($row->contextid, $remainingactives)) {
$remainingactives[$row->contextid] = array();
}
$remainingactives[$row->contextid][] = $row;
}
}
// Chuck away the ones that aren't active
foreach ($courseactive as $filter=>$score) {
if ($score <= 0) {
unset($courseactive[$filter]);
} else {
$courseactive[$filter] = array();
}
}
// Loop through the contexts to reconstruct filter_active lists for each
// cm on the course
if (!isset($FILTERLIB_PRIVATE->active)) {
$FILTERLIB_PRIVATE->active = array();
}
foreach ($cmcontextids as $contextid) {
// Copy course list
$FILTERLIB_PRIVATE->active[$contextid] = $courseactive;
// Are there any changes to the active list?
if (array_key_exists($contextid, $remainingactives)) {
foreach ($remainingactives[$contextid] as $row) {
if ($row->active > 0 && empty($banned[$row->filter])) {
// If it's marked active for specific context, add entry
// (doesn't matter if one exists already)
$FILTERLIB_PRIVATE->active[$contextid][$row->filter] = array();
} else {
// If it's marked inactive, remove entry (doesn't matter
// if it doesn't exist)
unset($FILTERLIB_PRIVATE->active[$contextid][$row->filter]);
}
}
}
}
// Process all config rows to add config data to these entries
foreach ($filterconfigs as $row) {
if (isset($FILTERLIB_PRIVATE->active[$row->contextid][$row->filter])) {
$FILTERLIB_PRIVATE->active[$row->contextid][$row->filter][$row->name] = $row->value;
}
}
}
/**
* List all of the filters that are available in this context, and what the
* local and inherited states of that filter are.
*
* @global object
* @param object $context a context that is not the system context.