XliffFileLoader.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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, $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. /**
  97. * @param \DOMDocument $dom
  98. * @param MessageCatalogue $catalogue
  99. * @param string $domain
  100. */
  101. private function extractXliff2(\DOMDocument $dom, MessageCatalogue $catalogue, $domain)
  102. {
  103. $xml = simplexml_import_dom($dom);
  104. $encoding = strtoupper($dom->encoding);
  105. $xml->registerXPathNamespace('xliff', 'urn:oasis:names:tc:xliff:document:2.0');
  106. foreach ($xml->xpath('//xliff:unit/xliff:segment') as $segment) {
  107. $source = $segment->source;
  108. // If the xlf file has another encoding specified, try to convert it because
  109. // simple_xml will always return utf-8 encoded values
  110. $target = $this->utf8ToCharset((string) (isset($segment->target) ? $segment->target : $source), $encoding);
  111. $catalogue->set((string) $source, $target, $domain);
  112. $metadata = array();
  113. if (isset($segment->target) && $segment->target->attributes()) {
  114. $metadata['target-attributes'] = array();
  115. foreach ($segment->target->attributes() as $key => $value) {
  116. $metadata['target-attributes'][$key] = (string) $value;
  117. }
  118. }
  119. $catalogue->setMetadata((string) $source, $metadata, $domain);
  120. }
  121. }
  122. /**
  123. * Convert a UTF8 string to the specified encoding.
  124. *
  125. * @param string $content String to decode
  126. * @param string $encoding Target encoding
  127. *
  128. * @return string
  129. */
  130. private function utf8ToCharset($content, $encoding = null)
  131. {
  132. if ('UTF-8' !== $encoding && !empty($encoding)) {
  133. return mb_convert_encoding($content, $encoding, 'UTF-8');
  134. }
  135. return $content;
  136. }
  137. /**
  138. * Validates and parses the given file into a DOMDocument.
  139. *
  140. * @param string $file
  141. * @param \DOMDocument $dom
  142. * @param string $schema source of the schema
  143. *
  144. * @throws InvalidResourceException
  145. */
  146. private function validateSchema($file, \DOMDocument $dom, $schema)
  147. {
  148. $internalErrors = libxml_use_internal_errors(true);
  149. $disableEntities = libxml_disable_entity_loader(false);
  150. if (!@$dom->schemaValidateSource($schema)) {
  151. libxml_disable_entity_loader($disableEntities);
  152. throw new InvalidResourceException(sprintf('Invalid resource provided: "%s"; Errors: %s', $file, implode("\n", $this->getXmlErrors($internalErrors))));
  153. }
  154. libxml_disable_entity_loader($disableEntities);
  155. $dom->normalizeDocument();
  156. libxml_clear_errors();
  157. libxml_use_internal_errors($internalErrors);
  158. }
  159. private function getSchema($xliffVersion)
  160. {
  161. if ('1.2' === $xliffVersion) {
  162. $schemaSource = file_get_contents(__DIR__.'/schema/dic/xliff-core/xliff-core-1.2-strict.xsd');
  163. $xmlUri = 'http://www.w3.org/2001/xml.xsd';
  164. } elseif ('2.0' === $xliffVersion) {
  165. $schemaSource = file_get_contents(__DIR__.'/schema/dic/xliff-core/xliff-core-2.0.xsd');
  166. $xmlUri = 'informativeCopiesOf3rdPartySchemas/w3c/xml.xsd';
  167. } else {
  168. throw new InvalidArgumentException(sprintf('No support implemented for loading XLIFF version "%s".', $xliffVersion));
  169. }
  170. return $this->fixXmlLocation($schemaSource, $xmlUri);
  171. }
  172. /**
  173. * Internally changes the URI of a dependent xsd to be loaded locally.
  174. *
  175. * @param string $schemaSource Current content of schema file
  176. * @param string $xmlUri External URI of XML to convert to local
  177. *
  178. * @return string
  179. */
  180. private function fixXmlLocation($schemaSource, $xmlUri)
  181. {
  182. $newPath = str_replace('\\', '/', __DIR__).'/schema/dic/xliff-core/xml.xsd';
  183. $parts = explode('/', $newPath);
  184. if (0 === stripos($newPath, 'phar://')) {
  185. $tmpfile = tempnam(sys_get_temp_dir(), 'sf2');
  186. if ($tmpfile) {
  187. copy($newPath, $tmpfile);
  188. $parts = explode('/', str_replace('\\', '/', $tmpfile));
  189. }
  190. }
  191. $drive = '\\' === DIRECTORY_SEPARATOR ? array_shift($parts).'/' : '';
  192. $newPath = 'file:///'.$drive.implode('/', array_map('rawurlencode', $parts));
  193. return str_replace($xmlUri, $newPath, $schemaSource);
  194. }
  195. /**
  196. * Returns the XML errors of the internal XML parser.
  197. *
  198. * @param bool $internalErrors
  199. *
  200. * @return array An array of errors
  201. */
  202. private function getXmlErrors($internalErrors)
  203. {
  204. $errors = array();
  205. foreach (libxml_get_errors() as $error) {
  206. $errors[] = sprintf('[%s %s] %s (in %s - line %d, column %d)',
  207. LIBXML_ERR_WARNING == $error->level ? 'WARNING' : 'ERROR',
  208. $error->code,
  209. trim($error->message),
  210. $error->file ?: 'n/a',
  211. $error->line,
  212. $error->column
  213. );
  214. }
  215. libxml_clear_errors();
  216. libxml_use_internal_errors($internalErrors);
  217. return $errors;
  218. }
  219. /**
  220. * Gets xliff file version based on the root "version" attribute.
  221. * Defaults to 1.2 for backwards compatibility.
  222. *
  223. * @param \DOMDocument $dom
  224. *
  225. * @throws InvalidArgumentException
  226. *
  227. * @return string
  228. */
  229. private function getVersionNumber(\DOMDocument $dom)
  230. {
  231. /** @var \DOMNode $xliff */
  232. foreach ($dom->getElementsByTagName('xliff') as $xliff) {
  233. $version = $xliff->attributes->getNamedItem('version');
  234. if ($version) {
  235. return $version->nodeValue;
  236. }
  237. $namespace = $xliff->attributes->getNamedItem('xmlns');
  238. if ($namespace) {
  239. if (substr_compare('urn:oasis:names:tc:xliff:document:', $namespace->nodeValue, 0, 34) !== 0) {
  240. throw new InvalidArgumentException(sprintf('Not a valid XLIFF namespace "%s"', $namespace));
  241. }
  242. return substr($namespace, 34);
  243. }
  244. }
  245. // Falls back to v1.2
  246. return '1.2';
  247. }
  248. /**
  249. * @param \SimpleXMLElement|null $noteElement
  250. * @param string|null $encoding
  251. *
  252. * @return array
  253. */
  254. private function parseNotesMetadata(\SimpleXMLElement $noteElement = null, $encoding = null)
  255. {
  256. $notes = array();
  257. if (null === $noteElement) {
  258. return $notes;
  259. }
  260. /** @var \SimpleXMLElement $xmlNote */
  261. foreach ($noteElement as $xmlNote) {
  262. $noteAttributes = $xmlNote->attributes();
  263. $note = array('content' => $this->utf8ToCharset((string) $xmlNote, $encoding));
  264. if (isset($noteAttributes['priority'])) {
  265. $note['priority'] = (int) $noteAttributes['priority'];
  266. }
  267. if (isset($noteAttributes['from'])) {
  268. $note['from'] = (string) $noteAttributes['from'];
  269. }
  270. $notes[] = $note;
  271. }
  272. return $notes;
  273. }
  274. }