MDL-65087 message: add aria-label to search, settings and starred
[moodle.git] / lib / filterlib.php
blobf210a257de50d00d920ba4cc5f82813ddc87cb48
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.
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/>.
17 /**
18 * Library functions for managing text filter plugins.
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
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);
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
41 define('TEXTFILTER_EXCL_SEPARATOR', '-%-');
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.
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 {
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.
59 protected $textfilters = array();
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.
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;
73 /**
74 * Constructor. Protected. Use {@link instance()} instead.
76 protected function __construct() {
77 $this->stringfilternames = filter_get_string_filters();
80 /**
81 * Factory method. Use this to get the filter manager.
83 * @return filter_manager the singleton instance.
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();
94 return self::$singletoninstance;
97 /**
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)) {
128 continue;
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) {
147 global $CFG;
148 $path = $CFG->dirroot .'/filter/'. $filtername .'/filter.php';
149 if (!is_readable($path)) {
150 return null;
152 include_once($path);
154 $filterclassname = 'filter_' . $filtername;
155 if (class_exists($filterclassname)) {
156 return new $filterclassname($context, $localconfig);
159 return null;
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 foreach ($filterchain as $filtername => $filter) {
173 if ($skipfilters !== null && in_array($filtername, $skipfilters)) {
174 continue;
176 $text = $filter->filter($text, $options);
178 return $text;
182 * Get all the filters that apply to a given context for calls to format_text.
184 * @param context $context
185 * @return moodle_text_filter[] A text filter
187 protected function get_text_filters($context) {
188 if (!isset($this->textfilters[$context->id])) {
189 $this->load_filters($context);
191 return $this->textfilters[$context->id];
195 * Get all the filters that apply to a given context for calls to format_string.
197 * @param context $context the context.
198 * @return moodle_text_filter[] A text filter
200 protected function get_string_filters($context) {
201 if (!isset($this->stringfilters[$context->id])) {
202 $this->load_filters($context);
204 return $this->stringfilters[$context->id];
208 * Filter some text
210 * @param string $text The text to filter
211 * @param context $context the context.
212 * @param array $options options passed to the filters
213 * @param array $skipfilters of filter names. Any filters that should not be applied to this text.
214 * @return string resulting text
216 public function filter_text($text, $context, array $options = array(),
217 array $skipfilters = null) {
218 $text = $this->apply_filter_chain($text, $this->get_text_filters($context), $options, $skipfilters);
219 // Remove <nolink> tags for XHTML compatibility.
220 $text = str_replace(array('<nolink>', '</nolink>'), '', $text);
221 return $text;
225 * Filter a piece of string
227 * @param string $string The text to filter
228 * @param context $context the context.
229 * @return string resulting string
231 public function filter_string($string, $context) {
232 return $this->apply_filter_chain($string, $this->get_string_filters($context));
236 * @deprecated Since Moodle 3.0 MDL-50491. This was used by the old text filtering system, but no more.
238 public function text_filtering_hash() {
239 throw new coding_exception('filter_manager::text_filtering_hash() can not be used any more');
243 * Setup page with filters requirements and other prepare stuff.
245 * This method is used by {@see format_text()} and {@see format_string()}
246 * in order to allow filters to setup any page requirement (js, css...)
247 * or perform any action needed to get them prepared before filtering itself
248 * happens by calling to each every active setup() method.
250 * Note it's executed for each piece of text filtered, so filter implementations
251 * are responsible of controlling the cardinality of the executions that may
252 * be different depending of the stuff to prepare.
254 * @param moodle_page $page the page we are going to add requirements to.
255 * @param context $context the context which contents are going to be filtered.
256 * @since Moodle 2.3
258 public function setup_page_for_filters($page, $context) {
259 $filters = $this->get_text_filters($context);
260 foreach ($filters as $filter) {
261 $filter->setup($page, $context);
266 * Setup the page for globally available filters.
268 * This helps setting up the page for filters which may be applied to
269 * the page, even if they do not belong to the current context, or are
270 * not yet visible because the content is lazily added (ajax). This method
271 * always uses to the system context which determines the globally
272 * available filters.
274 * This should only ever be called once per request.
276 * @param moodle_page $page The page.
277 * @since Moodle 3.2
279 public function setup_page_for_globally_available_filters($page) {
280 $context = context_system::instance();
281 $filterdata = filter_get_globally_enabled_filters_with_config();
282 foreach ($filterdata as $name => $config) {
283 if (isset($this->textfilters[$context->id][$name])) {
284 $filter = $this->textfilters[$context->id][$name];
285 } else {
286 $filter = $this->make_filter_object($name, $context, $config);
287 if (is_null($filter)) {
288 continue;
291 $filter->setup($page, $context);
298 * Filter manager subclass that does nothing. Having this simplifies the logic
299 * of format_text, etc.
301 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
302 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
304 class null_filter_manager {
306 * As for the equivalent {@link filter_manager} method.
308 * @param string $text The text to filter
309 * @param context $context not used.
310 * @param array $options not used
311 * @param array $skipfilters not used
312 * @return string resulting text.
314 public function filter_text($text, $context, array $options = array(),
315 array $skipfilters = null) {
316 return $text;
320 * As for the equivalent {@link filter_manager} method.
322 * @param string $string The text to filter
323 * @param context $context not used.
324 * @return string resulting string
326 public function filter_string($string, $context) {
327 return $string;
331 * As for the equivalent {@link filter_manager} method.
333 * @deprecated Since Moodle 3.0 MDL-50491.
335 public function text_filtering_hash() {
336 throw new coding_exception('filter_manager::text_filtering_hash() can not be used any more');
342 * Filter manager subclass that tracks how much work it does.
344 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
345 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
347 class performance_measuring_filter_manager extends filter_manager {
348 /** @var int number of filter objects created. */
349 protected $filterscreated = 0;
351 /** @var int number of calls to filter_text. */
352 protected $textsfiltered = 0;
354 /** @var int number of calls to filter_string. */
355 protected $stringsfiltered = 0;
357 protected function unload_all_filters() {
358 parent::unload_all_filters();
359 $this->filterscreated = 0;
360 $this->textsfiltered = 0;
361 $this->stringsfiltered = 0;
364 protected function make_filter_object($filtername, $context, $localconfig) {
365 $this->filterscreated++;
366 return parent::make_filter_object($filtername, $context, $localconfig);
369 public function filter_text($text, $context, array $options = array(),
370 array $skipfilters = null) {
371 $this->textsfiltered++;
372 return parent::filter_text($text, $context, $options, $skipfilters);
375 public function filter_string($string, $context) {
376 $this->stringsfiltered++;
377 return parent::filter_string($string, $context);
381 * Return performance information, in the form required by {@link get_performance_info()}.
382 * @return array the performance info.
384 public function get_performance_summary() {
385 return array(array(
386 'contextswithfilters' => count($this->textfilters),
387 'filterscreated' => $this->filterscreated,
388 'textsfiltered' => $this->textsfiltered,
389 'stringsfiltered' => $this->stringsfiltered,
390 ), array(
391 'contextswithfilters' => 'Contexts for which filters were loaded',
392 'filterscreated' => 'Filters created',
393 'textsfiltered' => 'Pieces of content filtered',
394 'stringsfiltered' => 'Strings filtered',
401 * Base class for text filters. You just need to override this class and
402 * implement the filter method.
404 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
405 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
407 abstract class moodle_text_filter {
408 /** @var context The context we are in. */
409 protected $context;
411 /** @var array Any local configuration for this filter in this context. */
412 protected $localconfig;
415 * Set any context-specific configuration for this filter.
417 * @param context $context The current context.
418 * @param array $localconfig Any context-specific configuration for this filter.
420 public function __construct($context, array $localconfig) {
421 $this->context = $context;
422 $this->localconfig = $localconfig;
426 * @deprecated Since Moodle 3.0 MDL-50491. This was used by the old text filtering system, but no more.
428 public function hash() {
429 throw new coding_exception('moodle_text_filter::hash() can not be used any more');
433 * Setup page with filter requirements and other prepare stuff.
435 * Override this method if the filter needs to setup page
436 * requirements or needs other stuff to be executed.
438 * Note this method is invoked from {@see setup_page_for_filters()}
439 * for each piece of text being filtered, so it is responsible
440 * for controlling its own execution cardinality.
442 * @param moodle_page $page the page we are going to add requirements to.
443 * @param context $context the context which contents are going to be filtered.
444 * @since Moodle 2.3
446 public function setup($page, $context) {
447 // Override me, if needed.
451 * Override this function to actually implement the filtering.
453 * @param string $text some HTML content to process.
454 * @param array $options options passed to the filters
455 * @return string the HTML content after the filtering has been applied.
457 public abstract function filter($text, array $options = array());
462 * This is just a little object to define a phrase and some instructions
463 * for how to process it. Filters can create an array of these to pass
464 * to the @{link filter_phrases()} function below.
466 * Note that although the fields here are public, you almost certainly should
467 * never use that. All that is supported is contructing new instances of this
468 * class, and then passing an array of them to filter_phrases.
470 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
471 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
473 class filterobject {
474 /** @var string this is the phrase that should be matched. */
475 public $phrase;
477 /** @var bool whether to match complete words. If true, 'T' won't be matched in 'Tim'. */
478 public $fullmatch;
480 /** @var bool whether the match needs to be case sensitive. */
481 public $casesensitive;
483 /** @var string HTML to insert before any match. */
484 public $hreftagbegin;
485 /** @var string HTML to insert after any match. */
486 public $hreftagend;
488 /** @var null|string replacement text to go inside begin and end. If not set,
489 * the body of the replacement will be the original phrase.
491 public $replacementphrase;
493 /** @var null|string once initialised, holds the regexp for matching this phrase. */
494 public $workregexp = null;
496 /** @var null|string once initialised, holds the mangled HTML to replace the regexp with. */
497 public $workreplacementphrase = null;
500 * Constructor.
502 * @param string $phrase this is the phrase that should be matched.
503 * @param string $hreftagbegin HTML to insert before any match. Default '<span class="highlight">'.
504 * @param string $hreftagend HTML to insert after any match. Default '</span>'.
505 * @param bool $casesensitive whether the match needs to be case sensitive
506 * @param bool $fullmatch whether to match complete words. If true, 'T' won't be matched in 'Tim'.
507 * @param mixed $replacementphrase replacement text to go inside begin and end. If not set,
508 * the body of the replacement will be the original phrase.
509 * @param callback $replacementcallback if set, then this will be called just before
510 * $hreftagbegin, $hreftagend and $replacementphrase are needed, so they can be computed only if required.
511 * The call made is
512 * list($linkobject->hreftagbegin, $linkobject->hreftagend, $linkobject->replacementphrase) =
513 * call_user_func_array($linkobject->replacementcallback, $linkobject->replacementcallbackdata);
514 * so the return should be an array [$hreftagbegin, $hreftagend, $replacementphrase], the last of which may be null.
515 * @param array $replacementcallbackdata data to be passed to $replacementcallback (optional).
517 public function __construct($phrase, $hreftagbegin = '<span class="highlight">',
518 $hreftagend = '</span>',
519 $casesensitive = false,
520 $fullmatch = false,
521 $replacementphrase = null,
522 $replacementcallback = null,
523 array $replacementcallbackdata = null) {
525 $this->phrase = $phrase;
526 $this->hreftagbegin = $hreftagbegin;
527 $this->hreftagend = $hreftagend;
528 $this->casesensitive = !empty($casesensitive);
529 $this->fullmatch = !empty($fullmatch);
530 $this->replacementphrase = $replacementphrase;
531 $this->replacementcallback = $replacementcallback;
532 $this->replacementcallbackdata = $replacementcallbackdata;
537 * Look up the name of this filter
539 * @param string $filter the filter name
540 * @return string the human-readable name for this filter.
542 function filter_get_name($filter) {
543 if (strpos($filter, 'filter/') === 0) {
544 debugging("Old '$filter'' parameter used in filter_get_name()");
545 $filter = substr($filter, 7);
546 } else if (strpos($filter, '/') !== false) {
547 throw new coding_exception('Unknown filter type ' . $filter);
550 if (get_string_manager()->string_exists('filtername', 'filter_' . $filter)) {
551 return get_string('filtername', 'filter_' . $filter);
552 } else {
553 return $filter;
558 * Get the names of all the filters installed in this Moodle.
560 * @return array path => filter name from the appropriate lang file. e.g.
561 * array('tex' => 'TeX Notation');
562 * sorted in alphabetical order of name.
564 function filter_get_all_installed() {
565 $filternames = array();
566 foreach (core_component::get_plugin_list('filter') as $filter => $fulldir) {
567 if (is_readable("$fulldir/filter.php")) {
568 $filternames[$filter] = filter_get_name($filter);
571 core_collator::asort($filternames);
572 return $filternames;
576 * Set the global activated state for a text filter.
578 * @param string $filtername The filter name, for example 'tex'.
579 * @param int $state One of the values TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_DISABLED.
580 * @param int $move -1 means up, 0 means the same, 1 means down
582 function filter_set_global_state($filtername, $state, $move = 0) {
583 global $DB;
585 // Check requested state is valid.
586 if (!in_array($state, array(TEXTFILTER_ON, TEXTFILTER_OFF, TEXTFILTER_DISABLED))) {
587 throw new coding_exception("Illegal option '$state' passed to filter_set_global_state. " .
588 "Must be one of TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_DISABLED.");
591 if ($move > 0) {
592 $move = 1;
593 } else if ($move < 0) {
594 $move = -1;
597 if (strpos($filtername, 'filter/') === 0) {
598 $filtername = substr($filtername, 7);
599 } else if (strpos($filtername, '/') !== false) {
600 throw new coding_exception("Invalid filter name '$filtername' used in filter_set_global_state()");
603 $transaction = $DB->start_delegated_transaction();
605 $syscontext = context_system::instance();
606 $filters = $DB->get_records('filter_active', array('contextid' => $syscontext->id), 'sortorder ASC');
608 $on = array();
609 $off = array();
611 foreach ($filters as $f) {
612 if ($f->active == TEXTFILTER_DISABLED) {
613 $off[$f->filter] = $f;
614 } else {
615 $on[$f->filter] = $f;
619 // Update the state or add new record.
620 if (isset($on[$filtername])) {
621 $filter = $on[$filtername];
622 if ($filter->active != $state) {
623 add_to_config_log('filter_active', $filter->active, $state, $filtername);
625 $filter->active = $state;
626 $DB->update_record('filter_active', $filter);
627 if ($filter->active == TEXTFILTER_DISABLED) {
628 unset($on[$filtername]);
629 $off = array($filter->filter => $filter) + $off;
634 } else if (isset($off[$filtername])) {
635 $filter = $off[$filtername];
636 if ($filter->active != $state) {
637 add_to_config_log('filter_active', $filter->active, $state, $filtername);
639 $filter->active = $state;
640 $DB->update_record('filter_active', $filter);
641 if ($filter->active != TEXTFILTER_DISABLED) {
642 unset($off[$filtername]);
643 $on[$filter->filter] = $filter;
647 } else {
648 add_to_config_log('filter_active', '', $state, $filtername);
650 $filter = new stdClass();
651 $filter->filter = $filtername;
652 $filter->contextid = $syscontext->id;
653 $filter->active = $state;
654 $filter->sortorder = 99999;
655 $filter->id = $DB->insert_record('filter_active', $filter);
657 $filters[$filter->id] = $filter;
658 if ($state == TEXTFILTER_DISABLED) {
659 $off[$filter->filter] = $filter;
660 } else {
661 $on[$filter->filter] = $filter;
665 // Move only active.
666 if ($move != 0 and isset($on[$filter->filter])) {
667 $i = 1;
668 foreach ($on as $f) {
669 $f->newsortorder = $i;
670 $i++;
673 $filter->newsortorder = $filter->newsortorder + $move;
675 foreach ($on as $f) {
676 if ($f->id == $filter->id) {
677 continue;
679 if ($f->newsortorder == $filter->newsortorder) {
680 if ($move == 1) {
681 $f->newsortorder = $f->newsortorder - 1;
682 } else {
683 $f->newsortorder = $f->newsortorder + 1;
688 core_collator::asort_objects_by_property($on, 'newsortorder', core_collator::SORT_NUMERIC);
691 // Inactive are sorted by filter name.
692 core_collator::asort_objects_by_property($off, 'filter', core_collator::SORT_NATURAL);
694 // Update records if necessary.
695 $i = 1;
696 foreach ($on as $f) {
697 if ($f->sortorder != $i) {
698 $DB->set_field('filter_active', 'sortorder', $i, array('id' => $f->id));
700 $i++;
702 foreach ($off as $f) {
703 if ($f->sortorder != $i) {
704 $DB->set_field('filter_active', 'sortorder', $i, array('id' => $f->id));
706 $i++;
709 $transaction->allow_commit();
713 * @param string $filtername The filter name, for example 'tex'.
714 * @return boolean is this filter allowed to be used on this site. That is, the
715 * admin has set the global 'active' setting to On, or Off, but available.
717 function filter_is_enabled($filtername) {
718 if (strpos($filtername, 'filter/') === 0) {
719 $filtername = substr($filtername, 7);
720 } else if (strpos($filtername, '/') !== false) {
721 throw new coding_exception("Invalid filter name '$filtername' used in filter_is_enabled()");
723 return array_key_exists($filtername, filter_get_globally_enabled());
727 * Return a list of all the filters that may be in use somewhere.
729 * @return array where the keys and values are both the filter name, like 'tex'.
731 function filter_get_globally_enabled() {
732 $cache = \cache::make_from_params(\cache_store::MODE_REQUEST, 'core_filter', 'global_filters');
733 $enabledfilters = $cache->get('enabled');
734 if ($enabledfilters !== false) {
735 return $enabledfilters;
738 $filters = filter_get_global_states();
739 $enabledfilters = array();
740 foreach ($filters as $filter => $filerinfo) {
741 if ($filerinfo->active != TEXTFILTER_DISABLED) {
742 $enabledfilters[$filter] = $filter;
746 $cache->set('enabled', $enabledfilters);
747 return $enabledfilters;
751 * Get the globally enabled filters.
753 * This returns the filters which could be used in any context. Essentially
754 * the filters which are not disabled for the entire site.
756 * @return array Keys are filter names, and values the config.
758 function filter_get_globally_enabled_filters_with_config() {
759 global $DB;
761 $sql = "SELECT f.filter, fc.name, fc.value
762 FROM {filter_active} f
763 LEFT JOIN {filter_config} fc
764 ON fc.filter = f.filter
765 AND fc.contextid = f.contextid
766 WHERE f.contextid = :contextid
767 AND f.active != :disabled
768 ORDER BY f.sortorder";
770 $rs = $DB->get_recordset_sql($sql, [
771 'contextid' => context_system::instance()->id,
772 'disabled' => TEXTFILTER_DISABLED
775 // Massage the data into the specified format to return.
776 $filters = array();
777 foreach ($rs as $row) {
778 if (!isset($filters[$row->filter])) {
779 $filters[$row->filter] = array();
781 if ($row->name !== null) {
782 $filters[$row->filter][$row->name] = $row->value;
785 $rs->close();
787 return $filters;
791 * Return the names of the filters that should also be applied to strings
792 * (when they are enabled).
794 * @return array where the keys and values are both the filter name, like 'tex'.
796 function filter_get_string_filters() {
797 global $CFG;
798 $stringfilters = array();
799 if (!empty($CFG->filterall) && !empty($CFG->stringfilters)) {
800 $stringfilters = explode(',', $CFG->stringfilters);
801 $stringfilters = array_combine($stringfilters, $stringfilters);
803 return $stringfilters;
807 * Sets whether a particular active filter should be applied to all strings by
808 * format_string, or just used by format_text.
810 * @param string $filter The filter name, for example 'tex'.
811 * @param boolean $applytostrings if true, this filter will apply to format_string
812 * and format_text, when it is enabled.
814 function filter_set_applies_to_strings($filter, $applytostrings) {
815 $stringfilters = filter_get_string_filters();
816 $prevfilters = $stringfilters;
817 $allfilters = core_component::get_plugin_list('filter');
819 if ($applytostrings) {
820 $stringfilters[$filter] = $filter;
821 } else {
822 unset($stringfilters[$filter]);
825 // Remove missing filters.
826 foreach ($stringfilters as $filter) {
827 if (!isset($allfilters[$filter])) {
828 unset($stringfilters[$filter]);
832 if ($prevfilters != $stringfilters) {
833 set_config('stringfilters', implode(',', $stringfilters));
834 set_config('filterall', !empty($stringfilters));
839 * Set the local activated state for a text filter.
841 * @param string $filter The filter name, for example 'tex'.
842 * @param integer $contextid The id of the context to get the local config for.
843 * @param integer $state One of the values TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_INHERIT.
844 * @return void
846 function filter_set_local_state($filter, $contextid, $state) {
847 global $DB;
849 // Check requested state is valid.
850 if (!in_array($state, array(TEXTFILTER_ON, TEXTFILTER_OFF, TEXTFILTER_INHERIT))) {
851 throw new coding_exception("Illegal option '$state' passed to filter_set_local_state. " .
852 "Must be one of TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_INHERIT.");
855 if ($contextid == context_system::instance()->id) {
856 throw new coding_exception('You cannot use filter_set_local_state ' .
857 'with $contextid equal to the system context id.');
860 if ($state == TEXTFILTER_INHERIT) {
861 $DB->delete_records('filter_active', array('filter' => $filter, 'contextid' => $contextid));
862 return;
865 $rec = $DB->get_record('filter_active', array('filter' => $filter, 'contextid' => $contextid));
866 $insert = false;
867 if (empty($rec)) {
868 $insert = true;
869 $rec = new stdClass;
870 $rec->filter = $filter;
871 $rec->contextid = $contextid;
874 $rec->active = $state;
876 if ($insert) {
877 $DB->insert_record('filter_active', $rec);
878 } else {
879 $DB->update_record('filter_active', $rec);
884 * Set a particular local config variable for a filter in a context.
886 * @param string $filter The filter name, for example 'tex'.
887 * @param integer $contextid The id of the context to get the local config for.
888 * @param string $name the setting name.
889 * @param string $value the corresponding value.
891 function filter_set_local_config($filter, $contextid, $name, $value) {
892 global $DB;
893 $rec = $DB->get_record('filter_config', array('filter' => $filter, 'contextid' => $contextid, 'name' => $name));
894 $insert = false;
895 if (empty($rec)) {
896 $insert = true;
897 $rec = new stdClass;
898 $rec->filter = $filter;
899 $rec->contextid = $contextid;
900 $rec->name = $name;
903 $rec->value = $value;
905 if ($insert) {
906 $DB->insert_record('filter_config', $rec);
907 } else {
908 $DB->update_record('filter_config', $rec);
913 * Remove a particular local config variable for a filter in a context.
915 * @param string $filter The filter name, for example 'tex'.
916 * @param integer $contextid The id of the context to get the local config for.
917 * @param string $name the setting name.
919 function filter_unset_local_config($filter, $contextid, $name) {
920 global $DB;
921 $DB->delete_records('filter_config', array('filter' => $filter, 'contextid' => $contextid, 'name' => $name));
925 * Get local config variables for a filter in a context. Normally (when your
926 * filter is running) you don't need to call this, becuase the config is fetched
927 * for you automatically. You only need this, for example, when you are getting
928 * the config so you can show the user an editing from.
930 * @param string $filter The filter name, for example 'tex'.
931 * @param integer $contextid The ID of the context to get the local config for.
932 * @return array of name => value pairs.
934 function filter_get_local_config($filter, $contextid) {
935 global $DB;
936 return $DB->get_records_menu('filter_config', array('filter' => $filter, 'contextid' => $contextid), '', 'name,value');
940 * This function is for use by backup. Gets all the filter information specific
941 * to one context.
943 * @param int $contextid
944 * @return array Array with two elements. The first element is an array of objects with
945 * fields filter and active. These come from the filter_active table. The
946 * second element is an array of objects with fields filter, name and value
947 * from the filter_config table.
949 function filter_get_all_local_settings($contextid) {
950 global $DB;
951 return array(
952 $DB->get_records('filter_active', array('contextid' => $contextid), 'filter', 'filter,active'),
953 $DB->get_records('filter_config', array('contextid' => $contextid), 'filter,name', 'filter,name,value'),
958 * Get the list of active filters, in the order that they should be used
959 * for a particular context, along with any local configuration variables.
961 * @param context $context a context
962 * @return array an array where the keys are the filter names, for example
963 * 'tex' and the values are any local
964 * configuration for that filter, as an array of name => value pairs
965 * from the filter_config table. In a lot of cases, this will be an
966 * empty array. So, an example return value for this function might be
967 * array(tex' => array())
969 function filter_get_active_in_context($context) {
970 global $DB, $FILTERLIB_PRIVATE;
972 if (!isset($FILTERLIB_PRIVATE)) {
973 $FILTERLIB_PRIVATE = new stdClass();
976 // Use cache (this is a within-request cache only) if available. See
977 // function filter_preload_activities.
978 if (isset($FILTERLIB_PRIVATE->active) &&
979 array_key_exists($context->id, $FILTERLIB_PRIVATE->active)) {
980 return $FILTERLIB_PRIVATE->active[$context->id];
983 $contextids = str_replace('/', ',', trim($context->path, '/'));
985 // The following SQL is tricky. It is explained on
986 // http://docs.moodle.org/dev/Filter_enable/disable_by_context.
987 $sql = "SELECT active.filter, fc.name, fc.value
988 FROM (SELECT f.filter, MAX(f.sortorder) AS sortorder
989 FROM {filter_active} f
990 JOIN {context} ctx ON f.contextid = ctx.id
991 WHERE ctx.id IN ($contextids)
992 GROUP BY filter
993 HAVING MAX(f.active * ctx.depth) > -MIN(f.active * ctx.depth)
994 ) active
995 LEFT JOIN {filter_config} fc ON fc.filter = active.filter AND fc.contextid = $context->id
996 ORDER BY active.sortorder";
997 $rs = $DB->get_recordset_sql($sql);
999 // Massage the data into the specified format to return.
1000 $filters = array();
1001 foreach ($rs as $row) {
1002 if (!isset($filters[$row->filter])) {
1003 $filters[$row->filter] = array();
1005 if (!is_null($row->name)) {
1006 $filters[$row->filter][$row->name] = $row->value;
1010 $rs->close();
1012 return $filters;
1016 * Preloads the list of active filters for all activities (modules) on the course
1017 * using two database queries.
1019 * @param course_modinfo $modinfo Course object from get_fast_modinfo
1021 function filter_preload_activities(course_modinfo $modinfo) {
1022 global $DB, $FILTERLIB_PRIVATE;
1024 if (!isset($FILTERLIB_PRIVATE)) {
1025 $FILTERLIB_PRIVATE = new stdClass();
1028 // Don't repeat preload.
1029 if (!isset($FILTERLIB_PRIVATE->preloaded)) {
1030 $FILTERLIB_PRIVATE->preloaded = array();
1032 if (!empty($FILTERLIB_PRIVATE->preloaded[$modinfo->get_course_id()])) {
1033 return;
1035 $FILTERLIB_PRIVATE->preloaded[$modinfo->get_course_id()] = true;
1037 // Get contexts for all CMs.
1038 $cmcontexts = array();
1039 $cmcontextids = array();
1040 foreach ($modinfo->get_cms() as $cm) {
1041 $modulecontext = context_module::instance($cm->id);
1042 $cmcontextids[] = $modulecontext->id;
1043 $cmcontexts[] = $modulecontext;
1046 // Get course context and all other parents.
1047 $coursecontext = context_course::instance($modinfo->get_course_id());
1048 $parentcontextids = explode('/', substr($coursecontext->path, 1));
1049 $allcontextids = array_merge($cmcontextids, $parentcontextids);
1051 // Get all filter_active rows relating to all these contexts.
1052 list ($sql, $params) = $DB->get_in_or_equal($allcontextids);
1053 $filteractives = $DB->get_records_select('filter_active', "contextid $sql", $params, 'sortorder');
1055 // Get all filter_config only for the cm contexts.
1056 list ($sql, $params) = $DB->get_in_or_equal($cmcontextids);
1057 $filterconfigs = $DB->get_records_select('filter_config', "contextid $sql", $params);
1059 // Note: I was a bit surprised that filter_config only works for the
1060 // most specific context (i.e. it does not need to be checked for course
1061 // context if we only care about CMs) however basede on code in
1062 // filter_get_active_in_context, this does seem to be correct.
1064 // Build course default active list. Initially this will be an array of
1065 // filter name => active score (where an active score >0 means it's active).
1066 $courseactive = array();
1068 // Also build list of filter_active rows below course level, by contextid.
1069 $remainingactives = array();
1071 // Array lists filters that are banned at top level.
1072 $banned = array();
1074 // Add any active filters in parent contexts to the array.
1075 foreach ($filteractives as $row) {
1076 $depth = array_search($row->contextid, $parentcontextids);
1077 if ($depth !== false) {
1078 // Find entry.
1079 if (!array_key_exists($row->filter, $courseactive)) {
1080 $courseactive[$row->filter] = 0;
1082 // This maths copes with reading rows in any order. Turning on/off
1083 // at site level counts 1, at next level down 4, at next level 9,
1084 // then 16, etc. This means the deepest level always wins, except
1085 // against the -9999 at top level.
1086 $courseactive[$row->filter] +=
1087 ($depth + 1) * ($depth + 1) * $row->active;
1089 if ($row->active == TEXTFILTER_DISABLED) {
1090 $banned[$row->filter] = true;
1092 } else {
1093 // Build list of other rows indexed by contextid.
1094 if (!array_key_exists($row->contextid, $remainingactives)) {
1095 $remainingactives[$row->contextid] = array();
1097 $remainingactives[$row->contextid][] = $row;
1101 // Chuck away the ones that aren't active.
1102 foreach ($courseactive as $filter => $score) {
1103 if ($score <= 0) {
1104 unset($courseactive[$filter]);
1105 } else {
1106 $courseactive[$filter] = array();
1110 // Loop through the contexts to reconstruct filter_active lists for each
1111 // cm on the course.
1112 if (!isset($FILTERLIB_PRIVATE->active)) {
1113 $FILTERLIB_PRIVATE->active = array();
1115 foreach ($cmcontextids as $contextid) {
1116 // Copy course list.
1117 $FILTERLIB_PRIVATE->active[$contextid] = $courseactive;
1119 // Are there any changes to the active list?
1120 if (array_key_exists($contextid, $remainingactives)) {
1121 foreach ($remainingactives[$contextid] as $row) {
1122 if ($row->active > 0 && empty($banned[$row->filter])) {
1123 // If it's marked active for specific context, add entry
1124 // (doesn't matter if one exists already).
1125 $FILTERLIB_PRIVATE->active[$contextid][$row->filter] = array();
1126 } else {
1127 // If it's marked inactive, remove entry (doesn't matter
1128 // if it doesn't exist).
1129 unset($FILTERLIB_PRIVATE->active[$contextid][$row->filter]);
1135 // Process all config rows to add config data to these entries.
1136 foreach ($filterconfigs as $row) {
1137 if (isset($FILTERLIB_PRIVATE->active[$row->contextid][$row->filter])) {
1138 $FILTERLIB_PRIVATE->active[$row->contextid][$row->filter][$row->name] = $row->value;
1144 * List all of the filters that are available in this context, and what the
1145 * local and inherited states of that filter are.
1147 * @param context $context a context that is not the system context.
1148 * @return array an array with filter names, for example 'tex'
1149 * as keys. and and the values are objects with fields:
1150 * ->filter filter name, same as the key.
1151 * ->localstate TEXTFILTER_ON/OFF/INHERIT
1152 * ->inheritedstate TEXTFILTER_ON/OFF - the state that will be used if localstate is set to TEXTFILTER_INHERIT.
1154 function filter_get_available_in_context($context) {
1155 global $DB;
1157 // The complex logic is working out the active state in the parent context,
1158 // so strip the current context from the list.
1159 $contextids = explode('/', trim($context->path, '/'));
1160 array_pop($contextids);
1161 $contextids = implode(',', $contextids);
1162 if (empty($contextids)) {
1163 throw new coding_exception('filter_get_available_in_context cannot be called with the system context.');
1166 // The following SQL is tricky, in the same way at the SQL in filter_get_active_in_context.
1167 $sql = "SELECT parent_states.filter,
1168 CASE WHEN fa.active IS NULL THEN " . TEXTFILTER_INHERIT . "
1169 ELSE fa.active END AS localstate,
1170 parent_states.inheritedstate
1171 FROM (SELECT f.filter, MAX(f.sortorder) AS sortorder,
1172 CASE WHEN MAX(f.active * ctx.depth) > -MIN(f.active * ctx.depth) THEN " . TEXTFILTER_ON . "
1173 ELSE " . TEXTFILTER_OFF . " END AS inheritedstate
1174 FROM {filter_active} f
1175 JOIN {context} ctx ON f.contextid = ctx.id
1176 WHERE ctx.id IN ($contextids)
1177 GROUP BY f.filter
1178 HAVING MIN(f.active) > " . TEXTFILTER_DISABLED . "
1179 ) parent_states
1180 LEFT JOIN {filter_active} fa ON fa.filter = parent_states.filter AND fa.contextid = $context->id
1181 ORDER BY parent_states.sortorder";
1182 return $DB->get_records_sql($sql);
1186 * This function is for use by the filter administration page.
1188 * @return array 'filtername' => object with fields 'filter' (=filtername), 'active' and 'sortorder'
1190 function filter_get_global_states() {
1191 global $DB;
1192 $context = context_system::instance();
1193 return $DB->get_records('filter_active', array('contextid' => $context->id), 'sortorder', 'filter,active,sortorder');
1197 * Delete all the data in the database relating to a filter, prior to deleting it.
1199 * @param string $filter The filter name, for example 'tex'.
1201 function filter_delete_all_for_filter($filter) {
1202 global $DB;
1204 unset_all_config_for_plugin('filter_' . $filter);
1205 $DB->delete_records('filter_active', array('filter' => $filter));
1206 $DB->delete_records('filter_config', array('filter' => $filter));
1210 * Delete all the data in the database relating to a context, used when contexts are deleted.
1212 * @param integer $contextid The id of the context being deleted.
1214 function filter_delete_all_for_context($contextid) {
1215 global $DB;
1216 $DB->delete_records('filter_active', array('contextid' => $contextid));
1217 $DB->delete_records('filter_config', array('contextid' => $contextid));
1221 * Does this filter have a global settings page in the admin tree?
1222 * (The settings page for a filter must be called, for example, filtersettingfiltertex.)
1224 * @param string $filter The filter name, for example 'tex'.
1225 * @return boolean Whether there should be a 'Settings' link on the config page.
1227 function filter_has_global_settings($filter) {
1228 global $CFG;
1229 $settingspath = $CFG->dirroot . '/filter/' . $filter . '/settings.php';
1230 if (is_readable($settingspath)) {
1231 return true;
1233 $settingspath = $CFG->dirroot . '/filter/' . $filter . '/filtersettings.php';
1234 return is_readable($settingspath);
1238 * Does this filter have local (per-context) settings?
1240 * @param string $filter The filter name, for example 'tex'.
1241 * @return boolean Whether there should be a 'Settings' link on the manage filters in context page.
1243 function filter_has_local_settings($filter) {
1244 global $CFG;
1245 $settingspath = $CFG->dirroot . '/filter/' . $filter . '/filterlocalsettings.php';
1246 return is_readable($settingspath);
1250 * Certain types of context (block and user) may not have local filter settings.
1251 * the function checks a context to see whether it may have local config.
1253 * @param object $context a context.
1254 * @return boolean whether this context may have local filter settings.
1256 function filter_context_may_have_filter_settings($context) {
1257 return $context->contextlevel != CONTEXT_BLOCK && $context->contextlevel != CONTEXT_USER;
1261 * Process phrases intelligently found within a HTML text (such as adding links).
1263 * @param string $text the text that we are filtering
1264 * @param filterobject[] $linkarray an array of filterobjects
1265 * @param array $ignoretagsopen an array of opening tags that we should ignore while filtering
1266 * @param array $ignoretagsclose an array of corresponding closing tags
1267 * @param bool $overridedefaultignore True to only use tags provided by arguments
1268 * @param bool $linkarrayalreadyprepared True to say that filter_prepare_phrases_for_filtering
1269 * has already been called for $linkarray. Default false.
1270 * @return string
1272 function filter_phrases($text, $linkarray, $ignoretagsopen = null, $ignoretagsclose = null,
1273 $overridedefaultignore = false, $linkarrayalreadyprepared = false) {
1275 global $CFG;
1277 // Used if $CFG->filtermatchoneperpage is on. Array with keys being the workregexp
1278 // for things that have already been matched on this page.
1279 static $usedphrases = [];
1281 $ignoretags = array(); // To store all the enclosing tags to be completely ignored.
1282 $tags = array(); // To store all the simple tags to be ignored.
1284 if (!$linkarrayalreadyprepared) {
1285 $linkarray = filter_prepare_phrases_for_filtering($linkarray);
1288 if (!$overridedefaultignore) {
1289 // A list of open/close tags that we should not replace within.
1290 // Extended to include <script>, <textarea>, <select> and <a> tags.
1291 // Regular expression allows tags with or without attributes.
1292 $filterignoretagsopen = array('<head>', '<nolink>', '<span(\s[^>]*?)?class="nolink"(\s[^>]*?)?>',
1293 '<script(\s[^>]*?)?>', '<textarea(\s[^>]*?)?>',
1294 '<select(\s[^>]*?)?>', '<a(\s[^>]*?)?>');
1295 $filterignoretagsclose = array('</head>', '</nolink>', '</span>',
1296 '</script>', '</textarea>', '</select>', '</a>');
1297 } else {
1298 // Set an empty default list.
1299 $filterignoretagsopen = array();
1300 $filterignoretagsclose = array();
1303 // Add the user defined ignore tags to the default list.
1304 if ( is_array($ignoretagsopen) ) {
1305 foreach ($ignoretagsopen as $open) {
1306 $filterignoretagsopen[] = $open;
1308 foreach ($ignoretagsclose as $close) {
1309 $filterignoretagsclose[] = $close;
1313 // Double up some magic chars to avoid "accidental matches".
1314 $text = preg_replace('/([#*%])/', '\1\1', $text);
1316 // Remove everything enclosed by the ignore tags from $text.
1317 filter_save_ignore_tags($text, $filterignoretagsopen, $filterignoretagsclose, $ignoretags);
1319 // Remove tags from $text.
1320 filter_save_tags($text, $tags);
1322 // Prepare the limit for preg_match calls.
1323 if (!empty($CFG->filtermatchonepertext) || !empty($CFG->filtermatchoneperpage)) {
1324 $pregreplacelimit = 1;
1325 } else {
1326 $pregreplacelimit = -1; // No limit.
1329 // Time to cycle through each phrase to be linked.
1330 foreach ($linkarray as $key => $linkobject) {
1331 if ($linkobject->workregexp === null) {
1332 // This is the case if, when preparing the phrases for filtering,
1333 // we decided that this was not a suitable phrase to match.
1334 continue;
1337 // If $CFG->filtermatchoneperpage, avoid previously matched linked phrases.
1338 if (!empty($CFG->filtermatchoneperpage) && isset($usedphrases[$linkobject->workregexp])) {
1339 continue;
1342 // Do our highlighting.
1343 $resulttext = preg_replace_callback($linkobject->workregexp,
1344 function ($matches) use ($linkobject) {
1345 if ($linkobject->workreplacementphrase === null) {
1346 filter_prepare_phrase_for_replacement($linkobject);
1349 return str_replace('$1', $matches[1], $linkobject->workreplacementphrase);
1350 }, $text, $pregreplacelimit);
1352 // If the text has changed we have to look for links again.
1353 if ($resulttext != $text) {
1354 $text = $resulttext;
1355 // Remove everything enclosed by the ignore tags from $text.
1356 filter_save_ignore_tags($text, $filterignoretagsopen, $filterignoretagsclose, $ignoretags);
1357 // Remove tags from $text.
1358 filter_save_tags($text, $tags);
1359 // If $CFG->filtermatchoneperpage, save linked phrases to request.
1360 if (!empty($CFG->filtermatchoneperpage)) {
1361 $usedphrases[$linkobject->workregexp] = 1;
1366 // Rebuild the text with all the excluded areas.
1367 if (!empty($tags)) {
1368 $text = str_replace(array_keys($tags), $tags, $text);
1371 if (!empty($ignoretags)) {
1372 $ignoretags = array_reverse($ignoretags); // Reversed so "progressive" str_replace() will solve some nesting problems.
1373 $text = str_replace(array_keys($ignoretags), $ignoretags, $text);
1376 // Remove the protective doubleups.
1377 $text = preg_replace('/([#*%])(\1)/', '\1', $text);
1379 // Add missing javascript for popus.
1380 $text = filter_add_javascript($text);
1382 return $text;
1386 * Prepare a list of link for processing with {@link filter_phrases()}.
1388 * @param filterobject[] $linkarray the links that will be passed to filter_phrases().
1389 * @return filterobject[] the updated list of links with necessary pre-processing done.
1391 function filter_prepare_phrases_for_filtering(array $linkarray) {
1392 // Time to cycle through each phrase to be linked.
1393 foreach ($linkarray as $linkobject) {
1395 // Set some defaults if certain properties are missing.
1396 // Properties may be missing if the filterobject class has not been used to construct the object.
1397 if (empty($linkobject->phrase)) {
1398 continue;
1401 // Avoid integers < 1000 to be linked. See bug 1446.
1402 $intcurrent = intval($linkobject->phrase);
1403 if (!empty($intcurrent) && strval($intcurrent) == $linkobject->phrase && $intcurrent < 1000) {
1404 continue;
1407 // Strip tags out of the phrase.
1408 $linkobject->workregexp = strip_tags($linkobject->phrase);
1410 if (!$linkobject->casesensitive) {
1411 $linkobject->workregexp = core_text::strtolower($linkobject->workregexp);
1414 // Double up chars that might cause a false match -- the duplicates will
1415 // be cleared up before returning to the user.
1416 $linkobject->workregexp = preg_replace('/([#*%])/', '\1\1', $linkobject->workregexp);
1418 // Quote any regular expression characters and the delimiter in the work phrase to be searched.
1419 $linkobject->workregexp = preg_quote($linkobject->workregexp, '/');
1421 // If we ony want to match entire words then add \b assertions. However, only
1422 // do this if the first or last thing in the phrase to match is a word character.
1423 if ($linkobject->fullmatch) {
1424 if (preg_match('~^\w~', $linkobject->workregexp)) {
1425 $linkobject->workregexp = '\b' . $linkobject->workregexp;
1427 if (preg_match('~\w$~', $linkobject->workregexp)) {
1428 $linkobject->workregexp = $linkobject->workregexp . '\b';
1432 $linkobject->workregexp = '/(' . $linkobject->workregexp . ')/s';
1434 if (!$linkobject->casesensitive) {
1435 $linkobject->workregexp .= 'iu';
1439 return $linkarray;
1443 * Fill in the remaining ->work... fields, that would be needed to replace the phrase.
1445 * @param filterobject $linkobject the link object on which to set additional fields.
1447 function filter_prepare_phrase_for_replacement(filterobject $linkobject) {
1448 if ($linkobject->replacementcallback !== null) {
1449 list($linkobject->hreftagbegin, $linkobject->hreftagend, $linkobject->replacementphrase) =
1450 call_user_func_array($linkobject->replacementcallback, $linkobject->replacementcallbackdata);
1453 if (!isset($linkobject->hreftagbegin) or !isset($linkobject->hreftagend)) {
1454 $linkobject->hreftagbegin = '<span class="highlight"';
1455 $linkobject->hreftagend = '</span>';
1458 // Double up chars to protect true duplicates
1459 // be cleared up before returning to the user.
1460 $hreftagbeginmangled = preg_replace('/([#*%])/', '\1\1', $linkobject->hreftagbegin);
1462 // Set the replacement phrase properly.
1463 if ($linkobject->replacementphrase) { // We have specified a replacement phrase.
1464 $linkobject->workreplacementphrase = strip_tags($linkobject->replacementphrase);
1465 } else { // The replacement is the original phrase as matched below.
1466 $linkobject->workreplacementphrase = '$1';
1469 $linkobject->workreplacementphrase = $hreftagbeginmangled .
1470 $linkobject->workreplacementphrase . $linkobject->hreftagend;
1474 * Remove duplicate from a list of {@link filterobject}.
1476 * @param filterobject[] $linkarray a list of filterobject.
1477 * @return filterobject[] the same list, but with dupicates removed.
1479 function filter_remove_duplicates($linkarray) {
1481 $concepts = array(); // Keep a record of concepts as we cycle through.
1482 $lconcepts = array(); // A lower case version for case insensitive.
1484 $cleanlinks = array();
1486 foreach ($linkarray as $key => $filterobject) {
1487 if ($filterobject->casesensitive) {
1488 $exists = in_array($filterobject->phrase, $concepts);
1489 } else {
1490 $exists = in_array(core_text::strtolower($filterobject->phrase), $lconcepts);
1493 if (!$exists) {
1494 $cleanlinks[] = $filterobject;
1495 $concepts[] = $filterobject->phrase;
1496 $lconcepts[] = core_text::strtolower($filterobject->phrase);
1500 return $cleanlinks;
1504 * Extract open/lose tags and their contents to avoid being processed by filters.
1505 * Useful to extract pieces of code like <a>...</a> tags. It returns the text
1506 * converted with some <#xTEXTFILTER_EXCL_SEPARATORx#> codes replacing the extracted text. Such extracted
1507 * texts are returned in the ignoretags array (as values), with codes as keys.
1509 * @param string $text the text that we are filtering (in/out)
1510 * @param array $filterignoretagsopen an array of open tags to start searching
1511 * @param array $filterignoretagsclose an array of close tags to end searching
1512 * @param array $ignoretags an array of saved strings useful to rebuild the original text (in/out)
1514 function filter_save_ignore_tags(&$text, $filterignoretagsopen, $filterignoretagsclose, &$ignoretags) {
1516 // Remove everything enclosed by the ignore tags from $text.
1517 foreach ($filterignoretagsopen as $ikey => $opentag) {
1518 $closetag = $filterignoretagsclose[$ikey];
1519 // Form regular expression.
1520 $opentag = str_replace('/', '\/', $opentag); // Delimit forward slashes.
1521 $closetag = str_replace('/', '\/', $closetag); // Delimit forward slashes.
1522 $pregexp = '/'.$opentag.'(.*?)'.$closetag.'/is';
1524 preg_match_all($pregexp, $text, $listofignores);
1525 foreach (array_unique($listofignores[0]) as $key => $value) {
1526 $prefix = (string) (count($ignoretags) + 1);
1527 $ignoretags['<#'.$prefix.TEXTFILTER_EXCL_SEPARATOR.$key.'#>'] = $value;
1529 if (!empty($ignoretags)) {
1530 $text = str_replace($ignoretags, array_keys($ignoretags), $text);
1536 * Extract tags (any text enclosed by < and > to avoid being processed by filters.
1537 * It returns the text converted with some <%xTEXTFILTER_EXCL_SEPARATORx%> codes replacing the extracted text. Such extracted
1538 * texts are returned in the tags array (as values), with codes as keys.
1540 * @param string $text the text that we are filtering (in/out)
1541 * @param array $tags an array of saved strings useful to rebuild the original text (in/out)
1543 function filter_save_tags(&$text, &$tags) {
1545 preg_match_all('/<([^#%*].*?)>/is', $text, $listofnewtags);
1546 foreach (array_unique($listofnewtags[0]) as $ntkey => $value) {
1547 $prefix = (string)(count($tags) + 1);
1548 $tags['<%'.$prefix.TEXTFILTER_EXCL_SEPARATOR.$ntkey.'%>'] = $value;
1550 if (!empty($tags)) {
1551 $text = str_replace($tags, array_keys($tags), $text);
1556 * Add missing openpopup javascript to HTML files.
1558 * @param string $text
1559 * @return string
1561 function filter_add_javascript($text) {
1562 global $CFG;
1564 if (stripos($text, '</html>') === false) {
1565 return $text; // This is not a html file.
1567 if (strpos($text, 'onclick="return openpopup') === false) {
1568 return $text; // No popup - no need to add javascript.
1570 $js = "
1571 <script type=\"text/javascript\">
1572 <!--
1573 function openpopup(url,name,options,fullscreen) {
1574 fullurl = \"".$CFG->wwwroot."\" + url;
1575 windowobj = window.open(fullurl,name,options);
1576 if (fullscreen) {
1577 windowobj.moveTo(0,0);
1578 windowobj.resizeTo(screen.availWidth,screen.availHeight);
1580 windowobj.focus();
1581 return false;
1583 // -->
1584 </script>";
1585 if (stripos($text, '</head>') !== false) {
1586 // Try to add it into the head element.
1587 $text = str_ireplace('</head>', $js.'</head>', $text);
1588 return $text;
1591 // Last chance - try adding head element.
1592 return preg_replace("/<html.*?>/is", "\\0<head>".$js.'</head>', $text);