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