Updated Drupal to 8.6. This goes with the following updates because it's possible...
[yaffs-website] / vendor / symfony / translation / Loader / XliffFileLoader.php
1 <?php
2
3 /*
4  * This file is part of the Symfony package.
5  *
6  * (c) Fabien Potencier <fabien@symfony.com>
7  *
8  * For the full copyright and license information, please view the LICENSE
9  * file that was distributed with this source code.
10  */
11
12 namespace Symfony\Component\Translation\Loader;
13
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;
20
21 /**
22  * XliffFileLoader loads translations from XLIFF files.
23  *
24  * @author Fabien Potencier <fabien@symfony.com>
25  */
26 class XliffFileLoader implements LoaderInterface
27 {
28     /**
29      * {@inheritdoc}
30      */
31     public function load($resource, $locale, $domain = 'messages')
32     {
33         if (!stream_is_local($resource)) {
34             throw new InvalidResourceException(sprintf('This is not a local file "%s".', $resource));
35         }
36
37         if (!file_exists($resource)) {
38             throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource));
39         }
40
41         $catalogue = new MessageCatalogue($locale);
42         $this->extract($resource, $catalogue, $domain);
43
44         if (class_exists('Symfony\Component\Config\Resource\FileResource')) {
45             $catalogue->addResource(new FileResource($resource));
46         }
47
48         return $catalogue;
49     }
50
51     private function extract($resource, MessageCatalogue $catalogue, $domain)
52     {
53         try {
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);
57         }
58
59         $xliffVersion = $this->getVersionNumber($dom);
60         $this->validateSchema($xliffVersion, $dom, $this->getSchema($xliffVersion));
61
62         if ('1.2' === $xliffVersion) {
63             $this->extractXliff1($dom, $catalogue, $domain);
64         }
65
66         if ('2.0' === $xliffVersion) {
67             $this->extractXliff2($dom, $catalogue, $domain);
68         }
69     }
70
71     /**
72      * Extract messages and metadata from DOMDocument into a MessageCatalogue.
73      *
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
77      */
78     private function extractXliff1(\DOMDocument $dom, MessageCatalogue $catalogue, $domain)
79     {
80         $xml = simplexml_import_dom($dom);
81         $encoding = strtoupper($dom->encoding);
82
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();
86
87             if (!(isset($attributes['resname']) || isset($translation->source))) {
88                 continue;
89             }
90
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);
95
96             $catalogue->set((string) $source, $target, $domain);
97
98             $metadata = array();
99             if ($notes = $this->parseNotesMetadata($translation->note, $encoding)) {
100                 $metadata['notes'] = $notes;
101             }
102
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;
107                 }
108             }
109
110             if (isset($attributes['id'])) {
111                 $metadata['id'] = (string) $attributes['id'];
112             }
113
114             $catalogue->setMetadata((string) $source, $metadata, $domain);
115         }
116     }
117
118     /**
119      * @param \DOMDocument     $dom
120      * @param MessageCatalogue $catalogue
121      * @param string           $domain
122      */
123     private function extractXliff2(\DOMDocument $dom, MessageCatalogue $catalogue, $domain)
124     {
125         $xml = simplexml_import_dom($dom);
126         $encoding = strtoupper($dom->encoding);
127
128         $xml->registerXPathNamespace('xliff', 'urn:oasis:names:tc:xliff:document:2.0');
129
130         foreach ($xml->xpath('//xliff:unit') as $unit) {
131             foreach ($unit->segment as $segment) {
132                 $source = $segment->source;
133
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);
137
138                 $catalogue->set((string) $source, $target, $domain);
139
140                 $metadata = array();
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;
145                     }
146                 }
147
148                 if (isset($unit->notes)) {
149                     $metadata['notes'] = array();
150                     foreach ($unit->notes->note as $noteNode) {
151                         $note = array();
152                         foreach ($noteNode->attributes() as $key => $value) {
153                             $note[$key] = (string) $value;
154                         }
155                         $note['content'] = (string) $noteNode;
156                         $metadata['notes'][] = $note;
157                     }
158                 }
159
160                 $catalogue->setMetadata((string) $source, $metadata, $domain);
161             }
162         }
163     }
164
165     /**
166      * Convert a UTF8 string to the specified encoding.
167      *
168      * @param string $content  String to decode
169      * @param string $encoding Target encoding
170      *
171      * @return string
172      */
173     private function utf8ToCharset($content, $encoding = null)
174     {
175         if ('UTF-8' !== $encoding && !empty($encoding)) {
176             return mb_convert_encoding($content, $encoding, 'UTF-8');
177         }
178
179         return $content;
180     }
181
182     /**
183      * Validates and parses the given file into a DOMDocument.
184      *
185      * @param string       $file
186      * @param \DOMDocument $dom
187      * @param string       $schema source of the schema
188      *
189      * @throws InvalidResourceException
190      */
191     private function validateSchema($file, \DOMDocument $dom, $schema)
192     {
193         $internalErrors = libxml_use_internal_errors(true);
194
195         $disableEntities = libxml_disable_entity_loader(false);
196
197         if (!@$dom->schemaValidateSource($schema)) {
198             libxml_disable_entity_loader($disableEntities);
199
200             throw new InvalidResourceException(sprintf('Invalid resource provided: "%s"; Errors: %s', $file, implode("\n", $this->getXmlErrors($internalErrors))));
201         }
202
203         libxml_disable_entity_loader($disableEntities);
204
205         $dom->normalizeDocument();
206
207         libxml_clear_errors();
208         libxml_use_internal_errors($internalErrors);
209     }
210
211     private function getSchema($xliffVersion)
212     {
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';
219         } else {
220             throw new InvalidArgumentException(sprintf('No support implemented for loading XLIFF version "%s".', $xliffVersion));
221         }
222
223         return $this->fixXmlLocation($schemaSource, $xmlUri);
224     }
225
226     /**
227      * Internally changes the URI of a dependent xsd to be loaded locally.
228      *
229      * @param string $schemaSource Current content of schema file
230      * @param string $xmlUri       External URI of XML to convert to local
231      *
232      * @return string
233      */
234     private function fixXmlLocation($schemaSource, $xmlUri)
235     {
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');
241             if ($tmpfile) {
242                 copy($newPath, $tmpfile);
243                 $parts = explode('/', str_replace('\\', '/', $tmpfile));
244             } else {
245                 array_shift($parts);
246                 $locationstart = 'phar:///';
247             }
248         }
249
250         $drive = '\\' === \DIRECTORY_SEPARATOR ? array_shift($parts).'/' : '';
251         $newPath = $locationstart.$drive.implode('/', array_map('rawurlencode', $parts));
252
253         return str_replace($xmlUri, $newPath, $schemaSource);
254     }
255
256     /**
257      * Returns the XML errors of the internal XML parser.
258      *
259      * @param bool $internalErrors
260      *
261      * @return array An array of errors
262      */
263     private function getXmlErrors($internalErrors)
264     {
265         $errors = array();
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',
269                 $error->code,
270                 trim($error->message),
271                 $error->file ?: 'n/a',
272                 $error->line,
273                 $error->column
274             );
275         }
276
277         libxml_clear_errors();
278         libxml_use_internal_errors($internalErrors);
279
280         return $errors;
281     }
282
283     /**
284      * Gets xliff file version based on the root "version" attribute.
285      * Defaults to 1.2 for backwards compatibility.
286      *
287      * @param \DOMDocument $dom
288      *
289      * @throws InvalidArgumentException
290      *
291      * @return string
292      */
293     private function getVersionNumber(\DOMDocument $dom)
294     {
295         /** @var \DOMNode $xliff */
296         foreach ($dom->getElementsByTagName('xliff') as $xliff) {
297             $version = $xliff->attributes->getNamedItem('version');
298             if ($version) {
299                 return $version->nodeValue;
300             }
301
302             $namespace = $xliff->attributes->getNamedItem('xmlns');
303             if ($namespace) {
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));
306                 }
307
308                 return substr($namespace, 34);
309             }
310         }
311
312         // Falls back to v1.2
313         return '1.2';
314     }
315
316     /**
317      * @param \SimpleXMLElement|null $noteElement
318      * @param string|null            $encoding
319      *
320      * @return array
321      */
322     private function parseNotesMetadata(\SimpleXMLElement $noteElement = null, $encoding = null)
323     {
324         $notes = array();
325
326         if (null === $noteElement) {
327             return $notes;
328         }
329
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'];
336             }
337
338             if (isset($noteAttributes['from'])) {
339                 $note['from'] = (string) $noteAttributes['from'];
340             }
341
342             $notes[] = $note;
343         }
344
345         return $notes;
346     }
347 }