3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * Library functions for managing text filter plugins.
23 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') ||
die();
29 /** The states a filter can be in, stored in the filter_active table. */
30 define('TEXTFILTER_ON', 1);
31 /** The states a filter can be in, stored in the filter_active table. */
32 define('TEXTFILTER_INHERIT', 0);
33 /** The states a filter can be in, stored in the filter_active table. */
34 define('TEXTFILTER_OFF', -1);
35 /** The states a filter can be in, stored in the filter_active table. */
36 define('TEXTFILTER_DISABLED', -9999);
39 * Define one exclusive separator that we'll use in the temp saved tags
40 * keys. It must be something rare enough to avoid having matches with
41 * filterobjects. MDL-18165
43 define('TEXTFILTER_EXCL_SEPARATOR', '-%-');
47 * Class to manage the filtering of strings. It is intended that this class is
48 * only used by weblib.php. Client code should probably be using the
49 * format_text and format_string functions.
51 * This class is a singleton.
55 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
56 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
58 class filter_manager
{
60 * @var array This list of active filters, by context, for filtering content.
61 * An array contextid => array of filter objects.
63 protected $textfilters = array();
66 * @var array This list of active filters, by context, for filtering strings.
67 * An array contextid => array of filter objects.
69 protected $stringfilters = array();
71 /** @var array Exploded version of $CFG->stringfilters. */
72 protected $stringfilternames = array();
74 /** @var object Holds the singleton instance. */
75 protected static $singletoninstance;
77 protected function __construct() {
78 $this->stringfilternames
= filter_get_string_filters();
82 * @return filter_manager the singleton instance.
84 public static function instance() {
86 if (is_null(self
::$singletoninstance)) {
87 if (!empty($CFG->perfdebug
)) {
88 self
::$singletoninstance = new performance_measuring_filter_manager();
90 self
::$singletoninstance = new self();
93 return self
::$singletoninstance;
97 * Load all the filters required by this context.
99 * @param object $context
101 protected function load_filters($context) {
102 $filters = filter_get_active_in_context($context);
103 $this->textfilters
[$context->id
] = array();
104 $this->stringfilters
[$context->id
] = array();
105 foreach ($filters as $filtername => $localconfig) {
106 $filter = $this->make_filter_object($filtername, $context, $localconfig);
107 if (is_null($filter)) {
110 $this->textfilters
[$context->id
][] = $filter;
111 if (in_array($filtername, $this->stringfilternames
)) {
112 $this->stringfilters
[$context->id
][] = $filter;
118 * Factory method for creating a filter
120 * @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
121 * @param object $context context object.
122 * @param array $localconfig array of local configuration variables for this filter.
123 * @return object moodle_text_filter The filter, or null, if this type of filter is
124 * not recognised or could not be created.
126 protected function make_filter_object($filtername, $context, $localconfig) {
128 $path = $CFG->dirroot
.'/'. $filtername .'/filter.php';
129 if (!is_readable($path)) {
134 $filterclassname = 'filter_' . basename($filtername);
135 if (class_exists($filterclassname)) {
136 return new $filterclassname($context, $localconfig);
139 // TODO: deprecated since 2.2, will be out in 2.3, see MDL-29996
140 $legacyfunctionname = basename($filtername) . '_filter';
141 if (function_exists($legacyfunctionname)) {
142 return new legacy_filter($legacyfunctionname, $context, $localconfig);
149 * @todo Document this function
150 * @param string $text
151 * @param array $filterchain
152 * @param array $options options passed to the filters
153 * @return string $text
155 protected function apply_filter_chain($text, $filterchain, array $options = array()) {
156 foreach ($filterchain as $filter) {
157 $text = $filter->filter($text, $options);
163 * @todo Document this function
164 * @param object $context
165 * @return object A text filter
167 protected function get_text_filters($context) {
168 if (!isset($this->textfilters
[$context->id
])) {
169 $this->load_filters($context);
171 return $this->textfilters
[$context->id
];
175 * @todo Document this function
176 * @param object $context
177 * @return object A string filter
179 protected function get_string_filters($context) {
180 if (!isset($this->stringfilters
[$context->id
])) {
181 $this->load_filters($context);
183 return $this->stringfilters
[$context->id
];
189 * @param string $text The text to filter
190 * @param object $context
191 * @param array $options options passed to the filters
192 * @return string resulting text
194 public function filter_text($text, $context, array $options = array()) {
195 $text = $this->apply_filter_chain($text, $this->get_text_filters($context), $options);
196 /// <nolink> tags removed for XHTML compatibility
197 $text = str_replace(array('<nolink>', '</nolink>'), '', $text);
202 * Filter a piece of string
204 * @param string $string The text to filter
205 * @param object $context
206 * @return string resulting string
208 public function filter_string($string, $context) {
209 return $this->apply_filter_chain($string, $this->get_string_filters($context));
213 * @todo Document this function
214 * @param object $context
215 * @return object A string filter
217 public function text_filtering_hash($context) {
218 $filters = $this->get_text_filters($context);
220 foreach ($filters as $filter) {
221 $hashes[] = $filter->hash();
223 return implode('-', $hashes);
228 * Filter manager subclass that does nothing. Having this simplifies the logic
229 * of format_text, etc.
231 * @todo Document this class
235 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
236 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
238 class null_filter_manager
{
242 public function filter_text($text, $context, $options) {
249 public function filter_string($string, $context) {
256 public function text_filtering_hash() {
262 * Filter manager subclass that tacks how much work it does.
264 * @todo Document this class
268 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
269 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
271 class performance_measuring_filter_manager
extends filter_manager
{
273 protected $filterscreated = 0;
274 protected $textsfiltered = 0;
275 protected $stringsfiltered = 0;
278 * @param string $filtername
279 * @param object $context
280 * @param mixed $localconfig
283 protected function make_filter_object($filtername, $context, $localconfig) {
284 $this->filterscreated++
;
285 return parent
::make_filter_object($filtername, $context, $localconfig);
289 * @param string $text
290 * @param object $context
291 * @param array $options options passed to the filters
294 public function filter_text($text, $context, array $options = array()) {
295 $this->textsfiltered++
;
296 return parent
::filter_text($text, $context, $options);
300 * @param string $string
301 * @param object $context
304 public function filter_string($string, $context) {
305 $this->stringsfiltered++
;
306 return parent
::filter_string($string, $context);
312 public function get_performance_summary() {
314 'contextswithfilters' => count($this->textfilters
),
315 'filterscreated' => $this->filterscreated
,
316 'textsfiltered' => $this->textsfiltered
,
317 'stringsfiltered' => $this->stringsfiltered
,
319 'contextswithfilters' => 'Contexts for which filters were loaded',
320 'filterscreated' => 'Filters created',
321 'textsfiltered' => 'Pieces of content filtered',
322 'stringsfiltered' => 'Strings filtered',
328 * Base class for text filters. You just need to override this class and
329 * implement the filter method.
333 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
334 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
336 abstract class moodle_text_filter
{
337 /** @var object The context we are in. */
339 /** @var array Any local configuration for this filter in this context. */
340 protected $localconfig;
343 * Set any context-specific configuration for this filter.
344 * @param object $context The current course id.
345 * @param object $context The current context.
346 * @param array $config Any context-specific configuration for this filter.
348 public function __construct($context, array $localconfig) {
349 $this->context
= $context;
350 $this->localconfig
= $localconfig;
354 * @return string The class name of the current class
356 public function hash() {
361 * Override this function to actually implement the filtering.
363 * @param $text some HTML content.
364 * @param array $options options passed to the filters
365 * @return the HTML content after the filtering has been applied.
367 public abstract function filter($text, array $options = array());
371 * moodle_text_filter implementation that encapsulates an old-style filter that
372 * only defines a function, not a class.
374 * @deprecated since 2.2, see MDL-29995
375 * @todo will be out in 2.3, see MDL-29996
378 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
379 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
381 class legacy_filter
extends moodle_text_filter
{
383 protected $filterfunction;
387 * Set any context-specific configuration for this filter.
389 * @param string $filterfunction
390 * @param object $context The current context.
391 * @param array $config Any context-specific configuration for this filter.
393 public function __construct($filterfunction, $context, array $localconfig) {
394 parent
::__construct($context, $localconfig);
395 $this->filterfunction
= $filterfunction;
396 $this->courseid
= get_courseid_from_context($this->context
);
400 * @param string $text
401 * @param array $options options - not supported for legacy filters
404 public function filter($text, array $options = array()) {
405 if ($this->courseid
) {
406 // old filters are called only when inside courses
407 return call_user_func($this->filterfunction
, $this->courseid
, $text);
415 * This is just a little object to define a phrase and some instructions
416 * for how to process it. Filters can create an array of these to pass
417 * to the filter_phrases function below.
421 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
422 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
433 var $replacementphrase;
435 var $work_hreftagbegin;
436 var $work_hreftagend;
437 var $work_casesensitive;
439 var $work_replacementphrase;
441 var $work_calculated;
444 * A constructor just because I like constructing
446 * @param string $phrase
447 * @param string $hreftagbegin
448 * @param string $hreftagend
449 * @param bool $casesensitive
450 * @param bool $fullmatch
451 * @param mixed $replacementphrase
453 function filterobject($phrase, $hreftagbegin = '<span class="highlight">',
454 $hreftagend = '</span>',
455 $casesensitive = false,
457 $replacementphrase = NULL) {
459 $this->phrase
= $phrase;
460 $this->hreftagbegin
= $hreftagbegin;
461 $this->hreftagend
= $hreftagend;
462 $this->casesensitive
= $casesensitive;
463 $this->fullmatch
= $fullmatch;
464 $this->replacementphrase
= $replacementphrase;
465 $this->work_calculated
= false;
471 * Look up the name of this filter in the most appropriate location.
472 * If $filterlocation = 'mod' then does get_string('filtername', $filter);
473 * else if $filterlocation = 'filter' then does get_string('filtername', 'filter_' . $filter);
474 * with a fallback to get_string('filtername', $filter) for backwards compatibility.
475 * These are the only two options supported at the moment.
477 * @param string $filter the folder name where the filter lives.
478 * @return string the human-readable name for this filter.
480 function filter_get_name($filter) {
481 // TODO: should we be using pluginname here instead? , see MDL-29998
482 list($type, $filter) = explode('/', $filter);
485 $strfiltername = get_string('filtername', 'filter_' . $filter);
486 if (substr($strfiltername, 0, 2) != '[[') {
487 // found a valid string.
488 return $strfiltername;
490 // Fall through to try the legacy location.
492 // TODO: deprecated since 2.2, will be out in 2.3, see MDL-29996
494 $strfiltername = get_string('filtername', $filter);
495 if (substr($strfiltername, 0, 2) == '[[') {
496 $strfiltername .= ' (' . $type . '/' . $filter . ')';
498 return $strfiltername;
501 throw new coding_exception('Unknown filter type ' . $type);
506 * Get the names of all the filters installed in this Moodle.
509 * @return array path => filter name from the appropriate lang file. e.g.
510 * array('mod/glossary' => 'Glossary Auto-linking', 'filter/tex' => 'TeX Notation');
511 * sorted in alphabetical order of name.
513 function filter_get_all_installed() {
515 $filternames = array();
516 // TODO: deprecated since 2.2, will be out in 2.3, see MDL-29996
517 $filterlocations = array('mod', 'filter');
518 foreach ($filterlocations as $filterlocation) {
519 // TODO: move get_list_of_plugins() to get_plugin_list()
520 $filters = get_list_of_plugins($filterlocation);
521 foreach ($filters as $filter) {
522 // MDL-29994 - Ignore mod/data and mod/glossary filters forever, this will be out in 2.3
523 if ($filterlocation == 'mod' && ($filter == 'data' ||
$filter == 'glossary')) {
526 $path = $filterlocation . '/' . $filter;
527 if (is_readable($CFG->dirroot
. '/' . $path . '/filter.php')) {
528 $strfiltername = filter_get_name($path);
529 $filternames[$path] = $strfiltername;
533 collatorlib
::asort($filternames);
538 * Set the global activated state for a text filter.
541 * @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
542 * @param integer $state One of the values TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_DISABLED.
543 * @param integer $sortorder (optional) a position in the sortorder to place this filter.
544 * If not given defaults to:
545 * No change in order if we are updating an existing record, and not changing to or from TEXTFILTER_DISABLED.
546 * Just after the last currently active filter when adding an unknown filter
547 * in state TEXTFILTER_ON or TEXTFILTER_OFF, or enabling/disabling an existing filter.
548 * Just after the very last filter when adding an unknown filter in state TEXTFILTER_DISABLED
550 function filter_set_global_state($filter, $state, $sortorder = false) {
553 // Check requested state is valid.
554 if (!in_array($state, array(TEXTFILTER_ON
, TEXTFILTER_OFF
, TEXTFILTER_DISABLED
))) {
555 throw new coding_exception("Illegal option '$state' passed to filter_set_global_state. " .
556 "Must be one of TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_DISABLED.");
559 // Check sortorder is valid.
560 if ($sortorder !== false) {
561 if ($sortorder < 1 ||
$sortorder > $DB->get_field('filter_active', 'MAX(sortorder)', array()) +
1) {
562 throw new coding_exception("Invalid sort order passed to filter_set_global_state.");
566 // See if there is an existing record.
567 $syscontext = get_context_instance(CONTEXT_SYSTEM
);
568 $rec = $DB->get_record('filter_active', array('filter' => $filter, 'contextid' => $syscontext->id
));
572 $rec->filter
= $filter;
573 $rec->contextid
= $syscontext->id
;
576 if ($sortorder === false && !($rec->active
== TEXTFILTER_DISABLED
xor $state == TEXTFILTER_DISABLED
)) {
577 $sortorder = $rec->sortorder
;
581 // Automatic sort order.
582 if ($sortorder === false) {
583 if ($state == TEXTFILTER_DISABLED
&& $insert) {
584 $prevmaxsortorder = $DB->get_field('filter_active', 'MAX(sortorder)', array());
586 $prevmaxsortorder = $DB->get_field_select('filter_active', 'MAX(sortorder)', 'active <> ?', array(TEXTFILTER_DISABLED
));
588 if (empty($prevmaxsortorder)) {
591 $sortorder = $prevmaxsortorder +
1;
592 if (!$insert && $state == TEXTFILTER_DISABLED
) {
593 $sortorder = $prevmaxsortorder;
598 // Move any existing records out of the way of the sortorder.
600 $DB->execute('UPDATE {filter_active} SET sortorder = sortorder + 1 WHERE sortorder >= ?', array($sortorder));
601 } else if ($sortorder != $rec->sortorder
) {
602 $sparesortorder = $DB->get_field('filter_active', 'MIN(sortorder)', array()) - 1;
603 $DB->set_field('filter_active', 'sortorder', $sparesortorder, array('filter' => $filter, 'contextid' => $syscontext->id
));
604 if ($sortorder < $rec->sortorder
) {
605 $DB->execute('UPDATE {filter_active} SET sortorder = sortorder + 1 WHERE sortorder >= ? AND sortorder < ?',
606 array($sortorder, $rec->sortorder
));
607 } else if ($sortorder > $rec->sortorder
) {
608 $DB->execute('UPDATE {filter_active} SET sortorder = sortorder - 1 WHERE sortorder <= ? AND sortorder > ?',
609 array($sortorder, $rec->sortorder
));
613 // Insert/update the new record.
614 $rec->active
= $state;
615 $rec->sortorder
= $sortorder;
617 $DB->insert_record('filter_active', $rec);
619 $DB->update_record('filter_active', $rec);
624 * @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
625 * @return boolean is this filter allowed to be used on this site. That is, the
626 * admin has set the global 'active' setting to On, or Off, but available.
628 function filter_is_enabled($filter) {
629 return array_key_exists($filter, filter_get_globally_enabled());
633 * Return a list of all the filters that may be in use somewhere.
635 * @staticvar array $enabledfilters
636 * @return array where the keys and values are both the filter name, like 'filter/tex'.
638 function filter_get_globally_enabled() {
639 static $enabledfilters = null;
640 if (is_null($enabledfilters)) {
641 $filters = filter_get_global_states();
642 $enabledfilters = array();
643 foreach ($filters as $filter => $filerinfo) {
644 if ($filerinfo->active
!= TEXTFILTER_DISABLED
) {
645 $enabledfilters[$filter] = $filter;
649 return $enabledfilters;
653 * Return the names of the filters that should also be applied to strings
654 * (when they are enabled).
657 * @return array where the keys and values are both the filter name, like 'filter/tex'.
659 function filter_get_string_filters() {
661 $stringfilters = array();
662 if (!empty($CFG->filterall
) && !empty($CFG->stringfilters
)) {
663 $stringfilters = explode(',', $CFG->stringfilters
);
664 $stringfilters = array_combine($stringfilters, $stringfilters);
666 return $stringfilters;
670 * Sets whether a particular active filter should be applied to all strings by
671 * format_string, or just used by format_text.
673 * @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
674 * @param boolean $applytostrings if true, this filter will apply to format_string
675 * and format_text, when it is enabled.
677 function filter_set_applies_to_strings($filter, $applytostrings) {
678 $stringfilters = filter_get_string_filters();
679 $numstringfilters = count($stringfilters);
680 if ($applytostrings) {
681 $stringfilters[$filter] = $filter;
683 unset($stringfilters[$filter]);
685 if (count($stringfilters) != $numstringfilters) {
686 set_config('stringfilters', implode(',', $stringfilters));
687 set_config('filterall', !empty($stringfilters));
692 * Set the local activated state for a text filter.
695 * @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
696 * @param integer $contextid The id of the context to get the local config for.
697 * @param integer $state One of the values TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_INHERIT.
700 function filter_set_local_state($filter, $contextid, $state) {
703 // Check requested state is valid.
704 if (!in_array($state, array(TEXTFILTER_ON
, TEXTFILTER_OFF
, TEXTFILTER_INHERIT
))) {
705 throw new coding_exception("Illegal option '$state' passed to filter_set_local_state. " .
706 "Must be one of TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_INHERIT.");
709 if ($contextid == get_context_instance(CONTEXT_SYSTEM
)->id
) {
710 throw new coding_exception('You cannot use filter_set_local_state ' .
711 'with $contextid equal to the system context id.');
714 if ($state == TEXTFILTER_INHERIT
) {
715 $DB->delete_records('filter_active', array('filter' => $filter, 'contextid' => $contextid));
719 $rec = $DB->get_record('filter_active', array('filter' => $filter, 'contextid' => $contextid));
724 $rec->filter
= $filter;
725 $rec->contextid
= $contextid;
728 $rec->active
= $state;
731 $DB->insert_record('filter_active', $rec);
733 $DB->update_record('filter_active', $rec);
738 * Set a particular local config variable for a filter in a context.
741 * @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
742 * @param integer $contextid The id of the context to get the local config for.
743 * @param string $name the setting name.
744 * @param string $value the corresponding value.
746 function filter_set_local_config($filter, $contextid, $name, $value) {
748 $rec = $DB->get_record('filter_config', array('filter' => $filter, 'contextid' => $contextid, 'name' => $name));
753 $rec->filter
= $filter;
754 $rec->contextid
= $contextid;
758 $rec->value
= $value;
761 $DB->insert_record('filter_config', $rec);
763 $DB->update_record('filter_config', $rec);
768 * Remove a particular local config variable for a filter in a context.
771 * @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
772 * @param integer $contextid The id of the context to get the local config for.
773 * @param string $name the setting name.
775 function filter_unset_local_config($filter, $contextid, $name) {
777 $DB->delete_records('filter_config', array('filter' => $filter, 'contextid' => $contextid, 'name' => $name));
781 * Get local config variables for a filter in a context. Normally (when your
782 * filter is running) you don't need to call this, becuase the config is fetched
783 * for you automatically. You only need this, for example, when you are getting
784 * the config so you can show the user an editing from.
787 * @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
788 * @param integer $contextid The ID of the context to get the local config for.
789 * @return array of name => value pairs.
791 function filter_get_local_config($filter, $contextid) {
793 return $DB->get_records_menu('filter_config', array('filter' => $filter, 'contextid' => $contextid), '', 'name,value');
797 * This function is for use by backup. Gets all the filter information specific
801 * @param int $contextid
802 * @return array Array with two elements. The first element is an array of objects with
803 * fields filter and active. These come from the filter_active table. The
804 * second element is an array of objects with fields filter, name and value
805 * from the filter_config table.
807 function filter_get_all_local_settings($contextid) {
809 $context = get_context_instance(CONTEXT_SYSTEM
);
811 $DB->get_records('filter_active', array('contextid' => $contextid), 'filter', 'filter,active'),
812 $DB->get_records('filter_config', array('contextid' => $contextid), 'filter,name', 'filter,name,value'),
817 * Get the list of active filters, in the order that they should be used
818 * for a particular context, along with any local configuration variables.
821 * @param object $context a context
822 * @return array an array where the keys are the filter names, for example
823 * 'filter/tex' or 'mod/glossary' and the values are any local
824 * configuration for that filter, as an array of name => value pairs
825 * from the filter_config table. In a lot of cases, this will be an
826 * empty array. So, an example return value for this function might be
827 * array('filter/tex' => array(), 'mod/glossary' => array('glossaryid', 123))
829 function filter_get_active_in_context($context) {
830 global $DB, $FILTERLIB_PRIVATE;
832 if (!isset($FILTERLIB_PRIVATE)) {
833 $FILTERLIB_PRIVATE = new stdClass();
836 // Use cache (this is a within-request cache only) if available. See
837 // function filter_preload_activities.
838 if (isset($FILTERLIB_PRIVATE->active
) &&
839 array_key_exists($context->id
, $FILTERLIB_PRIVATE->active
)) {
840 return $FILTERLIB_PRIVATE->active
[$context->id
];
843 $contextids = str_replace('/', ',', trim($context->path
, '/'));
845 // The following SQL is tricky. It is explained on
846 // http://docs.moodle.org/dev/Filter_enable/disable_by_context
847 $sql = "SELECT active.filter, fc.name, fc.value
848 FROM (SELECT f.filter, MAX(f.sortorder) AS sortorder
849 FROM {filter_active} f
850 JOIN {context} ctx ON f.contextid = ctx.id
851 WHERE ctx.id IN ($contextids)
853 HAVING MAX(f.active * " . $DB->sql_cast_2signed('ctx.depth') .
854 ") > -MIN(f.active * " . $DB->sql_cast_2signed('ctx.depth') . ")
856 LEFT JOIN {filter_config} fc ON fc.filter = active.filter AND fc.contextid = $context->id
857 ORDER BY active.sortorder";
858 $rs = $DB->get_recordset_sql($sql);
860 // Masssage the data into the specified format to return.
862 foreach ($rs as $row) {
863 if (!isset($filters[$row->filter
])) {
864 $filters[$row->filter
] = array();
866 if (!is_null($row->name
)) {
867 $filters[$row->filter
][$row->name
] = $row->value
;
877 * Preloads the list of active filters for all activities (modules) on the course
878 * using two database queries.
879 * @param course_modinfo $modinfo Course object from get_fast_modinfo
881 function filter_preload_activities(course_modinfo
$modinfo) {
882 global $DB, $FILTERLIB_PRIVATE;
884 if (!isset($FILTERLIB_PRIVATE)) {
885 $FILTERLIB_PRIVATE = new stdClass();
888 // Don't repeat preload
889 if (!isset($FILTERLIB_PRIVATE->preloaded
)) {
890 $FILTERLIB_PRIVATE->preloaded
= array();
892 if (!empty($FILTERLIB_PRIVATE->preloaded
[$modinfo->get_course_id()])) {
895 $FILTERLIB_PRIVATE->preloaded
[$modinfo->get_course_id()] = true;
897 // Get contexts for all CMs
898 $cmcontexts = array();
899 $cmcontextids = array();
900 foreach ($modinfo->get_cms() as $cm) {
901 $modulecontext = get_context_instance(CONTEXT_MODULE
, $cm->id
);
902 $cmcontextids[] = $modulecontext->id
;
903 $cmcontexts[] = $modulecontext;
906 // Get course context and all other parents...
907 $coursecontext = get_context_instance(CONTEXT_COURSE
, $modinfo->get_course_id());
908 $parentcontextids = explode('/', substr($coursecontext->path
, 1));
909 $allcontextids = array_merge($cmcontextids, $parentcontextids);
911 // Get all filter_active rows relating to all these contexts
912 list ($sql, $params) = $DB->get_in_or_equal($allcontextids);
913 $filteractives = $DB->get_records_select('filter_active', "contextid $sql", $params);
915 // Get all filter_config only for the cm contexts
916 list ($sql, $params) = $DB->get_in_or_equal($cmcontextids);
917 $filterconfigs = $DB->get_records_select('filter_config', "contextid $sql", $params);
919 // Note: I was a bit surprised that filter_config only works for the
920 // most specific context (i.e. it does not need to be checked for course
921 // context if we only care about CMs) however basede on code in
922 // filter_get_active_in_context, this does seem to be correct.
924 // Build course default active list. Initially this will be an array of
925 // filter name => active score (where an active score >0 means it's active)
926 $courseactive = array();
928 // Also build list of filter_active rows below course level, by contextid
929 $remainingactives = array();
931 // Array lists filters that are banned at top level
934 // Add any active filters in parent contexts to the array
935 foreach ($filteractives as $row) {
936 $depth = array_search($row->contextid
, $parentcontextids);
937 if ($depth !== false) {
939 if (!array_key_exists($row->filter
, $courseactive)) {
940 $courseactive[$row->filter
] = 0;
942 // This maths copes with reading rows in any order. Turning on/off
943 // at site level counts 1, at next level down 4, at next level 9,
944 // then 16, etc. This means the deepest level always wins, except
945 // against the -9999 at top level.
946 $courseactive[$row->filter
] +
=
947 ($depth +
1) * ($depth +
1) * $row->active
;
949 if ($row->active
== TEXTFILTER_DISABLED
) {
950 $banned[$row->filter
] = true;
953 // Build list of other rows indexed by contextid
954 if (!array_key_exists($row->contextid
, $remainingactives)) {
955 $remainingactives[$row->contextid
] = array();
957 $remainingactives[$row->contextid
][] = $row;
961 // Chuck away the ones that aren't active
962 foreach ($courseactive as $filter=>$score) {
964 unset($courseactive[$filter]);
966 $courseactive[$filter] = array();
970 // Loop through the contexts to reconstruct filter_active lists for each
972 if (!isset($FILTERLIB_PRIVATE->active
)) {
973 $FILTERLIB_PRIVATE->active
= array();
975 foreach ($cmcontextids as $contextid) {
977 $FILTERLIB_PRIVATE->active
[$contextid] = $courseactive;
979 // Are there any changes to the active list?
980 if (array_key_exists($contextid, $remainingactives)) {
981 foreach ($remainingactives[$contextid] as $row) {
982 if ($row->active
> 0 && empty($banned[$row->filter
])) {
983 // If it's marked active for specific context, add entry
984 // (doesn't matter if one exists already)
985 $FILTERLIB_PRIVATE->active
[$contextid][$row->filter
] = array();
987 // If it's marked inactive, remove entry (doesn't matter
988 // if it doesn't exist)
989 unset($FILTERLIB_PRIVATE->active
[$contextid][$row->filter
]);
995 // Process all config rows to add config data to these entries
996 foreach ($filterconfigs as $row) {
997 if (isset($FILTERLIB_PRIVATE->active
[$row->contextid
][$row->filter
])) {
998 $FILTERLIB_PRIVATE->active
[$row->contextid
][$row->filter
][$row->name
] = $row->value
;
1004 * List all of the filters that are available in this context, and what the
1005 * local and inherited states of that filter are.
1008 * @param object $context a context that is not the system context.
1009 * @return array an array with filter names, for example 'filter/tex' or
1010 * 'mod/glossary' as keys. and and the values are objects with fields:
1011 * ->filter filter name, same as the key.
1012 * ->localstate TEXTFILTER_ON/OFF/INHERIT
1013 * ->inheritedstate TEXTFILTER_ON/OFF - the state that will be used if localstate is set to TEXTFILTER_INHERIT.
1015 function filter_get_available_in_context($context) {
1018 // The complex logic is working out the active state in the parent context,
1019 // so strip the current context from the list.
1020 $contextids = explode('/', trim($context->path
, '/'));
1021 array_pop($contextids);
1022 $contextids = implode(',', $contextids);
1023 if (empty($contextids)) {
1024 throw new coding_exception('filter_get_available_in_context cannot be called with the system context.');
1027 // The following SQL is tricky, in the same way at the SQL in filter_get_active_in_context.
1028 $sql = "SELECT parent_states.filter,
1029 CASE WHEN fa.active IS NULL THEN " . TEXTFILTER_INHERIT
. "
1030 ELSE fa.active END AS localstate,
1031 parent_states.inheritedstate
1032 FROM (SELECT f.filter, MAX(f.sortorder) AS sortorder,
1033 CASE WHEN MAX(f.active * " . $DB->sql_cast_2signed('ctx.depth') .
1034 ") > -MIN(f.active * " . $DB->sql_cast_2signed('ctx.depth') . ") THEN " . TEXTFILTER_ON
. "
1035 ELSE " . TEXTFILTER_OFF
. " END AS inheritedstate
1036 FROM {filter_active} f
1037 JOIN {context} ctx ON f.contextid = ctx.id
1038 WHERE ctx.id IN ($contextids)
1040 HAVING MIN(f.active) > " . TEXTFILTER_DISABLED
. "
1042 LEFT JOIN {filter_active} fa ON fa.filter = parent_states.filter AND fa.contextid = $context->id
1043 ORDER BY parent_states.sortorder";
1044 return $DB->get_records_sql($sql);
1048 * This function is for use by the filter administration page.
1051 * @return array 'filtername' => object with fields 'filter' (=filtername), 'active' and 'sortorder'
1053 function filter_get_global_states() {
1055 $context = get_context_instance(CONTEXT_SYSTEM
);
1056 return $DB->get_records('filter_active', array('contextid' => $context->id
), 'sortorder', 'filter,active,sortorder');
1060 * Delete all the data in the database relating to a filter, prior to deleting it.
1063 * @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
1065 function filter_delete_all_for_filter($filter) {
1067 if (substr($filter, 0, 7) == 'filter/') {
1068 unset_all_config_for_plugin('filter_' . basename($filter));
1070 $DB->delete_records('filter_active', array('filter' => $filter));
1071 $DB->delete_records('filter_config', array('filter' => $filter));
1075 * Delete all the data in the database relating to a context, used when contexts are deleted.
1077 * @param integer $contextid The id of the context being deleted.
1079 function filter_delete_all_for_context($contextid) {
1081 $DB->delete_records('filter_active', array('contextid' => $contextid));
1082 $DB->delete_records('filter_config', array('contextid' => $contextid));
1086 * Does this filter have a global settings page in the admin tree?
1087 * (The settings page for a filter must be called, for example,
1088 * filtersettingfiltertex or filtersettingmodglossay.)
1090 * @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
1091 * @return boolean Whether there should be a 'Settings' link on the config page.
1093 function filter_has_global_settings($filter) {
1095 $settingspath = $CFG->dirroot
. '/' . $filter . '/filtersettings.php';
1096 return is_readable($settingspath);
1100 * Does this filter have local (per-context) settings?
1102 * @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
1103 * @return boolean Whether there should be a 'Settings' link on the manage filters in context page.
1105 function filter_has_local_settings($filter) {
1107 $settingspath = $CFG->dirroot
. '/' . $filter . '/filterlocalsettings.php';
1108 return is_readable($settingspath);
1112 * Certain types of context (block and user) may not have local filter settings.
1113 * the function checks a context to see whether it may have local config.
1115 * @param object $context a context.
1116 * @return boolean whether this context may have local filter settings.
1118 function filter_context_may_have_filter_settings($context) {
1119 return $context->contextlevel
!= CONTEXT_BLOCK
&& $context->contextlevel
!= CONTEXT_USER
;
1123 * Process phrases intelligently found within a HTML text (such as adding links)
1125 * @staticvar array $usedpharses
1126 * @param string $text the text that we are filtering
1127 * @param array $link_array an array of filterobjects
1128 * @param array $ignoretagsopen an array of opening tags that we should ignore while filtering
1129 * @param array $ignoretagsclose an array of corresponding closing tags
1130 * @param bool $overridedefaultignore True to only use tags provided by arguments
1133 function filter_phrases($text, &$link_array, $ignoretagsopen=NULL, $ignoretagsclose=NULL,
1134 $overridedefaultignore=false) {
1138 static $usedphrases;
1140 $ignoretags = array(); //To store all the enclosig tags to be completely ignored
1141 $tags = array(); //To store all the simple tags to be ignored
1143 if (!$overridedefaultignore) {
1144 // A list of open/close tags that we should not replace within
1145 // Extended to include <script>, <textarea>, <select> and <a> tags
1146 // Regular expression allows tags with or without attributes
1147 $filterignoretagsopen = array('<head>' , '<nolink>' , '<span class="nolink">',
1148 '<script(\s[^>]*?)?>', '<textarea(\s[^>]*?)?>',
1149 '<select(\s[^>]*?)?>', '<a(\s[^>]*?)?>');
1150 $filterignoretagsclose = array('</head>', '</nolink>', '</span>',
1151 '</script>', '</textarea>', '</select>','</a>');
1153 // Set an empty default list
1154 $filterignoretagsopen = array();
1155 $filterignoretagsclose = array();
1158 // Add the user defined ignore tags to the default list
1159 if ( is_array($ignoretagsopen) ) {
1160 foreach ($ignoretagsopen as $open) {
1161 $filterignoretagsopen[] = $open;
1163 foreach ($ignoretagsclose as $close) {
1164 $filterignoretagsclose[] = $close;
1168 /// Invalid prefixes and suffixes for the fullmatch searches
1169 /// Every "word" character, but the underscore, is a invalid suffix or prefix.
1170 /// (nice to use this because it includes national characters (accents...) as word characters.
1171 $filterinvalidprefixes = '([^\W_])';
1172 $filterinvalidsuffixes = '([^\W_])';
1174 //// Double up some magic chars to avoid "accidental matches"
1175 $text = preg_replace('/([#*%])/','\1\1',$text);
1178 ////Remove everything enclosed by the ignore tags from $text
1179 filter_save_ignore_tags($text,$filterignoretagsopen,$filterignoretagsclose,$ignoretags);
1181 /// Remove tags from $text
1182 filter_save_tags($text,$tags);
1184 /// Time to cycle through each phrase to be linked
1185 $size = sizeof($link_array);
1186 for ($n=0; $n < $size; $n++
) {
1187 $linkobject =& $link_array[$n];
1189 /// Set some defaults if certain properties are missing
1190 /// Properties may be missing if the filterobject class has not been used to construct the object
1191 if (empty($linkobject->phrase
)) {
1195 /// Avoid integers < 1000 to be linked. See bug 1446.
1196 $intcurrent = intval($linkobject->phrase
);
1197 if (!empty($intcurrent) && strval($intcurrent) == $linkobject->phrase
&& $intcurrent < 1000) {
1201 /// All this work has to be done ONLY it it hasn't been done before
1202 if (!$linkobject->work_calculated
) {
1203 if (!isset($linkobject->hreftagbegin
) or !isset($linkobject->hreftagend
)) {
1204 $linkobject->work_hreftagbegin
= '<span class="highlight"';
1205 $linkobject->work_hreftagend
= '</span>';
1207 $linkobject->work_hreftagbegin
= $linkobject->hreftagbegin
;
1208 $linkobject->work_hreftagend
= $linkobject->hreftagend
;
1211 /// Double up chars to protect true duplicates
1212 /// be cleared up before returning to the user.
1213 $linkobject->work_hreftagbegin
= preg_replace('/([#*%])/','\1\1',$linkobject->work_hreftagbegin
);
1215 if (empty($linkobject->casesensitive
)) {
1216 $linkobject->work_casesensitive
= false;
1218 $linkobject->work_casesensitive
= true;
1220 if (empty($linkobject->fullmatch
)) {
1221 $linkobject->work_fullmatch
= false;
1223 $linkobject->work_fullmatch
= true;
1226 /// Strip tags out of the phrase
1227 $linkobject->work_phrase
= strip_tags($linkobject->phrase
);
1229 /// Double up chars that might cause a false match -- the duplicates will
1230 /// be cleared up before returning to the user.
1231 $linkobject->work_phrase
= preg_replace('/([#*%])/','\1\1',$linkobject->work_phrase
);
1233 /// Set the replacement phrase properly
1234 if ($linkobject->replacementphrase
) { //We have specified a replacement phrase
1236 $linkobject->work_replacementphrase
= strip_tags($linkobject->replacementphrase
);
1237 } else { //The replacement is the original phrase as matched below
1238 $linkobject->work_replacementphrase
= '$1';
1241 /// Quote any regular expression characters and the delimiter in the work phrase to be searched
1242 $linkobject->work_phrase
= preg_quote($linkobject->work_phrase
, '/');
1245 $linkobject->work_calculated
= true;
1249 /// If $CFG->filtermatchoneperpage, avoid previously (request) linked phrases
1250 if (!empty($CFG->filtermatchoneperpage
)) {
1251 if (!empty($usedphrases) && in_array($linkobject->work_phrase
,$usedphrases)) {
1256 /// Regular expression modifiers
1257 $modifiers = ($linkobject->work_casesensitive
) ?
's' : 'isu'; // works in unicode mode!
1259 /// Do we need to do a fullmatch?
1260 /// If yes then go through and remove any non full matching entries
1261 if ($linkobject->work_fullmatch
) {
1262 $notfullmatches = array();
1263 $regexp = '/'.$filterinvalidprefixes.'('.$linkobject->work_phrase
.')|('.$linkobject->work_phrase
.')'.$filterinvalidsuffixes.'/'.$modifiers;
1265 preg_match_all($regexp,$text,$list_of_notfullmatches);
1267 if ($list_of_notfullmatches) {
1268 foreach (array_unique($list_of_notfullmatches[0]) as $key=>$value) {
1269 $notfullmatches['<*'.$key.'*>'] = $value;
1271 if (!empty($notfullmatches)) {
1272 $text = str_replace($notfullmatches,array_keys($notfullmatches),$text);
1277 /// Finally we do our highlighting
1278 if (!empty($CFG->filtermatchonepertext
) ||
!empty($CFG->filtermatchoneperpage
)) {
1279 $resulttext = preg_replace('/('.$linkobject->work_phrase
.')/'.$modifiers,
1280 $linkobject->work_hreftagbegin
.
1281 $linkobject->work_replacementphrase
.
1282 $linkobject->work_hreftagend
, $text, 1);
1284 $resulttext = preg_replace('/('.$linkobject->work_phrase
.')/'.$modifiers,
1285 $linkobject->work_hreftagbegin
.
1286 $linkobject->work_replacementphrase
.
1287 $linkobject->work_hreftagend
, $text);
1291 /// If the text has changed we have to look for links again
1292 if ($resulttext != $text) {
1293 /// Set $text to $resulttext
1294 $text = $resulttext;
1295 /// Remove everything enclosed by the ignore tags from $text
1296 filter_save_ignore_tags($text,$filterignoretagsopen,$filterignoretagsclose,$ignoretags);
1297 /// Remove tags from $text
1298 filter_save_tags($text,$tags);
1299 /// If $CFG->filtermatchoneperpage, save linked phrases to request
1300 if (!empty($CFG->filtermatchoneperpage
)) {
1301 $usedphrases[] = $linkobject->work_phrase
;
1306 /// Replace the not full matches before cycling to next link object
1307 if (!empty($notfullmatches)) {
1308 $text = str_replace(array_keys($notfullmatches),$notfullmatches,$text);
1309 unset($notfullmatches);
1313 /// Rebuild the text with all the excluded areas
1315 if (!empty($tags)) {
1316 $text = str_replace(array_keys($tags), $tags, $text);
1319 if (!empty($ignoretags)) {
1320 $ignoretags = array_reverse($ignoretags); /// Reversed so "progressive" str_replace() will solve some nesting problems.
1321 $text = str_replace(array_keys($ignoretags),$ignoretags,$text);
1324 //// Remove the protective doubleups
1325 $text = preg_replace('/([#*%])(\1)/','\1',$text);
1327 /// Add missing javascript for popus
1328 $text = filter_add_javascript($text);
1335 * @todo Document this function
1336 * @param array $linkarray
1339 function filter_remove_duplicates($linkarray) {
1341 $concepts = array(); // keep a record of concepts as we cycle through
1342 $lconcepts = array(); // a lower case version for case insensitive
1344 $cleanlinks = array();
1346 foreach ($linkarray as $key=>$filterobject) {
1347 if ($filterobject->casesensitive
) {
1348 $exists = in_array($filterobject->phrase
, $concepts);
1350 $exists = in_array(moodle_strtolower($filterobject->phrase
), $lconcepts);
1354 $cleanlinks[] = $filterobject;
1355 $concepts[] = $filterobject->phrase
;
1356 $lconcepts[] = moodle_strtolower($filterobject->phrase
);
1364 * Extract open/lose tags and their contents to avoid being processed by filters.
1365 * Useful to extract pieces of code like <a>...</a> tags. It returns the text
1366 * converted with some <#xTEXTFILTER_EXCL_SEPARATORx#> codes replacing the extracted text. Such extracted
1367 * texts are returned in the ignoretags array (as values), with codes as keys.
1369 * @param string $text the text that we are filtering (in/out)
1370 * @param array $filterignoretagsopen an array of open tags to start searching
1371 * @param array $filterignoretagsclose an array of close tags to end searching
1372 * @param array $ignoretags an array of saved strings useful to rebuild the original text (in/out)
1374 function filter_save_ignore_tags(&$text, $filterignoretagsopen, $filterignoretagsclose, &$ignoretags) {
1376 /// Remove everything enclosed by the ignore tags from $text
1377 foreach ($filterignoretagsopen as $ikey=>$opentag) {
1378 $closetag = $filterignoretagsclose[$ikey];
1379 /// form regular expression
1380 $opentag = str_replace('/','\/',$opentag); // delimit forward slashes
1381 $closetag = str_replace('/','\/',$closetag); // delimit forward slashes
1382 $pregexp = '/'.$opentag.'(.*?)'.$closetag.'/is';
1384 preg_match_all($pregexp, $text, $list_of_ignores);
1385 foreach (array_unique($list_of_ignores[0]) as $key=>$value) {
1386 $prefix = (string)(count($ignoretags) +
1);
1387 $ignoretags['<#'.$prefix.TEXTFILTER_EXCL_SEPARATOR
.$key.'#>'] = $value;
1389 if (!empty($ignoretags)) {
1390 $text = str_replace($ignoretags,array_keys($ignoretags),$text);
1396 * Extract tags (any text enclosed by < and > to avoid being processed by filters.
1397 * It returns the text converted with some <%xTEXTFILTER_EXCL_SEPARATORx%> codes replacing the extracted text. Such extracted
1398 * texts are returned in the tags array (as values), with codes as keys.
1400 * @param string $text the text that we are filtering (in/out)
1401 * @param array $tags an array of saved strings useful to rebuild the original text (in/out)
1403 function filter_save_tags(&$text, &$tags) {
1405 preg_match_all('/<([^#%*].*?)>/is',$text,$list_of_newtags);
1406 foreach (array_unique($list_of_newtags[0]) as $ntkey=>$value) {
1407 $prefix = (string)(count($tags) +
1);
1408 $tags['<%'.$prefix.TEXTFILTER_EXCL_SEPARATOR
.$ntkey.'%>'] = $value;
1410 if (!empty($tags)) {
1411 $text = str_replace($tags,array_keys($tags),$text);
1416 * Add missing openpopup javascript to HTML files.
1418 * @param string $text
1421 function filter_add_javascript($text) {
1424 if (stripos($text, '</html>') === FALSE) {
1425 return $text; // this is not a html file
1427 if (strpos($text, 'onclick="return openpopup') === FALSE) {
1428 return $text; // no popup - no need to add javascript
1431 <script type=\"text/javascript\">
1433 function openpopup(url,name,options,fullscreen) {
1434 fullurl = \"".$CFG->httpswwwroot
."\" + url;
1435 windowobj = window.open(fullurl,name,options);
1437 windowobj.moveTo(0,0);
1438 windowobj.resizeTo(screen.availWidth,screen.availHeight);
1445 if (stripos($text, '</head>') !== FALSE) {
1446 //try to add it into the head element
1447 $text = str_ireplace('</head>', $js.'</head>', $text);
1451 //last chance - try adding head element
1452 return preg_replace("/<html.*?>/is", "\\0<head>".$js.'</head>', $text);