Xml.php 26 KB

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