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 $legacyfunctionname = basename($filtername) . '_filter';
140 if (function_exists($legacyfunctionname)) {
141 return new legacy_filter($legacyfunctionname, $context, $localconfig);
148 * @todo Document this function
149 * @param string $text
150 * @param array $filterchain
151 * @param array $options options passed to the filters
152 * @return string $text
154 protected function apply_filter_chain($text, $filterchain, array $options = array()) {
155 foreach ($filterchain as $filter) {
156 $text = $filter->filter($text, $options);
162 * @todo Document this function
163 * @param object $context
164 * @return object A text filter
166 protected function get_text_filters($context) {
167 if (!isset($this->textfilters
[$context->id
])) {
168 $this->load_filters($context);
170 return $this->textfilters
[$context->id
];
174 * @todo Document this function
175 * @param object $context
176 * @return object A string filter
178 protected function get_string_filters($context) {
179 if (!isset($this->stringfilters
[$context->id
])) {
180 $this->load_filters($context);
182 return $this->stringfilters
[$context->id
];
188 * @param string $text The text to filter
189 * @param object $context
190 * @param array $options options passed to the filters
191 * @return string resulting text
193 public function filter_text($text, $context, array $options = array()) {
194 $text = $this->apply_filter_chain($text, $this->get_text_filters($context), $options);
195 /// <nolink> tags removed for XHTML compatibility
196 $text = str_replace(array('<nolink>', '</nolink>'), '', $text);
201 * Filter a piece of string
203 * @param string $string The text to filter
204 * @param object $context
205 * @return string resulting string
207 public function filter_string($string, $context) {
208 return $this->apply_filter_chain($string, $this->get_string_filters($context));
212 * @todo Document this function
213 * @param object $context
214 * @return object A string filter
216 public function text_filtering_hash($context) {
217 $filters = $this->get_text_filters($context);
219 foreach ($filters as $filter) {
220 $hashes[] = $filter->hash();
222 return implode('-', $hashes);
227 * Filter manager subclass that does nothing. Having this simplifies the logic
228 * of format_text, etc.
230 * @todo Document this class
234 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
235 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
237 class null_filter_manager
{
241 public function filter_text($text, $context, $options) {
248 public function filter_string($string, $context) {
255 public function text_filtering_hash() {
261 * Filter manager subclass that tacks how much work it does.
263 * @todo Document this class
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 performance_measuring_filter_manager
extends filter_manager
{
272 protected $filterscreated = 0;
273 protected $textsfiltered = 0;
274 protected $stringsfiltered = 0;
277 * @param string $filtername
278 * @param object $context
279 * @param mixed $localconfig
282 protected function make_filter_object($filtername, $context, $localconfig) {
283 $this->filterscreated++
;
284 return parent
::make_filter_object($filtername, $context, $localconfig);
288 * @param string $text
289 * @param object $context
290 * @param array $options options passed to the filters
293 public function filter_text($text, $context, array $options = array()) {
294 $this->textsfiltered++
;
295 return parent
::filter_text($text, $context, $options);
299 * @param string $string
300 * @param object $context
303 public function filter_string($string, $context) {
304 $this->stringsfiltered++
;
305 return parent
::filter_string($string, $context);
311 public function get_performance_summary() {
313 'contextswithfilters' => count($this->textfilters
),
314 'filterscreated' => $this->filterscreated
,
315 'textsfiltered' => $this->textsfiltered
,
316 'stringsfiltered' => $this->stringsfiltered
,
318 'contextswithfilters' => 'Contexts for which filters were loaded',
319 'filterscreated' => 'Filters created',
320 'textsfiltered' => 'Pieces of content filtered',
321 'stringsfiltered' => 'Strings filtered',
327 * Base class for text filters. You just need to override this class and
328 * implement the filter method.
332 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
333 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
335 abstract class moodle_text_filter
{
336 /** @var object The context we are in. */
338 /** @var array Any local configuration for this filter in this context. */
339 protected $localconfig;
342 * Set any context-specific configuration for this filter.
343 * @param object $context The current course id.
344 * @param object $context The current context.
345 * @param array $config Any context-specific configuration for this filter.
347 public function __construct($context, array $localconfig) {
348 $this->context
= $context;
349 $this->localconfig
= $localconfig;
353 * @return string The class name of the current class
355 public function hash() {
360 * Override this function to actually implement the filtering.
362 * @param $text some HTML content.
363 * @param array $options options passed to the filters
364 * @return the HTML content after the filtering has been applied.
366 public abstract function filter($text, array $options = array());
370 * moodle_text_filter implementation that encapsulates an old-style filter that
371 * only defines a function, not a class.
375 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
376 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
378 class legacy_filter
extends moodle_text_filter
{
380 protected $filterfunction;
384 * Set any context-specific configuration for this filter.
386 * @param string $filterfunction
387 * @param object $context The current context.
388 * @param array $config Any context-specific configuration for this filter.
390 public function __construct($filterfunction, $context, array $localconfig) {
391 parent
::__construct($context, $localconfig);
392 $this->filterfunction
= $filterfunction;
393 $this->courseid
= get_courseid_from_context($this->context
);
397 * @param string $text
398 * @param array $options options - not supported for legacy filters
401 public function filter($text, array $options = array()) {
402 if ($this->courseid
) {
403 // old filters are called only when inside courses
404 return call_user_func($this->filterfunction
, $this->courseid
, $text);
412 * This is just a little object to define a phrase and some instructions
413 * for how to process it. Filters can create an array of these to pass
414 * to the filter_phrases function below.
418 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
419 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
430 var $replacementphrase;
432 var $work_hreftagbegin;
433 var $work_hreftagend;
434 var $work_casesensitive;
436 var $work_replacementphrase;
438 var $work_calculated;
441 * A constructor just because I like constructing
443 * @param string $phrase
444 * @param string $hreftagbegin
445 * @param string $hreftagend
446 * @param bool $casesensitive
447 * @param bool $fullmatch
448 * @param mixed $replacementphrase
450 function filterobject($phrase, $hreftagbegin = '<span class="highlight">',
451 $hreftagend = '</span>',
452 $casesensitive = false,
454 $replacementphrase = NULL) {
456 $this->phrase
= $phrase;
457 $this->hreftagbegin
= $hreftagbegin;
458 $this->hreftagend
= $hreftagend;
459 $this->casesensitive
= $casesensitive;
460 $this->fullmatch
= $fullmatch;
461 $this->replacementphrase
= $replacementphrase;
462 $this->work_calculated
= false;
468 * Look up the name of this filter in the most appropriate location.
469 * If $filterlocation = 'mod' then does get_string('filtername', $filter);
470 * else if $filterlocation = 'filter' then does get_string('filtername', 'filter_' . $filter);
471 * with a fallback to get_string('filtername', $filter) for backwards compatibility.
472 * These are the only two options supported at the moment.
474 * @param string $filter the folder name where the filter lives.
475 * @return string the human-readable name for this filter.
477 function filter_get_name($filter) {
478 list($type, $filter) = explode('/', $filter);
481 $strfiltername = get_string('filtername', 'filter_' . $filter);
482 if (substr($strfiltername, 0, 2) != '[[') {
483 // found a valid string.
484 return $strfiltername;
486 // Fall through to try the legacy location.
489 $strfiltername = get_string('filtername', $filter);
490 if (substr($strfiltername, 0, 2) == '[[') {
491 $strfiltername .= ' (' . $type . '/' . $filter . ')';
493 return $strfiltername;
496 throw new coding_exception('Unknown filter type ' . $type);
501 * Get the names of all the filters installed in this Moodle.
504 * @return array path => filter name from the appropriate lang file. e.g.
505 * array('mod/glossary' => 'Glossary Auto-linking', 'filter/tex' => 'TeX Notation');
506 * sorted in alphabetical order of name.
508 function filter_get_all_installed() {
510 $filternames = array();
511 $filterlocations = array('mod', 'filter');
512 foreach ($filterlocations as $filterlocation) {
513 $filters = get_list_of_plugins($filterlocation);
514 foreach ($filters as $filter) {
515 $path = $filterlocation . '/' . $filter;
516 if (is_readable($CFG->dirroot
. '/' . $path . '/filter.php')) {
517 $strfiltername = filter_get_name($path);
518 $filternames[$path] = $strfiltername;
522 collatorlib
::asort($filternames);
527 * Set the global activated state for a text filter.
530 * @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
531 * @param integer $state One of the values TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_DISABLED.
532 * @param integer $sortorder (optional) a position in the sortorder to place this filter.
533 * If not given defaults to:
534 * No change in order if we are updating an existing record, and not changing to or from TEXTFILTER_DISABLED.
535 * Just after the last currently active filter when adding an unknown filter
536 * in state TEXTFILTER_ON or TEXTFILTER_OFF, or enabling/disabling an existing filter.
537 * Just after the very last filter when adding an unknown filter in state TEXTFILTER_DISABLED
539 function filter_set_global_state($filter, $state, $sortorder = false) {
542 // Check requested state is valid.
543 if (!in_array($state, array(TEXTFILTER_ON
, TEXTFILTER_OFF
, TEXTFILTER_DISABLED
))) {
544 throw new coding_exception("Illegal option '$state' passed to filter_set_global_state. " .
545 "Must be one of TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_DISABLED.");
548 // Check sortorder is valid.
549 if ($sortorder !== false) {
550 if ($sortorder < 1 ||
$sortorder > $DB->get_field('filter_active', 'MAX(sortorder)', array()) +
1) {
551 throw new coding_exception("Invalid sort order passed to filter_set_global_state.");
555 // See if there is an existing record.
556 $syscontext = get_context_instance(CONTEXT_SYSTEM
);
557 $rec = $DB->get_record('filter_active', array('filter' => $filter, 'contextid' => $syscontext->id
));
561 $rec->filter
= $filter;
562 $rec->contextid
= $syscontext->id
;
565 if ($sortorder === false && !($rec->active
== TEXTFILTER_DISABLED
xor $state == TEXTFILTER_DISABLED
)) {
566 $sortorder = $rec->sortorder
;
570 // Automatic sort order.
571 if ($sortorder === false) {
572 if ($state == TEXTFILTER_DISABLED
&& $insert) {
573 $prevmaxsortorder = $DB->get_field('filter_active', 'MAX(sortorder)', array());
575 $prevmaxsortorder = $DB->get_field_select('filter_active', 'MAX(sortorder)', 'active <> ?', array(TEXTFILTER_DISABLED
));
577 if (empty($prevmaxsortorder)) {
580 $sortorder = $prevmaxsortorder +
1;
581 if (!$insert && $state == TEXTFILTER_DISABLED
) {
582 $sortorder = $prevmaxsortorder;
587 // Move any existing records out of the way of the sortorder.
589 $DB->execute('UPDATE {filter_active} SET sortorder = sortorder + 1 WHERE sortorder >= ?', array($sortorder));
590 } else if ($sortorder != $rec->sortorder
) {
591 $sparesortorder = $DB->get_field('filter_active', 'MIN(sortorder)', array()) - 1;
592 $DB->set_field('filter_active', 'sortorder', $sparesortorder, array('filter' => $filter, 'contextid' => $syscontext->id
));
593 if ($sortorder < $rec->sortorder
) {
594 $DB->execute('UPDATE {filter_active} SET sortorder = sortorder + 1 WHERE sortorder >= ? AND sortorder < ?',
595 array($sortorder, $rec->sortorder
));
596 } else if ($sortorder > $rec->sortorder
) {
597 $DB->execute('UPDATE {filter_active} SET sortorder = sortorder - 1 WHERE sortorder <= ? AND sortorder > ?',
598 array($sortorder, $rec->sortorder
));
602 // Insert/update the new record.
603 $rec->active
= $state;
604 $rec->sortorder
= $sortorder;
606 $DB->insert_record('filter_active', $rec);
608 $DB->update_record('filter_active', $rec);
613 * @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
614 * @return boolean is this filter allowed to be used on this site. That is, the
615 * admin has set the global 'active' setting to On, or Off, but available.
617 function filter_is_enabled($filter) {
618 return array_key_exists($filter, filter_get_globally_enabled());
622 * Return a list of all the filters that may be in use somewhere.
624 * @staticvar array $enabledfilters
625 * @return array where the keys and values are both the filter name, like 'filter/tex'.
627 function filter_get_globally_enabled() {
628 static $enabledfilters = null;
629 if (is_null($enabledfilters)) {
630 $filters = filter_get_global_states();
631 $enabledfilters = array();
632 foreach ($filters as $filter => $filerinfo) {
633 if ($filerinfo->active
!= TEXTFILTER_DISABLED
) {
634 $enabledfilters[$filter] = $filter;
638 return $enabledfilters;
642 * Return the names of the filters that should also be applied to strings
643 * (when they are enabled).
646 * @return array where the keys and values are both the filter name, like 'filter/tex'.
648 function filter_get_string_filters() {
650 $stringfilters = array();
651 if (!empty($CFG->filterall
) && !empty($CFG->stringfilters
)) {
652 $stringfilters = explode(',', $CFG->stringfilters
);
653 $stringfilters = array_combine($stringfilters, $stringfilters);
655 return $stringfilters;
659 * Sets whether a particular active filter should be applied to all strings by
660 * format_string, or just used by format_text.
662 * @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
663 * @param boolean $applytostrings if true, this filter will apply to format_string
664 * and format_text, when it is enabled.
666 function filter_set_applies_to_strings($filter, $applytostrings) {
667 $stringfilters = filter_get_string_filters();
668 $numstringfilters = count($stringfilters);
669 if ($applytostrings) {
670 $stringfilters[$filter] = $filter;
672 unset($stringfilters[$filter]);
674 if (count($stringfilters) != $numstringfilters) {
675 set_config('stringfilters', implode(',', $stringfilters));
676 set_config('filterall', !empty($stringfilters));
681 * Set the local activated state for a text filter.
684 * @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
685 * @param integer $contextid The id of the context to get the local config for.
686 * @param integer $state One of the values TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_INHERIT.
689 function filter_set_local_state($filter, $contextid, $state) {
692 // Check requested state is valid.
693 if (!in_array($state, array(TEXTFILTER_ON
, TEXTFILTER_OFF
, TEXTFILTER_INHERIT
))) {
694 throw new coding_exception("Illegal option '$state' passed to filter_set_local_state. " .
695 "Must be one of TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_INHERIT.");
698 if ($contextid == get_context_instance(CONTEXT_SYSTEM
)->id
) {
699 throw new coding_exception('You cannot use filter_set_local_state ' .
700 'with $contextid equal to the system context id.');
703 if ($state == TEXTFILTER_INHERIT
) {
704 $DB->delete_records('filter_active', array('filter' => $filter, 'contextid' => $contextid));
708 $rec = $DB->get_record('filter_active', array('filter' => $filter, 'contextid' => $contextid));
713 $rec->filter
= $filter;
714 $rec->contextid
= $contextid;
717 $rec->active
= $state;
720 $DB->insert_record('filter_active', $rec);
722 $DB->update_record('filter_active', $rec);
727 * Set a particular local config variable for a filter in a context.
730 * @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
731 * @param integer $contextid The id of the context to get the local config for.
732 * @param string $name the setting name.
733 * @param string $value the corresponding value.
735 function filter_set_local_config($filter, $contextid, $name, $value) {
737 $rec = $DB->get_record('filter_config', array('filter' => $filter, 'contextid' => $contextid, 'name' => $name));
742 $rec->filter
= $filter;
743 $rec->contextid
= $contextid;
747 $rec->value
= $value;
750 $DB->insert_record('filter_config', $rec);
752 $DB->update_record('filter_config', $rec);
757 * Remove a particular local config variable for a filter in a context.
760 * @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
761 * @param integer $contextid The id of the context to get the local config for.
762 * @param string $name the setting name.
764 function filter_unset_local_config($filter, $contextid, $name) {
766 $DB->delete_records('filter_config', array('filter' => $filter, 'contextid' => $contextid, 'name' => $name));
770 * Get local config variables for a filter in a context. Normally (when your
771 * filter is running) you don't need to call this, becuase the config is fetched
772 * for you automatically. You only need this, for example, when you are getting
773 * the config so you can show the user an editing from.
776 * @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
777 * @param integer $contextid The ID of the context to get the local config for.
778 * @return array of name => value pairs.
780 function filter_get_local_config($filter, $contextid) {
782 return $DB->get_records_menu('filter_config', array('filter' => $filter, 'contextid' => $contextid), '', 'name,value');
786 * This function is for use by backup. Gets all the filter information specific
790 * @param int $contextid
791 * @return array Array with two elements. The first element is an array of objects with
792 * fields filter and active. These come from the filter_active table. The
793 * second element is an array of objects with fields filter, name and value
794 * from the filter_config table.
796 function filter_get_all_local_settings($contextid) {
798 $context = get_context_instance(CONTEXT_SYSTEM
);
800 $DB->get_records('filter_active', array('contextid' => $contextid), 'filter', 'filter,active'),
801 $DB->get_records('filter_config', array('contextid' => $contextid), 'filter,name', 'filter,name,value'),
806 * Get the list of active filters, in the order that they should be used
807 * for a particular context, along with any local configuration variables.
810 * @param object $context a context
811 * @return array an array where the keys are the filter names, for example
812 * 'filter/tex' or 'mod/glossary' and the values are any local
813 * configuration for that filter, as an array of name => value pairs
814 * from the filter_config table. In a lot of cases, this will be an
815 * empty array. So, an example return value for this function might be
816 * array('filter/tex' => array(), 'mod/glossary' => array('glossaryid', 123))
818 function filter_get_active_in_context($context) {
819 global $DB, $FILTERLIB_PRIVATE;
821 // Use cache (this is a within-request cache only) if available. See
822 // function filter_preload_activities.
823 if (isset($FILTERLIB_PRIVATE->active
) &&
824 array_key_exists($context->id
, $FILTERLIB_PRIVATE->active
)) {
825 return $FILTERLIB_PRIVATE->active
[$context->id
];
828 $contextids = str_replace('/', ',', trim($context->path
, '/'));
830 // The following SQL is tricky. It is explained on
831 // http://docs.moodle.org/dev/Filter_enable/disable_by_context
832 $sql = "SELECT active.filter, fc.name, fc.value
833 FROM (SELECT f.filter, MAX(f.sortorder) AS sortorder
834 FROM {filter_active} f
835 JOIN {context} ctx ON f.contextid = ctx.id
836 WHERE ctx.id IN ($contextids)
838 HAVING MAX(f.active * " . $DB->sql_cast_2signed('ctx.depth') .
839 ") > -MIN(f.active * " . $DB->sql_cast_2signed('ctx.depth') . ")
841 LEFT JOIN {filter_config} fc ON fc.filter = active.filter AND fc.contextid = $context->id
842 ORDER BY active.sortorder";
843 $rs = $DB->get_recordset_sql($sql);
845 // Masssage the data into the specified format to return.
847 foreach ($rs as $row) {
848 if (!isset($filters[$row->filter
])) {
849 $filters[$row->filter
] = array();
851 if (!is_null($row->name
)) {
852 $filters[$row->filter
][$row->name
] = $row->value
;
862 * Preloads the list of active filters for all activities (modules) on the course
863 * using two database queries.
864 * @param course_modinfo $modinfo Course object from get_fast_modinfo
866 function filter_preload_activities(course_modinfo
$modinfo) {
867 global $DB, $FILTERLIB_PRIVATE;
869 // Don't repeat preload
870 if (!isset($FILTERLIB_PRIVATE->preloaded
)) {
871 $FILTERLIB_PRIVATE->preloaded
= array();
873 if (!empty($FILTERLIB_PRIVATE->preloaded
[$modinfo->get_course_id()])) {
876 $FILTERLIB_PRIVATE->preloaded
[$modinfo->get_course_id()] = true;
878 // Get contexts for all CMs
879 $cmcontexts = array();
880 $cmcontextids = array();
881 foreach ($modinfo->get_cms() as $cm) {
882 $modulecontext = get_context_instance(CONTEXT_MODULE
, $cm->id
);
883 $cmcontextids[] = $modulecontext->id
;
884 $cmcontexts[] = $modulecontext;
887 // Get course context and all other parents...
888 $coursecontext = get_context_instance(CONTEXT_COURSE
, $modinfo->get_course_id());
889 $parentcontextids = explode('/', substr($coursecontext->path
, 1));
890 $allcontextids = array_merge($cmcontextids, $parentcontextids);
892 // Get all filter_active rows relating to all these contexts
893 list ($sql, $params) = $DB->get_in_or_equal($allcontextids);
894 $filteractives = $DB->get_records_select('filter_active', "contextid $sql", $params);
896 // Get all filter_config only for the cm contexts
897 list ($sql, $params) = $DB->get_in_or_equal($cmcontextids);
898 $filterconfigs = $DB->get_records_select('filter_config', "contextid $sql", $params);
900 // Note: I was a bit surprised that filter_config only works for the
901 // most specific context (i.e. it does not need to be checked for course
902 // context if we only care about CMs) however basede on code in
903 // filter_get_active_in_context, this does seem to be correct.
905 // Build course default active list. Initially this will be an array of
906 // filter name => active score (where an active score >0 means it's active)
907 $courseactive = array();
909 // Also build list of filter_active rows below course level, by contextid
910 $remainingactives = array();
912 // Array lists filters that are banned at top level
915 // Add any active filters in parent contexts to the array
916 foreach ($filteractives as $row) {
917 $depth = array_search($row->contextid
, $parentcontextids);
918 if ($depth !== false) {
920 if (!array_key_exists($row->filter
, $courseactive)) {
921 $courseactive[$row->filter
] = 0;
923 // This maths copes with reading rows in any order. Turning on/off
924 // at site level counts 1, at next level down 4, at next level 9,
925 // then 16, etc. This means the deepest level always wins, except
926 // against the -9999 at top level.
927 $courseactive[$row->filter
] +
=
928 ($depth +
1) * ($depth +
1) * $row->active
;
930 if ($row->active
== TEXTFILTER_DISABLED
) {
931 $banned[$row->filter
] = true;
934 // Build list of other rows indexed by contextid
935 if (!array_key_exists($row->contextid
, $remainingactives)) {
936 $remainingactives[$row->contextid
] = array();
938 $remainingactives[$row->contextid
][] = $row;
942 // Chuck away the ones that aren't active
943 foreach ($courseactive as $filter=>$score) {
945 unset($courseactive[$filter]);
947 $courseactive[$filter] = array();
951 // Loop through the contexts to reconstruct filter_active lists for each
953 if (!isset($FILTERLIB_PRIVATE->active
)) {
954 $FILTERLIB_PRIVATE->active
= array();
956 foreach ($cmcontextids as $contextid) {
958 $FILTERLIB_PRIVATE->active
[$contextid] = $courseactive;
960 // Are there any changes to the active list?
961 if (array_key_exists($contextid, $remainingactives)) {
962 foreach ($remainingactives[$contextid] as $row) {
963 if ($row->active
> 0 && empty($banned[$row->filter
])) {
964 // If it's marked active for specific context, add entry
965 // (doesn't matter if one exists already)
966 $FILTERLIB_PRIVATE->active
[$contextid][$row->filter
] = array();
968 // If it's marked inactive, remove entry (doesn't matter
969 // if it doesn't exist)
970 unset($FILTERLIB_PRIVATE->active
[$contextid][$row->filter
]);
976 // Process all config rows to add config data to these entries
977 foreach ($filterconfigs as $row) {
978 if (isset($FILTERLIB_PRIVATE->active
[$row->contextid
][$row->filter
])) {
979 $FILTERLIB_PRIVATE->active
[$row->contextid
][$row->filter
][$row->name
] = $row->value
;
985 * List all of the filters that are available in this context, and what the
986 * local and inherited states of that filter are.
989 * @param object $context a context that is not the system context.
990 * @return array an array with filter names, for example 'filter/tex' or
991 * 'mod/glossary' as keys. and and the values are objects with fields:
992 * ->filter filter name, same as the key.
993 * ->localstate TEXTFILTER_ON/OFF/INHERIT
994 * ->inheritedstate TEXTFILTER_ON/OFF - the state that will be used if localstate is set to TEXTFILTER_INHERIT.
996 function filter_get_available_in_context($context) {
999 // The complex logic is working out the active state in the parent context,
1000 // so strip the current context from the list.
1001 $contextids = explode('/', trim($context->path
, '/'));
1002 array_pop($contextids);
1003 $contextids = implode(',', $contextids);
1004 if (empty($contextids)) {
1005 throw new coding_exception('filter_get_available_in_context cannot be called with the system context.');
1008 // The following SQL is tricky, in the same way at the SQL in filter_get_active_in_context.
1009 $sql = "SELECT parent_states.filter,
1010 CASE WHEN fa.active IS NULL THEN " . TEXTFILTER_INHERIT
. "
1011 ELSE fa.active END AS localstate,
1012 parent_states.inheritedstate
1013 FROM (SELECT f.filter, MAX(f.sortorder) AS sortorder,
1014 CASE WHEN MAX(f.active * " . $DB->sql_cast_2signed('ctx.depth') .
1015 ") > -MIN(f.active * " . $DB->sql_cast_2signed('ctx.depth') . ") THEN " . TEXTFILTER_ON
. "
1016 ELSE " . TEXTFILTER_OFF
. " END AS inheritedstate
1017 FROM {filter_active} f
1018 JOIN {context} ctx ON f.contextid = ctx.id
1019 WHERE ctx.id IN ($contextids)
1021 HAVING MIN(f.active) > " . TEXTFILTER_DISABLED
. "
1023 LEFT JOIN {filter_active} fa ON fa.filter = parent_states.filter AND fa.contextid = $context->id
1024 ORDER BY parent_states.sortorder";
1025 return $DB->get_records_sql($sql);
1029 * This function is for use by the filter administration page.
1032 * @return array 'filtername' => object with fields 'filter' (=filtername), 'active' and 'sortorder'
1034 function filter_get_global_states() {
1036 $context = get_context_instance(CONTEXT_SYSTEM
);
1037 return $DB->get_records('filter_active', array('contextid' => $context->id
), 'sortorder', 'filter,active,sortorder');
1041 * Delete all the data in the database relating to a filter, prior to deleting it.
1044 * @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
1046 function filter_delete_all_for_filter($filter) {
1048 if (substr($filter, 0, 7) == 'filter/') {
1049 unset_all_config_for_plugin('filter_' . basename($filter));
1051 $DB->delete_records('filter_active', array('filter' => $filter));
1052 $DB->delete_records('filter_config', array('filter' => $filter));
1056 * Delete all the data in the database relating to a context, used when contexts are deleted.
1058 * @param integer $contextid The id of the context being deleted.
1060 function filter_delete_all_for_context($contextid) {
1062 $DB->delete_records('filter_active', array('contextid' => $contextid));
1063 $DB->delete_records('filter_config', array('contextid' => $contextid));
1067 * Does this filter have a global settings page in the admin tree?
1068 * (The settings page for a filter must be called, for example,
1069 * filtersettingfiltertex or filtersettingmodglossay.)
1071 * @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
1072 * @return boolean Whether there should be a 'Settings' link on the config page.
1074 function filter_has_global_settings($filter) {
1076 $settingspath = $CFG->dirroot
. '/' . $filter . '/filtersettings.php';
1077 return is_readable($settingspath);
1081 * Does this filter have local (per-context) settings?
1083 * @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
1084 * @return boolean Whether there should be a 'Settings' link on the manage filters in context page.
1086 function filter_has_local_settings($filter) {
1088 $settingspath = $CFG->dirroot
. '/' . $filter . '/filterlocalsettings.php';
1089 return is_readable($settingspath);
1093 * Certain types of context (block and user) may not have local filter settings.
1094 * the function checks a context to see whether it may have local config.
1096 * @param object $context a context.
1097 * @return boolean whether this context may have local filter settings.
1099 function filter_context_may_have_filter_settings($context) {
1100 return $context->contextlevel
!= CONTEXT_BLOCK
&& $context->contextlevel
!= CONTEXT_USER
;
1104 * Process phrases intelligently found within a HTML text (such as adding links)
1106 * @staticvar array $usedpharses
1107 * @param string $text the text that we are filtering
1108 * @param array $link_array an array of filterobjects
1109 * @param array $ignoretagsopen an array of opening tags that we should ignore while filtering
1110 * @param array $ignoretagsclose an array of corresponding closing tags
1111 * @param bool $overridedefaultignore True to only use tags provided by arguments
1114 function filter_phrases($text, &$link_array, $ignoretagsopen=NULL, $ignoretagsclose=NULL,
1115 $overridedefaultignore=false) {
1119 static $usedphrases;
1121 $ignoretags = array(); //To store all the enclosig tags to be completely ignored
1122 $tags = array(); //To store all the simple tags to be ignored
1124 if (!$overridedefaultignore) {
1125 // A list of open/close tags that we should not replace within
1126 // Extended to include <script>, <textarea>, <select> and <a> tags
1127 // Regular expression allows tags with or without attributes
1128 $filterignoretagsopen = array('<head>' , '<nolink>' , '<span class="nolink">',
1129 '<script(\s[^>]*?)?>', '<textarea(\s[^>]*?)?>',
1130 '<select(\s[^>]*?)?>', '<a(\s[^>]*?)?>');
1131 $filterignoretagsclose = array('</head>', '</nolink>', '</span>',
1132 '</script>', '</textarea>', '</select>','</a>');
1134 // Set an empty default list
1135 $filterignoretagsopen = array();
1136 $filterignoretagsclose = array();
1139 // Add the user defined ignore tags to the default list
1140 if ( is_array($ignoretagsopen) ) {
1141 foreach ($ignoretagsopen as $open) {
1142 $filterignoretagsopen[] = $open;
1144 foreach ($ignoretagsclose as $close) {
1145 $filterignoretagsclose[] = $close;
1149 /// Invalid prefixes and suffixes for the fullmatch searches
1150 /// Every "word" character, but the underscore, is a invalid suffix or prefix.
1151 /// (nice to use this because it includes national characters (accents...) as word characters.
1152 $filterinvalidprefixes = '([^\W_])';
1153 $filterinvalidsuffixes = '([^\W_])';
1155 //// Double up some magic chars to avoid "accidental matches"
1156 $text = preg_replace('/([#*%])/','\1\1',$text);
1159 ////Remove everything enclosed by the ignore tags from $text
1160 filter_save_ignore_tags($text,$filterignoretagsopen,$filterignoretagsclose,$ignoretags);
1162 /// Remove tags from $text
1163 filter_save_tags($text,$tags);
1165 /// Time to cycle through each phrase to be linked
1166 $size = sizeof($link_array);
1167 for ($n=0; $n < $size; $n++
) {
1168 $linkobject =& $link_array[$n];
1170 /// Set some defaults if certain properties are missing
1171 /// Properties may be missing if the filterobject class has not been used to construct the object
1172 if (empty($linkobject->phrase
)) {
1176 /// Avoid integers < 1000 to be linked. See bug 1446.
1177 $intcurrent = intval($linkobject->phrase
);
1178 if (!empty($intcurrent) && strval($intcurrent) == $linkobject->phrase
&& $intcurrent < 1000) {
1182 /// All this work has to be done ONLY it it hasn't been done before
1183 if (!$linkobject->work_calculated
) {
1184 if (!isset($linkobject->hreftagbegin
) or !isset($linkobject->hreftagend
)) {
1185 $linkobject->work_hreftagbegin
= '<span class="highlight"';
1186 $linkobject->work_hreftagend
= '</span>';
1188 $linkobject->work_hreftagbegin
= $linkobject->hreftagbegin
;
1189 $linkobject->work_hreftagend
= $linkobject->hreftagend
;
1192 /// Double up chars to protect true duplicates
1193 /// be cleared up before returning to the user.
1194 $linkobject->work_hreftagbegin
= preg_replace('/([#*%])/','\1\1',$linkobject->work_hreftagbegin
);
1196 if (empty($linkobject->casesensitive
)) {
1197 $linkobject->work_casesensitive
= false;
1199 $linkobject->work_casesensitive
= true;
1201 if (empty($linkobject->fullmatch
)) {
1202 $linkobject->work_fullmatch
= false;
1204 $linkobject->work_fullmatch
= true;
1207 /// Strip tags out of the phrase
1208 $linkobject->work_phrase
= strip_tags($linkobject->phrase
);
1210 /// Double up chars that might cause a false match -- the duplicates will
1211 /// be cleared up before returning to the user.
1212 $linkobject->work_phrase
= preg_replace('/([#*%])/','\1\1',$linkobject->work_phrase
);
1214 /// Set the replacement phrase properly
1215 if ($linkobject->replacementphrase
) { //We have specified a replacement phrase
1217 $linkobject->work_replacementphrase
= strip_tags($linkobject->replacementphrase
);
1218 } else { //The replacement is the original phrase as matched below
1219 $linkobject->work_replacementphrase
= '$1';
1222 /// Quote any regular expression characters and the delimiter in the work phrase to be searched
1223 $linkobject->work_phrase
= preg_quote($linkobject->work_phrase
, '/');
1226 $linkobject->work_calculated
= true;
1230 /// If $CFG->filtermatchoneperpage, avoid previously (request) linked phrases
1231 if (!empty($CFG->filtermatchoneperpage
)) {
1232 if (!empty($usedphrases) && in_array($linkobject->work_phrase
,$usedphrases)) {
1237 /// Regular expression modifiers
1238 $modifiers = ($linkobject->work_casesensitive
) ?
's' : 'isu'; // works in unicode mode!
1240 /// Do we need to do a fullmatch?
1241 /// If yes then go through and remove any non full matching entries
1242 if ($linkobject->work_fullmatch
) {
1243 $notfullmatches = array();
1244 $regexp = '/'.$filterinvalidprefixes.'('.$linkobject->work_phrase
.')|('.$linkobject->work_phrase
.')'.$filterinvalidsuffixes.'/'.$modifiers;
1246 preg_match_all($regexp,$text,$list_of_notfullmatches);
1248 if ($list_of_notfullmatches) {
1249 foreach (array_unique($list_of_notfullmatches[0]) as $key=>$value) {
1250 $notfullmatches['<*'.$key.'*>'] = $value;
1252 if (!empty($notfullmatches)) {
1253 $text = str_replace($notfullmatches,array_keys($notfullmatches),$text);
1258 /// Finally we do our highlighting
1259 if (!empty($CFG->filtermatchonepertext
) ||
!empty($CFG->filtermatchoneperpage
)) {
1260 $resulttext = preg_replace('/('.$linkobject->work_phrase
.')/'.$modifiers,
1261 $linkobject->work_hreftagbegin
.
1262 $linkobject->work_replacementphrase
.
1263 $linkobject->work_hreftagend
, $text, 1);
1265 $resulttext = preg_replace('/('.$linkobject->work_phrase
.')/'.$modifiers,
1266 $linkobject->work_hreftagbegin
.
1267 $linkobject->work_replacementphrase
.
1268 $linkobject->work_hreftagend
, $text);
1272 /// If the text has changed we have to look for links again
1273 if ($resulttext != $text) {
1274 /// Set $text to $resulttext
1275 $text = $resulttext;
1276 /// Remove everything enclosed by the ignore tags from $text
1277 filter_save_ignore_tags($text,$filterignoretagsopen,$filterignoretagsclose,$ignoretags);
1278 /// Remove tags from $text
1279 filter_save_tags($text,$tags);
1280 /// If $CFG->filtermatchoneperpage, save linked phrases to request
1281 if (!empty($CFG->filtermatchoneperpage
)) {
1282 $usedphrases[] = $linkobject->work_phrase
;
1287 /// Replace the not full matches before cycling to next link object
1288 if (!empty($notfullmatches)) {
1289 $text = str_replace(array_keys($notfullmatches),$notfullmatches,$text);
1290 unset($notfullmatches);
1294 /// Rebuild the text with all the excluded areas
1296 if (!empty($tags)) {
1297 $text = str_replace(array_keys($tags), $tags, $text);
1300 if (!empty($ignoretags)) {
1301 $ignoretags = array_reverse($ignoretags); /// Reversed so "progressive" str_replace() will solve some nesting problems.
1302 $text = str_replace(array_keys($ignoretags),$ignoretags,$text);
1305 //// Remove the protective doubleups
1306 $text = preg_replace('/([#*%])(\1)/','\1',$text);
1308 /// Add missing javascript for popus
1309 $text = filter_add_javascript($text);
1316 * @todo Document this function
1317 * @param array $linkarray
1320 function filter_remove_duplicates($linkarray) {
1322 $concepts = array(); // keep a record of concepts as we cycle through
1323 $lconcepts = array(); // a lower case version for case insensitive
1325 $cleanlinks = array();
1327 foreach ($linkarray as $key=>$filterobject) {
1328 if ($filterobject->casesensitive
) {
1329 $exists = in_array($filterobject->phrase
, $concepts);
1331 $exists = in_array(moodle_strtolower($filterobject->phrase
), $lconcepts);
1335 $cleanlinks[] = $filterobject;
1336 $concepts[] = $filterobject->phrase
;
1337 $lconcepts[] = moodle_strtolower($filterobject->phrase
);
1345 * Extract open/lose tags and their contents to avoid being processed by filters.
1346 * Useful to extract pieces of code like <a>...</a> tags. It returns the text
1347 * converted with some <#xTEXTFILTER_EXCL_SEPARATORx#> codes replacing the extracted text. Such extracted
1348 * texts are returned in the ignoretags array (as values), with codes as keys.
1350 * @param string $text the text that we are filtering (in/out)
1351 * @param array $filterignoretagsopen an array of open tags to start searching
1352 * @param array $filterignoretagsclose an array of close tags to end searching
1353 * @param array $ignoretags an array of saved strings useful to rebuild the original text (in/out)
1355 function filter_save_ignore_tags(&$text, $filterignoretagsopen, $filterignoretagsclose, &$ignoretags) {
1357 /// Remove everything enclosed by the ignore tags from $text
1358 foreach ($filterignoretagsopen as $ikey=>$opentag) {
1359 $closetag = $filterignoretagsclose[$ikey];
1360 /// form regular expression
1361 $opentag = str_replace('/','\/',$opentag); // delimit forward slashes
1362 $closetag = str_replace('/','\/',$closetag); // delimit forward slashes
1363 $pregexp = '/'.$opentag.'(.*?)'.$closetag.'/is';
1365 preg_match_all($pregexp, $text, $list_of_ignores);
1366 foreach (array_unique($list_of_ignores[0]) as $key=>$value) {
1367 $prefix = (string)(count($ignoretags) +
1);
1368 $ignoretags['<#'.$prefix.TEXTFILTER_EXCL_SEPARATOR
.$key.'#>'] = $value;
1370 if (!empty($ignoretags)) {
1371 $text = str_replace($ignoretags,array_keys($ignoretags),$text);
1377 * Extract tags (any text enclosed by < and > to avoid being processed by filters.
1378 * It returns the text converted with some <%xTEXTFILTER_EXCL_SEPARATORx%> codes replacing the extracted text. Such extracted
1379 * texts are returned in the tags array (as values), with codes as keys.
1381 * @param string $text the text that we are filtering (in/out)
1382 * @param array $tags an array of saved strings useful to rebuild the original text (in/out)
1384 function filter_save_tags(&$text, &$tags) {
1386 preg_match_all('/<([^#%*].*?)>/is',$text,$list_of_newtags);
1387 foreach (array_unique($list_of_newtags[0]) as $ntkey=>$value) {
1388 $prefix = (string)(count($tags) +
1);
1389 $tags['<%'.$prefix.TEXTFILTER_EXCL_SEPARATOR
.$ntkey.'%>'] = $value;
1391 if (!empty($tags)) {
1392 $text = str_replace($tags,array_keys($tags),$text);
1397 * Add missing openpopup javascript to HTML files.
1399 * @param string $text
1402 function filter_add_javascript($text) {
1405 if (stripos($text, '</html>') === FALSE) {
1406 return $text; // this is not a html file
1408 if (strpos($text, 'onclick="return openpopup') === FALSE) {
1409 return $text; // no popup - no need to add javascript
1412 <script type=\"text/javascript\">
1414 function openpopup(url,name,options,fullscreen) {
1415 fullurl = \"".$CFG->httpswwwroot
."\" + url;
1416 windowobj = window.open(fullurl,name,options);
1418 windowobj.moveTo(0,0);
1419 windowobj.resizeTo(screen.availWidth,screen.availHeight);
1426 if (stripos($text, '</head>') !== FALSE) {
1427 //try to add it into the head element
1428 $text = str_ireplace('</head>', $js.'</head>', $text);
1432 //last chance - try adding head element
1433 return preg_replace("/<html.*?>/is", "\\0<head>".$js.'</head>', $text);