Add special case handling of the XHTML character entity "'" to normalizeEntity...
[lhc/web/wiklou.git] / includes / Sanitizer.php
1 <?php
2 /**
3 * XHTML sanitizer for MediaWiki
4 *
5 * Copyright (C) 2002-2005 Brion Vibber <brion@pobox.com> et al
6 * http://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 /**
28 * Regular expression to match various types of character references in
29 * Sanitizer::normalizeCharReferences and Sanitizer::decodeCharReferences
30 */
31 define( 'MW_CHAR_REFS_REGEX',
32 '/&([A-Za-z0-9\x80-\xff]+);
33 |&\#([0-9]+);
34 |&\#x([0-9A-Za-z]+);
35 |&\#X([0-9A-Za-z]+);
36 |(&)/x' );
37
38 /**
39 * Regular expression to match HTML/XML attribute pairs within a tag.
40 * Allows some... latitude.
41 * Used in Sanitizer::fixTagAttributes and Sanitizer::decodeTagAttributes
42 */
43 $attrib = '[A-Za-z0-9]';
44 $space = '[\x09\x0a\x0d\x20]';
45 define( 'MW_ATTRIBS_REGEX',
46 "/(?:^|$space)($attrib+)
47 ($space*=$space*
48 (?:
49 # The attribute value: quoted or alone
50 \"([^<\"]*)\"
51 | '([^<']*)'
52 | ([a-zA-Z0-9!#$%&()*,\\-.\\/:;<>?@[\\]^_`{|}~]+)
53 | (\#[0-9a-fA-F]+) # Technically wrong, but lots of
54 # colors are specified like this.
55 # We'll be normalizing it.
56 )
57 )?(?=$space|\$)/sx" );
58
59 /**
60 * List of all named character entities defined in HTML 4.01
61 * http://www.w3.org/TR/html4/sgml/entities.html
62 * This list does *not* include &apos;, which is part of XHTML
63 * 1.0 but not HTML 4.01. It is handled as a special case in
64 * the code.
65 * @private
66 */
67 global $wgHtmlEntities;
68 $wgHtmlEntities = array(
69 'Aacute' => 193,
70 'aacute' => 225,
71 'Acirc' => 194,
72 'acirc' => 226,
73 'acute' => 180,
74 'AElig' => 198,
75 'aelig' => 230,
76 'Agrave' => 192,
77 'agrave' => 224,
78 'alefsym' => 8501,
79 'Alpha' => 913,
80 'alpha' => 945,
81 'amp' => 38,
82 'and' => 8743,
83 'ang' => 8736,
84 'Aring' => 197,
85 'aring' => 229,
86 'asymp' => 8776,
87 'Atilde' => 195,
88 'atilde' => 227,
89 'Auml' => 196,
90 'auml' => 228,
91 'bdquo' => 8222,
92 'Beta' => 914,
93 'beta' => 946,
94 'brvbar' => 166,
95 'bull' => 8226,
96 'cap' => 8745,
97 'Ccedil' => 199,
98 'ccedil' => 231,
99 'cedil' => 184,
100 'cent' => 162,
101 'Chi' => 935,
102 'chi' => 967,
103 'circ' => 710,
104 'clubs' => 9827,
105 'cong' => 8773,
106 'copy' => 169,
107 'crarr' => 8629,
108 'cup' => 8746,
109 'curren' => 164,
110 'dagger' => 8224,
111 'Dagger' => 8225,
112 'darr' => 8595,
113 'dArr' => 8659,
114 'deg' => 176,
115 'Delta' => 916,
116 'delta' => 948,
117 'diams' => 9830,
118 'divide' => 247,
119 'Eacute' => 201,
120 'eacute' => 233,
121 'Ecirc' => 202,
122 'ecirc' => 234,
123 'Egrave' => 200,
124 'egrave' => 232,
125 'empty' => 8709,
126 'emsp' => 8195,
127 'ensp' => 8194,
128 'Epsilon' => 917,
129 'epsilon' => 949,
130 'equiv' => 8801,
131 'Eta' => 919,
132 'eta' => 951,
133 'ETH' => 208,
134 'eth' => 240,
135 'Euml' => 203,
136 'euml' => 235,
137 'euro' => 8364,
138 'exist' => 8707,
139 'fnof' => 402,
140 'forall' => 8704,
141 'frac12' => 189,
142 'frac14' => 188,
143 'frac34' => 190,
144 'frasl' => 8260,
145 'Gamma' => 915,
146 'gamma' => 947,
147 'ge' => 8805,
148 'gt' => 62,
149 'harr' => 8596,
150 'hArr' => 8660,
151 'hearts' => 9829,
152 'hellip' => 8230,
153 'Iacute' => 205,
154 'iacute' => 237,
155 'Icirc' => 206,
156 'icirc' => 238,
157 'iexcl' => 161,
158 'Igrave' => 204,
159 'igrave' => 236,
160 'image' => 8465,
161 'infin' => 8734,
162 'int' => 8747,
163 'Iota' => 921,
164 'iota' => 953,
165 'iquest' => 191,
166 'isin' => 8712,
167 'Iuml' => 207,
168 'iuml' => 239,
169 'Kappa' => 922,
170 'kappa' => 954,
171 'Lambda' => 923,
172 'lambda' => 955,
173 'lang' => 9001,
174 'laquo' => 171,
175 'larr' => 8592,
176 'lArr' => 8656,
177 'lceil' => 8968,
178 'ldquo' => 8220,
179 'le' => 8804,
180 'lfloor' => 8970,
181 'lowast' => 8727,
182 'loz' => 9674,
183 'lrm' => 8206,
184 'lsaquo' => 8249,
185 'lsquo' => 8216,
186 'lt' => 60,
187 'macr' => 175,
188 'mdash' => 8212,
189 'micro' => 181,
190 'middot' => 183,
191 'minus' => 8722,
192 'Mu' => 924,
193 'mu' => 956,
194 'nabla' => 8711,
195 'nbsp' => 160,
196 'ndash' => 8211,
197 'ne' => 8800,
198 'ni' => 8715,
199 'not' => 172,
200 'notin' => 8713,
201 'nsub' => 8836,
202 'Ntilde' => 209,
203 'ntilde' => 241,
204 'Nu' => 925,
205 'nu' => 957,
206 'Oacute' => 211,
207 'oacute' => 243,
208 'Ocirc' => 212,
209 'ocirc' => 244,
210 'OElig' => 338,
211 'oelig' => 339,
212 'Ograve' => 210,
213 'ograve' => 242,
214 'oline' => 8254,
215 'Omega' => 937,
216 'omega' => 969,
217 'Omicron' => 927,
218 'omicron' => 959,
219 'oplus' => 8853,
220 'or' => 8744,
221 'ordf' => 170,
222 'ordm' => 186,
223 'Oslash' => 216,
224 'oslash' => 248,
225 'Otilde' => 213,
226 'otilde' => 245,
227 'otimes' => 8855,
228 'Ouml' => 214,
229 'ouml' => 246,
230 'para' => 182,
231 'part' => 8706,
232 'permil' => 8240,
233 'perp' => 8869,
234 'Phi' => 934,
235 'phi' => 966,
236 'Pi' => 928,
237 'pi' => 960,
238 'piv' => 982,
239 'plusmn' => 177,
240 'pound' => 163,
241 'prime' => 8242,
242 'Prime' => 8243,
243 'prod' => 8719,
244 'prop' => 8733,
245 'Psi' => 936,
246 'psi' => 968,
247 'quot' => 34,
248 'radic' => 8730,
249 'rang' => 9002,
250 'raquo' => 187,
251 'rarr' => 8594,
252 'rArr' => 8658,
253 'rceil' => 8969,
254 'rdquo' => 8221,
255 'real' => 8476,
256 'reg' => 174,
257 'rfloor' => 8971,
258 'Rho' => 929,
259 'rho' => 961,
260 'rlm' => 8207,
261 'rsaquo' => 8250,
262 'rsquo' => 8217,
263 'sbquo' => 8218,
264 'Scaron' => 352,
265 'scaron' => 353,
266 'sdot' => 8901,
267 'sect' => 167,
268 'shy' => 173,
269 'Sigma' => 931,
270 'sigma' => 963,
271 'sigmaf' => 962,
272 'sim' => 8764,
273 'spades' => 9824,
274 'sub' => 8834,
275 'sube' => 8838,
276 'sum' => 8721,
277 'sup' => 8835,
278 'sup1' => 185,
279 'sup2' => 178,
280 'sup3' => 179,
281 'supe' => 8839,
282 'szlig' => 223,
283 'Tau' => 932,
284 'tau' => 964,
285 'there4' => 8756,
286 'Theta' => 920,
287 'theta' => 952,
288 'thetasym' => 977,
289 'thinsp' => 8201,
290 'THORN' => 222,
291 'thorn' => 254,
292 'tilde' => 732,
293 'times' => 215,
294 'trade' => 8482,
295 'Uacute' => 218,
296 'uacute' => 250,
297 'uarr' => 8593,
298 'uArr' => 8657,
299 'Ucirc' => 219,
300 'ucirc' => 251,
301 'Ugrave' => 217,
302 'ugrave' => 249,
303 'uml' => 168,
304 'upsih' => 978,
305 'Upsilon' => 933,
306 'upsilon' => 965,
307 'Uuml' => 220,
308 'uuml' => 252,
309 'weierp' => 8472,
310 'Xi' => 926,
311 'xi' => 958,
312 'Yacute' => 221,
313 'yacute' => 253,
314 'yen' => 165,
315 'Yuml' => 376,
316 'yuml' => 255,
317 'Zeta' => 918,
318 'zeta' => 950,
319 'zwj' => 8205,
320 'zwnj' => 8204 );
321
322 /**
323 * Character entity aliases accepted by MediaWiki
324 * XXX: decodeEntity() assumes that all values in this array are valid keys to $wgHtmlEntities
325 */
326 global $wgHtmlEntityAliases;
327 $wgHtmlEntityAliases = array(
328 'רלמ' => 'rlm',
329 'رلم' => 'rlm',
330 );
331
332
333 /**
334 * XHTML sanitizer for MediaWiki
335 * @ingroup Parser
336 */
337 class Sanitizer {
338 /**
339 * Cleans up HTML, removes dangerous tags and attributes, and
340 * removes HTML comments
341 * @private
342 * @param string $text
343 * @param callback $processCallback to do any variable or parameter replacements in HTML attribute values
344 * @param array $args for the processing callback
345 * @return string
346 */
347 static function removeHTMLtags( $text, $processCallback = null, $args = array(), $extratags = array() ) {
348 global $wgUseTidy;
349
350 static $htmlpairs, $htmlsingle, $htmlsingleonly, $htmlnest, $tabletags,
351 $htmllist, $listtags, $htmlsingleallowed, $htmlelements, $staticInitialised;
352
353 wfProfileIn( __METHOD__ );
354
355 if ( !$staticInitialised ) {
356
357 $htmlpairs = array_merge( $extratags, array( # Tags that must be closed
358 'b', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
359 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
360 'strike', 'strong', 'tt', 'var', 'div', 'center',
361 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
362 'ruby', 'rt' , 'rb' , 'rp', 'p', 'span', 'u'
363 ) );
364 $htmlsingle = array(
365 'br', 'hr', 'li', 'dt', 'dd'
366 );
367 $htmlsingleonly = array( # Elements that cannot have close tags
368 'br', 'hr'
369 );
370 $htmlnest = array( # Tags that can be nested--??
371 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
372 'dl', 'font', 'big', 'small', 'sub', 'sup', 'span'
373 );
374 $tabletags = array( # Can only appear inside table, we will close them
375 'td', 'th', 'tr',
376 );
377 $htmllist = array( # Tags used by list
378 'ul','ol',
379 );
380 $listtags = array( # Tags that can appear in a list
381 'li',
382 );
383
384 $htmlsingleallowed = array_merge( $htmlsingle, $tabletags );
385 $htmlelements = array_merge( $htmlsingle, $htmlpairs, $htmlnest );
386
387 # Convert them all to hashtables for faster lookup
388 $vars = array( 'htmlpairs', 'htmlsingle', 'htmlsingleonly', 'htmlnest', 'tabletags',
389 'htmllist', 'listtags', 'htmlsingleallowed', 'htmlelements' );
390 foreach ( $vars as $var ) {
391 $$var = array_flip( $$var );
392 }
393 $staticInitialised = true;
394 }
395
396 # Remove HTML comments
397 $text = Sanitizer::removeHTMLcomments( $text );
398 $bits = explode( '<', $text );
399 $text = str_replace( '>', '&gt;', array_shift( $bits ) );
400 if(!$wgUseTidy) {
401 $tagstack = $tablestack = array();
402 foreach ( $bits as $x ) {
403 $regs = array();
404 if( preg_match( '!^(/?)(\\w+)([^>]*?)(/{0,1}>)([^<]*)$!', $x, $regs ) ) {
405 list( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
406 } else {
407 $slash = $t = $params = $brace = $rest = null;
408 }
409
410 $badtag = 0 ;
411 if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
412 # Check our stack
413 if ( $slash ) {
414 # Closing a tag...
415 if( isset( $htmlsingleonly[$t] ) ) {
416 $badtag = 1;
417 } elseif ( ( $ot = @array_pop( $tagstack ) ) != $t ) {
418 if ( isset( $htmlsingleallowed[$ot] ) ) {
419 # Pop all elements with an optional close tag
420 # and see if we find a match below them
421 $optstack = array();
422 array_push ($optstack, $ot);
423 while ( ( ( $ot = @array_pop( $tagstack ) ) != $t ) &&
424 isset( $htmlsingleallowed[$ot] ) )
425 {
426 array_push ($optstack, $ot);
427 }
428 if ( $t != $ot ) {
429 # No match. Push the optinal elements back again
430 $badtag = 1;
431 while ( $ot = @array_pop( $optstack ) ) {
432 array_push( $tagstack, $ot );
433 }
434 }
435 } else {
436 @array_push( $tagstack, $ot );
437 # <li> can be nested in <ul> or <ol>, skip those cases:
438 if(!(isset( $htmllist[$ot] ) && isset( $listtags[$t] ) )) {
439 $badtag = 1;
440 }
441 }
442 } else {
443 if ( $t == 'table' ) {
444 $tagstack = array_pop( $tablestack );
445 }
446 }
447 $newparams = '';
448 } else {
449 # Keep track for later
450 if ( isset( $tabletags[$t] ) &&
451 ! in_array( 'table', $tagstack ) ) {
452 $badtag = 1;
453 } else if ( in_array( $t, $tagstack ) &&
454 ! isset( $htmlnest [$t ] ) ) {
455 $badtag = 1 ;
456 # Is it a self closed htmlpair ? (bug 5487)
457 } else if( $brace == '/>' &&
458 isset( $htmlpairs[$t] ) ) {
459 $badtag = 1;
460 } elseif( isset( $htmlsingleonly[$t] ) ) {
461 # Hack to force empty tag for uncloseable elements
462 $brace = '/>';
463 } else if( isset( $htmlsingle[$t] ) ) {
464 # Hack to not close $htmlsingle tags
465 $brace = NULL;
466 } else if( isset( $tabletags[$t] )
467 && in_array($t ,$tagstack) ) {
468 // New table tag but forgot to close the previous one
469 $text .= "</$t>";
470 } else {
471 if ( $t == 'table' ) {
472 array_push( $tablestack, $tagstack );
473 $tagstack = array();
474 }
475 array_push( $tagstack, $t );
476 }
477
478 # Replace any variables or template parameters with
479 # plaintext results.
480 if( is_callable( $processCallback ) ) {
481 call_user_func_array( $processCallback, array( &$params, $args ) );
482 }
483
484 # Strip non-approved attributes from the tag
485 $newparams = Sanitizer::fixTagAttributes( $params, $t );
486 }
487 if ( ! $badtag ) {
488 $rest = str_replace( '>', '&gt;', $rest );
489 $close = ( $brace == '/>' && !$slash ) ? ' /' : '';
490 $text .= "<$slash$t$newparams$close>$rest";
491 continue;
492 }
493 }
494 $text .= '&lt;' . str_replace( '>', '&gt;', $x);
495 }
496 # Close off any remaining tags
497 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
498 $text .= "</$t>\n";
499 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
500 }
501 } else {
502 # this might be possible using tidy itself
503 foreach ( $bits as $x ) {
504 preg_match( '/^(\\/?)(\\w+)([^>]*?)(\\/{0,1}>)([^<]*)$/',
505 $x, $regs );
506 @list( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
507 if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
508 if( is_callable( $processCallback ) ) {
509 call_user_func_array( $processCallback, array( &$params, $args ) );
510 }
511 $newparams = Sanitizer::fixTagAttributes( $params, $t );
512 $rest = str_replace( '>', '&gt;', $rest );
513 $text .= "<$slash$t$newparams$brace$rest";
514 } else {
515 $text .= '&lt;' . str_replace( '>', '&gt;', $x);
516 }
517 }
518 }
519 wfProfileOut( __METHOD__ );
520 return $text;
521 }
522
523 /**
524 * Remove '<!--', '-->', and everything between.
525 * To avoid leaving blank lines, when a comment is both preceded
526 * and followed by a newline (ignoring spaces), trim leading and
527 * trailing spaces and one of the newlines.
528 *
529 * @private
530 * @param string $text
531 * @return string
532 */
533 static function removeHTMLcomments( $text ) {
534 wfProfileIn( __METHOD__ );
535 while (($start = strpos($text, '<!--')) !== false) {
536 $end = strpos($text, '-->', $start + 4);
537 if ($end === false) {
538 # Unterminated comment; bail out
539 break;
540 }
541
542 $end += 3;
543
544 # Trim space and newline if the comment is both
545 # preceded and followed by a newline
546 $spaceStart = max($start - 1, 0);
547 $spaceLen = $end - $spaceStart;
548 while (substr($text, $spaceStart, 1) === ' ' && $spaceStart > 0) {
549 $spaceStart--;
550 $spaceLen++;
551 }
552 while (substr($text, $spaceStart + $spaceLen, 1) === ' ')
553 $spaceLen++;
554 if (substr($text, $spaceStart, 1) === "\n" and substr($text, $spaceStart + $spaceLen, 1) === "\n") {
555 # Remove the comment, leading and trailing
556 # spaces, and leave only one newline.
557 $text = substr_replace($text, "\n", $spaceStart, $spaceLen + 1);
558 }
559 else {
560 # Remove just the comment.
561 $text = substr_replace($text, '', $start, $end - $start);
562 }
563 }
564 wfProfileOut( __METHOD__ );
565 return $text;
566 }
567
568 /**
569 * Take an array of attribute names and values and normalize or discard
570 * illegal values for the given element type.
571 *
572 * - Discards attributes not on a whitelist for the given element
573 * - Unsafe style attributes are discarded
574 * - Invalid id attributes are reencoded
575 *
576 * @param array $attribs
577 * @param string $element
578 * @return array
579 *
580 * @todo Check for legal values where the DTD limits things.
581 * @todo Check for unique id attribute :P
582 */
583 static function validateTagAttributes( $attribs, $element ) {
584 return Sanitizer::validateAttributes( $attribs,
585 Sanitizer::attributeWhitelist( $element ) );
586 }
587
588 /**
589 * Take an array of attribute names and values and normalize or discard
590 * illegal values for the given whitelist.
591 *
592 * - Discards attributes not the given whitelist
593 * - Unsafe style attributes are discarded
594 * - Invalid id attributes are reencoded
595 *
596 * @param array $attribs
597 * @param array $whitelist list of allowed attribute names
598 * @return array
599 *
600 * @todo Check for legal values where the DTD limits things.
601 * @todo Check for unique id attribute :P
602 */
603 static function validateAttributes( $attribs, $whitelist ) {
604 $whitelist = array_flip( $whitelist );
605 $out = array();
606 foreach( $attribs as $attribute => $value ) {
607 if( !isset( $whitelist[$attribute] ) ) {
608 continue;
609 }
610 # Strip javascript "expression" from stylesheets.
611 # http://msdn.microsoft.com/workshop/author/dhtml/overview/recalc.asp
612 if( $attribute == 'style' ) {
613 $value = Sanitizer::checkCss( $value );
614 if( $value === false ) {
615 # haxx0r
616 continue;
617 }
618 }
619
620 if ( $attribute === 'id' ) {
621 global $wgEnforceHtmlIds;
622 $value = Sanitizer::escapeId( $value,
623 $wgEnforceHtmlIds ? array() : 'xml' );
624 }
625
626 // If this attribute was previously set, override it.
627 // Output should only have one attribute of each name.
628 $out[$attribute] = $value;
629 }
630 return $out;
631 }
632
633 /**
634 * Merge two sets of HTML attributes. Conflicting items in the second set
635 * will override those in the first, except for 'class' attributes which
636 * will be combined (if they're both strings).
637 *
638 * @todo implement merging for other attributes such as style
639 * @param array $a
640 * @param array $b
641 * @return array
642 */
643 static function mergeAttributes( $a, $b ) {
644 $out = array_merge( $a, $b );
645 if( isset( $a['class'] ) && isset( $b['class'] )
646 && is_string( $a['class'] ) && is_string( $b['class'] )
647 && $a['class'] !== $b['class'] ) {
648 $classes = preg_split( '/\s+/', "{$a['class']} {$b['class']}",
649 -1, PREG_SPLIT_NO_EMPTY );
650 $out['class'] = implode( ' ', array_unique( $classes ) );
651 }
652 return $out;
653 }
654
655 /**
656 * Pick apart some CSS and check it for forbidden or unsafe structures.
657 * Returns a sanitized string, or false if it was just too evil.
658 *
659 * Currently URL references, 'expression', 'tps' are forbidden.
660 *
661 * @param string $value
662 * @return mixed
663 */
664 static function checkCss( $value ) {
665 $stripped = Sanitizer::decodeCharReferences( $value );
666
667 // Remove any comments; IE gets token splitting wrong
668 $stripped = StringUtils::delimiterReplace( '/*', '*/', ' ', $stripped );
669
670 $value = $stripped;
671
672 // ... and continue checks
673 $stripped = preg_replace( '!\\\\([0-9A-Fa-f]{1,6})[ \\n\\r\\t\\f]?!e',
674 'codepointToUtf8(hexdec("$1"))', $stripped );
675 $stripped = str_replace( '\\', '', $stripped );
676 if( preg_match( '/(?:expression|tps*:\/\/|url\\s*\().*/is',
677 $stripped ) ) {
678 # haxx0r
679 return false;
680 }
681
682 return $value;
683 }
684
685 /**
686 * Take a tag soup fragment listing an HTML element's attributes
687 * and normalize it to well-formed XML, discarding unwanted attributes.
688 * Output is safe for further wikitext processing, with escaping of
689 * values that could trigger problems.
690 *
691 * - Normalizes attribute names to lowercase
692 * - Discards attributes not on a whitelist for the given element
693 * - Turns broken or invalid entities into plaintext
694 * - Double-quotes all attribute values
695 * - Attributes without values are given the name as attribute
696 * - Double attributes are discarded
697 * - Unsafe style attributes are discarded
698 * - Prepends space if there are attributes.
699 *
700 * @param string $text
701 * @param string $element
702 * @return string
703 */
704 static function fixTagAttributes( $text, $element ) {
705 if( trim( $text ) == '' ) {
706 return '';
707 }
708
709 $stripped = Sanitizer::validateTagAttributes(
710 Sanitizer::decodeTagAttributes( $text ), $element );
711
712 $attribs = array();
713 foreach( $stripped as $attribute => $value ) {
714 $encAttribute = htmlspecialchars( $attribute );
715 $encValue = Sanitizer::safeEncodeAttribute( $value );
716
717 $attribs[] = "$encAttribute=\"$encValue\"";
718 }
719 return count( $attribs ) ? ' ' . implode( ' ', $attribs ) : '';
720 }
721
722 /**
723 * Encode an attribute value for HTML output.
724 * @param $text
725 * @return HTML-encoded text fragment
726 */
727 static function encodeAttribute( $text ) {
728 $encValue = htmlspecialchars( $text, ENT_QUOTES );
729
730 // Whitespace is normalized during attribute decoding,
731 // so if we've been passed non-spaces we must encode them
732 // ahead of time or they won't be preserved.
733 $encValue = strtr( $encValue, array(
734 "\n" => '&#10;',
735 "\r" => '&#13;',
736 "\t" => '&#9;',
737 ) );
738
739 return $encValue;
740 }
741
742 /**
743 * Encode an attribute value for HTML tags, with extra armoring
744 * against further wiki processing.
745 * @param $text
746 * @return HTML-encoded text fragment
747 */
748 static function safeEncodeAttribute( $text ) {
749 $encValue = Sanitizer::encodeAttribute( $text );
750
751 # Templates and links may be expanded in later parsing,
752 # creating invalid or dangerous output. Suppress this.
753 $encValue = strtr( $encValue, array(
754 '<' => '&lt;', // This should never happen,
755 '>' => '&gt;', // we've received invalid input
756 '"' => '&quot;', // which should have been escaped.
757 '{' => '&#123;',
758 '[' => '&#91;',
759 "''" => '&#39;&#39;',
760 'ISBN' => '&#73;SBN',
761 'RFC' => '&#82;FC',
762 'PMID' => '&#80;MID',
763 '|' => '&#124;',
764 '__' => '&#95;_',
765 ) );
766
767 # Stupid hack
768 $encValue = preg_replace_callback(
769 '/(' . wfUrlProtocols() . ')/',
770 array( 'Sanitizer', 'armorLinksCallback' ),
771 $encValue );
772 return $encValue;
773 }
774
775 /**
776 * Given a value escape it so that it can be used in an id attribute and
777 * return it, this does not validate the value however (see first link)
778 *
779 * @see http://www.w3.org/TR/html401/types.html#type-name Valid characters
780 * in the id and
781 * name attributes
782 * @see http://www.w3.org/TR/html401/struct/links.html#h-12.2.3 Anchors with the id attribute
783 *
784 * @param string $id Id to validate
785 * @param mixed $options String or array of strings (default is array()):
786 * 'noninitial': This is a non-initial fragment of an id, not a full id,
787 * so don't pay attention if the first character isn't valid at the
788 * beginning of an id.
789 * 'xml': Don't restrict the id to be HTML4-compatible. This option
790 * allows any alphabetic character to be used, per the XML standard.
791 * Therefore, it also completely changes the type of escaping: instead
792 * of weird dot-encoding, runs of invalid characters (mostly
793 * whitespace) are just compressed into a single underscore.
794 * @return string
795 */
796 static function escapeId( $id, $options = array() ) {
797 $options = (array)$options;
798
799 if ( !in_array( 'xml', $options ) ) {
800 # HTML4-style escaping
801 static $replace = array(
802 '%3A' => ':',
803 '%' => '.'
804 );
805
806 $id = urlencode( Sanitizer::decodeCharReferences( strtr( $id, ' ', '_' ) ) );
807 $id = str_replace( array_keys( $replace ), array_values( $replace ), $id );
808
809 /*
810 // Let's not go changing our links just yet, since we plan to
811 // rip this out anyway and switch to the prettier Unicode-friendly
812 // links as XHTML and HTML 5 allow and browsers seem to think is
813 // just a-ok to do.
814 //
815 if ( !preg_match( '/^[a-zA-Z]/', $id )
816 && !in_array( 'noninitial', $options ) ) {
817 // Initial character must be a letter!
818 $id = "x$id";
819 }
820 */
821 return $id;
822 }
823
824 # XML-style escaping. For the patterns used, see the XML 1.0 standard,
825 # 5th edition, NameStartChar and NameChar: <http://www.w3.org/TR/REC-xml/>
826 $nameStartChar = ':a-zA-Z_\xC0-\xD6\xD8-\xF6\xF8-\x{2FF}\x{370}-\x{37D}'
827 . '\x{37F}-\x{1FFF}\x{200C}-\x{200D}\x{2070}-\x{218F}\x{2C00}-\x{2FEF}'
828 . '\x{3001}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFFD}\x{10000}-\x{EFFFF}';
829 $nameChar = $nameStartChar . '.\-0-9\xB7\x{0300}-\x{036F}'
830 . '\x{203F}-\x{2040}';
831 # Replace _ as well so we don't get multiple consecutive underscores
832 $id = preg_replace( "/([^$nameChar]|_)+/u", '_', $id );
833 $id = trim( $id, '_' );
834
835 if ( !preg_match( "/^[$nameStartChar]/u", $id )
836 && !in_array( 'noninitial', $options ) ) {
837 $id = "_$id";
838 }
839
840 return $id;
841 }
842
843 /**
844 * Given a value, escape it so that it can be used as a CSS class and
845 * return it.
846 *
847 * @todo For extra validity, input should be validated UTF-8.
848 *
849 * @see http://www.w3.org/TR/CSS21/syndata.html Valid characters/format
850 *
851 * @param string $class
852 * @return string
853 */
854 static function escapeClass( $class ) {
855 // Convert ugly stuff to underscores and kill underscores in ugly places
856 return rtrim(preg_replace(
857 array('/(^[0-9\\-])|[\\x00-\\x20!"#$%&\'()*+,.\\/:;<=>?@[\\]^`{|}~]|\\xC2\\xA0/','/_+/'),
858 '_',
859 $class ), '_');
860 }
861
862 /**
863 * Given HTML input, escape with htmlspecialchars but un-escape entites.
864 * This allows (generally harmless) entities like &nbsp; to survive.
865 *
866 * @param string $html String to escape
867 * @return string Escaped input
868 */
869 static function escapeHtmlAllowEntities( $html ) {
870 # It seems wise to escape ' as well as ", as a matter of course. Can't
871 # hurt.
872 $html = htmlspecialchars( $html, ENT_QUOTES );
873 $html = str_replace( '&amp;', '&', $html );
874 $html = Sanitizer::normalizeCharReferences( $html );
875 return $html;
876 }
877
878 /**
879 * Regex replace callback for armoring links against further processing.
880 * @param array $matches
881 * @return string
882 * @private
883 */
884 private static function armorLinksCallback( $matches ) {
885 return str_replace( ':', '&#58;', $matches[1] );
886 }
887
888 /**
889 * Return an associative array of attribute names and values from
890 * a partial tag string. Attribute names are forces to lowercase,
891 * character references are decoded to UTF-8 text.
892 *
893 * @param string
894 * @return array
895 */
896 public static function decodeTagAttributes( $text ) {
897 $attribs = array();
898
899 if( trim( $text ) == '' ) {
900 return $attribs;
901 }
902
903 $pairs = array();
904 if( !preg_match_all(
905 MW_ATTRIBS_REGEX,
906 $text,
907 $pairs,
908 PREG_SET_ORDER ) ) {
909 return $attribs;
910 }
911
912 foreach( $pairs as $set ) {
913 $attribute = strtolower( $set[1] );
914 $value = Sanitizer::getTagAttributeCallback( $set );
915
916 // Normalize whitespace
917 $value = preg_replace( '/[\t\r\n ]+/', ' ', $value );
918 $value = trim( $value );
919
920 // Decode character references
921 $attribs[$attribute] = Sanitizer::decodeCharReferences( $value );
922 }
923 return $attribs;
924 }
925
926 /**
927 * Pick the appropriate attribute value from a match set from the
928 * MW_ATTRIBS_REGEX matches.
929 *
930 * @param array $set
931 * @return string
932 * @private
933 */
934 private static function getTagAttributeCallback( $set ) {
935 if( isset( $set[6] ) ) {
936 # Illegal #XXXXXX color with no quotes.
937 return $set[6];
938 } elseif( isset( $set[5] ) ) {
939 # No quotes.
940 return $set[5];
941 } elseif( isset( $set[4] ) ) {
942 # Single-quoted
943 return $set[4];
944 } elseif( isset( $set[3] ) ) {
945 # Double-quoted
946 return $set[3];
947 } elseif( !isset( $set[2] ) ) {
948 # In XHTML, attributes must have a value.
949 # For 'reduced' form, return explicitly the attribute name here.
950 return $set[1];
951 } else {
952 throw new MWException( "Tag conditions not met. This should never happen and is a bug." );
953 }
954 }
955
956 /**
957 * Normalize whitespace and character references in an XML source-
958 * encoded text for an attribute value.
959 *
960 * See http://www.w3.org/TR/REC-xml/#AVNormalize for background,
961 * but note that we are not returning the value, but are returning
962 * XML source fragments that will be slapped into output.
963 *
964 * @param string $text
965 * @return string
966 * @private
967 */
968 private static function normalizeAttributeValue( $text ) {
969 return str_replace( '"', '&quot;',
970 self::normalizeWhitespace(
971 Sanitizer::normalizeCharReferences( $text ) ) );
972 }
973
974 private static function normalizeWhitespace( $text ) {
975 return preg_replace(
976 '/\r\n|[\x20\x0d\x0a\x09]/',
977 ' ',
978 $text );
979 }
980
981 /**
982 * Ensure that any entities and character references are legal
983 * for XML and XHTML specifically. Any stray bits will be
984 * &amp;-escaped to result in a valid text fragment.
985 *
986 * a. any named char refs must be known in XHTML
987 * b. any numeric char refs must be legal chars, not invalid or forbidden
988 * c. use &#x, not &#X
989 * d. fix or reject non-valid attributes
990 *
991 * @param string $text
992 * @return string
993 * @private
994 */
995 static function normalizeCharReferences( $text ) {
996 return preg_replace_callback(
997 MW_CHAR_REFS_REGEX,
998 array( 'Sanitizer', 'normalizeCharReferencesCallback' ),
999 $text );
1000 }
1001 /**
1002 * @param string $matches
1003 * @return string
1004 */
1005 static function normalizeCharReferencesCallback( $matches ) {
1006 $ret = null;
1007 if( $matches[1] != '' ) {
1008 $ret = Sanitizer::normalizeEntity( $matches[1] );
1009 } elseif( $matches[2] != '' ) {
1010 $ret = Sanitizer::decCharReference( $matches[2] );
1011 } elseif( $matches[3] != '' ) {
1012 $ret = Sanitizer::hexCharReference( $matches[3] );
1013 } elseif( $matches[4] != '' ) {
1014 $ret = Sanitizer::hexCharReference( $matches[4] );
1015 }
1016 if( is_null( $ret ) ) {
1017 return htmlspecialchars( $matches[0] );
1018 } else {
1019 return $ret;
1020 }
1021 }
1022
1023 /**
1024 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
1025 * return the named entity reference as is. If the entity is a
1026 * MediaWiki-specific alias, returns the HTML equivalent. Otherwise,
1027 * returns HTML-escaped text of pseudo-entity source (eg &amp;foo;)
1028 *
1029 * @param string $name
1030 * @return string
1031 * @static
1032 */
1033 static function normalizeEntity( $name ) {
1034 global $wgHtmlEntities, $wgHtmlEntityAliases;
1035 if ( isset( $wgHtmlEntityAliases[$name] ) ) {
1036 return "&{$wgHtmlEntityAliases[$name]};";
1037 } elseif( isset( $wgHtmlEntities[$name] ) ) {
1038 return "&$name;";
1039 } elseif( $name == 'apos' ) {
1040 return "&#39;"; // "&apos;" is valid in XHTML, but not in HTML4
1041 } else {
1042 return "&amp;$name;";
1043 }
1044 }
1045
1046 static function decCharReference( $codepoint ) {
1047 $point = intval( $codepoint );
1048 if( Sanitizer::validateCodepoint( $point ) ) {
1049 return sprintf( '&#%d;', $point );
1050 } else {
1051 return null;
1052 }
1053 }
1054
1055 static function hexCharReference( $codepoint ) {
1056 $point = hexdec( $codepoint );
1057 if( Sanitizer::validateCodepoint( $point ) ) {
1058 return sprintf( '&#x%x;', $point );
1059 } else {
1060 return null;
1061 }
1062 }
1063
1064 /**
1065 * Returns true if a given Unicode codepoint is a valid character in XML.
1066 * @param int $codepoint
1067 * @return bool
1068 */
1069 private static function validateCodepoint( $codepoint ) {
1070 return ($codepoint == 0x09)
1071 || ($codepoint == 0x0a)
1072 || ($codepoint == 0x0d)
1073 || ($codepoint >= 0x20 && $codepoint <= 0xd7ff)
1074 || ($codepoint >= 0xe000 && $codepoint <= 0xfffd)
1075 || ($codepoint >= 0x10000 && $codepoint <= 0x10ffff);
1076 }
1077
1078 /**
1079 * Decode any character references, numeric or named entities,
1080 * in the text and return a UTF-8 string.
1081 *
1082 * @param string $text
1083 * @return string
1084 * @public
1085 * @static
1086 */
1087 public static function decodeCharReferences( $text ) {
1088 return preg_replace_callback(
1089 MW_CHAR_REFS_REGEX,
1090 array( 'Sanitizer', 'decodeCharReferencesCallback' ),
1091 $text );
1092 }
1093
1094 /**
1095 * @param string $matches
1096 * @return string
1097 */
1098 static function decodeCharReferencesCallback( $matches ) {
1099 if( $matches[1] != '' ) {
1100 return Sanitizer::decodeEntity( $matches[1] );
1101 } elseif( $matches[2] != '' ) {
1102 return Sanitizer::decodeChar( intval( $matches[2] ) );
1103 } elseif( $matches[3] != '' ) {
1104 return Sanitizer::decodeChar( hexdec( $matches[3] ) );
1105 } elseif( $matches[4] != '' ) {
1106 return Sanitizer::decodeChar( hexdec( $matches[4] ) );
1107 }
1108 # Last case should be an ampersand by itself
1109 return $matches[0];
1110 }
1111
1112 /**
1113 * Return UTF-8 string for a codepoint if that is a valid
1114 * character reference, otherwise U+FFFD REPLACEMENT CHARACTER.
1115 * @param int $codepoint
1116 * @return string
1117 * @private
1118 */
1119 static function decodeChar( $codepoint ) {
1120 if( Sanitizer::validateCodepoint( $codepoint ) ) {
1121 return codepointToUtf8( $codepoint );
1122 } else {
1123 return UTF8_REPLACEMENT;
1124 }
1125 }
1126
1127 /**
1128 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
1129 * return the UTF-8 encoding of that character. Otherwise, returns
1130 * pseudo-entity source (eg &foo;)
1131 *
1132 * @param string $name
1133 * @return string
1134 */
1135 static function decodeEntity( $name ) {
1136 global $wgHtmlEntities, $wgHtmlEntityAliases;
1137 if ( isset( $wgHtmlEntityAliases[$name] ) ) {
1138 $name = $wgHtmlEntityAliases[$name];
1139 }
1140 if( isset( $wgHtmlEntities[$name] ) ) {
1141 return codepointToUtf8( $wgHtmlEntities[$name] );
1142 } elseif( $name == 'apos' ) {
1143 return "'"; // "&apos;" is not in $wgHtmlEntities, but it's still valid XHTML
1144 } else {
1145 return "&$name;";
1146 }
1147 }
1148
1149 /**
1150 * Fetch the whitelist of acceptable attributes for a given
1151 * element name.
1152 *
1153 * @param string $element
1154 * @return array
1155 */
1156 static function attributeWhitelist( $element ) {
1157 static $list;
1158 if( !isset( $list ) ) {
1159 $list = Sanitizer::setupAttributeWhitelist();
1160 }
1161 return isset( $list[$element] )
1162 ? $list[$element]
1163 : array();
1164 }
1165
1166 /**
1167 * Foreach array key (an allowed HTML element), return an array
1168 * of allowed attributes
1169 * @return array
1170 */
1171 static function setupAttributeWhitelist() {
1172 $common = array( 'id', 'class', 'lang', 'dir', 'title', 'style' );
1173 $block = array_merge( $common, array( 'align' ) );
1174 $tablealign = array( 'align', 'char', 'charoff', 'valign' );
1175 $tablecell = array( 'abbr',
1176 'axis',
1177 'headers',
1178 'scope',
1179 'rowspan',
1180 'colspan',
1181 'nowrap', # deprecated
1182 'width', # deprecated
1183 'height', # deprecated
1184 'bgcolor' # deprecated
1185 );
1186
1187 # Numbers refer to sections in HTML 4.01 standard describing the element.
1188 # See: http://www.w3.org/TR/html4/
1189 $whitelist = array (
1190 # 7.5.4
1191 'div' => $block,
1192 'center' => $common, # deprecated
1193 'span' => $block, # ??
1194
1195 # 7.5.5
1196 'h1' => $block,
1197 'h2' => $block,
1198 'h3' => $block,
1199 'h4' => $block,
1200 'h5' => $block,
1201 'h6' => $block,
1202
1203 # 7.5.6
1204 # address
1205
1206 # 8.2.4
1207 # bdo
1208
1209 # 9.2.1
1210 'em' => $common,
1211 'strong' => $common,
1212 'cite' => $common,
1213 # dfn
1214 'code' => $common,
1215 # samp
1216 # kbd
1217 'var' => $common,
1218 # abbr
1219 # acronym
1220
1221 # 9.2.2
1222 'blockquote' => array_merge( $common, array( 'cite' ) ),
1223 # q
1224
1225 # 9.2.3
1226 'sub' => $common,
1227 'sup' => $common,
1228
1229 # 9.3.1
1230 'p' => $block,
1231
1232 # 9.3.2
1233 'br' => array( 'id', 'class', 'title', 'style', 'clear' ),
1234
1235 # 9.3.4
1236 'pre' => array_merge( $common, array( 'width' ) ),
1237
1238 # 9.4
1239 'ins' => array_merge( $common, array( 'cite', 'datetime' ) ),
1240 'del' => array_merge( $common, array( 'cite', 'datetime' ) ),
1241
1242 # 10.2
1243 'ul' => array_merge( $common, array( 'type' ) ),
1244 'ol' => array_merge( $common, array( 'type', 'start' ) ),
1245 'li' => array_merge( $common, array( 'type', 'value' ) ),
1246
1247 # 10.3
1248 'dl' => $common,
1249 'dd' => $common,
1250 'dt' => $common,
1251
1252 # 11.2.1
1253 'table' => array_merge( $common,
1254 array( 'summary', 'width', 'border', 'frame',
1255 'rules', 'cellspacing', 'cellpadding',
1256 'align', 'bgcolor',
1257 ) ),
1258
1259 # 11.2.2
1260 'caption' => array_merge( $common, array( 'align' ) ),
1261
1262 # 11.2.3
1263 'thead' => array_merge( $common, $tablealign ),
1264 'tfoot' => array_merge( $common, $tablealign ),
1265 'tbody' => array_merge( $common, $tablealign ),
1266
1267 # 11.2.4
1268 'colgroup' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1269 'col' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1270
1271 # 11.2.5
1272 'tr' => array_merge( $common, array( 'bgcolor' ), $tablealign ),
1273
1274 # 11.2.6
1275 'td' => array_merge( $common, $tablecell, $tablealign ),
1276 'th' => array_merge( $common, $tablecell, $tablealign ),
1277
1278 # 13.2
1279 # Not usually allowed, but may be used for extension-style hooks
1280 # such as <math> when it is rasterized
1281 'img' => array_merge( $common, array( 'alt' ) ),
1282
1283 # 15.2.1
1284 'tt' => $common,
1285 'b' => $common,
1286 'i' => $common,
1287 'big' => $common,
1288 'small' => $common,
1289 'strike' => $common,
1290 's' => $common,
1291 'u' => $common,
1292
1293 # 15.2.2
1294 'font' => array_merge( $common, array( 'size', 'color', 'face' ) ),
1295 # basefont
1296
1297 # 15.3
1298 'hr' => array_merge( $common, array( 'noshade', 'size', 'width' ) ),
1299
1300 # XHTML Ruby annotation text module, simple ruby only.
1301 # http://www.w3c.org/TR/ruby/
1302 'ruby' => $common,
1303 # rbc
1304 # rtc
1305 'rb' => $common,
1306 'rt' => $common, #array_merge( $common, array( 'rbspan' ) ),
1307 'rp' => $common,
1308
1309 # MathML root element, where used for extensions
1310 # 'title' may not be 100% valid here; it's XHTML
1311 # http://www.w3.org/TR/REC-MathML/
1312 'math' => array( 'class', 'style', 'id', 'title' ),
1313 );
1314 return $whitelist;
1315 }
1316
1317 /**
1318 * Take a fragment of (potentially invalid) HTML and return
1319 * a version with any tags removed, encoded as plain text.
1320 *
1321 * Warning: this return value must be further escaped for literal
1322 * inclusion in HTML output as of 1.10!
1323 *
1324 * @param string $text HTML fragment
1325 * @return string
1326 */
1327 static function stripAllTags( $text ) {
1328 # Actual <tags>
1329 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
1330
1331 # Normalize &entities and whitespace
1332 $text = self::decodeCharReferences( $text );
1333 $text = self::normalizeWhitespace( $text );
1334
1335 return $text;
1336 }
1337
1338 /**
1339 * Hack up a private DOCTYPE with HTML's standard entity declarations.
1340 * PHP 4 seemed to know these if you gave it an HTML doctype, but
1341 * PHP 5.1 doesn't.
1342 *
1343 * Use for passing XHTML fragments to PHP's XML parsing functions
1344 *
1345 * @return string
1346 * @static
1347 */
1348 static function hackDocType() {
1349 global $wgHtmlEntities;
1350 $out = "<!DOCTYPE html [\n";
1351 foreach( $wgHtmlEntities as $entity => $codepoint ) {
1352 $out .= "<!ENTITY $entity \"&#$codepoint;\">";
1353 }
1354 $out .= "]>\n";
1355 return $out;
1356 }
1357
1358 static function cleanUrl( $url ) {
1359 # Normalize any HTML entities in input. They will be
1360 # re-escaped by makeExternalLink().
1361 $url = Sanitizer::decodeCharReferences( $url );
1362
1363 # Escape any control characters introduced by the above step
1364 $url = preg_replace( '/[\][<>"\\x00-\\x20\\x7F]/e', "urlencode('\\0')", $url );
1365
1366 # Validate hostname portion
1367 $matches = array();
1368 if( preg_match( '!^([^:]+:)(//[^/]+)?(.*)$!iD', $url, $matches ) ) {
1369 list( /* $whole */, $protocol, $host, $rest ) = $matches;
1370
1371 // Characters that will be ignored in IDNs.
1372 // http://tools.ietf.org/html/3454#section-3.1
1373 // Strip them before further processing so blacklists and such work.
1374 $strip = "/
1375 \\s| # general whitespace
1376 \xc2\xad| # 00ad SOFT HYPHEN
1377 \xe1\xa0\x86| # 1806 MONGOLIAN TODO SOFT HYPHEN
1378 \xe2\x80\x8b| # 200b ZERO WIDTH SPACE
1379 \xe2\x81\xa0| # 2060 WORD JOINER
1380 \xef\xbb\xbf| # feff ZERO WIDTH NO-BREAK SPACE
1381 \xcd\x8f| # 034f COMBINING GRAPHEME JOINER
1382 \xe1\xa0\x8b| # 180b MONGOLIAN FREE VARIATION SELECTOR ONE
1383 \xe1\xa0\x8c| # 180c MONGOLIAN FREE VARIATION SELECTOR TWO
1384 \xe1\xa0\x8d| # 180d MONGOLIAN FREE VARIATION SELECTOR THREE
1385 \xe2\x80\x8c| # 200c ZERO WIDTH NON-JOINER
1386 \xe2\x80\x8d| # 200d ZERO WIDTH JOINER
1387 [\xef\xb8\x80-\xef\xb8\x8f] # fe00-fe00f VARIATION SELECTOR-1-16
1388 /xuD";
1389
1390 $host = preg_replace( $strip, '', $host );
1391
1392 // @fixme: validate hostnames here
1393
1394 return $protocol . $host . $rest;
1395 } else {
1396 return $url;
1397 }
1398 }
1399
1400 }