MediaWiki REL1_32
Sanitizer.php
Go to the documentation of this file.
1<?php
28
33class Sanitizer {
39 '/&([A-Za-z0-9\x80-\xff]+);
40 |&\#([0-9]+);
41 |&\#[xX]([0-9A-Fa-f]+);
42 |(&)/x';
43
48 const ELEMENT_BITS_REGEX = '!^(/?)([A-Za-z][^\t\n\v />\0]*+)([^>]*?)(/?>)([^<]*)$!';
49
58 const EVIL_URI_PATTERN = '!(^|\s|\*/\s*)(javascript|vbscript)([^\w]|$)!i';
59 const XMLNS_ATTRIBUTE_PATTERN = "/^xmlns:[:A-Z_a-z-.0-9]+$/";
60
66 const ID_PRIMARY = 0;
67
74 const ID_FALLBACK = 1;
75
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
340 private static $htmlEntityAliases = [
341 'רלמ' => 'rlm',
342 'رلم' => 'rlm',
343 ];
344
348 private static $attribsRegex;
349
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
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
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
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
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
774 static function validateTagAttributes( $attribs, $element ) {
775 return self::validateAttributes( $attribs,
776 self::attributeWhitelist( $element ) );
777 }
778
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
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
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
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
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 | var\s*\‍(
1060 !ix', $value ) ) {
1061 return '/* insecure input */';
1062 }
1063 return $value;
1064 }
1065
1070 static function cssDecodeCallback( $matches ) {
1071 if ( $matches[1] !== '' ) {
1072 // Line continuation
1073 return '';
1074 } elseif ( $matches[2] !== '' ) {
1075 $char = UtfNormal\Utils::codepointToUtf8( hexdec( $matches[2] ) );
1076 } elseif ( $matches[3] !== '' ) {
1077 $char = $matches[3];
1078 } else {
1079 $char = '\\';
1080 }
1081 if ( $char == "\n" || $char == '"' || $char == "'" || $char == '\\' ) {
1082 // These characters need to be escaped in strings
1083 // Clean up the escape sequence to avoid parsing errors by clients
1084 return '\\' . dechex( ord( $char ) ) . ' ';
1085 } else {
1086 // Decode unnecessary escape
1087 return $char;
1088 }
1089 }
1090
1112 static function fixTagAttributes( $text, $element, $sorted = false ) {
1113 if ( trim( $text ) == '' ) {
1114 return '';
1115 }
1116
1117 $decoded = self::decodeTagAttributes( $text );
1118 $stripped = self::validateTagAttributes( $decoded, $element );
1119
1120 if ( $sorted ) {
1121 ksort( $stripped );
1122 }
1123
1124 return self::safeEncodeTagAttributes( $stripped );
1125 }
1126
1132 static function encodeAttribute( $text ) {
1133 $encValue = htmlspecialchars( $text, ENT_QUOTES );
1134
1135 // Whitespace is normalized during attribute decoding,
1136 // so if we've been passed non-spaces we must encode them
1137 // ahead of time or they won't be preserved.
1138 $encValue = strtr( $encValue, [
1139 "\n" => '&#10;',
1140 "\r" => '&#13;',
1141 "\t" => '&#9;',
1142 ] );
1143
1144 return $encValue;
1145 }
1146
1155 public static function armorFrenchSpaces( $text, $space = '&#160;' ) {
1156 // Replace $ with \$ and \ with \\
1157 $space = preg_replace( '#(?<!\\\\‍)(\\$|\\\\‍)#', '\\\\$1', $space );
1158 $fixtags = [
1159 # French spaces, last one Guillemet-left
1160 # only if there is something before the space
1161 # and a non-word character after the punctuation.
1162 '/(\S) (?=[?:;!%»›](?!\w))/u' => "\\1$space",
1163 # French spaces, Guillemet-right
1164 '/([«‹]) /u' => "\\1$space",
1165 ];
1166 return preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
1167 }
1168
1175 static function safeEncodeAttribute( $text ) {
1176 $encValue = self::encodeAttribute( $text );
1177
1178 # Templates and links may be expanded in later parsing,
1179 # creating invalid or dangerous output. Suppress this.
1180 $encValue = strtr( $encValue, [
1181 '<' => '&lt;', // This should never happen,
1182 '>' => '&gt;', // we've received invalid input
1183 '"' => '&quot;', // which should have been escaped.
1184 '{' => '&#123;',
1185 '}' => '&#125;', // prevent unpaired language conversion syntax
1186 '[' => '&#91;',
1187 ']' => '&#93;',
1188 "''" => '&#39;&#39;',
1189 'ISBN' => '&#73;SBN',
1190 'RFC' => '&#82;FC',
1191 'PMID' => '&#80;MID',
1192 '|' => '&#124;',
1193 '__' => '&#95;_',
1194 ] );
1195
1196 # Armor against French spaces detection (T5158)
1197 $encValue = self::armorFrenchSpaces( $encValue, '&#32;' );
1198
1199 # Stupid hack
1200 $encValue = preg_replace_callback(
1201 '/((?i)' . wfUrlProtocols() . ')/',
1202 function ( $matches ) {
1203 return str_replace( ':', '&#58;', $matches[1] );
1204 },
1205 $encValue );
1206 return $encValue;
1207 }
1208
1237 static function escapeId( $id, $options = [] ) {
1239
1240 // HTML4-style escaping
1241 static $replace = [
1242 '%3A' => ':',
1243 '%' => '.'
1244 ];
1245
1246 $id = urlencode( strtr( $id, ' ', '_' ) );
1247 $id = strtr( $id, $replace );
1248
1249 if ( !preg_match( '/^[a-zA-Z]/', $id ) && !in_array( 'noninitial', $options ) ) {
1250 // Initial character must be a letter!
1251 $id = "x$id";
1252 }
1253 return $id;
1254 }
1255
1271 public static function escapeIdForAttribute( $id, $mode = self::ID_PRIMARY ) {
1272 global $wgFragmentMode;
1273
1274 if ( !isset( $wgFragmentMode[$mode] ) ) {
1275 if ( $mode === self::ID_PRIMARY ) {
1276 throw new UnexpectedValueException( '$wgFragmentMode is configured with no primary mode' );
1277 }
1278 return false;
1279 }
1280
1281 $internalMode = $wgFragmentMode[$mode];
1282
1283 return self::escapeIdInternal( $id, $internalMode );
1284 }
1285
1298 public static function escapeIdForLink( $id ) {
1299 global $wgFragmentMode;
1300
1301 if ( !isset( $wgFragmentMode[self::ID_PRIMARY] ) ) {
1302 throw new UnexpectedValueException( '$wgFragmentMode is configured with no primary mode' );
1303 }
1304
1305 $mode = $wgFragmentMode[self::ID_PRIMARY];
1306
1307 $id = self::escapeIdInternal( $id, $mode );
1308
1309 return $id;
1310 }
1311
1321 public static function escapeIdForExternalInterwiki( $id ) {
1323
1324 $id = self::escapeIdInternal( $id, $wgExternalInterwikiFragmentMode );
1325
1326 return $id;
1327 }
1328
1336 private static function escapeIdInternal( $id, $mode ) {
1337 switch ( $mode ) {
1338 case 'html5':
1339 $id = str_replace( ' ', '_', $id );
1340 break;
1341 case 'legacy':
1342 // This corresponds to 'noninitial' mode of the old escapeId()
1343 static $replace = [
1344 '%3A' => ':',
1345 '%' => '.'
1346 ];
1347
1348 $id = urlencode( str_replace( ' ', '_', $id ) );
1349 $id = strtr( $id, $replace );
1350 break;
1351 default:
1352 throw new InvalidArgumentException( "Invalid mode '$mode' passed to '" . __METHOD__ );
1353 }
1354
1355 return $id;
1356 }
1357
1370 static function escapeIdReferenceList( $referenceString, $options = [] ) {
1371 if ( $options ) {
1372 wfDeprecated( __METHOD__ . ' with $options', '1.31' );
1373 }
1374 # Explode the space delimited list string into an array of tokens
1375 $references = preg_split( '/\s+/', "{$referenceString}", -1, PREG_SPLIT_NO_EMPTY );
1376
1377 # Escape each token as an id
1378 foreach ( $references as &$ref ) {
1379 $ref = self::escapeIdForAttribute( $ref );
1380 }
1381
1382 # Merge the array back to a space delimited list string
1383 # If the array is empty, the result will be an empty string ('')
1384 $referenceString = implode( ' ', $references );
1385
1386 return $referenceString;
1387 }
1388
1400 static function escapeClass( $class ) {
1401 // Convert ugly stuff to underscores and kill underscores in ugly places
1402 return rtrim( preg_replace(
1403 [ '/(^[0-9\\-])|[\\x00-\\x20!"#$%&\'()*+,.\\/:;<=>?@[\\]^`{|}~]|\\xC2\\xA0/', '/_+/' ],
1404 '_',
1405 $class ), '_' );
1406 }
1407
1415 static function escapeHtmlAllowEntities( $html ) {
1416 $html = self::decodeCharReferences( $html );
1417 # It seems wise to escape ' as well as ", as a matter of course. Can't
1418 # hurt. Use ENT_SUBSTITUTE so that incorrectly truncated multibyte characters
1419 # don't cause the entire string to disappear.
1420 $html = htmlspecialchars( $html, ENT_QUOTES | ENT_SUBSTITUTE );
1421 return $html;
1422 }
1423
1432 public static function decodeTagAttributes( $text ) {
1433 if ( trim( $text ) == '' ) {
1434 return [];
1435 }
1436
1437 $attribs = [];
1438 $pairs = [];
1439 if ( !preg_match_all(
1440 self::getAttribsRegex(),
1441 $text,
1442 $pairs,
1443 PREG_SET_ORDER ) ) {
1444 return $attribs;
1445 }
1446
1447 foreach ( $pairs as $set ) {
1448 $attribute = strtolower( $set[1] );
1449 $value = self::getTagAttributeCallback( $set );
1450
1451 // Normalize whitespace
1452 $value = preg_replace( '/[\t\r\n ]+/', ' ', $value );
1453 $value = trim( $value );
1454
1455 // Decode character references
1456 $attribs[$attribute] = self::decodeCharReferences( $value );
1457 }
1458 return $attribs;
1459 }
1460
1468 public static function safeEncodeTagAttributes( $assoc_array ) {
1469 $attribs = [];
1470 foreach ( $assoc_array as $attribute => $value ) {
1471 $encAttribute = htmlspecialchars( $attribute );
1472 $encValue = self::safeEncodeAttribute( $value );
1473
1474 $attribs[] = "$encAttribute=\"$encValue\"";
1475 }
1476 return count( $attribs ) ? ' ' . implode( ' ', $attribs ) : '';
1477 }
1478
1487 private static function getTagAttributeCallback( $set ) {
1488 if ( isset( $set[5] ) ) {
1489 # No quotes.
1490 return $set[5];
1491 } elseif ( isset( $set[4] ) ) {
1492 # Single-quoted
1493 return $set[4];
1494 } elseif ( isset( $set[3] ) ) {
1495 # Double-quoted
1496 return $set[3];
1497 } elseif ( !isset( $set[2] ) ) {
1498 # In XHTML, attributes must have a value so return an empty string.
1499 # See "Empty attribute syntax",
1500 # https://www.w3.org/TR/html5/syntax.html#syntax-attribute-name
1501 return "";
1502 } else {
1503 throw new MWException( "Tag conditions not met. This should never happen and is a bug." );
1504 }
1505 }
1506
1511 private static function normalizeWhitespace( $text ) {
1512 return trim( preg_replace(
1513 '/(?:\r\n|[\x20\x0d\x0a\x09])+/',
1514 ' ',
1515 $text ) );
1516 }
1517
1527 return trim( preg_replace( '/[ _]+/', ' ', $section ) );
1528 }
1529
1545 static function normalizeCharReferences( $text ) {
1546 return preg_replace_callback(
1547 self::CHAR_REFS_REGEX,
1548 [ self::class, 'normalizeCharReferencesCallback' ],
1549 $text );
1550 }
1551
1557 $ret = null;
1558 if ( $matches[1] != '' ) {
1559 $ret = self::normalizeEntity( $matches[1] );
1560 } elseif ( $matches[2] != '' ) {
1561 $ret = self::decCharReference( $matches[2] );
1562 } elseif ( $matches[3] != '' ) {
1563 $ret = self::hexCharReference( $matches[3] );
1564 }
1565 if ( is_null( $ret ) ) {
1566 return htmlspecialchars( $matches[0] );
1567 } else {
1568 return $ret;
1569 }
1570 }
1571
1582 static function normalizeEntity( $name ) {
1583 if ( isset( self::$htmlEntityAliases[$name] ) ) {
1584 return '&' . self::$htmlEntityAliases[$name] . ';';
1585 } elseif ( in_array( $name, [ 'lt', 'gt', 'amp', 'quot' ] ) ) {
1586 return "&$name;";
1587 } elseif ( isset( self::$htmlEntities[$name] ) ) {
1588 return '&#' . self::$htmlEntities[$name] . ';';
1589 } else {
1590 return "&amp;$name;";
1591 }
1592 }
1593
1598 static function decCharReference( $codepoint ) {
1599 $point = intval( $codepoint );
1600 if ( self::validateCodepoint( $point ) ) {
1601 return sprintf( '&#%d;', $point );
1602 } else {
1603 return null;
1604 }
1605 }
1606
1611 static function hexCharReference( $codepoint ) {
1612 $point = hexdec( $codepoint );
1613 if ( self::validateCodepoint( $point ) ) {
1614 return sprintf( '&#x%x;', $point );
1615 } else {
1616 return null;
1617 }
1618 }
1619
1626 private static function validateCodepoint( $codepoint ) {
1627 # U+000C is valid in HTML5 but not allowed in XML.
1628 # U+000D is valid in XML but not allowed in HTML5.
1629 # U+007F - U+009F are disallowed in HTML5 (control characters).
1630 return $codepoint == 0x09
1631 || $codepoint == 0x0a
1632 || ( $codepoint >= 0x20 && $codepoint <= 0x7e )
1633 || ( $codepoint >= 0xa0 && $codepoint <= 0xd7ff )
1634 || ( $codepoint >= 0xe000 && $codepoint <= 0xfffd )
1635 || ( $codepoint >= 0x10000 && $codepoint <= 0x10ffff );
1636 }
1637
1645 public static function decodeCharReferences( $text ) {
1646 return preg_replace_callback(
1647 self::CHAR_REFS_REGEX,
1648 [ self::class, 'decodeCharReferencesCallback' ],
1649 $text );
1650 }
1651
1662 public static function decodeCharReferencesAndNormalize( $text ) {
1663 $text = preg_replace_callback(
1664 self::CHAR_REFS_REGEX,
1665 [ self::class, 'decodeCharReferencesCallback' ],
1666 $text,
1667 -1, //limit
1668 $count
1669 );
1670
1671 if ( $count ) {
1672 return MediaWikiServices::getInstance()->getContentLanguage()->normalize( $text );
1673 } else {
1674 return $text;
1675 }
1676 }
1677
1683 if ( $matches[1] != '' ) {
1684 return self::decodeEntity( $matches[1] );
1685 } elseif ( $matches[2] != '' ) {
1686 return self::decodeChar( intval( $matches[2] ) );
1687 } elseif ( $matches[3] != '' ) {
1688 return self::decodeChar( hexdec( $matches[3] ) );
1689 }
1690 # Last case should be an ampersand by itself
1691 return $matches[0];
1692 }
1693
1701 static function decodeChar( $codepoint ) {
1702 if ( self::validateCodepoint( $codepoint ) ) {
1703 return UtfNormal\Utils::codepointToUtf8( $codepoint );
1704 } else {
1705 return UtfNormal\Constants::UTF8_REPLACEMENT;
1706 }
1707 }
1708
1717 static function decodeEntity( $name ) {
1718 if ( isset( self::$htmlEntityAliases[$name] ) ) {
1719 $name = self::$htmlEntityAliases[$name];
1720 }
1721 if ( isset( self::$htmlEntities[$name] ) ) {
1722 return UtfNormal\Utils::codepointToUtf8( self::$htmlEntities[$name] );
1723 } else {
1724 return "&$name;";
1725 }
1726 }
1727
1734 static function attributeWhitelist( $element ) {
1735 $list = self::setupAttributeWhitelist();
1736 return $list[$element] ?? [];
1737 }
1738
1744 static function setupAttributeWhitelist() {
1745 static $whitelist;
1746
1747 if ( $whitelist !== null ) {
1748 return $whitelist;
1749 }
1750
1751 $common = [
1752 # HTML
1753 'id',
1754 'class',
1755 'style',
1756 'lang',
1757 'dir',
1758 'title',
1759
1760 # WAI-ARIA
1761 'aria-describedby',
1762 'aria-flowto',
1763 'aria-label',
1764 'aria-labelledby',
1765 'aria-owns',
1766 'role',
1767
1768 # RDFa
1769 # These attributes are specified in section 9 of
1770 # https://www.w3.org/TR/2008/REC-rdfa-syntax-20081014
1771 'about',
1772 'property',
1773 'resource',
1774 'datatype',
1775 'typeof',
1776
1777 # Microdata. These are specified by
1778 # https://html.spec.whatwg.org/multipage/microdata.html#the-microdata-model
1779 'itemid',
1780 'itemprop',
1781 'itemref',
1782 'itemscope',
1783 'itemtype',
1784 ];
1785
1786 $block = array_merge( $common, [ 'align' ] );
1787 $tablealign = [ 'align', 'valign' ];
1788 $tablecell = [
1789 'abbr',
1790 'axis',
1791 'headers',
1792 'scope',
1793 'rowspan',
1794 'colspan',
1795 'nowrap', # deprecated
1796 'width', # deprecated
1797 'height', # deprecated
1798 'bgcolor', # deprecated
1799 ];
1800
1801 # Numbers refer to sections in HTML 4.01 standard describing the element.
1802 # See: https://www.w3.org/TR/html4/
1803 $whitelist = [
1804 # 7.5.4
1805 'div' => $block,
1806 'center' => $common, # deprecated
1807 'span' => $common,
1808
1809 # 7.5.5
1810 'h1' => $block,
1811 'h2' => $block,
1812 'h3' => $block,
1813 'h4' => $block,
1814 'h5' => $block,
1815 'h6' => $block,
1816
1817 # 7.5.6
1818 # address
1819
1820 # 8.2.4
1821 'bdo' => $common,
1822
1823 # 9.2.1
1824 'em' => $common,
1825 'strong' => $common,
1826 'cite' => $common,
1827 'dfn' => $common,
1828 'code' => $common,
1829 'samp' => $common,
1830 'kbd' => $common,
1831 'var' => $common,
1832 'abbr' => $common,
1833 # acronym
1834
1835 # 9.2.2
1836 'blockquote' => array_merge( $common, [ 'cite' ] ),
1837 'q' => array_merge( $common, [ 'cite' ] ),
1838
1839 # 9.2.3
1840 'sub' => $common,
1841 'sup' => $common,
1842
1843 # 9.3.1
1844 'p' => $block,
1845
1846 # 9.3.2
1847 'br' => array_merge( $common, [ 'clear' ] ),
1848
1849 # https://www.w3.org/TR/html5/text-level-semantics.html#the-wbr-element
1850 'wbr' => $common,
1851
1852 # 9.3.4
1853 'pre' => array_merge( $common, [ 'width' ] ),
1854
1855 # 9.4
1856 'ins' => array_merge( $common, [ 'cite', 'datetime' ] ),
1857 'del' => array_merge( $common, [ 'cite', 'datetime' ] ),
1858
1859 # 10.2
1860 'ul' => array_merge( $common, [ 'type' ] ),
1861 'ol' => array_merge( $common, [ 'type', 'start', 'reversed' ] ),
1862 'li' => array_merge( $common, [ 'type', 'value' ] ),
1863
1864 # 10.3
1865 'dl' => $common,
1866 'dd' => $common,
1867 'dt' => $common,
1868
1869 # 11.2.1
1870 'table' => array_merge( $common,
1871 [ 'summary', 'width', 'border', 'frame',
1872 'rules', 'cellspacing', 'cellpadding',
1873 'align', 'bgcolor',
1874 ] ),
1875
1876 # 11.2.2
1877 'caption' => $block,
1878
1879 # 11.2.3
1880 'thead' => $common,
1881 'tfoot' => $common,
1882 'tbody' => $common,
1883
1884 # 11.2.4
1885 'colgroup' => array_merge( $common, [ 'span' ] ),
1886 'col' => array_merge( $common, [ 'span' ] ),
1887
1888 # 11.2.5
1889 'tr' => array_merge( $common, [ 'bgcolor' ], $tablealign ),
1890
1891 # 11.2.6
1892 'td' => array_merge( $common, $tablecell, $tablealign ),
1893 'th' => array_merge( $common, $tablecell, $tablealign ),
1894
1895 # 12.2
1896 # NOTE: <a> is not allowed directly, but the attrib
1897 # whitelist is used from the Parser object
1898 'a' => array_merge( $common, [ 'href', 'rel', 'rev' ] ), # rel/rev esp. for RDFa
1899
1900 # 13.2
1901 # Not usually allowed, but may be used for extension-style hooks
1902 # such as <math> when it is rasterized, or if $wgAllowImageTag is
1903 # true
1904 'img' => array_merge( $common, [ 'alt', 'src', 'width', 'height', 'srcset' ] ),
1905
1906 'video' => array_merge( $common, [ 'poster', 'controls', 'preload', 'width', 'height' ] ),
1907 'source' => array_merge( $common, [ 'type', 'src' ] ),
1908 'track' => array_merge( $common, [ 'type', 'src', 'srclang', 'kind', 'label' ] ),
1909
1910 # 15.2.1
1911 'tt' => $common,
1912 'b' => $common,
1913 'i' => $common,
1914 'big' => $common,
1915 'small' => $common,
1916 'strike' => $common,
1917 's' => $common,
1918 'u' => $common,
1919
1920 # 15.2.2
1921 'font' => array_merge( $common, [ 'size', 'color', 'face' ] ),
1922 # basefont
1923
1924 # 15.3
1925 'hr' => array_merge( $common, [ 'width' ] ),
1926
1927 # HTML Ruby annotation text module, simple ruby only.
1928 # https://www.w3.org/TR/html5/text-level-semantics.html#the-ruby-element
1929 'ruby' => $common,
1930 # rbc
1931 'rb' => $common,
1932 'rp' => $common,
1933 'rt' => $common, # array_merge( $common, array( 'rbspan' ) ),
1934 'rtc' => $common,
1935
1936 # MathML root element, where used for extensions
1937 # 'title' may not be 100% valid here; it's XHTML
1938 # https://www.w3.org/TR/REC-MathML/
1939 'math' => [ 'class', 'style', 'id', 'title' ],
1940
1941 // HTML 5 section 4.5
1942 'figure' => $common,
1943 'figcaption' => $common,
1944
1945 # HTML 5 section 4.6
1946 'bdi' => $common,
1947
1948 # HTML5 elements, defined by:
1949 # https://html.spec.whatwg.org/multipage/semantics.html#the-data-element
1950 'data' => array_merge( $common, [ 'value' ] ),
1951 'time' => array_merge( $common, [ 'datetime' ] ),
1952 'mark' => $common,
1953
1954 // meta and link are only permitted by removeHTMLtags when Microdata
1955 // is enabled so we don't bother adding a conditional to hide these
1956 // Also meta and link are only valid in WikiText as Microdata elements
1957 // (ie: validateTag rejects tags missing the attributes needed for Microdata)
1958 // So we don't bother including $common attributes that have no purpose.
1959 'meta' => [ 'itemprop', 'content' ],
1960 'link' => [ 'itemprop', 'href', 'title' ],
1961 ];
1962
1963 return $whitelist;
1964 }
1965
1976 static function stripAllTags( $html ) {
1977 // Use RemexHtml to tokenize $html and extract the text
1979 $tokenizer = new RemexHtml\Tokenizer\Tokenizer( $handler, $html, [
1980 'ignoreErrors' => true,
1981 // don't ignore char refs, we want them to be decoded
1982 'ignoreNulls' => true,
1983 'skipPreprocess' => true,
1984 ] );
1985 $tokenizer->execute();
1986 $text = $handler->getResult();
1987
1988 $text = self::normalizeWhitespace( $text );
1989 return $text;
1990 }
1991
2001 static function hackDocType() {
2002 $out = "<!DOCTYPE html [\n";
2003 foreach ( self::$htmlEntities as $entity => $codepoint ) {
2004 $out .= "<!ENTITY $entity \"&#$codepoint;\">";
2005 }
2006 $out .= "]>\n";
2007 return $out;
2008 }
2009
2014 static function cleanUrl( $url ) {
2015 # Normalize any HTML entities in input. They will be
2016 # re-escaped by makeExternalLink().
2017 $url = self::decodeCharReferences( $url );
2018
2019 # Escape any control characters introduced by the above step
2020 $url = preg_replace_callback( '/[\][<>"\\x00-\\x20\\x7F\|]/',
2021 [ __CLASS__, 'cleanUrlCallback' ], $url );
2022
2023 # Validate hostname portion
2024 $matches = [];
2025 if ( preg_match( '!^([^:]+:)(//[^/]+)?(.*)$!iD', $url, $matches ) ) {
2026 list( /* $whole */, $protocol, $host, $rest ) = $matches;
2027
2028 // Characters that will be ignored in IDNs.
2029 // https://tools.ietf.org/html/rfc3454#section-3.1
2030 // Strip them before further processing so blacklists and such work.
2031 $strip = "/
2032 \\s| # general whitespace
2033 \xc2\xad| # 00ad SOFT HYPHEN
2034 \xe1\xa0\x86| # 1806 MONGOLIAN TODO SOFT HYPHEN
2035 \xe2\x80\x8b| # 200b ZERO WIDTH SPACE
2036 \xe2\x81\xa0| # 2060 WORD JOINER
2037 \xef\xbb\xbf| # feff ZERO WIDTH NO-BREAK SPACE
2038 \xcd\x8f| # 034f COMBINING GRAPHEME JOINER
2039 \xe1\xa0\x8b| # 180b MONGOLIAN FREE VARIATION SELECTOR ONE
2040 \xe1\xa0\x8c| # 180c MONGOLIAN FREE VARIATION SELECTOR TWO
2041 \xe1\xa0\x8d| # 180d MONGOLIAN FREE VARIATION SELECTOR THREE
2042 \xe2\x80\x8c| # 200c ZERO WIDTH NON-JOINER
2043 \xe2\x80\x8d| # 200d ZERO WIDTH JOINER
2044 [\xef\xb8\x80-\xef\xb8\x8f] # fe00-fe0f VARIATION SELECTOR-1-16
2045 /xuD";
2046
2047 $host = preg_replace( $strip, '', $host );
2048
2049 // IPv6 host names are bracketed with []. Url-decode these.
2050 if ( substr_compare( "//%5B", $host, 0, 5 ) === 0 &&
2051 preg_match( '!^//%5B([0-9A-Fa-f:.]+)%5D((:\d+)?)$!', $host, $matches )
2052 ) {
2053 $host = '//[' . $matches[1] . ']' . $matches[2];
2054 }
2055
2056 // @todo FIXME: Validate hostnames here
2057
2058 return $protocol . $host . $rest;
2059 } else {
2060 return $url;
2061 }
2062 }
2063
2068 static function cleanUrlCallback( $matches ) {
2069 return urlencode( $matches[0] );
2070 }
2071
2100 public static function validateEmail( $addr ) {
2101 $result = null;
2102 if ( !Hooks::run( 'isValidEmailAddr', [ $addr, &$result ] ) ) {
2103 return $result;
2104 }
2105
2106 // Please note strings below are enclosed in brackets [], this make the
2107 // hyphen "-" a range indicator. Hence it is double backslashed below.
2108 // See T28948
2109 $rfc5322_atext = "a-z0-9!#$%&'*+\\-\/=?^_`{|}~";
2110 $rfc1034_ldh_str = "a-z0-9\\-";
2111
2112 $html5_email_regexp = "/
2113 ^ # start of string
2114 [$rfc5322_atext\\.]+ # user part which is liberal :p
2115 @ # 'apostrophe'
2116 [$rfc1034_ldh_str]+ # First domain part
2117 (\\.[$rfc1034_ldh_str]+)* # Following part prefixed with a dot
2118 $ # End of string
2119 /ix"; // case Insensitive, eXtended
2120
2121 return (bool)preg_match( $html5_email_regexp, $addr );
2122 }
2123}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for and distribution as defined by Sections through of this document Licensor shall mean the copyright owner or entity authorized by the copyright owner that is granting the License Legal Entity shall mean the union of the acting entity and all other entities that control are controlled by or are under common control with that entity For the purposes of this definition control direct or to cause the direction or management of such whether by contract or including but not limited to software source documentation and configuration files Object form shall mean any form resulting from mechanical transformation or translation of a Source including but not limited to compiled object generated and conversions to other media types Work shall mean the work of whether in Source or Object made available under the as indicated by a copyright notice that is included in or attached to the whether in Source or Object that is based or other modifications as a an original work of authorship For the purposes of this Derivative Works shall not include works that remain separable or merely the Work and Derivative Works thereof Contribution shall mean any work of including the original version of the Work and any modifications or additions to that Work or Derivative Works that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner For the purposes of this submitted means any form of or written communication sent to the Licensor or its including but not limited to communication on electronic mailing source code control and issue tracking systems that are managed by
</td >< td > &</td >< td > t want your writing to be edited mercilessly and redistributed at will
$wgAllowImageTag
A different approach to the above: simply allow the "<img>" tag to be used.
$wgFragmentMode
How should section IDs be encoded? This array can contain 1 or 2 elements, each of them can be one of...
$wgExternalInterwikiFragmentMode
Which ID escaping mode should be used for external interwiki links? See documentation for $wgFragment...
wfUrlProtocols( $includeProtocolRelative=true)
Returns a regular expression of url protocols.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
if( $line===false) $args
Definition cdb.php:64
MediaWiki exception.
static isEnabled()
Definition MWTidy.php:58
MediaWikiServices is the service locator for the application scope of MediaWiki.
HTML sanitizer for MediaWiki.
Definition Sanitizer.php:33
static fixTagAttributes( $text, $element, $sorted=false)
Take a tag soup fragment listing an HTML element's attributes and normalize it to well-formed XML,...
const CHAR_REFS_REGEX
Regular expression to match various types of character references in Sanitizer::normalizeCharReferenc...
Definition Sanitizer.php:38
static cleanUrl( $url)
static validateAttributes( $attribs, $whitelist)
Take an array of attribute names and values and normalize or discard illegal values for the given whi...
static decCharReference( $codepoint)
static isReservedDataAttribute( $attr)
Given an attribute name, checks whether it is a reserved data attribute (such as data-mw-foo) which i...
static decodeChar( $codepoint)
Return UTF-8 string for a codepoint if that is a valid character reference, otherwise U+FFFD REPLACEM...
static escapeHtmlAllowEntities( $html)
Given HTML input, escape with htmlspecialchars but un-escape entities.
static checkCss( $value)
Pick apart some CSS and check it for forbidden or unsafe structures.
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...
static normalizeEntity( $name)
If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD, return the equivalent numeric entity re...
static armorFrenchSpaces( $text, $space='&#160;')
Armor French spaces with a replacement character.
static getRecognizedTagData( $extratags=[], $removetags=[])
Return the various lists of recognized tags.
static $attribsRegex
Lazy-initialised attributes regex, see getAttribsRegex()
static escapeIdForLink( $id)
Given a section name or other user-generated or otherwise unsafe string, escapes it to be a valid URL...
static removeHTMLcomments( $text)
Remove '', and everything between.
static encodeAttribute( $text)
Encode an attribute value for HTML output.
static hexCharReference( $codepoint)
static validateTagAttributes( $attribs, $element)
Take an array of attribute names and values and normalize or discard illegal values for the given ele...
static escapeClass( $class)
Given a value, escape it so that it can be used as a CSS class and return it.
const EVIL_URI_PATTERN
Blacklist for evil uris like javascript: WARNING: DO NOT use this in any place that actually requires...
Definition Sanitizer.php:58
static normalizeSectionNameWhitespace( $section)
Normalizes whitespace in a section name, such as might be returned by Parser::stripSectionName(),...
static setupAttributeWhitelist()
Foreach array key (an allowed HTML element), return an array of allowed attributes.
static normalizeCharReferencesCallback( $matches)
static hackDocType()
Hack up a private DOCTYPE with HTML's standard entity declarations.
static cleanUrlCallback( $matches)
static normalizeCharReferences( $text)
Ensure that any entities and character references are legal for XML and XHTML specifically.
static escapeIdReferenceList( $referenceString, $options=[])
Given a string containing a space delimited list of ids, escape each id to match ids escaped by the e...
static cssDecodeCallback( $matches)
static normalizeWhitespace( $text)
static removeHTMLtags( $text, $processCallback=null, $args=[], $extratags=[], $removetags=[], $warnCallback=null)
Cleans up HTML, removes dangerous tags and attributes, and removes HTML comments.
static getAttribsRegex()
Regular expression to match HTML/XML attribute pairs within a tag.
static validateCodepoint( $codepoint)
Returns true if a given Unicode codepoint is a valid character in both HTML5 and XML.
const ID_FALLBACK
Tells escapeUrlForHtml() to encode the ID using the fallback encoding, or return false if no fallback...
Definition Sanitizer.php:74
static $htmlEntities
List of all named character entities defined in HTML 4.01 https://www.w3.org/TR/html4/sgml/entities....
Definition Sanitizer.php:81
static decodeCharReferences( $text)
Decode any character references, numeric or named entities, in the text and return a UTF-8 string.
static escapeIdForAttribute( $id, $mode=self::ID_PRIMARY)
Given a section name or other user-generated or otherwise unsafe string, escapes it to be a valid HTM...
static getTagAttributeCallback( $set)
Pick the appropriate attribute value from a match set from the attribs regex matches.
static escapeIdInternal( $id, $mode)
Helper for escapeIdFor*() functions.
static validateTag( $params, $element)
Takes attribute names and values for a tag and the tag name and validates that the tag is allowed to ...
static stripAllTags( $html)
Take a fragment of (potentially invalid) HTML and return a version with any tags removed,...
static decodeCharReferencesAndNormalize( $text)
Decode any character references, numeric or named entities, in the next and normalize the resulting s...
static $htmlEntityAliases
Character entity aliases accepted by MediaWiki.
static escapeId( $id, $options=[])
Given a value, escape it so that it can be used in an id attribute and return it.
static attributeWhitelist( $element)
Fetch the whitelist of acceptable attributes for a given element name.
static decodeCharReferencesCallback( $matches)
static mergeAttributes( $a, $b)
Merge two sets of HTML attributes.
static escapeIdForExternalInterwiki( $id)
Given a section name or other user-generated or otherwise unsafe string, escapes it to be a valid URL...
static validateEmail( $addr)
Does a string look like an e-mail address?
const ID_PRIMARY
Tells escapeUrlForHtml() to encode the ID using the wiki's primary encoding.
Definition Sanitizer.php:66
const ELEMENT_BITS_REGEX
Acceptable tag name charset from HTML5 parsing spec https://www.w3.org/TR/html5/syntax....
Definition Sanitizer.php:48
static safeEncodeAttribute( $text)
Encode an attribute value for HTML tags, with extra armoring against further wiki processing.
const XMLNS_ATTRIBUTE_PATTERN
Definition Sanitizer.php:59
static normalizeCss( $value)
Normalize CSS into a format we can easily search for hostile input.
static delimiterReplace( $startDelim, $endDelim, $replace, $subject, $flags='')
Perform an operation equivalent to preg_replace() with flags.
Unicode normalization routines for working with UTF-8 strings.
Definition UtfNormal.php:48
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition deferred.txt:11
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global then executing the whole list after the page is displayed We don t do anything smart like collating updates to the same table or such because the list is almost always going to have just one item on if that
Definition deferred.txt:13
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global then executing the whole list after the page is displayed We don t do anything smart like collating updates to the same table or such because the list is almost always going to have just one item on if so it s not worth the trouble Since there is a job queue in the jobs table
Definition deferred.txt:16
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
Definition hooks.txt:2278
this hook is for auditing only RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing them
Definition hooks.txt:1038
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\d*-\d*)") will be honored when streaming the file. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED since 1.16! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition hooks.txt:2042
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition hooks.txt:2050
null for the local wiki Added in
Definition hooks.txt:1627
you don t have to do a grep find to see where the $wgReverseTitle variable is used
Definition hooks.txt:115
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition hooks.txt:2054
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output $out
Definition hooks.txt:894
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses & $html
Definition hooks.txt:2062
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:302
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing & $attribs
Definition hooks.txt:2063
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check set to true or false to override the $wgMaxImageArea check result gives extension the possibility to transform it themselves $handler
Definition hooks.txt:933
usually copyright or history_copyright This message must be in HTML not wikitext if the section is included from a template $section
Definition hooks.txt:3107
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition injection.txt:37
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
$params