OutputPage: Fix blank line between <html> and <head>
[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 * 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 */
25
26 /**
27 * This class is a collection of static functions that serve two purposes:
28 *
29 * 1) Implement any algorithms specified by HTML5, or other HTML
30 * specifications, in a convenient and self-contained way.
31 *
32 * 2) Allow HTML elements to be conveniently and safely generated, like the
33 * current Xml class but a) less confused (Xml supports HTML-specific things,
34 * but only sometimes!) and b) not necessarily confined to XML-compatible
35 * output.
36 *
37 * There are two important configuration options this class uses:
38 *
39 * $wgMimeType: If this is set to an xml MIME type then output should be
40 * valid XHTML5.
41 *
42 * This class is meant to be confined to utility functions that are called from
43 * trusted code paths. It does not do enforcement of policy like not allowing
44 * <a> elements.
45 *
46 * @since 1.16
47 */
48 class Html {
49 // List of void elements from HTML5, section 8.1.2 as of 2011-08-12
50 private static $voidElements = [
51 'area',
52 'base',
53 'br',
54 'col',
55 'command',
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., array(
160 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
161 * further documentation.
162 * @param string[] $modifiers classes to add to the button
163 * @see http://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., array(
180 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
181 * further documentation.
182 * @param string[] $modifiers classes to add to the button
183 * @see http://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., array(
204 * 'href' => 'http://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
225 * @param array $attribs
226 * @param string $contents
227 *
228 * @return string
229 */
230 public static function element( $element, $attribs = [], $contents = '' ) {
231 return self::rawElement( $element, $attribs, strtr( $contents, [
232 // There's no point in escaping quotes, >, etc. in the contents of
233 // elements.
234 '&' => '&amp;',
235 '<' => '&lt;'
236 ] ) );
237 }
238
239 /**
240 * Identical to rawElement(), but has no third parameter and omits the end
241 * tag (and the self-closing '/' in XML mode for empty elements).
242 *
243 * @param string $element
244 * @param array $attribs
245 *
246 * @return string
247 */
248 public static function openElement( $element, $attribs = [] ) {
249 $attribs = (array)$attribs;
250 // This is not required in HTML5, but let's do it anyway, for
251 // consistency and better compression.
252 $element = strtolower( $element );
253
254 // Remove invalid input types
255 if ( $element == 'input' ) {
256 $validTypes = [
257 'hidden',
258 'text',
259 'password',
260 'checkbox',
261 'radio',
262 'file',
263 'submit',
264 'image',
265 'reset',
266 'button',
267
268 // HTML input types
269 'datetime',
270 'datetime-local',
271 'date',
272 'month',
273 'time',
274 'week',
275 'number',
276 'range',
277 'email',
278 'url',
279 'search',
280 'tel',
281 'color',
282 ];
283 if ( isset( $attribs['type'] ) && !in_array( $attribs['type'], $validTypes ) ) {
284 unset( $attribs['type'] );
285 }
286 }
287
288 // According to standard the default type for <button> elements is "submit".
289 // Depending on compatibility mode IE might use "button", instead.
290 // We enforce the standard "submit".
291 if ( $element == 'button' && !isset( $attribs['type'] ) ) {
292 $attribs['type'] = 'submit';
293 }
294
295 return "<$element" . self::expandAttributes(
296 self::dropDefaults( $element, $attribs ) ) . '>';
297 }
298
299 /**
300 * Returns "</$element>"
301 *
302 * @since 1.17
303 * @param string $element Name of the element, e.g., 'a'
304 * @return string A closing tag
305 */
306 public static function closeElement( $element ) {
307 $element = strtolower( $element );
308
309 return "</$element>";
310 }
311
312 /**
313 * Given an element name and an associative array of element attributes,
314 * return an array that is functionally identical to the input array, but
315 * possibly smaller. In particular, attributes might be stripped if they
316 * are given their default values.
317 *
318 * This method is not guaranteed to remove all redundant attributes, only
319 * some common ones and some others selected arbitrarily at random. It
320 * only guarantees that the output array should be functionally identical
321 * to the input array (currently per the HTML 5 draft as of 2009-09-06).
322 *
323 * @param string $element Name of the element, e.g., 'a'
324 * @param array $attribs Associative array of attributes, e.g., array(
325 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
326 * further documentation.
327 * @return array An array of attributes functionally identical to $attribs
328 */
329 private static function dropDefaults( $element, array $attribs ) {
330 // Whenever altering this array, please provide a covering test case
331 // in HtmlTest::provideElementsWithAttributesHavingDefaultValues
332 static $attribDefaults = [
333 'area' => [ 'shape' => 'rect' ],
334 'button' => [
335 'formaction' => 'GET',
336 'formenctype' => 'application/x-www-form-urlencoded',
337 ],
338 'canvas' => [
339 'height' => '150',
340 'width' => '300',
341 ],
342 'command' => [ 'type' => 'command' ],
343 'form' => [
344 'action' => 'GET',
345 'autocomplete' => 'on',
346 'enctype' => 'application/x-www-form-urlencoded',
347 ],
348 'input' => [
349 'formaction' => 'GET',
350 'type' => 'text',
351 ],
352 'keygen' => [ 'keytype' => 'rsa' ],
353 'link' => [ 'media' => 'all' ],
354 'menu' => [ 'type' => 'list' ],
355 'script' => [ 'type' => 'text/javascript' ],
356 'style' => [
357 'media' => 'all',
358 'type' => 'text/css',
359 ],
360 'textarea' => [ 'wrap' => 'soft' ],
361 ];
362
363 $element = strtolower( $element );
364
365 foreach ( $attribs as $attrib => $value ) {
366 $lcattrib = strtolower( $attrib );
367 if ( is_array( $value ) ) {
368 $value = implode( ' ', $value );
369 } else {
370 $value = strval( $value );
371 }
372
373 // Simple checks using $attribDefaults
374 if ( isset( $attribDefaults[$element][$lcattrib] )
375 && $attribDefaults[$element][$lcattrib] == $value
376 ) {
377 unset( $attribs[$attrib] );
378 }
379
380 if ( $lcattrib == 'class' && $value == '' ) {
381 unset( $attribs[$attrib] );
382 }
383 }
384
385 // More subtle checks
386 if ( $element === 'link'
387 && isset( $attribs['type'] ) && strval( $attribs['type'] ) == 'text/css'
388 ) {
389 unset( $attribs['type'] );
390 }
391 if ( $element === 'input' ) {
392 $type = isset( $attribs['type'] ) ? $attribs['type'] : null;
393 $value = isset( $attribs['value'] ) ? $attribs['value'] : null;
394 if ( $type === 'checkbox' || $type === 'radio' ) {
395 // The default value for checkboxes and radio buttons is 'on'
396 // not ''. By stripping value="" we break radio boxes that
397 // actually wants empty values.
398 if ( $value === 'on' ) {
399 unset( $attribs['value'] );
400 }
401 } elseif ( $type === 'submit' ) {
402 // The default value for submit appears to be "Submit" but
403 // let's not bother stripping out localized text that matches
404 // that.
405 } else {
406 // The default value for nearly every other field type is ''
407 // The 'range' and 'color' types use different defaults but
408 // stripping a value="" does not hurt them.
409 if ( $value === '' ) {
410 unset( $attribs['value'] );
411 }
412 }
413 }
414 if ( $element === 'select' && isset( $attribs['size'] ) ) {
415 if ( in_array( 'multiple', $attribs )
416 || ( isset( $attribs['multiple'] ) && $attribs['multiple'] !== false )
417 ) {
418 // A multi-select
419 if ( strval( $attribs['size'] ) == '4' ) {
420 unset( $attribs['size'] );
421 }
422 } else {
423 // Single select
424 if ( strval( $attribs['size'] ) == '1' ) {
425 unset( $attribs['size'] );
426 }
427 }
428 }
429
430 return $attribs;
431 }
432
433 /**
434 * Given an associative array of element attributes, generate a string
435 * to stick after the element name in HTML output. Like array( 'href' =>
436 * 'http://www.mediawiki.org/' ) becomes something like
437 * ' href="http://www.mediawiki.org"'. Again, this is like
438 * Xml::expandAttributes(), but it implements some HTML-specific logic.
439 *
440 * Attributes that can contain space-separated lists ('class', 'accesskey' and 'rel') array
441 * values are allowed as well, which will automagically be normalized
442 * and converted to a space-separated string. In addition to a numerical
443 * array, the attribute value may also be an associative array. See the
444 * example below for how that works.
445 *
446 * @par Numerical array
447 * @code
448 * Html::element( 'em', array(
449 * 'class' => array( 'foo', 'bar' )
450 * ) );
451 * // gives '<em class="foo bar"></em>'
452 * @endcode
453 *
454 * @par Associative array
455 * @code
456 * Html::element( 'em', array(
457 * 'class' => array( 'foo', 'bar', 'foo' => false, 'quux' => true )
458 * ) );
459 * // gives '<em class="bar quux"></em>'
460 * @endcode
461 *
462 * @param array $attribs Associative array of attributes, e.g., array(
463 * 'href' => 'http://www.mediawiki.org/' ). Values will be HTML-escaped.
464 * A value of false means to omit the attribute. For boolean attributes,
465 * you can omit the key, e.g., array( 'checked' ) instead of
466 * array( 'checked' => 'checked' ) or such.
467 *
468 * @throws MWException If an attribute that doesn't allow lists is set to an array
469 * @return string HTML fragment that goes between element name and '>'
470 * (starting with a space if at least one attribute is output)
471 */
472 public static function expandAttributes( array $attribs ) {
473 $ret = '';
474 foreach ( $attribs as $key => $value ) {
475 // Support intuitive array( 'checked' => true/false ) form
476 if ( $value === false || is_null( $value ) ) {
477 continue;
478 }
479
480 // For boolean attributes, support array( 'foo' ) instead of
481 // requiring array( 'foo' => 'meaningless' ).
482 if ( is_int( $key ) && in_array( strtolower( $value ), self::$boolAttribs ) ) {
483 $key = $value;
484 }
485
486 // Not technically required in HTML5 but we'd like consistency
487 // and better compression anyway.
488 $key = strtolower( $key );
489
490 // Bug 23769: Blacklist all form validation attributes for now. Current
491 // (June 2010) WebKit has no UI, so the form just refuses to submit
492 // without telling the user why, which is much worse than failing
493 // server-side validation. Opera is the only other implementation at
494 // this time, and has ugly UI, so just kill the feature entirely until
495 // we have at least one good implementation.
496
497 // As the default value of "1" for "step" rejects decimal
498 // numbers to be entered in 'type="number"' fields, allow
499 // the special case 'step="any"'.
500
501 if ( in_array( $key, [ 'max', 'min', 'pattern', 'required' ] )
502 || $key === 'step' && $value !== 'any' ) {
503 continue;
504 }
505
506 // http://www.w3.org/TR/html401/index/attributes.html ("space-separated")
507 // http://www.w3.org/TR/html5/index.html#attributes-1 ("space-separated")
508 $spaceSeparatedListAttributes = [
509 'class', // html4, html5
510 'accesskey', // as of html5, multiple space-separated values allowed
511 // html4-spec doesn't document rel= as space-separated
512 // but has been used like that and is now documented as such
513 // in the html5-spec.
514 'rel',
515 ];
516
517 // Specific features for attributes that allow a list of space-separated values
518 if ( in_array( $key, $spaceSeparatedListAttributes ) ) {
519 // Apply some normalization and remove duplicates
520
521 // Convert into correct array. Array can contain space-separated
522 // values. Implode/explode to get those into the main array as well.
523 if ( is_array( $value ) ) {
524 // If input wasn't an array, we can skip this step
525 $newValue = [];
526 foreach ( $value as $k => $v ) {
527 if ( is_string( $v ) ) {
528 // String values should be normal `array( 'foo' )`
529 // Just append them
530 if ( !isset( $value[$v] ) ) {
531 // As a special case don't set 'foo' if a
532 // separate 'foo' => true/false exists in the array
533 // keys should be authoritative
534 $newValue[] = $v;
535 }
536 } elseif ( $v ) {
537 // If the value is truthy but not a string this is likely
538 // an array( 'foo' => true ), falsy values don't add strings
539 $newValue[] = $k;
540 }
541 }
542 $value = implode( ' ', $newValue );
543 }
544 $value = explode( ' ', $value );
545
546 // Normalize spacing by fixing up cases where people used
547 // more than 1 space and/or a trailing/leading space
548 $value = array_diff( $value, [ '', ' ' ] );
549
550 // Remove duplicates and create the string
551 $value = implode( ' ', array_unique( $value ) );
552 } elseif ( is_array( $value ) ) {
553 throw new MWException( "HTML attribute $key can not contain a list of values" );
554 }
555
556 $quote = '"';
557
558 if ( in_array( $key, self::$boolAttribs ) ) {
559 $ret .= " $key=\"\"";
560 } else {
561 // Apparently we need to entity-encode \n, \r, \t, although the
562 // spec doesn't mention that. Since we're doing strtr() anyway,
563 // we may as well not call htmlspecialchars().
564 // @todo FIXME: Verify that we actually need to
565 // escape \n\r\t here, and explain why, exactly.
566 // We could call Sanitizer::encodeAttribute() for this, but we
567 // don't because we're stubborn and like our marginal savings on
568 // byte size from not having to encode unnecessary quotes.
569 // The only difference between this transform and the one by
570 // Sanitizer::encodeAttribute() is ' is not encoded.
571 $map = [
572 '&' => '&amp;',
573 '"' => '&quot;',
574 '>' => '&gt;',
575 // '<' allegedly allowed per spec
576 // but breaks some tools if not escaped.
577 "<" => '&lt;',
578 "\n" => '&#10;',
579 "\r" => '&#13;',
580 "\t" => '&#9;'
581 ];
582 $ret .= " $key=$quote" . strtr( $value, $map ) . $quote;
583 }
584 }
585 return $ret;
586 }
587
588 /**
589 * Output a "<script>" tag with the given contents.
590 *
591 * @todo do some useful escaping as well, like if $contents contains
592 * literal "</script>" or (for XML) literal "]]>".
593 *
594 * @param string $contents JavaScript
595 * @return string Raw HTML
596 */
597 public static function inlineScript( $contents ) {
598 $attrs = [];
599
600 if ( preg_match( '/[<&]/', $contents ) ) {
601 $contents = "/*<![CDATA[*/$contents/*]]>*/";
602 }
603
604 return self::rawElement( 'script', $attrs, $contents );
605 }
606
607 /**
608 * Output a "<script>" tag linking to the given URL, e.g.,
609 * "<script src=foo.js></script>".
610 *
611 * @param string $url
612 * @return string Raw HTML
613 */
614 public static function linkedScript( $url ) {
615 $attrs = [ 'src' => $url ];
616
617 return self::element( 'script', $attrs );
618 }
619
620 /**
621 * Output a "<style>" tag with the given contents for the given media type
622 * (if any). TODO: do some useful escaping as well, like if $contents
623 * contains literal "</style>" (admittedly unlikely).
624 *
625 * @param string $contents CSS
626 * @param string $media A media type string, like 'screen'
627 * @return string Raw HTML
628 */
629 public static function inlineStyle( $contents, $media = 'all' ) {
630 if ( preg_match( '/[<&]/', $contents ) ) {
631 $contents = "/*<![CDATA[*/$contents/*]]>*/";
632 }
633
634 return self::rawElement( 'style', [
635 'media' => $media,
636 ], $contents );
637 }
638
639 /**
640 * Output a "<link rel=stylesheet>" linking to the given URL for the given
641 * media type (if any).
642 *
643 * @param string $url
644 * @param string $media A media type string, like 'screen'
645 * @return string Raw HTML
646 */
647 public static function linkedStyle( $url, $media = 'all' ) {
648 return self::element( 'link', [
649 'rel' => 'stylesheet',
650 'href' => $url,
651 'media' => $media,
652 ] );
653 }
654
655 /**
656 * Convenience function to produce an "<input>" element. This supports the
657 * new HTML5 input types and attributes.
658 *
659 * @param string $name Name attribute
660 * @param string $value Value attribute
661 * @param string $type Type attribute
662 * @param array $attribs Associative array of miscellaneous extra
663 * attributes, passed to Html::element()
664 * @return string Raw HTML
665 */
666 public static function input( $name, $value = '', $type = 'text', array $attribs = [] ) {
667 $attribs['type'] = $type;
668 $attribs['value'] = $value;
669 $attribs['name'] = $name;
670 if ( in_array( $type, [ 'text', 'search', 'email', 'password', 'number' ] ) ) {
671 $attribs = self::getTextInputAttributes( $attribs );
672 }
673 if ( in_array( $type, [ 'button', 'reset', 'submit' ] ) ) {
674 $attribs = self::buttonAttributes( $attribs );
675 }
676 return self::element( 'input', $attribs );
677 }
678
679 /**
680 * Convenience function to produce a checkbox (input element with type=checkbox)
681 *
682 * @param string $name Name attribute
683 * @param bool $checked Whether the checkbox is checked or not
684 * @param array $attribs Array of additional attributes
685 * @return string Raw HTML
686 */
687 public static function check( $name, $checked = false, array $attribs = [] ) {
688 if ( isset( $attribs['value'] ) ) {
689 $value = $attribs['value'];
690 unset( $attribs['value'] );
691 } else {
692 $value = 1;
693 }
694
695 if ( $checked ) {
696 $attribs[] = 'checked';
697 }
698
699 return self::input( $name, $value, 'checkbox', $attribs );
700 }
701
702 /**
703 * Convenience function to produce a radio button (input element with type=radio)
704 *
705 * @param string $name Name attribute
706 * @param bool $checked Whether the radio button is checked or not
707 * @param array $attribs Array of additional attributes
708 * @return string Raw HTML
709 */
710 public static function radio( $name, $checked = false, array $attribs = [] ) {
711 if ( isset( $attribs['value'] ) ) {
712 $value = $attribs['value'];
713 unset( $attribs['value'] );
714 } else {
715 $value = 1;
716 }
717
718 if ( $checked ) {
719 $attribs[] = 'checked';
720 }
721
722 return self::input( $name, $value, 'radio', $attribs );
723 }
724
725 /**
726 * Convenience function for generating a label for inputs.
727 *
728 * @param string $label Contents of the label
729 * @param string $id ID of the element being labeled
730 * @param array $attribs Additional attributes
731 * @return string Raw HTML
732 */
733 public static function label( $label, $id, array $attribs = [] ) {
734 $attribs += [
735 'for' => $id
736 ];
737 return self::element( 'label', $attribs, $label );
738 }
739
740 /**
741 * Convenience function to produce an input element with type=hidden
742 *
743 * @param string $name Name attribute
744 * @param string $value Value attribute
745 * @param array $attribs Associative array of miscellaneous extra
746 * attributes, passed to Html::element()
747 * @return string Raw HTML
748 */
749 public static function hidden( $name, $value, array $attribs = [] ) {
750 return self::input( $name, $value, 'hidden', $attribs );
751 }
752
753 /**
754 * Convenience function to produce a <textarea> element.
755 *
756 * This supports leaving out the cols= and rows= which Xml requires and are
757 * required by HTML4/XHTML but not required by HTML5.
758 *
759 * @param string $name Name attribute
760 * @param string $value Value attribute
761 * @param array $attribs Associative array of miscellaneous extra
762 * attributes, passed to Html::element()
763 * @return string Raw HTML
764 */
765 public static function textarea( $name, $value = '', array $attribs = [] ) {
766 $attribs['name'] = $name;
767
768 if ( substr( $value, 0, 1 ) == "\n" ) {
769 // Workaround for bug 12130: browsers eat the initial newline
770 // assuming that it's just for show, but they do keep the later
771 // newlines, which we may want to preserve during editing.
772 // Prepending a single newline
773 $spacedValue = "\n" . $value;
774 } else {
775 $spacedValue = $value;
776 }
777 return self::element( 'textarea', self::getTextInputAttributes( $attribs ), $spacedValue );
778 }
779
780 /**
781 * Helper for Html::namespaceSelector().
782 * @param array $params See Html::namespaceSelector()
783 * @return array
784 */
785 public static function namespaceSelectorOptions( array $params = [] ) {
786 global $wgContLang;
787
788 $options = [];
789
790 if ( !isset( $params['exclude'] ) || !is_array( $params['exclude'] ) ) {
791 $params['exclude'] = [];
792 }
793
794 if ( isset( $params['all'] ) ) {
795 // add an option that would let the user select all namespaces.
796 // Value is provided by user, the name shown is localized for the user.
797 $options[$params['all']] = wfMessage( 'namespacesall' )->text();
798 }
799 // Add all namespaces as options (in the content language)
800 $options += $wgContLang->getFormattedNamespaces();
801
802 $optionsOut = [];
803 // Filter out namespaces below 0 and massage labels
804 foreach ( $options as $nsId => $nsName ) {
805 if ( $nsId < NS_MAIN || in_array( $nsId, $params['exclude'] ) ) {
806 continue;
807 }
808 if ( $nsId === NS_MAIN ) {
809 // For other namespaces use the namespace prefix as label, but for
810 // main we don't use "" but the user message describing it (e.g. "(Main)" or "(Article)")
811 $nsName = wfMessage( 'blanknamespace' )->text();
812 } elseif ( is_int( $nsId ) ) {
813 $nsName = $wgContLang->convertNamespace( $nsId );
814 }
815 $optionsOut[$nsId] = $nsName;
816 }
817
818 return $optionsOut;
819 }
820
821 /**
822 * Build a drop-down box for selecting a namespace
823 *
824 * @param array $params Params to set.
825 * - selected: [optional] Id of namespace which should be pre-selected
826 * - all: [optional] Value of item for "all namespaces". If null or unset,
827 * no "<option>" is generated to select all namespaces.
828 * - label: text for label to add before the field.
829 * - exclude: [optional] Array of namespace ids to exclude.
830 * - disable: [optional] Array of namespace ids for which the option should
831 * be disabled in the selector.
832 * @param array $selectAttribs HTML attributes for the generated select element.
833 * - id: [optional], default: 'namespace'.
834 * - name: [optional], default: 'namespace'.
835 * @return string HTML code to select a namespace.
836 */
837 public static function namespaceSelector( array $params = [],
838 array $selectAttribs = []
839 ) {
840 ksort( $selectAttribs );
841
842 // Is a namespace selected?
843 if ( isset( $params['selected'] ) ) {
844 // If string only contains digits, convert to clean int. Selected could also
845 // be "all" or "" etc. which needs to be left untouched.
846 // PHP is_numeric() has issues with large strings, PHP ctype_digit has other issues
847 // and returns false for already clean ints. Use regex instead..
848 if ( preg_match( '/^\d+$/', $params['selected'] ) ) {
849 $params['selected'] = intval( $params['selected'] );
850 }
851 // else: leaves it untouched for later processing
852 } else {
853 $params['selected'] = '';
854 }
855
856 if ( !isset( $params['disable'] ) || !is_array( $params['disable'] ) ) {
857 $params['disable'] = [];
858 }
859
860 // Associative array between option-values and option-labels
861 $options = self::namespaceSelectorOptions( $params );
862
863 // Convert $options to HTML
864 $optionsHtml = [];
865 foreach ( $options as $nsId => $nsName ) {
866 $optionsHtml[] = self::element(
867 'option', [
868 'disabled' => in_array( $nsId, $params['disable'] ),
869 'value' => $nsId,
870 'selected' => $nsId === $params['selected'],
871 ], $nsName
872 );
873 }
874
875 if ( !array_key_exists( 'id', $selectAttribs ) ) {
876 $selectAttribs['id'] = 'namespace';
877 }
878
879 if ( !array_key_exists( 'name', $selectAttribs ) ) {
880 $selectAttribs['name'] = 'namespace';
881 }
882
883 $ret = '';
884 if ( isset( $params['label'] ) ) {
885 $ret .= self::element(
886 'label', [
887 'for' => isset( $selectAttribs['id'] ) ? $selectAttribs['id'] : null,
888 ], $params['label']
889 ) . '&#160;';
890 }
891
892 // Wrap options in a <select>
893 $ret .= self::openElement( 'select', $selectAttribs )
894 . "\n"
895 . implode( "\n", $optionsHtml )
896 . "\n"
897 . self::closeElement( 'select' );
898
899 return $ret;
900 }
901
902 /**
903 * Constructs the opening html-tag with necessary doctypes depending on
904 * global variables.
905 *
906 * @param array $attribs Associative array of miscellaneous extra
907 * attributes, passed to Html::element() of html tag.
908 * @return string Raw HTML
909 */
910 public static function htmlHeader( array $attribs = [] ) {
911 $ret = '';
912
913 global $wgHtml5Version, $wgMimeType, $wgXhtmlNamespaces;
914
915 $isXHTML = self::isXmlMimeType( $wgMimeType );
916
917 if ( $isXHTML ) { // XHTML5
918 // XML MIME-typed markup should have an xml header.
919 // However a DOCTYPE is not needed.
920 $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?" . ">\n";
921
922 // Add the standard xmlns
923 $attribs['xmlns'] = 'http://www.w3.org/1999/xhtml';
924
925 // And support custom namespaces
926 foreach ( $wgXhtmlNamespaces as $tag => $ns ) {
927 $attribs["xmlns:$tag"] = $ns;
928 }
929 } else { // HTML5
930 // DOCTYPE
931 $ret .= "<!DOCTYPE html>\n";
932 }
933
934 if ( $wgHtml5Version ) {
935 $attribs['version'] = $wgHtml5Version;
936 }
937
938 $ret .= self::openElement( 'html', $attribs );
939
940 return $ret;
941 }
942
943 /**
944 * Determines if the given MIME type is xml.
945 *
946 * @param string $mimetype MIME type
947 * @return bool
948 */
949 public static function isXmlMimeType( $mimetype ) {
950 # http://www.whatwg.org/html/infrastructure.html#xml-mime-type
951 # * text/xml
952 # * application/xml
953 # * Any MIME type with a subtype ending in +xml (this implicitly includes application/xhtml+xml)
954 return (bool)preg_match( '!^(text|application)/xml$|^.+/.+\+xml$!', $mimetype );
955 }
956
957 /**
958 * Get HTML for an info box with an icon.
959 *
960 * @param string $text Wikitext, get this with wfMessage()->plain()
961 * @param string $icon Path to icon file (used as 'src' attribute)
962 * @param string $alt Alternate text for the icon
963 * @param string $class Additional class name to add to the wrapper div
964 *
965 * @return string
966 */
967 static function infoBox( $text, $icon, $alt, $class = '' ) {
968 $s = self::openElement( 'div', [ 'class' => "mw-infobox $class" ] );
969
970 $s .= self::openElement( 'div', [ 'class' => 'mw-infobox-left' ] ) .
971 self::element( 'img',
972 [
973 'src' => $icon,
974 'alt' => $alt,
975 ]
976 ) .
977 self::closeElement( 'div' );
978
979 $s .= self::openElement( 'div', [ 'class' => 'mw-infobox-right' ] ) .
980 $text .
981 self::closeElement( 'div' );
982 $s .= self::element( 'div', [ 'style' => 'clear: left;' ], ' ' );
983
984 $s .= self::closeElement( 'div' );
985
986 $s .= self::element( 'div', [ 'style' => 'clear: left;' ], ' ' );
987
988 return $s;
989 }
990
991 /**
992 * Generate a srcset attribute value.
993 *
994 * Generates a srcset attribute value from an array mapping pixel densities
995 * to URLs. A trailing 'x' in pixel density values is optional.
996 *
997 * @note srcset width and height values are not supported.
998 *
999 * @see http://www.whatwg.org/html/embedded-content-1.html#attr-img-srcset
1000 *
1001 * @par Example:
1002 * @code
1003 * Html::srcSet( array(
1004 * '1x' => 'standard.jpeg',
1005 * '1.5x' => 'large.jpeg',
1006 * '3x' => 'extra-large.jpeg',
1007 * ) );
1008 * // gives 'standard.jpeg 1x, large.jpeg 1.5x, extra-large.jpeg 2x'
1009 * @endcode
1010 *
1011 * @param string[] $urls
1012 * @return string
1013 */
1014 static function srcSet( array $urls ) {
1015 $candidates = [];
1016 foreach ( $urls as $density => $url ) {
1017 // Cast density to float to strip 'x', then back to string to serve
1018 // as array index.
1019 $density = (string)(float)$density;
1020 $candidates[$density] = $url;
1021 }
1022
1023 // Remove duplicates that are the same as a smaller value
1024 ksort( $candidates, SORT_NUMERIC );
1025 $candidates = array_unique( $candidates );
1026
1027 // Append density info to the url
1028 foreach ( $candidates as $density => $url ) {
1029 $candidates[$density] = $url . ' ' . $density . 'x';
1030 }
1031
1032 return implode( ", ", $candidates );
1033 }
1034 }