Chris@0: Chris@0: * Chris@0: * For the full copyright and license information, please view the LICENSE Chris@0: * file that was distributed with this source code. Chris@0: */ Chris@0: Chris@0: namespace Symfony\Component\Translation\Loader; Chris@0: Chris@17: use Symfony\Component\Config\Resource\FileResource; Chris@0: use Symfony\Component\Config\Util\XmlUtils; Chris@17: use Symfony\Component\Translation\Exception\InvalidArgumentException; Chris@0: use Symfony\Component\Translation\Exception\InvalidResourceException; Chris@0: use Symfony\Component\Translation\Exception\NotFoundResourceException; Chris@17: use Symfony\Component\Translation\MessageCatalogue; Chris@0: Chris@0: /** Chris@0: * XliffFileLoader loads translations from XLIFF files. Chris@0: * Chris@0: * @author Fabien Potencier Chris@0: */ Chris@0: class XliffFileLoader implements LoaderInterface Chris@0: { Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function load($resource, $locale, $domain = 'messages') Chris@0: { Chris@0: if (!stream_is_local($resource)) { Chris@0: throw new InvalidResourceException(sprintf('This is not a local file "%s".', $resource)); Chris@0: } Chris@0: Chris@0: if (!file_exists($resource)) { Chris@0: throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource)); Chris@0: } Chris@0: Chris@0: $catalogue = new MessageCatalogue($locale); Chris@0: $this->extract($resource, $catalogue, $domain); Chris@0: Chris@0: if (class_exists('Symfony\Component\Config\Resource\FileResource')) { Chris@0: $catalogue->addResource(new FileResource($resource)); Chris@0: } Chris@0: Chris@0: return $catalogue; Chris@0: } Chris@0: Chris@0: private function extract($resource, MessageCatalogue $catalogue, $domain) Chris@0: { Chris@0: try { Chris@0: $dom = XmlUtils::loadFile($resource); Chris@0: } catch (\InvalidArgumentException $e) { Chris@0: throw new InvalidResourceException(sprintf('Unable to load "%s": %s', $resource, $e->getMessage()), $e->getCode(), $e); Chris@0: } Chris@0: Chris@0: $xliffVersion = $this->getVersionNumber($dom); Chris@0: $this->validateSchema($xliffVersion, $dom, $this->getSchema($xliffVersion)); Chris@0: Chris@0: if ('1.2' === $xliffVersion) { Chris@0: $this->extractXliff1($dom, $catalogue, $domain); Chris@0: } Chris@0: Chris@0: if ('2.0' === $xliffVersion) { Chris@0: $this->extractXliff2($dom, $catalogue, $domain); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Extract messages and metadata from DOMDocument into a MessageCatalogue. Chris@0: * Chris@0: * @param \DOMDocument $dom Source to extract messages and metadata Chris@0: * @param MessageCatalogue $catalogue Catalogue where we'll collect messages and metadata Chris@0: * @param string $domain The domain Chris@0: */ Chris@0: private function extractXliff1(\DOMDocument $dom, MessageCatalogue $catalogue, $domain) Chris@0: { Chris@0: $xml = simplexml_import_dom($dom); Chris@0: $encoding = strtoupper($dom->encoding); Chris@0: Chris@0: $xml->registerXPathNamespace('xliff', 'urn:oasis:names:tc:xliff:document:1.2'); Chris@0: foreach ($xml->xpath('//xliff:trans-unit') as $translation) { Chris@0: $attributes = $translation->attributes(); Chris@0: Chris@0: if (!(isset($attributes['resname']) || isset($translation->source))) { Chris@0: continue; Chris@0: } Chris@0: Chris@0: $source = isset($attributes['resname']) && $attributes['resname'] ? $attributes['resname'] : $translation->source; Chris@0: // If the xlf file has another encoding specified, try to convert it because Chris@0: // simple_xml will always return utf-8 encoded values Chris@17: $target = $this->utf8ToCharset((string) (isset($translation->target) ? $translation->target : $translation->source), $encoding); Chris@0: Chris@0: $catalogue->set((string) $source, $target, $domain); Chris@0: Chris@17: $metadata = []; Chris@0: if ($notes = $this->parseNotesMetadata($translation->note, $encoding)) { Chris@0: $metadata['notes'] = $notes; Chris@0: } Chris@0: Chris@0: if (isset($translation->target) && $translation->target->attributes()) { Chris@17: $metadata['target-attributes'] = []; Chris@0: foreach ($translation->target->attributes() as $key => $value) { Chris@0: $metadata['target-attributes'][$key] = (string) $value; Chris@0: } Chris@0: } Chris@0: Chris@0: if (isset($attributes['id'])) { Chris@0: $metadata['id'] = (string) $attributes['id']; Chris@0: } Chris@0: Chris@0: $catalogue->setMetadata((string) $source, $metadata, $domain); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * @param \DOMDocument $dom Chris@0: * @param MessageCatalogue $catalogue Chris@0: * @param string $domain Chris@0: */ Chris@0: private function extractXliff2(\DOMDocument $dom, MessageCatalogue $catalogue, $domain) Chris@0: { Chris@0: $xml = simplexml_import_dom($dom); Chris@0: $encoding = strtoupper($dom->encoding); Chris@0: Chris@0: $xml->registerXPathNamespace('xliff', 'urn:oasis:names:tc:xliff:document:2.0'); Chris@0: Chris@14: foreach ($xml->xpath('//xliff:unit') as $unit) { Chris@14: foreach ($unit->segment as $segment) { Chris@14: $source = $segment->source; Chris@0: Chris@14: // If the xlf file has another encoding specified, try to convert it because Chris@14: // simple_xml will always return utf-8 encoded values Chris@14: $target = $this->utf8ToCharset((string) (isset($segment->target) ? $segment->target : $source), $encoding); Chris@0: Chris@14: $catalogue->set((string) $source, $target, $domain); Chris@0: Chris@17: $metadata = []; Chris@14: if (isset($segment->target) && $segment->target->attributes()) { Chris@17: $metadata['target-attributes'] = []; Chris@14: foreach ($segment->target->attributes() as $key => $value) { Chris@14: $metadata['target-attributes'][$key] = (string) $value; Chris@14: } Chris@0: } Chris@14: Chris@14: if (isset($unit->notes)) { Chris@17: $metadata['notes'] = []; Chris@14: foreach ($unit->notes->note as $noteNode) { Chris@17: $note = []; Chris@14: foreach ($noteNode->attributes() as $key => $value) { Chris@14: $note[$key] = (string) $value; Chris@14: } Chris@14: $note['content'] = (string) $noteNode; Chris@14: $metadata['notes'][] = $note; Chris@14: } Chris@14: } Chris@14: Chris@14: $catalogue->setMetadata((string) $source, $metadata, $domain); Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Convert a UTF8 string to the specified encoding. Chris@0: * Chris@0: * @param string $content String to decode Chris@0: * @param string $encoding Target encoding Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: private function utf8ToCharset($content, $encoding = null) Chris@0: { Chris@0: if ('UTF-8' !== $encoding && !empty($encoding)) { Chris@0: return mb_convert_encoding($content, $encoding, 'UTF-8'); Chris@0: } Chris@0: Chris@0: return $content; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Validates and parses the given file into a DOMDocument. Chris@0: * Chris@0: * @param string $file Chris@0: * @param \DOMDocument $dom Chris@0: * @param string $schema source of the schema Chris@0: * Chris@0: * @throws InvalidResourceException Chris@0: */ Chris@0: private function validateSchema($file, \DOMDocument $dom, $schema) Chris@0: { Chris@0: $internalErrors = libxml_use_internal_errors(true); Chris@0: Chris@0: $disableEntities = libxml_disable_entity_loader(false); Chris@0: Chris@0: if (!@$dom->schemaValidateSource($schema)) { Chris@0: libxml_disable_entity_loader($disableEntities); Chris@0: Chris@0: throw new InvalidResourceException(sprintf('Invalid resource provided: "%s"; Errors: %s', $file, implode("\n", $this->getXmlErrors($internalErrors)))); Chris@0: } Chris@0: Chris@0: libxml_disable_entity_loader($disableEntities); Chris@0: Chris@0: $dom->normalizeDocument(); Chris@0: Chris@0: libxml_clear_errors(); Chris@0: libxml_use_internal_errors($internalErrors); Chris@0: } Chris@0: Chris@0: private function getSchema($xliffVersion) Chris@0: { Chris@0: if ('1.2' === $xliffVersion) { Chris@0: $schemaSource = file_get_contents(__DIR__.'/schema/dic/xliff-core/xliff-core-1.2-strict.xsd'); Chris@0: $xmlUri = 'http://www.w3.org/2001/xml.xsd'; Chris@0: } elseif ('2.0' === $xliffVersion) { Chris@0: $schemaSource = file_get_contents(__DIR__.'/schema/dic/xliff-core/xliff-core-2.0.xsd'); Chris@0: $xmlUri = 'informativeCopiesOf3rdPartySchemas/w3c/xml.xsd'; Chris@0: } else { Chris@0: throw new InvalidArgumentException(sprintf('No support implemented for loading XLIFF version "%s".', $xliffVersion)); Chris@0: } Chris@0: Chris@0: return $this->fixXmlLocation($schemaSource, $xmlUri); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Internally changes the URI of a dependent xsd to be loaded locally. Chris@0: * Chris@0: * @param string $schemaSource Current content of schema file Chris@0: * @param string $xmlUri External URI of XML to convert to local Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: private function fixXmlLocation($schemaSource, $xmlUri) Chris@0: { Chris@0: $newPath = str_replace('\\', '/', __DIR__).'/schema/dic/xliff-core/xml.xsd'; Chris@0: $parts = explode('/', $newPath); Chris@14: $locationstart = 'file:///'; Chris@0: if (0 === stripos($newPath, 'phar://')) { Chris@14: $tmpfile = tempnam(sys_get_temp_dir(), 'symfony'); Chris@0: if ($tmpfile) { Chris@0: copy($newPath, $tmpfile); Chris@0: $parts = explode('/', str_replace('\\', '/', $tmpfile)); Chris@14: } else { Chris@14: array_shift($parts); Chris@14: $locationstart = 'phar:///'; Chris@0: } Chris@0: } Chris@0: Chris@17: $drive = '\\' === \DIRECTORY_SEPARATOR ? array_shift($parts).'/' : ''; Chris@14: $newPath = $locationstart.$drive.implode('/', array_map('rawurlencode', $parts)); Chris@0: Chris@0: return str_replace($xmlUri, $newPath, $schemaSource); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the XML errors of the internal XML parser. Chris@0: * Chris@0: * @param bool $internalErrors Chris@0: * Chris@0: * @return array An array of errors Chris@0: */ Chris@0: private function getXmlErrors($internalErrors) Chris@0: { Chris@17: $errors = []; Chris@0: foreach (libxml_get_errors() as $error) { Chris@0: $errors[] = sprintf('[%s %s] %s (in %s - line %d, column %d)', Chris@0: LIBXML_ERR_WARNING == $error->level ? 'WARNING' : 'ERROR', Chris@0: $error->code, Chris@0: trim($error->message), Chris@0: $error->file ?: 'n/a', Chris@0: $error->line, Chris@0: $error->column Chris@0: ); Chris@0: } Chris@0: Chris@0: libxml_clear_errors(); Chris@0: libxml_use_internal_errors($internalErrors); Chris@0: Chris@0: return $errors; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets xliff file version based on the root "version" attribute. Chris@0: * Defaults to 1.2 for backwards compatibility. Chris@0: * Chris@0: * @param \DOMDocument $dom Chris@0: * Chris@0: * @throws InvalidArgumentException Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: private function getVersionNumber(\DOMDocument $dom) Chris@0: { Chris@0: /** @var \DOMNode $xliff */ Chris@0: foreach ($dom->getElementsByTagName('xliff') as $xliff) { Chris@0: $version = $xliff->attributes->getNamedItem('version'); Chris@0: if ($version) { Chris@0: return $version->nodeValue; Chris@0: } Chris@0: Chris@0: $namespace = $xliff->attributes->getNamedItem('xmlns'); Chris@0: if ($namespace) { Chris@14: if (0 !== substr_compare('urn:oasis:names:tc:xliff:document:', $namespace->nodeValue, 0, 34)) { Chris@0: throw new InvalidArgumentException(sprintf('Not a valid XLIFF namespace "%s"', $namespace)); Chris@0: } Chris@0: Chris@0: return substr($namespace, 34); Chris@0: } Chris@0: } Chris@0: Chris@0: // Falls back to v1.2 Chris@0: return '1.2'; Chris@0: } Chris@0: Chris@0: /** Chris@0: * @param \SimpleXMLElement|null $noteElement Chris@0: * @param string|null $encoding Chris@0: * Chris@0: * @return array Chris@0: */ Chris@0: private function parseNotesMetadata(\SimpleXMLElement $noteElement = null, $encoding = null) Chris@0: { Chris@17: $notes = []; Chris@0: Chris@0: if (null === $noteElement) { Chris@0: return $notes; Chris@0: } Chris@0: Chris@0: /** @var \SimpleXMLElement $xmlNote */ Chris@0: foreach ($noteElement as $xmlNote) { Chris@0: $noteAttributes = $xmlNote->attributes(); Chris@17: $note = ['content' => $this->utf8ToCharset((string) $xmlNote, $encoding)]; Chris@0: if (isset($noteAttributes['priority'])) { Chris@0: $note['priority'] = (int) $noteAttributes['priority']; Chris@0: } Chris@0: Chris@0: if (isset($noteAttributes['from'])) { Chris@0: $note['from'] = (string) $noteAttributes['from']; Chris@0: } Chris@0: Chris@0: $notes[] = $note; Chris@0: } Chris@0: Chris@0: return $notes; Chris@0: } Chris@0: }