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);
227 * Setup page with filters requirements and other prepare stuff.
229 * This method is used by {@see format_text()} and {@see format_string()}
230 * in order to allow filters to setup any page requirement (js, css...)
231 * or perform any action needed to get them prepared before filtering itself
232 * happens by calling to each every active setup() method.
234 * Note it's executed for each piece of text filtered, so filter implementations
235 * are responsible of controlling the cardinality of the executions that may
236 * be different depending of the stuff to prepare.
238 * @param moodle_page $page the page we are going to add requirements to.
239 * @param context $context the context which contents are going to be filtered.
242 public function setup_page_for_filters($page, $context) {
243 $filters = $this->get_text_filters($context);
244 foreach ($filters as $filter) {
245 $filter->setup($page, $context);
251 * Filter manager subclass that does nothing. Having this simplifies the logic
252 * of format_text, etc.
254 * @todo Document this class
258 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
259 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
261 class null_filter_manager
{
265 public function filter_text($text, $context, $options) {
272 public function filter_string($string, $context) {
279 public function text_filtering_hash() {
285 * Filter manager subclass that tacks how much work it does.
287 * @todo Document this class
291 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
292 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
294 class performance_measuring_filter_manager
extends filter_manager
{
296 protected $filterscreated = 0;
297 protected $textsfiltered = 0;
298 protected $stringsfiltered = 0;
301 * @param string $filtername
302 * @param object $context
303 * @param mixed $localconfig
306 protected function make_filter_object($filtername, $context, $localconfig) {
307 $this->filterscreated++
;
308 return parent
::make_filter_object($filtername, $context, $localconfig);
312 * @param string $text
313 * @param object $context
314 * @param array $options options passed to the filters
317 public function filter_text($text, $context, array $options = array()) {
318 $this->textsfiltered++
;
319 return parent
::filter_text($text, $context, $options);
323 * @param string $string
324 * @param object $context
327 public function filter_string($string, $context) {
328 $this->stringsfiltered++
;
329 return parent
::filter_string($string, $context);
335 public function get_performance_summary() {
337 'contextswithfilters' => count($this->textfilters
),
338 'filterscreated' => $this->filterscreated
,
339 'textsfiltered' => $this->textsfiltered
,
340 'stringsfiltered' => $this->stringsfiltered
,
342 'contextswithfilters' => 'Contexts for which filters were loaded',
343 'filterscreated' => 'Filters created',
344 'textsfiltered' => 'Pieces of content filtered',
345 'stringsfiltered' => 'Strings filtered',
351 * Base class for text filters. You just need to override this class and
352 * implement the filter method.
356 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
357 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
359 abstract class moodle_text_filter
{
360 /** @var object The context we are in. */
362 /** @var array Any local configuration for this filter in this context. */
363 protected $localconfig;
366 * Set any context-specific configuration for this filter.
367 * @param object $context The current course id.
368 * @param object $context The current context.
369 * @param array $config Any context-specific configuration for this filter.
371 public function __construct($context, array $localconfig) {
372 $this->context
= $context;
373 $this->localconfig
= $localconfig;
377 * @return string The class name of the current class
379 public function hash() {
384 * Setup page with filter requirements and other prepare stuff.
386 * Override this method if the filter needs to setup page
387 * requirements or needs other stuff to be executed.
389 * Note this method is invoked from {@see setup_page_for_filters()}
390 * for each piece of text being filtered, so it is responsible
391 * for controlling its own execution cardinality.
393 * @param moodle_page $page the page we are going to add requirements to.
394 * @param context $context the context which contents are going to be filtered.
397 public function setup($page, $context) {
398 // Override me, if needed.
402 * Override this function to actually implement the filtering.
404 * @param $text some HTML content.
405 * @param array $options options passed to the filters
406 * @return the HTML content after the filtering has been applied.
408 public abstract function filter($text, array $options = array());
412 * moodle_text_filter implementation that encapsulates an old-style filter that
413 * only defines a function, not a class.
415 * @deprecated since 2.2, see MDL-29995
416 * @todo will be out in 2.3, see MDL-29996
419 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
420 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
422 class legacy_filter
extends moodle_text_filter
{
424 protected $filterfunction;
428 * Set any context-specific configuration for this filter.
430 * @param string $filterfunction
431 * @param object $context The current context.
432 * @param array $config Any context-specific configuration for this filter.
434 public function __construct($filterfunction, $context, array $localconfig) {
435 parent
::__construct($context, $localconfig);
436 $this->filterfunction
= $filterfunction;
437 $this->courseid
= get_courseid_from_context($this->context
);
441 * @param string $text
442 * @param array $options options - not supported for legacy filters
445 public function filter($text, array $options = array()) {
446 if ($this->courseid
) {
447 // old filters are called only when inside courses
448 return call_user_func($this->filterfunction
, $this->courseid
, $text);
456 * This is just a little object to define a phrase and some instructions
457 * for how to process it. Filters can create an array of these to pass
458 * to the filter_phrases function below.
462 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
463 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
474 var $replacementphrase;
476 var $work_hreftagbegin;
477 var $work_hreftagend;
478 var $work_casesensitive;
480 var $work_replacementphrase;
482 var $work_calculated;
485 * A constructor just because I like constructing
487 * @param string $phrase
488 * @param string $hreftagbegin
489 * @param string $hreftagend
490 * @param bool $casesensitive
491 * @param bool $fullmatch
492 * @param mixed $replacementphrase
494 function filterobject($phrase, $hreftagbegin = '<span class="highlight">',
495 $hreftagend = '</span>',
496 $casesensitive = false,
498 $replacementphrase = NULL) {
500 $this->phrase
= $phrase;
501 $this->hreftagbegin
= $hreftagbegin;
502 $this->hreftagend
= $hreftagend;
503 $this->casesensitive
= $casesensitive;
504 $this->fullmatch
= $fullmatch;
505 $this->replacementphrase
= $replacementphrase;
506 $this->work_calculated
= false;
512 * Look up the name of this filter in the most appropriate location.
513 * If $filterlocation = 'mod' then does get_string('filtername', $filter);
514 * else if $filterlocation = 'filter' then does get_string('filtername', 'filter_' . $filter);
515 * with a fallback to get_string('filtername', $filter) for backwards compatibility.
516 * These are the only two options supported at the moment.
518 * @param string $filter the folder name where the filter lives.
519 * @return string the human-readable name for this filter.
521 function filter_get_name($filter) {
522 // TODO: should we be using pluginname here instead? , see MDL-29998
523 list($type, $filter) = explode('/', $filter);
526 $strfiltername = get_string('filtername', 'filter_' . $filter);
527 if (substr($strfiltername, 0, 2) != '[[') {
528 // found a valid string.
529 return $strfiltername;
531 // Fall through to try the legacy location.
533 // TODO: deprecated since 2.2, will be out in 2.3, see MDL-29996
535 $strfiltername = get_string('filtername', $filter);
536 if (substr($strfiltername, 0, 2) == '[[') {
537 $strfiltername .= ' (' . $type . '/' . $filter . ')';
539 return $strfiltername;
542 throw new coding_exception('Unknown filter type ' . $type);
547 * Get the names of all the filters installed in this Moodle.
550 * @return array path => filter name from the appropriate lang file. e.g.
551 * array('mod/glossary' => 'Glossary Auto-linking', 'filter/tex' => 'TeX Notation');
552 * sorted in alphabetical order of name.
554 function filter_get_all_installed() {
556 $filternames = array();
557 // TODO: deprecated since 2.2, will be out in 2.3, see MDL-29996
558 $filterlocations = array('mod', 'filter');
559 foreach ($filterlocations as $filterlocation) {
560 // TODO: move get_list_of_plugins() to get_plugin_list()
561 $filters = get_list_of_plugins($filterlocation);
562 foreach ($filters as $filter) {
563 // MDL-29994 - Ignore mod/data and mod/glossary filters forever, this will be out in 2.3
564 if ($filterlocation == 'mod' && ($filter == 'data' ||
$filter == 'glossary')) {
567 $path = $filterlocation . '/' . $filter;
568 if (is_readable($CFG->dirroot
. '/' . $path . '/filter.php')) {
569 $strfiltername = filter_get_name($path);
570 $filternames[$path] = $strfiltername;
574 collatorlib
::asort($filternames);
579 * Set the global activated state for a text filter.
582 * @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
583 * @param integer $state One of the values TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_DISABLED.
584 * @param integer $sortorder (optional) a position in the sortorder to place this filter.
585 * If not given defaults to:
586 * No change in order if we are updating an existing record, and not changing to or from TEXTFILTER_DISABLED.
587 * Just after the last currently active filter when adding an unknown filter
588 * in state TEXTFILTER_ON or TEXTFILTER_OFF, or enabling/disabling an existing filter.
589 * Just after the very last filter when adding an unknown filter in state TEXTFILTER_DISABLED
591 function filter_set_global_state($filter, $state, $sortorder = false) {
594 // Check requested state is valid.
595 if (!in_array($state, array(TEXTFILTER_ON
, TEXTFILTER_OFF
, TEXTFILTER_DISABLED
))) {
596 throw new coding_exception("Illegal option '$state' passed to filter_set_global_state. " .
597 "Must be one of TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_DISABLED.");
600 // Check sortorder is valid.
601 if ($sortorder !== false) {
602 if ($sortorder < 1 ||
$sortorder > $DB->get_field('filter_active', 'MAX(sortorder)', array()) +
1) {
603 throw new coding_exception("Invalid sort order passed to filter_set_global_state.");
607 // See if there is an existing record.
608 $syscontext = context_system
::instance();
609 $rec = $DB->get_record('filter_active', array('filter' => $filter, 'contextid' => $syscontext->id
));
613 $rec->filter
= $filter;
614 $rec->contextid
= $syscontext->id
;
617 if ($sortorder === false && !($rec->active
== TEXTFILTER_DISABLED
xor $state == TEXTFILTER_DISABLED
)) {
618 $sortorder = $rec->sortorder
;
622 // Automatic sort order.
623 if ($sortorder === false) {
624 if ($state == TEXTFILTER_DISABLED
&& $insert) {
625 $prevmaxsortorder = $DB->get_field('filter_active', 'MAX(sortorder)', array());
627 $prevmaxsortorder = $DB->get_field_select('filter_active', 'MAX(sortorder)', 'active <> ?', array(TEXTFILTER_DISABLED
));
629 if (empty($prevmaxsortorder)) {
632 $sortorder = $prevmaxsortorder +
1;
633 if (!$insert && $state == TEXTFILTER_DISABLED
) {
634 $sortorder = $prevmaxsortorder;
639 // Move any existing records out of the way of the sortorder.
641 $DB->execute('UPDATE {filter_active} SET sortorder = sortorder + 1 WHERE sortorder >= ?', array($sortorder));
642 } else if ($sortorder != $rec->sortorder
) {
643 $sparesortorder = $DB->get_field('filter_active', 'MIN(sortorder)', array()) - 1;
644 $DB->set_field('filter_active', 'sortorder', $sparesortorder, array('filter' => $filter, 'contextid' => $syscontext->id
));
645 if ($sortorder < $rec->sortorder
) {
646 $DB->execute('UPDATE {filter_active} SET sortorder = sortorder + 1 WHERE sortorder >= ? AND sortorder < ?',
647 array($sortorder, $rec->sortorder
));
648 } else if ($sortorder > $rec->sortorder
) {
649 $DB->execute('UPDATE {filter_active} SET sortorder = sortorder - 1 WHERE sortorder <= ? AND sortorder > ?',
650 array($sortorder, $rec->sortorder
));
654 // Insert/update the new record.
655 $rec->active
= $state;
656 $rec->sortorder
= $sortorder;
658 $DB->insert_record('filter_active', $rec);
660 $DB->update_record('filter_active', $rec);
665 * @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
666 * @return boolean is this filter allowed to be used on this site. That is, the
667 * admin has set the global 'active' setting to On, or Off, but available.
669 function filter_is_enabled($filter) {
670 return array_key_exists($filter, filter_get_globally_enabled());
674 * Return a list of all the filters that may be in use somewhere.
676 * @staticvar array $enabledfilters
677 * @return array where the keys and values are both the filter name, like 'filter/tex'.
679 function filter_get_globally_enabled() {
680 static $enabledfilters = null;
681 if (is_null($enabledfilters)) {
682 $filters = filter_get_global_states();
683 $enabledfilters = array();
684 foreach ($filters as $filter => $filerinfo) {
685 if ($filerinfo->active
!= TEXTFILTER_DISABLED
) {
686 $enabledfilters[$filter] = $filter;
690 return $enabledfilters;
694 * Return the names of the filters that should also be applied to strings
695 * (when they are enabled).
698 * @return array where the keys and values are both the filter name, like 'filter/tex'.
700 function filter_get_string_filters() {
702 $stringfilters = array();
703 if (!empty($CFG->filterall
) && !empty($CFG->stringfilters
)) {
704 $stringfilters = explode(',', $CFG->stringfilters
);
705 $stringfilters = array_combine($stringfilters, $stringfilters);
707 return $stringfilters;
711 * Sets whether a particular active filter should be applied to all strings by
712 * format_string, or just used by format_text.
714 * @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
715 * @param boolean $applytostrings if true, this filter will apply to format_string
716 * and format_text, when it is enabled.
718 function filter_set_applies_to_strings($filter, $applytostrings) {
719 $stringfilters = filter_get_string_filters();
720 $numstringfilters = count($stringfilters);
721 if ($applytostrings) {
722 $stringfilters[$filter] = $filter;
724 unset($stringfilters[$filter]);
726 if (count($stringfilters) != $numstringfilters) {
727 set_config('stringfilters', implode(',', $stringfilters));
728 set_config('filterall', !empty($stringfilters));
733 * Set the local activated state for a text filter.
736 * @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
737 * @param integer $contextid The id of the context to get the local config for.
738 * @param integer $state One of the values TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_INHERIT.
741 function filter_set_local_state($filter, $contextid, $state) {
744 // Check requested state is valid.
745 if (!in_array($state, array(TEXTFILTER_ON
, TEXTFILTER_OFF
, TEXTFILTER_INHERIT
))) {
746 throw new coding_exception("Illegal option '$state' passed to filter_set_local_state. " .
747 "Must be one of TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_INHERIT.");
750 if ($contextid == context_system
::instance()->id
) {
751 throw new coding_exception('You cannot use filter_set_local_state ' .
752 'with $contextid equal to the system context id.');
755 if ($state == TEXTFILTER_INHERIT
) {
756 $DB->delete_records('filter_active', array('filter' => $filter, 'contextid' => $contextid));
760 $rec = $DB->get_record('filter_active', array('filter' => $filter, 'contextid' => $contextid));
765 $rec->filter
= $filter;
766 $rec->contextid
= $contextid;
769 $rec->active
= $state;
772 $DB->insert_record('filter_active', $rec);
774 $DB->update_record('filter_active', $rec);
779 * Set a particular local config variable for a filter in a context.
782 * @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
783 * @param integer $contextid The id of the context to get the local config for.
784 * @param string $name the setting name.
785 * @param string $value the corresponding value.
787 function filter_set_local_config($filter, $contextid, $name, $value) {
789 $rec = $DB->get_record('filter_config', array('filter' => $filter, 'contextid' => $contextid, 'name' => $name));
794 $rec->filter
= $filter;
795 $rec->contextid
= $contextid;
799 $rec->value
= $value;
802 $DB->insert_record('filter_config', $rec);
804 $DB->update_record('filter_config', $rec);
809 * Remove a particular local config variable for a filter in a context.
812 * @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
813 * @param integer $contextid The id of the context to get the local config for.
814 * @param string $name the setting name.
816 function filter_unset_local_config($filter, $contextid, $name) {
818 $DB->delete_records('filter_config', array('filter' => $filter, 'contextid' => $contextid, 'name' => $name));
822 * Get local config variables for a filter in a context. Normally (when your
823 * filter is running) you don't need to call this, becuase the config is fetched
824 * for you automatically. You only need this, for example, when you are getting
825 * the config so you can show the user an editing from.
828 * @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
829 * @param integer $contextid The ID of the context to get the local config for.
830 * @return array of name => value pairs.
832 function filter_get_local_config($filter, $contextid) {
834 return $DB->get_records_menu('filter_config', array('filter' => $filter, 'contextid' => $contextid), '', 'name,value');
838 * This function is for use by backup. Gets all the filter information specific
842 * @param int $contextid
843 * @return array Array with two elements. The first element is an array of objects with
844 * fields filter and active. These come from the filter_active table. The
845 * second element is an array of objects with fields filter, name and value
846 * from the filter_config table.
848 function filter_get_all_local_settings($contextid) {
850 $context = context_system
::instance();
852 $DB->get_records('filter_active', array('contextid' => $contextid), 'filter', 'filter,active'),
853 $DB->get_records('filter_config', array('contextid' => $contextid), 'filter,name', 'filter,name,value'),
858 * Get the list of active filters, in the order that they should be used
859 * for a particular context, along with any local configuration variables.
862 * @param object $context a context
863 * @return array an array where the keys are the filter names, for example
864 * 'filter/tex' or 'mod/glossary' and the values are any local
865 * configuration for that filter, as an array of name => value pairs
866 * from the filter_config table. In a lot of cases, this will be an
867 * empty array. So, an example return value for this function might be
868 * array('filter/tex' => array(), 'mod/glossary' => array('glossaryid', 123))
870 function filter_get_active_in_context($context) {
871 global $DB, $FILTERLIB_PRIVATE;
873 if (!isset($FILTERLIB_PRIVATE)) {
874 $FILTERLIB_PRIVATE = new stdClass();
877 // Use cache (this is a within-request cache only) if available. See
878 // function filter_preload_activities.
879 if (isset($FILTERLIB_PRIVATE->active
) &&
880 array_key_exists($context->id
, $FILTERLIB_PRIVATE->active
)) {
881 return $FILTERLIB_PRIVATE->active
[$context->id
];
884 $contextids = str_replace('/', ',', trim($context->path
, '/'));
886 // The following SQL is tricky. It is explained on
887 // http://docs.moodle.org/dev/Filter_enable/disable_by_context
888 $sql = "SELECT active.filter, fc.name, fc.value
889 FROM (SELECT f.filter, MAX(f.sortorder) AS sortorder
890 FROM {filter_active} f
891 JOIN {context} ctx ON f.contextid = ctx.id
892 WHERE ctx.id IN ($contextids)
894 HAVING MAX(f.active * " . $DB->sql_cast_2signed('ctx.depth') .
895 ") > -MIN(f.active * " . $DB->sql_cast_2signed('ctx.depth') . ")
897 LEFT JOIN {filter_config} fc ON fc.filter = active.filter AND fc.contextid = $context->id
898 ORDER BY active.sortorder";
899 //TODO: remove sql_cast_2signed() once we do not support upgrade from Moodle 2.2
900 $rs = $DB->get_recordset_sql($sql);
902 // Masssage the data into the specified format to return.
904 foreach ($rs as $row) {
905 if (!isset($filters[$row->filter
])) {
906 $filters[$row->filter
] = array();
908 if (!is_null($row->name
)) {
909 $filters[$row->filter
][$row->name
] = $row->value
;
919 * Preloads the list of active filters for all activities (modules) on the course
920 * using two database queries.
921 * @param course_modinfo $modinfo Course object from get_fast_modinfo
923 function filter_preload_activities(course_modinfo
$modinfo) {
924 global $DB, $FILTERLIB_PRIVATE;
926 if (!isset($FILTERLIB_PRIVATE)) {
927 $FILTERLIB_PRIVATE = new stdClass();
930 // Don't repeat preload
931 if (!isset($FILTERLIB_PRIVATE->preloaded
)) {
932 $FILTERLIB_PRIVATE->preloaded
= array();
934 if (!empty($FILTERLIB_PRIVATE->preloaded
[$modinfo->get_course_id()])) {
937 $FILTERLIB_PRIVATE->preloaded
[$modinfo->get_course_id()] = true;
939 // Get contexts for all CMs
940 $cmcontexts = array();
941 $cmcontextids = array();
942 foreach ($modinfo->get_cms() as $cm) {
943 $modulecontext = context_module
::instance($cm->id
);
944 $cmcontextids[] = $modulecontext->id
;
945 $cmcontexts[] = $modulecontext;
948 // Get course context and all other parents...
949 $coursecontext = context_course
::instance($modinfo->get_course_id());
950 $parentcontextids = explode('/', substr($coursecontext->path
, 1));
951 $allcontextids = array_merge($cmcontextids, $parentcontextids);
953 // Get all filter_active rows relating to all these contexts
954 list ($sql, $params) = $DB->get_in_or_equal($allcontextids);
955 $filteractives = $DB->get_records_select('filter_active', "contextid $sql", $params);
957 // Get all filter_config only for the cm contexts
958 list ($sql, $params) = $DB->get_in_or_equal($cmcontextids);
959 $filterconfigs = $DB->get_records_select('filter_config', "contextid $sql", $params);
961 // Note: I was a bit surprised that filter_config only works for the
962 // most specific context (i.e. it does not need to be checked for course
963 // context if we only care about CMs) however basede on code in
964 // filter_get_active_in_context, this does seem to be correct.
966 // Build course default active list. Initially this will be an array of
967 // filter name => active score (where an active score >0 means it's active)
968 $courseactive = array();
970 // Also build list of filter_active rows below course level, by contextid
971 $remainingactives = array();
973 // Array lists filters that are banned at top level
976 // Add any active filters in parent contexts to the array
977 foreach ($filteractives as $row) {
978 $depth = array_search($row->contextid
, $parentcontextids);
979 if ($depth !== false) {
981 if (!array_key_exists($row->filter
, $courseactive)) {
982 $courseactive[$row->filter
] = 0;
984 // This maths copes with reading rows in any order. Turning on/off
985 // at site level counts 1, at next level down 4, at next level 9,
986 // then 16, etc. This means the deepest level always wins, except
987 // against the -9999 at top level.
988 $courseactive[$row->filter
] +
=
989 ($depth +
1) * ($depth +
1) * $row->active
;
991 if ($row->active
== TEXTFILTER_DISABLED
) {
992 $banned[$row->filter
] = true;
995 // Build list of other rows indexed by contextid
996 if (!array_key_exists($row->contextid
, $remainingactives)) {
997 $remainingactives[$row->contextid
] = array();
999 $remainingactives[$row->contextid
][] = $row;
1003 // Chuck away the ones that aren't active
1004 foreach ($courseactive as $filter=>$score) {
1006 unset($courseactive[$filter]);
1008 $courseactive[$filter] = array();
1012 // Loop through the contexts to reconstruct filter_active lists for each
1014 if (!isset($FILTERLIB_PRIVATE->active
)) {
1015 $FILTERLIB_PRIVATE->active
= array();
1017 foreach ($cmcontextids as $contextid) {
1019 $FILTERLIB_PRIVATE->active
[$contextid] = $courseactive;
1021 // Are there any changes to the active list?
1022 if (array_key_exists($contextid, $remainingactives)) {
1023 foreach ($remainingactives[$contextid] as $row) {
1024 if ($row->active
> 0 && empty($banned[$row->filter
])) {
1025 // If it's marked active for specific context, add entry
1026 // (doesn't matter if one exists already)
1027 $FILTERLIB_PRIVATE->active
[$contextid][$row->filter
] = array();
1029 // If it's marked inactive, remove entry (doesn't matter
1030 // if it doesn't exist)
1031 unset($FILTERLIB_PRIVATE->active
[$contextid][$row->filter
]);
1037 // Process all config rows to add config data to these entries
1038 foreach ($filterconfigs as $row) {
1039 if (isset($FILTERLIB_PRIVATE->active
[$row->contextid
][$row->filter
])) {
1040 $FILTERLIB_PRIVATE->active
[$row->contextid
][$row->filter
][$row->name
] = $row->value
;
1046 * List all of the filters that are available in this context, and what the
1047 * local and inherited states of that filter are.
1050 * @param object $context a context that is not the system context.
1051 * @return array an array with filter names, for example 'filter/tex' or
1052 * 'mod/glossary' as keys. and and the values are objects with fields:
1053 * ->filter filter name, same as the key.
1054 * ->localstate TEXTFILTER_ON/OFF/INHERIT
1055 * ->inheritedstate TEXTFILTER_ON/OFF - the state that will be used if localstate is set to TEXTFILTER_INHERIT.
1057 function filter_get_available_in_context($context) {
1060 // The complex logic is working out the active state in the parent context,
1061 // so strip the current context from the list.
1062 $contextids = explode('/', trim($context->path
, '/'));
1063 array_pop($contextids);
1064 $contextids = implode(',', $contextids);
1065 if (empty($contextids)) {
1066 throw new coding_exception('filter_get_available_in_context cannot be called with the system context.');
1069 // The following SQL is tricky, in the same way at the SQL in filter_get_active_in_context.
1070 $sql = "SELECT parent_states.filter,
1071 CASE WHEN fa.active IS NULL THEN " . TEXTFILTER_INHERIT
. "
1072 ELSE fa.active END AS localstate,
1073 parent_states.inheritedstate
1074 FROM (SELECT f.filter, MAX(f.sortorder) AS sortorder,
1075 CASE WHEN MAX(f.active * " . $DB->sql_cast_2signed('ctx.depth') .
1076 ") > -MIN(f.active * " . $DB->sql_cast_2signed('ctx.depth') . ") THEN " . TEXTFILTER_ON
. "
1077 ELSE " . TEXTFILTER_OFF
. " END AS inheritedstate
1078 FROM {filter_active} f
1079 JOIN {context} ctx ON f.contextid = ctx.id
1080 WHERE ctx.id IN ($contextids)
1082 HAVING MIN(f.active) > " . TEXTFILTER_DISABLED
. "
1084 LEFT JOIN {filter_active} fa ON fa.filter = parent_states.filter AND fa.contextid = $context->id
1085 ORDER BY parent_states.sortorder";
1086 return $DB->get_records_sql($sql);
1090 * This function is for use by the filter administration page.
1093 * @return array 'filtername' => object with fields 'filter' (=filtername), 'active' and 'sortorder'
1095 function filter_get_global_states() {
1097 $context = context_system
::instance();
1098 return $DB->get_records('filter_active', array('contextid' => $context->id
), 'sortorder', 'filter,active,sortorder');
1102 * Delete all the data in the database relating to a filter, prior to deleting it.
1105 * @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
1107 function filter_delete_all_for_filter($filter) {
1109 if (substr($filter, 0, 7) == 'filter/') {
1110 unset_all_config_for_plugin('filter_' . basename($filter));
1112 $DB->delete_records('filter_active', array('filter' => $filter));
1113 $DB->delete_records('filter_config', array('filter' => $filter));
1117 * Delete all the data in the database relating to a context, used when contexts are deleted.
1119 * @param integer $contextid The id of the context being deleted.
1121 function filter_delete_all_for_context($contextid) {
1123 $DB->delete_records('filter_active', array('contextid' => $contextid));
1124 $DB->delete_records('filter_config', array('contextid' => $contextid));
1128 * Does this filter have a global settings page in the admin tree?
1129 * (The settings page for a filter must be called, for example,
1130 * filtersettingfiltertex or filtersettingmodglossay.)
1132 * @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
1133 * @return boolean Whether there should be a 'Settings' link on the config page.
1135 function filter_has_global_settings($filter) {
1137 $settingspath = $CFG->dirroot
. '/' . $filter . '/filtersettings.php';
1138 return is_readable($settingspath);
1142 * Does this filter have local (per-context) settings?
1144 * @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
1145 * @return boolean Whether there should be a 'Settings' link on the manage filters in context page.
1147 function filter_has_local_settings($filter) {
1149 $settingspath = $CFG->dirroot
. '/' . $filter . '/filterlocalsettings.php';
1150 return is_readable($settingspath);
1154 * Certain types of context (block and user) may not have local filter settings.
1155 * the function checks a context to see whether it may have local config.
1157 * @param object $context a context.
1158 * @return boolean whether this context may have local filter settings.
1160 function filter_context_may_have_filter_settings($context) {
1161 return $context->contextlevel
!= CONTEXT_BLOCK
&& $context->contextlevel
!= CONTEXT_USER
;
1165 * Process phrases intelligently found within a HTML text (such as adding links)
1167 * @staticvar array $usedpharses
1168 * @param string $text the text that we are filtering
1169 * @param array $link_array an array of filterobjects
1170 * @param array $ignoretagsopen an array of opening tags that we should ignore while filtering
1171 * @param array $ignoretagsclose an array of corresponding closing tags
1172 * @param bool $overridedefaultignore True to only use tags provided by arguments
1175 function filter_phrases($text, &$link_array, $ignoretagsopen=NULL, $ignoretagsclose=NULL,
1176 $overridedefaultignore=false) {
1180 static $usedphrases;
1182 $ignoretags = array(); //To store all the enclosig tags to be completely ignored
1183 $tags = array(); //To store all the simple tags to be ignored
1185 if (!$overridedefaultignore) {
1186 // A list of open/close tags that we should not replace within
1187 // Extended to include <script>, <textarea>, <select> and <a> tags
1188 // Regular expression allows tags with or without attributes
1189 $filterignoretagsopen = array('<head>' , '<nolink>' , '<span class="nolink">',
1190 '<script(\s[^>]*?)?>', '<textarea(\s[^>]*?)?>',
1191 '<select(\s[^>]*?)?>', '<a(\s[^>]*?)?>');
1192 $filterignoretagsclose = array('</head>', '</nolink>', '</span>',
1193 '</script>', '</textarea>', '</select>','</a>');
1195 // Set an empty default list
1196 $filterignoretagsopen = array();
1197 $filterignoretagsclose = array();
1200 // Add the user defined ignore tags to the default list
1201 if ( is_array($ignoretagsopen) ) {
1202 foreach ($ignoretagsopen as $open) {
1203 $filterignoretagsopen[] = $open;
1205 foreach ($ignoretagsclose as $close) {
1206 $filterignoretagsclose[] = $close;
1210 /// Invalid prefixes and suffixes for the fullmatch searches
1211 /// Every "word" character, but the underscore, is a invalid suffix or prefix.
1212 /// (nice to use this because it includes national characters (accents...) as word characters.
1213 $filterinvalidprefixes = '([^\W_])';
1214 $filterinvalidsuffixes = '([^\W_])';
1216 //// Double up some magic chars to avoid "accidental matches"
1217 $text = preg_replace('/([#*%])/','\1\1',$text);
1220 ////Remove everything enclosed by the ignore tags from $text
1221 filter_save_ignore_tags($text,$filterignoretagsopen,$filterignoretagsclose,$ignoretags);
1223 /// Remove tags from $text
1224 filter_save_tags($text,$tags);
1226 /// Time to cycle through each phrase to be linked
1227 $size = sizeof($link_array);
1228 for ($n=0; $n < $size; $n++
) {
1229 $linkobject =& $link_array[$n];
1231 /// Set some defaults if certain properties are missing
1232 /// Properties may be missing if the filterobject class has not been used to construct the object
1233 if (empty($linkobject->phrase
)) {
1237 /// Avoid integers < 1000 to be linked. See bug 1446.
1238 $intcurrent = intval($linkobject->phrase
);
1239 if (!empty($intcurrent) && strval($intcurrent) == $linkobject->phrase
&& $intcurrent < 1000) {
1243 /// All this work has to be done ONLY it it hasn't been done before
1244 if (!$linkobject->work_calculated
) {
1245 if (!isset($linkobject->hreftagbegin
) or !isset($linkobject->hreftagend
)) {
1246 $linkobject->work_hreftagbegin
= '<span class="highlight"';
1247 $linkobject->work_hreftagend
= '</span>';
1249 $linkobject->work_hreftagbegin
= $linkobject->hreftagbegin
;
1250 $linkobject->work_hreftagend
= $linkobject->hreftagend
;
1253 /// Double up chars to protect true duplicates
1254 /// be cleared up before returning to the user.
1255 $linkobject->work_hreftagbegin
= preg_replace('/([#*%])/','\1\1',$linkobject->work_hreftagbegin
);
1257 if (empty($linkobject->casesensitive
)) {
1258 $linkobject->work_casesensitive
= false;
1260 $linkobject->work_casesensitive
= true;
1262 if (empty($linkobject->fullmatch
)) {
1263 $linkobject->work_fullmatch
= false;
1265 $linkobject->work_fullmatch
= true;
1268 /// Strip tags out of the phrase
1269 $linkobject->work_phrase
= strip_tags($linkobject->phrase
);
1271 /// Double up chars that might cause a false match -- the duplicates will
1272 /// be cleared up before returning to the user.
1273 $linkobject->work_phrase
= preg_replace('/([#*%])/','\1\1',$linkobject->work_phrase
);
1275 /// Set the replacement phrase properly
1276 if ($linkobject->replacementphrase
) { //We have specified a replacement phrase
1278 $linkobject->work_replacementphrase
= strip_tags($linkobject->replacementphrase
);
1279 } else { //The replacement is the original phrase as matched below
1280 $linkobject->work_replacementphrase
= '$1';
1283 /// Quote any regular expression characters and the delimiter in the work phrase to be searched
1284 $linkobject->work_phrase
= preg_quote($linkobject->work_phrase
, '/');
1287 $linkobject->work_calculated
= true;
1291 /// If $CFG->filtermatchoneperpage, avoid previously (request) linked phrases
1292 if (!empty($CFG->filtermatchoneperpage
)) {
1293 if (!empty($usedphrases) && in_array($linkobject->work_phrase
,$usedphrases)) {
1298 /// Regular expression modifiers
1299 $modifiers = ($linkobject->work_casesensitive
) ?
's' : 'isu'; // works in unicode mode!
1301 /// Do we need to do a fullmatch?
1302 /// If yes then go through and remove any non full matching entries
1303 if ($linkobject->work_fullmatch
) {
1304 $notfullmatches = array();
1305 $regexp = '/'.$filterinvalidprefixes.'('.$linkobject->work_phrase
.')|('.$linkobject->work_phrase
.')'.$filterinvalidsuffixes.'/'.$modifiers;
1307 preg_match_all($regexp,$text,$list_of_notfullmatches);
1309 if ($list_of_notfullmatches) {
1310 foreach (array_unique($list_of_notfullmatches[0]) as $key=>$value) {
1311 $notfullmatches['<*'.$key.'*>'] = $value;
1313 if (!empty($notfullmatches)) {
1314 $text = str_replace($notfullmatches,array_keys($notfullmatches),$text);
1319 /// Finally we do our highlighting
1320 if (!empty($CFG->filtermatchonepertext
) ||
!empty($CFG->filtermatchoneperpage
)) {
1321 $resulttext = preg_replace('/('.$linkobject->work_phrase
.')/'.$modifiers,
1322 $linkobject->work_hreftagbegin
.
1323 $linkobject->work_replacementphrase
.
1324 $linkobject->work_hreftagend
, $text, 1);
1326 $resulttext = preg_replace('/('.$linkobject->work_phrase
.')/'.$modifiers,
1327 $linkobject->work_hreftagbegin
.
1328 $linkobject->work_replacementphrase
.
1329 $linkobject->work_hreftagend
, $text);
1333 /// If the text has changed we have to look for links again
1334 if ($resulttext != $text) {
1335 /// Set $text to $resulttext
1336 $text = $resulttext;
1337 /// Remove everything enclosed by the ignore tags from $text
1338 filter_save_ignore_tags($text,$filterignoretagsopen,$filterignoretagsclose,$ignoretags);
1339 /// Remove tags from $text
1340 filter_save_tags($text,$tags);
1341 /// If $CFG->filtermatchoneperpage, save linked phrases to request
1342 if (!empty($CFG->filtermatchoneperpage
)) {
1343 $usedphrases[] = $linkobject->work_phrase
;
1348 /// Replace the not full matches before cycling to next link object
1349 if (!empty($notfullmatches)) {
1350 $text = str_replace(array_keys($notfullmatches),$notfullmatches,$text);
1351 unset($notfullmatches);
1355 /// Rebuild the text with all the excluded areas
1357 if (!empty($tags)) {
1358 $text = str_replace(array_keys($tags), $tags, $text);
1361 if (!empty($ignoretags)) {
1362 $ignoretags = array_reverse($ignoretags); /// Reversed so "progressive" str_replace() will solve some nesting problems.
1363 $text = str_replace(array_keys($ignoretags),$ignoretags,$text);
1366 //// Remove the protective doubleups
1367 $text = preg_replace('/([#*%])(\1)/','\1',$text);
1369 /// Add missing javascript for popus
1370 $text = filter_add_javascript($text);
1377 * @todo Document this function
1378 * @param array $linkarray
1381 function filter_remove_duplicates($linkarray) {
1383 $concepts = array(); // keep a record of concepts as we cycle through
1384 $lconcepts = array(); // a lower case version for case insensitive
1386 $cleanlinks = array();
1388 foreach ($linkarray as $key=>$filterobject) {
1389 if ($filterobject->casesensitive
) {
1390 $exists = in_array($filterobject->phrase
, $concepts);
1392 $exists = in_array(textlib
::strtolower($filterobject->phrase
), $lconcepts);
1396 $cleanlinks[] = $filterobject;
1397 $concepts[] = $filterobject->phrase
;
1398 $lconcepts[] = textlib
::strtolower($filterobject->phrase
);
1406 * Extract open/lose tags and their contents to avoid being processed by filters.
1407 * Useful to extract pieces of code like <a>...</a> tags. It returns the text
1408 * converted with some <#xTEXTFILTER_EXCL_SEPARATORx#> codes replacing the extracted text. Such extracted
1409 * texts are returned in the ignoretags array (as values), with codes as keys.
1411 * @param string $text the text that we are filtering (in/out)
1412 * @param array $filterignoretagsopen an array of open tags to start searching
1413 * @param array $filterignoretagsclose an array of close tags to end searching
1414 * @param array $ignoretags an array of saved strings useful to rebuild the original text (in/out)
1416 function filter_save_ignore_tags(&$text, $filterignoretagsopen, $filterignoretagsclose, &$ignoretags) {
1418 /// Remove everything enclosed by the ignore tags from $text
1419 foreach ($filterignoretagsopen as $ikey=>$opentag) {
1420 $closetag = $filterignoretagsclose[$ikey];
1421 /// form regular expression
1422 $opentag = str_replace('/','\/',$opentag); // delimit forward slashes
1423 $closetag = str_replace('/','\/',$closetag); // delimit forward slashes
1424 $pregexp = '/'.$opentag.'(.*?)'.$closetag.'/is';
1426 preg_match_all($pregexp, $text, $list_of_ignores);
1427 foreach (array_unique($list_of_ignores[0]) as $key=>$value) {
1428 $prefix = (string)(count($ignoretags) +
1);
1429 $ignoretags['<#'.$prefix.TEXTFILTER_EXCL_SEPARATOR
.$key.'#>'] = $value;
1431 if (!empty($ignoretags)) {
1432 $text = str_replace($ignoretags,array_keys($ignoretags),$text);
1438 * Extract tags (any text enclosed by < and > to avoid being processed by filters.
1439 * It returns the text converted with some <%xTEXTFILTER_EXCL_SEPARATORx%> codes replacing the extracted text. Such extracted
1440 * texts are returned in the tags array (as values), with codes as keys.
1442 * @param string $text the text that we are filtering (in/out)
1443 * @param array $tags an array of saved strings useful to rebuild the original text (in/out)
1445 function filter_save_tags(&$text, &$tags) {
1447 preg_match_all('/<([^#%*].*?)>/is',$text,$list_of_newtags);
1448 foreach (array_unique($list_of_newtags[0]) as $ntkey=>$value) {
1449 $prefix = (string)(count($tags) +
1);
1450 $tags['<%'.$prefix.TEXTFILTER_EXCL_SEPARATOR
.$ntkey.'%>'] = $value;
1452 if (!empty($tags)) {
1453 $text = str_replace($tags,array_keys($tags),$text);
1458 * Add missing openpopup javascript to HTML files.
1460 * @param string $text
1463 function filter_add_javascript($text) {
1466 if (stripos($text, '</html>') === FALSE) {
1467 return $text; // this is not a html file
1469 if (strpos($text, 'onclick="return openpopup') === FALSE) {
1470 return $text; // no popup - no need to add javascript
1473 <script type=\"text/javascript\">
1475 function openpopup(url,name,options,fullscreen) {
1476 fullurl = \"".$CFG->httpswwwroot
."\" + url;
1477 windowobj = window.open(fullurl,name,options);
1479 windowobj.moveTo(0,0);
1480 windowobj.resizeTo(screen.availWidth,screen.availHeight);
1487 if (stripos($text, '</head>') !== FALSE) {
1488 //try to add it into the head element
1489 $text = str_ireplace('</head>', $js.'</head>', $text);
1493 //last chance - try adding head element
1494 return preg_replace("/<html.*?>/is", "\\0<head>".$js.'</head>', $text);