4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Translation\Loader;
14 use Symfony\Component\Config\Resource\FileResource;
15 use Symfony\Component\Config\Util\XmlUtils;
16 use Symfony\Component\Translation\Exception\InvalidArgumentException;
17 use Symfony\Component\Translation\Exception\InvalidResourceException;
18 use Symfony\Component\Translation\Exception\NotFoundResourceException;
19 use Symfony\Component\Translation\MessageCatalogue;
22 * XliffFileLoader loads translations from XLIFF files.
24 * @author Fabien Potencier <fabien@symfony.com>
26 class XliffFileLoader implements LoaderInterface
31 public function load($resource, $locale, $domain = 'messages')
33 if (!stream_is_local($resource)) {
34 throw new InvalidResourceException(sprintf('This is not a local file "%s".', $resource));
37 if (!file_exists($resource)) {
38 throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource));
41 $catalogue = new MessageCatalogue($locale);
42 $this->extract($resource, $catalogue, $domain);
44 if (class_exists('Symfony\Component\Config\Resource\FileResource')) {
45 $catalogue->addResource(new FileResource($resource));
51 private function extract($resource, MessageCatalogue $catalogue, $domain)
54 $dom = XmlUtils::loadFile($resource);
55 } catch (\InvalidArgumentException $e) {
56 throw new InvalidResourceException(sprintf('Unable to load "%s": %s', $resource, $e->getMessage()), $e->getCode(), $e);
59 $xliffVersion = $this->getVersionNumber($dom);
60 $this->validateSchema($xliffVersion, $dom, $this->getSchema($xliffVersion));
62 if ('1.2' === $xliffVersion) {
63 $this->extractXliff1($dom, $catalogue, $domain);
66 if ('2.0' === $xliffVersion) {
67 $this->extractXliff2($dom, $catalogue, $domain);
72 * Extract messages and metadata from DOMDocument into a MessageCatalogue.
74 * @param \DOMDocument $dom Source to extract messages and metadata
75 * @param MessageCatalogue $catalogue Catalogue where we'll collect messages and metadata
76 * @param string $domain The domain
78 private function extractXliff1(\DOMDocument $dom, MessageCatalogue $catalogue, $domain)
80 $xml = simplexml_import_dom($dom);
81 $encoding = strtoupper($dom->encoding);
83 $xml->registerXPathNamespace('xliff', 'urn:oasis:names:tc:xliff:document:1.2');
84 foreach ($xml->xpath('//xliff:trans-unit') as $translation) {
85 $attributes = $translation->attributes();
87 if (!(isset($attributes['resname']) || isset($translation->source))) {
91 $source = isset($attributes['resname']) && $attributes['resname'] ? $attributes['resname'] : $translation->source;
92 // If the xlf file has another encoding specified, try to convert it because
93 // simple_xml will always return utf-8 encoded values
94 $target = $this->utf8ToCharset((string) (isset($translation->target) ? $translation->target : $source), $encoding);
96 $catalogue->set((string) $source, $target, $domain);
99 if ($notes = $this->parseNotesMetadata($translation->note, $encoding)) {
100 $metadata['notes'] = $notes;
103 if (isset($translation->target) && $translation->target->attributes()) {
104 $metadata['target-attributes'] = array();
105 foreach ($translation->target->attributes() as $key => $value) {
106 $metadata['target-attributes'][$key] = (string) $value;
110 if (isset($attributes['id'])) {
111 $metadata['id'] = (string) $attributes['id'];
114 $catalogue->setMetadata((string) $source, $metadata, $domain);
119 * @param \DOMDocument $dom
120 * @param MessageCatalogue $catalogue
121 * @param string $domain
123 private function extractXliff2(\DOMDocument $dom, MessageCatalogue $catalogue, $domain)
125 $xml = simplexml_import_dom($dom);
126 $encoding = strtoupper($dom->encoding);
128 $xml->registerXPathNamespace('xliff', 'urn:oasis:names:tc:xliff:document:2.0');
130 foreach ($xml->xpath('//xliff:unit') as $unit) {
131 foreach ($unit->segment as $segment) {
132 $source = $segment->source;
134 // If the xlf file has another encoding specified, try to convert it because
135 // simple_xml will always return utf-8 encoded values
136 $target = $this->utf8ToCharset((string) (isset($segment->target) ? $segment->target : $source), $encoding);
138 $catalogue->set((string) $source, $target, $domain);
141 if (isset($segment->target) && $segment->target->attributes()) {
142 $metadata['target-attributes'] = array();
143 foreach ($segment->target->attributes() as $key => $value) {
144 $metadata['target-attributes'][$key] = (string) $value;
148 if (isset($unit->notes)) {
149 $metadata['notes'] = array();
150 foreach ($unit->notes->note as $noteNode) {
152 foreach ($noteNode->attributes() as $key => $value) {
153 $note[$key] = (string) $value;
155 $note['content'] = (string) $noteNode;
156 $metadata['notes'][] = $note;
160 $catalogue->setMetadata((string) $source, $metadata, $domain);
166 * Convert a UTF8 string to the specified encoding.
168 * @param string $content String to decode
169 * @param string $encoding Target encoding
173 private function utf8ToCharset($content, $encoding = null)
175 if ('UTF-8' !== $encoding && !empty($encoding)) {
176 return mb_convert_encoding($content, $encoding, 'UTF-8');
183 * Validates and parses the given file into a DOMDocument.
185 * @param string $file
186 * @param \DOMDocument $dom
187 * @param string $schema source of the schema
189 * @throws InvalidResourceException
191 private function validateSchema($file, \DOMDocument $dom, $schema)
193 $internalErrors = libxml_use_internal_errors(true);
195 $disableEntities = libxml_disable_entity_loader(false);
197 if (!@$dom->schemaValidateSource($schema)) {
198 libxml_disable_entity_loader($disableEntities);
200 throw new InvalidResourceException(sprintf('Invalid resource provided: "%s"; Errors: %s', $file, implode("\n", $this->getXmlErrors($internalErrors))));
203 libxml_disable_entity_loader($disableEntities);
205 $dom->normalizeDocument();
207 libxml_clear_errors();
208 libxml_use_internal_errors($internalErrors);
211 private function getSchema($xliffVersion)
213 if ('1.2' === $xliffVersion) {
214 $schemaSource = file_get_contents(__DIR__.'/schema/dic/xliff-core/xliff-core-1.2-strict.xsd');
215 $xmlUri = 'http://www.w3.org/2001/xml.xsd';
216 } elseif ('2.0' === $xliffVersion) {
217 $schemaSource = file_get_contents(__DIR__.'/schema/dic/xliff-core/xliff-core-2.0.xsd');
218 $xmlUri = 'informativeCopiesOf3rdPartySchemas/w3c/xml.xsd';
220 throw new InvalidArgumentException(sprintf('No support implemented for loading XLIFF version "%s".', $xliffVersion));
223 return $this->fixXmlLocation($schemaSource, $xmlUri);
227 * Internally changes the URI of a dependent xsd to be loaded locally.
229 * @param string $schemaSource Current content of schema file
230 * @param string $xmlUri External URI of XML to convert to local
234 private function fixXmlLocation($schemaSource, $xmlUri)
236 $newPath = str_replace('\\', '/', __DIR__).'/schema/dic/xliff-core/xml.xsd';
237 $parts = explode('/', $newPath);
238 $locationstart = 'file:///';
239 if (0 === stripos($newPath, 'phar://')) {
240 $tmpfile = tempnam(sys_get_temp_dir(), 'symfony');
242 copy($newPath, $tmpfile);
243 $parts = explode('/', str_replace('\\', '/', $tmpfile));
246 $locationstart = 'phar:///';
250 $drive = '\\' === \DIRECTORY_SEPARATOR ? array_shift($parts).'/' : '';
251 $newPath = $locationstart.$drive.implode('/', array_map('rawurlencode', $parts));
253 return str_replace($xmlUri, $newPath, $schemaSource);
257 * Returns the XML errors of the internal XML parser.
259 * @param bool $internalErrors
261 * @return array An array of errors
263 private function getXmlErrors($internalErrors)
266 foreach (libxml_get_errors() as $error) {
267 $errors[] = sprintf('[%s %s] %s (in %s - line %d, column %d)',
268 LIBXML_ERR_WARNING == $error->level ? 'WARNING' : 'ERROR',
270 trim($error->message),
271 $error->file ?: 'n/a',
277 libxml_clear_errors();
278 libxml_use_internal_errors($internalErrors);
284 * Gets xliff file version based on the root "version" attribute.
285 * Defaults to 1.2 for backwards compatibility.
287 * @param \DOMDocument $dom
289 * @throws InvalidArgumentException
293 private function getVersionNumber(\DOMDocument $dom)
295 /** @var \DOMNode $xliff */
296 foreach ($dom->getElementsByTagName('xliff') as $xliff) {
297 $version = $xliff->attributes->getNamedItem('version');
299 return $version->nodeValue;
302 $namespace = $xliff->attributes->getNamedItem('xmlns');
304 if (0 !== substr_compare('urn:oasis:names:tc:xliff:document:', $namespace->nodeValue, 0, 34)) {
305 throw new InvalidArgumentException(sprintf('Not a valid XLIFF namespace "%s"', $namespace));
308 return substr($namespace, 34);
312 // Falls back to v1.2
317 * @param \SimpleXMLElement|null $noteElement
318 * @param string|null $encoding
322 private function parseNotesMetadata(\SimpleXMLElement $noteElement = null, $encoding = null)
326 if (null === $noteElement) {
330 /** @var \SimpleXMLElement $xmlNote */
331 foreach ($noteElement as $xmlNote) {
332 $noteAttributes = $xmlNote->attributes();
333 $note = array('content' => $this->utf8ToCharset((string) $xmlNote, $encoding));
334 if (isset($noteAttributes['priority'])) {
335 $note['priority'] = (int) $noteAttributes['priority'];
338 if (isset($noteAttributes['from'])) {
339 $note['from'] = (string) $noteAttributes['from'];