XliffFileLoader.php 12 KB

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