Drupal investigation

XliffFileLoader.php 11KB

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