Title: Title::getSubpage should not lose the interwiki prefix
[lhc/web/wiklou.git] / includes / Html.php
1 <?php
2 /**
3 * Collection of methods to generate HTML content
4 *
5 * Copyright © 2009 Aryeh Gregor
6 * https://www.mediawiki.org/
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
22 *
23 * @file
24 */
25 use MediaWiki\MediaWikiServices;
26
27 /**
28 * This class is a collection of static functions that serve two purposes:
29 *
30 * 1) Implement any algorithms specified by HTML5, or other HTML
31 * specifications, in a convenient and self-contained way.
32 *
33 * 2) Allow HTML elements to be conveniently and safely generated, like the
34 * current Xml class but a) less confused (Xml supports HTML-specific things,
35 * but only sometimes!) and b) not necessarily confined to XML-compatible
36 * output.
37 *
38 * There are two important configuration options this class uses:
39 *
40 * $wgMimeType: If this is set to an xml MIME type then output should be
41 * valid XHTML5.
42 *
43 * This class is meant to be confined to utility functions that are called from
44 * trusted code paths. It does not do enforcement of policy like not allowing
45 * <a> elements.
46 *
47 * @since 1.16
48 */
49 class Html {
50 // List of void elements from HTML5, section 8.1.2 as of 2016-09-19
51 private static $voidElements = [
52 'area',
53 'base',
54 'br',
55 'col',
56 'embed',
57 'hr',
58 'img',
59 'input',
60 'keygen',
61 'link',
62 'meta',
63 'param',
64 'source',
65 'track',
66 'wbr',
67 ];
68
69 // Boolean attributes, which may have the value omitted entirely. Manually
70 // collected from the HTML5 spec as of 2011-08-12.
71 private static $boolAttribs = [
72 'async',
73 'autofocus',
74 'autoplay',
75 'checked',
76 'controls',
77 'default',
78 'defer',
79 'disabled',
80 'formnovalidate',
81 'hidden',
82 'ismap',
83 'itemscope',
84 'loop',
85 'multiple',
86 'muted',
87 'novalidate',
88 'open',
89 'pubdate',
90 'readonly',
91 'required',
92 'reversed',
93 'scoped',
94 'seamless',
95 'selected',
96 'truespeed',
97 'typemustmatch',
98 // HTML5 Microdata
99 'itemscope',
100 ];
101
102 /**
103 * Modifies a set of attributes meant for button elements
104 * and apply a set of default attributes when $wgUseMediaWikiUIEverywhere enabled.
105 * @param array $attrs HTML attributes in an associative array
106 * @param string[] $modifiers classes to add to the button
107 * @see https://tools.wmflabs.org/styleguide/desktop/index.html for guidance on available modifiers
108 * @return array $attrs A modified attribute array
109 */
110 public static function buttonAttributes( array $attrs, array $modifiers = [] ) {
111 global $wgUseMediaWikiUIEverywhere;
112 if ( $wgUseMediaWikiUIEverywhere ) {
113 if ( isset( $attrs['class'] ) ) {
114 if ( is_array( $attrs['class'] ) ) {
115 $attrs['class'][] = 'mw-ui-button';
116 $attrs['class'] = array_merge( $attrs['class'], $modifiers );
117 // ensure compatibility with Xml
118 $attrs['class'] = implode( ' ', $attrs['class'] );
119 } else {
120 $attrs['class'] .= ' mw-ui-button ' . implode( ' ', $modifiers );
121 }
122 } else {
123 // ensure compatibility with Xml
124 $attrs['class'] = 'mw-ui-button ' . implode( ' ', $modifiers );
125 }
126 }
127 return $attrs;
128 }
129
130 /**
131 * Modifies a set of attributes meant for text input elements
132 * and apply a set of default attributes.
133 * Removes size attribute when $wgUseMediaWikiUIEverywhere enabled.
134 * @param array $attrs An attribute array.
135 * @return array $attrs A modified attribute array
136 */
137 public static function getTextInputAttributes( array $attrs ) {
138 global $wgUseMediaWikiUIEverywhere;
139 if ( $wgUseMediaWikiUIEverywhere ) {
140 if ( isset( $attrs['class'] ) ) {
141 if ( is_array( $attrs['class'] ) ) {
142 $attrs['class'][] = 'mw-ui-input';
143 } else {
144 $attrs['class'] .= ' mw-ui-input';
145 }
146 } else {
147 $attrs['class'] = 'mw-ui-input';
148 }
149 }
150 return $attrs;
151 }
152
153 /**
154 * Returns an HTML link element in a string styled as a button
155 * (when $wgUseMediaWikiUIEverywhere is enabled).
156 *
157 * @param string $contents The raw HTML contents of the element: *not*
158 * escaped!
159 * @param array $attrs Associative array of attributes, e.g., [
160 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
161 * further documentation.
162 * @param string[] $modifiers classes to add to the button
163 * @see https://tools.wmflabs.org/styleguide/desktop/index.html for guidance on available modifiers
164 * @return string Raw HTML
165 */
166 public static function linkButton( $contents, array $attrs, array $modifiers = [] ) {
167 return self::element( 'a',
168 self::buttonAttributes( $attrs, $modifiers ),
169 $contents
170 );
171 }
172
173 /**
174 * Returns an HTML link element in a string styled as a button
175 * (when $wgUseMediaWikiUIEverywhere is enabled).
176 *
177 * @param string $contents The raw HTML contents of the element: *not*
178 * escaped!
179 * @param array $attrs Associative array of attributes, e.g., [
180 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
181 * further documentation.
182 * @param string[] $modifiers classes to add to the button
183 * @see https://tools.wmflabs.org/styleguide/desktop/index.html for guidance on available modifiers
184 * @return string Raw HTML
185 */
186 public static function submitButton( $contents, array $attrs, array $modifiers = [] ) {
187 $attrs['type'] = 'submit';
188 $attrs['value'] = $contents;
189 return self::element( 'input', self::buttonAttributes( $attrs, $modifiers ) );
190 }
191
192 /**
193 * Returns an HTML element in a string. The major advantage here over
194 * manually typing out the HTML is that it will escape all attribute
195 * values.
196 *
197 * This is quite similar to Xml::tags(), but it implements some useful
198 * HTML-specific logic. For instance, there is no $allowShortTag
199 * parameter: the closing tag is magically omitted if $element has an empty
200 * content model.
201 *
202 * @param string $element The element's name, e.g., 'a'
203 * @param array $attribs Associative array of attributes, e.g., [
204 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
205 * further documentation.
206 * @param string $contents The raw HTML contents of the element: *not*
207 * escaped!
208 * @return string Raw HTML
209 */
210 public static function rawElement( $element, $attribs = [], $contents = '' ) {
211 $start = self::openElement( $element, $attribs );
212 if ( in_array( $element, self::$voidElements ) ) {
213 // Silly XML.
214 return substr( $start, 0, -1 ) . '/>';
215 } else {
216 return $start . $contents . self::closeElement( $element );
217 }
218 }
219
220 /**
221 * Identical to rawElement(), but HTML-escapes $contents (like
222 * Xml::element()).
223 *
224 * @param string $element Name of the element, e.g., 'a'
225 * @param array $attribs Associative array of attributes, e.g., [
226 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
227 * further documentation.
228 * @param string $contents
229 *
230 * @return string
231 */
232 public static function element( $element, $attribs = [], $contents = '' ) {
233 return self::rawElement( $element, $attribs, strtr( $contents, [
234 // There's no point in escaping quotes, >, etc. in the contents of
235 // elements.
236 '&' => '&amp;',
237 '<' => '&lt;'
238 ] ) );
239 }
240
241 /**
242 * Identical to rawElement(), but has no third parameter and omits the end
243 * tag (and the self-closing '/' in XML mode for empty elements).
244 *
245 * @param string $element Name of the element, e.g., 'a'
246 * @param array $attribs Associative array of attributes, e.g., [
247 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
248 * further documentation.
249 *
250 * @return string
251 */
252 public static function openElement( $element, $attribs = [] ) {
253 $attribs = (array)$attribs;
254 // This is not required in HTML5, but let's do it anyway, for
255 // consistency and better compression.
256 $element = strtolower( $element );
257
258 // Some people were abusing this by passing things like
259 // 'h1 id="foo" to $element, which we don't want.
260 if ( strpos( $element, ' ' ) !== false ) {
261 wfWarn( __METHOD__ . " given element name with space '$element'" );
262 }
263
264 // Remove invalid input types
265 if ( $element == 'input' ) {
266 $validTypes = [
267 'hidden',
268 'text',
269 'password',
270 'checkbox',
271 'radio',
272 'file',
273 'submit',
274 'image',
275 'reset',
276 'button',
277
278 // HTML input types
279 'datetime',
280 'datetime-local',
281 'date',
282 'month',
283 'time',
284 'week',
285 'number',
286 'range',
287 'email',
288 'url',
289 'search',
290 'tel',
291 'color',
292 ];
293 if ( isset( $attribs['type'] ) && !in_array( $attribs['type'], $validTypes ) ) {
294 unset( $attribs['type'] );
295 }
296 }
297
298 // According to standard the default type for <button> elements is "submit".
299 // Depending on compatibility mode IE might use "button", instead.
300 // We enforce the standard "submit".
301 if ( $element == 'button' && !isset( $attribs['type'] ) ) {
302 $attribs['type'] = 'submit';
303 }
304
305 return "<$element" . self::expandAttributes(
306 self::dropDefaults( $element, $attribs ) ) . '>';
307 }
308
309 /**
310 * Returns "</$element>"
311 *
312 * @since 1.17
313 * @param string $element Name of the element, e.g., 'a'
314 * @return string A closing tag
315 */
316 public static function closeElement( $element ) {
317 $element = strtolower( $element );
318
319 return "</$element>";
320 }
321
322 /**
323 * Given an element name and an associative array of element attributes,
324 * return an array that is functionally identical to the input array, but
325 * possibly smaller. In particular, attributes might be stripped if they
326 * are given their default values.
327 *
328 * This method is not guaranteed to remove all redundant attributes, only
329 * some common ones and some others selected arbitrarily at random. It
330 * only guarantees that the output array should be functionally identical
331 * to the input array (currently per the HTML 5 draft as of 2009-09-06).
332 *
333 * @param string $element Name of the element, e.g., 'a'
334 * @param array $attribs Associative array of attributes, e.g., [
335 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
336 * further documentation.
337 * @return array An array of attributes functionally identical to $attribs
338 */
339 private static function dropDefaults( $element, array $attribs ) {
340 // Whenever altering this array, please provide a covering test case
341 // in HtmlTest::provideElementsWithAttributesHavingDefaultValues
342 static $attribDefaults = [
343 'area' => [ 'shape' => 'rect' ],
344 'button' => [
345 'formaction' => 'GET',
346 'formenctype' => 'application/x-www-form-urlencoded',
347 ],
348 'canvas' => [
349 'height' => '150',
350 'width' => '300',
351 ],
352 'form' => [
353 'action' => 'GET',
354 'autocomplete' => 'on',
355 'enctype' => 'application/x-www-form-urlencoded',
356 ],
357 'input' => [
358 'formaction' => 'GET',
359 'type' => 'text',
360 ],
361 'keygen' => [ 'keytype' => 'rsa' ],
362 'link' => [ 'media' => 'all' ],
363 'menu' => [ 'type' => 'list' ],
364 'script' => [ 'type' => 'text/javascript' ],
365 'style' => [
366 'media' => 'all',
367 'type' => 'text/css',
368 ],
369 'textarea' => [ 'wrap' => 'soft' ],
370 ];
371
372 $element = strtolower( $element );
373
374 foreach ( $attribs as $attrib => $value ) {
375 $lcattrib = strtolower( $attrib );
376 if ( is_array( $value ) ) {
377 $value = implode( ' ', $value );
378 } else {
379 $value = strval( $value );
380 }
381
382 // Simple checks using $attribDefaults
383 if ( isset( $attribDefaults[$element][$lcattrib] )
384 && $attribDefaults[$element][$lcattrib] == $value
385 ) {
386 unset( $attribs[$attrib] );
387 }
388
389 if ( $lcattrib == 'class' && $value == '' ) {
390 unset( $attribs[$attrib] );
391 }
392 }
393
394 // More subtle checks
395 if ( $element === 'link'
396 && isset( $attribs['type'] ) && strval( $attribs['type'] ) == 'text/css'
397 ) {
398 unset( $attribs['type'] );
399 }
400 if ( $element === 'input' ) {
401 $type = $attribs['type'] ?? null;
402 $value = $attribs['value'] ?? null;
403 if ( $type === 'checkbox' || $type === 'radio' ) {
404 // The default value for checkboxes and radio buttons is 'on'
405 // not ''. By stripping value="" we break radio boxes that
406 // actually wants empty values.
407 if ( $value === 'on' ) {
408 unset( $attribs['value'] );
409 }
410 } elseif ( $type === 'submit' ) {
411 // The default value for submit appears to be "Submit" but
412 // let's not bother stripping out localized text that matches
413 // that.
414 } else {
415 // The default value for nearly every other field type is ''
416 // The 'range' and 'color' types use different defaults but
417 // stripping a value="" does not hurt them.
418 if ( $value === '' ) {
419 unset( $attribs['value'] );
420 }
421 }
422 }
423 if ( $element === 'select' && isset( $attribs['size'] ) ) {
424 if ( in_array( 'multiple', $attribs )
425 || ( isset( $attribs['multiple'] ) && $attribs['multiple'] !== false )
426 ) {
427 // A multi-select
428 if ( strval( $attribs['size'] ) == '4' ) {
429 unset( $attribs['size'] );
430 }
431 } else {
432 // Single select
433 if ( strval( $attribs['size'] ) == '1' ) {
434 unset( $attribs['size'] );
435 }
436 }
437 }
438
439 return $attribs;
440 }
441
442 /**
443 * Given an associative array of element attributes, generate a string
444 * to stick after the element name in HTML output. Like [ 'href' =>
445 * 'https://www.mediawiki.org/' ] becomes something like
446 * ' href="https://www.mediawiki.org"'. Again, this is like
447 * Xml::expandAttributes(), but it implements some HTML-specific logic.
448 *
449 * Attributes that can contain space-separated lists ('class', 'accesskey' and 'rel') array
450 * values are allowed as well, which will automagically be normalized
451 * and converted to a space-separated string. In addition to a numerical
452 * array, the attribute value may also be an associative array. See the
453 * example below for how that works.
454 *
455 * @par Numerical array
456 * @code
457 * Html::element( 'em', [
458 * 'class' => [ 'foo', 'bar' ]
459 * ] );
460 * // gives '<em class="foo bar"></em>'
461 * @endcode
462 *
463 * @par Associative array
464 * @code
465 * Html::element( 'em', [
466 * 'class' => [ 'foo', 'bar', 'foo' => false, 'quux' => true ]
467 * ] );
468 * // gives '<em class="bar quux"></em>'
469 * @endcode
470 *
471 * @param array $attribs Associative array of attributes, e.g., [
472 * 'href' => 'https://www.mediawiki.org/' ]. Values will be HTML-escaped.
473 * A value of false or null means to omit the attribute. For boolean attributes,
474 * you can omit the key, e.g., [ 'checked' ] instead of
475 * [ 'checked' => 'checked' ] or such.
476 *
477 * @throws MWException If an attribute that doesn't allow lists is set to an array
478 * @return string HTML fragment that goes between element name and '>'
479 * (starting with a space if at least one attribute is output)
480 */
481 public static function expandAttributes( array $attribs ) {
482 $ret = '';
483 foreach ( $attribs as $key => $value ) {
484 // Support intuitive [ 'checked' => true/false ] form
485 if ( $value === false || is_null( $value ) ) {
486 continue;
487 }
488
489 // For boolean attributes, support [ 'foo' ] instead of
490 // requiring [ 'foo' => 'meaningless' ].
491 if ( is_int( $key ) && in_array( strtolower( $value ), self::$boolAttribs ) ) {
492 $key = $value;
493 }
494
495 // Not technically required in HTML5 but we'd like consistency
496 // and better compression anyway.
497 $key = strtolower( $key );
498
499 // https://www.w3.org/TR/html401/index/attributes.html ("space-separated")
500 // https://www.w3.org/TR/html5/index.html#attributes-1 ("space-separated")
501 $spaceSeparatedListAttributes = [
502 'class', // html4, html5
503 'accesskey', // as of html5, multiple space-separated values allowed
504 // html4-spec doesn't document rel= as space-separated
505 // but has been used like that and is now documented as such
506 // in the html5-spec.
507 'rel',
508 ];
509
510 // Specific features for attributes that allow a list of space-separated values
511 if ( in_array( $key, $spaceSeparatedListAttributes ) ) {
512 // Apply some normalization and remove duplicates
513
514 // Convert into correct array. Array can contain space-separated
515 // values. Implode/explode to get those into the main array as well.
516 if ( is_array( $value ) ) {
517 // If input wasn't an array, we can skip this step
518 $newValue = [];
519 foreach ( $value as $k => $v ) {
520 if ( is_string( $v ) ) {
521 // String values should be normal `[ 'foo' ]`
522 // Just append them
523 if ( !isset( $value[$v] ) ) {
524 // As a special case don't set 'foo' if a
525 // separate 'foo' => true/false exists in the array
526 // keys should be authoritative
527 $newValue[] = $v;
528 }
529 } elseif ( $v ) {
530 // If the value is truthy but not a string this is likely
531 // an [ 'foo' => true ], falsy values don't add strings
532 $newValue[] = $k;
533 }
534 }
535 $value = implode( ' ', $newValue );
536 }
537 $value = explode( ' ', $value );
538
539 // Normalize spacing by fixing up cases where people used
540 // more than 1 space and/or a trailing/leading space
541 $value = array_diff( $value, [ '', ' ' ] );
542
543 // Remove duplicates and create the string
544 $value = implode( ' ', array_unique( $value ) );
545 } elseif ( is_array( $value ) ) {
546 throw new MWException( "HTML attribute $key can not contain a list of values" );
547 }
548
549 $quote = '"';
550
551 if ( in_array( $key, self::$boolAttribs ) ) {
552 $ret .= " $key=\"\"";
553 } else {
554 $ret .= " $key=$quote" . Sanitizer::encodeAttribute( $value ) . $quote;
555 }
556 }
557 return $ret;
558 }
559
560 /**
561 * Output an HTML script tag with the given contents.
562 *
563 * It is unsupported for the contents to contain the sequence `<script` or `</script`
564 * (case-insensitive). This ensures the script can be terminated easily and consistently.
565 * It is the responsibility of the caller to avoid such character sequence by escaping
566 * or avoiding it. If found at run-time, the contents are replaced with a comment, and
567 * a warning is logged server-side.
568 *
569 * @param string $contents JavaScript
570 * @param string|null $nonce Nonce for CSP header, from OutputPage::getCSPNonce()
571 * @return string Raw HTML
572 */
573 public static function inlineScript( $contents, $nonce = null ) {
574 $attrs = [];
575 if ( $nonce !== null ) {
576 $attrs['nonce'] = $nonce;
577 } elseif ( ContentSecurityPolicy::isNonceRequired( RequestContext::getMain()->getConfig() ) ) {
578 wfWarn( "no nonce set on script. CSP will break it" );
579 }
580
581 if ( preg_match( '/<\/?script/i', $contents ) ) {
582 wfLogWarning( __METHOD__ . ': Illegal character sequence found in inline script.' );
583 $contents = '/* ERROR: Invalid script */';
584 }
585
586 return self::rawElement( 'script', $attrs, $contents );
587 }
588
589 /**
590 * Output a "<script>" tag linking to the given URL, e.g.,
591 * "<script src=foo.js></script>".
592 *
593 * @param string $url
594 * @param string|null $nonce Nonce for CSP header, from OutputPage::getCSPNonce()
595 * @return string Raw HTML
596 */
597 public static function linkedScript( $url, $nonce = null ) {
598 $attrs = [ 'src' => $url ];
599 if ( $nonce !== null ) {
600 $attrs['nonce'] = $nonce;
601 } elseif ( ContentSecurityPolicy::isNonceRequired( RequestContext::getMain()->getConfig() ) ) {
602 wfWarn( "no nonce set on script. CSP will break it" );
603 }
604
605 return self::element( 'script', $attrs );
606 }
607
608 /**
609 * Output a "<style>" tag with the given contents for the given media type
610 * (if any). TODO: do some useful escaping as well, like if $contents
611 * contains literal "</style>" (admittedly unlikely).
612 *
613 * @param string $contents CSS
614 * @param string $media A media type string, like 'screen'
615 * @param array $attribs (since 1.31) Associative array of attributes, e.g., [
616 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
617 * further documentation.
618 * @return string Raw HTML
619 */
620 public static function inlineStyle( $contents, $media = 'all', $attribs = [] ) {
621 // Don't escape '>' since that is used
622 // as direct child selector.
623 // Remember, in css, there is no "x" for hexadecimal escapes, and
624 // the space immediately after an escape sequence is swallowed.
625 $contents = strtr( $contents, [
626 '<' => '\3C ',
627 // CDATA end tag for good measure, but the main security
628 // is from escaping the '<'.
629 ']]>' => '\5D\5D\3E '
630 ] );
631
632 if ( preg_match( '/[<&]/', $contents ) ) {
633 $contents = "/*<![CDATA[*/$contents/*]]>*/";
634 }
635
636 return self::rawElement( 'style', [
637 'media' => $media,
638 ] + $attribs, $contents );
639 }
640
641 /**
642 * Output a "<link rel=stylesheet>" linking to the given URL for the given
643 * media type (if any).
644 *
645 * @param string $url
646 * @param string $media A media type string, like 'screen'
647 * @return string Raw HTML
648 */
649 public static function linkedStyle( $url, $media = 'all' ) {
650 return self::element( 'link', [
651 'rel' => 'stylesheet',
652 'href' => $url,
653 'media' => $media,
654 ] );
655 }
656
657 /**
658 * Convenience function to produce an "<input>" element. This supports the
659 * new HTML5 input types and attributes.
660 *
661 * @param string $name Name attribute
662 * @param string $value Value attribute
663 * @param string $type Type attribute
664 * @param array $attribs Associative array of miscellaneous extra
665 * attributes, passed to Html::element()
666 * @return string Raw HTML
667 */
668 public static function input( $name, $value = '', $type = 'text', array $attribs = [] ) {
669 $attribs['type'] = $type;
670 $attribs['value'] = $value;
671 $attribs['name'] = $name;
672 if ( in_array( $type, [ 'text', 'search', 'email', 'password', 'number' ] ) ) {
673 $attribs = self::getTextInputAttributes( $attribs );
674 }
675 if ( in_array( $type, [ 'button', 'reset', 'submit' ] ) ) {
676 $attribs = self::buttonAttributes( $attribs );
677 }
678 return self::element( 'input', $attribs );
679 }
680
681 /**
682 * Convenience function to produce a checkbox (input element with type=checkbox)
683 *
684 * @param string $name Name attribute
685 * @param bool $checked Whether the checkbox is checked or not
686 * @param array $attribs Array of additional attributes
687 * @return string Raw HTML
688 */
689 public static function check( $name, $checked = false, array $attribs = [] ) {
690 if ( isset( $attribs['value'] ) ) {
691 $value = $attribs['value'];
692 unset( $attribs['value'] );
693 } else {
694 $value = 1;
695 }
696
697 if ( $checked ) {
698 $attribs[] = 'checked';
699 }
700
701 return self::input( $name, $value, 'checkbox', $attribs );
702 }
703
704 /**
705 * Return the HTML for a message box.
706 * @since 1.31
707 * @param string $html of contents of box
708 * @param string $className corresponding to box
709 * @param string $heading (optional)
710 * @return string of HTML representing a box.
711 */
712 private static function messageBox( $html, $className, $heading = '' ) {
713 if ( $heading !== '' ) {
714 $html = self::element( 'h2', [], $heading ) . $html;
715 }
716 return self::rawElement( 'div', [ 'class' => $className ], $html );
717 }
718
719 /**
720 * Return a warning box.
721 * @since 1.31
722 * @param string $html of contents of box
723 * @return string of HTML representing a warning box.
724 */
725 public static function warningBox( $html ) {
726 return self::messageBox( $html, 'warningbox' );
727 }
728
729 /**
730 * Return an error box.
731 * @since 1.31
732 * @param string $html of contents of error box
733 * @param string $heading (optional)
734 * @return string of HTML representing an error box.
735 */
736 public static function errorBox( $html, $heading = '' ) {
737 return self::messageBox( $html, 'errorbox', $heading );
738 }
739
740 /**
741 * Return a success box.
742 * @since 1.31
743 * @param string $html of contents of box
744 * @return string of HTML representing a success box.
745 */
746 public static function successBox( $html ) {
747 return self::messageBox( $html, 'successbox' );
748 }
749
750 /**
751 * Convenience function to produce a radio button (input element with type=radio)
752 *
753 * @param string $name Name attribute
754 * @param bool $checked Whether the radio button is checked or not
755 * @param array $attribs Array of additional attributes
756 * @return string Raw HTML
757 */
758 public static function radio( $name, $checked = false, array $attribs = [] ) {
759 if ( isset( $attribs['value'] ) ) {
760 $value = $attribs['value'];
761 unset( $attribs['value'] );
762 } else {
763 $value = 1;
764 }
765
766 if ( $checked ) {
767 $attribs[] = 'checked';
768 }
769
770 return self::input( $name, $value, 'radio', $attribs );
771 }
772
773 /**
774 * Convenience function for generating a label for inputs.
775 *
776 * @param string $label Contents of the label
777 * @param string $id ID of the element being labeled
778 * @param array $attribs Additional attributes
779 * @return string Raw HTML
780 */
781 public static function label( $label, $id, array $attribs = [] ) {
782 $attribs += [
783 'for' => $id
784 ];
785 return self::element( 'label', $attribs, $label );
786 }
787
788 /**
789 * Convenience function to produce an input element with type=hidden
790 *
791 * @param string $name Name attribute
792 * @param string $value Value attribute
793 * @param array $attribs Associative array of miscellaneous extra
794 * attributes, passed to Html::element()
795 * @return string Raw HTML
796 */
797 public static function hidden( $name, $value, array $attribs = [] ) {
798 return self::input( $name, $value, 'hidden', $attribs );
799 }
800
801 /**
802 * Convenience function to produce a <textarea> element.
803 *
804 * This supports leaving out the cols= and rows= which Xml requires and are
805 * required by HTML4/XHTML but not required by HTML5.
806 *
807 * @param string $name Name attribute
808 * @param string $value Value attribute
809 * @param array $attribs Associative array of miscellaneous extra
810 * attributes, passed to Html::element()
811 * @return string Raw HTML
812 */
813 public static function textarea( $name, $value = '', array $attribs = [] ) {
814 $attribs['name'] = $name;
815
816 if ( substr( $value, 0, 1 ) == "\n" ) {
817 // Workaround for T14130: browsers eat the initial newline
818 // assuming that it's just for show, but they do keep the later
819 // newlines, which we may want to preserve during editing.
820 // Prepending a single newline
821 $spacedValue = "\n" . $value;
822 } else {
823 $spacedValue = $value;
824 }
825 return self::element( 'textarea', self::getTextInputAttributes( $attribs ), $spacedValue );
826 }
827
828 /**
829 * Helper for Html::namespaceSelector().
830 * @param array $params See Html::namespaceSelector()
831 * @return array
832 */
833 public static function namespaceSelectorOptions( array $params = [] ) {
834 if ( !isset( $params['exclude'] ) || !is_array( $params['exclude'] ) ) {
835 $params['exclude'] = [];
836 }
837
838 if ( $params['in-user-lang'] ?? false ) {
839 global $wgLang;
840 $lang = $wgLang;
841 } else {
842 $lang = MediaWikiServices::getInstance()->getContentLanguage();
843 }
844
845 $optionsOut = [];
846 if ( isset( $params['all'] ) ) {
847 // add an option that would let the user select all namespaces.
848 // Value is provided by user, the name shown is localized for the user.
849 $optionsOut[$params['all']] = wfMessage( 'namespacesall' )->text();
850 }
851 // Add all namespaces as options
852 $options = $lang->getFormattedNamespaces();
853 // Filter out namespaces below 0 and massage labels
854 foreach ( $options as $nsId => $nsName ) {
855 if ( $nsId < NS_MAIN || in_array( $nsId, $params['exclude'] ) ) {
856 continue;
857 }
858 if ( $nsId === NS_MAIN ) {
859 // For other namespaces use the namespace prefix as label, but for
860 // main we don't use "" but the user message describing it (e.g. "(Main)" or "(Article)")
861 $nsName = wfMessage( 'blanknamespace' )->text();
862 } elseif ( is_int( $nsId ) ) {
863 $nsName = $lang->convertNamespace( $nsId );
864 }
865 $optionsOut[$nsId] = $nsName;
866 }
867
868 return $optionsOut;
869 }
870
871 /**
872 * Build a drop-down box for selecting a namespace
873 *
874 * @param array $params Params to set.
875 * - selected: [optional] Id of namespace which should be pre-selected
876 * - all: [optional] Value of item for "all namespaces". If null or unset,
877 * no "<option>" is generated to select all namespaces.
878 * - label: text for label to add before the field.
879 * - exclude: [optional] Array of namespace ids to exclude.
880 * - disable: [optional] Array of namespace ids for which the option should
881 * be disabled in the selector.
882 * @param array $selectAttribs HTML attributes for the generated select element.
883 * - id: [optional], default: 'namespace'.
884 * - name: [optional], default: 'namespace'.
885 * @return string HTML code to select a namespace.
886 */
887 public static function namespaceSelector( array $params = [],
888 array $selectAttribs = []
889 ) {
890 ksort( $selectAttribs );
891
892 // Is a namespace selected?
893 if ( isset( $params['selected'] ) ) {
894 // If string only contains digits, convert to clean int. Selected could also
895 // be "all" or "" etc. which needs to be left untouched.
896 // PHP is_numeric() has issues with large strings, PHP ctype_digit has other issues
897 // and returns false for already clean ints. Use regex instead..
898 if ( preg_match( '/^\d+$/', $params['selected'] ) ) {
899 $params['selected'] = intval( $params['selected'] );
900 }
901 // else: leaves it untouched for later processing
902 } else {
903 $params['selected'] = '';
904 }
905
906 if ( !isset( $params['disable'] ) || !is_array( $params['disable'] ) ) {
907 $params['disable'] = [];
908 }
909
910 // Associative array between option-values and option-labels
911 $options = self::namespaceSelectorOptions( $params );
912
913 // Convert $options to HTML
914 $optionsHtml = [];
915 foreach ( $options as $nsId => $nsName ) {
916 $optionsHtml[] = self::element(
917 'option', [
918 'disabled' => in_array( $nsId, $params['disable'] ),
919 'value' => $nsId,
920 'selected' => $nsId === $params['selected'],
921 ], $nsName
922 );
923 }
924
925 if ( !array_key_exists( 'id', $selectAttribs ) ) {
926 $selectAttribs['id'] = 'namespace';
927 }
928
929 if ( !array_key_exists( 'name', $selectAttribs ) ) {
930 $selectAttribs['name'] = 'namespace';
931 }
932
933 $ret = '';
934 if ( isset( $params['label'] ) ) {
935 $ret .= self::element(
936 'label', [
937 'for' => $selectAttribs['id'] ?? null,
938 ], $params['label']
939 ) . "\u{00A0}";
940 }
941
942 // Wrap options in a <select>
943 $ret .= self::openElement( 'select', $selectAttribs )
944 . "\n"
945 . implode( "\n", $optionsHtml )
946 . "\n"
947 . self::closeElement( 'select' );
948
949 return $ret;
950 }
951
952 /**
953 * Constructs the opening html-tag with necessary doctypes depending on
954 * global variables.
955 *
956 * @param array $attribs Associative array of miscellaneous extra
957 * attributes, passed to Html::element() of html tag.
958 * @return string Raw HTML
959 */
960 public static function htmlHeader( array $attribs = [] ) {
961 $ret = '';
962
963 global $wgHtml5Version, $wgMimeType, $wgXhtmlNamespaces;
964
965 $isXHTML = self::isXmlMimeType( $wgMimeType );
966
967 if ( $isXHTML ) { // XHTML5
968 // XML MIME-typed markup should have an xml header.
969 // However a DOCTYPE is not needed.
970 $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";
971
972 // Add the standard xmlns
973 $attribs['xmlns'] = 'http://www.w3.org/1999/xhtml';
974
975 // And support custom namespaces
976 foreach ( $wgXhtmlNamespaces as $tag => $ns ) {
977 $attribs["xmlns:$tag"] = $ns;
978 }
979 } else { // HTML5
980 $ret .= "<!DOCTYPE html>\n";
981 }
982
983 if ( $wgHtml5Version ) {
984 $attribs['version'] = $wgHtml5Version;
985 }
986
987 $ret .= self::openElement( 'html', $attribs );
988
989 return $ret;
990 }
991
992 /**
993 * Determines if the given MIME type is xml.
994 *
995 * @param string $mimetype MIME type
996 * @return bool
997 */
998 public static function isXmlMimeType( $mimetype ) {
999 # https://html.spec.whatwg.org/multipage/infrastructure.html#xml-mime-type
1000 # * text/xml
1001 # * application/xml
1002 # * Any MIME type with a subtype ending in +xml (this implicitly includes application/xhtml+xml)
1003 return (bool)preg_match( '!^(text|application)/xml$|^.+/.+\+xml$!', $mimetype );
1004 }
1005
1006 /**
1007 * Get HTML for an information message box with an icon.
1008 *
1009 * @internal For use by the WebInstaller class.
1010 * @param string $rawHtml HTML
1011 * @param string $icon Path to icon file (used as 'src' attribute)
1012 * @param string $alt Alternate text for the icon
1013 * @param string $class Additional class name to add to the wrapper div
1014 * @return string HTML
1015 */
1016 public static function infoBox( $rawHtml, $icon, $alt, $class = '' ) {
1017 $s = self::openElement( 'div', [ 'class' => "mw-infobox $class" ] );
1018
1019 $s .= self::openElement( 'div', [ 'class' => 'mw-infobox-left' ] ) .
1020 self::element( 'img',
1021 [
1022 'src' => $icon,
1023 'alt' => $alt,
1024 ]
1025 ) .
1026 self::closeElement( 'div' );
1027
1028 $s .= self::openElement( 'div', [ 'class' => 'mw-infobox-right' ] ) .
1029 $rawHtml .
1030 self::closeElement( 'div' );
1031 $s .= self::element( 'div', [ 'style' => 'clear: left;' ], ' ' );
1032
1033 $s .= self::closeElement( 'div' );
1034
1035 $s .= self::element( 'div', [ 'style' => 'clear: left;' ], ' ' );
1036
1037 return $s;
1038 }
1039
1040 /**
1041 * Generate a srcset attribute value.
1042 *
1043 * Generates a srcset attribute value from an array mapping pixel densities
1044 * to URLs. A trailing 'x' in pixel density values is optional.
1045 *
1046 * @note srcset width and height values are not supported.
1047 *
1048 * @see https://html.spec.whatwg.org/#attr-img-srcset
1049 *
1050 * @par Example:
1051 * @code
1052 * Html::srcSet( [
1053 * '1x' => 'standard.jpeg',
1054 * '1.5x' => 'large.jpeg',
1055 * '3x' => 'extra-large.jpeg',
1056 * ] );
1057 * // gives 'standard.jpeg 1x, large.jpeg 1.5x, extra-large.jpeg 2x'
1058 * @endcode
1059 *
1060 * @param string[] $urls
1061 * @return string
1062 */
1063 static function srcSet( array $urls ) {
1064 $candidates = [];
1065 foreach ( $urls as $density => $url ) {
1066 // Cast density to float to strip 'x', then back to string to serve
1067 // as array index.
1068 $density = (string)(float)$density;
1069 $candidates[$density] = $url;
1070 }
1071
1072 // Remove duplicates that are the same as a smaller value
1073 ksort( $candidates, SORT_NUMERIC );
1074 $candidates = array_unique( $candidates );
1075
1076 // Append density info to the url
1077 foreach ( $candidates as $density => $url ) {
1078 $candidates[$density] = $url . ' ' . $density . 'x';
1079 }
1080
1081 return implode( ", ", $candidates );
1082 }
1083 }