Adds links to xml nodes to resolve paths

@param DomDocument $dom where to add links
166877
protected function _addLinks($dom)
    {
        $url = 'index.php?'; // session parameters will be included later (after cache processor)
        $xPath = new DomXPath($dom);

        // building
        $nodeList = $xPath->query("//SUBMENU[@cl]");
        foreach ($nodeList as $node) {
            // fetching class
            $cl = $node->getAttribute('cl');
            $cl = $cl ? "cl=$cl" : '';

            // fetching params
            $param = $node->getAttribute('clparam');
            $param = $param ? "&$param" : '';

            // setting link
            $node->setAttribute('link', "{$url}{$cl}{$param}");
        }
    }
561711
public function parseDom(\DOMDocument $dom)
    {
        return $this->parseSource(
            $dom,
            new DomDocumentFactory(),
            (new RdfaLiteElementProcessor())->setHtml(true),
            new RdfaLiteContext()
        );
    }
1270298
private function removeScripts(DOMDocument $dom)
    {
        foreach (['script', 'noscript'] as $tag) {
            $nodes = $dom->getElementsByTagName($tag);
            foreach (iterator_to_array($nodes) as $node) {
                NodeUtility::removeNode($node);
            }
        }
    }
315989
protected function transformLinksToRemoteLinks(DOMDocument $xml)
    {
        $xpath = new DOMXPath($xml);
        $xpath->registerNamespace('docbook', 'http://docbook.org/ns/docbook');

        foreach (array('ezembedinline', 'ezembed', 'link', 'ezlink') as $tagName) {
            $xpathExpression = "//docbook:{$tagName}[starts-with( @xlink:href, 'ezcontent://' ) or starts-with( @xlink:href, 'ezlocation://' )]";
            /** @var \DOMElement $element */
            foreach ($xpath->query($xpathExpression) as $element) {
                preg_match('~^(.+)://([^#]*)?(#.*|\\s*)?$~', $element->getAttribute('xlink:href'), $matches);
                list(, $scheme, $id, $fragment) = $matches;

                if (empty($id)) {
                    continue;
                }

                $href = '';

                if ($scheme === 'ezcontent') {
                    $object = eZContentObject::fetch($id);
                    if (!$object instanceof eZContentObject) {
                        continue;
                    }

                    $href = "{$scheme}://{$object->attribute('remote_id')}{$fragment}";
                } elseif ($scheme === 'ezlocation') {
                    $node = eZContentObjectTreeNode::fetch($id);
                    if (!$node instanceof eZContentObjectTreeNode) {
                        continue;
                    }

                    $href = "{$scheme}://{$node->attribute('remote_id')}{$fragment}";
                }

                if (empty($href)) {
                    continue;
                }

                $element->setAttribute('xlink:href', $href);
            }
        }
    }
14841
public function convert(DOMDocument $xmlDoc): void
    {
        foreach ($xmlDoc->getElementsByTagName('link') as $link) {
            /** @var \DOMElement $link */
            if (!$link->hasAttribute('custom:file')) {
                continue;
            }

            $content = null;
            $location = null;

            if ($link->hasAttribute('object_id')) {
                try {
                    $content = $this->loadService->loadContent($link->getAttribute('object_id'));
                    $location = $content->mainLocation;
                } catch (NotFoundException $e) {
                    $this->logger->warning(
                        'While generating links for xmltext, could not locate ' .
                        'Content object with ID ' . $link->getAttribute('object_id')
                    );
                } catch (UnauthorizedException $e) {
                    $this->logger->notice(
                        'While generating links for xmltext, unauthorized to load ' .
                        'Content object with ID ' . $link->getAttribute('object_id')
                    );
                }
            }

            if ($link->hasAttribute('node_id')) {
                try {
                    $location = $this->loadService->loadLocation($link->getAttribute('node_id'));
                    $content = $location->content;
                } catch (NotFoundException $e) {
                    $this->logger->warning(
                        'While generating links for xmltext, could not locate ' .
                        'Location with ID ' . $link->getAttribute('node_id')
                    );
                } catch (UnauthorizedException $e) {
                    $this->logger->notice(
                        'While generating links for xmltext, unauthorized to load ' .
                        'Location with ID ' . $link->getAttribute('node_id')
                    );
                }
            }

            if ($content !== null && $content->hasField('file')) {
                $field = $content->getField('file');
                if (!$field->isEmpty()) {
                    $url = $this->router->generate('ngsite_download', ['contentId' => $content->id, 'fieldId' => $field->id, 'isInline' => $link->hasAttribute('custom:inline')]);
                }
            }

            if (empty($url) && $location !== null) {
                $link->setAttribute('url', $this->router->generate($location));
            } elseif (!empty($url)) {
                $link->setAttribute('url', $url);
            } else {
                $link->setAttribute('url', '');
            }

            if ($link->hasAttribute('anchor_name')) {
                $link->setAttribute('url', $link->getAttribute('url') . '#' . $link->getAttribute('anchor_name'));
            }

            // With this we disable the original pre-converter
            // (and hopefully all other that touch link element)
            $link->removeAttribute('object_id');
            $link->removeAttribute('node_id');
            $link->removeAttribute('anchor_name');
        }
    }
1324625
private function createText(\DOMDocument $dom, \DOMNode $node, $value)
    {
        $text = $dom->createTextNode($value);
        $node->appendChild($text);
    }
1286592
private function writeDocument(\DOMDocument $dom)
    {
        $dom->formatOutput = true;
        $this->write($dom->saveXML());
    }
503630
protected function fixDocument(DOMDocument $document)
    {
        $rootElement = $document->firstChild;

        $xp = new DOMXPath($document);

        $nodes = $xp->query("/testsuites/testsuite/testsuite/testsuite");

        if ($nodes->length === 0) {
            $nodes = $xp->query("/testsuites/testsuite");

            foreach ($nodes as $node) {
                $children = $xp->query("./testsuite", $node);

                if ($children->length) {
                    $this->handleChildren($rootElement, $children);
                    $rootElement->removeChild($node);
                }
            }
        } else {
            $nodes = $xp->query("/testsuites/testsuite/testsuite");

            foreach ($nodes as $node) {
                $children = $xp->query("./testsuite", $node);

                if ($children->length) {
                    $this->handleChildren($rootElement, $children);
                    $rootElement->firstChild->removeChild($node);
                }
            }
        }
    }
182821
protected function appendNode(DOMNode $node, $xquery = null)
    {
      // Determine parent node
      if(!is_null($xquery))
        $parentNode = $this->getNode($xquery);
      else if(!is_null($this->node))
        $parentNode = $this->node;
      else
        $parentNode = $this->document;

      $parentNode->appendChild($node);
    }
585356
public static function addNodePathSegment($nodePath, $nodePathSegment)
    {
        $nodePath = rtrim($nodePath, '/');
        if ($nodePathSegment !== '' || $nodePath === '') {
            $nodePath .= '/' . trim($nodePathSegment, '/');
        }

        return $nodePath;
    }
1356816
protected function buildXmlFromTraversable(\DOMDocument $dom, \DOMNode $node, $data)
    {
        $normalizer    = $this->getNormalizer();
        $hasAttributes = false;
        $isList        = is_array($data) && Arr::isList($data, true);

        foreach ($data as $key => $value) {
            if (!is_scalar($value) && !($value = $normalizer->ensureBuildable($value))) {
                continue;
            }

            if ($this->mapAttributes($node, $normalizer->normalize($key), $value)) {
                $hasAttributes = true;
                continue;
            }

            // ensure "node value keys" are at the bottom.
            if (null !== $this->nodeValueKey && is_array($value) && isset($value[$this->nodeValueKey])) {
                $val = $value[$this->nodeValueKey];
                unset($value[$this->nodeValueKey]);
                $value[$this->nodeValueKey] = $val;
            }

            // Set the default index key if there's no other way.
            if (is_int($key) || !$this->isValidNodeName($key)) {
                $cey = $key;
                $key = $this->indexKey;
                // In order to keep the original index for none "list-like" arrays
                // (numeric keys and none zero based indecies) add the original key
                // as index attribute
                if (is_int($cey) && !$isList) {
                    $value = [
                        '@AAA' => [$this->indexAttrKey ?: 'index' => $cey],
                        $this->nodeValueKey ?: 'value' => $value,
                    ];
                }
            }

            if (is_array($value) && !is_int($key) && $this->appendDomList($normalizer, $dom, $node, $key, $value)) {
                continue;
            }

            // if this is a non scalar value at this time, just set the
            // value on the element
            if ($this->isXMLElement($value)) {
                $element = $dom->createElement($normalizer->normalize($key));
                $node->appendChild($element);
                $this->setElementValue($dom, $element, $value);
                continue;
            }

            if ($this->isValidNodeName($key)) {
                $this->appendDOMNode($dom, $node, $normalizer->normalize($key), $value, $hasAttributes);
            }
        }
    }
105563
public function validateSchema(\DOMDocument $dom)
    {
        $schemaLocations = ['http://symfony.com/schema/dic/services' => str_replace('\\', '/', __DIR__.'/schema/dic/services/services-1.0.xsd')];

        if ($element = $dom->documentElement->getAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'schemaLocation')) {
            $items = preg_split('/\s+/', $element);
            for ($i = 0, $nb = \count($items); $i < $nb; $i += 2) {
                if (!$this->container->hasExtension($items[$i])) {
                    continue;
                }

                if (($extension = $this->container->getExtension($items[$i])) && false !== $extension->getXsdValidationBasePath()) {
                    $ns = $extension->getNamespace();
                    $path = str_replace([$ns, str_replace('http://', 'https://', $ns)], str_replace('\\', '/', $extension->getXsdValidationBasePath()).'/', $items[$i + 1]);

                    if (!is_file($path)) {
                        throw new RuntimeException(sprintf('Extension "%s" references a non-existent XSD file "%s"', \get_class($extension), $path));
                    }

                    $schemaLocations[$items[$i]] = $path;
                }
            }
        }

        $tmpfiles = [];
        $imports = '';
        foreach ($schemaLocations as $namespace => $location) {
            $parts = explode('/', $location);
            $locationstart = 'file:///';
            if (0 === stripos($location, 'phar://')) {
                $tmpfile = tempnam(sys_get_temp_dir(), 'symfony');
                if ($tmpfile) {
                    copy($location, $tmpfile);
                    $tmpfiles[] = $tmpfile;
                    $parts = explode('/', str_replace('\\', '/', $tmpfile));
                } else {
                    array_shift($parts);
                    $locationstart = 'phar:///';
                }
            }
            $drive = '\\' === \DIRECTORY_SEPARATOR ? array_shift($parts).'/' : '';
            $location = $locationstart.$drive.implode('/', array_map('rawurlencode', $parts));

            $imports .= sprintf('  <xsd:import namespace="%s" schemaLocation="%s" />'."\n", $namespace, $location);
        }

        $source = <<<EOF
<?xml version="1.0" encoding="utf-8" ?>
<xsd:schema xmlns="http://symfony.com/schema"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://symfony.com/schema"
    elementFormDefault="qualified">

    <xsd:import namespace="http://www.w3.org/XML/1998/namespace"/>
$imports
</xsd:schema>
EOF
        ;

        $disableEntities = libxml_disable_entity_loader(false);
        $valid = @$dom->schemaValidateSource($source);
        libxml_disable_entity_loader($disableEntities);

        foreach ($tmpfiles as $tmpfile) {
            @unlink($tmpfile);
        }

        return $valid;
    }
118792
protected function validate(\DOMDocument $dom)
    {
        $restRoutinglocation = realpath(__DIR__.'/../../Resources/config/schema/routing/rest_routing-1.0.xsd');
        $restRoutinglocation = rawurlencode(str_replace('\\', '/', $restRoutinglocation));
        $routinglocation = realpath(__DIR__.'/../../Resources/config/schema/routing-1.0.xsd');
        $routinglocation = rawurlencode(str_replace('\\', '/', $routinglocation));
        $source = <<<EOF
<?xml version="1.0" encoding="utf-8" ?>
<xsd:schema xmlns="http://symfony.com/schema"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://symfony.com/schema"
    elementFormDefault="qualified">

    <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
    <xsd:import namespace="http://friendsofsymfony.github.com/schema/rest" schemaLocation="$restRoutinglocation" />
    <xsd:import namespace="http://symfony.com/schema/routing" schemaLocation="$routinglocation" />
</xsd:schema>
EOF;

        $current = libxml_use_internal_errors(true);
        libxml_clear_errors();

        if (!$dom->schemaValidateSource($source)) {
            throw new \InvalidArgumentException(implode("\n", $this->getXmlErrors_($current)));
        }
        libxml_use_internal_errors($current);
    }
388146
protected function importItems(\DOMDocument $xml)
    {
        foreach ($xml->documentElement->getElementsByTagName('item') as $item) {
            $dom = simplexml_import_dom($item);
            $this->addMenuItem($dom);
        }
    }
511740
private function extractLinks(DOMDocument $html)
    {
        foreach ($html->getElementsByTagName('link') as $link) {
            if ($link->hasAttribute('rel') && $link->hasAttribute('href')) {
                $rel = trim(strtolower($link->getAttribute('rel')));
                $href = $link->getAttribute('href');

                if (empty($href)) {
                    continue;
                }

                switch ($rel) {
                    case 'favicon':
                    case 'favico':
                    case 'icon':
                    case 'shortcut icon':
                    case 'apple-touch-icon-precomposed':
                    case 'apple-touch-icon':
                        $this->bag->add('icons', $href);
                        break;

                    case 'image_src':
                        $this->bag->add('images', $href);
                        break;

                    case 'alternate':
                        switch ($link->getAttribute('type')) {
                            case 'application/atom+xml':
                            case 'application/json':
                            case 'application/rdf+xml':
                            case 'application/rss+xml':
                            case 'application/xml':
                            case 'text/xml':
                                $this->bag->add('feeds', $href);
                                break;
                        }
                        break;

                    default:
                        $this->bag->set($rel, $href);
                }
            }
        }
    }
1331695
public function validate(DOMDocument $xml)
    {
        $errors = [];

        $xpath = new DOMXPath($xml);
        foreach ($xpath->query('//link') as $link) {
            if ($link->hasAttribute('object_id')) {
                $objectId = $link->getAttribute('object_id');
                if ($objectId && !$this->validateEzObject($objectId)) {
                    $errors[] = $this->getInvalidLinkError('ezobject', $objectId, $link->getAttribute('anchor_name'));
                }
            } elseif ($link->hasAttribute('node_id')) {
                $nodeId = $link->getAttribute('node_id');
                if ($nodeId && !$this->validateEzNode($nodeId)) {
                    $errors[] = $this->getInvalidLinkError('eznode', $nodeId, $link->getAttribute('anchor_name'));
                }
            }
        }

        return $errors;
    }
1056688
function createLinksArray( $dom )
    {
        $links = array();
        $node = array();

        if ( $dom )
        {
            // Fetch all links and cache the url's
            $links = $dom->getElementsByTagName( "link" );
        }

        $linkIDArray = array();
        // Find all Link id's
        foreach ( $links as $link )
        {
            $linkIDValue = $link->getAttribute( 'url_id' );
            if ( !$linkIDValue )
            {
                continue;
            }
            if ( !in_array( $linkIDValue, $linkIDArray ) )
            {
                 $linkIDArray[] = $linkIDValue;
             }
        }

        if ( count( $linkIDArray ) > 0 )
        {
            $inIDSQL = implode( ', ', $linkIDArray );
            $db = eZDB::instance();
            $linkArray = $db->arrayQuery( "SELECT * FROM ezurl WHERE id IN ( $inIDSQL ) " );
            foreach ( $linkArray as $linkRow )
            {
                $this->LinkArray[$linkRow['id']] = $linkRow['url'];
            }
        }
    }