weekly release 2.1.6+
[moodle.git] / lib / filterlib.php
blob0b77f6d354893c4180727ca835b10e3af22a5d3d
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
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.
9 //
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/>.
18 /**
19 * Library functions for managing text filter plugins.
21 * @package core
22 * @subpackage filter
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);
38 /**
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', '-%-');
46 /**
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.
53 * @package core
54 * @subpackage filter
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 {
59 /**
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();
65 /**
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();
81 /**
82 * @return filter_manager the singleton instance.
84 public static function instance() {
85 global $CFG;
86 if (is_null(self::$singletoninstance)) {
87 if (!empty($CFG->perfdebug)) {
88 self::$singletoninstance = new performance_measuring_filter_manager();
89 } else {
90 self::$singletoninstance = new self();
93 return self::$singletoninstance;
96 /**
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)) {
108 continue;
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) {
127 global $CFG;
128 $path = $CFG->dirroot .'/'. $filtername .'/filter.php';
129 if (!is_readable($path)) {
130 return null;
132 include_once($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);
144 return null;
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);
158 return $text;
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];
186 * Filter some text
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);
197 return $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);
218 $hashes = array();
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
232 * @package core
233 * @subpackage filter
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 {
239 * @return string
241 public function filter_text($text, $context, $options) {
242 return $text;
246 * @return string
248 public function filter_string($string, $context) {
249 return $string;
253 * @return string
255 public function text_filtering_hash() {
256 return '';
261 * Filter manager subclass that tacks how much work it does.
263 * @todo Document this class
265 * @package core
266 * @subpackage 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 performance_measuring_filter_manager extends filter_manager {
271 /** @var int */
272 protected $filterscreated = 0;
273 protected $textsfiltered = 0;
274 protected $stringsfiltered = 0;
277 * @param string $filtername
278 * @param object $context
279 * @param mixed $localconfig
280 * @return mixed
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
291 * @return mixed
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
301 * @return mixed
303 public function filter_string($string, $context) {
304 $this->stringsfiltered++;
305 return parent::filter_string($string, $context);
309 * @return array
311 public function get_performance_summary() {
312 return array(array(
313 'contextswithfilters' => count($this->textfilters),
314 'filterscreated' => $this->filterscreated,
315 'textsfiltered' => $this->textsfiltered,
316 'stringsfiltered' => $this->stringsfiltered,
317 ), array(
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.
330 * @package core
331 * @subpackage filter
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. */
337 protected $context;
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() {
356 return __CLASS__;
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.
373 * @package core
374 * @subpackage filter
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 {
379 /** @var string */
380 protected $filterfunction;
381 protected $courseid;
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
399 * @return mixed
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);
405 } else {
406 return $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.
416 * @package core
417 * @subpackage filter
418 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
419 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
421 class filterobject {
422 /** @var string */
423 var $phrase;
424 var $hreftagbegin;
425 var $hreftagend;
426 /** @var bool */
427 var $casesensitive;
428 var $fullmatch;
429 /** @var mixed */
430 var $replacementphrase;
431 var $work_phrase;
432 var $work_hreftagbegin;
433 var $work_hreftagend;
434 var $work_casesensitive;
435 var $work_fullmatch;
436 var $work_replacementphrase;
437 /** @var bool */
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,
453 $fullmatch = 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);
479 switch ($type) {
480 case '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.
488 case 'mod':
489 $strfiltername = get_string('filtername', $filter);
490 if (substr($strfiltername, 0, 2) == '[[') {
491 $strfiltername .= ' (' . $type . '/' . $filter . ')';
493 return $strfiltername;
495 default:
496 throw new coding_exception('Unknown filter type ' . $type);
501 * Get the names of all the filters installed in this Moodle.
503 * @global object
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() {
509 global $CFG;
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 textlib_get_instance()->asort($filternames);
523 return $filternames;
527 * Set the global activated state for a text filter.
529 * @global object
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) {
540 global $DB;
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));
558 if (empty($rec)) {
559 $insert = true;
560 $rec = new stdClass;
561 $rec->filter = $filter;
562 $rec->contextid = $syscontext->id;
563 } else {
564 $insert = false;
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());
574 } else {
575 $prevmaxsortorder = $DB->get_field_select('filter_active', 'MAX(sortorder)', 'active <> ?', array(TEXTFILTER_DISABLED));
577 if (empty($prevmaxsortorder)) {
578 $sortorder = 1;
579 } else {
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.
588 if ($insert) {
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;
605 if ($insert) {
606 $DB->insert_record('filter_active', $rec);
607 } else {
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).
645 * @global object
646 * @return array where the keys and values are both the filter name, like 'filter/tex'.
648 function filter_get_string_filters() {
649 global $CFG;
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;
671 } else {
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.
683 * @global object
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.
687 * @return void
689 function filter_set_local_state($filter, $contextid, $state) {
690 global $DB;
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));
705 return;
708 $rec = $DB->get_record('filter_active', array('filter' => $filter, 'contextid' => $contextid));
709 $insert = false;
710 if (empty($rec)) {
711 $insert = true;
712 $rec = new stdClass;
713 $rec->filter = $filter;
714 $rec->contextid = $contextid;
717 $rec->active = $state;
719 if ($insert) {
720 $DB->insert_record('filter_active', $rec);
721 } else {
722 $DB->update_record('filter_active', $rec);
727 * Set a particular local config variable for a filter in a context.
729 * @global object
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) {
736 global $DB;
737 $rec = $DB->get_record('filter_config', array('filter' => $filter, 'contextid' => $contextid, 'name' => $name));
738 $insert = false;
739 if (empty($rec)) {
740 $insert = true;
741 $rec = new stdClass;
742 $rec->filter = $filter;
743 $rec->contextid = $contextid;
744 $rec->name = $name;
747 $rec->value = $value;
749 if ($insert) {
750 $DB->insert_record('filter_config', $rec);
751 } else {
752 $DB->update_record('filter_config', $rec);
757 * Remove a particular local config variable for a filter in a context.
759 * @global object
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) {
765 global $DB;
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.
775 * @global object
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) {
781 global $DB;
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
787 * to one context.
789 * @global object
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) {
797 global $DB;
798 $context = get_context_instance(CONTEXT_SYSTEM);
799 return array(
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.
809 * @global object
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;
820 $contextids = str_replace('/', ',', trim($context->path, '/'));
822 // The following SQL is tricky. It is explained on
823 // http://docs.moodle.org/dev/Filter_enable/disable_by_context
824 $sql = "SELECT active.filter, fc.name, fc.value
825 FROM (SELECT f.filter, MAX(f.sortorder) AS sortorder
826 FROM {filter_active} f
827 JOIN {context} ctx ON f.contextid = ctx.id
828 WHERE ctx.id IN ($contextids)
829 GROUP BY filter
830 HAVING MAX(f.active * " . $DB->sql_cast_2signed('ctx.depth') .
831 ") > -MIN(f.active * " . $DB->sql_cast_2signed('ctx.depth') . ")
832 ) active
833 LEFT JOIN {filter_config} fc ON fc.filter = active.filter AND fc.contextid = $context->id
834 ORDER BY active.sortorder";
835 $rs = $DB->get_recordset_sql($sql);
837 // Masssage the data into the specified format to return.
838 $filters = array();
839 foreach ($rs as $row) {
840 if (!isset($filters[$row->filter])) {
841 $filters[$row->filter] = array();
843 if (!is_null($row->name)) {
844 $filters[$row->filter][$row->name] = $row->value;
848 $rs->close();
850 return $filters;
854 * List all of the filters that are available in this context, and what the
855 * local and inherited states of that filter are.
857 * @global object
858 * @param object $context a context that is not the system context.
859 * @return array an array with filter names, for example 'filter/tex' or
860 * 'mod/glossary' as keys. and and the values are objects with fields:
861 * ->filter filter name, same as the key.
862 * ->localstate TEXTFILTER_ON/OFF/INHERIT
863 * ->inheritedstate TEXTFILTER_ON/OFF - the state that will be used if localstate is set to TEXTFILTER_INHERIT.
865 function filter_get_available_in_context($context) {
866 global $DB;
868 // The complex logic is working out the active state in the parent context,
869 // so strip the current context from the list.
870 $contextids = explode('/', trim($context->path, '/'));
871 array_pop($contextids);
872 $contextids = implode(',', $contextids);
873 if (empty($contextids)) {
874 throw new coding_exception('filter_get_available_in_context cannot be called with the system context.');
877 // The following SQL is tricky, in the same way at the SQL in filter_get_active_in_context.
878 $sql = "SELECT parent_states.filter,
879 CASE WHEN fa.active IS NULL THEN " . TEXTFILTER_INHERIT . "
880 ELSE fa.active END AS localstate,
881 parent_states.inheritedstate
882 FROM (SELECT f.filter, MAX(f.sortorder) AS sortorder,
883 CASE WHEN MAX(f.active * " . $DB->sql_cast_2signed('ctx.depth') .
884 ") > -MIN(f.active * " . $DB->sql_cast_2signed('ctx.depth') . ") THEN " . TEXTFILTER_ON . "
885 ELSE " . TEXTFILTER_OFF . " END AS inheritedstate
886 FROM {filter_active} f
887 JOIN {context} ctx ON f.contextid = ctx.id
888 WHERE ctx.id IN ($contextids)
889 GROUP BY f.filter
890 HAVING MIN(f.active) > " . TEXTFILTER_DISABLED . "
891 ) parent_states
892 LEFT JOIN {filter_active} fa ON fa.filter = parent_states.filter AND fa.contextid = $context->id
893 ORDER BY parent_states.sortorder";
894 return $DB->get_records_sql($sql);
898 * This function is for use by the filter administration page.
900 * @global object
901 * @return array 'filtername' => object with fields 'filter' (=filtername), 'active' and 'sortorder'
903 function filter_get_global_states() {
904 global $DB;
905 $context = get_context_instance(CONTEXT_SYSTEM);
906 return $DB->get_records('filter_active', array('contextid' => $context->id), 'sortorder', 'filter,active,sortorder');
910 * Delete all the data in the database relating to a filter, prior to deleting it.
912 * @global object
913 * @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
915 function filter_delete_all_for_filter($filter) {
916 global $DB;
917 if (substr($filter, 0, 7) == 'filter/') {
918 unset_all_config_for_plugin('filter_' . basename($filter));
920 $DB->delete_records('filter_active', array('filter' => $filter));
921 $DB->delete_records('filter_config', array('filter' => $filter));
925 * Delete all the data in the database relating to a context, used when contexts are deleted.
927 * @param integer $contextid The id of the context being deleted.
929 function filter_delete_all_for_context($contextid) {
930 global $DB;
931 $DB->delete_records('filter_active', array('contextid' => $contextid));
932 $DB->delete_records('filter_config', array('contextid' => $contextid));
936 * Does this filter have a global settings page in the admin tree?
937 * (The settings page for a filter must be called, for example,
938 * filtersettingfiltertex or filtersettingmodglossay.)
940 * @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
941 * @return boolean Whether there should be a 'Settings' link on the config page.
943 function filter_has_global_settings($filter) {
944 global $CFG;
945 $settingspath = $CFG->dirroot . '/' . $filter . '/filtersettings.php';
946 return is_readable($settingspath);
950 * Does this filter have local (per-context) settings?
952 * @param string $filter The filter name, for example 'filter/tex' or 'mod/glossary'.
953 * @return boolean Whether there should be a 'Settings' link on the manage filters in context page.
955 function filter_has_local_settings($filter) {
956 global $CFG;
957 $settingspath = $CFG->dirroot . '/' . $filter . '/filterlocalsettings.php';
958 return is_readable($settingspath);
962 * Certain types of context (block and user) may not have local filter settings.
963 * the function checks a context to see whether it may have local config.
965 * @param object $context a context.
966 * @return boolean whether this context may have local filter settings.
968 function filter_context_may_have_filter_settings($context) {
969 return $context->contextlevel != CONTEXT_BLOCK && $context->contextlevel != CONTEXT_USER;
973 * Process phrases intelligently found within a HTML text (such as adding links)
975 * @staticvar array $usedpharses
976 * @param string $text the text that we are filtering
977 * @param array $link_array an array of filterobjects
978 * @param array $ignoretagsopen an array of opening tags that we should ignore while filtering
979 * @param array $ignoretagsclose an array of corresponding closing tags
980 * @return string
982 function filter_phrases($text, &$link_array, $ignoretagsopen=NULL, $ignoretagsclose=NULL) {
984 global $CFG;
986 static $usedphrases;
988 $ignoretags = array(); //To store all the enclosig tags to be completely ignored
989 $tags = array(); //To store all the simple tags to be ignored
991 /// A list of open/close tags that we should not replace within
992 /// No reason why you can't put full preg expressions in here too
993 /// eg '<script(.+?)>' to match any type of script tag
994 $filterignoretagsopen = array('<head>' , '<nolink>' , '<span class="nolink">');
995 $filterignoretagsclose = array('</head>', '</nolink>', '</span>');
997 /// Invalid prefixes and suffixes for the fullmatch searches
998 /// Every "word" character, but the underscore, is a invalid suffix or prefix.
999 /// (nice to use this because it includes national characters (accents...) as word characters.
1000 $filterinvalidprefixes = '([^\W_])';
1001 $filterinvalidsuffixes = '([^\W_])';
1003 /// Add the user defined ignore tags to the default list
1004 /// Unless specified otherwise, we will not replace within <a></a> tags
1005 if ( $ignoretagsopen === NULL ) {
1006 //$ignoretagsopen = array('<a(.+?)>');
1007 $ignoretagsopen = array('<a\s[^>]+?>');
1008 $ignoretagsclose = array('</a>');
1011 if ( is_array($ignoretagsopen) ) {
1012 foreach ($ignoretagsopen as $open) $filterignoretagsopen[] = $open;
1013 foreach ($ignoretagsclose as $close) $filterignoretagsclose[] = $close;
1016 //// Double up some magic chars to avoid "accidental matches"
1017 $text = preg_replace('/([#*%])/','\1\1',$text);
1020 ////Remove everything enclosed by the ignore tags from $text
1021 filter_save_ignore_tags($text,$filterignoretagsopen,$filterignoretagsclose,$ignoretags);
1023 /// Remove tags from $text
1024 filter_save_tags($text,$tags);
1026 /// Time to cycle through each phrase to be linked
1027 $size = sizeof($link_array);
1028 for ($n=0; $n < $size; $n++) {
1029 $linkobject =& $link_array[$n];
1031 /// Set some defaults if certain properties are missing
1032 /// Properties may be missing if the filterobject class has not been used to construct the object
1033 if (empty($linkobject->phrase)) {
1034 continue;
1037 /// Avoid integers < 1000 to be linked. See bug 1446.
1038 $intcurrent = intval($linkobject->phrase);
1039 if (!empty($intcurrent) && strval($intcurrent) == $linkobject->phrase && $intcurrent < 1000) {
1040 continue;
1043 /// All this work has to be done ONLY it it hasn't been done before
1044 if (!$linkobject->work_calculated) {
1045 if (!isset($linkobject->hreftagbegin) or !isset($linkobject->hreftagend)) {
1046 $linkobject->work_hreftagbegin = '<span class="highlight"';
1047 $linkobject->work_hreftagend = '</span>';
1048 } else {
1049 $linkobject->work_hreftagbegin = $linkobject->hreftagbegin;
1050 $linkobject->work_hreftagend = $linkobject->hreftagend;
1053 /// Double up chars to protect true duplicates
1054 /// be cleared up before returning to the user.
1055 $linkobject->work_hreftagbegin = preg_replace('/([#*%])/','\1\1',$linkobject->work_hreftagbegin);
1057 if (empty($linkobject->casesensitive)) {
1058 $linkobject->work_casesensitive = false;
1059 } else {
1060 $linkobject->work_casesensitive = true;
1062 if (empty($linkobject->fullmatch)) {
1063 $linkobject->work_fullmatch = false;
1064 } else {
1065 $linkobject->work_fullmatch = true;
1068 /// Strip tags out of the phrase
1069 $linkobject->work_phrase = strip_tags($linkobject->phrase);
1071 /// Double up chars that might cause a false match -- the duplicates will
1072 /// be cleared up before returning to the user.
1073 $linkobject->work_phrase = preg_replace('/([#*%])/','\1\1',$linkobject->work_phrase);
1075 /// Set the replacement phrase properly
1076 if ($linkobject->replacementphrase) { //We have specified a replacement phrase
1077 /// Strip tags
1078 $linkobject->work_replacementphrase = strip_tags($linkobject->replacementphrase);
1079 } else { //The replacement is the original phrase as matched below
1080 $linkobject->work_replacementphrase = '$1';
1083 /// Quote any regular expression characters and the delimiter in the work phrase to be searched
1084 $linkobject->work_phrase = preg_quote($linkobject->work_phrase, '/');
1086 /// Work calculated
1087 $linkobject->work_calculated = true;
1091 /// If $CFG->filtermatchoneperpage, avoid previously (request) linked phrases
1092 if (!empty($CFG->filtermatchoneperpage)) {
1093 if (!empty($usedphrases) && in_array($linkobject->work_phrase,$usedphrases)) {
1094 continue;
1098 /// Regular expression modifiers
1099 $modifiers = ($linkobject->work_casesensitive) ? 's' : 'isu'; // works in unicode mode!
1101 /// Do we need to do a fullmatch?
1102 /// If yes then go through and remove any non full matching entries
1103 if ($linkobject->work_fullmatch) {
1104 $notfullmatches = array();
1105 $regexp = '/'.$filterinvalidprefixes.'('.$linkobject->work_phrase.')|('.$linkobject->work_phrase.')'.$filterinvalidsuffixes.'/'.$modifiers;
1107 preg_match_all($regexp,$text,$list_of_notfullmatches);
1109 if ($list_of_notfullmatches) {
1110 foreach (array_unique($list_of_notfullmatches[0]) as $key=>$value) {
1111 $notfullmatches['<*'.$key.'*>'] = $value;
1113 if (!empty($notfullmatches)) {
1114 $text = str_replace($notfullmatches,array_keys($notfullmatches),$text);
1119 /// Finally we do our highlighting
1120 if (!empty($CFG->filtermatchonepertext) || !empty($CFG->filtermatchoneperpage)) {
1121 $resulttext = preg_replace('/('.$linkobject->work_phrase.')/'.$modifiers,
1122 $linkobject->work_hreftagbegin.
1123 $linkobject->work_replacementphrase.
1124 $linkobject->work_hreftagend, $text, 1);
1125 } else {
1126 $resulttext = preg_replace('/('.$linkobject->work_phrase.')/'.$modifiers,
1127 $linkobject->work_hreftagbegin.
1128 $linkobject->work_replacementphrase.
1129 $linkobject->work_hreftagend, $text);
1133 /// If the text has changed we have to look for links again
1134 if ($resulttext != $text) {
1135 /// Set $text to $resulttext
1136 $text = $resulttext;
1137 /// Remove everything enclosed by the ignore tags from $text
1138 filter_save_ignore_tags($text,$filterignoretagsopen,$filterignoretagsclose,$ignoretags);
1139 /// Remove tags from $text
1140 filter_save_tags($text,$tags);
1141 /// If $CFG->filtermatchoneperpage, save linked phrases to request
1142 if (!empty($CFG->filtermatchoneperpage)) {
1143 $usedphrases[] = $linkobject->work_phrase;
1148 /// Replace the not full matches before cycling to next link object
1149 if (!empty($notfullmatches)) {
1150 $text = str_replace(array_keys($notfullmatches),$notfullmatches,$text);
1151 unset($notfullmatches);
1155 /// Rebuild the text with all the excluded areas
1157 if (!empty($tags)) {
1158 $text = str_replace(array_keys($tags), $tags, $text);
1161 if (!empty($ignoretags)) {
1162 $ignoretags = array_reverse($ignoretags); /// Reversed so "progressive" str_replace() will solve some nesting problems.
1163 $text = str_replace(array_keys($ignoretags),$ignoretags,$text);
1166 //// Remove the protective doubleups
1167 $text = preg_replace('/([#*%])(\1)/','\1',$text);
1169 /// Add missing javascript for popus
1170 $text = filter_add_javascript($text);
1173 return $text;
1177 * @todo Document this function
1178 * @param array $linkarray
1179 * @return array
1181 function filter_remove_duplicates($linkarray) {
1183 $concepts = array(); // keep a record of concepts as we cycle through
1184 $lconcepts = array(); // a lower case version for case insensitive
1186 $cleanlinks = array();
1188 foreach ($linkarray as $key=>$filterobject) {
1189 if ($filterobject->casesensitive) {
1190 $exists = in_array($filterobject->phrase, $concepts);
1191 } else {
1192 $exists = in_array(moodle_strtolower($filterobject->phrase), $lconcepts);
1195 if (!$exists) {
1196 $cleanlinks[] = $filterobject;
1197 $concepts[] = $filterobject->phrase;
1198 $lconcepts[] = moodle_strtolower($filterobject->phrase);
1202 return $cleanlinks;
1206 * Extract open/lose tags and their contents to avoid being processed by filters.
1207 * Useful to extract pieces of code like <a>...</a> tags. It returns the text
1208 * converted with some <#xTEXTFILTER_EXCL_SEPARATORx#> codes replacing the extracted text. Such extracted
1209 * texts are returned in the ignoretags array (as values), with codes as keys.
1211 * @param string $text the text that we are filtering (in/out)
1212 * @param array $filterignoretagsopen an array of open tags to start searching
1213 * @param array $filterignoretagsclose an array of close tags to end searching
1214 * @param array $ignoretags an array of saved strings useful to rebuild the original text (in/out)
1216 function filter_save_ignore_tags(&$text, $filterignoretagsopen, $filterignoretagsclose, &$ignoretags) {
1218 /// Remove everything enclosed by the ignore tags from $text
1219 foreach ($filterignoretagsopen as $ikey=>$opentag) {
1220 $closetag = $filterignoretagsclose[$ikey];
1221 /// form regular expression
1222 $opentag = str_replace('/','\/',$opentag); // delimit forward slashes
1223 $closetag = str_replace('/','\/',$closetag); // delimit forward slashes
1224 $pregexp = '/'.$opentag.'(.*?)'.$closetag.'/is';
1226 preg_match_all($pregexp, $text, $list_of_ignores);
1227 foreach (array_unique($list_of_ignores[0]) as $key=>$value) {
1228 $prefix = (string)(count($ignoretags) + 1);
1229 $ignoretags['<#'.$prefix.TEXTFILTER_EXCL_SEPARATOR.$key.'#>'] = $value;
1231 if (!empty($ignoretags)) {
1232 $text = str_replace($ignoretags,array_keys($ignoretags),$text);
1238 * Extract tags (any text enclosed by < and > to avoid being processed by filters.
1239 * It returns the text converted with some <%xTEXTFILTER_EXCL_SEPARATORx%> codes replacing the extracted text. Such extracted
1240 * texts are returned in the tags array (as values), with codes as keys.
1242 * @param string $text the text that we are filtering (in/out)
1243 * @param array $tags an array of saved strings useful to rebuild the original text (in/out)
1245 function filter_save_tags(&$text, &$tags) {
1247 preg_match_all('/<([^#%*].*?)>/is',$text,$list_of_newtags);
1248 foreach (array_unique($list_of_newtags[0]) as $ntkey=>$value) {
1249 $prefix = (string)(count($tags) + 1);
1250 $tags['<%'.$prefix.TEXTFILTER_EXCL_SEPARATOR.$ntkey.'%>'] = $value;
1252 if (!empty($tags)) {
1253 $text = str_replace($tags,array_keys($tags),$text);
1258 * Add missing openpopup javascript to HTML files.
1260 * @param string $text
1261 * @return string
1263 function filter_add_javascript($text) {
1264 global $CFG;
1266 if (stripos($text, '</html>') === FALSE) {
1267 return $text; // this is not a html file
1269 if (strpos($text, 'onclick="return openpopup') === FALSE) {
1270 return $text; // no popup - no need to add javascript
1272 $js ="
1273 <script type=\"text/javascript\">
1274 <!--
1275 function openpopup(url,name,options,fullscreen) {
1276 fullurl = \"".$CFG->httpswwwroot."\" + url;
1277 windowobj = window.open(fullurl,name,options);
1278 if (fullscreen) {
1279 windowobj.moveTo(0,0);
1280 windowobj.resizeTo(screen.availWidth,screen.availHeight);
1282 windowobj.focus();
1283 return false;
1285 // -->
1286 </script>";
1287 if (stripos($text, '</head>') !== FALSE) {
1288 //try to add it into the head element
1289 $text = str_ireplace('</head>', $js.'</head>', $text);
1290 return $text;
1293 //last chance - try adding head element
1294 return preg_replace("/<html.*?>/is", "\\0<head>".$js.'</head>', $text);