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