ILIAS  release_6 Revision v6.24-5-g0c8bfefb3b8
Sanitizer Class Reference
+ Collaboration diagram for Sanitizer:

Static Public Member Functions

static removeHTMLtags ($text, $processCallback=null, $args=array())
 Cleans up HTML, removes dangerous tags and attributes, and removes HTML comments. More...
 
static removeHTMLcomments ($text)
 Remove '', and everything between. 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...
 
static checkCss ($value)
 Pick apart some CSS and check it for forbidden or unsafe structures. 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 encodeAttribute ($text)
 Encode an attribute value for HTML output. More...
 
static safeEncodeAttribute ($text)
 Encode an attribute value for HTML tags, with extra armoring against further wiki processing. More...
 
static escapeId ($id)
 Given a value escape it so that it can be used in an id attribute and return it, this does not validate the value however (see first link) More...
 
static escapeClass ($class)
 Given a value, escape it so that it can be used as a CSS class and return it. More...
 
static decodeTagAttributes ($text)
 Return an associative array of attribute names and values from a partial tag string. 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 named entity reference as is. More...
 
static decCharReference ($codepoint)
 
static hexCharReference ($codepoint)
 
static decodeCharReferences ($text)
 Decode any character references, numeric or named entities, in the text and return a UTF-8 string. More...
 
static decodeCharReferencesCallback ($matches)
 
static decodeChar ($codepoint)
 Return UTF-8 string for a codepoint if that is a valid character reference, otherwise U+FFFD REPLACEMENT CHARACTER. More...
 
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 attributeWhitelist ($element)
 Fetch the whitelist of acceptable attributes for a given element name. More...
 
static setupAttributeWhitelist ()
 
static stripAllTags ($text)
 Take a fragment of (potentially invalid) HTML and return a version with any tags removed, encoded as plain text. More...
 
static hackDocType ()
 Hack up a private DOCTYPE with HTML's standard entity declarations. More...
 
static cleanUrl ($url, $hostname=true)
 

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 MW_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...
 

Detailed Description

Definition at line 332 of file Sanitizer.php.

Member Function Documentation

◆ armorLinksCallback()

static Sanitizer::armorLinksCallback (   $matches)
staticprivate

Regex replace callback for armoring links against further processing.

Parameters
array$matches
Returns
string

Definition at line 799 of file Sanitizer.php.

804 {

◆ attributeWhitelist()

static Sanitizer::attributeWhitelist (   $element)
static

Fetch the whitelist of acceptable attributes for a given element name.

Parameters
string$element
Returns
array

Definition at line 1091 of file Sanitizer.php.

1096 {
1097 static $list;
1098 if (!isset($list)) {
1100 }
static setupAttributeWhitelist()
Definition: Sanitizer.php:1106

◆ checkCss()

static Sanitizer::checkCss (   $value)
static

Pick apart some CSS and check it for forbidden or unsafe structures.

Returns a sanitized string, or false if it was just too evil.

Currently URL references, 'expression', 'tps' are forbidden.

Parameters
string$value
Returns
mixed

Definition at line 621 of file Sanitizer.php.

626 {
627 $stripped = Sanitizer::decodeCharReferences($value);
628
629 // Remove any comments; IE gets token splitting wrong
630 $stripped = StringUtils::delimiterReplace('/*', '*/', ' ', $stripped);
631
632 $value = $stripped;
633
634 // ... and continue checks
635 $stripped = preg_replace_callback(
636 '!\\\\([0-9A-Fa-f]{1,6})[ \\n\\r\\t\\f]?!',
637 function ($hit) {
638 return codepointToUtf8(hexdec($hit[1]));
639 },
640 $stripped
641 );
642 $stripped = str_replace('\\', '', $stripped);
643 if (preg_match(
644 '/(?:expression|tps*:\/\/|url\\s*\‍().*/is',
645 $stripped
646 )) {
647 # haxx0r
648 return false;
codepointToUtf8($codepoint)
Return UTF-8 sequence for a given Unicode code point.
static decodeCharReferences($text)
Decode any character references, numeric or named entities, in the text and return a UTF-8 string.
Definition: Sanitizer.php:1018

◆ cleanUrl()

static Sanitizer::cleanUrl (   $url,
  $hostname = true 
)
static

NOTE: The original preg_replace/e IMPLICITLY adds a forward-slash on double quotes This could be a bug, but we will just mimic this behaviour 1:1 for now.

Definition at line 1288 of file Sanitizer.php.

1293 {
1294 # Normalize any HTML entities in input. They will be
1295 # re-escaped by makeExternalLink().
1296
1298
1299 # Escape any control characters introduced by the above step
1300 $url = preg_replace_callback(
1301 '/[\][<>"\\x00-\\x20\\x7F]/',
1302 function ($hit) {
1303 if ($hit[0] === '"') {
1309 return urlencode('\\"');
1310 } else {
1311 return urlencode($hit[0]);
1312 }
1313 },
1314 $url
1315 );
1316
1317 # Validate hostname portion
1318 $matches = array();
1319 if (preg_match('!^([^:]+:)(//[^/]+)?(.*)$!iD', $url, $matches)) {
1320 list( /* $whole */, $protocol, $host, $rest) = $matches;
1321
1322 // Characters that will be ignored in IDNs.
1323 // http://tools.ietf.org/html/3454#section-3.1
1324 // Strip them before further processing so blacklists and such work.
1325 $strip = "/
1326 \\s| # general whitespace
1327 \xc2\xad| # 00ad SOFT HYPHEN
1328 \xe1\xa0\x86| # 1806 MONGOLIAN TODO SOFT HYPHEN
1329 \xe2\x80\x8b| # 200b ZERO WIDTH SPACE
1330 \xe2\x81\xa0| # 2060 WORD JOINER
1331 \xef\xbb\xbf| # feff ZERO WIDTH NO-BREAK SPACE
1332 \xcd\x8f| # 034f COMBINING GRAPHEME JOINER
1333 \xe1\xa0\x8b| # 180b MONGOLIAN FREE VARIATION SELECTOR ONE
1334 \xe1\xa0\x8c| # 180c MONGOLIAN FREE VARIATION SELECTOR TWO
1335 \xe1\xa0\x8d| # 180d MONGOLIAN FREE VARIATION SELECTOR THREE
1336 \xe2\x80\x8c| # 200c ZERO WIDTH NON-JOINER
1337 \xe2\x80\x8d| # 200d ZERO WIDTH JOINER
1338 [\xef\xb8\x80-\xef\xb8\x8f] # fe00-fe00f VARIATION SELECTOR-1-16
1339 /xuD";
1340
1341 $host = preg_replace($strip, '', $host);
1342
1343 // @fixme: validate hostnames here
1344
1345 return $protocol . $host . $rest;
$rest
Definition: goto.php:46
$url

◆ decCharReference()

static Sanitizer::decCharReference (   $codepoint)
static

Definition at line 974 of file Sanitizer.php.

979 {
980 $point = intval($codepoint);
981 if (Sanitizer::validateCodepoint($point)) {
982 return sprintf('&#%d;', $point);
static validateCodepoint($codepoint)
Returns true if a given Unicode codepoint is a valid character in XML.
Definition: Sanitizer.php:999

◆ decodeChar()

static Sanitizer::decodeChar (   $codepoint)
static

Return UTF-8 string for a codepoint if that is a valid character reference, otherwise U+FFFD REPLACEMENT CHARACTER.

Parameters
int$codepoint
Returns
string

Definition at line 1053 of file Sanitizer.php.

1058 {
1059 if (Sanitizer::validateCodepoint($codepoint)) {
1060 return codepointToUtf8($codepoint);

◆ decodeCharReferences()

static Sanitizer::decodeCharReferences (   $text)
static

Decode any character references, numeric or named entities, in the text and return a UTF-8 string.

Parameters
string$text
Returns
string

Definition at line 1018 of file Sanitizer.php.

1023 {
1024 return preg_replace_callback(
const MW_CHAR_REFS_REGEX
Regular expression to match various types of character references in Sanitizer::normalizeCharReferenc...
Definition: Sanitizer.php:30

Referenced by Title\escapeFragmentForURL(), and Title\newFromText().

+ Here is the caller graph for this function:

◆ decodeCharReferencesCallback()

static Sanitizer::decodeCharReferencesCallback (   $matches)
static
Parameters
string$matches
Returns
string

Definition at line 1031 of file Sanitizer.php.

1036 {
1037 if ($matches[1] != '') {
1038 return Sanitizer::decodeEntity($matches[1]);
1039 } elseif ($matches[2] != '') {
1040 return Sanitizer::decodeChar(intval($matches[2]));
1041 } elseif ($matches[3] != '') {
1042 return Sanitizer::decodeChar(hexdec($matches[3]));
1043 } elseif ($matches[4] != '') {
1044 return Sanitizer::decodeChar(hexdec($matches[4]));
static decodeChar($codepoint)
Return UTF-8 string for a codepoint if that is a valid character reference, otherwise U+FFFD REPLACEM...
Definition: Sanitizer.php:1053
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 chara...
Definition: Sanitizer.php:1070

◆ decodeEntity()

static Sanitizer::decodeEntity (   $name)
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;)

Parameters
string$name
Returns
string

Definition at line 1070 of file Sanitizer.php.

1075 {
1077
1078 if (isset($wgHtmlEntityAliases[$name])) {
1080 }
1081 if (isset($wgHtmlEntities[$name])) {
global $wgHtmlEntities
List of all named character entities defined in HTML 4.01 http://www.w3.org/TR/html4/sgml/entities....
Definition: Sanitizer.php:63
global $wgHtmlEntityAliases
Character entity aliases accepted by MediaWiki.
Definition: Sanitizer.php:321
if($format !==null) $name
Definition: metadata.php:230

◆ decodeTagAttributes()

static Sanitizer::decodeTagAttributes (   $text)
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.

Parameters
string
Returns
array

Definition at line 812 of file Sanitizer.php.

817 {
818 $attribs = array();
819
820 if (trim($text) == '') {
821 return $attribs;
822 }
823
824 $pairs = array();
825 if (!preg_match_all(
827 $text,
828 $pairs,
829 PREG_SET_ORDER
830 )) {
831 return $attribs;
832 }
833
834 foreach ($pairs as $set) {
835 $attribute = strtolower($set[1]);
837
838 // Normalize whitespace
839 $value = preg_replace('/[\t\r\n ]+/', ' ', $value);
840 $value = trim($value);
841
842 // Decode character references
const MW_ATTRIBS_REGEX
Definition: Sanitizer.php:44
static getTagAttributeCallback($set)
Pick the appropriate attribute value from a match set from the MW_ATTRIBS_REGEX matches.
Definition: Sanitizer.php:852

◆ encodeAttribute()

static Sanitizer::encodeAttribute (   $text)
static

Encode an attribute value for HTML output.

Parameters
$text
Returns
HTML-encoded text fragment

Definition at line 695 of file Sanitizer.php.

700 {
701 $encValue = htmlspecialchars($text);
702
703 // Whitespace is normalized during attribute decoding,
704 // so if we've been passed non-spaces we must encode them
705 // ahead of time or they won't be preserved.
706 $encValue = strtr($encValue, array(
707 "\n" => '&#10;',
708 "\r" => '&#13;',
709 "\t" => '&#9;',

◆ escapeClass()

static Sanitizer::escapeClass (   $class)
static

Given a value, escape it so that it can be used as a CSS class and return it.

Todo:
For extra validity, input should be validated UTF-8.
See also
http://www.w3.org/TR/CSS21/syndata.html Valid characters/format
Parameters
string$class
Returns
string

Definition at line 783 of file Sanitizer.php.

788 {
789 // Convert ugly stuff to underscores and kill underscores in ugly places
790 return rtrim(preg_replace(
791 array('/(^[0-9\\-])|[\\x00-\\x20!"#$%&\'()*+,.\\/:;<=>?@[\\]^`{|}~]|\\xC2\\xA0/','/_+/'),

◆ escapeId()

static Sanitizer::escapeId (   $id)
static

Given a value escape it so that it can be used in an id attribute and return it, this does not validate the value however (see first link)

See also
http://www.w3.org/TR/html401/types.html#type-name Valid characters in the id and name attributes
http://www.w3.org/TR/html401/struct/links.html#h-12.2.3 Anchors with the id attribute
Parameters
string$id
Returns
string

Definition at line 760 of file Sanitizer.php.

765 {
766 static $replace = array(
767 '%3A' => ':',
768 '%' => '.'
769 );
770

◆ fixTagAttributes()

static Sanitizer::fixTagAttributes (   $text,
  $element 
)
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.

  • Normalizes attribute names to lowercase
  • Discards attributes not on a whitelist for the given element
  • Turns broken or invalid entities into plaintext
  • Double-quotes all attribute values
  • Attributes without values are given the name as attribute
  • Double attributes are discarded
  • Unsafe style attributes are discarded
  • Prepends space if there are attributes.
Parameters
string$text
string$element
Returns
string

Definition at line 669 of file Sanitizer.php.

674 {
675 if (trim($text) == '') {
676 return '';
677 }
678
681 $element
682 );
683
684 $attribs = array();
685 foreach ($stripped as $attribute => $value) {
686 $encAttribute = htmlspecialchars($attribute);
687 $encValue = Sanitizer::safeEncodeAttribute($value);
688
static decodeTagAttributes($text)
Return an associative array of attribute names and values from a partial tag string.
Definition: Sanitizer.php:812
static safeEncodeAttribute($text)
Encode an attribute value for HTML tags, with extra armoring against further wiki processing.
Definition: Sanitizer.php:717
static validateTagAttributes($attribs, $element)
Take an array of attribute names and values and normalize or discard illegal values for the given ele...
Definition: Sanitizer.php:583

◆ getTagAttributeCallback()

static Sanitizer::getTagAttributeCallback (   $set)
staticprivate

Pick the appropriate attribute value from a match set from the MW_ATTRIBS_REGEX matches.

Parameters
array$set
Returns
string

Definition at line 852 of file Sanitizer.php.

857 {
858 if (isset($set[6])) {
859 # Illegal #XXXXXX color with no quotes.
860 return $set[6];
861 } elseif (isset($set[5])) {
862 # No quotes.
863 return $set[5];
864 } elseif (isset($set[4])) {
865 # Single-quoted
866 return $set[4];
867 } elseif (isset($set[3])) {
868 # Double-quoted
869 return $set[3];
870 } elseif (!isset($set[2])) {
871 # In XHTML, attributes must have a value.
872 # For 'reduced' form, return explicitly the attribute name here.
873 return $set[1];

◆ hackDocType()

static Sanitizer::hackDocType ( )
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

Returns
string

Definition at line 1277 of file Sanitizer.php.

1282 {
1283 global $wgHtmlEntities;
1284 $out = "<!DOCTYPE html [\n";
1285 foreach ($wgHtmlEntities as $entity => $codepoint) {
1286 $out .= "<!ENTITY $entity \"&#$codepoint;\">";

◆ hexCharReference()

static Sanitizer::hexCharReference (   $codepoint)
static

Definition at line 984 of file Sanitizer.php.

989 {
990 $point = hexdec($codepoint);
991 if (Sanitizer::validateCodepoint($point)) {
992 return sprintf('&#x%x;', $point);

◆ normalizeAttributeValue()

static Sanitizer::normalizeAttributeValue (   $text)
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.

Parameters
string$text
Returns
string

Definition at line 887 of file Sanitizer.php.

892 {
893 return str_replace(
894 '"',
895 '&quot;',
896 self::normalizeWhitespace(

◆ normalizeCharReferences()

static Sanitizer::normalizeCharReferences (   $text)
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. any named char refs must be known in XHTML b. any numeric char refs must be legal chars, not invalid or forbidden c. use &#x, not &#X d. fix or reject non-valid attributes

Parameters
string$text
Returns
string

Definition at line 921 of file Sanitizer.php.

926 {
927 return preg_replace_callback(

◆ normalizeCharReferencesCallback()

static Sanitizer::normalizeCharReferencesCallback (   $matches)
static
Parameters
string$matches
Returns
string

Definition at line 933 of file Sanitizer.php.

938 {
939 $ret = null;
940 if ($matches[1] != '') {
941 $ret = Sanitizer::normalizeEntity($matches[1]);
942 } elseif ($matches[2] != '') {
943 $ret = Sanitizer::decCharReference($matches[2]);
944 } elseif ($matches[3] != '') {
945 $ret = Sanitizer::hexCharReference($matches[3]);
946 } elseif ($matches[4] != '') {
947 $ret = Sanitizer::hexCharReference($matches[4]);
948 }
949 if (is_null($ret)) {
950 return htmlspecialchars($matches[0]);
static normalizeEntity($name)
If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD, return the named entity reference as is...
Definition: Sanitizer.php:962
static decCharReference($codepoint)
Definition: Sanitizer.php:974
static hexCharReference($codepoint)
Definition: Sanitizer.php:984
$ret
Definition: parser.php:6

◆ normalizeEntity()

static Sanitizer::normalizeEntity (   $name)
static

If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD, return the named entity reference as is.

If the entity is a MediaWiki-specific alias, returns the HTML equivalent. Otherwise, returns HTML-escaped text of pseudo-entity source (eg &foo;)

Parameters
string$name
Returns
string

Definition at line 962 of file Sanitizer.php.

967 {
969 if (isset($wgHtmlEntityAliases[$name])) {
970 return "&{$wgHtmlEntityAliases[$name]};";
971 } elseif (isset($wgHtmlEntities[$name])) {
972 return "&$name;";

◆ normalizeWhitespace()

static Sanitizer::normalizeWhitespace (   $text)
staticprivate

Definition at line 898 of file Sanitizer.php.

903 {
904 return preg_replace(
905 '/\r\n|[\x20\x0d\x0a\x09]/',

◆ removeHTMLcomments()

static Sanitizer::removeHTMLcomments (   $text)
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.

Parameters
string$text
Returns
string

Definition at line 533 of file Sanitizer.php.

538 {
539 wfProfileIn(__METHOD__);
540 while (($start = strpos($text, '<!--')) !== false) {
541 $end = strpos($text, '-->', $start + 4);
542 if ($end === false) {
543 # Unterminated comment; bail out
544 break;
545 }
546
547 $end += 3;
548
549 # Trim space and newline if the comment is both
550 # preceded and followed by a newline
551 $spaceStart = max($start - 1, 0);
552 $spaceLen = $end - $spaceStart;
553 while (substr($text, $spaceStart, 1) === ' ' && $spaceStart > 0) {
554 $spaceStart--;
555 $spaceLen++;
556 }
557 while (substr($text, $spaceStart + $spaceLen, 1) === ' ') {
558 $spaceLen++;
559 }
560 if (substr($text, $spaceStart, 1) === "\n" and substr($text, $spaceStart + $spaceLen, 1) === "\n") {
561 # Remove the comment, leading and trailing
562 # spaces, and leave only one newline.
563 $text = substr_replace($text, "\n", $spaceStart, $spaceLen + 1);
564 } else {
565 # Remove just the comment.
566 $text = substr_replace($text, '', $start, $end - $start);
567 }

◆ removeHTMLtags()

static Sanitizer::removeHTMLtags (   $text,
  $processCallback = null,
  $args = array() 
)
static

Cleans up HTML, removes dangerous tags and attributes, and removes HTML comments.

Parameters
string$text
callback$processCallbackto do any variable or parameter replacements in HTML attribute values
array$argsfor the processing callback
Returns
string

Definition at line 343 of file Sanitizer.php.

348 {
349 global $wgUseTidy;
350
351 static $htmlpairs, $htmlsingle, $htmlsingleonly, $htmlnest, $tabletags,
352 $htmllist, $listtags, $htmlsingleallowed, $htmlelements, $staticInitialised;
353
354 wfProfileIn(__METHOD__);
355
356 if (!$staticInitialised) {
357 $htmlpairs = array( # Tags that must be closed
358 'b', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
359 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
360 'strike', 'strong', 'tt', 'var', 'div', 'center',
361 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
362 'ruby', 'rt' , 'rb' , 'rp', 'p', 'span', 'u'
363 );
364 $htmlsingle = array(
365 'br', 'hr', 'li', 'dt', 'dd'
366 );
367 $htmlsingleonly = array( # Elements that cannot have close tags
368 'br', 'hr'
369 );
370 $htmlnest = array( # Tags that can be nested--??
371 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
372 'dl', 'font', 'big', 'small', 'sub', 'sup', 'span'
373 );
374 $tabletags = array( # Can only appear inside table, we will close them
375 'td', 'th', 'tr',
376 );
377 $htmllist = array( # Tags used by list
378 'ul','ol',
379 );
380 $listtags = array( # Tags that can appear in a list
381 'li',
382 );
383
384 $htmlsingleallowed = array_merge($htmlsingle, $tabletags);
385 $htmlelements = array_merge($htmlsingle, $htmlpairs, $htmlnest);
386
387 # Convert them all to hashtables for faster lookup
388 $vars = array( 'htmlpairs', 'htmlsingle', 'htmlsingleonly', 'htmlnest', 'tabletags',
389 'htmllist', 'listtags', 'htmlsingleallowed', 'htmlelements' );
390 foreach ($vars as $var) {
391 $$var = array_flip($$var);
392 }
393 $staticInitialised = true;
394 }
395
396 # Remove HTML comments
397 $text = Sanitizer::removeHTMLcomments($text);
398 $bits = explode('<', $text);
399 $text = str_replace('>', '&gt;', array_shift($bits));
400 if (!$wgUseTidy) {
401 $tagstack = $tablestack = array();
402 foreach ($bits as $x) {
403 $regs = array();
404 if (preg_match('!^(/?)(\\w+)([^>]*?)(/{0,1}>)([^<]*)$!', $x, $regs)) {
405 list( /* $qbar */, $slash, $t, $params, $brace, $rest) = $regs;
406 } else {
407 $slash = $t = $params = $brace = $rest = null;
408 }
409
410 $badtag = 0 ;
411 if (isset($htmlelements[$t = strtolower($t)])) {
412 # Check our stack
413 if ($slash) {
414 # Closing a tag...
415 if (isset($htmlsingleonly[$t])) {
416 $badtag = 1;
417 } elseif (($ot = @array_pop($tagstack)) != $t) {
418 if (isset($htmlsingleallowed[$ot])) {
419 # Pop all elements with an optional close tag
420 # and see if we find a match below them
421 $optstack = array();
422 array_push($optstack, $ot);
423 while ((($ot = @array_pop($tagstack)) != $t) &&
424 isset($htmlsingleallowed[$ot])) {
425 array_push($optstack, $ot);
426 }
427 if ($t != $ot) {
428 # No match. Push the optinal elements back again
429 $badtag = 1;
430 while ($ot = @array_pop($optstack)) {
431 array_push($tagstack, $ot);
432 }
433 }
434 } else {
435 @array_push($tagstack, $ot);
436 # <li> can be nested in <ul> or <ol>, skip those cases:
437 if (!(isset($htmllist[$ot]) && isset($listtags[$t]))) {
438 $badtag = 1;
439 }
440 }
441 } else {
442 if ($t == 'table') {
443 $tagstack = array_pop($tablestack);
444 }
445 }
446 $newparams = '';
447 } else {
448 # Keep track for later
449 if (isset($tabletags[$t]) &&
450 !in_array('table', $tagstack)) {
451 $badtag = 1;
452 } elseif (in_array($t, $tagstack) &&
453 !isset($htmlnest [$t ])) {
454 $badtag = 1 ;
455 # Is it a self closed htmlpair ? (bug 5487)
456 } elseif ($brace == '/>' &&
457 isset($htmlpairs[$t])) {
458 $badtag = 1;
459 } elseif (isset($htmlsingleonly[$t])) {
460 # Hack to force empty tag for uncloseable elements
461 $brace = '/>';
462 } elseif (isset($htmlsingle[$t])) {
463 # Hack to not close $htmlsingle tags
464 $brace = null;
465 } elseif (isset($tabletags[$t])
466 && in_array($t, $tagstack)) {
467 // New table tag but forgot to close the previous one
468 $text .= "</$t>";
469 } else {
470 if ($t == 'table') {
471 array_push($tablestack, $tagstack);
472 $tagstack = array();
473 }
474 array_push($tagstack, $t);
475 }
476
477 # Replace any variables or template parameters with
478 # plaintext results.
479 if (is_callable($processCallback)) {
480 call_user_func_array($processCallback, array( &$params, $args ));
481 }
482
483 # Strip non-approved attributes from the tag
484 $newparams = Sanitizer::fixTagAttributes($params, $t);
485 }
486 if (!$badtag) {
487 $rest = str_replace('>', '&gt;', $rest);
488 $close = ($brace == '/>' && !$slash) ? ' /' : '';
489 $text .= "<$slash$t$newparams$close>$rest";
490 continue;
491 }
492 }
493 $text .= '&lt;' . str_replace('>', '&gt;', $x);
494 }
495 # Close off any remaining tags
496 while (is_array($tagstack) && ($t = array_pop($tagstack))) {
497 $text .= "</$t>\n";
498 if ($t == 'table') {
499 $tagstack = array_pop($tablestack);
500 }
501 }
502 } else {
503 # this might be possible using tidy itself
504 foreach ($bits as $x) {
505 preg_match(
506 '/^(\\/?)(\\w+)([^>]*?)(\\/{0,1}>)([^<]*)$/',
507 $x,
508 $regs
509 );
510 @list( /* $qbar */, $slash, $t, $params, $brace, $rest) = $regs;
511 if (isset($htmlelements[$t = strtolower($t)])) {
512 if (is_callable($processCallback)) {
513 call_user_func_array($processCallback, array( &$params, $args ));
514 }
515 $newparams = Sanitizer::fixTagAttributes($params, $t);
516 $rest = str_replace('>', '&gt;', $rest);
517 $text .= "<$slash$t$newparams$brace$rest";
518 } else {
519 $text .= '&lt;' . str_replace('>', '&gt;', $x);
520 }
521 }
static removeHTMLcomments($text)
Remove '', and everything between.
Definition: Sanitizer.php:533
static fixTagAttributes($text, $element)
Take a tag soup fragment listing an HTML element's attributes and normalize it to well-formed XML,...
Definition: Sanitizer.php:669
close()
Definition: close.php:2

◆ safeEncodeAttribute()

static Sanitizer::safeEncodeAttribute (   $text)
static

Encode an attribute value for HTML tags, with extra armoring against further wiki processing.

Parameters
$text
Returns
HTML-encoded text fragment

Definition at line 717 of file Sanitizer.php.

722 {
723 $encValue = Sanitizer::encodeAttribute($text);
724
725 # Templates and links may be expanded in later parsing,
726 # creating invalid or dangerous output. Suppress this.
727 $encValue = strtr($encValue, array(
728 '<' => '&lt;', // This should never happen,
729 '>' => '&gt;', // we've received invalid input
730 '"' => '&quot;', // which should have been escaped.
731 '{' => '&#123;',
732 '[' => '&#91;',
733 "''" => '&#39;&#39;',
734 'ISBN' => '&#73;SBN',
735 'RFC' => '&#82;FC',
736 'PMID' => '&#80;MID',
737 '|' => '&#124;',
738 '__' => '&#95;_',
739 ));
740
741 # Stupid hack
742 $encValue = preg_replace_callback(
743 '/(' . wfUrlProtocols() . ')/',
744 array( 'Sanitizer', 'armorLinksCallback' ),
static encodeAttribute($text)
Encode an attribute value for HTML output.
Definition: Sanitizer.php:695
if(!defined( 'UTF8_REPLACEMENT')) wfUrlProtocols()
Returns a regular expression of url protocols.

◆ setupAttributeWhitelist()

static Sanitizer::setupAttributeWhitelist ( )
static
Todo:
Document it a bit
Returns
array

Definition at line 1106 of file Sanitizer.php.

1111 {
1112 $common = array( 'id', 'class', 'lang', 'dir', 'title', 'style' );
1113 $block = array_merge($common, array( 'align' ));
1114 $tablealign = array( 'align', 'char', 'charoff', 'valign' );
1115 $tablecell = array( 'abbr',
1116 'axis',
1117 'headers',
1118 'scope',
1119 'rowspan',
1120 'colspan',
1121 'nowrap', # deprecated
1122 'width', # deprecated
1123 'height', # deprecated
1124 'bgcolor' # deprecated
1125 );
1126
1127 # Numbers refer to sections in HTML 4.01 standard describing the element.
1128 # See: http://www.w3.org/TR/html4/
1129 $whitelist = array(
1130 # 7.5.4
1131 'div' => $block,
1132 'center' => $common, # deprecated
1133 'span' => $block, # ??
1134
1135 # 7.5.5
1136 'h1' => $block,
1137 'h2' => $block,
1138 'h3' => $block,
1139 'h4' => $block,
1140 'h5' => $block,
1141 'h6' => $block,
1142
1143 # 7.5.6
1144 # address
1145
1146 # 8.2.4
1147 # bdo
1148
1149 # 9.2.1
1150 'em' => $common,
1151 'strong' => $common,
1152 'cite' => $common,
1153 # dfn
1154 'code' => $common,
1155 # samp
1156 # kbd
1157 'var' => $common,
1158 # abbr
1159 # acronym
1160
1161 # 9.2.2
1162 'blockquote' => array_merge($common, array( 'cite' )),
1163 # q
1164
1165 # 9.2.3
1166 'sub' => $common,
1167 'sup' => $common,
1168
1169 # 9.3.1
1170 'p' => $block,
1171
1172 # 9.3.2
1173 'br' => array( 'id', 'class', 'title', 'style', 'clear' ),
1174
1175 # 9.3.4
1176 'pre' => array_merge($common, array( 'width' )),
1177
1178 # 9.4
1179 'ins' => array_merge($common, array( 'cite', 'datetime' )),
1180 'del' => array_merge($common, array( 'cite', 'datetime' )),
1181
1182 # 10.2
1183 'ul' => array_merge($common, array( 'type' )),
1184 'ol' => array_merge($common, array( 'type', 'start' )),
1185 'li' => array_merge($common, array( 'type', 'value' )),
1186
1187 # 10.3
1188 'dl' => $common,
1189 'dd' => $common,
1190 'dt' => $common,
1191
1192 # 11.2.1
1193 'table' => array_merge(
1194 $common,
1195 array( 'summary', 'width', 'border', 'frame',
1196 'rules', 'cellspacing', 'cellpadding',
1197 'align', 'bgcolor',
1198 )
1199 ),
1200
1201 # 11.2.2
1202 'caption' => array_merge($common, array( 'align' )),
1203
1204 # 11.2.3
1205 'thead' => array_merge($common, $tablealign),
1206 'tfoot' => array_merge($common, $tablealign),
1207 'tbody' => array_merge($common, $tablealign),
1208
1209 # 11.2.4
1210 'colgroup' => array_merge($common, array( 'span', 'width' ), $tablealign),
1211 'col' => array_merge($common, array( 'span', 'width' ), $tablealign),
1212
1213 # 11.2.5
1214 'tr' => array_merge($common, array( 'bgcolor' ), $tablealign),
1215
1216 # 11.2.6
1217 'td' => array_merge($common, $tablecell, $tablealign),
1218 'th' => array_merge($common, $tablecell, $tablealign),
1219
1220 # 15.2.1
1221 'tt' => $common,
1222 'b' => $common,
1223 'i' => $common,
1224 'big' => $common,
1225 'small' => $common,
1226 'strike' => $common,
1227 's' => $common,
1228 'u' => $common,
1229
1230 # 15.2.2
1231 'font' => array_merge($common, array( 'size', 'color', 'face' )),
1232 # basefont
1233
1234 # 15.3
1235 'hr' => array_merge($common, array( 'noshade', 'size', 'width' )),
1236
1237 # XHTML Ruby annotation text module, simple ruby only.
1238 # http://www.w3c.org/TR/ruby/
1239 'ruby' => $common,
1240 # rbc
1241 # rtc
1242 'rb' => $common,
1243 'rt' => $common, #array_merge( $common, array( 'rbspan' ) ),
static http()
Fetches the global http state from ILIAS.
simple()
Definition: simple.php:2

◆ stripAllTags()

static Sanitizer::stripAllTags (   $text)
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!

Parameters
string$textHTML fragment
Returns
string

Definition at line 1255 of file Sanitizer.php.

1260 {
1261 # Actual <tags>
1262 $text = StringUtils::delimiterReplace('<', '>', '', $text);
1263
1264 # Normalize &entities and whitespace
1265 $text = self::decodeCharReferences($text);

◆ validateCodepoint()

static Sanitizer::validateCodepoint (   $codepoint)
staticprivate

Returns true if a given Unicode codepoint is a valid character in XML.

Parameters
int$codepoint
Returns
bool

Definition at line 999 of file Sanitizer.php.

1004 {
1005 return ($codepoint == 0x09)
1006 || ($codepoint == 0x0a)
1007 || ($codepoint == 0x0d)

◆ validateTagAttributes()

static Sanitizer::validateTagAttributes (   $attribs,
  $element 
)
static

Take an array of attribute names and values and normalize or discard illegal values for the given element type.

  • Discards attributes not on a whitelist for the given element
  • Unsafe style attributes are discarded
Parameters
array$attribs
string$element
Returns
array
Todo:

Check for legal values where the DTD limits things.

Check for unique id attribute :P

Definition at line 583 of file Sanitizer.php.

585 :P
586 */
587 public static function validateTagAttributes($attribs, $element)
588 {
589 $whitelist = array_flip(Sanitizer::attributeWhitelist($element));
590 $out = array();
591 foreach ($attribs as $attribute => $value) {
592 if (!isset($whitelist[$attribute])) {
593 continue;
594 }
595 # Strip javascript "expression" from stylesheets.
596 # http://msdn.microsoft.com/workshop/author/dhtml/overview/recalc.asp
597 if ($attribute == 'style') {
598 $value = Sanitizer::checkCss($value);
599 if ($value === false) {
600 # haxx0r
601 continue;
602 }
603 }
604
605 if ($attribute === 'id') {
606 $value = Sanitizer::escapeId($value);
607 }
608
609 // If this attribute was previously set, override it.
610 // Output should only have one attribute of each name.
static escapeId($id)
Given a value escape it so that it can be used in an id attribute and return it, this does not valida...
Definition: Sanitizer.php:760
static checkCss($value)
Pick apart some CSS and check it for forbidden or unsafe structures.
Definition: Sanitizer.php:621
static attributeWhitelist($element)
Fetch the whitelist of acceptable attributes for a given element name.
Definition: Sanitizer.php:1091

The documentation for this class was generated from the following file: