/** * * @param string $xml * @return \DOMDocument * @throws ResponseException */ private function parseResponse($xml) { if (strlen($xml) === 0) { throw new ResponseException('Brak odpowiedzi na żądanie.'); } $doc = new \DOMDocument(); try { $doc->loadXML($xml); } catch (\Exception $e) { throw new ResponseException('Nieprawidłowy format odpowiedzi.'); } $xpath = new \DOMXpath($doc); $xpath->registerNamespace('env', 'http://schemas.xmlsoap.org/soap/envelope/'); $xpath->registerNamespace('xsi', 'http://www.w3.org/2001/XMLSchema-instance'); $xpath->registerNamespace('com', 'http://xml.kamsoft.pl/ws/common'); $fault = $xpath->query('//env:Fault'); if ($fault->length === 1) { $e = new ResponseException(); $com = $xpath->query('//com:*'); if ($com->length >= 1) { $type = $com->item(0)->getAttribute("xsi:type"); $type = mb_substr($type, mb_strpos($type, ':') + 1); $e->setType($type); $com = $xpath->query('//com:faultstring'); if ($com->length === 1) { $e->setMessage($com->item(0)->nodeValue); } } throw $e; } return $doc; }
function populate_resource($id, $overrideExportable = false) { //local SOLR index for fast searching $ci =& get_instance(); $ci->load->library('solr'); $ci->solr->clearOpt('fq'); $ci->solr->setOpt('fq', '+id:' . $id); $this->overrideExportable = $overrideExportable; $result = $ci->solr->executeSearch(true); if (sizeof($result['response']['docs']) == 1) { $this->index = $result['response']['docs'][0]; } //local XML resource $xml = $this->ro->getSimpleXML(); $xml = addXMLDeclarationUTF8($xml->registryObject ? $xml->registryObject->asXML() : $xml->asXML()); $xml = simplexml_load_string($xml); $xml = simplexml_load_string(addXMLDeclarationUTF8($xml->asXML())); if ($xml) { $this->xml = $xml; $rifDom = new DOMDocument(); $rifDom->loadXML($this->ro->getRif()); $gXPath = new DOMXpath($rifDom); $gXPath->registerNamespace('ro', 'http://ands.org.au/standards/rif-cs/registryObjects'); $this->gXPath = $gXPath; } }
/** * {@inheritDoc} */ protected function afterLoad() { $this->document = new \DOMDocument(); $this->document->loadXML($this->response); $this->xpath = new \DOMXpath($this->document); $this->xpath->registerNamespace('a', 'http://www.w3.org/2005/Atom'); }
/** * {@inheritdoc} */ public function loadMetadataFromFile(\ReflectionClass $class, $path) { $classMetadata = new ClassMetadata($class->getName()); $use = libxml_use_internal_errors(true); $dom = new \DOMDocument('1.0'); $dom->load($path); if (!$dom->schemaValidate(__DIR__ . '/../../../schema/mapping.xsd')) { $message = array_reduce(libxml_get_errors(), function ($foo, $error) { return $error->message; }); throw new \InvalidArgumentException(sprintf('Could not validate XML mapping at "%s": %s', $path, $message)); } libxml_use_internal_errors($use); $xpath = new \DOMXpath($dom); $xpath->registerNamespace('psict', self::XML_NAMESPACE); foreach ($xpath->query('//psict:class') as $classEl) { $classAttr = $classEl->getAttribute('name'); if ($classAttr !== $class->getName()) { throw new \InvalidArgumentException(sprintf('Expected class name to be "%s" but it is mapped as "%s"', $class->getName(), $classAttr)); } foreach ($xpath->query('./psict:field', $classEl) as $fieldEl) { $shared = $this->extractOptionSet($xpath, $fieldEl, 'shared-options'); $form = $this->extractOptionSet($xpath, $fieldEl, 'form-options'); $view = $this->extractOptionSet($xpath, $fieldEl, 'view-options'); $storage = $this->extractOptionSet($xpath, $fieldEl, 'storage-options'); $propertyMetadata = new PropertyMetadata($class->getName(), $fieldEl->getAttribute('name'), $fieldEl->getAttribute('type'), $fieldEl->getAttribute('role'), $fieldEl->getAttribute('group'), ['shared' => $shared, 'form' => $form, 'view' => $view, 'storage' => $storage]); $classMetadata->addPropertyMetadata($propertyMetadata); } } return $classMetadata; }
/** * Returns if significant whitespaces occur in the paragraph. * * This method checks if the paragraph $element contains significant * whitespaces in form of <text:s/> or <text:tab/> elements. * * @param DOMElement $element * @return bool */ protected function hasSignificantWhitespace(DOMElement $element) { $xpath = new DOMXpath($element->ownerDocument); $xpath->registerNamespace('text', ezcDocumentOdt::NS_ODT_TEXT); $whitespaces = $xpath->evaluate('.//text:s|.//text:tab|.//text:line-break', $element); return $whitespaces instanceof DOMNodeList && $whitespaces->length > 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; }
/** * 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'); }
function casValidate($cas) { $service = SimpleSAML_Utilities::selfURL(); $service = preg_replace("/(\\?|&)?ticket=.*/", "", $service); # always tagged on by cas /** * Got response from CAS server. */ if (isset($_GET['ticket'])) { $ticket = urlencode($_GET['ticket']); #ini_set('default_socket_timeout', 15); if (isset($cas['validate'])) { # cas v1 yes|no\r<username> style $paramPrefix = strpos($cas['validate'], '?') ? '&' : '?'; $result = SimpleSAML_Utilities::fetch($cas['validate'] . $paramPrefix . 'ticket=' . $ticket . '&service=' . urlencode($service)); $res = preg_split("/\r?\n/", $result); if (strcmp($res[0], "yes") == 0) { return array($res[1], array()); } else { throw new Exception("Failed to validate CAS service ticket: {$ticket}"); } } elseif (isset($cas['serviceValidate'])) { # cas v2 xml style $paramPrefix = strpos($cas['serviceValidate'], '?') ? '&' : '?'; $result = SimpleSAML_Utilities::fetch($cas['serviceValidate'] . $paramPrefix . 'ticket=' . $ticket . '&service=' . urlencode($service)); $dom = DOMDocument::loadXML($result); $xPath = new DOMXpath($dom); $xPath->registerNamespace("cas", 'http://www.yale.edu/tp/cas'); $success = $xPath->query("/cas:serviceResponse/cas:authenticationSuccess/cas:user"); if ($success->length == 0) { $failure = $xPath->evaluate("/cas:serviceResponse/cas:authenticationFailure"); throw new Exception("Error when validating CAS service ticket: " . $failure->item(0)->textContent); } else { $attributes = array(); if ($casattributes = $cas['attributes']) { # some has attributes in the xml - attributes is a list of XPath expressions to get them foreach ($casattributes as $name => $query) { $attrs = $xPath->query($query); foreach ($attrs as $attrvalue) { $attributes[$name][] = $attrvalue->textContent; } } } $casusername = $success->item(0)->textContent; return array($casusername, $attributes); } } else { throw new Exception("validate or serviceValidate not specified"); } /** * First request, will redirect the user to the CAS server for authentication. */ } else { SimpleSAML_Logger::info("AUTH - cas-ldap: redirecting to {$cas['login']}"); SimpleSAML_Utilities::redirectTrustedURL($cas['login'], array('service' => $service)); } }
private function parseToken($token) { $dom = new DOMDocument(); $token = str_replace('\\"', '"', $token); $dom->loadXML(str_replace("\r", "", $token)); $xpath = new DOMXpath($dom); $xpath->registerNamespace('wst', self::NS_WS_TRUST); $xpath->registerNamespace('saml', SAML2_Const::NS_SAML); $assertions = $xpath->query('/wst:RequestSecurityTokenResponse/wst:RequestedSecurityToken/saml:Assertion'); if ($assertions->length === 0) { $this->error('Received a response without an assertion on the WS-Fed PRP handler.'); } if ($assertions->length > 1) { $this->error('The WS-Fed PRP handler currently only supports a single assertion in a response.'); } $assertion = $assertions->item(0); return array('Assertion' => $assertion, 'XPath' => $xpath); }
function execute( $par ) { $this->setHeaders(); $this->outputHeader(); $request = $this->getRequest(); $file = !is_null( $par ) ? $par : $request->getText( 'file' ); $title = Title::newFromText( $file, NS_FILE ); if ( ! $title instanceof Title || $title->getNamespace() != NS_FILE ) { $this->showForm( $title ); } else { $file = wfFindFile( $title ); if ( $file && $file->exists() ){ $this->svg = new DOMDocument( '1.0' ); $this->svg->load( $file->getLocalRefPath() ); $this->xpath = new DOMXpath( $this->svg ); $this->xpath->registerNamespace( 'svg', 'http://www.w3.org/2000/svg' ); if( $this->makeTranslationReady() ){ $this->extractTranslations(); $this->tidyTranslations(); $params = $request->getQueryValues(); if( count( $params ) > 2 && isset( $params['title'] ) && isset( $params['file'] ) && isset( $params['step'] ) ){ $filename = $params['file']; unset( $params['title'], $params['file'], $params['step'] ); $this->updateTranslations( $params ); $this->updateSVG(); $this->saveSVG( $file->getLocalRefPath(), $filename ); $file->purgeThumbnails(); } else { $this->thumb = Linker::makeThumbLinkObj( $title, $file, $label = '', '', $align = $this->getLanguage()->alignEnd(), array( 'width' => 250, 'height' => 250 ) ); $this->printTranslations( $file->getName() ); } } else { $this->getOutput()->addWikiMsg( 'translatesvg-unsuccessful' ); } } else { $this->getOutput()->setStatusCode( 404 ); $this->showForm( $title ); } } }
private function registerNamespace(\DOMXpath $xpath) { $namespaces = $this->getNamespaces(); foreach ($namespaces as $prefix => $namespace) { if (empty($prefix) && $this->hasDefaultNamespace()) { $prefix = 'rootns'; } $xpath->registerNamespace($prefix, $namespace); } }
function check_ewus($username, $password, $pac_pesel) { $params = array('credentials' => array(array('name' => 'domain', 'value' => array('stringValue' => '07')), array('name' => 'login', 'value' => array('stringValue' => $username))), 'password' => $password); try { $clientAuth = new SoapClient('https://ewus.nfz.gov.pl/ws-broker-server-ewus/services/Auth?wsdl', array('trace' => true)); $clientAuth->__soapCall('login', array($params), null, null, $loginHeaders); $date = date('Y-m-d\\TH:i:s.BP'); $xml = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:com="http://xml.kamsoft.pl/ws/common" xmlns:brok="http://xml.kamsoft.pl/ws/broker"> <soapenv:Header> <com:session id="' . $loginHeaders['session']->id . '" xmlns:ns1="http://xml.kamsoft.pl/ws/common"/> <com:authToken id="' . $loginHeaders['authToken']->id . '" xmlns:ns1="http://xml.kamsoft.pl/ws/common"/> </soapenv:Header> <soapenv:Body> <brok:executeService> <com:location> <com:namespace>nfz.gov.pl/ws/broker/cwu</com:namespace> <com:localname>checkCWU</com:localname> <com:version>2.0</com:version> </com:location> <brok:date>' . $date . '</brok:date> <brok:payload> <brok:textload> <ewus:status_cwu_pyt xmlns:ewus="https://ewus.nfz.gov.pl/ws/broker/ewus/status_cwu/v2"> <ewus:numer_pesel>' . $pac_pesel . '</ewus:numer_pesel> <ewus:system_swiad nazwa="eWUS" wersja="2.0"/> </ewus:status_cwu_pyt> </brok:textload> </brok:payload> </brok:executeService> </soapenv:Body> </soapenv:Envelope>'; $clientBroker = new SoapClient('https://ewus.nfz.gov.pl/ws-broker-server-ewus/services/ServiceBroker?wsdl', array('trace' => true, 'exceptions' => true)); $r = $clientBroker->__doRequest($xml, 'https://ewus.nfz.gov.pl/ws-broker-server-ewus/services/ServiceBroker', 'executeService', SOAP_1_1); $doc = new DOMDocument(); $doc->loadXML($r); $blad = $doc->getElementsByTagName('faultstring')->item(0); if ($blad != '') { return $blad->nodeValue; } else { $match = $doc->getElementsByTagName('status_cwu_odp'); $foundXML = $doc->saveXML($match->item(0)); $xpath = new DOMXpath($doc); $xpath->registerNamespace('odp', 'https://ewus.nfz.gov.pl/ws/broker/ewus/status_cwu/v2'); $ewus_odp['nr_potw'] = $xpath->query("//odp:status_cwu_odp")->item(0)->getAttribute('id_operacji'); $ewus_odp['potwierdzenie'] = $foundXML; $elements = $xpath->query("//odp:status_ubezp"); $ewus_odp['status'] = $elements->item(0)->nodeValue; $ewus_odp['data'] = date('Y-m-d'); return $ewus_odp; } } catch (Exception $e) { return $e->faultstring; } }
/** * * @inheritdoc */ public function makeResponse(\DOMDocument $dom) { $response = new ChangePasswordResponse(); $xpath = new \DOMXpath($dom); $xpath->registerNamespace('lt', 'http://xml.kamsoft.pl/ws/kaas/login_types'); $element = $xpath->query("//lt:changePasswordReturn"); if ($element->length === 0) { throw new ResponseException('Nie można pobrać informacji zwrotnej.'); } $response->setMessage($element->item(0)->nodeValue); return $response; }
/** * Load Dom & Xpath of xml item content & register xpath namespace * * @param \core_kernel_classes_Resource $item * @return $this * @throws ExtractorException */ private function loadXml(\core_kernel_classes_Resource $item) { $itemService = Service::singleton(); $xml = $itemService->getXmlByRdfItem($item); if (empty($xml)) { throw new ExtractorException('No content found for item ' . $item->getUri()); } $this->dom = new \DOMDocument(); $this->dom->loadXml($xml); $this->xpath = new \DOMXpath($this->dom); $this->xpath->registerNamespace('qti', 'http://www.imsglobal.org/xsd/imsqti_v2p1'); return $this; }
private function cleanByCSS() { $xpath = new \DOMXpath($this->dom); $xpath->registerNamespace("php", "http://php.net/xpath"); $xpath->registerPHPFunctions(); foreach ($this->badCssSelector as $selector) { if ($nodeList = $xpath->query($selector)) { foreach ($nodeList as $node) { $node->parentNode->removeChild($node); } } } return $this->dom->saveHTML(); }
/** * Constructor * * @param * @return */ function __construct($a_manifest_dom, $a_obj_id) { $this->manifest_dom = $a_manifest_dom; $path = new DOMXpath($a_manifest_dom); $path->registerNamespace("ims", "http://www.imsproject.org/xsd/imscp_rootv1p1p2"); $items = $path->query("//ims:manifest/ims:metadata"); if ($items->length == 1) { foreach ($items as $i) { //echo htmlentities($a_manifest_dom->saveXML($i)); exit; parent::__construct($a_manifest_dom->saveXML($i), $a_obj_id, $a_obj_id, ilObject::_lookupType($a_obj_id)); $this->metadata_found = true; } } }
/** * Parse the table of contents file and populate nav data */ public function parse() { $this->navData = array(); $doc = new ChaucerDomDocument(); $doc->loadHTMLFile($this->path); $xpath = new DOMXpath($doc); $xpath->registerNamespace('epub', 'http://www.idpf.org/2007/ops'); $parentElements = $xpath->query("//nav"); if (!is_null($parentElements)) { foreach ($parentElements as $parentNode) { if ($parentNode->getAttribute('epub:type') == 'toc') { $this->navData = $this->parseTocNode($parentNode, $xpath, 0, 0); } } } }
/** * * @inheritdoc */ public function makeResponse(\DOMDocument $xml) { $xpath = new \DOMXpath($xml); $xpath->registerNamespace('odp', 'https://ewus.nfz.gov.pl/ws/broker/ewus/status_cwu/v3'); $response = new CheckPeselResponse(); $elements = $xpath->query("//odp:status_cwu_odp"); if ($elements->length !== 1) { throw new ResponseException('Nie można pobrać informacji o id operacji.'); } $response->setData($elements->item(0)->getAttribute('id_operacji'), CheckPeselResponse::DATA_OPERATION_ID); $elements = $xpath->query("//odp:status_cwu"); if ($elements->length !== 1) { throw new ResponseException('Nie można pobrać informacji o statusie pacjenta.'); } $status = $elements->item(0)->nodeValue; if ($status === '1') { $elements = $xpath->query("//odp:status_ubezp"); if ($elements->length !== 1) { throw new ResponseException('Nie można pobrać informacji o uprawnieniu do świadczeń.'); } } $response->setData($status === '1' ? $elements->item(0)->nodeValue : CheckPeselResponse::STATUS_NOT_EXIST, CheckPeselResponse::DATA_STATUS); if ($status === '1') { $elements = $xpath->query("//odp:imie"); if ($elements->length !== 1) { throw new ResponseException('Nie można pobrać informacji o imieniu pacjenta.'); } } $response->setData($status === '1' ? $elements->item(0)->nodeValue : null, CheckPeselResponse::DATA_PATIENT_NAME); if ($status === '1') { $elements = $xpath->query("//odp:nazwisko"); if ($elements->length !== 1) { throw new ResponseException('Nie można pobrać informacji o nazwisko upacjenta.'); } } $response->setData($status === '1' ? $elements->item(0)->nodeValue : null, CheckPeselResponse::DATA_PATIENT_SURNAME); if ($status === '1') { $elements = $xpath->query("//odp:id_ow"); if ($elements->length !== 1) { throw new ResponseException('Nie można pobrać informacji o identyfikatorze świadczeniodawcy.'); } } $response->setData($status === '1' ? $elements->item(0)->nodeValue : null, CheckPeselResponse::DATA_PROVIDER); return $response; }
public function set_element($name, $value = null, $attributes = array()) { $xpath = new DOMXpath($this->document); $xpath->registerNamespace('atom', SIMPLEPIE_NAMESPACE_ATOM_10); $existing = $xpath->query('/atom:entry/atom:' . $name); if ($existing->length > 0) { $existing = $existing->item(0); } else { $existing = $this->document->createElementNS(SIMPLEPIE_NAMESPACE_ATOM_10, $name); $this->document->firstChild->appendChild($existing); } if ($value !== null) { $existing->nodeValue = $value; } foreach ($attributes as $a_name => $a_value) { $existing->setAttributeNS(SIMPLEPIE_NAMESPACE_ATOM_10, $a_name, $a_value); } }
/** * 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; } }
/** * @dataProvider fixtures */ public function testC14N($rawContent, $canonicalizedContent, $comments, $exclusive, $subset, $predefinedNamespaces, $inclusiveNamespaces, $pathToRoot) { $rawDocument = new DOMDocument(); $oldDirectory = getcwd(); chdir($this->getFixturePath()); $rawDocument->loadXml($rawContent, LIBXML_DTDLOAD | LIBXML_DTDATTR | LIBXML_NOENT); chdir($oldDirectory); $canonicalizer = $this->getCanonicalizer()->withComments($comments)->exclusive($exclusive)->query($subset)->namespaces($predefinedNamespaces)->inclusiveNamespaces($inclusiveNamespaces); if ($pathToRoot) { $xpath = new DOMXpath($rawDocument); foreach ($predefinedNamespaces as $prefix => $ns) { $xpath->registerNamespace($prefix, $ns); } $nodeset = $xpath->query($pathToRoot); $rootNode = $nodeset->item(0); } else { $rootNode = $rawDocument; } $this->assertEquals($canonicalizedContent, $canonicalizer->canonicalize($rootNode)); }
function process_row($file, $collection, $writer, $count) { $fileArray = explode('/', $file); $id = str_replace('.xml', '', $fileArray[count($fileArray) - 1]); $dom = new DOMDocument('1.0', 'UTF-8'); if ($dom->load($file) === FALSE) { echo "{$file} failed to load.\n"; } else { $xpath = new DOMXpath($dom); $xpath->registerNamespace("lido", "http://www.lido-schema.org"); //look for the URI $terms = $xpath->query("descendant::lido:term[@lido:label='typereference']"); $hoardURI = null; $typeURI = null; foreach ($terms as $term) { if (preg_match('/coinhoards\\.org/', $term->nodeValue)) { $hoardURI = $term->nodeValue; echo "Found {$hoardURI}\n"; } else { //ignore IKMK type references $source = $term->getAttribute('lido:source'); if ($source == 'crro' || $source == 'ocre' || $source == 'pella') { $typeURI = $term->nodeValue; } } } //if the type URI can be assertained from the typereference LIDO field if (isset($typeURI)) { echo "Processing #{$count}: {$id}, {$typeURI}\n"; generateNumismaticObject($id, $typeURI, $collection, $xpath, $writer); } else { $typeURI = parseReference($xpath); if (isset($typeURI)) { echo "Processing #{$count}: {$id}, {$typeURI}\n"; generateNumismaticObject($id, $typeURI, $collection, $xpath, $writer); } else { echo "Processing #{$count}: {$id}, unable to match.\n"; } } } }
/** * Initializes document subset object * * If a query XPath expression is provided, it is used to * determine nodes in the subset; otherwise apex node subtree will * be used as a document subset. * * When query XPath expression is evaluated, apex node is used as * a context. * * @param DOMDocument $doc document being canonicalized * * @param DOMNode $apex apex node * * @param Sisyphus_C14n_Context $contenxt canonicalization * settings context */ function __construct(DOMDocument $doc, DOMNode $apex, Sisyphus_C14n_Context $context) { $query = $context->getQuery(); // Reset apex node to document base if we have explicitly // provided document subset XPath expression $this->setApex($query ? $doc : $apex); if (!$query) { $this->setNodeset(null); return $this; } $xpath = new DOMXpath($doc); foreach ($context->getNamespaces() as $prefix => $uri) { $xpath->registerNamespace($prefix, $uri); } $nodeset = array(); // Note that we should use original apex node as a // context node for XPath expression foreach ($xpath->query($query, $apex) as $n) { $nodeset[] = $n; } $this->setNodeset($nodeset); return $this; }
<?php $directories = glob('/home/komet/ans_migration/ebooks/*', GLOB_ONLYDIR); $csv = 'filename,title,author1,author2,author3'; foreach ($directories as $folder) { $files = scandir($folder); //echo $folder . "\n"; //var_dump($files); foreach ($files as $filename) { if (strpos($filename, '.xml') !== FALSE) { $file = "{$folder}/{$filename}"; $dom = new DOMDocument('1.0', 'UTF-8'); if ($dom->load($file) === FALSE) { echo "{$file} failed to load.\n"; } else { $xpath = new DOMXpath($dom); $xpath->registerNamespace("tei", "http://www.tei-c.org/ns/1.0"); $title = $xpath->query("descendant::tei:teiHeader/tei:fileDesc/tei:titleStmt/tei:title")->item(0)->nodeValue; $csv .= '"' . $filename . '","' . $title . '",'; $authors = $xpath->query("descendant::tei:teiHeader/tei:fileDesc/tei:titleStmt/tei:author"); foreach ($authors as $author) { $csv .= '"' . $author->nodeValue . '",'; } $csv .= "\n"; } } } } file_put_contents('metadata.csv', $csv);
/** * This function runs an xPath query on this authentication response. * * @param $query The query which should be run. * @param $node The node which this query is relative to. If this node is NULL (the default) * then the query will be relative to the root of the response. */ private function doXPathQuery($query, $node = NULL) { assert('is_string($query)'); assert('$this->dom instanceof DOMDocument'); if ($node === NULL) { $node = $this->dom->documentElement; } assert('$node instanceof DOMNode'); $xPath = new DOMXpath($this->dom); $xPath->registerNamespace('shibp', self::SHIB_PROTOCOL_NS); $xPath->registerNamespace('shib', self::SHIB_ASSERT_NS); return $xPath->query($query, $node); }
/** * This method will parse the DOM and pull out the attributes from the SAML * payload and put them into an array, then put the array into the session. * * @param string $text_response the SAML payload. * * @return bool true when successfull and false if no attributes a found */ private function _setSessionAttributes($text_response) { phpCAS::traceBegin(); $result = false; $attr_array = array(); // create new DOMDocument Object $dom = new DOMDocument(); // Fix possible whitspace problems $dom->preserveWhiteSpace = false; if ($dom->loadXML($text_response)) { $xPath = new DOMXpath($dom); $xPath->registerNamespace('samlp', 'urn:oasis:names:tc:SAML:1.0:protocol'); $xPath->registerNamespace('saml', 'urn:oasis:names:tc:SAML:1.0:assertion'); $nodelist = $xPath->query("//saml:Attribute"); if ($nodelist) { foreach ($nodelist as $node) { $xres = $xPath->query("saml:AttributeValue", $node); $name = $node->getAttribute("AttributeName"); $value_array = array(); foreach ($xres as $node2) { $value_array[] = $node2->nodeValue; } $attr_array[$name] = $value_array; } // UGent addition... foreach ($attr_array as $attr_key => $attr_value) { if (count($attr_value) > 1) { $this->_attributes[$attr_key] = $attr_value; phpCAS::trace("* " . $attr_key . "=" . $attr_value); } else { $this->_attributes[$attr_key] = $attr_value[0]; phpCAS::trace("* " . $attr_key . "=" . $attr_value[0]); } } $result = true; } else { phpCAS::trace("SAML Attributes are empty"); $result = false; } } phpCAS::traceEnd($result); return $result; }
/** * Converts a Zotero_Item object to a SimpleXMLElement Atom object * * Note: Increment Z_CONFIG::$CACHE_VERSION_ATOM_ENTRY when changing * the response. * * @param object $item Zotero_Item object * @param string $content * @return SimpleXMLElement Item data as SimpleXML element */ public static function convertItemToAtom(Zotero_Item $item, $queryParams, $permissions, $sharedData = null) { $t = microtime(true); // Uncached stuff or parts of the cache key $version = $item->version; $parent = $item->getSource(); $isRegularItem = !$parent && $item->isRegularItem(); $downloadDetails = $permissions->canAccess($item->libraryID, 'files') ? Zotero_Storage::getDownloadDetails($item) : false; if ($isRegularItem) { $numChildren = $permissions->canAccess($item->libraryID, 'notes') ? $item->numChildren() : $item->numAttachments(); } // <id> changes based on group visibility in v1 if ($queryParams['v'] < 2) { $id = Zotero_URI::getItemURI($item, false, true); } else { $id = Zotero_URI::getItemURI($item); } $libraryType = Zotero_Libraries::getType($item->libraryID); // Any query parameters that have an effect on the output // need to be added here $allowedParams = array('content', 'style', 'css', 'linkwrap'); $cachedParams = Z_Array::filterKeys($queryParams, $allowedParams); $cacheVersion = 2; $cacheKey = "atomEntry_" . $item->libraryID . "/" . $item->id . "_" . md5($version . json_encode($cachedParams) . ($downloadDetails ? 'hasFile' : '') . ($libraryType == 'group' ? 'id' . $id : '')) . "_" . $queryParams['v'] . "_" . $cacheVersion . (isset(Z_CONFIG::$CACHE_VERSION_ATOM_ENTRY) ? "_" . Z_CONFIG::$CACHE_VERSION_ATOM_ENTRY : "") . (in_array('bib', $queryParams['content']) && isset(Z_CONFIG::$CACHE_VERSION_BIB) ? "_" . Z_CONFIG::$CACHE_VERSION_BIB : ""); $xmlstr = Z_Core::$MC->get($cacheKey); if ($xmlstr) { try { // TEMP: Strip control characters $xmlstr = Zotero_Utilities::cleanString($xmlstr, true); $doc = new DOMDocument(); $doc->loadXML($xmlstr); $xpath = new DOMXpath($doc); $xpath->registerNamespace('atom', Zotero_Atom::$nsAtom); $xpath->registerNamespace('zapi', Zotero_Atom::$nsZoteroAPI); $xpath->registerNamespace('xhtml', Zotero_Atom::$nsXHTML); // Make sure numChildren reflects the current permissions if ($isRegularItem) { $xpath->query('/atom:entry/zapi:numChildren')->item(0)->nodeValue = $numChildren; } // To prevent PHP from messing with namespace declarations, // we have to extract, remove, and then add back <content> // subelements. Otherwise the subelements become, say, // <default:span xmlns="http://www.w3.org/1999/xhtml"> instead // of just <span xmlns="http://www.w3.org/1999/xhtml">, and // xmlns:default="http://www.w3.org/1999/xhtml" gets added to // the parent <entry>. While you might reasonably think that // // echo $xml->saveXML(); // // and // // $xml = new SimpleXMLElement($xml->saveXML()); // echo $xml->saveXML(); // // would be identical, you would be wrong. $multiFormat = !!$xpath->query('/atom:entry/atom:content/zapi:subcontent')->length; $contentNodes = array(); if ($multiFormat) { $contentNodes = $xpath->query('/atom:entry/atom:content/zapi:subcontent'); } else { $contentNodes = $xpath->query('/atom:entry/atom:content'); } foreach ($contentNodes as $contentNode) { $contentParts = array(); while ($contentNode->hasChildNodes()) { $contentParts[] = $doc->saveXML($contentNode->firstChild); $contentNode->removeChild($contentNode->firstChild); } foreach ($contentParts as $part) { if (!trim($part)) { continue; } // Strip the namespace and add it back via SimpleXMLElement, // which keeps it from being changed later if (preg_match('%^<[^>]+xmlns="http://www.w3.org/1999/xhtml"%', $part)) { $part = preg_replace('%^(<[^>]+)xmlns="http://www.w3.org/1999/xhtml"%', '$1', $part); $html = new SimpleXMLElement($part); $html['xmlns'] = "http://www.w3.org/1999/xhtml"; $subNode = dom_import_simplexml($html); $importedNode = $doc->importNode($subNode, true); $contentNode->appendChild($importedNode); } else { if (preg_match('%^<[^>]+xmlns="http://zotero.org/ns/transfer"%', $part)) { $part = preg_replace('%^(<[^>]+)xmlns="http://zotero.org/ns/transfer"%', '$1', $part); $html = new SimpleXMLElement($part); $html['xmlns'] = "http://zotero.org/ns/transfer"; $subNode = dom_import_simplexml($html); $importedNode = $doc->importNode($subNode, true); $contentNode->appendChild($importedNode); } else { $docFrag = $doc->createDocumentFragment(); $docFrag->appendXML($part); $contentNode->appendChild($docFrag); } } } } $xml = simplexml_import_dom($doc); StatsD::timing("api.items.itemToAtom.cached", (microtime(true) - $t) * 1000); StatsD::increment("memcached.items.itemToAtom.hit"); // Skip the cache every 10 times for now, to ensure cache sanity if (Z_Core::probability(10)) { $xmlstr = $xml->saveXML(); } else { return $xml; } } catch (Exception $e) { error_log($xmlstr); error_log("WARNING: " . $e); } } $content = $queryParams['content']; $contentIsHTML = sizeOf($content) == 1 && $content[0] == 'html'; $contentParamString = urlencode(implode(',', $content)); $style = $queryParams['style']; $entry = '<?xml version="1.0" encoding="UTF-8"?>' . '<entry xmlns="' . Zotero_Atom::$nsAtom . '" xmlns:zapi="' . Zotero_Atom::$nsZoteroAPI . '"/>'; $xml = new SimpleXMLElement($entry); $title = $item->getDisplayTitle(true); $title = $title ? $title : '[Untitled]'; $xml->title = $title; $author = $xml->addChild('author'); $createdByUserID = null; $lastModifiedByUserID = null; switch (Zotero_Libraries::getType($item->libraryID)) { case 'group': $createdByUserID = $item->createdByUserID; // Used for zapi:lastModifiedByUser below $lastModifiedByUserID = $item->lastModifiedByUserID; break; } if ($createdByUserID) { $author->name = Zotero_Users::getUsername($createdByUserID); $author->uri = Zotero_URI::getUserURI($createdByUserID); } else { $author->name = Zotero_Libraries::getName($item->libraryID); $author->uri = Zotero_URI::getLibraryURI($item->libraryID); } $xml->id = $id; $xml->published = Zotero_Date::sqlToISO8601($item->dateAdded); $xml->updated = Zotero_Date::sqlToISO8601($item->dateModified); $link = $xml->addChild("link"); $link['rel'] = "self"; $link['type'] = "application/atom+xml"; $href = Zotero_API::getItemURI($item); if (!$contentIsHTML) { $href .= "?content={$contentParamString}"; } $link['href'] = $href; if ($parent) { // TODO: handle group items? $parentItem = Zotero_Items::get($item->libraryID, $parent); $link = $xml->addChild("link"); $link['rel'] = "up"; $link['type'] = "application/atom+xml"; $href = Zotero_API::getItemURI($parentItem); if (!$contentIsHTML) { $href .= "?content={$contentParamString}"; } $link['href'] = $href; } $link = $xml->addChild('link'); $link['rel'] = 'alternate'; $link['type'] = 'text/html'; $link['href'] = Zotero_URI::getItemURI($item, true); // If appropriate permissions and the file is stored in ZFS, get file request link if ($downloadDetails) { $details = $downloadDetails; $link = $xml->addChild('link'); $link['rel'] = 'enclosure'; $type = $item->attachmentMIMEType; if ($type) { $link['type'] = $type; } $link['href'] = $details['url']; if (!empty($details['filename'])) { $link['title'] = $details['filename']; } if (isset($details['size'])) { $link['length'] = $details['size']; } } $xml->addChild('zapi:key', $item->key, Zotero_Atom::$nsZoteroAPI); $xml->addChild('zapi:version', $item->version, Zotero_Atom::$nsZoteroAPI); if ($lastModifiedByUserID) { $xml->addChild('zapi:lastModifiedByUser', Zotero_Users::getUsername($lastModifiedByUserID), Zotero_Atom::$nsZoteroAPI); } $xml->addChild('zapi:itemType', Zotero_ItemTypes::getName($item->itemTypeID), Zotero_Atom::$nsZoteroAPI); if ($isRegularItem) { $val = $item->creatorSummary; if ($val !== '') { $xml->addChild('zapi:creatorSummary', htmlspecialchars($val), Zotero_Atom::$nsZoteroAPI); } $val = $item->getField('date', true, true, true); if ($val !== '') { if ($queryParams['v'] < 3) { $val = substr($val, 0, 4); if ($val !== '0000') { $xml->addChild('zapi:year', $val, Zotero_Atom::$nsZoteroAPI); } } else { $sqlDate = Zotero_Date::multipartToSQL($val); if (substr($sqlDate, 0, 4) !== '0000') { $xml->addChild('zapi:parsedDate', Zotero_Date::sqlToISO8601($sqlDate), Zotero_Atom::$nsZoteroAPI); } } } $xml->addChild('zapi:numChildren', $numChildren, Zotero_Atom::$nsZoteroAPI); } if ($queryParams['v'] < 3) { $xml->addChild('zapi:numTags', $item->numTags(), Zotero_Atom::$nsZoteroAPI); } $xml->content = ''; // // DOM XML from here on out // $contentNode = dom_import_simplexml($xml->content); $domDoc = $contentNode->ownerDocument; $multiFormat = sizeOf($content) > 1; // Create a root XML document for multi-format responses if ($multiFormat) { $contentNode->setAttribute('type', 'application/xml'); /*$multicontent = $domDoc->createElementNS( Zotero_Atom::$nsZoteroAPI, 'multicontent' ); $contentNode->appendChild($multicontent);*/ } foreach ($content as $type) { // Set the target to either the main <content> // or a <multicontent> <content> if (!$multiFormat) { $target = $contentNode; } else { $target = $domDoc->createElementNS(Zotero_Atom::$nsZoteroAPI, 'subcontent'); $contentNode->appendChild($target); } $target->setAttributeNS(Zotero_Atom::$nsZoteroAPI, "zapi:type", $type); if ($type == 'html') { if (!$multiFormat) { $target->setAttribute('type', 'xhtml'); } $div = $domDoc->createElementNS(Zotero_Atom::$nsXHTML, 'div'); $target->appendChild($div); $html = $item->toHTML(true); $subNode = dom_import_simplexml($html); $importedNode = $domDoc->importNode($subNode, true); $div->appendChild($importedNode); } else { if ($type == 'citation') { if (!$multiFormat) { $target->setAttribute('type', 'xhtml'); } if (isset($sharedData[$type][$item->libraryID . "/" . $item->key])) { $html = $sharedData[$type][$item->libraryID . "/" . $item->key]; } else { if ($sharedData !== null) { //error_log("Citation not found in sharedData -- retrieving individually"); } $html = Zotero_Cite::getCitationFromCiteServer($item, $queryParams); } $html = new SimpleXMLElement($html); $html['xmlns'] = Zotero_Atom::$nsXHTML; $subNode = dom_import_simplexml($html); $importedNode = $domDoc->importNode($subNode, true); $target->appendChild($importedNode); } else { if ($type == 'bib') { if (!$multiFormat) { $target->setAttribute('type', 'xhtml'); } if (isset($sharedData[$type][$item->libraryID . "/" . $item->key])) { $html = $sharedData[$type][$item->libraryID . "/" . $item->key]; } else { if ($sharedData !== null) { //error_log("Bibliography not found in sharedData -- retrieving individually"); } $html = Zotero_Cite::getBibliographyFromCitationServer(array($item), $queryParams); } $html = new SimpleXMLElement($html); $html['xmlns'] = Zotero_Atom::$nsXHTML; $subNode = dom_import_simplexml($html); $importedNode = $domDoc->importNode($subNode, true); $target->appendChild($importedNode); } else { if ($type == 'json') { if ($queryParams['v'] < 2) { $target->setAttributeNS(Zotero_Atom::$nsZoteroAPI, "zapi:etag", $item->etag); } $textNode = $domDoc->createTextNode($item->toJSON(false, $queryParams, true)); $target->appendChild($textNode); } else { if ($type == 'csljson') { $arr = $item->toCSLItem(); $json = Zotero_Utilities::formatJSON($arr); $textNode = $domDoc->createTextNode($json); $target->appendChild($textNode); } else { if (in_array($type, Zotero_Translate::$exportFormats)) { $export = Zotero_Translate::doExport(array($item), $type); $target->setAttribute('type', $export['mimeType']); // Insert XML into document if (preg_match('/\\+xml$/', $export['mimeType'])) { // Strip prolog $body = preg_replace('/^<\\?xml.+\\n/', "", $export['body']); $subNode = $domDoc->createDocumentFragment(); $subNode->appendXML($body); $target->appendChild($subNode); } else { $textNode = $domDoc->createTextNode($export['body']); $target->appendChild($textNode); } } } } } } } } // TEMP if ($xmlstr) { $uncached = $xml->saveXML(); if ($xmlstr != $uncached) { $uncached = str_replace('<zapi:year></zapi:year>', '<zapi:year/>', $uncached); $uncached = str_replace('<content zapi:type="none"></content>', '<content zapi:type="none"/>', $uncached); $uncached = str_replace('<zapi:subcontent zapi:type="coins" type="text/html"></zapi:subcontent>', '<zapi:subcontent zapi:type="coins" type="text/html"/>', $uncached); $uncached = str_replace('<title></title>', '<title/>', $uncached); $uncached = str_replace('<note></note>', '<note/>', $uncached); $uncached = str_replace('<path></path>', '<path/>', $uncached); $uncached = str_replace('<td></td>', '<td/>', $uncached); if ($xmlstr != $uncached) { error_log("Cached Atom item entry does not match"); error_log(" Cached: " . $xmlstr); error_log("Uncached: " . $uncached); Z_Core::$MC->set($cacheKey, $uncached, 3600); // 1 hour for now } } } else { $xmlstr = $xml->saveXML(); Z_Core::$MC->set($cacheKey, $xmlstr, 3600); // 1 hour for now StatsD::timing("api.items.itemToAtom.uncached", (microtime(true) - $t) * 1000); StatsD::increment("memcached.items.itemToAtom.miss"); } return $xml; }
public function executeRangeQuery(RangeQuery $query, $storageName, $key, \Closure $hydrateRow = null) { $headers = ['Content-Type' => 'application/atom+xml', 'x-ms-date' => $this->now(), 'Content-Length' => 0]; $filters = ["PartitionKey eq " . $this->quoteFilterValue($query->getPartitionKey())]; foreach ($query->getConditions() as $condition) { if (!in_array($condition[0], ['eq', 'neq', 'le', 'lt', 'ge', 'gt'])) { throw new \InvalidArgumentException("Windows Azure Table only supports eq, neq, le, lt, ge, gt as conditions."); } $filters[] = $key[1] . " " . $condition[0] . " " . $this->quoteFilterValue($condition[1]); } // TODO: This sucks $tableName = $storageName; $url = $this->baseUrl . '/' . $tableName . '()?$filter=' . rawurlencode(implode(' ', $filters)); if ($query->getLimit()) { $url .= '&$top=' . $query->getLimit(); } $response = $this->request('GET', $url, '', $headers); if ($response->getStatusCode() >= 400) { $this->convertResponseToException($response); } $dom = new \DomDocument('1.0', 'UTF-8'); $dom->loadXML($response->getBody()); $xpath = new \DOMXpath($dom); $xpath->registerNamespace('d', 'http://schemas.microsoft.com/ado/2007/08/dataservices'); $xpath->registerNamespace('m', 'http://schemas.microsoft.com/ado/2007/08/dataservices/metadata'); $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom"); $entries = $xpath->evaluate('/atom:feed/atom:entry'); $results = []; foreach ($entries as $entry) { $data = $this->createRow($key, $xpath, $entry); $results[] = $hydrateRow ? $hydrateRow($data) : $data; } return $results; }
throw new Exception('Missing wctx parameter'); } } catch (Exception $exception) { throw new SimpleSAML_Error_Error('ACSPARAMS', $exception); } try { $wa = $_POST['wa']; $wresult = $_POST['wresult']; $wctx = $_POST['wctx']; /* Load and parse the XML. */ $dom = new DOMDocument(); /* Accommodate for MS-ADFS escaped quotes */ $wresult = str_replace('\\"', '"', $wresult); $dom->loadXML(str_replace("\r", "", $wresult)); $xpath = new DOMXpath($dom); $xpath->registerNamespace('wst', 'http://schemas.xmlsoap.org/ws/2005/02/trust'); $xpath->registerNamespace('saml', 'urn:oasis:names:tc:SAML:1.0:assertion'); /* Find the saml:Assertion element in the response. */ $assertions = $xpath->query('/wst:RequestSecurityTokenResponse/wst:RequestedSecurityToken/saml:Assertion'); if ($assertions->length === 0) { throw new Exception('Received a response without an assertion on the WS-Fed PRP handler.'); } if ($assertions->length > 1) { throw new Exception('The WS-Fed PRP handler currently only supports a single assertion in a response.'); } $assertion = $assertions->item(0); /* Find the entity id of the issuer. */ $idpEntityId = $assertion->getAttribute('Issuer'); /* Load the IdP metadata. */ $idpMetadata = $metadata->getMetaData($idpEntityId, 'wsfed-idp-remote'); /* Find the certificate used by the IdP. */
public function loadXML($xml, $ignoreErrors = false) { $document = $this->document; $ignoreErrors ? @$document->loadXML($xml) : $document->loadXML($xml); $xpath = new DOMXpath($document); preg_match_all('/xmlns=(".+"|\'.+\')/U', $xml, $matches); if (isset($matches[1])) { $matches[1] = array_values(array_unique($matches[1])); foreach ($matches[1] as $i => $namespace) { $_ns = substr($namespace, 1, -1); $_pf = "dns" . $i; $document->defaultNamespaces[$_ns] = $_pf; $xpath->registerNamespace($_pf, $_ns); } } $document->xpath = $xpath; return $this->getDocumentElement(); }