2 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
18 * Library functions for managing text filter plugins.
21 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 defined('MOODLE_INTERNAL') ||
die();
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);
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
41 define('TEXTFILTER_EXCL_SEPARATOR', chr(0x1F) . '%' . chr(0x1F));
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.
49 * This class is a singleton.
51 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
52 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
54 class filter_manager
{
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.
59 protected $textfilters = array();
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.
65 protected $stringfilters = array();
67 /** @var array Exploded version of $CFG->stringfilters. */
68 protected $stringfilternames = array();
70 /** @var filter_manager Holds the singleton instance. */
71 protected static $singletoninstance;
74 * Constructor. Protected. Use {@link instance()} instead.
76 protected function __construct() {
77 $this->stringfilternames
= filter_get_string_filters();
81 * Factory method. Use this to get the filter manager.
83 * @return filter_manager the singleton instance.
85 public static function instance() {
87 if (is_null(self
::$singletoninstance)) {
88 if (!empty($CFG->perfdebug
) and $CFG->perfdebug
> 7) {
89 self
::$singletoninstance = new performance_measuring_filter_manager();
91 self
::$singletoninstance = new self();
94 return self
::$singletoninstance;
98 * Resets the caches, usually to be called between unit tests
100 public static function reset_caches() {
101 if (self
::$singletoninstance) {
102 self
::$singletoninstance->unload_all_filters();
104 self
::$singletoninstance = null;
108 * Unloads all filters and other cached information
110 protected function unload_all_filters() {
111 $this->textfilters
= array();
112 $this->stringfilters
= array();
113 $this->stringfilternames
= array();
117 * Load all the filters required by this context.
119 * @param context $context the context.
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)) {
130 $this->textfilters
[$context->id
][$filtername] = $filter;
131 if (in_array($filtername, $this->stringfilternames
)) {
132 $this->stringfilters
[$context->id
][$filtername] = $filter;
138 * Factory method for creating a filter.
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.
146 protected function make_filter_object($filtername, $context, $localconfig) {
148 $path = $CFG->dirroot
.'/filter/'. $filtername .'/filter.php';
149 if (!is_readable($path)) {
154 $filterclassname = 'filter_' . $filtername;
155 if (class_exists($filterclassname)) {
156 return new $filterclassname($context, $localconfig);
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
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'];
177 $filtermethod = 'filter';
178 debugging('Invalid filter stage specified in options: ' . $options['stage'], DEBUG_DEVELOPER
);
180 if ($text === null ||
$text === '') {
181 // Nothing to filter.
184 foreach ($filterchain as $filtername => $filter) {
185 if ($skipfilters !== null && in_array($filtername, $skipfilters)) {
188 $text = $filter->$filtermethod($text, $options);
194 * Get all the filters that apply to a given context for calls to format_text.
196 * @param context $context
197 * @return moodle_text_filter[] A text filter
199 protected function get_text_filters($context) {
200 if (!isset($this->textfilters
[$context->id
])) {
201 $this->load_filters($context);
203 return $this->textfilters
[$context->id
];
207 * Get all the filters that apply to a given context for calls to format_string.
209 * @param context $context the context.
210 * @return moodle_text_filter[] A text filter
212 protected function get_string_filters($context) {
213 if (!isset($this->stringfilters
[$context->id
])) {
214 $this->load_filters($context);
216 return $this->stringfilters
[$context->id
];
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
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 // Remove <nolink> tags for XHTML compatibility.
232 $text = str_replace(array('<nolink>', '</nolink>'), '', $text);
237 * Filter a piece of string
239 * @param string $string The text to filter
240 * @param context $context the context.
241 * @return string resulting string
243 public function filter_string($string, $context) {
244 return $this->apply_filter_chain($string, $this->get_string_filters($context), ['stage' => 'string']);
248 * @deprecated Since Moodle 3.0 MDL-50491. This was used by the old text filtering system, but no more.
250 public function text_filtering_hash() {
251 throw new coding_exception('filter_manager::text_filtering_hash() can not be used any more');
255 * Setup page with filters requirements and other prepare stuff.
257 * This method is used by {@see format_text()} and {@see format_string()}
258 * in order to allow filters to setup any page requirement (js, css...)
259 * or perform any action needed to get them prepared before filtering itself
260 * happens by calling to each every active setup() method.
262 * Note it's executed for each piece of text filtered, so filter implementations
263 * are responsible of controlling the cardinality of the executions that may
264 * be different depending of the stuff to prepare.
266 * @param moodle_page $page the page we are going to add requirements to.
267 * @param context $context the context which contents are going to be filtered.
270 public function setup_page_for_filters($page, $context) {
271 $filters = $this->get_text_filters($context);
272 foreach ($filters as $filter) {
273 $filter->setup($page, $context);
278 * Setup the page for globally available filters.
280 * This helps setting up the page for filters which may be applied to
281 * the page, even if they do not belong to the current context, or are
282 * not yet visible because the content is lazily added (ajax). This method
283 * always uses to the system context which determines the globally
286 * This should only ever be called once per request.
288 * @param moodle_page $page The page.
291 public function setup_page_for_globally_available_filters($page) {
292 $context = context_system
::instance();
293 $filterdata = filter_get_globally_enabled_filters_with_config();
294 foreach ($filterdata as $name => $config) {
295 if (isset($this->textfilters
[$context->id
][$name])) {
296 $filter = $this->textfilters
[$context->id
][$name];
298 $filter = $this->make_filter_object($name, $context, $config);
299 if (is_null($filter)) {
303 $filter->setup($page, $context);
310 * Filter manager subclass that does nothing. Having this simplifies the logic
311 * of format_text, etc.
313 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
314 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
316 class null_filter_manager
{
318 * As for the equivalent {@link filter_manager} method.
320 * @param string $text The text to filter
321 * @param context $context not used.
322 * @param array $options not used
323 * @param array $skipfilters not used
324 * @return string resulting text.
326 public function filter_text($text, $context, array $options = array(),
327 array $skipfilters = null) {
332 * As for the equivalent {@link filter_manager} method.
334 * @param string $string The text to filter
335 * @param context $context not used.
336 * @return string resulting string
338 public function filter_string($string, $context) {
343 * As for the equivalent {@link filter_manager} method.
345 * @deprecated Since Moodle 3.0 MDL-50491.
347 public function text_filtering_hash() {
348 throw new coding_exception('filter_manager::text_filtering_hash() can not be used any more');
354 * Filter manager subclass that tracks how much work it does.
356 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
357 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
359 class performance_measuring_filter_manager
extends filter_manager
{
360 /** @var int number of filter objects created. */
361 protected $filterscreated = 0;
363 /** @var int number of calls to filter_text. */
364 protected $textsfiltered = 0;
366 /** @var int number of calls to filter_string. */
367 protected $stringsfiltered = 0;
369 protected function unload_all_filters() {
370 parent
::unload_all_filters();
371 $this->filterscreated
= 0;
372 $this->textsfiltered
= 0;
373 $this->stringsfiltered
= 0;
376 protected function make_filter_object($filtername, $context, $localconfig) {
377 $this->filterscreated++
;
378 return parent
::make_filter_object($filtername, $context, $localconfig);
381 public function filter_text($text, $context, array $options = array(),
382 array $skipfilters = null) {
383 if (!isset($options['stage']) ||
$options['stage'] === 'post_clean') {
384 $this->textsfiltered++
;
386 return parent
::filter_text($text, $context, $options, $skipfilters);
389 public function filter_string($string, $context) {
390 $this->stringsfiltered++
;
391 return parent
::filter_string($string, $context);
395 * Return performance information, in the form required by {@link get_performance_info()}.
396 * @return array the performance info.
398 public function get_performance_summary() {
400 'contextswithfilters' => count($this->textfilters
),
401 'filterscreated' => $this->filterscreated
,
402 'textsfiltered' => $this->textsfiltered
,
403 'stringsfiltered' => $this->stringsfiltered
,
405 'contextswithfilters' => 'Contexts for which filters were loaded',
406 'filterscreated' => 'Filters created',
407 'textsfiltered' => 'Pieces of content filtered',
408 'stringsfiltered' => 'Strings filtered',
415 * Base class for text filters. You just need to override this class and
416 * implement the filter method.
418 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
419 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
421 abstract class moodle_text_filter
{
422 /** @var context The context we are in. */
425 /** @var array Any local configuration for this filter in this context. */
426 protected $localconfig;
429 * Set any context-specific configuration for this filter.
431 * @param context $context The current context.
432 * @param array $localconfig Any context-specific configuration for this filter.
434 public function __construct($context, array $localconfig) {
435 $this->context
= $context;
436 $this->localconfig
= $localconfig;
440 * @deprecated Since Moodle 3.0 MDL-50491. This was used by the old text filtering system, but no more.
442 public function hash() {
443 throw new coding_exception('moodle_text_filter::hash() can not be used any more');
447 * Setup page with filter requirements and other prepare stuff.
449 * Override this method if the filter needs to setup page
450 * requirements or needs other stuff to be executed.
452 * Note this method is invoked from {@see setup_page_for_filters()}
453 * for each piece of text being filtered, so it is responsible
454 * for controlling its own execution cardinality.
456 * @param moodle_page $page the page we are going to add requirements to.
457 * @param context $context the context which contents are going to be filtered.
460 public function setup($page, $context) {
461 // Override me, if needed.
465 * Override this function to actually implement the filtering.
467 * Filter developers must make sure that filtering done after text cleaning
468 * does not introduce security vulnerabilities.
470 * @param string $text some HTML content to process.
471 * @param array $options options passed to the filters
472 * @return string the HTML content after the filtering has been applied.
474 public abstract function filter($text, array $options = array());
477 * Filter text before changing format to HTML.
479 * @param string $text
480 * @param array $options
483 public function filter_stage_pre_format(string $text, array $options): string {
484 // NOTE: override if necessary.
489 * Filter HTML text before sanitising text.
491 * NOTE: this is called even if $options['noclean'] is true and text is not cleaned.
493 * @param string $text
494 * @param array $options
497 public function filter_stage_pre_clean(string $text, array $options): string {
498 // NOTE: override if necessary.
503 * Filter HTML text at the very end after text is sanitised.
505 * NOTE: this is called even if $options['noclean'] is true and text is not cleaned.
507 * @param string $text
508 * @param array $options
511 public function filter_stage_post_clean(string $text, array $options): string {
512 // NOTE: override if necessary.
513 return $this->filter($text, $options);
517 * Filter simple text coming from format_string().
519 * Note that unless $CFG->formatstringstriptags is disabled
520 * HTML tags are not expected in returned value.
522 * @param string $text
523 * @param array $options
526 public function filter_stage_string(string $text, array $options): string {
527 // NOTE: override if necessary.
528 return $this->filter($text, $options);
534 * This is just a little object to define a phrase and some instructions
535 * for how to process it. Filters can create an array of these to pass
536 * to the @{link filter_phrases()} function below.
538 * Note that although the fields here are public, you almost certainly should
539 * never use that. All that is supported is contructing new instances of this
540 * class, and then passing an array of them to filter_phrases.
542 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
543 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
546 /** @var string this is the phrase that should be matched. */
549 /** @var bool whether to match complete words. If true, 'T' won't be matched in 'Tim'. */
552 /** @var bool whether the match needs to be case sensitive. */
553 public $casesensitive;
555 /** @var string HTML to insert before any match. */
556 public $hreftagbegin;
557 /** @var string HTML to insert after any match. */
560 /** @var null|string replacement text to go inside begin and end. If not set,
561 * the body of the replacement will be the original phrase.
563 public $replacementphrase;
565 /** @var null|string once initialised, holds the regexp for matching this phrase. */
566 public $workregexp = null;
568 /** @var null|string once initialised, holds the mangled HTML to replace the regexp with. */
569 public $workreplacementphrase = null;
571 /** @var null|callable hold a replacement function to be called. */
572 public $replacementcallback;
574 /** @var null|array data to be passed to $replacementcallback. */
575 public $replacementcallbackdata;
580 * @param string $phrase this is the phrase that should be matched.
581 * @param string $hreftagbegin HTML to insert before any match. Default '<span class="highlight">'.
582 * @param string $hreftagend HTML to insert after any match. Default '</span>'.
583 * @param bool $casesensitive whether the match needs to be case sensitive
584 * @param bool $fullmatch whether to match complete words. If true, 'T' won't be matched in 'Tim'.
585 * @param mixed $replacementphrase replacement text to go inside begin and end. If not set,
586 * the body of the replacement will be the original phrase.
587 * @param callback $replacementcallback if set, then this will be called just before
588 * $hreftagbegin, $hreftagend and $replacementphrase are needed, so they can be computed only if required.
590 * list($linkobject->hreftagbegin, $linkobject->hreftagend, $linkobject->replacementphrase) =
591 * call_user_func_array($linkobject->replacementcallback, $linkobject->replacementcallbackdata);
592 * so the return should be an array [$hreftagbegin, $hreftagend, $replacementphrase], the last of which may be null.
593 * @param array $replacementcallbackdata data to be passed to $replacementcallback (optional).
595 public function __construct($phrase, $hreftagbegin = '<span class="highlight">',
596 $hreftagend = '</span>',
597 $casesensitive = false,
599 $replacementphrase = null,
600 $replacementcallback = null,
601 array $replacementcallbackdata = null) {
603 $this->phrase
= $phrase;
604 $this->hreftagbegin
= $hreftagbegin;
605 $this->hreftagend
= $hreftagend;
606 $this->casesensitive
= !empty($casesensitive);
607 $this->fullmatch
= !empty($fullmatch);
608 $this->replacementphrase
= $replacementphrase;
609 $this->replacementcallback
= $replacementcallback;
610 $this->replacementcallbackdata
= $replacementcallbackdata;
615 * Look up the name of this filter
617 * @param string $filter the filter name
618 * @return string the human-readable name for this filter.
620 function filter_get_name($filter) {
621 if (strpos($filter, 'filter/') === 0) {
622 debugging("Old '$filter'' parameter used in filter_get_name()");
623 $filter = substr($filter, 7);
624 } else if (strpos($filter, '/') !== false) {
625 throw new coding_exception('Unknown filter type ' . $filter);
628 if (get_string_manager()->string_exists('filtername', 'filter_' . $filter)) {
629 return get_string('filtername', 'filter_' . $filter);
636 * Get the names of all the filters installed in this Moodle.
638 * @return array path => filter name from the appropriate lang file. e.g.
639 * array('tex' => 'TeX Notation');
640 * sorted in alphabetical order of name.
642 function filter_get_all_installed() {
643 $filternames = array();
644 foreach (core_component
::get_plugin_list('filter') as $filter => $fulldir) {
645 if (is_readable("$fulldir/filter.php")) {
646 $filternames[$filter] = filter_get_name($filter);
649 core_collator
::asort($filternames);
654 * Set the global activated state for a text filter.
656 * @param string $filtername The filter name, for example 'tex'.
657 * @param int $state One of the values TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_DISABLED.
658 * @param int $move -1 means up, 0 means the same, 1 means down
660 function filter_set_global_state($filtername, $state, $move = 0) {
663 // Check requested state is valid.
664 if (!in_array($state, array(TEXTFILTER_ON
, TEXTFILTER_OFF
, TEXTFILTER_DISABLED
))) {
665 throw new coding_exception("Illegal option '$state' passed to filter_set_global_state. " .
666 "Must be one of TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_DISABLED.");
671 } else if ($move < 0) {
675 if (strpos($filtername, 'filter/') === 0) {
676 $filtername = substr($filtername, 7);
677 } else if (strpos($filtername, '/') !== false) {
678 throw new coding_exception("Invalid filter name '$filtername' used in filter_set_global_state()");
681 $transaction = $DB->start_delegated_transaction();
683 $syscontext = context_system
::instance();
684 $filters = $DB->get_records('filter_active', array('contextid' => $syscontext->id
), 'sortorder ASC');
689 foreach ($filters as $f) {
690 if ($f->active
== TEXTFILTER_DISABLED
) {
691 $off[$f->filter
] = $f;
693 $on[$f->filter
] = $f;
697 // Update the state or add new record.
698 if (isset($on[$filtername])) {
699 $filter = $on[$filtername];
700 if ($filter->active
!= $state) {
701 add_to_config_log('filter_active', $filter->active
, $state, $filtername);
703 $filter->active
= $state;
704 $DB->update_record('filter_active', $filter);
705 if ($filter->active
== TEXTFILTER_DISABLED
) {
706 unset($on[$filtername]);
707 $off = array($filter->filter
=> $filter) +
$off;
712 } else if (isset($off[$filtername])) {
713 $filter = $off[$filtername];
714 if ($filter->active
!= $state) {
715 add_to_config_log('filter_active', $filter->active
, $state, $filtername);
717 $filter->active
= $state;
718 $DB->update_record('filter_active', $filter);
719 if ($filter->active
!= TEXTFILTER_DISABLED
) {
720 unset($off[$filtername]);
721 $on[$filter->filter
] = $filter;
726 add_to_config_log('filter_active', '', $state, $filtername);
728 $filter = new stdClass();
729 $filter->filter
= $filtername;
730 $filter->contextid
= $syscontext->id
;
731 $filter->active
= $state;
732 $filter->sortorder
= 99999;
733 $filter->id
= $DB->insert_record('filter_active', $filter);
735 $filters[$filter->id
] = $filter;
736 if ($state == TEXTFILTER_DISABLED
) {
737 $off[$filter->filter
] = $filter;
739 $on[$filter->filter
] = $filter;
744 if ($move != 0 and isset($on[$filter->filter
])) {
745 // Capture the old order for logging.
746 $oldorder = implode(', ', array_map(
751 // Work out the new order.
753 foreach ($on as $f) {
754 $f->newsortorder
= $i;
758 $filter->newsortorder
= $filter->newsortorder +
$move;
760 foreach ($on as $f) {
761 if ($f->id
== $filter->id
) {
764 if ($f->newsortorder
== $filter->newsortorder
) {
766 $f->newsortorder
= $f->newsortorder
- 1;
768 $f->newsortorder
= $f->newsortorder +
1;
773 core_collator
::asort_objects_by_property($on, 'newsortorder', core_collator
::SORT_NUMERIC
);
775 // Log in config_log.
776 $neworder = implode(', ', array_map(
780 add_to_config_log('order', $oldorder, $neworder, 'core_filter');
783 // Inactive are sorted by filter name.
784 core_collator
::asort_objects_by_property($off, 'filter', core_collator
::SORT_NATURAL
);
786 // Update records if necessary.
788 foreach ($on as $f) {
789 if ($f->sortorder
!= $i) {
790 $DB->set_field('filter_active', 'sortorder', $i, array('id' => $f->id
));
794 foreach ($off as $f) {
795 if ($f->sortorder
!= $i) {
796 $DB->set_field('filter_active', 'sortorder', $i, array('id' => $f->id
));
801 $transaction->allow_commit();
805 * Returns the active state for a filter in the given context.
807 * @param string $filtername The filter name, for example 'tex'.
808 * @param integer $contextid The id of the context to get the data for.
809 * @return int value of active field for the given filter.
811 function filter_get_active_state(string $filtername, $contextid = null): int {
814 if ($contextid === null) {
815 $contextid = context_system
::instance()->id
;
817 if (is_object($contextid)) {
818 $contextid = $contextid->id
;
821 if (strpos($filtername, 'filter/') === 0) {
822 $filtername = substr($filtername, 7);
823 } else if (strpos($filtername, '/') !== false) {
824 throw new coding_exception("Invalid filter name '$filtername' used in filter_is_enabled()");
826 if ($active = $DB->get_field('filter_active', 'active', array('filter' => $filtername, 'contextid' => $contextid))) {
830 return TEXTFILTER_DISABLED
;
834 * @param string $filtername The filter name, for example 'tex'.
835 * @return boolean is this filter allowed to be used on this site. That is, the
836 * admin has set the global 'active' setting to On, or Off, but available.
838 function filter_is_enabled($filtername) {
839 if (strpos($filtername, 'filter/') === 0) {
840 $filtername = substr($filtername, 7);
841 } else if (strpos($filtername, '/') !== false) {
842 throw new coding_exception("Invalid filter name '$filtername' used in filter_is_enabled()");
844 return array_key_exists($filtername, filter_get_globally_enabled());
848 * Return a list of all the filters that may be in use somewhere.
850 * @return array where the keys and values are both the filter name, like 'tex'.
852 function filter_get_globally_enabled() {
853 $cache = \cache
::make_from_params(\cache_store
::MODE_REQUEST
, 'core_filter', 'global_filters');
854 $enabledfilters = $cache->get('enabled');
855 if ($enabledfilters !== false) {
856 return $enabledfilters;
859 $filters = filter_get_global_states();
860 $enabledfilters = array();
861 foreach ($filters as $filter => $filerinfo) {
862 if ($filerinfo->active
!= TEXTFILTER_DISABLED
) {
863 $enabledfilters[$filter] = $filter;
867 $cache->set('enabled', $enabledfilters);
868 return $enabledfilters;
872 * Get the globally enabled filters.
874 * This returns the filters which could be used in any context. Essentially
875 * the filters which are not disabled for the entire site.
877 * @return array Keys are filter names, and values the config.
879 function filter_get_globally_enabled_filters_with_config() {
882 $sql = "SELECT f.filter, fc.name, fc.value
883 FROM {filter_active} f
884 LEFT JOIN {filter_config} fc
885 ON fc.filter = f.filter
886 AND fc.contextid = f.contextid
887 WHERE f.contextid = :contextid
888 AND f.active != :disabled
889 ORDER BY f.sortorder";
891 $rs = $DB->get_recordset_sql($sql, [
892 'contextid' => context_system
::instance()->id
,
893 'disabled' => TEXTFILTER_DISABLED
896 // Massage the data into the specified format to return.
898 foreach ($rs as $row) {
899 if (!isset($filters[$row->filter
])) {
900 $filters[$row->filter
] = array();
902 if ($row->name
!== null) {
903 $filters[$row->filter
][$row->name
] = $row->value
;
912 * Return the names of the filters that should also be applied to strings
913 * (when they are enabled).
915 * @return array where the keys and values are both the filter name, like 'tex'.
917 function filter_get_string_filters() {
919 $stringfilters = array();
920 if (!empty($CFG->filterall
) && !empty($CFG->stringfilters
)) {
921 $stringfilters = explode(',', $CFG->stringfilters
);
922 $stringfilters = array_combine($stringfilters, $stringfilters);
924 return $stringfilters;
928 * Sets whether a particular active filter should be applied to all strings by
929 * format_string, or just used by format_text.
931 * @param string $filter The filter name, for example 'tex'.
932 * @param boolean $applytostrings if true, this filter will apply to format_string
933 * and format_text, when it is enabled.
935 function filter_set_applies_to_strings($filter, $applytostrings) {
936 $stringfilters = filter_get_string_filters();
937 $prevfilters = $stringfilters;
938 $allfilters = core_component
::get_plugin_list('filter');
940 if ($applytostrings) {
941 $stringfilters[$filter] = $filter;
943 unset($stringfilters[$filter]);
946 // Remove missing filters.
947 foreach ($stringfilters as $filter) {
948 if (!isset($allfilters[$filter])) {
949 unset($stringfilters[$filter]);
953 if ($prevfilters != $stringfilters) {
954 set_config('stringfilters', implode(',', $stringfilters));
955 set_config('filterall', !empty($stringfilters));
960 * Set the local activated state for a text filter.
962 * @param string $filter The filter name, for example 'tex'.
963 * @param integer $contextid The id of the context to get the local config for.
964 * @param integer $state One of the values TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_INHERIT.
967 function filter_set_local_state($filter, $contextid, $state) {
970 // Check requested state is valid.
971 if (!in_array($state, array(TEXTFILTER_ON
, TEXTFILTER_OFF
, TEXTFILTER_INHERIT
))) {
972 throw new coding_exception("Illegal option '$state' passed to filter_set_local_state. " .
973 "Must be one of TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_INHERIT.");
976 if ($contextid == context_system
::instance()->id
) {
977 throw new coding_exception('You cannot use filter_set_local_state ' .
978 'with $contextid equal to the system context id.');
981 if ($state == TEXTFILTER_INHERIT
) {
982 $DB->delete_records('filter_active', array('filter' => $filter, 'contextid' => $contextid));
986 $rec = $DB->get_record('filter_active', array('filter' => $filter, 'contextid' => $contextid));
991 $rec->filter
= $filter;
992 $rec->contextid
= $contextid;
995 $rec->active
= $state;
998 $DB->insert_record('filter_active', $rec);
1000 $DB->update_record('filter_active', $rec);
1005 * Set a particular local config variable for a filter in a context.
1007 * @param string $filter The filter name, for example 'tex'.
1008 * @param integer $contextid The id of the context to get the local config for.
1009 * @param string $name the setting name.
1010 * @param string $value the corresponding value.
1012 function filter_set_local_config($filter, $contextid, $name, $value) {
1014 $rec = $DB->get_record('filter_config', array('filter' => $filter, 'contextid' => $contextid, 'name' => $name));
1018 $rec = new stdClass
;
1019 $rec->filter
= $filter;
1020 $rec->contextid
= $contextid;
1024 $rec->value
= $value;
1027 $DB->insert_record('filter_config', $rec);
1029 $DB->update_record('filter_config', $rec);
1034 * Remove a particular local config variable for a filter in a context.
1036 * @param string $filter The filter name, for example 'tex'.
1037 * @param integer $contextid The id of the context to get the local config for.
1038 * @param string $name the setting name.
1040 function filter_unset_local_config($filter, $contextid, $name) {
1042 $DB->delete_records('filter_config', array('filter' => $filter, 'contextid' => $contextid, 'name' => $name));
1046 * Get local config variables for a filter in a context. Normally (when your
1047 * filter is running) you don't need to call this, becuase the config is fetched
1048 * for you automatically. You only need this, for example, when you are getting
1049 * the config so you can show the user an editing from.
1051 * @param string $filter The filter name, for example 'tex'.
1052 * @param integer $contextid The ID of the context to get the local config for.
1053 * @return array of name => value pairs.
1055 function filter_get_local_config($filter, $contextid) {
1057 return $DB->get_records_menu('filter_config', array('filter' => $filter, 'contextid' => $contextid), '', 'name,value');
1061 * This function is for use by backup. Gets all the filter information specific
1064 * @param int $contextid
1065 * @return array Array with two elements. The first element is an array of objects with
1066 * fields filter and active. These come from the filter_active table. The
1067 * second element is an array of objects with fields filter, name and value
1068 * from the filter_config table.
1070 function filter_get_all_local_settings($contextid) {
1073 $DB->get_records('filter_active', array('contextid' => $contextid), 'filter', 'filter,active'),
1074 $DB->get_records('filter_config', array('contextid' => $contextid), 'filter,name', 'filter,name,value'),
1079 * Get the list of active filters, in the order that they should be used
1080 * for a particular context, along with any local configuration variables.
1082 * @param context $context a context
1083 * @return array an array where the keys are the filter names, for example
1084 * 'tex' and the values are any local
1085 * configuration for that filter, as an array of name => value pairs
1086 * from the filter_config table. In a lot of cases, this will be an
1087 * empty array. So, an example return value for this function might be
1088 * array(tex' => array())
1090 function filter_get_active_in_context($context) {
1091 global $DB, $FILTERLIB_PRIVATE;
1093 if (!isset($FILTERLIB_PRIVATE)) {
1094 $FILTERLIB_PRIVATE = new stdClass();
1097 // Use cache (this is a within-request cache only) if available. See
1098 // function filter_preload_activities.
1099 if (isset($FILTERLIB_PRIVATE->active
) &&
1100 array_key_exists($context->id
, $FILTERLIB_PRIVATE->active
)) {
1101 return $FILTERLIB_PRIVATE->active
[$context->id
];
1104 $contextids = str_replace('/', ',', trim($context->path
, '/'));
1106 // The following SQL is tricky. It is explained on
1107 // http://docs.moodle.org/dev/Filter_enable/disable_by_context.
1108 $sql = "SELECT active.filter, fc.name, fc.value
1109 FROM (SELECT f.filter, MAX(f.sortorder) AS sortorder
1110 FROM {filter_active} f
1111 JOIN {context} ctx ON f.contextid = ctx.id
1112 WHERE ctx.id IN ($contextids)
1114 HAVING MAX(f.active * ctx.depth) > -MIN(f.active * ctx.depth)
1116 LEFT JOIN {filter_config} fc ON fc.filter = active.filter AND fc.contextid = $context->id
1117 ORDER BY active.sortorder";
1118 $rs = $DB->get_recordset_sql($sql);
1120 // Massage the data into the specified format to return.
1122 foreach ($rs as $row) {
1123 if (!isset($filters[$row->filter
])) {
1124 $filters[$row->filter
] = array();
1126 if (!is_null($row->name
)) {
1127 $filters[$row->filter
][$row->name
] = $row->value
;
1137 * Preloads the list of active filters for all activities (modules) on the course
1138 * using two database queries.
1140 * @param course_modinfo $modinfo Course object from get_fast_modinfo
1142 function filter_preload_activities(course_modinfo
$modinfo) {
1143 global $DB, $FILTERLIB_PRIVATE;
1145 if (!isset($FILTERLIB_PRIVATE)) {
1146 $FILTERLIB_PRIVATE = new stdClass();
1149 // Don't repeat preload.
1150 if (!isset($FILTERLIB_PRIVATE->preloaded
)) {
1151 $FILTERLIB_PRIVATE->preloaded
= array();
1153 if (!empty($FILTERLIB_PRIVATE->preloaded
[$modinfo->get_course_id()])) {
1156 $FILTERLIB_PRIVATE->preloaded
[$modinfo->get_course_id()] = true;
1158 // Get contexts for all CMs.
1159 $cmcontexts = array();
1160 $cmcontextids = array();
1161 foreach ($modinfo->get_cms() as $cm) {
1162 $modulecontext = context_module
::instance($cm->id
);
1163 $cmcontextids[] = $modulecontext->id
;
1164 $cmcontexts[] = $modulecontext;
1167 // Get course context and all other parents.
1168 $coursecontext = context_course
::instance($modinfo->get_course_id());
1169 $parentcontextids = explode('/', substr($coursecontext->path
, 1));
1170 $allcontextids = array_merge($cmcontextids, $parentcontextids);
1172 // Get all filter_active rows relating to all these contexts.
1173 list ($sql, $params) = $DB->get_in_or_equal($allcontextids);
1174 $filteractives = $DB->get_records_select('filter_active', "contextid $sql", $params, 'sortorder');
1176 // Get all filter_config only for the cm contexts.
1177 list ($sql, $params) = $DB->get_in_or_equal($cmcontextids);
1178 $filterconfigs = $DB->get_records_select('filter_config', "contextid $sql", $params);
1180 // Note: I was a bit surprised that filter_config only works for the
1181 // most specific context (i.e. it does not need to be checked for course
1182 // context if we only care about CMs) however basede on code in
1183 // filter_get_active_in_context, this does seem to be correct.
1185 // Build course default active list. Initially this will be an array of
1186 // filter name => active score (where an active score >0 means it's active).
1187 $courseactive = array();
1189 // Also build list of filter_active rows below course level, by contextid.
1190 $remainingactives = array();
1192 // Array lists filters that are banned at top level.
1195 // Add any active filters in parent contexts to the array.
1196 foreach ($filteractives as $row) {
1197 $depth = array_search($row->contextid
, $parentcontextids);
1198 if ($depth !== false) {
1200 if (!array_key_exists($row->filter
, $courseactive)) {
1201 $courseactive[$row->filter
] = 0;
1203 // This maths copes with reading rows in any order. Turning on/off
1204 // at site level counts 1, at next level down 4, at next level 9,
1205 // then 16, etc. This means the deepest level always wins, except
1206 // against the -9999 at top level.
1207 $courseactive[$row->filter
] +
=
1208 ($depth +
1) * ($depth +
1) * $row->active
;
1210 if ($row->active
== TEXTFILTER_DISABLED
) {
1211 $banned[$row->filter
] = true;
1214 // Build list of other rows indexed by contextid.
1215 if (!array_key_exists($row->contextid
, $remainingactives)) {
1216 $remainingactives[$row->contextid
] = array();
1218 $remainingactives[$row->contextid
][] = $row;
1222 // Chuck away the ones that aren't active.
1223 foreach ($courseactive as $filter => $score) {
1225 unset($courseactive[$filter]);
1227 $courseactive[$filter] = array();
1231 // Loop through the contexts to reconstruct filter_active lists for each
1232 // cm on the course.
1233 if (!isset($FILTERLIB_PRIVATE->active
)) {
1234 $FILTERLIB_PRIVATE->active
= array();
1236 foreach ($cmcontextids as $contextid) {
1237 // Copy course list.
1238 $FILTERLIB_PRIVATE->active
[$contextid] = $courseactive;
1240 // Are there any changes to the active list?
1241 if (array_key_exists($contextid, $remainingactives)) {
1242 foreach ($remainingactives[$contextid] as $row) {
1243 if ($row->active
> 0 && empty($banned[$row->filter
])) {
1244 // If it's marked active for specific context, add entry
1245 // (doesn't matter if one exists already).
1246 $FILTERLIB_PRIVATE->active
[$contextid][$row->filter
] = array();
1248 // If it's marked inactive, remove entry (doesn't matter
1249 // if it doesn't exist).
1250 unset($FILTERLIB_PRIVATE->active
[$contextid][$row->filter
]);
1256 // Process all config rows to add config data to these entries.
1257 foreach ($filterconfigs as $row) {
1258 if (isset($FILTERLIB_PRIVATE->active
[$row->contextid
][$row->filter
])) {
1259 $FILTERLIB_PRIVATE->active
[$row->contextid
][$row->filter
][$row->name
] = $row->value
;
1265 * List all of the filters that are available in this context, and what the
1266 * local and inherited states of that filter are.
1268 * @param context $context a context that is not the system context.
1269 * @return array an array with filter names, for example 'tex'
1270 * as keys. and and the values are objects with fields:
1271 * ->filter filter name, same as the key.
1272 * ->localstate TEXTFILTER_ON/OFF/INHERIT
1273 * ->inheritedstate TEXTFILTER_ON/OFF - the state that will be used if localstate is set to TEXTFILTER_INHERIT.
1275 function filter_get_available_in_context($context) {
1278 // The complex logic is working out the active state in the parent context,
1279 // so strip the current context from the list.
1280 $contextids = explode('/', trim($context->path
, '/'));
1281 array_pop($contextids);
1282 $contextids = implode(',', $contextids);
1283 if (empty($contextids)) {
1284 throw new coding_exception('filter_get_available_in_context cannot be called with the system context.');
1287 // The following SQL is tricky, in the same way at the SQL in filter_get_active_in_context.
1288 $sql = "SELECT parent_states.filter,
1289 CASE WHEN fa.active IS NULL THEN " . TEXTFILTER_INHERIT
. "
1290 ELSE fa.active END AS localstate,
1291 parent_states.inheritedstate
1292 FROM (SELECT f.filter, MAX(f.sortorder) AS sortorder,
1293 CASE WHEN MAX(f.active * ctx.depth) > -MIN(f.active * ctx.depth) THEN " . TEXTFILTER_ON
. "
1294 ELSE " . TEXTFILTER_OFF
. " END AS inheritedstate
1295 FROM {filter_active} f
1296 JOIN {context} ctx ON f.contextid = ctx.id
1297 WHERE ctx.id IN ($contextids)
1299 HAVING MIN(f.active) > " . TEXTFILTER_DISABLED
. "
1301 LEFT JOIN {filter_active} fa ON fa.filter = parent_states.filter AND fa.contextid = $context->id
1302 ORDER BY parent_states.sortorder";
1303 return $DB->get_records_sql($sql);
1307 * This function is for use by the filter administration page.
1309 * @return array 'filtername' => object with fields 'filter' (=filtername), 'active' and 'sortorder'
1311 function filter_get_global_states() {
1313 $context = context_system
::instance();
1314 return $DB->get_records('filter_active', array('contextid' => $context->id
), 'sortorder', 'filter,active,sortorder');
1318 * Delete all the data in the database relating to a filter, prior to deleting it.
1320 * @param string $filter The filter name, for example 'tex'.
1322 function filter_delete_all_for_filter($filter) {
1325 unset_all_config_for_plugin('filter_' . $filter);
1326 $DB->delete_records('filter_active', array('filter' => $filter));
1327 $DB->delete_records('filter_config', array('filter' => $filter));
1331 * Delete all the data in the database relating to a context, used when contexts are deleted.
1333 * @param integer $contextid The id of the context being deleted.
1335 function filter_delete_all_for_context($contextid) {
1337 $DB->delete_records('filter_active', array('contextid' => $contextid));
1338 $DB->delete_records('filter_config', array('contextid' => $contextid));
1342 * Does this filter have a global settings page in the admin tree?
1343 * (The settings page for a filter must be called, for example, filtersettingfiltertex.)
1345 * @param string $filter The filter name, for example 'tex'.
1346 * @return boolean Whether there should be a 'Settings' link on the config page.
1348 function filter_has_global_settings($filter) {
1350 $settingspath = $CFG->dirroot
. '/filter/' . $filter . '/settings.php';
1351 if (is_readable($settingspath)) {
1354 $settingspath = $CFG->dirroot
. '/filter/' . $filter . '/filtersettings.php';
1355 return is_readable($settingspath);
1359 * Does this filter have local (per-context) settings?
1361 * @param string $filter The filter name, for example 'tex'.
1362 * @return boolean Whether there should be a 'Settings' link on the manage filters in context page.
1364 function filter_has_local_settings($filter) {
1366 $settingspath = $CFG->dirroot
. '/filter/' . $filter . '/filterlocalsettings.php';
1367 return is_readable($settingspath);
1371 * Certain types of context (block and user) may not have local filter settings.
1372 * the function checks a context to see whether it may have local config.
1374 * @param object $context a context.
1375 * @return boolean whether this context may have local filter settings.
1377 function filter_context_may_have_filter_settings($context) {
1378 return $context->contextlevel
!= CONTEXT_BLOCK
&& $context->contextlevel
!= CONTEXT_USER
;
1382 * Process phrases intelligently found within a HTML text (such as adding links).
1384 * @param string $text the text that we are filtering
1385 * @param filterobject[] $linkarray an array of filterobjects
1386 * @param array $ignoretagsopen an array of opening tags that we should ignore while filtering
1387 * @param array $ignoretagsclose an array of corresponding closing tags
1388 * @param bool $overridedefaultignore True to only use tags provided by arguments
1389 * @param bool $linkarrayalreadyprepared True to say that filter_prepare_phrases_for_filtering
1390 * has already been called for $linkarray. Default false.
1393 function filter_phrases($text, $linkarray, $ignoretagsopen = null, $ignoretagsclose = null,
1394 $overridedefaultignore = false, $linkarrayalreadyprepared = false) {
1398 // Used if $CFG->filtermatchoneperpage is on. Array with keys being the workregexp
1399 // for things that have already been matched on this page.
1400 static $usedphrases = [];
1402 $ignoretags = array(); // To store all the enclosing tags to be completely ignored.
1403 $tags = array(); // To store all the simple tags to be ignored.
1405 if (!$linkarrayalreadyprepared) {
1406 $linkarray = filter_prepare_phrases_for_filtering($linkarray);
1409 if (!$overridedefaultignore) {
1410 // A list of open/close tags that we should not replace within.
1411 // Extended to include <script>, <textarea>, <select> and <a> tags.
1412 // Regular expression allows tags with or without attributes.
1413 $filterignoretagsopen = array('<head>', '<nolink>', '<span(\s[^>]*?)?class="nolink"(\s[^>]*?)?>',
1414 '<script(\s[^>]*?)?>', '<textarea(\s[^>]*?)?>',
1415 '<select(\s[^>]*?)?>', '<a(\s[^>]*?)?>');
1416 $filterignoretagsclose = array('</head>', '</nolink>', '</span>',
1417 '</script>', '</textarea>', '</select>', '</a>');
1419 // Set an empty default list.
1420 $filterignoretagsopen = array();
1421 $filterignoretagsclose = array();
1424 // Add the user defined ignore tags to the default list.
1425 if ( is_array($ignoretagsopen) ) {
1426 foreach ($ignoretagsopen as $open) {
1427 $filterignoretagsopen[] = $open;
1429 foreach ($ignoretagsclose as $close) {
1430 $filterignoretagsclose[] = $close;
1434 // Double up some magic chars to avoid "accidental matches".
1435 $text = preg_replace('/([#*%])/', '\1\1', $text);
1437 // Remove everything enclosed by the ignore tags from $text.
1438 filter_save_ignore_tags($text, $filterignoretagsopen, $filterignoretagsclose, $ignoretags);
1440 // Remove tags from $text.
1441 filter_save_tags($text, $tags);
1443 // Prepare the limit for preg_match calls.
1444 if (!empty($CFG->filtermatchonepertext
) ||
!empty($CFG->filtermatchoneperpage
)) {
1445 $pregreplacelimit = 1;
1447 $pregreplacelimit = -1; // No limit.
1450 // Time to cycle through each phrase to be linked.
1451 foreach ($linkarray as $key => $linkobject) {
1452 if ($linkobject->workregexp
=== null) {
1453 // This is the case if, when preparing the phrases for filtering,
1454 // we decided that this was not a suitable phrase to match.
1458 // If $CFG->filtermatchoneperpage, avoid previously matched linked phrases.
1459 if (!empty($CFG->filtermatchoneperpage
) && isset($usedphrases[$linkobject->workregexp
])) {
1463 // Do our highlighting.
1464 $resulttext = preg_replace_callback($linkobject->workregexp
,
1465 function ($matches) use ($linkobject) {
1466 if ($linkobject->workreplacementphrase
=== null) {
1467 filter_prepare_phrase_for_replacement($linkobject);
1470 return str_replace('$1', $matches[1], $linkobject->workreplacementphrase
);
1471 }, $text, $pregreplacelimit);
1473 // If the text has changed we have to look for links again.
1474 if ($resulttext != $text) {
1475 $text = $resulttext;
1476 // Remove everything enclosed by the ignore tags from $text.
1477 filter_save_ignore_tags($text, $filterignoretagsopen, $filterignoretagsclose, $ignoretags);
1478 // Remove tags from $text.
1479 filter_save_tags($text, $tags);
1480 // If $CFG->filtermatchoneperpage, save linked phrases to request.
1481 if (!empty($CFG->filtermatchoneperpage
)) {
1482 $usedphrases[$linkobject->workregexp
] = 1;
1487 // Rebuild the text with all the excluded areas.
1488 if (!empty($tags)) {
1489 $text = str_replace(array_keys($tags), $tags, $text);
1492 if (!empty($ignoretags)) {
1493 $ignoretags = array_reverse($ignoretags); // Reversed so "progressive" str_replace() will solve some nesting problems.
1494 $text = str_replace(array_keys($ignoretags), $ignoretags, $text);
1497 // Remove the protective doubleups.
1498 $text = preg_replace('/([#*%])(\1)/', '\1', $text);
1500 // Add missing javascript for popus.
1501 $text = filter_add_javascript($text);
1507 * Prepare a list of link for processing with {@link filter_phrases()}.
1509 * @param filterobject[] $linkarray the links that will be passed to filter_phrases().
1510 * @return filterobject[] the updated list of links with necessary pre-processing done.
1512 function filter_prepare_phrases_for_filtering(array $linkarray) {
1513 // Time to cycle through each phrase to be linked.
1514 foreach ($linkarray as $linkobject) {
1516 // Set some defaults if certain properties are missing.
1517 // Properties may be missing if the filterobject class has not been used to construct the object.
1518 if (empty($linkobject->phrase
)) {
1522 // Avoid integers < 1000 to be linked. See bug 1446.
1523 $intcurrent = intval($linkobject->phrase
);
1524 if (!empty($intcurrent) && strval($intcurrent) == $linkobject->phrase
&& $intcurrent < 1000) {
1528 // Strip tags out of the phrase.
1529 $linkobject->workregexp
= strip_tags($linkobject->phrase
);
1531 if (!$linkobject->casesensitive
) {
1532 $linkobject->workregexp
= core_text
::strtolower($linkobject->workregexp
);
1535 // Double up chars that might cause a false match -- the duplicates will
1536 // be cleared up before returning to the user.
1537 $linkobject->workregexp
= preg_replace('/([#*%])/', '\1\1', $linkobject->workregexp
);
1539 // Quote any regular expression characters and the delimiter in the work phrase to be searched.
1540 $linkobject->workregexp
= preg_quote($linkobject->workregexp
, '/');
1542 // If we ony want to match entire words then add \b assertions. However, only
1543 // do this if the first or last thing in the phrase to match is a word character.
1544 if ($linkobject->fullmatch
) {
1545 if (preg_match('~^\w~', $linkobject->workregexp
)) {
1546 $linkobject->workregexp
= '\b' . $linkobject->workregexp
;
1548 if (preg_match('~\w$~', $linkobject->workregexp
)) {
1549 $linkobject->workregexp
= $linkobject->workregexp
. '\b';
1553 $linkobject->workregexp
= '/(' . $linkobject->workregexp
. ')/s';
1555 if (!$linkobject->casesensitive
) {
1556 $linkobject->workregexp
.= 'iu';
1564 * Fill in the remaining ->work... fields, that would be needed to replace the phrase.
1566 * @param filterobject $linkobject the link object on which to set additional fields.
1568 function filter_prepare_phrase_for_replacement(filterobject
$linkobject) {
1569 if ($linkobject->replacementcallback
!== null) {
1570 list($linkobject->hreftagbegin
, $linkobject->hreftagend
, $linkobject->replacementphrase
) =
1571 call_user_func_array($linkobject->replacementcallback
, $linkobject->replacementcallbackdata
);
1574 if (!isset($linkobject->hreftagbegin
) or !isset($linkobject->hreftagend
)) {
1575 $linkobject->hreftagbegin
= '<span class="highlight"';
1576 $linkobject->hreftagend
= '</span>';
1579 // Double up chars to protect true duplicates
1580 // be cleared up before returning to the user.
1581 $hreftagbeginmangled = preg_replace('/([#*%])/', '\1\1', $linkobject->hreftagbegin
);
1583 // Set the replacement phrase properly.
1584 if ($linkobject->replacementphrase
) { // We have specified a replacement phrase.
1585 $linkobject->workreplacementphrase
= strip_tags($linkobject->replacementphrase
);
1586 } else { // The replacement is the original phrase as matched below.
1587 $linkobject->workreplacementphrase
= '$1';
1590 $linkobject->workreplacementphrase
= $hreftagbeginmangled .
1591 $linkobject->workreplacementphrase
. $linkobject->hreftagend
;
1595 * Remove duplicate from a list of {@link filterobject}.
1597 * @param filterobject[] $linkarray a list of filterobject.
1598 * @return filterobject[] the same list, but with dupicates removed.
1600 function filter_remove_duplicates($linkarray) {
1602 $concepts = array(); // Keep a record of concepts as we cycle through.
1603 $lconcepts = array(); // A lower case version for case insensitive.
1605 $cleanlinks = array();
1607 foreach ($linkarray as $key => $filterobject) {
1608 if ($filterobject->casesensitive
) {
1609 $exists = in_array($filterobject->phrase
, $concepts);
1611 $exists = in_array(core_text
::strtolower($filterobject->phrase
), $lconcepts);
1615 $cleanlinks[] = $filterobject;
1616 $concepts[] = $filterobject->phrase
;
1617 $lconcepts[] = core_text
::strtolower($filterobject->phrase
);
1625 * Extract open/lose tags and their contents to avoid being processed by filters.
1626 * Useful to extract pieces of code like <a>...</a> tags. It returns the text
1627 * converted with some <#xTEXTFILTER_EXCL_SEPARATORx#> codes replacing the extracted text. Such extracted
1628 * texts are returned in the ignoretags array (as values), with codes as keys.
1630 * @param string $text the text that we are filtering (in/out)
1631 * @param array $filterignoretagsopen an array of open tags to start searching
1632 * @param array $filterignoretagsclose an array of close tags to end searching
1633 * @param array $ignoretags an array of saved strings useful to rebuild the original text (in/out)
1635 function filter_save_ignore_tags(&$text, $filterignoretagsopen, $filterignoretagsclose, &$ignoretags) {
1637 // Remove everything enclosed by the ignore tags from $text.
1638 foreach ($filterignoretagsopen as $ikey => $opentag) {
1639 $closetag = $filterignoretagsclose[$ikey];
1640 // Form regular expression.
1641 $opentag = str_replace('/', '\/', $opentag); // Delimit forward slashes.
1642 $closetag = str_replace('/', '\/', $closetag); // Delimit forward slashes.
1643 $pregexp = '/'.$opentag.'(.*?)'.$closetag.'/is';
1645 preg_match_all($pregexp, $text, $listofignores);
1646 foreach (array_unique($listofignores[0]) as $key => $value) {
1647 $prefix = (string) (count($ignoretags) +
1);
1648 $ignoretags['<#'.$prefix.TEXTFILTER_EXCL_SEPARATOR
.$key.'#>'] = $value;
1650 if (!empty($ignoretags)) {
1651 $text = str_replace($ignoretags, array_keys($ignoretags), $text);
1657 * Extract tags (any text enclosed by < and > to avoid being processed by filters.
1658 * It returns the text converted with some <%xTEXTFILTER_EXCL_SEPARATORx%> codes replacing the extracted text. Such extracted
1659 * texts are returned in the tags array (as values), with codes as keys.
1661 * @param string $text the text that we are filtering (in/out)
1662 * @param array $tags an array of saved strings useful to rebuild the original text (in/out)
1664 function filter_save_tags(&$text, &$tags) {
1666 preg_match_all('/<([^#%*].*?)>/is', $text, $listofnewtags);
1667 foreach (array_unique($listofnewtags[0]) as $ntkey => $value) {
1668 $prefix = (string)(count($tags) +
1);
1669 $tags['<%'.$prefix.TEXTFILTER_EXCL_SEPARATOR
.$ntkey.'%>'] = $value;
1671 if (!empty($tags)) {
1672 $text = str_replace($tags, array_keys($tags), $text);
1677 * Add missing openpopup javascript to HTML files.
1679 * @param string $text
1682 function filter_add_javascript($text) {
1685 if (stripos($text, '</html>') === false) {
1686 return $text; // This is not a html file.
1688 if (strpos($text, 'onclick="return openpopup') === false) {
1689 return $text; // No popup - no need to add javascript.
1692 <script type=\"text/javascript\">
1694 function openpopup(url,name,options,fullscreen) {
1695 fullurl = \"".$CFG->wwwroot
."\" + url;
1696 windowobj = window.open(fullurl,name,options);
1698 windowobj.moveTo(0,0);
1699 windowobj.resizeTo(screen.availWidth,screen.availHeight);
1706 if (stripos($text, '</head>') !== false) {
1707 // Try to add it into the head element.
1708 $text = str_ireplace('</head>', $js.'</head>', $text);
1712 // Last chance - try adding head element.
1713 return preg_replace("/<html.*?>/is", "\\0<head>".$js.'</head>', $text);