Xml.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863
  1. <?php
  2. /**
  3. * Methods to generate XML.
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License along
  16. * with this program; if not, write to the Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. * http://www.gnu.org/copyleft/gpl.html
  19. *
  20. * @file
  21. */
  22. use MediaWiki\MediaWikiServices;
  23. /**
  24. * Module of static functions for generating XML
  25. */
  26. class Xml {
  27. /**
  28. * Format an XML element with given attributes and, optionally, text content.
  29. * Element and attribute names are assumed to be ready for literal inclusion.
  30. * Strings are assumed to not contain XML-illegal characters; special
  31. * characters (<, >, &) are escaped but illegals are not touched.
  32. *
  33. * @param string $element Element name
  34. * @param array|null $attribs Name=>value pairs. Values will be escaped.
  35. * @param string $contents Null to make an open tag only; '' for a contentless closed tag (default)
  36. * @param bool $allowShortTag Whether '' in $contents will result in a contentless closed tag
  37. * @return string
  38. */
  39. public static function element( $element, $attribs = null, $contents = '',
  40. $allowShortTag = true
  41. ) {
  42. $out = '<' . $element;
  43. if ( !is_null( $attribs ) ) {
  44. $out .= self::expandAttributes( $attribs );
  45. }
  46. if ( is_null( $contents ) ) {
  47. $out .= '>';
  48. } else {
  49. if ( $allowShortTag && $contents === '' ) {
  50. $out .= ' />';
  51. } else {
  52. $out .= '>' . htmlspecialchars( $contents, ENT_NOQUOTES ) . "</$element>";
  53. }
  54. }
  55. return $out;
  56. }
  57. /**
  58. * Given an array of ('attributename' => 'value'), it generates the code
  59. * to set the XML attributes : attributename="value".
  60. * The values are passed to Sanitizer::encodeAttribute.
  61. * Returns null or empty string if no attributes given.
  62. * @param array|null $attribs Array of attributes for an XML element
  63. * @throws MWException
  64. * @return null|string
  65. */
  66. public static function expandAttributes( $attribs ) {
  67. $out = '';
  68. if ( is_null( $attribs ) ) {
  69. return null;
  70. } elseif ( is_array( $attribs ) ) {
  71. foreach ( $attribs as $name => $val ) {
  72. $out .= " {$name}=\"" . Sanitizer::encodeAttribute( $val ) . '"';
  73. }
  74. return $out;
  75. } else {
  76. throw new MWException( 'Expected attribute array, got something else in ' . __METHOD__ );
  77. }
  78. }
  79. /**
  80. * Format an XML element as with self::element(), but run text through the content language's
  81. * normalize() validator first to ensure that no invalid UTF-8 is passed.
  82. *
  83. * @param string $element
  84. * @param array $attribs Name=>value pairs. Values will be escaped.
  85. * @param string $contents Null to make an open tag only; '' for a contentless closed tag (default)
  86. * @return string
  87. */
  88. public static function elementClean( $element, $attribs = [], $contents = '' ) {
  89. if ( $attribs ) {
  90. $attribs = array_map( [ 'UtfNormal\Validator', 'cleanUp' ], $attribs );
  91. }
  92. if ( $contents ) {
  93. $contents =
  94. MediaWikiServices::getInstance()->getContentLanguage()->normalize( $contents );
  95. }
  96. return self::element( $element, $attribs, $contents );
  97. }
  98. /**
  99. * This opens an XML element
  100. *
  101. * @param string $element Name of the element
  102. * @param array|null $attribs Array of attributes, see Xml::expandAttributes()
  103. * @return string
  104. */
  105. public static function openElement( $element, $attribs = null ) {
  106. return '<' . $element . self::expandAttributes( $attribs ) . '>';
  107. }
  108. /**
  109. * Shortcut to close an XML element
  110. * @param string $element Element name
  111. * @return string
  112. */
  113. public static function closeElement( $element ) {
  114. return "</$element>";
  115. }
  116. /**
  117. * Same as Xml::element(), but does not escape contents. Handy when the
  118. * content you have is already valid xml.
  119. *
  120. * @param string $element Element name
  121. * @param array|null $attribs Array of attributes
  122. * @param string $contents Content of the element
  123. * @return string
  124. */
  125. public static function tags( $element, $attribs, $contents ) {
  126. return self::openElement( $element, $attribs ) . $contents . "</$element>";
  127. }
  128. /**
  129. * Create a date selector
  130. *
  131. * @param string $selected The month which should be selected, default ''.
  132. * @param string|null $allmonths Value of a special item denoting all month.
  133. * Null to not include (default).
  134. * @param string $id Element identifier
  135. * @return string Html string containing the month selector
  136. */
  137. public static function monthSelector( $selected = '', $allmonths = null, $id = 'month' ) {
  138. global $wgLang;
  139. $options = [];
  140. $data = new XmlSelect( 'month', $id, $selected );
  141. if ( is_null( $selected ) ) {
  142. $selected = '';
  143. }
  144. if ( !is_null( $allmonths ) ) {
  145. $options[wfMessage( 'monthsall' )->text()] = $allmonths;
  146. }
  147. for ( $i = 1; $i < 13; $i++ ) {
  148. $options[$wgLang->getMonthName( $i )] = $i;
  149. }
  150. $data->addOptions( $options );
  151. $data->setAttribute( 'class', 'mw-month-selector' );
  152. return $data->getHTML();
  153. }
  154. /**
  155. * @param int|string $year Use '' or 0 to start with no year preselected.
  156. * @param int|string $month A month in the 1..12 range. Use '', 0 or -1 to start with no month
  157. * preselected.
  158. * @return string Formatted HTML
  159. */
  160. public static function dateMenu( $year, $month ) {
  161. # Offset overrides year/month selection
  162. if ( $month && $month !== -1 ) {
  163. $encMonth = intval( $month );
  164. } else {
  165. $encMonth = '';
  166. }
  167. if ( $year ) {
  168. $encYear = intval( $year );
  169. } elseif ( $encMonth ) {
  170. $timestamp = MWTimestamp::getInstance();
  171. $thisMonth = intval( $timestamp->format( 'n' ) );
  172. $thisYear = intval( $timestamp->format( 'Y' ) );
  173. if ( intval( $encMonth ) > $thisMonth ) {
  174. $thisYear--;
  175. }
  176. $encYear = $thisYear;
  177. } else {
  178. $encYear = '';
  179. }
  180. $inputAttribs = [ 'id' => 'year', 'maxlength' => 4, 'size' => 7 ];
  181. return self::label( wfMessage( 'year' )->text(), 'year' ) . ' ' .
  182. Html::input( 'year', $encYear, 'number', $inputAttribs ) . ' ' .
  183. self::label( wfMessage( 'month' )->text(), 'month' ) . ' ' .
  184. self::monthSelector( $encMonth, -1 );
  185. }
  186. /**
  187. * Construct a language selector appropriate for use in a form or preferences
  188. *
  189. * @param string $selected The language code of the selected language
  190. * @param bool $customisedOnly If true only languages which have some content are listed
  191. * @param string|null $inLanguage The ISO code of the language to display the select list in
  192. * @param array $overrideAttrs Override the attributes of the select tag (since 1.20)
  193. * @param Message|null $msg Label message key (since 1.20)
  194. * @return array Array containing 2 items: label HTML and select list HTML
  195. */
  196. public static function languageSelector( $selected, $customisedOnly = true,
  197. $inLanguage = null, $overrideAttrs = [], Message $msg = null
  198. ) {
  199. global $wgLanguageCode;
  200. $include = $customisedOnly ? 'mwfile' : 'mw';
  201. $languages = Language::fetchLanguageNames( $inLanguage, $include );
  202. // Make sure the site language is in the list;
  203. // a custom language code might not have a defined name...
  204. if ( !array_key_exists( $wgLanguageCode, $languages ) ) {
  205. $languages[$wgLanguageCode] = $wgLanguageCode;
  206. // Sort the array again
  207. ksort( $languages );
  208. }
  209. /**
  210. * If a bogus value is set, default to the content language.
  211. * Otherwise, no default is selected and the user ends up
  212. * with Afrikaans since it's first in the list.
  213. */
  214. $selected = isset( $languages[$selected] ) ? $selected : $wgLanguageCode;
  215. $options = "\n";
  216. foreach ( $languages as $code => $name ) {
  217. $options .= self::option( "$code - $name", $code, $code == $selected ) . "\n";
  218. }
  219. $attrs = [ 'id' => 'wpUserLanguage', 'name' => 'wpUserLanguage' ];
  220. $attrs = array_merge( $attrs, $overrideAttrs );
  221. if ( $msg === null ) {
  222. $msg = wfMessage( 'yourlanguage' );
  223. }
  224. return [
  225. self::label( $msg->text(), $attrs['id'] ),
  226. self::tags( 'select', $attrs, $options )
  227. ];
  228. }
  229. /**
  230. * Shortcut to make a span element
  231. * @param string $text Content of the element, will be escaped
  232. * @param string $class Class name of the span element
  233. * @param array $attribs Other attributes
  234. * @return string
  235. */
  236. public static function span( $text, $class, $attribs = [] ) {
  237. return self::element( 'span', [ 'class' => $class ] + $attribs, $text );
  238. }
  239. /**
  240. * Shortcut to make a specific element with a class attribute
  241. * @param string $text Content of the element, will be escaped
  242. * @param string $class Class name of the span element
  243. * @param string $tag Element name
  244. * @param array $attribs Other attributes
  245. * @return string
  246. */
  247. public static function wrapClass( $text, $class, $tag = 'span', $attribs = [] ) {
  248. return self::tags( $tag, [ 'class' => $class ] + $attribs, $text );
  249. }
  250. /**
  251. * Convenience function to build an HTML text input field
  252. * @param string $name Value of the name attribute
  253. * @param int $size Value of the size attribute
  254. * @param mixed $value Value of the value attribute
  255. * @param array $attribs Other attributes
  256. * @return string HTML
  257. */
  258. public static function input( $name, $size = false, $value = false, $attribs = [] ) {
  259. $attributes = [ 'name' => $name ];
  260. if ( $size ) {
  261. $attributes['size'] = $size;
  262. }
  263. if ( $value !== false ) { // maybe 0
  264. $attributes['value'] = $value;
  265. }
  266. return self::element( 'input',
  267. Html::getTextInputAttributes( $attributes + $attribs ) );
  268. }
  269. /**
  270. * Convenience function to build an HTML password input field
  271. * @param string $name Value of the name attribute
  272. * @param int $size Value of the size attribute
  273. * @param mixed $value Value of the value attribute
  274. * @param array $attribs Other attributes
  275. * @return string HTML
  276. */
  277. public static function password( $name, $size = false, $value = false,
  278. $attribs = []
  279. ) {
  280. return self::input( $name, $size, $value,
  281. array_merge( $attribs, [ 'type' => 'password' ] ) );
  282. }
  283. /**
  284. * Internal function for use in checkboxes and radio buttons and such.
  285. *
  286. * @param string $name
  287. * @param bool $present
  288. *
  289. * @return array
  290. */
  291. public static function attrib( $name, $present = true ) {
  292. return $present ? [ $name => $name ] : [];
  293. }
  294. /**
  295. * Convenience function to build an HTML checkbox
  296. * @param string $name Value of the name attribute
  297. * @param bool $checked Whether the checkbox is checked or not
  298. * @param array $attribs Array other attributes
  299. * @return string HTML
  300. */
  301. public static function check( $name, $checked = false, $attribs = [] ) {
  302. return self::element( 'input', array_merge(
  303. [
  304. 'name' => $name,
  305. 'type' => 'checkbox',
  306. 'value' => 1 ],
  307. self::attrib( 'checked', $checked ),
  308. $attribs ) );
  309. }
  310. /**
  311. * Convenience function to build an HTML radio button
  312. * @param string $name Value of the name attribute
  313. * @param string $value Value of the value attribute
  314. * @param bool $checked Whether the checkbox is checked or not
  315. * @param array $attribs Other attributes
  316. * @return string HTML
  317. */
  318. public static function radio( $name, $value, $checked = false, $attribs = [] ) {
  319. return self::element( 'input', [
  320. 'name' => $name,
  321. 'type' => 'radio',
  322. 'value' => $value ] + self::attrib( 'checked', $checked ) + $attribs );
  323. }
  324. /**
  325. * Convenience function to build an HTML form label
  326. * @param string $label Text of the label
  327. * @param string $id
  328. * @param array $attribs An attribute array. This will usually be
  329. * the same array as is passed to the corresponding input element,
  330. * so this function will cherry-pick appropriate attributes to
  331. * apply to the label as well; only class and title are applied.
  332. * @return string HTML
  333. */
  334. public static function label( $label, $id, $attribs = [] ) {
  335. $a = [ 'for' => $id ];
  336. foreach ( [ 'class', 'title' ] as $attr ) {
  337. if ( isset( $attribs[$attr] ) ) {
  338. $a[$attr] = $attribs[$attr];
  339. }
  340. }
  341. return self::element( 'label', $a, $label );
  342. }
  343. /**
  344. * Convenience function to build an HTML text input field with a label
  345. * @param string $label Text of the label
  346. * @param string $name Value of the name attribute
  347. * @param string $id Id of the input
  348. * @param int|bool $size Value of the size attribute
  349. * @param string|bool $value Value of the value attribute
  350. * @param array $attribs Other attributes
  351. * @return string HTML
  352. */
  353. public static function inputLabel( $label, $name, $id, $size = false,
  354. $value = false, $attribs = []
  355. ) {
  356. list( $label, $input ) = self::inputLabelSep( $label, $name, $id, $size, $value, $attribs );
  357. return $label . "\u{00A0}" . $input;
  358. }
  359. /**
  360. * Same as Xml::inputLabel() but return input and label in an array
  361. *
  362. * @param string $label
  363. * @param string $name
  364. * @param string $id
  365. * @param int|bool $size
  366. * @param string|bool $value
  367. * @param array $attribs
  368. *
  369. * @return array
  370. */
  371. public static function inputLabelSep( $label, $name, $id, $size = false,
  372. $value = false, $attribs = []
  373. ) {
  374. return [
  375. self::label( $label, $id, $attribs ),
  376. self::input( $name, $size, $value, [ 'id' => $id ] + $attribs )
  377. ];
  378. }
  379. /**
  380. * Convenience function to build an HTML checkbox with a label
  381. *
  382. * @param string $label
  383. * @param string $name
  384. * @param string $id
  385. * @param bool $checked
  386. * @param array $attribs
  387. *
  388. * @return string HTML
  389. */
  390. public static function checkLabel( $label, $name, $id, $checked = false, $attribs = [] ) {
  391. global $wgUseMediaWikiUIEverywhere;
  392. $chkLabel = self::check( $name, $checked, [ 'id' => $id ] + $attribs ) .
  393. "\u{00A0}" .
  394. self::label( $label, $id, $attribs );
  395. if ( $wgUseMediaWikiUIEverywhere ) {
  396. $chkLabel = self::openElement( 'div', [ 'class' => 'mw-ui-checkbox' ] ) .
  397. $chkLabel . self::closeElement( 'div' );
  398. }
  399. return $chkLabel;
  400. }
  401. /**
  402. * Convenience function to build an HTML radio button with a label
  403. *
  404. * @param string $label
  405. * @param string $name
  406. * @param string $value
  407. * @param string $id
  408. * @param bool $checked
  409. * @param array $attribs
  410. *
  411. * @return string HTML
  412. */
  413. public static function radioLabel( $label, $name, $value, $id,
  414. $checked = false, $attribs = []
  415. ) {
  416. return self::radio( $name, $value, $checked, [ 'id' => $id ] + $attribs ) .
  417. "\u{00A0}" .
  418. self::label( $label, $id, $attribs );
  419. }
  420. /**
  421. * Convenience function to build an HTML submit button
  422. * When $wgUseMediaWikiUIEverywhere is true it will default to a progressive button
  423. * @param string $value Label text for the button (unescaped)
  424. * @param array $attribs Optional custom attributes
  425. * @return string HTML
  426. */
  427. public static function submitButton( $value, $attribs = [] ) {
  428. global $wgUseMediaWikiUIEverywhere;
  429. $baseAttrs = [
  430. 'type' => 'submit',
  431. 'value' => $value,
  432. ];
  433. // Done conditionally for time being as it is possible
  434. // some submit forms
  435. // might need to be mw-ui-destructive (e.g. delete a page)
  436. if ( $wgUseMediaWikiUIEverywhere ) {
  437. $baseAttrs['class'] = 'mw-ui-button mw-ui-progressive';
  438. }
  439. // Any custom attributes will take precendence of anything in baseAttrs e.g. override the class
  440. $attribs = $attribs + $baseAttrs;
  441. return Html::element( 'input', $attribs );
  442. }
  443. /**
  444. * Convenience function to build an HTML drop-down list item.
  445. * @param string $text Text for this item. Will be HTML escaped
  446. * @param string|null $value Form submission value; if empty, use text
  447. * @param bool $selected If true, will be the default selected item
  448. * @param array $attribs Optional additional HTML attributes
  449. * @return string HTML
  450. */
  451. public static function option( $text, $value = null, $selected = false,
  452. $attribs = [] ) {
  453. if ( !is_null( $value ) ) {
  454. $attribs['value'] = $value;
  455. }
  456. if ( $selected ) {
  457. $attribs['selected'] = 'selected';
  458. }
  459. return Html::element( 'option', $attribs, $text );
  460. }
  461. /**
  462. * Build a drop-down box from a textual list. This is a wrapper
  463. * for Xml::listDropDownOptions() plus the XmlSelect class.
  464. *
  465. * @param string $name Name and id for the drop-down
  466. * @param string $list Correctly formatted text (newline delimited) to be
  467. * used to generate the options.
  468. * @param string $other Text for the "Other reasons" option
  469. * @param string $selected Option which should be pre-selected
  470. * @param string $class CSS classes for the drop-down
  471. * @param int|null $tabindex Value of the tabindex attribute
  472. * @return string
  473. */
  474. public static function listDropDown( $name = '', $list = '', $other = '',
  475. $selected = '', $class = '', $tabindex = null
  476. ) {
  477. $options = self::listDropDownOptions( $list, [ 'other' => $other ] );
  478. $xmlSelect = new XmlSelect( $name, $name, $selected );
  479. $xmlSelect->addOptions( $options );
  480. if ( $class ) {
  481. $xmlSelect->setAttribute( 'class', $class );
  482. }
  483. if ( $tabindex ) {
  484. $xmlSelect->setAttribute( 'tabindex', $tabindex );
  485. }
  486. return $xmlSelect->getHTML();
  487. }
  488. /**
  489. * Build options for a drop-down box from a textual list.
  490. *
  491. * The result of this function can be passed to XmlSelect::addOptions()
  492. * (to render a plain `<select>` dropdown box) or to Xml::listDropDownOptionsOoui()
  493. * and then OOUI\DropdownInputWidget() (to render a pretty one).
  494. *
  495. * @param string $list Correctly formatted text (newline delimited) to be
  496. * used to generate the options.
  497. * @param array $params Extra parameters:
  498. * - string $params['other'] If set, add an option with this as text and a value of 'other'
  499. * @return array Array keys are textual labels, values are internal values
  500. */
  501. public static function listDropDownOptions( $list, $params = [] ) {
  502. $options = [];
  503. if ( isset( $params['other'] ) ) {
  504. $options[ $params['other'] ] = 'other';
  505. }
  506. $optgroup = false;
  507. foreach ( explode( "\n", $list ) as $option ) {
  508. $value = trim( $option );
  509. if ( $value == '' ) {
  510. continue;
  511. } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
  512. # A new group is starting...
  513. $value = trim( substr( $value, 1 ) );
  514. $optgroup = $value;
  515. } elseif ( substr( $value, 0, 2 ) == '**' ) {
  516. # groupmember
  517. $opt = trim( substr( $value, 2 ) );
  518. if ( $optgroup === false ) {
  519. $options[$opt] = $opt;
  520. } else {
  521. $options[$optgroup][$opt] = $opt;
  522. }
  523. } else {
  524. # groupless reason list
  525. $optgroup = false;
  526. $options[$option] = $option;
  527. }
  528. }
  529. return $options;
  530. }
  531. /**
  532. * Convert options for a drop-down box into a format accepted by OOUI\DropdownInputWidget etc.
  533. *
  534. * TODO Find a better home for this function.
  535. *
  536. * @param array $options Options, as returned e.g. by Xml::listDropDownOptions()
  537. * @return array
  538. */
  539. public static function listDropDownOptionsOoui( $options ) {
  540. $optionsOoui = [];
  541. foreach ( $options as $text => $value ) {
  542. if ( is_array( $value ) ) {
  543. $optionsOoui[] = [ 'optgroup' => (string)$text ];
  544. foreach ( $value as $text2 => $value2 ) {
  545. $optionsOoui[] = [ 'data' => (string)$value2, 'label' => (string)$text2 ];
  546. }
  547. } else {
  548. $optionsOoui[] = [ 'data' => (string)$value, 'label' => (string)$text ];
  549. }
  550. }
  551. return $optionsOoui;
  552. }
  553. /**
  554. * Shortcut for creating fieldsets.
  555. *
  556. * @param string|bool $legend Legend of the fieldset. If evaluates to false,
  557. * legend is not added.
  558. * @param string $content Pre-escaped content for the fieldset. If false,
  559. * only open fieldset is returned.
  560. * @param array $attribs Any attributes to fieldset-element.
  561. *
  562. * @return string
  563. */
  564. public static function fieldset( $legend = false, $content = false, $attribs = [] ) {
  565. $s = self::openElement( 'fieldset', $attribs ) . "\n";
  566. if ( $legend ) {
  567. $s .= self::element( 'legend', null, $legend ) . "\n";
  568. }
  569. if ( $content !== false ) {
  570. $s .= $content . "\n";
  571. $s .= self::closeElement( 'fieldset' ) . "\n";
  572. }
  573. return $s;
  574. }
  575. /**
  576. * Shortcut for creating textareas.
  577. *
  578. * @param string $name The 'name' for the textarea
  579. * @param string $content Content for the textarea
  580. * @param int $cols The number of columns for the textarea
  581. * @param int $rows The number of rows for the textarea
  582. * @param array $attribs Any other attributes for the textarea
  583. *
  584. * @return string
  585. */
  586. public static function textarea( $name, $content, $cols = 40, $rows = 5, $attribs = [] ) {
  587. return self::element( 'textarea',
  588. Html::getTextInputAttributes(
  589. [
  590. 'name' => $name,
  591. 'id' => $name,
  592. 'cols' => $cols,
  593. 'rows' => $rows
  594. ] + $attribs
  595. ),
  596. $content, false );
  597. }
  598. /**
  599. * Encode a variable of arbitrary type to JavaScript.
  600. * If the value is an XmlJsCode object, pass through the object's value verbatim.
  601. *
  602. * @note Only use this function for generating JavaScript code. If generating output
  603. * for a proper JSON parser, just call FormatJson::encode() directly.
  604. *
  605. * @param mixed $value The value being encoded. Can be any type except a resource.
  606. * @param bool $pretty If true, add non-significant whitespace to improve readability.
  607. * @return string|bool String if successful; false upon failure
  608. */
  609. public static function encodeJsVar( $value, $pretty = false ) {
  610. if ( $value instanceof XmlJsCode ) {
  611. return $value->value;
  612. }
  613. return FormatJson::encode( $value, $pretty, FormatJson::UTF8_OK );
  614. }
  615. /**
  616. * Create a call to a JavaScript function. The supplied arguments will be
  617. * encoded using Xml::encodeJsVar().
  618. *
  619. * @since 1.17
  620. * @param string $name The name of the function to call, or a JavaScript expression
  621. * which evaluates to a function object which is called.
  622. * @param array $args The arguments to pass to the function.
  623. * @param bool $pretty If true, add non-significant whitespace to improve readability.
  624. * @return string|bool String if successful; false upon failure
  625. */
  626. public static function encodeJsCall( $name, $args, $pretty = false ) {
  627. foreach ( $args as &$arg ) {
  628. $arg = self::encodeJsVar( $arg, $pretty );
  629. if ( $arg === false ) {
  630. return false;
  631. }
  632. }
  633. return "$name(" . ( $pretty
  634. ? ( ' ' . implode( ', ', $args ) . ' ' )
  635. : implode( ',', $args )
  636. ) . ");";
  637. }
  638. /**
  639. * Check if a string is well-formed XML.
  640. * Must include the surrounding tag.
  641. * This function is a DoS vector if an attacker can define
  642. * entities in $text.
  643. *
  644. * @param string $text String to test.
  645. * @return bool
  646. *
  647. * @todo Error position reporting return
  648. */
  649. private static function isWellFormed( $text ) {
  650. $parser = xml_parser_create( "UTF-8" );
  651. # case folding violates XML standard, turn it off
  652. xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
  653. if ( !xml_parse( $parser, $text, true ) ) {
  654. // $err = xml_error_string( xml_get_error_code( $parser ) );
  655. // $position = xml_get_current_byte_index( $parser );
  656. // $fragment = $this->extractFragment( $html, $position );
  657. // $this->mXmlError = "$err at byte $position:\n$fragment";
  658. xml_parser_free( $parser );
  659. return false;
  660. }
  661. xml_parser_free( $parser );
  662. return true;
  663. }
  664. /**
  665. * Check if a string is a well-formed XML fragment.
  666. * Wraps fragment in an \<html\> bit and doctype, so it can be a fragment
  667. * and can use HTML named entities.
  668. *
  669. * @param string $text
  670. * @return bool
  671. */
  672. public static function isWellFormedXmlFragment( $text ) {
  673. $html =
  674. Sanitizer::hackDocType() .
  675. '<html>' .
  676. $text .
  677. '</html>';
  678. return self::isWellFormed( $html );
  679. }
  680. /**
  681. * Replace " > and < with their respective HTML entities ( &quot;,
  682. * &gt;, &lt;)
  683. *
  684. * @param string $in Text that might contain HTML tags.
  685. * @return string Escaped string
  686. */
  687. public static function escapeTagsOnly( $in ) {
  688. return str_replace(
  689. [ '"', '>', '<' ],
  690. [ '&quot;', '&gt;', '&lt;' ],
  691. $in );
  692. }
  693. /**
  694. * Generate a form (without the opening form element).
  695. * Output optionally includes a submit button.
  696. * @param array $fields Associative array, key is the name of a message that
  697. * contains a description for the field, value is an HTML string
  698. * containing the appropriate input.
  699. * @param string|null $submitLabel The name of a message containing a label for
  700. * the submit button.
  701. * @param array $submitAttribs The attributes to add to the submit button
  702. * @return string HTML form.
  703. */
  704. public static function buildForm( $fields, $submitLabel = null, $submitAttribs = [] ) {
  705. $form = '';
  706. $form .= "<table><tbody>";
  707. foreach ( $fields as $labelmsg => $input ) {
  708. $id = "mw-$labelmsg";
  709. $form .= self::openElement( 'tr', [ 'id' => $id ] );
  710. // TODO use a <label> here for accessibility purposes - will need
  711. // to either not use a table to build the form, or find the ID of
  712. // the input somehow.
  713. $form .= self::tags( 'td', [ 'class' => 'mw-label' ], wfMessage( $labelmsg )->parse() );
  714. $form .= self::openElement( 'td', [ 'class' => 'mw-input' ] )
  715. . $input . self::closeElement( 'td' );
  716. $form .= self::closeElement( 'tr' );
  717. }
  718. if ( $submitLabel ) {
  719. $form .= self::openElement( 'tr' );
  720. $form .= self::tags( 'td', [], '' );
  721. $form .= self::openElement( 'td', [ 'class' => 'mw-submit' ] )
  722. . self::submitButton( wfMessage( $submitLabel )->text(), $submitAttribs )
  723. . self::closeElement( 'td' );
  724. $form .= self::closeElement( 'tr' );
  725. }
  726. $form .= "</tbody></table>";
  727. return $form;
  728. }
  729. /**
  730. * Build a table of data
  731. * @param array $rows An array of arrays of strings, each to be a row in a table
  732. * @param array $attribs An array of attributes to apply to the table tag [optional]
  733. * @param array|null $headers An array of strings to use as table headers [optional]
  734. * @return string
  735. */
  736. public static function buildTable( $rows, $attribs = [], $headers = null ) {
  737. $s = self::openElement( 'table', $attribs );
  738. if ( is_array( $headers ) ) {
  739. $s .= self::openElement( 'thead', $attribs );
  740. foreach ( $headers as $id => $header ) {
  741. $attribs = [];
  742. if ( is_string( $id ) ) {
  743. $attribs['id'] = $id;
  744. }
  745. $s .= self::element( 'th', $attribs, $header );
  746. }
  747. $s .= self::closeElement( 'thead' );
  748. }
  749. foreach ( $rows as $id => $row ) {
  750. $attribs = [];
  751. if ( is_string( $id ) ) {
  752. $attribs['id'] = $id;
  753. }
  754. $s .= self::buildTableRow( $attribs, $row );
  755. }
  756. $s .= self::closeElement( 'table' );
  757. return $s;
  758. }
  759. /**
  760. * Build a row for a table
  761. * @param array $attribs An array of attributes to apply to the tr tag
  762. * @param array $cells An array of strings to put in <td>
  763. * @return string
  764. */
  765. public static function buildTableRow( $attribs, $cells ) {
  766. $s = self::openElement( 'tr', $attribs );
  767. foreach ( $cells as $id => $cell ) {
  768. $attribs = [];
  769. if ( is_string( $id ) ) {
  770. $attribs['id'] = $id;
  771. }
  772. $s .= self::element( 'td', $attribs, $cell );
  773. }
  774. $s .= self::closeElement( 'tr' );
  775. return $s;
  776. }
  777. }