Fixed Style/StringLiterals RuboCop offense
[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 * $wgWellFormedXml: If this is set to true, then all output should be
42 * well-formed XML (quotes on attributes, self-closing tags, etc.).
43 *
44 * This class is meant to be confined to utility functions that are called from
45 * trusted code paths. It does not do enforcement of policy like not allowing
46 * <a> elements.
47 *
48 * @since 1.16
49 */
50 class Html {
51 // List of void elements from HTML5, section 8.1.2 as of 2011-08-12
52 private static $voidElements = array(
53 'area',
54 'base',
55 'br',
56 'col',
57 'command',
58 'embed',
59 'hr',
60 'img',
61 'input',
62 'keygen',
63 'link',
64 'meta',
65 'param',
66 'source',
67 'track',
68 'wbr',
69 );
70
71 // Boolean attributes, which may have the value omitted entirely. Manually
72 // collected from the HTML5 spec as of 2011-08-12.
73 private static $boolAttribs = array(
74 'async',
75 'autofocus',
76 'autoplay',
77 'checked',
78 'controls',
79 'default',
80 'defer',
81 'disabled',
82 'formnovalidate',
83 'hidden',
84 'ismap',
85 'itemscope',
86 'loop',
87 'multiple',
88 'muted',
89 'novalidate',
90 'open',
91 'pubdate',
92 'readonly',
93 'required',
94 'reversed',
95 'scoped',
96 'seamless',
97 'selected',
98 'truespeed',
99 'typemustmatch',
100 // HTML5 Microdata
101 'itemscope',
102 );
103
104 /**
105 * Modifies a set of attributes meant for button elements
106 * and apply a set of default attributes when $wgUseMediaWikiUIEverywhere enabled.
107 * @param array $modifiers to add to the button
108 * @see https://tools.wmflabs.org/styleguide/desktop/index.html for guidance on available modifiers
109 * @return array $attrs A modified attribute array
110 */
111 public static function buttonAttributes( $attrs, $modifiers = array() ) {
112 global $wgUseMediaWikiUIEverywhere;
113 if ( $wgUseMediaWikiUIEverywhere ) {
114 if ( isset( $attrs['class'] ) ) {
115 if ( is_array( $attrs['class'] ) ) {
116 $attrs['class'][] = 'mw-ui-button';
117 $attrs = array_merge( $attrs, $modifiers );
118 // ensure compatibility with Xml
119 $attrs['class'] = implode( ' ', $attrs['class'] );
120 } else {
121 $attrs['class'] .= ' mw-ui-button ' . implode( ' ', $modifiers );
122 }
123 } else {
124 $attrs['class'] = array( 'mw-ui-button' );
125 // ensure compatibility with Xml
126 $attrs['class'] = implode( ' ', array_merge( $attrs['class'], $modifiers ) );
127 }
128 }
129 return $attrs;
130 }
131
132 /**
133 * Modifies a set of attributes meant for text input elements
134 * and apply a set of default attributes.
135 * Removes size attribute when $wgUseMediaWikiUIEverywhere enabled.
136 * @param array $attrs An attribute array.
137 * @return array $attrs A modified attribute array
138 */
139 public static function getTextInputAttributes( $attrs ) {
140 global $wgUseMediaWikiUIEverywhere;
141 if ( !$attrs ) {
142 $attrs = array();
143 }
144 if ( $wgUseMediaWikiUIEverywhere ) {
145 if ( isset( $attrs['class'] ) ) {
146 if ( is_array( $attrs['class'] ) ) {
147 $attrs['class'][] = 'mw-ui-input';
148 } else {
149 $attrs['class'] .= ' mw-ui-input';
150 }
151 } else {
152 $attrs['class'] = 'mw-ui-input';
153 }
154
155 // Note that size can effect the desired width rendering of mw-ui-input elements
156 // so it is removed. Left intact when mediawiki ui not enabled.
157 unset( $attrs['size'] );
158 }
159 return $attrs;
160 }
161
162 /**
163 * Returns an HTML link element in a string styled as a button
164 * (when $wgUseMediaWikiUIEverywhere is enabled).
165 *
166 * @param string $contents The raw HTML contents of the element: *not*
167 * escaped!
168 * @param array $attrs Associative array of attributes, e.g., array(
169 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
170 * further documentation.
171 * @param array $modifiers to add to the button
172 * @see http://tools.wmflabs.org/styleguide/desktop/index.html for guidance on available modifiers
173 * @return string Raw HTML
174 */
175 public static function linkButton( $contents, $attrs, $modifiers = array() ) {
176 return Html::element( 'a',
177 self::buttonAttributes( $attrs, $modifiers ),
178 $contents
179 );
180 }
181
182 /**
183 * Returns an HTML link element in a string styled as a button
184 * (when $wgUseMediaWikiUIEverywhere is enabled).
185 *
186 * @param string $contents The raw HTML contents of the element: *not*
187 * escaped!
188 * @param array $attrs Associative array of attributes, e.g., array(
189 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
190 * further documentation.
191 * @param array $modifiers to add to the button
192 * @see http://tools.wmflabs.org/styleguide/desktop/index.html for guidance on available modifiers
193 * @return string Raw HTML
194 */
195 public static function submitButton( $contents, $attrs, $modifiers = array() ) {
196 $attrs['type'] = 'submit';
197 $attrs['value'] = $contents;
198 return Html::element( 'input', self::buttonAttributes( $attrs, $modifiers ) );
199 }
200
201 /**
202 * Returns an HTML element in a string. The major advantage here over
203 * manually typing out the HTML is that it will escape all attribute
204 * values.
205 *
206 * This is quite similar to Xml::tags(), but it implements some useful
207 * HTML-specific logic. For instance, there is no $allowShortTag
208 * parameter: the closing tag is magically omitted if $element has an empty
209 * content model. If $wgWellFormedXml is false, then a few bytes will be
210 * shaved off the HTML output as well.
211 *
212 * @param string $element The element's name, e.g., 'a'
213 * @param array $attribs Associative array of attributes, e.g., array(
214 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
215 * further documentation.
216 * @param string $contents The raw HTML contents of the element: *not*
217 * escaped!
218 * @return string Raw HTML
219 */
220 public static function rawElement( $element, $attribs = array(), $contents = '' ) {
221 global $wgWellFormedXml;
222 $start = self::openElement( $element, $attribs );
223 if ( in_array( $element, self::$voidElements ) ) {
224 if ( $wgWellFormedXml ) {
225 // Silly XML.
226 return substr( $start, 0, -1 ) . ' />';
227 }
228 return $start;
229 } else {
230 return "$start$contents" . self::closeElement( $element );
231 }
232 }
233
234 /**
235 * Identical to rawElement(), but HTML-escapes $contents (like
236 * Xml::element()).
237 *
238 * @param string $element
239 * @param array $attribs
240 * @param string $contents
241 *
242 * @return string
243 */
244 public static function element( $element, $attribs = array(), $contents = '' ) {
245 return self::rawElement( $element, $attribs, strtr( $contents, array(
246 // There's no point in escaping quotes, >, etc. in the contents of
247 // elements.
248 '&' => '&amp;',
249 '<' => '&lt;'
250 ) ) );
251 }
252
253 /**
254 * Identical to rawElement(), but has no third parameter and omits the end
255 * tag (and the self-closing '/' in XML mode for empty elements).
256 *
257 * @param string $element
258 * @param array $attribs
259 *
260 * @return string
261 */
262 public static function openElement( $element, $attribs = array() ) {
263 $attribs = (array)$attribs;
264 // This is not required in HTML5, but let's do it anyway, for
265 // consistency and better compression.
266 $element = strtolower( $element );
267
268 // Remove invalid input types
269 if ( $element == 'input' ) {
270 $validTypes = array(
271 'hidden',
272 'text',
273 'password',
274 'checkbox',
275 'radio',
276 'file',
277 'submit',
278 'image',
279 'reset',
280 'button',
281
282 // HTML input types
283 'datetime',
284 'datetime-local',
285 'date',
286 'month',
287 'time',
288 'week',
289 'number',
290 'range',
291 'email',
292 'url',
293 'search',
294 'tel',
295 'color',
296 );
297 if ( isset( $attribs['type'] ) && !in_array( $attribs['type'], $validTypes ) ) {
298 unset( $attribs['type'] );
299 }
300 }
301
302 // According to standard the default type for <button> elements is "submit".
303 // Depending on compatibility mode IE might use "button", instead.
304 // We enforce the standard "submit".
305 if ( $element == 'button' && !isset( $attribs['type'] ) ) {
306 $attribs['type'] = 'submit';
307 }
308
309 return "<$element" . self::expandAttributes(
310 self::dropDefaults( $element, $attribs ) ) . '>';
311 }
312
313 /**
314 * Returns "</$element>"
315 *
316 * @since 1.17
317 * @param string $element Name of the element, e.g., 'a'
318 * @return string A closing tag
319 */
320 public static function closeElement( $element ) {
321 $element = strtolower( $element );
322
323 return "</$element>";
324 }
325
326 /**
327 * Given an element name and an associative array of element attributes,
328 * return an array that is functionally identical to the input array, but
329 * possibly smaller. In particular, attributes might be stripped if they
330 * are given their default values.
331 *
332 * This method is not guaranteed to remove all redundant attributes, only
333 * some common ones and some others selected arbitrarily at random. It
334 * only guarantees that the output array should be functionally identical
335 * to the input array (currently per the HTML 5 draft as of 2009-09-06).
336 *
337 * @param string $element Name of the element, e.g., 'a'
338 * @param array $attribs Associative array of attributes, e.g., array(
339 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
340 * further documentation.
341 * @return array An array of attributes functionally identical to $attribs
342 */
343 private static function dropDefaults( $element, $attribs ) {
344
345 // Whenever altering this array, please provide a covering test case
346 // in HtmlTest::provideElementsWithAttributesHavingDefaultValues
347 static $attribDefaults = array(
348 'area' => array( 'shape' => 'rect' ),
349 'button' => array(
350 'formaction' => 'GET',
351 'formenctype' => 'application/x-www-form-urlencoded',
352 ),
353 'canvas' => array(
354 'height' => '150',
355 'width' => '300',
356 ),
357 'command' => array( 'type' => 'command' ),
358 'form' => array(
359 'action' => 'GET',
360 'autocomplete' => 'on',
361 'enctype' => 'application/x-www-form-urlencoded',
362 ),
363 'input' => array(
364 'formaction' => 'GET',
365 'type' => 'text',
366 ),
367 'keygen' => array( 'keytype' => 'rsa' ),
368 'link' => array( 'media' => 'all' ),
369 'menu' => array( 'type' => 'list' ),
370 // Note: the use of text/javascript here instead of other JavaScript
371 // MIME types follows the HTML5 spec.
372 'script' => array( 'type' => 'text/javascript' ),
373 'style' => array(
374 'media' => 'all',
375 'type' => 'text/css',
376 ),
377 'textarea' => array( 'wrap' => 'soft' ),
378 );
379
380 $element = strtolower( $element );
381
382 foreach ( $attribs as $attrib => $value ) {
383 $lcattrib = strtolower( $attrib );
384 if ( is_array( $value ) ) {
385 $value = implode( ' ', $value );
386 } else {
387 $value = strval( $value );
388 }
389
390 // Simple checks using $attribDefaults
391 if ( isset( $attribDefaults[$element][$lcattrib] )
392 && $attribDefaults[$element][$lcattrib] == $value
393 ) {
394 unset( $attribs[$attrib] );
395 }
396
397 if ( $lcattrib == 'class' && $value == '' ) {
398 unset( $attribs[$attrib] );
399 }
400 }
401
402 // More subtle checks
403 if ( $element === 'link'
404 && isset( $attribs['type'] ) && strval( $attribs['type'] ) == 'text/css'
405 ) {
406 unset( $attribs['type'] );
407 }
408 if ( $element === 'input' ) {
409 $type = isset( $attribs['type'] ) ? $attribs['type'] : null;
410 $value = isset( $attribs['value'] ) ? $attribs['value'] : null;
411 if ( $type === 'checkbox' || $type === 'radio' ) {
412 // The default value for checkboxes and radio buttons is 'on'
413 // not ''. By stripping value="" we break radio boxes that
414 // actually wants empty values.
415 if ( $value === 'on' ) {
416 unset( $attribs['value'] );
417 }
418 } elseif ( $type === 'submit' ) {
419 // The default value for submit appears to be "Submit" but
420 // let's not bother stripping out localized text that matches
421 // that.
422 } else {
423 // The default value for nearly every other field type is ''
424 // The 'range' and 'color' types use different defaults but
425 // stripping a value="" does not hurt them.
426 if ( $value === '' ) {
427 unset( $attribs['value'] );
428 }
429 }
430 }
431 if ( $element === 'select' && isset( $attribs['size'] ) ) {
432 if ( in_array( 'multiple', $attribs )
433 || ( isset( $attribs['multiple'] ) && $attribs['multiple'] !== false )
434 ) {
435 // A multi-select
436 if ( strval( $attribs['size'] ) == '4' ) {
437 unset( $attribs['size'] );
438 }
439 } else {
440 // Single select
441 if ( strval( $attribs['size'] ) == '1' ) {
442 unset( $attribs['size'] );
443 }
444 }
445 }
446
447 return $attribs;
448 }
449
450 /**
451 * Given an associative array of element attributes, generate a string
452 * to stick after the element name in HTML output. Like array( 'href' =>
453 * 'http://www.mediawiki.org/' ) becomes something like
454 * ' href="http://www.mediawiki.org"'. Again, this is like
455 * Xml::expandAttributes(), but it implements some HTML-specific logic.
456 * For instance, it will omit quotation marks if $wgWellFormedXml is false,
457 * and will treat boolean attributes specially.
458 *
459 * Attributes that can contain space-separated lists ('class', 'accesskey' and 'rel') array
460 * values are allowed as well, which will automagically be normalized
461 * and converted to a space-separated string. In addition to a numerical
462 * array, the attribute value may also be an associative array. See the
463 * example below for how that works.
464 *
465 * @par Numerical array
466 * @code
467 * Html::element( 'em', array(
468 * 'class' => array( 'foo', 'bar' )
469 * ) );
470 * // gives '<em class="foo bar"></em>'
471 * @endcode
472 *
473 * @par Associative array
474 * @code
475 * Html::element( 'em', array(
476 * 'class' => array( 'foo', 'bar', 'foo' => false, 'quux' => true )
477 * ) );
478 * // gives '<em class="bar quux"></em>'
479 * @endcode
480 *
481 * @param array $attribs Associative array of attributes, e.g., array(
482 * 'href' => 'http://www.mediawiki.org/' ). Values will be HTML-escaped.
483 * A value of false means to omit the attribute. For boolean attributes,
484 * you can omit the key, e.g., array( 'checked' ) instead of
485 * array( 'checked' => 'checked' ) or such.
486 *
487 * @throws MWException If an attribute that doesn't allow lists is set to an array
488 * @return string HTML fragment that goes between element name and '>'
489 * (starting with a space if at least one attribute is output)
490 */
491 public static function expandAttributes( $attribs ) {
492 global $wgWellFormedXml;
493
494 $ret = '';
495 $attribs = (array)$attribs;
496 foreach ( $attribs as $key => $value ) {
497 // Support intuitive array( 'checked' => true/false ) form
498 if ( $value === false || is_null( $value ) ) {
499 continue;
500 }
501
502 // For boolean attributes, support array( 'foo' ) instead of
503 // requiring array( 'foo' => 'meaningless' ).
504 if ( is_int( $key ) && in_array( strtolower( $value ), self::$boolAttribs ) ) {
505 $key = $value;
506 }
507
508 // Not technically required in HTML5 but we'd like consistency
509 // and better compression anyway.
510 $key = strtolower( $key );
511
512 // Bug 23769: Blacklist all form validation attributes for now. Current
513 // (June 2010) WebKit has no UI, so the form just refuses to submit
514 // without telling the user why, which is much worse than failing
515 // server-side validation. Opera is the only other implementation at
516 // this time, and has ugly UI, so just kill the feature entirely until
517 // we have at least one good implementation.
518
519 // As the default value of "1" for "step" rejects decimal
520 // numbers to be entered in 'type="number"' fields, allow
521 // the special case 'step="any"'.
522
523 if ( in_array( $key, array( 'max', 'min', 'pattern', 'required' ) )
524 || $key === 'step' && $value !== 'any' ) {
525 continue;
526 }
527
528 // http://www.w3.org/TR/html401/index/attributes.html ("space-separated")
529 // http://www.w3.org/TR/html5/index.html#attributes-1 ("space-separated")
530 $spaceSeparatedListAttributes = array(
531 'class', // html4, html5
532 'accesskey', // as of html5, multiple space-separated values allowed
533 // html4-spec doesn't document rel= as space-separated
534 // but has been used like that and is now documented as such
535 // in the html5-spec.
536 'rel',
537 );
538
539 // Specific features for attributes that allow a list of space-separated values
540 if ( in_array( $key, $spaceSeparatedListAttributes ) ) {
541 // Apply some normalization and remove duplicates
542
543 // Convert into correct array. Array can contain space-separated
544 // values. Implode/explode to get those into the main array as well.
545 if ( is_array( $value ) ) {
546 // If input wasn't an array, we can skip this step
547 $newValue = array();
548 foreach ( $value as $k => $v ) {
549 if ( is_string( $v ) ) {
550 // String values should be normal `array( 'foo' )`
551 // Just append them
552 if ( !isset( $value[$v] ) ) {
553 // As a special case don't set 'foo' if a
554 // separate 'foo' => true/false exists in the array
555 // keys should be authoritative
556 $newValue[] = $v;
557 }
558 } elseif ( $v ) {
559 // If the value is truthy but not a string this is likely
560 // an array( 'foo' => true ), falsy values don't add strings
561 $newValue[] = $k;
562 }
563 }
564 $value = implode( ' ', $newValue );
565 }
566 $value = explode( ' ', $value );
567
568 // Normalize spacing by fixing up cases where people used
569 // more than 1 space and/or a trailing/leading space
570 $value = array_diff( $value, array( '', ' ' ) );
571
572 // Remove duplicates and create the string
573 $value = implode( ' ', array_unique( $value ) );
574 } elseif ( is_array( $value ) ) {
575 throw new MWException( "HTML attribute $key can not contain a list of values" );
576 }
577
578 // See the "Attributes" section in the HTML syntax part of HTML5,
579 // 9.1.2.3 as of 2009-08-10. Most attributes can have quotation
580 // marks omitted, but not all. (Although a literal " is not
581 // permitted, we don't check for that, since it will be escaped
582 // anyway.)
583
584 // See also research done on further characters that need to be
585 // escaped: http://code.google.com/p/html5lib/issues/detail?id=93
586 $badChars = "\\x00- '=<>`/\x{00a0}\x{1680}\x{180e}\x{180F}\x{2000}\x{2001}"
587 . "\x{2002}\x{2003}\x{2004}\x{2005}\x{2006}\x{2007}\x{2008}\x{2009}"
588 . "\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}";
589 if ( $wgWellFormedXml || $value === '' || preg_match( "![$badChars]!u", $value ) ) {
590 $quote = '"';
591 } else {
592 $quote = '';
593 }
594
595 if ( in_array( $key, self::$boolAttribs ) ) {
596 // In HTML5, we can leave the value empty. If we don't need
597 // well-formed XML, we can omit the = entirely.
598 if ( !$wgWellFormedXml ) {
599 $ret .= " $key";
600 } else {
601 $ret .= " $key=\"\"";
602 }
603 } else {
604 // Apparently we need to entity-encode \n, \r, \t, although the
605 // spec doesn't mention that. Since we're doing strtr() anyway,
606 // and we don't need <> escaped here, we may as well not call
607 // htmlspecialchars().
608 // @todo FIXME: Verify that we actually need to
609 // escape \n\r\t here, and explain why, exactly.
610 #
611 // We could call Sanitizer::encodeAttribute() for this, but we
612 // don't because we're stubborn and like our marginal savings on
613 // byte size from not having to encode unnecessary quotes.
614 $map = array(
615 '&' => '&amp;',
616 '"' => '&quot;',
617 "\n" => '&#10;',
618 "\r" => '&#13;',
619 "\t" => '&#9;'
620 );
621 if ( $wgWellFormedXml ) {
622 // This is allowed per spec: <http://www.w3.org/TR/xml/#NT-AttValue>
623 // But reportedly it breaks some XML tools?
624 // @todo FIXME: Is this really true?
625 $map['<'] = '&lt;';
626 }
627 $ret .= " $key=$quote" . strtr( $value, $map ) . $quote;
628 }
629 }
630 return $ret;
631 }
632
633 /**
634 * Output a "<script>" tag with the given contents.
635 *
636 * @todo do some useful escaping as well, like if $contents contains
637 * literal "</script>" or (for XML) literal "]]>".
638 *
639 * @param string $contents JavaScript
640 * @return string Raw HTML
641 */
642 public static function inlineScript( $contents ) {
643 global $wgWellFormedXml;
644
645 $attrs = array();
646
647 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
648 $contents = "/*<![CDATA[*/$contents/*]]>*/";
649 }
650
651 return self::rawElement( 'script', $attrs, $contents );
652 }
653
654 /**
655 * Output a "<script>" tag linking to the given URL, e.g.,
656 * "<script src=foo.js></script>".
657 *
658 * @param string $url
659 * @return string Raw HTML
660 */
661 public static function linkedScript( $url ) {
662 $attrs = array( 'src' => $url );
663
664 return self::element( 'script', $attrs );
665 }
666
667 /**
668 * Output a "<style>" tag with the given contents for the given media type
669 * (if any). TODO: do some useful escaping as well, like if $contents
670 * contains literal "</style>" (admittedly unlikely).
671 *
672 * @param string $contents CSS
673 * @param string $media A media type string, like 'screen'
674 * @return string Raw HTML
675 */
676 public static function inlineStyle( $contents, $media = 'all' ) {
677 global $wgWellFormedXml;
678
679 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
680 $contents = "/*<![CDATA[*/$contents/*]]>*/";
681 }
682
683 return self::rawElement( 'style', array(
684 'type' => 'text/css',
685 'media' => $media,
686 ), $contents );
687 }
688
689 /**
690 * Output a "<link rel=stylesheet>" linking to the given URL for the given
691 * media type (if any).
692 *
693 * @param string $url
694 * @param string $media A media type string, like 'screen'
695 * @return string Raw HTML
696 */
697 public static function linkedStyle( $url, $media = 'all' ) {
698 return self::element( 'link', array(
699 'rel' => 'stylesheet',
700 'href' => $url,
701 'type' => 'text/css',
702 'media' => $media,
703 ) );
704 }
705
706 /**
707 * Convenience function to produce an "<input>" element. This supports the
708 * new HTML5 input types and attributes.
709 *
710 * @param string $name Name attribute
711 * @param array $value Value attribute
712 * @param string $type Type attribute
713 * @param array $attribs Associative array of miscellaneous extra
714 * attributes, passed to Html::element()
715 * @return string Raw HTML
716 */
717 public static function input( $name, $value = '', $type = 'text', $attribs = array() ) {
718 $attribs['type'] = $type;
719 $attribs['value'] = $value;
720 $attribs['name'] = $name;
721 if ( in_array( $type, array( 'text', 'search', 'email', 'password', 'number' ) ) ) {
722 $attribs = Html::getTextInputAttributes( $attribs );
723 }
724 return self::element( 'input', $attribs );
725 }
726
727 /**
728 * Convenience function to produce a checkbox (input element with type=checkbox)
729 *
730 * @param string $name Name attribute
731 * @param bool $checked Whether the checkbox is checked or not
732 * @param array $attribs Array of additional attributes
733 * @return string
734 */
735 public static function check( $name, $checked = false, array $attribs = array() ) {
736 if ( isset( $attribs['value'] ) ) {
737 $value = $attribs['value'];
738 unset( $attribs['value'] );
739 } else {
740 $value = 1;
741 }
742
743 if ( $checked ) {
744 $attribs[] = 'checked';
745 }
746
747 return self::input( $name, $value, 'checkbox', $attribs );
748 }
749
750 /**
751 * Convenience function to produce a checkbox (input element with type=checkbox)
752 *
753 * @param string $name Name attribute
754 * @param bool $checked Whether the checkbox is checked or not
755 * @param array $attribs Array of additional attributes
756 * @return string
757 */
758 public static function radio( $name, $checked = false, array $attribs = array() ) {
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
780 */
781 public static function label( $label, $id, array $attribs = array() ) {
782 $attribs += array(
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, $attribs = array() ) {
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 = '', $attribs = array() ) {
814 $attribs['name'] = $name;
815
816 if ( substr( $value, 0, 1 ) == "\n" ) {
817 // Workaround for bug 12130: 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', Html::getTextInputAttributes( $attribs ), $spacedValue );
826 }
827
828 /**
829 * Build a drop-down box for selecting a namespace
830 *
831 * @param array $params Params to set.
832 * - selected: [optional] Id of namespace which should be pre-selected
833 * - all: [optional] Value of item for "all namespaces". If null or unset,
834 * no "<option>" is generated to select all namespaces.
835 * - label: text for label to add before the field.
836 * - exclude: [optional] Array of namespace ids to exclude.
837 * - disable: [optional] Array of namespace ids for which the option should
838 * be disabled in the selector.
839 * @param array $selectAttribs HTML attributes for the generated select element.
840 * - id: [optional], default: 'namespace'.
841 * - name: [optional], default: 'namespace'.
842 * @return string HTML code to select a namespace.
843 */
844 public static function namespaceSelector( array $params = array(),
845 array $selectAttribs = array()
846 ) {
847 global $wgContLang;
848
849 ksort( $selectAttribs );
850
851 // Is a namespace selected?
852 if ( isset( $params['selected'] ) ) {
853 // If string only contains digits, convert to clean int. Selected could also
854 // be "all" or "" etc. which needs to be left untouched.
855 // PHP is_numeric() has issues with large strings, PHP ctype_digit has other issues
856 // and returns false for already clean ints. Use regex instead..
857 if ( preg_match( '/^\d+$/', $params['selected'] ) ) {
858 $params['selected'] = intval( $params['selected'] );
859 }
860 // else: leaves it untouched for later processing
861 } else {
862 $params['selected'] = '';
863 }
864
865 if ( !isset( $params['exclude'] ) || !is_array( $params['exclude'] ) ) {
866 $params['exclude'] = array();
867 }
868 if ( !isset( $params['disable'] ) || !is_array( $params['disable'] ) ) {
869 $params['disable'] = array();
870 }
871
872 // Associative array between option-values and option-labels
873 $options = array();
874
875 if ( isset( $params['all'] ) ) {
876 // add an option that would let the user select all namespaces.
877 // Value is provided by user, the name shown is localized for the user.
878 $options[$params['all']] = wfMessage( 'namespacesall' )->text();
879 }
880 // Add all namespaces as options (in the content language)
881 $options += $wgContLang->getFormattedNamespaces();
882
883 // Convert $options to HTML and filter out namespaces below 0
884 $optionsHtml = array();
885 foreach ( $options as $nsId => $nsName ) {
886 if ( $nsId < NS_MAIN || in_array( $nsId, $params['exclude'] ) ) {
887 continue;
888 }
889 if ( $nsId === NS_MAIN ) {
890 // For other namespaces use the namespace prefix as label, but for
891 // main we don't use "" but the user message describing it (e.g. "(Main)" or "(Article)")
892 $nsName = wfMessage( 'blanknamespace' )->text();
893 } elseif ( is_int( $nsId ) ) {
894 $nsName = $wgContLang->convertNamespace( $nsId );
895 }
896 $optionsHtml[] = Html::element(
897 'option', array(
898 'disabled' => in_array( $nsId, $params['disable'] ),
899 'value' => $nsId,
900 'selected' => $nsId === $params['selected'],
901 ), $nsName
902 );
903 }
904
905 if ( !array_key_exists( 'id', $selectAttribs ) ) {
906 $selectAttribs['id'] = 'namespace';
907 }
908
909 if ( !array_key_exists( 'name', $selectAttribs ) ) {
910 $selectAttribs['name'] = 'namespace';
911 }
912
913 $ret = '';
914 if ( isset( $params['label'] ) ) {
915 $ret .= Html::element(
916 'label', array(
917 'for' => isset( $selectAttribs['id'] ) ? $selectAttribs['id'] : null,
918 ), $params['label']
919 ) . '&#160;';
920 }
921
922 // Wrap options in a <select>
923 $ret .= Html::openElement( 'select', $selectAttribs )
924 . "\n"
925 . implode( "\n", $optionsHtml )
926 . "\n"
927 . Html::closeElement( 'select' );
928
929 return $ret;
930 }
931
932 /**
933 * Constructs the opening html-tag with necessary doctypes depending on
934 * global variables.
935 *
936 * @param array $attribs Associative array of miscellaneous extra
937 * attributes, passed to Html::element() of html tag.
938 * @return string Raw HTML
939 */
940 public static function htmlHeader( $attribs = array() ) {
941 $ret = '';
942
943 global $wgHtml5Version, $wgMimeType, $wgXhtmlNamespaces;
944
945 $isXHTML = self::isXmlMimeType( $wgMimeType );
946
947 if ( $isXHTML ) { // XHTML5
948 // XML MIME-typed markup should have an xml header.
949 // However a DOCTYPE is not needed.
950 $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?" . ">\n";
951
952 // Add the standard xmlns
953 $attribs['xmlns'] = 'http://www.w3.org/1999/xhtml';
954
955 // And support custom namespaces
956 foreach ( $wgXhtmlNamespaces as $tag => $ns ) {
957 $attribs["xmlns:$tag"] = $ns;
958 }
959 } else { // HTML5
960 // DOCTYPE
961 $ret .= "<!DOCTYPE html>\n";
962 }
963
964 if ( $wgHtml5Version ) {
965 $attribs['version'] = $wgHtml5Version;
966 }
967
968 $html = Html::openElement( 'html', $attribs );
969
970 if ( $html ) {
971 $html .= "\n";
972 }
973
974 $ret .= $html;
975
976 return $ret;
977 }
978
979 /**
980 * Determines if the given MIME type is xml.
981 *
982 * @param string $mimetype MIME type
983 * @return bool
984 */
985 public static function isXmlMimeType( $mimetype ) {
986 # http://www.whatwg.org/html/infrastructure.html#xml-mime-type
987 # * text/xml
988 # * application/xml
989 # * Any MIME type with a subtype ending in +xml (this implicitly includes application/xhtml+xml)
990 return (bool)preg_match( '!^(text|application)/xml$|^.+/.+\+xml$!', $mimetype );
991 }
992
993 /**
994 * Get HTML for an info box with an icon.
995 *
996 * @param string $text Wikitext, get this with wfMessage()->plain()
997 * @param string $icon Path to icon file (used as 'src' attribute)
998 * @param string $alt Alternate text for the icon
999 * @param string $class Additional class name to add to the wrapper div
1000 *
1001 * @return string
1002 */
1003 static function infoBox( $text, $icon, $alt, $class = false ) {
1004 $s = Html::openElement( 'div', array( 'class' => "mw-infobox $class" ) );
1005
1006 $s .= Html::openElement( 'div', array( 'class' => 'mw-infobox-left' ) ) .
1007 Html::element( 'img',
1008 array(
1009 'src' => $icon,
1010 'alt' => $alt,
1011 )
1012 ) .
1013 Html::closeElement( 'div' );
1014
1015 $s .= Html::openElement( 'div', array( 'class' => 'mw-infobox-right' ) ) .
1016 $text .
1017 Html::closeElement( 'div' );
1018 $s .= Html::element( 'div', array( 'style' => 'clear: left;' ), ' ' );
1019
1020 $s .= Html::closeElement( 'div' );
1021
1022 $s .= Html::element( 'div', array( 'style' => 'clear: left;' ), ' ' );
1023
1024 return $s;
1025 }
1026
1027 /**
1028 * Generate a srcset attribute value from an array mapping pixel densities
1029 * to URLs. Note that srcset supports width and height values as well, which
1030 * are not used here.
1031 *
1032 * @param array $urls
1033 * @return string
1034 */
1035 static function srcSet( $urls ) {
1036 $candidates = array();
1037 foreach ( $urls as $density => $url ) {
1038 // Image candidate syntax per current whatwg live spec, 2012-09-23:
1039 // http://www.whatwg.org/html/embedded-content-1.html#attr-img-srcset
1040 $candidates[] = "{$url} {$density}x";
1041 }
1042 return implode( ", ", $candidates );
1043 }
1044 }