MediaWiki
1.23.2
|
HTML sanitizer for MediaWiki. More...
Static Public Member Functions | |
static | attributeWhitelist ( $element) |
Fetch the whitelist of acceptable attributes for a given element name. More... | |
static | checkCss ( $value) |
Pick apart some CSS and check it for forbidden or unsafe structures. More... | |
static | cleanUrl ( $url) |
static | cleanUrlCallback ( $matches) |
static | cssDecodeCallback ( $matches) |
static | decCharReference ( $codepoint) |
static | decodeChar ( $codepoint) |
Return UTF-8 string for a codepoint if that is a valid character reference, otherwise U+FFFD REPLACEMENT CHARACTER. More... | |
static | decodeCharReferences ( $text) |
Decode any character references, numeric or named entities, in the text and return a UTF-8 string. More... | |
static | decodeCharReferencesAndNormalize ( $text) |
Decode any character references, numeric or named entities, in the next and normalize the resulting string. More... | |
static | decodeCharReferencesCallback ( $matches) |
static | decodeEntity ( $name) |
If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD, return the UTF-8 encoding of that character. More... | |
static | decodeTagAttributes ( $text) |
Return an associative array of attribute names and values from a partial tag string. More... | |
static | encodeAttribute ( $text) |
Encode an attribute value for HTML output. More... | |
static | escapeClass ( $class) |
Given a value, escape it so that it can be used as a CSS class and return it. More... | |
static | escapeHtmlAllowEntities ( $html) |
Given HTML input, escape with htmlspecialchars but un-escape entities. More... | |
static | escapeId ( $id, $options=array()) |
Given a value, escape it so that it can be used in an id attribute and return it. More... | |
static | fixTagAttributes ( $text, $element) |
Take a tag soup fragment listing an HTML element's attributes and normalize it to well-formed XML, discarding unwanted attributes. More... | |
static | getAttribsRegex () |
Regular expression to match HTML/XML attribute pairs within a tag. More... | |
static | hackDocType () |
Hack up a private DOCTYPE with HTML's standard entity declarations. More... | |
static | hexCharReference ( $codepoint) |
static | mergeAttributes ( $a, $b) |
Merge two sets of HTML attributes. More... | |
static | normalizeCharReferences ( $text) |
Ensure that any entities and character references are legal for XML and XHTML specifically. More... | |
static | normalizeCharReferencesCallback ( $matches) |
static | normalizeEntity ( $name) |
If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD, return the equivalent numeric entity reference (except for the core < > & "). More... | |
static | normalizeSectionNameWhitespace ( $section) |
Normalizes whitespace in a section name, such as might be returned by Parser::stripSectionName(), for use in the id's that are used for section links. More... | |
static | removeHTMLcomments ( $text) |
Remove '', and everything between. More... | |
static | removeHTMLtags ( $text, $processCallback=null, $args=array(), $extratags=array(), $removetags=array()) |
Cleans up HTML, removes dangerous tags and attributes, and removes HTML comments. More... | |
static | safeEncodeAttribute ( $text) |
Encode an attribute value for HTML tags, with extra armoring against further wiki processing. More... | |
static | safeEncodeTagAttributes ( $assoc_array) |
Build a partial tag string from an associative array of attribute names and values as returned by decodeTagAttributes. More... | |
static | setupAttributeWhitelist () |
Foreach array key (an allowed HTML element), return an array of allowed attributes. More... | |
static | stripAllTags ( $text) |
Take a fragment of (potentially invalid) HTML and return a version with any tags removed, encoded as plain text. More... | |
static | validateAttributes ( $attribs, $whitelist) |
Take an array of attribute names and values and normalize or discard illegal values for the given whitelist. More... | |
static | validateEmail ( $addr) |
Does a string look like an e-mail address? More... | |
static | validateTag ( $params, $element) |
Takes attribute names and values for a tag and the tag name and validates that the tag is allowed to be present. More... | |
static | validateTagAttributes ( $attribs, $element) |
Take an array of attribute names and values and normalize or discard illegal values for the given element type. More... | |
Public Attributes | |
const | CHAR_REFS_REGEX |
Regular expression to match various types of character references in Sanitizer::normalizeCharReferences and Sanitizer::decodeCharReferences. More... | |
const | EVIL_URI_PATTERN = '!(^|\s|\*/\s*)(javascript|vbscript)([^\w]|$)!i' |
Blacklist for evil uris like javascript: WARNING: DO NOT use this in any place that actually requires blacklisting for security reasons. More... | |
const | XMLNS_ATTRIBUTE_PATTERN = "/^xmlns:[:A-Z_a-z-.0-9]+$/" |
Static Private Member Functions | |
static | armorLinksCallback ( $matches) |
Regex replace callback for armoring links against further processing. More... | |
static | getTagAttributeCallback ( $set) |
Pick the appropriate attribute value from a match set from the attribs regex matches. More... | |
static | normalizeAttributeValue ( $text) |
Normalize whitespace and character references in an XML source- encoded text for an attribute value. More... | |
static | normalizeWhitespace ( $text) |
static | validateCodepoint ( $codepoint) |
Returns true if a given Unicode codepoint is a valid character in XML. More... | |
Static Private Attributes | |
static | $attribsRegex |
Lazy-initialised attributes regex, see getAttribsRegex() More... | |
static | $htmlEntities |
List of all named character entities defined in HTML 4.01 http://www.w3.org/TR/html4/sgml/entities.html As well as ' which is only defined starting in XHTML1. More... | |
static | $htmlEntityAliases |
Character entity aliases accepted by MediaWiki. More... | |
HTML sanitizer for MediaWiki.
Definition at line 31 of file Sanitizer.php.
|
staticprivate |
Regex replace callback for armoring links against further processing.
array | $matches |
Definition at line 1154 of file Sanitizer.php.
References $matches.
|
static |
Fetch the whitelist of acceptable attributes for a given element name.
string | $element |
Definition at line 1483 of file Sanitizer.php.
References array(), and setupAttributeWhitelist().
Referenced by validateTagAttributes().
|
static |
Pick apart some CSS and check it for forbidden or unsafe structures.
Returns a sanitized string. This sanitized string will have character references and escape sequences decoded and comments stripped (unless it is itself one valid comment, in which case the value will be passed through). If the input is just too evil, only a comment complaining about evilness will be returned.
Currently URL references, 'expression', 'tps' are forbidden.
NOTE: Despite the fact that character references are decoded, the returned string may contain character references given certain clever input strings. These character references must be escaped before the return value is embedded in HTML.
string | $value |
Definition at line 838 of file Sanitizer.php.
References $matches, $value, array(), decodeCharReferences(), StringUtils\delimiterReplace(), and utf8ToCodepoint().
Referenced by CoreParserFunctions\displaytitle(), SanitizerTest\testCssCommentsChecking(), and validateAttributes().
|
static |
string | $url |
Definition at line 1751 of file Sanitizer.php.
References $matches, array(), decodeCharReferences(), and list.
|
static |
array | $matches |
Definition at line 1798 of file Sanitizer.php.
References $matches.
|
static |
array | $matches |
Definition at line 947 of file Sanitizer.php.
References $matches, and codepointToUtf8().
|
static |
int | $codepoint |
Definition at line 1353 of file Sanitizer.php.
References validateCodepoint().
Referenced by normalizeCharReferencesCallback().
|
static |
Return UTF-8 string for a codepoint if that is a valid character reference, otherwise U+FFFD REPLACEMENT CHARACTER.
int | $codepoint |
Definition at line 1450 of file Sanitizer.php.
References codepointToUtf8(), UTF8_REPLACEMENT, and validateCodepoint().
Referenced by decodeCharReferencesCallback().
|
static |
Decode any character references, numeric or named entities, in the text and return a UTF-8 string.
string | $text |
Definition at line 1396 of file Sanitizer.php.
References array().
Referenced by checkCss(), IRCColourfulRCFeedFormatter\cleanupForIRC(), cleanUrl(), decodeTagAttributes(), UploadBase\detectScript(), Skin\doEditSectionLink(), escapeHtmlAllowEntities(), escapeId(), ImageCleanup\processRow(), stripAllTags(), SanitizerTest\testDecodeMixedComplexEntities(), SanitizerTest\testDecodeMixedEntities(), SanitizerTest\testDecodeNamedEntities(), SanitizerTest\testDecodeNumericEntities(), SanitizerTest\testInvalidAmpersand(), SanitizerTest\testInvalidEntities(), and SanitizerTest\testInvalidNumberedEntities().
|
static |
Decode any character references, numeric or named entities, in the next and normalize the resulting string.
(bug 14952)
This is useful for page titles, not for text to be displayed, MediaWiki allows HTML entities to escape normalization as a feature.
string | $text | Already normalized, containing entities |
Definition at line 1413 of file Sanitizer.php.
References $count, $wgContLang, array(), and global.
Referenced by Title\newFromText().
|
static |
string | $matches |
Definition at line 1431 of file Sanitizer.php.
References $matches, decodeChar(), and decodeEntity().
|
static |
If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD, return the UTF-8 encoding of that character.
Otherwise, returns pseudo-entity source (eg "&foo;")
string | $name |
Definition at line 1466 of file Sanitizer.php.
References $name, and codepointToUtf8().
Referenced by decodeCharReferencesCallback().
|
static |
Return an associative array of attribute names and values from a partial tag string.
Attribute names are forces to lowercase, character references are decoded to UTF-8 text.
string | $text |
Definition at line 1166 of file Sanitizer.php.
References $attribs, $value, array(), as, decodeCharReferences(), and getTagAttributeCallback().
Referenced by CoreParserFunctions\displaytitle(), fixTagAttributes(), Linker\makeKnownLinkObj(), SanitizerTest\testDecodeTagAttributes(), and validateTag().
|
static |
Encode an attribute value for HTML output.
string | $text |
Definition at line 1003 of file Sanitizer.php.
References array().
Referenced by Xml\expandAttributes(), and safeEncodeAttribute().
|
static |
Given a value, escape it so that it can be used as a CSS class and return it.
string | $class |
Definition at line 1126 of file Sanitizer.php.
References array().
Referenced by ChangesList\flag(), ChangeTags\formatSummaryRow(), SpecialStatistics\getGroupStats(), Skin\getPageClasses(), OutputPage\headElement(), SkinTemplate\prepareQuickTemplate(), EnhancedChangesList\recentChangesBlockGroup(), EnhancedChangesList\recentChangesBlockLine(), and OldChangesList\recentChangesLine().
|
static |
Given HTML input, escape with htmlspecialchars but un-escape entities.
This allows (generally harmless) entities like   to survive.
string | $html | HTML to escape |
Definition at line 1141 of file Sanitizer.php.
References $html, and decodeCharReferences().
Referenced by Linker\formatComment(), and AllmessagesTablePager\formatValue().
|
static |
Given a value, escape it so that it can be used in an id attribute and return it.
This will use HTML5 validation if $wgExperimentalHtmlIds is true, allowing anything but ASCII whitespace. Otherwise it will use HTML 4 rules, which means a narrow subset of ASCII, with bad characters escaped with lots of dots.
To ensure we don't have to bother escaping anything, we also strip ', ", & even if $wgExperimentalIds is true. TODO: Is this the best tactic? We also strip # because it upsets IE, and % because it could be ambiguous if it's part of something that looks like a percent escape (which don't work reliably in fragments cross-browser).
string | $id | id to escape |
$options | Mixed: string or array of strings (default is array()): 'noninitial': This is a non-initial fragment of an id, not a full id, so don't pay attention if the first character isn't valid at the beginning of an id. Only matters if $wgExperimentalHtmlIds is false. 'legacy': Behave the way the old HTML 4-based ID escaping worked even if $wgExperimentalHtmlIds is used, so we can generate extra anchors and links won't break. |
Definition at line 1082 of file Sanitizer.php.
References $options, array(), decodeCharReferences(), and global.
Referenced by HTMLFormField\__construct(), Skin\addToSidebarPlain(), MonoBookTemplate\customBox(), HTMLForm\displaySection(), Title\escapeFragmentForURL(), SpecialListGroupRights\execute(), VectorTemplate\execute(), HTMLRadioField\formatOptions(), AllmessagesTablePager\getRowAttrs(), InfoAction\makeHeader(), ImagePage\makeMetadataTable(), CologneBlueTemplate\quickBar(), and validateAttributes().
|
static |
Take a tag soup fragment listing an HTML element's attributes and normalize it to well-formed XML, discarding unwanted attributes.
Output is safe for further wikitext processing, with escaping of values that could trigger problems.
string | $text | |
string | $element |
Definition at line 987 of file Sanitizer.php.
References decodeTagAttributes(), safeEncodeTagAttributes(), and validateTagAttributes().
Referenced by removeHTMLtags(), SanitizerTest\testAttributeSupport(), and SanitizerTest\testDeprecatedAttributesUnaltered().
|
static |
Regular expression to match HTML/XML attribute pairs within a tag.
Allows some... latitude. Used in Sanitizer::fixTagAttributes and Sanitizer::decodeTagAttributes
Definition at line 332 of file Sanitizer.php.
References $attribsRegex.
|
staticprivate |
Pick the appropriate attribute value from a match set from the attribs regex matches.
array | $set |
MWException | when tag conditions are not met. |
Definition at line 1221 of file Sanitizer.php.
Referenced by decodeTagAttributes().
|
static |
Hack up a private DOCTYPE with HTML's standard entity declarations.
PHP 4 seemed to know these if you gave it an HTML doctype, but PHP 5.1 doesn't.
Use for passing XHTML fragments to PHP's XML parsing functions
Definition at line 1738 of file Sanitizer.php.
|
static |
int | $codepoint |
Definition at line 1366 of file Sanitizer.php.
References validateCodepoint().
Referenced by normalizeCharReferencesCallback().
|
static |
Merge two sets of HTML attributes.
Conflicting items in the second set will override those in the first, except for 'class' attributes which will be combined (if they're both strings).
array | $a | |
array | $b |
Definition at line 807 of file Sanitizer.php.
References $out.
Referenced by Linker\linkAttribs(), Linker\makeKnownLinkObj(), and TraditionalImageGallery\toHTML().
|
staticprivate |
Normalize whitespace and character references in an XML source- encoded text for an attribute value.
See http://www.w3.org/TR/REC-xml/#AVNormalize for background, but note that we're not returning the value, but are returning XML source fragments that will be slapped into output.
string | $text |
Definition at line 1255 of file Sanitizer.php.
References normalizeCharReferences().
|
static |
Ensure that any entities and character references are legal for XML and XHTML specifically.
Any stray bits will be &-escaped to result in a valid text fragment.
a. named char refs can only be < > & ", others are numericized (this way we're well-formed even without a DTD) b. any numeric char refs must be legal chars, not invalid or forbidden c. use lower cased "&#x", not "&#X" d. fix or reject non-valid attributes
string | $text |
Definition at line 1299 of file Sanitizer.php.
References array().
Referenced by CoreParserFunctions\displaytitle(), normalizeAttributeValue(), and OutputPage\setPageTitle().
|
static |
string | $matches |
Definition at line 1310 of file Sanitizer.php.
References $matches, $ret, decCharReference(), hexCharReference(), and normalizeEntity().
|
static |
If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD, return the equivalent numeric entity reference (except for the core < > & ").
If the entity is a MediaWiki-specific alias, returns the HTML equivalent. Otherwise, returns HTML-escaped text of pseudo-entity source (eg &foo;)
string | $name |
Definition at line 1336 of file Sanitizer.php.
References $name, and array().
Referenced by normalizeCharReferencesCallback().
|
static |
Normalizes whitespace in a section name, such as might be returned by Parser::stripSectionName(), for use in the id's that are used for section links.
string | $section |
Definition at line 1280 of file Sanitizer.php.
References $section.
Referenced by ApiFeedWatchlist\createFeedItem(), and Linker\formatAutocommentsCallback().
|
staticprivate |
string | $text |
Definition at line 1265 of file Sanitizer.php.
Referenced by stripAllTags().
|
static |
Remove '', and everything between.
To avoid leaving blank lines, when a comment is both preceded and followed by a newline (ignoring spaces), trim leading and trailing spaces and one of the newlines.
string | $text |
Definition at line 607 of file Sanitizer.php.
References wfProfileIn(), and wfProfileOut().
Referenced by removeHTMLtags().
|
static |
Cleans up HTML, removes dangerous tags and attributes, and removes HTML comments.
string | $text | |
callable | $processCallback | Callback to do any variable or parameter replacements in HTML attribute values |
array | $args | Arguments for the processing callback |
array | $extratags | For any extra tags to include |
array | $removetags | For any tags (default or extra) to exclude |
Definition at line 366 of file Sanitizer.php.
References $args, $params, $t, $vars, array(), as, fixTagAttributes(), global, in, list, only, removeHTMLcomments(), table, tags(), that, used, validateTag(), wfProfileIn(), wfProfileOut(), wfRestoreWarnings(), wfSuppressWarnings(), and will.
Referenced by CoreParserFunctions\displaytitle(), OutputPage\setPageTitle(), SanitizerTest\testRemoveHTMLtags(), and SanitizerTest\testRemovehtmltagsOnHtml5Tags().
|
static |
Encode an attribute value for HTML tags, with extra armoring against further wiki processing.
string | $text |
Definition at line 1024 of file Sanitizer.php.
References array(), encodeAttribute(), and wfUrlProtocols().
Referenced by safeEncodeTagAttributes().
|
static |
Build a partial tag string from an associative array of attribute names and values as returned by decodeTagAttributes.
array | $assoc_array |
Definition at line 1202 of file Sanitizer.php.
References $attribs, $value, array(), as, and safeEncodeAttribute().
Referenced by CoreParserFunctions\displaytitle(), and fixTagAttributes().
|
static |
|
static |
Take a fragment of (potentially invalid) HTML and return a version with any tags removed, encoded as plain text.
Warning: this return value must be further escaped for literal inclusion in HTML output as of 1.10!
string | $text | HTML fragment |
Definition at line 1718 of file Sanitizer.php.
References decodeCharReferences(), StringUtils\delimiterReplace(), and normalizeWhitespace().
Referenced by MWDebug\appendDebugInfoToApiResult(), CoreParserFunctions\displaytitle(), and OutputPage\setPageTitle().
|
static |
Take an array of attribute names and values and normalize or discard illegal values for the given whitelist.
array | $attribs | |
array | $whitelist | list of allowed attribute names |
Check for legal values where the DTD limits things.
Check for unique id attribute :P
Definition at line 711 of file Sanitizer.php.
References $attribs, $out, $value, array(), as, checkCss(), escapeId(), global, and wfUrlProtocols().
Referenced by validateTagAttributes().
|
staticprivate |
Returns true if a given Unicode codepoint is a valid character in XML.
int | $codepoint |
Definition at line 1380 of file Sanitizer.php.
Referenced by decCharReference(), decodeChar(), and hexCharReference().
|
static |
Does a string look like an e-mail address?
This validates an email address using an HTML5 specification found at: http://www.whatwg.org/html/states-of-the-type-attribute.html#valid-e-mail-address Which as of 2011-01-24 says:
A valid e-mail address is a string that matches the ABNF production 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section 3.5.
This function is an implementation of the specification as requested in bug 22449.
Client-side forms will use the same standard validation rules via JS or HTML 5 validation; additional restrictions can be enforced server-side by extensions via the 'isValidEmailAddr' hook.
Note that this validation doesn't 100% match RFC 2822, but is believed to be liberal enough for wide use. Some invalid addresses will still pass validation here.
string | $addr | E-mail address |
Definition at line 1830 of file Sanitizer.php.
References array(), and wfRunHooks().
Referenced by LoginForm\addNewAccount(), LoginForm\addNewAccountInternal(), SpecialChangeEmail\attemptChange(), Autopromote\checkCondition(), SanitizerValidateEmailTest\checkEmail(), ApiCreateAccount\execute(), EmailConfirmation\execute(), User\isEmailConfirmed(), User\isValidEmailAddr(), and SpecialPasswordReset\onSubmit().
|
static |
Takes attribute names and values for a tag and the tag name and validates that the tag is allowed to be present.
This DOES NOT validate the attributes, nor does it validate the tags themselves. This method only handles the special circumstances where we may want to allow a tag within content but ONLY when it has specific attributes set.
string | $params | |
string | $element |
Definition at line 655 of file Sanitizer.php.
References $params, and decodeTagAttributes().
Referenced by removeHTMLtags().
|
static |
Take an array of attribute names and values and normalize or discard illegal values for the given element type.
array | $attribs | |
string | $element |
Check for legal values where the DTD limits things.
Check for unique id attribute :P
Definition at line 691 of file Sanitizer.php.
References $attribs, attributeWhitelist(), and validateAttributes().
Referenced by fixTagAttributes(), and CoreTagHooks\pre().
|
staticprivate |
Lazy-initialised attributes regex, see getAttribsRegex()
Definition at line 325 of file Sanitizer.php.
Referenced by getAttribsRegex().
|
staticprivate |
List of all named character entities defined in HTML 4.01 http://www.w3.org/TR/html4/sgml/entities.html As well as ' which is only defined starting in XHTML1.
Definition at line 58 of file Sanitizer.php.
|
staticprivate |
Character entity aliases accepted by MediaWiki.
Definition at line 317 of file Sanitizer.php.
const Sanitizer::CHAR_REFS_REGEX |
Regular expression to match various types of character references in Sanitizer::normalizeCharReferences and Sanitizer::decodeCharReferences.
Definition at line 36 of file Sanitizer.php.
const Sanitizer::EVIL_URI_PATTERN = '!(^|\s|\*/\s*)(javascript|vbscript)([^\w]|$)!i' |
Blacklist for evil uris like javascript: WARNING: DO NOT use this in any place that actually requires blacklisting for security reasons.
There are NUMEROUS1 ways to bypass blacklisting, the only way to be secure from javascript: uri based xss vectors is to whitelist things that you know are safe and deny everything else.
Definition at line 50 of file Sanitizer.php.
const Sanitizer::XMLNS_ATTRIBUTE_PATTERN = "/^xmlns:[:A-Z_a-z-.0-9]+$/" |
Definition at line 51 of file Sanitizer.php.