Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.11.x will end 14 Nov 2022 (12 months plus 6 months extension).
  • Bug fixes for security issues in 3.11.x will end 13 Nov 2023 (18 months plus 12 months extension).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.
/lib/ -> filterlib.php (source)

Differences Between: [Versions 310 and 311] [Versions 311 and 402] [Versions 311 and 403] [Versions 39 and 311]

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   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.
   8  //
   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.
  13  //
  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/>.
  16  
  17  /**
  18   * Library functions for managing text filter plugins.
  19   *
  20   * @package   core
  21   * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
  22   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23   */
  24  
  25  defined('MOODLE_INTERNAL') || die();
  26  
  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);
  35  
  36  /**
  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
  40   */
  41  define('TEXTFILTER_EXCL_SEPARATOR', chr(0x1F) . '%' . chr(0x1F));
  42  
  43  
  44  /**
  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.
  48   *
  49   * This class is a singleton.
  50   *
  51   * @copyright  1999 onwards Martin Dougiamas  {@link http://moodle.com}
  52   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  53   */
  54  class filter_manager {
  55      /**
  56       * @var moodle_text_filter[][] This list of active filters, by context, for filtering content.
  57       * An array contextid => ordered array of filter name => filter objects.
  58       */
  59      protected $textfilters = array();
  60  
  61      /**
  62       * @var moodle_text_filter[][] This list of active filters, by context, for filtering strings.
  63       * An array contextid => ordered array of filter name => filter objects.
  64       */
  65      protected $stringfilters = array();
  66  
  67      /** @var array Exploded version of $CFG->stringfilters. */
  68      protected $stringfilternames = array();
  69  
  70      /** @var filter_manager Holds the singleton instance. */
  71      protected static $singletoninstance;
  72  
  73      /**
  74       * Constructor. Protected. Use {@link instance()} instead.
  75       */
  76      protected function __construct() {
  77          $this->stringfilternames = filter_get_string_filters();
  78      }
  79  
  80      /**
  81       * Factory method. Use this to get the filter manager.
  82       *
  83       * @return filter_manager the singleton instance.
  84       */
  85      public static function instance() {
  86          global $CFG;
  87          if (is_null(self::$singletoninstance)) {
  88              if (!empty($CFG->perfdebug) and $CFG->perfdebug > 7) {
  89                  self::$singletoninstance = new performance_measuring_filter_manager();
  90              } else {
  91                  self::$singletoninstance = new self();
  92              }
  93          }
  94          return self::$singletoninstance;
  95      }
  96  
  97      /**
  98       * Resets the caches, usually to be called between unit tests
  99       */
 100      public static function reset_caches() {
 101          if (self::$singletoninstance) {
 102              self::$singletoninstance->unload_all_filters();
 103          }
 104          self::$singletoninstance = null;
 105      }
 106  
 107      /**
 108       * Unloads all filters and other cached information
 109       */
 110      protected function unload_all_filters() {
 111          $this->textfilters = array();
 112          $this->stringfilters = array();
 113          $this->stringfilternames = array();
 114      }
 115  
 116      /**
 117       * Load all the filters required by this context.
 118       *
 119       * @param context $context the context.
 120       */
 121      protected function load_filters($context) {
 122          $filters = filter_get_active_in_context($context);
 123          $this->textfilters[$context->id] = array();
 124          $this->stringfilters[$context->id] = array();
 125          foreach ($filters as $filtername => $localconfig) {
 126              $filter = $this->make_filter_object($filtername, $context, $localconfig);
 127              if (is_null($filter)) {
 128                  continue;
 129              }
 130              $this->textfilters[$context->id][$filtername] = $filter;
 131              if (in_array($filtername, $this->stringfilternames)) {
 132                  $this->stringfilters[$context->id][$filtername] = $filter;
 133              }
 134          }
 135      }
 136  
 137      /**
 138       * Factory method for creating a filter.
 139       *
 140       * @param string $filtername The filter name, for example 'tex'.
 141       * @param context $context context object.
 142       * @param array $localconfig array of local configuration variables for this filter.
 143       * @return moodle_text_filter The filter, or null, if this type of filter is
 144       *      not recognised or could not be created.
 145       */
 146      protected function make_filter_object($filtername, $context, $localconfig) {
 147          global $CFG;
 148          $path = $CFG->dirroot .'/filter/'. $filtername .'/filter.php';
 149          if (!is_readable($path)) {
 150              return null;
 151          }
 152          include_once($path);
 153  
 154          $filterclassname = 'filter_' . $filtername;
 155          if (class_exists($filterclassname)) {
 156              return new $filterclassname($context, $localconfig);
 157          }
 158  
 159          return null;
 160      }
 161  
 162      /**
 163       * Apply a list of filters to some content.
 164       * @param string $text
 165       * @param moodle_text_filter[] $filterchain array filter name => filter object.
 166       * @param array $options options passed to the filters.
 167       * @param array $skipfilters of filter names. Any filters that should not be applied to this text.
 168       * @return string $text
 169       */
 170      protected function apply_filter_chain($text, $filterchain, array $options = array(),
 171              array $skipfilters = null) {
 172          if (!isset($options['stage'])) {
 173              $filtermethod = 'filter';
 174          } else if (in_array($options['stage'], ['pre_format', 'pre_clean', 'post_clean', 'string'], true)) {
 175              $filtermethod = 'filter_stage_' . $options['stage'];
 176          } else {
 177              $filtermethod = 'filter';
 178              debugging('Invalid filter stage specified in options: ' . $options['stage'], DEBUG_DEVELOPER);
 179          }
 180          if ($text === null || $text === '') {
 181              // Nothing to filter.
 182              return '';
 183          }
 184          foreach ($filterchain as $filtername => $filter) {
 185              if ($skipfilters !== null && in_array($filtername, $skipfilters)) {
 186                  continue;
 187              }
 188              $text = $filter->$filtermethod($text, $options);
 189          }
 190          return $text;
 191      }
 192  
 193      /**
 194       * Get all the filters that apply to a given context for calls to format_text.
 195       *
 196       * @param context $context
 197       * @return moodle_text_filter[] A text filter
 198       */
 199      protected function get_text_filters($context) {
 200          if (!isset($this->textfilters[$context->id])) {
 201              $this->load_filters($context);
 202          }
 203          return $this->textfilters[$context->id];
 204      }
 205  
 206      /**
 207       * Get all the filters that apply to a given context for calls to format_string.
 208       *
 209       * @param context $context the context.
 210       * @return moodle_text_filter[] A text filter
 211       */
 212      protected function get_string_filters($context) {
 213          if (!isset($this->stringfilters[$context->id])) {
 214              $this->load_filters($context);
 215          }
 216          return $this->stringfilters[$context->id];
 217      }
 218  
 219      /**
 220       * Filter some text
 221       *
 222       * @param string $text The text to filter
 223       * @param context $context the context.
 224       * @param array $options options passed to the filters
 225       * @param array $skipfilters of filter names. Any filters that should not be applied to this text.
 226       * @return string resulting text
 227       */
 228      public function filter_text($text, $context, array $options = array(),
 229              array $skipfilters = null) {
 230          $text = $this->apply_filter_chain($text, $this->get_text_filters($context), $options, $skipfilters);
 231          if (!isset($options['stage']) || $options['stage'] === 'post_clean') {
 232              // Remove <nolink> tags for XHTML compatibility after the last filtering stage.
 233              $text = str_replace(array('<nolink>', '</nolink>'), '', $text);
 234          }
 235          return $text;
 236      }
 237  
 238      /**
 239       * Filter a piece of string
 240       *
 241       * @param string $string The text to filter
 242       * @param context $context the context.
 243       * @return string resulting string
 244       */
 245      public function filter_string($string, $context) {
 246          return $this->apply_filter_chain($string, $this->get_string_filters($context), ['stage' => 'string']);
 247      }
 248  
 249      /**
 250       * @deprecated Since Moodle 3.0 MDL-50491. This was used by the old text filtering system, but no more.
 251       */
 252      public function text_filtering_hash() {
 253          throw new coding_exception('filter_manager::text_filtering_hash() can not be used any more');
 254      }
 255  
 256      /**
 257       * Setup page with filters requirements and other prepare stuff.
 258       *
 259       * This method is used by {@see format_text()} and {@see format_string()}
 260       * in order to allow filters to setup any page requirement (js, css...)
 261       * or perform any action needed to get them prepared before filtering itself
 262       * happens by calling to each every active setup() method.
 263       *
 264       * Note it's executed for each piece of text filtered, so filter implementations
 265       * are responsible of controlling the cardinality of the executions that may
 266       * be different depending of the stuff to prepare.
 267       *
 268       * @param moodle_page $page the page we are going to add requirements to.
 269       * @param context $context the context which contents are going to be filtered.
 270       * @since Moodle 2.3
 271       */
 272      public function setup_page_for_filters($page, $context) {
 273          $filters = $this->get_text_filters($context);
 274          foreach ($filters as $filter) {
 275              $filter->setup($page, $context);
 276          }
 277      }
 278  
 279      /**
 280       * Setup the page for globally available filters.
 281       *
 282       * This helps setting up the page for filters which may be applied to
 283       * the page, even if they do not belong to the current context, or are
 284       * not yet visible because the content is lazily added (ajax). This method
 285       * always uses to the system context which determines the globally
 286       * available filters.
 287       *
 288       * This should only ever be called once per request.
 289       *
 290       * @param moodle_page $page The page.
 291       * @since Moodle 3.2
 292       */
 293      public function setup_page_for_globally_available_filters($page) {
 294          $context = context_system::instance();
 295          $filterdata = filter_get_globally_enabled_filters_with_config();
 296          foreach ($filterdata as $name => $config) {
 297              if (isset($this->textfilters[$context->id][$name])) {
 298                  $filter = $this->textfilters[$context->id][$name];
 299              } else {
 300                  $filter = $this->make_filter_object($name, $context, $config);
 301                  if (is_null($filter)) {
 302                      continue;
 303                  }
 304              }
 305              $filter->setup($page, $context);
 306          }
 307      }
 308  }
 309  
 310  
 311  /**
 312   * Filter manager subclass that does nothing. Having this simplifies the logic
 313   * of format_text, etc.
 314   *
 315   * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
 316   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 317   */
 318  class null_filter_manager {
 319      /**
 320       * As for the equivalent {@link filter_manager} method.
 321       *
 322       * @param string $text The text to filter
 323       * @param context $context not used.
 324       * @param array $options not used
 325       * @param array $skipfilters not used
 326       * @return string resulting text.
 327       */
 328      public function filter_text($text, $context, array $options = array(),
 329              array $skipfilters = null) {
 330          return $text;
 331      }
 332  
 333      /**
 334       * As for the equivalent {@link filter_manager} method.
 335       *
 336       * @param string $string The text to filter
 337       * @param context $context not used.
 338       * @return string resulting string
 339       */
 340      public function filter_string($string, $context) {
 341          return $string;
 342      }
 343  
 344      /**
 345       * As for the equivalent {@link filter_manager} method.
 346       *
 347       * @deprecated Since Moodle 3.0 MDL-50491.
 348       */
 349      public function text_filtering_hash() {
 350          throw new coding_exception('filter_manager::text_filtering_hash() can not be used any more');
 351      }
 352  }
 353  
 354  
 355  /**
 356   * Filter manager subclass that tracks how much work it does.
 357   *
 358   * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
 359   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 360   */
 361  class performance_measuring_filter_manager extends filter_manager {
 362      /** @var int number of filter objects created. */
 363      protected $filterscreated = 0;
 364  
 365      /** @var int number of calls to filter_text. */
 366      protected $textsfiltered = 0;
 367  
 368      /** @var int number of calls to filter_string. */
 369      protected $stringsfiltered = 0;
 370  
 371      protected function unload_all_filters() {
 372          parent::unload_all_filters();
 373          $this->filterscreated = 0;
 374          $this->textsfiltered = 0;
 375          $this->stringsfiltered = 0;
 376      }
 377  
 378      protected function make_filter_object($filtername, $context, $localconfig) {
 379          $this->filterscreated++;
 380          return parent::make_filter_object($filtername, $context, $localconfig);
 381      }
 382  
 383      public function filter_text($text, $context, array $options = array(),
 384              array $skipfilters = null) {
 385          if (!isset($options['stage']) || $options['stage'] === 'post_clean') {
 386              $this->textsfiltered++;
 387          }
 388          return parent::filter_text($text, $context, $options, $skipfilters);
 389      }
 390  
 391      public function filter_string($string, $context) {
 392          $this->stringsfiltered++;
 393          return parent::filter_string($string, $context);
 394      }
 395  
 396      /**
 397       * Return performance information, in the form required by {@link get_performance_info()}.
 398       * @return array the performance info.
 399       */
 400      public function get_performance_summary() {
 401          return array(array(
 402              'contextswithfilters' => count($this->textfilters),
 403              'filterscreated' => $this->filterscreated,
 404              'textsfiltered' => $this->textsfiltered,
 405              'stringsfiltered' => $this->stringsfiltered,
 406          ), array(
 407              'contextswithfilters' => 'Contexts for which filters were loaded',
 408              'filterscreated' => 'Filters created',
 409              'textsfiltered' => 'Pieces of content filtered',
 410              'stringsfiltered' => 'Strings filtered',
 411          ));
 412      }
 413  }
 414  
 415  
 416  /**
 417   * Base class for text filters. You just need to override this class and
 418   * implement the filter method.
 419   *
 420   * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
 421   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 422   */
 423  abstract class moodle_text_filter {
 424      /** @var context The context we are in. */
 425      protected $context;
 426  
 427      /** @var array Any local configuration for this filter in this context. */
 428      protected $localconfig;
 429  
 430      /**
 431       * Set any context-specific configuration for this filter.
 432       *
 433       * @param context $context The current context.
 434       * @param array $localconfig Any context-specific configuration for this filter.
 435       */
 436      public function __construct($context, array $localconfig) {
 437          $this->context = $context;
 438          $this->localconfig = $localconfig;
 439      }
 440  
 441      /**
 442       * @deprecated Since Moodle 3.0 MDL-50491. This was used by the old text filtering system, but no more.
 443       */
 444      public function hash() {
 445          throw new coding_exception('moodle_text_filter::hash() can not be used any more');
 446      }
 447  
 448      /**
 449       * Setup page with filter requirements and other prepare stuff.
 450       *
 451       * Override this method if the filter needs to setup page
 452       * requirements or needs other stuff to be executed.
 453       *
 454       * Note this method is invoked from {@see setup_page_for_filters()}
 455       * for each piece of text being filtered, so it is responsible
 456       * for controlling its own execution cardinality.
 457       *
 458       * @param moodle_page $page the page we are going to add requirements to.
 459       * @param context $context the context which contents are going to be filtered.
 460       * @since Moodle 2.3
 461       */
 462      public function setup($page, $context) {
 463          // Override me, if needed.
 464      }
 465  
 466      /**
 467       * Override this function to actually implement the filtering.
 468       *
 469       * Filter developers must make sure that filtering done after text cleaning
 470       * does not introduce security vulnerabilities.
 471       *
 472       * @param string $text some HTML content to process.
 473       * @param array $options options passed to the filters
 474       * @return string the HTML content after the filtering has been applied.
 475       */
 476      public abstract function filter($text, array $options = array());
 477  
 478      /**
 479       * Filter text before changing format to HTML.
 480       *
 481       * @param string $text
 482       * @param array $options
 483       * @return string
 484       */
 485      public function filter_stage_pre_format(string $text, array $options): string {
 486          // NOTE: override if necessary.
 487          return $text;
 488      }
 489  
 490      /**
 491       * Filter HTML text before sanitising text.
 492       *
 493       * NOTE: this is called even if $options['noclean'] is true and text is not cleaned.
 494       *
 495       * @param string $text
 496       * @param array $options
 497       * @return string
 498       */
 499      public function filter_stage_pre_clean(string $text, array $options): string {
 500          // NOTE: override if necessary.
 501          return $text;
 502      }
 503  
 504      /**
 505       * Filter HTML text at the very end after text is sanitised.
 506       *
 507       * NOTE: this is called even if $options['noclean'] is true and text is not cleaned.
 508       *
 509       * @param string $text
 510       * @param array $options
 511       * @return string
 512       */
 513      public function filter_stage_post_clean(string $text, array $options): string {
 514          // NOTE: override if necessary.
 515          return $this->filter($text, $options);
 516      }
 517  
 518      /**
 519       * Filter simple text coming from format_string().
 520       *
 521       * Note that unless $CFG->formatstringstriptags is disabled
 522       * HTML tags are not expected in returned value.
 523       *
 524       * @param string $text
 525       * @param array $options
 526       * @return string
 527       */
 528      public function filter_stage_string(string $text, array $options): string {
 529          // NOTE: override if necessary.
 530          return $this->filter($text, $options);
 531      }
 532  }
 533  
 534  
 535  /**
 536   * This is just a little object to define a phrase and some instructions
 537   * for how to process it.  Filters can create an array of these to pass
 538   * to the @{link filter_phrases()} function below.
 539   *
 540   * Note that although the fields here are public, you almost certainly should
 541   * never use that. All that is supported is contructing new instances of this
 542   * class, and then passing an array of them to filter_phrases.
 543   *
 544   * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
 545   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 546   */
 547  class filterobject {
 548      /** @var string this is the phrase that should be matched. */
 549      public $phrase;
 550  
 551      /** @var bool whether to match complete words. If true, 'T' won't be matched in 'Tim'. */
 552      public $fullmatch;
 553  
 554      /** @var bool whether the match needs to be case sensitive. */
 555      public $casesensitive;
 556  
 557      /** @var string HTML to insert before any match. */
 558      public $hreftagbegin;
 559      /** @var string HTML to insert after any match. */
 560      public $hreftagend;
 561  
 562      /** @var null|string replacement text to go inside begin and end. If not set,
 563       * the body of the replacement will be the original phrase.
 564       */
 565      public $replacementphrase;
 566  
 567      /** @var null|string once initialised, holds the regexp for matching this phrase. */
 568      public $workregexp = null;
 569  
 570      /** @var null|string once initialised, holds the mangled HTML to replace the regexp with. */
 571      public $workreplacementphrase = null;
 572  
 573      /**
 574       * Constructor.
 575       *
 576       * @param string $phrase this is the phrase that should be matched.
 577       * @param string $hreftagbegin HTML to insert before any match. Default '<span class="highlight">'.
 578       * @param string $hreftagend HTML to insert after any match. Default '</span>'.
 579       * @param bool $casesensitive whether the match needs to be case sensitive
 580       * @param bool $fullmatch whether to match complete words. If true, 'T' won't be matched in 'Tim'.
 581       * @param mixed $replacementphrase replacement text to go inside begin and end. If not set,
 582       * the body of the replacement will be the original phrase.
 583       * @param callback $replacementcallback if set, then this will be called just before
 584       * $hreftagbegin, $hreftagend and $replacementphrase are needed, so they can be computed only if required.
 585       * The call made is
 586       * list($linkobject->hreftagbegin, $linkobject->hreftagend, $linkobject->replacementphrase) =
 587       *         call_user_func_array($linkobject->replacementcallback, $linkobject->replacementcallbackdata);
 588       * so the return should be an array [$hreftagbegin, $hreftagend, $replacementphrase], the last of which may be null.
 589       * @param array $replacementcallbackdata data to be passed to $replacementcallback (optional).
 590       */
 591      public function __construct($phrase, $hreftagbegin = '<span class="highlight">',
 592              $hreftagend = '</span>',
 593              $casesensitive = false,
 594              $fullmatch = false,
 595              $replacementphrase = null,
 596              $replacementcallback = null,
 597              array $replacementcallbackdata = null) {
 598  
 599          $this->phrase                  = $phrase;
 600          $this->hreftagbegin            = $hreftagbegin;
 601          $this->hreftagend              = $hreftagend;
 602          $this->casesensitive           = !empty($casesensitive);
 603          $this->fullmatch               = !empty($fullmatch);
 604          $this->replacementphrase       = $replacementphrase;
 605          $this->replacementcallback     = $replacementcallback;
 606          $this->replacementcallbackdata = $replacementcallbackdata;
 607      }
 608  }
 609  
 610  /**
 611   * Look up the name of this filter
 612   *
 613   * @param string $filter the filter name
 614   * @return string the human-readable name for this filter.
 615   */
 616  function filter_get_name($filter) {
 617      if (strpos($filter, 'filter/') === 0) {
 618          debugging("Old '$filter'' parameter used in filter_get_name()");
 619          $filter = substr($filter, 7);
 620      } else if (strpos($filter, '/') !== false) {
 621          throw new coding_exception('Unknown filter type ' . $filter);
 622      }
 623  
 624      if (get_string_manager()->string_exists('filtername', 'filter_' . $filter)) {
 625          return get_string('filtername', 'filter_' . $filter);
 626      } else {
 627          return $filter;
 628      }
 629  }
 630  
 631  /**
 632   * Get the names of all the filters installed in this Moodle.
 633   *
 634   * @return array path => filter name from the appropriate lang file. e.g.
 635   * array('tex' => 'TeX Notation');
 636   * sorted in alphabetical order of name.
 637   */
 638  function filter_get_all_installed() {
 639      $filternames = array();
 640      foreach (core_component::get_plugin_list('filter') as $filter => $fulldir) {
 641          if (is_readable("$fulldir/filter.php")) {
 642              $filternames[$filter] = filter_get_name($filter);
 643          }
 644      }
 645      core_collator::asort($filternames);
 646      return $filternames;
 647  }
 648  
 649  /**
 650   * Set the global activated state for a text filter.
 651   *
 652   * @param string $filtername The filter name, for example 'tex'.
 653   * @param int $state One of the values TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_DISABLED.
 654   * @param int $move -1 means up, 0 means the same, 1 means down
 655   */
 656  function filter_set_global_state($filtername, $state, $move = 0) {
 657      global $DB;
 658  
 659      // Check requested state is valid.
 660      if (!in_array($state, array(TEXTFILTER_ON, TEXTFILTER_OFF, TEXTFILTER_DISABLED))) {
 661          throw new coding_exception("Illegal option '$state' passed to filter_set_global_state. " .
 662                  "Must be one of TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_DISABLED.");
 663      }
 664  
 665      if ($move > 0) {
 666          $move = 1;
 667      } else if ($move < 0) {
 668          $move = -1;
 669      }
 670  
 671      if (strpos($filtername, 'filter/') === 0) {
 672          $filtername = substr($filtername, 7);
 673      } else if (strpos($filtername, '/') !== false) {
 674          throw new coding_exception("Invalid filter name '$filtername' used in filter_set_global_state()");
 675      }
 676  
 677      $transaction = $DB->start_delegated_transaction();
 678  
 679      $syscontext = context_system::instance();
 680      $filters = $DB->get_records('filter_active', array('contextid' => $syscontext->id), 'sortorder ASC');
 681  
 682      $on = array();
 683      $off = array();
 684  
 685      foreach ($filters as $f) {
 686          if ($f->active == TEXTFILTER_DISABLED) {
 687              $off[$f->filter] = $f;
 688          } else {
 689              $on[$f->filter] = $f;
 690          }
 691      }
 692  
 693      // Update the state or add new record.
 694      if (isset($on[$filtername])) {
 695          $filter = $on[$filtername];
 696          if ($filter->active != $state) {
 697              add_to_config_log('filter_active', $filter->active, $state, $filtername);
 698  
 699              $filter->active = $state;
 700              $DB->update_record('filter_active', $filter);
 701              if ($filter->active == TEXTFILTER_DISABLED) {
 702                  unset($on[$filtername]);
 703                  $off = array($filter->filter => $filter) + $off;
 704              }
 705  
 706          }
 707  
 708      } else if (isset($off[$filtername])) {
 709          $filter = $off[$filtername];
 710          if ($filter->active != $state) {
 711              add_to_config_log('filter_active', $filter->active, $state, $filtername);
 712  
 713              $filter->active = $state;
 714              $DB->update_record('filter_active', $filter);
 715              if ($filter->active != TEXTFILTER_DISABLED) {
 716                  unset($off[$filtername]);
 717                  $on[$filter->filter] = $filter;
 718              }
 719          }
 720  
 721      } else {
 722          add_to_config_log('filter_active', '', $state, $filtername);
 723  
 724          $filter = new stdClass();
 725          $filter->filter    = $filtername;
 726          $filter->contextid = $syscontext->id;
 727          $filter->active    = $state;
 728          $filter->sortorder = 99999;
 729          $filter->id = $DB->insert_record('filter_active', $filter);
 730  
 731          $filters[$filter->id] = $filter;
 732          if ($state == TEXTFILTER_DISABLED) {
 733              $off[$filter->filter] = $filter;
 734          } else {
 735              $on[$filter->filter] = $filter;
 736          }
 737      }
 738  
 739      // Move only active.
 740      if ($move != 0 and isset($on[$filter->filter])) {
 741          // Capture the old order for logging.
 742          $oldorder = implode(', ', array_map(
 743                  function($f) {
 744                      return $f->filter;
 745                  }, $on));
 746  
 747          // Work out the new order.
 748          $i = 1;
 749          foreach ($on as $f) {
 750              $f->newsortorder = $i;
 751              $i++;
 752          }
 753  
 754          $filter->newsortorder = $filter->newsortorder + $move;
 755  
 756          foreach ($on as $f) {
 757              if ($f->id == $filter->id) {
 758                  continue;
 759              }
 760              if ($f->newsortorder == $filter->newsortorder) {
 761                  if ($move == 1) {
 762                      $f->newsortorder = $f->newsortorder - 1;
 763                  } else {
 764                      $f->newsortorder = $f->newsortorder + 1;
 765                  }
 766              }
 767          }
 768  
 769          core_collator::asort_objects_by_property($on, 'newsortorder', core_collator::SORT_NUMERIC);
 770  
 771          // Log in config_log.
 772          $neworder = implode(', ', array_map(
 773                  function($f) {
 774                      return $f->filter;
 775                  }, $on));
 776          add_to_config_log('order', $oldorder, $neworder, 'core_filter');
 777      }
 778  
 779      // Inactive are sorted by filter name.
 780      core_collator::asort_objects_by_property($off, 'filter', core_collator::SORT_NATURAL);
 781  
 782      // Update records if necessary.
 783      $i = 1;
 784      foreach ($on as $f) {
 785          if ($f->sortorder != $i) {
 786              $DB->set_field('filter_active', 'sortorder', $i, array('id' => $f->id));
 787          }
 788          $i++;
 789      }
 790      foreach ($off as $f) {
 791          if ($f->sortorder != $i) {
 792              $DB->set_field('filter_active', 'sortorder', $i, array('id' => $f->id));
 793          }
 794          $i++;
 795      }
 796  
 797      $transaction->allow_commit();
 798  }
 799  
 800  /**
 801   * Returns the active state for a filter in the given context.
 802   *
 803   * @param string $filtername The filter name, for example 'tex'.
 804   * @param integer $contextid The id of the context to get the data for.
 805   * @return int value of active field for the given filter.
 806   */
 807  function filter_get_active_state(string $filtername, $contextid = null): int {
 808      global $DB;
 809  
 810      if ($contextid === null) {
 811          $contextid = context_system::instance()->id;
 812      }
 813      if (is_object($contextid)) {
 814          $contextid = $contextid->id;
 815      }
 816  
 817      if (strpos($filtername, 'filter/') === 0) {
 818          $filtername = substr($filtername, 7);
 819      } else if (strpos($filtername, '/') !== false) {
 820          throw new coding_exception("Invalid filter name '$filtername' used in filter_is_enabled()");
 821      }
 822      if ($active = $DB->get_field('filter_active', 'active', array('filter' => $filtername, 'contextid' => $contextid))) {
 823          return $active;
 824      }
 825  
 826      return TEXTFILTER_DISABLED;
 827  }
 828  
 829  /**
 830   * @param string $filtername The filter name, for example 'tex'.
 831   * @return boolean is this filter allowed to be used on this site. That is, the
 832   *      admin has set the global 'active' setting to On, or Off, but available.
 833   */
 834  function filter_is_enabled($filtername) {
 835      if (strpos($filtername, 'filter/') === 0) {
 836          $filtername = substr($filtername, 7);
 837      } else if (strpos($filtername, '/') !== false) {
 838          throw new coding_exception("Invalid filter name '$filtername' used in filter_is_enabled()");
 839      }
 840      return array_key_exists($filtername, filter_get_globally_enabled());
 841  }
 842  
 843  /**
 844   * Return a list of all the filters that may be in use somewhere.
 845   *
 846   * @return array where the keys and values are both the filter name, like 'tex'.
 847   */
 848  function filter_get_globally_enabled() {
 849      $cache = \cache::make_from_params(\cache_store::MODE_REQUEST, 'core_filter', 'global_filters');
 850      $enabledfilters = $cache->get('enabled');
 851      if ($enabledfilters !== false) {
 852          return $enabledfilters;
 853      }
 854  
 855      $filters = filter_get_global_states();
 856      $enabledfilters = array();
 857      foreach ($filters as $filter => $filerinfo) {
 858          if ($filerinfo->active != TEXTFILTER_DISABLED) {
 859              $enabledfilters[$filter] = $filter;
 860          }
 861      }
 862  
 863      $cache->set('enabled', $enabledfilters);
 864      return $enabledfilters;
 865  }
 866  
 867  /**
 868   * Get the globally enabled filters.
 869   *
 870   * This returns the filters which could be used in any context. Essentially
 871   * the filters which are not disabled for the entire site.
 872   *
 873   * @return array Keys are filter names, and values the config.
 874   */
 875  function filter_get_globally_enabled_filters_with_config() {
 876      global $DB;
 877  
 878      $sql = "SELECT f.filter, fc.name, fc.value
 879                FROM {filter_active} f
 880           LEFT JOIN {filter_config} fc
 881                  ON fc.filter = f.filter
 882                 AND fc.contextid = f.contextid
 883               WHERE f.contextid = :contextid
 884                 AND f.active != :disabled
 885            ORDER BY f.sortorder";
 886  
 887      $rs = $DB->get_recordset_sql($sql, [
 888          'contextid' => context_system::instance()->id,
 889          'disabled' => TEXTFILTER_DISABLED
 890      ]);
 891  
 892      // Massage the data into the specified format to return.
 893      $filters = array();
 894      foreach ($rs as $row) {
 895          if (!isset($filters[$row->filter])) {
 896              $filters[$row->filter] = array();
 897          }
 898          if ($row->name !== null) {
 899              $filters[$row->filter][$row->name] = $row->value;
 900          }
 901      }
 902      $rs->close();
 903  
 904      return $filters;
 905  }
 906  
 907  /**
 908   * Return the names of the filters that should also be applied to strings
 909   * (when they are enabled).
 910   *
 911   * @return array where the keys and values are both the filter name, like 'tex'.
 912   */
 913  function filter_get_string_filters() {
 914      global $CFG;
 915      $stringfilters = array();
 916      if (!empty($CFG->filterall) && !empty($CFG->stringfilters)) {
 917          $stringfilters = explode(',', $CFG->stringfilters);
 918          $stringfilters = array_combine($stringfilters, $stringfilters);
 919      }
 920      return $stringfilters;
 921  }
 922  
 923  /**
 924   * Sets whether a particular active filter should be applied to all strings by
 925   * format_string, or just used by format_text.
 926   *
 927   * @param string $filter The filter name, for example 'tex'.
 928   * @param boolean $applytostrings if true, this filter will apply to format_string
 929   *      and format_text, when it is enabled.
 930   */
 931  function filter_set_applies_to_strings($filter, $applytostrings) {
 932      $stringfilters = filter_get_string_filters();
 933      $prevfilters = $stringfilters;
 934      $allfilters = core_component::get_plugin_list('filter');
 935  
 936      if ($applytostrings) {
 937          $stringfilters[$filter] = $filter;
 938      } else {
 939          unset($stringfilters[$filter]);
 940      }
 941  
 942      // Remove missing filters.
 943      foreach ($stringfilters as $filter) {
 944          if (!isset($allfilters[$filter])) {
 945              unset($stringfilters[$filter]);
 946          }
 947      }
 948  
 949      if ($prevfilters != $stringfilters) {
 950          set_config('stringfilters', implode(',', $stringfilters));
 951          set_config('filterall', !empty($stringfilters));
 952      }
 953  }
 954  
 955  /**
 956   * Set the local activated state for a text filter.
 957   *
 958   * @param string $filter The filter name, for example 'tex'.
 959   * @param integer $contextid The id of the context to get the local config for.
 960   * @param integer $state One of the values TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_INHERIT.
 961   * @return void
 962   */
 963  function filter_set_local_state($filter, $contextid, $state) {
 964      global $DB;
 965  
 966      // Check requested state is valid.
 967      if (!in_array($state, array(TEXTFILTER_ON, TEXTFILTER_OFF, TEXTFILTER_INHERIT))) {
 968          throw new coding_exception("Illegal option '$state' passed to filter_set_local_state. " .
 969                  "Must be one of TEXTFILTER_ON, TEXTFILTER_OFF or TEXTFILTER_INHERIT.");
 970      }
 971  
 972      if ($contextid == context_system::instance()->id) {
 973          throw new coding_exception('You cannot use filter_set_local_state ' .
 974                  'with $contextid equal to the system context id.');
 975      }
 976  
 977      if ($state == TEXTFILTER_INHERIT) {
 978          $DB->delete_records('filter_active', array('filter' => $filter, 'contextid' => $contextid));
 979          return;
 980      }
 981  
 982      $rec = $DB->get_record('filter_active', array('filter' => $filter, 'contextid' => $contextid));
 983      $insert = false;
 984      if (empty($rec)) {
 985          $insert = true;
 986          $rec = new stdClass;
 987          $rec->filter = $filter;
 988          $rec->contextid = $contextid;
 989      }
 990  
 991      $rec->active = $state;
 992  
 993      if ($insert) {
 994          $DB->insert_record('filter_active', $rec);
 995      } else {
 996          $DB->update_record('filter_active', $rec);
 997      }
 998  }
 999  
1000  /**
1001   * Set a particular local config variable for a filter in a context.
1002   *
1003   * @param string $filter The filter name, for example 'tex'.
1004   * @param integer $contextid The id of the context to get the local config for.
1005   * @param string $name the setting name.
1006   * @param string $value the corresponding value.
1007   */
1008  function filter_set_local_config($filter, $contextid, $name, $value) {
1009      global $DB;
1010      $rec = $DB->get_record('filter_config', array('filter' => $filter, 'contextid' => $contextid, 'name' => $name));
1011      $insert = false;
1012      if (empty($rec)) {
1013          $insert = true;
1014          $rec = new stdClass;
1015          $rec->filter = $filter;
1016          $rec->contextid = $contextid;
1017          $rec->name = $name;
1018      }
1019  
1020      $rec->value = $value;
1021  
1022      if ($insert) {
1023          $DB->insert_record('filter_config', $rec);
1024      } else {
1025          $DB->update_record('filter_config', $rec);
1026      }
1027  }
1028  
1029  /**
1030   * Remove a particular local config variable for a filter in a context.
1031   *
1032   * @param string $filter The filter name, for example 'tex'.
1033   * @param integer $contextid The id of the context to get the local config for.
1034   * @param string $name the setting name.
1035   */
1036  function filter_unset_local_config($filter, $contextid, $name) {
1037      global $DB;
1038      $DB->delete_records('filter_config', array('filter' => $filter, 'contextid' => $contextid, 'name' => $name));
1039  }
1040  
1041  /**
1042   * Get local config variables for a filter in a context. Normally (when your
1043   * filter is running) you don't need to call this, becuase the config is fetched
1044   * for you automatically. You only need this, for example, when you are getting
1045   * the config so you can show the user an editing from.
1046   *
1047   * @param string $filter The filter name, for example 'tex'.
1048   * @param integer $contextid The ID of the context to get the local config for.
1049   * @return array of name => value pairs.
1050   */
1051  function filter_get_local_config($filter, $contextid) {
1052      global $DB;
1053      return $DB->get_records_menu('filter_config', array('filter' => $filter, 'contextid' => $contextid), '', 'name,value');
1054  }
1055  
1056  /**
1057   * This function is for use by backup. Gets all the filter information specific
1058   * to one context.
1059   *
1060   * @param int $contextid
1061   * @return array Array with two elements. The first element is an array of objects with
1062   *      fields filter and active. These come from the filter_active table. The
1063   *      second element is an array of objects with fields filter, name and value
1064   *      from the filter_config table.
1065   */
1066  function filter_get_all_local_settings($contextid) {
1067      global $DB;
1068      return array(
1069          $DB->get_records('filter_active', array('contextid' => $contextid), 'filter', 'filter,active'),
1070          $DB->get_records('filter_config', array('contextid' => $contextid), 'filter,name', 'filter,name,value'),
1071      );
1072  }
1073  
1074  /**
1075   * Get the list of active filters, in the order that they should be used
1076   * for a particular context, along with any local configuration variables.
1077   *
1078   * @param context $context a context
1079   * @return array an array where the keys are the filter names, for example
1080   *      'tex' and the values are any local
1081   *      configuration for that filter, as an array of name => value pairs
1082   *      from the filter_config table. In a lot of cases, this will be an
1083   *      empty array. So, an example return value for this function might be
1084   *      array(tex' => array())
1085   */
1086  function filter_get_active_in_context($context) {
1087      global $DB, $FILTERLIB_PRIVATE;
1088  
1089      if (!isset($FILTERLIB_PRIVATE)) {
1090          $FILTERLIB_PRIVATE = new stdClass();
1091      }
1092  
1093      // Use cache (this is a within-request cache only) if available. See
1094      // function filter_preload_activities.
1095      if (isset($FILTERLIB_PRIVATE->active) &&
1096              array_key_exists($context->id, $FILTERLIB_PRIVATE->active)) {
1097          return $FILTERLIB_PRIVATE->active[$context->id];
1098      }
1099  
1100      $contextids = str_replace('/', ',', trim($context->path, '/'));
1101  
1102      // The following SQL is tricky. It is explained on
1103      // http://docs.moodle.org/dev/Filter_enable/disable_by_context.
1104      $sql = "SELECT active.filter, fc.name, fc.value
1105           FROM (SELECT f.filter, MAX(f.sortorder) AS sortorder
1106               FROM {filter_active} f
1107               JOIN {context} ctx ON f.contextid = ctx.id
1108               WHERE ctx.id IN ($contextids)
1109               GROUP BY filter
1110               HAVING MAX(f.active * ctx.depth) > -MIN(f.active * ctx.depth)
1111           ) active
1112           LEFT JOIN {filter_config} fc ON fc.filter = active.filter AND fc.contextid = $context->id
1113           ORDER BY active.sortorder";
1114      $rs = $DB->get_recordset_sql($sql);
1115  
1116      // Massage the data into the specified format to return.
1117      $filters = array();
1118      foreach ($rs as $row) {
1119          if (!isset($filters[$row->filter])) {
1120              $filters[$row->filter] = array();
1121          }
1122          if (!is_null($row->name)) {
1123              $filters[$row->filter][$row->name] = $row->value;
1124          }
1125      }
1126  
1127      $rs->close();
1128  
1129      return $filters;
1130  }
1131  
1132  /**
1133   * Preloads the list of active filters for all activities (modules) on the course
1134   * using two database queries.
1135   *
1136   * @param course_modinfo $modinfo Course object from get_fast_modinfo
1137   */
1138  function filter_preload_activities(course_modinfo $modinfo) {
1139      global $DB, $FILTERLIB_PRIVATE;
1140  
1141      if (!isset($FILTERLIB_PRIVATE)) {
1142          $FILTERLIB_PRIVATE = new stdClass();
1143      }
1144  
1145      // Don't repeat preload.
1146      if (!isset($FILTERLIB_PRIVATE->preloaded)) {
1147          $FILTERLIB_PRIVATE->preloaded = array();
1148      }
1149      if (!empty($FILTERLIB_PRIVATE->preloaded[$modinfo->get_course_id()])) {
1150          return;
1151      }
1152      $FILTERLIB_PRIVATE->preloaded[$modinfo->get_course_id()] = true;
1153  
1154      // Get contexts for all CMs.
1155      $cmcontexts = array();
1156      $cmcontextids = array();
1157      foreach ($modinfo->get_cms() as $cm) {
1158          $modulecontext = context_module::instance($cm->id);
1159          $cmcontextids[] = $modulecontext->id;
1160          $cmcontexts[] = $modulecontext;
1161      }
1162  
1163      // Get course context and all other parents.
1164      $coursecontext = context_course::instance($modinfo->get_course_id());
1165      $parentcontextids = explode('/', substr($coursecontext->path, 1));
1166      $allcontextids = array_merge($cmcontextids, $parentcontextids);
1167  
1168      // Get all filter_active rows relating to all these contexts.
1169      list ($sql, $params) = $DB->get_in_or_equal($allcontextids);
1170      $filteractives = $DB->get_records_select('filter_active', "contextid $sql", $params, 'sortorder');
1171  
1172      // Get all filter_config only for the cm contexts.
1173      list ($sql, $params) = $DB->get_in_or_equal($cmcontextids);
1174      $filterconfigs = $DB->get_records_select('filter_config', "contextid $sql", $params);
1175  
1176      // Note: I was a bit surprised that filter_config only works for the
1177      // most specific context (i.e. it does not need to be checked for course
1178      // context if we only care about CMs) however basede on code in
1179      // filter_get_active_in_context, this does seem to be correct.
1180  
1181      // Build course default active list. Initially this will be an array of
1182      // filter name => active score (where an active score >0 means it's active).
1183      $courseactive = array();
1184  
1185      // Also build list of filter_active rows below course level, by contextid.
1186      $remainingactives = array();
1187  
1188      // Array lists filters that are banned at top level.
1189      $banned = array();
1190  
1191      // Add any active filters in parent contexts to the array.
1192      foreach ($filteractives as $row) {
1193          $depth = array_search($row->contextid, $parentcontextids);
1194          if ($depth !== false) {
1195              // Find entry.
1196              if (!array_key_exists($row->filter, $courseactive)) {
1197                  $courseactive[$row->filter] = 0;
1198              }
1199              // This maths copes with reading rows in any order. Turning on/off
1200              // at site level counts 1, at next level down 4, at next level 9,
1201              // then 16, etc. This means the deepest level always wins, except
1202              // against the -9999 at top level.
1203              $courseactive[$row->filter] +=
1204                  ($depth + 1) * ($depth + 1) * $row->active;
1205  
1206              if ($row->active == TEXTFILTER_DISABLED) {
1207                  $banned[$row->filter] = true;
1208              }
1209          } else {
1210              // Build list of other rows indexed by contextid.
1211              if (!array_key_exists($row->contextid, $remainingactives)) {
1212                  $remainingactives[$row->contextid] = array();
1213              }
1214              $remainingactives[$row->contextid][] = $row;
1215          }
1216      }
1217  
1218      // Chuck away the ones that aren't active.
1219      foreach ($courseactive as $filter => $score) {
1220          if ($score <= 0) {
1221              unset($courseactive[$filter]);
1222          } else {
1223              $courseactive[$filter] = array();
1224          }
1225      }
1226  
1227      // Loop through the contexts to reconstruct filter_active lists for each
1228      // cm on the course.
1229      if (!isset($FILTERLIB_PRIVATE->active)) {
1230          $FILTERLIB_PRIVATE->active = array();
1231      }
1232      foreach ($cmcontextids as $contextid) {
1233          // Copy course list.
1234          $FILTERLIB_PRIVATE->active[$contextid] = $courseactive;
1235  
1236          // Are there any changes to the active list?
1237          if (array_key_exists($contextid, $remainingactives)) {
1238              foreach ($remainingactives[$contextid] as $row) {
1239                  if ($row->active > 0 && empty($banned[$row->filter])) {
1240                      // If it's marked active for specific context, add entry
1241                      // (doesn't matter if one exists already).
1242                      $FILTERLIB_PRIVATE->active[$contextid][$row->filter] = array();
1243                  } else {
1244                      // If it's marked inactive, remove entry (doesn't matter
1245                      // if it doesn't exist).
1246                      unset($FILTERLIB_PRIVATE->active[$contextid][$row->filter]);
1247                  }
1248              }
1249          }
1250      }
1251  
1252      // Process all config rows to add config data to these entries.
1253      foreach ($filterconfigs as $row) {
1254          if (isset($FILTERLIB_PRIVATE->active[$row->contextid][$row->filter])) {
1255              $FILTERLIB_PRIVATE->active[$row->contextid][$row->filter][$row->name] = $row->value;
1256          }
1257      }
1258  }
1259  
1260  /**
1261   * List all of the filters that are available in this context, and what the
1262   * local and inherited states of that filter are.
1263   *
1264   * @param context $context a context that is not the system context.
1265   * @return array an array with filter names, for example 'tex'
1266   *      as keys. and and the values are objects with fields:
1267   *      ->filter filter name, same as the key.
1268   *      ->localstate TEXTFILTER_ON/OFF/INHERIT
1269   *      ->inheritedstate TEXTFILTER_ON/OFF - the state that will be used if localstate is set to TEXTFILTER_INHERIT.
1270   */
1271  function filter_get_available_in_context($context) {
1272      global $DB;
1273  
1274      // The complex logic is working out the active state in the parent context,
1275      // so strip the current context from the list.
1276      $contextids = explode('/', trim($context->path, '/'));
1277      array_pop($contextids);
1278      $contextids = implode(',', $contextids);
1279      if (empty($contextids)) {
1280          throw new coding_exception('filter_get_available_in_context cannot be called with the system context.');
1281      }
1282  
1283      // The following SQL is tricky, in the same way at the SQL in filter_get_active_in_context.
1284      $sql = "SELECT parent_states.filter,
1285                  CASE WHEN fa.active IS NULL THEN " . TEXTFILTER_INHERIT . "
1286                  ELSE fa.active END AS localstate,
1287               parent_states.inheritedstate
1288           FROM (SELECT f.filter, MAX(f.sortorder) AS sortorder,
1289                      CASE WHEN MAX(f.active * ctx.depth) > -MIN(f.active * ctx.depth) THEN " . TEXTFILTER_ON . "
1290                      ELSE " . TEXTFILTER_OFF . " END AS inheritedstate
1291               FROM {filter_active} f
1292               JOIN {context} ctx ON f.contextid = ctx.id
1293               WHERE ctx.id IN ($contextids)
1294               GROUP BY f.filter
1295               HAVING MIN(f.active) > " . TEXTFILTER_DISABLED . "
1296           ) parent_states
1297           LEFT JOIN {filter_active} fa ON fa.filter = parent_states.filter AND fa.contextid = $context->id
1298           ORDER BY parent_states.sortorder";
1299      return $DB->get_records_sql($sql);
1300  }
1301  
1302  /**
1303   * This function is for use by the filter administration page.
1304   *
1305   * @return array 'filtername' => object with fields 'filter' (=filtername), 'active' and 'sortorder'
1306   */
1307  function filter_get_global_states() {
1308      global $DB;
1309      $context = context_system::instance();
1310      return $DB->get_records('filter_active', array('contextid' => $context->id), 'sortorder', 'filter,active,sortorder');
1311  }
1312  
1313  /**
1314   * Delete all the data in the database relating to a filter, prior to deleting it.
1315   *
1316   * @param string $filter The filter name, for example 'tex'.
1317   */
1318  function filter_delete_all_for_filter($filter) {
1319      global $DB;
1320  
1321      unset_all_config_for_plugin('filter_' . $filter);
1322      $DB->delete_records('filter_active', array('filter' => $filter));
1323      $DB->delete_records('filter_config', array('filter' => $filter));
1324  }
1325  
1326  /**
1327   * Delete all the data in the database relating to a context, used when contexts are deleted.
1328   *
1329   * @param integer $contextid The id of the context being deleted.
1330   */
1331  function filter_delete_all_for_context($contextid) {
1332      global $DB;
1333      $DB->delete_records('filter_active', array('contextid' => $contextid));
1334      $DB->delete_records('filter_config', array('contextid' => $contextid));
1335  }
1336  
1337  /**
1338   * Does this filter have a global settings page in the admin tree?
1339   * (The settings page for a filter must be called, for example, filtersettingfiltertex.)
1340   *
1341   * @param string $filter The filter name, for example 'tex'.
1342   * @return boolean Whether there should be a 'Settings' link on the config page.
1343   */
1344  function filter_has_global_settings($filter) {
1345      global $CFG;
1346      $settingspath = $CFG->dirroot . '/filter/' . $filter . '/settings.php';
1347      if (is_readable($settingspath)) {
1348          return true;
1349      }
1350      $settingspath = $CFG->dirroot . '/filter/' . $filter . '/filtersettings.php';
1351      return is_readable($settingspath);
1352  }
1353  
1354  /**
1355   * Does this filter have local (per-context) settings?
1356   *
1357   * @param string $filter The filter name, for example 'tex'.
1358   * @return boolean Whether there should be a 'Settings' link on the manage filters in context page.
1359   */
1360  function filter_has_local_settings($filter) {
1361      global $CFG;
1362      $settingspath = $CFG->dirroot . '/filter/' . $filter . '/filterlocalsettings.php';
1363      return is_readable($settingspath);
1364  }
1365  
1366  /**
1367   * Certain types of context (block and user) may not have local filter settings.
1368   * the function checks a context to see whether it may have local config.
1369   *
1370   * @param object $context a context.
1371   * @return boolean whether this context may have local filter settings.
1372   */
1373  function filter_context_may_have_filter_settings($context) {
1374      return $context->contextlevel != CONTEXT_BLOCK && $context->contextlevel != CONTEXT_USER;
1375  }
1376  
1377  /**
1378   * Process phrases intelligently found within a HTML text (such as adding links).
1379   *
1380   * @param string $text            the text that we are filtering
1381   * @param filterobject[] $linkarray an array of filterobjects
1382   * @param array $ignoretagsopen   an array of opening tags that we should ignore while filtering
1383   * @param array $ignoretagsclose  an array of corresponding closing tags
1384   * @param bool $overridedefaultignore True to only use tags provided by arguments
1385   * @param bool $linkarrayalreadyprepared True to say that filter_prepare_phrases_for_filtering
1386   *      has already been called for $linkarray. Default false.
1387   * @return string
1388   */
1389  function filter_phrases($text, $linkarray, $ignoretagsopen = null, $ignoretagsclose = null,
1390          $overridedefaultignore = false, $linkarrayalreadyprepared = false) {
1391  
1392      global $CFG;
1393  
1394      // Used if $CFG->filtermatchoneperpage is on. Array with keys being the workregexp
1395      // for things that have already been matched on this page.
1396      static $usedphrases = [];
1397  
1398      $ignoretags = array();  // To store all the enclosing tags to be completely ignored.
1399      $tags = array();        // To store all the simple tags to be ignored.
1400  
1401      if (!$linkarrayalreadyprepared) {
1402          $linkarray = filter_prepare_phrases_for_filtering($linkarray);
1403      }
1404  
1405      if (!$overridedefaultignore) {
1406          // A list of open/close tags that we should not replace within.
1407          // Extended to include <script>, <textarea>, <select> and <a> tags.
1408          // Regular expression allows tags with or without attributes.
1409          $filterignoretagsopen  = array('<head>', '<nolink>', '<span(\s[^>]*?)?class="nolink"(\s[^>]*?)?>',
1410                  '<script(\s[^>]*?)?>', '<textarea(\s[^>]*?)?>',
1411                  '<select(\s[^>]*?)?>', '<a(\s[^>]*?)?>');
1412          $filterignoretagsclose = array('</head>', '</nolink>', '</span>',
1413                   '</script>', '</textarea>', '</select>', '</a>');
1414      } else {
1415          // Set an empty default list.
1416          $filterignoretagsopen = array();
1417          $filterignoretagsclose = array();
1418      }
1419  
1420      // Add the user defined ignore tags to the default list.
1421      if ( is_array($ignoretagsopen) ) {
1422          foreach ($ignoretagsopen as $open) {
1423              $filterignoretagsopen[] = $open;
1424          }
1425          foreach ($ignoretagsclose as $close) {
1426              $filterignoretagsclose[] = $close;
1427          }
1428      }
1429  
1430      // Double up some magic chars to avoid "accidental matches".
1431      $text = preg_replace('/([#*%])/', '\1\1', $text);
1432  
1433      // Remove everything enclosed by the ignore tags from $text.
1434      filter_save_ignore_tags($text, $filterignoretagsopen, $filterignoretagsclose, $ignoretags);
1435  
1436      // Remove tags from $text.
1437      filter_save_tags($text, $tags);
1438  
1439      // Prepare the limit for preg_match calls.
1440      if (!empty($CFG->filtermatchonepertext) || !empty($CFG->filtermatchoneperpage)) {
1441          $pregreplacelimit = 1;
1442      } else {
1443          $pregreplacelimit = -1; // No limit.
1444      }
1445  
1446      // Time to cycle through each phrase to be linked.
1447      foreach ($linkarray as $key => $linkobject) {
1448          if ($linkobject->workregexp === null) {
1449              // This is the case if, when preparing the phrases for filtering,
1450              // we decided that this was not a suitable phrase to match.
1451              continue;
1452          }
1453  
1454          // If $CFG->filtermatchoneperpage, avoid previously matched linked phrases.
1455          if (!empty($CFG->filtermatchoneperpage) && isset($usedphrases[$linkobject->workregexp])) {
1456              continue;
1457          }
1458  
1459          // Do our highlighting.
1460          $resulttext = preg_replace_callback($linkobject->workregexp,
1461                  function ($matches) use ($linkobject) {
1462                      if ($linkobject->workreplacementphrase === null) {
1463                          filter_prepare_phrase_for_replacement($linkobject);
1464                      }
1465  
1466                      return str_replace('$1', $matches[1], $linkobject->workreplacementphrase);
1467                  }, $text, $pregreplacelimit);
1468  
1469          // If the text has changed we have to look for links again.
1470          if ($resulttext != $text) {
1471              $text = $resulttext;
1472              // Remove everything enclosed by the ignore tags from $text.
1473              filter_save_ignore_tags($text, $filterignoretagsopen, $filterignoretagsclose, $ignoretags);
1474              // Remove tags from $text.
1475              filter_save_tags($text, $tags);
1476              // If $CFG->filtermatchoneperpage, save linked phrases to request.
1477              if (!empty($CFG->filtermatchoneperpage)) {
1478                  $usedphrases[$linkobject->workregexp] = 1;
1479              }
1480          }
1481      }
1482  
1483      // Rebuild the text with all the excluded areas.
1484      if (!empty($tags)) {
1485          $text = str_replace(array_keys($tags), $tags, $text);
1486      }
1487  
1488      if (!empty($ignoretags)) {
1489          $ignoretags = array_reverse($ignoretags);     // Reversed so "progressive" str_replace() will solve some nesting problems.
1490          $text = str_replace(array_keys($ignoretags), $ignoretags, $text);
1491      }
1492  
1493      // Remove the protective doubleups.
1494      $text = preg_replace('/([#*%])(\1)/', '\1', $text);
1495  
1496      // Add missing javascript for popus.
1497      $text = filter_add_javascript($text);
1498  
1499      return $text;
1500  }
1501  
1502  /**
1503   * Prepare a list of link for processing with {@link filter_phrases()}.
1504   *
1505   * @param filterobject[] $linkarray the links that will be passed to filter_phrases().
1506   * @return filterobject[] the updated list of links with necessary pre-processing done.
1507   */
1508  function filter_prepare_phrases_for_filtering(array $linkarray) {
1509      // Time to cycle through each phrase to be linked.
1510      foreach ($linkarray as $linkobject) {
1511  
1512          // Set some defaults if certain properties are missing.
1513          // Properties may be missing if the filterobject class has not been used to construct the object.
1514          if (empty($linkobject->phrase)) {
1515              continue;
1516          }
1517  
1518          // Avoid integers < 1000 to be linked. See bug 1446.
1519          $intcurrent = intval($linkobject->phrase);
1520          if (!empty($intcurrent) && strval($intcurrent) == $linkobject->phrase && $intcurrent < 1000) {
1521              continue;
1522          }
1523  
1524          // Strip tags out of the phrase.
1525          $linkobject->workregexp = strip_tags($linkobject->phrase);
1526  
1527          if (!$linkobject->casesensitive) {
1528              $linkobject->workregexp = core_text::strtolower($linkobject->workregexp);
1529          }
1530  
1531          // Double up chars that might cause a false match -- the duplicates will
1532          // be cleared up before returning to the user.
1533          $linkobject->workregexp = preg_replace('/([#*%])/', '\1\1', $linkobject->workregexp);
1534  
1535          // Quote any regular expression characters and the delimiter in the work phrase to be searched.
1536          $linkobject->workregexp = preg_quote($linkobject->workregexp, '/');
1537  
1538          // If we ony want to match entire words then add \b assertions. However, only
1539          // do this if the first or last thing in the phrase to match is a word character.
1540          if ($linkobject->fullmatch) {
1541              if (preg_match('~^\w~', $linkobject->workregexp)) {
1542                  $linkobject->workregexp = '\b' . $linkobject->workregexp;
1543              }
1544              if (preg_match('~\w$~', $linkobject->workregexp)) {
1545                  $linkobject->workregexp = $linkobject->workregexp . '\b';
1546              }
1547          }
1548  
1549          $linkobject->workregexp = '/(' . $linkobject->workregexp . ')/s';
1550  
1551          if (!$linkobject->casesensitive) {
1552              $linkobject->workregexp .= 'iu';
1553          }
1554      }
1555  
1556      return $linkarray;
1557  }
1558  
1559  /**
1560   * Fill in the remaining ->work... fields, that would be needed to replace the phrase.
1561   *
1562   * @param filterobject $linkobject the link object on which to set additional fields.
1563   */
1564  function filter_prepare_phrase_for_replacement(filterobject $linkobject) {
1565      if ($linkobject->replacementcallback !== null) {
1566          list($linkobject->hreftagbegin, $linkobject->hreftagend, $linkobject->replacementphrase) =
1567                  call_user_func_array($linkobject->replacementcallback, $linkobject->replacementcallbackdata);
1568      }
1569  
1570      if (!isset($linkobject->hreftagbegin) or !isset($linkobject->hreftagend)) {
1571          $linkobject->hreftagbegin = '<span class="highlight"';
1572          $linkobject->hreftagend   = '</span>';
1573      }
1574  
1575      // Double up chars to protect true duplicates
1576      // be cleared up before returning to the user.
1577      $hreftagbeginmangled = preg_replace('/([#*%])/', '\1\1', $linkobject->hreftagbegin);
1578  
1579      // Set the replacement phrase properly.
1580      if ($linkobject->replacementphrase) {    // We have specified a replacement phrase.
1581          $linkobject->workreplacementphrase = strip_tags($linkobject->replacementphrase);
1582      } else {                                 // The replacement is the original phrase as matched below.
1583          $linkobject->workreplacementphrase = '$1';
1584      }
1585  
1586      $linkobject->workreplacementphrase = $hreftagbeginmangled .
1587              $linkobject->workreplacementphrase . $linkobject->hreftagend;
1588  }
1589  
1590  /**
1591   * Remove duplicate from a list of {@link filterobject}.
1592   *
1593   * @param filterobject[] $linkarray a list of filterobject.
1594   * @return filterobject[] the same list, but with dupicates removed.
1595   */
1596  function filter_remove_duplicates($linkarray) {
1597  
1598      $concepts  = array(); // Keep a record of concepts as we cycle through.
1599      $lconcepts = array(); // A lower case version for case insensitive.
1600  
1601      $cleanlinks = array();
1602  
1603      foreach ($linkarray as $key => $filterobject) {
1604          if ($filterobject->casesensitive) {
1605              $exists = in_array($filterobject->phrase, $concepts);
1606          } else {
1607              $exists = in_array(core_text::strtolower($filterobject->phrase), $lconcepts);
1608          }
1609  
1610          if (!$exists) {
1611              $cleanlinks[] = $filterobject;
1612              $concepts[] = $filterobject->phrase;
1613              $lconcepts[] = core_text::strtolower($filterobject->phrase);
1614          }
1615      }
1616  
1617      return $cleanlinks;
1618  }
1619  
1620  /**
1621   * Extract open/lose tags and their contents to avoid being processed by filters.
1622   * Useful to extract pieces of code like <a>...</a> tags. It returns the text
1623   * converted with some <#xTEXTFILTER_EXCL_SEPARATORx#> codes replacing the extracted text. Such extracted
1624   * texts are returned in the ignoretags array (as values), with codes as keys.
1625   *
1626   * @param string $text                  the text that we are filtering (in/out)
1627   * @param array $filterignoretagsopen  an array of open tags to start searching
1628   * @param array $filterignoretagsclose an array of close tags to end searching
1629   * @param array $ignoretags            an array of saved strings useful to rebuild the original text (in/out)
1630   **/
1631  function filter_save_ignore_tags(&$text, $filterignoretagsopen, $filterignoretagsclose, &$ignoretags) {
1632  
1633      // Remove everything enclosed by the ignore tags from $text.
1634      foreach ($filterignoretagsopen as $ikey => $opentag) {
1635          $closetag = $filterignoretagsclose[$ikey];
1636          // Form regular expression.
1637          $opentag  = str_replace('/', '\/', $opentag); // Delimit forward slashes.
1638          $closetag = str_replace('/', '\/', $closetag); // Delimit forward slashes.
1639          $pregexp = '/'.$opentag.'(.*?)'.$closetag.'/is';
1640  
1641          preg_match_all($pregexp, $text, $listofignores);
1642          foreach (array_unique($listofignores[0]) as $key => $value) {
1643              $prefix = (string) (count($ignoretags) + 1);
1644              $ignoretags['<#'.$prefix.TEXTFILTER_EXCL_SEPARATOR.$key.'#>'] = $value;
1645          }
1646          if (!empty($ignoretags)) {
1647              $text = str_replace($ignoretags, array_keys($ignoretags), $text);
1648          }
1649      }
1650  }
1651  
1652  /**
1653   * Extract tags (any text enclosed by < and > to avoid being processed by filters.
1654   * It returns the text converted with some <%xTEXTFILTER_EXCL_SEPARATORx%> codes replacing the extracted text. Such extracted
1655   * texts are returned in the tags array (as values), with codes as keys.
1656   *
1657   * @param string $text   the text that we are filtering (in/out)
1658   * @param array $tags   an array of saved strings useful to rebuild the original text (in/out)
1659   **/
1660  function filter_save_tags(&$text, &$tags) {
1661  
1662      preg_match_all('/<([^#%*].*?)>/is', $text, $listofnewtags);
1663      foreach (array_unique($listofnewtags[0]) as $ntkey => $value) {
1664          $prefix = (string)(count($tags) + 1);
1665          $tags['<%'.$prefix.TEXTFILTER_EXCL_SEPARATOR.$ntkey.'%>'] = $value;
1666      }
1667      if (!empty($tags)) {
1668          $text = str_replace($tags, array_keys($tags), $text);
1669      }
1670  }
1671  
1672  /**
1673   * Add missing openpopup javascript to HTML files.
1674   *
1675   * @param string $text
1676   * @return string
1677   */
1678  function filter_add_javascript($text) {
1679      global $CFG;
1680  
1681      if (stripos($text, '</html>') === false) {
1682          return $text; // This is not a html file.
1683      }
1684      if (strpos($text, 'onclick="return openpopup') === false) {
1685          return $text; // No popup - no need to add javascript.
1686      }
1687      $js = "
1688      <script type=\"text/javascript\">
1689      <!--
1690          function openpopup(url,name,options,fullscreen) {
1691            fullurl = \"".$CFG->wwwroot."\" + url;
1692            windowobj = window.open(fullurl,name,options);
1693            if (fullscreen) {
1694              windowobj.moveTo(0,0);
1695              windowobj.resizeTo(screen.availWidth,screen.availHeight);
1696            }
1697            windowobj.focus();
1698            return false;
1699          }
1700      // -->
1701      </script>";
1702      if (stripos($text, '</head>') !== false) {
1703          // Try to add it into the head element.
1704          $text = str_ireplace('</head>', $js.'</head>', $text);
1705          return $text;
1706      }
1707  
1708      // Last chance - try adding head element.
1709      return preg_replace("/<html.*?>/is", "\\0<head>".$js.'</head>', $text);
1710  }