2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Library functions for managing text filter plugins.
21 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 defined('MOODLE_INTERNAL') ||
die();
27 /** The states a filter can be in, stored in the filter_active table. */
28 define('TEXTFILTER_ON', 1);
29 /** The states a filter can be in, stored in the filter_active table. */
30 define('TEXTFILTER_INHERIT', 0);
31 /** The states a filter can be in, stored in the filter_active table. */
32 define('TEXTFILTER_OFF', -1);
33 /** The states a filter can be in, stored in the filter_active table. */
34 define('TEXTFILTER_DISABLED', -9999);
37 * Define one exclusive separator that we'll use in the temp saved tags
38 * keys. It must be something rare enough to avoid having matches with
39 * filterobjects. MDL-18165
41 define('TEXTFILTER_EXCL_SEPARATOR', '-%-');
45 * Class to manage the filtering of strings. It is intended that this class is
46 * only used by weblib.php. Client code should probably be using the
47 * format_text and format_string functions.
49 * This class is a singleton.
51 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
52 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
54 class filter_manager
{
56 * @var moodle_text_filter[][] This list of active filters, by context, for filtering content.
57 * An array contextid => ordered array of filter name => filter objects.
59 protected $textfilters = array();
62 * @var moodle_text_filter[][] This list of active filters, by context, for filtering strings.
63 * An array contextid => ordered array of filter name => filter objects.
65 protected $stringfilters = array();
67 /** @var array Exploded version of $CFG->stringfilters. */
68 protected $stringfilternames = array();
70 /** @var filter_manager Holds the singleton instance. */
71 protected static $singletoninstance;
74 * Constructor. Protected. Use {@link instance()} instead.
76 protected function __construct() {
77 $this->stringfilternames
= filter_get_string_filters();
81 * Factory method. Use this to get the filter manager.
83 * @return filter_manager the singleton instance.
85 public static function instance() {
87 if (is_null(self
::$singletoninstance)) {
88 if (!empty($CFG->perfdebug
) and $CFG->perfdebug
> 7) {
89 self
::$singletoninstance = new performance_measuring_filter_manager();
91 self
::$singletoninstance = new self();
94 return self
::$singletoninstance;
98 * Resets the caches, usually to be called between unit tests
100 public static function reset_caches() {
101 if (self
::$singletoninstance) {
102 self
::$singletoninstance->unload_all_filters();
104 self
::$singletoninstance = null;
108 * Unloads all filters and other cached information
110 protected function unload_all_filters() {
111 $this->textfilters
= array();
112 $this->stringfilters
= array();
113 $this->stringfilternames
= array();
117 * Load all the filters required by this context.
119 * @param context $context the context.
121 protected function load_filters($context) {
122 $filters = filter_get_active_in_context($context);
123 $this->textfilters
[$context->id
] = array();
124 $this->stringfilters
[$context->id
] = array();
125 foreach ($filters as $filtername => $localconfig) {
126 $filter = $this->make_filter_object($filtername, $context, $localconfig);
127 if (is_null($filter)) {
130 $this->textfilters
[$context->id
][$filtername] = $filter;
131 if (in_array($filtername, $this->stringfilternames
)) {
132 $this->stringfilters
[$context->id
][$filtername] = $filter;
138 * Factory method for creating a filter.
140 * @param string $filtername The filter name, for example 'tex'.
141 * @param context $context context object.
142 * @param array $localconfig array of local configuration variables for this filter.
143 * @return moodle_text_filter The filter, or null, if this type of filter is
144 * not recognised or could not be created.
146 protected function make_filter_object($filtername, $context, $localconfig) {
148 $path = $CFG->dirroot
.'/filter/'. $filtername .'/filter.php';
149 if (!is_readable($path)) {
154 $filterclassname = 'filter_' . $filtername;
155 if (class_exists($filterclassname)) {
156 return new $filterclassname($context, $localconfig);
163 * Apply a list of filters to some content.
164 * @param string $text
165 * @param moodle_text_filter[] $filterchain array filter name => filter object.
166 * @param array $options options passed to the filters.
167 * @param array $skipfilters of filter names. Any filters that should not be applied to this text.
168 * @return string $text
170 protected function apply_filter_chain($text, $filterchain, array $options = array(),
171 array $skipfilters = null) {
172 foreach ($filterchain as $filtername => $filter) {
173 if ($skipfilters !== null && in_array($filtername, $skipfilters)) {
176 $text = $filter->filter($text, $options);
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
];
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);
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.
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
274 * This should only ever be called once per request.
276 * @param moodle_page $page The page.
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];
286 $filter = $this->make_filter_object($name, $context, $config);
287 if (is_null($filter)) {
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
{
305 public function filter_text($text, $context, array $options = array(),
306 array $skipfilters = null) {
310 public function filter_string($string, $context) {
314 public function text_filtering_hash() {
315 throw new coding_exception('filter_manager::text_filtering_hash() can not be used any more');
321 * Filter manager subclass that tracks how much work it does.
323 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
324 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
326 class performance_measuring_filter_manager
extends filter_manager
{
327 /** @var int number of filter objects created. */
328 protected $filterscreated = 0;
330 /** @var int number of calls to filter_text. */
331 protected $textsfiltered = 0;
333 /** @var int number of calls to filter_string. */
334 protected $stringsfiltered = 0;
336 protected function unload_all_filters() {
337 parent
::unload_all_filters();
338 $this->filterscreated
= 0;
339 $this->textsfiltered
= 0;
340 $this->stringsfiltered
= 0;
343 protected function make_filter_object($filtername, $context, $localconfig) {
344 $this->filterscreated++
;
345 return parent
::make_filter_object($filtername, $context, $localconfig);
348 public function filter_text($text, $context, array $options = array(),
349 array $skipfilters = null) {
350 $this->textsfiltered++
;
351 return parent
::filter_text($text, $context, $options, $skipfilters);
354 public function filter_string($string, $context) {
355 $this->stringsfiltered++
;
356 return parent
::filter_string($string, $context);
360 * Return performance information, in the form required by {@link get_performance_info()}.
361 * @return array the performance info.
363 public function get_performance_summary() {
365 'contextswithfilters' => count($this->textfilters
),
366 'filterscreated' => $this->filterscreated
,
367 'textsfiltered' => $this->textsfiltered
,
368 'stringsfiltered' => $this->stringsfiltered
,
370 'contextswithfilters' => 'Contexts for which filters were loaded',
371 'filterscreated' => 'Filters created',
372 'textsfiltered' => 'Pieces of content filtered',
373 'stringsfiltered' => 'Strings filtered',
380 * Base class for text filters. You just need to override this class and
381 * implement the filter method.
383 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
384 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
386 abstract class moodle_text_filter
{
387 /** @var context The context we are in. */
390 /** @var array Any local configuration for this filter in this context. */
391 protected $localconfig;
394 * Set any context-specific configuration for this filter.
396 * @param context $context The current context.
397 * @param array $localconfig Any context-specific configuration for this filter.
399 public function __construct($context, array $localconfig) {
400 $this->context
= $context;
401 $this->localconfig
= $localconfig;
405 * @deprecated Since Moodle 3.0 MDL-50491. This was used by the old text filtering system, but no more.
407 public function hash() {
408 throw new coding_exception('moodle_text_filter::hash() can not be used any more');
412 * Setup page with filter requirements and other prepare stuff.
414 * Override this method if the filter needs to setup page
415 * requirements or needs other stuff to be executed.
417 * Note this method is invoked from {@see setup_page_for_filters()}
418 * for each piece of text being filtered, so it is responsible
419 * for controlling its own execution cardinality.
421 * @param moodle_page $page the page we are going to add requirements to.
422 * @param context $context the context which contents are going to be filtered.
425 public function setup($page, $context) {
426 // Override me, if needed.
430 * Override this function to actually implement the filtering.
432 * @param $text some HTML content.
433 * @param array $options options passed to the filters
434 * @return the HTML content after the filtering has been applied.
436 public abstract function filter($text, array $options = array());
441 * This is just a little object to define a phrase and some instructions
442 * for how to process it. Filters can create an array of these to pass
443 * to the filter_phrases function below.
445 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
446 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
457 var $replacementphrase;
459 var $work_hreftagbegin;
460 var $work_hreftagend;
461 var $work_casesensitive;
463 var $work_replacementphrase;
465 var $work_calculated;
468 * A constructor just because I like constructing
470 * @param string $phrase
471 * @param string $hreftagbegin
472 * @param string $hreftagend
473 * @param bool $casesensitive
474 * @param bool $fullmatch
475 * @param mixed $replacementphrase
477 public function __construct($phrase, $hreftagbegin = '<span class="highlight">',
478 $hreftagend = '</span>',
479 $casesensitive = false,
481 $replacementphrase = NULL) {
483 $this->phrase
= $phrase;
484 $this->hreftagbegin
= $hreftagbegin;
485 $this->hreftagend
= $hreftagend;
486 $this->casesensitive
= $casesensitive;
487 $this->fullmatch
= $fullmatch;
488 $this->replacementphrase
= $replacementphrase;
489 $this->work_calculated
= false;
495 * Look up the name of this filter
497 * @param string $filter the filter name
498 * @return string the human-readable name for this filter.
500 function filter_get_name($filter) {
501 if (strpos($filter, 'filter/') === 0) {
502 debugging("Old '$filter'' parameter used in filter_get_name()");
503 $filter = substr($filter, 7);
504 } else if (strpos($filter, '/') !== false) {
505 throw new coding_exception('Unknown filter type ' . $filter);
508 if (get_string_manager()->string_exists('filtername', 'filter_' . $filter)) {
509 return get_string('filtername', 'filter_' . $filter);
516 * Get the names of all the filters installed in this Moodle.
518 * @return array path => filter name from the appropriate lang file. e.g.
519 * array('tex' => 'TeX Notation');
520 * sorted in alphabetical order of name.
522 function filter_get_all_installed() {
525 $filternames = array();
526 foreach (core_component
::get_plugin_list('filter') as $filter => $fulldir) {
527 if (is_readable("$fulldir/filter.php")) {
528 $filternames[$filter] = filter_get_name($filter);
531 core_collator
::asort($filternames);
536 * Set the global activated state for a text filter.
538 * @param string $filtername The filter name, for example 'tex'.
539 * @param int $state One of the values TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_DISABLED.
540 * @param int $move -1 means up, 0 means the same, 1 means down
542 function filter_set_global_state($filtername, $state, $move = 0) {
545 // Check requested state is valid.
546 if (!in_array($state, array(TEXTFILTER_ON
, TEXTFILTER_OFF
, TEXTFILTER_DISABLED
))) {
547 throw new coding_exception("Illegal option '$state' passed to filter_set_global_state. " .
548 "Must be one of TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_DISABLED.");
553 } else if ($move < 0) {
557 if (strpos($filtername, 'filter/') === 0) {
558 //debugging("Old filtername '$filtername' parameter used in filter_set_global_state()", DEBUG_DEVELOPER);
559 $filtername = substr($filtername, 7);
560 } else if (strpos($filtername, '/') !== false) {
561 throw new coding_exception("Invalid filter name '$filtername' used in filter_set_global_state()");
564 $transaction = $DB->start_delegated_transaction();
566 $syscontext = context_system
::instance();
567 $filters = $DB->get_records('filter_active', array('contextid' => $syscontext->id
), 'sortorder ASC');
572 foreach($filters as $f) {
573 if ($f->active
== TEXTFILTER_DISABLED
) {
574 $off[$f->filter
] = $f;
576 $on[$f->filter
] = $f;
580 // Update the state or add new record.
581 if (isset($on[$filtername])) {
582 $filter = $on[$filtername];
583 if ($filter->active
!= $state) {
584 add_to_config_log('filter_active', $filter->active
, $state, $filtername);
586 $filter->active
= $state;
587 $DB->update_record('filter_active', $filter);
588 if ($filter->active
== TEXTFILTER_DISABLED
) {
589 unset($on[$filtername]);
590 $off = array($filter->filter
=> $filter) +
$off;
595 } else if (isset($off[$filtername])) {
596 $filter = $off[$filtername];
597 if ($filter->active
!= $state) {
598 add_to_config_log('filter_active', $filter->active
, $state, $filtername);
600 $filter->active
= $state;
601 $DB->update_record('filter_active', $filter);
602 if ($filter->active
!= TEXTFILTER_DISABLED
) {
603 unset($off[$filtername]);
604 $on[$filter->filter
] = $filter;
609 add_to_config_log('filter_active', '', $state, $filtername);
611 $filter = new stdClass();
612 $filter->filter
= $filtername;
613 $filter->contextid
= $syscontext->id
;
614 $filter->active
= $state;
615 $filter->sortorder
= 99999;
616 $filter->id
= $DB->insert_record('filter_active', $filter);
618 $filters[$filter->id
] = $filter;
619 if ($state == TEXTFILTER_DISABLED
) {
620 $off[$filter->filter
] = $filter;
622 $on[$filter->filter
] = $filter;
627 if ($move != 0 and isset($on[$filter->filter
])) {
629 foreach ($on as $f) {
630 $f->newsortorder
= $i;
634 $filter->newsortorder
= $filter->newsortorder +
$move;
636 foreach ($on as $f) {
637 if ($f->id
== $filter->id
) {
640 if ($f->newsortorder
== $filter->newsortorder
) {
642 $f->newsortorder
= $f->newsortorder
- 1;
644 $f->newsortorder
= $f->newsortorder +
1;
649 core_collator
::asort_objects_by_property($on, 'newsortorder', core_collator
::SORT_NUMERIC
);
652 // Inactive are sorted by filter name.
653 core_collator
::asort_objects_by_property($off, 'filter', core_collator
::SORT_NATURAL
);
655 // Update records if necessary.
657 foreach ($on as $f) {
658 if ($f->sortorder
!= $i) {
659 $DB->set_field('filter_active', 'sortorder', $i, array('id'=>$f->id
));
663 foreach ($off as $f) {
664 if ($f->sortorder
!= $i) {
665 $DB->set_field('filter_active', 'sortorder', $i, array('id'=>$f->id
));
670 $transaction->allow_commit();
674 * @param string $filtername The filter name, for example 'tex'.
675 * @return boolean is this filter allowed to be used on this site. That is, the
676 * admin has set the global 'active' setting to On, or Off, but available.
678 function filter_is_enabled($filtername) {
679 if (strpos($filtername, 'filter/') === 0) {
680 //debugging("Old filtername '$filtername' parameter used in filter_is_enabled()", DEBUG_DEVELOPER);
681 $filtername = substr($filtername, 7);
682 } else if (strpos($filtername, '/') !== false) {
683 throw new coding_exception("Invalid filter name '$filtername' used in filter_is_enabled()");
685 return array_key_exists($filtername, filter_get_globally_enabled());
689 * Return a list of all the filters that may be in use somewhere.
691 * @staticvar array $enabledfilters
692 * @return array where the keys and values are both the filter name, like 'tex'.
694 function filter_get_globally_enabled() {
695 static $enabledfilters = null;
696 if (is_null($enabledfilters)) {
697 $filters = filter_get_global_states();
698 $enabledfilters = array();
699 foreach ($filters as $filter => $filerinfo) {
700 if ($filerinfo->active
!= TEXTFILTER_DISABLED
) {
701 $enabledfilters[$filter] = $filter;
705 return $enabledfilters;
709 * Get the globally enabled filters.
711 * This returns the filters which could be used in any context. Essentially
712 * the filters which are not disabled for the entire site.
714 * @return array Keys are filter names, and values the config.
716 function filter_get_globally_enabled_filters_with_config() {
719 $sql = "SELECT f.filter, fc.name, fc.value
720 FROM {filter_active} f
721 LEFT JOIN {filter_config} fc
722 ON fc.filter = f.filter
723 AND fc.contextid = f.contextid
724 WHERE f.contextid = :contextid
725 AND f.active != :disabled
726 ORDER BY f.sortorder";
728 $rs = $DB->get_recordset_sql($sql, [
729 'contextid' => context_system
::instance()->id
,
730 'disabled' => TEXTFILTER_DISABLED
733 // Massage the data into the specified format to return.
735 foreach ($rs as $row) {
736 if (!isset($filters[$row->filter
])) {
737 $filters[$row->filter
] = array();
739 if ($row->name
!== null) {
740 $filters[$row->filter
][$row->name
] = $row->value
;
749 * Return the names of the filters that should also be applied to strings
750 * (when they are enabled).
752 * @return array where the keys and values are both the filter name, like 'tex'.
754 function filter_get_string_filters() {
756 $stringfilters = array();
757 if (!empty($CFG->filterall
) && !empty($CFG->stringfilters
)) {
758 $stringfilters = explode(',', $CFG->stringfilters
);
759 $stringfilters = array_combine($stringfilters, $stringfilters);
761 return $stringfilters;
765 * Sets whether a particular active filter should be applied to all strings by
766 * format_string, or just used by format_text.
768 * @param string $filter The filter name, for example 'tex'.
769 * @param boolean $applytostrings if true, this filter will apply to format_string
770 * and format_text, when it is enabled.
772 function filter_set_applies_to_strings($filter, $applytostrings) {
773 $stringfilters = filter_get_string_filters();
774 $prevfilters = $stringfilters;
775 $allfilters = core_component
::get_plugin_list('filter');
777 if ($applytostrings) {
778 $stringfilters[$filter] = $filter;
780 unset($stringfilters[$filter]);
783 // Remove missing filters.
784 foreach ($stringfilters as $filter) {
785 if (!isset($allfilters[$filter])) {
786 unset($stringfilters[$filter]);
790 if ($prevfilters != $stringfilters) {
791 set_config('stringfilters', implode(',', $stringfilters));
792 set_config('filterall', !empty($stringfilters));
797 * Set the local activated state for a text filter.
799 * @param string $filter The filter name, for example 'tex'.
800 * @param integer $contextid The id of the context to get the local config for.
801 * @param integer $state One of the values TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_INHERIT.
804 function filter_set_local_state($filter, $contextid, $state) {
807 // Check requested state is valid.
808 if (!in_array($state, array(TEXTFILTER_ON
, TEXTFILTER_OFF
, TEXTFILTER_INHERIT
))) {
809 throw new coding_exception("Illegal option '$state' passed to filter_set_local_state. " .
810 "Must be one of TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_INHERIT.");
813 if ($contextid == context_system
::instance()->id
) {
814 throw new coding_exception('You cannot use filter_set_local_state ' .
815 'with $contextid equal to the system context id.');
818 if ($state == TEXTFILTER_INHERIT
) {
819 $DB->delete_records('filter_active', array('filter' => $filter, 'contextid' => $contextid));
823 $rec = $DB->get_record('filter_active', array('filter' => $filter, 'contextid' => $contextid));
828 $rec->filter
= $filter;
829 $rec->contextid
= $contextid;
832 $rec->active
= $state;
835 $DB->insert_record('filter_active', $rec);
837 $DB->update_record('filter_active', $rec);
842 * Set a particular local config variable for a filter in a context.
844 * @param string $filter The filter name, for example 'tex'.
845 * @param integer $contextid The id of the context to get the local config for.
846 * @param string $name the setting name.
847 * @param string $value the corresponding value.
849 function filter_set_local_config($filter, $contextid, $name, $value) {
851 $rec = $DB->get_record('filter_config', array('filter' => $filter, 'contextid' => $contextid, 'name' => $name));
856 $rec->filter
= $filter;
857 $rec->contextid
= $contextid;
861 $rec->value
= $value;
864 $DB->insert_record('filter_config', $rec);
866 $DB->update_record('filter_config', $rec);
871 * Remove a particular local config variable for a filter in a context.
873 * @param string $filter The filter name, for example 'tex'.
874 * @param integer $contextid The id of the context to get the local config for.
875 * @param string $name the setting name.
877 function filter_unset_local_config($filter, $contextid, $name) {
879 $DB->delete_records('filter_config', array('filter' => $filter, 'contextid' => $contextid, 'name' => $name));
883 * Get local config variables for a filter in a context. Normally (when your
884 * filter is running) you don't need to call this, becuase the config is fetched
885 * for you automatically. You only need this, for example, when you are getting
886 * the config so you can show the user an editing from.
888 * @param string $filter The filter name, for example 'tex'.
889 * @param integer $contextid The ID of the context to get the local config for.
890 * @return array of name => value pairs.
892 function filter_get_local_config($filter, $contextid) {
894 return $DB->get_records_menu('filter_config', array('filter' => $filter, 'contextid' => $contextid), '', 'name,value');
898 * This function is for use by backup. Gets all the filter information specific
901 * @param int $contextid
902 * @return array Array with two elements. The first element is an array of objects with
903 * fields filter and active. These come from the filter_active table. The
904 * second element is an array of objects with fields filter, name and value
905 * from the filter_config table.
907 function filter_get_all_local_settings($contextid) {
910 $DB->get_records('filter_active', array('contextid' => $contextid), 'filter', 'filter,active'),
911 $DB->get_records('filter_config', array('contextid' => $contextid), 'filter,name', 'filter,name,value'),
916 * Get the list of active filters, in the order that they should be used
917 * for a particular context, along with any local configuration variables.
919 * @param context $context a context
920 * @return array an array where the keys are the filter names, for example
921 * 'tex' and the values are any local
922 * configuration for that filter, as an array of name => value pairs
923 * from the filter_config table. In a lot of cases, this will be an
924 * empty array. So, an example return value for this function might be
925 * array(tex' => array())
927 function filter_get_active_in_context($context) {
928 global $DB, $FILTERLIB_PRIVATE;
930 if (!isset($FILTERLIB_PRIVATE)) {
931 $FILTERLIB_PRIVATE = new stdClass();
934 // Use cache (this is a within-request cache only) if available. See
935 // function filter_preload_activities.
936 if (isset($FILTERLIB_PRIVATE->active
) &&
937 array_key_exists($context->id
, $FILTERLIB_PRIVATE->active
)) {
938 return $FILTERLIB_PRIVATE->active
[$context->id
];
941 $contextids = str_replace('/', ',', trim($context->path
, '/'));
943 // The following SQL is tricky. It is explained on
944 // http://docs.moodle.org/dev/Filter_enable/disable_by_context
945 $sql = "SELECT active.filter, fc.name, fc.value
946 FROM (SELECT f.filter, MAX(f.sortorder) AS sortorder
947 FROM {filter_active} f
948 JOIN {context} ctx ON f.contextid = ctx.id
949 WHERE ctx.id IN ($contextids)
951 HAVING MAX(f.active * ctx.depth) > -MIN(f.active * ctx.depth)
953 LEFT JOIN {filter_config} fc ON fc.filter = active.filter AND fc.contextid = $context->id
954 ORDER BY active.sortorder";
955 $rs = $DB->get_recordset_sql($sql);
957 // Massage the data into the specified format to return.
959 foreach ($rs as $row) {
960 if (!isset($filters[$row->filter
])) {
961 $filters[$row->filter
] = array();
963 if (!is_null($row->name
)) {
964 $filters[$row->filter
][$row->name
] = $row->value
;
974 * Preloads the list of active filters for all activities (modules) on the course
975 * using two database queries.
977 * @param course_modinfo $modinfo Course object from get_fast_modinfo
979 function filter_preload_activities(course_modinfo
$modinfo) {
980 global $DB, $FILTERLIB_PRIVATE;
982 if (!isset($FILTERLIB_PRIVATE)) {
983 $FILTERLIB_PRIVATE = new stdClass();
986 // Don't repeat preload
987 if (!isset($FILTERLIB_PRIVATE->preloaded
)) {
988 $FILTERLIB_PRIVATE->preloaded
= array();
990 if (!empty($FILTERLIB_PRIVATE->preloaded
[$modinfo->get_course_id()])) {
993 $FILTERLIB_PRIVATE->preloaded
[$modinfo->get_course_id()] = true;
995 // Get contexts for all CMs
996 $cmcontexts = array();
997 $cmcontextids = array();
998 foreach ($modinfo->get_cms() as $cm) {
999 $modulecontext = context_module
::instance($cm->id
);
1000 $cmcontextids[] = $modulecontext->id
;
1001 $cmcontexts[] = $modulecontext;
1004 // Get course context and all other parents...
1005 $coursecontext = context_course
::instance($modinfo->get_course_id());
1006 $parentcontextids = explode('/', substr($coursecontext->path
, 1));
1007 $allcontextids = array_merge($cmcontextids, $parentcontextids);
1009 // Get all filter_active rows relating to all these contexts
1010 list ($sql, $params) = $DB->get_in_or_equal($allcontextids);
1011 $filteractives = $DB->get_records_select('filter_active', "contextid $sql", $params, 'sortorder');
1013 // Get all filter_config only for the cm contexts
1014 list ($sql, $params) = $DB->get_in_or_equal($cmcontextids);
1015 $filterconfigs = $DB->get_records_select('filter_config', "contextid $sql", $params);
1017 // Note: I was a bit surprised that filter_config only works for the
1018 // most specific context (i.e. it does not need to be checked for course
1019 // context if we only care about CMs) however basede on code in
1020 // filter_get_active_in_context, this does seem to be correct.
1022 // Build course default active list. Initially this will be an array of
1023 // filter name => active score (where an active score >0 means it's active)
1024 $courseactive = array();
1026 // Also build list of filter_active rows below course level, by contextid
1027 $remainingactives = array();
1029 // Array lists filters that are banned at top level
1032 // Add any active filters in parent contexts to the array
1033 foreach ($filteractives as $row) {
1034 $depth = array_search($row->contextid
, $parentcontextids);
1035 if ($depth !== false) {
1037 if (!array_key_exists($row->filter
, $courseactive)) {
1038 $courseactive[$row->filter
] = 0;
1040 // This maths copes with reading rows in any order. Turning on/off
1041 // at site level counts 1, at next level down 4, at next level 9,
1042 // then 16, etc. This means the deepest level always wins, except
1043 // against the -9999 at top level.
1044 $courseactive[$row->filter
] +
=
1045 ($depth +
1) * ($depth +
1) * $row->active
;
1047 if ($row->active
== TEXTFILTER_DISABLED
) {
1048 $banned[$row->filter
] = true;
1051 // Build list of other rows indexed by contextid
1052 if (!array_key_exists($row->contextid
, $remainingactives)) {
1053 $remainingactives[$row->contextid
] = array();
1055 $remainingactives[$row->contextid
][] = $row;
1059 // Chuck away the ones that aren't active.
1060 foreach ($courseactive as $filter=>$score) {
1062 unset($courseactive[$filter]);
1064 $courseactive[$filter] = array();
1068 // Loop through the contexts to reconstruct filter_active lists for each
1069 // cm on the course.
1070 if (!isset($FILTERLIB_PRIVATE->active
)) {
1071 $FILTERLIB_PRIVATE->active
= array();
1073 foreach ($cmcontextids as $contextid) {
1075 $FILTERLIB_PRIVATE->active
[$contextid] = $courseactive;
1077 // Are there any changes to the active list?
1078 if (array_key_exists($contextid, $remainingactives)) {
1079 foreach ($remainingactives[$contextid] as $row) {
1080 if ($row->active
> 0 && empty($banned[$row->filter
])) {
1081 // If it's marked active for specific context, add entry
1082 // (doesn't matter if one exists already).
1083 $FILTERLIB_PRIVATE->active
[$contextid][$row->filter
] = array();
1085 // If it's marked inactive, remove entry (doesn't matter
1086 // if it doesn't exist).
1087 unset($FILTERLIB_PRIVATE->active
[$contextid][$row->filter
]);
1093 // Process all config rows to add config data to these entries.
1094 foreach ($filterconfigs as $row) {
1095 if (isset($FILTERLIB_PRIVATE->active
[$row->contextid
][$row->filter
])) {
1096 $FILTERLIB_PRIVATE->active
[$row->contextid
][$row->filter
][$row->name
] = $row->value
;
1102 * List all of the filters that are available in this context, and what the
1103 * local and inherited states of that filter are.
1105 * @param context $context a context that is not the system context.
1106 * @return array an array with filter names, for example 'tex'
1107 * as keys. and and the values are objects with fields:
1108 * ->filter filter name, same as the key.
1109 * ->localstate TEXTFILTER_ON/OFF/INHERIT
1110 * ->inheritedstate TEXTFILTER_ON/OFF - the state that will be used if localstate is set to TEXTFILTER_INHERIT.
1112 function filter_get_available_in_context($context) {
1115 // The complex logic is working out the active state in the parent context,
1116 // so strip the current context from the list.
1117 $contextids = explode('/', trim($context->path
, '/'));
1118 array_pop($contextids);
1119 $contextids = implode(',', $contextids);
1120 if (empty($contextids)) {
1121 throw new coding_exception('filter_get_available_in_context cannot be called with the system context.');
1124 // The following SQL is tricky, in the same way at the SQL in filter_get_active_in_context.
1125 $sql = "SELECT parent_states.filter,
1126 CASE WHEN fa.active IS NULL THEN " . TEXTFILTER_INHERIT
. "
1127 ELSE fa.active END AS localstate,
1128 parent_states.inheritedstate
1129 FROM (SELECT f.filter, MAX(f.sortorder) AS sortorder,
1130 CASE WHEN MAX(f.active * ctx.depth) > -MIN(f.active * ctx.depth) THEN " . TEXTFILTER_ON
. "
1131 ELSE " . TEXTFILTER_OFF
. " END AS inheritedstate
1132 FROM {filter_active} f
1133 JOIN {context} ctx ON f.contextid = ctx.id
1134 WHERE ctx.id IN ($contextids)
1136 HAVING MIN(f.active) > " . TEXTFILTER_DISABLED
. "
1138 LEFT JOIN {filter_active} fa ON fa.filter = parent_states.filter AND fa.contextid = $context->id
1139 ORDER BY parent_states.sortorder";
1140 return $DB->get_records_sql($sql);
1144 * This function is for use by the filter administration page.
1146 * @return array 'filtername' => object with fields 'filter' (=filtername), 'active' and 'sortorder'
1148 function filter_get_global_states() {
1150 $context = context_system
::instance();
1151 return $DB->get_records('filter_active', array('contextid' => $context->id
), 'sortorder', 'filter,active,sortorder');
1155 * Delete all the data in the database relating to a filter, prior to deleting it.
1157 * @param string $filter The filter name, for example 'tex'.
1159 function filter_delete_all_for_filter($filter) {
1162 unset_all_config_for_plugin('filter_' . $filter);
1163 $DB->delete_records('filter_active', array('filter' => $filter));
1164 $DB->delete_records('filter_config', array('filter' => $filter));
1168 * Delete all the data in the database relating to a context, used when contexts are deleted.
1170 * @param integer $contextid The id of the context being deleted.
1172 function filter_delete_all_for_context($contextid) {
1174 $DB->delete_records('filter_active', array('contextid' => $contextid));
1175 $DB->delete_records('filter_config', array('contextid' => $contextid));
1179 * Does this filter have a global settings page in the admin tree?
1180 * (The settings page for a filter must be called, for example, filtersettingfiltertex.)
1182 * @param string $filter The filter name, for example 'tex'.
1183 * @return boolean Whether there should be a 'Settings' link on the config page.
1185 function filter_has_global_settings($filter) {
1187 $settingspath = $CFG->dirroot
. '/filter/' . $filter . '/settings.php';
1188 if (is_readable($settingspath)) {
1191 $settingspath = $CFG->dirroot
. '/filter/' . $filter . '/filtersettings.php';
1192 return is_readable($settingspath);
1196 * Does this filter have local (per-context) settings?
1198 * @param string $filter The filter name, for example 'tex'.
1199 * @return boolean Whether there should be a 'Settings' link on the manage filters in context page.
1201 function filter_has_local_settings($filter) {
1203 $settingspath = $CFG->dirroot
. '/filter/' . $filter . '/filterlocalsettings.php';
1204 return is_readable($settingspath);
1208 * Certain types of context (block and user) may not have local filter settings.
1209 * the function checks a context to see whether it may have local config.
1211 * @param object $context a context.
1212 * @return boolean whether this context may have local filter settings.
1214 function filter_context_may_have_filter_settings($context) {
1215 return $context->contextlevel
!= CONTEXT_BLOCK
&& $context->contextlevel
!= CONTEXT_USER
;
1219 * Process phrases intelligently found within a HTML text (such as adding links).
1221 * @staticvar array $usedpharses
1222 * @param string $text the text that we are filtering
1223 * @param array $link_array an array of filterobjects
1224 * @param array $ignoretagsopen an array of opening tags that we should ignore while filtering
1225 * @param array $ignoretagsclose an array of corresponding closing tags
1226 * @param bool $overridedefaultignore True to only use tags provided by arguments
1229 function filter_phrases($text, &$link_array, $ignoretagsopen=NULL, $ignoretagsclose=NULL,
1230 $overridedefaultignore=false) {
1234 static $usedphrases;
1236 $ignoretags = array(); // To store all the enclosig tags to be completely ignored.
1237 $tags = array(); // To store all the simple tags to be ignored.
1239 if (!$overridedefaultignore) {
1240 // A list of open/close tags that we should not replace within
1241 // Extended to include <script>, <textarea>, <select> and <a> tags
1242 // Regular expression allows tags with or without attributes
1243 $filterignoretagsopen = array('<head>' , '<nolink>' , '<span class="nolink">',
1244 '<script(\s[^>]*?)?>', '<textarea(\s[^>]*?)?>',
1245 '<select(\s[^>]*?)?>', '<a(\s[^>]*?)?>');
1246 $filterignoretagsclose = array('</head>', '</nolink>', '</span>',
1247 '</script>', '</textarea>', '</select>','</a>');
1249 // Set an empty default list.
1250 $filterignoretagsopen = array();
1251 $filterignoretagsclose = array();
1254 // Add the user defined ignore tags to the default list.
1255 if ( is_array($ignoretagsopen) ) {
1256 foreach ($ignoretagsopen as $open) {
1257 $filterignoretagsopen[] = $open;
1259 foreach ($ignoretagsclose as $close) {
1260 $filterignoretagsclose[] = $close;
1264 // Invalid prefixes and suffixes for the fullmatch searches
1265 // Every "word" character, but the underscore, is a invalid suffix or prefix.
1266 // (nice to use this because it includes national characters (accents...) as word characters.
1267 $filterinvalidprefixes = '([^\W_])';
1268 $filterinvalidsuffixes = '([^\W_])';
1270 // Double up some magic chars to avoid "accidental matches"
1271 $text = preg_replace('/([#*%])/','\1\1',$text);
1274 //Remove everything enclosed by the ignore tags from $text
1275 filter_save_ignore_tags($text,$filterignoretagsopen,$filterignoretagsclose,$ignoretags);
1277 // Remove tags from $text
1278 filter_save_tags($text,$tags);
1280 // Time to cycle through each phrase to be linked
1281 $size = sizeof($link_array);
1282 for ($n=0; $n < $size; $n++
) {
1283 $linkobject =& $link_array[$n];
1285 // Set some defaults if certain properties are missing
1286 // Properties may be missing if the filterobject class has not been used to construct the object
1287 if (empty($linkobject->phrase
)) {
1291 // Avoid integers < 1000 to be linked. See bug 1446.
1292 $intcurrent = intval($linkobject->phrase
);
1293 if (!empty($intcurrent) && strval($intcurrent) == $linkobject->phrase
&& $intcurrent < 1000) {
1297 // All this work has to be done ONLY it it hasn't been done before
1298 if (!$linkobject->work_calculated
) {
1299 if (!isset($linkobject->hreftagbegin
) or !isset($linkobject->hreftagend
)) {
1300 $linkobject->work_hreftagbegin
= '<span class="highlight"';
1301 $linkobject->work_hreftagend
= '</span>';
1303 $linkobject->work_hreftagbegin
= $linkobject->hreftagbegin
;
1304 $linkobject->work_hreftagend
= $linkobject->hreftagend
;
1307 // Double up chars to protect true duplicates
1308 // be cleared up before returning to the user.
1309 $linkobject->work_hreftagbegin
= preg_replace('/([#*%])/','\1\1',$linkobject->work_hreftagbegin
);
1311 if (empty($linkobject->casesensitive
)) {
1312 $linkobject->work_casesensitive
= false;
1314 $linkobject->work_casesensitive
= true;
1316 if (empty($linkobject->fullmatch
)) {
1317 $linkobject->work_fullmatch
= false;
1319 $linkobject->work_fullmatch
= true;
1322 // Strip tags out of the phrase
1323 $linkobject->work_phrase
= strip_tags($linkobject->phrase
);
1325 // Double up chars that might cause a false match -- the duplicates will
1326 // be cleared up before returning to the user.
1327 $linkobject->work_phrase
= preg_replace('/([#*%])/','\1\1',$linkobject->work_phrase
);
1329 // Set the replacement phrase properly
1330 if ($linkobject->replacementphrase
) { //We have specified a replacement phrase
1332 $linkobject->work_replacementphrase
= strip_tags($linkobject->replacementphrase
);
1333 } else { //The replacement is the original phrase as matched below
1334 $linkobject->work_replacementphrase
= '$1';
1337 // Quote any regular expression characters and the delimiter in the work phrase to be searched
1338 $linkobject->work_phrase
= preg_quote($linkobject->work_phrase
, '/');
1341 $linkobject->work_calculated
= true;
1345 // If $CFG->filtermatchoneperpage, avoid previously (request) linked phrases
1346 if (!empty($CFG->filtermatchoneperpage
)) {
1347 if (!empty($usedphrases) && in_array($linkobject->work_phrase
,$usedphrases)) {
1352 // Regular expression modifiers
1353 $modifiers = ($linkobject->work_casesensitive
) ?
's' : 'isu'; // works in unicode mode!
1355 // Do we need to do a fullmatch?
1356 // If yes then go through and remove any non full matching entries
1357 if ($linkobject->work_fullmatch
) {
1358 $notfullmatches = array();
1359 $regexp = '/'.$filterinvalidprefixes.'('.$linkobject->work_phrase
.')|('.$linkobject->work_phrase
.')'.$filterinvalidsuffixes.'/'.$modifiers;
1361 preg_match_all($regexp,$text,$list_of_notfullmatches);
1363 if ($list_of_notfullmatches) {
1364 foreach (array_unique($list_of_notfullmatches[0]) as $key=>$value) {
1365 $notfullmatches['<*'.$key.'*>'] = $value;
1367 if (!empty($notfullmatches)) {
1368 $text = str_replace($notfullmatches,array_keys($notfullmatches),$text);
1373 // Finally we do our highlighting
1374 if (!empty($CFG->filtermatchonepertext
) ||
!empty($CFG->filtermatchoneperpage
)) {
1375 $resulttext = preg_replace('/('.$linkobject->work_phrase
.')/'.$modifiers,
1376 $linkobject->work_hreftagbegin
.
1377 $linkobject->work_replacementphrase
.
1378 $linkobject->work_hreftagend
, $text, 1);
1380 $resulttext = preg_replace('/('.$linkobject->work_phrase
.')/'.$modifiers,
1381 $linkobject->work_hreftagbegin
.
1382 $linkobject->work_replacementphrase
.
1383 $linkobject->work_hreftagend
, $text);
1387 // If the text has changed we have to look for links again
1388 if ($resulttext != $text) {
1389 // Set $text to $resulttext
1390 $text = $resulttext;
1391 // Remove everything enclosed by the ignore tags from $text
1392 filter_save_ignore_tags($text,$filterignoretagsopen,$filterignoretagsclose,$ignoretags);
1393 // Remove tags from $text
1394 filter_save_tags($text,$tags);
1395 // If $CFG->filtermatchoneperpage, save linked phrases to request
1396 if (!empty($CFG->filtermatchoneperpage
)) {
1397 $usedphrases[] = $linkobject->work_phrase
;
1402 // Replace the not full matches before cycling to next link object
1403 if (!empty($notfullmatches)) {
1404 $text = str_replace(array_keys($notfullmatches),$notfullmatches,$text);
1405 unset($notfullmatches);
1409 // Rebuild the text with all the excluded areas
1411 if (!empty($tags)) {
1412 $text = str_replace(array_keys($tags), $tags, $text);
1415 if (!empty($ignoretags)) {
1416 $ignoretags = array_reverse($ignoretags); // Reversed so "progressive" str_replace() will solve some nesting problems.
1417 $text = str_replace(array_keys($ignoretags),$ignoretags,$text);
1420 // Remove the protective doubleups
1421 $text = preg_replace('/([#*%])(\1)/','\1',$text);
1423 // Add missing javascript for popus
1424 $text = filter_add_javascript($text);
1431 * @todo Document this function
1432 * @param array $linkarray
1435 function filter_remove_duplicates($linkarray) {
1437 $concepts = array(); // keep a record of concepts as we cycle through
1438 $lconcepts = array(); // a lower case version for case insensitive
1440 $cleanlinks = array();
1442 foreach ($linkarray as $key=>$filterobject) {
1443 if ($filterobject->casesensitive
) {
1444 $exists = in_array($filterobject->phrase
, $concepts);
1446 $exists = in_array(core_text
::strtolower($filterobject->phrase
), $lconcepts);
1450 $cleanlinks[] = $filterobject;
1451 $concepts[] = $filterobject->phrase
;
1452 $lconcepts[] = core_text
::strtolower($filterobject->phrase
);
1460 * Extract open/lose tags and their contents to avoid being processed by filters.
1461 * Useful to extract pieces of code like <a>...</a> tags. It returns the text
1462 * converted with some <#xTEXTFILTER_EXCL_SEPARATORx#> codes replacing the extracted text. Such extracted
1463 * texts are returned in the ignoretags array (as values), with codes as keys.
1465 * @param string $text the text that we are filtering (in/out)
1466 * @param array $filterignoretagsopen an array of open tags to start searching
1467 * @param array $filterignoretagsclose an array of close tags to end searching
1468 * @param array $ignoretags an array of saved strings useful to rebuild the original text (in/out)
1470 function filter_save_ignore_tags(&$text, $filterignoretagsopen, $filterignoretagsclose, &$ignoretags) {
1472 // Remove everything enclosed by the ignore tags from $text
1473 foreach ($filterignoretagsopen as $ikey=>$opentag) {
1474 $closetag = $filterignoretagsclose[$ikey];
1475 // form regular expression
1476 $opentag = str_replace('/','\/',$opentag); // delimit forward slashes
1477 $closetag = str_replace('/','\/',$closetag); // delimit forward slashes
1478 $pregexp = '/'.$opentag.'(.*?)'.$closetag.'/is';
1480 preg_match_all($pregexp, $text, $list_of_ignores);
1481 foreach (array_unique($list_of_ignores[0]) as $key=>$value) {
1482 $prefix = (string)(count($ignoretags) +
1);
1483 $ignoretags['<#'.$prefix.TEXTFILTER_EXCL_SEPARATOR
.$key.'#>'] = $value;
1485 if (!empty($ignoretags)) {
1486 $text = str_replace($ignoretags,array_keys($ignoretags),$text);
1492 * Extract tags (any text enclosed by < and > to avoid being processed by filters.
1493 * It returns the text converted with some <%xTEXTFILTER_EXCL_SEPARATORx%> codes replacing the extracted text. Such extracted
1494 * texts are returned in the tags array (as values), with codes as keys.
1496 * @param string $text the text that we are filtering (in/out)
1497 * @param array $tags an array of saved strings useful to rebuild the original text (in/out)
1499 function filter_save_tags(&$text, &$tags) {
1501 preg_match_all('/<([^#%*].*?)>/is',$text,$list_of_newtags);
1502 foreach (array_unique($list_of_newtags[0]) as $ntkey=>$value) {
1503 $prefix = (string)(count($tags) +
1);
1504 $tags['<%'.$prefix.TEXTFILTER_EXCL_SEPARATOR
.$ntkey.'%>'] = $value;
1506 if (!empty($tags)) {
1507 $text = str_replace($tags,array_keys($tags),$text);
1512 * Add missing openpopup javascript to HTML files.
1514 * @param string $text
1517 function filter_add_javascript($text) {
1520 if (stripos($text, '</html>') === FALSE) {
1521 return $text; // This is not a html file.
1523 if (strpos($text, 'onclick="return openpopup') === FALSE) {
1524 return $text; // No popup - no need to add javascript.
1527 <script type=\"text/javascript\">
1529 function openpopup(url,name,options,fullscreen) {
1530 fullurl = \"".$CFG->wwwroot
."\" + url;
1531 windowobj = window.open(fullurl,name,options);
1533 windowobj.moveTo(0,0);
1534 windowobj.resizeTo(screen.availWidth,screen.availHeight);
1541 if (stripos($text, '</head>') !== FALSE) {
1542 // Try to add it into the head element.
1543 $text = str_ireplace('</head>', $js.'</head>', $text);
1547 // Last chance - try adding head element.
1548 return preg_replace("/<html.*?>/is", "\\0<head>".$js.'</head>', $text);