XliffFileLoader.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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. * @param string $file
  135. * @param \DOMDocument $dom
  136. * @param string $schema source of the schema
  137. *
  138. * @throws InvalidResourceException
  139. */
  140. private function validateSchema($file, \DOMDocument $dom, $schema)
  141. {
  142. $internalErrors = libxml_use_internal_errors(true);
  143. if (!@$dom->schemaValidateSource($schema)) {
  144. throw new InvalidResourceException(sprintf('Invalid resource provided: "%s"; Errors: %s', $file, implode("\n", $this->getXmlErrors($internalErrors))));
  145. }
  146. $dom->normalizeDocument();
  147. libxml_clear_errors();
  148. libxml_use_internal_errors($internalErrors);
  149. }
  150. private function getSchema($xliffVersion)
  151. {
  152. if ('1.2' === $xliffVersion) {
  153. $schemaSource = file_get_contents(__DIR__.'/schema/dic/xliff-core/xliff-core-1.2-strict.xsd');
  154. $xmlUri = 'http://www.w3.org/2001/xml.xsd';
  155. } elseif ('2.0' === $xliffVersion) {
  156. $schemaSource = file_get_contents(__DIR__.'/schema/dic/xliff-core/xliff-core-2.0.xsd');
  157. $xmlUri = 'informativeCopiesOf3rdPartySchemas/w3c/xml.xsd';
  158. } else {
  159. throw new \InvalidArgumentException(sprintf('No support implemented for loading XLIFF version "%s".', $xliffVersion));
  160. }
  161. return $this->fixXmlLocation($schemaSource, $xmlUri);
  162. }
  163. /**
  164. * Internally changes the URI of a dependent xsd to be loaded locally.
  165. *
  166. * @param string $schemaSource Current content of schema file
  167. * @param string $xmlUri External URI of XML to convert to local
  168. *
  169. * @return string
  170. */
  171. private function fixXmlLocation($schemaSource, $xmlUri)
  172. {
  173. $newPath = str_replace('\\', '/', __DIR__).'/schema/dic/xliff-core/xml.xsd';
  174. $parts = explode('/', $newPath);
  175. if (0 === stripos($newPath, 'phar://')) {
  176. $tmpfile = tempnam(sys_get_temp_dir(), 'sf2');
  177. if ($tmpfile) {
  178. copy($newPath, $tmpfile);
  179. $parts = explode('/', str_replace('\\', '/', $tmpfile));
  180. }
  181. }
  182. $drive = '\\' === DIRECTORY_SEPARATOR ? array_shift($parts).'/' : '';
  183. $newPath = 'file:///'.$drive.implode('/', array_map('rawurlencode', $parts));
  184. return str_replace($xmlUri, $newPath, $schemaSource);
  185. }
  186. /**
  187. * Returns the XML errors of the internal XML parser.
  188. *
  189. * @param bool $internalErrors
  190. *
  191. * @return array An array of errors
  192. */
  193. private function getXmlErrors($internalErrors)
  194. {
  195. $errors = array();
  196. foreach (libxml_get_errors() as $error) {
  197. $errors[] = sprintf('[%s %s] %s (in %s - line %d, column %d)',
  198. LIBXML_ERR_WARNING == $error->level ? 'WARNING' : 'ERROR',
  199. $error->code,
  200. trim($error->message),
  201. $error->file ?: 'n/a',
  202. $error->line,
  203. $error->column
  204. );
  205. }
  206. libxml_clear_errors();
  207. libxml_use_internal_errors($internalErrors);
  208. return $errors;
  209. }
  210. /**
  211. * Gets xliff file version based on the root "version" attribute.
  212. * Defaults to 1.2 for backwards compatibility.
  213. *
  214. * @param \DOMDocument $dom
  215. *
  216. * @throws \InvalidArgumentException
  217. *
  218. * @return string
  219. */
  220. private function getVersionNumber(\DOMDocument $dom)
  221. {
  222. /** @var \DOMNode $xliff */
  223. foreach ($dom->getElementsByTagName('xliff') as $xliff) {
  224. $version = $xliff->attributes->getNamedItem('version');
  225. if ($version) {
  226. return $version->nodeValue;
  227. }
  228. $namespace = $xliff->attributes->getNamedItem('xmlns');
  229. if ($namespace) {
  230. if (substr_compare('urn:oasis:names:tc:xliff:document:', $namespace->nodeValue, 0, 34) !== 0) {
  231. throw new \InvalidArgumentException(sprintf('Not a valid XLIFF namespace "%s"', $namespace));
  232. }
  233. return substr($namespace, 34);
  234. }
  235. }
  236. // Falls back to v1.2
  237. return '1.2';
  238. }
  239. /*
  240. * @param \SimpleXMLElement|null $noteElement
  241. * @param string|null $encoding
  242. *
  243. * @return array
  244. */
  245. private function parseNotesMetadata(\SimpleXMLElement $noteElement = null, $encoding = null)
  246. {
  247. $notes = array();
  248. if (null === $noteElement) {
  249. return $notes;
  250. }
  251. foreach ($noteElement as $xmlNote) {
  252. $noteAttributes = $xmlNote->attributes();
  253. $note = array('content' => $this->utf8ToCharset((string) $xmlNote, $encoding));
  254. if (isset($noteAttributes['priority'])) {
  255. $note['priority'] = (int) $noteAttributes['priority'];
  256. }
  257. if (isset($noteAttributes['from'])) {
  258. $note['from'] = (string) $noteAttributes['from'];
  259. }
  260. $notes[] = $note;
  261. }
  262. return $notes;
  263. }
  264. }