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