/third_party/daisydiff/src/Xml.php

https://github.com/testlinkjp/testlink-japanese-localization · PHP · 589 lines · 490 code · 28 blank · 71 comment · 18 complexity · 5d7f9f1d677fd4e2c518b3370459a210 MD5 · raw file

  1. <?php
  2. /**
  3. * Module of static functions for generating XML
  4. */
  5. include_once 'Sanitizer.php';
  6. class Xml {
  7. /**
  8. * Format an XML element with given attributes and, optionally, text content.
  9. * Element and attribute names are assumed to be ready for literal inclusion.
  10. * Strings are assumed to not contain XML-illegal characters; special
  11. * characters (<, >, &) are escaped but illegals are not touched.
  12. *
  13. * @param $element String: element name
  14. * @param $attribs Array: Name=>value pairs. Values will be escaped.
  15. * @param $contents String: NULL to make an open tag only; '' for a contentless closed tag (default)
  16. * @param $allowShortTag Bool: whether '' in $contents will result in a contentless closed tag
  17. * @return string
  18. */
  19. public static function element( $element, $attribs = null, $contents = '', $allowShortTag = true ) {
  20. $out = '<' . $element;
  21. if( !is_null( $attribs ) ) {
  22. $out .= self::expandAttributes( $attribs );
  23. }
  24. if( is_null( $contents ) ) {
  25. $out .= '>';
  26. } else {
  27. if( $allowShortTag && $contents === '' ) {
  28. $out .= ' />';
  29. } else {
  30. $out .= '>' . htmlspecialchars( $contents ) . "</$element>";
  31. }
  32. }
  33. return $out;
  34. }
  35. /**
  36. * Given an array of ('attributename' => 'value'), it generates the code
  37. * to set the XML attributes : attributename="value".
  38. * The values are passed to Sanitizer::encodeAttribute.
  39. * Return null if no attributes given.
  40. * @param $attribs Array of attributes for an XML element
  41. */
  42. public static function expandAttributes( $attribs ) {
  43. $out = '';
  44. if( is_null( $attribs ) ) {
  45. return null;
  46. } elseif( is_array( $attribs ) ) {
  47. foreach( $attribs as $name => $val )
  48. $out .= " {$name}=\"" . Sanitizer::encodeAttribute( $val ) . '"';
  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. * UtfNormal::cleanUp() 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. if( $attribs ) {
  66. $attribs = array_map( array( 'UtfNormal', 'cleanUp' ), $attribs );
  67. }
  68. if( $contents ) {
  69. $contents = UtfNormal::cleanUp( $contents );
  70. }
  71. return self::element( $element, $attribs, $contents );
  72. }
  73. /**
  74. * This opens an XML element
  75. *
  76. * @param $element name of the element
  77. * @param $attribs array of attributes, see Xml::expandAttributes()
  78. * @return string
  79. */
  80. public static function openElement( $element, $attribs = null ) {
  81. return '<' . $element . self::expandAttributes( $attribs ) . '>';
  82. }
  83. /**
  84. * Shortcut to close an XML element
  85. * @param $element element name
  86. * @return string
  87. */
  88. public static function closeElement( $element ) { return "</$element>"; }
  89. /**
  90. * Same as Xml::element(), but does not escape contents. Handy when the
  91. * content you have is already valid xml.
  92. *
  93. * @param $element element name
  94. * @param $attribs array of attributes
  95. * @param $contents content of the element
  96. * @return string
  97. */
  98. public static function tags( $element, $attribs = null, $contents ) {
  99. return self::openElement( $element, $attribs ) . $contents . "</$element>";
  100. }
  101. /**
  102. * Shortcut to make a span element
  103. * @param $text content of the element, will be escaped
  104. * @param $class class name of the span element
  105. * @param $attribs other attributes
  106. * @return string
  107. */
  108. public static function span( $text, $class, $attribs=array() ) {
  109. return self::element( 'span', array( 'class' => $class ) + $attribs, $text );
  110. }
  111. /**
  112. * Shortcut to make a specific element with a class attribute
  113. * @param $text content of the element, will be escaped
  114. * @param $class class name of the span element
  115. * @param $tag element name
  116. * @param $attribs other attributes
  117. * @return string
  118. */
  119. public static function wrapClass( $text, $class, $tag='span', $attribs=array() ) {
  120. return self::tags( $tag, array( 'class' => $class ) + $attribs, $text );
  121. }
  122. /**
  123. * Convenience function to build an HTML text input field
  124. * @param $name value of the name attribute
  125. * @param $size value of the size attribute
  126. * @param $value value of the value attribute
  127. * @param $attribs other attributes
  128. * @return string HTML
  129. */
  130. public static function input( $name, $size=false, $value=false, $attribs=array() ) {
  131. return self::element( 'input', array(
  132. 'name' => $name,
  133. 'size' => $size,
  134. 'value' => $value ) + $attribs );
  135. }
  136. /**
  137. * Convenience function to build an HTML password input field
  138. * @param $name value of the name attribute
  139. * @param $size value of the size attribute
  140. * @param $value value of the value attribute
  141. * @param $attribs other attributes
  142. * @return string HTML
  143. */
  144. public static function password( $name, $size=false, $value=false, $attribs=array() ) {
  145. return self::input( $name, $size, $value, array_merge($attribs, array('type' => 'password')));
  146. }
  147. /**
  148. * Internal function for use in checkboxes and radio buttons and such.
  149. * @return array
  150. */
  151. public static function attrib( $name, $present = true ) {
  152. return $present ? array( $name => $name ) : array();
  153. }
  154. /**
  155. * Convenience function to build an HTML checkbox
  156. * @param $name value of the name attribute
  157. * @param $checked Whether the checkbox is checked or not
  158. * @param $attribs other attributes
  159. * @return string HTML
  160. */
  161. public static function check( $name, $checked=false, $attribs=array() ) {
  162. return self::element( 'input', array_merge(
  163. array(
  164. 'name' => $name,
  165. 'type' => 'checkbox',
  166. 'value' => 1 ),
  167. self::attrib( 'checked', $checked ),
  168. $attribs ) );
  169. }
  170. /**
  171. * Convenience function to build an HTML radio button
  172. * @param $name value of the name attribute
  173. * @param $value value of the value attribute
  174. * @param $checked Whether the checkbox is checked or not
  175. * @param $attribs other attributes
  176. * @return string HTML
  177. */
  178. public static function radio( $name, $value, $checked=false, $attribs=array() ) {
  179. return self::element( 'input', array(
  180. 'name' => $name,
  181. 'type' => 'radio',
  182. 'value' => $value ) + self::attrib( 'checked', $checked ) + $attribs );
  183. }
  184. /**
  185. * Convenience function to build an HTML form label
  186. * @param $label text of the label
  187. * @param $id
  188. * @return string HTML
  189. */
  190. public static function label( $label, $id ) {
  191. return self::element( 'label', array( 'for' => $id ), $label );
  192. }
  193. /**
  194. * Convenience function to build an HTML text input field with a label
  195. * @param $label text of the label
  196. * @param $name value of the name attribute
  197. * @param $id id of the input
  198. * @param $size value of the size attribute
  199. * @param $value value of the value attribute
  200. * @param $attribs other attributes
  201. * @return string HTML
  202. */
  203. public static function inputLabel( $label, $name, $id, $size=false, $value=false, $attribs=array() ) {
  204. list( $label, $input ) = self::inputLabelSep( $label, $name, $id, $size, $value, $attribs );
  205. return $label . '&nbsp;' . $input;
  206. }
  207. /**
  208. * Same as Xml::inputLabel() but return input and label in an array
  209. */
  210. public static function inputLabelSep( $label, $name, $id, $size=false, $value=false, $attribs=array() ) {
  211. return array(
  212. Xml::label( $label, $id ),
  213. self::input( $name, $size, $value, array( 'id' => $id ) + $attribs )
  214. );
  215. }
  216. /**
  217. * Convenience function to build an HTML checkbox with a label
  218. * @return string HTML
  219. */
  220. public static function checkLabel( $label, $name, $id, $checked=false, $attribs=array() ) {
  221. return self::check( $name, $checked, array( 'id' => $id ) + $attribs ) .
  222. '&nbsp;' .
  223. self::label( $label, $id );
  224. }
  225. /**
  226. * Convenience function to build an HTML radio button with a label
  227. * @return string HTML
  228. */
  229. public static function radioLabel( $label, $name, $value, $id, $checked=false, $attribs=array() ) {
  230. return self::radio( $name, $value, $checked, array( 'id' => $id ) + $attribs ) .
  231. '&nbsp;' .
  232. self::label( $label, $id );
  233. }
  234. /**
  235. * Convenience function to build an HTML submit button
  236. * @param $value String: label text for the button
  237. * @param $attribs Array: optional custom attributes
  238. * @return string HTML
  239. */
  240. public static function submitButton( $value, $attribs=array() ) {
  241. return self::element( 'input', array( 'type' => 'submit', 'value' => $value ) + $attribs );
  242. }
  243. /**
  244. * Convenience function to build an HTML hidden form field.
  245. * @param $name String: name attribute for the field
  246. * @param $value String: value for the hidden field
  247. * @param $attribs Array: optional custom attributes
  248. * @return string HTML
  249. */
  250. public static function hidden( $name, $value, $attribs=array() ) {
  251. return self::element( 'input', array(
  252. 'name' => $name,
  253. 'type' => 'hidden',
  254. 'value' => $value ) + $attribs );
  255. }
  256. /**
  257. * Convenience function to build an HTML drop-down list item.
  258. * @param $text String: text for this item
  259. * @param $value String: form submission value; if empty, use text
  260. * @param $selected boolean: if true, will be the default selected item
  261. * @param $attribs array: optional additional HTML attributes
  262. * @return string HTML
  263. */
  264. public static function option( $text, $value=null, $selected=false,
  265. $attribs=array() ) {
  266. if( !is_null( $value ) ) {
  267. $attribs['value'] = $value;
  268. }
  269. if( $selected ) {
  270. $attribs['selected'] = 'selected';
  271. }
  272. return self::element( 'option', $attribs, $text );
  273. }
  274. /**
  275. * Build a drop-down box from a textual list.
  276. *
  277. * @param $name Mixed: Name and id for the drop-down
  278. * @param $class Mixed: CSS classes for the drop-down
  279. * @param $other Mixed: Text for the "Other reasons" option
  280. * @param $list Mixed: Correctly formatted text to be used to generate the options
  281. * @param $selected Mixed: Option which should be pre-selected
  282. * @param $tabindex Mixed: Value of the tabindex attribute
  283. * @return string
  284. */
  285. public static function listDropDown( $name= '', $list = '', $other = '', $selected = '', $class = '', $tabindex = Null ) {
  286. $options = '';
  287. $optgroup = false;
  288. $options = self::option( $other, 'other', $selected === 'other' );
  289. foreach ( explode( "\n", $list ) as $option) {
  290. $value = trim( $option );
  291. if ( $value == '' ) {
  292. continue;
  293. } elseif ( substr( $value, 0, 1) == '*' && substr( $value, 1, 1) != '*' ) {
  294. // A new group is starting ...
  295. $value = trim( substr( $value, 1 ) );
  296. if( $optgroup ) $options .= self::closeElement('optgroup');
  297. $options .= self::openElement( 'optgroup', array( 'label' => $value ) );
  298. $optgroup = true;
  299. } elseif ( substr( $value, 0, 2) == '**' ) {
  300. // groupmember
  301. $value = trim( substr( $value, 2 ) );
  302. $options .= self::option( $value, $value, $selected === $value );
  303. } else {
  304. // groupless reason list
  305. if( $optgroup ) $options .= self::closeElement('optgroup');
  306. $options .= self::option( $value, $value, $selected === $value );
  307. $optgroup = false;
  308. }
  309. }
  310. if( $optgroup ) $options .= self::closeElement('optgroup');
  311. $attribs = array();
  312. if( $name ) {
  313. $attribs['id'] = $name;
  314. $attribs['name'] = $name;
  315. }
  316. if( $class ) {
  317. $attribs['class'] = $class;
  318. }
  319. if( $tabindex ) {
  320. $attribs['tabindex'] = $tabindex;
  321. }
  322. return Xml::openElement( 'select', $attribs )
  323. . "\n"
  324. . $options
  325. . "\n"
  326. . Xml::closeElement( 'select' );
  327. }
  328. /**
  329. * Shortcut for creating fieldsets.
  330. *
  331. * @param $legend Legend of the fieldset. If evaluates to false, legend is not added.
  332. * @param $content Pre-escaped content for the fieldset. If false, only open fieldset is returned.
  333. * @param $attribs Any attributes to fieldset-element.
  334. */
  335. public static function fieldset( $legend = false, $content = false, $attribs = array() ) {
  336. $s = Xml::openElement( 'fieldset', $attribs ) . "\n";
  337. if ( $legend ) {
  338. $s .= Xml::element( 'legend', null, $legend ) . "\n";
  339. }
  340. if ( $content !== false ) {
  341. $s .= $content . "\n";
  342. $s .= Xml::closeElement( 'fieldset' ) . "\n";
  343. }
  344. return $s;
  345. }
  346. /**
  347. * Shortcut for creating textareas.
  348. *
  349. * @param $name The 'name' for the textarea
  350. * @param $content Content for the textarea
  351. * @param $cols The number of columns for the textarea
  352. * @param $rows The number of rows for the textarea
  353. * @param $attribs Any other attributes for the textarea
  354. */
  355. public static function textarea( $name, $content, $cols = 40, $rows = 5, $attribs = array() ) {
  356. return self::element( 'textarea',
  357. array( 'name' => $name,
  358. 'id' => $name,
  359. 'cols' => $cols,
  360. 'rows' => $rows
  361. ) + $attribs,
  362. $content, false );
  363. }
  364. /**
  365. * Returns an escaped string suitable for inclusion in a string literal
  366. * for JavaScript source code.
  367. * Illegal control characters are assumed not to be present.
  368. *
  369. * @param $string String to escape
  370. * @return String
  371. */
  372. public static function escapeJsString( $string ) {
  373. // See ECMA 262 section 7.8.4 for string literal format
  374. $pairs = array(
  375. "\\" => "\\\\",
  376. "\"" => "\\\"",
  377. '\'' => '\\\'',
  378. "\n" => "\\n",
  379. "\r" => "\\r",
  380. # To avoid closing the element or CDATA section
  381. "<" => "\\x3c",
  382. ">" => "\\x3e",
  383. # To avoid any complaints about bad entity refs
  384. "&" => "\\x26",
  385. # Work around https://bugzilla.mozilla.org/show_bug.cgi?id=274152
  386. # Encode certain Unicode formatting chars so affected
  387. # versions of Gecko don't misinterpret our strings;
  388. # this is a common problem with Farsi text.
  389. "\xe2\x80\x8c" => "\\u200c", // ZERO WIDTH NON-JOINER
  390. "\xe2\x80\x8d" => "\\u200d", // ZERO WIDTH JOINER
  391. );
  392. return strtr( $string, $pairs );
  393. }
  394. /**
  395. * Encode a variable of unknown type to JavaScript.
  396. * Arrays are converted to JS arrays, objects are converted to JS associative
  397. * arrays (objects). So cast your PHP associative arrays to objects before
  398. * passing them to here.
  399. */
  400. public static function encodeJsVar( $value ) {
  401. if ( is_bool( $value ) ) {
  402. $s = $value ? 'true' : 'false';
  403. } elseif ( is_null( $value ) ) {
  404. $s = 'null';
  405. } elseif ( is_int( $value ) ) {
  406. $s = $value;
  407. } elseif ( is_array( $value ) ) {
  408. $s = '[';
  409. foreach ( $value as $elt ) {
  410. if ( $s != '[' ) {
  411. $s .= ', ';
  412. }
  413. $s .= self::encodeJsVar( $elt );
  414. }
  415. $s .= ']';
  416. } elseif ( is_object( $value ) ) {
  417. $s = '{';
  418. foreach ( (array)$value as $name => $elt ) {
  419. if ( $s != '{' ) {
  420. $s .= ', ';
  421. }
  422. $s .= '"' . self::escapeJsString( $name ) . '": ' .
  423. self::encodeJsVar( $elt );
  424. }
  425. $s .= '}';
  426. } else {
  427. $s = '"' . self::escapeJsString( $value ) . '"';
  428. }
  429. return $s;
  430. }
  431. /**
  432. * Check if a string is well-formed XML.
  433. * Must include the surrounding tag.
  434. *
  435. * @param $text String: string to test.
  436. * @return bool
  437. *
  438. * @todo Error position reporting return
  439. */
  440. public static function isWellFormed( $text ) {
  441. $parser = xml_parser_create( "UTF-8" );
  442. # case folding violates XML standard, turn it off
  443. xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
  444. if( !xml_parse( $parser, $text, true ) ) {
  445. //$err = xml_error_string( xml_get_error_code( $parser ) );
  446. //$position = xml_get_current_byte_index( $parser );
  447. //$fragment = $this->extractFragment( $html, $position );
  448. //$this->mXmlError = "$err at byte $position:\n$fragment";
  449. xml_parser_free( $parser );
  450. return false;
  451. }
  452. xml_parser_free( $parser );
  453. return true;
  454. }
  455. /**
  456. * Check if a string is a well-formed XML fragment.
  457. * Wraps fragment in an \<html\> bit and doctype, so it can be a fragment
  458. * and can use HTML named entities.
  459. *
  460. * @param $text String:
  461. * @return bool
  462. */
  463. public static function isWellFormedXmlFragment( $text ) {
  464. $html =
  465. Sanitizer::hackDocType() .
  466. '<html>' .
  467. $text .
  468. '</html>';
  469. return Xml::isWellFormed( $html );
  470. }
  471. /**
  472. * Replace " > and < with their respective HTML entities ( &quot;,
  473. * &gt;, &lt;)
  474. *
  475. * @param $in String: text that might contain HTML tags.
  476. * @return string Escaped string
  477. */
  478. public static function escapeTagsOnly( $in ) {
  479. return str_replace(
  480. array( '"', '>', '<' ),
  481. array( '&quot;', '&gt;', '&lt;' ),
  482. $in );
  483. }
  484. /**
  485. * Generate a form (without the opening form element).
  486. * Output optionally includes a submit button.
  487. * @param $fields Associative array, key is html corresponding to a description for the field, value is appropriate input.
  488. * @param $submitLabel Label for the submit button.
  489. * @return string HTML form.
  490. */
  491. public static function buildForm( $fields, $submitLabel = null ) {
  492. $form = '';
  493. $form .= "<table><tbody>";
  494. foreach( $fields as $labelHtml => $input ) {
  495. $id = "mw-$labelHtml";
  496. $form .= Xml::openElement( 'tr', array( 'id' => $id ) );
  497. $form .= Xml::tags( 'td', array('class' => 'mw-label'), $labelHtml);
  498. $form .= Xml::openElement( 'td', array( 'class' => 'mw-input' ) ) . $input . Xml::closeElement( 'td' );
  499. $form .= Xml::closeElement( 'tr' );
  500. }
  501. if( $submitLabel ) {
  502. $form .= Xml::openElement( 'tr', array( 'id' => $id ) );
  503. $form .= Xml::tags( 'td', array(), '' );
  504. $form .= Xml::openElement( 'td', array( 'class' => 'mw-submit' ) ) . Xml::submitButton( $submitLabel ) . Xml::closeElement( 'td' );
  505. $form .= Xml::closeElement( 'tr' );
  506. }
  507. $form .= "</tbody></table>";
  508. return $form;
  509. }
  510. }
  511. class XmlSelect {
  512. protected $options = array();
  513. protected $default = false;
  514. protected $attributes = array();
  515. public function __construct( $name = false, $id = false, $default = false ) {
  516. if ( $name ) $this->setAttribute( 'name', $name );
  517. if ( $id ) $this->setAttribute( 'id', $id );
  518. if ( $default ) $this->default = $default;
  519. }
  520. public function setDefault( $default ) {
  521. $this->default = $default;
  522. }
  523. public function setAttribute( $name, $value ) {
  524. $this->attributes[$name] = $value;
  525. }
  526. public function addOption( $name, $value = false ) {
  527. // Stab stab stab
  528. $value = ($value !== false) ? $value : $name;
  529. $this->options[] = Xml::option( $name, $value, $value === $this->default );
  530. }
  531. public function getHTML() {
  532. return Xml::tags( 'select', $this->attributes, implode( "\n", $this->options ) );
  533. }
  534. }