Preserve whitespace in search index text content
[lhc/web/wiklou.git] / includes / parser / Sanitizer.php
1 <?php
2 /**
3 * HTML sanitizer for %MediaWiki.
4 *
5 * Copyright © 2002-2005 Brion Vibber <brion@pobox.com> et al
6 * https://www.mediawiki.org/
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
22 *
23 * @file
24 * @ingroup Parser
25 */
26
27 use MediaWiki\MediaWikiServices;
28
29 /**
30 * HTML sanitizer for MediaWiki
31 * @ingroup Parser
32 */
33 class Sanitizer {
34 /**
35 * Regular expression to match various types of character references in
36 * Sanitizer::normalizeCharReferences and Sanitizer::decodeCharReferences
37 */
38 const CHAR_REFS_REGEX =
39 '/&([A-Za-z0-9\x80-\xff]+);
40 |&\#([0-9]+);
41 |&\#[xX]([0-9A-Fa-f]+);
42 |(&)/x';
43
44 /**
45 * Acceptable tag name charset from HTML5 parsing spec
46 * https://www.w3.org/TR/html5/syntax.html#tag-open-state
47 */
48 const ELEMENT_BITS_REGEX = '!^(/?)([A-Za-z][^\t\n\v />\0]*+)([^>]*?)(/?>)([^<]*)$!';
49
50 /**
51 * Blacklist for evil uris like javascript:
52 * WARNING: DO NOT use this in any place that actually requires blacklisting
53 * for security reasons. There are NUMEROUS[1] ways to bypass blacklisting, the
54 * only way to be secure from javascript: uri based xss vectors is to whitelist
55 * things that you know are safe and deny everything else.
56 * [1]: http://ha.ckers.org/xss.html
57 */
58 const EVIL_URI_PATTERN = '!(^|\s|\*/\s*)(javascript|vbscript)([^\w]|$)!i';
59 const XMLNS_ATTRIBUTE_PATTERN = "/^xmlns:[:A-Z_a-z-.0-9]+$/";
60
61 /**
62 * Tells escapeUrlForHtml() to encode the ID using the wiki's primary encoding.
63 *
64 * @since 1.30
65 */
66 const ID_PRIMARY = 0;
67
68 /**
69 * Tells escapeUrlForHtml() to encode the ID using the fallback encoding, or return false
70 * if no fallback is configured.
71 *
72 * @since 1.30
73 */
74 const ID_FALLBACK = 1;
75
76 /**
77 * List of all named character entities defined in HTML 4.01
78 * https://www.w3.org/TR/html4/sgml/entities.html
79 * As well as &apos; which is only defined starting in XHTML1.
80 */
81 private static $htmlEntities = [
82 'Aacute' => 193,
83 'aacute' => 225,
84 'Acirc' => 194,
85 'acirc' => 226,
86 'acute' => 180,
87 'AElig' => 198,
88 'aelig' => 230,
89 'Agrave' => 192,
90 'agrave' => 224,
91 'alefsym' => 8501,
92 'Alpha' => 913,
93 'alpha' => 945,
94 'amp' => 38,
95 'and' => 8743,
96 'ang' => 8736,
97 'apos' => 39, // New in XHTML & HTML 5; avoid in output for compatibility with IE.
98 'Aring' => 197,
99 'aring' => 229,
100 'asymp' => 8776,
101 'Atilde' => 195,
102 'atilde' => 227,
103 'Auml' => 196,
104 'auml' => 228,
105 'bdquo' => 8222,
106 'Beta' => 914,
107 'beta' => 946,
108 'brvbar' => 166,
109 'bull' => 8226,
110 'cap' => 8745,
111 'Ccedil' => 199,
112 'ccedil' => 231,
113 'cedil' => 184,
114 'cent' => 162,
115 'Chi' => 935,
116 'chi' => 967,
117 'circ' => 710,
118 'clubs' => 9827,
119 'cong' => 8773,
120 'copy' => 169,
121 'crarr' => 8629,
122 'cup' => 8746,
123 'curren' => 164,
124 'dagger' => 8224,
125 'Dagger' => 8225,
126 'darr' => 8595,
127 'dArr' => 8659,
128 'deg' => 176,
129 'Delta' => 916,
130 'delta' => 948,
131 'diams' => 9830,
132 'divide' => 247,
133 'Eacute' => 201,
134 'eacute' => 233,
135 'Ecirc' => 202,
136 'ecirc' => 234,
137 'Egrave' => 200,
138 'egrave' => 232,
139 'empty' => 8709,
140 'emsp' => 8195,
141 'ensp' => 8194,
142 'Epsilon' => 917,
143 'epsilon' => 949,
144 'equiv' => 8801,
145 'Eta' => 919,
146 'eta' => 951,
147 'ETH' => 208,
148 'eth' => 240,
149 'Euml' => 203,
150 'euml' => 235,
151 'euro' => 8364,
152 'exist' => 8707,
153 'fnof' => 402,
154 'forall' => 8704,
155 'frac12' => 189,
156 'frac14' => 188,
157 'frac34' => 190,
158 'frasl' => 8260,
159 'Gamma' => 915,
160 'gamma' => 947,
161 'ge' => 8805,
162 'gt' => 62,
163 'harr' => 8596,
164 'hArr' => 8660,
165 'hearts' => 9829,
166 'hellip' => 8230,
167 'Iacute' => 205,
168 'iacute' => 237,
169 'Icirc' => 206,
170 'icirc' => 238,
171 'iexcl' => 161,
172 'Igrave' => 204,
173 'igrave' => 236,
174 'image' => 8465,
175 'infin' => 8734,
176 'int' => 8747,
177 'Iota' => 921,
178 'iota' => 953,
179 'iquest' => 191,
180 'isin' => 8712,
181 'Iuml' => 207,
182 'iuml' => 239,
183 'Kappa' => 922,
184 'kappa' => 954,
185 'Lambda' => 923,
186 'lambda' => 955,
187 'lang' => 9001,
188 'laquo' => 171,
189 'larr' => 8592,
190 'lArr' => 8656,
191 'lceil' => 8968,
192 'ldquo' => 8220,
193 'le' => 8804,
194 'lfloor' => 8970,
195 'lowast' => 8727,
196 'loz' => 9674,
197 'lrm' => 8206,
198 'lsaquo' => 8249,
199 'lsquo' => 8216,
200 'lt' => 60,
201 'macr' => 175,
202 'mdash' => 8212,
203 'micro' => 181,
204 'middot' => 183,
205 'minus' => 8722,
206 'Mu' => 924,
207 'mu' => 956,
208 'nabla' => 8711,
209 'nbsp' => 160,
210 'ndash' => 8211,
211 'ne' => 8800,
212 'ni' => 8715,
213 'not' => 172,
214 'notin' => 8713,
215 'nsub' => 8836,
216 'Ntilde' => 209,
217 'ntilde' => 241,
218 'Nu' => 925,
219 'nu' => 957,
220 'Oacute' => 211,
221 'oacute' => 243,
222 'Ocirc' => 212,
223 'ocirc' => 244,
224 'OElig' => 338,
225 'oelig' => 339,
226 'Ograve' => 210,
227 'ograve' => 242,
228 'oline' => 8254,
229 'Omega' => 937,
230 'omega' => 969,
231 'Omicron' => 927,
232 'omicron' => 959,
233 'oplus' => 8853,
234 'or' => 8744,
235 'ordf' => 170,
236 'ordm' => 186,
237 'Oslash' => 216,
238 'oslash' => 248,
239 'Otilde' => 213,
240 'otilde' => 245,
241 'otimes' => 8855,
242 'Ouml' => 214,
243 'ouml' => 246,
244 'para' => 182,
245 'part' => 8706,
246 'permil' => 8240,
247 'perp' => 8869,
248 'Phi' => 934,
249 'phi' => 966,
250 'Pi' => 928,
251 'pi' => 960,
252 'piv' => 982,
253 'plusmn' => 177,
254 'pound' => 163,
255 'prime' => 8242,
256 'Prime' => 8243,
257 'prod' => 8719,
258 'prop' => 8733,
259 'Psi' => 936,
260 'psi' => 968,
261 'quot' => 34,
262 'radic' => 8730,
263 'rang' => 9002,
264 'raquo' => 187,
265 'rarr' => 8594,
266 'rArr' => 8658,
267 'rceil' => 8969,
268 'rdquo' => 8221,
269 'real' => 8476,
270 'reg' => 174,
271 'rfloor' => 8971,
272 'Rho' => 929,
273 'rho' => 961,
274 'rlm' => 8207,
275 'rsaquo' => 8250,
276 'rsquo' => 8217,
277 'sbquo' => 8218,
278 'Scaron' => 352,
279 'scaron' => 353,
280 'sdot' => 8901,
281 'sect' => 167,
282 'shy' => 173,
283 'Sigma' => 931,
284 'sigma' => 963,
285 'sigmaf' => 962,
286 'sim' => 8764,
287 'spades' => 9824,
288 'sub' => 8834,
289 'sube' => 8838,
290 'sum' => 8721,
291 'sup' => 8835,
292 'sup1' => 185,
293 'sup2' => 178,
294 'sup3' => 179,
295 'supe' => 8839,
296 'szlig' => 223,
297 'Tau' => 932,
298 'tau' => 964,
299 'there4' => 8756,
300 'Theta' => 920,
301 'theta' => 952,
302 'thetasym' => 977,
303 'thinsp' => 8201,
304 'THORN' => 222,
305 'thorn' => 254,
306 'tilde' => 732,
307 'times' => 215,
308 'trade' => 8482,
309 'Uacute' => 218,
310 'uacute' => 250,
311 'uarr' => 8593,
312 'uArr' => 8657,
313 'Ucirc' => 219,
314 'ucirc' => 251,
315 'Ugrave' => 217,
316 'ugrave' => 249,
317 'uml' => 168,
318 'upsih' => 978,
319 'Upsilon' => 933,
320 'upsilon' => 965,
321 'Uuml' => 220,
322 'uuml' => 252,
323 'weierp' => 8472,
324 'Xi' => 926,
325 'xi' => 958,
326 'Yacute' => 221,
327 'yacute' => 253,
328 'yen' => 165,
329 'Yuml' => 376,
330 'yuml' => 255,
331 'Zeta' => 918,
332 'zeta' => 950,
333 'zwj' => 8205,
334 'zwnj' => 8204
335 ];
336
337 /**
338 * Character entity aliases accepted by MediaWiki
339 */
340 private static $htmlEntityAliases = [
341 'רלמ' => 'rlm',
342 'رلم' => 'rlm',
343 ];
344
345 /**
346 * Lazy-initialised attributes regex, see getAttribsRegex()
347 */
348 private static $attribsRegex;
349
350 /**
351 * Regular expression to match HTML/XML attribute pairs within a tag.
352 * Allows some... latitude. Based on,
353 * https://www.w3.org/TR/html5/syntax.html#before-attribute-value-state
354 * Used in Sanitizer::fixTagAttributes and Sanitizer::decodeTagAttributes
355 * @return string
356 */
357 static function getAttribsRegex() {
358 if ( self::$attribsRegex === null ) {
359 $attribFirst = "[:_\p{L}\p{N}]";
360 $attrib = "[:_\.\-\p{L}\p{N}]";
361 $space = '[\x09\x0a\x0c\x0d\x20]';
362 self::$attribsRegex =
363 "/(?:^|$space)({$attribFirst}{$attrib}*)
364 ($space*=$space*
365 (?:
366 # The attribute value: quoted or alone
367 \"([^\"]*)(?:\"|\$)
368 | '([^']*)(?:'|\$)
369 | (((?!$space|>).)*)
370 )
371 )?(?=$space|\$)/sxu";
372 }
373 return self::$attribsRegex;
374 }
375
376 /**
377 * Return the various lists of recognized tags
378 * @param array $extratags For any extra tags to include
379 * @param array $removetags For any tags (default or extra) to exclude
380 * @return array
381 */
382 public static function getRecognizedTagData( $extratags = [], $removetags = [] ) {
383 global $wgAllowImageTag;
384
385 static $htmlpairsStatic, $htmlsingle, $htmlsingleonly, $htmlnest, $tabletags,
386 $htmllist, $listtags, $htmlsingleallowed, $htmlelementsStatic, $staticInitialised;
387
388 // Base our staticInitialised variable off of the global config state so that if the globals
389 // are changed (like in the screwed up test system) we will re-initialise the settings.
390 $globalContext = $wgAllowImageTag;
391 if ( !$staticInitialised || $staticInitialised != $globalContext ) {
392 $htmlpairsStatic = [ # Tags that must be closed
393 'b', 'bdi', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
394 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
395 'strike', 'strong', 'tt', 'var', 'div', 'center',
396 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
397 'ruby', 'rb', 'rp', 'rt', 'rtc', 'p', 'span', 'abbr', 'dfn',
398 'kbd', 'samp', 'data', 'time', 'mark'
399 ];
400 $htmlsingle = [
401 'br', 'wbr', 'hr', 'li', 'dt', 'dd', 'meta', 'link'
402 ];
403
404 # Elements that cannot have close tags. This is (not coincidentally)
405 # also the list of tags for which the HTML 5 parsing algorithm
406 # requires you to "acknowledge the token's self-closing flag", i.e.
407 # a self-closing tag like <br/> is not an HTML 5 parse error only
408 # for this list.
409 $htmlsingleonly = [
410 'br', 'wbr', 'hr', 'meta', 'link'
411 ];
412
413 $htmlnest = [ # Tags that can be nested--??
414 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
415 'li', 'dl', 'dt', 'dd', 'font', 'big', 'small', 'sub', 'sup', 'span',
416 'var', 'kbd', 'samp', 'em', 'strong', 'q', 'ruby', 'bdo'
417 ];
418 $tabletags = [ # Can only appear inside table, we will close them
419 'td', 'th', 'tr',
420 ];
421 $htmllist = [ # Tags used by list
422 'ul', 'ol',
423 ];
424 $listtags = [ # Tags that can appear in a list
425 'li',
426 ];
427
428 if ( $wgAllowImageTag ) {
429 $htmlsingle[] = 'img';
430 $htmlsingleonly[] = 'img';
431 }
432
433 $htmlsingleallowed = array_unique( array_merge( $htmlsingle, $tabletags ) );
434 $htmlelementsStatic = array_unique( array_merge( $htmlsingle, $htmlpairsStatic, $htmlnest ) );
435
436 # Convert them all to hashtables for faster lookup
437 $vars = [ 'htmlpairsStatic', 'htmlsingle', 'htmlsingleonly', 'htmlnest', 'tabletags',
438 'htmllist', 'listtags', 'htmlsingleallowed', 'htmlelementsStatic' ];
439 foreach ( $vars as $var ) {
440 $$var = array_flip( $$var );
441 }
442 $staticInitialised = $globalContext;
443 }
444
445 # Populate $htmlpairs and $htmlelements with the $extratags and $removetags arrays
446 $extratags = array_flip( $extratags );
447 $removetags = array_flip( $removetags );
448 $htmlpairs = array_merge( $extratags, $htmlpairsStatic );
449 $htmlelements = array_diff_key( array_merge( $extratags, $htmlelementsStatic ), $removetags );
450
451 return [
452 'htmlpairs' => $htmlpairs,
453 'htmlsingle' => $htmlsingle,
454 'htmlsingleonly' => $htmlsingleonly,
455 'htmlnest' => $htmlnest,
456 'tabletags' => $tabletags,
457 'htmllist' => $htmllist,
458 'listtags' => $listtags,
459 'htmlsingleallowed' => $htmlsingleallowed,
460 'htmlelements' => $htmlelements,
461 ];
462 }
463
464 /**
465 * Cleans up HTML, removes dangerous tags and attributes, and
466 * removes HTML comments
467 * @param string $text
468 * @param callable|null $processCallback Callback to do any variable or parameter
469 * replacements in HTML attribute values
470 * @param array|bool $args Arguments for the processing callback
471 * @param array $extratags For any extra tags to include
472 * @param array $removetags For any tags (default or extra) to exclude
473 * @param callable|null $warnCallback (Deprecated) Callback allowing the
474 * addition of a tracking category when bad input is encountered.
475 * DO NOT ADD NEW PARAMETERS AFTER $warnCallback, since it will be
476 * removed shortly.
477 * @return string
478 */
479 public static function removeHTMLtags( $text, $processCallback = null,
480 $args = [], $extratags = [], $removetags = [], $warnCallback = null
481 ) {
482 $tagData = self::getRecognizedTagData( $extratags, $removetags );
483 $htmlpairs = $tagData['htmlpairs'];
484 $htmlsingle = $tagData['htmlsingle'];
485 $htmlsingleonly = $tagData['htmlsingleonly'];
486 $htmlnest = $tagData['htmlnest'];
487 $tabletags = $tagData['tabletags'];
488 $htmllist = $tagData['htmllist'];
489 $listtags = $tagData['listtags'];
490 $htmlsingleallowed = $tagData['htmlsingleallowed'];
491 $htmlelements = $tagData['htmlelements'];
492
493 # Remove HTML comments
494 $text = self::removeHTMLcomments( $text );
495 $bits = explode( '<', $text );
496 $text = str_replace( '>', '&gt;', array_shift( $bits ) );
497 if ( !MWTidy::isEnabled() ) {
498 $tagstack = $tablestack = [];
499 foreach ( $bits as $x ) {
500 $regs = [];
501 # $slash: Does the current element start with a '/'?
502 # $t: Current element name
503 # $params: String between element name and >
504 # $brace: Ending '>' or '/>'
505 # $rest: Everything until the next element of $bits
506 if ( preg_match( self::ELEMENT_BITS_REGEX, $x, $regs ) ) {
507 list( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
508 } else {
509 $slash = $t = $params = $brace = $rest = null;
510 }
511
512 $badtag = false;
513 $t = strtolower( $t );
514 if ( isset( $htmlelements[$t] ) ) {
515 # Check our stack
516 if ( $slash && isset( $htmlsingleonly[$t] ) ) {
517 $badtag = true;
518 } elseif ( $slash ) {
519 # Closing a tag... is it the one we just opened?
520 Wikimedia\suppressWarnings();
521 $ot = array_pop( $tagstack );
522 Wikimedia\restoreWarnings();
523
524 if ( $ot != $t ) {
525 if ( isset( $htmlsingleallowed[$ot] ) ) {
526 # Pop all elements with an optional close tag
527 # and see if we find a match below them
528 $optstack = [];
529 array_push( $optstack, $ot );
530 Wikimedia\suppressWarnings();
531 $ot = array_pop( $tagstack );
532 Wikimedia\restoreWarnings();
533 while ( $ot != $t && isset( $htmlsingleallowed[$ot] ) ) {
534 array_push( $optstack, $ot );
535 Wikimedia\suppressWarnings();
536 $ot = array_pop( $tagstack );
537 Wikimedia\restoreWarnings();
538 }
539 if ( $t != $ot ) {
540 # No match. Push the optional elements back again
541 $badtag = true;
542 Wikimedia\suppressWarnings();
543 $ot = array_pop( $optstack );
544 Wikimedia\restoreWarnings();
545 while ( $ot ) {
546 array_push( $tagstack, $ot );
547 Wikimedia\suppressWarnings();
548 $ot = array_pop( $optstack );
549 Wikimedia\restoreWarnings();
550 }
551 }
552 } else {
553 Wikimedia\suppressWarnings();
554 array_push( $tagstack, $ot );
555 Wikimedia\restoreWarnings();
556
557 # <li> can be nested in <ul> or <ol>, skip those cases:
558 if ( !isset( $htmllist[$ot] ) || !isset( $listtags[$t] ) ) {
559 $badtag = true;
560 }
561 }
562 } else {
563 if ( $t == 'table' ) {
564 $tagstack = array_pop( $tablestack );
565 }
566 }
567 $newparams = '';
568 } else {
569 # Keep track for later
570 if ( isset( $tabletags[$t] ) && !in_array( 'table', $tagstack ) ) {
571 $badtag = true;
572 } elseif ( in_array( $t, $tagstack ) && !isset( $htmlnest[$t] ) ) {
573 $badtag = true;
574 #  Is it a self closed htmlpair ? (T7487)
575 } elseif ( $brace == '/>' && isset( $htmlpairs[$t] ) ) {
576 // Eventually we'll just remove the self-closing
577 // slash, in order to be consistent with HTML5
578 // semantics.
579 // $brace = '>';
580 // For now, let's just warn authors to clean up.
581 if ( is_callable( $warnCallback ) ) {
582 call_user_func_array( $warnCallback, [ 'deprecated-self-close-category' ] );
583 }
584 $badtag = true;
585 } elseif ( isset( $htmlsingleonly[$t] ) ) {
586 # Hack to force empty tag for unclosable elements
587 $brace = '/>';
588 } elseif ( isset( $htmlsingle[$t] ) ) {
589 # Hack to not close $htmlsingle tags
590 $brace = null;
591 # Still need to push this optionally-closed tag to
592 # the tag stack so that we can match end tags
593 # instead of marking them as bad.
594 array_push( $tagstack, $t );
595 } elseif ( isset( $tabletags[$t] ) && in_array( $t, $tagstack ) ) {
596 // New table tag but forgot to close the previous one
597 $text .= "</$t>";
598 } else {
599 if ( $t == 'table' ) {
600 array_push( $tablestack, $tagstack );
601 $tagstack = [];
602 }
603 array_push( $tagstack, $t );
604 }
605
606 # Replace any variables or template parameters with
607 # plaintext results.
608 if ( is_callable( $processCallback ) ) {
609 call_user_func_array( $processCallback, [ &$params, $args ] );
610 }
611
612 if ( !self::validateTag( $params, $t ) ) {
613 $badtag = true;
614 }
615
616 # Strip non-approved attributes from the tag
617 $newparams = self::fixTagAttributes( $params, $t );
618 }
619 if ( !$badtag ) {
620 $rest = str_replace( '>', '&gt;', $rest );
621 $close = ( $brace == '/>' && !$slash ) ? ' /' : '';
622 $text .= "<$slash$t$newparams$close>$rest";
623 continue;
624 }
625 }
626 $text .= '&lt;' . str_replace( '>', '&gt;', $x );
627 }
628 # Close off any remaining tags
629 while ( is_array( $tagstack ) && ( $t = array_pop( $tagstack ) ) ) {
630 $text .= "</$t>\n";
631 if ( $t == 'table' ) {
632 $tagstack = array_pop( $tablestack );
633 }
634 }
635 } else {
636 # this might be possible using tidy itself
637 foreach ( $bits as $x ) {
638 if ( preg_match( self::ELEMENT_BITS_REGEX, $x, $regs ) ) {
639 list( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
640
641 $badtag = false;
642 $t = strtolower( $t );
643 if ( isset( $htmlelements[$t] ) ) {
644 if ( is_callable( $processCallback ) ) {
645 call_user_func_array( $processCallback, [ &$params, $args ] );
646 }
647
648 if ( $brace == '/>' && !( isset( $htmlsingle[$t] ) || isset( $htmlsingleonly[$t] ) ) ) {
649 // Eventually we'll just remove the self-closing
650 // slash, in order to be consistent with HTML5
651 // semantics.
652 // $brace = '>';
653 // For now, let's just warn authors to clean up.
654 if ( is_callable( $warnCallback ) ) {
655 call_user_func_array( $warnCallback, [ 'deprecated-self-close-category' ] );
656 }
657 }
658 if ( !self::validateTag( $params, $t ) ) {
659 $badtag = true;
660 }
661
662 $newparams = self::fixTagAttributes( $params, $t );
663 if ( !$badtag ) {
664 if ( $brace === '/>' && !isset( $htmlsingleonly[$t] ) ) {
665 # Interpret self-closing tags as empty tags even when
666 # HTML 5 would interpret them as start tags. Such input
667 # is commonly seen on Wikimedia wikis with this intention.
668 $brace = "></$t>";
669 }
670
671 $rest = str_replace( '>', '&gt;', $rest );
672 $text .= "<$slash$t$newparams$brace$rest";
673 continue;
674 }
675 }
676 }
677 $text .= '&lt;' . str_replace( '>', '&gt;', $x );
678 }
679 }
680 return $text;
681 }
682
683 /**
684 * Remove '<!--', '-->', and everything between.
685 * To avoid leaving blank lines, when a comment is both preceded
686 * and followed by a newline (ignoring spaces), trim leading and
687 * trailing spaces and one of the newlines.
688 *
689 * @param string $text
690 * @return string
691 */
692 public static function removeHTMLcomments( $text ) {
693 while ( ( $start = strpos( $text, '<!--' ) ) !== false ) {
694 $end = strpos( $text, '-->', $start + 4 );
695 if ( $end === false ) {
696 # Unterminated comment; bail out
697 break;
698 }
699
700 $end += 3;
701
702 # Trim space and newline if the comment is both
703 # preceded and followed by a newline
704 $spaceStart = max( $start - 1, 0 );
705 $spaceLen = $end - $spaceStart;
706 while ( substr( $text, $spaceStart, 1 ) === ' ' && $spaceStart > 0 ) {
707 $spaceStart--;
708 $spaceLen++;
709 }
710 while ( substr( $text, $spaceStart + $spaceLen, 1 ) === ' ' ) {
711 $spaceLen++;
712 }
713 if ( substr( $text, $spaceStart, 1 ) === "\n"
714 && substr( $text, $spaceStart + $spaceLen, 1 ) === "\n" ) {
715 # Remove the comment, leading and trailing
716 # spaces, and leave only one newline.
717 $text = substr_replace( $text, "\n", $spaceStart, $spaceLen + 1 );
718 } else {
719 # Remove just the comment.
720 $text = substr_replace( $text, '', $start, $end - $start );
721 }
722 }
723 return $text;
724 }
725
726 /**
727 * Takes attribute names and values for a tag and the tag name and
728 * validates that the tag is allowed to be present.
729 * This DOES NOT validate the attributes, nor does it validate the
730 * tags themselves. This method only handles the special circumstances
731 * where we may want to allow a tag within content but ONLY when it has
732 * specific attributes set.
733 *
734 * @param string $params
735 * @param string $element
736 * @return bool
737 */
738 static function validateTag( $params, $element ) {
739 $params = self::decodeTagAttributes( $params );
740
741 if ( $element == 'meta' || $element == 'link' ) {
742 if ( !isset( $params['itemprop'] ) ) {
743 // <meta> and <link> must have an itemprop="" otherwise they are not valid or safe in content
744 return false;
745 }
746 if ( $element == 'meta' && !isset( $params['content'] ) ) {
747 // <meta> must have a content="" for the itemprop
748 return false;
749 }
750 if ( $element == 'link' && !isset( $params['href'] ) ) {
751 // <link> must have an associated href=""
752 return false;
753 }
754 }
755
756 return true;
757 }
758
759 /**
760 * Take an array of attribute names and values and normalize or discard
761 * illegal values for the given element type.
762 *
763 * - Discards attributes not on a whitelist for the given element
764 * - Unsafe style attributes are discarded
765 * - Invalid id attributes are re-encoded
766 *
767 * @param array $attribs
768 * @param string $element
769 * @return array
770 *
771 * @todo Check for legal values where the DTD limits things.
772 * @todo Check for unique id attribute :P
773 */
774 static function validateTagAttributes( $attribs, $element ) {
775 return self::validateAttributes( $attribs,
776 self::attributeWhitelist( $element ) );
777 }
778
779 /**
780 * Take an array of attribute names and values and normalize or discard
781 * illegal values for the given whitelist.
782 *
783 * - Discards attributes not on the given whitelist
784 * - Unsafe style attributes are discarded
785 * - Invalid id attributes are re-encoded
786 *
787 * @param array $attribs
788 * @param array $whitelist List of allowed attribute names
789 * @return array
790 *
791 * @todo Check for legal values where the DTD limits things.
792 * @todo Check for unique id attribute :P
793 */
794 static function validateAttributes( $attribs, $whitelist ) {
795 $whitelist = array_flip( $whitelist );
796 $hrefExp = '/^(' . wfUrlProtocols() . ')[^\s]+$/';
797
798 $out = [];
799 foreach ( $attribs as $attribute => $value ) {
800 # Allow XML namespace declaration to allow RDFa
801 if ( preg_match( self::XMLNS_ATTRIBUTE_PATTERN, $attribute ) ) {
802 if ( !preg_match( self::EVIL_URI_PATTERN, $value ) ) {
803 $out[$attribute] = $value;
804 }
805
806 continue;
807 }
808
809 # Allow any attribute beginning with "data-"
810 # However:
811 # * Disallow data attributes used by MediaWiki code
812 # * Ensure that the attribute is not namespaced by banning
813 # colons.
814 if ( !preg_match( '/^data-[^:]*$/i', $attribute )
815 && !isset( $whitelist[$attribute] )
816 || self::isReservedDataAttribute( $attribute )
817 ) {
818 continue;
819 }
820
821 # Strip javascript "expression" from stylesheets.
822 # https://msdn.microsoft.com/en-us/library/ms537634.aspx
823 if ( $attribute == 'style' ) {
824 $value = self::checkCss( $value );
825 }
826
827 # Escape HTML id attributes
828 if ( $attribute === 'id' ) {
829 $value = self::escapeIdForAttribute( $value, self::ID_PRIMARY );
830 }
831
832 # Escape HTML id reference lists
833 if ( $attribute === 'aria-describedby'
834 || $attribute === 'aria-flowto'
835 || $attribute === 'aria-labelledby'
836 || $attribute === 'aria-owns'
837 ) {
838 $value = self::escapeIdReferenceList( $value );
839 }
840
841 // RDFa and microdata properties allow URLs, URIs and/or CURIs.
842 // Check them for sanity.
843 if ( $attribute === 'rel' || $attribute === 'rev'
844 # RDFa
845 || $attribute === 'about' || $attribute === 'property'
846 || $attribute === 'resource' || $attribute === 'datatype'
847 || $attribute === 'typeof'
848 # HTML5 microdata
849 || $attribute === 'itemid' || $attribute === 'itemprop'
850 || $attribute === 'itemref' || $attribute === 'itemscope'
851 || $attribute === 'itemtype'
852 ) {
853 // Paranoia. Allow "simple" values but suppress javascript
854 if ( preg_match( self::EVIL_URI_PATTERN, $value ) ) {
855 continue;
856 }
857 }
858
859 # NOTE: even though elements using href/src are not allowed directly, supply
860 # validation code that can be used by tag hook handlers, etc
861 if ( $attribute === 'href' || $attribute === 'src' || $attribute === 'poster' ) {
862 if ( !preg_match( $hrefExp, $value ) ) {
863 continue; // drop any href or src attributes not using an allowed protocol.
864 // NOTE: this also drops all relative URLs
865 }
866 }
867
868 // If this attribute was previously set, override it.
869 // Output should only have one attribute of each name.
870 $out[$attribute] = $value;
871 }
872
873 # itemtype, itemid, itemref don't make sense without itemscope
874 if ( !array_key_exists( 'itemscope', $out ) ) {
875 unset( $out['itemtype'] );
876 unset( $out['itemid'] );
877 unset( $out['itemref'] );
878 }
879 # TODO: Strip itemprop if we aren't descendants of an itemscope or pointed to by an itemref.
880
881 return $out;
882 }
883
884 /**
885 * Given an attribute name, checks whether it is a reserved data attribute
886 * (such as data-mw-foo) which is unavailable to user-generated HTML so MediaWiki
887 * core and extension code can safely use it to communicate with frontend code.
888 * @param string $attr Attribute name.
889 * @return bool
890 */
891 public static function isReservedDataAttribute( $attr ) {
892 // data-ooui is reserved for ooui.
893 // data-mw and data-parsoid are reserved for parsoid.
894 // data-mw-<name here> is reserved for extensions (or core) if
895 // they need to communicate some data to the client and want to be
896 // sure that it isn't coming from an untrusted user.
897 // We ignore the possibility of namespaces since user-generated HTML
898 // can't use them anymore.
899 return (bool)preg_match( '/^data-(ooui|mw|parsoid)/i', $attr );
900 }
901
902 /**
903 * Merge two sets of HTML attributes. Conflicting items in the second set
904 * will override those in the first, except for 'class' attributes which
905 * will be combined (if they're both strings).
906 *
907 * @todo implement merging for other attributes such as style
908 * @param array $a
909 * @param array $b
910 * @return array
911 */
912 static function mergeAttributes( $a, $b ) {
913 $out = array_merge( $a, $b );
914 if ( isset( $a['class'] ) && isset( $b['class'] )
915 && is_string( $a['class'] ) && is_string( $b['class'] )
916 && $a['class'] !== $b['class']
917 ) {
918 $classes = preg_split( '/\s+/', "{$a['class']} {$b['class']}",
919 -1, PREG_SPLIT_NO_EMPTY );
920 $out['class'] = implode( ' ', array_unique( $classes ) );
921 }
922 return $out;
923 }
924
925 /**
926 * Normalize CSS into a format we can easily search for hostile input
927 * - decode character references
928 * - decode escape sequences
929 * - convert characters that IE6 interprets into ascii
930 * - remove comments, unless the entire value is one single comment
931 * @param string $value the css string
932 * @return string normalized css
933 */
934 public static function normalizeCss( $value ) {
935 // Decode character references like &#123;
936 $value = self::decodeCharReferences( $value );
937
938 // Decode escape sequences and line continuation
939 // See the grammar in the CSS 2 spec, appendix D.
940 // This has to be done AFTER decoding character references.
941 // This means it isn't possible for this function to return
942 // unsanitized escape sequences. It is possible to manufacture
943 // input that contains character references that decode to
944 // escape sequences that decode to character references, but
945 // it's OK for the return value to contain character references
946 // because the caller is supposed to escape those anyway.
947 static $decodeRegex;
948 if ( !$decodeRegex ) {
949 $space = '[\\x20\\t\\r\\n\\f]';
950 $nl = '(?:\\n|\\r\\n|\\r|\\f)';
951 $backslash = '\\\\';
952 $decodeRegex = "/ $backslash
953 (?:
954 ($nl) | # 1. Line continuation
955 ([0-9A-Fa-f]{1,6})$space? | # 2. character number
956 (.) | # 3. backslash cancelling special meaning
957 () | # 4. backslash at end of string
958 )/xu";
959 }
960 $value = preg_replace_callback( $decodeRegex,
961 [ __CLASS__, 'cssDecodeCallback' ], $value );
962
963 // Normalize Halfwidth and Fullwidth Unicode block that IE6 might treat as ascii
964 $value = preg_replace_callback(
965 '/[!-[]-z]/u', // U+FF01 to U+FF5A, excluding U+FF3C (T60088)
966 function ( $matches ) {
967 $cp = UtfNormal\Utils::utf8ToCodepoint( $matches[0] );
968 if ( $cp === false ) {
969 return '';
970 }
971 return chr( $cp - 65248 ); // ASCII range \x21-\x7A
972 },
973 $value
974 );
975
976 // Convert more characters IE6 might treat as ascii
977 // U+0280, U+0274, U+207F, U+029F, U+026A, U+207D, U+208D
978 $value = str_replace(
979 [ 'ʀ', 'ɴ', 'ⁿ', 'ʟ', 'ɪ', '⁽', '₍' ],
980 [ 'r', 'n', 'n', 'l', 'i', '(', '(' ],
981 $value
982 );
983
984 // Let the value through if it's nothing but a single comment, to
985 // allow other functions which may reject it to pass some error
986 // message through.
987 if ( !preg_match( '! ^ \s* /\* [^*\\/]* \*/ \s* $ !x', $value ) ) {
988 // Remove any comments; IE gets token splitting wrong
989 // This must be done AFTER decoding character references and
990 // escape sequences, because those steps can introduce comments
991 // This step cannot introduce character references or escape
992 // sequences, because it replaces comments with spaces rather
993 // than removing them completely.
994 $value = StringUtils::delimiterReplace( '/*', '*/', ' ', $value );
995
996 // Remove anything after a comment-start token, to guard against
997 // incorrect client implementations.
998 $commentPos = strpos( $value, '/*' );
999 if ( $commentPos !== false ) {
1000 $value = substr( $value, 0, $commentPos );
1001 }
1002 }
1003
1004 // S followed by repeat, iteration, or prolonged sound marks,
1005 // which IE will treat as "ss"
1006 $value = preg_replace(
1007 '/s(?:
1008 \xE3\x80\xB1 | # U+3031
1009 \xE3\x82\x9D | # U+309D
1010 \xE3\x83\xBC | # U+30FC
1011 \xE3\x83\xBD | # U+30FD
1012 \xEF\xB9\xBC | # U+FE7C
1013 \xEF\xB9\xBD | # U+FE7D
1014 \xEF\xBD\xB0 # U+FF70
1015 )/ix',
1016 'ss',
1017 $value
1018 );
1019
1020 return $value;
1021 }
1022
1023 /**
1024 * Pick apart some CSS and check it for forbidden or unsafe structures.
1025 * Returns a sanitized string. This sanitized string will have
1026 * character references and escape sequences decoded and comments
1027 * stripped (unless it is itself one valid comment, in which case the value
1028 * will be passed through). If the input is just too evil, only a comment
1029 * complaining about evilness will be returned.
1030 *
1031 * Currently URL references, 'expression', 'tps' are forbidden.
1032 *
1033 * NOTE: Despite the fact that character references are decoded, the
1034 * returned string may contain character references given certain
1035 * clever input strings. These character references must
1036 * be escaped before the return value is embedded in HTML.
1037 *
1038 * @param string $value
1039 * @return string
1040 */
1041 static function checkCss( $value ) {
1042 $value = self::normalizeCss( $value );
1043
1044 // Reject problematic keywords and control characters
1045 if ( preg_match( '/[\000-\010\013\016-\037\177]/', $value ) ||
1046 strpos( $value, UtfNormal\Constants::UTF8_REPLACEMENT ) !== false ) {
1047 return '/* invalid control char */';
1048 } elseif ( preg_match(
1049 '! expression
1050 | filter\s*:
1051 | accelerator\s*:
1052 | -o-link\s*:
1053 | -o-link-source\s*:
1054 | -o-replace\s*:
1055 | url\s*\(
1056 | image\s*\(
1057 | image-set\s*\(
1058 | attr\s*\([^)]+[\s,]+url
1059 !ix', $value ) ) {
1060 return '/* insecure input */';
1061 }
1062 return $value;
1063 }
1064
1065 /**
1066 * @param array $matches
1067 * @return string
1068 */
1069 static function cssDecodeCallback( $matches ) {
1070 if ( $matches[1] !== '' ) {
1071 // Line continuation
1072 return '';
1073 } elseif ( $matches[2] !== '' ) {
1074 $char = UtfNormal\Utils::codepointToUtf8( hexdec( $matches[2] ) );
1075 } elseif ( $matches[3] !== '' ) {
1076 $char = $matches[3];
1077 } else {
1078 $char = '\\';
1079 }
1080 if ( $char == "\n" || $char == '"' || $char == "'" || $char == '\\' ) {
1081 // These characters need to be escaped in strings
1082 // Clean up the escape sequence to avoid parsing errors by clients
1083 return '\\' . dechex( ord( $char ) ) . ' ';
1084 } else {
1085 // Decode unnecessary escape
1086 return $char;
1087 }
1088 }
1089
1090 /**
1091 * Take a tag soup fragment listing an HTML element's attributes
1092 * and normalize it to well-formed XML, discarding unwanted attributes.
1093 * Output is safe for further wikitext processing, with escaping of
1094 * values that could trigger problems.
1095 *
1096 * - Normalizes attribute names to lowercase
1097 * - Discards attributes not on a whitelist for the given element
1098 * - Turns broken or invalid entities into plaintext
1099 * - Double-quotes all attribute values
1100 * - Attributes without values are given the name as attribute
1101 * - Double attributes are discarded
1102 * - Unsafe style attributes are discarded
1103 * - Prepends space if there are attributes.
1104 * - (Optionally) Sorts attributes by name.
1105 *
1106 * @param string $text
1107 * @param string $element
1108 * @param bool $sorted Whether to sort the attributes (default: false)
1109 * @return string
1110 */
1111 static function fixTagAttributes( $text, $element, $sorted = false ) {
1112 if ( trim( $text ) == '' ) {
1113 return '';
1114 }
1115
1116 $decoded = self::decodeTagAttributes( $text );
1117 $stripped = self::validateTagAttributes( $decoded, $element );
1118
1119 if ( $sorted ) {
1120 ksort( $stripped );
1121 }
1122
1123 return self::safeEncodeTagAttributes( $stripped );
1124 }
1125
1126 /**
1127 * Encode an attribute value for HTML output.
1128 * @param string $text
1129 * @return string HTML-encoded text fragment
1130 */
1131 static function encodeAttribute( $text ) {
1132 $encValue = htmlspecialchars( $text, ENT_QUOTES );
1133
1134 // Whitespace is normalized during attribute decoding,
1135 // so if we've been passed non-spaces we must encode them
1136 // ahead of time or they won't be preserved.
1137 $encValue = strtr( $encValue, [
1138 "\n" => '&#10;',
1139 "\r" => '&#13;',
1140 "\t" => '&#9;',
1141 ] );
1142
1143 return $encValue;
1144 }
1145
1146 /**
1147 * Armor French spaces with a replacement character
1148 *
1149 * @since 1.32
1150 * @param string $text Text to armor
1151 * @param string $space Space character for the French spaces, defaults to '&#160;'
1152 * @return string Armored text
1153 */
1154 public static function armorFrenchSpaces( $text, $space = '&#160;' ) {
1155 // Replace $ with \$ and \ with \\
1156 $space = preg_replace( '#(?<!\\\\)(\\$|\\\\)#', '\\\\$1', $space );
1157 $fixtags = [
1158 # French spaces, last one Guillemet-left
1159 # only if there is something before the space
1160 # and a non-word character after the punctuation.
1161 '/(\S) (?=[?:;!%»›](?!\w))/u' => "\\1$space",
1162 # French spaces, Guillemet-right
1163 '/([«‹]) /u' => "\\1$space",
1164 ];
1165 return preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
1166 }
1167
1168 /**
1169 * Encode an attribute value for HTML tags, with extra armoring
1170 * against further wiki processing.
1171 * @param string $text
1172 * @return string HTML-encoded text fragment
1173 */
1174 static function safeEncodeAttribute( $text ) {
1175 $encValue = self::encodeAttribute( $text );
1176
1177 # Templates and links may be expanded in later parsing,
1178 # creating invalid or dangerous output. Suppress this.
1179 $encValue = strtr( $encValue, [
1180 '<' => '&lt;', // This should never happen,
1181 '>' => '&gt;', // we've received invalid input
1182 '"' => '&quot;', // which should have been escaped.
1183 '{' => '&#123;',
1184 '}' => '&#125;', // prevent unpaired language conversion syntax
1185 '[' => '&#91;',
1186 ']' => '&#93;',
1187 "''" => '&#39;&#39;',
1188 'ISBN' => '&#73;SBN',
1189 'RFC' => '&#82;FC',
1190 'PMID' => '&#80;MID',
1191 '|' => '&#124;',
1192 '__' => '&#95;_',
1193 ] );
1194
1195 # Armor against French spaces detection (T5158)
1196 $encValue = self::armorFrenchSpaces( $encValue, '&#32;' );
1197
1198 # Stupid hack
1199 $encValue = preg_replace_callback(
1200 '/((?i)' . wfUrlProtocols() . ')/',
1201 function ( $matches ) {
1202 return str_replace( ':', '&#58;', $matches[1] );
1203 },
1204 $encValue );
1205 return $encValue;
1206 }
1207
1208 /**
1209 * Given a value, escape it so that it can be used in an id attribute and
1210 * return it. This will use HTML5 validation, allowing anything but ASCII
1211 * whitespace.
1212 *
1213 * To ensure we don't have to bother escaping anything, we also strip ', ".
1214 * TODO: Is this the best tactic?
1215 *
1216 * We also strip # because it upsets IE, and % because it could be
1217 * ambiguous if it's part of something that looks like a percent escape
1218 * (which don't work reliably in fragments cross-browser).
1219 *
1220 * @deprecated since 1.30, use one of this class' escapeIdFor*() functions
1221 *
1222 * @see https://www.w3.org/TR/html401/types.html#type-name Valid characters
1223 * in the id and name attributes
1224 * @see https://www.w3.org/TR/html401/struct/links.html#h-12.2.3 Anchors with
1225 * the id attribute
1226 * @see https://www.w3.org/TR/html5/dom.html#the-id-attribute
1227 * HTML5 definition of id attribute
1228 *
1229 * @param string $id Id to escape
1230 * @param string|array $options String or array of strings (default is array()):
1231 * 'noninitial': This is a non-initial fragment of an id, not a full id,
1232 * so don't pay attention if the first character isn't valid at the
1233 * beginning of an id.
1234 * @return string
1235 */
1236 static function escapeId( $id, $options = [] ) {
1237 $options = (array)$options;
1238
1239 // HTML4-style escaping
1240 static $replace = [
1241 '%3A' => ':',
1242 '%' => '.'
1243 ];
1244
1245 $id = urlencode( strtr( $id, ' ', '_' ) );
1246 $id = strtr( $id, $replace );
1247
1248 if ( !preg_match( '/^[a-zA-Z]/', $id ) && !in_array( 'noninitial', $options ) ) {
1249 // Initial character must be a letter!
1250 $id = "x$id";
1251 }
1252 return $id;
1253 }
1254
1255 /**
1256 * Given a section name or other user-generated or otherwise unsafe string, escapes it to be
1257 * a valid HTML id attribute.
1258 *
1259 * WARNING: unlike escapeId(), the output of this function is not guaranteed to be HTML safe,
1260 * be sure to use proper escaping.
1261 *
1262 * @param string $id String to escape
1263 * @param int $mode One of ID_* constants, specifying whether the primary or fallback encoding
1264 * should be used.
1265 * @return string|bool Escaped ID or false if fallback encoding is requested but it's not
1266 * configured.
1267 *
1268 * @since 1.30
1269 */
1270 public static function escapeIdForAttribute( $id, $mode = self::ID_PRIMARY ) {
1271 global $wgFragmentMode;
1272
1273 if ( !isset( $wgFragmentMode[$mode] ) ) {
1274 if ( $mode === self::ID_PRIMARY ) {
1275 throw new UnexpectedValueException( '$wgFragmentMode is configured with no primary mode' );
1276 }
1277 return false;
1278 }
1279
1280 $internalMode = $wgFragmentMode[$mode];
1281
1282 return self::escapeIdInternal( $id, $internalMode );
1283 }
1284
1285 /**
1286 * Given a section name or other user-generated or otherwise unsafe string, escapes it to be
1287 * a valid URL fragment.
1288 *
1289 * WARNING: unlike escapeId(), the output of this function is not guaranteed to be HTML safe,
1290 * be sure to use proper escaping.
1291 *
1292 * @param string $id String to escape
1293 * @return string Escaped ID
1294 *
1295 * @since 1.30
1296 */
1297 public static function escapeIdForLink( $id ) {
1298 global $wgFragmentMode;
1299
1300 if ( !isset( $wgFragmentMode[self::ID_PRIMARY] ) ) {
1301 throw new UnexpectedValueException( '$wgFragmentMode is configured with no primary mode' );
1302 }
1303
1304 $mode = $wgFragmentMode[self::ID_PRIMARY];
1305
1306 $id = self::escapeIdInternal( $id, $mode );
1307
1308 return $id;
1309 }
1310
1311 /**
1312 * Given a section name or other user-generated or otherwise unsafe string, escapes it to be
1313 * a valid URL fragment for external interwikis.
1314 *
1315 * @param string $id String to escape
1316 * @return string Escaped ID
1317 *
1318 * @since 1.30
1319 */
1320 public static function escapeIdForExternalInterwiki( $id ) {
1321 global $wgExternalInterwikiFragmentMode;
1322
1323 $id = self::escapeIdInternal( $id, $wgExternalInterwikiFragmentMode );
1324
1325 return $id;
1326 }
1327
1328 /**
1329 * Helper for escapeIdFor*() functions. Performs most of the actual escaping.
1330 *
1331 * @param string $id String to escape
1332 * @param string $mode One of modes from $wgFragmentMode
1333 * @return string
1334 */
1335 private static function escapeIdInternal( $id, $mode ) {
1336 switch ( $mode ) {
1337 case 'html5':
1338 $id = str_replace( ' ', '_', $id );
1339 break;
1340 case 'legacy':
1341 // This corresponds to 'noninitial' mode of the old escapeId()
1342 static $replace = [
1343 '%3A' => ':',
1344 '%' => '.'
1345 ];
1346
1347 $id = urlencode( str_replace( ' ', '_', $id ) );
1348 $id = strtr( $id, $replace );
1349 break;
1350 default:
1351 throw new InvalidArgumentException( "Invalid mode '$mode' passed to '" . __METHOD__ );
1352 }
1353
1354 return $id;
1355 }
1356
1357 /**
1358 * Given a string containing a space delimited list of ids, escape each id
1359 * to match ids escaped by the escapeId() function.
1360 *
1361 * @todo remove $options completely in 1.32
1362 *
1363 * @since 1.27
1364 *
1365 * @param string $referenceString Space delimited list of ids
1366 * @param string|array $options Deprecated and does nothing.
1367 * @return string
1368 */
1369 static function escapeIdReferenceList( $referenceString, $options = [] ) {
1370 if ( $options ) {
1371 wfDeprecated( __METHOD__ . ' with $options', '1.31' );
1372 }
1373 # Explode the space delimited list string into an array of tokens
1374 $references = preg_split( '/\s+/', "{$referenceString}", -1, PREG_SPLIT_NO_EMPTY );
1375
1376 # Escape each token as an id
1377 foreach ( $references as &$ref ) {
1378 $ref = self::escapeIdForAttribute( $ref );
1379 }
1380
1381 # Merge the array back to a space delimited list string
1382 # If the array is empty, the result will be an empty string ('')
1383 $referenceString = implode( ' ', $references );
1384
1385 return $referenceString;
1386 }
1387
1388 /**
1389 * Given a value, escape it so that it can be used as a CSS class and
1390 * return it.
1391 *
1392 * @todo For extra validity, input should be validated UTF-8.
1393 *
1394 * @see https://www.w3.org/TR/CSS21/syndata.html Valid characters/format
1395 *
1396 * @param string $class
1397 * @return string
1398 */
1399 static function escapeClass( $class ) {
1400 // Convert ugly stuff to underscores and kill underscores in ugly places
1401 return rtrim( preg_replace(
1402 [ '/(^[0-9\\-])|[\\x00-\\x20!"#$%&\'()*+,.\\/:;<=>?@[\\]^`{|}~]|\\xC2\\xA0/', '/_+/' ],
1403 '_',
1404 $class ), '_' );
1405 }
1406
1407 /**
1408 * Given HTML input, escape with htmlspecialchars but un-escape entities.
1409 * This allows (generally harmless) entities like &#160; to survive.
1410 *
1411 * @param string $html HTML to escape
1412 * @return string Escaped input
1413 */
1414 static function escapeHtmlAllowEntities( $html ) {
1415 $html = self::decodeCharReferences( $html );
1416 # It seems wise to escape ' as well as ", as a matter of course. Can't
1417 # hurt. Use ENT_SUBSTITUTE so that incorrectly truncated multibyte characters
1418 # don't cause the entire string to disappear.
1419 $html = htmlspecialchars( $html, ENT_QUOTES | ENT_SUBSTITUTE );
1420 return $html;
1421 }
1422
1423 /**
1424 * Return an associative array of attribute names and values from
1425 * a partial tag string. Attribute names are forced to lowercase,
1426 * character references are decoded to UTF-8 text.
1427 *
1428 * @param string $text
1429 * @return array
1430 */
1431 public static function decodeTagAttributes( $text ) {
1432 if ( trim( $text ) == '' ) {
1433 return [];
1434 }
1435
1436 $attribs = [];
1437 $pairs = [];
1438 if ( !preg_match_all(
1439 self::getAttribsRegex(),
1440 $text,
1441 $pairs,
1442 PREG_SET_ORDER ) ) {
1443 return $attribs;
1444 }
1445
1446 foreach ( $pairs as $set ) {
1447 $attribute = strtolower( $set[1] );
1448 $value = self::getTagAttributeCallback( $set );
1449
1450 // Normalize whitespace
1451 $value = preg_replace( '/[\t\r\n ]+/', ' ', $value );
1452 $value = trim( $value );
1453
1454 // Decode character references
1455 $attribs[$attribute] = self::decodeCharReferences( $value );
1456 }
1457 return $attribs;
1458 }
1459
1460 /**
1461 * Build a partial tag string from an associative array of attribute
1462 * names and values as returned by decodeTagAttributes.
1463 *
1464 * @param array $assoc_array
1465 * @return string
1466 */
1467 public static function safeEncodeTagAttributes( $assoc_array ) {
1468 $attribs = [];
1469 foreach ( $assoc_array as $attribute => $value ) {
1470 $encAttribute = htmlspecialchars( $attribute );
1471 $encValue = self::safeEncodeAttribute( $value );
1472
1473 $attribs[] = "$encAttribute=\"$encValue\"";
1474 }
1475 return count( $attribs ) ? ' ' . implode( ' ', $attribs ) : '';
1476 }
1477
1478 /**
1479 * Pick the appropriate attribute value from a match set from the
1480 * attribs regex matches.
1481 *
1482 * @param array $set
1483 * @throws MWException When tag conditions are not met.
1484 * @return string
1485 */
1486 private static function getTagAttributeCallback( $set ) {
1487 if ( isset( $set[5] ) ) {
1488 # No quotes.
1489 return $set[5];
1490 } elseif ( isset( $set[4] ) ) {
1491 # Single-quoted
1492 return $set[4];
1493 } elseif ( isset( $set[3] ) ) {
1494 # Double-quoted
1495 return $set[3];
1496 } elseif ( !isset( $set[2] ) ) {
1497 # In XHTML, attributes must have a value so return an empty string.
1498 # See "Empty attribute syntax",
1499 # https://www.w3.org/TR/html5/syntax.html#syntax-attribute-name
1500 return "";
1501 } else {
1502 throw new MWException( "Tag conditions not met. This should never happen and is a bug." );
1503 }
1504 }
1505
1506 /**
1507 * @param string $text
1508 * @return string
1509 */
1510 private static function normalizeWhitespace( $text ) {
1511 return trim( preg_replace(
1512 '/(?:\r\n|[\x20\x0d\x0a\x09])+/',
1513 ' ',
1514 $text ) );
1515 }
1516
1517 /**
1518 * Normalizes whitespace in a section name, such as might be returned
1519 * by Parser::stripSectionName(), for use in the id's that are used for
1520 * section links.
1521 *
1522 * @param string $section
1523 * @return string
1524 */
1525 static function normalizeSectionNameWhitespace( $section ) {
1526 return trim( preg_replace( '/[ _]+/', ' ', $section ) );
1527 }
1528
1529 /**
1530 * Ensure that any entities and character references are legal
1531 * for XML and XHTML specifically. Any stray bits will be
1532 * &amp;-escaped to result in a valid text fragment.
1533 *
1534 * a. named char refs can only be &lt; &gt; &amp; &quot;, others are
1535 * numericized (this way we're well-formed even without a DTD)
1536 * b. any numeric char refs must be legal chars, not invalid or forbidden
1537 * c. use lower cased "&#x", not "&#X"
1538 * d. fix or reject non-valid attributes
1539 *
1540 * @param string $text
1541 * @return string
1542 * @private
1543 */
1544 static function normalizeCharReferences( $text ) {
1545 return preg_replace_callback(
1546 self::CHAR_REFS_REGEX,
1547 [ self::class, 'normalizeCharReferencesCallback' ],
1548 $text );
1549 }
1550
1551 /**
1552 * @param string $matches
1553 * @return string
1554 */
1555 static function normalizeCharReferencesCallback( $matches ) {
1556 $ret = null;
1557 if ( $matches[1] != '' ) {
1558 $ret = self::normalizeEntity( $matches[1] );
1559 } elseif ( $matches[2] != '' ) {
1560 $ret = self::decCharReference( $matches[2] );
1561 } elseif ( $matches[3] != '' ) {
1562 $ret = self::hexCharReference( $matches[3] );
1563 }
1564 if ( is_null( $ret ) ) {
1565 return htmlspecialchars( $matches[0] );
1566 } else {
1567 return $ret;
1568 }
1569 }
1570
1571 /**
1572 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
1573 * return the equivalent numeric entity reference (except for the core &lt;
1574 * &gt; &amp; &quot;). If the entity is a MediaWiki-specific alias, returns
1575 * the HTML equivalent. Otherwise, returns HTML-escaped text of
1576 * pseudo-entity source (eg &amp;foo;)
1577 *
1578 * @param string $name
1579 * @return string
1580 */
1581 static function normalizeEntity( $name ) {
1582 if ( isset( self::$htmlEntityAliases[$name] ) ) {
1583 return '&' . self::$htmlEntityAliases[$name] . ';';
1584 } elseif ( in_array( $name, [ 'lt', 'gt', 'amp', 'quot' ] ) ) {
1585 return "&$name;";
1586 } elseif ( isset( self::$htmlEntities[$name] ) ) {
1587 return '&#' . self::$htmlEntities[$name] . ';';
1588 } else {
1589 return "&amp;$name;";
1590 }
1591 }
1592
1593 /**
1594 * @param int $codepoint
1595 * @return null|string
1596 */
1597 static function decCharReference( $codepoint ) {
1598 $point = intval( $codepoint );
1599 if ( self::validateCodepoint( $point ) ) {
1600 return sprintf( '&#%d;', $point );
1601 } else {
1602 return null;
1603 }
1604 }
1605
1606 /**
1607 * @param int $codepoint
1608 * @return null|string
1609 */
1610 static function hexCharReference( $codepoint ) {
1611 $point = hexdec( $codepoint );
1612 if ( self::validateCodepoint( $point ) ) {
1613 return sprintf( '&#x%x;', $point );
1614 } else {
1615 return null;
1616 }
1617 }
1618
1619 /**
1620 * Returns true if a given Unicode codepoint is a valid character in
1621 * both HTML5 and XML.
1622 * @param int $codepoint
1623 * @return bool
1624 */
1625 private static function validateCodepoint( $codepoint ) {
1626 # U+000C is valid in HTML5 but not allowed in XML.
1627 # U+000D is valid in XML but not allowed in HTML5.
1628 # U+007F - U+009F are disallowed in HTML5 (control characters).
1629 return $codepoint == 0x09
1630 || $codepoint == 0x0a
1631 || ( $codepoint >= 0x20 && $codepoint <= 0x7e )
1632 || ( $codepoint >= 0xa0 && $codepoint <= 0xd7ff )
1633 || ( $codepoint >= 0xe000 && $codepoint <= 0xfffd )
1634 || ( $codepoint >= 0x10000 && $codepoint <= 0x10ffff );
1635 }
1636
1637 /**
1638 * Decode any character references, numeric or named entities,
1639 * in the text and return a UTF-8 string.
1640 *
1641 * @param string $text
1642 * @return string
1643 */
1644 public static function decodeCharReferences( $text ) {
1645 return preg_replace_callback(
1646 self::CHAR_REFS_REGEX,
1647 [ self::class, 'decodeCharReferencesCallback' ],
1648 $text );
1649 }
1650
1651 /**
1652 * Decode any character references, numeric or named entities,
1653 * in the next and normalize the resulting string. (T16952)
1654 *
1655 * This is useful for page titles, not for text to be displayed,
1656 * MediaWiki allows HTML entities to escape normalization as a feature.
1657 *
1658 * @param string $text Already normalized, containing entities
1659 * @return string Still normalized, without entities
1660 */
1661 public static function decodeCharReferencesAndNormalize( $text ) {
1662 $text = preg_replace_callback(
1663 self::CHAR_REFS_REGEX,
1664 [ self::class, 'decodeCharReferencesCallback' ],
1665 $text,
1666 -1, //limit
1667 $count
1668 );
1669
1670 if ( $count ) {
1671 return MediaWikiServices::getInstance()->getContentLanguage()->normalize( $text );
1672 } else {
1673 return $text;
1674 }
1675 }
1676
1677 /**
1678 * @param string $matches
1679 * @return string
1680 */
1681 static function decodeCharReferencesCallback( $matches ) {
1682 if ( $matches[1] != '' ) {
1683 return self::decodeEntity( $matches[1] );
1684 } elseif ( $matches[2] != '' ) {
1685 return self::decodeChar( intval( $matches[2] ) );
1686 } elseif ( $matches[3] != '' ) {
1687 return self::decodeChar( hexdec( $matches[3] ) );
1688 }
1689 # Last case should be an ampersand by itself
1690 return $matches[0];
1691 }
1692
1693 /**
1694 * Return UTF-8 string for a codepoint if that is a valid
1695 * character reference, otherwise U+FFFD REPLACEMENT CHARACTER.
1696 * @param int $codepoint
1697 * @return string
1698 * @private
1699 */
1700 static function decodeChar( $codepoint ) {
1701 if ( self::validateCodepoint( $codepoint ) ) {
1702 return UtfNormal\Utils::codepointToUtf8( $codepoint );
1703 } else {
1704 return UtfNormal\Constants::UTF8_REPLACEMENT;
1705 }
1706 }
1707
1708 /**
1709 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
1710 * return the UTF-8 encoding of that character. Otherwise, returns
1711 * pseudo-entity source (eg "&foo;")
1712 *
1713 * @param string $name
1714 * @return string
1715 */
1716 static function decodeEntity( $name ) {
1717 if ( isset( self::$htmlEntityAliases[$name] ) ) {
1718 $name = self::$htmlEntityAliases[$name];
1719 }
1720 if ( isset( self::$htmlEntities[$name] ) ) {
1721 return UtfNormal\Utils::codepointToUtf8( self::$htmlEntities[$name] );
1722 } else {
1723 return "&$name;";
1724 }
1725 }
1726
1727 /**
1728 * Fetch the whitelist of acceptable attributes for a given element name.
1729 *
1730 * @param string $element
1731 * @return array
1732 */
1733 static function attributeWhitelist( $element ) {
1734 $list = self::setupAttributeWhitelist();
1735 return $list[$element] ?? [];
1736 }
1737
1738 /**
1739 * Foreach array key (an allowed HTML element), return an array
1740 * of allowed attributes
1741 * @return array
1742 */
1743 static function setupAttributeWhitelist() {
1744 static $whitelist;
1745
1746 if ( $whitelist !== null ) {
1747 return $whitelist;
1748 }
1749
1750 $common = [
1751 # HTML
1752 'id',
1753 'class',
1754 'style',
1755 'lang',
1756 'dir',
1757 'title',
1758
1759 # WAI-ARIA
1760 'aria-describedby',
1761 'aria-flowto',
1762 'aria-label',
1763 'aria-labelledby',
1764 'aria-owns',
1765 'role',
1766
1767 # RDFa
1768 # These attributes are specified in section 9 of
1769 # https://www.w3.org/TR/2008/REC-rdfa-syntax-20081014
1770 'about',
1771 'property',
1772 'resource',
1773 'datatype',
1774 'typeof',
1775
1776 # Microdata. These are specified by
1777 # https://html.spec.whatwg.org/multipage/microdata.html#the-microdata-model
1778 'itemid',
1779 'itemprop',
1780 'itemref',
1781 'itemscope',
1782 'itemtype',
1783 ];
1784
1785 $block = array_merge( $common, [ 'align' ] );
1786 $tablealign = [ 'align', 'valign' ];
1787 $tablecell = [
1788 'abbr',
1789 'axis',
1790 'headers',
1791 'scope',
1792 'rowspan',
1793 'colspan',
1794 'nowrap', # deprecated
1795 'width', # deprecated
1796 'height', # deprecated
1797 'bgcolor', # deprecated
1798 ];
1799
1800 # Numbers refer to sections in HTML 4.01 standard describing the element.
1801 # See: https://www.w3.org/TR/html4/
1802 $whitelist = [
1803 # 7.5.4
1804 'div' => $block,
1805 'center' => $common, # deprecated
1806 'span' => $common,
1807
1808 # 7.5.5
1809 'h1' => $block,
1810 'h2' => $block,
1811 'h3' => $block,
1812 'h4' => $block,
1813 'h5' => $block,
1814 'h6' => $block,
1815
1816 # 7.5.6
1817 # address
1818
1819 # 8.2.4
1820 'bdo' => $common,
1821
1822 # 9.2.1
1823 'em' => $common,
1824 'strong' => $common,
1825 'cite' => $common,
1826 'dfn' => $common,
1827 'code' => $common,
1828 'samp' => $common,
1829 'kbd' => $common,
1830 'var' => $common,
1831 'abbr' => $common,
1832 # acronym
1833
1834 # 9.2.2
1835 'blockquote' => array_merge( $common, [ 'cite' ] ),
1836 'q' => array_merge( $common, [ 'cite' ] ),
1837
1838 # 9.2.3
1839 'sub' => $common,
1840 'sup' => $common,
1841
1842 # 9.3.1
1843 'p' => $block,
1844
1845 # 9.3.2
1846 'br' => array_merge( $common, [ 'clear' ] ),
1847
1848 # https://www.w3.org/TR/html5/text-level-semantics.html#the-wbr-element
1849 'wbr' => $common,
1850
1851 # 9.3.4
1852 'pre' => array_merge( $common, [ 'width' ] ),
1853
1854 # 9.4
1855 'ins' => array_merge( $common, [ 'cite', 'datetime' ] ),
1856 'del' => array_merge( $common, [ 'cite', 'datetime' ] ),
1857
1858 # 10.2
1859 'ul' => array_merge( $common, [ 'type' ] ),
1860 'ol' => array_merge( $common, [ 'type', 'start', 'reversed' ] ),
1861 'li' => array_merge( $common, [ 'type', 'value' ] ),
1862
1863 # 10.3
1864 'dl' => $common,
1865 'dd' => $common,
1866 'dt' => $common,
1867
1868 # 11.2.1
1869 'table' => array_merge( $common,
1870 [ 'summary', 'width', 'border', 'frame',
1871 'rules', 'cellspacing', 'cellpadding',
1872 'align', 'bgcolor',
1873 ] ),
1874
1875 # 11.2.2
1876 'caption' => $block,
1877
1878 # 11.2.3
1879 'thead' => $common,
1880 'tfoot' => $common,
1881 'tbody' => $common,
1882
1883 # 11.2.4
1884 'colgroup' => array_merge( $common, [ 'span' ] ),
1885 'col' => array_merge( $common, [ 'span' ] ),
1886
1887 # 11.2.5
1888 'tr' => array_merge( $common, [ 'bgcolor' ], $tablealign ),
1889
1890 # 11.2.6
1891 'td' => array_merge( $common, $tablecell, $tablealign ),
1892 'th' => array_merge( $common, $tablecell, $tablealign ),
1893
1894 # 12.2
1895 # NOTE: <a> is not allowed directly, but the attrib
1896 # whitelist is used from the Parser object
1897 'a' => array_merge( $common, [ 'href', 'rel', 'rev' ] ), # rel/rev esp. for RDFa
1898
1899 # 13.2
1900 # Not usually allowed, but may be used for extension-style hooks
1901 # such as <math> when it is rasterized, or if $wgAllowImageTag is
1902 # true
1903 'img' => array_merge( $common, [ 'alt', 'src', 'width', 'height', 'srcset' ] ),
1904
1905 'video' => array_merge( $common, [ 'poster', 'controls', 'preload', 'width', 'height' ] ),
1906 'source' => array_merge( $common, [ 'type', 'src' ] ),
1907 'track' => array_merge( $common, [ 'type', 'src', 'srclang', 'kind', 'label' ] ),
1908
1909 # 15.2.1
1910 'tt' => $common,
1911 'b' => $common,
1912 'i' => $common,
1913 'big' => $common,
1914 'small' => $common,
1915 'strike' => $common,
1916 's' => $common,
1917 'u' => $common,
1918
1919 # 15.2.2
1920 'font' => array_merge( $common, [ 'size', 'color', 'face' ] ),
1921 # basefont
1922
1923 # 15.3
1924 'hr' => array_merge( $common, [ 'width' ] ),
1925
1926 # HTML Ruby annotation text module, simple ruby only.
1927 # https://www.w3.org/TR/html5/text-level-semantics.html#the-ruby-element
1928 'ruby' => $common,
1929 # rbc
1930 'rb' => $common,
1931 'rp' => $common,
1932 'rt' => $common, # array_merge( $common, array( 'rbspan' ) ),
1933 'rtc' => $common,
1934
1935 # MathML root element, where used for extensions
1936 # 'title' may not be 100% valid here; it's XHTML
1937 # https://www.w3.org/TR/REC-MathML/
1938 'math' => [ 'class', 'style', 'id', 'title' ],
1939
1940 // HTML 5 section 4.5
1941 'figure' => $common,
1942 'figcaption' => $common,
1943
1944 # HTML 5 section 4.6
1945 'bdi' => $common,
1946
1947 # HTML5 elements, defined by:
1948 # https://html.spec.whatwg.org/multipage/semantics.html#the-data-element
1949 'data' => array_merge( $common, [ 'value' ] ),
1950 'time' => array_merge( $common, [ 'datetime' ] ),
1951 'mark' => $common,
1952
1953 // meta and link are only permitted by removeHTMLtags when Microdata
1954 // is enabled so we don't bother adding a conditional to hide these
1955 // Also meta and link are only valid in WikiText as Microdata elements
1956 // (ie: validateTag rejects tags missing the attributes needed for Microdata)
1957 // So we don't bother including $common attributes that have no purpose.
1958 'meta' => [ 'itemprop', 'content' ],
1959 'link' => [ 'itemprop', 'href', 'title' ],
1960 ];
1961
1962 return $whitelist;
1963 }
1964
1965 /**
1966 * Take a fragment of (potentially invalid) HTML and return
1967 * a version with any tags removed, encoded as plain text.
1968 *
1969 * Warning: this return value must be further escaped for literal
1970 * inclusion in HTML output as of 1.10!
1971 *
1972 * @param string $html HTML fragment
1973 * @return string
1974 */
1975 static function stripAllTags( $html ) {
1976 // Use RemexHtml to tokenize $html and extract the text
1977 $handler = new RemexStripTagHandler;
1978 $tokenizer = new RemexHtml\Tokenizer\Tokenizer( $handler, $html, [
1979 'ignoreErrors' => true,
1980 // don't ignore char refs, we want them to be decoded
1981 'ignoreNulls' => true,
1982 'skipPreprocess' => true,
1983 ] );
1984 $tokenizer->execute();
1985 $text = $handler->getResult();
1986
1987 $text = self::normalizeWhitespace( $text );
1988 return $text;
1989 }
1990
1991 /**
1992 * Hack up a private DOCTYPE with HTML's standard entity declarations.
1993 * PHP 4 seemed to know these if you gave it an HTML doctype, but
1994 * PHP 5.1 doesn't.
1995 *
1996 * Use for passing XHTML fragments to PHP's XML parsing functions
1997 *
1998 * @return string
1999 */
2000 static function hackDocType() {
2001 $out = "<!DOCTYPE html [\n";
2002 foreach ( self::$htmlEntities as $entity => $codepoint ) {
2003 $out .= "<!ENTITY $entity \"&#$codepoint;\">";
2004 }
2005 $out .= "]>\n";
2006 return $out;
2007 }
2008
2009 /**
2010 * @param string $url
2011 * @return mixed|string
2012 */
2013 static function cleanUrl( $url ) {
2014 # Normalize any HTML entities in input. They will be
2015 # re-escaped by makeExternalLink().
2016 $url = self::decodeCharReferences( $url );
2017
2018 # Escape any control characters introduced by the above step
2019 $url = preg_replace_callback( '/[\][<>"\\x00-\\x20\\x7F\|]/',
2020 [ __CLASS__, 'cleanUrlCallback' ], $url );
2021
2022 # Validate hostname portion
2023 $matches = [];
2024 if ( preg_match( '!^([^:]+:)(//[^/]+)?(.*)$!iD', $url, $matches ) ) {
2025 list( /* $whole */, $protocol, $host, $rest ) = $matches;
2026
2027 // Characters that will be ignored in IDNs.
2028 // https://tools.ietf.org/html/rfc3454#section-3.1
2029 // Strip them before further processing so blacklists and such work.
2030 $strip = "/
2031 \\s| # general whitespace
2032 \xc2\xad| # 00ad SOFT HYPHEN
2033 \xe1\xa0\x86| # 1806 MONGOLIAN TODO SOFT HYPHEN
2034 \xe2\x80\x8b| # 200b ZERO WIDTH SPACE
2035 \xe2\x81\xa0| # 2060 WORD JOINER
2036 \xef\xbb\xbf| # feff ZERO WIDTH NO-BREAK SPACE
2037 \xcd\x8f| # 034f COMBINING GRAPHEME JOINER
2038 \xe1\xa0\x8b| # 180b MONGOLIAN FREE VARIATION SELECTOR ONE
2039 \xe1\xa0\x8c| # 180c MONGOLIAN FREE VARIATION SELECTOR TWO
2040 \xe1\xa0\x8d| # 180d MONGOLIAN FREE VARIATION SELECTOR THREE
2041 \xe2\x80\x8c| # 200c ZERO WIDTH NON-JOINER
2042 \xe2\x80\x8d| # 200d ZERO WIDTH JOINER
2043 [\xef\xb8\x80-\xef\xb8\x8f] # fe00-fe0f VARIATION SELECTOR-1-16
2044 /xuD";
2045
2046 $host = preg_replace( $strip, '', $host );
2047
2048 // IPv6 host names are bracketed with []. Url-decode these.
2049 if ( substr_compare( "//%5B", $host, 0, 5 ) === 0 &&
2050 preg_match( '!^//%5B([0-9A-Fa-f:.]+)%5D((:\d+)?)$!', $host, $matches )
2051 ) {
2052 $host = '//[' . $matches[1] . ']' . $matches[2];
2053 }
2054
2055 // @todo FIXME: Validate hostnames here
2056
2057 return $protocol . $host . $rest;
2058 } else {
2059 return $url;
2060 }
2061 }
2062
2063 /**
2064 * @param array $matches
2065 * @return string
2066 */
2067 static function cleanUrlCallback( $matches ) {
2068 return urlencode( $matches[0] );
2069 }
2070
2071 /**
2072 * Does a string look like an e-mail address?
2073 *
2074 * This validates an email address using an HTML5 specification found at:
2075 * http://www.whatwg.org/html/states-of-the-type-attribute.html#valid-e-mail-address
2076 * Which as of 2011-01-24 says:
2077 *
2078 * A valid e-mail address is a string that matches the ABNF production
2079 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
2080 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
2081 * 3.5.
2082 *
2083 * This function is an implementation of the specification as requested in
2084 * T24449.
2085 *
2086 * Client-side forms will use the same standard validation rules via JS or
2087 * HTML 5 validation; additional restrictions can be enforced server-side
2088 * by extensions via the 'isValidEmailAddr' hook.
2089 *
2090 * Note that this validation doesn't 100% match RFC 2822, but is believed
2091 * to be liberal enough for wide use. Some invalid addresses will still
2092 * pass validation here.
2093 *
2094 * @since 1.18
2095 *
2096 * @param string $addr E-mail address
2097 * @return bool
2098 */
2099 public static function validateEmail( $addr ) {
2100 $result = null;
2101 if ( !Hooks::run( 'isValidEmailAddr', [ $addr, &$result ] ) ) {
2102 return $result;
2103 }
2104
2105 // Please note strings below are enclosed in brackets [], this make the
2106 // hyphen "-" a range indicator. Hence it is double backslashed below.
2107 // See T28948
2108 $rfc5322_atext = "a-z0-9!#$%&'*+\\-\/=?^_`{|}~";
2109 $rfc1034_ldh_str = "a-z0-9\\-";
2110
2111 $html5_email_regexp = "/
2112 ^ # start of string
2113 [$rfc5322_atext\\.]+ # user part which is liberal :p
2114 @ # 'apostrophe'
2115 [$rfc1034_ldh_str]+ # First domain part
2116 (\\.[$rfc1034_ldh_str]+)* # Following part prefixed with a dot
2117 $ # End of string
2118 /ix"; // case Insensitive, eXtended
2119
2120 return (bool)preg_match( $html5_email_regexp, $addr );
2121 }
2122 }