diff --git a/filter/algebra/classes/text_filter.php b/filter/algebra/classes/text_filter.php
index 56fe83566eb..3e308408a72 100644
--- a/filter/algebra/classes/text_filter.php
+++ b/filter/algebra/classes/text_filter.php
@@ -39,7 +39,7 @@ use stdClass;
* You will then need to edit your moodle/config.php to invoke mathml_filter.php
* -------------------------------------------------------------------------
*
- * @package filter
+ * @package filter_algebra
* @subpackage algebra
* @copyright 2004 Zbigniew Fiedorowicz fiedorow@math.ohio-state.edu
* Originally based on code provided by Bruno Vernier bruno@vsbeducation.ca
@@ -50,39 +50,22 @@ class text_filter extends \core_filters\text_filter {
public function filter($text, array $options = []) {
global $CFG, $DB;
- /// Do a quick check using stripos to avoid unnecessary wor
- if (!preg_match('/get_record("forum_discussions",array("id"=>$parent->discussion));
-# } else if (strstr($scriptname,'discuss.php')) {
-# $discussion = $DB->get_record("forum_discussions",array("id"=>$_GET['d']));
-# } else {
-# return $text;
-# }
-# if ($discussion->forum != 130) {
-# return $text;
-# }
-
- preg_match_all('/@(@@+)([^@])/',$text,$matches);
- for ($i=0;$i some algebraic input expression
- // or @@ some algebraic input expression @@
-
+ // or @@ some algebraic input expression @@.
preg_match_all('/(.+?)<\/algebra>|@@(.+?)@@/is', $text, $matches);
- for ($i=0; $i','',$algebra);
- $algebra = str_replace('','',$algebra);
- $algebra = str_replace('','',$algebra);
- $algebra = str_replace('','',$algebra);
+ $algebra = str_replace('', '', $algebra);
+ $algebra = str_replace('', '', $algebra);
+ $algebra = str_replace('', '', $algebra);
+ $algebra = str_replace('', '', $algebra);
$align = "middle";
- if (preg_match('/^align=bottom /',$algebra)) {
- $align = "text-bottom";
- $algebra = preg_replace('/^align=bottom /','',$algebra);
- } else if (preg_match('/^align=top /',$algebra)) {
- $align = "text-top";
- $algebra = preg_replace('/^align=top /','',$algebra);
+ if (preg_match('/^align=bottom /', $algebra)) {
+ $align = "text-bottom";
+ $algebra = preg_replace('/^align=bottom /', '', $algebra);
+ } else if (preg_match('/^align=top /', $algebra)) {
+ $align = "text-top";
+ $algebra = preg_replace('/^align=top /', '', $algebra);
}
- $md5 = md5($algebra);
- $filename = $md5 . ".gif";
- if (! $texcache = $DB->get_record("cache_filters",array("filter"=>"algebra", "md5key"=>$md5))) {
- $algebra = str_replace('<','<',$algebra);
- $algebra = str_replace('>','>',$algebra);
- $algebra = str_replace('<>','#',$algebra);
- $algebra = str_replace('<=','%',$algebra);
- $algebra = str_replace('>=','!',$algebra);
- $algebra = preg_replace('/([=><%!#] *)-/',"\$1 zeroplace -",$algebra);
- $algebra = str_replace('delta','zdelta',$algebra);
- $algebra = str_replace('beta','bita',$algebra);
- $algebra = str_replace('theta','thita',$algebra);
- $algebra = str_replace('zeta','zita',$algebra);
- $algebra = str_replace('eta','xeta',$algebra);
- $algebra = str_replace('epsilon','zepslon',$algebra);
- $algebra = str_replace('upsilon','zupslon',$algebra);
- $algebra = preg_replace('!\r\n?!',' ',$algebra);
- $algebra = escapeshellarg($algebra);
- if ( (PHP_OS == "WINNT") || (PHP_OS == "WIN32") || (PHP_OS == "Windows")) {
- $cmd = "cd $CFG->dirroot\\filter\\algebra & algebra2tex.pl $algebra";
- } else {
- $cmd = "cd $CFG->dirroot/filter/algebra; ./algebra2tex.pl $algebra";
- }
- $texexp = `$cmd`;
- if (preg_match('/parsehilight/',$texexp)) {
- $text = str_replace( $matches[0][$i],"Syntax error: " . $texexp,$text);
- } else if ($texexp) {
- $texexp = str_replace('zeroplace','',$texexp);
- $texexp = str_replace('#','\not= ',$texexp);
- $texexp = str_replace('%','\leq ',$texexp);
- $texexp = str_replace('!','\geq ',$texexp);
- $texexp = str_replace('\left{','{',$texexp);
- $texexp = str_replace('\right}','}',$texexp);
- $texexp = str_replace('\fun',' ',$texexp);
- $texexp = str_replace('infty','\infty',$texexp);
- $texexp = str_replace('alpha','\alpha',$texexp);
- $texexp = str_replace('gamma','\gamma',$texexp);
- $texexp = str_replace('iota','\iota',$texexp);
- $texexp = str_replace('kappa','\kappa',$texexp);
- $texexp = str_replace('lambda','\lambda',$texexp);
- $texexp = str_replace('mu','\mu',$texexp);
- $texexp = str_replace('nu','\nu',$texexp);
- $texexp = str_replace('xi','\xi',$texexp);
- $texexp = str_replace('rho','\rho',$texexp);
- $texexp = str_replace('sigma','\sigma',$texexp);
- $texexp = str_replace('tau','\tau',$texexp);
- $texexp = str_replace('phi','\phi',$texexp);
- $texexp = str_replace('chi','\chi',$texexp);
- $texexp = str_replace('psi','\psi',$texexp);
- $texexp = str_replace('omega','\omega',$texexp);
- $texexp = str_replace('zdelta','\delta',$texexp);
- $texexp = str_replace('bita','\beta',$texexp);
- $texexp = str_replace('thita','\theta',$texexp);
- $texexp = str_replace('zita','\zeta',$texexp);
- $texexp = str_replace('xeta','\eta',$texexp);
- $texexp = str_replace('zepslon','\epsilon',$texexp);
- $texexp = str_replace('zupslon','\upsilon',$texexp);
- $texexp = str_replace('\mbox{logten}','\mbox{log}_{10}',$texexp);
- $texexp = str_replace('\mbox{acos}','\mbox{cos}^{-1}',$texexp);
- $texexp = str_replace('\mbox{asin}','\mbox{sin}^{-1}',$texexp);
- $texexp = str_replace('\mbox{atan}','\mbox{tan}^{-1}',$texexp);
- $texexp = str_replace('\mbox{asec}','\mbox{sec}^{-1}',$texexp);
- $texexp = str_replace('\mbox{acsc}','\mbox{csc}^{-1}',$texexp);
- $texexp = str_replace('\mbox{acot}','\mbox{cot}^{-1}',$texexp);
- $texexp = str_replace('\mbox{acosh}','\mbox{cosh}^{-1}',$texexp);
- $texexp = str_replace('\mbox{asinh}','\mbox{sinh}^{-1}',$texexp);
- $texexp = str_replace('\mbox{atanh}','\mbox{tanh}^{-1}',$texexp);
- $texexp = str_replace('\mbox{asech}','\mbox{sech}^{-1}',$texexp);
- $texexp = str_replace('\mbox{acsch}','\mbox{csch}^{-1}',$texexp);
- $texexp = str_replace('\mbox{acoth}','\mbox{coth}^{-1}',$texexp);
- //$texexp = preg_replace('/\\\frac{(.+?)}{\\\left\((.+?)\\\right\)}/s','\frac{'."\$1}{\$2}",$texexp);
- $texexp = preg_replace('/\\\sqrt{(.+?),(.+?)}/s','\sqrt['. "\$2]{\$1}",$texexp);
- $texexp = preg_replace('/\\\mbox{abs}\\\left\((.+?)\\\right\)/s',"|\$1|",$texexp);
- $texexp = preg_replace('/\\\log\\\left\((.+?),(.+?)\\\right\)/s','\log_{'. "\$2}\\left(\$1\\right)",$texexp);
- $texexp = preg_replace('/(\\\cos|\\\sin|\\\tan|\\\sec|\\\csc|\\\cot)([h]*)\\\left\((.+?),(.+?)\\\right\)/s',"\$1\$2^{". "\$4}\\left(\$3\\right)",$texexp);
- $texexp = preg_replace('/\\\int\\\left\((.+?),(.+?),(.+?)\\\right\)/s','\int_'. "{\$2}^{\$3}\$1 ",$texexp);
- $texexp = preg_replace('/\\\int\\\left\((.+?d[a-z])\\\right\)/s','\int '. "\$1 ",$texexp);
- $texexp = preg_replace('/\\\lim\\\left\((.+?),(.+?),(.+?)\\\right\)/s','\lim_'. "{\$2\\to \$3}\$1 ",$texexp);
- // Remove a forbidden keyword.
- $texexp = str_replace('\mbox', '', $texexp);
- $texcache = new stdClass();
- $texcache->filter = 'algebra';
- $texcache->version = 1;
- $texcache->md5key = $md5;
- $texcache->rawtext = $texexp;
- $texcache->timemodified = time();
- $DB->insert_record("cache_filters", $texcache, false);
- $text = str_replace( $matches[0][$i], self::get_image_markup($filename, $texexp, '', '', $align), $text);
- } else {
- $text = str_replace( $matches[0][$i],"Undetermined error: " . $matches[0][$i], $text);
- }
+
+ $md5 = md5($algebra);
+ $filename = $md5 . ".gif";
+ if (! $texcache = $DB->get_record("cache_filters", ["filter" => "algebra", "md5key" => $md5])) {
+ $algebra = str_replace('<', '<', $algebra);
+ $algebra = str_replace('>', '>', $algebra);
+ $algebra = str_replace('<>', '#', $algebra);
+ $algebra = str_replace('<=', '%', $algebra);
+ $algebra = str_replace('>=', '!', $algebra);
+ $algebra = preg_replace('/([=><%!#] *)-/', "\$1 zeroplace -", $algebra);
+ $algebra = str_replace('delta', 'zdelta', $algebra);
+ $algebra = str_replace('beta', 'bita', $algebra);
+ $algebra = str_replace('theta', 'thita', $algebra);
+ $algebra = str_replace('zeta', 'zita', $algebra);
+ $algebra = str_replace('eta', 'xeta', $algebra);
+ $algebra = str_replace('epsilon', 'zepslon', $algebra);
+ $algebra = str_replace('upsilon', 'zupslon', $algebra);
+ $algebra = preg_replace('!\r\n?!', ' ', $algebra);
+ $algebra = escapeshellarg($algebra);
+ if ((PHP_OS == "WINNT") || (PHP_OS == "WIN32") || (PHP_OS == "Windows")) {
+ $cmd = "cd $CFG->dirroot\\filter\\algebra & algebra2tex.pl $algebra";
+ } else {
+ $cmd = "cd $CFG->dirroot/filter/algebra; ./algebra2tex.pl $algebra";
+ }
+ $texexp = `$cmd`;
+ if (preg_match('/parsehilight/', $texexp)) {
+ $text = str_replace($matches[0][$i], "Syntax error: " . $texexp, $text);
+ } else if ($texexp) {
+ $texexp = str_replace('zeroplace', '', $texexp);
+ $texexp = str_replace('#', '\not= ', $texexp);
+ $texexp = str_replace('%', '\leq ', $texexp);
+ $texexp = str_replace('!', '\geq ', $texexp);
+ $texexp = str_replace('\left{', '{', $texexp);
+ $texexp = str_replace('\right}', '}', $texexp);
+ $texexp = str_replace('\fun', ' ', $texexp);
+ $texexp = str_replace('infty', '\infty', $texexp);
+ $texexp = str_replace('alpha', '\alpha', $texexp);
+ $texexp = str_replace('gamma', '\gamma', $texexp);
+ $texexp = str_replace('iota', '\iota', $texexp);
+ $texexp = str_replace('kappa', '\kappa', $texexp);
+ $texexp = str_replace('lambda', '\lambda', $texexp);
+ $texexp = str_replace('mu', '\mu', $texexp);
+ $texexp = str_replace('nu', '\nu', $texexp);
+ $texexp = str_replace('xi', '\xi', $texexp);
+ $texexp = str_replace('rho', '\rho', $texexp);
+ $texexp = str_replace('sigma', '\sigma', $texexp);
+ $texexp = str_replace('tau', '\tau', $texexp);
+ $texexp = str_replace('phi', '\phi', $texexp);
+ $texexp = str_replace('chi', '\chi', $texexp);
+ $texexp = str_replace('psi', '\psi', $texexp);
+ $texexp = str_replace('omega', '\omega', $texexp);
+ $texexp = str_replace('zdelta', '\delta', $texexp);
+ $texexp = str_replace('bita', '\beta', $texexp);
+ $texexp = str_replace('thita', '\theta', $texexp);
+ $texexp = str_replace('zita', '\zeta', $texexp);
+ $texexp = str_replace('xeta', '\eta', $texexp);
+ $texexp = str_replace('zepslon', '\epsilon', $texexp);
+ $texexp = str_replace('zupslon', '\upsilon', $texexp);
+ $texexp = str_replace('\mbox{logten}', '\mbox{log}_{10}', $texexp);
+ $texexp = str_replace('\mbox{acos}', '\mbox{cos}^{-1}', $texexp);
+ $texexp = str_replace('\mbox{asin}', '\mbox{sin}^{-1}', $texexp);
+ $texexp = str_replace('\mbox{atan}', '\mbox{tan}^{-1}', $texexp);
+ $texexp = str_replace('\mbox{asec}', '\mbox{sec}^{-1}', $texexp);
+ $texexp = str_replace('\mbox{acsc}', '\mbox{csc}^{-1}', $texexp);
+ $texexp = str_replace('\mbox{acot}', '\mbox{cot}^{-1}', $texexp);
+ $texexp = str_replace('\mbox{acosh}', '\mbox{cosh}^{-1}', $texexp);
+ $texexp = str_replace('\mbox{asinh}', '\mbox{sinh}^{-1}', $texexp);
+ $texexp = str_replace('\mbox{atanh}', '\mbox{tanh}^{-1}', $texexp);
+ $texexp = str_replace('\mbox{asech}', '\mbox{sech}^{-1}', $texexp);
+ $texexp = str_replace('\mbox{acsch}', '\mbox{csch}^{-1}', $texexp);
+ $texexp = str_replace('\mbox{acoth}', '\mbox{coth}^{-1}', $texexp);
+ $texexp = preg_replace('/\\\sqrt{(.+?),(.+?)}/s', '\sqrt[' . "\$2]{\$1}", $texexp);
+ $texexp = preg_replace('/\\\mbox{abs}\\\left\((.+?)\\\right\)/s', "|\$1|", $texexp);
+ $texexp = preg_replace('/\\\log\\\left\((.+?),(.+?)\\\right\)/s', '\log_{' . "\$2}\\left(\$1\\right)", $texexp);
+ $texexp = preg_replace(
+ '/(\\\cos|\\\sin|\\\tan|\\\sec|\\\csc|\\\cot)([h]*)\\\left\((.+?),(.+?)\\\right\)/s',
+ "\$1\$2^{" . "\$4}\\left(\$3\\right)",
+ $texexp,
+ );
+ $texexp = preg_replace('/\\\int\\\left\((.+?),(.+?),(.+?)\\\right\)/s', '\int_' . "{\$2}^{\$3}\$1 ", $texexp);
+ $texexp = preg_replace('/\\\int\\\left\((.+?d[a-z])\\\right\)/s', '\int ' . "\$1 ", $texexp);
+ $texexp = preg_replace('/\\\lim\\\left\((.+?),(.+?),(.+?)\\\right\)/s', '\lim_' . "{\$2\\to \$3}\$1 ", $texexp);
+ // Remove a forbidden keyword.
+ $texexp = str_replace('\mbox', '', $texexp);
+ $texcache = new stdClass();
+ $texcache->filter = 'algebra';
+ $texcache->version = 1;
+ $texcache->md5key = $md5;
+ $texcache->rawtext = $texexp;
+ $texcache->timemodified = time();
+ $DB->insert_record("cache_filters", $texcache, false);
+ $text = str_replace($matches[0][$i], filter_algebra_image($filename, $texexp, '', '', $align), $text);
+ } else {
+ $text = str_replace($matches[0][$i], "Undetermined error: " . $matches[0][$i], $text);
+ }
} else {
$text = str_replace($matches[0][$i], self::get_image_markup($filename, $texcache->rawtext), $text);
}
@@ -251,7 +238,8 @@ class text_filter extends \core_filters\text_filter {
}
$anchorcontents .= "\" $style />";
- if (!file_exists("$CFG->dataroot/filter/algebra/$imagefile") && has_capability('moodle/site:config', context_system::instance())) {
+ $imagefound = file_exists("$CFG->dataroot/filter/algebra/$imagefile");
+ if (!$imagefound && has_capability('moodle/site:config', context_system::instance())) {
$link = '/filter/algebra/algebradebug.php';
$action = null;
} else {
diff --git a/filter/classes/external/get_all_states.php b/filter/classes/external/get_all_states.php
index 97116b0910b..fd995c44a8c 100644
--- a/filter/classes/external/get_all_states.php
+++ b/filter/classes/external/get_all_states.php
@@ -33,7 +33,6 @@ use context;
* @since Moodle 4.4
*/
class get_all_states extends external_api {
-
/**
* Webservice parameters.
*
@@ -85,24 +84,22 @@ class get_all_states extends external_api {
* @return external_single_structure
*/
public static function execute_returns(): external_single_structure {
- return new external_single_structure(
- [
- 'filters' => new external_multiple_structure(
- new external_single_structure(
- [
- 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level where the filters are:
- (coursecat, course, module).'),
- 'instanceid' => new external_value(PARAM_INT, 'The instance id of item associated with the context.'),
- 'contextid' => new external_value(PARAM_INT, 'The context id.'),
- 'filter' => new external_value(PARAM_PLUGIN, 'Filter plugin name.'),
- 'state' => new external_value(PARAM_INT, 'Filter state: 1 for on, -1 for off, -9999 if disabled.'),
- 'sortorder' => new external_value(PARAM_INT, 'Execution order.'),
- ]
+ return new external_single_structure([
+ 'filters' => new external_multiple_structure(
+ new external_single_structure([
+ 'contextlevel' => new external_value(
+ PARAM_ALPHA,
+ 'The context level where the filters are: (coursecat, course, module).',
),
- 'All filters states'
- ),
- 'warnings' => new external_warnings(),
- ]
- );
+ 'instanceid' => new external_value(PARAM_INT, 'The instance id of item associated with the context.'),
+ 'contextid' => new external_value(PARAM_INT, 'The context id.'),
+ 'filter' => new external_value(PARAM_PLUGIN, 'Filter plugin name.'),
+ 'state' => new external_value(PARAM_INT, 'Filter state: 1 for on, -1 for off, -9999 if disabled.'),
+ 'sortorder' => new external_value(PARAM_INT, 'Execution order.'),
+ ]),
+ 'All filters states'
+ ),
+ 'warnings' => new external_warnings(),
+ ]);
}
}
diff --git a/filter/classes/external/get_available_in_context.php b/filter/classes/external/get_available_in_context.php
index 84e78954b46..0c6e1229a8f 100644
--- a/filter/classes/external/get_available_in_context.php
+++ b/filter/classes/external/get_available_in_context.php
@@ -23,9 +23,6 @@
*/
namespace core_filters\external;
-defined('MOODLE_INTERNAL') || die();
-
-require_once($CFG->libdir . '/filterlib.php');
use core_external\external_api;
use core_external\external_function_parameters;
@@ -49,19 +46,18 @@ class get_available_in_context extends external_api {
* @since Moodle 3.4
*/
public static function execute_parameters() {
- return new external_function_parameters (
- array(
- 'contexts' => new external_multiple_structure(
- new external_single_structure(
- array(
- 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level where the filters are:
- (coursecat, course, module)'),
- 'instanceid' => new external_value(PARAM_INT, 'The instance id of item associated with the context.')
- )
- ), 'The list of contexts to check.'
- ),
- )
- );
+ return new external_function_parameters([
+ 'contexts' => new external_multiple_structure(
+ new external_single_structure([
+ 'contextlevel' => new external_value(
+ PARAM_ALPHA,
+ 'The context level where the filters are: (coursecat, course, module)',
+ ),
+ 'instanceid' => new external_value(PARAM_INT, 'The instance id of item associated with the context.'),
+ ]),
+ 'The list of contexts to check.'
+ ),
+ ]);
}
/**
@@ -72,8 +68,12 @@ class get_available_in_context extends external_api {
* @since Moodle 3.4
*/
public static function execute($contexts) {
- $params = self::validate_parameters(self::get_available_in_context_parameters(), array('contexts' => $contexts));
- $filters = $warnings = array();
+ global $CFG;
+
+ require_once($CFG->libdir . '/filterlib.php');
+
+ $params = self::validate_parameters(self::execute_parameters(), ['contexts' => $contexts]);
+ $filters = $warnings = [];
foreach ($params['contexts'] as $contextinfo) {
try {
@@ -81,12 +81,12 @@ class get_available_in_context extends external_api {
self::validate_context($context);
$contextinfo['contextid'] = $context->id;
} catch (Exception $e) {
- $warnings[] = array(
+ $warnings[] = [
'item' => 'context',
'itemid' => $contextinfo['instanceid'],
'warningcode' => $e->getCode(),
'message' => $e->getMessage(),
- );
+ ];
continue;
}
$contextfilters = filter_get_available_in_context($context);
@@ -96,10 +96,10 @@ class get_available_in_context extends external_api {
}
}
- return array(
+ return [
'filters' => $filters,
'warnings' => $warnings,
- );
+ ];
}
/**
@@ -109,24 +109,22 @@ class get_available_in_context extends external_api {
* @since Moodle 3.4
*/
public static function execute_returns() {
- return new external_single_structure(
- array(
- 'filters' => new external_multiple_structure(
- new external_single_structure(
- array(
- 'contextlevel' => new external_value(PARAM_ALPHA, 'The context level where the filters are:
- (coursecat, course, module).'),
- 'instanceid' => new external_value(PARAM_INT, 'The instance id of item associated with the context.'),
- 'contextid' => new external_value(PARAM_INT, 'The context id.'),
- 'filter' => new external_value(PARAM_PLUGIN, 'Filter plugin name.'),
- 'localstate' => new external_value(PARAM_INT, 'Filter state: 1 for on, -1 for off, 0 if inherit.'),
- 'inheritedstate' => new external_value(PARAM_INT, '1 or 0 to use when localstate is set to inherit.'),
- )
+ return new external_single_structure([
+ 'filters' => new external_multiple_structure(
+ new external_single_structure([
+ 'contextlevel' => new external_value(
+ PARAM_ALPHA,
+ 'The context level where the filters are: (coursecat, course, module).',
),
- 'Available filters'
- ),
- 'warnings' => new external_warnings(),
- )
- );
+ 'instanceid' => new external_value(PARAM_INT, 'The instance id of item associated with the context.'),
+ 'contextid' => new external_value(PARAM_INT, 'The context id.'),
+ 'filter' => new external_value(PARAM_PLUGIN, 'Filter plugin name.'),
+ 'localstate' => new external_value(PARAM_INT, 'Filter state: 1 for on, -1 for off, 0 if inherit.'),
+ 'inheritedstate' => new external_value(PARAM_INT, '1 or 0 to use when localstate is set to inherit.'),
+ ]),
+ 'Available filters'
+ ),
+ 'warnings' => new external_warnings(),
+ ]);
}
}
diff --git a/filter/classes/filter_manager.php b/filter/classes/filter_manager.php
index 615c52d1d80..dfb315eeb38 100644
--- a/filter/classes/filter_manager.php
+++ b/filter/classes/filter_manager.php
@@ -36,22 +36,22 @@ class filter_manager {
* @var text_filter[][] This list of active filters, by context, for filtering content.
* An array contextid => ordered array of filter name => filter objects.
*/
- protected $textfilters = array();
+ protected $textfilters = [];
/**
* @var text_filter[][] This list of active filters, by context, for filtering strings.
* An array contextid => ordered array of filter name => filter objects.
*/
- protected $stringfilters = array();
+ protected $stringfilters = [];
/** @var array Exploded version of $CFG->stringfilters. */
- protected $stringfilternames = array();
+ protected $stringfilternames = [];
/** @var filter_manager Holds the singleton instance. */
protected static $singletoninstance;
/**
- * Constructor. Protected. Use {@link instance()} instead.
+ * Constructor. Protected. Use {@see instance()} instead.
*/
protected function __construct() {
$this->stringfilternames = filter_get_string_filters();
@@ -65,7 +65,7 @@ class filter_manager {
public static function instance() {
global $CFG;
if (is_null(self::$singletoninstance)) {
- if (!empty($CFG->perfdebug) and $CFG->perfdebug > 7) {
+ if (!empty($CFG->perfdebug) && $CFG->perfdebug > 7) {
self::$singletoninstance = new performance_measuring_filter_manager();
} else {
self::$singletoninstance = new self();
@@ -88,9 +88,9 @@ class filter_manager {
* Unloads all filters and other cached information
*/
protected function unload_all_filters() {
- $this->textfilters = array();
- $this->stringfilters = array();
- $this->stringfilternames = array();
+ $this->textfilters = [];
+ $this->stringfilters = [];
+ $this->stringfilternames = [];
}
/**
@@ -100,8 +100,8 @@ class filter_manager {
*/
protected function load_filters($context) {
$filters = filter_get_active_in_context($context);
- $this->textfilters[$context->id] = array();
- $this->stringfilters[$context->id] = array();
+ $this->textfilters[$context->id] = [];
+ $this->stringfilters[$context->id] = [];
foreach ($filters as $filtername => $localconfig) {
$filter = $this->make_filter_object($filtername, $context, $localconfig);
if (is_null($filter)) {
@@ -131,7 +131,7 @@ class filter_manager {
return new $filterclass($context, $localconfig);
}
- $path = $CFG->dirroot .'/filter/'. $filtername .'/filter.php';
+ $path = $CFG->dirroot . '/filter/' . $filtername . '/filter.php';
if (!is_readable($path)) {
return null;
}
@@ -148,13 +148,17 @@ class filter_manager {
/**
* Apply a list of filters to some content.
* @param string $text
- * @param moodle_text_filter[] $filterchain array filter name => filter object.
+ * @param text_filter[] $filterchain array filter name => filter object.
* @param array $options options passed to the filters.
- * @param array $skipfilters of filter names. Any filters that should not be applied to this text.
+ * @param null|array $skipfilters of filter names. Any filters that should not be applied to this text.
* @return string $text
*/
- protected function apply_filter_chain($text, $filterchain, array $options = array(),
- array $skipfilters = null) {
+ protected function apply_filter_chain(
+ $text,
+ $filterchain,
+ array $options = [],
+ ?array $skipfilters = null
+ ) {
if (!isset($options['stage'])) {
$filtermethod = 'filter';
} else if (in_array($options['stage'], ['pre_format', 'pre_clean', 'post_clean', 'string'], true)) {
@@ -208,15 +212,19 @@ class filter_manager {
* @param string $text The text to filter
* @param context $context the context.
* @param array $options options passed to the filters
- * @param array $skipfilters of filter names. Any filters that should not be applied to this text.
+ * @param null|array $skipfilters of filter names. Any filters that should not be applied to this text.
* @return string resulting text
*/
- public function filter_text($text, $context, array $options = array(),
- array $skipfilters = null) {
+ public function filter_text(
+ $text,
+ $context,
+ array $options = [],
+ ?array $skipfilters = null
+ ) {
$text = $this->apply_filter_chain($text, $this->get_text_filters($context), $options, $skipfilters);
if (!isset($options['stage']) || $options['stage'] === 'post_clean') {
// Remove tags for XHTML compatibility after the last filtering stage.
- $text = str_replace(array('', ''), '', $text);
+ $text = str_replace(['', ''], '', $text);
}
return $text;
}
diff --git a/filter/classes/filter_object.php b/filter/classes/filter_object.php
index a1c2166ba3d..7181fc595ac 100644
--- a/filter/classes/filter_object.php
+++ b/filter/classes/filter_object.php
@@ -77,15 +77,18 @@ class filter_object {
* list($linkobject->hreftagbegin, $linkobject->hreftagend, $linkobject->replacementphrase) =
* call_user_func_array($linkobject->replacementcallback, $linkobject->replacementcallbackdata);
* so the return should be an array [$hreftagbegin, $hreftagend, $replacementphrase], the last of which may be null.
- * @param array $replacementcallbackdata data to be passed to $replacementcallback (optional).
+ * @param null|array $replacementcallbackdata data to be passed to $replacementcallback (optional).
*/
- public function __construct($phrase, $hreftagbegin = '',
- $hreftagend = '',
- $casesensitive = false,
- $fullmatch = false,
- $replacementphrase = null,
- $replacementcallback = null,
- array $replacementcallbackdata = null) {
+ public function __construct(
+ $phrase,
+ $hreftagbegin = '',
+ $hreftagend = '',
+ $casesensitive = false,
+ $fullmatch = false,
+ $replacementphrase = null,
+ $replacementcallback = null,
+ ?array $replacementcallbackdata = null
+ ) {
$this->phrase = $phrase;
$this->hreftagbegin = $hreftagbegin;
diff --git a/filter/classes/form/local_settings_form.php b/filter/classes/form/local_settings_form.php
index c736430d71d..88ce25a3cf1 100644
--- a/filter/classes/form/local_settings_form.php
+++ b/filter/classes/form/local_settings_form.php
@@ -1,5 +1,4 @@
libdir . '/formslib.php');
* A Moodle form base class for editing local filter settings.
*
* @copyright Tim Hunt
- * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @package core_filters
*/
abstract class local_settings_form extends moodleform {
- /** @var string The filter to manage */
- protected $filter;
-
- /** @var \core\context The context */
- protected $context;
-
- public function __construct($submiturl, $filter, $context) {
- $this->filter = $filter;
- $this->context = $context;
+ /**
+ * Create an instance of the form.
+ *
+ * @param string $submiturl
+ * @param string $filter
+ * @param context $context
+ */
+ public function __construct(
+ string $submiturl,
+ /** @var string The filter to manage */
+ protected string $filter,
+ /** @var \core\context The context */
+ protected context $context,
+ ) {
parent::__construct($submiturl);
}
@@ -63,7 +68,7 @@ abstract class local_settings_form extends moodleform {
/**
* Override this method to add your form controls.
*
- * @param $mform the form we are building. $this->_form, but passed in for convenience.
+ * @param \MoodleQuickForm $mform the form we are building. $this->_form, but passed in for convenience.
*/
abstract protected function definition_inner($mform);
diff --git a/filter/classes/null_filter_manager.php b/filter/classes/null_filter_manager.php
index 018be83f4d2..f24759a1ab7 100644
--- a/filter/classes/null_filter_manager.php
+++ b/filter/classes/null_filter_manager.php
@@ -28,21 +28,25 @@ use core\context;
*/
class null_filter_manager {
/**
- * As for the equivalent {@link filter_manager} method.
+ * As for the equivalent {@see filter_manager} method.
*
* @param string $text The text to filter
* @param context $context not used.
* @param array $options not used
- * @param array $skipfilters not used
+ * @param null|array $skipfilters not used
* @return string resulting text.
*/
- public function filter_text($text, $context, array $options = array(),
- array $skipfilters = null) {
+ public function filter_text(
+ $text,
+ $context,
+ array $options = [],
+ ?array $skipfilters = null
+ ) {
return $text;
}
/**
- * As for the equivalent {@link filter_manager} method.
+ * As for the equivalent {@see filter_manager} method.
*
* @param string $string The text to filter
* @param context $context not used.
diff --git a/filter/classes/performance_measuring_filter_manager.php b/filter/classes/performance_measuring_filter_manager.php
index 12dc8969306..c712e78e8be 100644
--- a/filter/classes/performance_measuring_filter_manager.php
+++ b/filter/classes/performance_measuring_filter_manager.php
@@ -25,14 +25,15 @@ namespace core_filters;
*/
class performance_measuring_filter_manager extends filter_manager {
/** @var int number of filter objects created. */
- protected $filterscreated = 0;
+ protected int $filterscreated = 0;
/** @var int number of calls to filter_text. */
- protected $textsfiltered = 0;
+ protected int $textsfiltered = 0;
/** @var int number of calls to filter_string. */
- protected $stringsfiltered = 0;
+ protected int $stringsfiltered = 0;
+ #[\Override]
protected function unload_all_filters() {
parent::unload_all_filters();
$this->filterscreated = 0;
@@ -40,40 +41,51 @@ class performance_measuring_filter_manager extends filter_manager {
$this->stringsfiltered = 0;
}
+ #[\Override]
protected function make_filter_object($filtername, $context, $localconfig) {
$this->filterscreated++;
return parent::make_filter_object($filtername, $context, $localconfig);
}
- public function filter_text($text, $context, array $options = array(),
- array $skipfilters = null) {
+ #[\Override]
+ public function filter_text(
+ $text,
+ $context,
+ array $options = [],
+ ?array $skipfilters = null
+ ) {
if (!isset($options['stage']) || $options['stage'] === 'post_clean') {
$this->textsfiltered++;
}
return parent::filter_text($text, $context, $options, $skipfilters);
}
+ #[\Override]
public function filter_string($string, $context) {
$this->stringsfiltered++;
return parent::filter_string($string, $context);
}
/**
- * Return performance information, in the form required by {@link get_performance_info()}.
+ * Return performance information, in the form required by {@see get_performance_info()}.
+ *
* @return array the performance info.
*/
- public function get_performance_summary() {
- return array(array(
- 'contextswithfilters' => count($this->textfilters),
- 'filterscreated' => $this->filterscreated,
- 'textsfiltered' => $this->textsfiltered,
- 'stringsfiltered' => $this->stringsfiltered,
- ), array(
- 'contextswithfilters' => 'Contexts for which filters were loaded',
- 'filterscreated' => 'Filters created',
- 'textsfiltered' => 'Pieces of content filtered',
- 'stringsfiltered' => 'Strings filtered',
- ));
+ public function get_performance_summary(): array {
+ return [
+ [
+ 'contextswithfilters' => count($this->textfilters),
+ 'filterscreated' => $this->filterscreated,
+ 'textsfiltered' => $this->textsfiltered,
+ 'stringsfiltered' => $this->stringsfiltered,
+ ],
+ [
+ 'contextswithfilters' => 'Contexts for which filters were loaded',
+ 'filterscreated' => 'Filters created',
+ 'textsfiltered' => 'Pieces of content filtered',
+ 'stringsfiltered' => 'Strings filtered',
+ ],
+ ];
}
}
diff --git a/filter/classes/privacy/provider.php b/filter/classes/privacy/provider.php
index cd3132c8722..d0ec7375ffe 100644
--- a/filter/classes/privacy/provider.php
+++ b/filter/classes/privacy/provider.php
@@ -14,26 +14,16 @@
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see .
+namespace core_filters\privacy;
+
/**
- * Privacy Subsystem implementation for core_filters.
+ * Privacy Subsystem for core_filters implementing null_provider.
*
* @package core_filters
* @copyright 2018 Andrew Nicols
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
-
-namespace core_filters\privacy;
-
-defined('MOODLE_INTERNAL') || die();
-
-/**
- * Privacy Subsystem for core_filters implementing null_provider.
- *
- * @copyright 2018 Andrew Nicols
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
class provider implements \core_privacy\local\metadata\null_provider {
-
/**
* Get the language string identifier with the component's language
* file to explain why this plugin stores no data.
diff --git a/filter/classes/text_filter.php b/filter/classes/text_filter.php
index f9914a3d91d..39acd05266d 100644
--- a/filter/classes/text_filter.php
+++ b/filter/classes/text_filter.php
@@ -74,7 +74,7 @@ abstract class text_filter {
* @param array $options options passed to the filters
* @return string the HTML content after the filtering has been applied.
*/
- abstract public function filter($text, array $options = array());
+ abstract public function filter($text, array $options = []);
/**
* Filter text before changing format to HTML.
diff --git a/filter/data/classes/text_filter.php b/filter/data/classes/text_filter.php
index d5ccfbe6ddf..91996c92129 100644
--- a/filter/data/classes/text_filter.php
+++ b/filter/data/classes/text_filter.php
@@ -26,36 +26,32 @@ use core_filters\filter_object;
*/
class text_filter extends \core_filters\text_filter {
#[\Override]
- public function filter($text, array $options = array()) {
+ public function filter($text, array $options = []) {
global $CFG, $DB, $USER;
// Trivial-cache - keyed on $cachedcourseid + $cacheduserid.
static $cachedcourseid = null;
static $cacheduserid = null;
- static $coursecontentlist = array();
- static $sitecontentlist = array();
+ static $coursecontentlist = [];
+ static $sitecontentlist = [];
static $nothingtodo;
// Try to get current course.
$coursectx = $this->context->get_course_context(false);
- if (!$coursectx) {
- // We could be in a course category so no entries for courseid == 0 will be found.
- $courseid = 0;
- } else {
- $courseid = $coursectx->instanceid;
- }
+ // We could be in a course category so no entries for courseid == 0 will be found.
+ $courseid = $coursectx?->instanceid ?: 0;
if ($cacheduserid !== $USER->id) {
// Invalidate all caches if the user changed.
- $coursecontentlist = array();
- $sitecontentlist = array();
+ $coursecontentlist = [];
+ $sitecontentlist = [];
$cacheduserid = $USER->id;
$cachedcourseid = $courseid;
$nothingtodo = false;
} else if ($courseid != get_site()->id && $courseid != 0 && $cachedcourseid != $courseid) {
// Invalidate course-level caches if the course id changed.
- $coursecontentlist = array();
+ $coursecontentlist = [];
$cachedcourseid = $courseid;
$nothingtodo = false;
}
@@ -65,6 +61,7 @@ class text_filter extends \core_filters\text_filter {
}
// If courseid == 0 only site entries will be returned.
+ $site = get_site();
if ($courseid == get_site()->id || $courseid == 0) {
$contentlist = & $sitecontentlist;
} else {
@@ -73,12 +70,12 @@ class text_filter extends \core_filters\text_filter {
// Create a list of all the resources to search for. It may be cached already.
if (empty($contentlist)) {
- $coursestosearch = $courseid ? array($courseid) : array(); // Add courseid if found
- if (get_site()->id != $courseid) { // Add siteid if was not courseid
+ $coursestosearch = $courseid ? [$courseid] : []; // Add courseid if found.
+ if (get_site()->id != $courseid) { // Add siteid if was not courseid.
$coursestosearch[] = get_site()->id;
}
- // We look for text field contents only if have autolink enabled (param1)
- list ($coursesql, $params) = $DB->get_in_or_equal($coursestosearch);
+ // We look for text field contents only if have autolink enabled (param1).
+ [$coursesql, $params] = $DB->get_in_or_equal($coursestosearch);
$sql = 'SELECT dc.id AS contentid, dr.id AS recordid, dc.content AS content, d.id AS dataid
FROM {data} d
JOIN {data_fields} df ON df.dataid = d.id
@@ -94,7 +91,7 @@ class text_filter extends \core_filters\text_filter {
}
foreach ($contents as $key => $content) {
- // Trim empty or unlinkable concepts
+ // Trim empty or unlinkable concepts.
$currentcontent = trim(strip_tags($content->content));
if (empty($currentcontent)) {
unset($contents[$key]);
@@ -103,7 +100,7 @@ class text_filter extends \core_filters\text_filter {
$contents[$key]->content = $currentcontent;
}
- // Rule out any small integers. See bug 1446
+ // Rule out any small integers. See bug 1446.
$currentint = intval($currentcontent);
if ($currentint && (strval($currentint) == $currentcontent) && $currentint < 1000) {
unset($contents[$key]);
@@ -118,17 +115,24 @@ class text_filter extends \core_filters\text_filter {
usort($contents, [self::class, 'sort_entries_by_length']);
foreach ($contents as $content) {
- $href_tag_begin = 'wwwroot.'/mod/data/view.php?d='.$content->dataid.
- '&rid='.$content->recordid.'">';
- $contentlist[] = new filter_object($content->content, $href_tag_begin, '', false, true);
+ $hrefopen = 'wwwroot . '/mod/data/view.php?d=' . $content->dataid .
+ '&rid=' . $content->recordid . '">';
+ $contentlist[] = new filter_object($content->content, $hrefopen, '', false, true);
}
- $contentlist = filter_remove_duplicates($contentlist); // Clean dupes
+ $contentlist = filter_remove_duplicates($contentlist); // Clean dupes.
}
- return filter_phrases($text, $contentlist); // Look for all these links in the text
+ return filter_phrases($text, $contentlist); // Look for all these links in the text.
}
+ /**
+ * Helper to sort array values by content length.
+ *
+ * @param mixed $content0
+ * @param mixed $content1
+ * @return int
+ */
private static function sort_entries_by_length($content0, $content1) {
$len0 = strlen($content0->content);
$len1 = strlen($content1->content);
diff --git a/filter/displayh5p/classes/text_filter.php b/filter/displayh5p/classes/text_filter.php
index 4996b11ed49..be53ee624d4 100644
--- a/filter/displayh5p/classes/text_filter.php
+++ b/filter/displayh5p/classes/text_filter.php
@@ -31,22 +31,14 @@ use core_h5p\local\library\autoloader;
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class text_filter extends \core_filters\text_filter {
- /**
- * @var boolean $loadresizerjs This is whether to request the resize.js script.
- */
+ /** @var bool $loadresizerjs This is whether to request the resize.js script */
private static $loadresizerjs = true;
- /**
- * Function filter replaces any h5p-sources.
- *
- * @param string $text HTML content to process
- * @param array $options options passed to the filters
- * @return string
- */
- public function filter($text, array $options = array()) {
+ #[\Override]
+ public function filter($text, array $options = []) {
global $CFG, $USER;
- if (!is_string($text) or empty($text)) {
+ if (!is_string($text) || empty($text)) {
// Non string data can not be filtered anyway.
return $text;
}
@@ -60,18 +52,18 @@ class text_filter extends \core_filters\text_filter {
$allowedsources = get_config('filter_displayh5p', 'allowedsources');
$allowedsources = array_filter(array_map('trim', explode("\n", $allowedsources)));
- $localsource = '('.preg_quote($CFG->wwwroot, '~').'/[^ &\#"\'<]*\.h5p([?][^ "\'<]*)?[^ \#"\'<]*)';
+ $localsource = '(' . preg_quote($CFG->wwwroot, '~') . '/[^ &\#"\'<]*\.h5p([?][^ "\'<]*)?[^ \#"\'<]*)';
$allowedsources[] = $localsource;
- $params = array(
+ $params = [
'tagbegin' => '','',$texexp);
- $texexp = str_replace('','',$texexp);
- $texexp = str_replace('','',$texexp);
- $texexp = preg_replace("/
/i", '', $texexp); //dlnsk
+ $texexp = str_replace('', '', $texexp);
+ $texexp = str_replace('', '', $texexp);
+ $texexp = str_replace('', '', $texexp);
+ $texexp = str_replace('', '', $texexp);
+ $texexp = preg_replace("/
/i", '', $texexp);
$align = "middle";
- if (preg_match('/^align=bottom /',$texexp)) {
- $align = "text-bottom";
- $texexp = preg_replace('/^align=bottom /','',$texexp);
- } else if (preg_match('/^align=top /',$texexp)) {
- $align = "text-top";
- $texexp = preg_replace('/^align=top /','',$texexp);
+ if (preg_match('/^align=bottom /', $texexp)) {
+ $align = "text-bottom";
+ $texexp = preg_replace('/^align=bottom /', '', $texexp);
+ } else if (preg_match('/^align=top /', $texexp)) {
+ $align = "text-top";
+ $texexp = preg_replace('/^align=top /', '', $texexp);
}
- // decode entities encoded by editor, luckily there is very little chance of double decoding
+ // Decode entities encoded by editor, luckily there is very little chance of double decoding.
$texexp = html_entity_decode($texexp, ENT_QUOTES, 'UTF-8');
if ($texexp === '') {
@@ -122,7 +109,7 @@ class text_filter extends \core_filters\text_filter {
$texexp = clean_param($texexp, PARAM_TEXT);
$md5 = md5($texexp);
- if (!$DB->record_exists("cache_filters", array("filter"=>"tex", "md5key"=>$md5))) {
+ if (!$DB->record_exists("cache_filters", ["filter" => "tex", "md5key" => $md5])) {
$texcache = new stdClass();
$texcache->filter = 'tex';
$texcache->version = 1;
@@ -135,8 +122,8 @@ class text_filter extends \core_filters\text_filter {
if ($convertformat == 'svg' && !core_useragent::supports_svg()) {
$convertformat = 'png';
}
- $filename = $md5.".{$convertformat}";
- $text = str_replace( $matches[0][$i], self::get_image_markup($filename, $texexp, 0, 0, $align, $alt), $text);
+ $filename = $md5 . ".{$convertformat}";
+ $text = str_replace($matches[0][$i], $this->get_image_markup($filename, $texexp, 0, 0, $align, $alt), $text);
}
return $text;
}
@@ -163,11 +150,11 @@ class text_filter extends \core_filters\text_filter {
global $CFG, $OUTPUT;
if (!$imagefile) {
- throw new coding_exception('image file argument empty in get_image_markup()');
+ throw new coding_exception('Image file argument empty in get_image_markup()');
}
// Work out any necessary inline style.
- $rules = array();
+ $rules = [];
if ($align !== 'middle') {
$rules[] = 'vertical-align:' . $align . ';';
}
@@ -189,7 +176,7 @@ class text_filter extends \core_filters\text_filter {
// users (to provide a text equivalent to the equation) while the title
// is there as a convenience for sighted users who want to see the TeX
// code.
- $title = 'title="'.s($tex).'"';
+ $title = 'title="' . s($tex) . '"';
if ($alt === '') {
$alt = s($tex);
@@ -199,21 +186,24 @@ class text_filter extends \core_filters\text_filter {
// Build the output.
$anchorcontents = "
slasharguments) { // Use this method if possible for better caching
+ if ($CFG->slasharguments) {
+ // Use this method if possible for better client-side caching.
$anchorcontents .= "$CFG->wwwroot/filter/tex/pix.php/$imagefile";
} else {
$anchorcontents .= "$CFG->wwwroot/filter/tex/pix.php?file=$imagefile";
}
$anchorcontents .= "\" $style/>";
- if (!file_exists("$CFG->dataroot/filter/tex/$imagefile") && has_capability('moodle/site:config', context_system::instance())) {
+ $imagefound = file_exists("$CFG->dataroot/filter/tex/$imagefile");
+ if (!$imagefound && has_capability('moodle/site:config', context_system::instance())) {
$link = '/filter/tex/texdebug.php';
$action = null;
} else {
- $link = new url('/filter/tex/displaytex.php', array('texexp'=>$tex));
- $action = new popup_action('click', $link, 'popup', array('width'=>320,'height'=>240));
+ $link = new url('/filter/tex/displaytex.php', ['texexp' => $tex]);
+ $action = new popup_action('click', $link, 'popup', ['width' => 320, 'height' => 240]);
}
- $output = $OUTPUT->action_link($link, $anchorcontents, $action, array('title'=>'TeX')); //TODO: the popups do not work when text caching is enabled!!
+ // TODO: the popups do not work when text caching is enabled.
+ $output = $OUTPUT->action_link($link, $anchorcontents, $action, ['title' => 'TeX']);
$output = "$output";
return $output;
diff --git a/filter/tex/tests/text_filter_test.php b/filter/tex/tests/text_filter_test.php
index 5efcf584965..837cd03bb23 100644
--- a/filter/tex/tests/text_filter_test.php
+++ b/filter/tex/tests/text_filter_test.php
@@ -81,7 +81,7 @@ final class text_filter_test extends \advanced_testcase {
['$', '$', false],
['(', ')', false],
['[', ']', false],
- ['$$', '\\]', false]
+ ['$$', '\\]', false],
];
}
}
diff --git a/filter/tidy/classes/text_filter.php b/filter/tidy/classes/text_filter.php
index bfe2b95da9c..93ac723d15d 100644
--- a/filter/tidy/classes/text_filter.php
+++ b/filter/tidy/classes/text_filter.php
@@ -14,6 +14,8 @@
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see .
+namespace filter_tidy;
+
/**
* HTML tidy text filter.
*
@@ -36,8 +38,8 @@
class text_filter extends \core_filters\text_filter {
#[\Override]
public function filter($text, array $options = []) {
- // Configuration for tidy. Feel free to tune for your needs, e.g. to allow
- // proprietary markup.
+ // Configuration for tidy.
+ // See https://api.html-tidy.org/tidy/quickref_5.0.0.html for details.
$tidyoptions = [
'output-xhtml' => true,
'show-body-only' => true,
@@ -53,12 +55,11 @@ class text_filter extends \core_filters\text_filter {
return $text;
}
-
// If enabled: run tidy over the entire string.
- if (function_exists('tidy_repair_string')) {
+ if (extension_loaded('tidy')) {
$currentlocale = \core\locale::get_locale();
try {
- $text = tidy_repair_string($text, $tidyoptions, 'utf8');
+ $text = (new \tidy())->repairString($text, $tidyoptions, 'utf8');
} finally {
\core\locale::set_locale(LC_ALL, $currentlocale);
}
diff --git a/filter/urltolink/classes/text_filter.php b/filter/urltolink/classes/text_filter.php
index de18157e3a7..bc471ef0988 100644
--- a/filter/urltolink/classes/text_filter.php
+++ b/filter/urltolink/classes/text_filter.php
@@ -1,5 +1,4 @@
- //<a href="blah">
- //<a href="blah">
- $filterignoretagsopen = array(']+?>', ']+?class="nolink"[^>]*?>');
- $filterignoretagsclose = array('', '');
+ // I've added img tags to this list of tags to ignore.
+ // See MDL-21168 for more info. A better way to ignore tags whether or not
+ // they are escaped partially or completely would be desirable. For example:
+ //
+ // <a href="blah">
+ // <a href="blah">.
+ $filterignoretagsopen = [']+?>', ']+?class="nolink"[^>]*?>'];
+ $filterignoretagsclose = ['', ''];
$ignoretags = [];
- filter_save_ignore_tags($text,$filterignoretagsopen,$filterignoretagsclose,$ignoretags);
+ filter_save_ignore_tags($text, $filterignoretagsopen, $filterignoretagsclose, $ignoretags);
// Check if we support unicode modifiers in regular expressions. Cache it.
// TODO: this check should be a environment requirement in Moodle 2.0, as far as unicode
@@ -76,10 +71,10 @@ class text_filter extends \core_filters\text_filter {
// Unicode check, negative assertion and other bits from Moodle.
static $unicoderegexp;
if (!isset($unicoderegexp)) {
- $unicoderegexp = @preg_match('/\pL/u', 'a'); // This will fail silently, returning false,
+ $unicoderegexp = @preg_match('/\pL/u', 'a'); // This will fail silently, returning false.
}
- // TODO MDL-21296 - use of unicode modifiers may cause a timeout
+ // TODO MDL-21296 - use of unicode modifiers may cause a timeout.
$urlstart = '(?:http(s)?://|(?([^>]*)<\/a>/is';
$text = preg_replace_callback($search, [self::class, 'get_image_markup'], $text);
}
@@ -153,14 +148,14 @@ class text_filter extends \core_filters\text_filter {
*
* This plugin is intended for automatic conversion of image URLs when FORMAT_MOODLE used.
*
- * @param $link
+ * @param array $link
* @return string
*/
private function get_image_markup($link) {
if ($link[1] !== $link[3]) {
- // this is not a link created by this filter, because the url does not match the text
+ // This is not a link created by this filter, because the url does not match the text.
return $link[0];
}
- return '
';
+ return '
';
}
}
diff --git a/filter/urltolink/tests/text_filter_test.php b/filter/urltolink/tests/text_filter_test.php
index c8945606591..2583b20d511 100644
--- a/filter/urltolink/tests/text_filter_test.php
+++ b/filter/urltolink/tests/text_filter_test.php
@@ -26,11 +26,17 @@ namespace filter_urltolink;
* @covers \filter_urltolink\text_filter
*/
final class text_filter_test extends \basic_testcase {
+ /**
+ * Data provider for test_convert_urls_into_links.
+ *
+ * @return array
+ */
public static function get_convert_urls_into_links_test_cases(): array {
// Create a 4095 and 4096 long URLs.
$superlong4095 = str_pad('http://www.superlong4095.com?this=something', 4095, 'a');
$superlong4096 = str_pad('http://www.superlong4096.com?this=something', 4096, 'a');
+ // phpcs:disable moodle.Files.LineLength.MaxExceeded, moodle.Files.LineLength.TooLong
$texts = [
// Just a url.
'http://moodle.org - URL' => 'http://moodle.org - URL',
@@ -70,8 +76,6 @@ final class text_filter_test extends \basic_testcase {
'URL: www.cc.org/url_(withpar)_go/?i=2' => 'URL: www.cc.org/url_(withpar)_go/?i=2',
'URL: http://cc.org/url_(with)_(par)_go/?i=2' => 'URL: http://cc.org/url_(with)_(par)_go/?i=2',
'URL: www.cc.org/url_(with)_(par)_go/?i=2' => 'URL: www.cc.org/url_(with)_(par)_go/?i=2',
- // URL legitimately ending in a bracket. Commented out as part of MDL-22390. See next tests for work-arounds.
- // 'http://en.wikipedia.org/wiki/Slash_(punctuation)'=>'http://en.wikipedia.org/wiki/Slash_(punctuation)',
'http://en.wikipedia.org/wiki/%28#Parentheses_.28_.29 - URL' => 'http://en.wikipedia.org/wiki/%28#Parentheses_.28_.29 - URL',
'http://en.wikipedia.org/wiki/(#Parentheses_.28_.29 - URL' => 'http://en.wikipedia.org/wiki/(#Parentheses_.28_.29 - URL',
// Escaped brackets in url.
@@ -134,16 +138,14 @@ final class text_filter_test extends \basic_testcase {
'' => '',
'' => '',
'' => '',
- // Partially escaped img tag
+ // Partially escaped img tag.
'partially escaped img tag <img src="http://moodle.org/logo/logo-240x60.gif" />' => 'partially escaped img tag <img src="http://moodle.org/logo/logo-240x60.gif" />',
- // Fully escaped img tag. Commented out as part of MDL-21183
- // Htmlspecialchars('fully escaped img tag
') => 'fully escaped img tag <img src="http://moodle.org/logo/logo-240x60.gif" />',
- // Double http with www
+ // Double http with www.
'One more link like http://www.moodle.org to test' => 'One more link like http://www.moodle.org to test',
- // Encoded URLs in the path
+ // Encoded URLs in the path.
'URL: http://127.0.0.1/one%28parenthesis%29/path?param=value' => 'URL: http://127.0.0.1/one%28parenthesis%29/path?param=value',
'URL: www.localhost.com/one%28parenthesis%29/path?param=value' => 'URL: www.localhost.com/one%28parenthesis%29/path?param=value',
- // Encoded URLs in the query
+ // Encoded URLs in the query.
'URL: http://127.0.0.1/path/to?param=value_with%28parenthesis%29¶m2=1' => 'URL: http://127.0.0.1/path/to?param=value_with%28parenthesis%29¶m2=1',
'URL: www.localhost.com/path/to?param=value_with%28parenthesis%29¶m2=1' => 'URL: www.localhost.com/path/to?param=value_with%28parenthesis%29¶m2=1',
// Test URL less than 4096 characters in size is converted to link.
@@ -173,6 +175,8 @@ final class text_filter_test extends \basic_testcase {
'URL: http://moodle.org' => 'URL: http://moodle.org',
];
+ // phpcs:enable
+
$data = [];
foreach ($texts as $text => $correctresult) {
$data[] = [$text, $correctresult];
@@ -181,7 +185,11 @@ final class text_filter_test extends \basic_testcase {
}
/**
+ * Test the convert_urls_into_links method.
+ *
* @dataProvider get_convert_urls_into_links_test_cases
+ * @param string $text
+ * @param string $correctresult
*/
public function test_convert_urls_into_links($text, $correctresult): void {
$testablefilter = $this->get_testable_text_filter();
@@ -193,13 +201,15 @@ final class text_filter_test extends \basic_testcase {
/**
* Get a copy of the filter configured for testing.
*
- * @param array $args
+ * @param array ...$args
* @return \filter_urltolink\text_filter
*/
protected function get_testable_text_filter(...$args): text_filter {
return new class extends text_filter {
+ // phpcs:ignore moodle.Commenting.MissingDocblock.MissingTestcaseMethodDescription
public function __construct() {
}
+ // phpcs:ignore moodle.Commenting.MissingDocblock.MissingTestcaseMethodDescription, Generic.CodeAnalysis.UselessOverridingMethod.Found
public function convert_urls_into_links(&$text) {
parent::convert_urls_into_links($text);
}