PageRenderTime 71ms CodeModel.GetById 36ms RepoModel.GetById 0ms app.codeStats 0ms

/includes/Xml.php

https://github.com/spenser-roark/OOUG-Wiki
PHP | 971 lines | 762 code | 62 blank | 147 comment | 32 complexity | a3012524a01378c2014754fab1d07898 MD5 | raw file
Possible License(s): GPL-2.0, Apache-2.0, LGPL-3.0
  1. <?php
  2. /**
  3. * Module of static functions for generating XML
  4. */
  5. class Xml {
  6. /**
  7. * Format an XML element with given attributes and, optionally, text content.
  8. * Element and attribute names are assumed to be ready for literal inclusion.
  9. * Strings are assumed to not contain XML-illegal characters; special
  10. * characters (<, >, &) are escaped but illegals are not touched.
  11. *
  12. * @param $element String: element name
  13. * @param $attribs Array: Name=>value pairs. Values will be escaped.
  14. * @param $contents String: NULL to make an open tag only; '' for a contentless closed tag (default)
  15. * @param $allowShortTag Bool: whether '' in $contents will result in a contentless closed tag
  16. * @return string
  17. */
  18. public static function element( $element, $attribs = null, $contents = '', $allowShortTag = true ) {
  19. $out = '<' . $element;
  20. if( !is_null( $attribs ) ) {
  21. $out .= self::expandAttributes( $attribs );
  22. }
  23. if( is_null( $contents ) ) {
  24. $out .= '>';
  25. } else {
  26. if( $allowShortTag && $contents === '' ) {
  27. $out .= ' />';
  28. } else {
  29. $out .= '>' . htmlspecialchars( $contents ) . "</$element>";
  30. }
  31. }
  32. return $out;
  33. }
  34. /**
  35. * Given an array of ('attributename' => 'value'), it generates the code
  36. * to set the XML attributes : attributename="value".
  37. * The values are passed to Sanitizer::encodeAttribute.
  38. * Return null if no attributes given.
  39. * @param $attribs Array of attributes for an XML element
  40. */
  41. public static function expandAttributes( $attribs ) {
  42. $out = '';
  43. if( is_null( $attribs ) ) {
  44. return null;
  45. } elseif( is_array( $attribs ) ) {
  46. foreach( $attribs as $name => $val ) {
  47. $out .= " {$name}=\"" . Sanitizer::encodeAttribute( $val ) . '"';
  48. }
  49. return $out;
  50. } else {
  51. throw new MWException( 'Expected attribute array, got something else in ' . __METHOD__ );
  52. }
  53. }
  54. /**
  55. * Format an XML element as with self::element(), but run text through the
  56. * $wgContLang->normalize() validator first to ensure that no invalid UTF-8
  57. * is passed.
  58. *
  59. * @param $element String:
  60. * @param $attribs Array: Name=>value pairs. Values will be escaped.
  61. * @param $contents String: NULL to make an open tag only; '' for a contentless closed tag (default)
  62. * @return string
  63. */
  64. public static function elementClean( $element, $attribs = array(), $contents = '') {
  65. global $wgContLang;
  66. if( $attribs ) {
  67. $attribs = array_map( array( 'UtfNormal', 'cleanUp' ), $attribs );
  68. }
  69. if( $contents ) {
  70. wfProfileIn( __METHOD__ . '-norm' );
  71. $contents = $wgContLang->normalize( $contents );
  72. wfProfileOut( __METHOD__ . '-norm' );
  73. }
  74. return self::element( $element, $attribs, $contents );
  75. }
  76. /**
  77. * This opens an XML element
  78. *
  79. * @param $element String name of the element
  80. * @param $attribs array of attributes, see Xml::expandAttributes()
  81. * @return string
  82. */
  83. public static function openElement( $element, $attribs = null ) {
  84. return '<' . $element . self::expandAttributes( $attribs ) . '>';
  85. }
  86. /**
  87. * Shortcut to close an XML element
  88. * @param $element String element name
  89. * @return string
  90. */
  91. public static function closeElement( $element ) { return "</$element>"; }
  92. /**
  93. * Same as Xml::element(), but does not escape contents. Handy when the
  94. * content you have is already valid xml.
  95. *
  96. * @param $element String element name
  97. * @param $attribs array of attributes
  98. * @param $contents String content of the element
  99. * @return string
  100. */
  101. public static function tags( $element, $attribs = null, $contents ) {
  102. return self::openElement( $element, $attribs ) . $contents . "</$element>";
  103. }
  104. /**
  105. * Build a drop-down box for selecting a namespace
  106. *
  107. * @param $selected Mixed: Namespace which should be pre-selected
  108. * @param $all Mixed: Value of an item denoting all namespaces, or null to omit
  109. * @param $element_name String: value of the "name" attribute of the select tag
  110. * @param $label String: optional label to add to the field
  111. * @return string
  112. * @deprecated since 1.19
  113. */
  114. public static function namespaceSelector( $selected = '', $all = null, $element_name = 'namespace', $label = null ) {
  115. wfDeprecated( __METHOD__, '1.19' );
  116. return Html::namespaceSelector( array(
  117. 'selected' => $selected,
  118. 'all' => $all,
  119. 'label' => $label,
  120. ), array(
  121. 'name' => $element_name,
  122. 'id' => 'namespace',
  123. 'class' => 'namespaceselector',
  124. ) );
  125. }
  126. /**
  127. * Create a date selector
  128. *
  129. * @param $selected Mixed: the month which should be selected, default ''
  130. * @param $allmonths String: value of a special item denoting all month. Null to not include (default)
  131. * @param $id String: Element identifier
  132. * @return String: Html string containing the month selector
  133. */
  134. public static function monthSelector( $selected = '', $allmonths = null, $id = 'month' ) {
  135. global $wgLang;
  136. $options = array();
  137. if( is_null( $selected ) )
  138. $selected = '';
  139. if( !is_null( $allmonths ) )
  140. $options[] = self::option( wfMsg( 'monthsall' ), $allmonths, $selected === $allmonths );
  141. for( $i = 1; $i < 13; $i++ )
  142. $options[] = self::option( $wgLang->getMonthName( $i ), $i, $selected === $i );
  143. return self::openElement( 'select', array( 'id' => $id, 'name' => 'month', 'class' => 'mw-month-selector' ) )
  144. . implode( "\n", $options )
  145. . self::closeElement( 'select' );
  146. }
  147. /**
  148. * @param $year Integer
  149. * @param $month Integer
  150. * @return string Formatted HTML
  151. */
  152. public static function dateMenu( $year, $month ) {
  153. # Offset overrides year/month selection
  154. if( $month && $month !== -1 ) {
  155. $encMonth = intval( $month );
  156. } else {
  157. $encMonth = '';
  158. }
  159. if( $year ) {
  160. $encYear = intval( $year );
  161. } elseif( $encMonth ) {
  162. $thisMonth = intval( gmdate( 'n' ) );
  163. $thisYear = intval( gmdate( 'Y' ) );
  164. if( intval($encMonth) > $thisMonth ) {
  165. $thisYear--;
  166. }
  167. $encYear = $thisYear;
  168. } else {
  169. $encYear = '';
  170. }
  171. return Xml::label( wfMsg( 'year' ), 'year' ) . ' '.
  172. Xml::input( 'year', 4, $encYear, array('id' => 'year', 'maxlength' => 4) ) . ' '.
  173. Xml::label( wfMsg( 'month' ), 'month' ) . ' '.
  174. Xml::monthSelector( $encMonth, -1 );
  175. }
  176. /**
  177. * Construct a language selector appropriate for use in a form or preferences
  178. *
  179. * @param string $selected The language code of the selected language
  180. * @param boolean $customisedOnly If true only languages which have some content are listed
  181. * @param string $language The ISO code of the language to display the select list in (optional)
  182. * @return array containing 2 items: label HTML and select list HTML
  183. */
  184. public static function languageSelector( $selected, $customisedOnly = true, $language = null ) {
  185. global $wgLanguageCode;
  186. // If a specific language was requested and CLDR is installed, use it
  187. if ( $language && is_callable( array( 'LanguageNames', 'getNames' ) ) ) {
  188. if ( $customisedOnly ) {
  189. $listType = LanguageNames::LIST_MW_SUPPORTED; // Only pull names that have localisation in MediaWiki
  190. } else {
  191. $listType = LanguageNames::LIST_MW; // Pull all languages that are in Names.php
  192. }
  193. // Retrieve the list of languages in the requested language (via CLDR)
  194. $languages = LanguageNames::getNames(
  195. $language, // Code of the requested language
  196. LanguageNames::FALLBACK_NORMAL, // Use fallback chain
  197. $listType
  198. );
  199. } else {
  200. $languages = Language::getLanguageNames( $customisedOnly );
  201. }
  202. // Make sure the site language is in the list; a custom language code might not have a
  203. // 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 an Afrikaans interface 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 .= Xml::option( "$code - $name", $code, ($code == $selected) ) . "\n";
  217. }
  218. return array(
  219. Xml::label( wfMsg('yourlanguage'), 'wpUserLanguage' ),
  220. Xml::tags( 'select',
  221. array( 'id' => 'wpUserLanguage', 'name' => 'wpUserLanguage' ),
  222. $options
  223. )
  224. );
  225. }
  226. /**
  227. * Shortcut to make a span element
  228. * @param $text String content of the element, will be escaped
  229. * @param $class String class name of the span element
  230. * @param $attribs array other attributes
  231. * @return string
  232. */
  233. public static function span( $text, $class, $attribs = array() ) {
  234. return self::element( 'span', array( 'class' => $class ) + $attribs, $text );
  235. }
  236. /**
  237. * Shortcut to make a specific element with a class attribute
  238. * @param $text content of the element, will be escaped
  239. * @param $class class name of the span element
  240. * @param $tag string element name
  241. * @param $attribs array other attributes
  242. * @return string
  243. */
  244. public static function wrapClass( $text, $class, $tag = 'span', $attribs = array() ) {
  245. return self::tags( $tag, array( 'class' => $class ) + $attribs, $text );
  246. }
  247. /**
  248. * Convenience function to build an HTML text input field
  249. * @param $name String value of the name attribute
  250. * @param $size int value of the size attribute
  251. * @param $value mixed value of the value attribute
  252. * @param $attribs array other attributes
  253. * @return string HTML
  254. */
  255. public static function input( $name, $size = false, $value = false, $attribs = array() ) {
  256. $attributes = array( 'name' => $name );
  257. if( $size ) {
  258. $attributes['size'] = $size;
  259. }
  260. if( $value !== false ) { // maybe 0
  261. $attributes['value'] = $value;
  262. }
  263. return self::element( 'input', $attributes + $attribs );
  264. }
  265. /**
  266. * Convenience function to build an HTML password input field
  267. * @param $name string value of the name attribute
  268. * @param $size int value of the size attribute
  269. * @param $value mixed value of the value attribute
  270. * @param $attribs array other attributes
  271. * @return string HTML
  272. */
  273. public static function password( $name, $size = false, $value = false, $attribs = array() ) {
  274. return self::input( $name, $size, $value, array_merge( $attribs, array( 'type' => 'password' ) ) );
  275. }
  276. /**
  277. * Internal function for use in checkboxes and radio buttons and such.
  278. *
  279. * @param $name string
  280. * @param $present bool
  281. *
  282. * @return array
  283. */
  284. public static function attrib( $name, $present = true ) {
  285. return $present ? array( $name => $name ) : array();
  286. }
  287. /**
  288. * Convenience function to build an HTML checkbox
  289. * @param $name String value of the name attribute
  290. * @param $checked Bool Whether the checkbox is checked or not
  291. * @param $attribs Array other attributes
  292. * @return string HTML
  293. */
  294. public static function check( $name, $checked = false, $attribs=array() ) {
  295. return self::element( 'input', array_merge(
  296. array(
  297. 'name' => $name,
  298. 'type' => 'checkbox',
  299. 'value' => 1 ),
  300. self::attrib( 'checked', $checked ),
  301. $attribs ) );
  302. }
  303. /**
  304. * Convenience function to build an HTML radio button
  305. * @param $name String value of the name attribute
  306. * @param $value String value of the value attribute
  307. * @param $checked Bool Whether the checkbox is checked or not
  308. * @param $attribs Array other attributes
  309. * @return string HTML
  310. */
  311. public static function radio( $name, $value, $checked = false, $attribs = array() ) {
  312. return self::element( 'input', array(
  313. 'name' => $name,
  314. 'type' => 'radio',
  315. 'value' => $value ) + self::attrib( 'checked', $checked ) + $attribs );
  316. }
  317. /**
  318. * Convenience function to build an HTML form label
  319. * @param $label String text of the label
  320. * @param $id
  321. * @param $attribs Array an attribute array. This will usuall be
  322. * the same array as is passed to the corresponding input element,
  323. * so this function will cherry-pick appropriate attributes to
  324. * apply to the label as well; only class and title are applied.
  325. * @return string HTML
  326. */
  327. public static function label( $label, $id, $attribs = array() ) {
  328. $a = array( 'for' => $id );
  329. # FIXME avoid copy pasting below:
  330. if( isset( $attribs['class'] ) ){
  331. $a['class'] = $attribs['class'];
  332. }
  333. if( isset( $attribs['title'] ) ){
  334. $a['title'] = $attribs['title'];
  335. }
  336. return self::element( 'label', $a, $label );
  337. }
  338. /**
  339. * Convenience function to build an HTML text input field with a label
  340. * @param $label String text of the label
  341. * @param $name String value of the name attribute
  342. * @param $id String id of the input
  343. * @param $size Int|Bool value of the size attribute
  344. * @param $value String|Bool value of the value attribute
  345. * @param $attribs array other attributes
  346. * @return string HTML
  347. */
  348. public static function inputLabel( $label, $name, $id, $size=false, $value=false, $attribs = array() ) {
  349. list( $label, $input ) = self::inputLabelSep( $label, $name, $id, $size, $value, $attribs );
  350. return $label . '&#160;' . $input;
  351. }
  352. /**
  353. * Same as Xml::inputLabel() but return input and label in an array
  354. *
  355. * @param $label String
  356. * @param $name String
  357. * @param $id String
  358. * @param $size Int|Bool
  359. * @param $value String|Bool
  360. * @param $attribs array
  361. *
  362. * @return array
  363. */
  364. public static function inputLabelSep( $label, $name, $id, $size = false, $value = false, $attribs = array() ) {
  365. return array(
  366. Xml::label( $label, $id, $attribs ),
  367. self::input( $name, $size, $value, array( 'id' => $id ) + $attribs )
  368. );
  369. }
  370. /**
  371. * Convenience function to build an HTML checkbox with a label
  372. *
  373. * @param $label
  374. * @param $name
  375. * @param $id
  376. * @param $checked bool
  377. * @param $attribs array
  378. *
  379. * @return string HTML
  380. */
  381. public static function checkLabel( $label, $name, $id, $checked = false, $attribs = array() ) {
  382. return self::check( $name, $checked, array( 'id' => $id ) + $attribs ) .
  383. '&#160;' .
  384. self::label( $label, $id, $attribs );
  385. }
  386. /**
  387. * Convenience function to build an HTML radio button with a label
  388. *
  389. * @param $label
  390. * @param $name
  391. * @param $value
  392. * @param $id
  393. * @param $checked bool
  394. * @param $attribs array
  395. *
  396. * @return string HTML
  397. */
  398. public static function radioLabel( $label, $name, $value, $id, $checked = false, $attribs = array() ) {
  399. return self::radio( $name, $value, $checked, array( 'id' => $id ) + $attribs ) .
  400. '&#160;' .
  401. self::label( $label, $id, $attribs );
  402. }
  403. /**
  404. * Convenience function to build an HTML submit button
  405. * @param $value String: label text for the button
  406. * @param $attribs Array: optional custom attributes
  407. * @return string HTML
  408. */
  409. public static function submitButton( $value, $attribs = array() ) {
  410. return Html::element( 'input', array( 'type' => 'submit', 'value' => $value ) + $attribs );
  411. }
  412. /**
  413. * Convenience function to build an HTML drop-down list item.
  414. * @param $text String: text for this item
  415. * @param $value String: form submission value; if empty, use text
  416. * @param $selected boolean: if true, will be the default selected item
  417. * @param $attribs array: optional additional HTML attributes
  418. * @return string HTML
  419. */
  420. public static function option( $text, $value=null, $selected = false,
  421. $attribs = array() ) {
  422. if( !is_null( $value ) ) {
  423. $attribs['value'] = $value;
  424. }
  425. if( $selected ) {
  426. $attribs['selected'] = 'selected';
  427. }
  428. return Html::element( 'option', $attribs, $text );
  429. }
  430. /**
  431. * Build a drop-down box from a textual list.
  432. *
  433. * @param $name Mixed: Name and id for the drop-down
  434. * @param $list Mixed: Correctly formatted text (newline delimited) to be used to generate the options
  435. * @param $other Mixed: Text for the "Other reasons" option
  436. * @param $selected Mixed: Option which should be pre-selected
  437. * @param $class Mixed: CSS classes for the drop-down
  438. * @param $tabindex Mixed: Value of the tabindex attribute
  439. * @return string
  440. */
  441. public static function listDropDown( $name= '', $list = '', $other = '', $selected = '', $class = '', $tabindex = null ) {
  442. $optgroup = false;
  443. $options = self::option( $other, 'other', $selected === 'other' );
  444. foreach ( explode( "\n", $list ) as $option) {
  445. $value = trim( $option );
  446. if ( $value == '' ) {
  447. continue;
  448. } elseif ( substr( $value, 0, 1) == '*' && substr( $value, 1, 1) != '*' ) {
  449. // A new group is starting ...
  450. $value = trim( substr( $value, 1 ) );
  451. if( $optgroup ) $options .= self::closeElement('optgroup');
  452. $options .= self::openElement( 'optgroup', array( 'label' => $value ) );
  453. $optgroup = true;
  454. } elseif ( substr( $value, 0, 2) == '**' ) {
  455. // groupmember
  456. $value = trim( substr( $value, 2 ) );
  457. $options .= self::option( $value, $value, $selected === $value );
  458. } else {
  459. // groupless reason list
  460. if( $optgroup ) $options .= self::closeElement('optgroup');
  461. $options .= self::option( $value, $value, $selected === $value );
  462. $optgroup = false;
  463. }
  464. }
  465. if( $optgroup ) $options .= self::closeElement('optgroup');
  466. $attribs = array();
  467. if( $name ) {
  468. $attribs['id'] = $name;
  469. $attribs['name'] = $name;
  470. }
  471. if( $class ) {
  472. $attribs['class'] = $class;
  473. }
  474. if( $tabindex ) {
  475. $attribs['tabindex'] = $tabindex;
  476. }
  477. return Xml::openElement( 'select', $attribs )
  478. . "\n"
  479. . $options
  480. . "\n"
  481. . Xml::closeElement( 'select' );
  482. }
  483. /**
  484. * Shortcut for creating fieldsets.
  485. *
  486. * @param $legend Legend of the fieldset. If evaluates to false, legend is not added.
  487. * @param $content Pre-escaped content for the fieldset. If false, only open fieldset is returned.
  488. * @param $attribs array Any attributes to fieldset-element.
  489. *
  490. * @return string
  491. */
  492. public static function fieldset( $legend = false, $content = false, $attribs = array() ) {
  493. $s = Xml::openElement( 'fieldset', $attribs ) . "\n";
  494. if ( $legend ) {
  495. $s .= Xml::element( 'legend', null, $legend ) . "\n";
  496. }
  497. if ( $content !== false ) {
  498. $s .= $content . "\n";
  499. $s .= Xml::closeElement( 'fieldset' ) . "\n";
  500. }
  501. return $s;
  502. }
  503. /**
  504. * Shortcut for creating textareas.
  505. *
  506. * @param $name string The 'name' for the textarea
  507. * @param $content string Content for the textarea
  508. * @param $cols int The number of columns for the textarea
  509. * @param $rows int The number of rows for the textarea
  510. * @param $attribs array Any other attributes for the textarea
  511. *
  512. * @return string
  513. */
  514. public static function textarea( $name, $content, $cols = 40, $rows = 5, $attribs = array() ) {
  515. return self::element( 'textarea',
  516. array( 'name' => $name,
  517. 'id' => $name,
  518. 'cols' => $cols,
  519. 'rows' => $rows
  520. ) + $attribs,
  521. $content, false );
  522. }
  523. /**
  524. * Returns an escaped string suitable for inclusion in a string literal
  525. * for JavaScript source code.
  526. * Illegal control characters are assumed not to be present.
  527. *
  528. * @param $string String to escape
  529. * @return String
  530. */
  531. public static function escapeJsString( $string ) {
  532. // See ECMA 262 section 7.8.4 for string literal format
  533. $pairs = array(
  534. "\\" => "\\\\",
  535. "\"" => "\\\"",
  536. '\'' => '\\\'',
  537. "\n" => "\\n",
  538. "\r" => "\\r",
  539. # To avoid closing the element or CDATA section
  540. "<" => "\\x3c",
  541. ">" => "\\x3e",
  542. # To avoid any complaints about bad entity refs
  543. "&" => "\\x26",
  544. # Work around https://bugzilla.mozilla.org/show_bug.cgi?id=274152
  545. # Encode certain Unicode formatting chars so affected
  546. # versions of Gecko don't misinterpret our strings;
  547. # this is a common problem with Farsi text.
  548. "\xe2\x80\x8c" => "\\u200c", // ZERO WIDTH NON-JOINER
  549. "\xe2\x80\x8d" => "\\u200d", // ZERO WIDTH JOINER
  550. );
  551. return strtr( $string, $pairs );
  552. }
  553. /**
  554. * Encode a variable of unknown type to JavaScript.
  555. * Arrays are converted to JS arrays, objects are converted to JS associative
  556. * arrays (objects). So cast your PHP associative arrays to objects before
  557. * passing them to here.
  558. *
  559. * @param $value
  560. *
  561. * @return string
  562. */
  563. public static function encodeJsVar( $value ) {
  564. if ( is_bool( $value ) ) {
  565. $s = $value ? 'true' : 'false';
  566. } elseif ( is_null( $value ) ) {
  567. $s = 'null';
  568. } elseif ( is_int( $value ) || is_float( $value ) ) {
  569. $s = strval($value);
  570. } elseif ( is_array( $value ) && // Make sure it's not associative.
  571. array_keys($value) === range( 0, count($value) - 1 ) ||
  572. count($value) == 0
  573. ) {
  574. $s = '[';
  575. foreach ( $value as $elt ) {
  576. if ( $s != '[' ) {
  577. $s .= ',';
  578. }
  579. $s .= self::encodeJsVar( $elt );
  580. }
  581. $s .= ']';
  582. } elseif ( $value instanceof XmlJsCode ) {
  583. $s = $value->value;
  584. } elseif ( is_object( $value ) || is_array( $value ) ) {
  585. // Objects and associative arrays
  586. $s = '{';
  587. foreach ( (array)$value as $name => $elt ) {
  588. if ( $s != '{' ) {
  589. $s .= ',';
  590. }
  591. $s .= '"' . self::escapeJsString( $name ) . '":' .
  592. self::encodeJsVar( $elt );
  593. }
  594. $s .= '}';
  595. } else {
  596. $s = '"' . self::escapeJsString( $value ) . '"';
  597. }
  598. return $s;
  599. }
  600. /**
  601. * Create a call to a JavaScript function. The supplied arguments will be
  602. * encoded using Xml::encodeJsVar().
  603. *
  604. * @param $name String The name of the function to call, or a JavaScript expression
  605. * which evaluates to a function object which is called.
  606. * @param $args Array of arguments to pass to the function.
  607. *
  608. * @since 1.17
  609. *
  610. * @return string
  611. */
  612. public static function encodeJsCall( $name, $args ) {
  613. $s = "$name(";
  614. $first = true;
  615. foreach ( $args as $arg ) {
  616. if ( $first ) {
  617. $first = false;
  618. } else {
  619. $s .= ', ';
  620. }
  621. $s .= Xml::encodeJsVar( $arg );
  622. }
  623. $s .= ");\n";
  624. return $s;
  625. }
  626. /**
  627. * Check if a string is well-formed XML.
  628. * Must include the surrounding tag.
  629. *
  630. * @param $text String: string to test.
  631. * @return bool
  632. *
  633. * @todo Error position reporting return
  634. */
  635. public static function isWellFormed( $text ) {
  636. $parser = xml_parser_create( "UTF-8" );
  637. # case folding violates XML standard, turn it off
  638. xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
  639. if( !xml_parse( $parser, $text, true ) ) {
  640. //$err = xml_error_string( xml_get_error_code( $parser ) );
  641. //$position = xml_get_current_byte_index( $parser );
  642. //$fragment = $this->extractFragment( $html, $position );
  643. //$this->mXmlError = "$err at byte $position:\n$fragment";
  644. xml_parser_free( $parser );
  645. return false;
  646. }
  647. xml_parser_free( $parser );
  648. return true;
  649. }
  650. /**
  651. * Check if a string is a well-formed XML fragment.
  652. * Wraps fragment in an \<html\> bit and doctype, so it can be a fragment
  653. * and can use HTML named entities.
  654. *
  655. * @param $text String:
  656. * @return bool
  657. */
  658. public static function isWellFormedXmlFragment( $text ) {
  659. $html =
  660. Sanitizer::hackDocType() .
  661. '<html>' .
  662. $text .
  663. '</html>';
  664. return Xml::isWellFormed( $html );
  665. }
  666. /**
  667. * Replace " > and < with their respective HTML entities ( &quot;,
  668. * &gt;, &lt;)
  669. *
  670. * @param $in String: text that might contain HTML tags.
  671. * @return string Escaped string
  672. */
  673. public static function escapeTagsOnly( $in ) {
  674. return str_replace(
  675. array( '"', '>', '<' ),
  676. array( '&quot;', '&gt;', '&lt;' ),
  677. $in );
  678. }
  679. /**
  680. * Generate a form (without the opening form element).
  681. * Output optionally includes a submit button.
  682. * @param $fields Array Associative array, key is message corresponding to a description for the field (colon is in the message), value is appropriate input.
  683. * @param $submitLabel String A message containing a label for the submit button.
  684. * @return string HTML form.
  685. */
  686. public static function buildForm( $fields, $submitLabel = null ) {
  687. $form = '';
  688. $form .= "<table><tbody>";
  689. foreach( $fields as $labelmsg => $input ) {
  690. $id = "mw-$labelmsg";
  691. $form .= Xml::openElement( 'tr', array( 'id' => $id ) );
  692. $form .= Xml::tags( 'td', array('class' => 'mw-label'), wfMsgExt( $labelmsg, array('parseinline') ) );
  693. $form .= Xml::openElement( 'td', array( 'class' => 'mw-input' ) ) . $input . Xml::closeElement( 'td' );
  694. $form .= Xml::closeElement( 'tr' );
  695. }
  696. if( $submitLabel ) {
  697. $form .= Xml::openElement( 'tr' );
  698. $form .= Xml::tags( 'td', array(), '' );
  699. $form .= Xml::openElement( 'td', array( 'class' => 'mw-submit' ) ) . Xml::submitButton( wfMsg( $submitLabel ) ) . Xml::closeElement( 'td' );
  700. $form .= Xml::closeElement( 'tr' );
  701. }
  702. $form .= "</tbody></table>";
  703. return $form;
  704. }
  705. /**
  706. * Build a table of data
  707. * @param $rows array An array of arrays of strings, each to be a row in a table
  708. * @param $attribs array An array of attributes to apply to the table tag [optional]
  709. * @param $headers array An array of strings to use as table headers [optional]
  710. * @return string
  711. */
  712. public static function buildTable( $rows, $attribs = array(), $headers = null ) {
  713. $s = Xml::openElement( 'table', $attribs );
  714. if ( is_array( $headers ) ) {
  715. $s .= Xml::openElement( 'thead', $attribs );
  716. foreach( $headers as $id => $header ) {
  717. $attribs = array();
  718. if ( is_string( $id ) ) {
  719. $attribs['id'] = $id;
  720. }
  721. $s .= Xml::element( 'th', $attribs, $header );
  722. }
  723. $s .= Xml::closeElement( 'thead' );
  724. }
  725. foreach( $rows as $id => $row ) {
  726. $attribs = array();
  727. if ( is_string( $id ) ) {
  728. $attribs['id'] = $id;
  729. }
  730. $s .= Xml::buildTableRow( $attribs, $row );
  731. }
  732. $s .= Xml::closeElement( 'table' );
  733. return $s;
  734. }
  735. /**
  736. * Build a row for a table
  737. * @param $attribs array An array of attributes to apply to the tr tag
  738. * @param $cells array An array of strings to put in <td>
  739. * @return string
  740. */
  741. public static function buildTableRow( $attribs, $cells ) {
  742. $s = Xml::openElement( 'tr', $attribs );
  743. foreach( $cells as $id => $cell ) {
  744. $attribs = array();
  745. if ( is_string( $id ) ) {
  746. $attribs['id'] = $id;
  747. }
  748. $s .= Xml::element( 'td', $attribs, $cell );
  749. }
  750. $s .= Xml::closeElement( 'tr' );
  751. return $s;
  752. }
  753. }
  754. class XmlSelect {
  755. protected $options = array();
  756. protected $default = false;
  757. protected $attributes = array();
  758. public function __construct( $name = false, $id = false, $default = false ) {
  759. if ( $name ) {
  760. $this->setAttribute( 'name', $name );
  761. }
  762. if ( $id ) {
  763. $this->setAttribute( 'id', $id );
  764. }
  765. if ( $default !== false ) {
  766. $this->default = $default;
  767. }
  768. }
  769. /**
  770. * @param $default
  771. */
  772. public function setDefault( $default ) {
  773. $this->default = $default;
  774. }
  775. /**
  776. * @param $name string
  777. * @param $value
  778. */
  779. public function setAttribute( $name, $value ) {
  780. $this->attributes[$name] = $value;
  781. }
  782. /**
  783. * @param $name
  784. * @return array|null
  785. */
  786. public function getAttribute( $name ) {
  787. if ( isset( $this->attributes[$name] ) ) {
  788. return $this->attributes[$name];
  789. } else {
  790. return null;
  791. }
  792. }
  793. /**
  794. * @param $name
  795. * @param $value bool
  796. */
  797. public function addOption( $name, $value = false ) {
  798. // Stab stab stab
  799. $value = ($value !== false) ? $value : $name;
  800. $this->options[] = array( $name => $value );
  801. }
  802. /**
  803. * This accepts an array of form
  804. * label => value
  805. * label => ( label => value, label => value )
  806. *
  807. * @param $options
  808. */
  809. public function addOptions( $options ) {
  810. $this->options[] = $options;
  811. }
  812. /**
  813. * This accepts an array of form
  814. * label => value
  815. * label => ( label => value, label => value )
  816. *
  817. * @param $options
  818. * @param bool $default
  819. * @return string
  820. */
  821. static function formatOptions( $options, $default = false ) {
  822. $data = '';
  823. foreach( $options as $label => $value ) {
  824. if ( is_array( $value ) ) {
  825. $contents = self::formatOptions( $value, $default );
  826. $data .= Html::rawElement( 'optgroup', array( 'label' => $label ), $contents ) . "\n";
  827. } else {
  828. $data .= Xml::option( $label, $value, $value === $default ) . "\n";
  829. }
  830. }
  831. return $data;
  832. }
  833. /**
  834. * @return string
  835. */
  836. public function getHTML() {
  837. $contents = '';
  838. foreach ( $this->options as $options ) {
  839. $contents .= self::formatOptions( $options, $this->default );
  840. }
  841. return Html::rawElement( 'select', $this->attributes, rtrim( $contents ) );
  842. }
  843. }
  844. /**
  845. * A wrapper class which causes Xml::encodeJsVar() and Xml::encodeJsCall() to
  846. * interpret a given string as being a JavaScript expression, instead of string
  847. * data.
  848. *
  849. * Example:
  850. *
  851. * Xml::encodeJsVar( new XmlJsCode( 'a + b' ) );
  852. *
  853. * Returns "a + b".
  854. * @since 1.17
  855. */
  856. class XmlJsCode {
  857. public $value;
  858. function __construct( $value ) {
  859. $this->value = $value;
  860. }
  861. }