PageRenderTime 55ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/includes/Html.php

https://github.com/spenser-roark/OOUG-Wiki
PHP | 879 lines | 446 code | 84 blank | 349 comment | 82 complexity | 3ee661bfe12c623f72cf6c5f03b779b1 MD5 | raw file
Possible License(s): GPL-2.0, Apache-2.0, LGPL-3.0
  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. * This class is a collection of static functions that serve two purposes:
  27. *
  28. * 1) Implement any algorithms specified by HTML5, or other HTML
  29. * specifications, in a convenient and self-contained way.
  30. *
  31. * 2) Allow HTML elements to be conveniently and safely generated, like the
  32. * current Xml class but a) less confused (Xml supports HTML-specific things,
  33. * but only sometimes!) and b) not necessarily confined to XML-compatible
  34. * output.
  35. *
  36. * There are two important configuration options this class uses:
  37. *
  38. * $wgHtml5: If this is set to false, then all output should be valid XHTML 1.0
  39. * Transitional.
  40. * $wgWellFormedXml: If this is set to true, then all output should be
  41. * well-formed XML (quotes on attributes, self-closing tags, etc.).
  42. *
  43. * This class is meant to be confined to utility functions that are called from
  44. * trusted code paths. It does not do enforcement of policy like not allowing
  45. * <a> elements.
  46. *
  47. * @since 1.16
  48. */
  49. class Html {
  50. # List of void elements from HTML5, section 8.1.2 as of 2011-08-12
  51. private static $voidElements = array(
  52. 'area',
  53. 'base',
  54. 'br',
  55. 'col',
  56. 'command',
  57. 'embed',
  58. 'hr',
  59. 'img',
  60. 'input',
  61. 'keygen',
  62. 'link',
  63. 'meta',
  64. 'param',
  65. 'source',
  66. 'track',
  67. 'wbr',
  68. );
  69. # Boolean attributes, which may have the value omitted entirely. Manually
  70. # collected from the HTML5 spec as of 2011-08-12.
  71. private static $boolAttribs = array(
  72. 'async',
  73. 'autofocus',
  74. 'autoplay',
  75. 'checked',
  76. 'controls',
  77. 'default',
  78. 'defer',
  79. 'disabled',
  80. 'formnovalidate',
  81. 'hidden',
  82. 'ismap',
  83. 'itemscope',
  84. 'loop',
  85. 'multiple',
  86. 'muted',
  87. 'novalidate',
  88. 'open',
  89. 'pubdate',
  90. 'readonly',
  91. 'required',
  92. 'reversed',
  93. 'scoped',
  94. 'seamless',
  95. 'selected',
  96. 'truespeed',
  97. 'typemustmatch',
  98. # HTML5 Microdata
  99. 'itemscope',
  100. );
  101. private static $HTMLFiveOnlyAttribs = array(
  102. 'autocomplete',
  103. 'autofocus',
  104. 'max',
  105. 'min',
  106. 'multiple',
  107. 'pattern',
  108. 'placeholder',
  109. 'required',
  110. 'step',
  111. 'spellcheck',
  112. );
  113. /**
  114. * Returns an HTML element in a string. The major advantage here over
  115. * manually typing out the HTML is that it will escape all attribute
  116. * values. If you're hardcoding all the attributes, or there are none, you
  117. * should probably just type out the html element yourself.
  118. *
  119. * This is quite similar to Xml::tags(), but it implements some useful
  120. * HTML-specific logic. For instance, there is no $allowShortTag
  121. * parameter: the closing tag is magically omitted if $element has an empty
  122. * content model. If $wgWellFormedXml is false, then a few bytes will be
  123. * shaved off the HTML output as well.
  124. *
  125. * @param $element string The element's name, e.g., 'a'
  126. * @param $attribs array Associative array of attributes, e.g., array(
  127. * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
  128. * further documentation.
  129. * @param $contents string The raw HTML contents of the element: *not*
  130. * escaped!
  131. * @return string Raw HTML
  132. */
  133. public static function rawElement( $element, $attribs = array(), $contents = '' ) {
  134. global $wgWellFormedXml;
  135. $start = self::openElement( $element, $attribs );
  136. if ( in_array( $element, self::$voidElements ) ) {
  137. if ( $wgWellFormedXml ) {
  138. # Silly XML.
  139. return substr( $start, 0, -1 ) . ' />';
  140. }
  141. return $start;
  142. } else {
  143. return "$start$contents" . self::closeElement( $element );
  144. }
  145. }
  146. /**
  147. * Identical to rawElement(), but HTML-escapes $contents (like
  148. * Xml::element()).
  149. *
  150. * @param $element string
  151. * @param $attribs array
  152. * @param $contents string
  153. *
  154. * @return string
  155. */
  156. public static function element( $element, $attribs = array(), $contents = '' ) {
  157. return self::rawElement( $element, $attribs, strtr( $contents, array(
  158. # There's no point in escaping quotes, >, etc. in the contents of
  159. # elements.
  160. '&' => '&amp;',
  161. '<' => '&lt;'
  162. ) ) );
  163. }
  164. /**
  165. * Identical to rawElement(), but has no third parameter and omits the end
  166. * tag (and the self-closing '/' in XML mode for empty elements).
  167. *
  168. * @param $element string
  169. * @param $attribs array
  170. *
  171. * @return string
  172. */
  173. public static function openElement( $element, $attribs = array() ) {
  174. global $wgHtml5, $wgWellFormedXml;
  175. $attribs = (array)$attribs;
  176. # This is not required in HTML5, but let's do it anyway, for
  177. # consistency and better compression.
  178. $element = strtolower( $element );
  179. # In text/html, initial <html> and <head> tags can be omitted under
  180. # pretty much any sane circumstances, if they have no attributes. See:
  181. # <http://www.whatwg.org/specs/web-apps/current-work/multipage/syntax.html#optional-tags>
  182. if ( !$wgWellFormedXml && !$attribs
  183. && in_array( $element, array( 'html', 'head' ) ) ) {
  184. return '';
  185. }
  186. # Remove HTML5-only attributes if we aren't doing HTML5, and disable
  187. # form validation regardless (see bug 23769 and the more detailed
  188. # comment in expandAttributes())
  189. if ( $element == 'input' ) {
  190. # Whitelist of types that don't cause validation. All except
  191. # 'search' are valid in XHTML1.
  192. $validTypes = array(
  193. 'hidden',
  194. 'text',
  195. 'password',
  196. 'checkbox',
  197. 'radio',
  198. 'file',
  199. 'submit',
  200. 'image',
  201. 'reset',
  202. 'button',
  203. 'search',
  204. );
  205. if ( isset( $attribs['type'] )
  206. && !in_array( $attribs['type'], $validTypes ) ) {
  207. unset( $attribs['type'] );
  208. }
  209. if ( isset( $attribs['type'] ) && $attribs['type'] == 'search'
  210. && !$wgHtml5 ) {
  211. unset( $attribs['type'] );
  212. }
  213. }
  214. if ( !$wgHtml5 && $element == 'textarea' && isset( $attribs['maxlength'] ) ) {
  215. unset( $attribs['maxlength'] );
  216. }
  217. return "<$element" . self::expandAttributes(
  218. self::dropDefaults( $element, $attribs ) ) . '>';
  219. }
  220. /**
  221. * Returns "</$element>", except if $wgWellFormedXml is off, in which case
  222. * it returns the empty string when that's guaranteed to be safe.
  223. *
  224. * @since 1.17
  225. * @param $element string Name of the element, e.g., 'a'
  226. * @return string A closing tag, if required
  227. */
  228. public static function closeElement( $element ) {
  229. global $wgWellFormedXml;
  230. $element = strtolower( $element );
  231. # Reference:
  232. # http://www.whatwg.org/specs/web-apps/current-work/multipage/syntax.html#optional-tags
  233. if ( !$wgWellFormedXml && in_array( $element, array(
  234. 'html',
  235. 'head',
  236. 'body',
  237. 'li',
  238. 'dt',
  239. 'dd',
  240. 'tr',
  241. 'td',
  242. 'th',
  243. ) ) ) {
  244. return '';
  245. }
  246. return "</$element>";
  247. }
  248. /**
  249. * Given an element name and an associative array of element attributes,
  250. * return an array that is functionally identical to the input array, but
  251. * possibly smaller. In particular, attributes might be stripped if they
  252. * are given their default values.
  253. *
  254. * This method is not guaranteed to remove all redundant attributes, only
  255. * some common ones and some others selected arbitrarily at random. It
  256. * only guarantees that the output array should be functionally identical
  257. * to the input array (currently per the HTML 5 draft as of 2009-09-06).
  258. *
  259. * @param $element string Name of the element, e.g., 'a'
  260. * @param $attribs array Associative array of attributes, e.g., array(
  261. * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
  262. * further documentation.
  263. * @return array An array of attributes functionally identical to $attribs
  264. */
  265. private static function dropDefaults( $element, $attribs ) {
  266. # Don't bother doing anything if we aren't outputting HTML5; it's too
  267. # much of a pain to maintain two sets of defaults.
  268. global $wgHtml5;
  269. if ( !$wgHtml5 ) {
  270. return $attribs;
  271. }
  272. static $attribDefaults = array(
  273. 'area' => array( 'shape' => 'rect' ),
  274. 'button' => array(
  275. 'formaction' => 'GET',
  276. 'formenctype' => 'application/x-www-form-urlencoded',
  277. 'type' => 'submit',
  278. ),
  279. 'canvas' => array(
  280. 'height' => '150',
  281. 'width' => '300',
  282. ),
  283. 'command' => array( 'type' => 'command' ),
  284. 'form' => array(
  285. 'action' => 'GET',
  286. 'autocomplete' => 'on',
  287. 'enctype' => 'application/x-www-form-urlencoded',
  288. ),
  289. 'input' => array(
  290. 'formaction' => 'GET',
  291. 'type' => 'text',
  292. 'value' => '',
  293. ),
  294. 'keygen' => array( 'keytype' => 'rsa' ),
  295. 'link' => array( 'media' => 'all' ),
  296. 'menu' => array( 'type' => 'list' ),
  297. # Note: the use of text/javascript here instead of other JavaScript
  298. # MIME types follows the HTML5 spec.
  299. 'script' => array( 'type' => 'text/javascript' ),
  300. 'style' => array(
  301. 'media' => 'all',
  302. 'type' => 'text/css',
  303. ),
  304. 'textarea' => array( 'wrap' => 'soft' ),
  305. );
  306. $element = strtolower( $element );
  307. foreach ( $attribs as $attrib => $value ) {
  308. $lcattrib = strtolower( $attrib );
  309. $value = strval( $value );
  310. # Simple checks using $attribDefaults
  311. if ( isset( $attribDefaults[$element][$lcattrib] ) &&
  312. $attribDefaults[$element][$lcattrib] == $value ) {
  313. unset( $attribs[$attrib] );
  314. }
  315. if ( $lcattrib == 'class' && $value == '' ) {
  316. unset( $attribs[$attrib] );
  317. }
  318. }
  319. # More subtle checks
  320. if ( $element === 'link' && isset( $attribs['type'] )
  321. && strval( $attribs['type'] ) == 'text/css' ) {
  322. unset( $attribs['type'] );
  323. }
  324. if ( $element === 'select' && isset( $attribs['size'] ) ) {
  325. if ( in_array( 'multiple', $attribs )
  326. || ( isset( $attribs['multiple'] ) && $attribs['multiple'] !== false )
  327. ) {
  328. # A multi-select
  329. if ( strval( $attribs['size'] ) == '4' ) {
  330. unset( $attribs['size'] );
  331. }
  332. } else {
  333. # Single select
  334. if ( strval( $attribs['size'] ) == '1' ) {
  335. unset( $attribs['size'] );
  336. }
  337. }
  338. }
  339. return $attribs;
  340. }
  341. /**
  342. * Given an associative array of element attributes, generate a string
  343. * to stick after the element name in HTML output. Like array( 'href' =>
  344. * 'http://www.mediawiki.org/' ) becomes something like
  345. * ' href="http://www.mediawiki.org"'. Again, this is like
  346. * Xml::expandAttributes(), but it implements some HTML-specific logic.
  347. * For instance, it will omit quotation marks if $wgWellFormedXml is false,
  348. * and will treat boolean attributes specially.
  349. *
  350. * Attributes that should contain space-separated lists (such as 'class') array
  351. * values are allowed as well, which will automagically be normalized
  352. * and converted to a space-separated string. In addition to a numerical
  353. * array, the attribute value may also be an associative array. See the
  354. * example below for how that works.
  355. *
  356. * @par Numerical array
  357. * @code
  358. * Html::element( 'em', array(
  359. * 'class' => array( 'foo', 'bar' )
  360. * ) );
  361. * // gives '<em class="foo bar"></em>'
  362. * @endcode
  363. *
  364. * @par Associative array
  365. * @code
  366. * Html::element( 'em', array(
  367. * 'class' => array( 'foo', 'bar', 'foo' => false, 'quux' => true )
  368. * ) );
  369. * // gives '<em class="bar quux"></em>'
  370. * @endcode
  371. *
  372. * @param $attribs array Associative array of attributes, e.g., array(
  373. * 'href' => 'http://www.mediawiki.org/' ). Values will be HTML-escaped.
  374. * A value of false means to omit the attribute. For boolean attributes,
  375. * you can omit the key, e.g., array( 'checked' ) instead of
  376. * array( 'checked' => 'checked' ) or such.
  377. * @return string HTML fragment that goes between element name and '>'
  378. * (starting with a space if at least one attribute is output)
  379. */
  380. public static function expandAttributes( $attribs ) {
  381. global $wgHtml5, $wgWellFormedXml;
  382. $ret = '';
  383. $attribs = (array)$attribs;
  384. foreach ( $attribs as $key => $value ) {
  385. if ( $value === false || is_null( $value ) ) {
  386. continue;
  387. }
  388. # For boolean attributes, support array( 'foo' ) instead of
  389. # requiring array( 'foo' => 'meaningless' ).
  390. if ( is_int( $key )
  391. && in_array( strtolower( $value ), self::$boolAttribs ) ) {
  392. $key = $value;
  393. }
  394. # Not technically required in HTML5, but required in XHTML 1.0,
  395. # and we'd like consistency and better compression anyway.
  396. $key = strtolower( $key );
  397. # Here we're blacklisting some HTML5-only attributes...
  398. if ( !$wgHtml5 && in_array( $key, self::$HTMLFiveOnlyAttribs )
  399. ) {
  400. continue;
  401. }
  402. # Bug 23769: Blacklist all form validation attributes for now. Current
  403. # (June 2010) WebKit has no UI, so the form just refuses to submit
  404. # without telling the user why, which is much worse than failing
  405. # server-side validation. Opera is the only other implementation at
  406. # this time, and has ugly UI, so just kill the feature entirely until
  407. # we have at least one good implementation.
  408. if ( in_array( $key, array( 'max', 'min', 'pattern', 'required', 'step' ) ) ) {
  409. continue;
  410. }
  411. // http://www.w3.org/TR/html401/index/attributes.html ("space-separated")
  412. // http://www.w3.org/TR/html5/index.html#attributes-1 ("space-separated")
  413. $spaceSeparatedListAttributes = array(
  414. 'class', // html4, html5
  415. 'accesskey', // as of html5, multiple space-separated values allowed
  416. // html4-spec doesn't document rel= as space-separated
  417. // but has been used like that and is now documented as such
  418. // in the html5-spec.
  419. 'rel',
  420. );
  421. # Specific features for attributes that allow a list of space-separated values
  422. if ( in_array( $key, $spaceSeparatedListAttributes ) ) {
  423. // Apply some normalization and remove duplicates
  424. // Convert into correct array. Array can contain space-seperated
  425. // values. Implode/explode to get those into the main array as well.
  426. if ( is_array( $value ) ) {
  427. // If input wasn't an array, we can skip this step
  428. $newValue = array();
  429. foreach ( $value as $k => $v ) {
  430. if ( is_string( $v ) ) {
  431. // String values should be normal `array( 'foo' )`
  432. // Just append them
  433. if ( !isset( $value[$v] ) ) {
  434. // As a special case don't set 'foo' if a
  435. // separate 'foo' => true/false exists in the array
  436. // keys should be authoritive
  437. $newValue[] = $v;
  438. }
  439. } elseif ( $v ) {
  440. // If the value is truthy but not a string this is likely
  441. // an array( 'foo' => true ), falsy values don't add strings
  442. $newValue[] = $k;
  443. }
  444. }
  445. $value = implode( ' ', $newValue );
  446. }
  447. $value = explode( ' ', $value );
  448. // Normalize spacing by fixing up cases where people used
  449. // more than 1 space and/or a trailing/leading space
  450. $value = array_diff( $value, array( '', ' ' ) );
  451. // Remove duplicates and create the string
  452. $value = implode( ' ', array_unique( $value ) );
  453. }
  454. # See the "Attributes" section in the HTML syntax part of HTML5,
  455. # 9.1.2.3 as of 2009-08-10. Most attributes can have quotation
  456. # marks omitted, but not all. (Although a literal " is not
  457. # permitted, we don't check for that, since it will be escaped
  458. # anyway.)
  459. #
  460. # See also research done on further characters that need to be
  461. # escaped: http://code.google.com/p/html5lib/issues/detail?id=93
  462. $badChars = "\\x00- '=<>`/\x{00a0}\x{1680}\x{180e}\x{180F}\x{2000}\x{2001}"
  463. . "\x{2002}\x{2003}\x{2004}\x{2005}\x{2006}\x{2007}\x{2008}\x{2009}"
  464. . "\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}";
  465. if ( $wgWellFormedXml || $value === ''
  466. || preg_match( "![$badChars]!u", $value ) ) {
  467. $quote = '"';
  468. } else {
  469. $quote = '';
  470. }
  471. if ( in_array( $key, self::$boolAttribs ) ) {
  472. # In XHTML 1.0 Transitional, the value needs to be equal to the
  473. # key. In HTML5, we can leave the value empty instead. If we
  474. # don't need well-formed XML, we can omit the = entirely.
  475. if ( !$wgWellFormedXml ) {
  476. $ret .= " $key";
  477. } elseif ( $wgHtml5 ) {
  478. $ret .= " $key=\"\"";
  479. } else {
  480. $ret .= " $key=\"$key\"";
  481. }
  482. } else {
  483. # Apparently we need to entity-encode \n, \r, \t, although the
  484. # spec doesn't mention that. Since we're doing strtr() anyway,
  485. # and we don't need <> escaped here, we may as well not call
  486. # htmlspecialchars().
  487. # @todo FIXME: Verify that we actually need to
  488. # escape \n\r\t here, and explain why, exactly.
  489. #
  490. # We could call Sanitizer::encodeAttribute() for this, but we
  491. # don't because we're stubborn and like our marginal savings on
  492. # byte size from not having to encode unnecessary quotes.
  493. $map = array(
  494. '&' => '&amp;',
  495. '"' => '&quot;',
  496. "\n" => '&#10;',
  497. "\r" => '&#13;',
  498. "\t" => '&#9;'
  499. );
  500. if ( $wgWellFormedXml ) {
  501. # This is allowed per spec: <http://www.w3.org/TR/xml/#NT-AttValue>
  502. # But reportedly it breaks some XML tools?
  503. # @todo FIXME: Is this really true?
  504. $map['<'] = '&lt;';
  505. }
  506. $ret .= " $key=$quote" . strtr( $value, $map ) . $quote;
  507. }
  508. }
  509. return $ret;
  510. }
  511. /**
  512. * Output a <script> tag with the given contents. TODO: do some useful
  513. * escaping as well, like if $contents contains literal '</script>' or (for
  514. * XML) literal "]]>".
  515. *
  516. * @param $contents string JavaScript
  517. * @return string Raw HTML
  518. */
  519. public static function inlineScript( $contents ) {
  520. global $wgHtml5, $wgJsMimeType, $wgWellFormedXml;
  521. $attrs = array();
  522. if ( !$wgHtml5 ) {
  523. $attrs['type'] = $wgJsMimeType;
  524. }
  525. if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
  526. $contents = "/*<![CDATA[*/$contents/*]]>*/";
  527. }
  528. return self::rawElement( 'script', $attrs, $contents );
  529. }
  530. /**
  531. * Output a <script> tag linking to the given URL, e.g.,
  532. * <script src=foo.js></script>.
  533. *
  534. * @param $url string
  535. * @return string Raw HTML
  536. */
  537. public static function linkedScript( $url ) {
  538. global $wgHtml5, $wgJsMimeType;
  539. $attrs = array( 'src' => $url );
  540. if ( !$wgHtml5 ) {
  541. $attrs['type'] = $wgJsMimeType;
  542. }
  543. return self::element( 'script', $attrs );
  544. }
  545. /**
  546. * Output a <style> tag with the given contents for the given media type
  547. * (if any). TODO: do some useful escaping as well, like if $contents
  548. * contains literal '</style>' (admittedly unlikely).
  549. *
  550. * @param $contents string CSS
  551. * @param $media mixed A media type string, like 'screen'
  552. * @return string Raw HTML
  553. */
  554. public static function inlineStyle( $contents, $media = 'all' ) {
  555. global $wgWellFormedXml;
  556. if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
  557. $contents = "/*<![CDATA[*/$contents/*]]>*/";
  558. }
  559. return self::rawElement( 'style', array(
  560. 'type' => 'text/css',
  561. 'media' => $media,
  562. ), $contents );
  563. }
  564. /**
  565. * Output a <link rel=stylesheet> linking to the given URL for the given
  566. * media type (if any).
  567. *
  568. * @param $url string
  569. * @param $media mixed A media type string, like 'screen'
  570. * @return string Raw HTML
  571. */
  572. public static function linkedStyle( $url, $media = 'all' ) {
  573. return self::element( 'link', array(
  574. 'rel' => 'stylesheet',
  575. 'href' => $url,
  576. 'type' => 'text/css',
  577. 'media' => $media,
  578. ) );
  579. }
  580. /**
  581. * Convenience function to produce an <input> element. This supports the
  582. * new HTML5 input types and attributes, and will silently strip them if
  583. * $wgHtml5 is false.
  584. *
  585. * @param $name string name attribute
  586. * @param $value mixed value attribute
  587. * @param $type string type attribute
  588. * @param $attribs array Associative array of miscellaneous extra
  589. * attributes, passed to Html::element()
  590. * @return string Raw HTML
  591. */
  592. public static function input( $name, $value = '', $type = 'text', $attribs = array() ) {
  593. $attribs['type'] = $type;
  594. $attribs['value'] = $value;
  595. $attribs['name'] = $name;
  596. return self::element( 'input', $attribs );
  597. }
  598. /**
  599. * Convenience function to produce an input element with type=hidden
  600. *
  601. * @param $name string name attribute
  602. * @param $value string value attribute
  603. * @param $attribs array Associative array of miscellaneous extra
  604. * attributes, passed to Html::element()
  605. * @return string Raw HTML
  606. */
  607. public static function hidden( $name, $value, $attribs = array() ) {
  608. return self::input( $name, $value, 'hidden', $attribs );
  609. }
  610. /**
  611. * Convenience function to produce an <input> element. This supports leaving
  612. * out the cols= and rows= which Xml requires and are required by HTML4/XHTML
  613. * but not required by HTML5 and will silently set cols="" and rows="" if
  614. * $wgHtml5 is false and cols and rows are omitted (HTML4 validates present
  615. * but empty cols="" and rows="" as valid).
  616. *
  617. * @param $name string name attribute
  618. * @param $value string value attribute
  619. * @param $attribs array Associative array of miscellaneous extra
  620. * attributes, passed to Html::element()
  621. * @return string Raw HTML
  622. */
  623. public static function textarea( $name, $value = '', $attribs = array() ) {
  624. global $wgHtml5;
  625. $attribs['name'] = $name;
  626. if ( !$wgHtml5 ) {
  627. if ( !isset( $attribs['cols'] ) ) {
  628. $attribs['cols'] = "";
  629. }
  630. if ( !isset( $attribs['rows'] ) ) {
  631. $attribs['rows'] = "";
  632. }
  633. }
  634. if (substr($value, 0, 1) == "\n") {
  635. // Workaround for bug 12130: browsers eat the initial newline
  636. // assuming that it's just for show, but they do keep the later
  637. // newlines, which we may want to preserve during editing.
  638. // Prepending a single newline
  639. $spacedValue = "\n" . $value;
  640. } else {
  641. $spacedValue = $value;
  642. }
  643. return self::element( 'textarea', $attribs, $spacedValue );
  644. }
  645. /**
  646. * Build a drop-down box for selecting a namespace
  647. *
  648. * @param $params array:
  649. * - selected: [optional] Id of namespace which should be pre-selected
  650. * - all: [optional] Value of item for "all namespaces". If null or unset, no <option> is generated to select all namespaces
  651. * - label: text for label to add before the field
  652. * @param $selectAttribs array HTML attributes for the generated select element.
  653. * - id: [optional], default: 'namespace'
  654. * - name: [optional], default: 'namespace'
  655. * @return string HTML code to select a namespace.
  656. */
  657. public static function namespaceSelector( Array $params = array(), Array $selectAttribs = array() ) {
  658. global $wgContLang;
  659. // Default 'id' & 'name' <select> attributes
  660. $selectAttribs = $selectAttribs + array(
  661. 'id' => 'namespace',
  662. 'name' => 'namespace',
  663. );
  664. ksort( $selectAttribs );
  665. // Is a namespace selected?
  666. if ( isset( $params['selected'] ) ) {
  667. // If string only contains digits, convert to clean int. Selected could also
  668. // be "all" or "" etc. which needs to be left untouched.
  669. // PHP is_numeric() has issues with large strings, PHP ctype_digit has other issues
  670. // and returns false for already clean ints. Use regex instead..
  671. if ( preg_match( '/^\d+$/', $params['selected'] ) ) {
  672. $params['selected'] = intval( $params['selected'] );
  673. }
  674. // else: leaves it untouched for later processing
  675. } else {
  676. $params['selected'] = '';
  677. }
  678. // Array holding the <option> elements
  679. $options = array();
  680. if ( isset( $params['all'] ) ) {
  681. // add an <option> that would let the user select all namespaces.
  682. // Value is provided by user, the name shown is localized.
  683. $options[$params['all']] = wfMsg( 'namespacesall' );
  684. }
  685. // Add defaults <option> according to content language
  686. $options += $wgContLang->getFormattedNamespaces();
  687. // Convert $options to HTML
  688. $optionsHtml = array();
  689. foreach ( $options as $nsId => $nsName ) {
  690. if ( $nsId < NS_MAIN ) {
  691. continue;
  692. }
  693. if ( $nsId === 0 ) {
  694. $nsName = wfMsg( 'blanknamespace' );
  695. }
  696. $optionsHtml[] = Xml::option( $nsName, $nsId, $nsId === $params['selected'] );
  697. }
  698. // Forge a <select> element and returns it
  699. $ret = '';
  700. if ( isset( $params['label'] ) ) {
  701. $ret .= Xml::label( $params['label'], $selectAttribs['id'] ) . '&#160;';
  702. }
  703. $ret .= Html::openElement( 'select', $selectAttribs )
  704. . "\n"
  705. . implode( "\n", $optionsHtml )
  706. . "\n"
  707. . Html::closeElement( 'select' );
  708. return $ret;
  709. }
  710. /**
  711. * Constructs the opening html-tag with necessary doctypes depending on
  712. * global variables.
  713. *
  714. * @param $attribs array Associative array of miscellaneous extra
  715. * attributes, passed to Html::element() of html tag.
  716. * @return string Raw HTML
  717. */
  718. public static function htmlHeader( $attribs = array() ) {
  719. $ret = '';
  720. global $wgMimeType;
  721. if ( self::isXmlMimeType( $wgMimeType ) ) {
  722. $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?" . ">\n";
  723. }
  724. global $wgHtml5, $wgHtml5Version, $wgDocType, $wgDTD;
  725. global $wgXhtmlNamespaces, $wgXhtmlDefaultNamespace;
  726. if ( $wgHtml5 ) {
  727. $ret .= "<!DOCTYPE html>\n";
  728. if ( $wgHtml5Version ) {
  729. $attribs['version'] = $wgHtml5Version;
  730. }
  731. } else {
  732. $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\" \"$wgDTD\">\n";
  733. $attribs['xmlns'] = $wgXhtmlDefaultNamespace;
  734. foreach ( $wgXhtmlNamespaces as $tag => $ns ) {
  735. $attribs["xmlns:$tag"] = $ns;
  736. }
  737. }
  738. $html = Html::openElement( 'html', $attribs );
  739. if ( $html ) {
  740. $html .= "\n";
  741. }
  742. $ret .= $html;
  743. return $ret;
  744. }
  745. /**
  746. * Determines if the given mime type is xml.
  747. *
  748. * @param $mimetype string MimeType
  749. * @return Boolean
  750. */
  751. public static function isXmlMimeType( $mimetype ) {
  752. switch ( $mimetype ) {
  753. case 'text/xml':
  754. case 'application/xhtml+xml':
  755. case 'application/xml':
  756. return true;
  757. default:
  758. return false;
  759. }
  760. }
  761. /**
  762. * Get HTML for an info box with an icon.
  763. *
  764. * @param $text String: wikitext, get this with wfMsgNoTrans()
  765. * @param $icon String: icon name, file in skins/common/images
  766. * @param $alt String: alternate text for the icon
  767. * @param $class String: additional class name to add to the wrapper div
  768. * @param $useStylePath
  769. *
  770. * @return string
  771. */
  772. static function infoBox( $text, $icon, $alt, $class = false, $useStylePath = true ) {
  773. global $wgStylePath;
  774. if ( $useStylePath ) {
  775. $icon = $wgStylePath.'/common/images/'.$icon;
  776. }
  777. $s = Html::openElement( 'div', array( 'class' => "mw-infobox $class") );
  778. $s .= Html::openElement( 'div', array( 'class' => 'mw-infobox-left' ) ).
  779. Html::element( 'img',
  780. array(
  781. 'src' => $icon,
  782. 'alt' => $alt,
  783. )
  784. ).
  785. Html::closeElement( 'div' );
  786. $s .= Html::openElement( 'div', array( 'class' => 'mw-infobox-right' ) ).
  787. $text.
  788. Html::closeElement( 'div' );
  789. $s .= Html::element( 'div', array( 'style' => 'clear: left;' ), ' ' );
  790. $s .= Html::closeElement( 'div' );
  791. $s .= Html::element( 'div', array( 'style' => 'clear: left;' ), ' ' );
  792. return $s;
  793. }
  794. }