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
12namespace Symfony\Component\Translation\Util;
13
14use Symfony\Component\Translation\Exception\InvalidArgumentException;
15use Symfony\Component\Translation\Exception\InvalidResourceException;
16
17/**
18 * Provides some utility methods for XLIFF translation files, such as validating
19 * their contents according to the XSD schema.
20 *
21 * @author Fabien Potencier <fabien@symfony.com>
22 */
23class XliffUtils
24{
25    /**
26     * Gets xliff file version based on the root "version" attribute.
27     *
28     * Defaults to 1.2 for backwards compatibility.
29     *
30     * @throws InvalidArgumentException
31     */
32    public static function getVersionNumber(\DOMDocument $dom): string
33    {
34        /** @var \DOMNode $xliff */
35        foreach ($dom->getElementsByTagName('xliff') as $xliff) {
36            $version = $xliff->attributes->getNamedItem('version');
37            if ($version) {
38                return $version->nodeValue;
39            }
40
41            $namespace = $xliff->attributes->getNamedItem('xmlns');
42            if ($namespace) {
43                if (0 !== substr_compare('urn:oasis:names:tc:xliff:document:', $namespace->nodeValue, 0, 34)) {
44                    throw new InvalidArgumentException(sprintf('Not a valid XLIFF namespace "%s".', $namespace));
45                }
46
47                return substr($namespace, 34);
48            }
49        }
50
51        // Falls back to v1.2
52        return '1.2';
53    }
54
55    /**
56     * Validates and parses the given file into a DOMDocument.
57     *
58     * @throws InvalidResourceException
59     */
60    public static function validateSchema(\DOMDocument $dom): array
61    {
62        $xliffVersion = static::getVersionNumber($dom);
63        $internalErrors = libxml_use_internal_errors(true);
64        if ($shouldEnable = self::shouldEnableEntityLoader()) {
65            $disableEntities = libxml_disable_entity_loader(false);
66        }
67        try {
68            $isValid = @$dom->schemaValidateSource(self::getSchema($xliffVersion));
69            if (!$isValid) {
70                return self::getXmlErrors($internalErrors);
71            }
72        } finally {
73            if ($shouldEnable) {
74                libxml_disable_entity_loader($disableEntities);
75            }
76        }
77
78        $dom->normalizeDocument();
79
80        libxml_clear_errors();
81        libxml_use_internal_errors($internalErrors);
82
83        return [];
84    }
85
86    private static function shouldEnableEntityLoader(): bool
87    {
88        // Version prior to 8.0 can be enabled without deprecation
89        if (\PHP_VERSION_ID < 80000) {
90            return true;
91        }
92
93        static $dom, $schema;
94        if (null === $dom) {
95            $dom = new \DOMDocument();
96            $dom->loadXML('<?xml version="1.0"?><test/>');
97
98            $tmpfile = tempnam(sys_get_temp_dir(), 'symfony');
99            register_shutdown_function(static function () use ($tmpfile) {
100                @unlink($tmpfile);
101            });
102            $schema = '<?xml version="1.0" encoding="utf-8"?>
103<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
104  <xsd:include schemaLocation="file:///'.str_replace('\\', '/', $tmpfile).'" />
105</xsd:schema>';
106            file_put_contents($tmpfile, '<?xml version="1.0" encoding="utf-8"?>
107<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
108  <xsd:element name="test" type="testType" />
109  <xsd:complexType name="testType"/>
110</xsd:schema>');
111        }
112
113        return !@$dom->schemaValidateSource($schema);
114    }
115
116    public static function getErrorsAsString(array $xmlErrors): string
117    {
118        $errorsAsString = '';
119
120        foreach ($xmlErrors as $error) {
121            $errorsAsString .= sprintf("[%s %s] %s (in %s - line %d, column %d)\n",
122                \LIBXML_ERR_WARNING === $error['level'] ? 'WARNING' : 'ERROR',
123                $error['code'],
124                $error['message'],
125                $error['file'],
126                $error['line'],
127                $error['column']
128            );
129        }
130
131        return $errorsAsString;
132    }
133
134    private static function getSchema(string $xliffVersion): string
135    {
136        if ('1.2' === $xliffVersion) {
137            $schemaSource = file_get_contents(__DIR__.'/../Resources/schemas/xliff-core-1.2-strict.xsd');
138            $xmlUri = 'http://www.w3.org/2001/xml.xsd';
139        } elseif ('2.0' === $xliffVersion) {
140            $schemaSource = file_get_contents(__DIR__.'/../Resources/schemas/xliff-core-2.0.xsd');
141            $xmlUri = 'informativeCopiesOf3rdPartySchemas/w3c/xml.xsd';
142        } else {
143            throw new InvalidArgumentException(sprintf('No support implemented for loading XLIFF version "%s".', $xliffVersion));
144        }
145
146        return self::fixXmlLocation($schemaSource, $xmlUri);
147    }
148
149    /**
150     * Internally changes the URI of a dependent xsd to be loaded locally.
151     */
152    private static function fixXmlLocation(string $schemaSource, string $xmlUri): string
153    {
154        $newPath = str_replace('\\', '/', __DIR__).'/../Resources/schemas/xml.xsd';
155        $parts = explode('/', $newPath);
156        $locationstart = 'file:///';
157        if (0 === stripos($newPath, 'phar://')) {
158            $tmpfile = tempnam(sys_get_temp_dir(), 'symfony');
159            if ($tmpfile) {
160                copy($newPath, $tmpfile);
161                $parts = explode('/', str_replace('\\', '/', $tmpfile));
162            } else {
163                array_shift($parts);
164                $locationstart = 'phar:///';
165            }
166        }
167
168        $drive = '\\' === \DIRECTORY_SEPARATOR ? array_shift($parts).'/' : '';
169        $newPath = $locationstart.$drive.implode('/', array_map('rawurlencode', $parts));
170
171        return str_replace($xmlUri, $newPath, $schemaSource);
172    }
173
174    /**
175     * Returns the XML errors of the internal XML parser.
176     */
177    private static function getXmlErrors(bool $internalErrors): array
178    {
179        $errors = [];
180        foreach (libxml_get_errors() as $error) {
181            $errors[] = [
182                'level' => \LIBXML_ERR_WARNING == $error->level ? 'WARNING' : 'ERROR',
183                'code' => $error->code,
184                'message' => trim($error->message),
185                'file' => $error->file ?: 'n/a',
186                'line' => $error->line,
187                'column' => $error->column,
188            ];
189        }
190
191        libxml_clear_errors();
192        libxml_use_internal_errors($internalErrors);
193
194        return $errors;
195    }
196}
197