MDL-42243 fix filter settings regression and support standard settings.php
[moodle.git] / lib / filterlib.php
bloba93a74b87b17fb345d640427dc70a895cb10cced
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_filter
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 * @package core_filter
52 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
53 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
55 class filter_manager {
56 /**
57 * @var array This list of active filters, by context, for filtering content.
58 * An array contextid => array of filter objects.
60 protected $textfilters = array();
62 /**
63 * @var array This list of active filters, by context, for filtering strings.
64 * An array contextid => array of filter objects.
66 protected $stringfilters = array();
68 /** @var array Exploded version of $CFG->stringfilters. */
69 protected $stringfilternames = array();
71 /** @var object Holds the singleton instance. */
72 protected static $singletoninstance;
74 protected function __construct() {
75 $this->stringfilternames = filter_get_string_filters();
78 /**
79 * @return filter_manager the singleton instance.
81 public static function instance() {
82 global $CFG;
83 if (is_null(self::$singletoninstance)) {
84 if (!empty($CFG->perfdebug)) {
85 self::$singletoninstance = new performance_measuring_filter_manager();
86 } else {
87 self::$singletoninstance = new self();
90 return self::$singletoninstance;
93 /**
94 * Resets the caches, usually to be called between unit tests
96 public static function reset_caches() {
97 if (self::$singletoninstance) {
98 self::$singletoninstance->unload_all_filters();
100 self::$singletoninstance = null;
104 * Unloads all filters and other cached information
106 protected function unload_all_filters() {
107 $this->textfilters = array();
108 $this->stringfilters = array();
109 $this->stringfilternames = array();
113 * Load all the filters required by this context.
115 * @param object $context
117 protected function load_filters($context) {
118 $filters = filter_get_active_in_context($context);
119 $this->textfilters[$context->id] = array();
120 $this->stringfilters[$context->id] = array();
121 foreach ($filters as $filtername => $localconfig) {
122 $filter = $this->make_filter_object($filtername, $context, $localconfig);
123 if (is_null($filter)) {
124 continue;
126 $this->textfilters[$context->id][] = $filter;
127 if (in_array($filtername, $this->stringfilternames)) {
128 $this->stringfilters[$context->id][] = $filter;
134 * Factory method for creating a filter.
136 * @param string $filtername The filter name, for example 'tex'.
137 * @param context $context context object.
138 * @param array $localconfig array of local configuration variables for this filter.
139 * @return moodle_text_filter The filter, or null, if this type of filter is
140 * not recognised or could not be created.
142 protected function make_filter_object($filtername, $context, $localconfig) {
143 global $CFG;
144 $path = $CFG->dirroot .'/filter/'. $filtername .'/filter.php';
145 if (!is_readable($path)) {
146 return null;
148 include_once($path);
150 $filterclassname = 'filter_' . $filtername;
151 if (class_exists($filterclassname)) {
152 return new $filterclassname($context, $localconfig);
155 return null;
159 * @todo Document this function
160 * @param string $text
161 * @param array $filterchain
162 * @param array $options options passed to the filters
163 * @return string $text
165 protected function apply_filter_chain($text, $filterchain, array $options = array()) {
166 foreach ($filterchain as $filter) {
167 $text = $filter->filter($text, $options);
169 return $text;
173 * @todo Document this function
174 * @param object $context
175 * @return object A text filter
177 protected function get_text_filters($context) {
178 if (!isset($this->textfilters[$context->id])) {
179 $this->load_filters($context);
181 return $this->textfilters[$context->id];
185 * @todo Document this function
186 * @param object $context
187 * @return object A string filter
189 protected function get_string_filters($context) {
190 if (!isset($this->stringfilters[$context->id])) {
191 $this->load_filters($context);
193 return $this->stringfilters[$context->id];
197 * Filter some text
199 * @param string $text The text to filter
200 * @param object $context
201 * @param array $options options passed to the filters
202 * @return string resulting text
204 public function filter_text($text, $context, array $options = array()) {
205 $text = $this->apply_filter_chain($text, $this->get_text_filters($context), $options);
206 // <nolink> tags removed for XHTML compatibility
207 $text = str_replace(array('<nolink>', '</nolink>'), '', $text);
208 return $text;
212 * Filter a piece of string
214 * @param string $string The text to filter
215 * @param context $context
216 * @return string resulting string
218 public function filter_string($string, $context) {
219 return $this->apply_filter_chain($string, $this->get_string_filters($context));
223 * @todo Document this function
224 * @param context $context
225 * @return object A string filter
227 public function text_filtering_hash($context) {
228 $filters = $this->get_text_filters($context);
229 $hashes = array();
230 foreach ($filters as $filter) {
231 $hashes[] = $filter->hash();
233 return implode('-', $hashes);
237 * Setup page with filters requirements and other prepare stuff.
239 * This method is used by {@see format_text()} and {@see format_string()}
240 * in order to allow filters to setup any page requirement (js, css...)
241 * or perform any action needed to get them prepared before filtering itself
242 * happens by calling to each every active setup() method.
244 * Note it's executed for each piece of text filtered, so filter implementations
245 * are responsible of controlling the cardinality of the executions that may
246 * be different depending of the stuff to prepare.
248 * @param moodle_page $page the page we are going to add requirements to.
249 * @param context $context the context which contents are going to be filtered.
250 * @since 2.3
252 public function setup_page_for_filters($page, $context) {
253 $filters = $this->get_text_filters($context);
254 foreach ($filters as $filter) {
255 $filter->setup($page, $context);
261 * Filter manager subclass that does nothing. Having this simplifies the logic
262 * of format_text, etc.
264 * @todo Document this class
266 * @package core_filter
267 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
268 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
270 class null_filter_manager {
272 * @return string
274 public function filter_text($text, $context, $options) {
275 return $text;
279 * @return string
281 public function filter_string($string, $context) {
282 return $string;
286 * @return string
288 public function text_filtering_hash() {
289 return '';
294 * Filter manager subclass that tacks how much work it does.
296 * @todo Document this class
298 * @package core_filter
299 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
300 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
302 class performance_measuring_filter_manager extends filter_manager {
303 /** @var int */
304 protected $filterscreated = 0;
305 protected $textsfiltered = 0;
306 protected $stringsfiltered = 0;
309 * Unloads all filters and other cached information
311 protected function unload_all_filters() {
312 parent::unload_all_filters();
313 $this->filterscreated = 0;
314 $this->textsfiltered = 0;
315 $this->stringsfiltered = 0;
319 * @param string $filtername
320 * @param object $context
321 * @param mixed $localconfig
322 * @return mixed
324 protected function make_filter_object($filtername, $context, $localconfig) {
325 $this->filterscreated++;
326 return parent::make_filter_object($filtername, $context, $localconfig);
330 * @param string $text
331 * @param object $context
332 * @param array $options options passed to the filters
333 * @return mixed
335 public function filter_text($text, $context, array $options = array()) {
336 $this->textsfiltered++;
337 return parent::filter_text($text, $context, $options);
341 * @param string $string
342 * @param object $context
343 * @return mixed
345 public function filter_string($string, $context) {
346 $this->stringsfiltered++;
347 return parent::filter_string($string, $context);
351 * @return array
353 public function get_performance_summary() {
354 return array(array(
355 'contextswithfilters' => count($this->textfilters),
356 'filterscreated' => $this->filterscreated,
357 'textsfiltered' => $this->textsfiltered,
358 'stringsfiltered' => $this->stringsfiltered,
359 ), array(
360 'contextswithfilters' => 'Contexts for which filters were loaded',
361 'filterscreated' => 'Filters created',
362 'textsfiltered' => 'Pieces of content filtered',
363 'stringsfiltered' => 'Strings filtered',
369 * Base class for text filters. You just need to override this class and
370 * implement the filter method.
372 * @package core_filter
373 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
374 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
376 abstract class moodle_text_filter {
377 /** @var object The context we are in. */
378 protected $context;
379 /** @var array Any local configuration for this filter in this context. */
380 protected $localconfig;
383 * Set any context-specific configuration for this filter.
385 * @param context $context The current context.
386 * @param array $localconfig Any context-specific configuration for this filter.
388 public function __construct($context, array $localconfig) {
389 $this->context = $context;
390 $this->localconfig = $localconfig;
394 * @return string The class name of the current class
396 public function hash() {
397 return __CLASS__;
401 * Setup page with filter requirements and other prepare stuff.
403 * Override this method if the filter needs to setup page
404 * requirements or needs other stuff to be executed.
406 * Note this method is invoked from {@see setup_page_for_filters()}
407 * for each piece of text being filtered, so it is responsible
408 * for controlling its own execution cardinality.
410 * @param moodle_page $page the page we are going to add requirements to.
411 * @param context $context the context which contents are going to be filtered.
412 * @since 2.3
414 public function setup($page, $context) {
415 // Override me, if needed.
419 * Override this function to actually implement the filtering.
421 * @param $text some HTML content.
422 * @param array $options options passed to the filters
423 * @return the HTML content after the filtering has been applied.
425 public abstract function filter($text, array $options = array());
429 * This is just a little object to define a phrase and some instructions
430 * for how to process it. Filters can create an array of these to pass
431 * to the filter_phrases function below.
433 * @package core
434 * @subpackage filter
435 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
436 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
438 class filterobject {
439 /** @var string */
440 var $phrase;
441 var $hreftagbegin;
442 var $hreftagend;
443 /** @var bool */
444 var $casesensitive;
445 var $fullmatch;
446 /** @var mixed */
447 var $replacementphrase;
448 var $work_phrase;
449 var $work_hreftagbegin;
450 var $work_hreftagend;
451 var $work_casesensitive;
452 var $work_fullmatch;
453 var $work_replacementphrase;
454 /** @var bool */
455 var $work_calculated;
458 * A constructor just because I like constructing
460 * @param string $phrase
461 * @param string $hreftagbegin
462 * @param string $hreftagend
463 * @param bool $casesensitive
464 * @param bool $fullmatch
465 * @param mixed $replacementphrase
467 function filterobject($phrase, $hreftagbegin = '<span class="highlight">',
468 $hreftagend = '</span>',
469 $casesensitive = false,
470 $fullmatch = false,
471 $replacementphrase = NULL) {
473 $this->phrase = $phrase;
474 $this->hreftagbegin = $hreftagbegin;
475 $this->hreftagend = $hreftagend;
476 $this->casesensitive = $casesensitive;
477 $this->fullmatch = $fullmatch;
478 $this->replacementphrase= $replacementphrase;
479 $this->work_calculated = false;
485 * Look up the name of this filter
487 * @param string $filter the filter name
488 * @return string the human-readable name for this filter.
490 function filter_get_name($filter) {
491 if (strpos($filter, 'filter/') === 0) {
492 debugging("Old '$filter'' parameter used in filter_get_name()");
493 $filter = substr($filter, 7);
494 } else if (strpos($filter, '/') !== false) {
495 throw new coding_exception('Unknown filter type ' . $filter);
498 if (get_string_manager()->string_exists('filtername', 'filter_' . $filter)) {
499 return get_string('filtername', 'filter_' . $filter);
500 } else {
501 return $filter;
506 * Get the names of all the filters installed in this Moodle.
508 * @return array path => filter name from the appropriate lang file. e.g.
509 * array('tex' => 'TeX Notation');
510 * sorted in alphabetical order of name.
512 function filter_get_all_installed() {
513 global $CFG;
515 $filternames = array();
516 foreach (core_component::get_plugin_list('filter') as $filter => $fulldir) {
517 if (is_readable("$fulldir/filter.php")) {
518 $filternames[$filter] = filter_get_name($filter);
521 core_collator::asort($filternames);
522 return $filternames;
526 * Set the global activated state for a text filter.
528 * @param string $filtername The filter name, for example 'tex'.
529 * @param int $state One of the values TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_DISABLED.
530 * @param int $move 1 means up, 0 means the same, -1 means down
532 function filter_set_global_state($filtername, $state, $move = 0) {
533 global $DB;
535 // Check requested state is valid.
536 if (!in_array($state, array(TEXTFILTER_ON, TEXTFILTER_OFF, TEXTFILTER_DISABLED))) {
537 throw new coding_exception("Illegal option '$state' passed to filter_set_global_state. " .
538 "Must be one of TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_DISABLED.");
541 if ($move > 0) {
542 $move = 1;
543 } else if ($move < 0) {
544 $move = -1;
547 if (strpos($filtername, 'filter/') === 0) {
548 //debugging("Old filtername '$filtername' parameter used in filter_set_global_state()", DEBUG_DEVELOPER);
549 $filtername = substr($filtername, 7);
550 } else if (strpos($filtername, '/') !== false) {
551 throw new coding_exception("Invalid filter name '$filtername' used in filter_set_global_state()");
554 $transaction = $DB->start_delegated_transaction();
556 $syscontext = context_system::instance();
557 $filters = $DB->get_records('filter_active', array('contextid' => $syscontext->id), 'sortorder ASC');
559 $on = array();
560 $off = array();
562 foreach($filters as $f) {
563 if ($f->active == TEXTFILTER_DISABLED) {
564 $off[$f->filter] = $f;
565 } else {
566 $on[$f->filter] = $f;
570 // Update the state or add new record.
571 if (isset($on[$filtername])) {
572 $filter = $on[$filtername];
573 if ($filter->active != $state) {
574 add_to_config_log('filter_active', $filter->active, $state, $filtername);
576 $filter->active = $state;
577 $DB->update_record('filter_active', $filter);
578 if ($filter->active == TEXTFILTER_DISABLED) {
579 unset($on[$filtername]);
580 $off = array($filter->filter => $filter) + $off;
585 } else if (isset($off[$filtername])) {
586 $filter = $off[$filtername];
587 if ($filter->active != $state) {
588 add_to_config_log('filter_active', $filter->active, $state, $filtername);
590 $filter->active = $state;
591 $DB->update_record('filter_active', $filter);
592 if ($filter->active != TEXTFILTER_DISABLED) {
593 unset($off[$filtername]);
594 $on[$filter->filter] = $filter;
598 } else {
599 add_to_config_log('filter_active', '', $state, $filtername);
601 $filter = new stdClass();
602 $filter->filter = $filtername;
603 $filter->contextid = $syscontext->id;
604 $filter->active = $state;
605 $filter->sortorder = 99999;
606 $filter->id = $DB->insert_record('filter_active', $filter);
608 $filters[$filter->id] = $filter;
609 if ($state == TEXTFILTER_DISABLED) {
610 $off[$filter->filter] = $filter;
611 } else {
612 $on[$filter->filter] = $filter;
616 // Move only active.
617 if ($move != 0 and isset($on[$filter->filter])) {
618 $i = 1;
619 foreach ($on as $f) {
620 $f->newsortorder = $i;
621 $i++;
624 $filter->newsortorder = $filter->newsortorder + $move;
626 foreach ($on as $f) {
627 if ($f->id == $filter->id) {
628 continue;
630 if ($f->newsortorder == $filter->newsortorder) {
631 if ($move == 1) {
632 $f->newsortorder = $f->newsortorder - 1;
633 } else {
634 $f->newsortorder = $f->newsortorder + 1;
639 core_collator::asort_objects_by_property($on, 'newsortorder', core_collator::SORT_NUMERIC);
642 // Inactive are sorted by filter name.
643 core_collator::asort_objects_by_property($off, 'filter', core_collator::SORT_NATURAL);
645 // Update records if necessary.
646 $i = 1;
647 foreach ($on as $f) {
648 if ($f->sortorder != $i) {
649 $DB->set_field('filter_active', 'sortorder', $i, array('id'=>$f->id));
651 $i++;
653 foreach ($off as $f) {
654 if ($f->sortorder != $i) {
655 $DB->set_field('filter_active', 'sortorder', $i, array('id'=>$f->id));
657 $i++;
660 $transaction->allow_commit();
664 * @param string $filtername The filter name, for example 'tex'.
665 * @return boolean is this filter allowed to be used on this site. That is, the
666 * admin has set the global 'active' setting to On, or Off, but available.
668 function filter_is_enabled($filtername) {
669 if (strpos($filtername, 'filter/') === 0) {
670 //debugging("Old filtername '$filtername' parameter used in filter_is_enabled()", DEBUG_DEVELOPER);
671 $filtername = substr($filtername, 7);
672 } else if (strpos($filtername, '/') !== false) {
673 throw new coding_exception("Invalid filter name '$filtername' used in filter_is_enabled()");
675 return array_key_exists($filtername, filter_get_globally_enabled());
679 * Return a list of all the filters that may be in use somewhere.
681 * @staticvar array $enabledfilters
682 * @return array where the keys and values are both the filter name, like 'tex'.
684 function filter_get_globally_enabled() {
685 static $enabledfilters = null;
686 if (is_null($enabledfilters)) {
687 $filters = filter_get_global_states();
688 $enabledfilters = array();
689 foreach ($filters as $filter => $filerinfo) {
690 if ($filerinfo->active != TEXTFILTER_DISABLED) {
691 $enabledfilters[$filter] = $filter;
695 return $enabledfilters;
699 * Return the names of the filters that should also be applied to strings
700 * (when they are enabled).
702 * @return array where the keys and values are both the filter name, like 'tex'.
704 function filter_get_string_filters() {
705 global $CFG;
706 $stringfilters = array();
707 if (!empty($CFG->filterall) && !empty($CFG->stringfilters)) {
708 $stringfilters = explode(',', $CFG->stringfilters);
709 $stringfilters = array_combine($stringfilters, $stringfilters);
711 return $stringfilters;
715 * Sets whether a particular active filter should be applied to all strings by
716 * format_string, or just used by format_text.
718 * @param string $filter The filter name, for example 'tex'.
719 * @param boolean $applytostrings if true, this filter will apply to format_string
720 * and format_text, when it is enabled.
722 function filter_set_applies_to_strings($filter, $applytostrings) {
723 $stringfilters = filter_get_string_filters();
724 $numstringfilters = count($stringfilters);
725 if ($applytostrings) {
726 $stringfilters[$filter] = $filter;
727 } else {
728 unset($stringfilters[$filter]);
730 if (count($stringfilters) != $numstringfilters) {
731 set_config('stringfilters', implode(',', $stringfilters));
732 set_config('filterall', !empty($stringfilters));
737 * Set the local activated state for a text filter.
739 * @param string $filter The filter name, for example 'tex'.
740 * @param integer $contextid The id of the context to get the local config for.
741 * @param integer $state One of the values TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_INHERIT.
742 * @return void
744 function filter_set_local_state($filter, $contextid, $state) {
745 global $DB;
747 // Check requested state is valid.
748 if (!in_array($state, array(TEXTFILTER_ON, TEXTFILTER_OFF, TEXTFILTER_INHERIT))) {
749 throw new coding_exception("Illegal option '$state' passed to filter_set_local_state. " .
750 "Must be one of TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_INHERIT.");
753 if ($contextid == context_system::instance()->id) {
754 throw new coding_exception('You cannot use filter_set_local_state ' .
755 'with $contextid equal to the system context id.');
758 if ($state == TEXTFILTER_INHERIT) {
759 $DB->delete_records('filter_active', array('filter' => $filter, 'contextid' => $contextid));
760 return;
763 $rec = $DB->get_record('filter_active', array('filter' => $filter, 'contextid' => $contextid));
764 $insert = false;
765 if (empty($rec)) {
766 $insert = true;
767 $rec = new stdClass;
768 $rec->filter = $filter;
769 $rec->contextid = $contextid;
772 $rec->active = $state;
774 if ($insert) {
775 $DB->insert_record('filter_active', $rec);
776 } else {
777 $DB->update_record('filter_active', $rec);
782 * Set a particular local config variable for a filter in a context.
784 * @param string $filter The filter name, for example 'tex'.
785 * @param integer $contextid The id of the context to get the local config for.
786 * @param string $name the setting name.
787 * @param string $value the corresponding value.
789 function filter_set_local_config($filter, $contextid, $name, $value) {
790 global $DB;
791 $rec = $DB->get_record('filter_config', array('filter' => $filter, 'contextid' => $contextid, 'name' => $name));
792 $insert = false;
793 if (empty($rec)) {
794 $insert = true;
795 $rec = new stdClass;
796 $rec->filter = $filter;
797 $rec->contextid = $contextid;
798 $rec->name = $name;
801 $rec->value = $value;
803 if ($insert) {
804 $DB->insert_record('filter_config', $rec);
805 } else {
806 $DB->update_record('filter_config', $rec);
811 * Remove a particular local config variable for a filter in a context.
813 * @param string $filter The filter name, for example 'tex'.
814 * @param integer $contextid The id of the context to get the local config for.
815 * @param string $name the setting name.
817 function filter_unset_local_config($filter, $contextid, $name) {
818 global $DB;
819 $DB->delete_records('filter_config', array('filter' => $filter, 'contextid' => $contextid, 'name' => $name));
823 * Get local config variables for a filter in a context. Normally (when your
824 * filter is running) you don't need to call this, becuase the config is fetched
825 * for you automatically. You only need this, for example, when you are getting
826 * the config so you can show the user an editing from.
828 * @param string $filter The filter name, for example 'tex'.
829 * @param integer $contextid The ID of the context to get the local config for.
830 * @return array of name => value pairs.
832 function filter_get_local_config($filter, $contextid) {
833 global $DB;
834 return $DB->get_records_menu('filter_config', array('filter' => $filter, 'contextid' => $contextid), '', 'name,value');
838 * This function is for use by backup. Gets all the filter information specific
839 * to one context.
841 * @param int $contextid
842 * @return array Array with two elements. The first element is an array of objects with
843 * fields filter and active. These come from the filter_active table. The
844 * second element is an array of objects with fields filter, name and value
845 * from the filter_config table.
847 function filter_get_all_local_settings($contextid) {
848 global $DB;
849 return array(
850 $DB->get_records('filter_active', array('contextid' => $contextid), 'filter', 'filter,active'),
851 $DB->get_records('filter_config', array('contextid' => $contextid), 'filter,name', 'filter,name,value'),
856 * Get the list of active filters, in the order that they should be used
857 * for a particular context, along with any local configuration variables.
859 * @param context $context a context
860 * @return array an array where the keys are the filter names, for example
861 * 'tex' and the values are any local
862 * configuration for that filter, as an array of name => value pairs
863 * from the filter_config table. In a lot of cases, this will be an
864 * empty array. So, an example return value for this function might be
865 * array(tex' => array())
867 function filter_get_active_in_context($context) {
868 global $DB, $FILTERLIB_PRIVATE;
870 if (!isset($FILTERLIB_PRIVATE)) {
871 $FILTERLIB_PRIVATE = new stdClass();
874 // Use cache (this is a within-request cache only) if available. See
875 // function filter_preload_activities.
876 if (isset($FILTERLIB_PRIVATE->active) &&
877 array_key_exists($context->id, $FILTERLIB_PRIVATE->active)) {
878 return $FILTERLIB_PRIVATE->active[$context->id];
881 $contextids = str_replace('/', ',', trim($context->path, '/'));
883 // The following SQL is tricky. It is explained on
884 // http://docs.moodle.org/dev/Filter_enable/disable_by_context
885 $sql = "SELECT active.filter, fc.name, fc.value
886 FROM (SELECT f.filter, MAX(f.sortorder) AS sortorder
887 FROM {filter_active} f
888 JOIN {context} ctx ON f.contextid = ctx.id
889 WHERE ctx.id IN ($contextids)
890 GROUP BY filter
891 HAVING MAX(f.active * ctx.depth) > -MIN(f.active * ctx.depth)
892 ) active
893 LEFT JOIN {filter_config} fc ON fc.filter = active.filter AND fc.contextid = $context->id
894 ORDER BY active.sortorder";
895 $rs = $DB->get_recordset_sql($sql);
897 // Massage the data into the specified format to return.
898 $filters = array();
899 foreach ($rs as $row) {
900 if (!isset($filters[$row->filter])) {
901 $filters[$row->filter] = array();
903 if (!is_null($row->name)) {
904 $filters[$row->filter][$row->name] = $row->value;
908 $rs->close();
910 return $filters;
914 * Preloads the list of active filters for all activities (modules) on the course
915 * using two database queries.
917 * @param course_modinfo $modinfo Course object from get_fast_modinfo
919 function filter_preload_activities(course_modinfo $modinfo) {
920 global $DB, $FILTERLIB_PRIVATE;
922 if (!isset($FILTERLIB_PRIVATE)) {
923 $FILTERLIB_PRIVATE = new stdClass();
926 // Don't repeat preload
927 if (!isset($FILTERLIB_PRIVATE->preloaded)) {
928 $FILTERLIB_PRIVATE->preloaded = array();
930 if (!empty($FILTERLIB_PRIVATE->preloaded[$modinfo->get_course_id()])) {
931 return;
933 $FILTERLIB_PRIVATE->preloaded[$modinfo->get_course_id()] = true;
935 // Get contexts for all CMs
936 $cmcontexts = array();
937 $cmcontextids = array();
938 foreach ($modinfo->get_cms() as $cm) {
939 $modulecontext = context_module::instance($cm->id);
940 $cmcontextids[] = $modulecontext->id;
941 $cmcontexts[] = $modulecontext;
944 // Get course context and all other parents...
945 $coursecontext = context_course::instance($modinfo->get_course_id());
946 $parentcontextids = explode('/', substr($coursecontext->path, 1));
947 $allcontextids = array_merge($cmcontextids, $parentcontextids);
949 // Get all filter_active rows relating to all these contexts
950 list ($sql, $params) = $DB->get_in_or_equal($allcontextids);
951 $filteractives = $DB->get_records_select('filter_active', "contextid $sql", $params);
953 // Get all filter_config only for the cm contexts
954 list ($sql, $params) = $DB->get_in_or_equal($cmcontextids);
955 $filterconfigs = $DB->get_records_select('filter_config', "contextid $sql", $params);
957 // Note: I was a bit surprised that filter_config only works for the
958 // most specific context (i.e. it does not need to be checked for course
959 // context if we only care about CMs) however basede on code in
960 // filter_get_active_in_context, this does seem to be correct.
962 // Build course default active list. Initially this will be an array of
963 // filter name => active score (where an active score >0 means it's active)
964 $courseactive = array();
966 // Also build list of filter_active rows below course level, by contextid
967 $remainingactives = array();
969 // Array lists filters that are banned at top level
970 $banned = array();
972 // Add any active filters in parent contexts to the array
973 foreach ($filteractives as $row) {
974 $depth = array_search($row->contextid, $parentcontextids);
975 if ($depth !== false) {
976 // Find entry
977 if (!array_key_exists($row->filter, $courseactive)) {
978 $courseactive[$row->filter] = 0;
980 // This maths copes with reading rows in any order. Turning on/off
981 // at site level counts 1, at next level down 4, at next level 9,
982 // then 16, etc. This means the deepest level always wins, except
983 // against the -9999 at top level.
984 $courseactive[$row->filter] +=
985 ($depth + 1) * ($depth + 1) * $row->active;
987 if ($row->active == TEXTFILTER_DISABLED) {
988 $banned[$row->filter] = true;
990 } else {
991 // Build list of other rows indexed by contextid
992 if (!array_key_exists($row->contextid, $remainingactives)) {
993 $remainingactives[$row->contextid] = array();
995 $remainingactives[$row->contextid][] = $row;
999 // Chuck away the ones that aren't active.
1000 foreach ($courseactive as $filter=>$score) {
1001 if ($score <= 0) {
1002 unset($courseactive[$filter]);
1003 } else {
1004 $courseactive[$filter] = array();
1008 // Loop through the contexts to reconstruct filter_active lists for each
1009 // cm on the course.
1010 if (!isset($FILTERLIB_PRIVATE->active)) {
1011 $FILTERLIB_PRIVATE->active = array();
1013 foreach ($cmcontextids as $contextid) {
1014 // Copy course list
1015 $FILTERLIB_PRIVATE->active[$contextid] = $courseactive;
1017 // Are there any changes to the active list?
1018 if (array_key_exists($contextid, $remainingactives)) {
1019 foreach ($remainingactives[$contextid] as $row) {
1020 if ($row->active > 0 && empty($banned[$row->filter])) {
1021 // If it's marked active for specific context, add entry
1022 // (doesn't matter if one exists already).
1023 $FILTERLIB_PRIVATE->active[$contextid][$row->filter] = array();
1024 } else {
1025 // If it's marked inactive, remove entry (doesn't matter
1026 // if it doesn't exist).
1027 unset($FILTERLIB_PRIVATE->active[$contextid][$row->filter]);
1033 // Process all config rows to add config data to these entries.
1034 foreach ($filterconfigs as $row) {
1035 if (isset($FILTERLIB_PRIVATE->active[$row->contextid][$row->filter])) {
1036 $FILTERLIB_PRIVATE->active[$row->contextid][$row->filter][$row->name] = $row->value;
1042 * List all of the filters that are available in this context, and what the
1043 * local and inherited states of that filter are.
1045 * @param context $context a context that is not the system context.
1046 * @return array an array with filter names, for example 'tex'
1047 * as keys. and and the values are objects with fields:
1048 * ->filter filter name, same as the key.
1049 * ->localstate TEXTFILTER_ON/OFF/INHERIT
1050 * ->inheritedstate TEXTFILTER_ON/OFF - the state that will be used if localstate is set to TEXTFILTER_INHERIT.
1052 function filter_get_available_in_context($context) {
1053 global $DB;
1055 // The complex logic is working out the active state in the parent context,
1056 // so strip the current context from the list.
1057 $contextids = explode('/', trim($context->path, '/'));
1058 array_pop($contextids);
1059 $contextids = implode(',', $contextids);
1060 if (empty($contextids)) {
1061 throw new coding_exception('filter_get_available_in_context cannot be called with the system context.');
1064 // The following SQL is tricky, in the same way at the SQL in filter_get_active_in_context.
1065 $sql = "SELECT parent_states.filter,
1066 CASE WHEN fa.active IS NULL THEN " . TEXTFILTER_INHERIT . "
1067 ELSE fa.active END AS localstate,
1068 parent_states.inheritedstate
1069 FROM (SELECT f.filter, MAX(f.sortorder) AS sortorder,
1070 CASE WHEN MAX(f.active * ctx.depth) > -MIN(f.active * ctx.depth) THEN " . TEXTFILTER_ON . "
1071 ELSE " . TEXTFILTER_OFF . " END AS inheritedstate
1072 FROM {filter_active} f
1073 JOIN {context} ctx ON f.contextid = ctx.id
1074 WHERE ctx.id IN ($contextids)
1075 GROUP BY f.filter
1076 HAVING MIN(f.active) > " . TEXTFILTER_DISABLED . "
1077 ) parent_states
1078 LEFT JOIN {filter_active} fa ON fa.filter = parent_states.filter AND fa.contextid = $context->id
1079 ORDER BY parent_states.sortorder";
1080 return $DB->get_records_sql($sql);
1084 * This function is for use by the filter administration page.
1086 * @return array 'filtername' => object with fields 'filter' (=filtername), 'active' and 'sortorder'
1088 function filter_get_global_states() {
1089 global $DB;
1090 $context = context_system::instance();
1091 return $DB->get_records('filter_active', array('contextid' => $context->id), 'sortorder', 'filter,active,sortorder');
1095 * Delete all the data in the database relating to a filter, prior to deleting it.
1097 * @param string $filter The filter name, for example 'tex'.
1099 function filter_delete_all_for_filter($filter) {
1100 global $DB;
1102 unset_all_config_for_plugin('filter_' . $filter);
1103 $DB->delete_records('filter_active', array('filter' => $filter));
1104 $DB->delete_records('filter_config', array('filter' => $filter));
1108 * Delete all the data in the database relating to a context, used when contexts are deleted.
1110 * @param integer $contextid The id of the context being deleted.
1112 function filter_delete_all_for_context($contextid) {
1113 global $DB;
1114 $DB->delete_records('filter_active', array('contextid' => $contextid));
1115 $DB->delete_records('filter_config', array('contextid' => $contextid));
1119 * Does this filter have a global settings page in the admin tree?
1120 * (The settings page for a filter must be called, for example, filtersettingfiltertex.)
1122 * @param string $filter The filter name, for example 'tex'.
1123 * @return boolean Whether there should be a 'Settings' link on the config page.
1125 function filter_has_global_settings($filter) {
1126 global $CFG;
1127 $settingspath = $CFG->dirroot . '/filter/' . $filter . '/settings.php';
1128 if (is_readable($settingspath)) {
1129 return true;
1131 $settingspath = $CFG->dirroot . '/filter/' . $filter . '/filtersettings.php';
1132 return is_readable($settingspath);
1136 * Does this filter have local (per-context) settings?
1138 * @param string $filter The filter name, for example 'tex'.
1139 * @return boolean Whether there should be a 'Settings' link on the manage filters in context page.
1141 function filter_has_local_settings($filter) {
1142 global $CFG;
1143 $settingspath = $CFG->dirroot . '/filter/' . $filter . '/filterlocalsettings.php';
1144 return is_readable($settingspath);
1148 * Certain types of context (block and user) may not have local filter settings.
1149 * the function checks a context to see whether it may have local config.
1151 * @param object $context a context.
1152 * @return boolean whether this context may have local filter settings.
1154 function filter_context_may_have_filter_settings($context) {
1155 return $context->contextlevel != CONTEXT_BLOCK && $context->contextlevel != CONTEXT_USER;
1159 * Process phrases intelligently found within a HTML text (such as adding links).
1161 * @staticvar array $usedpharses
1162 * @param string $text the text that we are filtering
1163 * @param array $link_array an array of filterobjects
1164 * @param array $ignoretagsopen an array of opening tags that we should ignore while filtering
1165 * @param array $ignoretagsclose an array of corresponding closing tags
1166 * @param bool $overridedefaultignore True to only use tags provided by arguments
1167 * @return string
1169 function filter_phrases($text, &$link_array, $ignoretagsopen=NULL, $ignoretagsclose=NULL,
1170 $overridedefaultignore=false) {
1172 global $CFG;
1174 static $usedphrases;
1176 $ignoretags = array(); // To store all the enclosig tags to be completely ignored.
1177 $tags = array(); // To store all the simple tags to be ignored.
1179 if (!$overridedefaultignore) {
1180 // A list of open/close tags that we should not replace within
1181 // Extended to include <script>, <textarea>, <select> and <a> tags
1182 // Regular expression allows tags with or without attributes
1183 $filterignoretagsopen = array('<head>' , '<nolink>' , '<span class="nolink">',
1184 '<script(\s[^>]*?)?>', '<textarea(\s[^>]*?)?>',
1185 '<select(\s[^>]*?)?>', '<a(\s[^>]*?)?>');
1186 $filterignoretagsclose = array('</head>', '</nolink>', '</span>',
1187 '</script>', '</textarea>', '</select>','</a>');
1188 } else {
1189 // Set an empty default list.
1190 $filterignoretagsopen = array();
1191 $filterignoretagsclose = array();
1194 // Add the user defined ignore tags to the default list.
1195 if ( is_array($ignoretagsopen) ) {
1196 foreach ($ignoretagsopen as $open) {
1197 $filterignoretagsopen[] = $open;
1199 foreach ($ignoretagsclose as $close) {
1200 $filterignoretagsclose[] = $close;
1204 // Invalid prefixes and suffixes for the fullmatch searches
1205 // Every "word" character, but the underscore, is a invalid suffix or prefix.
1206 // (nice to use this because it includes national characters (accents...) as word characters.
1207 $filterinvalidprefixes = '([^\W_])';
1208 $filterinvalidsuffixes = '([^\W_])';
1210 // Double up some magic chars to avoid "accidental matches"
1211 $text = preg_replace('/([#*%])/','\1\1',$text);
1214 //Remove everything enclosed by the ignore tags from $text
1215 filter_save_ignore_tags($text,$filterignoretagsopen,$filterignoretagsclose,$ignoretags);
1217 // Remove tags from $text
1218 filter_save_tags($text,$tags);
1220 // Time to cycle through each phrase to be linked
1221 $size = sizeof($link_array);
1222 for ($n=0; $n < $size; $n++) {
1223 $linkobject =& $link_array[$n];
1225 // Set some defaults if certain properties are missing
1226 // Properties may be missing if the filterobject class has not been used to construct the object
1227 if (empty($linkobject->phrase)) {
1228 continue;
1231 // Avoid integers < 1000 to be linked. See bug 1446.
1232 $intcurrent = intval($linkobject->phrase);
1233 if (!empty($intcurrent) && strval($intcurrent) == $linkobject->phrase && $intcurrent < 1000) {
1234 continue;
1237 // All this work has to be done ONLY it it hasn't been done before
1238 if (!$linkobject->work_calculated) {
1239 if (!isset($linkobject->hreftagbegin) or !isset($linkobject->hreftagend)) {
1240 $linkobject->work_hreftagbegin = '<span class="highlight"';
1241 $linkobject->work_hreftagend = '</span>';
1242 } else {
1243 $linkobject->work_hreftagbegin = $linkobject->hreftagbegin;
1244 $linkobject->work_hreftagend = $linkobject->hreftagend;
1247 // Double up chars to protect true duplicates
1248 // be cleared up before returning to the user.
1249 $linkobject->work_hreftagbegin = preg_replace('/([#*%])/','\1\1',$linkobject->work_hreftagbegin);
1251 if (empty($linkobject->casesensitive)) {
1252 $linkobject->work_casesensitive = false;
1253 } else {
1254 $linkobject->work_casesensitive = true;
1256 if (empty($linkobject->fullmatch)) {
1257 $linkobject->work_fullmatch = false;
1258 } else {
1259 $linkobject->work_fullmatch = true;
1262 // Strip tags out of the phrase
1263 $linkobject->work_phrase = strip_tags($linkobject->phrase);
1265 // Double up chars that might cause a false match -- the duplicates will
1266 // be cleared up before returning to the user.
1267 $linkobject->work_phrase = preg_replace('/([#*%])/','\1\1',$linkobject->work_phrase);
1269 // Set the replacement phrase properly
1270 if ($linkobject->replacementphrase) { //We have specified a replacement phrase
1271 // Strip tags
1272 $linkobject->work_replacementphrase = strip_tags($linkobject->replacementphrase);
1273 } else { //The replacement is the original phrase as matched below
1274 $linkobject->work_replacementphrase = '$1';
1277 // Quote any regular expression characters and the delimiter in the work phrase to be searched
1278 $linkobject->work_phrase = preg_quote($linkobject->work_phrase, '/');
1280 // Work calculated
1281 $linkobject->work_calculated = true;
1285 // If $CFG->filtermatchoneperpage, avoid previously (request) linked phrases
1286 if (!empty($CFG->filtermatchoneperpage)) {
1287 if (!empty($usedphrases) && in_array($linkobject->work_phrase,$usedphrases)) {
1288 continue;
1292 // Regular expression modifiers
1293 $modifiers = ($linkobject->work_casesensitive) ? 's' : 'isu'; // works in unicode mode!
1295 // Do we need to do a fullmatch?
1296 // If yes then go through and remove any non full matching entries
1297 if ($linkobject->work_fullmatch) {
1298 $notfullmatches = array();
1299 $regexp = '/'.$filterinvalidprefixes.'('.$linkobject->work_phrase.')|('.$linkobject->work_phrase.')'.$filterinvalidsuffixes.'/'.$modifiers;
1301 preg_match_all($regexp,$text,$list_of_notfullmatches);
1303 if ($list_of_notfullmatches) {
1304 foreach (array_unique($list_of_notfullmatches[0]) as $key=>$value) {
1305 $notfullmatches['<*'.$key.'*>'] = $value;
1307 if (!empty($notfullmatches)) {
1308 $text = str_replace($notfullmatches,array_keys($notfullmatches),$text);
1313 // Finally we do our highlighting
1314 if (!empty($CFG->filtermatchonepertext) || !empty($CFG->filtermatchoneperpage)) {
1315 $resulttext = preg_replace('/('.$linkobject->work_phrase.')/'.$modifiers,
1316 $linkobject->work_hreftagbegin.
1317 $linkobject->work_replacementphrase.
1318 $linkobject->work_hreftagend, $text, 1);
1319 } else {
1320 $resulttext = preg_replace('/('.$linkobject->work_phrase.')/'.$modifiers,
1321 $linkobject->work_hreftagbegin.
1322 $linkobject->work_replacementphrase.
1323 $linkobject->work_hreftagend, $text);
1327 // If the text has changed we have to look for links again
1328 if ($resulttext != $text) {
1329 // Set $text to $resulttext
1330 $text = $resulttext;
1331 // Remove everything enclosed by the ignore tags from $text
1332 filter_save_ignore_tags($text,$filterignoretagsopen,$filterignoretagsclose,$ignoretags);
1333 // Remove tags from $text
1334 filter_save_tags($text,$tags);
1335 // If $CFG->filtermatchoneperpage, save linked phrases to request
1336 if (!empty($CFG->filtermatchoneperpage)) {
1337 $usedphrases[] = $linkobject->work_phrase;
1342 // Replace the not full matches before cycling to next link object
1343 if (!empty($notfullmatches)) {
1344 $text = str_replace(array_keys($notfullmatches),$notfullmatches,$text);
1345 unset($notfullmatches);
1349 // Rebuild the text with all the excluded areas
1351 if (!empty($tags)) {
1352 $text = str_replace(array_keys($tags), $tags, $text);
1355 if (!empty($ignoretags)) {
1356 $ignoretags = array_reverse($ignoretags); // Reversed so "progressive" str_replace() will solve some nesting problems.
1357 $text = str_replace(array_keys($ignoretags),$ignoretags,$text);
1360 // Remove the protective doubleups
1361 $text = preg_replace('/([#*%])(\1)/','\1',$text);
1363 // Add missing javascript for popus
1364 $text = filter_add_javascript($text);
1367 return $text;
1371 * @todo Document this function
1372 * @param array $linkarray
1373 * @return array
1375 function filter_remove_duplicates($linkarray) {
1377 $concepts = array(); // keep a record of concepts as we cycle through
1378 $lconcepts = array(); // a lower case version for case insensitive
1380 $cleanlinks = array();
1382 foreach ($linkarray as $key=>$filterobject) {
1383 if ($filterobject->casesensitive) {
1384 $exists = in_array($filterobject->phrase, $concepts);
1385 } else {
1386 $exists = in_array(core_text::strtolower($filterobject->phrase), $lconcepts);
1389 if (!$exists) {
1390 $cleanlinks[] = $filterobject;
1391 $concepts[] = $filterobject->phrase;
1392 $lconcepts[] = core_text::strtolower($filterobject->phrase);
1396 return $cleanlinks;
1400 * Extract open/lose tags and their contents to avoid being processed by filters.
1401 * Useful to extract pieces of code like <a>...</a> tags. It returns the text
1402 * converted with some <#xTEXTFILTER_EXCL_SEPARATORx#> codes replacing the extracted text. Such extracted
1403 * texts are returned in the ignoretags array (as values), with codes as keys.
1405 * @param string $text the text that we are filtering (in/out)
1406 * @param array $filterignoretagsopen an array of open tags to start searching
1407 * @param array $filterignoretagsclose an array of close tags to end searching
1408 * @param array $ignoretags an array of saved strings useful to rebuild the original text (in/out)
1410 function filter_save_ignore_tags(&$text, $filterignoretagsopen, $filterignoretagsclose, &$ignoretags) {
1412 // Remove everything enclosed by the ignore tags from $text
1413 foreach ($filterignoretagsopen as $ikey=>$opentag) {
1414 $closetag = $filterignoretagsclose[$ikey];
1415 // form regular expression
1416 $opentag = str_replace('/','\/',$opentag); // delimit forward slashes
1417 $closetag = str_replace('/','\/',$closetag); // delimit forward slashes
1418 $pregexp = '/'.$opentag.'(.*?)'.$closetag.'/is';
1420 preg_match_all($pregexp, $text, $list_of_ignores);
1421 foreach (array_unique($list_of_ignores[0]) as $key=>$value) {
1422 $prefix = (string)(count($ignoretags) + 1);
1423 $ignoretags['<#'.$prefix.TEXTFILTER_EXCL_SEPARATOR.$key.'#>'] = $value;
1425 if (!empty($ignoretags)) {
1426 $text = str_replace($ignoretags,array_keys($ignoretags),$text);
1432 * Extract tags (any text enclosed by < and > to avoid being processed by filters.
1433 * It returns the text converted with some <%xTEXTFILTER_EXCL_SEPARATORx%> codes replacing the extracted text. Such extracted
1434 * texts are returned in the tags array (as values), with codes as keys.
1436 * @param string $text the text that we are filtering (in/out)
1437 * @param array $tags an array of saved strings useful to rebuild the original text (in/out)
1439 function filter_save_tags(&$text, &$tags) {
1441 preg_match_all('/<([^#%*].*?)>/is',$text,$list_of_newtags);
1442 foreach (array_unique($list_of_newtags[0]) as $ntkey=>$value) {
1443 $prefix = (string)(count($tags) + 1);
1444 $tags['<%'.$prefix.TEXTFILTER_EXCL_SEPARATOR.$ntkey.'%>'] = $value;
1446 if (!empty($tags)) {
1447 $text = str_replace($tags,array_keys($tags),$text);
1452 * Add missing openpopup javascript to HTML files.
1454 * @param string $text
1455 * @return string
1457 function filter_add_javascript($text) {
1458 global $CFG;
1460 if (stripos($text, '</html>') === FALSE) {
1461 return $text; // This is not a html file.
1463 if (strpos($text, 'onclick="return openpopup') === FALSE) {
1464 return $text; // No popup - no need to add javascript.
1466 $js ="
1467 <script type=\"text/javascript\">
1468 <!--
1469 function openpopup(url,name,options,fullscreen) {
1470 fullurl = \"".$CFG->httpswwwroot."\" + url;
1471 windowobj = window.open(fullurl,name,options);
1472 if (fullscreen) {
1473 windowobj.moveTo(0,0);
1474 windowobj.resizeTo(screen.availWidth,screen.availHeight);
1476 windowobj.focus();
1477 return false;
1479 // -->
1480 </script>";
1481 if (stripos($text, '</head>') !== FALSE) {
1482 // Try to add it into the head element.
1483 $text = str_ireplace('</head>', $js.'</head>', $text);
1484 return $text;
1487 // Last chance - try adding head element.
1488 return preg_replace("/<html.*?>/is", "\\0<head>".$js.'</head>', $text);