XliffFileLoader.php 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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\Loader;
  11. use Symfony\Component\Config\Util\XmlUtils;
  12. use Symfony\Component\Translation\MessageCatalogue;
  13. use Symfony\Component\Translation\Exception\InvalidResourceException;
  14. use Symfony\Component\Translation\Exception\NotFoundResourceException;
  15. use Symfony\Component\Translation\Exception\InvalidArgumentException;
  16. use Symfony\Component\Config\Resource\FileResource;
  17. /**
  18. * XliffFileLoader loads translations from XLIFF files.
  19. *
  20. * @author Fabien Potencier <fabien@symfony.com>
  21. */
  22. class XliffFileLoader implements LoaderInterface
  23. {
  24. /**
  25. * {@inheritdoc}
  26. */
  27. public function load($resource, $locale, $domain = 'messages')
  28. {
  29. if (!stream_is_local($resource)) {
  30. throw new InvalidResourceException(sprintf('This is not a local file "%s".', $resource));
  31. }
  32. if (!file_exists($resource)) {
  33. throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource));
  34. }
  35. $catalogue = new MessageCatalogue($locale);
  36. $this->extract($resource, $catalogue, $domain);
  37. if (class_exists('Symfony\Component\Config\Resource\FileResource')) {
  38. $catalogue->addResource(new FileResource($resource));
  39. }
  40. return $catalogue;
  41. }
  42. private function extract($resource, MessageCatalogue $catalogue, $domain)
  43. {
  44. try {
  45. $dom = XmlUtils::loadFile($resource);
  46. } catch (\InvalidArgumentException $e) {
  47. throw new InvalidResourceException(sprintf('Unable to load "%s": %s', $resource, $e->getMessage()), $e->getCode(), $e);
  48. }
  49. $xliffVersion = $this->getVersionNumber($dom);
  50. $this->validateSchema($xliffVersion, $dom, $this->getSchema($xliffVersion));
  51. if ('1.2' === $xliffVersion) {
  52. $this->extractXliff1($dom, $catalogue, $domain);
  53. }
  54. if ('2.0' === $xliffVersion) {
  55. $this->extractXliff2($dom, $catalogue, $domain);
  56. }
  57. }
  58. /**
  59. * Extract messages and metadata from DOMDocument into a MessageCatalogue.
  60. *
  61. * @param \DOMDocument $dom Source to extract messages and metadata
  62. * @param MessageCatalogue $catalogue Catalogue where we'll collect messages and metadata
  63. * @param string $domain The domain
  64. */
  65. private function extractXliff1(\DOMDocument $dom, MessageCatalogue $catalogue, string $domain)
  66. {
  67. $xml = simplexml_import_dom($dom);
  68. $encoding = strtoupper($dom->encoding);
  69. $xml->registerXPathNamespace('xliff', 'urn:oasis:names:tc:xliff:document:1.2');
  70. foreach ($xml->xpath('//xliff:trans-unit') as $translation) {
  71. $attributes = $translation->attributes();
  72. if (!(isset($attributes['resname']) || isset($translation->source))) {
  73. continue;
  74. }
  75. $source = isset($attributes['resname']) && $attributes['resname'] ? $attributes['resname'] : $translation->source;
  76. // If the xlf file has another encoding specified, try to convert it because
  77. // simple_xml will always return utf-8 encoded values
  78. $target = $this->utf8ToCharset((string) (isset($translation->target) ? $translation->target : $source), $encoding);
  79. $catalogue->set((string) $source, $target, $domain);
  80. $metadata = array();
  81. if ($notes = $this->parseNotesMetadata($translation->note, $encoding)) {
  82. $metadata['notes'] = $notes;
  83. }
  84. if (isset($translation->target) && $translation->target->attributes()) {
  85. $metadata['target-attributes'] = array();
  86. foreach ($translation->target->attributes() as $key => $value) {
  87. $metadata['target-attributes'][$key] = (string) $value;
  88. }
  89. }
  90. if (isset($attributes['id'])) {
  91. $metadata['id'] = (string) $attributes['id'];
  92. }
  93. $catalogue->setMetadata((string) $source, $metadata, $domain);
  94. }
  95. }
  96. private function extractXliff2(\DOMDocument $dom, MessageCatalogue $catalogue, string $domain)
  97. {
  98. $xml = simplexml_import_dom($dom);
  99. $encoding = strtoupper($dom->encoding);
  100. $xml->registerXPathNamespace('xliff', 'urn:oasis:names:tc:xliff:document:2.0');
  101. foreach ($xml->xpath('//xliff:unit') as $unit) {
  102. foreach ($unit->segment as $segment) {
  103. $source = $segment->source;
  104. // If the xlf file has another encoding specified, try to convert it because
  105. // simple_xml will always return utf-8 encoded values
  106. $target = $this->utf8ToCharset((string) (isset($segment->target) ? $segment->target : $source), $encoding);
  107. $catalogue->set((string) $source, $target, $domain);
  108. $metadata = array();
  109. if (isset($segment->target) && $segment->target->attributes()) {
  110. $metadata['target-attributes'] = array();
  111. foreach ($segment->target->attributes() as $key => $value) {
  112. $metadata['target-attributes'][$key] = (string) $value;
  113. }
  114. }
  115. if (isset($unit->notes)) {
  116. $metadata['notes'] = array();
  117. foreach ($unit->notes->note as $noteNode) {
  118. $note = array();
  119. foreach ($noteNode->attributes() as $key => $value) {
  120. $note[$key] = (string) $value;
  121. }
  122. $note['content'] = (string) $noteNode;
  123. $metadata['notes'][] = $note;
  124. }
  125. }
  126. $catalogue->setMetadata((string) $source, $metadata, $domain);
  127. }
  128. }
  129. }
  130. /**
  131. * Convert a UTF8 string to the specified encoding.
  132. */
  133. private function utf8ToCharset(string $content, string $encoding = null): string
  134. {
  135. if ('UTF-8' !== $encoding && !empty($encoding)) {
  136. return mb_convert_encoding($content, $encoding, 'UTF-8');
  137. }
  138. return $content;
  139. }
  140. /**
  141. * Validates and parses the given file into a DOMDocument.
  142. *
  143. * @throws InvalidResourceException
  144. */
  145. private function validateSchema(string $file, \DOMDocument $dom, string $schema)
  146. {
  147. $internalErrors = libxml_use_internal_errors(true);
  148. $disableEntities = libxml_disable_entity_loader(false);
  149. if (!@$dom->schemaValidateSource($schema)) {
  150. libxml_disable_entity_loader($disableEntities);
  151. throw new InvalidResourceException(sprintf('Invalid resource provided: "%s"; Errors: %s', $file, implode("\n", $this->getXmlErrors($internalErrors))));
  152. }
  153. libxml_disable_entity_loader($disableEntities);
  154. $dom->normalizeDocument();
  155. libxml_clear_errors();
  156. libxml_use_internal_errors($internalErrors);
  157. }
  158. private function getSchema($xliffVersion)
  159. {
  160. if ('1.2' === $xliffVersion) {
  161. $schemaSource = file_get_contents(__DIR__.'/schema/dic/xliff-core/xliff-core-1.2-strict.xsd');
  162. $xmlUri = 'http://www.w3.org/2001/xml.xsd';
  163. } elseif ('2.0' === $xliffVersion) {
  164. $schemaSource = file_get_contents(__DIR__.'/schema/dic/xliff-core/xliff-core-2.0.xsd');
  165. $xmlUri = 'informativeCopiesOf3rdPartySchemas/w3c/xml.xsd';
  166. } else {
  167. throw new InvalidArgumentException(sprintf('No support implemented for loading XLIFF version "%s".', $xliffVersion));
  168. }
  169. return $this->fixXmlLocation($schemaSource, $xmlUri);
  170. }
  171. /**
  172. * Internally changes the URI of a dependent xsd to be loaded locally.
  173. */
  174. private function fixXmlLocation(string $schemaSource, string $xmlUri): string
  175. {
  176. $newPath = str_replace('\\', '/', __DIR__).'/schema/dic/xliff-core/xml.xsd';
  177. $parts = explode('/', $newPath);
  178. $locationstart = 'file:///';
  179. if (0 === stripos($newPath, 'phar://')) {
  180. $tmpfile = tempnam(sys_get_temp_dir(), 'symfony');
  181. if ($tmpfile) {
  182. copy($newPath, $tmpfile);
  183. $parts = explode('/', str_replace('\\', '/', $tmpfile));
  184. } else {
  185. array_shift($parts);
  186. $locationstart = 'phar:///';
  187. }
  188. }
  189. $drive = '\\' === DIRECTORY_SEPARATOR ? array_shift($parts).'/' : '';
  190. $newPath = $locationstart.$drive.implode('/', array_map('rawurlencode', $parts));
  191. return str_replace($xmlUri, $newPath, $schemaSource);
  192. }
  193. /**
  194. * Returns the XML errors of the internal XML parser.
  195. */
  196. private function getXmlErrors(bool $internalErrors): array
  197. {
  198. $errors = array();
  199. foreach (libxml_get_errors() as $error) {
  200. $errors[] = sprintf('[%s %s] %s (in %s - line %d, column %d)',
  201. LIBXML_ERR_WARNING == $error->level ? 'WARNING' : 'ERROR',
  202. $error->code,
  203. trim($error->message),
  204. $error->file ?: 'n/a',
  205. $error->line,
  206. $error->column
  207. );
  208. }
  209. libxml_clear_errors();
  210. libxml_use_internal_errors($internalErrors);
  211. return $errors;
  212. }
  213. /**
  214. * Gets xliff file version based on the root "version" attribute.
  215. * Defaults to 1.2 for backwards compatibility.
  216. *
  217. * @throws InvalidArgumentException
  218. */
  219. private function getVersionNumber(\DOMDocument $dom): string
  220. {
  221. /** @var \DOMNode $xliff */
  222. foreach ($dom->getElementsByTagName('xliff') as $xliff) {
  223. $version = $xliff->attributes->getNamedItem('version');
  224. if ($version) {
  225. return $version->nodeValue;
  226. }
  227. $namespace = $xliff->attributes->getNamedItem('xmlns');
  228. if ($namespace) {
  229. if (0 !== substr_compare('urn:oasis:names:tc:xliff:document:', $namespace->nodeValue, 0, 34)) {
  230. throw new InvalidArgumentException(sprintf('Not a valid XLIFF namespace "%s"', $namespace));
  231. }
  232. return substr($namespace, 34);
  233. }
  234. }
  235. // Falls back to v1.2
  236. return '1.2';
  237. }
  238. private function parseNotesMetadata(\SimpleXMLElement $noteElement = null, string $encoding = null): array
  239. {
  240. $notes = array();
  241. if (null === $noteElement) {
  242. return $notes;
  243. }
  244. /** @var \SimpleXMLElement $xmlNote */
  245. foreach ($noteElement as $xmlNote) {
  246. $noteAttributes = $xmlNote->attributes();
  247. $note = array('content' => $this->utf8ToCharset((string) $xmlNote, $encoding));
  248. if (isset($noteAttributes['priority'])) {
  249. $note['priority'] = (int) $noteAttributes['priority'];
  250. }
  251. if (isset($noteAttributes['from'])) {
  252. $note['from'] = (string) $noteAttributes['from'];
  253. }
  254. $notes[] = $note;
  255. }
  256. return $notes;
  257. }
  258. }