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