Example #1
0
 /**
  * Build DOM with initial XML contents and specifying identifier attributes for merging
  *
  * Format of $idAttributes: array('/xpath/to/some/node' => 'id_attribute_name')
  * The path to ID attribute name should not include any attribute notations or modifiers -- only node names
  *
  * @param string $xml
  * @param array $idAttributes
  * @param string $typeAttributeName
  * @param string $schemaFile
  * @param string $errorFormat
  */
 public function __construct($xml, array $idAttributes = array(), $typeAttributeName = null, $schemaFile = null, $errorFormat = self::ERROR_FORMAT_DEFAULT)
 {
     $this->_schemaFile = $schemaFile;
     $this->_nodeMergingConfig = new Dom\NodeMergingConfig(new Dom\NodePathMatcher(), $idAttributes);
     $this->_typeAttributeName = $typeAttributeName;
     $this->_errorFormat = $errorFormat;
     $this->_dom = $this->_initDom($xml);
     $this->_rootNamespace = $this->_dom->lookupNamespaceUri($this->_dom->namespaceURI);
 }
Example #2
0
function parseXmlStream($content, $field_mapping)
{
    $res = array();
    $xml = new DOMDocument();
    $xml->loadXML($content);
    $xpath = new DOMXpath($xml);
    $rootNamespace = $xml->lookupNamespaceUri($xml->namespaceURI);
    $xpath->registerNamespace('x', $rootNamespace);
    foreach ($field_mapping as $skey => $sval) {
        $path = preg_replace("/\\/([a-zA-Z])/", "/x:\$1", $skey);
        $elements = $xpath->query($path);
        if (!is_null($elements)) {
            $ele_cnt = 1;
            foreach ($elements as $element) {
                foreach ($sval as $field => $innerpath) {
                    $ipath = preg_replace(array("/^([a-zA-Z])/", "/\\/([a-zA-Z])/"), array("x:\$1", "/x:\$1"), $innerpath);
                    $val = $xpath->query($ipath, $element)->item(0)->textContent;
                    if ($val) {
                        $field_details = explode(':', $field);
                        $res[$field_details[0]][$ele_cnt][$field_details[1]] = $val;
                    }
                }
                $ele_cnt++;
            }
        }
    }
    return $res;
}
 /**
  * Add Certificate to the Role
  *
  * @param string $roleName
  * @param RemoteDesktopCertificate $certificate
  */
 public function addCertificate($roleName, RemoteDesktopCertificate $certificate)
 {
     $namespaceUri = $this->dom->lookupNamespaceUri($this->dom->namespaceURI);
     $xpath = new \DOMXpath($this->dom);
     $xpath->registerNamespace('sc', $namespaceUri);
     $xpathExpression = '//sc:Role[@name="' . $roleName . '"]//sc:Certificates';
     $certificateList = $xpath->evaluate($xpathExpression);
     if ($certificateList->length == 1) {
         $certificatesNode = $certificateList->item(0);
         foreach ($certificatesNode->childNodes as $certificateNode) {
             $certificatesNode->removeElement($certificateNode);
         }
     } else {
         $certificatesNode = $this->dom->createElementNS($namespaceUri, 'Certificates');
         $roleNodeList = $xpath->evaluate('//sc:Role[@name="' . $roleName . '"]');
         if ($roleNodeList->length == 0) {
             throw new \RuntimeException("No Role found with name '" . $roleName . "'.");
         }
         $roleNode = $roleNodeList->item(0);
         $roleNode->appendChild($certificatesNode);
     }
     $certificateNode = $this->dom->createElementNS($namespaceUri, 'Certificate');
     $certificateNode->setAttribute('name', 'Microsoft.WindowsAzure.Plugins.RemoteAccess.PasswordEncryption');
     $certificateNode->setAttribute('thumbprint', $certificate->getThumbprint());
     $certificateNode->setAttribute('thumbprintAlgorithm', 'sha1');
     $certificatesNode->appendChild($certificateNode);
     $this->save();
 }
    /**
     * Copy ServiceConfiguration over to build directory given with target path
     * and modify some of the settings to point to development settings.
     *
     * @param string $targetPath
     * @return void
     */
    public function copyForDeployment($targetPath, $development = true)
    {
        $dom = new \DOMDocument('1.0', 'UTF-8');
        $dom->loadXML($this->dom->saveXML());
        $xpath = new \DOMXpath($dom);
        $xpath->registerNamespace('sc', $dom->lookupNamespaceUri($dom->namespaceURI));
        $settings = $xpath->evaluate('//sc:ConfigurationSettings/sc:Setting[@name="Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString"]');
        foreach ($settings as $setting) {
            if ($development) {
                $setting->setAttribute('value', 'UseDevelopmentStorage=true');
            } else {
                if (strlen($setting->getAttribute('value')) === 0) {
                    if ($this->storage) {
                        $setting->setAttribute('value', sprintf('DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s', $this->storage['accountName'], $this->storage['accountKey']));
                    } else {
                        throw new \RuntimeException(<<<EXC
ServiceConfiguration.csdef: Missing value for
'Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString'.

You have to modify the app/azure/ServiceConfiguration.csdef to contain
a value for the diagnostics connection string or better configure
'windows_azure_distribution.diagnostics.accountName' and
'windows_azure_distribution.diagnostics.accountKey' in your
app/config/config.yml

If you don't want to enable diagnostics you should delete the
connection string elements from ServiceConfiguration.csdef file.
EXC
);
                    }
                }
            }
        }
        $dom->save($targetPath . '/ServiceConfiguration.cscfg');
    }
Example #5
0
 /**
  * Build DOM with initial XML contents and specifying identifier attributes for merging
  *
  * Format of $idAttributes: array('/xpath/to/some/node' => 'id_attribute_name')
  * The path to ID attribute name should not include any attribute notations or modifiers -- only node names
  *
  * @param string $xml
  * @param \Magento\Framework\Config\ValidationStateInterface $validationState
  * @param array $idAttributes
  * @param string $typeAttributeName
  * @param string $schemaFile
  * @param string $errorFormat
  */
 public function __construct($xml, \Magento\Framework\Config\ValidationStateInterface $validationState, array $idAttributes = [], $typeAttributeName = null, $schemaFile = null, $errorFormat = self::ERROR_FORMAT_DEFAULT)
 {
     $this->validationState = $validationState;
     $this->schema = $schemaFile;
     $this->nodeMergingConfig = new Dom\NodeMergingConfig(new Dom\NodePathMatcher(), $idAttributes);
     $this->typeAttributeName = $typeAttributeName;
     $this->errorFormat = $errorFormat;
     $this->dom = $this->_initDom($xml);
     $this->rootNamespace = $this->dom->lookupNamespaceUri($this->dom->namespaceURI);
 }
Example #6
0
 public function getInfo($sUrl)
 {
     $oDom = new \DOMDocument();
     if (!@$oDom->load(static::API_URL . $this->getVideoId($sUrl))) {
         return false;
     }
     $this->oData = new \DOMXPath($oDom);
     $sRootNameSpace = $oDom->lookupNamespaceUri($oDom->namespaceURI);
     $this->oData->registerNamespace('media', $sRootNameSpace);
     return $this;
 }
Example #7
0
 static function loadXml($xml, $nsPrefix = 'd')
 {
     $dom = new \DOMDocument();
     @$dom->loadXML($xml);
     $xpath = new \DomXPath($dom);
     $rootNamespace = $dom->lookupNamespaceUri($dom->namespaceURI);
     if ($rootNamespace) {
         if ($dom->documentElement->getAttribute('xmlns:d')) {
             Debug::toss('Namespace prefix "' . $nsPrefix . '" taken');
         }
         $xpath->registerNamespace($nsPrefix, $rootNamespace);
         $nsPrefix .= ':';
     } else {
         $nsPrefix = '';
     }
     return array($dom, $xpath, $nsPrefix);
 }
Example #8
0
 /**
  * Constructor.
  *
  * @param resource|string $xml The package.xml as stream or path.
  */
 public function __construct($xml, $factory = null)
 {
     if (is_resource($xml)) {
         rewind($xml);
     } else {
         $this->_path = $xml;
         $xml = fopen($xml, 'r');
     }
     $old_libxml_use_errors = libxml_use_internal_errors(true);
     $this->_xml = new DOMDocument('1.0', 'UTF-8');
     $this->_xml->loadXML(stream_get_contents($xml));
     foreach (libxml_get_errors() as $error) {
         switch ($error->level) {
             case LIBXML_ERR_WARNING:
                 $error_str = 'Warning ';
                 break;
             case LIBXML_ERR_ERROR:
                 $error_str = 'Error ';
                 break;
             case LIBXML_ERR_FATAL:
                 $error_str = 'Fatal error ';
                 break;
         }
         $error_str .= $error->code . ': ';
         $error_str .= trim($error->message) . ' on file ';
         $error_str .= $this->_path . ', line ' . $error->line . ' column ' . $error->column;
         fwrite(STDERR, "{$error_str}\n");
     }
     libxml_clear_errors();
     libxml_use_internal_errors($old_libxml_use_errors);
     $rootNamespace = $this->_xml->lookupNamespaceUri($this->_xml->namespaceURI);
     $this->_xpath = new DOMXpath($this->_xml);
     if ($rootNamespace !== null) {
         $this->_xpath->registerNamespace('p', $rootNamespace);
         $this->_namespace_prefix = 'p:';
     }
     if ($factory === null) {
         $this->_factory = new Horde_Pear_Package_Xml_Factory();
     } else {
         $this->_factory = $factory;
     }
 }
Example #9
0
 /**
  * @override
  * @see \Magento\Framework\Config\Dom::_initDom()
  * @param string $xml
  * @return \DOMDocument
  * @throws \Magento\Framework\Config\Dom\ValidationException
  */
 protected function _initDom($xml)
 {
     /** @var string $defaultSchema */
     $defaultSchema = $this->schema;
     /** @var \DOMDocument $dom */
     $dom = new \DOMDocument();
     $dom->loadXML($xml);
     // Возвращает строку вида: «urn:magento:module:Magento_Config:etc/system_file.xsd»
     /** @var string $schema */
     $schema = $dom->documentElement->getAttributeNS($dom->lookupNamespaceUri('xsi'), 'noNamespaceSchemaLocation');
     /**
      * Используем df_starts_with($customSchema, 'urn:')
      * для совместимости с устаревшим и нигде в ядре не используемым форматом
      * с обратными файловыми путями: ../
      *
      * 2016-06-07
      * Раньше тут стояло:
      * if ($schema && && df_starts_with($schema, 'urn:')
      * Однако сторонние модули используют хуёвые невалидные схемы типа
      * urn:magento:framework:Backend/etc/system_file.xsd
      * что приводило к сбоям.
      */
     if ($schema && 'urn:magento:module:Df_Config:etc/system_file.xsd' === $schema) {
         /**
          * Переводить схему в формат файлового пути необязательно:
          * https://github.com/magento/magento2/blob/2335247d4ae2dc1e0728ee73022b0a244ccd7f4c/lib/internal/Magento/Framework/Config/Dom/UrnResolver.php#L69-L71
          * https://github.com/magento/magento2/blob/2335247d4ae2dc1e0728ee73022b0a244ccd7f4c/lib/internal/Magento/Framework/Config/Dom/UrnResolver.php#L26-L55
          */
         $this->schema = $schema;
     }
     /** @var \DOMDocument $result */
     try {
         $result = parent::_initDom($xml);
     } finally {
         $this->schema = $defaultSchema;
     }
     return $result;
 }
 /**
  * This function will load an extension's meta information given the extension
  * `$name`. Since Symphony 2.3, this function will look for an `extension.meta.xml`
  * file inside the extension's folder. If this is not found, it will initialise
  * the extension and invoke the `about()` function. By default this extension will
  * return an associative array display the basic meta data about the given extension.
  * If the `$rawXML` parameter is passed true, and the extension has a `extension.meta.xml`
  * file, this function will return `DOMDocument` of the file.
  *
  * @deprecated Since Symphony 2.3, the `about()` function is deprecated for extensions
  *  in favour of the `extension.meta.xml` file.
  * @param string $name
  *  The name of the Extension Class minus the extension prefix.
  * @param boolean $rawXML
  *  If passed as true, and is available, this function will return the
  *  DOMDocument of representation of the given extension's `extension.meta.xml`
  *  file. If the file is not available, the extension will return the normal
  *  `about()` results. By default this is false.
  * @return array
  *  An associative array describing this extension
  */
 public static function about($name, $rawXML = false)
 {
     // See if the extension has the new meta format
     if (file_exists(self::__getClassPath($name) . '/extension.meta.xml')) {
         try {
             $meta = new DOMDocument();
             $meta->load(self::__getClassPath($name) . '/extension.meta.xml');
             $xpath = new DOMXPath($meta);
             $rootNamespace = $meta->lookupNamespaceUri($meta->namespaceURI);
             if (is_null($rootNamespace)) {
                 throw new Exception(__('Missing default namespace definition.'));
             } else {
                 $xpath->registerNamespace('ext', $rootNamespace);
             }
         } catch (Exception $ex) {
             throw new SymphonyErrorPage(__('The %1$s file for the %2$s extension is not valid XML: %3$s', array('<code>extension.meta.xml</code>', '<code>' . $name . '</code>', '<br /><code>' . $ex->getMessage() . '</code>')));
         }
         // If `$rawXML` is set, just return our DOMDocument instance
         if ($rawXML) {
             return $meta;
         }
         // Load <extension>
         $extension = $xpath->query('/ext:extension')->item(0);
         $about = array('name' => $xpath->evaluate('string(ext:name)', $extension), 'status' => array());
         // find the latest <release> (largest version number)
         $latest_release_version = '0.0.0';
         foreach ($xpath->query('//ext:release', $extension) as $release) {
             $version = $xpath->evaluate('string(@version)', $release);
             if (version_compare($version, $latest_release_version, '>')) {
                 $latest_release_version = $version;
             }
         }
         // Load the latest <release> information
         if ($release = $xpath->query("//ext:release[@version='{$latest_release_version}']", $extension)->item(0)) {
             $about += array('version' => $xpath->evaluate('string(@version)', $release), 'release-date' => $xpath->evaluate('string(@date)', $release));
             // If it exists, load in the 'min/max' version data for this release
             $required_version = null;
             $required_min_version = $xpath->evaluate('string(@min)', $release);
             $required_max_version = $xpath->evaluate('string(@max)', $release);
             $current_symphony_version = Symphony::Configuration()->get('version', 'symphony');
             // Min version
             if (!empty($required_min_version) && version_compare($current_symphony_version, $required_min_version, '<')) {
                 $about['status'][] = EXTENSION_NOT_COMPATIBLE;
                 $about['required_version'] = $required_min_version;
             } else {
                 if (!empty($required_max_version) && version_compare($current_symphony_version, $required_max_version, '>')) {
                     $about['status'][] = EXTENSION_NOT_COMPATIBLE;
                     $about['required_version'] = $required_max_version;
                 }
             }
         }
         // Add the <author> information
         foreach ($xpath->query('//ext:author', $extension) as $author) {
             $a = array('name' => $xpath->evaluate('string(ext:name)', $author), 'website' => $xpath->evaluate('string(ext:website)', $author), 'email' => $xpath->evaluate('string(ext:email)', $author));
             $about['author'][] = array_filter($a);
         }
     } else {
         $obj = self::getInstance($name);
         $about = $obj->about();
         // If this is empty then the extension has managed to not provide
         // an `about()` function or an `extension.meta.xml` file. So
         // ignore this extension even exists
         if (empty($about)) {
             return array();
         }
         $about['status'] = array();
     }
     $about['handle'] = $name;
     $about['status'] = array_merge($about['status'], self::fetchStatus($about));
     return $about;
 }
 /**
  * This function will load an extension's meta information given the extension
  * `$name`. Since Symphony 2.3, this function will look for an `extension.meta.xml`
  * file inside the extension's folder. If this is not found, it will initialise
  * the extension and invoke the `about()` function. By default this extension will
  * return an associative array display the basic meta data about the given extension.
  * If the `$rawXML` parameter is passed true, and the extension has a `extension.meta.xml`
  * file, this function will return `DOMDocument` of the file.
  *
  * @param string $name
  *  The name of the Extension Class minus the extension prefix.
  * @param boolean $rawXML
  *  If passed as true, and is available, this function will return the
  *  DOMDocument of representation of the given extension's `extension.meta.xml`
  *  file. If the file is not available, the extension will return the normal
  *  `about()` results. By default this is false.
  * @throws Exception
  * @throws SymphonyErrorPage
  * @return array
  *  An associative array describing this extension
  */
 public static function about($name, $rawXML = false)
 {
     // See if the extension has the new meta format
     if (file_exists(self::__getClassPath($name) . '/extension.meta.xml')) {
         try {
             $meta = new DOMDocument();
             $meta->load(self::__getClassPath($name) . '/extension.meta.xml');
             $xpath = new DOMXPath($meta);
             $rootNamespace = $meta->lookupNamespaceUri($meta->namespaceURI);
             if (is_null($rootNamespace)) {
                 throw new Exception(__('Missing default namespace definition.'));
             } else {
                 $xpath->registerNamespace('ext', $rootNamespace);
             }
         } catch (Exception $ex) {
             Symphony::Engine()->throwCustomError(__('The %1$s file for the %2$s extension is not valid XML: %3$s', array('<code>extension.meta.xml</code>', '<code>' . $name . '</code>', '<br /><code>' . $ex->getMessage() . '</code>')));
         }
         // Load <extension>
         $extension = $xpath->query('/ext:extension')->item(0);
         // Check to see that the extension is named correctly, if it is
         // not, then return nothing
         if (self::__getClassName($name) !== self::__getClassName($xpath->evaluate('string(@id)', $extension))) {
             return array();
         }
         // If `$rawXML` is set, just return our DOMDocument instance
         if ($rawXML) {
             return $meta;
         }
         $about = array('name' => $xpath->evaluate('string(ext:name)', $extension), 'handle' => $name, 'github' => $xpath->evaluate('string(ext:repo)', $extension), 'discuss' => $xpath->evaluate('string(ext:url[@type="discuss"])', $extension), 'homepage' => $xpath->evaluate('string(ext:url[@type="homepage"])', $extension), 'wiki' => $xpath->evaluate('string(ext:url[@type="wiki"])', $extension), 'issues' => $xpath->evaluate('string(ext:url[@type="issues"])', $extension), 'status' => array());
         // find the latest <release> (largest version number)
         $latest_release_version = '0.0.0';
         foreach ($xpath->query('//ext:release', $extension) as $release) {
             $version = $xpath->evaluate('string(@version)', $release);
             if (version_compare($version, $latest_release_version, '>')) {
                 $latest_release_version = $version;
             }
         }
         // Load the latest <release> information
         if ($release = $xpath->query("//ext:release[@version='{$latest_release_version}']", $extension)->item(0)) {
             $about += array('version' => $xpath->evaluate('string(@version)', $release), 'release-date' => $xpath->evaluate('string(@date)', $release));
             // If it exists, load in the 'min/max' version data for this release
             $required_min_version = $xpath->evaluate('string(@min)', $release);
             $required_max_version = $xpath->evaluate('string(@max)', $release);
             $current_symphony_version = Symphony::Configuration()->get('version', 'symphony');
             // Remove pre-release notes from the current Symphony version so that
             // we don't get false erros in the backend
             $current_symphony_version = preg_replace(array('/dev/i', '/-?beta\\.?\\d/i', '/-?rc\\.?\\d/i', '/.0/i'), '', $current_symphony_version);
             // Munge the version number so that it makes sense in the backend.
             // Consider, 2.3.x. As the min version, this means 2.3 onwards,
             // for the max it implies any 2.3 release. RE: #1019
             // Also remove any .0 when doing the comparison to prevent extensions
             // that don't use semver yet. RE: #2146
             $required_min_version = preg_replace(array('/\\.x/', '/\\.0$/'), '', $required_min_version);
             $required_max_version = preg_replace(array('/\\.x/', '/\\.0$/'), 'p', $required_max_version);
             // Min version
             if (!empty($required_min_version) && version_compare($current_symphony_version, $required_min_version, '<')) {
                 $about['status'][] = Extension::EXTENSION_NOT_COMPATIBLE;
                 $about['required_version'] = $required_min_version;
                 // Max version
             } elseif (!empty($required_max_version) && version_compare($current_symphony_version, $required_max_version, '>')) {
                 $about['status'][] = Extension::EXTENSION_NOT_COMPATIBLE;
                 $about['required_version'] = str_replace('p', '.x', $required_max_version);
             }
         }
         // Add the <author> information
         foreach ($xpath->query('//ext:author', $extension) as $author) {
             $a = array('name' => $xpath->evaluate('string(ext:name)', $author), 'website' => $xpath->evaluate('string(ext:website)', $author), 'github' => $xpath->evaluate('string(ext:name/@github)', $author), 'email' => $xpath->evaluate('string(ext:email)', $author));
             $about['author'][] = array_filter($a);
         }
         $about['status'] = array_merge($about['status'], self::fetchStatus($about));
         return $about;
     } else {
         Symphony::Log()->pushToLog(sprintf('%s does not have an extension.meta.xml file', $name), E_DEPRECATED, true);
         return array();
     }
 }
Example #12
0
 public function replaceXml($file)
 {
     $dom = new \DOMDocument('1.0', 'UTF-8');
     if ($dom->load($file) === true) {
         $xpath = new \DOMXPath($dom);
         $textNodes = $xpath->query('//text()');
         unset($xpath);
         foreach ($textNodes as $textNode) {
             if (ctype_space($textNode->wholeText) === false) {
                 $string = trim($textNode->wholeText);
                 if (strlen($string) > 1 && !is_numeric($string)) {
                     $nodeName = $textNode->parentNode->nodeName;
                     if (strpos($nodeName, ':') !== false) {
                         list($prefix, $suffix) = explode(':', $nodeName, 2);
                         $nodeName = $dom->lookupNamespaceUri($prefix) . ':' . $suffix;
                     }
                     if (in_array($nodeName, self::$replace)) {
                         //$replacement = mb_substr($lstrnig, mb_strpos($lstrnig, ' ',rand(0, 2000))+1, strlen($string));
                         $replacement = mb_substr(self::$replacement, rand(0, 1300), strlen($string), "UTF-8");
                         $textNode->data = $replacement;
                     } elseif (!in_array($nodeName, self::$leave)) {
                         throw new UndefinedStrategy('Unknown Tag "' . $nodeName . '" with value "' . $string . '"');
                     }
                 }
             }
         }
     } else {
         echo '[EE] "' . $file . '" is not a valid XML file' . PHP_EOL;
     }
     if (!$this->dryRun) {
         $dom->save($file);
     }
     $xpath = new \DOMXPath($dom);
     $xpath->registerNamespace('xi', 'http://www.w3.org/2001/XInclude');
     foreach ($xpath->query('//xi:include') as $node) {
         $includefile = dirname($file) . DIRECTORY_SEPARATOR . $node->getAttribute('href');
         $this->addXml($includefile);
     }
     $this->done[] = $file;
 }
 /**
  * @param OutputInterface $output
  * @param \SplFileInfo    $feed
  * @param string          $filterExpression
  *
  * @return array<array, integer>
  */
 protected function inspect(OutputInterface $output, \SplFileInfo $feed, $filterExpression)
 {
     $options = LIBXML_NOENT | LIBXML_NONET | LIBXML_COMPACT | LIBXML_PARSEHUGE | LIBXML_NOERROR | LIBXML_NOWARNING;
     $this->reader = new \XMLReader($options);
     $this->reader->open($feed->getPathname());
     $this->reader->setParserProperty(\XMLReader::SUBST_ENTITIES, true);
     libxml_clear_errors();
     libxml_use_internal_errors(true);
     libxml_disable_entity_loader(true);
     $total = 0;
     $results = [];
     $output->writeln(sprintf('Reading <comment>%s</comment>', $feed->getFilename()));
     if ($filterExpression) {
         $output->writeln(sprintf('Filtering nodes with expression "<info>%s</info>"', $filterExpression));
     }
     $progress = new ProgressBar($output);
     $progress->start();
     // go through the whole thing
     while ($this->reader->read()) {
         if ($this->reader->nodeType === \XMLReader::ELEMENT && $this->reader->name === 'listing') {
             $progress->advance();
             ++$total;
             $node = $this->reader->expand();
             $doc = new \DOMDocument();
             $doc->appendChild($node);
             $xpath = new \DOMXPath($doc);
             $xpath->registerNamespace('x', $doc->lookupNamespaceUri($doc->namespaceURI));
             $query = $xpath->evaluate($filterExpression, $node);
             $result = $query instanceof \DOMNodeList ? $query->length : !empty($query);
             if ($result) {
                 $results[] = $node;
             }
         }
     }
     $progress->finish();
     $output->writeln('');
     return [$results, $total];
 }
Example #14
0
 /**
  * function_description
  *
  * @param   string  $xml  track xml object
  *
  * @return array
  */
 private function extractCoordsKML($xml)
 {
     // TODO use XMLReader
     $xmldom = new DOMDocument();
     $xmldom->loadXML($xml->asXML());
     $rootNamespace = $xmldom->lookupNamespaceUri($xmldom->namespaceURI);
     $xpath = new DomXPath($xmldom);
     $xpath->registerNamespace('kml', $rootNamespace);
     $documentNodes = $xpath->query('kml:Document/kml:name|kml:Document/kml:description');
     $gps_file_name = '';
     $gps_file_description = '';
     // Search for NAME (Title) and description of GPS file
     foreach ($documentNodes as $documentNode) {
         switch ($documentNode->nodeName) {
             case 'name':
                 $gps_file_name .= preg_replace('/<!\\[CDATA\\[(.*?)\\]\\]>/s', '', $documentNode->nodeValue);
                 break;
             case 'description':
                 $gps_file_description .= preg_replace('/<!\\[CDATA\\[(.*?)\\]\\]>/s', '', $documentNode->nodeValue);
                 break;
         }
     }
     // Search for tracks (name (title), description and coordinates
     $placemarkNodes = $xpath->query('//kml:Placemark');
     $this->trackCount = 0;
     $tracks_description = '';
     $track_name = '';
     foreach ($placemarkNodes as $placemarkNode) {
         $nodes = $xpath->query('.//kml:name|.//kml:description|.//kml:LineString|.//kml:coordinates', $placemarkNode);
         if ($nodes) {
             $found_linestring = false;
             $name = '';
             $description = '';
             $coordinates = null;
             foreach ($nodes as $node) {
                 switch ($node->nodeName) {
                     case 'name':
                         $name = $node->nodeValue;
                         break;
                     case 'description':
                         $description = $node->nodeValue;
                         $tracks_description .= $description;
                         $description = ($description = '&nbsp;') ? '' : $description;
                         break;
                     case 'LineString':
                         $found_linestring = true;
                         break;
                     case 'coordinates':
                         // Exploit coordinates only when it is a child of LineString
                         if ($found_linestring) {
                             $coordinates = $this->extractKmlCoordinates($node->nodeValue);
                             if ($coordinates) {
                                 $coordinatesCount = count($coordinates);
                                 $this->trackCount++;
                                 $this->track[$this->trackCount] = new stdClass();
                                 $this->track[$this->trackCount]->coords = $coordinates;
                                 $this->track[$this->trackCount]->start = $coordinates[0][0] . "," . $coordinates[0][1];
                                 $this->track[$this->trackCount]->stop = $coordinates[$coordinatesCount - 1][0] . "," . $coordinates[$coordinatesCount - 1][1];
                             }
                         }
                         break;
                 }
             }
         }
         if ($this->trackCount and $coordinates) {
             $this->track[$this->trackCount]->trackname = $name ? $name : $description;
             $this->track[$this->trackCount]->description = $description;
         }
         // Use description and name for file description
         if ($name or $description) {
             $gps_file_description .= '<br />' . $name . ':' . $description;
         }
     }
     if ($this->trackCount) {
         // GPS file name (title) and description
         $this->trackname = $gps_file_name;
         if (strlen($gps_file_name) > 2) {
             $this->trackname = $gps_file_name;
         }
         if (strlen($this->trackname) < 10 and $this->trackCount == 1) {
             $this->trackname .= $this->track[1]->trackname;
         }
         if (strlen($this->trackname) < 10) {
             $this->trackname .= $this->gpsFile;
         }
         if ($gps_file_description and $tracks_description) {
             $this->description = $gps_file_description . '<br />' . $tracks_description;
         } elseif ($tracks_description) {
             $this->description = $tracks_description;
         } else {
             $this->description = $this->trackname;
         }
         $this->isTrack = $this->trackCount > 0;
         $this->isCache = $this->isThisCache($xml);
     }
     // Nothing to return
     return true;
 }