Example #1
0
function parseSDSS($output)
{
    $xml = new SimpleXMLElement($output);
    $xpath_run = "//field[@col='run']";
    $xpath_camcol = "//field[@col='camcol']";
    $xpath_rerun = "//field[@col='rerun']";
    $xpath_field = "//field[@col='field']";
    $out_run = $xml->xpath($xpath_run);
    $out_camcol = $xml->xpath($xpath_camcol);
    $out_rerun = $xml->xpath($xpath_rerun);
    $out_field = $xml->xpath($xpath_field);
    $imagefields = array();
    $i = 0;
    while (list(, $node) = each($out_run)) {
        $imagefields[$i] = array(trim($node), 0);
        $i++;
    }
    $i = 0;
    while (list(, $node) = each($out_camcol)) {
        $imagefields[$i][1] = trim($node);
        $i++;
    }
    $i = 0;
    while (list(, $node) = each($out_rerun)) {
        $imagefields[$i][2] = trim($node);
        $i++;
    }
    $i = 0;
    while (list(, $node) = each($out_field)) {
        $imagefields[$i][3] = trim($node);
        $i++;
    }
    return $imagefields;
}
Example #2
0
 /**
  * @param \SimpleXMLElement $node
  * @param $structureExtensionId extension of structures.xml
  * @return static
  */
 public static function fromSimpleXMLElement(\SimpleXMLElement $node, $structureExtensionId)
 {
     $url = isset($node['url']) ? (string) $node['url'] : '#';
     if ($url == '#' || empty($url)) {
         $extension = null;
         $controller = null;
         $action = null;
     } else {
         $parts = explode('/', trim($url, '/'));
         $parts = array_replace(array_fill(0, 3, null), $parts);
         list($extension, $controller, $action) = $parts;
     }
     $data = array('id' => (string) $node['id'], 'name' => (string) $node['name'], 'url' => $url, 'extension' => $extension, 'controller' => $controller, 'action' => $action, 'binding' => isset($node['binding']) ? (string) $node['binding'] : null, 'policy' => isset($node['policy']) ? (string) $node['policy'] : self::POLICY_MERGE, 'disabled' => isset($node['disabled']) ? true : false);
     $trees = array();
     foreach ($node->xpath("trees/tree") as $treeNode) {
         $trees[] = Tree::fromSimpleXMLElement($treeNode, $structureExtensionId);
     }
     $actions = array();
     foreach ($node->xpath("actions/action") as $actionNode) {
         $actions[] = Action::fromSimpleXMLElement($actionNode, $structureExtensionId);
     }
     $includeClassActions = isset($node->actions) && isset($node->actions['allowClassActions']) && $node->actions['allowClassActions'] == 'true';
     if ($includeClassActions) {
         foreach ($trees as $tree) {
             $rootNodeUri = $tree->get('rootNode');
             if (!empty($rootNodeUri)) {
                 $rootNode = new \core_kernel_classes_Class($rootNodeUri);
                 foreach (ClassActionRegistry::getRegistry()->getClassActions($rootNode) as $action) {
                     $actions[] = $action;
                 }
             }
         }
     }
     return new static($data, $trees, $actions);
 }
 /**
  * Parses additional exception information from the response body
  *
  * @param \SimpleXMLElement $body The response body as XML
  * @param array             $data The current set of exception data
  */
 protected function parseBody(\SimpleXMLElement $body, array &$data)
 {
     $data['parsed'] = $body;
     $namespaces = $body->getDocNamespaces();
     if (isset($namespaces[''])) {
         // Account for the default namespace being defined and PHP not being able to handle it :(
         $body->registerXPathNamespace('ns', $namespaces['']);
         $prefix = 'ns:';
     } else {
         $prefix = '';
     }
     if ($tempXml = $body->xpath("//{$prefix}Code[1]")) {
         $data['code'] = (string) $tempXml[0];
     }
     if ($tempXml = $body->xpath("//{$prefix}Message[1]")) {
         $data['message'] = (string) $tempXml[0];
     }
     $tempXml = $body->xpath("//{$prefix}RequestId[1]");
     if (empty($tempXml)) {
         $tempXml = $body->xpath("//{$prefix}RequestID[1]");
     }
     if (isset($tempXml[0])) {
         $data['request_id'] = (string) $tempXml[0];
     }
 }
 /**
  * 
  * @access private
  * @author "Lionel Lecaque, <*****@*****.**>"
  * @param SimpleXMLElement $releaseNode
  * @return array
  */
 private function getReleaseInfo($releaseNode)
 {
     $versionNode = $releaseNode->xpath('version');
     $commentNode = $releaseNode->xpath('comment');
     $patchs = $releaseNode->xpath('patchs');
     $returnValue = array('version' => (string) $versionNode[0], 'comment' => (string) trim($commentNode[0]));
     if (!empty($patchs)) {
         foreach ($patchs[0] as $patch) {
             $patchNode = $patch->xpath('version');
             $patchNodeValue = (string) $patchNode[0];
             $returnValue['patchs'][$patchNodeValue] = $this->getReleaseInfo($patch);
         }
     }
     $extensions = $releaseNode->xpath('extensions');
     if (!empty($extensions)) {
         foreach ($extensions[0] as $extension) {
             $returnValue['extensions'][] = (string) $extension;
         }
     }
     $messages = $releaseNode->xpath('messages');
     if (!empty($messages)) {
         foreach ($messages[0] as $message) {
             $returnValue['messages'][$message->getName()][] = (string) $message;
         }
     } else {
         $returnValue['messages'] = array();
     }
     return $returnValue;
 }
Example #5
0
function getSVGMetadata($infile)
{
    if (!($fileContent = file_get_contents($infile))) {
        return -1;
    }
    // can't access file
    $svgMetaRoot = '/svg:svg/svg:metadata/rdf:RDF/cc:Work';
    $svgElements = ['Title' => 'dc:title', 'Date' => 'dc:date', 'Publisher' => 'dc:publisher/cc:Agent/dc:title', 'Language' => 'dc:language', 'Description' => 'dc:description'];
    $meta = [];
    $xml = new SimpleXMLElement($fileContent);
    if (!$xml->xpath($svgMetaRoot)) {
        return false;
    }
    // metadata block not found
    foreach ($svgElements as $title => $path) {
        $el = $xml->xpath("{$svgMetaRoot}/{$path}");
        $meta[$title] = $el ? $el[0]->__toString() : '';
    }
    // getting keywords
    $meta['Tags'] = '';
    $svgKeywords = $xml->xpath("{$svgMetaRoot}/dc:subject/rdf:Bag/rdf:li");
    if ($svgKeywords) {
        foreach ($svgKeywords as $keyword) {
            $keyword = trim($keyword->__toString());
            if ($keyword) {
                $meta['Tags'] .= "{$keyword}, ";
            }
        }
        $meta['Tags'] = substr($meta['Tags'], 0, -2);
    }
    $meta = array_map('trim', $meta);
    return $meta;
}
 /**
  * @param string $data
  * @param string $element
  * @return array Parsed data.
  */
 public function readFromVariable($data, $element = 'target')
 {
     $messages = array();
     $mangler = $this->group->getMangler();
     $reader = new SimpleXMLElement($data);
     $reader->registerXPathNamespace('xliff', 'urn:oasis:names:tc:xliff:document:1.2');
     $items = array_merge($reader->xpath('//trans-unit'), $reader->xpath('//xliff:trans-unit'));
     foreach ($items as $item) {
         /** @var SimpleXMLElement $source */
         $source = $item->{$element};
         if (!$source) {
             continue;
         }
         $key = (string) $item['id'];
         /* In case there are tags inside the element, preserve
          * them. */
         $dom = new DOMDocument('1.0');
         $dom->loadXML($source->asXml());
         $value = self::getInnerXml($dom->documentElement);
         /* This might not be 100% according to the spec, but
          * for now if there is explicit approved=no, mark it
          * as fuzzy, but don't do that if the attribute is not
          * set */
         if ((string) $source['state'] === 'needs-l10n') {
             $value = TRANSLATE_FUZZY . $value;
         }
         // Strip CDATA if present
         $value = preg_replace('/<!\\[CDATA\\[(.*?)\\]\\]>/s', '\\1', $value);
         $messages[$key] = $value;
     }
     return array('MESSAGES' => $mangler->mangle($messages));
 }
 /**
  * Hook for the __construct() method of dlf/common/class.tx_dlf_document.php
  * When using Goobi.Production the record identifier is saved only in MODS, but not
  * in METS. To get it anyway, we have to do some magic.
  *
  * @access	public
  *
  * @param	SimpleXMLElement		&$xml: The XML object
  * @param	mixed		$record_id: The record identifier
  *
  * @return	void
  */
 public function construct_postProcessRecordId(SimpleXMLElement &$xml, &$record_id)
 {
     if (!$record_id) {
         $xml->registerXPathNamespace('mods', 'http://www.loc.gov/mods/v3');
         if ($divs = $xml->xpath('//mets:structMap[@TYPE="LOGICAL"]//mets:div[@DMDID]')) {
             $smLinks = $xml->xpath('//mets:structLink/mets:smLink');
             if ($smLinks) {
                 foreach ($smLinks as $smLink) {
                     $links[(string) $smLink->attributes('http://www.w3.org/1999/xlink')->from][] = (string) $smLink->attributes('http://www.w3.org/1999/xlink')->to;
                 }
                 foreach ($divs as $div) {
                     if (!empty($links[(string) $div['ID']])) {
                         $id = (string) $div['DMDID'];
                         break;
                     }
                 }
             }
             if (empty($id)) {
                 $id = (string) $divs[0]['DMDID'];
             }
             $recordIds = $xml->xpath('//mets:dmdSec[@ID="' . $id . '"]//mods:mods/mods:recordInfo/mods:recordIdentifier');
             if (!empty($recordIds[0])) {
                 $record_id = (string) $recordIds[0];
             }
         }
     }
 }
Example #8
0
 public function testFormaterReturnsXml()
 {
     // all results
     $rs1 = $this->getMockBuilder('\\Hal\\Component\\Result\\ResultSet')->disableOriginalConstructor()->getMock();
     $rs1->expects($this->any())->method('asArray')->will($this->returnValue(array('volume' => 5)));
     $rs1->expects($this->any())->method('getFilename')->will($this->returnValue('path2/file1.php'));
     $rs2 = $this->getMockBuilder('\\Hal\\Component\\Result\\ResultSet')->disableOriginalConstructor()->getMock();
     $rs2->expects($this->any())->method('asArray')->will($this->returnValue(array('volume' => 15)));
     $rs2->expects($this->any())->method('getFilename')->will($this->returnValue('path1/file1.php'));
     $collection = $this->getMockBuilder('\\Hal\\Component\\Result\\ResultCollection')->disableOriginalConstructor()->getMock();
     $collection->expects($this->any())->method('getIterator')->will($this->returnValue(new \ArrayIterator(array($rs1, $rs2))));
     $collection->expects($this->any())->method('getFilename')->will($this->returnValue('abc'));
     $collection->expects($this->any())->method('asArray')->will($this->returnValue(array(array('volume' => 5), array('volume' => 15))));
     $bounds = new Bounds();
     // grouped results
     $groupedResults = new ResultCollection();
     $result = $this->getMockBuilder('\\Hal\\Component\\Result\\ResultAggregate')->disableOriginalConstructor()->getMock();
     $result->expects($this->any())->method('getName')->will($this->returnValue('path1'));
     $result->expects($this->any())->method('getBounds')->will($this->returnValue($this->getMock('\\Hal\\Component\\Bounds\\Result\\ResultInterface')));
     $groupedResults->push($result);
     $result = $this->getMockBuilder('\\Hal\\Component\\Result\\ResultAggregate')->disableOriginalConstructor()->getMock();
     $result->expects($this->any())->method('getName')->will($this->returnValue('path2'));
     $result->expects($this->any())->method('getBounds')->will($this->returnValue($this->getMock('\\Hal\\Component\\Bounds\\Result\\ResultInterface')));
     $groupedResults->push($result);
     // formater
     $validator = $this->getMockBuilder('\\Hal\\Application\\Rule\\Validator')->disableOriginalConstructor()->getMock();
     $formater = new Xml($validator, $bounds, $this->getMockBuilder('\\Hal\\Application\\Extension\\ExtensionService')->disableOriginalConstructor()->getMock());
     $output = $formater->terminate($collection, $groupedResults);
     $xml = new \SimpleXMLElement($output);
     $p = $xml->xpath('//project');
     $this->assertEquals('10', $p[0]['volume']);
     $m = $xml->xpath('//project/modules/module[@namespace="path1"]');
     $m = $m[0];
     $this->assertCount(2, $xml->xpath('//project/modules/module'));
 }
function smwf_ti_update($tiArticleName)
{
    global $smwgDIIP;
    require_once $smwgDIIP . "/specials/TermImport/SMW_WIL.php";
    $xmlString = smwf_om_GetWikiText('TermImport:' . $tiArticleName);
    $start = strpos($xmlString, "<ImportSettings>");
    $end = strpos($xmlString, "</ImportSettings>") + 17 - $start;
    $xmlString = substr($xmlString, $start, $end);
    $simpleXMLElement = new SimpleXMLElement($xmlString);
    $moduleConfig = $simpleXMLElement->xpath("//ModuleConfiguration");
    $moduleConfig = trim($moduleConfig[0]->asXML());
    $dataSource = $simpleXMLElement->xpath("//DataSource");
    $dataSource = trim($dataSource[0]->asXML());
    $mappingPolicy = $simpleXMLElement->xpath("//MappingPolicy");
    $mappingPolicy = trim($mappingPolicy[0]->asXML());
    $conflictPolicy = $simpleXMLElement->xpath("//ConflictPolicy");
    $conflictPolicy = trim($conflictPolicy[0]->asXML());
    $inputPolicy = $simpleXMLElement->xpath("//InputPolicy");
    $inputPolicy = trim($inputPolicy[0]->asXML());
    $importSets = $simpleXMLElement->xpath("//ImportSets");
    $importSets = trim($importSets[0]->asXML());
    $wil = new WIL();
    $terms = $wil->importTerms($moduleConfig, $dataSource, $importSets, $inputPolicy, $mappingPolicy, $conflictPolicy, $tiArticleName, true);
    if ($terms != wfMsg('smw_ti_import_successful')) {
        return $terms;
    } else {
        return "success";
    }
}
Example #10
0
 public function getData($parsed)
 {
     $video_id = $parsed['video_id'];
     $buffer = file_get_contents("http://www.metacafe.com/api/item/{$video_id}");
     $xml = new SimpleXMLElement($buffer);
     return array('title' => current($xml->xpath('/rss/channel/item/title')), 'description' => strip_tags(current($xml->xpath('/rss/channel/item/description'))), 'thumbnail' => current($xml->xpath('/rss/channel/item/media:thumbnail/@url')), 'embedurl' => current($xml->xpath('/rss/channel/item/media:content/@url')));
 }
 public function fetchData()
 {
     $rss = $this->_getRss();
     if ($rss) {
         $xml = new \SimpleXMLElement($rss);
         // Ветер
         $tmp = $xml->xpath('/rss/channel/yweather:wind');
         if ($tmp === false) {
             throw new \Exception("Error parsing XML.");
         }
         $this->_wind = $tmp[0];
         // Текущая температура воздуха и погода
         $tmp = $xml->xpath('/rss/channel/item/yweather:condition');
         if ($tmp === false) {
             throw new \Exception("Error parsing XML.");
         }
         $tmp = $tmp[0];
         $this->_temperature = $tmp['temp'];
         $this->_condition = (int) $tmp['code'];
         $this->_forecasts = $xml->xpath('/rss/channel/item/yweather:forecast');
         //$this->condition_text = strtolower((string)$tmp['text']);
         $location = $xml->xpath('/rss/channel/yweather:location');
         $this->_city = (string) $location[0]['city'];
         return true;
     }
     return false;
 }
Example #12
0
 /**
  * Processes the rewrites on the all of the config.xmls in a given path
  *
  * @return void
  */
 protected function _processRewrites()
 {
     $baseIter = new RecursiveDirectoryIterator($this->_basePath());
     $recurse = new RecursiveIteratorIterator($baseIter);
     $configs = new RegexIterator($recurse, '/config\\.xml$/');
     $reportsObserver = $this->_reportObserver();
     foreach ($configs as $configFile) {
         $this->_writeLine("Consuming file {$configFile}");
         $xml = new SimpleXMLElement($configFile, 0, true);
         $models = $xml->xpath('//models/*/rewrite');
         foreach ($models as $model) {
             foreach (get_object_vars($model) as $key => $class) {
                 $this->_writeLine("|_ Found model rewrite {$key}: {$class}");
             }
         }
         $block = $xml->xpath('//blocks/*/rewrite');
         foreach ($blocks as $block) {
             foreach (get_object_vars($block) as $key => $path) {
                 $this->_writeLine("|_ Found block rewrite {$key}: {$path}");
             }
         }
         if ($reportsObserver) {
             $events = $xml->xpath('//events');
             foreach ($events as $observers) {
                 foreach ($observers->children() as $event) {
                     $this->_writeLine("|_ Found observer(s) for {$event->getName()}:");
                     foreach ($event->xpath('observers/*') as $observer) {
                         $this->_writeLine("|__ Observer {$observer->getName()}: {$observer->class->__toString()}::{$observer->method->__toString()}");
                     }
                 }
             }
         }
     }
 }
Example #13
0
function buscarPorTag($tag)
{
    #Using the tag we complete the url
    $flickr = "https://api.flickr.com/services/feeds/photos_public.gne?tags=" . $tag;
    #With the complete url we obtain the xml content
    $xml = file_get_contents($flickr);
    #Create a simple xml element using the xml data obtained
    $entradas = new SimpleXMLElement($xml);
    #The namespace is registered for the xpath search
    $entradas->registerXPathNamespace("feed", "http://www.w3.org/2005/Atom");
    #Printing the header
    echo "<h1 align='center'>Últimas 10 fotos con la etiqueta " . $tag . "</h1><table>";
    #Declaring the string for the table creation beginning for the header
    $tabla = "<th colspan='2'>¿Quieres buscar por otra etiqueta?<br><pre>Para usar varias separar con coma(sin espacios)</pre><form method='get'>\t\t\t\n\t\t\t<input type='text'name='tag'><br><input type='submit' value='Aceptar'>\n\t\t\t</form><th>";
    #Getting links with xpath expression
    $lauthor = $entradas->xpath("//feed:entry/feed:author/feed:name");
    $links = $entradas->xpath("//feed:entry/feed:link[@rel='enclosure']/@href");
    #We make a loop for showing the results
    for ($i = 0; $i < 10; $i++) {
        #we add the xml data to the table creation string, navigating through the document and using the previously created array
        $tabla = $tabla . "<tr><td><a href='" . $links[$i] . "'><img src=" . $links[$i] . " width='500px'></a></td><td width='300px'><b>Título</b><br>" . $entradas->entry[$i]->title . "<br><b>Autor</b></br>" . $entradas->entry[$i]->author->name . "</td></tr>";
    }
    #Finally we print the complete table
    echo "<table align='center'bgcolor='#F2F2F2' cellpadding='20px'>" . $tabla . "</table>";
}
Example #14
0
 public function getData($parsed)
 {
     $video_id = $parsed['video_id'];
     $buffer = file_get_contents('http://blip.tv' . $video_id . '?skin=rss');
     $xml = new SimpleXMLElement($buffer);
     return array('title' => current($xml->xpath('/rss/channel/item/title')), 'description' => strip_tags(current($xml->xpath('/rss/channel/item/description'))), 'thumbnail' => current($xml->xpath('/rss/channel/item/media:thumbnail/@url')), 'embedurl' => current($xml->xpath('/rss/channel/item/blip:embedUrl')));
 }
Example #15
0
 /**
  * This method returns an object matching the description specified by the element.
  *
  * @access public
  * @param Spring\Object\Parser $parser                      a reference to the parser
  * @param \SimpleXMLElement $element                        the element to be parsed
  * @return mixed                                            an object matching the description
  *                                                          specified by the element
  * @throws Throwable\Parse\Exception                        indicates that a problem occurred
  *                                                          when parsing
  */
 public function getObject(Spring\Object\Parser $parser, \SimpleXMLElement $element)
 {
     $attributes = $element->attributes();
     $type = isset($attributes['type']) ? $parser->valueOf($attributes['type']) : '\\Unicity\\BT\\Task\\Semaphore';
     $element->registerXPathNamespace('spring-bt', BT\Task::NAMESPACE_URI);
     $children = $element->xpath('./spring-bt:blackboard');
     $blackboard = !empty($children) ? $parser->getObjectFromElement($children[0]) : null;
     $element->registerXPathNamespace('spring-bt', BT\Task::NAMESPACE_URI);
     $children = $element->xpath('./spring-bt:policy');
     $policy = !empty($children) ? $parser->getObjectFromElement($children[0]) : null;
     $object = new $type($blackboard, $policy);
     if (!$object instanceof BT\Task\Semaphore) {
         throw new Throwable\Parse\Exception('Invalid type defined. Expected a task semaphore, but got an element of type ":type" instead.', array(':type' => $type));
     }
     if (isset($attributes['title'])) {
         $object->setTitle($parser->valueOf($attributes['title']));
     }
     $element->registerXPathNamespace('spring-bt', BT\Task::NAMESPACE_URI);
     $children = $element->xpath('./spring-bt:tasks');
     if (!empty($children)) {
         foreach ($children as $child) {
             $object->addTasks($parser->getObjectFromElement($child));
         }
     }
     return $object;
 }
Example #16
0
 /**
  * {@inheritDoc}
  */
 public function getGeocodedData($address, $boundingBox = null)
 {
     if (null === $this->apiKey) {
         throw new InvalidCredentialsException('No API Key provided');
     }
     // This API doesn't handle IPs
     if (filter_var($address, FILTER_VALIDATE_IP)) {
         throw new UnsupportedException('The IGNOpenLSProvider does not support IP addresses.');
     }
     $query = sprintf(self::ENDPOINT_URL, $this->apiKey) . urlencode(sprintf(self::ENDPOINT_QUERY, $address));
     $content = $this->getAdapter()->getContent($query);
     $data = (array) json_decode($content, true);
     if (empty($data) || null === $data['xml']) {
         throw new NoResultException(sprintf('Could not execute query %s', $query));
     }
     if (200 !== $data['http']['status'] || null !== $data['http']['error']) {
         throw new NoResultException(sprintf('Could not execute query %s', $query));
     }
     $xpath = new \SimpleXMLElement($data['xml']);
     $xpath->registerXPathNamespace('gml', 'http://www.opengis.net/gml');
     $positions = $xpath->xpath('//gml:pos');
     $positions = explode(' ', $positions[0]);
     $xpath->registerXPathNamespace('xls', 'http://www.opengis.net/xls');
     $zipcode = $xpath->xpath('//xls:PostalCode');
     $city = $xpath->xpath('//xls:Place[@type="Municipality"]');
     $streetNumber = $xpath->xpath('//xls:Building');
     $cityDistrict = $xpath->xpath('//xls:Street');
     return array_merge($this->getDefaults(), array('latitude' => isset($positions[0]) ? (double) $positions[0] : null, 'longitude' => isset($positions[1]) ? (double) $positions[1] : null, 'streetNumber' => isset($streetNumber[0]) ? (string) $streetNumber[0]->attributes() : null, 'streetName' => isset($cityDistrict[0]) ? (string) $cityDistrict[0] : null, 'city' => isset($city[0]) ? (string) $city[0] : null, 'zipcode' => isset($zipcode[0]) ? (string) $zipcode[0] : null, 'cityDistrict' => isset($cityDistrict[0]) ? (string) $cityDistrict[0] : null, 'country' => 'France', 'countryCode' => 'FR', 'timezone' => 'Europe/Paris'));
 }
Example #17
0
 public function createTicketDetail($obj)
 {
     $dbh = $this->coreDB();
     $ticketID = $obj->ticket;
     $companyFile = $obj->strCompanyFileName;
     $qbXMLCountry = $obj->qbXMLCountry;
     $qbXMLMajorVersion = $obj->qbXMLMajorVers;
     $qbXMLMinorVersion = $obj->qbXMLMinorVers;
     $responseData = $obj->strHCPResponse;
     // If con do not update ticket details again
     if (!empty($responseData)) {
         $xmlData = new SimpleXMLElement($responseData);
         $hostData = $xmlData->xpath('//HostRet');
         $companyData = $xmlData->xpath('//CompanyRet');
         $q = $dbh->prepare("INSERT INTO QB_Ticket_Details(qbTicketID,\n                                                                  qbProductName,\n                                                                  qbMajorVersion,\n                                                                  qbMinorVersion,\n                                                                  qbCompanyName,\n                                                                  qbCompanyFile,\n                                                                  qbXMLCountry,\n                                                                  qbXMLMajorVersion,\n                                                                  qbXMLMinorVersion,\n                                                                  createdOn)\n\n                                          VALUES(:ticketID,\n                                                  :productName,\n                                                  :majorVersion,\n                                                  :minorVersion,\n                                                  :companyName,\n                                                  :companyFile,\n                                                  :qbXMLCountry,\n                                                  :qbXMLMajorVersion,\n                                                  :qbXMLMinorVersion,\n                                                  current_timestamp)");
         $q->bindParam("ticketID", $ticketID);
         $q->bindParam("productName", $hostData[0]->ProductName);
         $q->bindParam("majorVersion", $hostData[0]->MajorVersion);
         $q->bindParam("minorVersion", $hostData[0]->MinorVersion);
         $q->bindParam("companyName", $companyData[0]->CompanyName);
         $q->bindParam("companyFile", $companyFile);
         $q->bindParam("qbXMLCountry", $qbXMLCountry);
         $q->bindParam("qbXMLMajorVersion", $qbXMLMajorVersion);
         $q->bindParam("qbXMLMinorVersion", $qbXMLMinorVersion);
         $q->execute();
         $dbh = null;
     }
 }
Example #18
0
 public static function get_import_strategies_for_entry(SimpleXMLElement $entry, PluginImport $importer)
 {
     $strategies = array();
     // TODO: when the xpath has an error in it, count(error) == 1 also.. so should check return type
     $correctrdftype = count($entry->xpath('rdf:type[' . $importer->curie_xpath('@rdf:resource', PluginImportLeap::NS_LEAPTYPE, 'selection') . ']')) == 1;
     $correctcategoryscheme = count($entry->xpath('a:category[(' . $importer->curie_xpath('@scheme', PluginImportLeap::NS_CATEGORIES, 'selection_type#') . ') and @term="Blog"]')) == 1;
     if ($correctrdftype && $correctcategoryscheme) {
         $otherrequiredentries = array();
         // Get entries that this blog feels are a part of it
         foreach ($entry->link as $link) {
             if ($importer->curie_equals($link['rel'], PluginImportLeap::NS_LEAP, 'has_part') && isset($link['href'])) {
                 $otherrequiredentries[] = (string) $link['href'];
             }
         }
         // TODO: Get entries that feel they should be a part of this blog.
         // We can compare the lists and perhaps warn if they're different
         //    $otherentries = $importer->xml->xpath('//a:feed/a:entry/a:link[@rel="leap:is_part_of" and @href="' . $entryid . '"]/../a:id');
         $otherrequiredentries = array_unique($otherrequiredentries);
         $strategies[] = array('strategy' => self::STRATEGY_IMPORT_AS_BLOG, 'score' => 100, 'other_required_entries' => $otherrequiredentries);
     } else {
         // The blog can import any entry as a literal blog post
         $strategies[] = array('strategy' => self::STRATEGY_IMPORT_AS_ENTRY, 'score' => 10, 'other_required_entries' => array());
     }
     return $strategies;
 }
Example #19
0
 /**
  * @return array of SVGFont
  */
 public function getFonts()
 {
     $fonts = array();
     foreach ($this->document->xpath('//font') as $font) {
         $fonts[] = new SVGFont($font, $this);
     }
     return $fonts;
 }
Example #20
0
 public function getTable($_tableName)
 {
     $table = $this->_spreadSheet->xpath("//office:body/office:spreadsheet/table:table[@table:name='{$_tableName}']");
     if (count($table) === 0) {
         return false;
     }
     return new OpenDocument_SpreadSheet_Table($table[0]);
 }
 /**
  * @param SimpleXMLElement $xml
  * @param int $chNum
  * @param int $vsNum
  * @return bool
  */
 private static function hasVerse($xml, $chNum, $vsNum)
 {
     $nextCh = $chNum + 1;
     // Check that we got, say, John 3:16 and not John 4:16
     $result = $xml->xpath("//verse[@number={$vsNum}][preceding::chapter[@number={$chNum}]][following::chapter[@number={$nextCh}]]");
     // Other possibility: the verse we're looking for was in the last chapter of our fragment
     $result2 = $xml->xpath("//verse[@number={$vsNum}][preceding::chapter[@number={$chNum}]][not(following::chapter)]");
     return !empty($result) || !empty($result2);
 }
Example #22
0
 public function testXpath()
 {
     $f = new File("/" . FRAMEWORK_CORE_PATH . "tests/xml/xml_file.xml");
     $xml_doc = new SimpleXMLElement(str_replace("xmlns", "ns", $f->getContent()));
     $config_params = $xml_doc->xpath("/module-declaration/config-params");
     $this->assertTrue($config_params, "Impossibile leggere i parametri di configurazione!!");
     $install_data = $xml_doc->xpath('/module-declaration/action[@name="install"]');
     $this->assertTrue($install_data, "Impossibile leggere i dati per l'installazione!!");
 }
 protected function _createXmlFromTexts($texts, $targetFile, $languages)
 {
     if (empty($texts)) {
         return;
     }
     if (!file_exists($targetFile)) {
         $file = fopen($targetFile, 'a+');
         fputs($file, "<hlp></hlp>");
         fclose($file);
     }
     // Suchen, obs Eintrag schon gibt
     $xml = new SimpleXMLElement(file_get_contents($targetFile));
     foreach ($texts as $key => $controllers) {
         $xpath = "/hlp/text[@key='{$key}']";
         $search = $xml->xpath($xpath);
         if (!$search) {
             // Wenn nein, hinzufügen
             $element = $xml->addChild('text');
             $element->addAttribute('key', $key);
             $element->addAttribute('file', implode(', ', $controllers));
         } else {
             $element = $search[0];
         }
         // Für aktuellen Eintrag die Sprachen, die es noch nicht gibt, hinzufügen
         foreach ($languages as $language) {
             if (!$xml->xpath("{$xpath}/{$language}")) {
                 $element->addChild($language, '');
             }
         }
     }
     $string = $xml->asXML();
     // XML formatieren, echt schiach
     $string = str_replace("\t", "", $string);
     $string = str_replace("\n", "", $string);
     $string = str_replace(">", ">\n", $string);
     foreach ($languages as $language) {
         $string = str_replace("<{$language}>\n", "<{$language}>", $string);
         $string = str_replace("{$language}/>", "{$language}></{$language}>", $string);
     }
     $string = str_replace(">_</", "></", $string);
     $string = str_replace("></text>", ">\n</text>", $string);
     $string = str_replace("></hlp>", ">\n</hlp>", $string);
     $result = '';
     foreach (explode("\n", $string) as $line) {
         if (substr($line, 0, 6) == '<text ' || substr($line, 0, 6) == '</text') {
             $result .= "    ";
         } else {
             if (substr($line, 0, 4) != '<hlp' && substr($line, 0, 5) != '<?xml' && substr($line, 0, 2) != '</') {
                 $result .= "        ";
             }
         }
         $result .= $line . "\n";
     }
     // XML in Datei schreiben
     file_put_contents($targetFile, $result);
     echo "Datei {$targetFile} erstellt.\n";
 }
 /**
  * 
  * @return boolean
  */
 public function hasErrors()
 {
     foreach ($this->xml->xpath("//batch:status/@code") as $el) {
         if ($el->__toString() !== "200") {
             return true;
         }
     }
     return false;
 }
Example #25
0
 /**
  * Create list from array
  *
  * @param array $data
  * @param string $type
  * @return Processor
  */
 protected function _addElements($data, $type)
 {
     array_walk_recursive($data, function ($value) use($type) {
         if (!$this->_referenceList->xpath("//item[@type='{$type}' and @value='{$value}']")) {
             $element = $this->_referenceList->addChild('item');
             $element->addAttribute('type', $type);
             $element->addAttribute('value', $value);
         }
     });
     return $this;
 }
Example #26
0
 /**
  * Получает значение параметра из XML на основе языковой разметки
  *
  * @param SimpleXMLElement $oXml       XML узел
  * @param string           $sProperty  Свойство, которое нужно вернуть
  * @param string           $sLang      Название языка
  * @param bool             $bParseText
  */
 protected function _xlang($oXml, $sProperty, $sLang, $bParseText = false)
 {
     $sProperty = trim($sProperty);
     if (!count($data = $oXml->xpath("{$sProperty}/lang[@name='{$sLang}']"))) {
         $data = $oXml->xpath("{$sProperty}/lang[@name='default']");
     }
     if ($bParseText) {
         $oXml->{$sProperty}->data = E::ModuleText()->Parser(trim((string) array_shift($data)));
     } else {
         $oXml->{$sProperty}->data = trim((string) array_shift($data));
     }
 }
 /**
  * @param object \SimpleXMLIterator $data data
  * @return array
  */
 public function getFormDefinition($data)
 {
     $language = strtolower((string) $data->auth->language);
     $router = $this->serviceManager->get('PlatformRouter');
     $xmlDefinition = $router->getFileResource((int) $data->xmlDefinition['fileRef']);
     $xmlTranslation = $router->getFileResource((int) $data->xmlTranslation['fileRef']);
     $translationXml = new \SimpleXMLElement($xmlTranslation['file']);
     $translation = [];
     foreach ($translationXml->xpath('//key') as $key) {
         $translation[(string) $key['name']] = [];
         foreach ($key->value as $value) {
             if (strtolower(substr((string) $value['lang'], 0, 2)) == $language) {
                 $translation[(string) $key['name']] = strip_tags((string) $value);
             }
         }
     }
     $form = new \SimpleXMLElement($xmlDefinition['file']);
     $fields = [];
     foreach ($form->xpath('//input') as $input) {
         $name = (string) $input['name'];
         $label = isset($input['label']) ? (string) $input['label'] : $name;
         $binding = [];
         if (isset($input->binding->service)) {
             $url = $this->_getBindingUrl(trim((string) $input->binding->service['url']));
             if ($url !== '') {
                 $binding['service'] = ['url' => $url];
             }
         }
         $type = (string) $input['type'];
         if ($type == 'file') {
             // (string)$input['type'] == 'date_dropdown' || (string)$input['type'] == 'date' ||
             continue;
         }
         switch ($type) {
             case 'date_dropdown':
             case 'date_time_dropdown':
                 $type = 'date';
                 break;
             case 'time_dropdown':
                 $type = 'text';
                 break;
         }
         $fields[$name] = ['type' => (string) $input['type'], 'label' => isset($translation[$label]) ? $translation[$label] : $label, 'binding' => $binding];
     }
     foreach ($form->xpath('//fieldset') as $fieldset) {
         foreach ($fieldset->input as $input) {
             if (isset($fields[(string) $input['name']])) {
                 $fields[(string) $input['name']]['fieldset'] = (string) $fieldset['name'];
             }
         }
     }
     return ['form' => $fields];
 }
Example #28
0
 public static function getClipDetailByIdentifier($id)
 {
     $video = new stdClass();
     # XML data URL
     $file_data = 'http://video.google.com/videofeed?docid=' . $id;
     $video->xml_url = $file_data;
     # XML
     $xml = new SimpleXMLElement(utf8_encode(file_get_contents($file_data)));
     $xml->registerXPathNamespace('media', 'http://search.yahoo.com/mrss/');
     # Title
     $title_query = $xml->xpath('/rss/channel/item/title');
     $video->title = $title_query ? strval($title_query[0]) : null;
     # Description
     $description_query = $xml->xpath('/rss/channel/item/media:group/media:description');
     $video->description = $description_query ? strval(trim($description_query[0])) : null;
     # Tags
     $video->tags = null;
     # Duration
     $duration_query = $xml->xpath('/rss/channel/item/media:group/media:content/@duration');
     $video->duration = $duration_query ? intval($duration_query[0]) : null;
     # Author & author URL
     // TODO: WTF?
     // $author_query = $xml->xpath('/rss/channel/item/author');
     // $video->author = $author_query ? strval($author_query[0]) : false;
     $video->author = null;
     $video->author_url = null;
     # Publication date
     $date_published_query = $xml->xpath('/rss/channel/item/pubDate');
     $video->date_published = $date_published_query ? new DateTime($date_published_query[0]) : null;
     # Last update date
     $video->date_updated = null;
     # Thumbnails
     $thumbnails_query = $xml->xpath('/rss/channel/item/media:group/media:thumbnail');
     $thumbnails_query = $thumbnails_query[0]->attributes();
     $thumbnail = new stdClass();
     $thumbnail->url = strval(preg_replace('#&amp;#', '&', $thumbnails_query['url']));
     $thumbnail->width = intval($thumbnails_query['width']);
     $thumbnail->height = intval($thumbnails_query['height']);
     $video->thumbnails[] = $thumbnail;
     # Player URL
     $player_url_query = $xml->xpath('/rss/channel/item/media:group/media:content[@type="application/x-shockwave-flash"]/@url');
     $video->player_url = $player_url_query ? strval($player_url_query[0]) : null;
     # AVI file URL
     $avi_url_query = $xml->xpath('/rss/channel/item/media:group/media:content[@type="video/x-msvideo"]/@url');
     $video->files['video/x-msvideo'] = $avi_url_query ? preg_replace('#&amp;#', '&', $avi_url_query[0]) : null;
     # FLV file URL
     $flv_url_query = $xml->xpath('/rss/channel/item/media:group/media:content[@type="video/x-flv"]/@url');
     $video->files['video/x-flv'] = $flv_url_query ? strval($flv_url_query[0]) : null;
     # MP4 file URL
     $mp4_url_query = $xml->xpath('/rss/channel/item/media:group/media:content[@type="video/mp4"]/@url');
     $video->files['video/mp4'] = $mp4_url_query ? preg_replace('#&amp;#', '&', $mp4_url_query[0]) : null;
     return $video;
 }
Example #29
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     //Проверим запущена ли команда уже, если да то выходим
     $lockHandler = new LockHandler('xml.generate.lock');
     if (!$lockHandler->lock()) {
         $output->writeln('Command is locked');
         return 0;
     }
     $email = $input->getArgument('email');
     if ($email && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
         throw new InvalidArgumentException('The argument must be valid email');
     }
     $container = $this->getContainer();
     $em = $container->get('doctrine.orm.entity_manager');
     $persons = $em->getRepository('AppBundle:Person')->findAll();
     $serializer = SerializerBuilder::create()->build();
     //ищем файл XML для экспорта, если нет - создаем
     $fs = new Filesystem();
     $path = $container->get('kernel')->getRootDir() . '/data/result.xml';
     if ($fs->exists($path)) {
         $content = file_get_contents($path);
         $xml = new \SimpleXMLElement($content);
     } else {
         $xml = new \SimpleXMLElement('<persons/>');
         $xml->asXML($path);
     }
     //идем по всем Person и ищем соответствующий айди в XML
     foreach ($persons as $person) {
         $serialized = $serializer->serialize($person, 'xml');
         $t = $xml->xpath(sprintf('//person[@id="%d"]', $person->getId()));
         if ($t) {
             //если находим - удаляем нод
             $dom = dom_import_simplexml($t[0]);
             $dom->parentNode->removeChild($dom);
         }
         //вставляем новый нод
         $target = $xml->xpath('/persons');
         $dom = dom_import_simplexml($target[0]);
         $insertDom = $dom->ownerDocument->importNode(dom_import_simplexml(new \SimpleXMLElement($serialized)), true);
         $dom->appendChild($insertDom);
     }
     $xml->asXML($path);
     $publicPath = $container->get('kernel')->getRootDir() . '/../web/' . XmlCommand::XML_PATH;
     $fs->copy($path, $publicPath);
     $timeFinished = new \DateTime();
     if ($email) {
         $context = $container->get('router')->getContext();
         $message = \Swift_Message::newInstance()->setSubject('Task finished')->setFrom('noreply@' . $context->getHost())->setTo($email)->setBody($container->get('templating')->render('emails/xmlFinished.html.twig', ['taskName' => XmlCommand::TASK_NAME, 'time' => $timeFinished, 'link' => $context->getHost() . '/' . XmlCommand::XML_PATH]), 'text/html');
         $container->get('mailer')->send($message);
     }
     return 0;
 }
Example #30
0
 /**
  * Parse relative images a hrefs and style sheets to full paths
  *
  * @param   string  &$data  data
  *
  * @return  void
  */
 public static function fullPaths(&$data)
 {
     $data = str_replace('xmlns=', 'ns=', $data);
     libxml_use_internal_errors(true);
     try {
         $ok = new SimpleXMLElement($data);
         if ($ok) {
             $uri = JUri::getInstance();
             $base = $uri->getScheme() . '://' . $uri->getHost();
             $imgs = $ok->xpath('//img');
             foreach ($imgs as &$img) {
                 if (!strstr($img['src'], $base)) {
                     $img['src'] = $base . $img['src'];
                 }
             }
             // Links
             $as = $ok->xpath('//a');
             foreach ($as as &$a) {
                 if (!strstr($a['href'], $base)) {
                     $a['href'] = $base . $a['href'];
                 }
             }
             // CSS files.
             $links = $ok->xpath('//link');
             foreach ($links as &$link) {
                 if ($link['rel'] == 'stylesheet' && !strstr($link['href'], $base)) {
                     $link['href'] = $base . $link['href'];
                 }
             }
             $data = $ok->asXML();
         }
     } catch (Exception $err) {
         // Oho malformed html - if we are debugging the site then show the errors
         // otherwise continue, but it may mean that images/css/links are incorrect
         $errors = libxml_get_errors();
         $config = JComponentHelper::getParams('com_fabrik');
         // Don't show the errors if we want to debug the actual pdf html
         if (JDEBUG && $config->get('pdf_debug', true) === true) {
             echo "<pre>";
             print_r($errors);
             echo "</pre>";
             exit;
         } else {
             $uri = JUri::getInstance();
             $base = $uri->getScheme() . '://' . $uri->getHost();
             $data = str_replace('href="/', 'href="' . $base . '/', $data);
             $data = str_replace('src="/', 'src="' . $base . '/', $data);
             $data = str_replace("href='/", "href='" . $base . '/', $data);
             $data = str_replace("src='/", "src='" . $base . '/', $data);
         }
     }
 }