/**
  * Instancia uma nova validacao das Assinaturas Digitais de documentos XML
  *
  * @param string $sFile Arquivo a ser validado
  * @throws Exception
  */
 public function __construct($sFile)
 {
     if (empty($sFile)) {
         throw new Exception("Arquivo deve ser informado");
     }
     $this->sFile = $sFile;
     $this->oDomDocument = new DOMDocument();
     $this->oDomDocument->loadXml($sFile);
 }
function openxml($filepath, &$error_str = false)
{
    $xmlstr = @file_get_contents($filepath);
    if ($xmlstr == false) {
        $error_str = "failed to open file {$filepath}";
        return false;
    }
    $options = LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_ERR_NONE | LIBXML_COMPACT;
    $xmldoc = new DOMDocument();
    $xmldoc->strictErrorChecking = false;
    $xmldoc->recover = true;
    $old = error_reporting(0);
    $old_libxml = libxml_use_internal_errors(true);
    $ret = @$xmldoc->loadXml($xmlstr, $options);
    if ($ret == false) {
        $error_str = "failed to load xml from {$filepath}";
        return false;
    }
    $errors = libxml_get_errors();
    if (count($errors) > 0) {
        foreach ($errors as $error) {
            if ($error->level == LIBXML_ERR_FATAL) {
                $error_str = "file: {{$filepath}} line: {$error->line} column: {$error->column}: fatal error: {$error->code}: {$error->message}";
                return false;
            }
        }
    }
    $xml = @simplexml_import_dom($xmldoc);
    error_reporting($old);
    libxml_use_internal_errors($old_libxml);
    return $xml;
}
Example #3
0
/**
 * Load a single item by itemKey only if it belongs to a specific collection
 *
 * @param Zotero_Library $library
 * @param string $itemKey
 * @param string $collectionKey
 * @return Zotero_Item
 */
function fetchCollectionItem($library, $itemKey, $collectionKey)
{
    $citemKey = $itemKey . ',';
    //hackish way to get a single item by itemKey + collectionKey by forcing itemKey into querystring
    $aparams = array('target' => 'items', 'content' => 'json', 'itemKey' => $itemKey, 'collectionKey' => $collectionKey);
    $reqUrl = $library->apiRequestUrl($aparams) . $library->apiQueryString($aparams);
    $response = $library->_request($reqUrl, 'GET');
    if ($response->isError()) {
        return false;
        throw new Exception("Error fetching items");
    }
    $body = $response->getRawBody();
    $doc = new DOMDocument();
    $doc->loadXml($body);
    $entries = $doc->getElementsByTagName("entry");
    if (!$entries->length) {
        return false;
        throw new Exception("no item with specified key found");
    } else {
        $entry = $entries->item(0);
        $item = new Zotero_Item($entry);
        $library->items->addItem($item);
        return $item;
    }
}
 /**
  * @return \DOMDocument
  */
 public function testVisitWithoutEmbeddedVersion()
 {
     $visitor = $this->getVisitor();
     $generator = $this->getGenerator();
     $generator->startDocument(null);
     $restUser = $this->getBasicRestUser();
     $this->getVisitorMock()->expects($this->once())->method('visitValueObject');
     $locationPath = implode('/', $restUser->mainLocation->path);
     $this->addRouteExpectation('ezpublish_rest_loadUser', array('userId' => $restUser->contentInfo->id), "/user/users/{$restUser->contentInfo->id}");
     $this->addRouteExpectation('ezpublish_rest_loadContentType', array('contentTypeId' => $restUser->contentInfo->contentTypeId), "/content/types/{$restUser->contentInfo->contentTypeId}");
     $this->addRouteExpectation('ezpublish_rest_loadContentVersions', array('contentId' => $restUser->contentInfo->id), "/content/objects/{$restUser->contentInfo->id}/versions");
     $this->addRouteExpectation('ezpublish_rest_loadSection', array('sectionId' => $restUser->contentInfo->sectionId), "/content/sections/{$restUser->contentInfo->sectionId}");
     $this->addRouteExpectation('ezpublish_rest_loadLocation', array('locationPath' => $locationPath), "/content/locations/{$locationPath}");
     $this->addRouteExpectation('ezpublish_rest_loadLocationsForContent', array('contentId' => $restUser->contentInfo->id), "/content/objects/{$restUser->contentInfo->id}/locations");
     $this->addRouteExpectation('ezpublish_rest_loadUserGroupsOfUser', array('userId' => $restUser->contentInfo->id), "/user/users/{$restUser->contentInfo->id}/groups");
     $this->addRouteExpectation('ezpublish_rest_loadUser', array('userId' => $restUser->contentInfo->ownerId), "/user/users/{$restUser->contentInfo->ownerId}");
     $this->addRouteExpectation('ezpublish_rest_loadUserGroupsOfUser', array('userId' => $restUser->contentInfo->id), "/user/users/{$restUser->contentInfo->id}/groups");
     $this->addRouteExpectation('ezpublish_rest_loadRoleAssignmentsForUser', array('userId' => $restUser->contentInfo->id), "/user/users/{$restUser->contentInfo->id}/roles");
     $visitor->visit($this->getVisitorMock(), $generator, $restUser);
     $result = $generator->endDocument(null);
     $this->assertNotNull($result);
     $dom = new \DOMDocument();
     $dom->loadXml($result);
     return $dom;
 }
Example #5
0
 public function indexAction()
 {
     SxCms_Acl::requireAcl('ad', 'ad.edit');
     $filename = APPLICATION_PATH . '/var/ads.xml';
     $dom = new DOMDocument();
     $dom->preserveWhiteSpace = false;
     $dom->loadXml(file_get_contents($filename));
     $dom->formatOutput = true;
     $xpath = new DOMXpath($dom);
     $xml = simplexml_import_dom($dom);
     if ($this->getRequest()->isPost()) {
         $ads = $this->_getParam('ad');
         foreach ($ads as $key => $value) {
             $nodeList = $xpath->query("//zone[id='{$key}']/content");
             if ($nodeList->length) {
                 $cdata = $dom->createCDATASection(stripslashes($value));
                 $content = $dom->createElement('content');
                 $content->appendChild($cdata);
                 $nodeList->item(0)->parentNode->replaceChild($content, $nodeList->item(0));
             }
         }
         $dom->save($filename);
         $flashMessenger = $this->_helper->getHelper('FlashMessenger');
         $flashMessenger->addMessage('Advertentie werd succesvol aangepast');
     }
     $this->view->ads = $xml;
 }
 /**
  * @see Filter::process()
  * @param $document DOMDocument|string
  * @return array Array of imported documents
  */
 function &process(&$document)
 {
     // If necessary, convert $document to a DOMDocument.
     if (is_string($document)) {
         $xmlString = $document;
         $document = new DOMDocument();
         $document->loadXml($xmlString);
     }
     assert(is_a($document, 'DOMDocument'));
     $deployment = $this->getDeployment();
     $submissions = array();
     if ($document->documentElement->tagName == $this->getPluralElementName()) {
         // Multiple element (plural) import
         for ($n = $document->documentElement->firstChild; $n !== null; $n = $n->nextSibling) {
             if (!is_a($n, 'DOMElement')) {
                 continue;
             }
             $submissions[] = $this->handleElement($n);
         }
     } else {
         assert($document->documentElement->tagName == $this->getSingularElementName());
         // Single element (singular) import
         $submissions[] = $this->handleElement($document->documentElement);
     }
     return $submissions;
 }
Example #7
0
 public function getSRank($domain)
 {
     $xml = '<?xml version="1.0" encoding="UTF-8"?><methodCall><methodName>getRank</methodName><params><param><value><string>0</string></value></param><param><value><string>' . htmlspecialchars($domain) . '</string></value></param><param><value><i4>0</i4></value></param></params></methodCall>';
     $request = "POST /RPC2 HTTP/1.1\r\n";
     $request .= "Host: srank.seznam.cz\r\n";
     $request .= "Content-Type: text/xml\r\n";
     $request .= "Content-Length: " . strlen($xml) . "\r\n";
     $request .= "Connection: Close\r\n\r\n";
     $request .= $xml;
     $errNo = $errStr = '';
     $socket = fsockopen('srank.seznam.cz', 80, $errNo, $errStr, 10);
     if ($socket === FALSE) {
         return -1;
     }
     fwrite($socket, $request);
     $response = '';
     while (!feof($socket)) {
         $response .= fgets($socket, 1024);
     }
     $response = preg_replace('/^(.+\\r\\n)+\\r\\n/', '', $response);
     $doc = new DOMDocument();
     if (!$doc->loadXml($response)) {
         return -1;
     }
     $xpath = new DOMXPath($doc);
     $result = $xpath->evaluate('string(//member[name = "rank"]/value)');
     if (!is_numeric($result)) {
         return -1;
     }
     $rank = round((int) $result * 100 / 255 / 10);
     return $rank;
 }
Example #8
0
    public function loadXML($source, $options = 0, $appendEncoding = true, $appendDTD = true)
    {
        //append xml encoding and DTD if needed
        if ($appendEncoding) {
            //convert source encoding if needed
            if (io::isUTF8($source)) {
                if (io::strtolower(APPLICATION_DEFAULT_ENCODING) != 'utf-8') {
                    $source = utf8_decode($source);
                }
            } else {
                if (io::strtolower(APPLICATION_DEFAULT_ENCODING) == 'utf-8') {
                    $source = utf8_encode($source);
                }
            }
            if ($appendDTD) {
                $options = $options ? $options | LIBXML_DTDLOAD : LIBXML_DTDLOAD;
                $doctype = !APPLICATION_IS_WINDOWS ? '<!DOCTYPE automne SYSTEM "' . PATH_PACKAGES_FS . '/files/xhtml.ent">' : '<!DOCTYPE automne [' . file_get_contents(PATH_PACKAGES_FS . '/files/xhtml.ent') . ']>';
            }
            $source = '<?xml version="1.0" encoding="' . APPLICATION_DEFAULT_ENCODING . '"?>
			' . ($appendDTD ? $doctype : '') . '
			' . $source;
        }
        set_error_handler(array('CMS_DOMDocument', 'XmlError'));
        $return = parent::loadXml($source, $options);
        restore_error_handler();
        return $return;
    }
Example #9
0
 /**
  * Load HTML or XML.
  * 
  * @param string $string HTML or XML string or file path
  * @param bool   $isFile Indicates that in first parameter was passed to the file path
  * @param string $type Type of document
  * @param int    $options Additional parameters
  */
 public function load($string, $isFile = false, $type = 'html', $options = 0)
 {
     if (!is_string($string)) {
         throw new InvalidArgumentException(sprintf('%s expects parameter 1 to be string, %s given', __METHOD__, is_object($string) ? get_class($string) : gettype($string)));
     }
     if (!in_array(strtolower($type), ['xml', 'html'])) {
         throw new InvalidArgumentException(sprintf('Document type must be "xml" or "html", %s given', __METHOD__, is_object($type) ? get_class($type) : gettype($type)));
     }
     if (!is_integer($options)) {
         throw new InvalidArgumentException(sprintf('%s expects parameter 4 to be integer, %s given', __METHOD__, is_object($options) ? get_class($options) : gettype($options)));
     }
     $string = trim($string);
     if ($isFile) {
         $string = $this->loadFile($string);
     }
     if (substr($string, 0, 5) !== '<?xml') {
         $prolog = sprintf('<?xml version="1.0" encoding="%s"?>', $this->document->encoding);
         $string = $prolog . $string;
     }
     $this->type = strtolower($type);
     Errors::disable();
     $this->type === 'xml' ? $this->document->loadXml($string, $options) : $this->document->loadHtml($string, $options);
     Errors::restore();
     return $this;
 }
 /**
  * Prepara os dados para processar o arquivo do webservice
  *
  * @param string $sArquivo
  * @return bool
  * @throws Exception
  */
 public function preparaDados($sArquivo)
 {
     try {
         // Foi comentado o if de verificação pois estava ocorrendo um problema na emissão e retornava um arquivo em branco.
         // Somente em ambiente de desenvolvimento
         //if (APPLICATION_ENV == 'development') {
         $oDomDocument = new DOMDocument();
         $oDomDocument->loadXml($sArquivo);
         $oData = new Zend_Date();
         $this->sNomeArquivo = "/RecepcionarLote-{$oData->getTimestamp()}.xml";
         $this->sCaminhoArquivo = TEMP_PATH;
         /**
          * Verifica se o caminho do arquivo não existe recria a pasta
          */
         if (!file_exists($this->sCaminhoArquivo)) {
             mkdir($this->sCaminhoArquivo, 0777);
         }
         /**
          * Escreve os dados no arquivo
          */
         $this->sCaminhoNomeArquivo = $this->sCaminhoArquivo . $this->sNomeArquivo;
         $aArquivo = fopen($this->sCaminhoNomeArquivo, 'w');
         fputs($aArquivo, print_r($sArquivo, TRUE));
         fclose($aArquivo);
         //}
         $oValidacao = new DBSeller_Helper_Xml_AssinaturaDigital($sArquivo);
         /**
          * Validação digital do arquivo
          */
         if (!$oValidacao->validar()) {
             throw new Exception($oValidacao->getLastError());
         }
         $oUsuario = Administrativo_Model_Usuario::getByAttribute('cnpj', $oValidacao->getCnpj());
         if (!is_object($oUsuario)) {
             throw new Exception('Usuário contribuinte não existe!', 157);
         }
         /**
          * Busca usuário contribuinte através do usuário cadastrado
          */
         $aUsuarioContribuinte = Administrativo_Model_UsuarioContribuinte::getByAttributes(array('usuario' => $oUsuario->getId(), 'cnpj_cpf' => $oUsuario->getCnpj()));
         if (!is_object($aUsuarioContribuinte[0])) {
             throw new Exception('Usuário contribuinte não encontrado!', 160);
         }
         /**
          * Seta os dados do contribuinte
          */
         $this->oDadosUsuario = $oUsuario;
         $this->oContribuinte->sCpfCnpj = $aUsuarioContribuinte[0]->getCnpjCpf();
         $this->oContribuinte->iCodigoUsuario = $oUsuario->getId();
         $this->oContribuinte->iIdUsuarioContribuinte = $aUsuarioContribuinte[0]->getId();
         /**
          * Atualiza os dados do contribuinte na sessão
          */
         $oSessao = new Zend_Session_Namespace('nfse');
         $oSessao->contribuinte = Contribuinte_Model_Contribuinte::getById($this->oContribuinte->iIdUsuarioContribuinte);
         return TRUE;
     } catch (Exception $oErro) {
         throw new Exception($oErro->getMessage(), $oErro->getCode());
     }
 }
 /**
  * getTitle
  * Returns title
  * from a markdown source
  * eventually containing "====" underlined label,
  * usually parsed as <h1>
  *
  * @param string $markdown
  *
  * @return string $title
  */
 public function getTitle($markdown)
 {
     $html = "<xml>" . self::transform($markdown) . "</xml>";
     $dom = new \DOMDocument();
     $dom->loadXml($html);
     return $dom->getElementsByTagName('h1')->item(0)->nodeValue;
 }
Example #12
0
 /**
  * Normalizes a given xml string to be compareable.
  *
  * @param string $xml
  * @return string
  */
 protected function sanitizeXml($xml)
 {
     $dom = new \DOMDocument();
     $dom->loadXml($xml);
     //$dom->normalizeDocument();
     return $dom->saveXml();
 }
Example #13
0
 public function testParsing()
 {
     $collectionsJsonAtomString = file_get_contents("../data/collectionsjson.atom");
     $tagsJsonAtomString = file_get_contents("../data/tagsjson.atom");
     $doc = new DOMDocument();
     $doc->loadXml($collectionsJsonAtomString);
     $collectionfeed = new Zotero_Feed($doc);
     $this->assertEquals($collectionfeed->title, "Zotero / Z public library / Collections");
     $this->assertEquals($collectionfeed->id, "http://zotero.org/users/475425/collections?content=json");
     $this->assertEquals($collectionfeed->totalResults, 15);
     $this->assertEquals($collectionfeed->apiVersion, null);
     //deepEqual(collectionfeed.links, );
     //$this->assertEquals($collectionfeed->lastPageStart, '');
     //$this->assertEquals($collectionfeed->lastPage, 1);
     //$this->assertEquals($collectionfeed->currentPage, 1);
     $this->assertEquals($collectionfeed->dateUpdated, "2011-06-29T14:29:32Z");
     $doc = new DOMDocument();
     $doc->loadXml($tagsJsonAtomString);
     $tagsfeed = new Zotero_Feed($doc);
     $this->assertEquals($tagsfeed->title, "Zotero / Z public library / Tags");
     $this->assertEquals($tagsfeed->id, "http://zotero.org/users/475425/tags?content=json");
     $this->assertEquals($tagsfeed->totalResults, 192, "test total Results");
     $this->assertEquals($tagsfeed->apiVersion, null, "test apiVersion");
     //deepEqual(tagsfeed.links, );
     //$this->assertEquals($tagsfeed->lastPageStart, 150, "correctly found lastPageStart");
     //$this->assertEquals($tagsfeed->lastPage, 4, "correctly found lastPage");
     //$this->assertEquals($tagsfeed->currentPage, 1, "correctly found currentPage");
     $this->assertEquals($tagsfeed->dateUpdated, "2011-04-11T16:37:49Z", "found and parsed updated date");
 }
    protected function doRemoveNamespacedNodes(&$pq)
    {
        $xsl = <<<____EOF
      <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" exclude-result-prefixes="xsl">
          <xsl:template match="*[local-name()=name()]">
              <xsl:element name="{local-name()}">
                  <xsl:apply-templates select="@* | node()"/>
              </xsl:element>
          </xsl:template>
          <xsl:template match="@* | text()">
              <xsl:copy/>
          </xsl:template>
      </xsl:stylesheet>
____EOF;
        $xsl = \DOMDocument::loadXml($xsl);
        $proc = new \XSLTProcessor();
        $proc->importStyleSheet($xsl);
        $pq->document = $proc->transformToDoc($pq->document);
        for ($i = $pq->document->documentElement->attributes->length; $i >= 0; --$i) {
            $attr = $pq->document->documentElement->attributes->item($i);
            if (substr($attr->name, 0, 6) === 'xmlns:') {
                $pq->document->documentElement->removeAttributeNode($attr);
            }
        }
        $pq = PhpQuery::newDocumentHTML($pq->document->saveHTML());
        return $this;
    }
Example #15
0
 public function __construct($xml)
 {
     $dom = new \DOMDocument();
     $dom->loadXml($xml);
     $this->domXpath = new \DOMXPath($dom);
     $this->domXpath->registerNamespace('php', 'http://php.net/xpath');
     $this->domXpath->registerPhpFunctions('strtolower');
 }
Example #16
0
 public function testWithExplicitLinkType()
 {
     $template = $this->getContainer()->get('twig')->createTemplate('{{ knp_menu_render("another-menu") }}');
     $dom = new \DOMDocument();
     $dom->loadXml($template->render(array()));
     $items = array('This node has uri, route and content set. but linkType is set to route' => '/link_test_route', 'item-2' => null);
     $this->assertMenu($items, $dom);
 }
Example #17
0
 /**
  * Test showXml
  *
  * @param   string  $form  The form.
  *
  * @return void
  */
 private function _showXml($form)
 {
     $dom = new DOMDocument('1.0');
     $dom->preserveWhiteSpace = false;
     $dom->formatOutput = true;
     $dom->loadXml($form->getXml()->asXml());
     echo $dom->saveXml();
 }
Example #18
0
function parseXML($file)
{
    $xml = file_get_contents($file);
    $dom = new DOMDocument('1.0', 'UTF-8');
    $dom->preserveWhiteSpace = true;
    $dom->loadXml($xml);
    return $dom;
}
Example #19
0
 public function readXml($xml)
 {
     $doc = new \DOMDocument();
     $doc->loadXml($xml);
     $entryNode = $doc->getElementsByTagName('entry')->item(0);
     $this->apiObj['meta']['created'] = $entryNode->getElementsByTagName("published")->item(0)->nodeValue;
     $this->apiObj['meta']['lastModified'] = $entryNode->getElementsByTagName("updated")->item(0)->nodeValue;
 }
Example #20
0
 /**
  * Loads an XRD document from string
  *
  * @param string $xrdString 
  * @return XRD_Document
  * @throws XRD_Exception
  */
 public static function fromString($xrdString)
 {
     $dom = new DOMDocument();
     if (!$dom->loadXml($xrdString)) {
         throw new XRD_Exception("Could not load XRD from string");
     }
     return self::fromDOMDocument($dom);
 }
Example #21
0
 public function write()
 {
     $modification = array();
     foreach ($this->data as $xml) {
         $dom = new DOMDocument('1.0', 'UTF-8');
         $dom->loadXml($xml);
         $files = $dom->getElementsByTagName('modification')->item(0)->getElementsByTagName('file');
         foreach ($files as $file) {
             $files = glob($this->directory . $file->getAttribute('name'));
             $operations = $file->getElementsByTagName('operation');
             if ($files) {
                 foreach ($files as $file) {
                     if (!isset($modification[$file])) {
                         $modification[$file] = file_get_contents($file);
                     }
                     foreach ($operations as $operation) {
                         $search = $operation->getElementsByTagName('search')->item(0)->nodeValue;
                         $index = $operation->getElementsByTagName('search')->item(0)->getAttribute('index');
                         $add = $operation->getElementsByTagName('add')->item(0)->nodeValue;
                         $position = $operation->getElementsByTagName('add')->item(0)->getAttribute('position');
                         if (!$index) {
                             $index = 1;
                         }
                         switch ($position) {
                             default:
                             case 'replace':
                                 $replace = $add;
                                 break;
                             case 'before':
                                 $replace = $add . $search;
                                 break;
                             case 'after':
                                 $replace = $search . $add;
                                 break;
                         }
                         $i = 0;
                         $pos = -1;
                         $result = array();
                         while (($pos = strpos($modification[$file], $search, $pos + 1)) !== false) {
                             $result[$i++] = $pos;
                         }
                         // Only replace the occurance of the string that is equal to the index
                         if (isset($result[$index - 1])) {
                             $modification[$file] = substr_replace($modification[$file], $replace, $result[$index - 1], strlen($search));
                         }
                     }
                 }
             }
         }
     }
     // Write all modification files
     foreach ($modification as $key => $value) {
         $file = DIR_MODIFICATION . str_replace('/', '_', substr($key, strlen($this->directory)));
         $handle = fopen($file, 'w');
         fwrite($handle, $value);
         fclose($handle);
     }
 }
Example #22
0
 /**
  * Converts an XML result set to an array
  */
 public function toArray($xmlSparqlResults)
 {
     $document = new DOMDocument();
     $document->preserveWhiteSpace = false;
     $document->loadXml($xmlSparqlResults);
     $this->detectNamespacesFromDocument($document);
     $vars = array();
     $bindings = array();
     $root = $document->firstChild;
     $set = $root->firstChild;
     foreach ($set->childNodes as $node) {
         if (!$node->hasChildNodes()) {
             continue;
         }
         $row = array();
         foreach ($node->childNodes as $binding) {
             // exlude text nodes etc.
             if (!$binding instanceof DOMElement) {
                 continue;
             }
             $attrKey = $binding->getAttributeNodeNS($this->_namespaces['rs'], 'name');
             $nodeValue = $binding->firstChild;
             $dataKey = $attrKey->value;
             if (!in_array($dataKey, $vars)) {
                 array_push($vars, $dataKey);
             }
             $attributes = array();
             foreach ($nodeValue->attributes as $attribute) {
                 $attributes[$attribute->name] = $attribute->value;
             }
             switch (true) {
                 case array_key_exists('resource', $attributes):
                     $row[$dataKey] = array('value' => $nodeValue->getAttributeNodeNS($this->_namespaces['rdf'], 'resource')->value, 'type' => 'uri');
                     break;
                 case array_key_exists('nodeID', $attributes):
                     $row[$dataKey] = array('value' => $nodeValue->getAttributeNodeNS($this->_namespaces['rdf'], 'nodeID')->value, 'type' => 'bnode');
                     break;
                 default:
                     // literal
                     $lang = $nodeValue->getAttributeNodeNS($this->_namespaces['xml'], 'lang');
                     $datatype = $nodeValue->getAttributeNodeNS($this->_namespaces['rdf'], 'datatype');
                     $row[$dataKey] = array('value' => $nodeValue->textContent, 'type' => $datatype ? 'typed-literal' : 'literal');
                     if ($datatype) {
                         $row[$dataKey]['datatype'] = (string) $datatype->value;
                     }
                     if ($lang) {
                         $row[$dataKey]['xml:lang'] = (string) $lang->value;
                     }
                     break;
             }
         }
         // add row
         array_push($bindings, $row);
     }
     $result = array('head' => array('vars' => $vars), 'bindings' => $bindings);
     return $result;
 }
 protected function doParse($xml)
 {
     set_error_handler(function ($errno, $errstr, $errfile = null, $errline = null, array $errcontext = null) {
         throw new InvalidArgumentException($errstr);
     });
     $dom = new \DOMDocument();
     $dom->loadXml($xml);
     restore_error_handler();
     $fixField = function ($s) {
         return preg_replace('/\\s+/', " ", trim($s));
     };
     $fixReleaseDate = function ($releaseDate) {
         if (preg_match('/(\\d{4,4})(\\d{2,2})(\\d{2,2})/', $releaseDate, $matches)) {
             $date = sprintf('%d-%d-%d', $matches[1], $matches[2], $matches[3]);
             return \DateTime::createFromFormat('Y-m-d', $date);
         }
         return '0000-00-00';
     };
     $fixBundleRestriction = function ($bundleRestriction) {
         return preg_match('/^True$/i', $bundleRestriction) ? 1 : 0;
     };
     $release = clone $this->releasePrototype;
     $release->setLabel($fixField($this->getDomVal($dom, 'labelname')));
     $release->setName($fixField($this->getDomVal($dom, 'release_name')));
     $release->setEan($fixField($this->getDomVal($dom, 'release_ean')));
     $release->setCatalogNumber($fixField($this->getDomVal($dom, 'release_catno')));
     $release->setUuid($fixField($this->getDomVal($dom, 'release_uuid')));
     $release->setPhysicalReleaseDate($fixReleaseDate($this->getDomVal($dom, 'release_physical_releasedate')));
     $release->setDigitalReleaseDate($fixReleaseDate($this->getDomVal($dom, 'release_digital_releasedate')));
     $release->setOriginalFormat($fixField($this->getDomVal($dom, 'release_originalformat')));
     $release->setShortInfoEn($fixField($this->getDomVal($dom, 'release_short_info_e')));
     $release->setShortInfoDe($fixField($this->getDomVal($dom, 'release_short_info_d')));
     $release->setInfoEn($fixField($this->getDomVal($dom, 'release_info_e')));
     $release->setInfoDe($fixField($this->getDomVal($dom, 'release_info_d')));
     $release->setSaleTerritories($fixField($this->getDomVal($dom, 'release_saleterritories')));
     $release->setBundleRestriction($fixBundleRestriction($this->getDomVal($dom, 'release_bundlerestriction')));
     $tracks = $this->getDomElement($dom, 'tracks');
     foreach ($tracks->getElementsByTagName('track') as $t) {
         $track = clone $this->trackPrototype;
         $track->setIsrc($fixField($this->getDomVal($t, 'track_isrc')));
         $track->setUuid($fixField($this->getDomVal($t, 'track_uuid')));
         $track->setPosition($fixField($this->getDomVal($t, 'track_originalposition')));
         $track->setArtist($fixField($this->getDomVal($t, 'track_artist')));
         $track->setComposer($fixField($this->getDomVal($t, 'track_composer')));
         $track->setSongwriter($fixField($this->getDomVal($t, 'track_songwriter')));
         $track->setPublisher($fixField($this->getDomVal($t, 'track_publisher')));
         $track->setTitle($fixField($this->getDomVal($t, 'track_title')));
         $track->setGenre($fixField($this->getDomVal($t, 'track_genre')));
         $track->setMedia($fixField($this->getDomVal($t, 'track_media')));
         $track->setDiscNr($fixField($this->getDomVal($t, 'track_num_disc_num')));
         $track->setAlbumNr($fixField($this->getDomVal($t, 'track_num_album_num')));
         $track->setDuration($fixField($this->getDomVal($t, 'track_duration')));
         $release->addTrack($track);
     }
     return $release;
 }
Example #24
0
 /**
  * Scan XML string for potential XXE and XEE attacks
  *
  * @param   string $xml
  * @param   DomDocument $dom
  * @throws  Zend_Xml_Exception
  * @return  SimpleXMLElement|DomDocument|boolean
  */
 public static function scan($xml, DOMDocument $dom = null)
 {
     // If running with PHP-FPM we perform an heuristic scan
     // We cannot use libxml_disable_entity_loader because of this bug
     // @see https://bugs.php.net/bug.php?id=64938
     if (self::isPhpFpm()) {
         self::heuristicScan($xml);
     }
     if (null === $dom) {
         $simpleXml = true;
         $dom = new DOMDocument();
     }
     if (!self::isPhpFpm()) {
         $loadEntities = libxml_disable_entity_loader(true);
         $useInternalXmlErrors = libxml_use_internal_errors(true);
     }
     // Load XML with network access disabled (LIBXML_NONET)
     // error disabled with @ for PHP-FPM scenario
     set_error_handler(array('Zend_Xml_Security', 'loadXmlErrorHandler'), E_WARNING);
     $result = $dom->loadXml($xml, LIBXML_NONET);
     restore_error_handler();
     if (!$result) {
         // Entity load to previous setting
         if (!self::isPhpFpm()) {
             libxml_disable_entity_loader($loadEntities);
             libxml_use_internal_errors($useInternalXmlErrors);
         }
         return false;
     }
     // Scan for potential XEE attacks using ENTITY, if not PHP-FPM
     if (!self::isPhpFpm()) {
         foreach ($dom->childNodes as $child) {
             if ($child->nodeType === XML_DOCUMENT_TYPE_NODE) {
                 if ($child->entities->length > 0) {
                     libxml_disable_entity_loader($loadEntities);
                     libxml_use_internal_errors($useInternalXmlErrors);
                     #require_once 'Exception.php';
                     throw new Zend_Xml_Exception(self::ENTITY_DETECT);
                 }
             }
         }
     }
     // Entity load to previous setting
     if (!self::isPhpFpm()) {
         libxml_disable_entity_loader($loadEntities);
         libxml_use_internal_errors($useInternalXmlErrors);
     }
     if (isset($simpleXml)) {
         $result = simplexml_import_dom($dom);
         if (!$result instanceof SimpleXMLElement) {
             return false;
         }
         return $result;
     }
     return $dom;
 }
 public function validateXml($xmlString, $schemaFileName, $errorMessageIntro = "Error validating XML: ")
 {
     $domXml = new DOMDocument();
     $domXml->loadXml($xmlString);
     $schemaFilePath = realpath("../application/schema") . '/' . $schemaFileName;
     if (!$domXml->schemaValidate(realpath($schemaFilePath))) {
         throw new ZendExt_XmlRequestBodyException($errorMessageIntro . libxml_get_last_error()->message);
     }
     return $domXml;
 }
 function PerformXslTransform()
 {
     $xmlObject = new DOMDocument();
     $xmlObject->loadXml($this->xml);
     $xslt = new XSLTProcessor();
     $xsl = new DOMDocument();
     $xsl->load($this->xslFile, LIBXML_NOCDATA);
     $xslt->importStylesheet($xsl);
     // TODO - Need to pass back xsl styled xml as string, currently does not work
 }
Example #27
0
 /**
  * 
  */
 public function next()
 {
     $this->pos++;
     $this->token = $this->results->fetch(\PDO::FETCH_COLUMN);
     if ($this->token !== false) {
         $tokenDom = new \DOMDocument();
         $tokenDom->loadXml($this->token);
         $this->token = new \import\Token($tokenDom->documentElement, $this->document);
     }
 }
Example #28
0
 public function load($xml)
 {
     set_error_handler(function ($errno, $errstr, $errfile = null, $errline = null, array $errcontext = null) {
         throw new InvalidArgumentException($errstr);
     });
     $dom = new \DOMDocument();
     $dom->loadXml($xml);
     restore_error_handler();
     return $dom;
 }
 public function getRecommendationsDom($html = null)
 {
     if (!$html) {
         $html = $this->toHtml();
     }
     $dom = new DOMDocument('1.0', 'utf8');
     $dom->loadXml('<root/>');
     $fragment = $dom->createDocumentFragment();
     $fragment->appendXML($html);
     return $fragment;
 }
Example #30
0
 function test()
 {
     $textarea = new FormKit\Widget\TextareaInput('address');
     $html = $textarea->render(array('rows' => 30, 'cols' => 45));
     $dom = new DOMDocument();
     $dom->loadXml($html);
     is('formkit-widget formkit-widget-textarea', $dom->documentElement->getAttribute('class'));
     is('address', $dom->documentElement->getAttribute('name'));
     is('45', $dom->documentElement->getAttribute('cols'));
     is('30', $dom->documentElement->getAttribute('rows'));
 }