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 (get_plugin_list('filter') as $filter => $fulldir) {
517 if (is_readable("$fulldir/filter.php")) {
518 $filternames[$filter] = filter_get_name($filter);
521 collatorlib
::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 $filter->active
= $state;
575 $DB->update_record('filter_active', $filter);
576 if ($filter->active
== TEXTFILTER_DISABLED
) {
577 unset($on[$filtername]);
578 $off = array($filter->filter
=> $filter) +
$off;
582 } else if (isset($off[$filtername])) {
583 $filter = $off[$filtername];
584 if ($filter->active
!= $state) {
585 $filter->active
= $state;
586 $DB->update_record('filter_active', $filter);
587 if ($filter->active
!= TEXTFILTER_DISABLED
) {
588 unset($off[$filtername]);
589 $on[$filter->filter
] = $filter;
594 $filter = new stdClass();
595 $filter->filter
= $filtername;
596 $filter->contextid
= $syscontext->id
;
597 $filter->active
= $state;
598 $filter->sortorder
= 99999;
599 $filter->id
= $DB->insert_record('filter_active', $filter);
601 $filters[$filter->id
] = $filter;
602 if ($state == TEXTFILTER_DISABLED
) {
603 $off[$filter->filter
] = $filter;
605 $on[$filter->filter
] = $filter;
610 if ($move != 0 and isset($on[$filter->filter
])) {
612 foreach ($on as $f) {
613 $f->newsortorder
= $i;
617 $filter->newsortorder
= $filter->newsortorder +
$move;
619 foreach ($on as $f) {
620 if ($f->id
== $filter->id
) {
623 if ($f->newsortorder
== $filter->newsortorder
) {
625 $f->newsortorder
= $f->newsortorder
- 1;
627 $f->newsortorder
= $f->newsortorder +
1;
632 collatorlib
::asort_objects_by_property($on, 'newsortorder', collatorlib
::SORT_NUMERIC
);
635 // Inactive are sorted by filter name.
636 collatorlib
::asort_objects_by_property($off, 'filter', collatorlib
::SORT_NATURAL
);
638 // Update records if necessary.
640 foreach ($on as $f) {
641 if ($f->sortorder
!= $i) {
642 $DB->set_field('filter_active', 'sortorder', $i, array('id'=>$f->id
));
646 foreach ($off as $f) {
647 if ($f->sortorder
!= $i) {
648 $DB->set_field('filter_active', 'sortorder', $i, array('id'=>$f->id
));
653 $transaction->allow_commit();
657 * @param string $filtername The filter name, for example 'tex'.
658 * @return boolean is this filter allowed to be used on this site. That is, the
659 * admin has set the global 'active' setting to On, or Off, but available.
661 function filter_is_enabled($filtername) {
662 if (strpos($filtername, 'filter/') === 0) {
663 //debugging("Old filtername '$filtername' parameter used in filter_is_enabled()", DEBUG_DEVELOPER);
664 $filtername = substr($filtername, 7);
665 } else if (strpos($filtername, '/') !== false) {
666 throw new coding_exception("Invalid filter name '$filtername' used in filter_is_enabled()");
668 return array_key_exists($filtername, filter_get_globally_enabled());
672 * Return a list of all the filters that may be in use somewhere.
674 * @staticvar array $enabledfilters
675 * @return array where the keys and values are both the filter name, like 'tex'.
677 function filter_get_globally_enabled() {
678 static $enabledfilters = null;
679 if (is_null($enabledfilters)) {
680 $filters = filter_get_global_states();
681 $enabledfilters = array();
682 foreach ($filters as $filter => $filerinfo) {
683 if ($filerinfo->active
!= TEXTFILTER_DISABLED
) {
684 $enabledfilters[$filter] = $filter;
688 return $enabledfilters;
692 * Return the names of the filters that should also be applied to strings
693 * (when they are enabled).
695 * @return array where the keys and values are both the filter name, like 'tex'.
697 function filter_get_string_filters() {
699 $stringfilters = array();
700 if (!empty($CFG->filterall
) && !empty($CFG->stringfilters
)) {
701 $stringfilters = explode(',', $CFG->stringfilters
);
702 $stringfilters = array_combine($stringfilters, $stringfilters);
704 return $stringfilters;
708 * Sets whether a particular active filter should be applied to all strings by
709 * format_string, or just used by format_text.
711 * @param string $filter The filter name, for example 'tex'.
712 * @param boolean $applytostrings if true, this filter will apply to format_string
713 * and format_text, when it is enabled.
715 function filter_set_applies_to_strings($filter, $applytostrings) {
716 $stringfilters = filter_get_string_filters();
717 $numstringfilters = count($stringfilters);
718 if ($applytostrings) {
719 $stringfilters[$filter] = $filter;
721 unset($stringfilters[$filter]);
723 if (count($stringfilters) != $numstringfilters) {
724 set_config('stringfilters', implode(',', $stringfilters));
725 set_config('filterall', !empty($stringfilters));
730 * Set the local activated state for a text filter.
732 * @param string $filter The filter name, for example 'tex'.
733 * @param integer $contextid The id of the context to get the local config for.
734 * @param integer $state One of the values TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_INHERIT.
737 function filter_set_local_state($filter, $contextid, $state) {
740 // Check requested state is valid.
741 if (!in_array($state, array(TEXTFILTER_ON
, TEXTFILTER_OFF
, TEXTFILTER_INHERIT
))) {
742 throw new coding_exception("Illegal option '$state' passed to filter_set_local_state. " .
743 "Must be one of TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_INHERIT.");
746 if ($contextid == context_system
::instance()->id
) {
747 throw new coding_exception('You cannot use filter_set_local_state ' .
748 'with $contextid equal to the system context id.');
751 if ($state == TEXTFILTER_INHERIT
) {
752 $DB->delete_records('filter_active', array('filter' => $filter, 'contextid' => $contextid));
756 $rec = $DB->get_record('filter_active', array('filter' => $filter, 'contextid' => $contextid));
761 $rec->filter
= $filter;
762 $rec->contextid
= $contextid;
765 $rec->active
= $state;
768 $DB->insert_record('filter_active', $rec);
770 $DB->update_record('filter_active', $rec);
775 * Set a particular local config variable for a filter in a context.
777 * @param string $filter The filter name, for example 'tex'.
778 * @param integer $contextid The id of the context to get the local config for.
779 * @param string $name the setting name.
780 * @param string $value the corresponding value.
782 function filter_set_local_config($filter, $contextid, $name, $value) {
784 $rec = $DB->get_record('filter_config', array('filter' => $filter, 'contextid' => $contextid, 'name' => $name));
789 $rec->filter
= $filter;
790 $rec->contextid
= $contextid;
794 $rec->value
= $value;
797 $DB->insert_record('filter_config', $rec);
799 $DB->update_record('filter_config', $rec);
804 * Remove a particular local config variable for a filter in a context.
806 * @param string $filter The filter name, for example 'tex'.
807 * @param integer $contextid The id of the context to get the local config for.
808 * @param string $name the setting name.
810 function filter_unset_local_config($filter, $contextid, $name) {
812 $DB->delete_records('filter_config', array('filter' => $filter, 'contextid' => $contextid, 'name' => $name));
816 * Get local config variables for a filter in a context. Normally (when your
817 * filter is running) you don't need to call this, becuase the config is fetched
818 * for you automatically. You only need this, for example, when you are getting
819 * the config so you can show the user an editing from.
821 * @param string $filter The filter name, for example 'tex'.
822 * @param integer $contextid The ID of the context to get the local config for.
823 * @return array of name => value pairs.
825 function filter_get_local_config($filter, $contextid) {
827 return $DB->get_records_menu('filter_config', array('filter' => $filter, 'contextid' => $contextid), '', 'name,value');
831 * This function is for use by backup. Gets all the filter information specific
834 * @param int $contextid
835 * @return array Array with two elements. The first element is an array of objects with
836 * fields filter and active. These come from the filter_active table. The
837 * second element is an array of objects with fields filter, name and value
838 * from the filter_config table.
840 function filter_get_all_local_settings($contextid) {
843 $DB->get_records('filter_active', array('contextid' => $contextid), 'filter', 'filter,active'),
844 $DB->get_records('filter_config', array('contextid' => $contextid), 'filter,name', 'filter,name,value'),
849 * Get the list of active filters, in the order that they should be used
850 * for a particular context, along with any local configuration variables.
852 * @param context $context a context
853 * @return array an array where the keys are the filter names, for example
854 * 'tex' and the values are any local
855 * configuration for that filter, as an array of name => value pairs
856 * from the filter_config table. In a lot of cases, this will be an
857 * empty array. So, an example return value for this function might be
858 * array(tex' => array())
860 function filter_get_active_in_context($context) {
861 global $DB, $FILTERLIB_PRIVATE;
863 if (!isset($FILTERLIB_PRIVATE)) {
864 $FILTERLIB_PRIVATE = new stdClass();
867 // Use cache (this is a within-request cache only) if available. See
868 // function filter_preload_activities.
869 if (isset($FILTERLIB_PRIVATE->active
) &&
870 array_key_exists($context->id
, $FILTERLIB_PRIVATE->active
)) {
871 return $FILTERLIB_PRIVATE->active
[$context->id
];
874 $contextids = str_replace('/', ',', trim($context->path
, '/'));
876 // The following SQL is tricky. It is explained on
877 // http://docs.moodle.org/dev/Filter_enable/disable_by_context
878 $sql = "SELECT active.filter, fc.name, fc.value
879 FROM (SELECT f.filter, MAX(f.sortorder) AS sortorder
880 FROM {filter_active} f
881 JOIN {context} ctx ON f.contextid = ctx.id
882 WHERE ctx.id IN ($contextids)
884 HAVING MAX(f.active * ctx.depth) > -MIN(f.active * ctx.depth)
886 LEFT JOIN {filter_config} fc ON fc.filter = active.filter AND fc.contextid = $context->id
887 ORDER BY active.sortorder";
888 $rs = $DB->get_recordset_sql($sql);
890 // Massage the data into the specified format to return.
892 foreach ($rs as $row) {
893 if (!isset($filters[$row->filter
])) {
894 $filters[$row->filter
] = array();
896 if (!is_null($row->name
)) {
897 $filters[$row->filter
][$row->name
] = $row->value
;
907 * Preloads the list of active filters for all activities (modules) on the course
908 * using two database queries.
910 * @param course_modinfo $modinfo Course object from get_fast_modinfo
912 function filter_preload_activities(course_modinfo
$modinfo) {
913 global $DB, $FILTERLIB_PRIVATE;
915 if (!isset($FILTERLIB_PRIVATE)) {
916 $FILTERLIB_PRIVATE = new stdClass();
919 // Don't repeat preload
920 if (!isset($FILTERLIB_PRIVATE->preloaded
)) {
921 $FILTERLIB_PRIVATE->preloaded
= array();
923 if (!empty($FILTERLIB_PRIVATE->preloaded
[$modinfo->get_course_id()])) {
926 $FILTERLIB_PRIVATE->preloaded
[$modinfo->get_course_id()] = true;
928 // Get contexts for all CMs
929 $cmcontexts = array();
930 $cmcontextids = array();
931 foreach ($modinfo->get_cms() as $cm) {
932 $modulecontext = context_module
::instance($cm->id
);
933 $cmcontextids[] = $modulecontext->id
;
934 $cmcontexts[] = $modulecontext;
937 // Get course context and all other parents...
938 $coursecontext = context_course
::instance($modinfo->get_course_id());
939 $parentcontextids = explode('/', substr($coursecontext->path
, 1));
940 $allcontextids = array_merge($cmcontextids, $parentcontextids);
942 // Get all filter_active rows relating to all these contexts
943 list ($sql, $params) = $DB->get_in_or_equal($allcontextids);
944 $filteractives = $DB->get_records_select('filter_active', "contextid $sql", $params);
946 // Get all filter_config only for the cm contexts
947 list ($sql, $params) = $DB->get_in_or_equal($cmcontextids);
948 $filterconfigs = $DB->get_records_select('filter_config', "contextid $sql", $params);
950 // Note: I was a bit surprised that filter_config only works for the
951 // most specific context (i.e. it does not need to be checked for course
952 // context if we only care about CMs) however basede on code in
953 // filter_get_active_in_context, this does seem to be correct.
955 // Build course default active list. Initially this will be an array of
956 // filter name => active score (where an active score >0 means it's active)
957 $courseactive = array();
959 // Also build list of filter_active rows below course level, by contextid
960 $remainingactives = array();
962 // Array lists filters that are banned at top level
965 // Add any active filters in parent contexts to the array
966 foreach ($filteractives as $row) {
967 $depth = array_search($row->contextid
, $parentcontextids);
968 if ($depth !== false) {
970 if (!array_key_exists($row->filter
, $courseactive)) {
971 $courseactive[$row->filter
] = 0;
973 // This maths copes with reading rows in any order. Turning on/off
974 // at site level counts 1, at next level down 4, at next level 9,
975 // then 16, etc. This means the deepest level always wins, except
976 // against the -9999 at top level.
977 $courseactive[$row->filter
] +
=
978 ($depth +
1) * ($depth +
1) * $row->active
;
980 if ($row->active
== TEXTFILTER_DISABLED
) {
981 $banned[$row->filter
] = true;
984 // Build list of other rows indexed by contextid
985 if (!array_key_exists($row->contextid
, $remainingactives)) {
986 $remainingactives[$row->contextid
] = array();
988 $remainingactives[$row->contextid
][] = $row;
992 // Chuck away the ones that aren't active.
993 foreach ($courseactive as $filter=>$score) {
995 unset($courseactive[$filter]);
997 $courseactive[$filter] = array();
1001 // Loop through the contexts to reconstruct filter_active lists for each
1002 // cm on the course.
1003 if (!isset($FILTERLIB_PRIVATE->active
)) {
1004 $FILTERLIB_PRIVATE->active
= array();
1006 foreach ($cmcontextids as $contextid) {
1008 $FILTERLIB_PRIVATE->active
[$contextid] = $courseactive;
1010 // Are there any changes to the active list?
1011 if (array_key_exists($contextid, $remainingactives)) {
1012 foreach ($remainingactives[$contextid] as $row) {
1013 if ($row->active
> 0 && empty($banned[$row->filter
])) {
1014 // If it's marked active for specific context, add entry
1015 // (doesn't matter if one exists already).
1016 $FILTERLIB_PRIVATE->active
[$contextid][$row->filter
] = array();
1018 // If it's marked inactive, remove entry (doesn't matter
1019 // if it doesn't exist).
1020 unset($FILTERLIB_PRIVATE->active
[$contextid][$row->filter
]);
1026 // Process all config rows to add config data to these entries.
1027 foreach ($filterconfigs as $row) {
1028 if (isset($FILTERLIB_PRIVATE->active
[$row->contextid
][$row->filter
])) {
1029 $FILTERLIB_PRIVATE->active
[$row->contextid
][$row->filter
][$row->name
] = $row->value
;
1035 * List all of the filters that are available in this context, and what the
1036 * local and inherited states of that filter are.
1038 * @param context $context a context that is not the system context.
1039 * @return array an array with filter names, for example 'tex'
1040 * as keys. and and the values are objects with fields:
1041 * ->filter filter name, same as the key.
1042 * ->localstate TEXTFILTER_ON/OFF/INHERIT
1043 * ->inheritedstate TEXTFILTER_ON/OFF - the state that will be used if localstate is set to TEXTFILTER_INHERIT.
1045 function filter_get_available_in_context($context) {
1048 // The complex logic is working out the active state in the parent context,
1049 // so strip the current context from the list.
1050 $contextids = explode('/', trim($context->path
, '/'));
1051 array_pop($contextids);
1052 $contextids = implode(',', $contextids);
1053 if (empty($contextids)) {
1054 throw new coding_exception('filter_get_available_in_context cannot be called with the system context.');
1057 // The following SQL is tricky, in the same way at the SQL in filter_get_active_in_context.
1058 $sql = "SELECT parent_states.filter,
1059 CASE WHEN fa.active IS NULL THEN " . TEXTFILTER_INHERIT
. "
1060 ELSE fa.active END AS localstate,
1061 parent_states.inheritedstate
1062 FROM (SELECT f.filter, MAX(f.sortorder) AS sortorder,
1063 CASE WHEN MAX(f.active * ctx.depth) > -MIN(f.active * ctx.depth) THEN " . TEXTFILTER_ON
. "
1064 ELSE " . TEXTFILTER_OFF
. " END AS inheritedstate
1065 FROM {filter_active} f
1066 JOIN {context} ctx ON f.contextid = ctx.id
1067 WHERE ctx.id IN ($contextids)
1069 HAVING MIN(f.active) > " . TEXTFILTER_DISABLED
. "
1071 LEFT JOIN {filter_active} fa ON fa.filter = parent_states.filter AND fa.contextid = $context->id
1072 ORDER BY parent_states.sortorder";
1073 return $DB->get_records_sql($sql);
1077 * This function is for use by the filter administration page.
1079 * @return array 'filtername' => object with fields 'filter' (=filtername), 'active' and 'sortorder'
1081 function filter_get_global_states() {
1083 $context = context_system
::instance();
1084 return $DB->get_records('filter_active', array('contextid' => $context->id
), 'sortorder', 'filter,active,sortorder');
1088 * Delete all the data in the database relating to a filter, prior to deleting it.
1090 * @param string $filter The filter name, for example 'tex'.
1092 function filter_delete_all_for_filter($filter) {
1095 unset_all_config_for_plugin('filter_' . $filter);
1096 $DB->delete_records('filter_active', array('filter' => $filter));
1097 $DB->delete_records('filter_config', array('filter' => $filter));
1101 * Delete all the data in the database relating to a context, used when contexts are deleted.
1103 * @param integer $contextid The id of the context being deleted.
1105 function filter_delete_all_for_context($contextid) {
1107 $DB->delete_records('filter_active', array('contextid' => $contextid));
1108 $DB->delete_records('filter_config', array('contextid' => $contextid));
1112 * Does this filter have a global settings page in the admin tree?
1113 * (The settings page for a filter must be called, for example, filtersettingfiltertex.)
1115 * @param string $filter The filter name, for example 'tex'.
1116 * @return boolean Whether there should be a 'Settings' link on the config page.
1118 function filter_has_global_settings($filter) {
1120 $settingspath = $CFG->dirroot
. '/filter/' . $filter . '/filtersettings.php';
1121 return is_readable($settingspath);
1125 * Does this filter have local (per-context) settings?
1127 * @param string $filter The filter name, for example 'tex'.
1128 * @return boolean Whether there should be a 'Settings' link on the manage filters in context page.
1130 function filter_has_local_settings($filter) {
1132 $settingspath = $CFG->dirroot
. '/filter/' . $filter . '/filterlocalsettings.php';
1133 return is_readable($settingspath);
1137 * Certain types of context (block and user) may not have local filter settings.
1138 * the function checks a context to see whether it may have local config.
1140 * @param object $context a context.
1141 * @return boolean whether this context may have local filter settings.
1143 function filter_context_may_have_filter_settings($context) {
1144 return $context->contextlevel
!= CONTEXT_BLOCK
&& $context->contextlevel
!= CONTEXT_USER
;
1148 * Process phrases intelligently found within a HTML text (such as adding links).
1150 * @staticvar array $usedpharses
1151 * @param string $text the text that we are filtering
1152 * @param array $link_array an array of filterobjects
1153 * @param array $ignoretagsopen an array of opening tags that we should ignore while filtering
1154 * @param array $ignoretagsclose an array of corresponding closing tags
1155 * @param bool $overridedefaultignore True to only use tags provided by arguments
1158 function filter_phrases($text, &$link_array, $ignoretagsopen=NULL, $ignoretagsclose=NULL,
1159 $overridedefaultignore=false) {
1163 static $usedphrases;
1165 $ignoretags = array(); // To store all the enclosig tags to be completely ignored.
1166 $tags = array(); // To store all the simple tags to be ignored.
1168 if (!$overridedefaultignore) {
1169 // A list of open/close tags that we should not replace within
1170 // Extended to include <script>, <textarea>, <select> and <a> tags
1171 // Regular expression allows tags with or without attributes
1172 $filterignoretagsopen = array('<head>' , '<nolink>' , '<span class="nolink">',
1173 '<script(\s[^>]*?)?>', '<textarea(\s[^>]*?)?>',
1174 '<select(\s[^>]*?)?>', '<a(\s[^>]*?)?>');
1175 $filterignoretagsclose = array('</head>', '</nolink>', '</span>',
1176 '</script>', '</textarea>', '</select>','</a>');
1178 // Set an empty default list.
1179 $filterignoretagsopen = array();
1180 $filterignoretagsclose = array();
1183 // Add the user defined ignore tags to the default list.
1184 if ( is_array($ignoretagsopen) ) {
1185 foreach ($ignoretagsopen as $open) {
1186 $filterignoretagsopen[] = $open;
1188 foreach ($ignoretagsclose as $close) {
1189 $filterignoretagsclose[] = $close;
1193 // Invalid prefixes and suffixes for the fullmatch searches
1194 // Every "word" character, but the underscore, is a invalid suffix or prefix.
1195 // (nice to use this because it includes national characters (accents...) as word characters.
1196 $filterinvalidprefixes = '([^\W_])';
1197 $filterinvalidsuffixes = '([^\W_])';
1199 // Double up some magic chars to avoid "accidental matches"
1200 $text = preg_replace('/([#*%])/','\1\1',$text);
1203 //Remove everything enclosed by the ignore tags from $text
1204 filter_save_ignore_tags($text,$filterignoretagsopen,$filterignoretagsclose,$ignoretags);
1206 // Remove tags from $text
1207 filter_save_tags($text,$tags);
1209 // Time to cycle through each phrase to be linked
1210 $size = sizeof($link_array);
1211 for ($n=0; $n < $size; $n++
) {
1212 $linkobject =& $link_array[$n];
1214 // Set some defaults if certain properties are missing
1215 // Properties may be missing if the filterobject class has not been used to construct the object
1216 if (empty($linkobject->phrase
)) {
1220 // Avoid integers < 1000 to be linked. See bug 1446.
1221 $intcurrent = intval($linkobject->phrase
);
1222 if (!empty($intcurrent) && strval($intcurrent) == $linkobject->phrase
&& $intcurrent < 1000) {
1226 // All this work has to be done ONLY it it hasn't been done before
1227 if (!$linkobject->work_calculated
) {
1228 if (!isset($linkobject->hreftagbegin
) or !isset($linkobject->hreftagend
)) {
1229 $linkobject->work_hreftagbegin
= '<span class="highlight"';
1230 $linkobject->work_hreftagend
= '</span>';
1232 $linkobject->work_hreftagbegin
= $linkobject->hreftagbegin
;
1233 $linkobject->work_hreftagend
= $linkobject->hreftagend
;
1236 // Double up chars to protect true duplicates
1237 // be cleared up before returning to the user.
1238 $linkobject->work_hreftagbegin
= preg_replace('/([#*%])/','\1\1',$linkobject->work_hreftagbegin
);
1240 if (empty($linkobject->casesensitive
)) {
1241 $linkobject->work_casesensitive
= false;
1243 $linkobject->work_casesensitive
= true;
1245 if (empty($linkobject->fullmatch
)) {
1246 $linkobject->work_fullmatch
= false;
1248 $linkobject->work_fullmatch
= true;
1251 // Strip tags out of the phrase
1252 $linkobject->work_phrase
= strip_tags($linkobject->phrase
);
1254 // Double up chars that might cause a false match -- the duplicates will
1255 // be cleared up before returning to the user.
1256 $linkobject->work_phrase
= preg_replace('/([#*%])/','\1\1',$linkobject->work_phrase
);
1258 // Set the replacement phrase properly
1259 if ($linkobject->replacementphrase
) { //We have specified a replacement phrase
1261 $linkobject->work_replacementphrase
= strip_tags($linkobject->replacementphrase
);
1262 } else { //The replacement is the original phrase as matched below
1263 $linkobject->work_replacementphrase
= '$1';
1266 // Quote any regular expression characters and the delimiter in the work phrase to be searched
1267 $linkobject->work_phrase
= preg_quote($linkobject->work_phrase
, '/');
1270 $linkobject->work_calculated
= true;
1274 // If $CFG->filtermatchoneperpage, avoid previously (request) linked phrases
1275 if (!empty($CFG->filtermatchoneperpage
)) {
1276 if (!empty($usedphrases) && in_array($linkobject->work_phrase
,$usedphrases)) {
1281 // Regular expression modifiers
1282 $modifiers = ($linkobject->work_casesensitive
) ?
's' : 'isu'; // works in unicode mode!
1284 // Do we need to do a fullmatch?
1285 // If yes then go through and remove any non full matching entries
1286 if ($linkobject->work_fullmatch
) {
1287 $notfullmatches = array();
1288 $regexp = '/'.$filterinvalidprefixes.'('.$linkobject->work_phrase
.')|('.$linkobject->work_phrase
.')'.$filterinvalidsuffixes.'/'.$modifiers;
1290 preg_match_all($regexp,$text,$list_of_notfullmatches);
1292 if ($list_of_notfullmatches) {
1293 foreach (array_unique($list_of_notfullmatches[0]) as $key=>$value) {
1294 $notfullmatches['<*'.$key.'*>'] = $value;
1296 if (!empty($notfullmatches)) {
1297 $text = str_replace($notfullmatches,array_keys($notfullmatches),$text);
1302 // Finally we do our highlighting
1303 if (!empty($CFG->filtermatchonepertext
) ||
!empty($CFG->filtermatchoneperpage
)) {
1304 $resulttext = preg_replace('/('.$linkobject->work_phrase
.')/'.$modifiers,
1305 $linkobject->work_hreftagbegin
.
1306 $linkobject->work_replacementphrase
.
1307 $linkobject->work_hreftagend
, $text, 1);
1309 $resulttext = preg_replace('/('.$linkobject->work_phrase
.')/'.$modifiers,
1310 $linkobject->work_hreftagbegin
.
1311 $linkobject->work_replacementphrase
.
1312 $linkobject->work_hreftagend
, $text);
1316 // If the text has changed we have to look for links again
1317 if ($resulttext != $text) {
1318 // Set $text to $resulttext
1319 $text = $resulttext;
1320 // Remove everything enclosed by the ignore tags from $text
1321 filter_save_ignore_tags($text,$filterignoretagsopen,$filterignoretagsclose,$ignoretags);
1322 // Remove tags from $text
1323 filter_save_tags($text,$tags);
1324 // If $CFG->filtermatchoneperpage, save linked phrases to request
1325 if (!empty($CFG->filtermatchoneperpage
)) {
1326 $usedphrases[] = $linkobject->work_phrase
;
1331 // Replace the not full matches before cycling to next link object
1332 if (!empty($notfullmatches)) {
1333 $text = str_replace(array_keys($notfullmatches),$notfullmatches,$text);
1334 unset($notfullmatches);
1338 // Rebuild the text with all the excluded areas
1340 if (!empty($tags)) {
1341 $text = str_replace(array_keys($tags), $tags, $text);
1344 if (!empty($ignoretags)) {
1345 $ignoretags = array_reverse($ignoretags); // Reversed so "progressive" str_replace() will solve some nesting problems.
1346 $text = str_replace(array_keys($ignoretags),$ignoretags,$text);
1349 // Remove the protective doubleups
1350 $text = preg_replace('/([#*%])(\1)/','\1',$text);
1352 // Add missing javascript for popus
1353 $text = filter_add_javascript($text);
1360 * @todo Document this function
1361 * @param array $linkarray
1364 function filter_remove_duplicates($linkarray) {
1366 $concepts = array(); // keep a record of concepts as we cycle through
1367 $lconcepts = array(); // a lower case version for case insensitive
1369 $cleanlinks = array();
1371 foreach ($linkarray as $key=>$filterobject) {
1372 if ($filterobject->casesensitive
) {
1373 $exists = in_array($filterobject->phrase
, $concepts);
1375 $exists = in_array(textlib
::strtolower($filterobject->phrase
), $lconcepts);
1379 $cleanlinks[] = $filterobject;
1380 $concepts[] = $filterobject->phrase
;
1381 $lconcepts[] = textlib
::strtolower($filterobject->phrase
);
1389 * Extract open/lose tags and their contents to avoid being processed by filters.
1390 * Useful to extract pieces of code like <a>...</a> tags. It returns the text
1391 * converted with some <#xTEXTFILTER_EXCL_SEPARATORx#> codes replacing the extracted text. Such extracted
1392 * texts are returned in the ignoretags array (as values), with codes as keys.
1394 * @param string $text the text that we are filtering (in/out)
1395 * @param array $filterignoretagsopen an array of open tags to start searching
1396 * @param array $filterignoretagsclose an array of close tags to end searching
1397 * @param array $ignoretags an array of saved strings useful to rebuild the original text (in/out)
1399 function filter_save_ignore_tags(&$text, $filterignoretagsopen, $filterignoretagsclose, &$ignoretags) {
1401 // Remove everything enclosed by the ignore tags from $text
1402 foreach ($filterignoretagsopen as $ikey=>$opentag) {
1403 $closetag = $filterignoretagsclose[$ikey];
1404 // form regular expression
1405 $opentag = str_replace('/','\/',$opentag); // delimit forward slashes
1406 $closetag = str_replace('/','\/',$closetag); // delimit forward slashes
1407 $pregexp = '/'.$opentag.'(.*?)'.$closetag.'/is';
1409 preg_match_all($pregexp, $text, $list_of_ignores);
1410 foreach (array_unique($list_of_ignores[0]) as $key=>$value) {
1411 $prefix = (string)(count($ignoretags) +
1);
1412 $ignoretags['<#'.$prefix.TEXTFILTER_EXCL_SEPARATOR
.$key.'#>'] = $value;
1414 if (!empty($ignoretags)) {
1415 $text = str_replace($ignoretags,array_keys($ignoretags),$text);
1421 * Extract tags (any text enclosed by < and > to avoid being processed by filters.
1422 * It returns the text converted with some <%xTEXTFILTER_EXCL_SEPARATORx%> codes replacing the extracted text. Such extracted
1423 * texts are returned in the tags array (as values), with codes as keys.
1425 * @param string $text the text that we are filtering (in/out)
1426 * @param array $tags an array of saved strings useful to rebuild the original text (in/out)
1428 function filter_save_tags(&$text, &$tags) {
1430 preg_match_all('/<([^#%*].*?)>/is',$text,$list_of_newtags);
1431 foreach (array_unique($list_of_newtags[0]) as $ntkey=>$value) {
1432 $prefix = (string)(count($tags) +
1);
1433 $tags['<%'.$prefix.TEXTFILTER_EXCL_SEPARATOR
.$ntkey.'%>'] = $value;
1435 if (!empty($tags)) {
1436 $text = str_replace($tags,array_keys($tags),$text);
1441 * Add missing openpopup javascript to HTML files.
1443 * @param string $text
1446 function filter_add_javascript($text) {
1449 if (stripos($text, '</html>') === FALSE) {
1450 return $text; // This is not a html file.
1452 if (strpos($text, 'onclick="return openpopup') === FALSE) {
1453 return $text; // No popup - no need to add javascript.
1456 <script type=\"text/javascript\">
1458 function openpopup(url,name,options,fullscreen) {
1459 fullurl = \"".$CFG->httpswwwroot
."\" + url;
1460 windowobj = window.open(fullurl,name,options);
1462 windowobj.moveTo(0,0);
1463 windowobj.resizeTo(screen.availWidth,screen.availHeight);
1470 if (stripos($text, '</head>') !== FALSE) {
1471 // Try to add it into the head element.
1472 $text = str_ireplace('</head>', $js.'</head>', $text);
1476 // Last chance - try adding head element.
1477 return preg_replace("/<html.*?>/is", "\\0<head>".$js.'</head>', $text);