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 //TODO: remove sql_cast_2signed() once we do not support upgrade from Moodle 2.2
859 $rs = $DB->get_recordset_sql($sql);
861 // Masssage the data into the specified format to return.
863 foreach ($rs as $row) {
864 if (!isset($filters[$row->filter
])) {
865 $filters[$row->filter
] = array();
867 if (!is_null($row->name
)) {
868 $filters[$row->filter
][$row->name
] = $row->value
;
878 * Preloads the list of active filters for all activities (modules) on the course
879 * using two database queries.
880 * @param course_modinfo $modinfo Course object from get_fast_modinfo
882 function filter_preload_activities(course_modinfo
$modinfo) {
883 global $DB, $FILTERLIB_PRIVATE;
885 if (!isset($FILTERLIB_PRIVATE)) {
886 $FILTERLIB_PRIVATE = new stdClass();
889 // Don't repeat preload
890 if (!isset($FILTERLIB_PRIVATE->preloaded
)) {
891 $FILTERLIB_PRIVATE->preloaded
= array();
893 if (!empty($FILTERLIB_PRIVATE->preloaded
[$modinfo->get_course_id()])) {
896 $FILTERLIB_PRIVATE->preloaded
[$modinfo->get_course_id()] = true;
898 // Get contexts for all CMs
899 $cmcontexts = array();
900 $cmcontextids = array();
901 foreach ($modinfo->get_cms() as $cm) {
902 $modulecontext = get_context_instance(CONTEXT_MODULE
, $cm->id
);
903 $cmcontextids[] = $modulecontext->id
;
904 $cmcontexts[] = $modulecontext;
907 // Get course context and all other parents...
908 $coursecontext = get_context_instance(CONTEXT_COURSE
, $modinfo->get_course_id());
909 $parentcontextids = explode('/', substr($coursecontext->path
, 1));
910 $allcontextids = array_merge($cmcontextids, $parentcontextids);
912 // Get all filter_active rows relating to all these contexts
913 list ($sql, $params) = $DB->get_in_or_equal($allcontextids);
914 $filteractives = $DB->get_records_select('filter_active', "contextid $sql", $params);
916 // Get all filter_config only for the cm contexts
917 list ($sql, $params) = $DB->get_in_or_equal($cmcontextids);
918 $filterconfigs = $DB->get_records_select('filter_config', "contextid $sql", $params);
920 // Note: I was a bit surprised that filter_config only works for the
921 // most specific context (i.e. it does not need to be checked for course
922 // context if we only care about CMs) however basede on code in
923 // filter_get_active_in_context, this does seem to be correct.
925 // Build course default active list. Initially this will be an array of
926 // filter name => active score (where an active score >0 means it's active)
927 $courseactive = array();
929 // Also build list of filter_active rows below course level, by contextid
930 $remainingactives = array();
932 // Array lists filters that are banned at top level
935 // Add any active filters in parent contexts to the array
936 foreach ($filteractives as $row) {
937 $depth = array_search($row->contextid
, $parentcontextids);
938 if ($depth !== false) {
940 if (!array_key_exists($row->filter
, $courseactive)) {
941 $courseactive[$row->filter
] = 0;
943 // This maths copes with reading rows in any order. Turning on/off
944 // at site level counts 1, at next level down 4, at next level 9,
945 // then 16, etc. This means the deepest level always wins, except
946 // against the -9999 at top level.
947 $courseactive[$row->filter
] +
=
948 ($depth +
1) * ($depth +
1) * $row->active
;
950 if ($row->active
== TEXTFILTER_DISABLED
) {
951 $banned[$row->filter
] = true;
954 // Build list of other rows indexed by contextid
955 if (!array_key_exists($row->contextid
, $remainingactives)) {
956 $remainingactives[$row->contextid
] = array();
958 $remainingactives[$row->contextid
][] = $row;
962 // Chuck away the ones that aren't active
963 foreach ($courseactive as $filter=>$score) {
965 unset($courseactive[$filter]);
967 $courseactive[$filter] = array();
971 // Loop through the contexts to reconstruct filter_active lists for each
973 if (!isset($FILTERLIB_PRIVATE->active
)) {
974 $FILTERLIB_PRIVATE->active
= array();
976 foreach ($cmcontextids as $contextid) {
978 $FILTERLIB_PRIVATE->active
[$contextid] = $courseactive;
980 // Are there any changes to the active list?
981 if (array_key_exists($contextid, $remainingactives)) {
982 foreach ($remainingactives[$contextid] as $row) {
983 if ($row->active
> 0 && empty($banned[$row->filter
])) {
984 // If it's marked active for specific context, add entry
985 // (doesn't matter if one exists already)
986 $FILTERLIB_PRIVATE->active
[$contextid][$row->filter
] = array();
988 // If it's marked inactive, remove entry (doesn't matter
989 // if it doesn't exist)
990 unset($FILTERLIB_PRIVATE->active
[$contextid][$row->filter
]);
996 // Process all config rows to add config data to these entries
997 foreach ($filterconfigs as $row) {
998 if (isset($FILTERLIB_PRIVATE->active
[$row->contextid
][$row->filter
])) {
999 $FILTERLIB_PRIVATE->active
[$row->contextid
][$row->filter
][$row->name
] = $row->value
;
1005 * List all of the filters that are available in this context, and what the
1006 * local and inherited states of that filter are.
1009 * @param object $context a context that is not the system context.
1010 * @return array an array with filter names, for example 'filter/tex' or
1011 * 'mod/glossary' as keys. and and the values are objects with fields:
1012 * ->filter filter name, same as the key.
1013 * ->localstate TEXTFILTER_ON/OFF/INHERIT
1014 * ->inheritedstate TEXTFILTER_ON/OFF - the state that will be used if localstate is set to TEXTFILTER_INHERIT.
1016 function filter_get_available_in_context($context) {
1019 // The complex logic is working out the active state in the parent context,
1020 // so strip the current context from the list.
1021 $contextids = explode('/', trim($context->path
, '/'));
1022 array_pop($contextids);
1023 $contextids = implode(',', $contextids);
1024 if (empty($contextids)) {
1025 throw new coding_exception('filter_get_available_in_context cannot be called with the system context.');
1028 // The following SQL is tricky, in the same way at the SQL in filter_get_active_in_context.
1029 $sql = "SELECT parent_states.filter,
1030 CASE WHEN fa.active IS NULL THEN " . TEXTFILTER_INHERIT
. "
1031 ELSE fa.active END AS localstate,
1032 parent_states.inheritedstate
1033 FROM (SELECT f.filter, MAX(f.sortorder) AS sortorder,
1034 CASE WHEN MAX(f.active * " . $DB->sql_cast_2signed('ctx.depth') .
1035 ") > -MIN(f.active * " . $DB->sql_cast_2signed('ctx.depth') . ") THEN " . TEXTFILTER_ON
. "
1036 ELSE " . TEXTFILTER_OFF
. " END AS inheritedstate
1037 FROM {filter_active} f
1038 JOIN {context} ctx ON f.contextid = ctx.id
1039 WHERE ctx.id IN ($contextids)
1041 HAVING MIN(f.active) > " . TEXTFILTER_DISABLED
. "
1043 LEFT JOIN {filter_active} fa ON fa.filter = parent_states.filter AND fa.contextid = $context->id
1044 ORDER BY parent_states.sortorder";
1045 return $DB->get_records_sql($sql);
1049 * This function is for use by the filter administration page.
1052 * @return array 'filtername' => object with fields 'filter' (=filtername), 'active' and 'sortorder'
1054 function filter_get_global_states() {
1056 $context = get_context_instance(CONTEXT_SYSTEM
);
1057 return $DB->get_records('filter_active', array('contextid' => $context->id
), 'sortorder', 'filter,active,sortorder');
1061 * Delete all the data in the database relating to a filter, prior to deleting it.
1064 * @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
1066 function filter_delete_all_for_filter($filter) {
1068 if (substr($filter, 0, 7) == 'filter/') {
1069 unset_all_config_for_plugin('filter_' . basename($filter));
1071 $DB->delete_records('filter_active', array('filter' => $filter));
1072 $DB->delete_records('filter_config', array('filter' => $filter));
1076 * Delete all the data in the database relating to a context, used when contexts are deleted.
1078 * @param integer $contextid The id of the context being deleted.
1080 function filter_delete_all_for_context($contextid) {
1082 $DB->delete_records('filter_active', array('contextid' => $contextid));
1083 $DB->delete_records('filter_config', array('contextid' => $contextid));
1087 * Does this filter have a global settings page in the admin tree?
1088 * (The settings page for a filter must be called, for example,
1089 * filtersettingfiltertex or filtersettingmodglossay.)
1091 * @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
1092 * @return boolean Whether there should be a 'Settings' link on the config page.
1094 function filter_has_global_settings($filter) {
1096 $settingspath = $CFG->dirroot
. '/' . $filter . '/filtersettings.php';
1097 return is_readable($settingspath);
1101 * Does this filter have local (per-context) settings?
1103 * @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
1104 * @return boolean Whether there should be a 'Settings' link on the manage filters in context page.
1106 function filter_has_local_settings($filter) {
1108 $settingspath = $CFG->dirroot
. '/' . $filter . '/filterlocalsettings.php';
1109 return is_readable($settingspath);
1113 * Certain types of context (block and user) may not have local filter settings.
1114 * the function checks a context to see whether it may have local config.
1116 * @param object $context a context.
1117 * @return boolean whether this context may have local filter settings.
1119 function filter_context_may_have_filter_settings($context) {
1120 return $context->contextlevel
!= CONTEXT_BLOCK
&& $context->contextlevel
!= CONTEXT_USER
;
1124 * Process phrases intelligently found within a HTML text (such as adding links)
1126 * @staticvar array $usedpharses
1127 * @param string $text the text that we are filtering
1128 * @param array $link_array an array of filterobjects
1129 * @param array $ignoretagsopen an array of opening tags that we should ignore while filtering
1130 * @param array $ignoretagsclose an array of corresponding closing tags
1131 * @param bool $overridedefaultignore True to only use tags provided by arguments
1134 function filter_phrases($text, &$link_array, $ignoretagsopen=NULL, $ignoretagsclose=NULL,
1135 $overridedefaultignore=false) {
1139 static $usedphrases;
1141 $ignoretags = array(); //To store all the enclosig tags to be completely ignored
1142 $tags = array(); //To store all the simple tags to be ignored
1144 if (!$overridedefaultignore) {
1145 // A list of open/close tags that we should not replace within
1146 // Extended to include <script>, <textarea>, <select> and <a> tags
1147 // Regular expression allows tags with or without attributes
1148 $filterignoretagsopen = array('<head>' , '<nolink>' , '<span class="nolink">',
1149 '<script(\s[^>]*?)?>', '<textarea(\s[^>]*?)?>',
1150 '<select(\s[^>]*?)?>', '<a(\s[^>]*?)?>');
1151 $filterignoretagsclose = array('</head>', '</nolink>', '</span>',
1152 '</script>', '</textarea>', '</select>','</a>');
1154 // Set an empty default list
1155 $filterignoretagsopen = array();
1156 $filterignoretagsclose = array();
1159 // Add the user defined ignore tags to the default list
1160 if ( is_array($ignoretagsopen) ) {
1161 foreach ($ignoretagsopen as $open) {
1162 $filterignoretagsopen[] = $open;
1164 foreach ($ignoretagsclose as $close) {
1165 $filterignoretagsclose[] = $close;
1169 /// Invalid prefixes and suffixes for the fullmatch searches
1170 /// Every "word" character, but the underscore, is a invalid suffix or prefix.
1171 /// (nice to use this because it includes national characters (accents...) as word characters.
1172 $filterinvalidprefixes = '([^\W_])';
1173 $filterinvalidsuffixes = '([^\W_])';
1175 //// Double up some magic chars to avoid "accidental matches"
1176 $text = preg_replace('/([#*%])/','\1\1',$text);
1179 ////Remove everything enclosed by the ignore tags from $text
1180 filter_save_ignore_tags($text,$filterignoretagsopen,$filterignoretagsclose,$ignoretags);
1182 /// Remove tags from $text
1183 filter_save_tags($text,$tags);
1185 /// Time to cycle through each phrase to be linked
1186 $size = sizeof($link_array);
1187 for ($n=0; $n < $size; $n++
) {
1188 $linkobject =& $link_array[$n];
1190 /// Set some defaults if certain properties are missing
1191 /// Properties may be missing if the filterobject class has not been used to construct the object
1192 if (empty($linkobject->phrase
)) {
1196 /// Avoid integers < 1000 to be linked. See bug 1446.
1197 $intcurrent = intval($linkobject->phrase
);
1198 if (!empty($intcurrent) && strval($intcurrent) == $linkobject->phrase
&& $intcurrent < 1000) {
1202 /// All this work has to be done ONLY it it hasn't been done before
1203 if (!$linkobject->work_calculated
) {
1204 if (!isset($linkobject->hreftagbegin
) or !isset($linkobject->hreftagend
)) {
1205 $linkobject->work_hreftagbegin
= '<span class="highlight"';
1206 $linkobject->work_hreftagend
= '</span>';
1208 $linkobject->work_hreftagbegin
= $linkobject->hreftagbegin
;
1209 $linkobject->work_hreftagend
= $linkobject->hreftagend
;
1212 /// Double up chars to protect true duplicates
1213 /// be cleared up before returning to the user.
1214 $linkobject->work_hreftagbegin
= preg_replace('/([#*%])/','\1\1',$linkobject->work_hreftagbegin
);
1216 if (empty($linkobject->casesensitive
)) {
1217 $linkobject->work_casesensitive
= false;
1219 $linkobject->work_casesensitive
= true;
1221 if (empty($linkobject->fullmatch
)) {
1222 $linkobject->work_fullmatch
= false;
1224 $linkobject->work_fullmatch
= true;
1227 /// Strip tags out of the phrase
1228 $linkobject->work_phrase
= strip_tags($linkobject->phrase
);
1230 /// Double up chars that might cause a false match -- the duplicates will
1231 /// be cleared up before returning to the user.
1232 $linkobject->work_phrase
= preg_replace('/([#*%])/','\1\1',$linkobject->work_phrase
);
1234 /// Set the replacement phrase properly
1235 if ($linkobject->replacementphrase
) { //We have specified a replacement phrase
1237 $linkobject->work_replacementphrase
= strip_tags($linkobject->replacementphrase
);
1238 } else { //The replacement is the original phrase as matched below
1239 $linkobject->work_replacementphrase
= '$1';
1242 /// Quote any regular expression characters and the delimiter in the work phrase to be searched
1243 $linkobject->work_phrase
= preg_quote($linkobject->work_phrase
, '/');
1246 $linkobject->work_calculated
= true;
1250 /// If $CFG->filtermatchoneperpage, avoid previously (request) linked phrases
1251 if (!empty($CFG->filtermatchoneperpage
)) {
1252 if (!empty($usedphrases) && in_array($linkobject->work_phrase
,$usedphrases)) {
1257 /// Regular expression modifiers
1258 $modifiers = ($linkobject->work_casesensitive
) ?
's' : 'isu'; // works in unicode mode!
1260 /// Do we need to do a fullmatch?
1261 /// If yes then go through and remove any non full matching entries
1262 if ($linkobject->work_fullmatch
) {
1263 $notfullmatches = array();
1264 $regexp = '/'.$filterinvalidprefixes.'('.$linkobject->work_phrase
.')|('.$linkobject->work_phrase
.')'.$filterinvalidsuffixes.'/'.$modifiers;
1266 preg_match_all($regexp,$text,$list_of_notfullmatches);
1268 if ($list_of_notfullmatches) {
1269 foreach (array_unique($list_of_notfullmatches[0]) as $key=>$value) {
1270 $notfullmatches['<*'.$key.'*>'] = $value;
1272 if (!empty($notfullmatches)) {
1273 $text = str_replace($notfullmatches,array_keys($notfullmatches),$text);
1278 /// Finally we do our highlighting
1279 if (!empty($CFG->filtermatchonepertext
) ||
!empty($CFG->filtermatchoneperpage
)) {
1280 $resulttext = preg_replace('/('.$linkobject->work_phrase
.')/'.$modifiers,
1281 $linkobject->work_hreftagbegin
.
1282 $linkobject->work_replacementphrase
.
1283 $linkobject->work_hreftagend
, $text, 1);
1285 $resulttext = preg_replace('/('.$linkobject->work_phrase
.')/'.$modifiers,
1286 $linkobject->work_hreftagbegin
.
1287 $linkobject->work_replacementphrase
.
1288 $linkobject->work_hreftagend
, $text);
1292 /// If the text has changed we have to look for links again
1293 if ($resulttext != $text) {
1294 /// Set $text to $resulttext
1295 $text = $resulttext;
1296 /// Remove everything enclosed by the ignore tags from $text
1297 filter_save_ignore_tags($text,$filterignoretagsopen,$filterignoretagsclose,$ignoretags);
1298 /// Remove tags from $text
1299 filter_save_tags($text,$tags);
1300 /// If $CFG->filtermatchoneperpage, save linked phrases to request
1301 if (!empty($CFG->filtermatchoneperpage
)) {
1302 $usedphrases[] = $linkobject->work_phrase
;
1307 /// Replace the not full matches before cycling to next link object
1308 if (!empty($notfullmatches)) {
1309 $text = str_replace(array_keys($notfullmatches),$notfullmatches,$text);
1310 unset($notfullmatches);
1314 /// Rebuild the text with all the excluded areas
1316 if (!empty($tags)) {
1317 $text = str_replace(array_keys($tags), $tags, $text);
1320 if (!empty($ignoretags)) {
1321 $ignoretags = array_reverse($ignoretags); /// Reversed so "progressive" str_replace() will solve some nesting problems.
1322 $text = str_replace(array_keys($ignoretags),$ignoretags,$text);
1325 //// Remove the protective doubleups
1326 $text = preg_replace('/([#*%])(\1)/','\1',$text);
1328 /// Add missing javascript for popus
1329 $text = filter_add_javascript($text);
1336 * @todo Document this function
1337 * @param array $linkarray
1340 function filter_remove_duplicates($linkarray) {
1342 $concepts = array(); // keep a record of concepts as we cycle through
1343 $lconcepts = array(); // a lower case version for case insensitive
1345 $cleanlinks = array();
1347 foreach ($linkarray as $key=>$filterobject) {
1348 if ($filterobject->casesensitive
) {
1349 $exists = in_array($filterobject->phrase
, $concepts);
1351 $exists = in_array(textlib
::strtolower($filterobject->phrase
), $lconcepts);
1355 $cleanlinks[] = $filterobject;
1356 $concepts[] = $filterobject->phrase
;
1357 $lconcepts[] = textlib
::strtolower($filterobject->phrase
);
1365 * Extract open/lose tags and their contents to avoid being processed by filters.
1366 * Useful to extract pieces of code like <a>...</a> tags. It returns the text
1367 * converted with some <#xTEXTFILTER_EXCL_SEPARATORx#> codes replacing the extracted text. Such extracted
1368 * texts are returned in the ignoretags array (as values), with codes as keys.
1370 * @param string $text the text that we are filtering (in/out)
1371 * @param array $filterignoretagsopen an array of open tags to start searching
1372 * @param array $filterignoretagsclose an array of close tags to end searching
1373 * @param array $ignoretags an array of saved strings useful to rebuild the original text (in/out)
1375 function filter_save_ignore_tags(&$text, $filterignoretagsopen, $filterignoretagsclose, &$ignoretags) {
1377 /// Remove everything enclosed by the ignore tags from $text
1378 foreach ($filterignoretagsopen as $ikey=>$opentag) {
1379 $closetag = $filterignoretagsclose[$ikey];
1380 /// form regular expression
1381 $opentag = str_replace('/','\/',$opentag); // delimit forward slashes
1382 $closetag = str_replace('/','\/',$closetag); // delimit forward slashes
1383 $pregexp = '/'.$opentag.'(.*?)'.$closetag.'/is';
1385 preg_match_all($pregexp, $text, $list_of_ignores);
1386 foreach (array_unique($list_of_ignores[0]) as $key=>$value) {
1387 $prefix = (string)(count($ignoretags) +
1);
1388 $ignoretags['<#'.$prefix.TEXTFILTER_EXCL_SEPARATOR
.$key.'#>'] = $value;
1390 if (!empty($ignoretags)) {
1391 $text = str_replace($ignoretags,array_keys($ignoretags),$text);
1397 * Extract tags (any text enclosed by < and > to avoid being processed by filters.
1398 * It returns the text converted with some <%xTEXTFILTER_EXCL_SEPARATORx%> codes replacing the extracted text. Such extracted
1399 * texts are returned in the tags array (as values), with codes as keys.
1401 * @param string $text the text that we are filtering (in/out)
1402 * @param array $tags an array of saved strings useful to rebuild the original text (in/out)
1404 function filter_save_tags(&$text, &$tags) {
1406 preg_match_all('/<([^#%*].*?)>/is',$text,$list_of_newtags);
1407 foreach (array_unique($list_of_newtags[0]) as $ntkey=>$value) {
1408 $prefix = (string)(count($tags) +
1);
1409 $tags['<%'.$prefix.TEXTFILTER_EXCL_SEPARATOR
.$ntkey.'%>'] = $value;
1411 if (!empty($tags)) {
1412 $text = str_replace($tags,array_keys($tags),$text);
1417 * Add missing openpopup javascript to HTML files.
1419 * @param string $text
1422 function filter_add_javascript($text) {
1425 if (stripos($text, '</html>') === FALSE) {
1426 return $text; // this is not a html file
1428 if (strpos($text, 'onclick="return openpopup') === FALSE) {
1429 return $text; // no popup - no need to add javascript
1432 <script type=\"text/javascript\">
1434 function openpopup(url,name,options,fullscreen) {
1435 fullurl = \"".$CFG->httpswwwroot
."\" + url;
1436 windowobj = window.open(fullurl,name,options);
1438 windowobj.moveTo(0,0);
1439 windowobj.resizeTo(screen.availWidth,screen.availHeight);
1446 if (stripos($text, '</head>') !== FALSE) {
1447 //try to add it into the head element
1448 $text = str_ireplace('</head>', $js.'</head>', $text);
1452 //last chance - try adding head element
1453 return preg_replace("/<html.*?>/is", "\\0<head>".$js.'</head>', $text);