Html.php 34 KB

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