/** * Creates the parser * * @param DOMDocument $dom */ public function __construct(DOMDocument $dom) { $this->dom = $dom; $this->xpath = new DOMXPath($dom); $this->xpath->registerNameSpace('cal', Sabre_CalDAV_Plugin::NS_CALDAV); $this->xpath->registerNameSpace('dav', 'DAV:'); }
/** * Creates the parser * * @param \DOMDocument $dom */ public function __construct(\DOMDocument $dom) { $this->dom = $dom; $this->xpath = new \DOMXPath($dom); $this->xpath->registerNameSpace('cal', Plugin::NS_CALDAV); $this->xpath->registerNameSpace('dav', 'urn:DAV'); }
/** * Tries to get the DOM for the file * @param string $form * @return DOMDocument */ protected function getDOMData($form) { if (array_key_exists($form, $this->dom_data) && is_array($this->dom_data[$form])) { return $this->dom_data[$form]; } $file_loc = $this->getFile($form); if (($file_data = $this->getFileData($form)) === false) { return false; } $doc = new DOMDocument(); if (!$doc->loadXML($file_data)) { I2CE::raiseError("Could not open {$file_loc} for reading."); return false; } $xpath = new DOMXPath($doc); foreach ($this->getNamespaces($form) as $ns => $uri) { $xpath->registerNameSpace($ns, $uri); } $entries = $xpath->query($this->getBaseQuery($form)); if ($entries->length != 1) { I2CE::raiseError("Could not find " . $this->getBaseQuery($form) . " in {$file_loc} -- " . $entries->length); return false; } $this->dom_data[$form] = array('doc' => $doc, 'xpath' => $xpath, 'dataset' => $entries->item(0)); return $this->dom_data[$form]; }
private function _flightType() { $xml = new DOMDocument(); $xml->loadXML($this->_response); $xpath = new DOMXPath($xml); $xpath->registerNameSpace('ns0', 'http://www.opentravel.org/OTA/2003/05'); $cities = array(); // XPath para ubicar solo la primera recomendacion, ya que con esta es suficiente para hacer las validaciones if (strpos($this->_response, 'OTA_AirLowFareSearch')) { $query = '/ns0:OTA_AirLowFareSearchRS'; $query .= '/ns0:PricedItineraries'; $query .= '/ns0:PricedItinerary[1]'; $query .= '/ns0:AirItinerary'; $query .= '/ns0:OriginDestinationOptions'; $query .= '/ns0:OriginDestinationOption'; } else { $query = '/ns0:OTA_AirBookRS'; $query .= '/ns0:AirReservation'; $query .= '/ns0:OriginDestinationOptions'; $query .= '/ns0:OriginDestinationOption'; } // Se obtiene los codigos IATA de origen y llegada de la disponbilidad, para saber si es nacional o internacional $results = $xpath->query($query . '/ns0:FlightSegment[1]/ns0:DepartureAirport/@LocationCode'); foreach ($results as $code) { $cities[$code->value] = true; } $results = $xpath->query($query . '/ns0:FlightSegment[position() = last()]/ns0:ArrivalAirport/@LocationCode'); foreach ($results as $code) { $cities[$code->value] = true; } $db = JFactory::getDBO(); $stmt = $db->getQuery(true); $lang = JFactory::getLanguage(); $lang = substr($lang->getTag(), 3); // Select que me indica si hay ciudades fuera del pais nacional $stmt->select('COUNT(1)'); $stmt->from('#__qs_cities AS qc'); $stmt->join('inner', '#__qs_countries AS qp ON qc.country = qp.id'); $stmt->where('qc.iata IN (\'' . join('\', \'', array_keys($cities)) . '\')'); // TODO mams827 // Es necesario dejar configurable el pais, debe validarse en donde debe quedar centralizada dicha informacion $stmt->where('qp.codigo <> ' . $db->Quote('VE')); $stmt->where('qc.lenguaje = ' . $db->Quote($lang)); $stmt->where('qp.lenguaje = ' . $db->Quote($lang)); $db->setQuery($stmt); $national = !$db->loadResult() ? 1 : 3; // Se valida cuantos segementos tiene la disponibilidad, para saber si es OW o RT $segments = 0; if (strpos($this->_response, 'OTA_AirLowFareSearch')) { $results = $xpath->query($query . '[@RefNumber=1]'); } else { $results = $xpath->query($query . '[@RefNumber=2]'); } if ($results->length) { $segments = 1; } return $national + $segments; }
protected function process_response($curl_out) { $doc = new DOMDocument(); if (!@$doc->loadXML($curl_out) || !($xpath = new DOMXPath($doc)) || !$xpath->registerNameSpace('dxf', 'http://dhis2.org/schema/dxf/2.0') || !($descNodes = $xpath->query("//dxf:description[1]")) instanceof DOMNodeList || !$descNodes->length == 1 || !($dvNodes = $xpath->query("//dxf:dataValueCount[1]/@*")) instanceof DOMNodeList) { return false; } $resp = array(); foreach ($dvNodes as $attrNode) { $resp[] = $attrNode->name . " = " . $attrNode->value; } $this->show_status("Response: " . $descNodes->item(0)->textContent . "\n\t" . implode("\n\t", $resp) . "\n"); return true; }
/** * Creates the parser * * @param \DOMDocument $dom */ function __construct(\DOMDocument $dom) { $this->dom = $dom; $this->xpath = new \DOMXPath($dom); $this->xpath->registerNameSpace('card', Plugin::NS_CARDDAV); }
function Script($n) { if ($n->hasChildNodes()) { $i = 0; while ($i < $n->childNodes->length) { $cur = $n->childNodes->item($i); if ($cur->nodeType == XML_DOCUMENT_NODE || $cur->nodeType == XML_ELEMENT_NODE) { $curname = $cur->nodeName; if (substr($curname, 0, 4) == "txs:") { $xpath = new DOMXPath($n->ownerDocument); $xpath->registerNameSpace("txs", "http://www.agencexml.com/txs"); $xpath->registerNameSpace("xsl", "http://www.w3.org/1999/XSL/Transform"); if ($cur->getAttribute("node") != '') { if ($xpath->query($cur->getAttribute("node"), $cur)->length == 0) { $curname = "dummy"; } } else { if ($xpath->query("ancestor::xsl:stylesheet", $cur)->length != 0 || $xpath->query("ancestor::txs:model", $cur)->length != 0) { $curname = "dummy"; } } } switch ($curname) { case "txs:load": Load($cur); break; case "txs:save": Script($cur); Save($cur); break; case "txs:transform": Script($cur); Transform($cur); continue 2; case "txs:httprequest": Httprequest($cur); break; case "txs:call": Call($cur); continue 2; case "txs:fileexists": FileExists($cur); break; case "txs:folderexists": FolderExists($cur); break; case "txs:from-model": Script($cur); FromModel($cur, $cur); break; case "txs:process": Process($cur); break; default: Script($cur); } } $i++; } } }
} catch (Exception $e) { drush_print("\n\n**********####### ERROR #######*********"); drush_print("***Could not get object {$objectPID} from repo***\n\n"); $skippedObjects[] = $objectPID; continue; } # grab the MODS data stream $modsDS = $object['MODS']; /****************MODS RECORD**********************/ // drush_print("Editing MODS record"); $modsDOMDoc = new DOMDocument(); $modsDOMDoc->preserveWhiteSpace = false; $modsDOMDoc->formatOutput = true; $modsDOMDoc->loadXML($modsDS->content); $modsXPath = new DOMXPath($modsDOMDoc); $modsXPath->registerNameSpace('mods', 'http://www.loc.gov/mods/v3'); // flag to indicate if datastream reingest and DC regen is needed $updateThisRecord = FALSE; $domElemsToRemove = array(); // loop through all <subject> nodes foreach ($modsXPath->query('//mods:subject') as $node) { // loop through all the <topic> nodes that are children of <subject> nodes // everytime we find a topic node, we create a new <subject><topic/></subject> // trio and insert it in the DOM before the original <subject> node foreach ($modsXPath->query('mods:topic', $node) as $topicNode) { $newSubjectNode = $modsDOMDoc->createElement('subject'); $newTopicNode = $modsDOMDoc->createElement('topic', htmlspecialchars($topicNode->nodeValue)); $newNode = $node->parentNode->insertBefore($newSubjectNode, $node); $newNode->appendChild($newTopicNode); $updateThisRecord = TRUE; // add this subject node to a list to be removed as it contains multiple topics
/** * Parses an XML file for known IMSCC content that makes sense for import. */ function processXML($path) { $xml = new \DOMDocument('1.0', 'utf-8'); $xml->load($path); $info = array(); $xpath = new \DOMXPath($xml); $xpath->registerNameSpace('fake', 'http://www.imsglobal.org/xsd/imsccv1p1/imscp_v1p1'); $elements = $xpath->query("//*"); foreach ($elements as $element) { $tag = $this->getTagName($element); switch ($tag) { case 'title': $info['title'] = $element->nodeValue; break; case 'url': $info['href'] = $element->getAttribute('href'); break; case '#text': case 'text': $text = $element->nodeValue; if (trim($text)) { $info['text'] = $text; } break; default: if (empty($info['type'])) { $info['type'] = $tag; } } } return $info; }
/** * Creates the parser * * @param DOMDocument $dom */ public function __construct(DOMDocument $dom) { $this->dom = $dom; $this->xpath = new DOMXPath($dom); $this->xpath->registerNameSpace('card', Sabre_CardDAV_Plugin::NS_CARDDAV); }
/** * This function handles the calendar-query REPORT * * This report is used by clients to request calendar objects based on * complex conditions. * * @param \DOMNode $dom * @return void */ function calendarQueryReport($dom) { $parser = new CalendarQueryParser($dom); $parser->parse(); $path = $this->server->getRequestUri(); // TODO: move this into CalendarQueryParser $xpath = new \DOMXPath($dom); $xpath->registerNameSpace('cal', Plugin::NS_CALDAV); $xpath->registerNameSpace('dav', 'urn:DAV'); $needsJson = $xpath->evaluate("boolean(/cal:calendar-query/dav:prop/cal:calendar-data[@content-type='application/calendar+json'])"); $node = $this->server->tree->getNodeForPath($this->server->getRequestUri()); $depth = $this->server->getHTTPDepth(0); // The default result is an empty array $result = []; $calendarTimeZone = null; if ($parser->expand) { // We're expanding, and for that we need to figure out the // calendar's timezone. $tzProp = '{' . self::NS_CALDAV . '}calendar-timezone'; $tzResult = $this->server->getProperties($path, [$tzProp]); if (isset($tzResult[$tzProp])) { // This property contains a VCALENDAR with a single // VTIMEZONE. $vtimezoneObj = VObject\Reader::read($tzResult[$tzProp]); $calendarTimeZone = $vtimezoneObj->VTIMEZONE->getTimeZone(); unset($vtimezoneObj); } else { // Defaulting to UTC. $calendarTimeZone = new DateTimeZone('UTC'); } } // The calendarobject was requested directly. In this case we handle // this locally. if ($depth == 0 && $node instanceof ICalendarObject) { $requestedCalendarData = true; $requestedProperties = $parser->requestedProperties; if (!in_array('{urn:ietf:params:xml:ns:caldav}calendar-data', $requestedProperties)) { // We always retrieve calendar-data, as we need it for filtering. $requestedProperties[] = '{urn:ietf:params:xml:ns:caldav}calendar-data'; // If calendar-data wasn't explicitly requested, we need to remove // it after processing. $requestedCalendarData = false; } $properties = $this->server->getPropertiesForPath($path, $requestedProperties, 0); // This array should have only 1 element, the first calendar // object. $properties = current($properties); // If there wasn't any calendar-data returned somehow, we ignore // this. if (isset($properties[200]['{urn:ietf:params:xml:ns:caldav}calendar-data'])) { $validator = new CalendarQueryValidator(); $vObject = VObject\Reader::read($properties[200]['{urn:ietf:params:xml:ns:caldav}calendar-data']); if ($validator->validate($vObject, $parser->filters)) { // If the client didn't require the calendar-data property, // we won't give it back. if (!$requestedCalendarData) { unset($properties[200]['{urn:ietf:params:xml:ns:caldav}calendar-data']); } else { if ($parser->expand) { $vObject->expand($parser->expand['start'], $parser->expand['end'], $calendarTimeZone); } if ($needsJson) { $properties[200]['{' . self::NS_CALDAV . '}calendar-data'] = json_encode($vObject->jsonSerialize()); } elseif ($parser->expand) { $properties[200]['{' . self::NS_CALDAV . '}calendar-data'] = $vObject->serialize(); } } $result = [$properties]; } } } // If we're dealing with a calendar, the calendar itself is responsible // for the calendar-query. if ($node instanceof ICalendarObjectContainer && $depth == 1) { $nodePaths = $node->calendarQuery($parser->filters); $timeZones = []; foreach ($nodePaths as $path) { list($properties) = $this->server->getPropertiesForPath($this->server->getRequestUri() . '/' . $path, $parser->requestedProperties); if ($needsJson || $parser->expand) { $vObject = VObject\Reader::read($properties[200]['{' . self::NS_CALDAV . '}calendar-data']); if ($parser->expand) { $vObject->expand($parser->expand['start'], $parser->expand['end'], $calendarTimeZone); } if ($needsJson) { $properties[200]['{' . self::NS_CALDAV . '}calendar-data'] = json_encode($vObject->jsonSerialize()); } else { $properties[200]['{' . self::NS_CALDAV . '}calendar-data'] = $vObject->serialize(); } } $result[] = $properties; } } $prefer = $this->server->getHTTPPRefer(); $this->server->httpResponse->setStatus(207); $this->server->httpResponse->setHeader('Content-Type', 'application/xml; charset=utf-8'); $this->server->httpResponse->setHeader('Vary', 'Brief,Prefer'); $this->server->httpResponse->setBody($this->server->generateMultiStatus($result, $prefer['return-minimal'])); }
public function getOrder() { // Objeto que va a almacenar la informacion de la orden $order = new stdClass(); // Inicializando el XML, para poder usar XPath $xml = new DOMDocument(); $xml->loadXML($this->_raw); $xpath = new DOMXPath($xml); $xpath->registerNameSpace('ns0', 'http://www.opentravel.org/OTA/2003/05'); // obteniendo el usuario $order->user_id = $this->_user->id; // Obteniendo el record $results = $xpath->query('/ns0:OTA_AirBookRS/ns0:AirReservation/ns0:BookingReferenceID/@ID'); foreach ($results as $result) { $order->recloc = $result->nodeValue; } $query = '/ns0:OTA_AirBookRS/ns0:AirReservation/ns0:TravelerInfo/ns0:AirTraveler'; // Obteniendo el nombre $order->firstname = $_POST['wsform']['contactname']; /* // Obteniendo el apellido $results = $xpath->query($query.'/ns0:PersonName/ns0:Surname'); foreach($results as $result) { $order->lastname = $result->nodeValue; break; } */ // Obteniendo el correo $results = $xpath->query($query . '/ns0:Email'); foreach ($results as $result) { $order->email = $result->nodeValue; } // Obteniendo el telefono $results = $xpath->query($query . '/ns0:Telephone/@PhoneNumber'); foreach ($results as $result) { $order->phone = $result->nodeValue; } // Obteniendo el total de la reserva $results = $xpath->query('/ns0:OTA_AirBookRS/ns0:AirReservation/ns0:PriceInfo/ns0:ItinTotalFare/ns0:TotalFare/@Amount'); foreach ($results as $result) { $order->total = $result->nodeValue; } // Obteniendo el total de la tarifa $results = $xpath->query('/ns0:OTA_AirBookRS/ns0:AirReservation/ns0:PriceInfo/ns0:ItinTotalFare/ns0:BaseFare/@Amount'); foreach ($results as $result) { $order->fare = $result->nodeValue; } // Obteniendo el total de los impuestos $results = $xpath->query('/ns0:OTA_AirBookRS/ns0:AirReservation/ns0:PriceInfo/ns0:ItinTotalFare/ns0:Taxes/@Amount'); foreach ($results as $result) { $order->taxes = $result->nodeValue; } //Tipo de Producto $order->product_type = $_POST['wsform']['product_type']; if ($_POST['wsform']['paymentmethod'] == 0) { $order->status = 2; } else { if ($_POST['wsform']['paymentmethod'] == 1) { $order->status = 1; } } //Verifica si el vuelo es nacional o Internacional $cities = array(); // XPath para ubicar solo la primera recomendacion, ya que con esta es suficiente para hacer las validaciones if (strpos($this->_response, 'OTA_AirLowFareSearch')) { $query = '/ns0:OTA_AirLowFareSearchRS'; $query .= '/ns0:PricedItineraries'; $query .= '/ns0:PricedItinerary[1]'; $query .= '/ns0:AirItinerary'; $query .= '/ns0:OriginDestinationOptions'; $query .= '/ns0:OriginDestinationOption'; } else { $query = '/ns0:OTA_AirBookRS'; $query .= '/ns0:AirReservation'; $query .= '/ns0:OriginDestinationOptions'; $query .= '/ns0:OriginDestinationOption'; } // Se obtiene los codigos IATA de origen y llegada de la disponbilidad, para saber si es nacional o internacional $results = $xpath->query($query . '/ns0:FlightSegment[1]/ns0:DepartureAirport/@LocationCode'); foreach ($results as $code) { $cities[$code->value] = true; } $results = $xpath->query($query . '/ns0:FlightSegment[position() = last()]/ns0:ArrivalAirport/@LocationCode'); foreach ($results as $code) { $cities[$code->value] = true; } $db = JFactory::getDBO(); $stmt = $db->getQuery(true); $lang = JFactory::getLanguage(); $lang = substr($lang->getTag(), 3); // Select que me indica si hay ciudades fuera del pais nacional $stmt->select('COUNT(1)'); $stmt->from('#__qs_cities AS qc'); $stmt->join('inner', '#__qs_countries AS qp ON qc.country = qp.id'); $stmt->where('qc.iata IN (\'' . join('\', \'', array_keys($cities)) . '\')'); // TODO mams827 // Es necesario dejar configurable el pais, debe validarse en donde debe quedar centralizada dicha informacion $stmt->where('qp.codigo <> ' . $db->Quote('VE')); $stmt->where('qc.lenguaje = ' . $db->Quote($lang)); $stmt->where('qp.lenguaje = ' . $db->Quote($lang)); $db->setQuery($stmt); //Guarda el nombre del producto $order->product_name = !$db->loadResult() ? 'Vuelo Nacional' : 'Vuelo Internacional'; // Parametro de configuracion del componente de tarifa administrativa //$params = JComponentHelper::getParams('com_adminfee'); $params = JComponentHelper::getParams('com_fees'); $IvaTA = $params->get('valIvaTaPortal', 16); // Obteniendo el total de la tarifa administrativa $ta = 0; $results = $xpath->query('/ns0:OTA_AirBookRS/ns0:AirReservation/ns0:PriceInfo/ns0:ItinTotalFare/ns0:Fees/@Amount'); foreach ($results as $result) { $ta = (double) $result->nodeValue; } $order->taxes_ta = round($ta / (1 + $IvaTA / 100) * ($IvaTA / 100), 2); $order->fare_ta = $ta - $order->taxes_ta; // Obteniendo la aerolinea validadora $results = $xpath->query('/ns0:OTA_AirBookRS/ns0:AirReservation/ns0:Ticketing/ns0:TicketingVendor/@Code'); foreach ($results as $result) { $order->provider = $result->nodeValue; } return $order; }
/** * Search and retieve records * * @throws Exception for diagnostic errors * * @param mixed $query the query in CQL format * @param int $iStartRecord [optional] start record to begin with, default 1 * @param int $iMaxiumumRecords [optional] maximum records to return, default 10 * @param string $strSort [optional] index to sort records on * * @return DOMDocument SRU results response */ public function searchRetrieve($query, $iStartRecord = 1, $iMaxiumumRecords = 10, $strSort = null) { // append any limits set earlier $this->query = $query . " " . $this->limits; // construct the request to the server $this->url = $this->base . "?wskey=" . $this->key; $this->url .= "&version=1.1"; $this->url .= "&operation=searchRetrieve"; $this->url .= "&query=" . urlencode($this->query); $this->url .= "&startRecord=" . $iStartRecord; $this->url .= "&maximumRecords=" . $iMaxiumumRecords; $this->url .= "&recordSchema=marcxml"; $this->url .= "&servicelevel=" . $this->service; // workset grouping if ($this->frbr == false) { $this->url .= "&frbrGrouping=off"; } // sort order if ($strSort != "") { $this->url .= "&sortKeys=" . $strSort; } // get the response from the server $results = $this->fetchResults($this->url); $objXml = Parser::convertToDOMDocument($results); $objXPath = new \DOMXPath($objXml); $objXPath->registerNameSpace("zs", "http://www.loc.gov/zing/srw/"); // check for diagnostic errors $objDiagnostics = $objXPath->query("zs:diagnostics"); if ($objDiagnostics->length > 0) { $strError = ""; $diagnostics = simplexml_import_dom($objDiagnostics->item(0)); foreach ($diagnostics->diagnostic as $diagnostic) { $strError .= $diagnostic->message; if ((string) $diagnostic->details != "") { $strError .= ": " . $diagnostic->details; } } throw new \Exception($strError); } // extract total hits $objTotal = $objXPath->query("zs:numberOfRecords")->item(0); if ($objTotal != null) { $this->total = (int) $objTotal->nodeValue; } return $objXml; }
/** * Obtiene la informacion si los vuelos de la orden actual * son nacionales o internacionales (true, false) */ public function isNational() { // Inicializando el XML, para poder usar XPath $xml = new DOMDocument(); $xml->loadXML($this->_raw); $xpath = new DOMXPath($xml); $xpath->registerNameSpace('ns0', 'http://www.opentravel.org/OTA/2003/05'); $cities = array(); // XPath para ubicar solo la primera recomendacion, ya que con esta es suficiente para hacer las validaciones $query = '/ns0:OTA_AirBookRS'; $query .= '/ns0:AirReservation'; $query .= '/ns0:OriginDestinationOptions'; $query .= '/ns0:OriginDestinationOption'; // Se obtiene los codigos IATA de origen y llegada de la disponbilidad, para saber si es nacional o internacional $results = $xpath->query($query . '/ns0:FlightSegment[1]/ns0:DepartureAirport/@LocationCode'); foreach ($results as $code) { $cities[$code->value] = true; } $results = $xpath->query($query . '/ns0:FlightSegment[position() = last()]/ns0:ArrivalAirport/@LocationCode'); foreach ($results as $code) { $cities[$code->value] = true; } $db = JFactory::getDBO(); $stmt = $db->getQuery(true); $lang = JFactory::getLanguage(); $lang = substr($lang->getTag(), 3); // Select que me indica si hay ciudades fuera del pais nacional $stmt->select('COUNT(1)'); $stmt->from('#__qs_cities AS qc'); $stmt->join('inner', '#__qs_countries AS qp ON qc.country = qp.id'); $stmt->where('qc.iata IN (\'' . join('\', \'', array_keys($cities)) . '\')'); // TODO mams827 // Es necesario dejar configurable el pais, debe validarse en donde debe quedar centralizada dicha informacion $stmt->where('qp.codigo <> ' . $db->Quote('VE')); $stmt->where('qc.lenguaje = ' . $db->Quote($lang)); $stmt->where('qp.lenguaje = ' . $db->Quote($lang)); $db->setQuery($stmt); return !$db->loadResult() ? true : false; }
/** * searches the sitemap index for a entries with $sLocation and returns them as DOMNodeList or false if nothing found * * @param string $sLocation * @return DOMNodeList */ private function getDOMNodeListSitemapSearchByLocation($sLocation) { $oXPath = new DOMXPath($this->oDocument); // we need to register the namespace with a fakeprefix. without it, xpath wont work $oXPath->registerNameSpace('fakeprefix', $this->sXMLNamespace); // query the DOM Document for sitemap elements with childNode loc and text = $sLocation //$oNodelist = $oXPath->evaluate('//fakeprefix:sitemapindex/fakeprefix:sitemap[./fakeprefix:loc/text(), "'.$sLocation.'"]'); $oNodelist = $oXPath->evaluate('//fakeprefix:sitemapindex/fakeprefix:sitemap[contains(./fakeprefix:loc/text(), "' . $sLocation . '")]'); return $oNodelist; }
public function processItinerary($id) { if ($id == 0) { return array('type' => 'error', 'msg' => JText::_('COM_LOWFARES_ID_EMPTY')); } else { JLoader::register('AawsController', JPATH_ROOT . DS . 'components' . DS . 'com_aaws' . DS . 'controller.php'); JLoader::register('AawsControllerAir', JPATH_ROOT . DS . 'components' . DS . 'com_aaws' . DS . 'controllers' . DS . 'air.php'); JTable::addIncludePath(JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_lowfares' . DS . 'tables'); $table = JTable::getInstance('flights'); $table->load($id); $Air = new AawsControllerAir(); if ($table->get('offset', '') == '') { $date1 = $table->get('departure'); } else { $date1 = date('Y-m-d', strtotime('+' . $table->get('offset') . ' days')); } $parts = explode('-', $date1); $date2 = date('Y-m-d', strtotime('+' . $table->get('duration') . ' days', mktime(0, 0, 0, $parts[1], $parts[2], $parts[0]))); $data = array(); $data['TRIP_TYPE'] = 'R'; $data['B_LOCATION_1'] = $table->get('origin'); $data['E_LOCATION_1'] = $table->get('destiny'); $data['B_DATE_1'] = $date1; $data['B_DATE_2'] = $date2; $data['TRAVELLER_TYPE_ADT'] = '1'; $data['TRAVELLER_TYPE_CHD'] = '0'; $data['TRAVELLER_TYPE_INF'] = '0'; $data['CABIN'] = 'Economy'; $data['AIRLINE'] = ''; $data['MAX_CONNECTIONS'] = ''; try { $response = $Air->processData($data); /** * Procesando la respuesta */ $xml = new DOMDocument(); $xml->loadXML($response); $xpath = new DOMXPath($xml); $xpath->registerNameSpace('ns0', 'http://www.opentravel.org/OTA/2003/05'); $query = '/ns0:OTA_AirLowFareSearchRS'; $query .= '/ns0:PricedItineraries'; $query .= '/ns0:PricedItinerary[1]'; $query .= '/ns0:AirItineraryPricingInfo'; $query .= '/ns0:ItinTotalFare'; $query .= '/ns0:TotalFare'; $query .= '/@Amount'; $value = 0; $results = $xpath->query($query); foreach ($results as $val) { $value = $val->value; } $table->value = $value; $table->store(); return array('type' => 'success', 'msg' => number_format($value, 2, ',', '.')); } catch (Exception $e) { $table->value = 0; $table->published = 0; $table->store(); return array('type' => 'error', 'msg' => $e->getMessage()); } } }
public function booking() { //================================================================================ $session =& JFactory::getSession(); $respuesta = $session->get('RespuestaInfo'); $objeto = simplexml_load_string($respuesta); $i = 0; foreach ($objeto->PricedItineraries->PricedItinerary->AirItinerary->OriginDestinationOptions->OriginDestinationOption as $destinos) { $arrayPas['NumVuelo'][$i] = (int) $destinos->FlightSegment['FlightNumber']; $arrayPas['AirVuelo'][$i] = (string) $destinos->FlightSegment->OperatingAirline['Code']; $arrayPas['FechaVuelo'][$i] = (string) substr($destinos->FlightSegment['DepartureDateTime'], 0, 10); $i++; } //================================================================================ try { // Se valida si el usuario esta registrado, para colocar ese correo de contacto $user = JFactory::getUser(); if ($user->get('id', 0) != 0) { $_POST['wsform']['contactemail'] = $user->get('email', ''); $_POST['wsform']['contactname'] = $user->get('name', ''); $_POST['wsform']['contactdocumenttype'] = $user->get('profile.documenttype', ''); $_POST['wsform']['contactdocumentid'] = $user->get('profile.documentnumber', ''); } $info = array(); $data = JRequest::getVar('wsform', array(), 'post'); if (!isset($data['tcorrelation']) || $data['tcorrelation'] == '' || !isset($data['tsequence']) || $data['tsequence'] == '' || !preg_match('/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}$/', $data['lastday'])) { throw new Exception(JText::_('COM_AAWS_DATA_ERROR'), 0); } if (!isset($data['paxtype']) || !is_array($data['paxtype']) || !count($data['paxtype']) || !isset($data['paxlastname']) || !is_array($data['paxlastname']) || !count($data['paxlastname']) || !isset($data['paymentmethod']) || $data['paymentmethod'] == '') { throw new Exception(JText::_('COM_AAWS_PAX_DATA_ERROR') . '{#}', 1); } //Validacion fecha tarjeta de credito if ($data['carddate-month'][0] != '') { if ($data['carddate-month'][0] <= date('m') && $data['carddate-year'][0] <= date('Y')) { throw new Exception(JText::_('COM_AAWS_CONTACT_MONTH_ERROR') . '{#carddate-month}', 1); } } if (preg_match('/[°|!"#$%&\\/()=+*~[\\]{}^`;,:.]/', $data['contactname'])) { throw new Exception(JText::_('COM_AAWS_CONTACT_NAME_ERROR') . '{#contactname}', 1); } // Se valida que el correo sea valido if (!JMailHelper::isEmailAddress($data['contactemail'])) { throw new Exception(JText::_('COM_AAWS_CONTACT_EMAIL_ERROR') . '{#contactemail}', 1); } /*$phone = '+ ('.trim($data['contactphonecountry']).') '; $phone .= trim($data['contactphonecode']).' '; $phone .= trim($data['contactphonenumber']);*/ $phone = trim($data['contactphonenumber']); $types = array_count_values($data['paxtype']); if (isset($types['INF'])) { if ($types['INF'] > $types['ADT']) { throw new Exception(JText::_('COM_AAWS_PAX_INFANT_ERROR') . '{#}', 1); } else { $infants = $types['INF']; } } else { $infants = 0; } $info['SequenceNmbr'] = $data['tsequence']; $info['CorrelationID'] = $data['tcorrelation']; $info['ContactPhone'] = $phone; $info['ContactMail'] = $data['contactemail']; // Fecha del ultimo vuelo, para validar las edades de los pasajeros $endDate = explode('T', $data['lastday']); $endDate = $endDate[0]; $passengers = array(); $i = 0; foreach ($data['paxtype'] as $key => $value) { if ($data['paxemail'] != '' && $data['paxemailconf'] != '') { if ($data['paxemail'] != $data['paxemailconf']) { throw new Exception(JText::_('COM_AAWS_EMAIL_DATA_ERROR') . '{#paxemailconf_' . ($key + 1) . '}', 1); } } if (!in_array($value, array('ADT', 'CHD', 'INF', 'YCD'))) { throw new Exception(JText::_('COM_AAWS_PAX_TYPE_ERROR') . '{#_' . ($key + 1) . '}', 1); } if (preg_match('/[0-9°|!"#$%&\\/()=+*~[\\]{}^`;,:.]/', $data['paxfirstname'][$key])) { throw new Exception(JText::_('COM_AAWS_PAX_FIRSTNAME_ERROR') . '{#paxfirstname_' . ($key + 1) . '}', 1); } if (preg_match('/[0-9°|!"#$%&\\/()=+*~[\\]{}^`;,:.]/', $data['paxlastname'][$key])) { throw new Exception(JText::_('COM_AAWS_PAX_LASTNAME_ERROR') . '{#paxlastname_' . ($key + 1) . '}', 1); } /* if(!preg_match('/^[A_Za-z0-9]+$/', $data['paxdocumentnumber'][$key])) { throw new Exception(JText::_('COM_AAWS_PAX_DOCUMENTNUMBER_ERROR').'{#paxdocumentnumber_'.($key + 1).'}', 1); } */ $day = (int) $data['paxborndate-day'][$key]; $month = (int) $data['paxborndate-month'][$key]; $year = (int) $data['paxborndate-year'][$key]; $date1 = sprintf('%04d', $year) . '-' . sprintf('%02d', $month) . '-' . sprintf('%02d', $day); $date2 = date('Y-m-d', mktime(0, 0, 0, $month, $day, $year)); if ($date1 != $date2) { throw new Exception(JText::_('COM_AAWS_DATE_FORMAT_ERROR') . '{#paxborndate-day_' . ($key + 1) . '}', 1); } $diff = strtotime($endDate) - strtotime($date1); /** * La información de la edad se valida de acuerdo a un año estandar, por consiguiente * al no tomar años bisiestos, el desface de la edad se puede presentar en 2 o 3 dias; * es decir es probable que la persona ya halla cmumplido la edad, pero 2 o 3 dias antes */ switch ($value) { case 'YCD': if ($diff / 31536000 <= 60) { throw new Exception(JText::_('COM_AAWS_YCD_BIRTHDATE') . '{#paxborndate-year_' . ($key + 1) . '}', 1); } break; case 'ADT': if ($diff / 31536000 <= 12 || $diff / 31536000 > 60) { throw new Exception(JText::_('COM_AAWS_ADT_BIRTHDATE') . '{#paxborndate-year_' . ($key + 1) . '}', 1); } break; case 'CHD': if ($diff / 31536000 <= 2 || $diff / 31536000 > 12) { throw new Exception(JText::_('COM_AAWS_CHD_BIRTHDATE') . '{#paxborndate-year_' . ($key + 1) . '}', 1); } break; case 'INF': if ($diff / 31536000 > 2) { throw new Exception(JText::_('COM_AAWS_INF_BIRTHDATE') . '{#paxborndate-year_' . ($key + 1) . '}', 1); } break; } $nationality = $data['paxnationality'][$key]; $lang = JFactory::getLanguage(); $lang = substr($lang->getTag(), 3); $db = JFactory::getDBO(); $stmt = $db->getQuery(true); // Select que me indica si el codigo del pais es válido $stmt->select('COUNT(1)'); $stmt->from('#__qs_countries AS c'); $stmt->where('c.codigo = ' . $db->Quote($nationality)); $stmt->where('c.lenguaje = ' . $db->Quote($lang)); $db->setQuery($stmt); if (!$db->loadResult()) { throw new Exception(JText::_('COM_AAWS_NATIONALITY_ERROR') . '{#paxnationality_' . ($key + 1) . '}', 1); } /** * Tipos de Documentos * * 5 National identity document * 4 Foreing Document * 2 Passport * 1 Visa * 20 Crew member certificate * 21 Passport card * 15 Redress number * 16 Known traveler number * */ $documenttype = $data['paxdocumenttype'][$key]; if (!in_array($documenttype, array('1', '2', '3', '4', '5', '15', '16', '20', '21'))) { throw new Exception(JText::_('COM_AAWS_DOCUMENTTYPE_ERROR') . '{#paxdocumenttype_' . ($key + 1) . '}', 1); } $paxinfo = array(); $paxinfo['Type'] = $value; $paxinfo['Treatment'] = $data['paxtreatment'][$key]; $paxinfo['BirthDate'] = $date1; $paxinfo['FirstName'] = $data['paxfirstname'][$key]; $paxinfo['LastName'] = $data['paxlastname'][$key]; $paxinfo['Gender'] = $data['paxgender'][$key]; $paxinfo['DocumentType'] = $documenttype; $paxinfo['Document'] = $data['paxdocumentnumber'][$key]; $paxinfo['Address'] = $data['paxfiscal'][$key]; //js $paxinfo['Phone'] = $data['paxphone'][$key]; //js $paxinfo['Nationality'] = $nationality; $paxinfo['Airline'] = $data['airline'][$key]; $paxinfo['FrecuentPassenger'] = $data['frecuentpassenger'][$key]; //=================================================================== $arrayPas['Pass'][$i]['TipDoc'] = $documenttype; $arrayPas['Pass'][$i]['NumDoc'] = $data['paxdocumentnumber'][$key]; $arrayPas['Pass'][$i]['TipoPas'] = $value; $arrayPas['Pass'][$i]['Name'] = $data['paxfirstname'][$key]; $arrayPas['Pass'][$i]['LastName'] = $data['paxlastname'][$key]; //=================================================================== if ($value == 'ADT') { $paxinfo['Email'] = $data['paxemail'][$key]; $paxinfo['ConfEmail'] = $data['paxemailconf'][$key]; } if ($value == 'ADT' && $infants > 0) { $paxinfo['hasInfant'] = 'true'; $infants--; } else { $paxinfo['hasInfant'] = 'false'; } $passengers[] = $paxinfo; $i++; } /*LLamado del Plugin evalChurning * Return TRUE o FALSE * + True = El usuario no puede realizar la reserva por que se encuentra una registrada en el sistema. * + False = El usuario puede realizar la reserva por que no se encuentra ninguna registrada en el sistema. */ //========================================================================= JPluginHelper::importPlugin('amadeus', 'evalChurning'); $dispatcher = JDispatcher::getInstance(); $isChurning = $dispatcher->trigger("plgevalChurning", array($arrayPas)); if ($isChurning[0] === true) { $app = JFactory::getApplication(); $app->redirect('index.php', JText::_('COM_AAWS_CHURNING_MENSAGE')); } else { $info['Passengers'] = $passengers; $params = JComponentHelper::getParams('com_aaws'); $this->setWebService($params->get('air_service', '')); // Se agrega la información de pasajeros $objRequest = new stdClass(); $objRequest->request = $this->getXmlAddDataPassenger($info); $response = $this->request('GetResponse', $objRequest); /** * Se confirma el Booking, para lo cual de la respuesta anterior * se obtiene el CorrelationID y el SequenceNmbr */ $info = array(); $xml = new DOMDocument(); $xml->loadXML($response); $xpath = new DOMXPath($xml); $xpath->registerNameSpace('ns0', 'http://www.opentravel.org/OTA/2003/05'); // Obteniendo el CorrelationID $results = $xpath->query('/ns0:OTA_AirBookRS/@CorrelationID'); foreach ($results as $result) { $info['CorrelationID'] = $result->nodeValue; } // Obteniendo el SequenceNmbr $results = $xpath->query('/ns0:OTA_AirBookRS/@SequenceNmbr'); foreach ($results as $result) { $info['SequenceNmbr'] = $result->nodeValue; } // Se confirma el Booking $objRequest = new stdClass(); $objRequest->request = $this->getXmlBook($info); $response = $this->request('GetResponse', $objRequest); /** * START Se ejecutan los plugins despues de hacer el booking. * * Los plugin pueden implementar las siguientes funcionalidades comunes * 1. Validar el usuario actual o crear uno para asignarle la orden (usar $_POST) * 2. Guardar la orden en el HistoryOrder o componente diseñado para tal fucionalidad * 3. O enviar la orden al medio de Pago contratado * * ES importante tener en cuenta que el orden de los plugins afecta el proceso, así * que revisar bien esa parte */ JPluginHelper::importPlugin('amadeus'); $dispatcher = JDispatcher::getInstance(); $user = JFactory::getUser(); // $IDPaymentMethod = 'P2P'; // $answer = $dispatcher->trigger('onAfterBooking', array(&$response, &$user, $IDPaymentMethod)); $answer = $dispatcher->trigger('onAfterBooking', array(&$response, &$user)); if (count($answer) == 0) { $booking = explode('BookingReferenceID ID="', $response); $booking = substr($booking[1], 0, 6); $app = JFactory::getApplication(); $app->redirect(JRoute::_(''), JText::sprintf('COM_AAWS_BOOKING_SAVED', $booking), 'error'); } } /** * En teoria cada plugin debe lanzar su excepción, y en caso que no arrojen excepción, * controlar el error o comportamiento deseado. Pero hasta aqui llega el flujo áereo. * * Si no existen plugins, se redirecciona al index y se muestra un mensaje de reserva exitosa. * END */ } catch (Exception $e) { if ($e->getCode() != 0 && $e->getCode() != 500) { $data = JRequest::getVar('wsform', array(), 'post'); JRequest::setVar('wsform', $data['detail'], 'post', true); unset($data['detail']); preg_match('/^([^{]*){#([^}]+)?}$/', $e->getMessage(), $matches); $data['error'] = array('message' => $matches[1], 'field' => $matches[2]); JRequest::setVar('info', $data, 'post', true); $this->passenger(); } else { $app = JFactory::getApplication(); $app->redirect(JRoute::_(''), $e->getMessage(), 'error'); } } }
/** * This function handles the calendar-multiget REPORT. * * This report is used by the client to fetch the content of a series * of urls. Effectively avoiding a lot of redundant requests. * * @param \DOMNode $dom * @return void */ public function calendarMultiGetReport($dom) { $properties = array_keys(DAV\XMLUtil::parseProperties($dom->firstChild)); $hrefElems = $dom->getElementsByTagNameNS('urn:DAV', 'href'); $xpath = new \DOMXPath($dom); $xpath->registerNameSpace('cal', Plugin::NS_CALDAV); $xpath->registerNameSpace('dav', 'urn:DAV'); $expand = $xpath->query('/cal:calendar-multiget/dav:prop/cal:calendar-data/cal:expand'); if ($expand->length > 0) { $expandElem = $expand->item(0); $start = $expandElem->getAttribute('start'); $end = $expandElem->getAttribute('end'); if (!$start || !$end) { throw new DAV\Exception\BadRequest('The "start" and "end" attributes are required for the CALDAV:expand element'); } $start = VObject\DateTimeParser::parseDateTime($start); $end = VObject\DateTimeParser::parseDateTime($end); if ($end <= $start) { throw new DAV\Exception\BadRequest('The end-date must be larger than the start-date in the expand element.'); } $expand = true; } else { $expand = false; } foreach ($hrefElems as $elem) { $uri = $this->server->calculateUri($elem->nodeValue); list($objProps) = $this->server->getPropertiesForPath($uri, $properties); if ($expand && isset($objProps[200]['{' . self::NS_CALDAV . '}calendar-data'])) { $vObject = VObject\Reader::read($objProps[200]['{' . self::NS_CALDAV . '}calendar-data']); $vObject->expand($start, $end); $objProps[200]['{' . self::NS_CALDAV . '}calendar-data'] = $vObject->serialize(); } $propertyList[] = $objProps; } $prefer = $this->server->getHTTPPRefer(); $this->server->httpResponse->sendStatus(207); $this->server->httpResponse->setHeader('Content-Type', 'application/xml; charset=utf-8'); $this->server->httpResponse->setHeader('Vary', 'Brief,Prefer'); $this->server->httpResponse->sendBody($this->server->generateMultiStatus($propertyList, $prefer['return-minimal'])); }
/** * Search and retieve records * * @throws Exception for diagnostic errors * * @param mixed $strQuery the query in CQL format * @param int $iStartRecord [optional] start record to begin with, default 1 * @param int $iMaxiumumRecords [optional] maximum records to return, default 10 * @param string $strSort [optional] index to sort records on * @return DOMDocument SRU results response */ public function searchRetrieve($search, $iStartRecord = 1, $iMaxiumumRecords = 10, $strSort = null) { $strQuery = null; if ($search instanceof Xerxes_Framework_Search_Query) { $strQuery = $search->toQuery(); } else { $strQuery = $search; } // append any limits set earlier $this->query = $strQuery . " " . $this->limits; // construct the request to the server $this->url = $this->base . "?wskey=" . $this->key; $this->url .= "&version=1.1"; $this->url .= "&operation=searchRetrieve"; $this->url .= "&query=" . urlencode($this->query); $this->url .= "&startRecord=" . $iStartRecord; $this->url .= "&maximumRecords=" . $iMaxiumumRecords; $this->url .= "&recordSchema=marcxml"; $this->url .= "&servicelevel=" . $this->service; // workset grouping if ($this->frbr == false) { $this->url .= "&frbrGrouping=off"; } // sort order if ($strSort != "") { $this->url .= "&sortKeys=" . $strSort; } // get the response from the server $objXml = new DOMDocument(); $objXml->load($this->url); // make sure we got something if ($objXml->documentElement == null) { throw new Exception("Could not connect to WorldCat database."); } $objXPath = new DOMXPath($objXml); $objXPath->registerNameSpace("zs", "http://www.loc.gov/zing/srw/"); // check for diagnostic errors $objDiagnostics = $objXPath->query("zs:diagnostics"); if ($objDiagnostics->length > 0) { $strError = ""; $diagnostics = simplexml_import_dom($objDiagnostics->item(0)); foreach ($diagnostics->diagnostic as $diagnostic) { $strError .= $diagnostic->message; if ((string) $diagnostic->details != "") { $strError .= ": " . $diagnostic->details; } } throw new Exception($strError); } // extract total hits $objTotal = $objXPath->query("zs:numberOfRecords")->item(0); if ($objTotal != null) { $this->total = (int) $objTotal->nodeValue; } return $objXml; }
/** * This function handles the addressbook-query REPORT * * This report is used by the client to filter an addressbook based on a * complex query. * * @param \DOMNode $dom * @return void */ protected function addressbookQueryReport($dom) { $query = new AddressBookQueryParser($dom); $query->parse(); $depth = $this->server->getHTTPDepth(0); if ($depth == 0) { $candidateNodes = [$this->server->tree->getNodeForPath($this->server->getRequestUri())]; if (!$candidateNodes[0] instanceof ICard) { throw new ReportNotSupported('The addressbook-query report is not supported on this url with Depth: 0'); } } else { $candidateNodes = $this->server->tree->getChildren($this->server->getRequestUri()); } $xpath = new \DOMXPath($dom); $xpath->registerNameSpace('card', Plugin::NS_CARDDAV); $xpath->registerNameSpace('dav', 'urn:DAV'); $contentType = $xpath->evaluate("string(/card:addressbook-query/dav:prop/card:address-data/@content-type)"); $version = $xpath->evaluate("string(/card:addressbook-query/dav:prop/card:address-data/@version)"); if ($version) { $contentType .= '; version=' . $version; } $vcardType = $this->negotiateVCard($contentType); $validNodes = []; foreach ($candidateNodes as $node) { if (!$node instanceof ICard) { continue; } $blob = $node->get(); if (is_resource($blob)) { $blob = stream_get_contents($blob); } if (!$this->validateFilters($blob, $query->filters, $query->test)) { continue; } $validNodes[] = $node; if ($query->limit && $query->limit <= count($validNodes)) { // We hit the maximum number of items, we can stop now. break; } } $result = []; foreach ($validNodes as $validNode) { if ($depth == 0) { $href = $this->server->getRequestUri(); } else { $href = $this->server->getRequestUri() . '/' . $validNode->getName(); } list($props) = $this->server->getPropertiesForPath($href, $query->requestedProperties, 0); if (isset($props[200]['{' . self::NS_CARDDAV . '}address-data'])) { $props[200]['{' . self::NS_CARDDAV . '}address-data'] = $this->convertVCard($props[200]['{' . self::NS_CARDDAV . '}address-data'], $vcardType); } $result[] = $props; } $prefer = $this->server->getHTTPPRefer(); $this->server->httpResponse->setStatus(207); $this->server->httpResponse->setHeader('Content-Type', 'application/xml; charset=utf-8'); $this->server->httpResponse->setHeader('Vary', 'Brief,Prefer'); $this->server->httpResponse->setBody($this->server->generateMultiStatus($result, $prefer['return-minimal'])); }
#<?php # include all php files necessary for Tuque foreach (glob("/var/www/drupal/htdocs/sites/all/libraries/tuque/*.php") as $filename) { require_once $filename; } // load file if (file_exists('/root/jpdcrecord.xml')) { $dcRecord = simplexml_load_file('/root/jpdcrecord.xml'); } else { echo "\n**********ERROR LOADING FILE********\n"; return; } $dcDOMDoc = new DOMDocument(); $dcDOMDoc->loadXML($dcRecord->asXML()); $dcXPath = new DOMXPath($dcDOMDoc); $dcXPath->registerNameSpace('dc', 'http://purl.org/dc/elements/1.1/'); $xml_out = $dcDOMDoc->saveXML($dcDOMDoc->documentElement); echo $xml_out . "\n\n"; foreach ($dcXPath->query('dc:contributor') as $node) { echo $node->nodeValue; } //xml_form_builder_transform_document($transform, $source_document) xml_form_builder_transform_document($transform, $dcDOMDoc); /** * Updates the DC datastream by applying the given transform. * * @param AbstractObject $object * The object whose DC will be updated. * @param string $transform * The transform to apply, as defined by the forms association. * @param DOMDocument $document