forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
filterlib.php
1498 lines (1313 loc) · 54.1 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
* @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.
*
* @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 moodle_text_filter[][] This list of active filters, by context, for filtering content.
* An array contextid => ordered array of filter name => filter objects.
*/
protected $textfilters = array();
/**
* @var moodle_text_filter[][] This list of active filters, by context, for filtering strings.
* An array contextid => ordered array of filter name => filter objects.
*/
protected $stringfilters = array();
/** @var array Exploded version of $CFG->stringfilters. */
protected $stringfilternames = array();
/** @var filter_manager Holds the singleton instance. */
protected static $singletoninstance;
/**
* Constructor. Protected. Use {@link instance()} instead.
*/
protected function __construct() {
$this->stringfilternames = filter_get_string_filters();
}
/**
* Factory method. Use this to get the filter manager.
*
* @return filter_manager the singleton instance.
*/
public static function instance() {
global $CFG;
if (is_null(self::$singletoninstance)) {
if (!empty($CFG->perfdebug) and $CFG->perfdebug > 7) {
self::$singletoninstance = new performance_measuring_filter_manager();
} else {
self::$singletoninstance = new self();
}
}
return self::$singletoninstance;
}
/**
* Resets the caches, usually to be called between unit tests
*/
public static function reset_caches() {
if (self::$singletoninstance) {
self::$singletoninstance->unload_all_filters();
}
self::$singletoninstance = null;
}
/**
* Unloads all filters and other cached information
*/
protected function unload_all_filters() {
$this->textfilters = array();
$this->stringfilters = array();
$this->stringfilternames = array();
}
/**
* Load all the filters required by this context.
*
* @param context $context the 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][$filtername] = $filter;
if (in_array($filtername, $this->stringfilternames)) {
$this->stringfilters[$context->id][$filtername] = $filter;
}
}
}
/**
* Factory method for creating a filter.
*
* @param string $filtername The filter name, for example 'tex'.
* @param context $context context object.
* @param array $localconfig array of local configuration variables for this filter.
* @return 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 .'/filter/'. $filtername .'/filter.php';
if (!is_readable($path)) {
return null;
}
include_once($path);
$filterclassname = 'filter_' . $filtername;
if (class_exists($filterclassname)) {
return new $filterclassname($context, $localconfig);
}
return null;
}
/**
* Apply a list of filters to some content.
* @param string $text
* @param moodle_text_filter[] $filterchain array filter name => filter object.
* @param array $options options passed to the filters.
* @param array $skipfilters of filter names. Any filters that should not be applied to this text.
* @return string $text
*/
protected function apply_filter_chain($text, $filterchain, array $options = array(),
array $skipfilters = null) {
foreach ($filterchain as $filtername => $filter) {
if ($skipfilters !== null && in_array($filtername, $skipfilters)) {
continue;
}
$text = $filter->filter($text, $options);
}
return $text;
}
/**
* Get all the filters that apply to a given context for calls to format_text.
*
* @param context $context
* @return moodle_text_filter[] A text filter
*/
protected function get_text_filters($context) {
if (!isset($this->textfilters[$context->id])) {
$this->load_filters($context);
}
return $this->textfilters[$context->id];
}
/**
* Get all the filters that apply to a given context for calls to format_string.
*
* @param context $context the context.
* @return moodle_text_filter[] A text 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 context $context the context.
* @param array $options options passed to the filters
* @param array $skipfilters of filter names. Any filters that should not be applied to this text.
* @return string resulting text
*/
public function filter_text($text, $context, array $options = array(),
array $skipfilters = null) {
$text = $this->apply_filter_chain($text, $this->get_text_filters($context), $options, $skipfilters);
// <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 context $context the context.
* @return string resulting string
*/
public function filter_string($string, $context) {
return $this->apply_filter_chain($string, $this->get_string_filters($context));
}
/**
* @deprecated Since Moodle 3.0 MDL-50491. This was used by the old text filtering system, but no more.
* @todo MDL-50632 This will be deleted in Moodle 3.2.
* @param context $context the context.
* @return string the hash.
*/
public function text_filtering_hash($context) {
debugging('filter_manager::text_filtering_hash() is deprecated. ' .
'It was an internal part of the old format_text caching, ' .
'and should not have been called from other code.', DEBUG_DEVELOPER);
$filters = $this->get_text_filters($context);
$hashes = array();
foreach ($filters as $filter) {
$hashes[] = $filter->hash();
}
return implode('-', $hashes);
}
/**
* Setup page with filters requirements and other prepare stuff.
*
* This method is used by {@see format_text()} and {@see format_string()}
* in order to allow filters to setup any page requirement (js, css...)
* or perform any action needed to get them prepared before filtering itself
* happens by calling to each every active setup() method.
*
* Note it's executed for each piece of text filtered, so filter implementations
* are responsible of controlling the cardinality of the executions that may
* be different depending of the stuff to prepare.
*
* @param moodle_page $page the page we are going to add requirements to.
* @param context $context the context which contents are going to be filtered.
* @since Moodle 2.3
*/
public function setup_page_for_filters($page, $context) {
$filters = $this->get_text_filters($context);
foreach ($filters as $filter) {
$filter->setup($page, $context);
}
}
}
/**
* Filter manager subclass that does nothing. Having this simplifies the logic
* of format_text, etc.
*
* @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 {
public function filter_text($text, $context, array $options = array(),
array $skipfilters = null) {
return $text;
}
public function filter_string($string, $context) {
return $string;
}
public function text_filtering_hash() {
debugging('filter_manager::text_filtering_hash() is deprecated. ' .
'It was an internal part of the old format_text caching, ' .
'and should not have been called from other code.', DEBUG_DEVELOPER);
return '';
}
}
/**
* Filter manager subclass that tracks how much work it does.
*
* @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 number of filter objects created. */
protected $filterscreated = 0;
/** @var int number of calls to filter_text. */
protected $textsfiltered = 0;
/** @var int number of calls to filter_string. */
protected $stringsfiltered = 0;
protected function unload_all_filters() {
parent::unload_all_filters();
$this->filterscreated = 0;
$this->textsfiltered = 0;
$this->stringsfiltered = 0;
}
protected function make_filter_object($filtername, $context, $localconfig) {
$this->filterscreated++;
return parent::make_filter_object($filtername, $context, $localconfig);
}
public function filter_text($text, $context, array $options = array(),
array $skipfilters = null) {
$this->textsfiltered++;
return parent::filter_text($text, $context, $options, $skipfilters);
}
public function filter_string($string, $context) {
$this->stringsfiltered++;
return parent::filter_string($string, $context);
}
/**
* Return performance information, in the form required by {@link get_performance_info()}.
* @return array the performance info.
*/
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.
*
* @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 context 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 context $context The current context.
* @param array $localconfig Any context-specific configuration for this filter.
*/
public function __construct($context, array $localconfig) {
$this->context = $context;
$this->localconfig = $localconfig;
}
/**
* @deprecated Since Moodle 3.0 MDL-50491. This was used by the old text filtering system, but no more.
* @todo MDL-50632 This will be deleted in Moodle 3.2.
* @return string The class name of the current class
*/
public function hash() {
debugging('moodle_text_filter::hash() is deprecated. ' .
'It was an internal part of the old format_text caching, ' .
'and should not have been called from other code.', DEBUG_DEVELOPER);
return __CLASS__;
}
/**
* Setup page with filter requirements and other prepare stuff.
*
* Override this method if the filter needs to setup page
* requirements or needs other stuff to be executed.
*
* Note this method is invoked from {@see setup_page_for_filters()}
* for each piece of text being filtered, so it is responsible
* for controlling its own execution cardinality.
*
* @param moodle_page $page the page we are going to add requirements to.
* @param context $context the context which contents are going to be filtered.
* @since Moodle 2.3
*/
public function setup($page, $context) {
// Override me, if needed.
}
/**
* 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());
}
/**
* 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.
*
* @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
*/
public function __construct($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
*
* @param string $filter the filter name
* @return string the human-readable name for this filter.
*/
function filter_get_name($filter) {
if (strpos($filter, 'filter/') === 0) {
debugging("Old '$filter'' parameter used in filter_get_name()");
$filter = substr($filter, 7);
} else if (strpos($filter, '/') !== false) {
throw new coding_exception('Unknown filter type ' . $filter);
}
if (get_string_manager()->string_exists('filtername', 'filter_' . $filter)) {
return get_string('filtername', 'filter_' . $filter);
} else {
return $filter;
}
}
/**
* Get the names of all the filters installed in this Moodle.
*
* @return array path => filter name from the appropriate lang file. e.g.
* array('tex' => 'TeX Notation');
* sorted in alphabetical order of name.
*/
function filter_get_all_installed() {
global $CFG;
$filternames = array();
foreach (core_component::get_plugin_list('filter') as $filter => $fulldir) {
if (is_readable("$fulldir/filter.php")) {
$filternames[$filter] = filter_get_name($filter);
}
}
core_collator::asort($filternames);
return $filternames;
}
/**
* Set the global activated state for a text filter.
*
* @param string $filtername The filter name, for example 'tex'.
* @param int $state One of the values TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_DISABLED.
* @param int $move -1 means up, 0 means the same, 1 means down
*/
function filter_set_global_state($filtername, $state, $move = 0) {
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.");
}
if ($move > 0) {
$move = 1;
} else if ($move < 0) {
$move = -1;
}
if (strpos($filtername, 'filter/') === 0) {
//debugging("Old filtername '$filtername' parameter used in filter_set_global_state()", DEBUG_DEVELOPER);
$filtername = substr($filtername, 7);
} else if (strpos($filtername, '/') !== false) {
throw new coding_exception("Invalid filter name '$filtername' used in filter_set_global_state()");
}
$transaction = $DB->start_delegated_transaction();
$syscontext = context_system::instance();
$filters = $DB->get_records('filter_active', array('contextid' => $syscontext->id), 'sortorder ASC');
$on = array();
$off = array();
foreach($filters as $f) {
if ($f->active == TEXTFILTER_DISABLED) {
$off[$f->filter] = $f;
} else {
$on[$f->filter] = $f;
}
}
// Update the state or add new record.
if (isset($on[$filtername])) {
$filter = $on[$filtername];
if ($filter->active != $state) {
add_to_config_log('filter_active', $filter->active, $state, $filtername);
$filter->active = $state;
$DB->update_record('filter_active', $filter);
if ($filter->active == TEXTFILTER_DISABLED) {
unset($on[$filtername]);
$off = array($filter->filter => $filter) + $off;
}
}
} else if (isset($off[$filtername])) {
$filter = $off[$filtername];
if ($filter->active != $state) {
add_to_config_log('filter_active', $filter->active, $state, $filtername);
$filter->active = $state;
$DB->update_record('filter_active', $filter);
if ($filter->active != TEXTFILTER_DISABLED) {
unset($off[$filtername]);
$on[$filter->filter] = $filter;
}
}
} else {
add_to_config_log('filter_active', '', $state, $filtername);
$filter = new stdClass();
$filter->filter = $filtername;
$filter->contextid = $syscontext->id;
$filter->active = $state;
$filter->sortorder = 99999;
$filter->id = $DB->insert_record('filter_active', $filter);
$filters[$filter->id] = $filter;
if ($state == TEXTFILTER_DISABLED) {
$off[$filter->filter] = $filter;
} else {
$on[$filter->filter] = $filter;
}
}
// Move only active.
if ($move != 0 and isset($on[$filter->filter])) {
$i = 1;
foreach ($on as $f) {
$f->newsortorder = $i;
$i++;
}
$filter->newsortorder = $filter->newsortorder + $move;
foreach ($on as $f) {
if ($f->id == $filter->id) {
continue;
}
if ($f->newsortorder == $filter->newsortorder) {
if ($move == 1) {
$f->newsortorder = $f->newsortorder - 1;
} else {
$f->newsortorder = $f->newsortorder + 1;
}
}
}
core_collator::asort_objects_by_property($on, 'newsortorder', core_collator::SORT_NUMERIC);
}
// Inactive are sorted by filter name.
core_collator::asort_objects_by_property($off, 'filter', core_collator::SORT_NATURAL);
// Update records if necessary.
$i = 1;
foreach ($on as $f) {
if ($f->sortorder != $i) {
$DB->set_field('filter_active', 'sortorder', $i, array('id'=>$f->id));
}
$i++;
}
foreach ($off as $f) {
if ($f->sortorder != $i) {
$DB->set_field('filter_active', 'sortorder', $i, array('id'=>$f->id));
}
$i++;
}
$transaction->allow_commit();
}
/**
* @param string $filtername The filter name, for example 'tex'.
* @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($filtername) {
if (strpos($filtername, 'filter/') === 0) {
//debugging("Old filtername '$filtername' parameter used in filter_is_enabled()", DEBUG_DEVELOPER);
$filtername = substr($filtername, 7);
} else if (strpos($filtername, '/') !== false) {
throw new coding_exception("Invalid filter name '$filtername' used in filter_is_enabled()");
}
return array_key_exists($filtername, 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 '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).
*
* @return array where the keys and values are both the filter name, like '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 'tex'.
* @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();
$prevfilters = $stringfilters;
$allfilters = core_component::get_plugin_list('filter');
if ($applytostrings) {
$stringfilters[$filter] = $filter;
} else {
unset($stringfilters[$filter]);
}
// Remove missing filters.
foreach ($stringfilters as $filter) {
if (!isset($allfilters[$filter])) {
unset($stringfilters[$filter]);
}
}
if ($prevfilters != $stringfilters) {
set_config('stringfilters', implode(',', $stringfilters));
set_config('filterall', !empty($stringfilters));
}
}
/**
* Set the local activated state for a text filter.
*
* @param string $filter The filter name, for example 'tex'.
* @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 == context_system::instance()->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.
*
* @param string $filter The filter name, for example 'tex'.
* @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.
*
* @param string $filter The filter name, for example 'tex'.
* @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.
*
* @param string $filter The filter name, for example 'tex'.
* @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.
*
* @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;
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.
*
* @param context $context a context
* @return array an array where the keys are the filter names, for example
* 'tex' 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(tex' => array())
*/
function filter_get_active_in_context($context) {
global $DB, $FILTERLIB_PRIVATE;
if (!isset($FILTERLIB_PRIVATE)) {
$FILTERLIB_PRIVATE = new stdClass();
}
// 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 * ctx.depth) > -MIN(f.active * 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);
// Massage 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;
if (!isset($FILTERLIB_PRIVATE)) {
$FILTERLIB_PRIVATE = new stdClass();
}
// 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 = context_module::instance($cm->id);
$cmcontextids[] = $modulecontext->id;
$cmcontexts[] = $modulecontext;
}
// Get course context and all other parents...
$coursecontext = context_course::instance($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