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