MDL-36754 output: Support token pluginfiles in group pic
[moodle.git] / lib / filterlib.php
blobbbb928947c750e0be3bfea7bba7dcbe4a5641a50
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 // <nolink> tags removed 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 filter_phrases function below.
466 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
467 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
469 class filterobject {
470 /** @var string */
471 var $phrase;
472 var $hreftagbegin;
473 var $hreftagend;
474 /** @var bool */
475 var $casesensitive;
476 var $fullmatch;
477 /** @var mixed */
478 var $replacementphrase;
479 var $work_phrase;
480 var $work_hreftagbegin;
481 var $work_hreftagend;
482 var $work_casesensitive;
483 var $work_fullmatch;
484 var $work_replacementphrase;
485 /** @var bool */
486 var $work_calculated;
489 * A constructor just because I like constructing
491 * @param string $phrase
492 * @param string $hreftagbegin
493 * @param string $hreftagend
494 * @param bool $casesensitive
495 * @param bool $fullmatch
496 * @param mixed $replacementphrase
498 public function __construct($phrase, $hreftagbegin = '<span class="highlight">',
499 $hreftagend = '</span>',
500 $casesensitive = false,
501 $fullmatch = false,
502 $replacementphrase = NULL) {
504 $this->phrase = $phrase;
505 $this->hreftagbegin = $hreftagbegin;
506 $this->hreftagend = $hreftagend;
507 $this->casesensitive = $casesensitive;
508 $this->fullmatch = $fullmatch;
509 $this->replacementphrase= $replacementphrase;
510 $this->work_calculated = false;
516 * Look up the name of this filter
518 * @param string $filter the filter name
519 * @return string the human-readable name for this filter.
521 function filter_get_name($filter) {
522 if (strpos($filter, 'filter/') === 0) {
523 debugging("Old '$filter'' parameter used in filter_get_name()");
524 $filter = substr($filter, 7);
525 } else if (strpos($filter, '/') !== false) {
526 throw new coding_exception('Unknown filter type ' . $filter);
529 if (get_string_manager()->string_exists('filtername', 'filter_' . $filter)) {
530 return get_string('filtername', 'filter_' . $filter);
531 } else {
532 return $filter;
537 * Get the names of all the filters installed in this Moodle.
539 * @return array path => filter name from the appropriate lang file. e.g.
540 * array('tex' => 'TeX Notation');
541 * sorted in alphabetical order of name.
543 function filter_get_all_installed() {
544 $filternames = array();
545 foreach (core_component::get_plugin_list('filter') as $filter => $fulldir) {
546 if (is_readable("$fulldir/filter.php")) {
547 $filternames[$filter] = filter_get_name($filter);
550 core_collator::asort($filternames);
551 return $filternames;
555 * Set the global activated state for a text filter.
557 * @param string $filtername The filter name, for example 'tex'.
558 * @param int $state One of the values TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_DISABLED.
559 * @param int $move -1 means up, 0 means the same, 1 means down
561 function filter_set_global_state($filtername, $state, $move = 0) {
562 global $DB;
564 // Check requested state is valid.
565 if (!in_array($state, array(TEXTFILTER_ON, TEXTFILTER_OFF, TEXTFILTER_DISABLED))) {
566 throw new coding_exception("Illegal option '$state' passed to filter_set_global_state. " .
567 "Must be one of TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_DISABLED.");
570 if ($move > 0) {
571 $move = 1;
572 } else if ($move < 0) {
573 $move = -1;
576 if (strpos($filtername, 'filter/') === 0) {
577 //debugging("Old filtername '$filtername' parameter used in filter_set_global_state()", DEBUG_DEVELOPER);
578 $filtername = substr($filtername, 7);
579 } else if (strpos($filtername, '/') !== false) {
580 throw new coding_exception("Invalid filter name '$filtername' used in filter_set_global_state()");
583 $transaction = $DB->start_delegated_transaction();
585 $syscontext = context_system::instance();
586 $filters = $DB->get_records('filter_active', array('contextid' => $syscontext->id), 'sortorder ASC');
588 $on = array();
589 $off = array();
591 foreach($filters as $f) {
592 if ($f->active == TEXTFILTER_DISABLED) {
593 $off[$f->filter] = $f;
594 } else {
595 $on[$f->filter] = $f;
599 // Update the state or add new record.
600 if (isset($on[$filtername])) {
601 $filter = $on[$filtername];
602 if ($filter->active != $state) {
603 add_to_config_log('filter_active', $filter->active, $state, $filtername);
605 $filter->active = $state;
606 $DB->update_record('filter_active', $filter);
607 if ($filter->active == TEXTFILTER_DISABLED) {
608 unset($on[$filtername]);
609 $off = array($filter->filter => $filter) + $off;
614 } else if (isset($off[$filtername])) {
615 $filter = $off[$filtername];
616 if ($filter->active != $state) {
617 add_to_config_log('filter_active', $filter->active, $state, $filtername);
619 $filter->active = $state;
620 $DB->update_record('filter_active', $filter);
621 if ($filter->active != TEXTFILTER_DISABLED) {
622 unset($off[$filtername]);
623 $on[$filter->filter] = $filter;
627 } else {
628 add_to_config_log('filter_active', '', $state, $filtername);
630 $filter = new stdClass();
631 $filter->filter = $filtername;
632 $filter->contextid = $syscontext->id;
633 $filter->active = $state;
634 $filter->sortorder = 99999;
635 $filter->id = $DB->insert_record('filter_active', $filter);
637 $filters[$filter->id] = $filter;
638 if ($state == TEXTFILTER_DISABLED) {
639 $off[$filter->filter] = $filter;
640 } else {
641 $on[$filter->filter] = $filter;
645 // Move only active.
646 if ($move != 0 and isset($on[$filter->filter])) {
647 $i = 1;
648 foreach ($on as $f) {
649 $f->newsortorder = $i;
650 $i++;
653 $filter->newsortorder = $filter->newsortorder + $move;
655 foreach ($on as $f) {
656 if ($f->id == $filter->id) {
657 continue;
659 if ($f->newsortorder == $filter->newsortorder) {
660 if ($move == 1) {
661 $f->newsortorder = $f->newsortorder - 1;
662 } else {
663 $f->newsortorder = $f->newsortorder + 1;
668 core_collator::asort_objects_by_property($on, 'newsortorder', core_collator::SORT_NUMERIC);
671 // Inactive are sorted by filter name.
672 core_collator::asort_objects_by_property($off, 'filter', core_collator::SORT_NATURAL);
674 // Update records if necessary.
675 $i = 1;
676 foreach ($on as $f) {
677 if ($f->sortorder != $i) {
678 $DB->set_field('filter_active', 'sortorder', $i, array('id'=>$f->id));
680 $i++;
682 foreach ($off as $f) {
683 if ($f->sortorder != $i) {
684 $DB->set_field('filter_active', 'sortorder', $i, array('id'=>$f->id));
686 $i++;
689 $transaction->allow_commit();
693 * @param string $filtername The filter name, for example 'tex'.
694 * @return boolean is this filter allowed to be used on this site. That is, the
695 * admin has set the global 'active' setting to On, or Off, but available.
697 function filter_is_enabled($filtername) {
698 if (strpos($filtername, 'filter/') === 0) {
699 //debugging("Old filtername '$filtername' parameter used in filter_is_enabled()", DEBUG_DEVELOPER);
700 $filtername = substr($filtername, 7);
701 } else if (strpos($filtername, '/') !== false) {
702 throw new coding_exception("Invalid filter name '$filtername' used in filter_is_enabled()");
704 return array_key_exists($filtername, filter_get_globally_enabled());
708 * Return a list of all the filters that may be in use somewhere.
710 * @staticvar array $enabledfilters
711 * @return array where the keys and values are both the filter name, like 'tex'.
713 function filter_get_globally_enabled() {
714 $cache = \cache::make_from_params(\cache_store::MODE_REQUEST, 'core_filter', 'global_filters');
715 $enabledfilters = $cache->get('enabled');
716 if ($enabledfilters !== false) {
717 return $enabledfilters;
720 $filters = filter_get_global_states();
721 $enabledfilters = array();
722 foreach ($filters as $filter => $filerinfo) {
723 if ($filerinfo->active != TEXTFILTER_DISABLED) {
724 $enabledfilters[$filter] = $filter;
728 $cache->set('enabled', $enabledfilters);
729 return $enabledfilters;
733 * Get the globally enabled filters.
735 * This returns the filters which could be used in any context. Essentially
736 * the filters which are not disabled for the entire site.
738 * @return array Keys are filter names, and values the config.
740 function filter_get_globally_enabled_filters_with_config() {
741 global $DB;
743 $sql = "SELECT f.filter, fc.name, fc.value
744 FROM {filter_active} f
745 LEFT JOIN {filter_config} fc
746 ON fc.filter = f.filter
747 AND fc.contextid = f.contextid
748 WHERE f.contextid = :contextid
749 AND f.active != :disabled
750 ORDER BY f.sortorder";
752 $rs = $DB->get_recordset_sql($sql, [
753 'contextid' => context_system::instance()->id,
754 'disabled' => TEXTFILTER_DISABLED
757 // Massage the data into the specified format to return.
758 $filters = array();
759 foreach ($rs as $row) {
760 if (!isset($filters[$row->filter])) {
761 $filters[$row->filter] = array();
763 if ($row->name !== null) {
764 $filters[$row->filter][$row->name] = $row->value;
767 $rs->close();
769 return $filters;
773 * Return the names of the filters that should also be applied to strings
774 * (when they are enabled).
776 * @return array where the keys and values are both the filter name, like 'tex'.
778 function filter_get_string_filters() {
779 global $CFG;
780 $stringfilters = array();
781 if (!empty($CFG->filterall) && !empty($CFG->stringfilters)) {
782 $stringfilters = explode(',', $CFG->stringfilters);
783 $stringfilters = array_combine($stringfilters, $stringfilters);
785 return $stringfilters;
789 * Sets whether a particular active filter should be applied to all strings by
790 * format_string, or just used by format_text.
792 * @param string $filter The filter name, for example 'tex'.
793 * @param boolean $applytostrings if true, this filter will apply to format_string
794 * and format_text, when it is enabled.
796 function filter_set_applies_to_strings($filter, $applytostrings) {
797 $stringfilters = filter_get_string_filters();
798 $prevfilters = $stringfilters;
799 $allfilters = core_component::get_plugin_list('filter');
801 if ($applytostrings) {
802 $stringfilters[$filter] = $filter;
803 } else {
804 unset($stringfilters[$filter]);
807 // Remove missing filters.
808 foreach ($stringfilters as $filter) {
809 if (!isset($allfilters[$filter])) {
810 unset($stringfilters[$filter]);
814 if ($prevfilters != $stringfilters) {
815 set_config('stringfilters', implode(',', $stringfilters));
816 set_config('filterall', !empty($stringfilters));
821 * Set the local activated state for a text filter.
823 * @param string $filter The filter name, for example 'tex'.
824 * @param integer $contextid The id of the context to get the local config for.
825 * @param integer $state One of the values TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_INHERIT.
826 * @return void
828 function filter_set_local_state($filter, $contextid, $state) {
829 global $DB;
831 // Check requested state is valid.
832 if (!in_array($state, array(TEXTFILTER_ON, TEXTFILTER_OFF, TEXTFILTER_INHERIT))) {
833 throw new coding_exception("Illegal option '$state' passed to filter_set_local_state. " .
834 "Must be one of TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_INHERIT.");
837 if ($contextid == context_system::instance()->id) {
838 throw new coding_exception('You cannot use filter_set_local_state ' .
839 'with $contextid equal to the system context id.');
842 if ($state == TEXTFILTER_INHERIT) {
843 $DB->delete_records('filter_active', array('filter' => $filter, 'contextid' => $contextid));
844 return;
847 $rec = $DB->get_record('filter_active', array('filter' => $filter, 'contextid' => $contextid));
848 $insert = false;
849 if (empty($rec)) {
850 $insert = true;
851 $rec = new stdClass;
852 $rec->filter = $filter;
853 $rec->contextid = $contextid;
856 $rec->active = $state;
858 if ($insert) {
859 $DB->insert_record('filter_active', $rec);
860 } else {
861 $DB->update_record('filter_active', $rec);
866 * Set a particular local config variable for a filter in a context.
868 * @param string $filter The filter name, for example 'tex'.
869 * @param integer $contextid The id of the context to get the local config for.
870 * @param string $name the setting name.
871 * @param string $value the corresponding value.
873 function filter_set_local_config($filter, $contextid, $name, $value) {
874 global $DB;
875 $rec = $DB->get_record('filter_config', array('filter' => $filter, 'contextid' => $contextid, 'name' => $name));
876 $insert = false;
877 if (empty($rec)) {
878 $insert = true;
879 $rec = new stdClass;
880 $rec->filter = $filter;
881 $rec->contextid = $contextid;
882 $rec->name = $name;
885 $rec->value = $value;
887 if ($insert) {
888 $DB->insert_record('filter_config', $rec);
889 } else {
890 $DB->update_record('filter_config', $rec);
895 * Remove a particular local config variable for a filter in a context.
897 * @param string $filter The filter name, for example 'tex'.
898 * @param integer $contextid The id of the context to get the local config for.
899 * @param string $name the setting name.
901 function filter_unset_local_config($filter, $contextid, $name) {
902 global $DB;
903 $DB->delete_records('filter_config', array('filter' => $filter, 'contextid' => $contextid, 'name' => $name));
907 * Get local config variables for a filter in a context. Normally (when your
908 * filter is running) you don't need to call this, becuase the config is fetched
909 * for you automatically. You only need this, for example, when you are getting
910 * the config so you can show the user an editing from.
912 * @param string $filter The filter name, for example 'tex'.
913 * @param integer $contextid The ID of the context to get the local config for.
914 * @return array of name => value pairs.
916 function filter_get_local_config($filter, $contextid) {
917 global $DB;
918 return $DB->get_records_menu('filter_config', array('filter' => $filter, 'contextid' => $contextid), '', 'name,value');
922 * This function is for use by backup. Gets all the filter information specific
923 * to one context.
925 * @param int $contextid
926 * @return array Array with two elements. The first element is an array of objects with
927 * fields filter and active. These come from the filter_active table. The
928 * second element is an array of objects with fields filter, name and value
929 * from the filter_config table.
931 function filter_get_all_local_settings($contextid) {
932 global $DB;
933 return array(
934 $DB->get_records('filter_active', array('contextid' => $contextid), 'filter', 'filter,active'),
935 $DB->get_records('filter_config', array('contextid' => $contextid), 'filter,name', 'filter,name,value'),
940 * Get the list of active filters, in the order that they should be used
941 * for a particular context, along with any local configuration variables.
943 * @param context $context a context
944 * @return array an array where the keys are the filter names, for example
945 * 'tex' and the values are any local
946 * configuration for that filter, as an array of name => value pairs
947 * from the filter_config table. In a lot of cases, this will be an
948 * empty array. So, an example return value for this function might be
949 * array(tex' => array())
951 function filter_get_active_in_context($context) {
952 global $DB, $FILTERLIB_PRIVATE;
954 if (!isset($FILTERLIB_PRIVATE)) {
955 $FILTERLIB_PRIVATE = new stdClass();
958 // Use cache (this is a within-request cache only) if available. See
959 // function filter_preload_activities.
960 if (isset($FILTERLIB_PRIVATE->active) &&
961 array_key_exists($context->id, $FILTERLIB_PRIVATE->active)) {
962 return $FILTERLIB_PRIVATE->active[$context->id];
965 $contextids = str_replace('/', ',', trim($context->path, '/'));
967 // The following SQL is tricky. It is explained on
968 // http://docs.moodle.org/dev/Filter_enable/disable_by_context
969 $sql = "SELECT active.filter, fc.name, fc.value
970 FROM (SELECT f.filter, MAX(f.sortorder) AS sortorder
971 FROM {filter_active} f
972 JOIN {context} ctx ON f.contextid = ctx.id
973 WHERE ctx.id IN ($contextids)
974 GROUP BY filter
975 HAVING MAX(f.active * ctx.depth) > -MIN(f.active * ctx.depth)
976 ) active
977 LEFT JOIN {filter_config} fc ON fc.filter = active.filter AND fc.contextid = $context->id
978 ORDER BY active.sortorder";
979 $rs = $DB->get_recordset_sql($sql);
981 // Massage the data into the specified format to return.
982 $filters = array();
983 foreach ($rs as $row) {
984 if (!isset($filters[$row->filter])) {
985 $filters[$row->filter] = array();
987 if (!is_null($row->name)) {
988 $filters[$row->filter][$row->name] = $row->value;
992 $rs->close();
994 return $filters;
998 * Preloads the list of active filters for all activities (modules) on the course
999 * using two database queries.
1001 * @param course_modinfo $modinfo Course object from get_fast_modinfo
1003 function filter_preload_activities(course_modinfo $modinfo) {
1004 global $DB, $FILTERLIB_PRIVATE;
1006 if (!isset($FILTERLIB_PRIVATE)) {
1007 $FILTERLIB_PRIVATE = new stdClass();
1010 // Don't repeat preload
1011 if (!isset($FILTERLIB_PRIVATE->preloaded)) {
1012 $FILTERLIB_PRIVATE->preloaded = array();
1014 if (!empty($FILTERLIB_PRIVATE->preloaded[$modinfo->get_course_id()])) {
1015 return;
1017 $FILTERLIB_PRIVATE->preloaded[$modinfo->get_course_id()] = true;
1019 // Get contexts for all CMs
1020 $cmcontexts = array();
1021 $cmcontextids = array();
1022 foreach ($modinfo->get_cms() as $cm) {
1023 $modulecontext = context_module::instance($cm->id);
1024 $cmcontextids[] = $modulecontext->id;
1025 $cmcontexts[] = $modulecontext;
1028 // Get course context and all other parents...
1029 $coursecontext = context_course::instance($modinfo->get_course_id());
1030 $parentcontextids = explode('/', substr($coursecontext->path, 1));
1031 $allcontextids = array_merge($cmcontextids, $parentcontextids);
1033 // Get all filter_active rows relating to all these contexts
1034 list ($sql, $params) = $DB->get_in_or_equal($allcontextids);
1035 $filteractives = $DB->get_records_select('filter_active', "contextid $sql", $params, 'sortorder');
1037 // Get all filter_config only for the cm contexts
1038 list ($sql, $params) = $DB->get_in_or_equal($cmcontextids);
1039 $filterconfigs = $DB->get_records_select('filter_config', "contextid $sql", $params);
1041 // Note: I was a bit surprised that filter_config only works for the
1042 // most specific context (i.e. it does not need to be checked for course
1043 // context if we only care about CMs) however basede on code in
1044 // filter_get_active_in_context, this does seem to be correct.
1046 // Build course default active list. Initially this will be an array of
1047 // filter name => active score (where an active score >0 means it's active)
1048 $courseactive = array();
1050 // Also build list of filter_active rows below course level, by contextid
1051 $remainingactives = array();
1053 // Array lists filters that are banned at top level
1054 $banned = array();
1056 // Add any active filters in parent contexts to the array
1057 foreach ($filteractives as $row) {
1058 $depth = array_search($row->contextid, $parentcontextids);
1059 if ($depth !== false) {
1060 // Find entry
1061 if (!array_key_exists($row->filter, $courseactive)) {
1062 $courseactive[$row->filter] = 0;
1064 // This maths copes with reading rows in any order. Turning on/off
1065 // at site level counts 1, at next level down 4, at next level 9,
1066 // then 16, etc. This means the deepest level always wins, except
1067 // against the -9999 at top level.
1068 $courseactive[$row->filter] +=
1069 ($depth + 1) * ($depth + 1) * $row->active;
1071 if ($row->active == TEXTFILTER_DISABLED) {
1072 $banned[$row->filter] = true;
1074 } else {
1075 // Build list of other rows indexed by contextid
1076 if (!array_key_exists($row->contextid, $remainingactives)) {
1077 $remainingactives[$row->contextid] = array();
1079 $remainingactives[$row->contextid][] = $row;
1083 // Chuck away the ones that aren't active.
1084 foreach ($courseactive as $filter=>$score) {
1085 if ($score <= 0) {
1086 unset($courseactive[$filter]);
1087 } else {
1088 $courseactive[$filter] = array();
1092 // Loop through the contexts to reconstruct filter_active lists for each
1093 // cm on the course.
1094 if (!isset($FILTERLIB_PRIVATE->active)) {
1095 $FILTERLIB_PRIVATE->active = array();
1097 foreach ($cmcontextids as $contextid) {
1098 // Copy course list
1099 $FILTERLIB_PRIVATE->active[$contextid] = $courseactive;
1101 // Are there any changes to the active list?
1102 if (array_key_exists($contextid, $remainingactives)) {
1103 foreach ($remainingactives[$contextid] as $row) {
1104 if ($row->active > 0 && empty($banned[$row->filter])) {
1105 // If it's marked active for specific context, add entry
1106 // (doesn't matter if one exists already).
1107 $FILTERLIB_PRIVATE->active[$contextid][$row->filter] = array();
1108 } else {
1109 // If it's marked inactive, remove entry (doesn't matter
1110 // if it doesn't exist).
1111 unset($FILTERLIB_PRIVATE->active[$contextid][$row->filter]);
1117 // Process all config rows to add config data to these entries.
1118 foreach ($filterconfigs as $row) {
1119 if (isset($FILTERLIB_PRIVATE->active[$row->contextid][$row->filter])) {
1120 $FILTERLIB_PRIVATE->active[$row->contextid][$row->filter][$row->name] = $row->value;
1126 * List all of the filters that are available in this context, and what the
1127 * local and inherited states of that filter are.
1129 * @param context $context a context that is not the system context.
1130 * @return array an array with filter names, for example 'tex'
1131 * as keys. and and the values are objects with fields:
1132 * ->filter filter name, same as the key.
1133 * ->localstate TEXTFILTER_ON/OFF/INHERIT
1134 * ->inheritedstate TEXTFILTER_ON/OFF - the state that will be used if localstate is set to TEXTFILTER_INHERIT.
1136 function filter_get_available_in_context($context) {
1137 global $DB;
1139 // The complex logic is working out the active state in the parent context,
1140 // so strip the current context from the list.
1141 $contextids = explode('/', trim($context->path, '/'));
1142 array_pop($contextids);
1143 $contextids = implode(',', $contextids);
1144 if (empty($contextids)) {
1145 throw new coding_exception('filter_get_available_in_context cannot be called with the system context.');
1148 // The following SQL is tricky, in the same way at the SQL in filter_get_active_in_context.
1149 $sql = "SELECT parent_states.filter,
1150 CASE WHEN fa.active IS NULL THEN " . TEXTFILTER_INHERIT . "
1151 ELSE fa.active END AS localstate,
1152 parent_states.inheritedstate
1153 FROM (SELECT f.filter, MAX(f.sortorder) AS sortorder,
1154 CASE WHEN MAX(f.active * ctx.depth) > -MIN(f.active * ctx.depth) THEN " . TEXTFILTER_ON . "
1155 ELSE " . TEXTFILTER_OFF . " END AS inheritedstate
1156 FROM {filter_active} f
1157 JOIN {context} ctx ON f.contextid = ctx.id
1158 WHERE ctx.id IN ($contextids)
1159 GROUP BY f.filter
1160 HAVING MIN(f.active) > " . TEXTFILTER_DISABLED . "
1161 ) parent_states
1162 LEFT JOIN {filter_active} fa ON fa.filter = parent_states.filter AND fa.contextid = $context->id
1163 ORDER BY parent_states.sortorder";
1164 return $DB->get_records_sql($sql);
1168 * This function is for use by the filter administration page.
1170 * @return array 'filtername' => object with fields 'filter' (=filtername), 'active' and 'sortorder'
1172 function filter_get_global_states() {
1173 global $DB;
1174 $context = context_system::instance();
1175 return $DB->get_records('filter_active', array('contextid' => $context->id), 'sortorder', 'filter,active,sortorder');
1179 * Delete all the data in the database relating to a filter, prior to deleting it.
1181 * @param string $filter The filter name, for example 'tex'.
1183 function filter_delete_all_for_filter($filter) {
1184 global $DB;
1186 unset_all_config_for_plugin('filter_' . $filter);
1187 $DB->delete_records('filter_active', array('filter' => $filter));
1188 $DB->delete_records('filter_config', array('filter' => $filter));
1192 * Delete all the data in the database relating to a context, used when contexts are deleted.
1194 * @param integer $contextid The id of the context being deleted.
1196 function filter_delete_all_for_context($contextid) {
1197 global $DB;
1198 $DB->delete_records('filter_active', array('contextid' => $contextid));
1199 $DB->delete_records('filter_config', array('contextid' => $contextid));
1203 * Does this filter have a global settings page in the admin tree?
1204 * (The settings page for a filter must be called, for example, filtersettingfiltertex.)
1206 * @param string $filter The filter name, for example 'tex'.
1207 * @return boolean Whether there should be a 'Settings' link on the config page.
1209 function filter_has_global_settings($filter) {
1210 global $CFG;
1211 $settingspath = $CFG->dirroot . '/filter/' . $filter . '/settings.php';
1212 if (is_readable($settingspath)) {
1213 return true;
1215 $settingspath = $CFG->dirroot . '/filter/' . $filter . '/filtersettings.php';
1216 return is_readable($settingspath);
1220 * Does this filter have local (per-context) settings?
1222 * @param string $filter The filter name, for example 'tex'.
1223 * @return boolean Whether there should be a 'Settings' link on the manage filters in context page.
1225 function filter_has_local_settings($filter) {
1226 global $CFG;
1227 $settingspath = $CFG->dirroot . '/filter/' . $filter . '/filterlocalsettings.php';
1228 return is_readable($settingspath);
1232 * Certain types of context (block and user) may not have local filter settings.
1233 * the function checks a context to see whether it may have local config.
1235 * @param object $context a context.
1236 * @return boolean whether this context may have local filter settings.
1238 function filter_context_may_have_filter_settings($context) {
1239 return $context->contextlevel != CONTEXT_BLOCK && $context->contextlevel != CONTEXT_USER;
1243 * Process phrases intelligently found within a HTML text (such as adding links).
1245 * @staticvar array $usedpharses
1246 * @param string $text the text that we are filtering
1247 * @param array $link_array an array of filterobjects
1248 * @param array $ignoretagsopen an array of opening tags that we should ignore while filtering
1249 * @param array $ignoretagsclose an array of corresponding closing tags
1250 * @param bool $overridedefaultignore True to only use tags provided by arguments
1251 * @return string
1253 function filter_phrases($text, &$link_array, $ignoretagsopen=NULL, $ignoretagsclose=NULL,
1254 $overridedefaultignore=false) {
1256 global $CFG;
1258 static $usedphrases;
1260 $ignoretags = array(); // To store all the enclosig tags to be completely ignored.
1261 $tags = array(); // To store all the simple tags to be ignored.
1263 if (!$overridedefaultignore) {
1264 // A list of open/close tags that we should not replace within
1265 // Extended to include <script>, <textarea>, <select> and <a> tags
1266 // Regular expression allows tags with or without attributes
1267 $filterignoretagsopen = array('<head>' , '<nolink>' , '<span(\s[^>]*?)?class="nolink"(\s[^>]*?)?>',
1268 '<script(\s[^>]*?)?>', '<textarea(\s[^>]*?)?>',
1269 '<select(\s[^>]*?)?>', '<a(\s[^>]*?)?>');
1270 $filterignoretagsclose = array('</head>', '</nolink>', '</span>',
1271 '</script>', '</textarea>', '</select>','</a>');
1272 } else {
1273 // Set an empty default list.
1274 $filterignoretagsopen = array();
1275 $filterignoretagsclose = array();
1278 // Add the user defined ignore tags to the default list.
1279 if ( is_array($ignoretagsopen) ) {
1280 foreach ($ignoretagsopen as $open) {
1281 $filterignoretagsopen[] = $open;
1283 foreach ($ignoretagsclose as $close) {
1284 $filterignoretagsclose[] = $close;
1288 // Invalid prefixes and suffixes for the fullmatch searches
1289 // Every "word" character, but the underscore, is a invalid suffix or prefix.
1290 // (nice to use this because it includes national characters (accents...) as word characters.
1291 $filterinvalidprefixes = '([^\W_])';
1292 $filterinvalidsuffixes = '([^\W_])';
1294 // Double up some magic chars to avoid "accidental matches"
1295 $text = preg_replace('/([#*%])/','\1\1',$text);
1298 //Remove everything enclosed by the ignore tags from $text
1299 filter_save_ignore_tags($text,$filterignoretagsopen,$filterignoretagsclose,$ignoretags);
1301 // Remove tags from $text
1302 filter_save_tags($text,$tags);
1304 // Time to cycle through each phrase to be linked
1305 $size = sizeof($link_array);
1306 for ($n=0; $n < $size; $n++) {
1307 $linkobject =& $link_array[$n];
1309 // Set some defaults if certain properties are missing
1310 // Properties may be missing if the filterobject class has not been used to construct the object
1311 if (empty($linkobject->phrase)) {
1312 continue;
1315 // Avoid integers < 1000 to be linked. See bug 1446.
1316 $intcurrent = intval($linkobject->phrase);
1317 if (!empty($intcurrent) && strval($intcurrent) == $linkobject->phrase && $intcurrent < 1000) {
1318 continue;
1321 // All this work has to be done ONLY it it hasn't been done before
1322 if (!$linkobject->work_calculated) {
1323 if (!isset($linkobject->hreftagbegin) or !isset($linkobject->hreftagend)) {
1324 $linkobject->work_hreftagbegin = '<span class="highlight"';
1325 $linkobject->work_hreftagend = '</span>';
1326 } else {
1327 $linkobject->work_hreftagbegin = $linkobject->hreftagbegin;
1328 $linkobject->work_hreftagend = $linkobject->hreftagend;
1331 // Double up chars to protect true duplicates
1332 // be cleared up before returning to the user.
1333 $linkobject->work_hreftagbegin = preg_replace('/([#*%])/','\1\1',$linkobject->work_hreftagbegin);
1335 if (empty($linkobject->casesensitive)) {
1336 $linkobject->work_casesensitive = false;
1337 } else {
1338 $linkobject->work_casesensitive = true;
1340 if (empty($linkobject->fullmatch)) {
1341 $linkobject->work_fullmatch = false;
1342 } else {
1343 $linkobject->work_fullmatch = true;
1346 // Strip tags out of the phrase
1347 $linkobject->work_phrase = strip_tags($linkobject->phrase);
1349 // Double up chars that might cause a false match -- the duplicates will
1350 // be cleared up before returning to the user.
1351 $linkobject->work_phrase = preg_replace('/([#*%])/','\1\1',$linkobject->work_phrase);
1353 // Set the replacement phrase properly
1354 if ($linkobject->replacementphrase) { //We have specified a replacement phrase
1355 // Strip tags
1356 $linkobject->work_replacementphrase = strip_tags($linkobject->replacementphrase);
1357 } else { //The replacement is the original phrase as matched below
1358 $linkobject->work_replacementphrase = '$1';
1361 // Quote any regular expression characters and the delimiter in the work phrase to be searched
1362 $linkobject->work_phrase = preg_quote($linkobject->work_phrase, '/');
1364 // Work calculated
1365 $linkobject->work_calculated = true;
1369 // If $CFG->filtermatchoneperpage, avoid previously (request) linked phrases
1370 if (!empty($CFG->filtermatchoneperpage)) {
1371 if (!empty($usedphrases) && in_array($linkobject->work_phrase,$usedphrases)) {
1372 continue;
1376 // Regular expression modifiers
1377 $modifiers = ($linkobject->work_casesensitive) ? 's' : 'isu'; // works in unicode mode!
1379 // Do we need to do a fullmatch?
1380 // If yes then go through and remove any non full matching entries
1381 if ($linkobject->work_fullmatch) {
1382 $notfullmatches = array();
1383 $regexp = '/'.$filterinvalidprefixes.'('.$linkobject->work_phrase.')|('.$linkobject->work_phrase.')'.$filterinvalidsuffixes.'/'.$modifiers;
1385 preg_match_all($regexp,$text,$list_of_notfullmatches);
1387 if ($list_of_notfullmatches) {
1388 foreach (array_unique($list_of_notfullmatches[0]) as $key=>$value) {
1389 $notfullmatches['<*'.$key.'*>'] = $value;
1391 if (!empty($notfullmatches)) {
1392 $text = str_replace($notfullmatches,array_keys($notfullmatches),$text);
1397 // Finally we do our highlighting
1398 if (!empty($CFG->filtermatchonepertext) || !empty($CFG->filtermatchoneperpage)) {
1399 $resulttext = preg_replace('/('.$linkobject->work_phrase.')/'.$modifiers,
1400 $linkobject->work_hreftagbegin.
1401 $linkobject->work_replacementphrase.
1402 $linkobject->work_hreftagend, $text, 1);
1403 } else {
1404 $resulttext = preg_replace('/('.$linkobject->work_phrase.')/'.$modifiers,
1405 $linkobject->work_hreftagbegin.
1406 $linkobject->work_replacementphrase.
1407 $linkobject->work_hreftagend, $text);
1411 // If the text has changed we have to look for links again
1412 if ($resulttext != $text) {
1413 // Set $text to $resulttext
1414 $text = $resulttext;
1415 // Remove everything enclosed by the ignore tags from $text
1416 filter_save_ignore_tags($text,$filterignoretagsopen,$filterignoretagsclose,$ignoretags);
1417 // Remove tags from $text
1418 filter_save_tags($text,$tags);
1419 // If $CFG->filtermatchoneperpage, save linked phrases to request
1420 if (!empty($CFG->filtermatchoneperpage)) {
1421 $usedphrases[] = $linkobject->work_phrase;
1426 // Replace the not full matches before cycling to next link object
1427 if (!empty($notfullmatches)) {
1428 $text = str_replace(array_keys($notfullmatches),$notfullmatches,$text);
1429 unset($notfullmatches);
1433 // Rebuild the text with all the excluded areas
1435 if (!empty($tags)) {
1436 $text = str_replace(array_keys($tags), $tags, $text);
1439 if (!empty($ignoretags)) {
1440 $ignoretags = array_reverse($ignoretags); // Reversed so "progressive" str_replace() will solve some nesting problems.
1441 $text = str_replace(array_keys($ignoretags),$ignoretags,$text);
1444 // Remove the protective doubleups
1445 $text = preg_replace('/([#*%])(\1)/','\1',$text);
1447 // Add missing javascript for popus
1448 $text = filter_add_javascript($text);
1451 return $text;
1455 * Remove duplicate from a list of {@link filterobject}.
1457 * @param filterobject[] $linkarray a list of filterobject.
1458 * @return filterobject[] the same list, but with dupicates removed.
1460 function filter_remove_duplicates($linkarray) {
1462 $concepts = array(); // keep a record of concepts as we cycle through
1463 $lconcepts = array(); // a lower case version for case insensitive
1465 $cleanlinks = array();
1467 foreach ($linkarray as $key=>$filterobject) {
1468 if ($filterobject->casesensitive) {
1469 $exists = in_array($filterobject->phrase, $concepts);
1470 } else {
1471 $exists = in_array(core_text::strtolower($filterobject->phrase), $lconcepts);
1474 if (!$exists) {
1475 $cleanlinks[] = $filterobject;
1476 $concepts[] = $filterobject->phrase;
1477 $lconcepts[] = core_text::strtolower($filterobject->phrase);
1481 return $cleanlinks;
1485 * Extract open/lose tags and their contents to avoid being processed by filters.
1486 * Useful to extract pieces of code like <a>...</a> tags. It returns the text
1487 * converted with some <#xTEXTFILTER_EXCL_SEPARATORx#> codes replacing the extracted text. Such extracted
1488 * texts are returned in the ignoretags array (as values), with codes as keys.
1490 * @param string $text the text that we are filtering (in/out)
1491 * @param array $filterignoretagsopen an array of open tags to start searching
1492 * @param array $filterignoretagsclose an array of close tags to end searching
1493 * @param array $ignoretags an array of saved strings useful to rebuild the original text (in/out)
1495 function filter_save_ignore_tags(&$text, $filterignoretagsopen, $filterignoretagsclose, &$ignoretags) {
1497 // Remove everything enclosed by the ignore tags from $text
1498 foreach ($filterignoretagsopen as $ikey=>$opentag) {
1499 $closetag = $filterignoretagsclose[$ikey];
1500 // form regular expression
1501 $opentag = str_replace('/','\/',$opentag); // delimit forward slashes
1502 $closetag = str_replace('/','\/',$closetag); // delimit forward slashes
1503 $pregexp = '/'.$opentag.'(.*?)'.$closetag.'/is';
1505 preg_match_all($pregexp, $text, $list_of_ignores);
1506 foreach (array_unique($list_of_ignores[0]) as $key=>$value) {
1507 $prefix = (string)(count($ignoretags) + 1);
1508 $ignoretags['<#'.$prefix.TEXTFILTER_EXCL_SEPARATOR.$key.'#>'] = $value;
1510 if (!empty($ignoretags)) {
1511 $text = str_replace($ignoretags,array_keys($ignoretags),$text);
1517 * Extract tags (any text enclosed by < and > to avoid being processed by filters.
1518 * It returns the text converted with some <%xTEXTFILTER_EXCL_SEPARATORx%> codes replacing the extracted text. Such extracted
1519 * texts are returned in the tags array (as values), with codes as keys.
1521 * @param string $text the text that we are filtering (in/out)
1522 * @param array $tags an array of saved strings useful to rebuild the original text (in/out)
1524 function filter_save_tags(&$text, &$tags) {
1526 preg_match_all('/<([^#%*].*?)>/is',$text,$list_of_newtags);
1527 foreach (array_unique($list_of_newtags[0]) as $ntkey=>$value) {
1528 $prefix = (string)(count($tags) + 1);
1529 $tags['<%'.$prefix.TEXTFILTER_EXCL_SEPARATOR.$ntkey.'%>'] = $value;
1531 if (!empty($tags)) {
1532 $text = str_replace($tags,array_keys($tags),$text);
1537 * Add missing openpopup javascript to HTML files.
1539 * @param string $text
1540 * @return string
1542 function filter_add_javascript($text) {
1543 global $CFG;
1545 if (stripos($text, '</html>') === FALSE) {
1546 return $text; // This is not a html file.
1548 if (strpos($text, 'onclick="return openpopup') === FALSE) {
1549 return $text; // No popup - no need to add javascript.
1551 $js ="
1552 <script type=\"text/javascript\">
1553 <!--
1554 function openpopup(url,name,options,fullscreen) {
1555 fullurl = \"".$CFG->wwwroot."\" + url;
1556 windowobj = window.open(fullurl,name,options);
1557 if (fullscreen) {
1558 windowobj.moveTo(0,0);
1559 windowobj.resizeTo(screen.availWidth,screen.availHeight);
1561 windowobj.focus();
1562 return false;
1564 // -->
1565 </script>";
1566 if (stripos($text, '</head>') !== FALSE) {
1567 // Try to add it into the head element.
1568 $text = str_ireplace('</head>', $js.'</head>', $text);
1569 return $text;
1572 // Last chance - try adding head element.
1573 return preg_replace("/<html.*?>/is", "\\0<head>".$js.'</head>', $text);