XliffFileLoader.php 11 KB

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