XliffUtils.php 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Translation\Util;
  11. use Symfony\Component\Translation\Exception\InvalidArgumentException;
  12. use Symfony\Component\Translation\Exception\InvalidResourceException;
  13. /**
  14. * Provides some utility methods for XLIFF translation files, such as validating
  15. * their contents according to the XSD schema.
  16. *
  17. * @author Fabien Potencier <fabien@symfony.com>
  18. */
  19. class XliffUtils
  20. {
  21. /**
  22. * Gets xliff file version based on the root "version" attribute.
  23. *
  24. * Defaults to 1.2 for backwards compatibility.
  25. *
  26. * @throws InvalidArgumentException
  27. */
  28. public static function getVersionNumber(\DOMDocument $dom): string
  29. {
  30. foreach ($dom->getElementsByTagName('xliff') as $xliff) {
  31. $version = $xliff->attributes->getNamedItem('version');
  32. if ($version) {
  33. return $version->nodeValue;
  34. }
  35. $namespace = $xliff->attributes->getNamedItem('xmlns');
  36. if ($namespace) {
  37. if (0 !== substr_compare('urn:oasis:names:tc:xliff:document:', $namespace->nodeValue, 0, 34)) {
  38. throw new InvalidArgumentException(\sprintf('Not a valid XLIFF namespace "%s".', $namespace));
  39. }
  40. return substr($namespace, 34);
  41. }
  42. }
  43. // Falls back to v1.2
  44. return '1.2';
  45. }
  46. /**
  47. * Validates and parses the given file into a DOMDocument.
  48. *
  49. * @throws InvalidResourceException
  50. */
  51. public static function validateSchema(\DOMDocument $dom): array
  52. {
  53. $xliffVersion = static::getVersionNumber($dom);
  54. $internalErrors = libxml_use_internal_errors(true);
  55. if ($shouldEnable = self::shouldEnableEntityLoader()) {
  56. $disableEntities = libxml_disable_entity_loader(false);
  57. }
  58. try {
  59. $isValid = @$dom->schemaValidateSource(self::getSchema($xliffVersion));
  60. if (!$isValid) {
  61. return self::getXmlErrors($internalErrors);
  62. }
  63. } finally {
  64. if ($shouldEnable) {
  65. libxml_disable_entity_loader($disableEntities);
  66. }
  67. }
  68. $dom->normalizeDocument();
  69. libxml_clear_errors();
  70. libxml_use_internal_errors($internalErrors);
  71. return [];
  72. }
  73. public static function getErrorsAsString(array $xmlErrors): string
  74. {
  75. $errorsAsString = '';
  76. foreach ($xmlErrors as $error) {
  77. $errorsAsString .= \sprintf("[%s %s] %s (in %s - line %d, column %d)\n",
  78. \LIBXML_ERR_WARNING === $error['level'] ? 'WARNING' : 'ERROR',
  79. $error['code'],
  80. $error['message'],
  81. $error['file'],
  82. $error['line'],
  83. $error['column']
  84. );
  85. }
  86. return $errorsAsString;
  87. }
  88. private static function shouldEnableEntityLoader(): bool
  89. {
  90. static $dom, $schema;
  91. if (null === $dom) {
  92. $dom = new \DOMDocument();
  93. $dom->loadXML('<?xml version="1.0"?><test/>');
  94. $tmpfile = tempnam(sys_get_temp_dir(), 'symfony');
  95. register_shutdown_function(static function () use ($tmpfile) {
  96. @unlink($tmpfile);
  97. });
  98. $schema = '<?xml version="1.0" encoding="utf-8"?>
  99. <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  100. <xsd:include schemaLocation="'.self::getFileUrl($tmpfile).'" />
  101. </xsd:schema>';
  102. file_put_contents($tmpfile, '<?xml version="1.0" encoding="utf-8"?>
  103. <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  104. <xsd:element name="test" type="testType" />
  105. <xsd:complexType name="testType"/>
  106. </xsd:schema>');
  107. }
  108. return !@$dom->schemaValidateSource($schema);
  109. }
  110. private static function getFileUrl(string $path): string
  111. {
  112. if ('\\' === \DIRECTORY_SEPARATOR) {
  113. $parts = explode('/', str_replace('\\', '/', $path));
  114. $drive = array_shift($parts).'/';
  115. } else {
  116. $parts = explode('/', $path);
  117. $drive = '';
  118. }
  119. return 'file:///'.$drive.implode('/', array_map('rawurlencode', $parts));
  120. }
  121. private static function getSchema(string $xliffVersion): string
  122. {
  123. if ('1.2' === $xliffVersion) {
  124. $schemaSource = file_get_contents(__DIR__.'/../Resources/schemas/xliff-core-1.2-transitional.xsd');
  125. $xmlUri = 'http://www.w3.org/2001/xml.xsd';
  126. } elseif ('2.0' === $xliffVersion) {
  127. $schemaSource = file_get_contents(__DIR__.'/../Resources/schemas/xliff-core-2.0.xsd');
  128. $xmlUri = 'informativeCopiesOf3rdPartySchemas/w3c/xml.xsd';
  129. } else {
  130. throw new InvalidArgumentException(\sprintf('No support implemented for loading XLIFF version "%s".', $xliffVersion));
  131. }
  132. return self::fixXmlLocation($schemaSource, $xmlUri);
  133. }
  134. /**
  135. * Internally changes the URI of a dependent xsd to be loaded locally.
  136. */
  137. private static function fixXmlLocation(string $schemaSource, string $xmlUri): string
  138. {
  139. $path = __DIR__.'/../Resources/schemas/xml.xsd';
  140. if (0 === stripos($path, 'phar://')) {
  141. if ($tmpfile = tempnam(sys_get_temp_dir(), 'symfony')) {
  142. copy($path, $tmpfile);
  143. $newPath = self::getFileUrl($tmpfile);
  144. } else {
  145. $parts = explode('/', '\\' === \DIRECTORY_SEPARATOR ? str_replace('\\', '/', $path) : $path);
  146. array_shift($parts);
  147. $drive = '\\' === \DIRECTORY_SEPARATOR ? array_shift($parts).'/' : '';
  148. $newPath = 'phar:///'.$drive.implode('/', array_map('rawurlencode', $parts));
  149. }
  150. } else {
  151. $newPath = self::getFileUrl($path);
  152. }
  153. return str_replace($xmlUri, $newPath, $schemaSource);
  154. }
  155. /**
  156. * Returns the XML errors of the internal XML parser.
  157. */
  158. private static function getXmlErrors(bool $internalErrors): array
  159. {
  160. $errors = [];
  161. foreach (libxml_get_errors() as $error) {
  162. $errors[] = [
  163. 'level' => \LIBXML_ERR_WARNING == $error->level ? 'WARNING' : 'ERROR',
  164. 'code' => $error->code,
  165. 'message' => trim($error->message),
  166. 'file' => $error->file ?: 'n/a',
  167. 'line' => $error->line,
  168. 'column' => $error->column,
  169. ];
  170. }
  171. libxml_clear_errors();
  172. libxml_use_internal_errors($internalErrors);
  173. return $errors;
  174. }
  175. }