Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
17
/**
18
 * Library functions for managing text filter plugins.
19
 *
20
 * @package   core
21
 * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
22
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23
 */
24
 
25
defined('MOODLE_INTERNAL') || die();
26
 
27
/** The states a filter can be in, stored in the filter_active table. */
28
define('TEXTFILTER_ON', 1);
29
/** The states a filter can be in, stored in the filter_active table. */
30
define('TEXTFILTER_INHERIT', 0);
31
/** The states a filter can be in, stored in the filter_active table. */
32
define('TEXTFILTER_OFF', -1);
33
/** The states a filter can be in, stored in the filter_active table. */
34
define('TEXTFILTER_DISABLED', -9999);
35
 
36
/**
37
 * Define one exclusive separator that we'll use in the temp saved tags
38
 *  keys. It must be something rare enough to avoid having matches with
39
 *  filterobjects. MDL-18165
40
 */
41
define('TEXTFILTER_EXCL_SEPARATOR', chr(0x1F) . '%' . chr(0x1F));
42
 
43
 
44
/**
45
 * Class to manage the filtering of strings. It is intended that this class is
46
 * only used by weblib.php. Client code should probably be using the
47
 * format_text and format_string functions.
48
 *
49
 * This class is a singleton.
50
 *
51
 * @copyright  1999 onwards Martin Dougiamas  {@link http://moodle.com}
52
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
53
 */
54
class filter_manager {
55
    /**
56
     * @var moodle_text_filter[][] This list of active filters, by context, for filtering content.
57
     * An array contextid => ordered array of filter name => filter objects.
58
     */
59
    protected $textfilters = array();
60
 
61
    /**
62
     * @var moodle_text_filter[][] This list of active filters, by context, for filtering strings.
63
     * An array contextid => ordered array of filter name => filter objects.
64
     */
65
    protected $stringfilters = array();
66
 
67
    /** @var array Exploded version of $CFG->stringfilters. */
68
    protected $stringfilternames = array();
69
 
70
    /** @var filter_manager Holds the singleton instance. */
71
    protected static $singletoninstance;
72
 
73
    /**
74
     * Constructor. Protected. Use {@link instance()} instead.
75
     */
76
    protected function __construct() {
77
        $this->stringfilternames = filter_get_string_filters();
78
    }
79
 
80
    /**
81
     * Factory method. Use this to get the filter manager.
82
     *
83
     * @return filter_manager the singleton instance.
84
     */
85
    public static function instance() {
86
        global $CFG;
87
        if (is_null(self::$singletoninstance)) {
88
            if (!empty($CFG->perfdebug) and $CFG->perfdebug > 7) {
89
                self::$singletoninstance = new performance_measuring_filter_manager();
90
            } else {
91
                self::$singletoninstance = new self();
92
            }
93
        }
94
        return self::$singletoninstance;
95
    }
96
 
97
    /**
98
     * Resets the caches, usually to be called between unit tests
99
     */
100
    public static function reset_caches() {
101
        if (self::$singletoninstance) {
102
            self::$singletoninstance->unload_all_filters();
103
        }
104
        self::$singletoninstance = null;
105
    }
106
 
107
    /**
108
     * Unloads all filters and other cached information
109
     */
110
    protected function unload_all_filters() {
111
        $this->textfilters = array();
112
        $this->stringfilters = array();
113
        $this->stringfilternames = array();
114
    }
115
 
116
    /**
117
     * Load all the filters required by this context.
118
     *
119
     * @param context $context the context.
120
     */
121
    protected function load_filters($context) {
122
        $filters = filter_get_active_in_context($context);
123
        $this->textfilters[$context->id] = array();
124
        $this->stringfilters[$context->id] = array();
125
        foreach ($filters as $filtername => $localconfig) {
126
            $filter = $this->make_filter_object($filtername, $context, $localconfig);
127
            if (is_null($filter)) {
128
                continue;
129
            }
130
            $this->textfilters[$context->id][$filtername] = $filter;
131
            if (in_array($filtername, $this->stringfilternames)) {
132
                $this->stringfilters[$context->id][$filtername] = $filter;
133
            }
134
        }
135
    }
136
 
137
    /**
138
     * Factory method for creating a filter.
139
     *
140
     * @param string $filtername The filter name, for example 'tex'.
141
     * @param context $context context object.
142
     * @param array $localconfig array of local configuration variables for this filter.
143
     * @return ?moodle_text_filter The filter, or null, if this type of filter is
144
     *      not recognised or could not be created.
145
     */
146
    protected function make_filter_object($filtername, $context, $localconfig) {
147
        global $CFG;
148
        $path = $CFG->dirroot .'/filter/'. $filtername .'/filter.php';
149
        if (!is_readable($path)) {
150
            return null;
151
        }
152
        include_once($path);
153
 
154
        $filterclassname = 'filter_' . $filtername;
155
        if (class_exists($filterclassname)) {
156
            return new $filterclassname($context, $localconfig);
157
        }
158
 
159
        return null;
160
    }
161
 
162
    /**
163
     * Apply a list of filters to some content.
164
     * @param string $text
165
     * @param moodle_text_filter[] $filterchain array filter name => filter object.
166
     * @param array $options options passed to the filters.
167
     * @param array $skipfilters of filter names. Any filters that should not be applied to this text.
168
     * @return string $text
169
     */
170
    protected function apply_filter_chain($text, $filterchain, array $options = array(),
171
            array $skipfilters = null) {
172
        if (!isset($options['stage'])) {
173
            $filtermethod = 'filter';
174
        } else if (in_array($options['stage'], ['pre_format', 'pre_clean', 'post_clean', 'string'], true)) {
175
            $filtermethod = 'filter_stage_' . $options['stage'];
176
        } else {
177
            $filtermethod = 'filter';
178
            debugging('Invalid filter stage specified in options: ' . $options['stage'], DEBUG_DEVELOPER);
179
        }
180
        if ($text === null || $text === '') {
181
            // Nothing to filter.
182
            return '';
183
        }
184
        foreach ($filterchain as $filtername => $filter) {
185
            if ($skipfilters !== null && in_array($filtername, $skipfilters)) {
186
                continue;
187
            }
188
            $text = $filter->$filtermethod($text, $options);
189
        }
190
        return $text;
191
    }
192
 
193
    /**
194
     * Get all the filters that apply to a given context for calls to format_text.
195
     *
196
     * @param context $context
197
     * @return moodle_text_filter[] A text filter
198
     */
199
    protected function get_text_filters($context) {
200
        if (!isset($this->textfilters[$context->id])) {
201
            $this->load_filters($context);
202
        }
203
        return $this->textfilters[$context->id];
204
    }
205
 
206
    /**
207
     * Get all the filters that apply to a given context for calls to format_string.
208
     *
209
     * @param context $context the context.
210
     * @return moodle_text_filter[] A text filter
211
     */
212
    protected function get_string_filters($context) {
213
        if (!isset($this->stringfilters[$context->id])) {
214
            $this->load_filters($context);
215
        }
216
        return $this->stringfilters[$context->id];
217
    }
218
 
219
    /**
220
     * Filter some text
221
     *
222
     * @param string $text The text to filter
223
     * @param context $context the context.
224
     * @param array $options options passed to the filters
225
     * @param array $skipfilters of filter names. Any filters that should not be applied to this text.
226
     * @return string resulting text
227
     */
228
    public function filter_text($text, $context, array $options = array(),
229
            array $skipfilters = null) {
230
        $text = $this->apply_filter_chain($text, $this->get_text_filters($context), $options, $skipfilters);
231
        if (!isset($options['stage']) || $options['stage'] === 'post_clean') {
232
            // Remove <nolink> tags for XHTML compatibility after the last filtering stage.
233
            $text = str_replace(array('<nolink>', '</nolink>'), '', $text);
234
        }
235
        return $text;
236
    }
237
 
238
    /**
239
     * Filter a piece of string
240
     *
241
     * @param string $string The text to filter
242
     * @param context $context the context.
243
     * @return string resulting string
244
     */
245
    public function filter_string($string, $context) {
246
        return $this->apply_filter_chain($string, $this->get_string_filters($context), ['stage' => 'string']);
247
    }
248
 
249
    /**
250
     * @deprecated Since Moodle 3.0 MDL-50491. This was used by the old text filtering system, but no more.
251
     */
252
    public function text_filtering_hash() {
253
        throw new coding_exception('filter_manager::text_filtering_hash() can not be used any more');
254
    }
255
 
256
    /**
257
     * Setup page with filters requirements and other prepare stuff.
258
     *
259
     * This method is used by {@see format_text()} and {@see format_string()}
260
     * in order to allow filters to setup any page requirement (js, css...)
261
     * or perform any action needed to get them prepared before filtering itself
262
     * happens by calling to each every active setup() method.
263
     *
264
     * Note it's executed for each piece of text filtered, so filter implementations
265
     * are responsible of controlling the cardinality of the executions that may
266
     * be different depending of the stuff to prepare.
267
     *
268
     * @param moodle_page $page the page we are going to add requirements to.
269
     * @param context $context the context which contents are going to be filtered.
270
     * @since Moodle 2.3
271
     */
272
    public function setup_page_for_filters($page, $context) {
273
        $filters = $this->get_text_filters($context);
274
        foreach ($filters as $filter) {
275
            $filter->setup($page, $context);
276
        }
277
    }
278
 
279
    /**
280
     * Setup the page for globally available filters.
281
     *
282
     * This helps setting up the page for filters which may be applied to
283
     * the page, even if they do not belong to the current context, or are
284
     * not yet visible because the content is lazily added (ajax). This method
285
     * always uses to the system context which determines the globally
286
     * available filters.
287
     *
288
     * This should only ever be called once per request.
289
     *
290
     * @param moodle_page $page The page.
291
     * @since Moodle 3.2
292
     */
293
    public function setup_page_for_globally_available_filters($page) {
294
        $context = context_system::instance();
295
        $filterdata = filter_get_globally_enabled_filters_with_config();
296
        foreach ($filterdata as $name => $config) {
297
            if (isset($this->textfilters[$context->id][$name])) {
298
                $filter = $this->textfilters[$context->id][$name];
299
            } else {
300
                $filter = $this->make_filter_object($name, $context, $config);
301
                if (is_null($filter)) {
302
                    continue;
303
                }
304
            }
305
            $filter->setup($page, $context);
306
        }
307
    }
308
}
309
 
310
 
311
/**
312
 * Filter manager subclass that does nothing. Having this simplifies the logic
313
 * of format_text, etc.
314
 *
315
 * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
316
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
317
 */
318
class null_filter_manager {
319
    /**
320
     * As for the equivalent {@link filter_manager} method.
321
     *
322
     * @param string $text The text to filter
323
     * @param context $context not used.
324
     * @param array $options not used
325
     * @param array $skipfilters not used
326
     * @return string resulting text.
327
     */
328
    public function filter_text($text, $context, array $options = array(),
329
            array $skipfilters = null) {
330
        return $text;
331
    }
332
 
333
    /**
334
     * As for the equivalent {@link filter_manager} method.
335
     *
336
     * @param string $string The text to filter
337
     * @param context $context not used.
338
     * @return string resulting string
339
     */
340
    public function filter_string($string, $context) {
341
        return $string;
342
    }
343
 
344
    /**
345
     * As for the equivalent {@link filter_manager} method.
346
     *
347
     * @deprecated Since Moodle 3.0 MDL-50491.
348
     */
349
    public function text_filtering_hash() {
350
        throw new coding_exception('filter_manager::text_filtering_hash() can not be used any more');
351
    }
352
}
353
 
354
 
355
/**
356
 * Filter manager subclass that tracks how much work it does.
357
 *
358
 * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
359
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
360
 */
361
class performance_measuring_filter_manager extends filter_manager {
362
    /** @var int number of filter objects created. */
363
    protected $filterscreated = 0;
364
 
365
    /** @var int number of calls to filter_text. */
366
    protected $textsfiltered = 0;
367
 
368
    /** @var int number of calls to filter_string. */
369
    protected $stringsfiltered = 0;
370
 
371
    protected function unload_all_filters() {
372
        parent::unload_all_filters();
373
        $this->filterscreated = 0;
374
        $this->textsfiltered = 0;
375
        $this->stringsfiltered = 0;
376
    }
377
 
378
    protected function make_filter_object($filtername, $context, $localconfig) {
379
        $this->filterscreated++;
380
        return parent::make_filter_object($filtername, $context, $localconfig);
381
    }
382
 
383
    public function filter_text($text, $context, array $options = array(),
384
            array $skipfilters = null) {
385
        if (!isset($options['stage']) || $options['stage'] === 'post_clean') {
386
            $this->textsfiltered++;
387
        }
388
        return parent::filter_text($text, $context, $options, $skipfilters);
389
    }
390
 
391
    public function filter_string($string, $context) {
392
        $this->stringsfiltered++;
393
        return parent::filter_string($string, $context);
394
    }
395
 
396
    /**
397
     * Return performance information, in the form required by {@link get_performance_info()}.
398
     * @return array the performance info.
399
     */
400
    public function get_performance_summary() {
401
        return array(array(
402
            'contextswithfilters' => count($this->textfilters),
403
            'filterscreated' => $this->filterscreated,
404
            'textsfiltered' => $this->textsfiltered,
405
            'stringsfiltered' => $this->stringsfiltered,
406
        ), array(
407
            'contextswithfilters' => 'Contexts for which filters were loaded',
408
            'filterscreated' => 'Filters created',
409
            'textsfiltered' => 'Pieces of content filtered',
410
            'stringsfiltered' => 'Strings filtered',
411
        ));
412
    }
413
}
414
 
415
 
416
/**
417
 * Base class for text filters. You just need to override this class and
418
 * implement the filter method.
419
 *
420
 * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
421
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
422
 */
423
abstract class moodle_text_filter {
424
    /** @var context The context we are in. */
425
    protected $context;
426
 
427
    /** @var array Any local configuration for this filter in this context. */
428
    protected $localconfig;
429
 
430
    /**
431
     * Set any context-specific configuration for this filter.
432
     *
433
     * @param context $context The current context.
434
     * @param array $localconfig Any context-specific configuration for this filter.
435
     */
436
    public function __construct($context, array $localconfig) {
437
        $this->context = $context;
438
        $this->localconfig = $localconfig;
439
    }
440
 
441
    /**
442
     * @deprecated Since Moodle 3.0 MDL-50491. This was used by the old text filtering system, but no more.
443
     */
444
    public function hash() {
445
        throw new coding_exception('moodle_text_filter::hash() can not be used any more');
446
    }
447
 
448
    /**
449
     * Setup page with filter requirements and other prepare stuff.
450
     *
451
     * Override this method if the filter needs to setup page
452
     * requirements or needs other stuff to be executed.
453
     *
454
     * Note this method is invoked from {@see setup_page_for_filters()}
455
     * for each piece of text being filtered, so it is responsible
456
     * for controlling its own execution cardinality.
457
     *
458
     * @param moodle_page $page the page we are going to add requirements to.
459
     * @param context $context the context which contents are going to be filtered.
460
     * @since Moodle 2.3
461
     */
462
    public function setup($page, $context) {
463
        // Override me, if needed.
464
    }
465
 
466
    /**
467
     * Override this function to actually implement the filtering.
468
     *
469
     * Filter developers must make sure that filtering done after text cleaning
470
     * does not introduce security vulnerabilities.
471
     *
472
     * @param string $text some HTML content to process.
473
     * @param array $options options passed to the filters
474
     * @return string the HTML content after the filtering has been applied.
475
     */
476
    abstract public function filter($text, array $options = array());
477
 
478
    /**
479
     * Filter text before changing format to HTML.
480
     *
481
     * @param string $text
482
     * @param array $options
483
     * @return string
484
     */
485
    public function filter_stage_pre_format(string $text, array $options): string {
486
        // NOTE: override if necessary.
487
        return $text;
488
    }
489
 
490
    /**
491
     * Filter HTML text before sanitising text.
492
     *
493
     * NOTE: this is called even if $options['noclean'] is true and text is not cleaned.
494
     *
495
     * @param string $text
496
     * @param array $options
497
     * @return string
498
     */
499
    public function filter_stage_pre_clean(string $text, array $options): string {
500
        // NOTE: override if necessary.
501
        return $text;
502
    }
503
 
504
    /**
505
     * Filter HTML text at the very end after text is sanitised.
506
     *
507
     * NOTE: this is called even if $options['noclean'] is true and text is not cleaned.
508
     *
509
     * @param string $text
510
     * @param array $options
511
     * @return string
512
     */
513
    public function filter_stage_post_clean(string $text, array $options): string {
514
        // NOTE: override if necessary.
515
        return $this->filter($text, $options);
516
    }
517
 
518
    /**
519
     * Filter simple text coming from format_string().
520
     *
521
     * Note that unless $CFG->formatstringstriptags is disabled
522
     * HTML tags are not expected in returned value.
523
     *
524
     * @param string $text
525
     * @param array $options
526
     * @return string
527
     */
528
    public function filter_stage_string(string $text, array $options): string {
529
        // NOTE: override if necessary.
530
        return $this->filter($text, $options);
531
    }
532
}
533
 
534
 
535
/**
536
 * This is just a little object to define a phrase and some instructions
537
 * for how to process it.  Filters can create an array of these to pass
538
 * to the @{link filter_phrases()} function below.
539
 *
540
 * Note that although the fields here are public, you almost certainly should
541
 * never use that. All that is supported is contructing new instances of this
542
 * class, and then passing an array of them to filter_phrases.
543
 *
544
 * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
545
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
546
 */
547
class filterobject {
548
    /** @var string this is the phrase that should be matched. */
549
    public $phrase;
550
 
551
    /** @var bool whether to match complete words. If true, 'T' won't be matched in 'Tim'. */
552
    public $fullmatch;
553
 
554
    /** @var bool whether the match needs to be case sensitive. */
555
    public $casesensitive;
556
 
557
    /** @var string HTML to insert before any match. */
558
    public $hreftagbegin;
559
    /** @var string HTML to insert after any match. */
560
    public $hreftagend;
561
 
562
    /** @var null|string replacement text to go inside begin and end. If not set,
563
     * the body of the replacement will be the original phrase.
564
     */
565
    public $replacementphrase;
566
 
567
    /** @var null|string once initialised, holds the regexp for matching this phrase. */
568
    public $workregexp = null;
569
 
570
    /** @var null|string once initialised, holds the mangled HTML to replace the regexp with. */
571
    public $workreplacementphrase = null;
572
 
573
    /** @var null|callable hold a replacement function to be called. */
574
    public $replacementcallback;
575
 
576
    /** @var null|array data to be passed to $replacementcallback. */
577
    public $replacementcallbackdata;
578
 
579
    /**
580
     * Constructor.
581
     *
582
     * @param string $phrase this is the phrase that should be matched.
583
     * @param string $hreftagbegin HTML to insert before any match. Default '<span class="highlight">'.
584
     * @param string $hreftagend HTML to insert after any match. Default '</span>'.
585
     * @param bool $casesensitive whether the match needs to be case sensitive
586
     * @param bool $fullmatch whether to match complete words. If true, 'T' won't be matched in 'Tim'.
587
     * @param mixed $replacementphrase replacement text to go inside begin and end. If not set,
588
     * the body of the replacement will be the original phrase.
589
     * @param callback $replacementcallback if set, then this will be called just before
590
     * $hreftagbegin, $hreftagend and $replacementphrase are needed, so they can be computed only if required.
591
     * The call made is
592
     * list($linkobject->hreftagbegin, $linkobject->hreftagend, $linkobject->replacementphrase) =
593
     *         call_user_func_array($linkobject->replacementcallback, $linkobject->replacementcallbackdata);
594
     * so the return should be an array [$hreftagbegin, $hreftagend, $replacementphrase], the last of which may be null.
595
     * @param array $replacementcallbackdata data to be passed to $replacementcallback (optional).
596
     */
597
    public function __construct($phrase, $hreftagbegin = '<span class="highlight">',
598
            $hreftagend = '</span>',
599
            $casesensitive = false,
600
            $fullmatch = false,
601
            $replacementphrase = null,
602
            $replacementcallback = null,
603
            array $replacementcallbackdata = null) {
604
 
605
        $this->phrase                  = $phrase;
606
        $this->hreftagbegin            = $hreftagbegin;
607
        $this->hreftagend              = $hreftagend;
608
        $this->casesensitive           = !empty($casesensitive);
609
        $this->fullmatch               = !empty($fullmatch);
610
        $this->replacementphrase       = $replacementphrase;
611
        $this->replacementcallback     = $replacementcallback;
612
        $this->replacementcallbackdata = $replacementcallbackdata;
613
    }
614
}
615
 
616
/**
617
 * Look up the name of this filter
618
 *
619
 * @param string $filter the filter name
620
 * @return string the human-readable name for this filter.
621
 */
622
function filter_get_name($filter) {
623
    if (strpos($filter, 'filter/') === 0) {
624
        debugging("Old '$filter'' parameter used in filter_get_name()");
625
        $filter = substr($filter, 7);
626
    } else if (strpos($filter, '/') !== false) {
627
        throw new coding_exception('Unknown filter type ' . $filter);
628
    }
629
 
630
    if (get_string_manager()->string_exists('filtername', 'filter_' . $filter)) {
631
        return get_string('filtername', 'filter_' . $filter);
632
    } else {
633
        return $filter;
634
    }
635
}
636
 
637
/**
638
 * Get the names of all the filters installed in this Moodle.
639
 *
640
 * @return array path => filter name from the appropriate lang file. e.g.
641
 * array('tex' => 'TeX Notation');
642
 * sorted in alphabetical order of name.
643
 */
644
function filter_get_all_installed() {
645
    $filternames = array();
646
    foreach (core_component::get_plugin_list('filter') as $filter => $fulldir) {
647
        if (is_readable("$fulldir/filter.php")) {
648
            $filternames[$filter] = filter_get_name($filter);
649
        }
650
    }
651
    core_collator::asort($filternames);
652
    return $filternames;
653
}
654
 
655
/**
656
 * Set the global activated state for a text filter.
657
 *
658
 * @param string $filtername The filter name, for example 'tex'.
659
 * @param int $state One of the values TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_DISABLED.
660
 * @param int $move -1 means up, 0 means the same, 1 means down
661
 */
662
function filter_set_global_state($filtername, $state, $move = 0) {
663
    global $DB;
664
 
665
    // Check requested state is valid.
666
    if (!in_array($state, array(TEXTFILTER_ON, TEXTFILTER_OFF, TEXTFILTER_DISABLED))) {
667
        throw new coding_exception("Illegal option '$state' passed to filter_set_global_state. " .
668
                "Must be one of TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_DISABLED.");
669
    }
670
 
671
    if ($move > 0) {
672
        $move = 1;
673
    } else if ($move < 0) {
674
        $move = -1;
675
    }
676
 
677
    if (strpos($filtername, 'filter/') === 0) {
678
        $filtername = substr($filtername, 7);
679
    } else if (strpos($filtername, '/') !== false) {
680
        throw new coding_exception("Invalid filter name '$filtername' used in filter_set_global_state()");
681
    }
682
 
683
    $transaction = $DB->start_delegated_transaction();
684
 
685
    $syscontext = context_system::instance();
686
    $filters = $DB->get_records('filter_active', array('contextid' => $syscontext->id), 'sortorder ASC');
687
 
688
    $on = array();
689
    $off = array();
690
 
691
    foreach ($filters as $f) {
692
        if ($f->active == TEXTFILTER_DISABLED) {
693
            $off[$f->filter] = $f;
694
        } else {
695
            $on[$f->filter] = $f;
696
        }
697
    }
698
 
699
    // Update the state or add new record.
700
    if (isset($on[$filtername])) {
701
        $filter = $on[$filtername];
702
        if ($filter->active != $state) {
703
            add_to_config_log('filter_active', $filter->active, $state, $filtername);
704
 
705
            $filter->active = $state;
706
            $DB->update_record('filter_active', $filter);
707
            if ($filter->active == TEXTFILTER_DISABLED) {
708
                unset($on[$filtername]);
709
                $off = array($filter->filter => $filter) + $off;
710
            }
711
 
712
        }
713
 
714
    } else if (isset($off[$filtername])) {
715
        $filter = $off[$filtername];
716
        if ($filter->active != $state) {
717
            add_to_config_log('filter_active', $filter->active, $state, $filtername);
718
 
719
            $filter->active = $state;
720
            $DB->update_record('filter_active', $filter);
721
            if ($filter->active != TEXTFILTER_DISABLED) {
722
                unset($off[$filtername]);
723
                $on[$filter->filter] = $filter;
724
            }
725
        }
726
 
727
    } else {
728
        add_to_config_log('filter_active', '', $state, $filtername);
729
 
730
        $filter = new stdClass();
731
        $filter->filter    = $filtername;
732
        $filter->contextid = $syscontext->id;
733
        $filter->active    = $state;
734
        $filter->sortorder = 99999;
735
        $filter->id = $DB->insert_record('filter_active', $filter);
736
 
737
        $filters[$filter->id] = $filter;
738
        if ($state == TEXTFILTER_DISABLED) {
739
            $off[$filter->filter] = $filter;
740
        } else {
741
            $on[$filter->filter] = $filter;
742
        }
743
    }
744
 
745
    // Move only active.
746
    if ($move != 0 and isset($on[$filter->filter])) {
747
        // Capture the old order for logging.
748
        $oldorder = implode(', ', array_map(
749
                function($f) {
750
                    return $f->filter;
751
                }, $on));
752
 
753
        // Work out the new order.
754
        $i = 1;
755
        foreach ($on as $f) {
756
            $f->newsortorder = $i;
757
            $i++;
758
        }
759
 
760
        $filter->newsortorder = $filter->newsortorder + $move;
761
 
762
        foreach ($on as $f) {
763
            if ($f->id == $filter->id) {
764
                continue;
765
            }
766
            if ($f->newsortorder == $filter->newsortorder) {
767
                if ($move == 1) {
768
                    $f->newsortorder = $f->newsortorder - 1;
769
                } else {
770
                    $f->newsortorder = $f->newsortorder + 1;
771
                }
772
            }
773
        }
774
 
775
        core_collator::asort_objects_by_property($on, 'newsortorder', core_collator::SORT_NUMERIC);
776
 
777
        // Log in config_log.
778
        $neworder = implode(', ', array_map(
779
                function($f) {
780
                    return $f->filter;
781
                }, $on));
782
        add_to_config_log('order', $oldorder, $neworder, 'core_filter');
783
    }
784
 
785
    // Inactive are sorted by filter name.
786
    core_collator::asort_objects_by_property($off, 'filter', core_collator::SORT_NATURAL);
787
 
788
    // Update records if necessary.
789
    $i = 1;
790
    foreach ($on as $f) {
791
        if ($f->sortorder != $i) {
792
            $DB->set_field('filter_active', 'sortorder', $i, array('id' => $f->id));
793
        }
794
        $i++;
795
    }
796
    foreach ($off as $f) {
797
        if ($f->sortorder != $i) {
798
            $DB->set_field('filter_active', 'sortorder', $i, array('id' => $f->id));
799
        }
800
        $i++;
801
    }
802
 
803
    $transaction->allow_commit();
804
}
805
 
806
/**
807
 * Returns the active state for a filter in the given context.
808
 *
809
 * @param string $filtername The filter name, for example 'tex'.
810
 * @param integer $contextid The id of the context to get the data for.
811
 * @return int value of active field for the given filter.
812
 */
813
function filter_get_active_state(string $filtername, $contextid = null): int {
814
    global $DB;
815
 
816
    if ($contextid === null) {
817
        $contextid = context_system::instance()->id;
818
    }
819
    if (is_object($contextid)) {
820
        $contextid = $contextid->id;
821
    }
822
 
823
    if (strpos($filtername, 'filter/') === 0) {
824
        $filtername = substr($filtername, 7);
825
    } else if (strpos($filtername, '/') !== false) {
826
        throw new coding_exception("Invalid filter name '$filtername' used in filter_is_enabled()");
827
    }
828
    if ($active = $DB->get_field('filter_active', 'active', array('filter' => $filtername, 'contextid' => $contextid))) {
829
        return $active;
830
    }
831
 
832
    return TEXTFILTER_DISABLED;
833
}
834
 
835
/**
836
 * @param string $filtername The filter name, for example 'tex'.
837
 * @return boolean is this filter allowed to be used on this site. That is, the
838
 *      admin has set the global 'active' setting to On, or Off, but available.
839
 */
840
function filter_is_enabled($filtername) {
841
    if (strpos($filtername, 'filter/') === 0) {
842
        $filtername = substr($filtername, 7);
843
    } else if (strpos($filtername, '/') !== false) {
844
        throw new coding_exception("Invalid filter name '$filtername' used in filter_is_enabled()");
845
    }
846
    return array_key_exists($filtername, filter_get_globally_enabled());
847
}
848
 
849
/**
850
 * Return a list of all the filters that may be in use somewhere.
851
 *
852
 * @return array where the keys and values are both the filter name, like 'tex'.
853
 */
854
function filter_get_globally_enabled() {
855
    $cache = \cache::make_from_params(\cache_store::MODE_REQUEST, 'core_filter', 'global_filters');
856
    $enabledfilters = $cache->get('enabled');
857
    if ($enabledfilters !== false) {
858
        return $enabledfilters;
859
    }
860
 
861
    $filters = filter_get_global_states();
862
    $enabledfilters = array();
863
    foreach ($filters as $filter => $filerinfo) {
864
        if ($filerinfo->active != TEXTFILTER_DISABLED) {
865
            $enabledfilters[$filter] = $filter;
866
        }
867
    }
868
 
869
    $cache->set('enabled', $enabledfilters);
870
    return $enabledfilters;
871
}
872
 
873
/**
874
 * Get the globally enabled filters.
875
 *
876
 * This returns the filters which could be used in any context. Essentially
877
 * the filters which are not disabled for the entire site.
878
 *
879
 * @return array Keys are filter names, and values the config.
880
 */
881
function filter_get_globally_enabled_filters_with_config() {
882
    global $DB;
883
 
884
    $sql = "SELECT f.filter, fc.name, fc.value
885
              FROM {filter_active} f
886
         LEFT JOIN {filter_config} fc
887
                ON fc.filter = f.filter
888
               AND fc.contextid = f.contextid
889
             WHERE f.contextid = :contextid
890
               AND f.active != :disabled
891
          ORDER BY f.sortorder";
892
 
893
    $rs = $DB->get_recordset_sql($sql, [
894
        'contextid' => context_system::instance()->id,
895
        'disabled' => TEXTFILTER_DISABLED
896
    ]);
897
 
898
    // Massage the data into the specified format to return.
899
    $filters = array();
900
    foreach ($rs as $row) {
901
        if (!isset($filters[$row->filter])) {
902
            $filters[$row->filter] = array();
903
        }
904
        if ($row->name !== null) {
905
            $filters[$row->filter][$row->name] = $row->value;
906
        }
907
    }
908
    $rs->close();
909
 
910
    return $filters;
911
}
912
 
913
/**
914
 * Return the names of the filters that should also be applied to strings
915
 * (when they are enabled).
916
 *
917
 * @return array where the keys and values are both the filter name, like 'tex'.
918
 */
919
function filter_get_string_filters() {
920
    global $CFG;
921
    $stringfilters = array();
922
    if (!empty($CFG->filterall) && !empty($CFG->stringfilters)) {
923
        $stringfilters = explode(',', $CFG->stringfilters);
924
        $stringfilters = array_combine($stringfilters, $stringfilters);
925
    }
926
    return $stringfilters;
927
}
928
 
929
/**
930
 * Sets whether a particular active filter should be applied to all strings by
931
 * format_string, or just used by format_text.
932
 *
933
 * @param string $filter The filter name, for example 'tex'.
934
 * @param boolean $applytostrings if true, this filter will apply to format_string
935
 *      and format_text, when it is enabled.
936
 */
937
function filter_set_applies_to_strings($filter, $applytostrings) {
938
    $stringfilters = filter_get_string_filters();
939
    $prevfilters = $stringfilters;
940
    $allfilters = core_component::get_plugin_list('filter');
941
 
942
    if ($applytostrings) {
943
        $stringfilters[$filter] = $filter;
944
    } else {
945
        unset($stringfilters[$filter]);
946
    }
947
 
948
    // Remove missing filters.
949
    foreach ($stringfilters as $filter) {
950
        if (!isset($allfilters[$filter])) {
951
            unset($stringfilters[$filter]);
952
        }
953
    }
954
 
955
    if ($prevfilters != $stringfilters) {
956
        set_config('stringfilters', implode(',', $stringfilters));
957
        set_config('filterall', !empty($stringfilters));
958
    }
959
}
960
 
961
/**
962
 * Set the local activated state for a text filter.
963
 *
964
 * @param string $filter The filter name, for example 'tex'.
965
 * @param integer $contextid The id of the context to get the local config for.
966
 * @param integer $state One of the values TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_INHERIT.
967
 * @return void
968
 */
969
function filter_set_local_state($filter, $contextid, $state) {
970
    global $DB;
971
 
972
    // Check requested state is valid.
973
    if (!in_array($state, array(TEXTFILTER_ON, TEXTFILTER_OFF, TEXTFILTER_INHERIT))) {
974
        throw new coding_exception("Illegal option '$state' passed to filter_set_local_state. " .
975
                "Must be one of TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_INHERIT.");
976
    }
977
 
978
    if ($contextid == context_system::instance()->id) {
979
        throw new coding_exception('You cannot use filter_set_local_state ' .
980
                'with $contextid equal to the system context id.');
981
    }
982
 
983
    if ($state == TEXTFILTER_INHERIT) {
984
        $DB->delete_records('filter_active', array('filter' => $filter, 'contextid' => $contextid));
985
        return;
986
    }
987
 
988
    $rec = $DB->get_record('filter_active', array('filter' => $filter, 'contextid' => $contextid));
989
    $insert = false;
990
    if (empty($rec)) {
991
        $insert = true;
992
        $rec = new stdClass;
993
        $rec->filter = $filter;
994
        $rec->contextid = $contextid;
995
    }
996
 
997
    $rec->active = $state;
998
 
999
    if ($insert) {
1000
        $DB->insert_record('filter_active', $rec);
1001
    } else {
1002
        $DB->update_record('filter_active', $rec);
1003
    }
1004
}
1005
 
1006
/**
1007
 * Set a particular local config variable for a filter in a context.
1008
 *
1009
 * @param string $filter The filter name, for example 'tex'.
1010
 * @param integer $contextid The id of the context to get the local config for.
1011
 * @param string $name the setting name.
1012
 * @param string $value the corresponding value.
1013
 */
1014
function filter_set_local_config($filter, $contextid, $name, $value) {
1015
    global $DB;
1016
    $rec = $DB->get_record('filter_config', array('filter' => $filter, 'contextid' => $contextid, 'name' => $name));
1017
    $insert = false;
1018
    if (empty($rec)) {
1019
        $insert = true;
1020
        $rec = new stdClass;
1021
        $rec->filter = $filter;
1022
        $rec->contextid = $contextid;
1023
        $rec->name = $name;
1024
    }
1025
 
1026
    $rec->value = $value;
1027
 
1028
    if ($insert) {
1029
        $DB->insert_record('filter_config', $rec);
1030
    } else {
1031
        $DB->update_record('filter_config', $rec);
1032
    }
1033
}
1034
 
1035
/**
1036
 * Remove a particular local config variable for a filter in a context.
1037
 *
1038
 * @param string $filter The filter name, for example 'tex'.
1039
 * @param integer $contextid The id of the context to get the local config for.
1040
 * @param string $name the setting name.
1041
 */
1042
function filter_unset_local_config($filter, $contextid, $name) {
1043
    global $DB;
1044
    $DB->delete_records('filter_config', array('filter' => $filter, 'contextid' => $contextid, 'name' => $name));
1045
}
1046
 
1047
/**
1048
 * Get local config variables for a filter in a context. Normally (when your
1049
 * filter is running) you don't need to call this, becuase the config is fetched
1050
 * for you automatically. You only need this, for example, when you are getting
1051
 * the config so you can show the user an editing from.
1052
 *
1053
 * @param string $filter The filter name, for example 'tex'.
1054
 * @param integer $contextid The ID of the context to get the local config for.
1055
 * @return array of name => value pairs.
1056
 */
1057
function filter_get_local_config($filter, $contextid) {
1058
    global $DB;
1059
    return $DB->get_records_menu('filter_config', array('filter' => $filter, 'contextid' => $contextid), '', 'name,value');
1060
}
1061
 
1062
/**
1063
 * This function is for use by backup. Gets all the filter information specific
1064
 * to one context.
1065
 *
1066
 * @param int $contextid
1067
 * @return array Array with two elements. The first element is an array of objects with
1068
 *      fields filter and active. These come from the filter_active table. The
1069
 *      second element is an array of objects with fields filter, name and value
1070
 *      from the filter_config table.
1071
 */
1072
function filter_get_all_local_settings($contextid) {
1073
    global $DB;
1074
    return array(
1075
        $DB->get_records('filter_active', array('contextid' => $contextid), 'filter', 'filter,active'),
1076
        $DB->get_records('filter_config', array('contextid' => $contextid), 'filter,name', 'filter,name,value'),
1077
    );
1078
}
1079
 
1080
/**
1081
 * Get the list of active filters, in the order that they should be used
1082
 * for a particular context, along with any local configuration variables.
1083
 *
1084
 * @param context $context a context
1085
 * @return array an array where the keys are the filter names, for example
1086
 *      'tex' and the values are any local
1087
 *      configuration for that filter, as an array of name => value pairs
1088
 *      from the filter_config table. In a lot of cases, this will be an
1089
 *      empty array. So, an example return value for this function might be
1090
 *      array(tex' => array())
1091
 */
1092
function filter_get_active_in_context($context) {
1093
    global $DB, $FILTERLIB_PRIVATE;
1094
 
1095
    if (!isset($FILTERLIB_PRIVATE)) {
1096
        $FILTERLIB_PRIVATE = new stdClass();
1097
    }
1098
 
1099
    // Use cache (this is a within-request cache only) if available. See
1100
    // function filter_preload_activities.
1101
    if (isset($FILTERLIB_PRIVATE->active) &&
1102
            array_key_exists($context->id, $FILTERLIB_PRIVATE->active)) {
1103
        return $FILTERLIB_PRIVATE->active[$context->id];
1104
    }
1105
 
1106
    $contextids = str_replace('/', ',', trim($context->path, '/'));
1107
 
11 efrain 1108
    // Postgres recordset performance is much better with a limit.
1109
    // This should be much larger than anything needed in practice. The code below checks we don't hit this limit.
1110
    $maxpossiblerows = 10000;
1111
    // The key line in the following query is the HAVING clause.
1112
    // If a filter is disabled at system context, then there is a row with active -9999 and depth 1,
1113
    // so the -MIN is always large, and the MAX will be smaller than that and this filter won't be returned.
1114
    // Otherwise, there will be a bunch of +/-1s at various depths,
1115
    // and this clause verifies there is a +1 that deeper than any -1.
1116
    $rows = $DB->get_recordset_sql("
1117
            SELECT active.filter, fc.name, fc.value
1 efrain 1118
 
11 efrain 1119
              FROM (
1120
                    SELECT fa.filter, MAX(fa.sortorder) AS sortorder
1121
                      FROM {filter_active} fa
1122
                      JOIN {context} ctx ON fa.contextid = ctx.id
1123
                     WHERE ctx.id IN ($contextids)
1124
                  GROUP BY fa.filter
1125
                    HAVING MAX(fa.active * ctx.depth) > -MIN(fa.active * ctx.depth)
1126
                   ) active
1127
         LEFT JOIN {filter_config} fc ON fc.filter = active.filter AND fc.contextid = ?
1128
 
1129
          ORDER BY active.sortorder
1130
        ", [$context->id], 0, $maxpossiblerows);
1131
 
1 efrain 1132
    // Massage the data into the specified format to return.
11 efrain 1133
    $filters = [];
1134
    $rowcount = 0;
1135
    foreach ($rows as $row) {
1136
        $rowcount += 1;
1 efrain 1137
        if (!isset($filters[$row->filter])) {
11 efrain 1138
            $filters[$row->filter] = [];
1 efrain 1139
        }
1140
        if (!is_null($row->name)) {
1141
            $filters[$row->filter][$row->name] = $row->value;
1142
        }
1143
    }
11 efrain 1144
    $rows->close();
1 efrain 1145
 
11 efrain 1146
    if ($rowcount >= $maxpossiblerows) {
1147
        // If this ever did happen, which seems essentially impossible, then it would lead to very subtle and
1148
        // hard to understand bugs, so ensure it leads to an unmissable error.
1149
        throw new coding_exception('Hit the row limit that should never be hit in filter_get_active_in_context.');
1150
    }
1 efrain 1151
 
1152
    return $filters;
1153
}
1154
 
1155
/**
1156
 * Preloads the list of active filters for all activities (modules) on the course
1157
 * using two database queries.
1158
 *
1159
 * @param course_modinfo $modinfo Course object from get_fast_modinfo
1160
 */
1161
function filter_preload_activities(course_modinfo $modinfo) {
1162
    global $DB, $FILTERLIB_PRIVATE;
1163
 
1164
    if (!isset($FILTERLIB_PRIVATE)) {
1165
        $FILTERLIB_PRIVATE = new stdClass();
1166
    }
1167
 
1168
    // Don't repeat preload.
1169
    if (!isset($FILTERLIB_PRIVATE->preloaded)) {
1170
        $FILTERLIB_PRIVATE->preloaded = array();
1171
    }
1172
    if (!empty($FILTERLIB_PRIVATE->preloaded[$modinfo->get_course_id()])) {
1173
        return;
1174
    }
1175
    $FILTERLIB_PRIVATE->preloaded[$modinfo->get_course_id()] = true;
1176
 
1177
    // Get contexts for all CMs.
1178
    $cmcontexts = array();
1179
    $cmcontextids = array();
1180
    foreach ($modinfo->get_cms() as $cm) {
1181
        $modulecontext = context_module::instance($cm->id);
1182
        $cmcontextids[] = $modulecontext->id;
1183
        $cmcontexts[] = $modulecontext;
1184
    }
1185
 
1186
    // Get course context and all other parents.
1187
    $coursecontext = context_course::instance($modinfo->get_course_id());
1188
    $parentcontextids = explode('/', substr($coursecontext->path, 1));
1189
    $allcontextids = array_merge($cmcontextids, $parentcontextids);
1190
 
1191
    // Get all filter_active rows relating to all these contexts.
1192
    list ($sql, $params) = $DB->get_in_or_equal($allcontextids);
1193
    $filteractives = $DB->get_records_select('filter_active', "contextid $sql", $params, 'sortorder');
1194
 
1195
    // Get all filter_config only for the cm contexts.
1196
    list ($sql, $params) = $DB->get_in_or_equal($cmcontextids);
1197
    $filterconfigs = $DB->get_records_select('filter_config', "contextid $sql", $params);
1198
 
1199
    // Note: I was a bit surprised that filter_config only works for the
1200
    // most specific context (i.e. it does not need to be checked for course
1201
    // context if we only care about CMs) however basede on code in
1202
    // filter_get_active_in_context, this does seem to be correct.
1203
 
1204
    // Build course default active list. Initially this will be an array of
1205
    // filter name => active score (where an active score >0 means it's active).
1206
    $courseactive = array();
1207
 
1208
    // Also build list of filter_active rows below course level, by contextid.
1209
    $remainingactives = array();
1210
 
1211
    // Array lists filters that are banned at top level.
1212
    $banned = array();
1213
 
1214
    // Add any active filters in parent contexts to the array.
1215
    foreach ($filteractives as $row) {
1216
        $depth = array_search($row->contextid, $parentcontextids);
1217
        if ($depth !== false) {
1218
            // Find entry.
1219
            if (!array_key_exists($row->filter, $courseactive)) {
1220
                $courseactive[$row->filter] = 0;
1221
            }
1222
            // This maths copes with reading rows in any order. Turning on/off
1223
            // at site level counts 1, at next level down 4, at next level 9,
1224
            // then 16, etc. This means the deepest level always wins, except
1225
            // against the -9999 at top level.
1226
            $courseactive[$row->filter] +=
1227
                ($depth + 1) * ($depth + 1) * $row->active;
1228
 
1229
            if ($row->active == TEXTFILTER_DISABLED) {
1230
                $banned[$row->filter] = true;
1231
            }
1232
        } else {
1233
            // Build list of other rows indexed by contextid.
1234
            if (!array_key_exists($row->contextid, $remainingactives)) {
1235
                $remainingactives[$row->contextid] = array();
1236
            }
1237
            $remainingactives[$row->contextid][] = $row;
1238
        }
1239
    }
1240
 
1241
    // Chuck away the ones that aren't active.
1242
    foreach ($courseactive as $filter => $score) {
1243
        if ($score <= 0) {
1244
            unset($courseactive[$filter]);
1245
        } else {
1246
            $courseactive[$filter] = array();
1247
        }
1248
    }
1249
 
1250
    // Loop through the contexts to reconstruct filter_active lists for each
1251
    // cm on the course.
1252
    if (!isset($FILTERLIB_PRIVATE->active)) {
1253
        $FILTERLIB_PRIVATE->active = array();
1254
    }
1255
    foreach ($cmcontextids as $contextid) {
1256
        // Copy course list.
1257
        $FILTERLIB_PRIVATE->active[$contextid] = $courseactive;
1258
 
1259
        // Are there any changes to the active list?
1260
        if (array_key_exists($contextid, $remainingactives)) {
1261
            foreach ($remainingactives[$contextid] as $row) {
1262
                if ($row->active > 0 && empty($banned[$row->filter])) {
1263
                    // If it's marked active for specific context, add entry
1264
                    // (doesn't matter if one exists already).
1265
                    $FILTERLIB_PRIVATE->active[$contextid][$row->filter] = array();
1266
                } else {
1267
                    // If it's marked inactive, remove entry (doesn't matter
1268
                    // if it doesn't exist).
1269
                    unset($FILTERLIB_PRIVATE->active[$contextid][$row->filter]);
1270
                }
1271
            }
1272
        }
1273
    }
1274
 
1275
    // Process all config rows to add config data to these entries.
1276
    foreach ($filterconfigs as $row) {
1277
        if (isset($FILTERLIB_PRIVATE->active[$row->contextid][$row->filter])) {
1278
            $FILTERLIB_PRIVATE->active[$row->contextid][$row->filter][$row->name] = $row->value;
1279
        }
1280
    }
1281
}
1282
 
1283
/**
1284
 * List all of the filters that are available in this context, and what the
1285
 * local and inherited states of that filter are.
1286
 *
1287
 * @param context $context a context that is not the system context.
1288
 * @return array an array with filter names, for example 'tex'
1289
 *      as keys. and and the values are objects with fields:
1290
 *      ->filter filter name, same as the key.
1291
 *      ->localstate TEXTFILTER_ON/OFF/INHERIT
1292
 *      ->inheritedstate TEXTFILTER_ON/OFF - the state that will be used if localstate is set to TEXTFILTER_INHERIT.
1293
 */
1294
function filter_get_available_in_context($context) {
1295
    global $DB;
1296
 
1297
    // The complex logic is working out the active state in the parent context,
1298
    // so strip the current context from the list.
1299
    $contextids = explode('/', trim($context->path, '/'));
1300
    array_pop($contextids);
1301
    $contextids = implode(',', $contextids);
1302
    if (empty($contextids)) {
1303
        throw new coding_exception('filter_get_available_in_context cannot be called with the system context.');
1304
    }
1305
 
1306
    // The following SQL is tricky, in the same way at the SQL in filter_get_active_in_context.
1307
    $sql = "SELECT parent_states.filter,
1308
                CASE WHEN fa.active IS NULL THEN " . TEXTFILTER_INHERIT . "
1309
                ELSE fa.active END AS localstate,
1310
             parent_states.inheritedstate
1311
         FROM (SELECT f.filter, MAX(f.sortorder) AS sortorder,
1312
                    CASE WHEN MAX(f.active * ctx.depth) > -MIN(f.active * ctx.depth) THEN " . TEXTFILTER_ON . "
1313
                    ELSE " . TEXTFILTER_OFF . " END AS inheritedstate
1314
             FROM {filter_active} f
1315
             JOIN {context} ctx ON f.contextid = ctx.id
1316
             WHERE ctx.id IN ($contextids)
1317
             GROUP BY f.filter
1318
             HAVING MIN(f.active) > " . TEXTFILTER_DISABLED . "
1319
         ) parent_states
1320
         LEFT JOIN {filter_active} fa ON fa.filter = parent_states.filter AND fa.contextid = $context->id
1321
         ORDER BY parent_states.sortorder";
1322
    return $DB->get_records_sql($sql);
1323
}
1324
 
1325
/**
1326
 * This function is for use by the filter administration page.
1327
 *
1328
 * @return array 'filtername' => object with fields 'filter' (=filtername), 'active' and 'sortorder'
1329
 */
1330
function filter_get_global_states() {
1331
    global $DB;
1332
    $context = context_system::instance();
1333
    return $DB->get_records('filter_active', array('contextid' => $context->id), 'sortorder', 'filter,active,sortorder');
1334
}
1335
 
1336
/**
1337
 * Retrieve all the filters and their states (including overridden ones in any context).
1338
 *
1339
 * @return array filters objects containing filter name, context, active state and sort order.
1340
 */
1341
function filter_get_all_states(): array {
1342
    global $DB;
1343
    return $DB->get_records('filter_active');
1344
}
1345
 
1346
/**
1347
 * Delete all the data in the database relating to a filter, prior to deleting it.
1348
 *
1349
 * @param string $filter The filter name, for example 'tex'.
1350
 */
1351
function filter_delete_all_for_filter($filter) {
1352
    global $DB;
1353
 
1354
    unset_all_config_for_plugin('filter_' . $filter);
1355
    $DB->delete_records('filter_active', array('filter' => $filter));
1356
    $DB->delete_records('filter_config', array('filter' => $filter));
1357
}
1358
 
1359
/**
1360
 * Delete all the data in the database relating to a context, used when contexts are deleted.
1361
 *
1362
 * @param integer $contextid The id of the context being deleted.
1363
 */
1364
function filter_delete_all_for_context($contextid) {
1365
    global $DB;
1366
    $DB->delete_records('filter_active', array('contextid' => $contextid));
1367
    $DB->delete_records('filter_config', array('contextid' => $contextid));
1368
}
1369
 
1370
/**
1371
 * Does this filter have a global settings page in the admin tree?
1372
 * (The settings page for a filter must be called, for example, filtersettingfiltertex.)
1373
 *
1374
 * @param string $filter The filter name, for example 'tex'.
1375
 * @return boolean Whether there should be a 'Settings' link on the config page.
1376
 */
1377
function filter_has_global_settings($filter) {
1378
    global $CFG;
1379
    $settingspath = $CFG->dirroot . '/filter/' . $filter . '/settings.php';
1380
    if (is_readable($settingspath)) {
1381
        return true;
1382
    }
1383
    $settingspath = $CFG->dirroot . '/filter/' . $filter . '/filtersettings.php';
1384
    return is_readable($settingspath);
1385
}
1386
 
1387
/**
1388
 * Does this filter have local (per-context) settings?
1389
 *
1390
 * @param string $filter The filter name, for example 'tex'.
1391
 * @return boolean Whether there should be a 'Settings' link on the manage filters in context page.
1392
 */
1393
function filter_has_local_settings($filter) {
1394
    global $CFG;
1395
    $settingspath = $CFG->dirroot . '/filter/' . $filter . '/filterlocalsettings.php';
1396
    return is_readable($settingspath);
1397
}
1398
 
1399
/**
1400
 * Certain types of context (block and user) may not have local filter settings.
1401
 * the function checks a context to see whether it may have local config.
1402
 *
1403
 * @param object $context a context.
1404
 * @return boolean whether this context may have local filter settings.
1405
 */
1406
function filter_context_may_have_filter_settings($context) {
1407
    return $context->contextlevel != CONTEXT_BLOCK && $context->contextlevel != CONTEXT_USER;
1408
}
1409
 
1410
/**
1411
 * Process phrases intelligently found within a HTML text (such as adding links).
1412
 *
1413
 * @param string $text            the text that we are filtering
1414
 * @param filterobject[] $linkarray an array of filterobjects
1415
 * @param array $ignoretagsopen   an array of opening tags that we should ignore while filtering
1416
 * @param array $ignoretagsclose  an array of corresponding closing tags
1417
 * @param bool $overridedefaultignore True to only use tags provided by arguments
1418
 * @param bool $linkarrayalreadyprepared True to say that filter_prepare_phrases_for_filtering
1419
 *      has already been called for $linkarray. Default false.
1420
 * @return string
1421
 */
1422
function filter_phrases($text, $linkarray, $ignoretagsopen = null, $ignoretagsclose = null,
1423
        $overridedefaultignore = false, $linkarrayalreadyprepared = false) {
1424
 
1425
    global $CFG;
1426
 
1427
    // Used if $CFG->filtermatchoneperpage is on. Array with keys being the workregexp
1428
    // for things that have already been matched on this page.
1429
    static $usedphrases = [];
1430
 
1431
    $ignoretags = array();  // To store all the enclosing tags to be completely ignored.
1432
    $tags = array();        // To store all the simple tags to be ignored.
1433
 
1434
    if (!$linkarrayalreadyprepared) {
1435
        $linkarray = filter_prepare_phrases_for_filtering($linkarray);
1436
    }
1437
 
1438
    if (!$overridedefaultignore) {
1439
        // A list of open/close tags that we should not replace within.
1440
        // Extended to include <script>, <textarea>, <select> and <a> tags.
1441
        // Regular expression allows tags with or without attributes.
1442
        $filterignoretagsopen  = array('<head>', '<nolink>', '<span(\s[^>]*?)?class="nolink"(\s[^>]*?)?>',
1443
                '<script(\s[^>]*?)?>', '<textarea(\s[^>]*?)?>',
1444
                '<select(\s[^>]*?)?>', '<a(\s[^>]*?)?>');
1445
        $filterignoretagsclose = array('</head>', '</nolink>', '</span>',
1446
                 '</script>', '</textarea>', '</select>', '</a>');
1447
    } else {
1448
        // Set an empty default list.
1449
        $filterignoretagsopen = array();
1450
        $filterignoretagsclose = array();
1451
    }
1452
 
1453
    // Add the user defined ignore tags to the default list.
1454
    if ( is_array($ignoretagsopen) ) {
1455
        foreach ($ignoretagsopen as $open) {
1456
            $filterignoretagsopen[] = $open;
1457
        }
1458
        foreach ($ignoretagsclose as $close) {
1459
            $filterignoretagsclose[] = $close;
1460
        }
1461
    }
1462
 
1463
    // Double up some magic chars to avoid "accidental matches".
1464
    $text = preg_replace('/([#*%])/', '\1\1', $text);
1465
 
1466
    // Remove everything enclosed by the ignore tags from $text.
1467
    filter_save_ignore_tags($text, $filterignoretagsopen, $filterignoretagsclose, $ignoretags);
1468
 
1469
    // Remove tags from $text.
1470
    filter_save_tags($text, $tags);
1471
 
1472
    // Prepare the limit for preg_match calls.
1473
    if (!empty($CFG->filtermatchonepertext) || !empty($CFG->filtermatchoneperpage)) {
1474
        $pregreplacelimit = 1;
1475
    } else {
1476
        $pregreplacelimit = -1; // No limit.
1477
    }
1478
 
1479
    // Time to cycle through each phrase to be linked.
1480
    foreach ($linkarray as $key => $linkobject) {
1481
        if ($linkobject->workregexp === null) {
1482
            // This is the case if, when preparing the phrases for filtering,
1483
            // we decided that this was not a suitable phrase to match.
1484
            continue;
1485
        }
1486
 
1487
        // If $CFG->filtermatchoneperpage, avoid previously matched linked phrases.
1488
        if (!empty($CFG->filtermatchoneperpage) && isset($usedphrases[$linkobject->workregexp])) {
1489
            continue;
1490
        }
1491
 
1492
        // Do our highlighting.
1493
        $resulttext = preg_replace_callback($linkobject->workregexp,
1494
                function ($matches) use ($linkobject) {
1495
                    if ($linkobject->workreplacementphrase === null) {
1496
                        filter_prepare_phrase_for_replacement($linkobject);
1497
                    }
1498
 
1499
                    return str_replace('$1', $matches[1], $linkobject->workreplacementphrase);
1500
                }, $text, $pregreplacelimit);
1501
 
1502
        // If the text has changed we have to look for links again.
1503
        if ($resulttext != $text) {
1504
            $text = $resulttext;
1505
            // Remove everything enclosed by the ignore tags from $text.
1506
            filter_save_ignore_tags($text, $filterignoretagsopen, $filterignoretagsclose, $ignoretags);
1507
            // Remove tags from $text.
1508
            filter_save_tags($text, $tags);
1509
            // If $CFG->filtermatchoneperpage, save linked phrases to request.
1510
            if (!empty($CFG->filtermatchoneperpage)) {
1511
                $usedphrases[$linkobject->workregexp] = 1;
1512
            }
1513
        }
1514
    }
1515
 
1516
    // Rebuild the text with all the excluded areas.
1517
    if (!empty($tags)) {
1518
        $text = str_replace(array_keys($tags), $tags, $text);
1519
    }
1520
 
1521
    if (!empty($ignoretags)) {
1522
        $ignoretags = array_reverse($ignoretags);     // Reversed so "progressive" str_replace() will solve some nesting problems.
1523
        $text = str_replace(array_keys($ignoretags), $ignoretags, $text);
1524
    }
1525
 
1526
    // Remove the protective doubleups.
1527
    $text = preg_replace('/([#*%])(\1)/', '\1', $text);
1528
 
1529
    // Add missing javascript for popus.
1530
    $text = filter_add_javascript($text);
1531
 
1532
    return $text;
1533
}
1534
 
1535
/**
1536
 * Prepare a list of link for processing with {@link filter_phrases()}.
1537
 *
1538
 * @param filterobject[] $linkarray the links that will be passed to filter_phrases().
1539
 * @return filterobject[] the updated list of links with necessary pre-processing done.
1540
 */
1541
function filter_prepare_phrases_for_filtering(array $linkarray) {
1542
    // Time to cycle through each phrase to be linked.
1543
    foreach ($linkarray as $linkobject) {
1544
 
1545
        // Set some defaults if certain properties are missing.
1546
        // Properties may be missing if the filterobject class has not been used to construct the object.
1547
        if (empty($linkobject->phrase)) {
1548
            continue;
1549
        }
1550
 
1551
        // Avoid integers < 1000 to be linked. See bug 1446.
1552
        $intcurrent = intval($linkobject->phrase);
1553
        if (!empty($intcurrent) && strval($intcurrent) == $linkobject->phrase && $intcurrent < 1000) {
1554
            continue;
1555
        }
1556
 
1557
        // Strip tags out of the phrase.
1558
        $linkobject->workregexp = strip_tags($linkobject->phrase);
1559
 
1560
        if (!$linkobject->casesensitive) {
1561
            $linkobject->workregexp = core_text::strtolower($linkobject->workregexp);
1562
        }
1563
 
1564
        // Double up chars that might cause a false match -- the duplicates will
1565
        // be cleared up before returning to the user.
1566
        $linkobject->workregexp = preg_replace('/([#*%])/', '\1\1', $linkobject->workregexp);
1567
 
1568
        // Quote any regular expression characters and the delimiter in the work phrase to be searched.
1569
        $linkobject->workregexp = preg_quote($linkobject->workregexp, '/');
1570
 
1571
        // If we ony want to match entire words then add \b assertions. However, only
1572
        // do this if the first or last thing in the phrase to match is a word character.
1573
        if ($linkobject->fullmatch) {
1574
            if (preg_match('~^\w~', $linkobject->workregexp)) {
1575
                $linkobject->workregexp = '\b' . $linkobject->workregexp;
1576
            }
1577
            if (preg_match('~\w$~', $linkobject->workregexp)) {
1578
                $linkobject->workregexp = $linkobject->workregexp . '\b';
1579
            }
1580
        }
1581
 
1582
        $linkobject->workregexp = '/(' . $linkobject->workregexp . ')/s';
1583
 
1584
        if (!$linkobject->casesensitive) {
1585
            $linkobject->workregexp .= 'iu';
1586
        }
1587
    }
1588
 
1589
    return $linkarray;
1590
}
1591
 
1592
/**
1593
 * Fill in the remaining ->work... fields, that would be needed to replace the phrase.
1594
 *
1595
 * @param filterobject $linkobject the link object on which to set additional fields.
1596
 */
1597
function filter_prepare_phrase_for_replacement(filterobject $linkobject) {
1598
    if ($linkobject->replacementcallback !== null) {
1599
        list($linkobject->hreftagbegin, $linkobject->hreftagend, $linkobject->replacementphrase) =
1600
                call_user_func_array($linkobject->replacementcallback, $linkobject->replacementcallbackdata);
1601
    }
1602
 
1603
    if (!isset($linkobject->hreftagbegin) or !isset($linkobject->hreftagend)) {
1604
        $linkobject->hreftagbegin = '<span class="highlight"';
1605
        $linkobject->hreftagend   = '</span>';
1606
    }
1607
 
1608
    // Double up chars to protect true duplicates
1609
    // be cleared up before returning to the user.
1610
    $hreftagbeginmangled = preg_replace('/([#*%])/', '\1\1', $linkobject->hreftagbegin);
1611
 
1612
    // Set the replacement phrase properly.
1613
    if ($linkobject->replacementphrase) {    // We have specified a replacement phrase.
1614
        $linkobject->workreplacementphrase = strip_tags($linkobject->replacementphrase);
1615
    } else {                                 // The replacement is the original phrase as matched below.
1616
        $linkobject->workreplacementphrase = '$1';
1617
    }
1618
 
1619
    $linkobject->workreplacementphrase = $hreftagbeginmangled .
1620
            $linkobject->workreplacementphrase . $linkobject->hreftagend;
1621
}
1622
 
1623
/**
1624
 * Remove duplicate from a list of {@link filterobject}.
1625
 *
1626
 * @param filterobject[] $linkarray a list of filterobject.
1627
 * @return filterobject[] the same list, but with dupicates removed.
1628
 */
1629
function filter_remove_duplicates($linkarray) {
1630
 
1631
    $concepts  = array(); // Keep a record of concepts as we cycle through.
1632
    $lconcepts = array(); // A lower case version for case insensitive.
1633
 
1634
    $cleanlinks = array();
1635
 
1636
    foreach ($linkarray as $key => $filterobject) {
1637
        if ($filterobject->casesensitive) {
1638
            $exists = in_array($filterobject->phrase, $concepts);
1639
        } else {
1640
            $exists = in_array(core_text::strtolower($filterobject->phrase), $lconcepts);
1641
        }
1642
 
1643
        if (!$exists) {
1644
            $cleanlinks[] = $filterobject;
1645
            $concepts[] = $filterobject->phrase;
1646
            $lconcepts[] = core_text::strtolower($filterobject->phrase);
1647
        }
1648
    }
1649
 
1650
    return $cleanlinks;
1651
}
1652
 
1653
/**
1654
 * Extract open/lose tags and their contents to avoid being processed by filters.
1655
 * Useful to extract pieces of code like <a>...</a> tags. It returns the text
1656
 * converted with some <#xTEXTFILTER_EXCL_SEPARATORx#> codes replacing the extracted text. Such extracted
1657
 * texts are returned in the ignoretags array (as values), with codes as keys.
1658
 *
1659
 * @param string $text                  the text that we are filtering (in/out)
1660
 * @param array $filterignoretagsopen  an array of open tags to start searching
1661
 * @param array $filterignoretagsclose an array of close tags to end searching
1662
 * @param array $ignoretags            an array of saved strings useful to rebuild the original text (in/out)
1663
 **/
1664
function filter_save_ignore_tags(&$text, $filterignoretagsopen, $filterignoretagsclose, &$ignoretags) {
1665
 
1666
    // Remove everything enclosed by the ignore tags from $text.
1667
    foreach ($filterignoretagsopen as $ikey => $opentag) {
1668
        $closetag = $filterignoretagsclose[$ikey];
1669
        // Form regular expression.
1670
        $opentag  = str_replace('/', '\/', $opentag); // Delimit forward slashes.
1671
        $closetag = str_replace('/', '\/', $closetag); // Delimit forward slashes.
1672
        $pregexp = '/'.$opentag.'(.*?)'.$closetag.'/is';
1673
 
1674
        preg_match_all($pregexp, $text, $listofignores);
1675
        foreach (array_unique($listofignores[0]) as $key => $value) {
1676
            $prefix = (string) (count($ignoretags) + 1);
1677
            $ignoretags['<#'.$prefix.TEXTFILTER_EXCL_SEPARATOR.$key.'#>'] = $value;
1678
        }
1679
        if (!empty($ignoretags)) {
1680
            $text = str_replace($ignoretags, array_keys($ignoretags), $text);
1681
        }
1682
    }
1683
}
1684
 
1685
/**
1686
 * Extract tags (any text enclosed by < and > to avoid being processed by filters.
1687
 * It returns the text converted with some <%xTEXTFILTER_EXCL_SEPARATORx%> codes replacing the extracted text. Such extracted
1688
 * texts are returned in the tags array (as values), with codes as keys.
1689
 *
1690
 * @param string $text   the text that we are filtering (in/out)
1691
 * @param array $tags   an array of saved strings useful to rebuild the original text (in/out)
1692
 **/
1693
function filter_save_tags(&$text, &$tags) {
1694
 
1695
    preg_match_all('/<([^#%*].*?)>/is', $text, $listofnewtags);
1696
    foreach (array_unique($listofnewtags[0]) as $ntkey => $value) {
1697
        $prefix = (string)(count($tags) + 1);
1698
        $tags['<%'.$prefix.TEXTFILTER_EXCL_SEPARATOR.$ntkey.'%>'] = $value;
1699
    }
1700
    if (!empty($tags)) {
1701
        $text = str_replace($tags, array_keys($tags), $text);
1702
    }
1703
}
1704
 
1705
/**
1706
 * Add missing openpopup javascript to HTML files.
1707
 *
1708
 * @param string $text
1709
 * @return string
1710
 */
1711
function filter_add_javascript($text) {
1712
    global $CFG;
1713
 
1714
    if (stripos($text, '</html>') === false) {
1715
        return $text; // This is not a html file.
1716
    }
1717
    if (strpos($text, 'onclick="return openpopup') === false) {
1718
        return $text; // No popup - no need to add javascript.
1719
    }
1720
    $js = "
1721
    <script type=\"text/javascript\">
1722
    <!--
1723
        function openpopup(url,name,options,fullscreen) {
1724
          fullurl = \"".$CFG->wwwroot."\" + url;
1725
          windowobj = window.open(fullurl,name,options);
1726
          if (fullscreen) {
1727
            windowobj.moveTo(0,0);
1728
            windowobj.resizeTo(screen.availWidth,screen.availHeight);
1729
          }
1730
          windowobj.focus();
1731
          return false;
1732
        }
1733
    // -->
1734
    </script>";
1735
    if (stripos($text, '</head>') !== false) {
1736
        // Try to add it into the head element.
1737
        $text = str_ireplace('</head>', $js.'</head>', $text);
1738
        return $text;
1739
    }
1740
 
1741
    // Last chance - try adding head element.
1742
    return preg_replace("/<html.*?>/is", "\\0<head>".$js.'</head>', $text);
1743
}