EditPage: Generate all messages using $this->context so we have titles
[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 // Don't escape '>' since that is used
631 // as direct child selector.
632 // Remember, in css, there is no "x" for hexadecimal escapes, and
633 // the space immediately after an escape sequence is swallowed.
634 $contents = strtr( $contents, [
635 '<' => '\3C ',
636 // CDATA end tag for good measure, but the main security
637 // is from escaping the '<'.
638 ']]>' => '\5D\5D\3E '
639 ] );
640
641 if ( preg_match( '/[<&]/', $contents ) ) {
642 $contents = "/*<![CDATA[*/$contents/*]]>*/";
643 }
644
645 return self::rawElement( 'style', [
646 'media' => $media,
647 ], $contents );
648 }
649
650 /**
651 * Output a "<link rel=stylesheet>" linking to the given URL for the given
652 * media type (if any).
653 *
654 * @param string $url
655 * @param string $media A media type string, like 'screen'
656 * @return string Raw HTML
657 */
658 public static function linkedStyle( $url, $media = 'all' ) {
659 return self::element( 'link', [
660 'rel' => 'stylesheet',
661 'href' => $url,
662 'media' => $media,
663 ] );
664 }
665
666 /**
667 * Convenience function to produce an "<input>" element. This supports the
668 * new HTML5 input types and attributes.
669 *
670 * @param string $name Name attribute
671 * @param string $value Value attribute
672 * @param string $type Type attribute
673 * @param array $attribs Associative array of miscellaneous extra
674 * attributes, passed to Html::element()
675 * @return string Raw HTML
676 */
677 public static function input( $name, $value = '', $type = 'text', array $attribs = [] ) {
678 $attribs['type'] = $type;
679 $attribs['value'] = $value;
680 $attribs['name'] = $name;
681 if ( in_array( $type, [ 'text', 'search', 'email', 'password', 'number' ] ) ) {
682 $attribs = self::getTextInputAttributes( $attribs );
683 }
684 if ( in_array( $type, [ 'button', 'reset', 'submit' ] ) ) {
685 $attribs = self::buttonAttributes( $attribs );
686 }
687 return self::element( 'input', $attribs );
688 }
689
690 /**
691 * Convenience function to produce a checkbox (input element with type=checkbox)
692 *
693 * @param string $name Name attribute
694 * @param bool $checked Whether the checkbox is checked or not
695 * @param array $attribs Array of additional attributes
696 * @return string Raw HTML
697 */
698 public static function check( $name, $checked = false, array $attribs = [] ) {
699 if ( isset( $attribs['value'] ) ) {
700 $value = $attribs['value'];
701 unset( $attribs['value'] );
702 } else {
703 $value = 1;
704 }
705
706 if ( $checked ) {
707 $attribs[] = 'checked';
708 }
709
710 return self::input( $name, $value, 'checkbox', $attribs );
711 }
712
713 /**
714 * Convenience function to produce a radio button (input element with type=radio)
715 *
716 * @param string $name Name attribute
717 * @param bool $checked Whether the radio button is checked or not
718 * @param array $attribs Array of additional attributes
719 * @return string Raw HTML
720 */
721 public static function radio( $name, $checked = false, array $attribs = [] ) {
722 if ( isset( $attribs['value'] ) ) {
723 $value = $attribs['value'];
724 unset( $attribs['value'] );
725 } else {
726 $value = 1;
727 }
728
729 if ( $checked ) {
730 $attribs[] = 'checked';
731 }
732
733 return self::input( $name, $value, 'radio', $attribs );
734 }
735
736 /**
737 * Convenience function for generating a label for inputs.
738 *
739 * @param string $label Contents of the label
740 * @param string $id ID of the element being labeled
741 * @param array $attribs Additional attributes
742 * @return string Raw HTML
743 */
744 public static function label( $label, $id, array $attribs = [] ) {
745 $attribs += [
746 'for' => $id
747 ];
748 return self::element( 'label', $attribs, $label );
749 }
750
751 /**
752 * Convenience function to produce an input element with type=hidden
753 *
754 * @param string $name Name attribute
755 * @param string $value Value attribute
756 * @param array $attribs Associative array of miscellaneous extra
757 * attributes, passed to Html::element()
758 * @return string Raw HTML
759 */
760 public static function hidden( $name, $value, array $attribs = [] ) {
761 return self::input( $name, $value, 'hidden', $attribs );
762 }
763
764 /**
765 * Convenience function to produce a <textarea> element.
766 *
767 * This supports leaving out the cols= and rows= which Xml requires and are
768 * required by HTML4/XHTML but not required by HTML5.
769 *
770 * @param string $name Name attribute
771 * @param string $value Value attribute
772 * @param array $attribs Associative array of miscellaneous extra
773 * attributes, passed to Html::element()
774 * @return string Raw HTML
775 */
776 public static function textarea( $name, $value = '', array $attribs = [] ) {
777 $attribs['name'] = $name;
778
779 if ( substr( $value, 0, 1 ) == "\n" ) {
780 // Workaround for bug 12130: browsers eat the initial newline
781 // assuming that it's just for show, but they do keep the later
782 // newlines, which we may want to preserve during editing.
783 // Prepending a single newline
784 $spacedValue = "\n" . $value;
785 } else {
786 $spacedValue = $value;
787 }
788 return self::element( 'textarea', self::getTextInputAttributes( $attribs ), $spacedValue );
789 }
790
791 /**
792 * Helper for Html::namespaceSelector().
793 * @param array $params See Html::namespaceSelector()
794 * @return array
795 */
796 public static function namespaceSelectorOptions( array $params = [] ) {
797 global $wgContLang;
798
799 $options = [];
800
801 if ( !isset( $params['exclude'] ) || !is_array( $params['exclude'] ) ) {
802 $params['exclude'] = [];
803 }
804
805 if ( isset( $params['all'] ) ) {
806 // add an option that would let the user select all namespaces.
807 // Value is provided by user, the name shown is localized for the user.
808 $options[$params['all']] = wfMessage( 'namespacesall' )->text();
809 }
810 // Add all namespaces as options (in the content language)
811 $options += $wgContLang->getFormattedNamespaces();
812
813 $optionsOut = [];
814 // Filter out namespaces below 0 and massage labels
815 foreach ( $options as $nsId => $nsName ) {
816 if ( $nsId < NS_MAIN || in_array( $nsId, $params['exclude'] ) ) {
817 continue;
818 }
819 if ( $nsId === NS_MAIN ) {
820 // For other namespaces use the namespace prefix as label, but for
821 // main we don't use "" but the user message describing it (e.g. "(Main)" or "(Article)")
822 $nsName = wfMessage( 'blanknamespace' )->text();
823 } elseif ( is_int( $nsId ) ) {
824 $nsName = $wgContLang->convertNamespace( $nsId );
825 }
826 $optionsOut[$nsId] = $nsName;
827 }
828
829 return $optionsOut;
830 }
831
832 /**
833 * Build a drop-down box for selecting a namespace
834 *
835 * @param array $params Params to set.
836 * - selected: [optional] Id of namespace which should be pre-selected
837 * - all: [optional] Value of item for "all namespaces". If null or unset,
838 * no "<option>" is generated to select all namespaces.
839 * - label: text for label to add before the field.
840 * - exclude: [optional] Array of namespace ids to exclude.
841 * - disable: [optional] Array of namespace ids for which the option should
842 * be disabled in the selector.
843 * @param array $selectAttribs HTML attributes for the generated select element.
844 * - id: [optional], default: 'namespace'.
845 * - name: [optional], default: 'namespace'.
846 * @return string HTML code to select a namespace.
847 */
848 public static function namespaceSelector( array $params = [],
849 array $selectAttribs = []
850 ) {
851 ksort( $selectAttribs );
852
853 // Is a namespace selected?
854 if ( isset( $params['selected'] ) ) {
855 // If string only contains digits, convert to clean int. Selected could also
856 // be "all" or "" etc. which needs to be left untouched.
857 // PHP is_numeric() has issues with large strings, PHP ctype_digit has other issues
858 // and returns false for already clean ints. Use regex instead..
859 if ( preg_match( '/^\d+$/', $params['selected'] ) ) {
860 $params['selected'] = intval( $params['selected'] );
861 }
862 // else: leaves it untouched for later processing
863 } else {
864 $params['selected'] = '';
865 }
866
867 if ( !isset( $params['disable'] ) || !is_array( $params['disable'] ) ) {
868 $params['disable'] = [];
869 }
870
871 // Associative array between option-values and option-labels
872 $options = self::namespaceSelectorOptions( $params );
873
874 // Convert $options to HTML
875 $optionsHtml = [];
876 foreach ( $options as $nsId => $nsName ) {
877 $optionsHtml[] = self::element(
878 'option', [
879 'disabled' => in_array( $nsId, $params['disable'] ),
880 'value' => $nsId,
881 'selected' => $nsId === $params['selected'],
882 ], $nsName
883 );
884 }
885
886 if ( !array_key_exists( 'id', $selectAttribs ) ) {
887 $selectAttribs['id'] = 'namespace';
888 }
889
890 if ( !array_key_exists( 'name', $selectAttribs ) ) {
891 $selectAttribs['name'] = 'namespace';
892 }
893
894 $ret = '';
895 if ( isset( $params['label'] ) ) {
896 $ret .= self::element(
897 'label', [
898 'for' => isset( $selectAttribs['id'] ) ? $selectAttribs['id'] : null,
899 ], $params['label']
900 ) . '&#160;';
901 }
902
903 // Wrap options in a <select>
904 $ret .= self::openElement( 'select', $selectAttribs )
905 . "\n"
906 . implode( "\n", $optionsHtml )
907 . "\n"
908 . self::closeElement( 'select' );
909
910 return $ret;
911 }
912
913 /**
914 * Constructs the opening html-tag with necessary doctypes depending on
915 * global variables.
916 *
917 * @param array $attribs Associative array of miscellaneous extra
918 * attributes, passed to Html::element() of html tag.
919 * @return string Raw HTML
920 */
921 public static function htmlHeader( array $attribs = [] ) {
922 $ret = '';
923
924 global $wgHtml5Version, $wgMimeType, $wgXhtmlNamespaces;
925
926 $isXHTML = self::isXmlMimeType( $wgMimeType );
927
928 if ( $isXHTML ) { // XHTML5
929 // XML MIME-typed markup should have an xml header.
930 // However a DOCTYPE is not needed.
931 $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?" . ">\n";
932
933 // Add the standard xmlns
934 $attribs['xmlns'] = 'http://www.w3.org/1999/xhtml';
935
936 // And support custom namespaces
937 foreach ( $wgXhtmlNamespaces as $tag => $ns ) {
938 $attribs["xmlns:$tag"] = $ns;
939 }
940 } else { // HTML5
941 // DOCTYPE
942 $ret .= "<!DOCTYPE html>\n";
943 }
944
945 if ( $wgHtml5Version ) {
946 $attribs['version'] = $wgHtml5Version;
947 }
948
949 $ret .= self::openElement( 'html', $attribs );
950
951 return $ret;
952 }
953
954 /**
955 * Determines if the given MIME type is xml.
956 *
957 * @param string $mimetype MIME type
958 * @return bool
959 */
960 public static function isXmlMimeType( $mimetype ) {
961 # http://www.whatwg.org/html/infrastructure.html#xml-mime-type
962 # * text/xml
963 # * application/xml
964 # * Any MIME type with a subtype ending in +xml (this implicitly includes application/xhtml+xml)
965 return (bool)preg_match( '!^(text|application)/xml$|^.+/.+\+xml$!', $mimetype );
966 }
967
968 /**
969 * Get HTML for an info box with an icon.
970 *
971 * @param string $text Wikitext, get this with wfMessage()->plain()
972 * @param string $icon Path to icon file (used as 'src' attribute)
973 * @param string $alt Alternate text for the icon
974 * @param string $class Additional class name to add to the wrapper div
975 *
976 * @return string
977 */
978 static function infoBox( $text, $icon, $alt, $class = '' ) {
979 $s = self::openElement( 'div', [ 'class' => "mw-infobox $class" ] );
980
981 $s .= self::openElement( 'div', [ 'class' => 'mw-infobox-left' ] ) .
982 self::element( 'img',
983 [
984 'src' => $icon,
985 'alt' => $alt,
986 ]
987 ) .
988 self::closeElement( 'div' );
989
990 $s .= self::openElement( 'div', [ 'class' => 'mw-infobox-right' ] ) .
991 $text .
992 self::closeElement( 'div' );
993 $s .= self::element( 'div', [ 'style' => 'clear: left;' ], ' ' );
994
995 $s .= self::closeElement( 'div' );
996
997 $s .= self::element( 'div', [ 'style' => 'clear: left;' ], ' ' );
998
999 return $s;
1000 }
1001
1002 /**
1003 * Generate a srcset attribute value.
1004 *
1005 * Generates a srcset attribute value from an array mapping pixel densities
1006 * to URLs. A trailing 'x' in pixel density values is optional.
1007 *
1008 * @note srcset width and height values are not supported.
1009 *
1010 * @see http://www.whatwg.org/html/embedded-content-1.html#attr-img-srcset
1011 *
1012 * @par Example:
1013 * @code
1014 * Html::srcSet( array(
1015 * '1x' => 'standard.jpeg',
1016 * '1.5x' => 'large.jpeg',
1017 * '3x' => 'extra-large.jpeg',
1018 * ) );
1019 * // gives 'standard.jpeg 1x, large.jpeg 1.5x, extra-large.jpeg 2x'
1020 * @endcode
1021 *
1022 * @param string[] $urls
1023 * @return string
1024 */
1025 static function srcSet( array $urls ) {
1026 $candidates = [];
1027 foreach ( $urls as $density => $url ) {
1028 // Cast density to float to strip 'x', then back to string to serve
1029 // as array index.
1030 $density = (string)(float)$density;
1031 $candidates[$density] = $url;
1032 }
1033
1034 // Remove duplicates that are the same as a smaller value
1035 ksort( $candidates, SORT_NUMERIC );
1036 $candidates = array_unique( $candidates );
1037
1038 // Append density info to the url
1039 foreach ( $candidates as $density => $url ) {
1040 $candidates[$density] = $url . ' ' . $density . 'x';
1041 }
1042
1043 return implode( ", ", $candidates );
1044 }
1045 }