function validate($xml, $schema) { $doc = new DomDocument(); $doc->Load($xml); if (@$doc->schemaValidate($schema)) { printf('%s is valid against %s' . "\n", $xml, $schema); } else { printf('!!! %s is not valid against %s' . "\n", $xml, $schema); } }
public function validate($path_to_mods) { $mods = new \DomDocument('1.0'); $mods->load($path_to_mods); if ($mods->schemaValidate($this->schema_location)) { $this->log->addInfo("MODS file validates", array('file' => $path_to_mods)); } else { $this->log->addWarning("MODS file does not validate", array('file' => $path_to_mods)); } }
public function testExportDemo() { $fname = "../../docs/export-demo.xml"; $version = WikiExporter::schemaVersion(); $dom = new DomDocument(); $dom->load($fname); // Ensure, the demo is for the current version $this->assertEquals($dom->documentElement->getAttribute('version'), $version, 'export-demo.xml should have the current version'); $this->assertTrue($dom->schemaValidate("../../docs/export-" . $version . ".xsd"), "schemaValidate has found an error"); }
/** * Validates a xml file against the xsd. * * The validation is slow, because php has to read the xsd on each call. * * @param $fname string: name of file to validate */ protected function validateXmlFileAgainstXsd($fname) { $version = WikiExporter::schemaVersion(); $dom = new DomDocument(); $dom->load($fname); try { $this->assertTrue($dom->schemaValidate("../../docs/export-" . $version . ".xsd"), "schemaValidate has found an error"); } catch (Exception $e) { $this->fail("xml not valid against xsd: " . $e->getMessage()); } }
public function validate_file($file) { libxml_use_internal_errors(true); $DOM = new DomDocument(); // $DOM->loadXML($xmlString); $DOM->load($file); if (!$DOM->schemaValidate(dirname(__FILE__) . '/xml/schema.xsd')) { $this->errors = libxml_get_errors(); return false; } return true; }
/** * Validates a xml file against the xsd. * * The validation is slow, because php has to read the xsd on each call. * * @param $fname string: name of file to validate */ protected function validateXmlFileAgainstXsd($fname) { $version = WikiExporter::schemaVersion(); $dom = new DomDocument(); $dom->load($fname); // Ensure, the demo is for the current version $this->assertEquals($dom->documentElement->getAttribute('version'), $version, 'export-demo.xml should have the current version'); try { $this->assertTrue($dom->schemaValidate("../../docs/export-" . $version . ".xsd"), "schemaValidate has found an error"); } catch (Exception $e) { $this->fail("xml not valid against xsd: " . $e->getMessage()); } }
function validate_xml($xmlString) { libxml_use_internal_errors(true); $dom = new DomDocument(); $dom->loadXML($xmlString); $errors = true; if (!@$dom->schemaValidate('')) { $errors = libxml_get_errors(); if (0 == sizeof($errors)) { $errors = true; } } return $errors; }
public function testDatabasePackageName() { $schema = <<<EOF <database name="bookstore" package="my.sub-directory"> <table name="book"> <column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" /> <column name="title" type="VARCHAR" size="100" primaryString="true" /> </table> </database> EOF; $dom = new DomDocument('1.0', 'UTF-8'); $dom->loadXML($schema); $this->assertTrue($dom->schemaValidate($this->xsdFile)); }
public static function isValid($data) { $doc = new DomDocument('1.0'); $doc->loadXML($data); $errors = libxml_get_errors(); if ($errors) { return false; } if (strpos($data, 'version="1.2">') !== false) { $schema = __DIR__ . '/../data/xliff-core-1.2-transitional.xsd'; if (!$doc->schemaValidate($schema)) { return false; } } return true; }
public function matches($schemaFile) { foreach ($this->xml as $id => $dom) { $configElement = $dom->getElementsByTagName('config'); if (1 !== $configElement->length) { throw new \InvalidArgumentException(sprintf('Can only test a file if it contains 1 <config> element, %d given', $configElement->length)); } $configDom = new \DomDocument(); $configDom->appendChild($configDom->importNode($configElement->item(0), true)); libxml_use_internal_errors(true); if (!$configDom->schemaValidate($schemaFile)) { $this->errors = libxml_get_errors(); $this->failingElement = $id; return false; } } return true; }
/** * Short description of method validate * * @access public * @author Bertrand Chevrier, <*****@*****.**> * @param string schema * @return boolean */ public function validate($schema = '') { //You know sometimes you think you have enough time, but it is not always true ... //(timeout in hudson with the generis-hard test suite) helpers_TimeOutHelper::setTimeOutLimit(helpers_TimeOutHelper::MEDIUM); $content = $this->getContent(); if (!empty($content)) { try { libxml_use_internal_errors(true); $dom = new DomDocument(); $dom->formatOutput = true; $dom->preserveWhiteSpace = false; $this->valid = $dom->loadXML($content); if ($this->valid && !empty($schema)) { $this->valid = $dom->schemaValidate($schema); } if (!$this->valid) { $this->addErrors(libxml_get_errors()); } libxml_clear_errors(); } catch (DOMException $de) { $this->addError($de); } } helpers_TimeOutHelper::reset(); return (bool) $this->valid; }
public static function validateXML($xmlStr) { if (SIF_VALIDATE == 'Y' or SIF_VALIDATE == 'W') { libxml_use_internal_errors(true); $xml = explode("\n", $xmlStr); $objDom = new DomDocument(); if ($xmlStr == '' || $xmlStr == null) { ZitLog::writeToErrorLog('[Xml missing in request]', 'Xml is missing in request can not process message', 'Process Message', $_SESSION['ZONE_ID']); echo '<FATAL_ERROR>XML FORMAT</FATAL_ERROR>'; exit; } if (!$objDom->loadXML($xmlStr)) { ZitLog::writeToErrorLog('[Error loading xml to parse]', $xmlStr, 'Process Message', $_SESSION['ZONE_ID']); echo '<FATAL_ERROR>XML FORMAT</FATAL_ERROR>'; exit; } $schema = $_SESSION['ZONE_VERSION_SCHEMA_DIR']; if (!$objDom->schemaValidate($schema)) { $errorString = ''; $allErrors = libxml_get_errors(); foreach ($allErrors as $error) { $errorString .= SifProcessRequest::Display_xml_error($error, $xml); } ZitLog::writeToErrorLog("[Error Validating Xml]", "Request Xml:\n{$xmlStr} \n\nSchema Errors:{$errorString}", "Process Message", $_SESSION['ZONE_ID']); if (SIF_VALIDATE == 'Y') { return false; } else { return true; } } else { return true; } } else { return true; } }
function add_xml_observations() { global $baseURL, $entryMessage, $objSession, $mailTo, $mailFrom, $loggedUser, $objConstellation, $objObject, $objCatalog, $objLocation, $objInstrument, $objFilter, $objEyepiece, $objLens, $objDatabase, $objObserver, $objObservation; if ($_FILES['xml']['tmp_name'] != "") { $xmlfile = $_FILES['xml']['tmp_name']; } else { $entryMessage .= LangXMLError3; $_GET['indexAction'] = "add_xml"; return; } // Make a DomDocument from the file. $dom = new DomDocument(); $xmlfile = realpath($xmlfile); // Load the xml document in the DOMDocument object $dom->Load($xmlfile); $searchNode = $dom->getElementsByTagName("observations"); $version = $searchNode->item(0)->getAttribute("version"); if ($version == "2.0" || $version == "2.1") { } else { $entryMessage .= LangXMLError1; $_GET['indexAction'] = "add_xml"; return; } // Use the correct schema definition to check the xml file. $xmlschema = str_replace(' ', '/', $searchNode->item(0)->getAttribute("xsi:schemaLocation")); $xmlschema = $baseURL . "xml/oal21/oal21.xsd"; // Validate the XML file against the schema if ($dom->schemaValidate($xmlschema)) { // The XML file is valid. Let's start reading in the file. // Only 2.0 and 2.1 files! // Check the observers -> In OpenAstronomyLog 2.0 the deepskylog_id is also added $searchNode = $dom->getElementsByTagName("observers"); $observer = $searchNode->item(0)->getElementsByTagName("observer"); $observerArray = array(); $id = ""; foreach ($observer as $observer) { $tmpObserverArray = array(); // Get the id and the name of the observers in the comast file $comastid = $observer->getAttribute("id"); $name = htmlentities($observer->getElementsByTagName("name")->item(0)->nodeValue, ENT_COMPAT, "UTF-8", 0); $tmpObserverArray['name'] = $name; $surname = htmlentities($observer->getElementsByTagName("surname")->item(0)->nodeValue, ENT_COMPAT, "UTF-8", 0); $tmpObserverArray['surname'] = $surname; if ($observer->getElementsByTagName("fstOffset")->item(0)) { $fstOffset[$comastid] = $observer->getElementsByTagName("fstOffset")->item(0)->nodeValue; } else { $fstOffset[$comastid] = 0.0; } $observerid = $observer->getElementsByTagName("account"); $obsid = ""; foreach ($observerid as $observerid) { if ($observerid->getAttribute("name") == "www.deepskylog.org") { $obsid = $observerid->nodeValue; } } // Get the name of the observer which is logged in in DeepskyLog $deepskylog_username = $objObserver->getObserverProperty($_SESSION['deepskylog_id'], 'firstname') . " " . $objObserver->getObserverProperty($_SESSION['deepskylog_id'], 'name'); if ($obsid != "") { if ($obsid == $_SESSION['deepskylog_id']) { $id = $comastid; } } else { if ($deepskylog_username == $name . " " . $surname) { $id = $comastid; } } $observerArray[$comastid] = $tmpObserverArray; } if ($id == "") { $entryMessage .= LangXMLError2 . $deepskylog_username . LangXMLError2a; $_GET['indexAction'] = "add_xml"; return; } else { $objObserver->setObserverProperty($_SESSION['deepskylog_id'], 'fstOffset', $fstOffset[$id]); } $targets = $dom->getElementsByTagName("targets"); $target = $targets->item(0)->getElementsByTagName("target"); $targetArray = array(); foreach ($target as $target) { $targetInfoArray = array(); $targetid = $target->getAttribute("id"); $targetInfoArray["name"] = $target->getElementsByTagName("name")->item(0)->nodeValue; $aliases = $target->getElementsByTagName("alias"); $aliasesArray = array(); $cnt = 0; foreach ($aliases as $aliases) { $aliasesArray["alias" . $cnt] = $aliases->nodeValue; $cnt = $cnt + 1; } // Check if the datasource is defined. If this is the case, get it. Otherwise, set to OAL if ($target->getElementsByTagName("datasource")->item(0)) { $targetInfoArray["datasource"] = $target->getElementsByTagName("datasource")->item(0)->nodeValue; } else { $targetInfoArray["datasource"] = "OAL"; } $valid = true; // Get the type if ($target->getAttribute("xsi:type")) { $type = $target->getAttribute("xsi:type"); $next = 1; if ($type == "oal:deepSkyAS") { $targetInfoArray["type"] = "ASTER"; } else { if ($type == "oal:deepSkyDS") { $targetInfoArray["type"] = "AA2STAR"; } else { if ($type == "oal:deepSkySC" || $type == "oal:deepSkyOC") { $targetInfoArray["type"] = "OPNCL"; } else { if ($type == "oal:deepSkyGC") { $targetInfoArray["type"] = "GLOCL"; } else { if ($type == "oal:deepSkyGX") { $targetInfoArray["type"] = "GALXY"; } else { if ($type == "oal:deepSkyCG") { $targetInfoArray["type"] = "GALCL"; } else { if ($type == "oal:deepSkyGN") { $targetInfoArray["type"] = "BRTNB"; } else { if ($type == "oal:deepSkyGN") { $targetInfoArray["type"] = "BRTNB"; } else { if ($type == "oal:deepSkyPN") { $targetInfoArray["type"] = "PLNNB"; } else { if ($type == "oal:deepSkyQS") { $targetInfoArray["type"] = "QUASR"; } else { if ($type == "oal:deepSkyDN") { $targetInfoArray["type"] = "DRKNB"; } else { if ($type == "oal:deepSkyNA") { $targetInfoArray["type"] = "NONEX"; } else { $next = 0; $valid = false; } } } } } } } } } } } } } else { $valid = false; } $targetInfoArray["known"] = $next; if ($valid) { // Get Ra and convert it to degrees if (!$target->getElementsByTagName("position")->item(0)->getElementsByTagName("ra")->item(0)) { $valid = false; } else { $unit = $target->getElementsByTagName("position")->item(0)->getElementsByTagName("ra")->item(0)->getAttribute("unit"); if ($unit == "deg") { $ra = $target->getElementsByTagName("position")->item(0)->getElementsByTagName("ra")->item(0)->nodeValue; } else { if ($unit == "rad") { $ra = Rad2Deg($target->getElementsByTagName("position")->item(0)->getElementsByTagName("ra")->item(0)->nodeValue); } else { if ($unit == "arcmin") { $ra = $target->getElementsByTagName("position")->item(0)->getElementsByTagName("ra")->item(0)->nodeValue / 60.0; } else { if ($unit == "arcsec") { $ra = $target->getElementsByTagName("position")->item(0)->getElementsByTagName("ra")->item(0)->nodeValue / 3600.0; } } } } $targetInfoArray["ra"] = $ra / 15.0; } if (!$target->getElementsByTagName("position")->item(0)->getElementsByTagName("dec")->item(0)) { $valid = false; } else { // Get Dec and convert it to degrees $unit = $target->getElementsByTagName("position")->item(0)->getElementsByTagName("dec")->item(0)->getAttribute("unit"); if ($unit == "deg") { $dec = $target->getElementsByTagName("position")->item(0)->getElementsByTagName("dec")->item(0)->nodeValue; } else { if ($unit == "rad") { $dec = Rad2Deg($target->getElementsByTagName("position")->item(0)->getElementsByTagName("dec")->item(0)->nodeValue); } else { if ($unit == "arcmin") { $dec = $target->getElementsByTagName("position")->item(0)->getElementsByTagName("dec")->item(0)->nodeValue / 60.0; } else { if ($unit == "arcsec") { $dec = $target->getElementsByTagName("position")->item(0)->getElementsByTagName("dec")->item(0)->nodeValue / 3600.0; } } } } $targetInfoArray["dec"] = $dec; } $targetInfoArray['constellation'] = $objConstellation->getConstellationFromCoordinates($targetInfoArray["ra"], $targetInfoArray["dec"]); // Check if the magnitude is defined. If this is the case, get it. Otherwise, set to 99.9 if ($target->getElementsByTagName("visMag")->item(0)) { $targetInfoArray["mag"] = $target->getElementsByTagName("visMag")->item(0)->nodeValue; } else { $targetInfoArray["mag"] = "99.9"; } // Check if the surface brightness is defined. If this is the case, get it. Otherwise, set to 99.9 if ($target->getElementsByTagName("surfBr")->item(0)) { // Get surface brightness and convert it $unit = $target->getElementsByTagName("surfBr")->item(0)->getAttribute("unit"); if ($unit == "mags-per-squarearcmin") { $subr = $target->getElementsByTagName("surfBr")->item(0)->nodeValue; } else { $subr = $target->getElementsByTagName("surfBr")->item(0)->nodeValue - 8.890000000000001; } $targetInfoArray["subr"] = $subr; } else { $targetInfoArray["subr"] = "99.9"; } // Check if the position angle is defined. If this is the case, get it. Otherwise, set to 999 if ($target->getElementsByTagName("pa")->item(0)) { $targetInfoArray["pa"] = $target->getElementsByTagName("pa")->item(0)->nodeValue; } else { $targetInfoArray["pa"] = "999"; } // Check if the largeDiameter is defined. If this is the case, get it. Otherwise, set to 0 if ($target->getElementsByTagName("largeDiameter")->item(0)) { // Get Dec and convert it to arcseconds $unit = $target->getElementsByTagName("largeDiameter")->item(0)->getAttribute("unit"); if ($unit == "deg") { $diam1 = $target->getElementsByTagName("largeDiameter")->item(0)->nodeValue * 3600.0; } else { if ($unit == "rad") { $diam1 = Rad2Deg($target->getElementsByTagName("largeDiameter")->item(0)->nodeValue) * 3600.0; } else { if ($unit == "arcmin") { $diam1 = $target->getElementsByTagName("largeDiameter")->item(0)->nodeValue * 60.0; } else { if ($unit == "arcsec") { $diam1 = $target->getElementsByTagName("largeDiameter")->item(0)->nodeValue; } } } } $targetInfoArray["diam1"] = $diam1; } else { $targetInfoArray["diam1"] = "0"; } // Check if the smallDiameter is defined. If this is the case, get it. Otherwise, set to 0 if ($target->getElementsByTagName("smallDiameter")->item(0)) { // Get Dec and convert it to arcseconds $unit = $target->getElementsByTagName("smallDiameter")->item(0)->getAttribute("unit"); if ($unit == "deg") { $diam2 = $target->getElementsByTagName("smallDiameter")->item(0)->nodeValue * 3600.0; } else { if ($unit == "rad") { $diam2 = Rad2Deg($target->getElementsByTagName("smallDiameter")->item(0)->nodeValue) * 3600.0; } else { if ($unit == "arcmin") { $diam2 = $target->getElementsByTagName("smallDiameter")->item(0)->nodeValue * 60.0; } else { if ($unit == "arcsec") { $diam2 = $target->getElementsByTagName("smallDiameter")->item(0)->nodeValue; } } } } $targetInfoArray["diam2"] = $diam2; } else { $targetInfoArray["diam2"] = "0"; } } $targetInfoArray["valid"] = $valid; $targetInfoArray["aliases"] = $aliasesArray; $targetArray[$targetid] = $targetInfoArray; } // SITES $sites = $dom->getElementsByTagName("sites"); $site = $sites->item(0)->getElementsByTagName("site"); $siteArray = array(); foreach ($site as $site) { $siteInfoArray = array(); $siteid = $site->getAttribute("id"); $siteInfoArray["name"] = htmlentities($site->getElementsByTagName("name")->item(0)->nodeValue, ENT_COMPAT, "UTF-8", 0); // Get longitude and convert it to degrees $unit = $site->getElementsByTagName("longitude")->item(0)->getAttribute("unit"); if ($unit == "deg") { $longitude = $site->getElementsByTagName("longitude")->item(0)->nodeValue; } else { if ($unit == "rad") { $longitude = Rad2Deg($site->getElementsByTagName("longitude")->item(0)->nodeValue); } else { if ($unit == "arcmin") { $longitude = $site->getElementsByTagName("longitude")->item(0)->nodeValue / 60.0; } else { if ($unit == "arcsec") { $longitude = $site->getElementsByTagName("longitude")->item(0)->nodeValue / 3600.0; } } } } $siteInfoArray["longitude"] = $longitude; // Get latitude and convert it to degrees $unit = $site->getElementsByTagName("latitude")->item(0)->getAttribute("unit"); if ($unit == "deg") { $latitude = $site->getElementsByTagName("latitude")->item(0)->nodeValue; } else { if ($unit == "rad") { $latitude = Rad2Deg($site->getElementsByTagName("latitude")->item(0)->nodeValue); } else { if ($unit == "arcmin") { $latitude = $site->getElementsByTagName("latitude")->item(0)->nodeValue / 60.0; } else { if ($unit == "arcsec") { $latitude = $site->getElementsByTagName("latitude")->item(0)->nodeValue / 3600.0; } } } } $siteInfoArray["latitude"] = $latitude; // Get the timezone $xmlfile2 = "http://api.geonames.org/timezone?lat=" . $latitude . "&lng=" . $longitude . "&username=deepskylog"; $timezones = simplexml_load_file($xmlfile2); $siteInfoArray["timezone"] = $timezones->timezone->timezoneId; $siteInfoArray["country"] = $timezones->timezone->countryName; $siteInfoArray["country"] = $timezones->timezone->countryName; if ($siteInfoArray["timezone"] == "") { $siteInfoArray["timezone"] = "UTC"; } $siteArray[$siteid] = $siteInfoArray; } // SESSIONS $sessions = $dom->getElementsByTagName("sessions"); $session = $sessions->item(0)->getElementsByTagName("session"); $sessionArray = array(); foreach ($session as $session) { $sessionInfoArray = array(); $sessionid = $session->getAttribute("id"); $sessionLang = $session->getAttribute("lang"); $sessionInfoArray['lang'] = $sessionLang; // Get the begindate and convert it to the DeepskyLog format $tmpBegin = $session->getElementsByTagName("begin")->item(0)->nodeValue; $beginDate = substr($tmpBegin, 0, 10); $beginTime = substr($tmpBegin, 11, 8); $timeDiff = substr($tmpBegin, 19, 6); $timeDiffHours = substr($timeDiff, 0, 3); $timeDiffMinutes = substr($timeDiff, 4, 2); if ($timeDiffHours > 0) { $beginDate2 = add_date($beginDate . " " . $beginTime, -$timeDiffHours, -$timeDiffMinutes); } else { $beginDate2 = add_date($beginDate . " " . $beginTime, -$timeDiffHours, $timeDiffMinutes); } $sessionInfoArray["begindate"] = $beginDate2; $tmpEnd = $session->getElementsByTagName("end")->item(0)->nodeValue; $endDate = substr($tmpEnd, 0, 10); $endTime = substr($tmpEnd, 11, 8); $timeDiff = substr($tmpEnd, 19, 6); $timeDiffHours = substr($timeDiff, 0, 3); $timeDiffMinutes = substr($timeDiff, 4, 2); if ($timeDiffHours > 0) { $endDate2 = add_date($endDate . " " . $endTime, -$timeDiffHours, -$timeDiffMinutes); } else { $endDate2 = add_date($endDate . " " . $endTime, -$timeDiffHours, $timeDiffMinutes); } $sessionInfoArray["enddate"] = $endDate2; // Get siteid -> Maybe we still have to add the site later $siteid = $session->getElementsByTagName("site")->item(0)->nodeValue; $sessionInfoArray["site"] = $siteid; // Get all coObservers if ($session->getElementsByTagName("coObserver")->item(0)) { $coObs = $session->getElementsByTagName("coObserver"); $coObsArray = array(); foreach ($coObs as $coObs) { $coObsArray[] = $coObs->nodeValue; } $sessionInfoArray["coObservers"] = $coObsArray; } // Get weather if ($session->getElementsByTagName("weather")->item(0)) { $sessionInfoArray["weather"] = htmlentities($session->getElementsByTagName("weather")->item(0)->nodeValue, ENT_COMPAT, "UTF-8", 0); } // Get the equipment if ($session->getElementsByTagName("equipment")->item(0)) { $sessionInfoArray["equipment"] = htmlentities($session->getElementsByTagName("equipment")->item(0)->nodeValue, ENT_COMPAT, "UTF-8", 0); } // Get the comments if ($session->getElementsByTagName("comments")->item(0)) { $sessionInfoArray["comments"] = htmlentities($session->getElementsByTagName("comments")->item(0)->nodeValue, ENT_COMPAT, "UTF-8", 0); } // We don't use the image tag of the session element to import, only to export $sessionArray[$sessionid] = $sessionInfoArray; } // SCOPES $scopes = $dom->getElementsByTagName("scopes"); $scope = $scopes->item(0)->getElementsByTagName("scope"); $scopeArray = array(); foreach ($scope as $scope) { $scopeInfoArray = array(); $scopeid = $scope->getAttribute("id"); $scopeInfoArray["name"] = htmlentities($scope->getElementsByTagName("model")->item(0)->nodeValue, ENT_COMPAT, "UTF-8", 0); $scopeInfoArray["diameter"] = $scope->getElementsByTagName("aperture")->item(0)->nodeValue; $tp = $scope->getAttribute("xsi:type"); if ($tp == "oal:scopeType") { if ($scope->getElementsByTagName("focalLength")->item(0)) { $type = $scope->getElementsByTagName("type")->item(0)->nodeValue; if ($type == "A" || $type == "Naked Eye") { $typeToSave = InstrumentNakedEye; } else { if ($type == "B" || $type == "Binoculars") { $typeToSave = InstrumentBinoculars; } else { if ($type == "R" || $type == "Refractor") { $typeToSave = InstrumentRefractor; } else { if ($type == "N" || $type == "Newton") { $typeToSave = InstrumentReflector; } else { if ($type == "C" || $type == "Cassegrain") { $typeToSave = InstrumentCassegrain; } else { if ($type == "K" || $type == "Kutter") { $typeToSave = InstrumentKutter; } else { if ($type == "M" || $type == "Maksutov") { $typeToSave = InstrumentMaksutov; } else { if ($type == "S" || $type == "Schmidt-Cassegrain") { $typeToSave = InstrumentSchmidtCassegrain; } else { $typeToSave = InstrumentOther; } } } } } } } } } else { $typeToSave = InstrumentOther; } } else { $typeToSave = InstrumentBinoculars; } $scopeInfoArray["type"] = $typeToSave; // Check if the focal length exists. If so, we are using a telescope, else a binocular if ($scope->getElementsByTagName("focalLength")->item(0)) { $fl = $scope->getElementsByTagName("focalLength")->item(0)->nodeValue; $scopeInfoArray["fd"] = $fl / $scopeInfoArray["diameter"]; $scopeInfoArray["fixedMagnification"] = 0; } else { $scopeInfoArray["fd"] = 0; $scopeInfoArray["fixedMagnification"] = $scope->getElementsByTagName("magnification")->item(0)->nodeValue; } $scopeArray[$scopeid] = $scopeInfoArray; } // EYEPIECES $eyepieces = $dom->getElementsByTagName("eyepieces"); $eyepiece = $eyepieces->item(0)->getElementsByTagName("eyepiece"); $eyepieceArray = array(); foreach ($eyepiece as $eyepiece) { $eyepieceInfoArray = array(); $eyepieceid = $eyepiece->getAttribute("id"); $eyepieceInfoArray["name"] = htmlentities($eyepiece->getElementsByTagName("model")->item(0)->nodeValue, ENT_COMPAT, "UTF-8", 0); $eyepieceInfoArray["focalLength"] = $eyepiece->getElementsByTagName("focalLength")->item(0)->nodeValue; // Check if the maximal focal length exists. If so, we are using a zoom eyepiece if ($eyepiece->getElementsByTagName("maxFocalLength")->item(0)) { $eyepieceInfoArray["maxFocalLength"] = $eyepiece->getElementsByTagName("maxFocalLength")->item(0)->nodeValue; } else { $eyepieceInfoArray["maxFocalLength"] = -1; } // Get focal length and convert it to degrees if (!$target->getElementsByTagName("apparentFOV")->item(0)) { $fov = 60.0; } else { $unit = $eyepiece->getElementsByTagName("apparentFOV")->item(0)->getAttribute("unit"); if ($unit == "deg") { $fov = $eyepiece->getElementsByTagName("apparentFOV")->item(0)->nodeValue; } else { if ($unit == "rad") { $fov = Rad2Deg($eyepiece->getElementsByTagName("apparentFOV")->item(0)->nodeValue); } else { if ($unit == "arcmin") { $fov = $eyepiece->getElementsByTagName("apparentFOV")->item(0)->nodeValue / 60.0; } else { if ($unit == "arcsec") { $fov = $eyepiece->getElementsByTagName("apparentFOV")->item(0)->nodeValue / 3600.0; } } } } } $eyepieceInfoArray["apparentFOV"] = $fov; $eyepieceArray[$eyepieceid] = $eyepieceInfoArray; } // LENSES $lenses = $dom->getElementsByTagName("lenses"); $lens = $lenses->item(0)->getElementsByTagName("lens"); $lensArray = array(); foreach ($lens as $lens) { $lensInfoArray = array(); $lensid = $lens->getAttribute("id"); $lensInfoArray["name"] = htmlentities($lens->getElementsByTagName("model")->item(0)->nodeValue, ENT_COMPAT, "UTF-8", 0); $lensInfoArray["factor"] = $lens->getElementsByTagName("factor")->item(0)->nodeValue; $lensArray[$lensid] = $lensInfoArray; } // FILTERS $filters = $dom->getElementsByTagName("filters"); $filter = $filters->item(0)->getElementsByTagName("filter"); $filterArray = array(); foreach ($filter as $filter) { $filterInfoArray = array(); $filterid = $filter->getAttribute("id"); $filterInfoArray["name"] = htmlentities($filter->getElementsByTagName("model")->item(0)->nodeValue, ENT_COMPAT, "UTF-8", 0); $type = $filter->getElementsByTagName("type")->item(0)->nodeValue; if ($type == "other") { $typeInfo = 0; } else { if ($type == "broad band") { $typeInfo = 1; } else { if ($type == "narrow band") { $typeInfo = 2; } else { if ($type == "O-III") { $typeInfo = 3; } else { if ($type == "H-beta") { $typeInfo = 4; } else { if ($type == "H-alpha") { $typeInfo = 5; } else { if ($type == "color") { $typeInfo = 6; } else { if ($type == "neutral") { $typeInfo = 7; } else { if ($type == "corrective") { $typeInfo = 8; } } } } } } } } } $filterInfoArray["type"] = $typeInfo; if ($filter->getElementsByTagName("wratten")->item(0)) { $filterInfoArray["wratten"] = $filter->getElementsByTagName("wratten")->item(0)->nodeValue; } else { $filterInfoArray["wratten"] = ""; } if ($filter->getElementsByTagName("schott")->item(0)) { $filterInfoArray["schott"] = $filter->getElementsByTagName("schott")->item(0)->nodeValue; } else { $filterInfoArray["schott"] = ""; } if ($filter->getElementsByTagName("color")->item(0)) { $color = $filter->getElementsByTagName("color")->item(0)->nodeValue; if ($color == "light red") { $filterInfoArray["color"] = 1; } else { if ($color == "red") { $filterInfoArray["color"] = 2; } else { if ($color == "deep red") { $filterInfoArray["color"] = 3; } else { if ($color == "orange") { $filterInfoArray["color"] = 4; } else { if ($color == "light yellow") { $filterInfoArray["color"] = 5; } else { if ($color == "deep yellow") { $filterInfoArray["color"] = 6; } else { if ($color == "yellow") { $filterInfoArray["color"] = 7; } else { if ($color == "yellow-green") { $filterInfoArray["color"] = 8; } else { if ($color == "light green") { $filterInfoArray["color"] = 9; } else { if ($color == "green") { $filterInfoArray["color"] = 10; } else { if ($color == "medium blue") { $filterInfoArray["color"] = 11; } else { if ($color == "pale blue") { $filterInfoArray["color"] = 12; } else { if ($color == "blue") { $filterInfoArray["color"] = 13; } else { if ($color == "deep blue") { $filterInfoArray["color"] = 14; } else { if ($color == "voilet") { $filterInfoArray["color"] = 15; } else { $filterInfoArray["color"] = 0; } } } } } } } } } } } } } } } } else { $filterInfoArray["color"] = 0; } $filterArray[$filterid] = $filterInfoArray; } // Add the sessions while (list($key, $value) = each($sessionArray)) { if (count($objDatabase->selectRecordArray("SELECT * from sessions where begindate = \"" . $sessionArray[$key]['begindate'] . "\" and enddate = \"" . $sessionArray[$key]['enddate'] . "\";")) == 0) { $sessionid = 0; } else { $sessionid = $objDatabase->selectRecordArray("SELECT * from sessions where begindate = \"" . $sessionArray[$key]['begindate'] . "\" and enddate = \"" . $sessionArray[$key]['enddate'] . "\";"); $sessionid = $sessionid['id']; } $beginday = substr($sessionArray[$key]['begindate'], 8, 2); $beginmonth = substr($sessionArray[$key]['begindate'], 5, 2); $beginyear = substr($sessionArray[$key]['begindate'], 0, 4); $beginhours = substr($sessionArray[$key]['begindate'], 11, 2); $beginminutes = substr($sessionArray[$key]['begindate'], 14, 2); $endday = substr($sessionArray[$key]['enddate'], 8, 2); $endmonth = substr($sessionArray[$key]['enddate'], 5, 2); $endyear = substr($sessionArray[$key]['enddate'], 0, 4); $endhours = substr($sessionArray[$key]['enddate'], 11, 2); $endminutes = substr($sessionArray[$key]['enddate'], 14, 2); $location = $sessionArray[$key]['site']; // Check if the site already exists in DeepskyLog $site = $siteArray[$sessionArray[$key]['site']]["name"]; $sa = $siteArray[$sessionArray[$key]['site']]; if (count($objDatabase->selectRecordArray("SELECT * from locations where observer = \"" . $_SESSION['deepskylog_id'] . "\" and name = \"" . $site . "\";")) > 0) { // Update the coordinates $run = $objDatabase->selectRecordset("SELECT id FROM locations WHERE observer = \"" . $_SESSION['deepskylog_id'] . "\" and name = \"" . $site . "\";"); $get = $run->fetch(PDO::FETCH_OBJ); $locId = $get->id; $objLocation->setLocationProperty($locId, "longitude", $sa["longitude"]); $objLocation->setLocationProperty($locId, "latitude", $sa["latitude"]); $objLocation->setLocationProperty($locId, "timezone", $sa["timezone"]); $objLocation->setLocationProperty($locId, "country", $sa["country"]); } else { // Add the new site! $locId = $objLocation->addLocation($sa["name"], $sa["longitude"], $sa["latitude"], "", $sa["country"], $sa["timezone"], 0); $objDatabase->execSQL("update locations set observer = \"" . $_SESSION['deepskylog_id'] . "\" where id = \"" . $locId . "\";"); $objDatabase->execSQL("update locations set checked = \"0\" where id = \"" . $locId . "\";"); } $location = $locId; if (array_key_exists('weather', $sessionArray[$key])) { $weather = $sessionArray[$key]['weather']; } else { $weather = ""; } if (array_key_exists('equipment', $sessionArray[$key])) { $equipment = $sessionArray[$key]['equipment']; } else { $equipment = ""; } if (array_key_exists('comments', $sessionArray[$key])) { $comments = $sessionArray[$key]['comments']; } else { $comments = ""; } // $language $language = $sessionArray[$key]['lang']; // If the observers exist, add them to the session $observers = array(); if (array_key_exists('coObservers', $sessionArray[$key])) { for ($cnt = 0; $cnt < count($sessionArray[$key]['coObservers']); $cnt++) { $name = $observerArray[$sessionArray[$key]['coObservers'][$cnt]]['surname']; $firstname = $observerArray[$sessionArray[$key]['coObservers'][$cnt]]['name']; $foundUser = $objDatabase->selectRecordArray("SELECT * from observers where name = \"" . $name . "\" and firstname = \"" . $firstname . "\""); if (count($foundUser) > 0) { $observers[] = $foundUser['id']; } } } if ($sessionid == 0) { // Add new session $objSession->addSession("", $beginday, $beginmonth, $beginyear, $beginhours, $beginminutes, $endday, $endmonth, $endyear, $endhours, $endminutes, $location, $weather, $equipment, $comments, $language, $observers, 0); } else { // Adapt sessions $objSession->updateSession($sessionid, "", $sessionArray[$key]['begindate'], $sessionArray[$key]['enddate'], $location, $weather, $equipment, $comments, $language); } } // Check if there are observations for the given observer $searchNode = $dom->getElementsByTagName("observations"); $observation = $searchNode->item(0)->getElementsByTagName("observation"); foreach ($observation as $observation) { $siteValid = true; if ($observation->getElementsByTagName("site")->item(0)) { $observerid = $observation->getElementsByTagName("observer")->item(0)->nodeValue; if ($observerid == $id) { // Check if the site already exists in DeepskyLog $site = $siteArray[$observation->getElementsByTagName("site")->item(0)->nodeValue]["name"]; $sa = $siteArray[$observation->getElementsByTagName("site")->item(0)->nodeValue]; if (count($objDatabase->selectRecordArray("SELECT * from locations where observer = \"" . $_SESSION['deepskylog_id'] . "\" and name = \"" . $site . "\";")) > 0) { // Update the coordinates $run = $objDatabase->selectRecordset("SELECT id FROM locations WHERE observer = \"" . $_SESSION['deepskylog_id'] . "\" and name = \"" . $site . "\";"); $get = $run->fetch(PDO::FETCH_OBJ); $locId = $get->id; $objLocation->setLocationProperty($locId, "longitude", $sa["longitude"]); $objLocation->setLocationProperty($locId, "latitude", $sa["latitude"]); $objLocation->setLocationProperty($locId, "timezone", $sa["timezone"]); } else { // Add the new site! $locId = $objLocation->addLocation($sa["name"], $sa["longitude"], $sa["latitude"], "", $sa["country"], $sa["timezone"]); $objDatabase->execSQL("update locations set observer = \"" . $_SESSION['deepskylog_id'] . "\" where id = \"" . $locId . "\";"); } } else { $siteValid = false; } $instId = -1; // Check if the instrument already exists in DeepskyLog if ($observation->getElementsByTagName("scope")->item(0)) { $instrument = $scopeArray[$observation->getElementsByTagName("scope")->item(0)->nodeValue]["name"]; $ia = $scopeArray[$observation->getElementsByTagName("scope")->item(0)->nodeValue]; if (count($objDatabase->selectRecordArray("SELECT * from instruments where observer = \"" . $_SESSION['deepskylog_id'] . "\" and name = \"" . $instrument . "\";")) > 0) { // Update $instId = $objInstrument->getInstrumentId($ia["name"], $_SESSION['deepskylog_id']); $objInstrument->setInstrumentProperty($instId, "name", $ia["name"]); $objInstrument->setInstrumentProperty($instId, "diameter", $ia["diameter"]); $objInstrument->setInstrumentProperty($instId, "fd", $ia["fd"]); $objInstrument->setInstrumentProperty($instId, "type", $ia["type"]); $objInstrument->setInstrumentProperty($instId, "fixedMagnification", $ia["fixedMagnification"]); } else { // Add the new instrument! $instId = $objInstrument->addInstrument($ia["name"], $ia["diameter"], $ia["fd"], $ia["type"], $ia["fixedMagnification"], $_SESSION['deepskylog_id']); } } else { // No scope defined, so this is a naked eye observation $instrument = "Naked eye"; if (count($objDatabase->selectRecordArray("SELECT * from instruments where observer = \"" . $_SESSION['deepskylog_id'] . "\" and name = \"" . $instrument . "\";")) > 0) { $instId = $objInstrument->getInstrumentId($instrument, $_SESSION['deepskylog_id']); } else { // Add the new instrument! $instId = $objInstrument->addInstrument($instrument, 7, 1, 0, 1, $_SESSION['deepskylog_id']); } } // Filter is not mandatory if ($observation->getElementsByTagName("filter")->item(0)) { // Check if the filter already exists in DeepskyLog $filter = $filterArray[$observation->getElementsByTagName("filter")->item(0)->nodeValue]["name"]; $fa = $filterArray[$observation->getElementsByTagName("filter")->item(0)->nodeValue]; if (count($objDatabase->selectRecordArray("SELECT * from filters where observer = \"" . $_SESSION['deepskylog_id'] . "\" and name = \"" . $filter . "\";")) > 0) { // Update the filter $filtId = $objFilter->getFilterId($fa["name"], $_SESSION['deepskylog_id']); $objFilter->setFilterProperty($filtId, "name", $fa["name"]); $objFilter->setFilterProperty($filtId, "type", $fa["type"]); $objFilter->setFilterProperty($filtId, "color", $fa["color"]); $objFilter->setFilterProperty($filtId, "wratten", $fa["wratten"]); $objFilter->setFilterProperty($filtId, "schott", $fa["schott"]); } else { // Add the new filter! $filtId = $objFilter->addFilter($fa["name"], $fa["type"], $fa["color"], $fa["wratten"], $fa["schott"]); $objDatabase->execSQL("update filters set observer = \"" . $_SESSION['deepskylog_id'] . "\" where id = \"" . $filtId . "\";"); } } // Eyepiece is not mandatory if ($observation->getElementsByTagName("eyepiece")->item(0)) { // Check if the eyepiece already exists in DeepskyLog $eyepiece = $eyepieceArray[$observation->getElementsByTagName("eyepiece")->item(0)->nodeValue]["name"]; $ea = $eyepieceArray[$observation->getElementsByTagName("eyepiece")->item(0)->nodeValue]; if (count($objDatabase->selectRecordArray("SELECT * from eyepieces where observer = \"" . $_SESSION['deepskylog_id'] . "\" and name = \"" . $ea["name"] . "\";")) > 0) { // Update the eyepiece $eyepId = $objEyepiece->getEyepieceId($ea["name"], $_SESSION['deepskylog_id']); $objEyepiece->setEyepieceProperty($eyepId, "name", $ea["name"]); $objEyepiece->setEyepieceProperty($eyepId, "focalLength", $ea["focalLength"]); $objEyepiece->setEyepieceProperty($eyepId, "apparentFOV", $ea["apparentFOV"]); $objEyepiece->setEyepieceProperty($eyepId, "maxFocalLength", $ea["maxFocalLength"]); } else { // Add the new eyepiece! $eyepId = $objEyepiece->addEyepiece($ea["name"], $ea["focalLength"], $ea["apparentFOV"]); $objDatabase->execSQL("update eyepieces set observer = \"" . $_SESSION['deepskylog_id'] . "\" where id = \"" . $eyepId . "\";"); $objEyepiece->setEyepieceProperty($eyepId, "maxFocalLength", $ea["maxFocalLength"]); } } // Lens is not mandatory if ($observation->getElementsByTagName("lens")->item(0)) { // Check if the eyepiece already exists in DeepskyLog $lens = $lensArray[$observation->getElementsByTagName("lens")->item(0)->nodeValue]["name"]; $la = $lensArray[$observation->getElementsByTagName("lens")->item(0)->nodeValue]; if (count($objDatabase->selectRecordArray("SELECT * from lenses where observer = \"" . $_SESSION['deepskylog_id'] . "\" and name = \"" . $lens . "\";")) > 0) { // Update the lens $lensId = $objLens->getLensId($la["name"], $_SESSION['deepskylog_id']); $objLens->setLensProperty($lensId, "name", $la["name"]); $objLens->setLensProperty($lensId, "factor", $la["factor"]); } else { // Add the new lens! $lensId = $objLens->addLens($la["name"], $la["factor"]); $objDatabase->execSQL("update lenses set observer = \"" . $_SESSION['deepskylog_id'] . "\" where id = \"" . $lensId . "\";"); } } // Object!!! $target = $targetArray[$observation->getElementsByTagName("target")->item(0)->nodeValue]["name"]; $ta = $targetArray[$observation->getElementsByTagName("target")->item(0)->nodeValue]; if ($ta["valid"] && $siteValid) { if ($ta["known"] == 1) { $pattern = '/([A-Za-z]+)([\\d\\D\\w]*)/'; $targetName = preg_replace($pattern, '${1} ${2}', $target); $targetName = str_replace(" ", " ", $targetName); $objeId = -1; // Check if the object with the given name exists. If this is the case, set the objeId, else check the alternative names $targetName = $objCatalog->checkObject($targetName); if (count($objDatabase->selectRecordArray("SELECT objectnames.objectname FROM objectnames WHERE (objectnames.altname = \"" . $targetName . "\");")) > 0) { $objeId = $objObject->getDsObjectName($targetName); } else { // Object with the given name does not exist... Check if the name is an alternative name for ($i = 0; $i < sizeof($ta["aliases"]); $i++) { $targetName = preg_replace($pattern, '${1} ${2}', $ta["aliases"]["alias" . $i]); $targetName = str_replace(" ", " ", $targetName); $targetName = $objCatalog->checkObject($targetName); if (count($objDatabase->selectRecordArray("SELECT objectnames.objectname FROM objectnames WHERE (objectnames.altname = \"" . $targetName . "\")")) > 0) { $objeId = $objObject->getDsObjectName($targetName); } } if ($objeId == -1) { // Object does not exist (name or alternative name) // Check for the type and coordinates. If there is already an object at the same coordinates with the same type, add the alternative name if (count($objDatabase->selectRecordArray("SELECT name FROM objects WHERE ra > " . ($ta["ra"] - 0.0001) . " and ra < " . ($ta["ra"] + 0.0001) . " and decl > " . ($ta["dec"] - 0.0001) . " and decl < " . ($ta["dec"] + 0.0001) . " and type = \"" . $ta["type"] . "\"")) > 0) { $run = $objDatabase->selectRecordset("SELECT name FROM objects WHERE ra > " . ($ta["ra"] - 0.0001) . " and ra < " . ($ta["ra"] + 0.0001) . " and decl > " . ($ta["dec"] - 0.0001) . " and decl < " . ($ta["dec"] + 0.0001) . " and type = \"" . $ta["type"] . "\""); $get = $run->fetch(PDO::FETCH_OBJ); $objeId = $get->name; // Also add alternative name to the existing object. $names = explode(" ", $objeId); $aliasNames = explode(" ", $targetName); $objObject->newAltName($names[0] . " " . $names[1], $aliasNames[0], $aliasNames[1]); } else { // else, add new object $targetName = preg_replace($pattern, '${1} ${2}', $target); $targetName = str_replace(" ", " ", $targetName); $targetName = $objCatalog->checkObject($targetName); $names = explode(" ", $targetName); $objObject->addDSObject($names[0] . " " . $names[1], $names[0], $names[1], $ta["type"], $ta["constellation"], $ta["ra"], $ta["dec"], $ta["mag"], $ta["subr"], $ta["diam1"], $ta["diam2"], $ta["pa"], $ta["datasource"]); for ($i = 0; $i < sizeof($ta["aliases"]); $i++) { $aliasName = preg_replace($pattern, '${1} ${2}', $ta["aliases"]["alias" . $i]); $aliasNames = explode(" ", $aliasName); $objObject->newAltName($names[0] . " " . $names[1], $aliasNames[0], $aliasNames[1]); } $objeId = $objObject->getDsObjectName($targetName); $body = LangValidateAccountEmailTitleObject . " <a href=\"http://www.deepskylog.org/index.php?indexAction=detail_object&object=" . urlencode($targetName) . "\">" . $targetName . "</a> " . LangValidateAccountEmailTitleObject2 . " " . LangValidateAccountEmailTitleObjectObserver . " <a href=\"http://www.deepskylog.org/index.php?indexAction=detail_observer&user="******"\">" . $objObserver->getObserverProperty($loggedUser, 'firstname') . " " . $objObserver->getObserverProperty($loggedUser, 'name') . "</a>.<br /><br />"; if (isset($developversion) && $developversion == 1) { $entryMessage .= "On the live server, a mail would be sent with the subject: " . $subject . ".<br />"; } else { $objMessage->sendEmail(LangValidateAccountEmailTitleObject . " " . $targetName . LangValidateAccountEmailTitleObject2, $body, "developers"); } } } } // Check if the observation already exists! $dateArray = sscanf($observation->getElementsByTagName("begin")->item(0)->nodeValue, "%4d-%2d-%2dT%2d:%2d:%2d%c%02d:%02d"); $date = mktime($dateArray[3], $dateArray[4], 0, $dateArray[1], $dateArray[2], $dateArray[0]); if ($dateArray[6] == "-") { $timeDiff = -($dateArray[7] * 60 + $dateArray[8]) * 60.0; } else { $timeDiff = ($dateArray[7] * 60 + $dateArray[8]) * 60.0; } // Get the time and date in UT. $date = $date - $timeDiff; $dateStr = date("Ymd", $date); $timeStr = date("Hi", $date); if ($instId > 1) { // Check if the observation does already exist $obsId = $objDatabase->selectRecordArray("SELECT id from observations WHERE objectname = \"" . $objeId . "\" and date = \"" . $dateStr . "\" and instrumentid = \"" . $instId . "\" and locationId = \"" . $locId . "\" and observerid = \"" . $_SESSION['deepskylog_id'] . "\";"); if (count($obsId) > 0) { // TODO : Adapt observation } else { // New observation $resultNode = $observation->getElementsByTagName("result")->item(0); if ($resultNode->getElementsByTagName("description")->item(0)) { $description = $resultNode->getElementsByTagName("description")->item(0)->nodeValue; } else { $description = ""; } // Seeing is not mandatory if ($observation->getElementsByTagName("seeing")->item(0)) { $seeing = $observation->getElementsByTagName("seeing")->item(0)->nodeValue; } else { $seeing = "-1"; } // Limiting magnitude is not mandatory if ($observation->getElementsByTagName("faintestStar")->item(0)) { $limmag = $observation->getElementsByTagName("faintestStar")->item(0)->nodeValue; } else { $limmag = ""; } if ($resultNode->hasAttribute("lang")) { $language = $resultNode->getAttribute("lang"); } else { $language = "en"; } // Rating is not mandatory if ($resultNode->getElementsByTagName("rating")->item(0)) { $visibility = $resultNode->getElementsByTagName("rating")->item(0)->nodeValue; } else { $visibility = 0; } if ($visibility == 99) { $visibility = 0; } if ($observation->getElementsByTagName("eyepiece")->item(0)) { $ei = $eyepId; } else { $ei = 0; } if ($observation->getElementsByTagName("filter")->item(0)) { $fi = $filtId; } else { $fi = 0; } if ($observation->getElementsByTagName("lens")->item(0)) { $li = $lensId; } else { $li = 0; } $obsId = $objObservation->addDSObservation2($objeId, $_SESSION['deepskylog_id'], $instId, $locId, $dateStr, $timeStr, $description, $seeing, $limmag, $visibility, $language, $ei, $fi, $li); $obsId = $objDatabase->selectSingleValue("SELECT id FROM observations ORDER BY id DESC LIMIT 1", 'id'); // Add the observation to the session $objSession->addObservationToSessions($obsId); // Magnification is not mandatory if ($observation->getElementsByTagName("magnification")->item(0)) { $objObservation->setDsObservationProperty($obsId, "magnification", $observation->getElementsByTagName("magnification")->item(0)->nodeValue); } // Sqm is not mandatory if ($observation->getElementsByTagName("sky-quality")->item(0)) { // Get sqm value and convert it $unit = $observation->getElementsByTagName("sky-quality")->item(0)->getAttribute("unit"); if ($unit == "mags-per-squarearcmin") { $sqm = $observation->getElementsByTagName("sky-quality")->item(0)->nodeValue + 8.890000000000001; } else { $sqm = $observation->getElementsByTagName("sky-quality")->item(0)->nodeValue; } $objObservation->setDsObservationProperty($obsId, "SQM", $sqm); } // The result of the observation! $resultNode = $observation->getElementsByTagName("result")->item(0); // colorContrasts is not mandatory if ($resultNode->hasAttribute("colorContrasts")) { if ($resultNode->getAttribute("colorContrasts") == "true") { $colorContrast = 1; } else { $colorContrast = 0; } } else { $colorContrast = -1; } $objObservation->setDsObservationProperty($obsId, "colorContrasts", $colorContrast); // extended is not mandatory if ($resultNode->hasAttribute("extended")) { if ($resultNode->getAttribute("extended") == "true") { $extended = 1; } else { $extended = 0; } } else { $extended = -1; } $objObservation->setDsObservationProperty($obsId, "extended", $extended); // mottled is not mandatory if ($resultNode->hasAttribute("mottled")) { if ($resultNode->getAttribute("mottled") == "true") { $mottled = 1; } else { $mottled = 0; } } else { $mottled = -1; } $objObservation->setDsObservationProperty($obsId, "mottled", $mottled); // resolved is not mandatory if ($resultNode->hasAttribute("resolved")) { if ($resultNode->getAttribute("resolved") == "true") { $resolved = 1; } else { $resolved = 0; } } else { $resolved = -1; } $objObservation->setDsObservationProperty($obsId, "resolved", $resolved); // stellar is not mandatory if ($resultNode->hasAttribute("stellar")) { if ($resultNode->getAttribute("stellar") == "true") { $stellar = 1; } else { $stellar = 0; } } else { $stellar = -1; } $objObservation->setDsObservationProperty($obsId, "stellar", $stellar); // unusualShape is not mandatory if ($resultNode->hasAttribute("unusualShape")) { if ($resultNode->getAttribute("unusualShape") == "true") { $unusualShape = 1; } else { $unusualShape = 0; } } else { $unusualShape = -1; } $objObservation->setDsObservationProperty($obsId, "unusualShape", $unusualShape); // partlyUnresolved is not mandatory if ($resultNode->hasAttribute("partlyUnresolved")) { if ($resultNode->getAttribute("partlyUnresolved") == "true") { $partlyUnresolved = 1; } else { $partlyUnresolved = 0; } } else { $partlyUnresolved = -1; } $objObservation->setDsObservationProperty($obsId, "partlyUnresolved", $partlyUnresolved); // equalBrightness is not mandatory if ($resultNode->hasAttribute("equalBrightness")) { if ($resultNode->getAttribute("equalBrightness") == "true") { $equalBrightness = 1; } else { $equalBrightness = 0; } } else { $equalBrightness = -1; } $objObservation->setDsObservationProperty($obsId, "equalBrightness", $equalBrightness); // niceSurrounding is not mandatory if ($resultNode->hasAttribute("niceSurrounding")) { if ($resultNode->getAttribute("niceSurrounding") == "true") { $niceSurrounding = 1; } else { $niceSurrounding = 0; } } else { $niceSurrounding = -1; } $objObservation->setDsObservationProperty($obsId, "nicefield", $niceSurrounding); // colorMain is not mandatory if ($resultNode->getElementsByTagName("colorMain")->item(0)) { $color1 = $resultNode->getElementsByTagName("colorMain")->item(0)->nodeValue; if ($color1 == "White" || $color1 == "white") { $col1 = 1; } if ($color1 == "Red" || $color1 == "red") { $col1 = 2; } if ($color1 == "Orange" || $color1 == "orange") { $col1 = 3; } if ($color1 == "Yellow" || $color1 == "yellow") { $col1 = 4; } if ($color1 == "Green" || $color1 == "green") { $col1 = 5; } if ($color1 == "Blue" || $color1 == "blue") { $col1 = 6; } $objObservation->setDsObservationProperty($obsId, "component1", $col1); } // colorCompanion is not mandatory if ($resultNode->getElementsByTagName("colorCompanion")->item(0)) { $color2 = $resultNode->getElementsByTagName("colorCompanion")->item(0)->nodeValue; if ($color2 == "White" || $color2 == "white") { $col2 = 1; } if ($color2 == "Red" || $color2 == "red") { $col2 = 2; } if ($color2 == "Orange" || $color2 == "orange") { $col2 = 3; } if ($color2 == "Yellow" || $color2 == "yellow") { $col2 = 4; } if ($color2 == "Green" || $color2 == "green") { $col2 = 5; } if ($color2 == "Blue" || $color2 == "blue") { $col2 = 6; } $objObservation->setDsObservationProperty($obsId, "component2", $col2); } // Character is not mandatory if ($resultNode->getElementsByTagName("character")->item(0)) { $objObservation->setDsObservationProperty($obsId, "clusterType", $resultNode->getElementsByTagName("character")->item(0)->nodeValue); } // smallDiameter is not mandatory if ($resultNode->getElementsByTagName("smallDiameter")->item(0)) { $unit = $resultNode->getElementsByTagName("smallDiameter")->item(0)->getAttribute("unit"); if ($unit == "deg") { $smallDiameter = $resultNode->getElementsByTagName("smallDiameter")->item(0)->nodeValue * 3600.0; } else { if ($unit == "rad") { $smallDiameter = Rad2Deg($resultNode->getElementsByTagName("smallDiameter")->item(0)->nodeValue) * 3600.0; } else { if ($unit == "arcmin") { $smallDiameter = $resultNode->getElementsByTagName("smallDiameter")->item(0)->nodeValue * 60.0; } else { if ($unit == "arcsec") { $smallDiameter = $resultNode->getElementsByTagName("smallDiameter")->item(0)->nodeValue; } } } } $objObservation->setDsObservationProperty($obsId, "smallDiameter", $smallDiameter); } // largeDiameter is not mandatory if ($resultNode->getElementsByTagName("largeDiameter")->item(0)) { $unit = $resultNode->getElementsByTagName("largeDiameter")->item(0)->getAttribute("unit"); if ($unit == "deg") { $largeDiameter = $resultNode->getElementsByTagName("largeDiameter")->item(0)->nodeValue * 3600.0; } else { if ($unit == "rad") { $largeDiameter = Rad2Deg($resultNode->getElementsByTagName("largeDiameter")->item(0)->nodeValue) * 3600.0; } else { if ($unit == "arcmin") { $largeDiameter = $resultNode->getElementsByTagName("largeDiameter")->item(0)->nodeValue * 60.0; } else { if ($unit == "arcsec") { $largeDiameter = $resultNode->getElementsByTagName("largeDiameter")->item(0)->nodeValue; } } } } $objObservation->setDsObservationProperty($obsId, "largeDiameter", $largeDiameter); } if ($observation->getElementsByTagName("magnification")->item(0)) { $objObservation->setDsObservationProperty($obsId, "magnification", $observation->getElementsByTagName("magnification")->item(0)->nodeValue); } } } } } } } } else { $entryMessage .= LangXMLError3; $_GET['indexAction'] = "add_xml"; return; } }
<?php // načtení dokumentu XML $xml = new DomDocument(); $xml->load("objednavka.xml"); //validace za použití konkrétního souboru se XML schématem; //pokud by schéma bylo v RelaxNG, je možné využít funkci $xml->relaxNGValidate(file) //pokud bychom nechtěli schéma načítat ze souboru, ale měli jej jako řetězec, použijeme funkci $xml->schemaValidateSource(schemaStr) $result = $xml->schemaValidate('objednavka.xsd'); if ($result) { echo 'Dokument je validní.'; } else { echo 'Dokument není validní'; }
public function testBuild() { $this->if($adapter = new atoum\test\adapter())->and($adapter->extension_loaded = true)->and($adapter->get_class = $class = 'class')->and($runner = new atoum\runner())->and($score = new runner\score())->and($report = $this->newTestedInstance($adapter))->and($runner->setScore($score))->and($testScore = new atoum\test\score())->and($testScore->addPass())->and($test = new \mock\mageekguy\atoum\test())->and($test->getMockController()->getCurrentMethod[1] = $method = 'method')->and($test->getMockController()->getCurrentMethod[2] = $otherMethod = 'otherMethod')->and($test->getMockController()->getCurrentMethod[3] = $thirdMethod = 'thirdMethod')->and($test->setScore($testScore))->and($path = join(DIRECTORY_SEPARATOR, array(__DIR__, 'resources')))->and($testScore->addDuration('foo', $class, $method, $duration = 1))->and($testScore->addUncompletedMethod(uniqid(), $class, $otherMethod, $exitCode = 1, $output = 'output'))->and($testScore->addSkippedMethod(uniqid(), $class, $thirdMethod, $line = rand(1, PHP_INT_MAX), $message = 'message'))->and($report->handleEvent(atoum\test::afterTestMethod, $test))->and($testScore->addPass())->and($testScore->addPass())->and($report->handleEvent(atoum\test::afterTestMethod, $test))->and($report->handleEvent(atoum\test::afterTestMethod, $test))->and($score->merge($testScore))->and($report->handleEvent(atoum\runner::runStop, $runner))->then->castToString($report)->isEqualToContentsOfFile(join(DIRECTORY_SEPARATOR, array($path, '1.xml')))->object($dom = new \DomDocument())->boolean($dom->loadXML((string) $report))->isTrue()->boolean($dom->schemaValidate(join(DIRECTORY_SEPARATOR, array($path, 'xunit.xsd'))))->isTrue(); }
function validateXML($xml, $schema_file) { Debug::text('Schema File: ' . $schema_file, __FILE__, __LINE__, __METHOD__, 10); if (class_exists('DomDocument') and file_exists($schema_file)) { libxml_use_internal_errors(TRUE); $dom = new DomDocument(); $dom->loadXML($xml); if ($dom->schemaValidate($schema_file)) { Debug::Text('Schema is valid!', __FILE__, __LINE__, __METHOD__, 10); return TRUE; } else { Debug::Text('Schema is NOT valid!', __FILE__, __LINE__, __METHOD__, 10); $errors = libxml_get_errors(); foreach ($errors as $error) { Debug::Text('XML Error (Line: ' . $error->line . '): ' . $error->message, __FILE__, __LINE__, __METHOD__, 10); } return array('api_retval' => FALSE, 'api_details' => array('code' => 'VALIDATION', 'description' => $error->message)); //return FALSE; } } else { Debug::Text('DomDocument not available!', __FILE__, __LINE__, __METHOD__, 10); return TRUE; } return FALSE; }
/** * Update a DOI * * @return boolean */ public function update($doi = NULL, $sendXml = false) { $doi = $doi ? $doi : $this->get('doi'); if (!$doi) { $this->setError(Lang::txt('COM_PUBLICATIONS_ERROR_DOI_UPDATE_NO_HANDLE')); return false; } if (!$this->on()) { $this->setError(Lang::txt('COM_PUBLICATIONS_ERROR_DOI_NO_SERVICE')); return false; } // Check that we are trying to update a DOI issued by the hub if (!preg_match("/" . $this->_configs->shoulder . "/", $doi)) { return false; } $input = $this->startInput(); if (!$input) { // Cannot procees if any required fields are missing return false; } // Are we sending extended data? if ($sendXml == true && $doi) { $xml = $this->buildXml($doi); // Load the xml document in the DOMDocument object $xdoc = new \DomDocument(); $xdoc->loadXML($xml); // Validate against schema if (!$xdoc->schemaValidate($this->_configs->xmlSchema)) { $this->setError(Lang::txt('COM_PUBLICATIONS_ERROR_DOI_XML_INVALID')); } else { // Append XML $input .= 'datacite: ' . strtr($xml, array(":" => "%3A", "%" => "%25", "\n" => "%0A", "\r" => "%0D")) . "\n"; } } // Get service call $url = $this->getServicePath($doi); // Make service call $result = $this->runCurl($url, $input); return $result ? $result : false; }
$dom->loadXML(str_replace(array("\n", "\r"), "", utf8_encode($xml->asXML()))); fwrite($toot, ($dom->saveXML())); */ // Kirjoitetaaan XML ja tehdään UTF8 encode fwrite($toot, str_replace(chr(10), "", utf8_encode($xml->asXML()))); fclose($toot); // Tehdään vielä tässä vaiheessa XML validointi, vaikka ainesto onkin jo tehty. :( libxml_use_internal_errors(true); $xml_virheet = ""; $xml_domdoc = new DomDocument(); $xml_file = $pankkitiedostot_polku . $kaunisnimi; $xml_schema = "{$pupe_root_polku}/datain/pain.001.001.02.xsd"; // Tämä tiedosto lähetetään pankkiin! $pankkiyhteys_tiedosto = $kaunisnimi; $xml_domdoc->Load($xml_file); if (!$xml_domdoc->schemaValidate($xml_schema)) { echo "<font class='message'>SEPA-aineistosta löytyi vielä seuraavat virheet, aineisto saattaa hylkääntyä pankissa!</font><br><br>"; $all_errors = libxml_get_errors(); foreach ($all_errors as $error) { echo "<font class='info'>{$error->message}</font><br>"; $xml_virheet .= "{$error->message}\n"; } echo "<br>"; // Lähetetään viesti adminille! mail($yhtiorow['admin_email'], mb_encode_mimeheader($yhtiorow['nimi'] . " - SEPA Error", "ISO-8859-1", "Q"), $xml_virheet . "\n", "From: " . mb_encode_mimeheader($yhtiorow["nimi"], "ISO-8859-1", "Q") . " <{$yhtiorow['postittaja_email']}>\n", "-f {$yhtiorow['postittaja_email']}"); } echo "<tr><th>" . t("Tallenna aineisto") . "</th>"; echo "<form method='post' class='multisubmit'>"; echo "<input type='hidden' name='tee' value='lataa_tiedosto'>"; echo "<input type='hidden' name='kaunisnimi' value='{$kaunisnimi}'>"; if ($tee == "KIRJOITAKOPIO") {
/** * Register a DOI * * @param array $authors Authors of a resource * @param object $config Parameter * @param array $metadata Metadata * @param string &$doierr Container for error messages * @return mixed False if error, string on success */ public function registerDOI($authors, $config, $metadata = array(), &$doierr = '') { if (empty($metadata)) { return false; } // Get configs $shoulder = $config->get('doi_shoulder'); $service = $config->get('doi_newservice'); $prefix = $config->get('doi_newprefix'); $userpw = $config->get('doi_userpw'); $xmlschema = trim($config->get('doi_xmlschema', 'http://schema.datacite.org/meta/kernel-2.1/metadata.xsd'), DS); $handle = ''; $doi = ''; if (!$shoulder || !$service) { $doierr .= 'Missing DOI configuration'; return false; } // Collect metadata $metadata['publisher'] = htmlspecialchars($config->get('doi_publisher', \Config::get('sitename'))); $metadata['pubYear'] = isset($metadata['pubYear']) ? $metadata['pubYear'] : date('Y'); $metadata['language'] = 'en'; // Clean up paths if (substr($service, -1, 1) == DS) { $service = substr($service, 0, strlen($service) - 1); } if (substr($shoulder, -1, 1) == DS) { $shoulder = substr($shoulder, 0, strlen($shoulder) - 1); } // Make service path $call = $service . DS . 'shoulder' . DS . 'doi:' . $shoulder; $call .= $prefix ? DS . $prefix : DS; // Get config $live_site = rtrim(\Request::base(), '/'); if (!$live_site || !isset($metadata['targetURL']) || !isset($metadata['title'])) { $doierr .= 'Missing url, title or live site configuration'; return false; } // Get first author / creator name if ($authors && count($authors) > 0) { $creatorName = $authors[0]->name; } else { $creatorName = \User::get('name'); } // Format name $nameParts = explode(" ", $creatorName); $metadata['creator'] = end($nameParts); $metadata['creator'] .= count($nameParts) > 1 ? ', ' . $nameParts[0] : ''; // Start input $input = "_target: " . $metadata['targetURL'] . "\n"; $input .= "datacite.creator: " . $metadata['creator'] . "\n"; $input .= "datacite.title: " . $metadata['title'] . "\n"; $input .= "datacite.publisher: " . $metadata['publisher'] . "\n"; $input .= "datacite.publicationyear: " . $metadata['pubYear'] . "\n"; $input .= "datacite.resourcetype: Software" . "\n"; $input .= "_profile: datacite"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $call); curl_setopt($ch, CURLOPT_USERPWD, $userpw); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/plain; charset=UTF-8', 'Content-Length: ' . strlen($input))); curl_setopt($ch, CURLOPT_POSTFIELDS, $input); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $output = curl_exec($ch); /*returns HTTP Code for success or fail */ $success = curl_getinfo($ch, CURLINFO_HTTP_CODE); if ($success === 201) { $out = explode('/', $output); $handle = trim(end($out)); } else { if (empty($output)) { $doierr = "{$success}: " . curl_error($ch); } else { $doierr = "{$success}: " . $output; } $doierr .= ' ' . $call; $handle = 0; } $handle = strtoupper($handle); $doi = $shoulder . DS . $handle; curl_close($ch); // Prepare XML data if ($handle) { $xdoc = new \DomDocument(); $xmlfile = $this->getXml($authors, $metadata, $doi); //Load the xml document in the DOMDocument object $xdoc->loadXML($xmlfile); //Validate the XML file against the schema if ($xdoc->schemaValidate($xmlschema)) { /*EZID parses text received based on new lines. */ $input = "_target: " . $metadata['targetURL'] . "\n"; $input .= "datacite.creator: " . $metadata['creator'] . "\n"; $input .= "datacite.title: " . $metadata['title'] . "\n"; $input .= "datacite.publisher: " . $metadata['publisher'] . "\n"; $input .= "datacite.publicationyear: " . $metadata['pubYear'] . "\n"; $input .= "datacite.resourcetype: Software" . "\n"; $input .= "_profile: datacite" . "\n"; /*colons(:),percent signs(%),line terminators(\n),carriage returns(\r) are percent encoded for given input string */ $input .= 'datacite: ' . strtr($xmlfile, array(":" => "%3A", "%" => "%25", "\n" => "%0A", "\r" => "%0D")) . "\n"; // Make service path $call = $service . DS . 'id' . DS . 'doi:' . $doi; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $call); curl_setopt($ch, CURLOPT_USERPWD, $userpw); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/plain; charset=UTF-8', 'Content-Length: ' . strlen($input))); curl_setopt($ch, CURLOPT_POSTFIELDS, $input); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $output = curl_exec($ch); curl_close($ch); } else { $doierr .= "XML is invaild. DOI has been created but unable to upload XML as it is invalid. Please modify the created DOI with a valid XML .\n"; } } return $handle ? $handle : NULL; }
/** * Validates the current document against an XML schema, * optionally validates embedded Schematron rules too. * * \param string $filename * Path to the XML schema to use for validation. * * \param bool $schematron * (optional) Whether embedded Schematron rules * should be validated too (\b true) or not (\b false). * The default is to also do $schematron validation. * * \retval bool * \b true if the document validates, * \b false otherwise. */ public function schemaValidate($filename, $schematron = true) { $success = parent::schemaValidate($filename); return $this->schematronValidation('file', $filename, 'XSD', $success, $schematron); }
/** * Short description of method validate * * @access public * @author firstname and lastname of author, <*****@*****.**> * @param string * @return boolean */ public function validate($schema) { $returnValue = (bool) false; $myDocument = new DomDocument(); if (!$myDocument->load($this->filepath)) { common_Logger::d('Error Loading Document', array('ImportCapi')); return false; } libxml_use_internal_errors(true); if (!$myDocument->schemaValidate($schema)) { $errors = libxml_get_last_error(); common_Logger::d('Error Parsing Document', array('ImportCapi')); $returnValue = false; common_Logger::d($errors->message, array('ImportCapi')); print_r($errors); $this->validationError = $errors->message; } else { $returnValue = true; $this->isValidated = true; } return (bool) $returnValue; }
/** * Checks whether the file is valid according to an XML schema. * * @Then /^the file "([^"]+)" should be a valid document according to "([^"]+)"$/ * * @param string $xmlFile * @param string $schemaPath relative to features/bootstrap/schema */ public function xmlShouldBeValid($xmlFile, $schemaPath) { $dom = new DomDocument(); $dom->load($this->workingDir . '/' . $xmlFile); $dom->schemaValidate(__DIR__ . '/schema/' . $schemaPath); }
<?php $xdoc = new DomDocument(); $xmlfile = '../examples/service.xml'; $xmlschema = './xrdl.xsd'; //Load the xml document in the DOMDocument object $xdoc->Load($xmlfile); //Validate the XML file against the schema if ($xdoc->schemaValidate($xmlschema)) { print "{$xmlfile} is valid.\n"; } else { print "{$xmlfile} is invalid.\n"; }
function axml2xslt_transform(&$row, &$params, $page) { // funkce pluginu jako takoveho, zadava se do $mainframe $style_directory = get_parameter("style_directory"); // parametr adresare se styly if (JPATH_BASE == JPATH_ADMINISTRATOR) { //zjistdz?me, jestli jsme v administraci a pokud ano, pdz?evedeme cestu na adresovdz?ndz? frontendu $style_directory = '../' . $style_directory; } $default_style = get_parameter("default_style"); // defaultni styl ktery se nastavuje v params $schema_validation = get_parameter("schema_validation"); // bude slouzit pro validaci dokumentu $validation_matters = get_parameter("validation_matters"); // zalezi na validaci? // parametry definovandz? ---> jsou to ty parametry u toho nastaveni pluginu $chyba = false; // tak tohle uz je doufam standardni zalezitost, pokud bude true, neprojde transformem $nekontrolovat_file = false; // overeni zda je to opravdu XML -> prichazi zde if (substr($row->text, 0, 5) == "<?xml") { // mame se tim vubec zatezovat? if (empty($style_directory)) { // pokud je vyplneny $chyba = true; $row->text = zapis_error($row->text, "Adresar se styly musi byt nastaven!<br>"); } else { // dodelat na konec lomitko if (eregi("\\\\", $style_directory)) { //kdyby tam byly ty idiotsky druhy lomitka $style_directory = str_replace("\\\\", "/", $style_directory); // tady se odstranuji } if (substr($style_directory, strlen($style_directory) - 1, 1) != "/") { //dodelani lomitka nakonec $style_directory = $style_directory . "/"; //pridani lomitka pokud tam neni } } if (eregi("http://", $style_directory) || eregi("http://", $default_style)) { $chyba = true; $row->text = zapis_error($row->text, "Styl ani adresar nesmi byt na jinem serveru!<br>"); } if (!file_exists($style_directory)) { $chyba = true; // pokud ten adresar neexistuje, tak to dame userovi vedet $row->text = zapis_error($row->text, "Adresar se styly je nastaven ale na serveru neexistuje!<br>"); } if (stripos($row->text, "<?xml-stylesheet") !== false) { //je v souboru deklarace toho souboru? $text2 = vypreparuj_data("<?xml-stylesheet", "?>", $row->text); $text = vypreparuj_data('href="', '"', $text2); //nj uvozovky uvozovky if (empty($text)) { $text = vypreparuj_data("href='", "'", $text2); // dalsi cek, pokud je prazdno } $text = basename($text); $style_file = $style_directory . $text; // takze slozeni souboru z filu, kdyz je tam ta stylesheet } else { if (empty($default_style)) { // neni defaultni styl ani nastavena transformace, nic tedy nedelej $chyba = true; // neni default styl, neni ani neni deklarace ve filu $nekontrolovat_file = true; } else { //neni nastaveny styl, ale je defaultni, tak tedy pouzij ten $style_file = $style_directory . $default_style; // pro kontrolu zda soubor existuje } if ($nekontrolovat_file === false) { if (!file_exists($style_file)) { // existuje ten soubor se stylem? $chyba = true; // nepusti dal, a vyhodi chybu pokud soubor se stylem neexistuje $row->text = zapis_error($row->text, "Soubor ({$style_file}) s definovanym stylem neexistuje!<br>"); } $file_extension = end(explode(".", $style_file)); if ($file_extension != "xsl") { $chyba = true; $row->text = zapis_error($row->text, "Soubor obsahujici xsl data musi mit koncovku .xsl! Tento soubor ma koncovku .{$file_extension}.<br>"); } } if ($chyba === false) { // vse je ok, probiha transformace $transform = true; $xp = new XsltProcessor(); // create a DOM document and load the XSL stylesheet $f = fopen($style_file, "r"); //otevrit soubor $file_data = fread($f, filesize($style_file)); //precist ho a vzit si data (nacteni do pameti) $xsl = new DomDocument(); // primo vlozeny XSL kod (je to o neco rychlejsi ac se musi udelat vic operaci) set_error_handler('handle_xsl_error'); //kvuli errorum (jsou tu spatne vyreseny) $xsl->loadXML($file_data); restore_error_handler(); // nastaveni erroru zpet, kvuli rychlosti provadeni //$row->text = zapis_error($row->text,"XSL kod neni v poradku.<br>"); // nacteni stylesheetu do dokumentu if ($GLOBALS["xsl_code_error"] == 1) { $transform = false; $row->text = zapis_error($row->text, "XSL kod neni v poradku.<br>"); } else { $xp->importStylesheet($xsl); } // docasny DOM dokument s primo vlozenejma datama k transformaci $xml_document = new DomDocument(); set_error_handler('handle_xml_error'); //kvuli errorum (jsou tu spatne vyreseny) $xml_document->loadXML($row->text); restore_error_handler(); // nastaveni erroru zpet, kvuli rychlosti provadeni if ($GLOBALS["xml_code_error"] == 1) { $transform = false; $row->text = zapis_error($row->text, "XML kod neni v poradku.<br>"); } libxml_use_internal_errors(true); if (!empty($schema_validation)) { if (!file_exists($style_directory . $schema_validation)) { $transform = false; $row->text = zapis_error($row->text, "Soubor se schdz?matem neexistuje.<br>"); } else { if (!$xml_document->schemaValidate($style_directory . $schema_validation)) { if ($validation_matters == 1) { $transform = false; $row->text = zapis_error($row->text, "XML dokument neni validni, transformace neprobehla.<br>"); //$row->text = zapis_error($row->text,libxml_display_errors()); } else { $GLOBALS["validation_error"] = 1; } } } } //nahozeni parametru dulezitych k transformaci (zavedeni namespacu) $xp->setParameter($namespace, 'id1', 'value1'); $xp->setParameter($namespace, 'id2', 'value2'); //transformace jako takovdz? se vsemi daty, ktera jsou zapotrebi if ($transform === true) { if ($html = $xp->transformToXML($xml_document)) { $row->text = $html; //nasazeni toho pretransformovaneho textu misto puvodniho xml filu if ($GLOBALS["validation_error"] == 1) { // nebyla nahodou chyba pri validaci, na ktere ale tolik nezalezi? $row->text = zapis_error($row->text, "XML dokument neni validni podle \"{$schema_validation}\", ale transformace probehla<br>"); $GLOBALS["validation_error"] = 0; } } else { $row->text = zapis_error($row->text, "Transformace XML souboru se nezdarila!<br>"); //nejaka neznama chyba pri transformaci -> to se uz bohuzel skriptem neda ovlivnit } } else { $GLOBALS["xml_code_error"] = 0; //kvuli tomu aby to pri pristim projiti, pokud nebude chyba pustilo transformaci neceho jinyho $GLOBALS["xsl_code_error"] = 0; //kvuli tomu aby to pri pristim projiti, pokud nebude chyba pustilo transformaci neceho jinyho } } } } }
/** * Static helper function to validate document against a schema * @param string * @param string * @param boolean */ public static function validate($xml, $schema, $relax = false) { $doc = new \DomDocument(); set_error_handler(function ($errNo, $errMsg) { restore_error_handler(); $errMsg = preg_replace('#^.*error :#', '', $errMsg); throw new DOMException($errMsg); }); $doc->loadXML($xml); $validation = $relax ? $doc->relaxNGValidate($schema) : $doc->schemaValidate($schema); restore_error_handler(); return $validation; }
if ($_GET['config']) { $old_conffile .= "_" . $_GET['config']; } $old_conffile .= '.xml'; if (true === is_readable($old_conffile)) { $conffile = $old_conffile; echo '<font color="#f00"><b>WARNING:</b> Depreciated position of config file!</font><hr/>'; } else { echo "File <b>{$conffile}</b> (nor the depreciated <b>{$old_conffile}</b>) does not exist!"; echo '</body></html>'; exit; } } $lines = file($conffile); $dom->load($conffile); if ($dom->schemaValidate('visu_config.xsd')) { print "config <b>" . $conffile . " is valid </b> XML<br/>"; checkVersion($dom); } else { print "config <b>" . $conffile . " is NOT </b> valid XML"; checkVersion($dom); echo '<hr />'; $errors = libxml_get_errors(); foreach ($errors as $error) { echo libxml_display_error($error); } libxml_clear_errors(); } echo '<hr />'; echo '<pre>'; foreach ($lines as $line_num => $line) {
require_once '../../sources/models/serializeRules/AncestorSerializeRules.php'; require_once '../../sources/models/serializeRules/SerializeRulesBackgroundAssociationRules.php'; require_once '../../sources/models/CompareXml.php'; session_start(); $_SESSION["ARBuilder_domDataDescr"] = "../../XML/datadescription.xml"; $json = "{\"rule0\":[{\"name\":\"NEG\",\"type\":\"neg\"},{\"name\":\"statusAgregovane\",\"type\":\"attr\",\"category\":\"One Category\",\"fields\":[{\"name\":\"category\",\"value\":\"cat1\"}]},{\"name\":\"AND\",\"type\":\"and\"},{\"name\":\"duration\",\"type\":\"attr\",\"category\":\"One Category\",\"fields\":[{\"name\":\"category\",\"value\":\"cat2\"}]},{\"name\":\"Support\",\"type\":\"oper\",\"fields\":[{\"name\":\"min value\",\"value\":\"\"}]},{\"name\":\"NEG\",\"type\":\"neg\"},{\"name\":\"name3\",\"type\":\"attr\",\"category\":\"One Category\",\"fields\":[{\"name\":\"category\",\"value\":\"cat3\"}]},{\"name\":\"AND\",\"type\":\"and\"},{\"name\":\"statusAgregovane\",\"type\":\"attr\",\"category\":\"One Category\",\"fields\":[{\"name\":\"category\",\"value\":\"cat5\"}]},{\"name\":\"OR\",\"type\":\"or\"},{\"name\":\"name6\",\"type\":\"attr\",\"category\":\"One Category\",\"fields\":[{\"name\":\"category\",\"value\":\"cat6\"}]}],\"rules\":1}"; $sr = new SerializeRulesBackgroundAssociationRules(); $xmlFileFinal = $sr->serializeRules($json); libxml_use_internal_errors(true); $correctXML = true; /* creating a DomDocument object */ $objDom = new DomDocument(); /* loading the xml data */ $objDom->loadXML($xmlFileFinal); /* tries to validade your data */ if (!$objDom->schemaValidate("../../XML/schemas/ARBuilder0_1.xsd")) { /* if anything goes wrong you can get all errors at once */ $allErrors = libxml_get_errors(); /* each element of the array $allErrors will be a LibXmlError Object */ print "<h2>XML file is not correct</h2>"; print_r($allErrors); } else { print "<h2>XML file is correct</h2>"; } $ret = $xmlFileFinal; print "<textarea rows='10' cols='20'>{$ret}</textarea>"; $filePath = "resultAsociationRule1.xml"; $file = fopen($filePath, "r"); $expectedResult = fread($file, filesize($filePath)); if (areXmlSame($xmlFileFinal, $expectedResult)) { print "<h2>XML file is as expected</h2>";
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { echo "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded."; } else { exit("image error"); } } } else { } break; default: break; } } } //check if shema is validate if (!$xml->schemaValidate('contactListSchema.xsd')) { $value = libxml_display_errors(); $dr = $value; appendToHtml(' <div class="alert alert-danger alert-fixed-bottom" id="alertMsg"> <strong>Warning !!!!</strong>' . $dr . ' <button onclick="hideAlert()">Make Modification</button>"</div>'); } else { //save the xml is validation o.k $xml->save("contactList.xml"); appendToHtml(' <div class="alert alert-success alert-fixed-bottom" id="alertMsg"> <strong>Success!</strong>' . $dr . ' <button onclick="goToMainPage()">Go to main Page</button>"</div>'); } $html = str_replace("{{alert}}", $html, $htmlFile);
/** * Gets all matching XML schema files and loads them into data models for class. * @return void */ protected function loadDataModels() { $ads = array(); // Get all matched files from schemaFilesets foreach ($this->schemaFilesets as $fs) { $ds = $fs->getDirectoryScanner($this->project); $srcDir = $fs->getDir($this->project); $dataModelFiles = $ds->getIncludedFiles(); $platform = $this->getGeneratorConfig()->getConfiguredPlatform(); // Make a transaction for each file foreach ($dataModelFiles as $dmFilename) { $this->log("Processing: " . $dmFilename); $xmlFile = new PhingFile($srcDir, $dmFilename); $dom = new DomDocument('1.0', 'UTF-8'); $dom->load($xmlFile->getAbsolutePath()); // normalize (or transform) the XML document using XSLT if ($this->xslFile) { $this->log("Transforming " . $xmlFile->getPath() . " using stylesheet " . $this->xslFile->getPath(), Project::MSG_VERBOSE); if (!class_exists('XSLTProcessor')) { $this->log("Could not perform XLST transformation. Make sure PHP has been compiled/configured to support XSLT.", Project::MSG_ERR); } else { // modify schema to include any external schema's (and remove the external-schema nodes) $this->includeExternalSchemas($dom, $srcDir); // normalize the document using normalizer stylesheet $xsl = new XsltProcessor(); $xsl->importStyleSheet(DomDocument::load($this->xslFile->getAbsolutePath())); $transformed = $xsl->transformToDoc($dom); $newXmlFilename = substr($xmlFile->getName(), 0, strrpos($xmlFile->getName(), '.')) . '-transformed.xml'; // now overwrite previous vars to point to newly transformed file $xmlFile = new PhingFile($srcDir, $newXmlFilename); $transformed->save($xmlFile->getAbsolutePath()); $this->log("\t- Using new (post-transformation) XML file: " . $xmlFile->getPath(), Project::MSG_VERBOSE); $dom = new DomDocument('1.0', 'UTF-8'); $dom->load($xmlFile->getAbsolutePath()); } } // validate the XML document using XSD schema if ($this->validate && $this->xsdFile) { $this->log("Validating XML doc (" . $xmlFile->getPath() . ") using schema file " . $this->xsdFile->getPath(), Project::MSG_VERBOSE); if (!$dom->schemaValidate($this->xsdFile->getAbsolutePath())) { throw new EngineException("XML schema file (" . $xmlFile->getPath() . ") does not validate. See warnings above for reasons validation failed (make sure error_reporting is set to show E_WARNING if you don't see any).", $this->getLocation()); } } $xmlParser = new XmlToAppData($platform, $this->getTargetPackage(), $this->dbEncoding); $ad = $xmlParser->parseFile($xmlFile->getAbsolutePath()); $ad->setName($dmFilename); // <-- Important: use the original name, not the -transformed name. $ads[] = $ad; } } if (empty($ads)) { throw new BuildException("No schema files were found (matching your schema fileset definition)."); } if (!$this->packageObjectModel) { $this->dataModels = $ads; $this->databaseNames = array(); // doesn't seem to be used anywhere $this->dataModelDbMap = array(); // Different datamodels may state the same database // names, we just want the unique names of databases. foreach ($this->dataModels as $dm) { $database = $dm->getDatabase(); $this->dataModelDbMap[$dm->getName()] = $database->getName(); $this->databaseNames[$database->getName()] = $database->getName(); // making list of *unique* dbnames. } } else { $this->joinDatamodels($ads); $this->dataModels[0]->getDatabases(); // calls doFinalInitialization() } $this->dataModelsLoaded = true; }
/** * Metoda pro vzdáelné přidávání článků. * * @param string XML dokument * @param string přihlašovací jméno * @param string heslo * @param string Název článku * @param int id článku, pokud má být určitě nový pak -1 * @param string Anotace článku. * @return string Výsledek přidání. * @since 1.5 */ function nahrajXML($xmldocument, $user, $pass, $nazevClanku, $id) { global $mainframe, $xmlrpcerruser, $proc; $plugin =& JPluginHelper::getPlugin('xmlrpc', 'uploadxml'); $params = new JParameter($plugin->params); $category = $params->get('catid'); $section = $params->get('sectionid'); $state = $params->get('publikovat'); $xmlpath = $params->get("xmlpath"); $db =& JFactory::getDBO(); if (!plgUploadXMLJoomlaServices::authenticateUser($user, $pass)) { $myVal = new xmlrpcval("Nepovedlo se kvuli autentikaci uzivatele. {$user}, {$pass}", "string"); return $myVal; } // Autorizace if (empty($id) || $id <= 0) { if (!plgUploadXMLJoomlaServices::authorizeArticleNew($user, $id, $debug)) { $myVal = new xmlrpcval("Nepovedlo se kvuli nedostatecnym pravum pro vytvareni novych dokumentu.", "string"); return $myVal; } } else { if (!plgUploadXMLJoomlaServices::authorizeArticleEdit($user, $id, $debug)) { $myVal = new xmlrpcval("Nepovedlo se kvuli nedostatecnym pravum pro zapis.", "string"); return $myVal; } } libxml_use_internal_errors(true); $odpovida = false; $title = $alias = $title_alias = $nazevClanku; $pattern = "../" . $xmlpath . "/*.xsd"; $files = glob($pattern); // vrati pole s nazvy xsd souboru //return new xmlrpcval(dirname(__FILE__) . " ". $pattern .implode(", ", $files), "string"); $xml = new DomDocument(); $xml->loadXML($xmldocument); if (!empty($files)) { error_reporting(0); $valid = false; foreach ($files as $xsdfile) { if ($xml->schemaValidate($xsdfile)) { $valid = true; $xslfile = str_replace(".xsd", ".xsl", $xsdfile); if (file_exists($xslfile)) { $xdoc2 = new DomDocument(); $xdoc2->load($xslfile); $xsl = new XSLTProcessor(); $xsl->importStylesheet($xdoc2); // transformace $xmldocument = $xsl->transformToXML($xml); } } } if (!$valid) { return new xmlrpcval("ERROR Nahravany soubor neodpovida zadnemu schematu", "string"); } } /* //POZOR to tu je pouze docasne, kvuli vypnute xsl transformaci if (!$XMLtext or $XMLtext == '') { $XMLtext = $xmldocument; }*/ //$query = "insert into #__content (title,alias,title_alias, introtext, fulltext, state, sectionid, mask, catid, created, created_by, created_by_alias, modified, modified_by, checked_out, checked_out_time, publish_up, publish_down, images, urls, attribs, version, parentid, ordering, metakey, metadesc, access, hits, metadata) " + // + "values ($title, $alias, $title_alias, $introtext, $XMLtext, $state, $sectionid, $mask, $catid, $created,)"; //$query = "insert into #__content (title,alias,title_alias, introtext, fulltext, created_by) " + // + "values ($title, $alias, $title_alias, $introtext, $XMLtext, $createdBy)"; $uid = plgUploadXMLJoomlaServices::getUserID($user); $now = date('YmdHis', $now); // columns fulltext and introtext are both of mediumtext datatype //as the primary column for saving article text joomla uses introtext, not mediumtext //if xml is saved into fulltext column, Joomla will insert <hr> line to the output when rendering the page //damaging the XML if ($id == -1) { $query = "insert into #__content (title, images, urls, attribs, metakey, metadesc, introtext, sectionid, catid, created_by, created_by_alias, state, created, modified) values ('{$title}','','','','','', '{$xmldocument}','{$section}','{$category}','{$uid}','{$user}','{$state}', NOW(), NOW());"; } else { $created = "select created from #__content where id=" . $id . ";"; $result1 = $db->Execute($created); $vytvoreno = $db->loadResult(); $query = "replace into #__content set title='{$title}', images='', urls='', attribs='', metakey='xml', metadesc='Compliant with {$complyingWith}', introtext='{$xmldocument}',id='{$id}', sectionid='{$section}', catid='{$category}',created_by = '{$uid}',created_by_alias='{$user}',state='{$state}', modified = NOW(), created = '{$vytvoreno}';"; } $result = $db->Execute($query); //tady je potřeba nahrát ten soubor do DB. $myVal = new xmlrpcval("Soubor se povedlo uspesne nahrat", "string"); return $myVal; }