From bf74fc2dafbc9dbd816fff061bb2bb5fe0f432b3 Mon Sep 17 00:00:00 2001 From: Elena.Budnik <ebudnik@irap.omp.eu> Date: Wed, 17 May 2017 12:00:44 +0200 Subject: [PATCH] IMPEX --- js/app/models/InteractiveNode.js | 6 +++--- js/app/models/RemoteSimuParamNode.js | 10 +++++++++- php/AmdaUpdate.php | 18 ++++++------------ php/RemoteDataCenter/FMI_GUMICS.php | 45 +++++++++++++++++++++++++++++++++++++++++++++ php/RemoteDataCenter/FMI_HYBRID.php | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ php/RemoteDataCenter/IPIM.php | 166 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ php/RemoteDataCenter/ImpexParamManager.php | 567 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ php/RemoteDataCenter/LATMOS.php | 72 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ php/RemoteDataCenter/LESIA.php | 346 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ php/RemoteDataCenter/RemoteDataCenterClass.php | 86 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ php/RemoteDataCenter/SINP.php | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ php/RemoteDataCenter/SimulationDataCenterClass.php | 499 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ php/RemoteDataCenter/makeArgs.php | 27 +++++++++++++++++++++++++++ php/RemoteDataCenter/makeOrbitsArgs.php | 82 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ php/RemoteDataCenter/makeOrbitsList.php | 76 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ php/RemoteDataCenter/makeProxy.php | 31 +++++++++++++++++++++++++++++++ php/classes/AmdaAction.php | 101 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------------------- php/classes/BaseManager.php | 793 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- php/classes/BestRunsMgr.php | 420 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- php/classes/EPNResourcesManager.php | 1042 ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- php/classes/FilesMgr.php | 2224 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ php/classes/VOTableMgr.php | 343 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- php/config.php | 488 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 23 files changed, 4215 insertions(+), 3345 deletions(-) create mode 100644 php/RemoteDataCenter/FMI_GUMICS.php create mode 100644 php/RemoteDataCenter/FMI_HYBRID.php create mode 100644 php/RemoteDataCenter/IPIM.php create mode 100644 php/RemoteDataCenter/ImpexParamManager.php create mode 100644 php/RemoteDataCenter/LATMOS.php create mode 100644 php/RemoteDataCenter/LESIA.php create mode 100644 php/RemoteDataCenter/RemoteDataCenterClass.php create mode 100644 php/RemoteDataCenter/SINP.php create mode 100644 php/RemoteDataCenter/SimulationDataCenterClass.php create mode 100644 php/RemoteDataCenter/makeArgs.php create mode 100644 php/RemoteDataCenter/makeOrbitsArgs.php create mode 100644 php/RemoteDataCenter/makeOrbitsList.php create mode 100644 php/RemoteDataCenter/makeProxy.php mode change 100755 => 100644 php/classes/BaseManager.php delete mode 100644 php/classes/EPNResourcesManager.php diff --git a/js/app/models/InteractiveNode.js b/js/app/models/InteractiveNode.js index 6d0c76e..2f0a869 100644 --- a/js/app/models/InteractiveNode.js +++ b/js/app/models/InteractiveNode.js @@ -483,7 +483,7 @@ Ext.define('amdaModel.InteractiveNode', { // edit newNode into Plot Module with node as contextNode newNode.editInModule(); if(node.get('globalStart') != 'depending on mission' && ( node.get('nodeType') == 'localParam' || - node.get('nodeType') == 'myDataParam')) { + node.get('nodeType') == 'myDataParam' || node.get('nodeType') == 'remoteSimuParam')) { module.getUiContent().setTimeFromData(node.getTimeFromNode(node)); } } @@ -506,8 +506,8 @@ Ext.define('amdaModel.InteractiveNode', { amdaModel.DownloadNode.set('object',request); // singleton! amdaModel.DownloadNode.editInModule(); - if(node.get('globalStart') != 'depending on mission' && ( node.get('nodeType') == 'localParam' || - node.get('nodeType') == 'myDataParam')) { + if (node.get('globalStart') != 'depending on mission' && ( node.get('nodeType') == 'localParam' || + node.get('nodeType') == 'myDataParam' || node.get('nodeType') == 'remoteSimuParam')) { module.getUiContent().setTimeFromData(node.getTimeFromNode(node)); } } diff --git a/js/app/models/RemoteSimuParamNode.js b/js/app/models/RemoteSimuParamNode.js index 15c5977..3893218 100644 --- a/js/app/models/RemoteSimuParamNode.js +++ b/js/app/models/RemoteSimuParamNode.js @@ -86,7 +86,15 @@ Ext.define('amdaModel.RemoteSimuParamNode', { fnId : 'leaf-downParam', text : 'Download Parameter', hidden : true - } + }, { + fnId : 'para-plotParam', + text : 'Plot Parameter', + hidden : true + }, { + fnId : 'para-downParam', + text : 'Download Parameter', + hidden : true + } ]; return menuItems; diff --git a/php/AmdaUpdate.php b/php/AmdaUpdate.php index 9992ea2..0122b0c 100644 --- a/php/AmdaUpdate.php +++ b/php/AmdaUpdate.php @@ -57,20 +57,14 @@ $ok = $amda->updateStartStop($locBases); /* - * Create EPNResource files - */ - $epnMgr = new EPNResourcesManager($amda); - $epnMgr->createResources(); - } -/* * Create/update Orbites.xml file */ - if (!$updateOnly) { - $postProcessing = new PostProcessing(); - $postProcessing->createOrbites(); - $postProcessing->createOrbites(LocalDataParam.'InternalParams.xml'); - $postProcessing->createOrbitesInfoFiles($locBases); - } +// if (!$updateOnly) { +// $postProcessing = new PostProcessing(); +// $postProcessing->createOrbites(); +// $postProcessing->createOrbites(LocalDataParam.'InternalParams.xml'); +// $postProcessing->createOrbitesInfoFiles($locBases); +// } /* * Get available external bases if exist diff --git a/php/RemoteDataCenter/FMI_GUMICS.php b/php/RemoteDataCenter/FMI_GUMICS.php new file mode 100644 index 0000000..e82cc74 --- /dev/null +++ b/php/RemoteDataCenter/FMI_GUMICS.php @@ -0,0 +1,45 @@ +<?php +/** + * @class FMI_GUMICS + * @brief + * @details + */ +class FMI_GUMICS extends SimulationDataCenterClass +{ + protected $url = "http://impex-fp7.fmi.fi/ws"; + protected $treeXML = "Tree_FMI_GUMICS.xml"; + protected $WSDL = "Methods_FMI.wsdl"; + + protected $templateFile = "FMI_GUMICS_Templates.xml"; + protected $needsArgs = true; + + public $soapMethod = "getDataPointValue"; + // OutputFormat netCDF, VOTable, ASCII + public $outputFormat = "VOTable"; + + protected function createSimulationRegionNodes($id) + { + $simulationRegionNodes = array(); + $simReg = "Earth.Magnetosphere"; + + $simuRegion = $this->domAmda->createElement('simulationRegion'); + $simuRegion->setAttribute('xml:id', $this->param2dd("FMI_GUMICS_$simReg")); + $simuRegion->setAttribute('name', $simReg); + $simuRegion->setAttribute('isAddable', true); + $simuRegion->setAttribute('rank', "5"); + $simuRegion->setAttribute('att', "simu/simu$simReg"); + + $this->addSimulatedRegionToTargetsFile($simReg, "GSE"); + + $simulationRegionNodes[] = $simuRegion; + + return $simulationRegionNodes; + } + + protected function setModelHelp($node, $helpFile) + { + $node->setAttribute('att', 'simu/Gumics'); + } +} +?> + \ No newline at end of file diff --git a/php/RemoteDataCenter/FMI_HYBRID.php b/php/RemoteDataCenter/FMI_HYBRID.php new file mode 100644 index 0000000..b43bf84 --- /dev/null +++ b/php/RemoteDataCenter/FMI_HYBRID.php @@ -0,0 +1,67 @@ +<?php +/** + * @class FMI_HYBRID + * @brief + * @details + */ +class FMI_HYBRID extends SimulationDataCenterClass +{ + protected $url = "http://impex-fp7.fmi.fi/ws"; + protected $treeXML = "Tree_FMI_HYB.xml"; + protected $WSDL = "Methods_FMI.wsdl"; + + protected $needsArgs = true; + protected $templateFile = "FMI_HYBRID_Templates.xml"; + public $interpolationMethod = array('Linear', 'NearestGridPoint'); + + public $soapMethod = "getDataPointValue"; + public $soapMethodSpectra = "getDataPointSpectra"; + + public $energyTableName = "EnergyRange", $tableTitle="Energy"; + + //<xs:element minOccurs="0" maxOccurs="1" ref="EnergyChannel"/> + + // OutputFormat netCDF, VOTable, ASCII + public $outputFormat = "VOTable"; + + protected function getDatasetName($no) + { + $name = explode("/",trim($no->ResourceID)); + return end($name); + } + + + protected function setSimulationRunNodeDescription($runNode,$sr) + { + $coords = $this->getCoordinateSystem($sr->SimulationDomain->CoordinateSystem); + $domain = $this->getRegionBoundaries($sr->SimulationDomain,$sr->RegionParameter); + $properties = $this->getProperties($sr); + + $runNode->setAttribute('desc', $coords.$domain.$properties); + } + + protected function getProperties($sr) + { + + + } + + protected function createSpecialArgs($dom) + { + $node = $dom->createElement('argument'); + $node->setAttribute('key', 'InterpolationMethod'); + $node->setAttribute('name', 'Interpolation Method'); + $node->setAttribute('type', 'list'); + $node->setAttribute('default', $this->interpolationMethod[0]); + for ($i = 0; $i < 2; $i++) + { + $item = $dom->createElement('item'); + $item->setAttribute('key', $this->interpolationMethod[$i]); + $item->setAttribute('name', $this->interpolationMethod[$i]); + $node->appendChild($item); + } + return array($node); + } + +} +?> diff --git a/php/RemoteDataCenter/IPIM.php b/php/RemoteDataCenter/IPIM.php new file mode 100644 index 0000000..d737760 --- /dev/null +++ b/php/RemoteDataCenter/IPIM.php @@ -0,0 +1,166 @@ +<?php +/** + * @class IPIM + * @brief + * @details + */ +class IPIM extends SimulationDataCenterClass +{ + protected $url = "http://transplanet.irap.omp.eu"; + protected $treeXML = "impex.xml"; + + public $alongOrbit = false; + + protected $hasAccessUrl = true; + + public $outputFormat = 'CDF'; + // altitude curvilinear_abscissa surface volume + public $energyTableName = "curvilinear_abscissa"; + protected $energyTableWidth = 200; + + + protected function addSimulatedRegionToTargetsFile($reg=null,$reg=null){} + + protected function getDatasetName($no) + { + $name = explode("/",trim($no->ResourceID)); + return end($name); + } + + protected function setHelpAttribute($node, $helpFile) + { + $node->setAttribute('att', ""); + } + + protected function setSimulationRunNodeDescription($runNode,$sr) + { + $coords = $this->getCoordinateSystem($sr->SimulationDomain->CoordinateSystem); + $domain = $this->getRegionBoundaries($sr->SimulationDomain, null); + $properties = $this->getProperties($sr); + + $runNode->setAttribute('desc', $coords.$domain.$properties); + } + + protected function getAccessUrl($no) + { + $url = $no->AccessInformation->AccessURL->URL; + $resourceID = $no->ResourceID; + + if ($url == '') + { + foreach ($this->tree->Granule as $granule) + { + $granuleID = $granule->ParentID; + + if ("$granuleID" == "$resourceID") + { + $url = $granule->Source->URL; + break; + } + } + } + + return $url; + } + + protected function getStartTime($no) + { + $start = $no->TemporalDescription->TimeSpan->StartDate; + $stpos = strpos($start, '+'); + if ($stpos > 0) + $start = substr($start,0,$stpos); + + return $start."Z"; + } + + protected function getStopTime($no) + { + $stop = $no->TemporalDescription->TimeSpan->StopDate; + $stpos = strpos($stop, '+'); + if ($stpos > 0) + $stop = substr($stop,0,$stpos); + + return $stop."Z"; + } + + protected function getProperties($sr) + { + $descInternal = "<b><br/>Internal Magnetic Field : </b> : "; + $inputFields = $sr->InputField; + + foreach ($inputFields as $field) + { + $descInternal .= $field->Name."<br/>"; + } + $descInternal .= "<b>Input Neutrals : </b>"; + $inputPopulations = $sr->InputPopulation; + foreach ($inputPopulations as $population) + { + $descInternal .= $population->Name.";"; + } + return $descInternal; + } + + protected function getRegionBoundaries($domain, $region = null) + { + $desc = "<b><br/>Domain: </b><br/>"; + + $spatialDimension = $domain->SpatialDimension; + + $ValidMinsDom = preg_split ("/\s+/", $domain->ValidMin); + $ValidMaxsDom = preg_split ("/\s+/", $domain->ValidMax); + $unitsDomain = preg_split ("/\s+/", $domain->Units); + $coordLabel = preg_split ("/\s+/",$domain->CoordinatesLabel); + + for($j=0; $j< $spatialDimension; $j++) + { + $desc .= $coordLabel[$j]." : [ ".$ValidMinsDom[$j].", ".$ValidMaxsDom[$j]."] ".$unitsDomain[$j]."<br/>"; + } + return $desc; + } + + public function getFileName($resourceID, $templateArgs = null, $start = null) + { + $strpos = strrpos($resourceID, "/"); + + if ($strpos > 0) + $fileName = substr(strtr($resourceID, $this->impex_pairs),0,$strpos); + + $fileName .= ".cdf"; + + return $fileName; + } + + public function getMask($resourceID, $templateArgs = null) + { + return $this->getFileName($resourceID); + } + + public function getData($params) + { +// $r = print_r($params,true); + // error_log($params['accessUrl'],3,'/home/budnik/LOG'); + + return $params['accessUrl']; + } + + public function getTableDefinition($viID = null) + { + $res = array(); + if ($viID) + { + // amdaParam (like EISCAT) + } + else + { + $res["tableDefType"] = "SELECT"; + $res["channelsDefType"] = "CENTER"; + $res["data"] = array(); + $res["data"]["center"] = $this->energyTableName; + $res["data"]["width"] = $this->energyTableWidth; + } + + return $res; + } +} +?> diff --git a/php/RemoteDataCenter/ImpexParamManager.php b/php/RemoteDataCenter/ImpexParamManager.php new file mode 100644 index 0000000..ba8423d --- /dev/null +++ b/php/RemoteDataCenter/ImpexParamManager.php @@ -0,0 +1,567 @@ +<?php +/** +* @class ImpexParamManager.php +* @brief Simations parameters Manager (Simulations db client) +* +*/ + +class ImpexParamManager +{ + // input parameters + protected $extraParam, $sampling; + protected $dataProducer, $argStartTime, $argStopTime; + protected $parameterID, $resourceID, $parameterKey, $parameterSize; + protected $vectorList = null, $isSpectra = false; + + protected $orbitTempFolder = null; + protected $center = null; + + protected $requestManager = null; + protected $baseManager = null; + protected $votManager = null; + protected $impex_pairs = array("/" => "_", ":" => "_"); + + public $startTime, $stopTime; + + private $impexParamInfo = null; + + //TODO + private $scale = array("km" => 1, "Rme" => 2438, "Rv" => 6052, "Re" => 6371, "Rma" => 3396, "Rm" => 3396, + "Rj" => 71492, "Rs" => 60268, "Ru" => 25559, "Rn" => 24764); + + function __construct() + { + $this->baseManager= new BaseManager(); + + date_default_timezone_set('UTC'); + ini_set("soap.wsdl_cache_enabled", "0"); + } + + public function getImpexFullParamId($param_id, $templateArgs = NULL) { + + if (!$templateArgs) + return $param_id; + + $fullParamId = $param_id; + foreach ($templateArgs as $key => $value) + $fullParamId .= "_".$value; + + return $fullParamId; + } + + private function initParam($param, $templateArgs = NULL) + { + $this->impexParamInfo = new IHMImpexParamClass(); + + $this->parameterID = $this->getImpexFullParamId($param, $templateArgs); + $this->dataProducer = $this->impexParamInfo->getDataProducer($param); + $this->resourceID = $this->impexParamInfo->getResourceID($param); + $this->parameterSize = $this->impexParamInfo->getParameterSize($param); + $this->vectorList = $this->impexParamInfo->getVectorList($this->resourceID); + $this->isSpectra = $this->impexParamInfo->isSpectra($param); + } + + public function createImpexParameter($param, $intervals, $templateArgs = NULL) + { + $this->initParam($param, $templateArgs); + $this->parameterKey = $this->impexParamInfo->getParameterKey($param); + + if (!$this->center) + $this->center = new $this->dataProducer(); + + $mask = $this->center->getMask($this->resourceID, $templateArgs); + + // if VI exists (i.e. another parameter from this dataset has been already created) + if ($this->baseManager->existsVi($mask)) + { + $result = $this->addImpexData($param, $intervals, $templateArgs); + $viID = $result['VIID']; + + $localFile = $this->baseManager->getFirstFileName($viID); + + if ($this->center->outputFormat == "VOTable") + { + if (!$this->votManager) + $this->votManager = new VOTableMgr(); + + if (!$this->votManager->load(IHMConfigClass::getLocalBasePath().$localFile)) + throw new Exception('Cannot load '.$localFile); + } + } + else + { + $start = $intervals[0]->getStart(); + $duration = $intervals[0]->getDuration(); + + $startTime = CommonClass::DDTimeToIso($start); + $stopTime = CommonClass::DDStartIntervalToStopIso($start,$duration); + $this->argStartTime = $startTime; + $this->argStopTime = $stopTime; + + if (is_array($templateArgs)) + $templateArgs = (object) $templateArgs; + + if ($templateArgs->url_XYZ) + { + $url_XYZ = $this->getOrbit($startTime, $stopTime, $templateArgs->url_XYZ); + $params = $this->makeRequest($templateArgs, $url_XYZ); + } + else + { + $params = $this->makeRequest($templateArgs); + } + + $remoteFile = $this->center->getData($params, $this->isSpectra); + + $localFile = $this->center->getFileName($this->resourceID, $templateArgs,$start); + + if (!copy($remoteFile, IHMConfigClass::getLocalBasePath().$localFile)) { + throw new Exception('Cannot wget '.$remoteFile); + } + + if ($this->center->outputFormat == "VOTable") + { + if (!$this->votManager) + $this->votManager = new VOTableMgr(); + + if (!$this->votManager->load(IHMConfigClass::getLocalBasePath().$localFile)) + throw new Exception('Cannot load '.$localFile); + + if (!$this->votManager->isData()) + { + unlink(IHMConfigClass::getLocalBasePath().$localFile); + throw new Exception('Empty file '.$localFile); + } + + if ($this->vectorList) + { + //TODO if it is needed to reload xml in case of several vectors + foreach ($this->vectorList as $vector) + { + $this->votManager->addVectorToVot($vector,IHMConfigClass::getLocalBasePath().$localFile); + } + } + $viID = $this->addFileToDb($mask, $localFile, $startTime, $stopTime); + } + elseif ($this->center->outputFormat == "CDF") + { + $viID = $this->addFileToDb($mask, $localFile, $startTime, $stopTime, 'cdf'); + } + + if ($this->orbitTempFolder) + CommonClass::rrmdir($this->orbitTempFolder); + } + + $res = $this->getInfoFromFile($localFile); + + $res["success"] = true; + $res["param"]["id"] = $this->parameterID; + $res["param"]["dateModif"] = time(); + $res["param"]["info"]["viId"] = $viID; + $res["param"]["info"]["name"] = $this->parameterKey; + $res["param"]["info"]["yTitle"] = $this->parameterKey; + $res["param"]["info"]["units"] = $this->impexParamInfo->getUnits($param); + + + //TODO define in DataCenter Class + // special info on EnergyRange Table for Spectra : LATMOS, FMI_HYBRID + if ($this->isSpectra) + { + $res["param"]["info"]["tableDef"] = $this->center->getTableDefinition(); + $res["param"]["info"]["yTitle"] = $this->center->tableTitle; + $res["param"]["info"]["yUnits"] = $this->impexParamInfo->getEnergyUnits($param); + } + if ($this->dataProducer == "IPIM") + { + $res["param"]["info"]["tableDef"] = $this->center->getTableDefinition(); // ($viID); + $res["param"]["info"]["yTitle"] = $this->center->energyTableName; + $res["param"]["info"]["yUnits"] = 'km'; + } + return $res; + } + + public function addImpexData($param, $intervals, $templateArgs = NULL) + { + $this->initParam($param, $templateArgs); + + $start = $intervals[0]->getStart(); + $duration = $intervals[0]->getDuration(); + + if (!$this->center) + $this->center = new $this->dataProducer(); + + $mask = $this->center->getMask($this->resourceID, $templateArgs); + + $startStamp = CommonClass::DDTimeToTimeStamp($start); + $stopStamp = $startStamp + CommonClass::DDTimeToTimeStamp($duration); + + $intervalsToGet = $this->baseManager->intervalsToGet($startStamp, $stopStamp, $mask); + + $startT = $intervalsToGet['start']; + $stopT = $intervalsToGet['stop']; + + if ( is_array($templateArgs) ) + $templateArgs = (object) $templateArgs; + + if (count($startT) > 0) + { + for ( $i = 0; $i < count($startT); $i++ ) + { + $startTime = date("Y-m-d\TH:i:s",$startT[$i]); + $stopTime = date("Y-m-d\TH:i:s",$stopT[$i]); + + $this->argStartTime = $startTime; + $this->argStopTime = $stopTime; + + if ($templateArgs->url_XYZ) + { + $url_XYZ = $this->getOrbit($startTime, $stopTime, $templateArgs->url_XYZ); + $params = $this->makeRequest($templateArgs, $url_XYZ); + } + else + { + $params = $this->makeRequest($templateArgs); + } + + + $remoteFile = $this->center->getData($params, $this->isSpectra); + + $localFile = $this->center->getFileName($this->resourceID,$templateArgs,$start); + + if (!copy($remoteFile, IHMConfigClass::getLocalBasePath().$localFile)) { + throw new Exception('Cannot wget '.$remoteFile); + } + + if ($this->center->outputFormat == "VOTable") + { + if (!$this->votManager) + $this->votManager = new VOTableMgr(); + + if (!$this->votManager->load(IHMConfigClass::getLocalBasePath().$localFile)) + throw new Exception('Cannot load '.$localFile); + + if (!$this->votManager->isData()) + { + unlink(IHMConfigClass::getLocalBasePath().$localFile); + throw new Exception('Empty file '.$localFile); + } + + if ($this->vectorList) + { + foreach ($this->vectorList as $vector) + { + $this->votManager->addVectorToVot($vector,IHMConfigClass::getLocalBasePath().$localFile); + } + } + + $viID = $this->addFileToDb($mask, $localFile, $startTime, $stopTime); + } + else if ($this->center->outputFormat == "CDF") + { + $viID = $this->addFileToDb($mask, $localFile, $startTime, $stopTime, 'cdf'); + } + if ($this->orbitTempFolder) + CommonClass::rrmdir($this->orbitTempFolder); + } + } + // nothing to add + else + { + $viID = $this->baseManager->getVI($mask); + } + + $startStop = $this->baseManager->getViDesc($viID); + + $res = array('VIID' => $viID, 'StartStop' => $startStop); + + return $res; + } + + private function getInfoFromFile($localFile) + { + $res = array(); + $res["param"] = array(); + $res["param"]["info"] = array(); + + if ($this->center->outputFormat == "VOTable") + { + if (!$this->votManager) + $this->votManager = new VOTableMgr(); + + // reload xml after adding vector field + if (!$this->votManager->load(IHMConfigClass::getLocalBasePath().$localFile)) + throw new Exception('Cannot load '.$localFile); + + $infos = $this->votManager->getFieldInfoByID($this->parameterKey); + $samplings = $this->votManager->getSamplings(); + $res["param"]["info"]["realVar"] = $infos["id"]; + $res["param"]["info"]["type"] = $infos["type"]; + $res["param"]["info"]["unit"] = $infos["unit"]; + $res["param"]["info"]["ucd"] = $infos["ucd"]; + $res["param"]["info"]["size"] = $infos["size"]; + $res["param"]["info"]["minSampling"] = $samplings["minSampling"]; + $res["param"]["info"]["maxSampling"] = $samplings["maxSampling"]; + $res["param"]["info"]["plotType"] = "Time Series"; + } + else if ($this->center->outputFormat == "CDF") + { + $filesMgr = new FilesMgr(); + $filesMgr->setFileName($localFile); + + $varInfo = $filesMgr->getCdfVarInfo($this->parameterKey); + $varSampling = $filesMgr->getCdfSampling(); + + $res["param"]["info"]["realVar"] = $this->parameterKey; + $res["param"]["info"]["type"] = $varInfo['type']; + $res["param"]["info"]["minSampling"] = $varSampling[4]; + $res["param"]["info"]["maxSampling"] = $varSampling[4]; + $res["param"]["info"]["plotType"] = "Spectro"; + $res["param"]["info"]["size"] = $varInfo['size']; + } + return $res; + } + + private function addFileToDb($maskName, $fileName, $startTime, $stopTime, $format = null) + { + if (!$format) + $format = "vot"; + + if (!$this->baseManager->existsVi($maskName)) + { + $viID = $this->baseManager->addVI($maskName, $format); + } + else + { + $viID = $this->baseManager->getVI($maskName); + } + + $start = strtotime($startTime); + $stop = strtotime($stopTime); + + $mask = $this->baseManager->addFile($fileName, $start, $stop); + + return $viID; + } + + public function getOrbit($startTime, $stopTime, $paramId) + { + $params = array(); + $params[] = (object)array("paramid" => $paramId); + + $obj = (object)array( + "nodeType" => "download", + "downloadSrc" => "0", + "structure" => 2, + "refparamSampling" => false, + "sampling" => 60, + "timesrc" => "Interval", + "startDate" => $startTime, + "stopDate" => $stopTime, + "list" => $params, + "fileformat" => "vot", + "timeformat" => "YYYY-MM-DDThh:mm:ss", + "compression" => "gzip" , + "disablebatch" => true + ); + + if (!isset($this->requestManager)) + $this->requestManager = new RequestManagerClass(); + + $userID = IHMConfigClass::getUserName(); + $userHost = IHMConfigClass::getUserHost(); + + try + { + $downloadResult = $this->requestManager->runIHMRequest($userID, $userHost, FunctionTypeEnumClass::PARAMS, $obj); + } + catch (Exception $e) + { + throw new Exception($e->getMessage()); + } + + $this->orbitTempFolder = IHMConfigClass::getRequestPath().$downloadResult['folder']; + + try + { + $this->convertVot($paramId, $downloadResult['result']); + $orbitURL = "http://apus.irap.omp.eu/NEWAMDA/data/budnik/RES/".$downloadResult['folder']."/".$downloadResult['result'].".vot"; + + return $orbitURL; + } + catch (Exception $e) + { + throw new Exception($e->getMessage()); + } + } + + public function makeRequest($templateArgs = null, $url_XYZ = null) + { + $params = array(); + + if ($templateArgs) + { + $extraParams = array(); + + foreach ($templateArgs as $key => $value) + { + if ($key != 'url_XYZ') + $extraParams[$key] = $value; + } + + $extraParams['OutputFileType'] = $this->center->outputFormat; + + if ($this->center->additionalArgs) + { + $args = $this->center->additionalArgs[$this->resourceID]; + foreach ($args as $key => $type) + { + if ($key == "StartTime") $params[$key] = $this->argStartTime; + if ($key == "StopTime") $params[$key] = $this->argStopTime; + if ($key == "Sampling") $params[$key] = 60; + } + } + + if ($url_XYZ) + { + $params['url_XYZ'] = $url_XYZ; + } + + $params['extraParams'] = $extraParams; + } + else + { + $params['accessUrl'] = $this->impexParamInfo->getAccessUrl($this->resourceID); + } + + $params['ResourceID'] = $this->resourceID; + + return $params; + } + + private function convertVot($paramID, $fileName) + { + $comps = array('x', 'y', 'z'); + + $xmlFile = $this->orbitTempFolder."/".$fileName.'.vot'; + + exec("gunzip ".$xmlFile.".gz"); + + $dom = new DomDocument("1.0"); + $dom->formatOutput = false; + $dom->preserveWhiteSpace = false; + $dom->load($xmlFile); + $xp = new domxpath($dom); + + $fields = $dom->getElementsByTagName('FIELD'); + $table = $dom->getElementsByTagName('TABLE')->item(0); + $data = $dom->getElementsByTagName('DATA')->item(0); + + $i=0; + + foreach ($fields as $field) + { + if ($field->getAttribute('ID') == $paramID) + { + $unit = $field->getAttribute('unit'); + $ucd = $field->getAttribute('ucd'); + $datatype = $field->getAttribute('datatype'); + $firstTD = $i; + } + $i++; + } + //TODO unit from output VOT file + /*----------------- temporary-----------------*/ + $temp = new DomDocument("1.0"); + $temp->load(IHMConfigClass::getLocalParamDBPath().$paramID.".xml"); + $unit = $temp->getElementsByTagName('units')->item(0)->nodeValue; + + /*----------------- temporary-----------------*/ + if ($firstTD > 0) + { + if (array_key_exists($unit, $this->scale)) + $unitScale = $this->scale[$unit]; + else + throw new Exception("Undefined unit ".$unit); + + $table->removeChild($fields->item($firstTD)); + + foreach ($comps as $comp) + { + $new_field = $dom->createElement('FIELD'); + $new_field->appendChild(new DOMAttr('ID', $comp)); + $new_field->appendChild(new DOMAttr('name', $comp)); + $new_field->appendChild(new DOMAttr('datatype', $datatype)); + $new_field->appendChild(new DOMAttr('unit', 'km')); // $unit + $new_field->appendChild(new DOMAttr('ucd', 'pos.cartesian.'.$comp)); + + $table->insertBefore($new_field,$data); + } + + $trs = $dom->getElementsByTagName('TR'); + foreach($trs as $tr) + { + $tds = $tr->getElementsByTagName('TD'); + $values = explode(' ',$tds->item($firstTD)->nodeValue); + $toRemote = $tds->item($firstTD); + $tr->removeChild($toRemote); + + foreach ($values as $value) + { + $td = $dom->createElement('TD', $value*$unitScale); //3400 + $tr->appendChild($td); + } + } + + $dom->save($xmlFile); + } + } + + /* + * Delete impex params descriptions in User WS dir (and in Plot?) + */ + public function deleteImpexParams() + { + $dom = new DomDocument("1.0"); + $params = glob(IHMConfigClass::getUserWSPath().IHMImpexParamClass::$paramPrefix.'*.xml'); + + $vis = array(); + foreach ($params as $param) + { + $dom->load($param); + $vi = $dom->getElementsByTagName('localvi'); + if ($vi->length == 0) { + // throw new Exception('No localVi tag in '.$param); + continue; + } + $viId = $vi->item(0)->getAttribute('id'); + if (!in_array ($viId, $vis)) + $vis[] = $viId; + } + + foreach ($params as $param) + { + unlink($param); + } + + // Delete params in Plot/params + foreach (glob(IHMConfigClass::getRequestPath().'Plot_/params/'.IHMImpexParamClass::$paramPrefix.'*.xml') as $param) + { + unlink($param); + } + + return $vis; + } + + /* + * Delete impex VIs and Files in User DATA dir + */ + public function deleteImpexStaff() + { + $vis = $this->deleteImpexParams(); + + foreach ($vis as $vi) + { + $this->baseManager->deleteViTotal($vi); + } + } +} \ No newline at end of file diff --git a/php/RemoteDataCenter/LATMOS.php b/php/RemoteDataCenter/LATMOS.php new file mode 100644 index 0000000..630ae19 --- /dev/null +++ b/php/RemoteDataCenter/LATMOS.php @@ -0,0 +1,72 @@ +<?php +/** + * @class LATMOS + * @brief + * @details + */ +class LATMOS extends SimulationDataCenterClass +{ + protected $url = "http://impex.latmos.ipsl.fr"; + protected $treeXML = "tree.xml"; + protected $WSDL = "Methods_LATMOS.wsdl"; + + protected $templateFile = "LATMOS_Templates.xml"; + protected $needsArgs = true; + public $soapMethod = "getDataPointValue"; + public $soapMethodSpectra = "getDataPointSpectra"; + + public $energyTableName = "EnergyRange", $tableTitle="Energy"; + + //<xs:element minOccurs="0" maxOccurs="1" ref="EnergyChannel"/> + //Extraparam: OutputFormat => netCDF, VOTable + + public $outputFormat = "VOTable"; + + protected function setSimulationRunNodeDescription($runNode,$sr) + { + $coords = $this->getCoordinateSystem($sr->SimulationDomain->CoordinateSystem); + $domain = $this->getRegionBoundaries($sr->SimulationDomain,$sr->RegionParameter); + $properties = $this->getProperties($sr); + + $runNode->setAttribute('desc', $coords.$domain.$properties); + } + + protected function getProperties($sr) + { + $descUpstream = "<b><br/>Upstream Conditions: </b><br/>"; + $descInternal = "<b><br/>Internal Conditions: </b><br/>"; + + $inputPopulations = $sr->InputPopulation; + $inputFields = $sr->InputField; + + foreach ($inputPopulations as $population) + { + if ($population->SimulatedRegion == "Heliosphere") { + $descUpstream .= "<u>".$population->Name."</u><br/>"; + } + } + + foreach ($inputFields as $field) + { + if ($field->SimulatedRegion == "Heliosphere") { + $descUpstream .= "<u>".$field->Name."</u> : "; + $descUpstream .= $field->Units." <i>[".$field->FieldValue."]</i> ".$field->Units."<br/>"; + } + } + + return $descUpstream; + } + + protected function createSpecialArgs($dom) + { + $node = $dom->createElement('argument'); + $node->setAttribute('key', 'IMFClockAngle'); + $node->setAttribute('name', 'IMF Clock Angle'); + $node->setAttribute('type', 'float'); + $node->setAttribute('default', '0'); + + return array($node); + } + +} +?> diff --git a/php/RemoteDataCenter/LESIA.php b/php/RemoteDataCenter/LESIA.php new file mode 100644 index 0000000..bfacf8f --- /dev/null +++ b/php/RemoteDataCenter/LESIA.php @@ -0,0 +1,346 @@ +<?php +/** + * @class LESIA + * @brief + * @details + */ +class LESIA extends SimulationDataCenterClass +{ + protected $url = "http://maser.obspm.fr/IMPExWS"; + protected $treeXML = "tree_Mag.xml"; + protected $WSDL = "Methods_LESIA-Mag.wsdl"; + + protected $templateFile = "LESIA_Templates.xml"; + + protected $needsArgs = true; + + //TODO temporary + protected $prefix = "spase://IMPEX/NumericalOutput/LESIA/MAG/Jupiter"; + protected $resourceID ="impex://LESIA/MAG/Jupiter"; + /* + public $soapMethod = "calculateDataPointValue_Spacecraft"; + <xs:element minOccurs="1" maxOccurs="1" ref="Spacecraft_name"/> + <xs:enumeration value="Cassini"/> + <xs:enumeration value="Galileo"/> + <xs:element minOccurs="1" maxOccurs="1" ref="StartTime"/> + <xs:element minOccurs="1" maxOccurs="1" ref="StopTime"/> + <xs:element minOccurs="1" maxOccurs="1" ref="Sampling"/> + + */ + + public $soapMethods = array("calculateDataPointValue", "calculateDataPointValue_Spacecraft"); +// <xs:element minOccurs="1" maxOccurs="1" ref="url_XYZ"/> +// <xs:element minOccurs="1" maxOccurs="1" ref="StartTime"/> + + public $additionalArgs = array("spase://IMPEX/NumericalOutput/LESIA/MAG/Jupiter/sc" => array("StartTime" => "dateTime", "StopTime" => "dateTime", "Sampling"=> "float" ), + "spase://IMPEX/NumericalOutput/LESIA/MAG/Jupiter/xyz" => array("StartTime" => "dateTime")); + + private $calculateDataPointValue_Args = null; + + private $spacecraft = array("Cassini", "Galileo"); + + private $internalModel = array("O6", "VIP4", "VIT4", "VIPAL"); + private $currentSheet = array("None", "Connerney", "Khurana"); + private $coordinateSystem = array("JSO", "JSM", "JSS", "PlanetaryCartesian","PlanetarySpherical","Planetarographic"); + + /* + <xs:sequence> + <xs:element minOccurs="0" maxOccurs="1" ref="IMF"/> + + */ + //Extraparam: OutputFormat => netCDF, VOTable + public $outputFormat = "VOTable"; + + private function initArgs() + { + if ($this->calculateDataPointValue_Args) return; + + $this->calculateDataPointValue_Args = array(); + $this->calculateDataPointValue_Args["InternalModel"] = $this->internalModel; + $this->calculateDataPointValue_Args["CurrentSheet"] = $this->currentSheet; + $this->calculateDataPointValue_Args["CoordinateSystem"] = $this->coordinateSystem; + + } + + protected function createMissionNodes() + { + $missionNodes = array(); + + foreach ($this->tree->SimulationModel as $sm) + { + $ResourceID = trim($sm->ResourceID); + + $simulationModel = $this->domAmda->createElement('simulationModel'); + $simReg = $sm->SimulatedRegion; + $simulationModel->setAttribute('xml:id', $sm->ResourceID); + + $simulationModel->setAttribute('name', $sm->ResourceHeader->ResourceName." : ".$simReg); + + $simulationModel->setAttribute('desc', $sm->ResourceHeader->Description.'<br/> ReleaseDate: '.$sm->ResourceHeader->ReleaseDate); + + if (file_exists(DATAPATH.'rank.json')) + $cmpArr = json_decode(file_get_contents(DATAPATH.'rank.json'), true); + else + $cmpArr = null; + + $index = $cmpArr["$simReg"]; + if ($index) + $simulationModel->setAttribute('rank',$index); + else + $simulationModel->setAttribute('rank', 999); + + $simulationModel->setAttribute('att', "simu/simu$simReg"); +// $this->setModelHelp($simulationModel,""); + + $this->addSimulatedRegionToTargetsFile($simReg, "JSM"); //TODO check this + + $datasetNodes = $this->createDatasetNodes($simReg); + + foreach ($datasetNodes as $ds) + { + $parameterNodes = $this->createParameterNodes($sm->OutputParameters->Parameter, $ds->getAttribute('xml:id')); + + foreach ($parameterNodes as $node ) + $ds->appendChild($node); + + $simulationModel->appendChild($ds); + } + $missionNodes[] = $simulationModel; + } + + return $missionNodes; + } + + protected function createDatasetNodes() + { + $datasetNodes = array(); + + foreach ($this->soapMethods as $soapMethod) + { + $datasetNode = $this->domAmda->createElement('dataset'); + $datasetNode->setAttribute('name', $soapMethod); + if ($soapMethod == "calculateDataPointValue_Spacecraft") + $datasetNode->setAttribute('xml:id', $this->prefix."/sc"); + else + $datasetNode->setAttribute('xml:id', $this->prefix."/xyz"); + + $datasetNode->setAttribute('globalStart', 'depending on mission'); + $datasetNodes[] = $datasetNode; + } + return $datasetNodes; + } + + protected function createParameterNodes($params, $dsid) + { + $paramNodes = array(); + + foreach ($params as $param) + { + $paramNode = $this->domAmda->createElement('parameter'); + $id = $this->param2dd($dsid."/".$param->ParameterKey); + $paramNode->setAttribute('xml:id',$id); + $paramNode->setAttribute('name', $param->ParameterKey); + $paramNode->setAttribute('desc', 'Units: '.$param->Units); + $paramNode->setAttribute('shortName',$param->ParameterKey); + $paramNode->setAttribute('needsArgs', $this->needsArgs); + + if ($this->hasComponents($param)) + { + if (strpos(trim($param->ParameterKey), ',') === false) + $comps = explode(' ',trim($param->ParameterKey)); + else + $comps = explode(',',trim($param->ParameterKey)); + + $paramNode->setAttribute('size', count($comps)); + + foreach ($comps as $comp) + { + $compNode = $this->domAmda->createElement('component'); + // $compNode->setAttribute('xml:id', $id."_".$comp); + + $compNode->setAttribute('xml:id',$this->param2dd($dsid."_".$comp)); + + $compNode->setAttribute('name', $comp); + $compNode->setAttribute('needsArgs', $this->needsArgs); + $compNode->setAttribute('shortName',$comp); + + $paramNode->appendChild($compNode); + } + } + $paramNodes[] = $paramNode; + } + + return $paramNodes; + } + + protected function createSpecialArgs($dom) + { + $this->initArgs(); + $nodes = array(); + + foreach ($this->calculateDataPointValue_Args as $key => $values) + { + $node = $dom->createElement('argument'); + $node->setAttribute('key', $key); + $node->setAttribute('name', $key); + $node->setAttribute('type', 'list'); + foreach ($values as $value) + { + $item = $dom->createElement('item'); + $item->setAttribute('name',$value); + $item->setAttribute('key', $value); + + $node->appendChild($item); + } + $node->setAttribute('default', $values[0]); + + $nodes[] = $node; + } + + $node = $dom->createElement('argument'); + + return $nodes; + } + + protected function createSpecialScArgs($dom) + { + $node = $dom->createElement('argument'); + $node->setAttribute('key', 'Spacecraft_name'); + $node->setAttribute('name', $key); + $node->setAttribute('type', 'list'); + foreach ($this->spacecraft as $value) + { + $item = $dom->createElement('item'); + $item->setAttribute('name',$value); + $item->setAttribute('key', $value); + + $node->appendChild($item); + } + $node->setAttribute('default', $this->spacecraft[0]); + + return $node; + } + + public function makeArgumentsList() + { + if (!file_exists(SimuTargetsXml)) + exit('NOT YET!'.PHP_EOL); + + if (file_exists($this->templateFile)) + unlink($this->templateFile); + + $TemplatesXml = new DomDocument("1.0"); + $TemplatesXml->formatOutput = TRUE; + $TemplatesXml->preserveWhiteSpace = FALSE; + + $rootNode = $TemplatesXml->createElement('paramTemplateList'); + $TemplatesXml->appendChild($rootNode); + + $TargetsXml = new DomDocument("1.0"); + $TargetsXml->load(SimuTargetsXml); + $targets = $TargetsXml->getElementsByTagName('Target'); + foreach ($targets as $target) + { + if ($target->hasAttribute($this->baseID)) + { + echo $target->getAttribute('xml:id').PHP_EOL; + foreach ($this->soapMethods as $soapMethod) + { + $paramNode = $TemplatesXml->createElement('paramTemplate'); + + $paramNode->setAttribute('fileName','##internalField####currentSheet##'); + $argsNode = $TemplatesXml->createElement('arguments'); + $paramNode->appendChild($argsNode); + $specialNodes = $this->createSpecialArgs($TemplatesXml); + + foreach ($specialNodes as $specialNode) + $argsNode->appendChild($specialNode); + + if ($soapMethod == "calculateDataPointValue") + { + $missionGrps = json_decode(file_get_contents(RemoteData.$target->nodeValue.".json"), true); + $node = $TemplatesXml->createElement('argument'); + $node->setAttribute('key', 'url_XYZ'); + $node->setAttribute('name', 'Mission Name'); + $node->setAttribute('type', 'list'); + + foreach ($missionGrps as $grp => $missions) + { + foreach ( $missions as $mission => $datasets) + { + echo 'MISSION: '.$mission.PHP_EOL; + foreach ($datasets as $dataset => $parameters) + { + echo " ".$dataset.PHP_EOL; + foreach ($parameters as $param => $value) + { + $item = $TemplatesXml->createElement('item'); + $item->setAttribute('name', $mission); + $item->setAttribute('key', $value); + + $node->appendChild($item); + } + } + } + } + //TODO select default s/c for each target + $node->setAttribute('default', $value); + $argsNode->appendChild($node); + $paramNode->setAttribute('paramId', $this->prefix."/xyz"); + } + else // calculateDataPointValue_Spacecraft + { + $scNode = $this->createSpecialScArgs($TemplatesXml); + $argsNode->appendChild($scNode); + $paramNode->setAttribute('paramId', $this->prefix."/sc"); + } + + $rootNode->appendChild($paramNode); + } + } + } + $TemplatesXml->save(RemoteData.$this->baseID."/".$this->templateFile); + } + + public function getData($params) + { +// $r = print_r($params,true); +// error_log($r,3,'/home/budnik/LOG'); + + if (strpos('xyz', $params['ResourceID']) > 0) + $realSoapMethod = $this->soapMethods[0]; + else + $realSoapMethod = $this->soapMethods[1]; + + $params['ResourceID'] = $this->resourceID; + + try + { + $client = new SoapClient($this->url."/".$this->WSDL, + array( + 'wsdl_cache' => 0, + 'trace' => 1, + 'soap_version'=>SOAP_1_2 + )); + } + catch (SoapFault $exception) + { + throw new Exception($exception->getMessage()." ".$exception->getTraceAsString()); + } + + $realSoapMethod = $this->soapMethods[0]; + + try + { + $file = $client->__soapCall($realSoapMethod, array($params)); + } + catch (SoapFault $exception) + { + throw new Exception($exception->getMessage()." ".$exception->getTraceAsString()); + } + + return $file; + + } +} +?> diff --git a/php/RemoteDataCenter/RemoteDataCenterClass.php b/php/RemoteDataCenter/RemoteDataCenterClass.php new file mode 100644 index 0000000..f83b73f --- /dev/null +++ b/php/RemoteDataCenter/RemoteDataCenterClass.php @@ -0,0 +1,86 @@ +<?php +/** + * @class RemoteDataCenterClass + * @brief + * @details + */ +abstract class RemoteDataCenterClass +{ + protected $url = null, $treeXML = null; + protected $baseID = null; + + protected $needsArgs = false; + protected $hasAccessUrl = false; + + public $domAmda = null, $dataCenter = null; + public $domAmdaName = "base.xml"; + public $additionalArgs = null; + + public $tree = null; + + /* + * @brief Constructor + */ + function __construct() + { + $this->baseID = get_class($this); + } + + public function param2dd($paramID) + { + $pairs = array(" " => "_","-" => "_","/" => "_","%" => "_","\\" => "_","$" => "_",":" => "_","+" =>"_","#" => "_","@" => "_","." => "_", ">" => "_", "<" => "_", "," => "_", ")" => "", "(" => "_"); + return strtr($paramID,$pairs); + } + + public function saveProxy() + { + $this->domAmda->save(RemoteData.$this->baseID."/".$this->domAmdaName); + } + + abstract public function init(); + + + abstract protected function getRemoteTree(); + abstract protected function setDataCenterAttributes(); + abstract protected function createMissionNodes(); + abstract protected function makeArgumentsList(); +// abstract protected function createDatasetNodes(); +// abstract protected function createParameterNodes(); +// abstract protected function createDatasetGroupNodes($data); + + public function initProxy() + { + if (!is_dir(RemoteData.$this->baseID)) + mkdir(RemoteData.$this->baseID); + + chmod(RemoteData.$this->baseID,0775); + + $this->getRemoteTree(); + } + + public function makeProxy() + { + $this->domAmda = new DOMDocument('1.0', 'utf-8'); + $this->domAmda->formatOutput = TRUE; + $this->domAmda->preserveWhiteSpace = FALSE; + + $dataRoot = $this->domAmda->createElement('dataRoot'); + $dataRoot->setAttribute('xml:id', 'myRemoteData-treeRootNode'); + $this->domAmda->appendChild($dataRoot); + + $this->dataCenter=$this->domAmda->createElement('dataCenter'); + + $this->dataCenter->setAttribute('xml:id', $this->baseID); + $this->dataCenter->setAttribute('name', $this->baseID); + + $dataRoot->appendChild($this->dataCenter); + + $this->setDataCenterAttributes(); + + $missionNodes = $this->createMissionNodes(); + + foreach ($missionNodes as $missionNode) + $this->dataCenter->appendChild($missionNode); + } +} +?> diff --git a/php/RemoteDataCenter/SINP.php b/php/RemoteDataCenter/SINP.php new file mode 100644 index 0000000..45d7d7d --- /dev/null +++ b/php/RemoteDataCenter/SINP.php @@ -0,0 +1,51 @@ +<?php +/** + * @class SINP + * @brief + * @details + */ +class SINP extends SimulationDataCenterClass +{ + protected $url = "http://smdc.sinp.msu.ru/impex"; + protected $treeXML = "SINP_tree.xml"; + protected $WSDL = "SINP_methods.wsdl"; + + protected $needsArgs = true; + protected $soapMethod = 'calculateDataPointValue'; + protected $templateFile = "SINP_Templates.xml"; + + // OutputFormat netCDF VOTable + public $outputFormat = "VOTable"; + + protected function createMissionNodes() + { + $missionNodes = array(); + + foreach ($this->tree->SimulationModel as $sm) + { + $ResourceID = trim($sm->ResourceID); + if (strpos($ResourceID, 'Static') === false) + { + $simulationModel = $this->domAmda->createElement('simulationModel'); + + $simulationModel->setAttribute('xml:id', $sm->ResourceID); + $simulationModel->setAttribute('name', $sm->ResourceHeader->ResourceName); + + $simulationModel->setAttribute('desc', $sm->ResourceHeader->Description.'<br/> ReleaseDate: '.$sm->ResourceHeader->ReleaseDate); + $this->setModelHelp($simulationModel,""); + + if ($this->tree->SimulationRun->count() > 0) + { + $simulationRegionNodes = $this->createSimulationRegionNodes(trim($simulationModel->getAttribute('xml:id'))); + foreach ( $simulationRegionNodes as $node ) + $simulationModel->appendChild($node); + } + $missionNodes[] = $simulationModel; + } + } + + return $missionNodes; + } + +} +?> diff --git a/php/RemoteDataCenter/SimulationDataCenterClass.php b/php/RemoteDataCenter/SimulationDataCenterClass.php new file mode 100644 index 0000000..8ab1cd2 --- /dev/null +++ b/php/RemoteDataCenter/SimulationDataCenterClass.php @@ -0,0 +1,499 @@ +<?php +/** + * @class SimulationDataCenterClass + * @brief + * @details + */ +class SimulationDataCenterClass extends RemoteDataCenterClass +{ + + protected $paramPrefix = "spase___IMPEX_NumericalOutput_"; + + protected $impex_pairs = array("/" => "_", ":" => "_", "?" => "_", '+' => "_"); + + public $alongOrbit = true; + /* + * @brief init + */ + protected function getRemoteTree() + { + $this->tree = simplexml_load_file($this->url."/".$this->treeXML); + } + + protected function setDataCenterAttributes() + { + $this->dataCenter->setAttribute('desc', $this->tree->Repository->ResourceHeader->Description.'<br/> ReleaseDate: '.$this->tree->Repository->ResourceHeader->ReleaseDate); + $this->dataCenter->setAttribute('isSimulation', "true"); + } + + public function init() {} + + // 1-st level : "Mission" : SimulationModel + protected function createMissionNodes() + { + $missionNodes = array(); + + foreach ($this->tree->SimulationModel as $sm) + { + $ResourceID = trim($sm->ResourceID); + + $simulationModel = $this->domAmda->createElement('simulationModel'); + + $simulationModel->setAttribute('xml:id', $sm->ResourceID); + $simulationModel->setAttribute('name', $sm->ResourceHeader->ResourceName); + + $simulationModel->setAttribute('desc', $sm->ResourceHeader->Description.'<br/> ReleaseDate: '.$sm->ResourceHeader->ReleaseDate); + $this->setModelHelp($simulationModel,""); + + if ($this->tree->SimulationRun->count() > 0) + { + $simulationRegionNodes = $this->createSimulationRegionNodes(trim($simulationModel->getAttribute('xml:id'))); + foreach ( $simulationRegionNodes as $node ) + $simulationModel->appendChild($node); + } + $missionNodes[] = $simulationModel; + } + + return $missionNodes; + } + + protected function setModelHelp($node, $helpFile){} + + protected function setHelpAttribute($node, $helpFile) + { + $node->setAttribute('att', $helpFile); + } + + // 2-nd level : SimulatedRegion of SimulationRun + protected function createSimulationRegionNodes($modelId) + { + if (file_exists(DATAPATH.'rank.json')) + $cmpArr = json_decode(file_get_contents(DATAPATH.'rank.json'), true); + else + $cmpArr = null; + + $simRegions = array(); + $simulationRegionNodes = array(); + + foreach($this->tree->SimulationRun as $sr) + { + if (trim($sr->Model->ModelID) == $modelId) + { + $simReg = trim($sr->SimulatedRegion); + if (! in_array($simReg, $simRegions)) + { + $simRegions[] = $simReg; + // add SimReg to TargetsSimu.xml + $this->addSimulatedRegionToTargetsFile($simReg, + $sr->SimulationDomain->CoordinateSystem->CoordinateSystemName); + + echo '$simRegions =>'.$sr->SimulatedRegion.PHP_EOL; + $simuRegion=$this->domAmda->createElement('simulationRegion'); + $simuRegion->setAttribute('xml:id', $this->baseID.'_'.$simReg); + $simuRegion->setAttribute('name', $simReg); + if (is_array($cmpArr)) + { + $target = explode('.',$simReg); + $index = $cmpArr[$target[0]]; + if ($index) + $simuRegion->setAttribute('rank',$index); + else + $simuRegion->setAttribute('rank', 999); + } + $this->setHelpAttribute($simuRegion, "simu/simu$simReg"); + $simulationRegionNodes[] = $simuRegion; + } + + $runNode = $this->createSimulationRunNode($sr); + $this->setSimulationRunNodeDescription($runNode,$sr); + + foreach ($simulationRegionNodes as $node) + { + if ($node->getAttribute('xml:id') == $this->baseID.'_'.$simReg) + { + $node->appendChild($runNode); + } + } + } + } + return $simulationRegionNodes; + } + + // 3-rd level : SimulationRun + protected function createSimulationRunNode($sr) + { + //$idSimulationRun = $sr->ResourceID; + $runNode = $this->domAmda->createElement('runID'); + $runNode->setAttribute('xml:id', $sr->ResourceID); + $runNode->setAttribute('name', $sr->ResourceHeader->ResourceName); + + foreach ($this->tree->NumericalOutput as $no) + { + if (((trim($no->InputResourceID) == $sr->ResourceID) || (trim($no->SimulationRunID) == $sr->ResourceID)) + && ((trim($no->SimulationProduct) == "3DCubes") || (trim($no->SimulationProduct) == "Spectra"))) + { + if (trim($no->SimulationProduct) == "Spectra") + $isSpectra = true; + else + $isSpectra = false; + + $datasetNode = $this->createDatasetNode($no, $isSpectra); + $runNode->appendChild($datasetNode); + } + } + return $runNode; + } + + // 4-th level : NumericalOutput (dataset) + protected function createDatasetNode($no, $isSpectra = false) + { + $dsNode = $this->domAmda->createElement('dataset'); + $dsNode->setAttribute('xml:id', trim($no->ResourceID)); + $dsName = $this->getDatasetName($no); + $dsNode->setAttribute('name', $dsName); + + $paramNodes = $this->createParameterNodes($no->Parameter, trim($no->ResourceID), $isSpectra); + + foreach ($paramNodes as $node) + { + $dsNode->appendChild($node); + } + + // Special case of IPIM + if ($this->hasAccessUrl) + { + $dsNode->setAttribute('accessUrl', $this->getAccessUrl($no)); + $dsNode->setAttribute('globalStart', $this->getStartTime($no)); + $dsNode->setAttribute('globalStop', $this->getStopTime($no)); + $dsNode->setAttribute('desc', 'TimeRange : '.$this->getStartTime($no)."-".$this->getStopTime($no)); + + } + else + { + $dsNode->setAttribute('globalStart', 'depending on mission'); + } + + return $dsNode; + } + + protected function getDatasetName($no) + { + if (trim($no->ResourceHeader->ResourceName) != '') + return trim($no->ResourceHeader->ResourceName); + else + return trim($no->ResourceID); + } + + protected function hasComponents($param) + { + if ($param->Particle->Qualifier) + { + return $param->Particle->Qualifier != "Scalar" && $param->Particle->Qualifier != "Total"; + + } + if ($param->Field->Qualifier) + { + return $param->Field->Qualifier != "Scalar" && $param->Field->Qualifier != "Total"; + } + + if (strpos(trim($param->ParameterKey), ',') === false) + $comps = explode(' ',trim($param->ParameterKey)); + else + $comps = explode(',',trim($param->ParameterKey)); + + return count($comps) > 1; + } + + // 5-th level : Parameters & Components + protected function createParameterNodes($params, $dsid, $isSpectra = false) + { + $paramNodes = array(); + foreach ($params as $param) + { + $paramNode = $this->domAmda->createElement('parameter'); + //$p = trim($sm->ResourceID).'/'.$argumentsParameterKey; + $id = $this->param2dd($dsid."/".$param->ParameterKey); + $paramNode->setAttribute('xml:id',$id); + $paramNode->setAttribute('name', $param->Name); + $paramNode->setAttribute('desc', 'Units: '.$param->Units); + $paramNode->setAttribute('needsArgs', $this->needsArgs); + $paramNode->setAttribute('units', $param->Units); + + if (!$isSpectra) + { + if ($this->hasComponents($param)) + { + if (strpos(trim($param->ParameterKey), ',') === false) + $comps = explode(' ',trim($param->ParameterKey)); + else + $comps = explode(',',trim($param->ParameterKey)); + + $paramNode->setAttribute('size', count($comps)); + + foreach ($comps as $comp) + { + $compNode = $this->domAmda->createElement('component'); + // $compNode->setAttribute('xml:id', $id."_".$comp); + $compNode->setAttribute('xml:id', $this->param2dd($dsid."_".$comp)); + $compNode->setAttribute('name', $comp); + $compNode->setAttribute('shortName',$comp); + $compNode->setAttribute('needsArgs', $this->needsArgs); + + $paramNode->appendChild($compNode); + } + } + $paramNode->setAttribute('shortName',$param->ParameterKey); + } + else + { + $paramNode->setAttribute('size', $this->getEnergyBinsNumber($param)); + $paramNode->setAttribute('display_type', 'spectrogram'); + $paramNode->setAttribute('isSpectra', true); + $paramNode->setAttribute('energyRange', 'EnergyRange'); // check if it allways so - should be ! SPASE + $paramNode->setAttribute('shortName','ParticleFlux'); + $paramNode->setAttribute('energyUnits',$param->Particle->EnergyRange->Units); + } + + $paramNodes[] = $paramNode; + } + + return $paramNodes; + } + + // EnergyBinsNumber + protected function getEnergyBinsNumber($param) + { + return count($param->Particle->EnergyRange->Bin); + } + + // Run Description + protected function getCoordinateSystem($coordSystem) + { + return "<b>Reference Frame :</b><br/>".$coordSystem->CoordinateSystemName.",".$coordSystem->CoordinateRepresentation; + } + // + protected function getRegionBoundaries($domain, $region) + { + $simReg = explode(".", $region->SimulatedRegion); + $desc = "<b><br/>Domain: </b>Units: radius of ".$simReg[0]."<br/>"; + // Recalcul domain from km or m to rad + $unitsDomain = $domain->Units; + + $spatialDimension = $domain->SpatialDimension; + $radius = $region->Radius; + + $regionParameterRadius = trim($region->Radius['Units']); + $radiusUnits = trim($domain->Units); + + $ValidMinsDom = preg_split ("/\s+/", $domain->ValidMin); + $ValidMaxsDom = preg_split ("/\s+/", $domain->ValidMax); + $coordLabel = preg_split ("/\s+/",$domain->CoordinatesLabel); + // Transform Simulation Domain to Martian radius from km & m + for($j=0; $j< $spatialDimension; $j++) + { + if ((strtolower($radiusUnits) == 'km') || (strtolower($radiusUnits)== 'm')) + { + if ($regionParameterRadius != $radiusUnits) + { + if (strtolower($radiusUnits) == 'km') $radius = ($region->Radius)/1000; + else $radius = ($region->Radius) * 1000; + } + + $ValidMinsDom[$j] = number_format($ValidMinsDom[$j]/$radius,2); + $ValidMaxsDom[$j] = number_format($ValidMaxsDom[$j]/$radius,2); + } + + $desc .= $coordLabel[$j]."=[".$ValidMinsDom[$j].', '.$ValidMaxsDom[$j]."]<br/>"; + + } + return $desc; + } + + protected function setSimulationRunNodeDescription($runNode,$sr) + { + } + + protected function getProperties($sr) + { + } + + protected function addSimulatedRegionToTargetsFile($simReg, $coordName) + { + $TargetsXml = new DomDocument("1.0"); + $TargetsXml->formatOutput = TRUE; + $TargetsXml->preserveWhiteSpace = FALSE; + + if (file_exists(SimuTargetsXml)) + { + $TargetsXml->load(SimuTargetsXml); + $rootElement = $TargetsXml->documentElement; + } + else + { + $rootElement = $TargetsXml->createElement('Targets'); + $TargetsXml->appendChild($rootElement); + } + + $targetNode = $TargetsXml->getElementById($simReg); + + if ($targetNode == null) + { + $simRegMain = explode(".",$simReg); + $targetNode = $TargetsXml->createElement("Target", $simReg); + $targetNode->setAttribute('CoordName',$coordName); + $targetNode->setAttribute('TargetMain',$simRegMain[0]); + $targetNode->setAttribute('xml:id',$simReg); + $targetNode->setAttribute($this->baseID,true); + $rootElement->appendChild($targetNode); + } + // add Simulation Data Center to existing target + else + { + $targetNode = $targetNode->setAttribute($this->baseID,true); + } + + $TargetsXml->save(SimuTargetsXml); + } + + public function getFileName($resourceID, $templateArgs, $start) + { + $fileName = strtr($resourceID, $this->impex_pairs); + foreach ($templateArgs as $key => $value) + $fileName .= "_".$value; + + + $fileName .= "_".$start.'.xml'; + + return $fileName; + } + + public function getMask($resourceID, $templateArgs) + { + $fileMask = strtr($resourceID, $this->impex_pairs); + foreach ($templateArgs as $key => $value) + $fileMask .= "_".$value; + + $fileMask .= '*.xml'; + + return $fileMask; + } + + public function makeArgumentsList() + { + if (!file_exists(SimuTargetsXml)) + exit('NOT YET!'.PHP_EOL); + + if (file_exists($this->templateFile)) + unlink($this->templateFile); + + $TemplatesXml = new DomDocument("1.0"); + $TemplatesXml->formatOutput = TRUE; + $TemplatesXml->preserveWhiteSpace = FALSE; + + $rootNode = $TemplatesXml->createElement('paramTemplateList'); + $TemplatesXml->appendChild($rootNode); + + $TargetsXml = new DomDocument("1.0"); + $TargetsXml->load(SimuTargetsXml); + $targets = $TargetsXml->getElementsByTagName('Target'); + foreach ($targets as $target) + { + if ($target->hasAttribute($this->baseID)) + { + echo $target->getAttribute('xml:id').PHP_EOL; + $paramNode = $TemplatesXml->createElement('paramTemplate'); + $paramNode->setAttribute('paramId',$this->baseID."_".$this->param2dd($target->getAttribute('xml:id'))); + $paramNode->setAttribute('fileName','##orbit##'); + $argsNode = $TemplatesXml->createElement('arguments'); + $paramNode->appendChild($argsNode); + $specialNodes = $this->createSpecialArgs($TemplatesXml); + + foreach ($specialNodes as $specialNode) + $argsNode->appendChild($specialNode); + + $missionGrps = json_decode(file_get_contents(RemoteData.$target->nodeValue.".json"), true); + $node = $TemplatesXml->createElement('argument'); + $node->setAttribute('key', 'url_XYZ'); + $node->setAttribute('name', 'Mission Name'); + $node->setAttribute('type', 'list'); + foreach ($missionGrps as $grp => $missions) + { + foreach ( $missions as $mission => $datasets) + { + echo 'MISSION: '.$mission.PHP_EOL; + foreach ($datasets as $dataset => $parameters) + { + echo " ".$dataset.PHP_EOL; + foreach ($parameters as $param => $value) + { + $item = $TemplatesXml->createElement('item'); + $item->setAttribute('name', $mission); + $item->setAttribute('key', $value); + + $node->appendChild($item); + } + } + } + } + //TODO select default s/c for each target + $node->setAttribute('default', $value); + $argsNode->appendChild($node); + $rootNode->appendChild($paramNode); + } + } + $TemplatesXml->save(RemoteData.$this->baseID.'/'.$this->templateFile); + } + + protected function createSpecialArgs($dom = null) + { + return array(); + } + + public function getTableDefinition() + { + $res = array(); + $res["tableDefType"] = "SELECT"; + $res["channelsDefType"] = "BOUND"; + $res["data"] = array(); + $res["data"]["bound"] = $this->energyTableName; + + return $res; + } + + public function getData($params, $isSpectra = false) + { +// $r = print_r($params,true); +// error_log($r,3,'/home/budnik/LOG'); + + try + { + $client = new SoapClient($this->url."/".$this->WSDL, + array( + 'wsdl_cache' => 0, + 'trace' => 1, + 'soap_version'=>SOAP_1_2 + )); + } + catch (SoapFault $exception) + { + throw new Exception($exception->getMessage()." ".$exception->getTraceAsString()); + } + + if ($isSpectra) + $soapMethod = $this->soapMethodSpectra; + else + $soapMethod = $this->soapMethod; + + try + { + $file = $client->__soapCall($soapMethod, array($params)); + } + catch (SoapFault $exception) + { + throw new Exception($exception->getMessage()." ".$exception->getTraceAsString()); + } + + return $file; + } +} +?> diff --git a/php/RemoteDataCenter/makeArgs.php b/php/RemoteDataCenter/makeArgs.php new file mode 100644 index 0000000..df4338c --- /dev/null +++ b/php/RemoteDataCenter/makeArgs.php @@ -0,0 +1,27 @@ +<?php +/* +* Executable to make arguments lists for IMPEX +* Uses target.json +*/ + require_once "../config.php"; + + if (!defined('SimuTargetsXml')) + exit('SimuTargetsXml is not defined in config.php'.PHP_EOL); + + if (!function_exists('__autoload')) { + function __autoload($class_name) { + require_once $class_name . '.php'; + } + } + + $simuBases = array("LATMOS", "FMI_HYBRID", "FMI_GUMICS", "LESIA"); + + foreach ($simuBases as $class) + { + echo PHP_EOL.$class.PHP_EOL; + $center = new $class(); + + $center->makeArgumentsList(); + } + +?> \ No newline at end of file diff --git a/php/RemoteDataCenter/makeOrbitsArgs.php b/php/RemoteDataCenter/makeOrbitsArgs.php new file mode 100644 index 0000000..1374c8d --- /dev/null +++ b/php/RemoteDataCenter/makeOrbitsArgs.php @@ -0,0 +1,82 @@ +<?php +/* +* Executable to make target.json files for IMPEX url_XYZ args +* is launched AFTER makeProxy and makeOrbitsList +*/ + + require_once "../config.php"; + + if (!defined('orbitsXml')) + exit("orbitsXml is not defined in config.php".PHP_EOL); + + if (!defined('SimuTargetsXml')) + exit('SimuTargetsXml is not defined in config.php'.PHP_EOL); + + if (!file_exists(orbitsXml)) + exit("ERROR : NO Orbites.xml FILE !!! Run makeOrbitsList.php".PHP_EOL); + + if (!file_exists(SimuTargetsXml)) + exit("ERROR : NO TargetsSimu FILE !!! Run makeProxy.php".PHP_EOL); + + $targetXml = simplexml_load_file(SimuTargetsXml); + $orbitsXml = new DomDocument("1.0"); + $orbitsXml->load(orbitsXml); + $xpath = new DOMXpath($orbitsXml); + + $targets = $targetXml->Target; + + foreach ($targets as $target) + { + if (file_exists(RemoteData."$target.json")) + unlink(RemoteData."$target.json"); + + $targetMain = $target['TargetMain']; + $coordImpex = $target['CoordName']; + + // Mecrury double definition + if ($coordImpex == "HSM") + $coordImpex == "MSM"; + + // general case + $params = $xpath->query('//orbites[@target="'.$target.'" and @coordinate_system="'.$coordImpex.'"]'); + + // case of targetImpex = Jupiter.Magnetosphere; targetAmda = Jupiter + if ($params->length == 0) + $params = $xpath->query('//orbites[@target="'.$targetMain.'" and @coordinate_system="'.$coordImpex.'"]'); + + // case of targetImpex = Ganymede; targetAmda = Jupiter.Ganymede + if ($params->length == 0) + // $params = $xpath->query('//orbites[contains(@target,"'.$target.')" and @coordinate_system="'.$coordImpex.'"]'); + $params = $xpath->query('//orbites[contains(@target,"'.$target.'")]'); + + if ($params->length > 0) + { + $dsArr = array(); + $misArr = array(); + $misGrpArr = array(); + + foreach ($params as $param) + { + $dsId = $param->getAttribute('dataset'); + + if (!is_array($dsArr[$dsId])) $dsArr[$dsId] = array(); + $dsArr[$dsId][] = $param->getAttribute('xml:id'); + + $misId = $param->getAttribute('mission'); + if (!is_array($misArr[$misId])) $misArr[$misId] = array(); + $misArr[$misId][$dsId] = $dsArr[$dsId]; + + // Mission Group + if ($param->hasAttribute('missionGroup')) + $misGrpId = $param->getAttribute('missionGroup'); + else + $misGrpId = 'None'; + + if (!is_array($misGrpArr[$misGrpId])) $misGrpArr[$misGrpId] = array(); + $misGrpArr[$misGrpId][$misId] = $misArr[$misId]; + } + + file_put_contents(RemoteData.$target.'.json', json_encode($misGrpArr)); + } + } +?> \ No newline at end of file diff --git a/php/RemoteDataCenter/makeOrbitsList.php b/php/RemoteDataCenter/makeOrbitsList.php new file mode 100644 index 0000000..63bce13 --- /dev/null +++ b/php/RemoteDataCenter/makeOrbitsList.php @@ -0,0 +1,76 @@ +<?php +/* +* Executable to make Orbits.xml with the description for all Ephemeris parameters +* Uses LocalParams.xml and AMDA params descriptions +*/ + require_once "../config.php"; + + if (!defined('orbitsXml')) + exit("orbitsXml is not defined in config.php".PHP_EOL); + + $pairs = array("-" => "_" ); + + $amdaXml = new DomDocument("1.0"); + $amdaXml->load(DATAPATH."LocalParams.xml"); + + $xpath = new DOMXpath($amdaXml); + + $amdaParamDir = DATAPATH."newKernelDDBase"; + + $orbitsXml = new DomDocument("1.0"); + $orbitsXml->formatOutput = TRUE; + $orbitsXml->preserveWhiteSpace = FALSE; + + $orbitsRoot = $orbitsXml->createElement('orbitesList'); + $orbitsXml->appendChild($orbitsRoot); + + $nodesAmda = $xpath->query('//*[@target]'); + + foreach ($nodesAmda as $node) + { + $target = $node->getAttribute('target'); + + if ( (($node->tagName == 'mission' && $node->getElementsByTagName('observatory')->length == 0) || + ($node->tagName == 'observatory') ) && $node->getAttribute('name') != $target ) + { + $instruments = $node->getElementsByTagName('instrument'); + foreach ($instruments as $ins) + { + if ($ins->getAttribute('name') != 'Ephemeris') continue; + $parameters = $ins->getElementsByTagName('parameter'); + foreach ($parameters as $parameter) + { + if ($parameter->hasAttribute('size') && $parameter->getAttribute('size') == '3') + { + $param_file = $amdaParamDir."/".$parameter->getAttribute('xml:id').".xml"; + if (file_exists($param_file)) + { + $paramXml = simplexml_load_file($param_file); + + $orbitNode = $orbitsXml->createElement('orbites'); + $dsId = strtr($paramXml->info->dataset_id,$pairs); + $orbitNode->setAttribute('xml:id',$parameter->getAttribute('xml:id')); + $orbitNode->setAttribute('coordinate_system', $paramXml->info->coordinates_system); + $orbitNode->setAttribute('units', $paramXml->info->units); + $orbitNode->setAttribute('mission', $node->getAttribute('name')); + + if ( $node->tagName == 'observatory' ) + $orbitNode->setAttribute('missionGroup',$node->parentNode->getAttribute('name')); + + $orbitNode->setAttribute('dataset', $dsId); + $ds = $amdaXml->getElementById($paramXml->info->dataset_id); + if ($ds->hasAttribute('target')) + $orbitNode->setAttribute('target', $ds->getAttribute('target')); + else + $orbitNode->setAttribute('target', $target); + + $orbitsRoot->appendChild($orbitNode); + } + } + } + } + } + } + + $orbitsXml->save(orbitsXml); +?> diff --git a/php/RemoteDataCenter/makeProxy.php b/php/RemoteDataCenter/makeProxy.php new file mode 100644 index 0000000..f505cb3 --- /dev/null +++ b/php/RemoteDataCenter/makeProxy.php @@ -0,0 +1,31 @@ +<?php +/* +* Executable to make 'base.xml' proxies for IMPEX centers from IMPEX original trees +*/ + + if (!function_exists('__autoload')) { + function __autoload($class_name) { + require_once $class_name . '.php'; + } + } + + require_once "../config.php"; + + if (!defined('SimuTargetsXml') + exit('SimuTargetsXml is not defined in config.php'.PHP_EOL); + + if (file_exists(SimuTargetsXml)) unlink(SimuTargetsXml); + + $simuBases = array("IPIM", "LATMOS", "FMI_HYBRID", "FMI_GUMICS", "SINP", "LESIA"); + + foreach ($simuBases as $class) + { + echo PHP_EOL.$class.PHP_EOL; + $center = new $class(); + + $center->initProxy(); + $center->makeProxy(); + $center->saveProxy(); + } + +?> \ No newline at end of file diff --git a/php/classes/AmdaAction.php b/php/classes/AmdaAction.php index 9dd6a10..3e91373 100644 --- a/php/classes/AmdaAction.php +++ b/php/classes/AmdaAction.php @@ -352,10 +352,13 @@ class AmdaAction break; case 'remoteSimuParam' : - + + $globalStart = null; + $isSimulation = true; - - if ($id == 'spase://IMPEX/SimulationModel/FMI/GUMICS' ) + + if ($child->getAttribute('isAddable')) + //if ($id == 'spase://IMPEX/SimulationModel/FMI/GUMICS' ) { $isLeaf = false; $isAddable = true; @@ -375,7 +378,25 @@ class AmdaAction { $rank = $child->getAttribute('rank'); } - + + if ( $child->tagName == 'parameter') + { + if ($child->parentNode->hasAttribute('globalStart')) + { + $globalStart = $child->parentNode->getAttribute('globalStart'); + $globalStop = $child->parentNode->getAttribute('globalStop'); + } + } + + if ( $child->tagName == 'component') + { + if ($child->parentNode->parentNode->hasAttribute('dataStart')) + { + $globalStart = $child->parentNode->parentNode->getAttribute('dataStart'); + $globalStop = $child->parentNode->parentNode->getAttribute('dataStop'); + } + } + case 'remoteParam' : if ($child->getAttribute('isSimulation') && $child->tagName == 'dataCenter') @@ -446,11 +467,16 @@ class AmdaAction $isScatter = false; $isSpectra = true; } - - $childrenToReturn[] = array('text' => $name,'alias' => $alias, - 'id' => $id,'nodeType' => $nodeType, 'info' => $info, 'help' => $help, - 'leaf' => $isLeaf, 'disable' => $disable, 'isParameter' => $isParameter, - 'isScatter' => $isScatter, 'isSpectra' => $isSpectra, 'needsArgs' => $needsArgs, "component_info" => $component_info); + if ($globalStart) + $childrenToReturn[] = array('text' => $name,'alias' => $alias, + 'id' => $id,'nodeType' => $nodeType, 'info' => $info, 'help' => $help, 'globalStart' => $globalStart, + 'globalStop' => $globalStop, 'leaf' => $isLeaf, 'disable' => $disable, 'isParameter' => $isParameter, + 'isScatter' => $isScatter, 'isSpectra' => $isSpectra, 'needsArgs' => $needsArgs, "component_info" => $component_info); + else + $childrenToReturn[] = array('text' => $name,'alias' => $alias, + 'id' => $id,'nodeType' => $nodeType, 'info' => $info, 'help' => $help, + 'leaf' => $isLeaf, 'disable' => $disable, 'isParameter' => $isParameter, + 'isScatter' => $isScatter, 'isSpectra' => $isSpectra, 'needsArgs' => $needsArgs, "component_info" => $component_info); } else { @@ -579,7 +605,7 @@ class AmdaAction default: return array("error" => $nodeType." NOT_IMPLEMENTED_YET"); } - return $objectMgr -> getUploadedObject($name, $format, true); + return $objectMgr->getUploadedObject($name, $format, true); } @@ -589,13 +615,13 @@ class AmdaAction public function getAsciiFile($obj) { $objectMgr = new FilesMgr(); - return $objectMgr -> getAsciiFile($obj->fileName); + return $objectMgr->getAsciiFile($obj->fileName); } - public function getMyParamInfo($object) + public function getMyParamInfo($object) { $objectMgr = new FilesMgr(); - return $objectMgr -> getParamInfo($object); + return $objectMgr->getParamInfo($object); } /* @@ -614,7 +640,7 @@ class AmdaAction default: return array("error" => $nodeType." NOT_IMPLEMENTED_YET"); } - return $objectMgr -> getTmpObject($folderId, $name, true); + return $objectMgr->getTmpObject($folderId, $name, true); } @@ -639,7 +665,7 @@ class AmdaAction $objectMgr = new RequestMgr($nodeType); break; case 'bkgWorks' : - require_once(INTEGRATION_SRC_DIR."RequestManager.php"); + require_once(INTEGRATION_SRC_DIR."RequestManager.php"); return $this->executeRequest($id, FunctionTypeEnumClass::PROCESSGETINFO); break; case 'myData' : @@ -648,7 +674,7 @@ class AmdaAction default: return array("error" => $nodeType." NOT_IMPLEMENTED_YET"); } - return $objectMgr -> getObject($id, $nodeType); + return $objectMgr->getObject($id, $nodeType); } /* @@ -677,7 +703,7 @@ class AmdaAction $obj->id = substr($obj->id,strlen('alias_')); break; case 'bkgWorks' : - require_once(INTEGRATION_SRC_DIR."RequestManager.php"); + require_once(INTEGRATION_SRC_DIR."RequestManager.php"); return $this->executeRequest($obj, FunctionTypeEnumClass::PROCESSDELETE); case 'myData' : @@ -1224,10 +1250,6 @@ class AmdaAction } else { - $myBaseMgr = new BaseManager(); - $myBaseMgr->delSimuFiles('mysimudata'); - $myBaseMgr->delSimuFiles('mywsrdata'); - $this->cleanUserWS(); } return; @@ -1269,19 +1291,28 @@ class AmdaAction public function addRun($obj) { $myBestRunsMgr = new BestRunsMgr(); - $myBestRunsMgr->init(); + + $ok = $myBestRunsMgr->init(); + + if (!$ok) + return array('success'=>false,'message'=>'cannot init addRun'); + $myBestRunsMgr->addRuns($obj); - - $res = array('success' => true,'addedRuns' => $obj); - return $res; + + return array('success'=>true,'addedRuns'=>$obj); } //AKKA - New action to clean user WS public function cleanUserWS() { $this->rrmdir(USERDIR.'DOWNLOAD.TEMP'); - require_once(INTEGRATION_SRC_DIR."RequestManager.php"); + IHMConfigClass::setUserName($this->user); + + // delete impex params and data + $impexParamMgr = new ImpexParamManager(); + $impexParamMgr->deleteImpexStaff(); + return $this->executeRequest($obj, FunctionTypeEnumClass::PROCESSCLEAN); } @@ -1321,19 +1352,31 @@ class AmdaAction public function getParamPlotInit($obj) { require_once(INTEGRATION_SRC_DIR."RequestManager.php"); + // IMPEX param + if (preg_match("#^spase___IMPEX_#",$obj->paramId)) + $type = 'impex_plot_init'; + else + $type = 'plot_init'; + $inputobj = (Object)array( 'paramId' => $obj->paramId, - 'type' => 'plot_init' + 'type' => $type ); return $this->executeRequest($inputobj, FunctionTypeEnumClass::PARAMINFO); } public function getParamInfo($obj) { - require_once(INTEGRATION_SRC_DIR."RequestManager.php"); + require_once(INTEGRATION_SRC_DIR."RequestManager.php"); + // IMPEX param + if (preg_match("#^spase___IMPEX_#",$obj->paramId)) + $type = 'impex_param_info'; + else + $type = 'param_info'; + $inputobj = (Object)array( 'paramId' => $obj->paramId, - 'type' => 'param_info' + 'type' => $type ); return $this->executeRequest($inputobj, FunctionTypeEnumClass::PARAMINFO); } diff --git a/php/classes/BaseManager.php b/php/classes/BaseManager.php old mode 100755 new mode 100644 index 6a6201f..62a8851 --- a/php/classes/BaseManager.php +++ b/php/classes/BaseManager.php @@ -7,254 +7,203 @@ * */ -class BaseManager { - - public $xp, $xslt; - public $baseDom; - private $fileDomName, $baseDomName; - - function __construct() - { - if (getenv('USER_DATA_PATH') != "") - $this->baseDomName = getenv('USER_DATA_PATH')."base.xml"; - else - $this->baseDomName = USERDATADIR."base.xml"; - - $this->fileDomName = USERWSDIR."Files.xml"; - $this->baseDom = new DomDocument("1.0"); - - if (file_exists($this->baseDomName)) - $this->baseDom->load($this->baseDomName); - else { - $baseElement = $this->baseDom->createElement("base"); - $this->baseDom->appendChild($baseElement); - } - - $this->xp = new domxpath($this->baseDom); - $this->xslt = new XSLTProcessor(); - - $xsl = new DomDocument("1.0"); - $xsl->load(XMLPATH."base.xsl"); - - $this->xslt->importStylesheet($xsl); - } +class BaseManager +{ + public $xp, $xslt; + public $baseDom; + private $fileDomName, $baseDomName; + + function __construct() + { + define("DELTA", 120); // minumum file size in secs + + if (getenv('USER_DATA_PATH') != "") + $this->baseDomName = getenv('USER_DATA_PATH')."base.xml"; + else + $this->baseDomName = USERDATADIR."base.xml"; + + $this->fileDomName = USERWSDIR."Files.xml"; + + $this->baseDom = new DomDocument("1.0"); + + if (file_exists($this->baseDomName)) + $this->baseDom->load($this->baseDomName); + else { + $baseElement = $this->baseDom->createElement("base"); + $this->baseDom->appendChild($baseElement); + } + + $this->xp = new domxpath($this->baseDom); + $this->xslt = new XSLTProcessor(); + + $xsl = new DomDocument("1.0"); + $xsl->load(XMLPATH."base.xsl"); + $this->xslt->importStylesheet($xsl); + } /* * Provide an unique ID */ - public function getNewId() - { - // Get all ID attributes - $vis = $this->xp->query("//vi/@id"); - - if ($vis->length > 0) { - $idList = array(); - if($vis->length > 0) for ($i = 0; $i < $vis->length; $i++) - $idList[] = $vis->item($i)->nodeValue; - sort($idList); - - for ($i = 0; $i < count($idList); $i++) { - if ($idList[$i] > $i) { - $newID = $i; - break; - } - $newID = $i+1; - } - } else - $newID = 0; - - return $newID; - } + public function getNewId() + { + // Get all ID attributes + $vis = $this->xp->query("//vi/@id"); + + if ($vis->length > 0) { + $idList = array(); + if($vis->length > 0) for ($i = 0; $i < $vis->length; $i++) + $idList[] = $vis->item($i)->nodeValue; + sort($idList); + + for ($i = 0; $i < count($idList); $i++) { + if ($idList[$i] > $i) { + $newID = $i; + break; + } + $newID = $i+1; + } + } else + $newID = 0; + + return $newID; + } - public function fileMask($fileName, $maskName) - { - $mask = explode("*", $maskName); - - for ($i = 0; $i < count($mask); $i++) - if ($mask[$i] != null) - if (strpos($fileName, $mask[$i]) === false) return false; - return true; - } - -/* -* new file is uploaded -> check if it should be added into MASK -*/ - public function addFile($fileName) - { - $fileDom = new DomDocument("1.0"); - $fileDom->load($this->fileDomName); - $file = $fileDom->getElementById($fileName); - $lastMask = null; - - $masks = $this->baseDom->getElementsByTagName("mask"); - - if ($masks->length > 0) - { - foreach ($masks as $mask) - if ($this->fileMask($fileName, $mask->nodeValue)) - { - $lastMask = $mask->nodeValue; - - $newFile = $this->baseDom->createElement("file"); - $newFile->setAttribute('name', $fileName); - $start = $file->getAttribute('start'); - $stop = $file->getAttribute('stop'); - $newFile->setAttribute('start', $start); - $newFile->setAttribute('stop', $stop); - - $vi = $mask->parentNode; - $vi->appendChild($newFile); - - $vi_start = $vi->getAttribute('start'); - if ($vi_start > $start) $vi->setAttribute('start',$start); - $vi_stop = $vi->getAttribute('stop'); - if ($vi_stop < $stop) $vi->setAttribute('stop',$stop); - } - } - - $this->xslt->transformToDoc($this->baseDom)->save($this->baseDomName); - - return $lastMask; - } - -/* -* special add method for "simulation" files -*/ - public function addWsFile($fileName, $start, $stop) - { - // add file description to base.xml file - $masks = $this->baseDom->getElementsByTagName("mask"); - - if ($masks->length > 0) - { - foreach ($masks as $mask) - if ($this->fileMask($fileName, $mask->nodeValue)) - { - $lastMask = $mask->nodeValue; - $newFile = $this->baseDom->createElement("file"); - $newFile->setAttribute('name', $fileName); - $newFile->setAttribute('start', $start); - $newFile->setAttribute('stop', $stop); - $vi = $mask->parentNode; - $vi->appendChild($newFile); - - $vi_start = $vi->getAttribute('start'); - if ($vi_start > $start) $vi->setAttribute('start',$start); - $vi_stop = $vi->getAttribute('stop'); - if ($vi_stop < $stop) $vi->setAttribute('stop',$stop); - } - } - - $this->xslt->transformToDoc($this->baseDom)->save($this->baseDomName); - - return $lastMask; - } + /* + * Get filename to create IMPEX parameter if VI exists already + */ + public function getFirstFileName($viID) + { + $vis = $this->xp->query("//vi[@id = '".$viID."']"); + if ($vis->length > 0) + $vi = $vis->item(0); + else + throw new Exception('No VI '.$viID); + + $files = $vi->getElementsByTagName('file'); + if ($files->length > 0) + return $files->item(0)->getAttribute('name'); + + throw new Exception('Empty VI '.$viID); + } + + + public function fileMask($fileName, $maskName) + { + $mask = explode("*", $maskName); + + for ($i = 0; $i < count($mask); $i++) + if ($mask[$i] != null) + if (strpos($fileName, $mask[$i]) === false) return false; + + return true; + } + /* + * New file is uploaded -> check if it should be added into MASK + */ + public function addFile($fileName, $start = null, $stop = null) + { + // standard file upload : start / stop get from file + if (!$start) + { + $fileDom = new DomDocument("1.0"); + $fileDom->load($this->fileDomName); + $file = $fileDom->getElementById($fileName); + $start = $file->getAttribute('start'); + $stop = $file->getAttribute('stop'); + } + + $lastMask = null; + + $masks = $this->baseDom->getElementsByTagName("mask"); + + if ($masks->length > 0) + { + foreach ($masks as $mask) + if ($this->fileMask($fileName, $mask->nodeValue)) + { + $lastMask = $mask->nodeValue; + + $newFile = $this->baseDom->createElement("file"); + $newFile->setAttribute('name', $fileName); + + $newFile->setAttribute('start', $start); + $newFile->setAttribute('stop', $stop); + + $vi = $mask->parentNode; + $vi->appendChild($newFile); + + $vi_start = $vi->getAttribute('start'); + if (!$vi_start || $vi_start > $start) + $vi->setAttribute('start',$start); + + $vi_stop = $vi->getAttribute('stop'); + if (!$vi_stop || $vi_stop < $stop) + $vi->setAttribute('stop',$stop); + } + } + // sort by time + $this->xslt->transformToDoc($this->baseDom)->save($this->baseDomName); + + return $lastMask; + } + /* * File was deleted */ - public function delFile($fileObj) - { - $start = $fileObj->getAttribute($start); - $stop = $fileObj->getAttribute($stop); - $vi = $fileObj->parentNode; - $vi->removeChild($fileObj); - $mask = $vi->getElementsByTagName("mask")->item(0)->nodeValue; - $length = $vi->getElementsByTagName("file")->length; - - if ($length == 0) - { - $this->baseDom->getElementsByTagName("base")->item(0)->removeChild($vi); - } - else - { - $vi->setAttribute('start', $this->updateStart($vi)); - $vi->setAttribute('stop',$this->updateStop($vi)); - } - - $this->baseDom->save($this->baseDomName); - - return array('mask' => $mask, 'length' => $length); - } - -/* -* Delete simu VI and simu Download Files -*/ - public function delSimuFiles($data) - { - if (file_exists(USERWSDIR.'WsParams.xml')) - { - $simuVIs = $this->xp->query("//vi[@moreData = 'true']"); - $dom = new DomDocument("1.0"); - $dom->load(USERWSDIR.'WsParams.xml'); - $xp = new domxpath($dom); - $dataList = $data.'List'; - $mysimudataList = $dom->getElementsByTagName($dataList); - foreach ($simuVIs as $simuVI) - { - $files = $simuVI->getElementsByTagName('file'); - foreach ($files as $file) - { - $fileName = $file->getAttribute('name'); - if (file_exists(USERDATADIR.$fileName)) unlink(USERDATADIR.$fileName); - } - $vi = $simuVI->getAttribute("id"); - $mask = $simuVI->getElementsByTagName('mask')->item(0)->nodeValue; - if ((strpos($mask, 'CLWEB_') !== false && $data == "mywsrdata") || (strpos($mask, 'CLWEB_') === false && $data == "mysimudata")) { - $mysimdata = $xp->query("//".$data."[@mask='".$mask."']/@*[namespace-uri()='http://www.w3.org/XML/1998/namespace' and local-name()='id']"); - $sumuParamName = $mysimdata->item(0)->nodeValue; - $base = $simuVI->parentNode; - $base->removeChild($simuVI); - - if (file_exists(USERWSDIR.$sumuParamName.'.xml')) - unlink(USERWSDIR.$sumuParamName.'.xml'); - } - } - - $mysimudata = $xp->query("//".$data.""); - - if ($mysimudata->length > 0) - { - foreach($mysimudata as $simudata) - $mysimudataList->item(0)->removeChild($simudata); - } - - $dom->save(USERWSDIR.'WsParams.xml'); - $this->baseDom->save($this->baseDomName); - } - - return; - } + public function delFile($fileObj) + { + $start = $fileObj->getAttribute($start); + $stop = $fileObj->getAttribute($stop); + $vi = $fileObj->parentNode; + $vi->removeChild($fileObj); + $mask = $vi->getElementsByTagName("mask")->item(0)->nodeValue; + $length = $vi->getElementsByTagName("file")->length; + + if ($length == 0) + { + $this->baseDom->getElementsByTagName("base")->item(0)->removeChild($vi); + } + else + { + $vi->setAttribute('start', $this->updateStart($vi)); + $vi->setAttribute('stop',$this->updateStop($vi)); + } + + $this->baseDom->save($this->baseDomName); + + return array('mask' => $mask, 'length' => $length); + } -/* -* -*/ - public function updateStart($vi) - { - $files = $vi->getElementsByTagName("file"); - if ($files->length == 0) return "EMPTY"; + /* + * + */ + public function updateStart($vi) + { + $files = $vi->getElementsByTagName("file"); + if ($files->length == 0) return "EMPTY"; - $starts = Array(); - foreach ($files as $file) - $starts[] = $file->getAttribute("start"); + $starts = Array(); + foreach ($files as $file) + $starts[] = $file->getAttribute("start"); - return min($starts); - } + return min($starts); + } /* * */ - public function updateStop($vi) - { - $files = $vi->getElementsByTagName("file"); - if ($files->length == 0) return "EMPTY"; + public function updateStop($vi) + { + $files = $vi->getElementsByTagName("file"); + if ($files->length == 0) return "EMPTY"; - $stops = Array(); - foreach ($files as $file) - $stops[] = $file->getAttribute("stop"); + $stops = Array(); + foreach ($files as $file) + $stops[] = $file->getAttribute("stop"); - return max($stops); - } + return max($stops); + } /* * New mask was added @@ -287,248 +236,188 @@ class BaseManager { } } - $newVi->setAttribute("start", min($starts)); - $newVi->setAttribute("stop", max($stops)); + $newVi->setAttribute("start", min($starts)); + $newVi->setAttribute("stop", max($stops)); } } /* * */ - public function getOldMask($fileMask) - { - $masks = $this->baseDom->getElementsByTagName("mask"); - - if ($masks->length > 0) - { - foreach ($masks as $mask) { - // mask exists - if (strcmp($mask->nodeValue, $fileMask) == 0) return null; - - if (strncmp($mask->nodeValue, $fileMask, 5) == 0) - { - // less common - if (strlen($mask->nodeValue) <= strlen($fileMask)) return null; - // more common - delete old, create new - return $mask->nodeValue; - } - } - } - return null; - } - + public function getOldMask($fileMask) + { + $masks = $this->baseDom->getElementsByTagName("mask"); + + if ($masks->length > 0) + { + foreach ($masks as $mask) { + // mask exists + if (strcmp($mask->nodeValue, $fileMask) == 0) return null; + + if (strncmp($mask->nodeValue, $fileMask, 5) == 0) + { + // less common + if (strlen($mask->nodeValue) <= strlen($fileMask)) return null; + // more common - delete old, create new + return $mask->nodeValue; + } + } + } + return null; + } /* * */ - public function addVI($fileMask, $format) - { - $newVi = $this->baseDom->createElement("vi"); - $newId = $this->getNewId(); - $newVi->setAttribute('id', $newId); - if ($format == 'txt') $format = 'ascii'; - $newVi->setAttribute('format', strtoupper($format)); - $newVi->appendChild($this->baseDom->createElement("mask",$fileMask)); - $this->appendFiles($newVi, $fileMask); - - $this->baseDom->getElementsByTagName("base")->item(0)->appendChild($newVi); - /* SORT files by Start Time */ - $this->xslt->transformToDoc($this->baseDom)->save($this->baseDomName); - - return $newId; - } - -/* -* -*/ - public function addSimuVI($p) - { - $newVi = $this->baseDom->createElement("vi"); - $newId = $this->getNewId(); - $newVi->setAttribute('id', $newId); - $newVi->appendChild($this->baseDom->createElement("mask",$p->mask)); - $newVi->appendChild($this->baseDom->createElement("param",$p->name)); - $newVi->setAttribute("start", $p->start); - $newVi->setAttribute("stop", $p->stop); - $newVi->setAttribute("moreData", "true"); - -// $this->appendFiles($newVi, $fileMask); - $newFile = $this->baseDom->createElement("file"); - $newFile->setAttribute('name', $p->file); - $newFile->setAttribute('start', $p->start); - $newFile->setAttribute('stop', $p->stop); - $this->baseDom->getElementsByTagName("base")->item(0)->appendChild($newVi); - - if (strpos($p->mask,'___CCMC_')=== FALSE){ - $arguments = $this->baseDom->createElement("arguments"); - - foreach ($p->args[$p->name] AS $key => $val) { - $arguments->appendChild($this->baseDom->createElement($key,$val)); - } - $newVi->appendChild($arguments); - } - - $newVi->appendChild($newFile); -// $this->baseDom->getElementsByTagName("base")->item(0)->appendChild($newFile); - /* SORT files by Start Time */ - $this->xslt->transformToDoc($this->baseDom)->save($this->baseDomName); - return $newId; - } - - public function delVI($fileMask) - { - $vi = $this->xp->query("//vi[mask='".$fileMask."']"); + public function addVI($fileMask, $format) + { + $newVi = $this->baseDom->createElement("vi"); + $newId = $this->getNewId(); + $newVi->setAttribute('id', $newId); + + if ($format == 'txt') $format = 'ascii'; + + $newVi->setAttribute('format', strtoupper($format)); + $newVi->appendChild($this->baseDom->createElement("mask",$fileMask)); + $this->appendFiles($newVi, $fileMask); + + $this->baseDom->documentElement->appendChild($newVi); + return $newId; + } + + public function delVI($fileMask) + { + $vi = $this->xp->query("//vi[mask='".$fileMask."']"); - if ($vi->length > 0) - $vi->item(0)->parentNode->removeChild($vi->item(0)); + if ($vi->length > 0) + $vi->item(0)->parentNode->removeChild($vi->item(0)); - $this->baseDom->save($this->baseDomName); - } + $this->baseDom->save($this->baseDomName); + } - public function getVI($fileMask) - { - $vi = $this->xp->query("//vi[mask='".$fileMask."']"); + public function getVI($fileMask) + { + $vi = $this->xp->query("//vi[mask='".$fileMask."']"); - if ($vi->length > 0) - return $vi->item(0)->getAttribute("id"); + if ($vi->length > 0) + return $vi->item(0)->getAttribute("id"); - return -1; - } + return -1; + } - public function existsSimuMask($start,$stop,$mask) - { - $vi = $this->xp->query("//vi[mask='".$mask."' and @start<=".$start." and @stop>=".$stop."]"); - - if ($vi->length > 0) - return true; - else - return false; - } - - public function existsWsrMask($start,$stop,$mask) - { - $vi = $this->xp->query("//vi[mask='".$mask."' and @start<=".$start." and @stop>=".$stop."]"); - - if ($vi->length > 0) - return true; - else - return false; - } - - public function intervalsToGet($requestStart, $requestStop, $mask) - { - $vis = $this->xp->query("//vi[mask='".$mask."']"); - if ($vis->length == 0) return false; - - $vi = $vis->item(0); - $files = $vi->getElementsByTagName('file'); - - $start = array(); - $stop = array(); - - $globalStart = (int)$vi->getAttribute("start"); - $globalStop = (int)$vi->getAttribute("stop"); - - if ($requestStart > $globalStop || $requestStop < $globalStart) - { - $start[] = $requestStart; - $stop[] = $requestStop; - } - else - { - if ($requestStart < $globalStart - DELTA ) { - $start[] = $requestStart; - $stop[] = $globalStart; - } - - if ($requestStop > $globalStop + DELTA ) { - $start[] = $globalStop; - $stop[] = $requestStop; - } - - for ($i = 0; $i < $files->length; $i++) - if ((int)$files->item($i)->getAttribute("stop") >= $requestStart) break; - - for ($j = $i; $j < $files->length; $j++) - if ((int)$files->item($j)->getAttribute("start") >= $requestStop) break; + public function existsVi($mask) + { + $vi = $this->xp->query("//vi[mask='".$mask."']"); + if ($vi->length > 0) + return true; + else + return false; + } - $d = $j+1 < $files->length -1 ? $j+1 : $files->length - 1; - - for ($k = $i; $k < $d ; $k++) { - $stopT = (int)$files->item($k)->getAttribute("stop"); - $startT = (int)$files->item($k+1)->getAttribute("start"); - if ($startT - $stopT > DELTA) { - $start[] = $stopT; - $stop[] = $startT; - } - } - } - - return array('start' => $start, 'stop' => $stop); - } - - public function getStartStopParam ($start,$stop,$mask) { - $vi = $this->xp->query("//vi[mask='".$mask."']"); - $isData = $this->xp->query("//vi[mask='".$mask."' and @start<=".$start." and @stop>=".$stop."]"); - - if ($isData->length > 0) - return true; - else { - if ($vi->length > 0) { - $viStart = $vi->item(0)->getAttribute('start'); - $viStop = $vi->item(0)->getAttribute('stop'); - if ($start < $viStart){ - if (($viStart - $start) > 60){ - $newStart = $start; - $newStop = $viStart; - } - } - elseif ($start >= $viStop){ - $newStart = $start; - $newStop = $stop; - } - elseif (($start = $viStart) && ($stop > $viStop)){ - $newStart = $viStop; - $newStop = $stop; - } - else { - if ($stop <= $viStart){ - $newStart = $start; - $newStop = $stop; + /* + * Check intervals to be ordered in the Remote Centers (IMPEX) + */ + public function intervalsToGet($requestStart, $requestStop, $mask) + { + $vis = $this->xp->query("//vi[mask='".$mask."']"); + if ($vis->length == 0) return false; + + $vi = $vis->item(0); + $files = $vi->getElementsByTagName('file'); + + $start = array(); + $stop = array(); + // otherwise - the case of IPIM - only one file + if (strpos($mask, "*") > 0) + { + $globalStart = (int)$vi->getAttribute("start"); + $globalStop = (int)$vi->getAttribute("stop"); + + if ($requestStart > $globalStop || $requestStop < $globalStart) + { + $start[] = $requestStart; + $stop[] = $requestStop; + } + else + { + if ($requestStart < $globalStart - DELTA ) { + $start[] = $requestStart; + $stop[] = $globalStart; + } + + if ($requestStop > $globalStop + DELTA ) { + $start[] = $globalStop; + $stop[] = $requestStop; + } + + for ($i = 0; $i < $files->length; $i++) + if ((int)$files->item($i)->getAttribute("stop") >= $requestStart) break; + + for ($j = $i; $j < $files->length; $j++) + if ((int)$files->item($j)->getAttribute("start") >= $requestStop) break; + + $d = $j+1 < $files->length -1 ? $j+1 : $files->length - 1; + + for ($k = $i; $k < $d ; $k++) { + $stopT = (int)$files->item($k)->getAttribute("stop"); + $startT = (int)$files->item($k+1)->getAttribute("start"); + if ($startT - $stopT > DELTA) { + $start[] = $stopT; + $stop[] = $startT; + } + } + } } - elseif ($stop > $viStop){ - $newStart = $viStop; - $newStop = $stop; - } - } - } - return array('start' => $newStart, 'stop' => $newStop); + return array('start' => $start, 'stop' => $stop); } - - } - - public function getStartStop($id) - { - $this->baseDom->load($this->baseDomName); - $xpath = new DOMXpath($this->baseDom); - - $vis = $xpath->query("//vi[@id=".$id."]"); - - if ($vis->length == 0) + + /* + * Get VI Start - Stop + */ + public function getStartStop($id) + { + $this->baseDom->load($this->baseDomName); + $xpath = new DOMXpath($this->baseDom); + + $vis = $xpath->query("//vi[@id=".$id."]"); + + if ($vis->length == 0) return "nodata"; - - $vi = $vis->item(0); - - $start = $vi->getAttribute("start"); - $stop = $vi->getAttribute("stop"); - return date("Y-m-d", $start)."T".date("H:i:s", $start)."-".date("Y-m-d", $stop)."T".date("H:i:s", $stop); - } - + $vi = $vis->item(0); + + $start = $vi->getAttribute("start"); + $stop = $vi->getAttribute("stop"); - public function getViDesc($vi) - { - return $this->getStartStop($vi); - } - + return date("Y-m-d", $start)."T".date("H:i:s", $start)."-".date("Y-m-d", $stop)."T".date("H:i:s", $stop); + } + + /* + * Return VI Description (Start - Stop) + */ + public function getViDesc($vi) + { + return $this->getStartStop($vi); + } + + /* + * Delete Vi in base.xml and delete corresponding files in User DATA dir + */ + public function deleteViTotal($viId) + { + $vi = $this->xp->query("//vi[@id=".$viId."]"); + + if ($vi->length > 0) { + $files = $vi->item(0)->getElementsByTagName('file'); + foreach ($files as $file) + { + $fileName = USERDATADIR.$file->getAttribute('name'); + if (file_exists($fileName)) unlink($fileName); + } + + $vi->item(0)->parentNode->removeChild($vi->item(0)); + $this->baseDom->save($this->baseDomName); + } + } + } ?> diff --git a/php/classes/BestRunsMgr.php b/php/classes/BestRunsMgr.php index b409ec7..8d522f0 100644 --- a/php/classes/BestRunsMgr.php +++ b/php/classes/BestRunsMgr.php @@ -5,213 +5,247 @@ * */ - - class BestRunsMgr { - - protected $runs; - protected $domRemoteData, $domTemplate; - protected $xpRemoteData, $xpTemplate; - protected $runsTemplate; - protected $json; - protected $factors; +class BestRunsMgr +{ + protected $runs; + protected $domRemoteData, $domTemplate; + protected $xpRemoteData, $xpTemplate; + protected $runsTemplate; + protected $json; + protected $factors = array("SW_Density"=>1e6, + "SW_Utot"=>1e3, + // "SW_Temperature"=>1e3, + "SW_Temperature"=>1.16e4, // ev => K + "SW_Btot"=>1e-9, + "SW_Bx"=>1e-9, + "SW_By"=>1e-9, + "SW_Bz"=>1e-9 + ); + function __construct() {} - function __construct() { - $this->factors = array("SW_Density"=>1e6, - "SW_Utot"=>1e3, - "SW_Temperature"=>1e3, - "SW_Btot"=>1e-9, - "SW_Bx"=>1e-9, - "SW_By"=>1e-9, - "SW_Bz"=>1e-9 - ); - - } - -/***************************************************************** -* PUBLIC FUNCTIONS -*****************************************************************/ - public function init() { + public function init() + { + // DOM of SIMU RUNs template + $this->domTemplate = new DomDocument("1.0"); + if (!$this->domTemplate->load(DATAPATH.'SimuTemplate/templateGUMICS.xml')) + return false; + + $this->xpTemplate = new domxpath($this->domTemplate); + $this->runTemplate = $this->xpTemplate->query("//runID")->item(0); + + // DOM of user RemoteParams + $this->domRemoteData = new DomDocument("1.0"); + + if (!$this->domRemoteData->load(USERWSDIR.'RemoteParams.xml')) + return false; - - // DOM of SIMU RUNs chablon - $this->domTemplate = new DomDocument(); - if (!$this->domTemplate->load( tmplGUMICS )) - return false; - $this->xpTemplate = new domxpath($this->domTemplate); - $this->runTemplate = $this->xpTemplate->query("//runID")->item(0); - - // DOM of user RemoteParams - $this->domRemoteData = new DomDocument(); - if (!$this->domRemoteData->load( USERWSDIR.'RemoteParams.xml' )) - return false; - $this->xpRemoteData = new domxpath($this->domRemoteData); - - $this->json = file_get_contents(USERWSDIR.'runs.json'); - - } - - // $obj ={"Object":"Earth","RunCount":"2", -// "SW_Density_value":"10","SW_Density_weight":"1","SW_Density_scale":"7","SW_Temperature_value":"100", ....} - public function getRun($obj) - { + $this->xpRemoteData = new domxpath($this->domRemoteData); + + $this->json = file_get_contents(USERWSDIR.'runs.json'); + + return true; + } - $params = $this->makeParams($obj); - try { - $client = new SoapClient(wsdl_FMI, - array( - 'wsdl_cache' => 0, - 'trace' => 1, - 'exceptions' => 0, - 'soap_version'=>SOAP_1_2 - )); - } - catch (SoapFault $exception) { - error_log("Problem with WSDL".PHP_EOL.$exception->getMessage().PHP_EOL.$exception->getTraceAsString().PHP_EOL."File = ".$exception->getFile(),1,email); - $res = array('success' => false,'error' => $exception->getMessage()); - } - try { - $data_json = $client->getMostRelevantRun($params); - $result = json_decode($data_json,true); + // $obj ={"Object":"Earth","RunCount":"2", + // "SW_Density_value":"10","SW_Density_weight":"1","SW_Density_scale":"7","SW_Temperature_value":"100", ....} + public function getRun($obj) + { + $params = $this->makeParams($obj); + try + { + $client = new SoapClient("http://impex-fp7.fmi.fi/ws/Methods_FMI.wsdl", + array( + 'wsdl_cache' => 0, + 'trace' => 1, + 'exceptions' => 0, + 'soap_version'=>SOAP_1_2 + )); + } + catch (SoapFault $exception) + { + $res = array('success' => false,'error' => $exception->getMessage()); + } + + try + { + $data_json = $client->getMostRelevantRun($params); + $result = json_decode($data_json,true); - if (count($result["runs"]) > 0) { - $result = $this->changeJson($result); - $res = array('success' => true,'runs' => $result["runs"]); - file_put_contents(USERWSDIR.'runs.json',json_encode($res)); - + if (count($result["runs"]) > 0) + { + $result = $this->changeJson($result); + $res = array('success' => true,'runs' => $result["runs"]); + file_put_contents(USERWSDIR.'runs.json',json_encode($res)); + } } - } - catch (Exception $e) { - error_log ($e->getMessage(),1,email); - $res = array('success' => false,'error' => $e->getMessage()); - } - - return $res; - } - + catch (Exception $e) + { + //error_log ($e->getMessage(),1,email); + $res = array('success' => false,'error' => $e->getMessage()); + } + return $res; + } + + public function addRuns($obj) + { + if (!$obj) return false; + else + { + $this->runsId = (array)$obj; + $object = json_decode($this->json,true); - - public function addRuns($obj){ - - if (!$obj) return false; - else { - $this->runsId = (array)$obj; - $object = json_decode($this->json,true); - $simuRegion = $this->domRemoteData->getElementById('FMI_GUMICS_Earth_Magnetosphere'); + $simuRegion = $this->domRemoteData->getElementById('FMI_GUMICS_Earth_Magnetosphere'); - foreach ( $this->runsId as $runId){ - if ($this->domRemoteData->getElementById($runId) == null){ + foreach ($this->runsId as $runId) + { + if ($this->domRemoteData->getElementById($runId) == null) + { + $newRun = $this->domRemoteData->importNode($this->runTemplate, true); + foreach ($object['runs'] as $r) + { + if ($r['ResourceID'] == $runId) $run=$r; + } + $newRun->setAttribute('xml:id', $run['ResourceID']); + $newRun->setAttribute('name', $run['ResourceName']); + $desc = $this->runTemplate->getAttribute('start_desc'). "<b>Param_values: </b><br/>"; + foreach ($run['Param_values'] as $key => $value) + { + $desc = $desc."<u>".$key." </u>".$value."<br/>"; + } + $newRun->setAttribute('desc', $desc); + $newRun->removeAttribute('start_desc'); + $datasets = $newRun->getElementsByTagName('dataset'); + + $numericalOutputs = $run['NumericalOutput']; // array ! + + foreach ($datasets as $dataset) + { + $name = $dataset->getAttribute('name'); + $find = false; + + foreach ($numericalOutputs as $no) + { + if (strpos($no, $name) > 0) + { + + $datasetId = $no; + $find = true; + break; + } + } + + if (!$find) + throw new Exception($name." is not found in FMI_GUMICS response"); + + // $datasetId = str_replace('SimulationRun','NumericalOutput',$run['ResourceID'].'/'.$name); + $dataset->setAttribute('xml:id', $datasetId); + $dataset->setAttribute('desc'); + $dataset->setAttribute('globalStart', 'depending on mission'); + $params = $dataset->getElementsByTagName('parameter'); + foreach($params as $param) + { + $paramName = $param->getAttribute('name'); + // $datasetId = str_replace('SimulationRun','NumericalOutput',$datasetId); + switch ($paramName) + { + case "H+ number density" : $paramName = "Density"; break; + case "H+ velocity" : $paramName = "Ux,Uy,Uz"; break; + case "H+ total velocity" : $paramName = "Utot"; break; + case "H+ thermal pressure" : $paramName = "Pressure"; break; + case "H+ temperature" : $paramName = "Temperature"; break; + } - $newRun = $this->domRemoteData->importNode($this->runTemplate, true); - foreach ($object['runs'] as $r){ - if ($r['ResourceID'] == $runId) $run=$r; - } - $newRun->setAttribute('xml:id', $run['ResourceID']); - $newRun->setAttribute('name', $run['ResourceName']); - $desc = $this->runTemplate->getAttribute('start_desc'). "<b>Param_values: </b><br/>"; - foreach ($run['Param_values'] as $key => $value) { - $desc = $desc."<u>".$key." </u>".$value."<br/>"; - } - $newRun->setAttribute('desc', $desc); - $newRun->removeAttribute('start_desc'); - $datasets = $newRun->getElementsByTagName('dataset'); - - foreach ($datasets as $dataset){ - $name = $dataset->getAttribute('name'); - $datasetId = str_replace('SimulationRun','NumericalOutput',$run['ResourceID'].'/'.$name); - $dataset->setAttribute('xml:id', $datasetId); - $dataset->setAttribute('desc'); - $params = $dataset->getElementsByTagName('parameter'); - foreach($params as $param){ - $paramName = $param->getAttribute('name'); -// $datasetId = str_replace('SimulationRun','NumericalOutput',$datasetId); - switch ($paramName) { - case "H+ number density" : $paramName = "Density"; break; - case "H+ velocity" : $paramName = "Ux,Uy,Uz"; break; - case "H+ total velocity" : $paramName = "Utot"; break; - case "H+ thermal pressure" : $paramName = "Pressure"; break; - case "H+ temperature" : $paramName = "Temperature"; break; - } - - - $paramId = $this->param2ddSimu($datasetId.'/'.$paramName); - $param->setAttribute('xml:id', str_replace('_EARTH___n_T_Vx_Bx_By_Bz','',str_replace('earth_synth_stationary_','',$paramId))); - $param->setAttribute('parentID',$datasetId); - $param->setAttribute('needsArgs','1'); - if ($param->hasChildNodes()) { - $components = $param->getElementsByTagName('component'); - foreach ($components as $component){ - $compName = $component->getAttribute('name'); - $component->setAttribute('xml:id', str_replace('_EARTH___n_T_Vx_Bx_By_Bz','',str_replace('earth_synth_stationary_','',$paramId.'_'.$compName))); - $component->setAttribute('parentID',$datasetId); - $component->setAttribute('needsArgs','1'); - } - } - } - } - $simuRegion->appendChild($newRun); - $this->domRemoteData->save(USERWSDIR.'RemoteParams.xml'); - } - } - + $paramId = $this->param2ddSimu($datasetId.'/'.$paramName); + $param->setAttribute('xml:id', str_replace('_EARTH___n_T_Vx_Bx_By_Bz','',str_replace('earth_synth_stationary_','',$paramId))); + // $param->setAttribute('parentID',$datasetId); + $param->setAttribute('needsArgs','1'); + if ($param->hasChildNodes()) + { + $components = $param->getElementsByTagName('component'); + + foreach ($components as $component) + { + $compName = $component->getAttribute('name'); + $component->setAttribute('xml:id', str_replace('_EARTH___n_T_Vx_Bx_By_Bz','',str_replace('earth_synth_stationary_','',$paramId.'_'.$compName))); + // $component->setAttribute('parentID',$datasetId); + $component->setAttribute('needsArgs','1'); + } + } + } + } + $simuRegion->appendChild($newRun); + $this->domRemoteData->save(USERWSDIR.'RemoteParams.xml'); + } + } + } } - } - protected function makeParams($json) - { - $obj = (array)$json; - $SW_parameters = array(); - foreach ($obj as $k => $v) { - if (empty($v)) - unset($obj[$k]); - } - foreach ($obj as $k => $v) { - if (strpos($k,'_value') !== FALSE ) { - $sw= str_replace ('_value', '', $k); - $SW_val = array(); - $SW_val['value'] = $obj[$sw.'_value'] * $this->factors[$sw]; - if ($obj[$sw.'_weight'] != '') $SW_val['weight'] = $obj[$sw.'_weight']; - if ($obj[$sw.'_scale'] != '') $SW_val['scale'] = $obj[$sw.'_scale']* $this->factors[$sw]; - $SW_parameters[$sw] = $SW_val; + protected function makeParams($json) + { + $obj = (array)$json; + $SW_parameters = array(); + + foreach ($obj as $k => $v) + { + if (empty($v)) + unset($obj[$k]); + } + + foreach ($obj as $k => $v) + { + if (strpos($k,'_value') !== FALSE ) + { + $sw= str_replace ('_value', '', $k); + $SW_val = array(); + $SW_val['value'] = $obj[$sw.'_value'] * $this->factors[$sw]; + if ($obj[$sw.'_weight'] != '') $SW_val['weight'] = $obj[$sw.'_weight']; + if ($obj[$sw.'_scale'] != '') $SW_val['scale'] = $obj[$sw.'_scale']* $this->factors[$sw]; + $SW_parameters[$sw] = $SW_val; + } } - } - $params = array ( - 'Object' => 'Earth', // Mandatory - 'RunCount' => $obj['RunCount'], // Number of runs returned. Optional, default = 1 - 'SW_parameters' => $SW_parameters); + $params = array ( + 'Object' => 'Earth', // Mandatory + 'RunCount' => $obj['RunCount'], // Number of runs returned. Optional, default = 1 + 'SW_parameters' => $SW_parameters); + return $params; - - } + } - protected function changeJson($object){ - - $i=0; - foreach ($object['runs'] as $run){ - $run['S_diff'] = round($run['S_diff'],3); - - - foreach ($run['S_diff_n'] as $k => $v){ - $v = round($v,3); - $run['S_diff_n'][$k] = $v; - } - foreach ($run['Param_values'] as $k => $v){ - if ($this->factors[$k]){ - $newValue = round($v / $this->factors[$k], 3); - $run['Param_values'][$k] = $newValue; - } - } - $object['runs'][$i] = $run; - $i++; - } - - return $object; - } + protected function changeJson($object) + { + $i=0; + foreach ($object['runs'] as $run) + { + $run['S_diff'] = round($run['S_diff'],1); + + foreach ($run['S_diff_n'] as $k => $v) + { + $v = round($v,3); + $run['S_diff_n'][$k] = $v; + } + + foreach ($run['Param_values'] as $k => $v) + { + if ($this->factors[$k]) + { + $newValue = round($v / $this->factors[$k], 3); + $run['Param_values'][$k] = $newValue; + } + } + $object['runs'][$i] = $run; + $i++; + } + return $object; + } - protected function param2ddSimu($paramID) { - $pairs = array(" " => "_","-" => "_","/" => "_","%" => "_","\\" => "_","$" => "_",":" => "_","+" =>"_","#" => "_","@" => "_","." => "_", ">" => "_", "<" => "_", "," => "_"); - return strtr($paramID,$pairs); - } - } - + protected function param2ddSimu($paramID) + { + $pairs = array("?" => "_", " " => "_","-" => "_","/" => "_","%" => "_","\\" => "_","$" => "_",":" => "_","+" =>"_", + "#" => "_","@" => "_","." => "_", ">" => "_", "<" => "_", "," => "_"); + return strtr($paramID,$pairs); + } + +} ?> diff --git a/php/classes/EPNResourcesManager.php b/php/classes/EPNResourcesManager.php deleted file mode 100644 index c9a8b27..0000000 --- a/php/classes/EPNResourcesManager.php +++ /dev/null @@ -1,1042 +0,0 @@ -<?php -/** @class EPNResourcesManager -* @version $Id: EPNResourcesManager.php 2183 2014-03-13 14:59:19Z elena $ -* @brief Manager to create EPN resources from AMDA descriptors files -* -*/ - -define("EPNRES_IVOID_CDPP","ivo://cdpp"); -define("EPNRES_IVOID_IRAP",EPNRES_IVOID_CDPP."/irap"); -define("EPNRES_IVOID_AMDA",EPNRES_IVOID_IRAP."/amda"); -define("EPNRES_IVOID_DATA",EPNRES_IVOID_AMDA."/dataset"); -define("EPNRES_IVOID_INST",EPNRES_IVOID_AMDA."/instrument"); -define("EPNRES_IVOID_MIS",EPNRES_IVOID_AMDA."/mission"); - - -define("EPNRES_PUBLISHER","CDPP - Centre de Données de la Physique des Plasma"); - -define("EPNRES_CONTACT_NAME","CDPP/AMDA Team"); -define("EPNRES_CONTACT_ADDRESS","IRAP, 9 avenue du Colonel Roche, 31028 TOULOUSE, CEDEX 4, FRANCE"); -define("EPNRES_CONTACT_EMAIL","amda@irap.omp.eu"); -define("EPNRES_CONTACT_TELEPHONE",""); - -define("EPNRES_REFERENCE_URL","http://cdpp-amda.cesr.fr/DDHTML/index.html"); - -define("EPNRES_INSTRUMENTS_FILE",EPNResources."instruments.xml"); -define("EPNRES_TARGETS_FILE",LocalData."targets.xml"); - - -class EPNResourcesManager -{ - protected $infoMgr; - protected $amdaClient; - protected $inst_doc; - protected $inst_xp; - protected $targ_doc; - protected $targ_xp; - - function __construct($amdaClient) - { - $this->infoMgr = new ParamsInfoMgr(); - $this->amdaClient = $amdaClient; - } - - private function initInstrumentsFile() - { - $this->inst_doc = new DOMDocument(); - $this->inst_doc->formatOutput = TRUE; - - $node = $this->inst_doc->createElement('Instruments'); - $this->inst_doc->appendChild($node); - - $this->inst_xp = new DOMXPath($this->inst_doc); - } - - private function loadTargetsFile() - { - $this->targ_doc = new DOMDocument(); - $this->targ_doc->formatOutput = TRUE; - - if (!$this->targ_doc->load(EPNRES_TARGETS_FILE)) - { - printf("[ERROR] Cannot load tagets file %s\n",EPNRES_TARGETS_FILE); - return false; - } - - $this->targ_xp = new DOMXPath($this->targ_doc); - - return true; - } - - public function createResources() - { - $this->initInstrumentsFile(); - - if (!$this->loadTargetsFile()) - return false; - - $this->infoMgr->forEachAllDDDatasets(array($this,'createResource')); - - $this->inst_doc->save(EPNRES_INSTRUMENTS_FILE); - } - - function createResource($infos) - { - $dataset_id = $infos["dataset"]["id"]; - - $newres_doc = new DOMDocument(); - $newres_doc->formatOutput = TRUE; - - $epn_id = str_replace(":","_",$dataset_id); - $newres_path = EPNResources."EPNresource_".$epn_id.".xml"; - - // create skeleton - - $this->getDataCollection($newres_doc); - $this->getAccessURL($newres_doc); - $this->getTitle($newres_doc); - $this->getShortName($newres_doc); - $this->getIdentifier($newres_doc); - $this->getCuration($newres_doc); - $this->getPublisher($newres_doc); - $this->getCreator($newres_doc); - $this->getCreatorName($newres_doc); - $this->getCreatorLogo($newres_doc); - $this->getContact($newres_doc); - $this->getContactName($newres_doc); - $this->getContactAddress($newres_doc); - $this->getContactEmail($newres_doc); - $this->getContactTelephone($newres_doc); - $this->getContent($newres_doc); - $this->getSubject($newres_doc); - $this->getDescription($newres_doc); - $this->getReferenceURL($newres_doc); - $this->getContributor($newres_doc); - $this->getResource($newres_doc); - $this->getDataset($newres_doc); - $this->getGeneralMetadata($newres_doc); - $this->getFormat($newres_doc); - $this->getRight($newres_doc); - $this->getCalibration($newres_doc); - $this->getResourceType($newres_doc); - $this->getInstrument($newres_doc); - $this->getFacility($newres_doc); - $this->getResourceName($newres_doc); - $this->getInstrumentName($newres_doc); - $this->getAlternateInstrumentName($newres_doc); - $this->getInstrumentClass($newres_doc); - $this->getInstrumentReferenceURL($newres_doc); - $this->getAnyURI($newres_doc); - $this->getTargets($newres_doc); - $this->getTargetType($newres_doc); - $this->getTargetClass($newres_doc); - $this->getCoverage($newres_doc); - $this->getMeasurementType($newres_doc); - $this->getAstroCoordSystem($newres_doc); - $this->getTimeFrame($newres_doc); - $this->getTimeScale($newres_doc); - $this->getAstroCoordArea($newres_doc); - $this->getTimeInterval($newres_doc); - $this->getIntegrationTime($newres_doc); - $this->getMinIntegrationTime($newres_doc); - $this->getMaxIntegrationTime($newres_doc); - $this->getSamplingStep($newres_doc); - $this->getMinSamplingStep($newres_doc); - $this->getMaxSamplingStep($newres_doc); - $this->getStartTime($newres_doc); - $this->getStartTimeISO($newres_doc); - $this->getStopTime($newres_doc); - $this->getStopTimeISO($newres_doc); - $this->getSpectralInterval($newres_doc); - $this->getSpectralResolution($newres_doc); - $this->getSpectralMinResolution($newres_doc); - $this->getSpectralMaxResolution($newres_doc); - $this->getSpectralLoLimit($newres_doc); - $this->getSpectralHiLimit($newres_doc); - $this->getSpectralSamplingStep($newres_doc); - $this->getMinSpectralSamplingStep($newres_doc); - $this->getMaxSpectralSamplingStep($newres_doc); - $this->getSpectralParticles($newres_doc); - $this->getParticlesResolution($newres_doc); - $this->getParticlesMinResolution($newres_doc); - $this->getParticlesMaxResolution($newres_doc); - $this->getParticlesLoLimit($newres_doc); - $this->getParticlesHiLimit($newres_doc); - $this->getParticlesSamplingStep($newres_doc); - $this->getMinParticlesSamplingStep($newres_doc); - $this->getMaxParticlesSamplingStep($newres_doc); - $this->getTableset($newres_doc); - $this->getSchema($newres_doc); - $this->getSchemaColumn($newres_doc); - $this->getSchemaColumnName($newres_doc); - $this->getSchemaColumnDescription($newres_doc); - $this->getSchemaColumnUnit($newres_doc); - $this->getSchemaColumnUCD($newres_doc); - $this->getSchemaColumnDataproductType($newres_doc); - $this->getSchemaColumnDataType($newres_doc); - - // fill - $date = date("Y-m-d\TH:i:s"); - - $this->setDataCollection($newres_doc,$epn_id,$date,$date,""); - - $accessURL = EPNTAP_AMDA."?REQUEST=doQuery&LANG=ADQL&QUERY=SELECT * FROM amdadb.epn_core WHERE dataset_id = '".$epn_id."' AND resource_type = 'granule' ORDER BY time_min&FORMAT=votable/td"; - $this->setAccessURL($newres_doc,$accessURL); - - $this->setTitle($newres_doc,$infos['dataset']['infos']['title']); - - $this->setShortName($newres_doc,$epn_id); - - $this->setIdentifier($newres_doc,EPNRES_IVOID_DATA,$epn_id); - - $this->setPublisher($newres_doc,EPNRES_PUBLISHER); - - $this->setCreator($newres_doc,$infos['dataset']['infos']['creator'],""); - - $this->setContact($newres_doc,EPNRES_IVOID_AMDA,EPNRES_CONTACT_NAME,EPNRES_CONTACT_ADDRESS,EPNRES_CONTACT_EMAIL,EPNRES_CONTACT_TELEPHONE); - - foreach ($infos['dataset']['infos']['subject'] as $s) - $this->addSubject($newres_doc,$s); - - $this->setDescription($newres_doc,$infos['dataset']['infos']['description']); - - $this->setReferenceURL($newres_doc,$infos['submission']['infos']['help'],$infos['instrument']['infos']['help'],$infos['dataset']['infos']['help']); - - foreach ($infos['dataset']['infos']['contributor'] as $c) - $this->addContributor($newres_doc,$c); - - $this->setCalibration($newres_doc,$infos['dataset']['infos']['calibration']); - - $this->setFormat($newres_doc,"votable"); - - if (!isset($infos['mission']['infos']['group']) || ($infos['mission']['infos']['group'] == "")) - $this->setRight($newres_doc,"secure"); - else - $this->setRight($newres_doc,"proprietary"); - - $this->setResourceType($newres_doc,"dataset"); - - $this->setInstrument($newres_doc,$infos['mission']['id'],$infos['submission']['name'],$infos['submission']['infos']['class'], - $infos['instrument']['infos']['id'],$infos['instrument']['name'],$infos['instrument']['infos']['alternamename'], - $infos['instrument']['infos']['class'],$infos['instrument']['infos']['refURL']); - - foreach ($infos['dataset']['infos']['target'] as $t) - $this->addTarget($newres_doc,$t); - - $this->setMeasurementType($newres_doc,$infos['dataset']['infos']['parameters']); - - $this->setTimeInterval($newres_doc,$dataset_id,$infos['dataset']['infos']['minsampling'],$infos['dataset']['infos']['maxsampling'], - $infos['dataset']['infos']['starttime'],$infos['dataset']['infos']['stoptime']); - - foreach ($infos['dataset']['infos']['parameters'] as $param) - $this->addColumn($newres_doc,$param['name'],$param['description'],$param['units'],$param['ucd'],$param['type'],'float'); - - $newres_doc->save($newres_path); - // printf("[INFO] Create new EPN resource file %s\n",$newres_path); - } - - function setDataCollection($res_doc,$id,$created,$updated,$status) - { - $node = $this->getDataCollection($res_doc); - $node->setAttribute('id',$id); - $node->setAttribute('created',$created); - $node->setAttribute('updated',$updated); - $node->setAttribute('status',$status); - } - - function setPublisher($res_doc,$publisher) - { - $node = $this->getPublisher($res_doc); - $node->nodeValue = $publisher; - } - - function setContact($res_doc,$ivo_id,$name,$address,$email,$telephone) - { - $node = $this->getContactName($res_doc); - $node->setAttribute('ivo-id',$ivo_id); - $node->nodeValue = $name; - $node = $this->getContactAddress($res_doc); - $node->nodeValue = $address; - $node = $this->getContactEmail($res_doc); - $node->nodeValue = $email; - $node = $this->getContactTelephone($res_doc); - $node->nodeValue = $telephone; - } - - function setReferenceURL($res_doc,$mission_help,$instrument_help,$dataset_help) - { - $node = $this->getReferenceURL($res_doc); - if (isset($dataset_help) && ($dataset_help != '')) - $node->nodeValue = $dataset_help; - else if (isset($instrument_help) && ($instrument_help != '')) - $node->nodeValue = $instrument_help; - else if (isset($mission_help) && ($mission_help != '')) - $node->nodeValue = $mission_help; - else - $node->nodeValue = EPNRES_REFERENCE_URL; - } - - function getRealSampling($sampling) - { - list($val,$unit) = sscanf($sampling,"%f%s"); - if ($unit == "s") - $sampling = 1*$sampling; - else if ($unit == "m") - $sampling = 60*$sampling; - else if ($unit == "h") - $sampling = 3600*$sampling; - else if ($unit == "Hz") - $sampling = 1./$sampling; - else - printf("[WARNING] EPNResource : Unknown sampling unit %s\n",$unit); - return $sampling; - } - - function getRealStartStop($name) - { - return $this->amdaClient->client->getStartStop($name); - } - - function days2MonthDay($oldDate) - { - list($year, $day, $hour, $min, $sec) = sscanf($oldDate, "%04d%03d%02d%02d%02d"); - $newDate = date("Y-m-d\TH:i:s",strtotime("+$day days",strtotime("$year-01-01 $hour:$min:$sec"))); - return $newDate; - } - - function setTimeInterval($res_doc,$dataset_id,$minres,$maxres,$start,$stop) - { - $node = $this->getTimeInterval($res_doc); - $node->setAttribute('ucd','time.epoch'); - $node = $this->getSamplingStep($res_doc); - if ($minres == $maxres) - $node->setAttribute('type','constant'); - else - $node->setAttribute('type','variable'); - $node->setAttribute('unit','secondes'); - $node = $this->getMinSamplingStep($res_doc); - $node->nodeValue = $this->getRealSampling($minres); - $node = $this->getMaxSamplingStep($res_doc); - $node->nodeValue = $this->getRealSampling($maxres); - - $startstop = $this->getRealStartStop($dataset_id); - $Time = explode("-",$startstop); - - $node = $this->getStartTimeISO($res_doc); - $node->nodeValue = $this->days2MonthDay($Time[0]); - $node = $this->getStopTimeISO($res_doc); - $node->nodeValue = $this->days2MonthDay($Time[1]); - $node = $this->getTimeScale($res_doc); - $node->nodeValue = 'UTC'; - } - - function setAccessURL($res_doc,$access_url) - { - $node = $this->getAccessURL($res_doc); - $node->nodeValue = $access_url; - } - - function setTitle($res_doc,$title) - { - $node = $this->getTitle($res_doc); - $node->nodeValue = $title; - } - - function setShortName($res_doc,$shortName) - { - $node = $this->getShortName($res_doc); - $node->nodeValue = $shortName; - } - - function setIdentifier($res_doc,$ivo_id,$dataset_id) - { - $node = $this->getIdentifier($res_doc); - $node->nodeValue = $ivo_id."/".$dataset_id; - } - - function setCreator($res_doc,$name,$logo) - { - $node = $this->getCreatorName($res_doc); - $node->nodeValue = $name; - - $node = $this->getCreatorLogo($res_doc); - $node->nodeValue = $logo; - } - - function setCalibration($res_doc,$cal) - { - $node = $this->getCalibration($res_doc); - $node->nodeValue = $cal; - } - - function setResourceType($res_doc,$type) - { - $node = $this->getResourceType($res_doc); - $node->nodeValue = $type; - } - - function setInstrument($res_doc,$mis_id,$submis_name,$mis_class,$inst_id,$inst_name,$inst_altname,$inst_class,$inst_refurl) - { - $node = $this->getInstrument($res_doc); - - $node->setAttribute('id',$inst_id); - - $node = $this->getFacility($res_doc); - $node->setAttribute('ivo-id',EPNRES_IVOID_MIS."/".$submis_name); - $node->setAttribute('class',$mis_class); - - $node = $this->getResourceName($res_doc); - $node->nodeValue = $mis_id; - - $node = $this->getInstrumentName($res_doc); - $node->setAttribute('ivo-id',EPNRES_IVOID_INST."/".$inst_id); - $node->nodeValue = $inst_name; - - foreach ($inst_altname as $a) - $this->addInstAltName($res_doc,$a); - - foreach ($inst_class as $c) - $this->addInstClass($res_doc,$c); - - $node = $this->getInstrumentReferenceURL($res_doc); - $node->setAttribute('use','full'); - - $node = $this->getAnyURI($res_doc); - $node->nodeValue = $inst_refurl; - - $instnode = $this->inst_xp->query("//Instruments/instrument[@id='".$inst_id."']"); - if ($instnode->length < 1) - { - $instnode = $this->inst_doc->importNode($this->getInstrument($res_doc),true); - $this->inst_doc->documentElement->appendChild($instnode); - } - } - - function setMeasurementType($res_doc,$params) - { - $node = $this->getMeasurementType($res_doc); - - $ucds = array(); - foreach ($params as $param) - { - $param_ucds = explode($param['ucd'],";"); - foreach ($param_ucds as $param_ucd) - { - if ($param_ucd == 'ToDo') - continue; - $toadd = true; - foreach ($ucds as $ucd) - if ($ucd == $param_ucd) - { - $toadd = false; - break; - } - if ($toadd) - array_push($ucds,$param['ucd']); - } - } - - $ucd_str = ""; - foreach ($ucds as $ucd) - { - if ($ucd_str != "") - $ucd_str .= ";"; - $ucd_str .= $ucd; - } - - $node->nodeValue = $ucd_str; - } - - function setFormat($res_doc,$format) - { - $node = $this->getFormat($res_doc); - $node->nodeValue = $format; - } - - function setRight($res_doc,$right) - { - $node = $this->getRight($res_doc); - $node->nodeValue = $right; - } - - function setDescription($res_doc,$description) - { - $node = $this->getDescription($res_doc); - $node->nodeValue .= $description; - } - - function addTarget($res_doc,$target_id) - { - //find target in targets file - $tar_info = $this->targ_xp->query("//Targets/TargetType[@id='".$target_id."']"); - if ($tar_info->length < 1) - { - printf("[WARNING] Cannot find target info %s\n",$target_id); - return; - } - $tar_info = $tar_info->item(0); - - //add target in epn resource - $targets = $this->getTargets($res_doc); - - $targetnodes = $targets->getElementsByTagName("TargetType"); - foreach ($targetnodes as $targetnode) - if ($targetnode->getAttribute("id") == $target_id) - return; - - foreach ($targetnodes as $targetnode) - if ($targetnode->getAttribute("id") == '') - $targets->removeChild($targetnode); - - $node = $res_doc->importNode($tar_info,true); - $targets->appendChild($node); - } - - function addColumn($res_doc,$param_name,$param_des,$param_unit,$param_ucd,$param_datatype,$param_prodtype) - { - $schema = $this->getSchema($res_doc); - - $columns = $schema->getElementsByTagName("column"); - foreach ($columns as $column) - { - $names = $column->getElementsByTagName("name"); - if ($names->length < 1) - continue; - if (($names->item(0)->nodeValue == $param_name) || ($names->item(0)->nodeValue == '')) - { - $param_column = $column; - break; - } - } - if (!isset($param_column)) - { - //create new column - $param_column = $this->addToNode($res_doc,$schema,'column'); - $this->addToNode($res_doc,$param_column,'name'); - $this->addToNode($res_doc,$param_column,'description'); - $this->addToNode($res_doc,$param_column,'unit'); - $this->addToNode($res_doc,$param_column,'ucd'); - $this->addToNode($res_doc,$param_column,'dataproduct_type'); - $this->addToNode($res_doc,$param_column,'dataType'); - } - //set param info - $node = $this->getFromNode($res_doc,$param_column,'name'); - $node->nodeValue = $param_name; - $node = $this->getFromNode($res_doc,$param_column,'description'); - $node->nodeValue = $param_des; - $node = $this->getFromNode($res_doc,$param_column,'unit'); - $node->nodeValue = $param_unit; - $node = $this->getFromNode($res_doc,$param_column,'ucd'); - $node->nodeValue = $param_ucd; - $node = $this->getFromNode($res_doc,$param_column,'dataproduct_type'); - $node->nodeValue = $param_datatype; - $node = $this->getFromNode($res_doc,$param_column,'dataType'); - $node->nodeValue = $param_prodtype; - } - - function addSubject($res_doc,$subject) - { - $content = $this->getContent($res_doc); - - $subjects = $content->getElementsByTagName("subject"); - foreach($subjects as $s) - if ($s->nodeValue == $subject) - return; - - foreach($subjects as $s) - if ($s->nodeValue == '') - { - $s->nodeValue = $subject; - return; - } - - $s = $this->addToNode($res_doc,$content,'subject'); - $s->nodeValue = $subject; - } - - function addContributor($res_doc,$contributor) - { - $content = $this->getContent($res_doc); - - $contributors = $content->getElementsByTagName("contributor"); - foreach($contributors as $c) - if ($c->nodeValue == $contributor) - return; - - foreach($contributors as $c) - if ($c->nodeValue == '') - { - $c->nodeValue = $contributor; - return; - } - - $c = $this->addToNode($res_doc,$content,'contributor'); - $c->nodeValue = $contributor; - } - - function addInstAltName($res_doc,$altName) - { - $content = $this->getInstrument($res_doc); - - $altnames = $content->getElementsByTagName("alternateInstrumentName"); - foreach($altnames as $a) - if ($a->nodeValue == $altName) - return; - - foreach($altnames as $a) - if ($a->nodeValue == '') - { - $a->nodeValue = $altName; - return; - } - - $a = $this->addToNode($res_doc,$content,'alternateInstrumentName'); - $a->nodeValue = $altName; - } - - function addInstClass($res_doc,$class) - { - $content = $this->getInstrument($res_doc); - - $classes = $content->getElementsByTagName("instrumentClass"); - foreach($classes as $c) - if ($c->nodeValue == $class) - return; - - foreach($classes as $c) - if ($c->nodeValue == '') - { - $c->nodeValue = $class; - return; - } - - $c = $this->addToNode($res_doc,$content,'instrumentClass'); - $c->nodeValue = $class; - } - - function addToNode($res_doc,$node,$tagname) - { - $newnode = $res_doc->createElement($tagname); - $node->appendChild($newnode); - return $newnode; - } - - function getFromNode($res_doc,$node,$tagname) - { - $nodes = $node->getElementsByTagName($tagname); - if ($nodes->length == 0) - return $this->addToNode($res_doc,$node,$tagname); - return $nodes->item(0); - } - - function getDataCollection($res_doc) - { - return $this->getFromNode($res_doc,$res_doc,'DataCollection'); - } - - function getAccessURL($res_doc) - { - return $this->getFromNode($res_doc,$this->getDataCollection($res_doc),'accessURL'); - } - - function getTitle($res_doc) - { - return $this->getFromNode($res_doc,$this->getDataCollection($res_doc),'title'); - } - - function getShortName($res_doc) - { - return $this->getFromNode($res_doc,$this->getDataCollection($res_doc),'shortName'); - } - - function getIdentifier($res_doc) - { - return $this->getFromNode($res_doc,$this->getDataCollection($res_doc),'Identifier'); - } - - function getCuration($res_doc) - { - return $this->getFromNode($res_doc,$this->getDataCollection($res_doc),'curation'); - } - - function getPublisher($res_doc) - { - return $this->getFromNode($res_doc,$this->getCuration($res_doc),'publisher'); - } - - function getCreator($res_doc) - { - return $this->getFromNode($res_doc,$this->getCuration($res_doc),'creator'); - } - - function getCreatorName($res_doc) - { - return $this->getFromNode($res_doc,$this->getCreator($res_doc),'name'); - } - - function getCreatorLogo($res_doc) - { - return $this->getFromNode($res_doc,$this->getCreator($res_doc),'logo'); - } - - function getContact($res_doc) - { - return $this->getFromNode($res_doc,$this->getCuration($res_doc),'contact'); - } - - function getContactName($res_doc) - { - return $this->getFromNode($res_doc,$this->getContact($res_doc),'name'); - } - - function getContactAddress($res_doc) - { - return $this->getFromNode($res_doc,$this->getContact($res_doc),'address'); - } - - function getContactEmail($res_doc) - { - return $this->getFromNode($res_doc,$this->getContact($res_doc),'email'); - } - - function getContactTelephone($res_doc) - { - return $this->getFromNode($res_doc,$this->getContact($res_doc),'telephone'); - } - - function getContent($res_doc) - { - return $this->getFromNode($res_doc,$this->getDataCollection($res_doc),'content'); - } - - function getSubject($res_doc) - { - return $this->getFromNode($res_doc,$this->getContent($res_doc),'subject'); - } - - function getDescription($res_doc) - { - return $this->getFromNode($res_doc,$this->getContent($res_doc),'description'); - } - - function getReferenceURL($res_doc) - { - return $this->getFromNode($res_doc,$this->getContent($res_doc),'referenceURL'); - } - - function getContributor($res_doc) - { - return $this->getFromNode($res_doc,$this->getContent($res_doc),'contributor'); - } - - function getResource($res_doc) - { - return $this->getFromNode($res_doc,$this->getDataCollection($res_doc),'resource'); - } - - function getDataset($res_doc) - { - return $this->getFromNode($res_doc,$this->getResource($res_doc),'dataset'); - } - - function getGeneralMetadata($res_doc) - { - return $this->getFromNode($res_doc,$this->getDataset($res_doc),'generalMetadata'); - } - - function getFormat($res_doc) - { - return $this->getFromNode($res_doc,$this->getGeneralMetadata($res_doc),'format'); - } - - function getRight($res_doc) - { - return $this->getFromNode($res_doc,$this->getGeneralMetadata($res_doc),'right'); - } - - function getResourceType($res_doc) - { - return $this->getFromNode($res_doc,$this->getGeneralMetadata($res_doc),'resource_type'); - } - - function getCalibration($res_doc) - { - return $this->getFromNode($res_doc,$this->getGeneralMetadata($res_doc),'calibration'); - } - - function getInstrument($res_doc) - { - return $this->getFromNode($res_doc,$this->getDataset($res_doc),'instrument'); - } - - function getFacility($res_doc,$inst) - { - return $this->getFromNode($res_doc,(isset($inst) ? $inst : $this->getInstrument($res_doc)),'facility'); - } - - function getResourceName($res_doc,$inst) - { - return $this->getFromNode($res_doc,$this->getFacility($res_doc,$inst),'ResourceName'); - } - - function getInstrumentName($res_doc,$inst) - { - return $this->getFromNode($res_doc,(isset($inst) ? $inst : $this->getInstrument($res_doc)),'InstrumentName'); - } - - function getAlternateInstrumentName($res_doc,$inst) - { - return $this->getFromNode($res_doc,(isset($inst) ? $inst : $this->getInstrument($res_doc)),'alternateInstrumentName'); - } - - function getInstrumentClass($res_doc,$inst) - { - return $this->getFromNode($res_doc,(isset($inst) ? $inst : $this->getInstrument($res_doc)),'instrumentClass'); - } - - function getInstrumentReferenceURL($res_doc,$inst) - { - return $this->getFromNode($res_doc,(isset($inst) ? $inst : $this->getInstrument($res_doc)),'referenceURL'); - } - - function getAnyURI($res_doc,$inst) - { - return $this->getFromNode($res_doc,$this->getInstrumentReferenceURL($res_doc,$inst),'anyURI'); - } - - function getTargets($res_doc) - { - return $this->getFromNode($res_doc,$this->getDataset($res_doc),'targets'); - } - - function getTargetType($res_doc) - { - return $this->getFromNode($res_doc,$this->getTargets($res_doc),'TargetType'); - } - - function getTargetClass($res_doc) - { - return $this->getFromNode($res_doc,$this->getTargetType($res_doc),'targetClass'); - } - - function getCoverage($res_doc) - { - return $this->getFromNode($res_doc,$this->getDataCollection($res_doc),'coverage'); - } - - function getMeasurementType($res_doc) - { - return $this->getFromNode($res_doc,$this->getCoverage($res_doc),'measurementType'); - } - - function getAstroCoordSystem($res_doc) - { - return $this->getFromNode($res_doc,$this->getCoverage($res_doc),'AstroCoordSystem'); - } - - function getTimeFrame($res_doc) - { - return $this->getFromNode($res_doc,$this->getAstroCoordSystem($res_doc),'TimeFrame'); - } - - function getTimeScale($res_doc) - { - return $this->getFromNode($res_doc,$this->getTimeFrame($res_doc),'TimeScale'); - } - - function getAstroCoordArea($res_doc) - { - return $this->getFromNode($res_doc,$this->getCoverage($res_doc),'AstroCoordArea'); - } - - function getTimeInterval($res_doc) - { - return $this->getFromNode($res_doc,$this->getAstroCoordArea($res_doc),'TimeInterval'); - } - - function getIntegrationTime($res_doc) - { - return $this->getFromNode($res_doc,$this->getTimeInterval($res_doc),'resolution'); - } - - function getMinIntegrationTime($res_doc) - { - return $this->getFromNode($res_doc,$this->getIntegrationTime($res_doc),'minResolution'); - } - - function getMaxIntegrationTime($res_doc) - { - return $this->getFromNode($res_doc,$this->getIntegrationTime($res_doc),'maxResolution'); - } - - function getSamplingStep($res_doc) - { - return $this->getFromNode($res_doc,$this->getTimeInterval($res_doc),'SamplingStep'); - } - - function getMinSamplingStep($res_doc) - { - return $this->getFromNode($res_doc,$this->getSamplingStep($res_doc),'minSamplingStep'); - } - - function getMaxSamplingStep($res_doc) - { - return $this->getFromNode($res_doc,$this->getSamplingStep($res_doc),'maxSamplingStep'); - } - - function getStartTime($res_doc) - { - return $this->getFromNode($res_doc,$this->getTimeInterval($res_doc),'StartTime'); - } - - function getStartTimeISO($res_doc) - { - return $this->getFromNode($res_doc,$this->getStartTime($res_doc),'ISOTime'); - } - - function getStopTime($res_doc) - { - return $this->getFromNode($res_doc,$this->getTimeInterval($res_doc),'StopTime'); - } - - function getStopTimeISO($res_doc) - { - return $this->getFromNode($res_doc,$this->getStopTime($res_doc),'ISOTime'); - } - - function getSpectralInterval($res_doc) - { - return $this->getFromNode($res_doc,$this->getAstroCoordArea($res_doc),'SpectralInterval'); - } - - function getSpectralResolution($res_doc) - { - return $this->getFromNode($res_doc,$this->getSpectralInterval($res_doc),'resolution'); - } - - function getSpectralMinResolution($res_doc) - { - return $this->getFromNode($res_doc,$this->getSpectralResolution($res_doc),'minResolution'); - } - - function getSpectralMaxResolution($res_doc) - { - return $this->getFromNode($res_doc,$this->getSpectralResolution($res_doc),'maxResolution'); - } - - function getSpectralLoLimit($res_doc) - { - return $this->getFromNode($res_doc,$this->getSpectralInterval($res_doc),'LoLimit'); - } - - function getSpectralHiLimit($res_doc) - { - return $this->getFromNode($res_doc,$this->getSpectralInterval($res_doc),'HiLimit'); - } - - function getSpectralSamplingStep($res_doc) - { - return $this->getFromNode($res_doc,$this->getSpectralInterval($res_doc),'SamplingStep'); - } - - function getMinSpectralSamplingStep($res_doc) - { - return $this->getFromNode($res_doc,$this->getSpectralSamplingStep($res_doc),'minSamplingStep'); - } - - function getMaxSpectralSamplingStep($res_doc) - { - return $this->getFromNode($res_doc,$this->getSpectralSamplingStep($res_doc),'maxSamplingStep'); - } - - function getSpectralParticles($res_doc) - { - return $this->getFromNode($res_doc,$this->getAstroCoordArea($res_doc),'SpectralParticles'); - } - - function getParticlesResolution($res_doc) - { - return $this->getFromNode($res_doc,$this->getSpectralParticles($res_doc),'resolution'); - } - - function getParticlesMinResolution($res_doc) - { - return $this->getFromNode($res_doc,$this->getParticlesResolution($res_doc),'minResolution'); - } - - function getParticlesMaxResolution($res_doc) - { - return $this->getFromNode($res_doc,$this->getParticlesResolution($res_doc),'maxResolution'); - } - - function getParticlesLoLimit($res_doc) - { - return $this->getFromNode($res_doc,$this->getSpectralParticles($res_doc),'LoLimit'); - } - - function getParticlesHiLimit($res_doc) - { - return $this->getFromNode($res_doc,$this->getSpectralParticles($res_doc),'HiLimit'); - } - - function getParticlesSamplingStep($res_doc) - { - return $this->getFromNode($res_doc,$this->getSpectralParticles($res_doc),'SamplingStep'); - } - - function getMinParticlesSamplingStep($res_doc) - { - return $this->getFromNode($res_doc,$this->getParticlesSamplingStep($res_doc),'minSamplingStep'); - } - - function getMaxParticlesSamplingStep($res_doc) - { - return $this->getFromNode($res_doc,$this->getParticlesSamplingStep($res_doc),'maxSamplingStep'); - } - - function getTableset($res_doc) - { - return $this->getFromNode($res_doc,$this->getDataCollection($res_doc),'tableset'); - } - - function getSchema($res_doc) - { - return $this->getFromNode($res_doc,$this->getTableset($res_doc),'schema'); - } - - function getSchemaColumn($res_doc) - { - return $this->getFromNode($res_doc,$this->getSchema($res_doc),'column'); - } - - function getSchemaColumnName($res_doc) - { - return $this->getFromNode($res_doc,$this->getSchemaColumn($res_doc),'name'); - } - - function getSchemaColumnDescription($res_doc) - { - return $this->getFromNode($res_doc,$this->getSchemaColumn($res_doc),'description'); - } - - function getSchemaColumnUnit($res_doc) - { - return $this->getFromNode($res_doc,$this->getSchemaColumn($res_doc),'unit'); - } - - function getSchemaColumnUCD($res_doc) - { - return $this->getFromNode($res_doc,$this->getSchemaColumn($res_doc),'ucd'); - } - - function getSchemaColumnDataType($res_doc) - { - return $this->getFromNode($res_doc,$this->getSchemaColumn($res_doc),'dataType'); - } - - function getSchemaColumnDataproductType($res_doc) - { - return $this->getFromNode($res_doc,$this->getSchemaColumn($res_doc),'dataproduct_type'); - } -} -?> \ No newline at end of file diff --git a/php/classes/FilesMgr.php b/php/classes/FilesMgr.php index 4c63607..21c6d77 100644 --- a/php/classes/FilesMgr.php +++ b/php/classes/FilesMgr.php @@ -1,6 +1,6 @@ <?php /** - * @class FilesMgr + * @class NewFilesMgr * @brief * @author Elena * @version $Id: FilesMgr.php 2830 2015-03-26 10:33:05Z elena $ @@ -9,1224 +9,1240 @@ // private $userDirs = array('USERWSDIR' => 'WS', 'USERREQDIR' => 'REQ', 'USERDATADIR' => 'DATA', // 'USERWORKINGDIR' =>'RES', 'USERTTDIR' => 'TT', 'USERJOBDIR' => 'JOBS'); -class FilesMgr extends AmdaObjectMgr { - - private $fileName, $fileId, $theFile; - public $xp; - private $fileMgr = NULL; //used when a file format needs to use a specific manager - private $sampling = -100.0, $maxSampling = -100.0; - private $ncID = NULL; - private $simuContentRootId; - - function __construct() - { - parent::__construct('Files.xml'); - $this->contentRootId = 'myData-treeRootNode'; - $this->contentRootTag = 'fileList'; - $this->attributes = array('name' => '', 'start' => '', 'stop' => ''); - $this->optionalAttributes = array(); - $this->objTagName = 'file'; - - if (!file_exists($this->xmlName)) { - $this->createDom(); - $this->xp = new domxpath($this->contentDom); - } - } +class FilesMgr extends AmdaObjectMgr +{ + + private $fileName, $fileId, $theFile; + + public $xp; + private $fileMgr = NULL; //used when a file format needs to use a specific manager + private $sampling = -100.0, $maxSampling = -100.0; + private $ncID = NULL; + private $simuContentRootId; + + function __construct() + { + parent::__construct('Files.xml'); + $this->contentRootId = 'myData-treeRootNode'; + $this->contentRootTag = 'fileList'; + $this->attributes = array('name' => '', 'start' => '', 'stop' => ''); + $this->optionalAttributes = array(); + $this->objTagName = 'file'; + + if (!file_exists($this->xmlName)) + { + $this->createDom(); + $this->xp = new domxpath($this->contentDom); + } + } /* * Create Content Dom 'Files.xml' if it doesn't exist */ - protected function createDom() - { - $rootElement = $this->contentDom->createElement('ws'); - - $typeElement = $this->contentDom->createElement($this->contentRootTag); - $typeElement->setAttribute('xml:id', $this->contentRootId); - $rootElement->appendChild($typeElement); - $this->contentDom->appendChild($rootElement); - - // $typeElement = $this->contentDom->createElement($this->contentRootTag); - // $rootElement->appendChild($typeElement); - // $this->contentDom->appendChild($rootElement); - - $this->contentDom->save($this->xmlName); - } - + protected function createDom() + { + $rootElement = $this->contentDom->createElement('ws'); + + $typeElement = $this->contentDom->createElement($this->contentRootTag); + $typeElement->setAttribute('xml:id', $this->contentRootId); + $rootElement->appendChild($typeElement); + $this->contentDom->appendChild($rootElement); + + $this->contentDom->save($this->xmlName); + } + /* * VOTable format processing done by an instance of VOTableMgr */ - - protected function getVotFileMgr() - { - if (!$this->fileMgr) - { - $this->fileMgr = new VOTableMgr(); - $this->fileMgr->load($this->fileName); - } - - return $this->fileMgr; - } - - + protected function getVotFileMgr() + { + if (!$this->fileMgr) + { + $this->fileMgr = new VOTableMgr(); + $this->fileMgr->load($this->fileName); + } + return $this->fileMgr; + } + /* * CDF format processing */ - protected function getCdfStartStop() - { - exec('cdfstartstopfromdata '.$this->fileName, $start_stop); - return $start_stop[0]; - } - - protected function getCdfVars() - { - exec('cdfinfo '.$this->fileName, $results); - return $results; - } - - - protected function getCdfVarInfo($cdfVarId) - { - exec('cdfvarinfo '.$this->fileName.' '.$cdfVarId, $results); - $tempArr = explode(' ', $results[0]); - // data type - switch ($tempArr[0]) - { - case "CDF_FLOAT" : - case "CDF_REAL4" : $data_type = 'FLOAT'; - break; - case "CDF_INT2": - case "CDF_UCHAR": - case "CDF_UINT1" : $data_type = 'SHORT'; - break; - case "CDF_UINT2": - case "CDF_INT4" : $data_type = 'INTEGER'; - break; - case "CDF_DOUBLE": - case "CDF_REAL8": - case "CDF_UINT4": $data_type = 'DOUBLE'; - break; - default : $data_type = 'FLOAT'; - } - // data dimensions & number of records - $n_recs = $tempArr[2]; - - if ($tempArr[1] != 0) { - $size = $tempArr[3]; - //TODO 2D,3D,4D array no processing - // if ($tempArr[1] > 1) - } - else { - $size = 1; - } - - return array('type' => $data_type, 'size' => $size, 'n_records' => $n_recs); - } + protected function getCdfStartStop() + { + exec('cdfstartstopfromdata '.$this->fileName, $start_stop); + return $start_stop[0]; + } + + protected function getCdfVars() + { + exec('cdfinfo '.$this->fileName, $results); + return $results; + } + + public function getCdfVarInfo($cdfVarId) + { + exec('cdfvarinfo '.$this->fileName.' '.$cdfVarId, $results); + $tempArr = explode(' ', $results[0]); + // data type + switch ($tempArr[0]) + { + case "CDF_FLOAT" : + case "CDF_REAL4" : $data_type = 'FLOAT'; + break; + case "CDF_INT2": + case "CDF_UCHAR": + case "CDF_UINT1" : $data_type = 'SHORT'; + break; + case "CDF_UINT2": + case "CDF_INT4" : $data_type = 'INTEGER'; + break; + case "CDF_DOUBLE": + case "CDF_REAL8": + case "CDF_UINT4": $data_type = 'DOUBLE'; + break; + default : $data_type = 'FLOAT'; + } + // data dimensions & number of records + $n_recs = $tempArr[2]; + + if ($tempArr[1] != 0) { + $size = $tempArr[3]; + //TODO 2D,3D,4D array no processing + // if ($tempArr[1] > 1) + } + else { + $size = 1; + } - protected function getCdfSampling() - { - copy($this->fileName, "temp.cdf"); - exec('cdfsamplingfromdata ', $results); - unlink("temp.cdf"); + return array('type' => $data_type, 'size' => $size, 'n_records' => $n_recs); + } - return $results; - } + public function getCdfSampling() + { + copy($this->fileName, "temp.cdf"); + exec('cdfsamplingfromdata ', $results); + unlink("temp.cdf"); + return $results; + } /* * CEF format processing */ - protected function getCefStartStop() { - exec("cefstartstop ".$this->fileName, $start_stop); - return $start_stop[0]; - } - - protected function getCefTimeInfo() { - - $timeinfo = exec("ceftimeinfo ".$this->fileName); - - return $timeinfo; - } - - protected function getCefVars() { - exec('cefinfo '.$this->fileName, $results); - return $results; - } - - protected function getCefVarInfo($cdfVarId) { - exec('cefvarinfo '.$this->fileName." ".$cdfVarId, $results); - - $tempArr = explode(' ', $results[0]); - // data type - switch ($tempArr[0]) { - case "CEF_FLOAT" : $data_type = 'FLOAT'; - break; - case "CEF_SHORT": $data_type = 'SHORT'; - break; - case "CEF_INT": $data_type = 'INTEGER'; - break; - case "CEF_DOUBLE": $data_type = 'DOUBLE'; - break; - default : $data_type = 'FLOAT'; - } - // data dimensions & number of records3 - $n_recs = $tempArr[2]; - - if ($tempArr[1] != 0) { - $size = $tempArr[3]; - //TODO 2D,3D,4D array no processing - // if ($tempArr[1] > 1) - } - else { - $size = 1; - } - - return array('type' => $data_type, 'size' => $size, 'n_records' => 'TBD'); - } + protected function getcefstartstop() + { + exec("cefstartstop ".$this->filename, $start_stop); + return $start_stop[0]; + } - protected function getCefSampling() { - exec('cefsampling '.$this->fileName, $results); - return $results; - } + protected function getCefTimeInfo() + { + $timeinfo = exec("ceftimeinfo ".$this->fileName); + return $timeinfo; + } + + protected function getCefVars() + { + exec('cefinfo '.$this->fileName, $results); + return $results; + } + + protected function getCefVarInfo($cdfVarId) + { + exec('cefvarinfo '.$this->fileName." ".$cdfVarId, $results); + + $tempArr = explode(' ', $results[0]); + // data type + switch ($tempArr[0]) { + case "CEF_FLOAT" : $data_type = 'FLOAT'; + break; + case "CEF_SHORT": $data_type = 'SHORT'; + break; + case "CEF_INT": $data_type = 'INTEGER'; + break; + case "CEF_DOUBLE": $data_type = 'DOUBLE'; + break; + default : $data_type = 'FLOAT'; + } + // data dimensions & number of records3 + $n_recs = $tempArr[2]; + + if ($tempArr[1] != 0) { + $size = $tempArr[3]; + //TODO 2D,3D,4D array no processing + // if ($tempArr[1] > 1) + } + else { + $size = 1; + } + return array('type' => $data_type, 'size' => $size, 'n_records' => 'TBD'); + } + + protected function getCefSampling() + { + exec('cefsampling '.$this->fileName, $results); + return $results; + } /* * netCDF format processing if needed */ - protected function reformatNcTime() { - exec('nctimestring2double '.$this->fileName, $results); - return $results[0]; - } + protected function reformatNcTime() + { + exec('nctimestring2double '.$this->fileName, $results); + return $results[0]; + } - protected function getNcTimeInfo() { - exec('nctimeinfo '.$this->fileName, $result); - return $result[0]; - } - - protected function getNcVars(){ - exec('getncvars '.$this->fileName, $result); - if ($result[0] < 0) - return $result[0]; - $varsArr = explode("#",$result[0]); - - return $varsArr; - } - - protected function getNcVarInfo($varId) { - - exec('ncvarinfo '.$this->fileName.' '.$this->param2dd($varId), $results); - $tempArr = explode(' ', $results[0]); - // data type - switch ($tempArr[0]) { - case "5": $data_type = 'FLOAT'; - break; - case "3": $data_type = 'SHORT'; - break; - case "4" : $data_type = 'INTEGER'; - break; - case "6": $data_type = 'DOUBLE'; - break; - default: $data_type = 'FLOAT'; - } - // data dimensions & number of records - $n_recs = $tempArr[2]; - - if (count($tempArr) > 3) { - $size = $tempArr[3]; - //TODO 2D,3D,4D array no processing - // if ($tempArr[1] > 1) - } - else { - $size = 1; - } - return array('type' => $data_type, 'size' => $size, 'n_records' => $n_recs); - } - - protected function param2dd($paramID) - { - $pairs = array("-" => "_", "%" => "_","\\" => "_","$" => "_",":" => "_","+" =>" _","-" => "_","#" => "_","@" => "_", "." => "_",">" => "_", "<" => "_"); - return strtr($paramID, $pairs); - } + protected function getNcTimeInfo() + { + exec('nctimeinfo '.$this->fileName, $result); + return $result[0]; + } + + protected function getNcVars() + { + exec('getncvars '.$this->fileName, $result); + + if ($result[0] < 0) + return $result[0]; + $varsArr = explode("#",$result[0]); + + return $varsArr; + } + + protected function getNcVarInfo($varId) + { + exec('ncvarinfo '.$this->fileName.' '.$this->param2dd($varId), $results); + $tempArr = explode(' ', $results[0]); + // data type + switch ($tempArr[0]) { + case "5": $data_type = 'FLOAT'; + break; + case "3": $data_type = 'SHORT'; + break; + case "4" : $data_type = 'INTEGER'; + break; + case "6": $data_type = 'DOUBLE'; + break; + default: $data_type = 'FLOAT'; + } + // data dimensions & number of records + $n_recs = $tempArr[2]; + + if (count($tempArr) > 3) { + $size = $tempArr[3]; + //TODO 2D,3D,4D array no processing + // if ($tempArr[1] > 1) + } + else { + $size = 1; + } + + return array('type' => $data_type, 'size' => $size, 'n_records' => $n_recs); + } + + protected function param2dd($paramID) + { + $pairs = array("-" => "_", "%" => "_","\\" => "_","$" => "_",":" => "_","+" =>" _","-" => "_","#" => "_","@" => "_", "." => "_",">" => "_", "<" => "_"); + return strtr($paramID, $pairs); + } /* * ascii format processing */ - protected function getTxtSampling() { - - $StartTime = null; - if (!file_exists($this->fileName)) return -100; - $i = 0; - $dt = -10; - - $handler = fopen($this->fileName, 'r'); - if ($handler) { - while (!feof($handler) && !$StartTime) { - $oneLine = trim(fgets($handler)); - $elems = explode(" ", preg_replace('/\s+/', ' ', $oneLine)); - if ((strlen($elems[0]) < 16) || !($time = strtotime($elems[0]))) { - $i++; - continue; - } - $StartTime = $time; - if (is_numeric($elems[1])) $dt = $elems[1]; - //else Array for sure !!! - } - } - - if (feof($handle)) return -10; - - $oneLine = trim(fgets($handler)); - $elems = explode(" ",$oneLine); - if (count($elems) < 2) return -10; - - // dT else Array - if (!($time = strtotime($elems[0]))) { - return $dt; - } - - return $time - $StartTime; - } + protected function getTxtSampling() + { + $StartTime = null; + if (!file_exists($this->fileName)) return -100; + $i = 0; + $dt = -10; + + $handler = fopen($this->fileName, 'r'); + if ($handler) { + while (!feof($handler) && !$StartTime) { + $oneLine = trim(fgets($handler)); + $elems = explode(" ", preg_replace('/\s+/', ' ', $oneLine)); + if ((strlen($elems[0]) < 16) || !($time = strtotime($elems[0]))) { + $i++; + continue; + } + $StartTime = $time; + if (is_numeric($elems[1])) $dt = $elems[1]; + //else Array for sure !!! + } + } + + if (feof($handle)) return -10; + + $oneLine = trim(fgets($handler)); + $elems = explode(" ",$oneLine); + if (count($elems) < 2) return -10; + + // dT else Array + if (!($time = strtotime($elems[0]))) { + return $dt; + } + + return $time - $StartTime; + } - public function getTxtSamplings() { - - $StartTime = null; - if (!file_exists($this->fileName)) return array(-100); - - $handler = fopen($this->fileName, 'r'); - if ($handler) { - $i = 0; - while (!feof($handler) && !$StartTime) { - $oneLine = trim(fgets($handler)); - $elems = explode(" ", preg_replace('/\s+/', ' ', $oneLine)); - if (strlen($elems[0]) < 16 || !($time = strtotime($elems[0]))) { - $i++; - continue; - } - - $StartTime = $time; - if (!(is_numeric($elems[1]))) return array(-10); - $dt = $elems[1]; - } - } - - if (feof($handle)) return array(-10); - $oneLine = trim(fgets($handler)); - $elems = explode(" ",$oneLine); - if (count($elems) < 2) return array (-1); + public function getTxtSamplings() + { + $StartTime = null; + if (!file_exists($this->fileName)) return array(-100); + + $handler = fopen($this->fileName, 'r'); + if ($handler) { + $i = 0; + while (!feof($handler) && !$StartTime) { + $oneLine = trim(fgets($handler)); + $elems = explode(" ", preg_replace('/\s+/', ' ', $oneLine)); + if (strlen($elems[0]) < 16 || !($time = strtotime($elems[0]))) { + $i++; + continue; + } + + $StartTime = $time; + if (!(is_numeric($elems[1]))) return array(-10); + $dt = $elems[1]; + } + } + + if (feof($handle)) return array(-10); + $oneLine = trim(fgets($handler)); + $elems = explode(" ",$oneLine); + if (count($elems) < 2) return array (-1); // dT else Array - if (!($time = strtotime($elems[0]))) return array($dt); - else { - $minSampling = +1.e31; - $maxSampling = 0.0; - - while (!feof($handler)) { - $oneLine = trim(fgets($handler)); - $elems = explode(" ",$oneLine); - if (count($elems) < 2) continue; - $StartTime = $time; - if (!($time = strtotime($elems[0]))) return array(-1); - $deltaT[$time - $StartTime]++; - } - - foreach ($deltaT as $key => $value) { - if ($value < 5) continue; - if ($key < $minSampling) $minSampling = $key; - if ($key > $maxSampling) $maxSampling = $key; - } - - return array($minSampling,$maxSampling); - } - } + if (!($time = strtotime($elems[0]))) + return array($dt); + else + { + $minSampling = +1.e31; + $maxSampling = 0.0; + + while (!feof($handler)) + { + $oneLine = trim(fgets($handler)); + $elems = explode(" ",$oneLine); + if (count($elems) < 2) continue; + $StartTime = $time; + if (!($time = strtotime($elems[0]))) return array(-1); + $deltaT[$time - $StartTime]++; + } + + foreach ($deltaT as $key => $value) + { + if ($value < 5) continue; + if ($key < $minSampling) $minSampling = $key; + if ($key > $maxSampling) $maxSampling = $key; + } + + return array($minSampling,$maxSampling); + } + } /* * Delete comments and convert time into double */ - public function reformatTxt() { - - $StartTime = null; - if (!file_exists($this->fileName)) return -100; - - $handler = fopen($this->fileName, 'r'); - if ($handler) { - $offset = ftell($handle); - $i = 0; - while (!$StartTime && !feof($handler)) { - $oneLine = trim(fgets($handler)); - $elems = explode(" ", preg_replace('/\s+/', ' ', $oneLine)); - if (!($time = strtotime($elems[0]))) { - $offset = ftell($handle); - $i++; - continue; - } - $StartTime = $time; - $dt = $elems[1]; - } - } + public function reformatTxt() + { + $StartTime = null; + if (!file_exists($this->fileName)) return -100; + + $handler = fopen($this->fileName, 'r'); + if ($handler) + { + $offset = ftell($handle); + $i = 0; + while (!$StartTime && !feof($handler)) + { + $oneLine = trim(fgets($handler)); + $elems = explode(" ", preg_replace('/\s+/', ' ', $oneLine)); + if (!($time = strtotime($elems[0]))) + { + $offset = ftell($handle); + $i++; + continue; + } + $StartTime = $time; + $dt = $elems[1]; + } + } - $newfile = fopen(USERDATADIR."temp", "w"); - - $oneLine = trim(fgets($handler)); - $elems = explode(" " , $oneLine); - // dT - if (!($time = strtotime($elems[0]))) { - - $newtime = $StartTime; - settype($dt, "float"); - if ($oneLine != PHP_EOL && count($elems) > 0) fwrite($newfile, $newtime." ".$oneLine.PHP_EOL); - $newtime += $dt; - - while (!feof($handler)) { - $oneLine = trim(fgets($handler)); - if ($oneLine != PHP_EOL && count($elems) > 0) fwrite($newfile, $newtime." ".$oneLine.PHP_EOL); - $newtime += $dt; - } - } - // Array - else { - fseek($handler, $offset); - while (!feof($handler)) { - $oneLine = trim(fgets($handler)); - $elems = explode(" " ,$oneLine); - // empty lines - if (count($elems) < 2) continue; - $newtime = strtotime($elems[0]); - //TODO Error message if wrong time format...??? - if (!$newtime) continue; - unset($elems[0]); - $newline = join($elems," "); - fwrite($newfile,$newtime." ". $newline.PHP_EOL); - } - } - fclose($newfile); - - rename(USERDATADIR."temp",$this->fileName); - - return $StartTime." ".$newtime; - } + $newfile = fopen(USERDATADIR."temp", "w"); + + $oneLine = trim(fgets($handler)); + $elems = explode(" " , $oneLine); + // dT + if (!($time = strtotime($elems[0]))) + { + $newtime = $StartTime; + settype($dt, "float"); + if ($oneLine != PHP_EOL && count($elems) > 0) fwrite($newfile, $newtime." ".$oneLine.PHP_EOL); + $newtime += $dt; + + while (!feof($handler)) + { + $oneLine = trim(fgets($handler)); + if ($oneLine != PHP_EOL && count($elems) > 0) fwrite($newfile, $newtime." ".$oneLine.PHP_EOL); + $newtime += $dt; + } + } + // Array + else + { + fseek($handler, $offset); + while (!feof($handler)) + { + $oneLine = trim(fgets($handler)); + $elems = explode(" " ,$oneLine); + // empty lines + if (count($elems) < 2) continue; + $newtime = strtotime($elems[0]); + //TODO Error message if wrong time format...??? + if (!$newtime) continue; + unset($elems[0]); + $newline = join($elems," "); + fwrite($newfile,$newtime." ". $newline.PHP_EOL); + } + } + fclose($newfile); + + rename(USERDATADIR."temp",$this->fileName); + + return $StartTime." ".$newtime; + } /* * Convert time into ISO */ - protected function reformatTime($timeFormat, $timeLength, $doy) { - - $formatLength = $timeLength == 'auto' ? strlen($timeFormat) + (strpos($timeFormat,"Y") !== false)*3 + (strpos($timeFormat,"y") !== false) - + (strpos($timeFormat,"M") !== false)*2 + (strpos($timeFormat,"m") !== false) - + (strpos($timeFormat,"d") !== false) + (strpos($timeFormat,"H") !== false) - + (strpos($timeFormat,"i") !== false) + (strpos($timeFormat,"s") !== false) - + (strpos($timeFormat,".u") !== false)*2 : $timeLength; + protected function reformatTime($timeFormat, $timeLength, $doy) + { + $formatLength = $timeLength == 'auto' ? strlen($timeFormat) + (strpos($timeFormat,"Y") !== false)*3 + (strpos($timeFormat,"y") !== false) + + (strpos($timeFormat,"M") !== false)*2 + (strpos($timeFormat,"m") !== false) + + (strpos($timeFormat,"d") !== false) + (strpos($timeFormat,"H") !== false) + + (strpos($timeFormat,"i") !== false) + (strpos($timeFormat,"s") !== false) + + (strpos($timeFormat,".u") !== false)*2 : $timeLength; - if (strpos($timeFormat,".u") !== false) { - $formatLength = $formatLength - 4; - $timeFormat = substr($timeFormat, 0, strlen($timeFormat)-2); - } + if (strpos($timeFormat,".u") !== false) + { + $formatLength = $formatLength - 4; + $timeFormat = substr($timeFormat, 0, strlen($timeFormat)-2); + } - if (strpos($timeFormat,".k") !== false) { - $formatLength = $formatLength - 2; - $timeFormat = substr($timeFormat, 0, strlen($timeFormat)-2); - } + if (strpos($timeFormat,".k") !== false) + { + $formatLength = $formatLength - 2; + $timeFormat = substr($timeFormat, 0, strlen($timeFormat)-2); + } - $handle = fopen($this->fileName,'r'); + $handle = fopen($this->fileName,'r'); - if ($handle) { - $newfile = fopen(USERDATADIR."temp", "w"); - while (!feof($handle)) { - if (($oneLine = fgets($handle)) !== false) { - $line = $timeLength == 'auto' ? $line = trim(preg_replace('/\s+/', ' ', $oneLine)) : trim($oneLine); - - if (strlen($line) > $formatLength) { - try - { - $date = DateTime::createFromFormat($timeFormat, trim(substr($line,0,$formatLength))); - if (!$date) { - if (strpos($line,'#') === 0) fwrite($newfile, $line.PHP_EOL); - } - else { - // DOY starts from 1 - if ($doy) { - $date->modify('-1 day'); - } - $suffix = preg_replace('/\s+/', ' ',substr($line, $formatLength)); - fwrite($newfile,$date->format('Y-m-d')."T".$date->format('H:i:s').$suffix.PHP_EOL); - } - } - catch (Exception $e) - { - // fwrite($newfile,$line.PHP_EOL); - } - } - else - if (strpos($line,'#') === 0) fwrite($newfile,$line.PHP_EOL); - } - } - } - else { - if (file_exists($this->fileName)) { - fclose($handle); - unlink($this->fileName); - } - return $false; - } - - fclose($newfile); - fclose($handle); - - rename(USERDATADIR."temp", $this->fileName); - return true; - } + if ($handle) + { + $newfile = fopen(USERDATADIR."temp", "w"); + while (!feof($handle)) + { + if (($oneLine = fgets($handle)) !== false) + { + $line = $timeLength == 'auto' ? $line = trim(preg_replace('/\s+/', ' ', $oneLine)) : trim($oneLine); + + if (strlen($line) > $formatLength) + { + try + { + $date = DateTime::createFromFormat($timeFormat, trim(substr($line,0,$formatLength))); + if (!$date) + { + if (strpos($line,'#') === 0) fwrite($newfile, $line.PHP_EOL); + } + else + { + // DOY starts from 1 + if ($doy) { + $date->modify('-1 day'); + } + $suffix = preg_replace('/\s+/', ' ',substr($line, $formatLength)); + fwrite($newfile,$date->format('Y-m-d')."T".$date->format('H:i:s').$suffix.PHP_EOL); + } + } + catch (Exception $e) + { + // fwrite($newfile,$line.PHP_EOL); + } + } + else + if (strpos($line,'#') === 0) fwrite($newfile,$line.PHP_EOL); + } + } + } + else + { + if (file_exists($this->fileName)) + { + fclose($handle); + unlink($this->fileName); + } + return $false; + } + + fclose($newfile); + fclose($handle); + + rename(USERDATADIR."temp", $this->fileName); + return true; + } /* -* Returns number of columns in text file to create data model fields in MyDataUI.js +* Returns number of columns in text file to create data model fields in MyDataUI.js */ - protected function getTxtColNumber($timeDouble) { - - if (!file_exists($this->fileName)) return -100; - $handle = fopen($this->fileName,'r'); - - if ($handle) { - $found = false; - $i = 0; - while (($line = trim(fgets($handle))) !== false && $i < 100) { - $elems = explode(" ", preg_replace('/\s+/', ' ', $line)); - $i++; - if (count($elems) < 2 || strpos($elems[0], '#') === 0) continue; - - if (!$timeDouble) { - if (strlen($elems[0]) >= 16 && ($time = strtotime($elems[0]))) { - $found = true; - break; - } - } - else { - $found = true; - break; - } - } - - if (!feof($handle) && !$found) { - fclose($handle); - unlink($this->fileName); - return -1; - } - } - fclose($handle); - - if (!$found) { - unlink($this->fileName); - return 0; - } - return count($elems); - } + protected function getTxtColNumber($timeDouble) + { + if (!file_exists($this->fileName)) return -100; + $handle = fopen($this->fileName,'r'); + + if ($handle) + { + $found = false; + $i = 0; + while (($line = trim(fgets($handle))) !== false && $i < 100) + { + $elems = explode(" ", preg_replace('/\s+/', ' ', $line)); + $i++; + if (count($elems) < 2 || strpos($elems[0], '#') === 0) continue; + + if (!$timeDouble) + { + if (strlen($elems[0]) >= 16 && ($time = strtotime($elems[0]))) + { + $found = true; + break; + } + } + else + { + $found = true; + break; + } + } + + if (!feof($handle) && !$found) + { + fclose($handle); + unlink($this->fileName); + return -1; + } + } + fclose($handle); + + if (!$found) + { + unlink($this->fileName); + return 0; + } + + return count($elems); + } /* * new file tag in Files.xml */ - protected function createSimuFile($format) { - - $newFile = $this->contentDom->createElement('file'); - $newFile->setAttribute('xml:id', $this->fileId); - $newFile->setAttribute('name', $this->fileId); - $newFile->setAttribute('format', $format); - - $start_stop = explode(" ",$this->getVotFileMgr()->getStartStop()); - $samplings = $this->getVotFileMgr()->getSamplings(); - $minSamp = $samplings["minSampling"]; - $maxSamp = $samplings["maxSampling"]; - $desc = $this->getVotFileMgr()->getDescription(); - - $start = $start_stop[0]; - $stop = $start_stop[1]; + protected function createSimuFile($format) + { + $newFile = $this->contentDom->createElement('file'); + $newFile->setAttribute('xml:id', $this->fileId); + $newFile->setAttribute('name', $this->fileId); + $newFile->setAttribute('format', $format); + + $start_stop = explode(" ",$this->getVotFileMgr()->getStartStop()); + $samplings = $this->getVotFileMgr()->getSamplings(); + $minSamp = $samplings["minSampling"]; + $maxSamp = $samplings["maxSampling"]; + $desc = $this->getVotFileMgr()->getDescription(); + + $start = $start_stop[0]; + $stop = $start_stop[1]; - $newFile->setAttribute("start",$start); - $newFile->setAttribute("stop",$stop); - $newFile->setAttribute('minsampling',$minSamp); - $newFile->setAttribute('maxsampling',$maxSamp); - $newFile->setAttribute('uploaded', date('Y-m-d H:i:s')); + $newFile->setAttribute("start",$start); + $newFile->setAttribute("stop",$stop); + $newFile->setAttribute('minsampling',$minSamp); + $newFile->setAttribute('maxsampling',$maxSamp); + $newFile->setAttribute('uploaded', date('Y-m-d H:i:s')); -// generic MASK without datas for simu params - if ((strncmp($this->fileId, "impex___", 8) == 0) || (strncmp($this->fileId, "spase___", 8) == 0)) - $newFile->setAttribute('mask', $this->getGenericMask()); - - $newFile->nodeValue = date('Y-m-d',$start)."T".date('H:i:s',$start)."-".date('Y-m-d',$stop)."T".date('H:i:s',$stop); - if ($desc != '') - $newFile->nodeValue .= (PHP_EOL.$desc); - return $newFile; - } - - - protected function createFile($format) { - - $newFile = $this->contentDom->createElement('file'); - $newFile->setAttribute('xml:id', $this->fileId); - $newFile->setAttribute('name', $this->fileId); - $newFile->setAttribute('format', $format); - - switch ($format){ - case "cdf": - $start_stop = explode(" ",$this->getCdfStartStop()); - $result = $this->getCdfSampling(); -//TODO process errors - $minSamp = $result[count($result)-1]; -//TODO if min & max - $maxSamp = $minSamp; - break; - case "txt": - $start_stop = explode(" ",$this->reformatTxt()); - if ($start_stop[0] < 0) return $start_stop; - $minSamp = $this->sampling; - $maxSamp = $this->maxSampling; - break; - case "cef": - - // Test if 'standard' meta exist in CEF - $cefMetaTest = $this->getCefStartStop(); - - if ($cefMetaTest != -1) { - $cefStartStop = explode("/",$cefMetaTest); - $start_stop[] = strtotime($cefStartStop[0]); - $start_stop[] = strtotime($cefStartStop[1]); - $result = $this->getCefSampling(); - $minSamp = $result[count($result)-1]; - } - else { - // no META data - so time processing - $timeInfo = $this->getCefTimeInfo(); - $timeInfoArr = explode(" ", $timeInfo); - $start_stop[] = $timeInfoArr[0]; - $start_stop[] = $timeInfoArr[1]; - $minSamp = $timeInfoArr[2]; - } -//TODO if min & max - $maxSamp = $minSamp; - break; - case "vot" : - $start_stop = explode(" ",$this->getVotFileMgr()->getStartStop()); - $samplings = $this->getVotFileMgr()->getSamplings(); - $minSamp = $samplings["minSampling"]; - $maxSamp = $samplings["maxSampling"]; - $desc = $this->getVotFileMgr()->getDescription(); - break; - case "nc": - $ncInfo = $this->getNcTimeInfo(); - if ($ncInfo < 0) { - unlink($this->fileName); - return $ncInfo; - } - $ncInfoArr = explode("#",$ncInfo); - $start_stop = explode(":",$ncInfoArr[0]); -//TODO process errors - $minSamp = $ncInfoArr[1]; -//TODO if min & max - $maxSamp = $minSamp; - break; - default: - - } - $start = $start_stop[0]; - $stop = $start_stop[1]; - - $newFile->setAttribute("start",$start); - $newFile->setAttribute("stop",$stop); - $newFile->setAttribute('minsampling',$minSamp); - $newFile->setAttribute('maxsampling',$maxSamp); - $newFile->setAttribute('uploaded', date('Y-m-d H:i:s')); + // generic MASK without datas for simu params + if ((strncmp($this->fileId, "impex___", 8) == 0) || (strncmp($this->fileId, "spase___", 8) == 0)) + $newFile->setAttribute('mask', $this->getGenericMask()); + + $newFile->nodeValue = date('Y-m-d',$start)."T".date('H:i:s',$start)."-".date('Y-m-d',$stop)."T".date('H:i:s',$stop); + if ($desc != '') + $newFile->nodeValue .= (PHP_EOL.$desc); + + return $newFile; + } + + + protected function createFile($format) + { + $newFile = $this->contentDom->createElement('file'); + $newFile->setAttribute('xml:id', $this->fileId); + $newFile->setAttribute('name', $this->fileId); + $newFile->setAttribute('format', $format); + + switch ($format) + { + case "cdf": + $start_stop = explode(" ",$this->getCdfStartStop()); + $result = $this->getCdfSampling(); + //TODO process errors + $minSamp = $result[count($result)-1]; + //TODO if min & max + $maxSamp = $minSamp; + break; + case "txt": + $start_stop = explode(" ",$this->reformatTxt()); + if ($start_stop[0] < 0) return $start_stop; + $minSamp = $this->sampling; + $maxSamp = $this->maxSampling; + break; + case "cef": + // Test if 'standard' meta exist in CEF + $cefMetaTest = $this->getCefStartStop(); + + if ($cefMetaTest != -1) + { + $cefStartStop = explode("/",$cefMetaTest); + $start_stop[] = strtotime($cefStartStop[0]); + $start_stop[] = strtotime($cefStartStop[1]); + $result = $this->getCefSampling(); + $minSamp = $result[count($result)-1]; + } + else + { + // no META data - so time processing + $timeInfo = $this->getCefTimeInfo(); + $timeInfoArr = explode(" ", $timeInfo); + $start_stop[] = $timeInfoArr[0]; + $start_stop[] = $timeInfoArr[1]; + $minSamp = $timeInfoArr[2]; + } + //TODO if min & max + $maxSamp = $minSamp; + break; + case "vot" : + $start_stop = explode(" ",$this->getVotFileMgr()->getStartStop()); + $samplings = $this->getVotFileMgr()->getSamplings(); + $minSamp = $samplings["minSampling"]; + $maxSamp = $samplings["maxSampling"]; + $desc = $this->getVotFileMgr()->getDescription(); + break; + case "nc": + $ncInfo = $this->getNcTimeInfo(); + if ($ncInfo < 0) { + unlink($this->fileName); + return $ncInfo; + } + $ncInfoArr = explode("#",$ncInfo); + $start_stop = explode(":",$ncInfoArr[0]); + //TODO process errors + $minSamp = $ncInfoArr[1]; + //TODO if min & max + $maxSamp = $minSamp; + break; + default: + } + $start = $start_stop[0]; + $stop = $start_stop[1]; + + $newFile->setAttribute("start",$start); + $newFile->setAttribute("stop",$stop); + $newFile->setAttribute('minsampling',$minSamp); + $newFile->setAttribute('maxsampling',$maxSamp); + $newFile->setAttribute('uploaded', date('Y-m-d H:i:s')); -// generic MASK without datas for simu params - if ((strncmp($this->fileId, "impex___", 8) === 0) || (strncmp($this->fileId, "spase___", 8) === 0)) - $newFile->setAttribute('mask', $this->getGenericMask()); - else - $newFile->setAttribute('mask', $this->fileId); - - $newFile->nodeValue = date('Y-m-d',$start)."T".date('H:i:s',$start)."-".date('Y-m-d',$stop)."T".date('H:i:s',$stop); - if ($desc != '') - $newFile->nodeValue .= (PHP_EOL.$desc); - - return $newFile; - } + // generic MASK without datas for simu params + if ((strncmp($this->fileId, "impex___", 8) === 0) || (strncmp($this->fileId, "spase___", 8) === 0)) + $newFile->setAttribute('mask', $this->getGenericMask()); + else + $newFile->setAttribute('mask', $this->fileId); + + $newFile->nodeValue = date('Y-m-d',$start)."T".date('H:i:s',$start)."-".date('Y-m-d',$stop)."T".date('H:i:s',$stop); + if ($desc != '') + $newFile->nodeValue .= (PHP_EOL.$desc); + + return $newFile; + } - protected function getGenericMask() { - if (strncmp($this->fileId, "impex___", 8) == 0) { - $prefix = "impex___"; - $tmpFileName = str_replace ("impex___", "", $this->fileId); - } - elseif (strncmp($this->fileId, "spase___", 8) == 0) { - $prefix = "spase___"; - $tmpFileName = str_replace ("spase___", "", $this->fileId); - } - $tmpFileArray = explode( '.', $tmpFileName); - $tmpParamArray = explode( '_', $tmpFileArray[0]); - array_pop($tmpParamArray); - array_pop($tmpParamArray); - $tmpName = implode("_", $tmpParamArray); - - $mask = $prefix.$tmpName."_*.xml"; - return $mask; - } + protected function getGenericMask() + { + if (strncmp($this->fileId, "impex___", 8) == 0) { + $prefix = "impex___"; + $tmpFileName = str_replace ("impex___", "", $this->fileId); + } + elseif (strncmp($this->fileId, "spase___", 8) == 0) { + $prefix = "spase___"; + $tmpFileName = str_replace ("spase___", "", $this->fileId); + } + $tmpFileArray = explode( '.', $tmpFileName); + $tmpParamArray = explode( '_', $tmpFileArray[0]); + array_pop($tmpParamArray); + array_pop($tmpParamArray); + $tmpName = implode("_", $tmpParamArray); + + $mask = $prefix.$tmpName."_*.xml"; + return $mask; + } /* //TODO check how to upgrade this */ - protected function getFormat() { - - $ext = pathinfo($this->fileName, PATHINFO_EXTENSION); + protected function getFormat() + { + $ext = pathinfo($this->fileName, PATHINFO_EXTENSION); + + if (PHP_VERSION_ID < 50300) + { + $finfo = new finfo(FILEINFO_MIME, MAGIC_FILE); + $file_info = explode(";", $finfo->file($this->fileName)); + } + else + { + // PHP v >= 5.3 comes with its own magic file !!!! + $finfo = finfo_open(FILEINFO_MIME); + $file_info = explode(";",finfo_file($finfo, $this->fileName)); + } - if (PHP_VERSION_ID < 50300) { - $finfo = new finfo(FILEINFO_MIME, MAGIC_FILE); - $file_info = explode(";", $finfo->file($this->fileName)); - } - else { - // PHP v >= 5.3 comes with its own magic file !!!! - $finfo = finfo_open(FILEINFO_MIME); - $file_info = explode(";",finfo_file($finfo, $this->fileName)); - } + if (strpos($file_info[0],"plain") !== false) + { + if (strpos($ext,"cef") !== false) return "cef"; + return "txt"; + } - if (strpos($file_info[0],"plain") !== false) { - if (strpos($ext,"cef") !== false) return "cef"; - return "txt"; - } - - if (strpos($file_info[0],"application/x-gzip") !== false) { - if (strpos($this->fileName,"cef.gz") !== false) return "cef"; - } - - if (strpos($file_info[0],"application/xml") !== false) - { - //if ($this->getVotFileMgr()->isValidSchema()) //BRE : No schema validation for the moment due to some trouble with Topcat (it can create not valid VOTable) - return "vot"; - } - - // check binary at different machines - if it works..... - if (strpos($file_info[0],"octet-stream") !== false) { - if (strpos($ext,"cdf") !== false) return "cdf"; - if (strpos($ext,"nc") !== false) return "nc"; - - } - return "unknown"; - } + if (strpos($file_info[0],"application/x-gzip") !== false) + { + if (strpos($this->fileName,"cef.gz") !== false) return "cef"; + } + + if (strpos($file_info[0],"application/xml") !== false) + { + //if ($this->getVotFileMgr()->isValidSchema()) //BRE : No schema validation for the moment due to some trouble with Topcat (it can create not valid VOTable) + return "vot"; + } + + // check binary at different machines - if it works..... + if (strpos($file_info[0],"octet-stream") !== false) + { + if (strpos($ext,"cdf") !== false) return "cdf"; + if (strpos($ext,"nc") !== false) return "nc"; + } + + return "unknown"; + } /* * PUBLIC FUNCTIONS -*/ - - public function getAsciiFile($name) { - - $this->fileName = USERDATADIR.$name; +*/ + public function getAsciiFile($name) + { + $this->fileName = USERDATADIR.$name; - if (!file_exists(USERDATADIR.$name)) - return array('success' => false, 'error' => 'No such file'); + if (!file_exists(USERDATADIR.$name)) + return array('success' => false, 'error' => 'No such file'); - $handle = fopen($this->fileName, "r"); - $fileToReturn = array(); - $index = 0; - $tempFileToReturn = array(); - - while (!feof($handle)) { - $line = trim(fgets($handle)); - $tempArr = explode(' ', preg_replace('/\s+/', ' ', $line)); - if (count($tempArr) > 1) { - for ($i = 0; $i < count($tempArr); $i++) { - $name = $i === 0 ? 'Time' : 'n'.$i; -//transform double time to ISO - if ($name == 'Time') { - $temp = $tempArr[0]; - settype($temp, 'double'); - $tempArr[0] = date('Y-m-d H:i:s', $temp); - } - $tempFileToReturn[$name] = $tempArr[$i]; - } - $fileToReturn[$index] = $tempFileToReturn; - $index++; - if ($index > MAX_FILE_INDEX_TO_SHOW) break; - } - } - return $fileToReturn; - } - - + $handle = fopen($this->fileName, "r"); + $fileToReturn = array(); + $index = 0; + $tempFileToReturn = array(); + + while (!feof($handle)) + { + $line = trim(fgets($handle)); + $tempArr = explode(' ', preg_replace('/\s+/', ' ', $line)); + if (count($tempArr) > 1) + { + for ($i = 0; $i < count($tempArr); $i++) + { + $name = $i === 0 ? 'Time' : 'n'.$i; + //transform double time to ISO + if ($name == 'Time') + { + $temp = $tempArr[0]; + settype($temp, 'double'); + $tempArr[0] = date('Y-m-d H:i:s', $temp); + } + $tempFileToReturn[$name] = $tempArr[$i]; + } + + $fileToReturn[$index] = $tempFileToReturn; + $index++; + if ($index > MAX_FILE_INDEX_TO_SHOW) break; + } + } + return $fileToReturn; + } /* * Get info on parameter */ - public function getParamInfo($obj){ - - $this->fileName = USERDATADIR.$obj->file; - $varId = $obj->varName; - $format = $obj->format; - -// at first info from Files.xml - $file = $this->contentDom->getElementById($obj->file); - if ($file) { - if ($file->parentNode->tagName == 'folder') - $mask = $file->parentNode->getAttribute('name'); - else - $mask = $file->getAttribute('mask'); - $dom_info = array( 'name' => $varId, - 'minsampling' => $file->getAttribute('minsampling'), - 'maxsampling' => $file->getAttribute('maxsampling'), - 'mask' => $mask); - } - else { - if ($format == "nc"){ - $status = $this->reformatNcTime(); - if ($status <= 0) { - unlink($this->fileName); - return array('success' => false, 'error' => 'error '.$timeFormat.PHP_EOL.'Time Format problem'); - } - $ncInfo = $this->getNcTimeInfo(); - $ncVars = $this->getNcVars(); - if ($ncInfo < 0) { - unlink($this->fileName); - return $ncInfo; - } - $ncInfoArr = explode("#",$ncInfo); - $start_stop = explode(":",$ncInfoArr[0]); - //TODO process errors - $minSamp = $ncInfoArr[1]; - //TODO if min & max - $maxSamp = $minSamp; + public function getParamInfo($obj) + { + $this->fileName = USERDATADIR.$obj->file; + $varId = $obj->varName; + $format = $obj->format; + + // at first info from Files.xml + $file = $this->contentDom->getElementById($obj->file); + if ($file) + { + if ($file->parentNode->tagName == 'folder') + $mask = $file->parentNode->getAttribute('name'); + else + $mask = $file->getAttribute('mask'); + + $dom_info = array( 'name' => $varId, + 'minsampling' => $file->getAttribute('minsampling'), + 'maxsampling' => $file->getAttribute('maxsampling'), + 'mask' => $mask); + } + else + { + if ($format == "nc") + { + $status = $this->reformatNcTime(); + if ($status <= 0) + { + unlink($this->fileName); + return array('success' => false, 'error' => 'error '.$timeFormat.PHP_EOL.'Time Format problem'); + } + $ncInfo = $this->getNcTimeInfo(); + $ncVars = $this->getNcVars(); + + if ($ncInfo < 0) + { + unlink($this->fileName); + return $ncInfo; + } + + $ncInfoArr = explode("#",$ncInfo); + $start_stop = explode(":",$ncInfoArr[0]); + //TODO process errors + $minSamp = $ncInfoArr[1]; + //TODO if min & max + $maxSamp = $minSamp; - $dom_info = array( 'name' => $varId, - 'minsampling' => $minSamp, - 'maxsampling' => $maxSamp, - 'mask' => $obj->mask); - } - } - - switch ($format){ - case "cdf": - $info = $this->getCdfVarInfo($varId); - break; - case "txt": - break; - case "cef": - $info = $this->getCefVarInfo($varId); - break; - case "nc": - $info = $this->getNcVarInfo($varId); - break; - case "vot": - $info = $this->getVotFileMgr()->getFieldInfoByID($varId); - break; - default: - - } - return array('success' => true, 'info' => array_merge($dom_info,$info)); - } - - - public function deleteObject($obj) - { - $myBaseManager = new BaseManager(); - - $paramMgr = new DerivedParamMgr('myDataParam'); - $xpd = new domxpath($paramMgr->contentDom); + $dom_info = array( 'name' => $varId, + 'minsampling' => $minSamp, + 'maxsampling' => $maxSamp, + 'mask' => $obj->mask); + } + } - //File, not a folder - if ($obj->leaf) { - $this->fileName = USERDATADIR.$obj->id; + switch ($format) + { + case "cdf": + $info = $this->getCdfVarInfo($varId); + break; + case "txt": + break; + case "cef": + $info = $this->getCefVarInfo($varId); + break; + case "nc": + $info = $this->getNcVarInfo($varId); + break; + case "vot": + $info = $this->getVotFileMgr()->getFieldInfoByID($varId); + break; + default: - if (file_exists($this->fileName)) - unlink($this->fileName); + } + return array('success' => true, 'info' => array_merge($dom_info,$info)); + } - $theFile = $this->contentDom->getElementById($obj->id); - - - // Update data base - $fileInBase = $myBaseManager->xp->query("//file[@name='".$obj->id."']"); - if ($fileInBase->length > 0) { - $viInfo = $myBaseManager->delFile($fileInBase->item(0)); - - $mask = $viInfo['mask']; - $length = $viInfo['length']; - - $params = $xpd->query("//mydata[@mask='".$mask."']"); + public function deleteObject($obj) + { + $myBaseManager = new BaseManager(); - if ($params->length > 0) { - // NO FILES in the mask; corresponding parameters are to be deleted - if ($length == 0) { - $paramsToDelete = array(); - for ($i = $params->length; --$i >= 0; ) { - $id = $params->item($i)->getAttribute('xml:id'); - $paramMgr->deleteParameter($id); - $paramMgr->deleteFromContent($params->item($i)); - $paramsToDelete[] = $id; - } - } - // update params description in Content Dom - else { - $vi = $myBaseManager->getVi($mask); - $desc = $myBaseManager->getStartStop($vi); - foreach ($params as $param) $param->setAttribute("desc",$desc); - $paramMgr->saveContent(); - } - } - } - // WS/Files.xml - if ($theFile) { - if ($desc) - $theFile->parentNode->setAttribute('info', $desc); - $theFile->parentNode->removeChild($theFile); - $this->contentDom->save($this->xmlName); - } - } - // Folder - else { - $mask = $obj->id; - $theMask = $this->contentDom->getElementById($obj->id); - $files = $theMask->getElementsByTagName('file'); - - foreach ($files as $file) { - $fileName = USERDATADIR.$file->getAttribute('name'); - if (file_exists($fileName)) unlink($fileName); - } - - $this->deleteFromContent($theMask); - $myBaseManager->delVI($mask); - - $params = $xpd->query("//mydata[@mask='".$mask."']"); - $paramsToDelete = array(); - for ($i = $params->length; --$i >= 0; ) { - $id = $params->item($i)->getAttribute('xml:id'); - $paramMgr->deleteParameter($id); - $paramMgr->deleteFromContent($params->item($i)); - $paramsToDelete[] = $id; - } - } - // No more files for myDataParams - if ($paramsToDelete) - return array('id' => $obj->id, 'params' => $paramsToDelete); - - // update info for myDataParams Start Stop were changed - return array('id' => $obj->id, 'mask' => $mask, 'maskDesc' => $desc); - } - - - public function deleteSimuObject($obj) { + $paramMgr = new DerivedParamMgr('myDataParam'); + $xpd = new domxpath($paramMgr->contentDom); - $myBaseManager = new BaseManager(); - $paramMgr = new DerivedParamMgr('mySimuParam'); - $xpd = new domxpath($paramMgr->contentDom); + //File, not a folder + if ($obj->leaf) + { + $this->fileName = USERDATADIR.$obj->id; - if ($obj->leaf) { - $this->fileName = USERDATADIR.$obj->id; + if (file_exists($this->fileName)) + unlink($this->fileName); + + $theFile = $this->contentDom->getElementById($obj->id); + // Update data base + $fileInBase = $myBaseManager->xp->query("//file[@name='".$obj->id."']"); - if (file_exists($this->fileName)) unlink($this->fileName); - $theFile = $this->contentDom->getElementById($obj->id); - if ($theFile) { - $theFile->parentNode->removeChild($theFile); - $this->contentDom->save($this->xmlName); - } - -// update base data - - $fileInBase = $myBaseManager->xp->query("//file[@name='".$obj->id."']"); - if ($fileInBase->length > 0) { - $mask = $myBaseManager->delFile($fileInBase->item(0)); - - $params = $xpd->query("//mydata[@mask='".$mask."']"); - if ($params->length > 0) { -// NO FILES in the mask; corresponding parameters are to be deleted - if (strcmp($mask, "NONEMPTY") != 0) { - $paramsToDelete = array(); - for ($i = $params->length; --$i >= 0; ) { - $id = $params->item($i)->getAttribute('xml:id'); - $paramMgr->deleteParameter($id); - $paramMgr->deleteFromContent($params->item($i)); - $paramsToDelete[] = $id; - } - } -// update params description in Content Dom - else { - $vi = $myBaseManager->getVi($mask); - $desc = $myBaseManager->getStartStop($vi); - foreach ($params as $param) $param->setAttribute("desc",$desc); - $paramMgr->saveContent(); - } - } - } - } - else { - $mask = $obj->id; - $theMask = $this->contentDom->getElementById($obj->id); - $files = $theMask->getElementsByTagName('file'); - foreach ($files as $file) { - $fileName = USERDATADIR.$file->getAttribute('name'); - if (file_exists($fileName)) unlink($fileName); + if ($fileInBase->length > 0) + { + $viInfo = $myBaseManager->delFile($fileInBase->item(0)); + + $mask = $viInfo['mask']; + $length = $viInfo['length']; + + $params = $xpd->query("//mydata[@mask='".$mask."']"); + + if ($params->length > 0) + { + // NO FILES in the mask; corresponding parameters are to be deleted + if ($length == 0) + { + $paramsToDelete = array(); + for ($i = $params->length; --$i >= 0; ) + { + $id = $params->item($i)->getAttribute('xml:id'); + $paramMgr->deleteParameter($id); + $paramMgr->deleteFromContent($params->item($i)); + $paramsToDelete[] = $id; + } + } + // update params description in Content Dom + else + { + $vi = $myBaseManager->getVi($mask); + $desc = $myBaseManager->getStartStop($vi); + foreach ($params as $param) $param->setAttribute("desc",$desc); + $paramMgr->saveContent(); + } + } + } + // WS/Files.xml + if ($theFile) + { + if ($desc) + $theFile->parentNode->setAttribute('info', $desc); + $theFile->parentNode->removeChild($theFile); + $this->contentDom->save($this->xmlName); + } } - $this->deleteFromContent($theMask); - $myBaseManager->delVI($mask); - - $params = $xpd->query("//mydata[@mask='".$mask."']"); - $paramsToDelete = array(); - for ($i = $params->length; --$i >= 0; ) { - $id = $params->item($i)->getAttribute('xml:id'); - $paramMgr->deleteParameter($id); - $paramMgr->deleteFromContent($params->item($i)); - $paramsToDelete[] = $id; - } - } - - if ($paramsToDelete) return array('id' => $obj->id, 'params' => $paramsToDelete); - else return array('id' => $obj->id); + // Folder + else + { + $mask = $obj->id; + $theMask = $this->contentDom->getElementById($obj->id); + $files = $theMask->getElementsByTagName('file'); + + foreach ($files as $file) + { + $fileName = USERDATADIR.$file->getAttribute('name'); + if (file_exists($fileName)) unlink($fileName); + } + + $this->deleteFromContent($theMask); + $myBaseManager->delVI($mask); + + $params = $xpd->query("//mydata[@mask='".$mask."']"); + $paramsToDelete = array(); + for ($i = $params->length; --$i >= 0; ) + { + $id = $params->item($i)->getAttribute('xml:id'); + $paramMgr->deleteParameter($id); + $paramMgr->deleteFromContent($params->item($i)); + $paramsToDelete[] = $id; + } + } + // No more files for myDataParams + if ($paramsToDelete) + return array('id' => $obj->id, 'params' => $paramsToDelete); + + // update info for myDataParams Start Stop were changed + return array('id' => $obj->id, 'mask' => $mask, 'maskDesc' => $desc); } - + /* * recombine files in Files.xml according to new Mask */ - public function addMask($fileMask, $type) { - if ($this->contentDom ->getElementById($fileMask) != null) return false; - $filesInRoot = $this->xp->query("/ws/fileList/file"); - $newMask = $this->contentDom->createElement("folder"); - $newMask->setAttribute('xml:id', $fileMask); - $newMask->setAttribute('name', $fileMask); + public function addMask($fileMask, $type) + { + if ($this->contentDom ->getElementById($fileMask) != null) return false; + $filesInRoot = $this->xp->query("/ws/fileList/file"); + $newMask = $this->contentDom->createElement("folder"); + $newMask->setAttribute('xml:id', $fileMask); + $newMask->setAttribute('name', $fileMask); - for ($i = $filesInRoot->length; --$i >= 0;) { - $aFile = $filesInRoot->item($i); - -// mask corresponds to file name - if ($this->fileMask($aFile->getAttribute("name"),$fileMask)) { - $newMask->appendChild($aFile); - } - } - - $files = $newMask->getElementsByTagName("file"); - if ($files->length == 0) return false; + for ($i = $filesInRoot->length; --$i >= 0;) + { + $aFile = $filesInRoot->item($i); + // mask corresponds to file name + if ($this->fileMask($aFile->getAttribute("name"),$fileMask)) + { + $newMask->appendChild($aFile); + } + } + + $files = $newMask->getElementsByTagName("file"); + if ($files->length == 0) return false; - foreach ($files as $file) { - $starts[] = $file->getAttribute("start"); - $stops[] = $file->getAttribute("stop"); - } + foreach ($files as $file) + { + $starts[] = $file->getAttribute("start"); + $stops[] = $file->getAttribute("stop"); + } - $newMask->setAttribute('info',date('Y-m-d',min($starts))."T".date('H:i:s',min($starts))."-".date('Y-m-d',max($stops))."T".date('H:i:s',max($stops))); + $newMask->setAttribute('info',date('Y-m-d',min($starts))."T".date('H:i:s',min($starts))."-".date('Y-m-d',max($stops))."T".date('H:i:s',max($stops))); - $fileList = $this->contentDom->getElementById($this->contentRootId); + $fileList = $this->contentDom->getElementById($this->contentRootId); - $fileList->appendChild($newMask); - $this->contentDom->save($this->xmlName); - return true; - } + $fileList->appendChild($newMask); + $this->contentDom->save($this->xmlName); + return true; + } /* * check correspondence FleName <=> Mask * returns true if Mask fits FileName */ - public function fileMask($fileName, $maskName) { - - $mask = explode("*", $maskName); - if (strpos($fileName, $mask[0]) !== 0) return false; - if (count($mask) == 1) return true; + public function fileMask($fileName, $maskName) + { + $mask = explode("*", $maskName); + if (strpos($fileName, $mask[0]) !== 0) return false; + if (count($mask) == 1) return true; - for ($i = 1; $i < count($mask); $i++) - if ($mask[$i] != null) - if (strpos($fileName, $mask[$i]) === false) return false; + for ($i = 1; $i < count($mask); $i++) + if ($mask[$i] != null) + if (strpos($fileName, $mask[$i]) === false) return false; - return true; - } + return true; + } /* * Delete Mask */ - public function delMask($oldMask) { - - $mask = $this->contentDom->getElementById($oldMask); - - if ($mask != null && $mask->tagName == "folder") { - $filesInMask = $mask->getElementsByTagName("file"); - $fileList = $this->contentDom->getElementById($this->contentRootId); - - while ($filesInMask->length > 0) - $fileList->appendChild($filesInMask->item(0)); - - $fileList->removeChild($mask); - $this->contentDom->save($this->xmlName); - - return true; - } + public function delMask($oldMask) + { + $mask = $this->contentDom->getElementById($oldMask); + + if ($mask != null && $mask->tagName == "folder") + { + $filesInMask = $mask->getElementsByTagName("file"); + $fileList = $this->contentDom->getElementById($this->contentRootId); + + while ($filesInMask->length > 0) + $fileList->appendChild($filesInMask->item(0)); + + $fileList->removeChild($mask); + $this->contentDom->save($this->xmlName); + + return true; + } - return false; - } + return false; + } /* * mask or file */ - public function getObject($name) { - - $object = $this->contentDom->getElementById($name); - - if (is_object($object)) { - // mask - if ($object->tagName == 'folder') { - $file = $object->getElementsByTagName('file'); - if ($file->length > 0) - return $this->getUploadedObject($file->item(0)->getAttribute('name')); - else - return array('success' => false, 'error' => 'Mask is empty'); - } - } - else - return array('success' => false, 'error' => 'No such mask in DOM'); - // file - return $this->getUploadedObject($name); - } + public function getObject($name) + { + $object = $this->contentDom->getElementById($name); + + if (is_object($object)) + { + // mask + if ($object->tagName == 'folder') + { + $file = $object->getElementsByTagName('file'); + if ($file->length > 0) + return $this->getUploadedObject($file->item(0)->getAttribute('name')); + else + return array('success' => false, 'error' => 'Mask is empty'); + } + } + else + return array('success' => false, 'error' => 'No such mask in DOM'); + // file + return $this->getUploadedObject($name); + } /* * Get generic info on uploaded file */ - public function getUploadedObject($name) { - - $this->fileName = USERDATADIR.$name; - $file = $this->contentDom->getElementById($name); - if (!$file) - return array('success' => false, 'error' => 'No such file in DOM'); - - $format = $file->getAttribute('format'); - $minSamp = $file->getAttribute('minsampling'); - $maxSamp = $file->getAttribute('maxsampling'); - - $mask = $file->parentNode->tagName == "folder" ? $file->parentNode->getAttribute("name") : null; - $maskDesc = $mask ? $file->parentNode->getAttribute('info') : null; - $desc = $file->nodeValue; - - $foundTime = true; + public function getUploadedObject($name) + { + $this->fileName = USERDATADIR.$name; + $file = $this->contentDom->getElementById($name); + if (!$file) + return array('success' => false, 'error' => 'No such file in DOM'); + + $format = $file->getAttribute('format'); + $minSamp = $file->getAttribute('minsampling'); + $maxSamp = $file->getAttribute('maxsampling'); + + $mask = $file->parentNode->tagName == "folder" ? $file->parentNode->getAttribute("name") : null; + $maskDesc = $mask ? $file->parentNode->getAttribute('info') : null; + $desc = $file->nodeValue; + + $foundTime = true; - switch ($format){ - case "cdf": - $vars = $this->getCdfVars(); - break; - case "txt": - $vars = $this->getTxtColNumber(true); - break; - case "nc" : - $vars = $this->getNcVars(); - break; - case "cef": - $vars = $this->getCefVars(); - break; - case "vot" : - $vars = $this->getVotFileMgr()->getFieldsInfo(); - $foundTime = ($this->getVotFileMgr()->getTimeFieldIndex() > -1); - break; - default: - } - - return array('success' => true, 'format' => $format, 'vars' => $vars, 'fileName' => $name, - 'minsampling' => $minSamp, 'maxsampling' => $maxSamp, 'mask' => $mask, 'maskDesc' => $maskDesc, - 'description' => $desc, 'foundTime' => $foundTime); - } + switch ($format) + { + case "cdf": + $vars = $this->getCdfVars(); + break; + case "txt": + $vars = $this->getTxtColNumber(true); + break; + case "nc" : + $vars = $this->getNcVars(); + break; + case "cef": + $vars = $this->getCefVars(); + break; + case "vot" : + $vars = $this->getVotFileMgr()->getFieldsInfo(); + $foundTime = ($this->getVotFileMgr()->getTimeFieldIndex() > -1); + break; + default: + } + + return array('success' => true, 'format' => $format, 'vars' => $vars, 'fileName' => $name, + 'minsampling' => $minSamp, 'maxsampling' => $maxSamp, 'mask' => $mask, 'maskDesc' => $maskDesc, + 'description' => $desc, 'foundTime' => $foundTime); + } /* * The very first processing of newly uploaded file file * $formats = array('fileFormat', 'timeFormat', 'timeSampling', 'nonStandard', 'doy'); */ - public function addFile($fileName, $formats) { - - $this->fileName = USERDATADIR.$fileName; - $this->fileId = $fileName; - - $format = $this->getFormat(); - - if ($format === 'unknown'){ - unlink($this->fileName); - return array('success' => false, 'error' => 'Sorry, unknown format of '.$fileName); - } - - if ($format == 'txt') { - if ($formats["timeFormat"] == "user") { - $res = $this->reformatTime($formats["nonStandard"], $formats["timeLength"], $formats["doy"]); - - if (!$res) { - unlink($this->fileName); - return array('success' => false, 'error' => 'can\'t reformat time'); - } - } - // check if file is not empty - $vars = $this->getTxtColNumber(false); - - if ($vars == -100) { - return array('success' => false, 'error' => 'no such file'); - } - if ($vars == -1) { - unlink($this->fileName); - return array('success' => false, 'error' => 'while reading file'); - } - - if ($vars === 0) { - unlink($this->fileName); - return array('success' => false, 'error' => 'file contains no data'); - } - - if ($formats["timeSampling"] == "constant") { - $this->sampling = $this->getTxtSampling(); - $this->maxSampling = $this->sampling; - } - else { - $samplings = $this->getTxtSamplings(); - $this->sampling = $samplings[0]; - $this->maxSampling = $samplings[1]; - } - - if ($this->sampling <= 0) { - unlink($this->fileName); - if ($this->sampling == -10) { - return array('success' => false, 'error' => 'Sorry, can\'t process'.$fileName.PHP_EOL.'. Check if there are non numeric chars in the data'); - } - return array('success' => false, 'error' => 'Sorry, can\'t process Time for '.$fileName.PHP_EOL.'. Check time format, start time (> 1970-01-01) or sampling time (>= 1s)'); - } - } - - if ($format == 'nc') { - $status = $this->reformatNcTime(); - if ($status <= 0) { - unlink($this->fileName); - return array('success' => false, 'error' => 'error '.$timeFormat.PHP_EOL.'Time Format problem'); - } - } - - //create new file tag with all attributes and add it to the content DOM - $newFile = $this->createFile($format); - if ($newFile < 0) { - unlink($this->fileName); - return array( 'success' => false, 'file' => $fileName); - } - - $isMask = false; - $masks = $this->contentDom->getElementsByTagName("folder"); - - foreach ($masks as $mask) { + public function addFile($fileName, $formats) + { + $this->fileName = USERDATADIR.$fileName; + $this->fileId = $fileName; - $folderMask = $mask->getAttribute("name"); - if ($this->fileMask($fileName, $folderMask)) { - $mask->appendChild($newFile); - - $files = $mask->getElementsByTagName("file"); - foreach ($files as $file) { - $starts[] = $file->getAttribute("start"); - $stops[] = $file->getAttribute("stop"); - } - $mask->setAttribute("info", date('Y-m-d',min($starts))."T".date('H:i:s',min($starts))."-".date('Y-m-d',max($stops))."T".date('H:i:s',max($stops))); - - $isMask = true; - break; - } - } - // no corresponding masks => add to fileList - if (!$isMask) { - $filesList = $this->contentDom->getElementById($this->contentRootId); - $filesList->appendChild($newFile); - } - - $this->contentDom->save($this->xmlName); - - //if mask exists - add to data base - $myBaseManager = new BaseManager(); - $mask = $myBaseManager->addFile($fileName); - if ($mask != null) { - $startstop = $myBaseManager->getStartStop($myBaseManager->getVi($mask)); - $myParamMgr = new DerivedParamMgr('myDataParam'); - $myParamMgr->updateMydata($mask,$startstop); - } - - return array( 'success' => true, 'file' => $fileName); - } + $format = $this->getFormat(); + + if ($format === 'unknown') + { + unlink($this->fileName); + return array('success' => false, 'error' => 'Sorry, unknown format of '.$fileName); + } + + if ($format == 'txt') + { + if ($formats["timeFormat"] == "user") + { + $res = $this->reformatTime($formats["nonStandard"], $formats["timeLength"], $formats["doy"]); + + if (!$res) + { + unlink($this->fileName); + return array('success' => false, 'error' => 'can\'t reformat time'); + } + } + // check if file is not empty + $vars = $this->getTxtColNumber(false); + + if ($vars == -100) + { + return array('success' => false, 'error' => 'no such file'); + } + + if ($vars == -1) + { + unlink($this->fileName); + return array('success' => false, 'error' => 'while reading file'); + } + + if ($vars === 0) + { + unlink($this->fileName); + return array('success' => false, 'error' => 'file contains no data'); + } + + if ($formats["timeSampling"] == "constant") + { + $this->sampling = $this->getTxtSampling(); + $this->maxSampling = $this->sampling; + } + else + { + $samplings = $this->getTxtSamplings(); + $this->sampling = $samplings[0]; + $this->maxSampling = $samplings[1]; + } + + if ($this->sampling <= 0) + { + unlink($this->fileName); + if ($this->sampling == -10) + { + return array('success' => false, 'error' => 'Sorry, can\'t process'.$fileName.PHP_EOL.'. Check if there are non numeric chars in the data'); + } + return array('success' => false, 'error' => 'Sorry, can\'t process Time for '.$fileName.PHP_EOL.'. Check time format, start time (> 1970-01-01) or sampling time (>= 1s)'); + } + } + + if ($format == 'nc') + { + $status = $this->reformatNcTime(); + if ($status <= 0) + { + unlink($this->fileName); + return array('success' => false, 'error' => 'error '.$timeFormat.PHP_EOL.'Time Format problem'); + } + } + + //create new file tag with all attributes and add it to the content DOM + $newFile = $this->createFile($format); + if ($newFile < 0) + { + unlink($this->fileName); + return array( 'success' => false, 'file' => $fileName); + } + + $isMask = false; + $masks = $this->contentDom->getElementsByTagName("folder"); + + foreach ($masks as $mask) + { + $folderMask = $mask->getAttribute("name"); + if ($this->fileMask($fileName, $folderMask)) + { + $mask->appendChild($newFile); + + $files = $mask->getElementsByTagName("file"); + foreach ($files as $file) + { + $starts[] = $file->getAttribute("start"); + $stops[] = $file->getAttribute("stop"); + } + $mask->setAttribute("info", date('Y-m-d',min($starts))."T".date('H:i:s',min($starts))."-".date('Y-m-d',max($stops))."T".date('H:i:s',max($stops))); + + $isMask = true; + break; + } + } + // no corresponding masks => add to fileList + if (!$isMask) + { + $filesList = $this->contentDom->getElementById($this->contentRootId); + $filesList->appendChild($newFile); + } + $this->contentDom->save($this->xmlName); + + //if mask exists - add to data base + $myBaseManager = new BaseManager(); + $mask = $myBaseManager->addFile($fileName); + if ($mask != null) + { + $startstop = $myBaseManager->getStartStop($myBaseManager->getVi($mask)); + $myParamMgr = new DerivedParamMgr('myDataParam'); + $myParamMgr->updateMydata($mask,$startstop); + } + + return array( 'success' => true, 'file' => $fileName); + } + + public function setFileName($name) + { + $this->fileName = USERDATADIR.$name; + } } ?> diff --git a/php/classes/VOTableMgr.php b/php/classes/VOTableMgr.php index 52e8e41..ffcaf45 100644 --- a/php/classes/VOTableMgr.php +++ b/php/classes/VOTableMgr.php @@ -4,14 +4,14 @@ * @version $Id: VOTableMgr.php 2916 2015-05-19 13:08:33Z elena $ */ - //set DEBUG_MODE to TRUE to have some log information in user data dir define("DEBUG_MODE",FALSE); -class VOTableMgr { - private $xml, $xp; - private $log; +class VOTableMgr +{ + public $xml = null; + private $log, $xp; function __construct() { @@ -185,6 +185,14 @@ class VOTableMgr { return $desc->item(0)->nodeValue; } + public function isData() + { + $trs = $this->xml->getElementsByTagName('TR'); + if ($trs->length > 0) return true; + + return false; + } + public function getFirstTR() { if (!$this->xp) @@ -260,53 +268,55 @@ class VOTableMgr { return -1; } - protected function getFieldByID($field_id) - { - if (!$this->xp) - return NULL; - - $fields = $this->xp->query($this->queryFields()); - - if ($fields->length < 1) - return NULL; - - foreach ($fields as $field) - if ($field->getAttribute("ID") == $field_id) - return $field; - - return NULL; - } + protected function getFieldByID($field_id) + { + if (!$this->xp) + return NULL; - protected function getFieldByName($field_id) - { - if (!$this->xp) - return NULL; - - $fields = $this->xp->query($this->queryFieldByName($field_id)); - - if ($fields->length < 1) - return NULL; - - foreach ($fields as $field) - if ($field->getAttribute("name") == $field_id) - return $field; - - return NULL; - } - - protected function checkIDAttribute(){ + $fields = $this->xp->query($this->queryFields()); + + if ($fields->length < 1) + return NULL; + + foreach ($fields as $field) + if ($field->getAttribute("ID") == $field_id) + return $field; + + return NULL; + } - $fields = $this->xml->getElementsByTagName('FIELD'); - $i = 0; - foreach ($fields as $field){ - $i++; - if (!$field->hasAttribute("ID")){ - $field->setAttribute("ID", "col".$i); + protected function getFieldByName($field_id) + { + if (!$this->xp) + return NULL; + + $fields = $this->xp->query($this->queryFieldByName($field_id)); + + if ($fields->length < 1) + return NULL; + + foreach ($fields as $field) + if ($field->getAttribute("name") == $field_id) + return $field; + + return NULL; } - } - $this->xml->saveXML(); - } + protected function checkIDAttribute() + { + + $fields = $this->xml->getElementsByTagName('FIELD'); + $i = 0; + foreach ($fields as $field) + { + $i++; + if (!$field->hasAttribute("ID")) + { + $field->setAttribute("ID", "col".$i); + } + } + $this->xml->saveXML(); + } public function getFieldIndexByID($field_id) { @@ -361,67 +371,69 @@ class VOTableMgr { return $start." ".$stop; } - public function getFieldInfoByID($field_id) - { - if (!$this->xp) - return array("id" => $field_id, - "error" => "No file loaded"); - $field = $this->getFieldByID($field_id); - - if (!$field) - $field = $this->getFieldByName($field_id); + public function getFieldInfoByID($field_id) + { + if (!$this->xp) + return array("id" => $field_id, "error" => "No file loaded"); + + $field = $this->getFieldByID($field_id); + + if (!$field) + $field = $this->getFieldByName($field_id); - if (!$field) - return array("id" => $field_id, - "error" => "This field doesn't exist"); - return $this->getFieldInfo($field); - } + if (!$field) + return array("id" => $field_id, "error" => "This field doesn't exist"); + + return $this->getFieldInfo($field); + } - public function getFieldInfo($field) - { - if (!$this->xp) - return array("id" => $field_id, - "error" => "No file loaded"); - $description = ''; - $desc = $field->getElementsByTagName("DESCRIPTION"); - if ($desc->length >= 1) - $description = $desc->item(0)->nodeValue; + public function getFieldInfo($field) + { + if (!$this->xp) + return array("id" => $field_id, "error" => "No file loaded"); + + $description = ''; + $desc = $field->getElementsByTagName("DESCRIPTION"); + if ($desc->length >= 1) + $description = $desc->item(0)->nodeValue; - $size = $field->getAttribute("arraysize"); - if ($size == '') - $size = 1; - else - $size = intval($size); + $size = $field->getAttribute("arraysize"); + if ($size == '') + $size = 1; + else + $size = intval($size); - switch ($field->getAttribute("datatype")) - { - case "short" : - $type = "SHORT"; - break; - case "int" : - $type = "INTEGER"; - break; - case "long" : - case "double" : - $type = "DOUBLE"; - break; - default : - $type = "FLOAT"; - } - if (!$field->getAttribute("ID")) - $id = "col".$n; - else $id = $field->getAttribute("ID"); - - return array("id" => $field->getAttribute("ID"), - "type" => $type, - "name" => $field->getAttribute("name"), - "ucd" => $field->getAttribute("ucd"), - "unit" => $field->getAttribute("unit"), - "size" => $size, - "description" => $description - ); - } + switch ($field->getAttribute("datatype")) + { + case "short" : + $type = "SHORT"; + break; + case "int" : + $type = "INTEGER"; + break; + case "long" : + case "double" : + $type = "DOUBLE"; + break; + default : + $type = "FLOAT"; + } + + if (!$field->getAttribute("ID")) + $id = "col".$n; + else + $id = $field->getAttribute("ID"); + + return array("id" => $field->getAttribute("ID"), + "type" => $type, + "name" => $field->getAttribute("name"), + "ucd" => $field->getAttribute("ucd"), + "unit" => $field->getAttribute("unit"), + "size" => $size, + "description" => $description + ); + } public function getFieldsInfo() { @@ -496,81 +508,58 @@ class VOTableMgr { "maxSampling" => $maxSampling); } - public function args2vector($file, $paramID){ + /* + * Add vector data made from components to IMPEX VOT + */ + public function addVectorToVot($paramID, $fileName) + { + $argsArr = explode(',', $paramID); + + $fields = $this->xml->getElementsByTagName('FIELD'); + $table = $this->xml->getElementsByTagName('TABLE')->item(0); + $data = $this->xml->getElementsByTagName('DATA')->item(0); + + $i=0; + $find = false; + foreach ($fields as $field) + { + if ($field->getAttribute('name') == $argsArr[0]) + { + $unit = $field->getAttribute('unit'); + $ucd = $field->getAttribute('ucd'); + $datatype = $field->getAttribute('datatype'); + $firstTD = $i; + $find = true; + break; + } + $i++; + } - $argsArr = explode('_', $paramID); - - $dom = new DOMDocument(); - $dom->load($file); - $fields = $dom->getElementsByTagName('FIELD'); - $table = $dom->getElementsByTagName('TABLE')->item(0); - $i=0; - foreach ($fields as $field){ - if ($field->getAttribute('name') == $argsArr[0]){ - $unit = $field->getAttribute('unit'); - $ucd = $field->getAttribute('ucd'); - $datatype = $field->getAttribute('datatype'); - $firstTD = $i; - } - $i++; - } - if ($firstTD > 0){ - $table->removeChild($fields->item($firstTD + 2)); - $table->removeChild($fields->item($firstTD + 1)); - $table->removeChild($fields->item($firstTD)); - - $i = 0; - foreach ($fields as $field){ - $i++; - if (strpos($field->getAttribute('ID'),'col') !== FALSE){ - $field->setAttribute('ID', 'col'.$i); - $dom->saveXML(); + if ($find) + { + $new_field = $this->xml->createElement('FIELD'); + $new_field->setAttribute('ID', $paramID); + $new_field->setAttribute('name', $paramID); + $new_field->setAttribute('datatype', $datatype); + $new_field->setAttribute('arraysize', '3'); + $new_field->setAttribute('unit', $unit); + $new_field->setAttribute('ucd', $ucd); + $colN = $fields->length + 1; + $new_field->setAttribute('ID', 'col'.$colN); + + $table->insertBefore($new_field,$data); + + $trs = $this->xml->getElementsByTagName('TR'); + foreach($trs as $tr) + { + $tds = $tr->getElementsByTagName('TD'); + $value = trim($tds->item($firstTD)->nodeValue).' '.trim($tds->item($firstTD + 1)->nodeValue).' '.trim($tds->item($firstTD + 2)->nodeValue); + $td = $this->xml->createElement('TD', $value); + $tr->appendChild($td); + } + + $this->xml->save($fileName); + } } - } - - $group = $dom->createElement('GROUP'); - $group->appendChild(new DOMAttr('ID', 'info_'.$paramID)); - $table->appendChild($group); - - $param = $dom->createElement('PARAM'); - $param->appendChild(new DOMAttr('ID', 'components_'.$paramID)); - $param->appendChild(new DOMAttr('name', 'components_'.$paramID)); - $param->appendChild(new DOMAttr('datatype', 'char')); - $param->appendChild(new DOMAttr('arraysize', '*')); - $param->appendChild(new DOMAttr('value', $argsArr[0].' '.$argsArr[1].' '.$argsArr[2] )); - $group->appendChild($param); - - $new_field = $dom->createElement('FIELD'); - $new_field->appendChild(new DOMAttr('ID', $paramID)); - $new_field->appendChild(new DOMAttr('name', $paramID)); - $new_field->appendChild(new DOMAttr('datatype', $datatype)); - $new_field->appendChild(new DOMAttr('arraysize', '3')); - $new_field->appendChild(new DOMAttr('unit', $unit)); - $new_field->appendChild(new DOMAttr('ucd', $ucd)); - $new_field->appendChild(new DOMAttr('ref', 'info_'.$paramID)); - $table->appendChild($new_field); - - $trs = $dom->getElementsByTagName('TR'); - foreach($trs as $tr){ - $tds = $tr->getElementsByTagName('TD'); - $value = trim($tds->item($firstTD)->nodeValue).' '.trim($tds->item($firstTD + 1)->nodeValue).' '.trim($tds->item($firstTD + 2)->nodeValue); - $toRemote = $tds->item($firstTD); - $tr->removeChild($toRemote); - $toRemote = $tds->item($firstTD); - $tr->removeChild($toRemote); - $toRemote = $tds->item($firstTD); - $tr->removeChild($toRemote); - - $td = $dom->createElement('TD', $value); - $tr->appendChild($td); - } - - $dom->save($file); - } - } - } - - - ?> \ No newline at end of file diff --git a/php/config.php b/php/config.php index 0e5417b..ae896f2 100644 --- a/php/config.php +++ b/php/config.php @@ -3,385 +3,209 @@ * @file config.php * @version $Id: config.php 2368 2014-05-21 08:46:23Z elena $ * - * */ - -$useFirePHP = false; -// require FirePHP files -if($useFirePHP) { - require_once("firephp/FirePHP.class.php"); - require_once("firephp/fb.php"); -} - -// define empty fb() function so code does not break -// on any forgotten fb() calls later -else { - function fb() {}; -} -ob_start(); - -// all installation dependent staff +/* + * ob_start + * This function will turn output buffering on. + * While output buffering is active no output is sent from the script (other than headers), + * instead the output is stored in an internal buffer. + * The contents of this internal buffer may be copied into a string variable using ob_get_contents(). + * To output what is stored in the internal buffer, use ob_end_flush(). + * Alternatively, ob_end_clean() will silently discard the buffer contents. +*/ +// ob_start(); + +/* +* Installation-dependent settings +*/ require_once 'my_config.php'; -if (is_file('php/amda_version.php') || is_file('amda_version.php')) - require_once 'amda_version.php'; - -// all impex dependent staff -// if (is_file('php/impex_config.php') || is_file('impex_config.php')) -// require_once 'impex_config.php'; -if (is_file('php/impex_config.php')) - require_once 'php/impex_config.php'; -else require_once 'impex_config.php'; -//--------------------------------------- - -if (!defined('PHP_VERSION_ID')) - { - $version = explode('.', PHP_VERSION); - define('PHP_VERSION_ID', ($version[0] * 10000 + $version[1] * 100 + $version[2])); +if (is_file('amda_version.php')) + require_once 'amda_version.php'; + +if (is_file('errors.php')) + require_once 'errors.php'; + +/*----------------------- SYSTEM config section --------*/ +if (!defined('PHP_VERSION_ID')) +{ + $version = explode('.', PHP_VERSION); + define('PHP_VERSION_ID', ($version[0] * 10000 + $version[1] * 100 + $version[2])); } -if (!defined('MAGIC_FILE')) - define('MAGIC_FILE','/usr/share/misc/magic'); +if (!defined('MAGIC_FILE')) + define('MAGIC_FILE','/usr/share/misc/magic'); + +date_default_timezone_set('UTC'); +/*-----------------------END SYSTEM config section --------*/ -define("MaxGuests", 10); +/*----------------------- GUESTS LOGIN section --------*/ +define("MaxGuests", 10); // Max Guests number define("GuestSessionDuration", 300); //300 minutes define("MaxGuestTimeInterval", 10); // days +/*-----------------------END GUESTS LOGIN section --------*/ -ini_set('upload_max_filesize',30000000); -// SHOULD BE DEFINED IN MASTER php.ini !!! -// ini_set('post_max_size',40000000); -ini_set('memory_limit',128000000); - -// max lines of uploaded ascii file to show -define('MAX_FILE_INDEX_TO_SHOW', 100); // user WS size limit define('DISK_QUOTA', 1024*1024*200); // 200MB - -// to avoid 403 error while copying from URL -ini_set('user_agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:7.0) Gecko/201001012 Firefox/7.0'); - +// max lines of uploaded ascii file to show +define('MAX_FILE_INDEX_TO_SHOW', 100); // private key used to be considerate as a trust client for some functions of DD web service define('DDSERVICE_PRIVATEKEY','!%p856Dc'); - -date_default_timezone_set('UTC'); -// time restriction suffix -define('restricted', '_restr'); -// one cycle secs to sleep to allow job be executed -define('JOBTIMEOUT', '1'); +/*----------------------- BATCH JOBS section --------*/ +define('JOBTIMEOUT', '1'); // one cycle secs to sleep to allow job be executed define('PLOT_CYCLES_NUMBER', 500); // cycles number for PNG define('JOB_CYCLES_NUMBER', 5); // cycles number for all the jobs - -//TODO secs wait before job is killed OR 'max_execution_time' - kill automatic? -//define('TIMEOUT', '100'); -//TODO define max PHP execution -ini_set('max_execution_time',600); - -//Error codes -define('-1','NAME_EXISTS'); -define('-2','ID_CREATION_ERROR'); -define('-3','NO_SUCH_ID'); -define('-4','NO_SUCH_PARENT_ID'); -define('-5','NO_OBJECT_FILE'); - -// SVN Repository for local parameters files (DD_*.xml, LocalParams.xml, ...) -define('SVN_DDMISSIONSINFO', 'svn://cdpp1.cesr.fr/depotINFO/'); -define('SVN_LOCALPARAMSINFO', SVN_DDMISSIONSINFO.'LocalParam/'); -define('SVN_TEMPLATES', SVN_DDMISSIONSINFO.'Templates/'); - -// EPN-TAP services -define('EPNTAP_APIS','http://voparis-tap.obspm.fr/__system__/tap/run/tap/sync'); -define('EPNTAP_AMDA','http://cdpp-epntap.cesr.fr/__system__/tap/run/tap/sync'); - -// General Info dirs; old AMDA -define('INFODIR', ROOT_PATH.'INFO/'); -define('XMLDIR', ROOT_PATH.'XML/'); +//define('TIMEOUT', '100'); //TODO secs wait before job is killed OR 'max_execution_time' - kill automatic? +/*-----------------------END BATCH JOBS section --------*/ -// General Info files; old AMDA -define('userGroupsXml',XMLDIR.'AMDA_Users.xml'); - -// PHP classes : new AMDA -define('CLASSPATH', BASE_PATH.'php/classes/'); -define('OLD_CLASSPATH', BASE_PATH.'php/old_amda/'); -define('XMLPATH', BASE_PATH.'php/XML/'); +/*----------------------- PHP run-time settings --------*/ +ini_set('memory_limit',128000000); +ini_set('max_execution_time',600); // max PHP execution +ini_set('default_socket_timeout', 600); //TODO if this is needed ? IMPEX LONG DURATION WEBSERVICES +// to avoid 403 error while copying from URL +ini_set('user_agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:7.0) Gecko/201001012 Firefox/7.0'); +// SHOULD BE DEFINED IN MASTER /etc/php.ini !!! +// ini_set('upload_max_filesize',100000000); +// ini_set('post_max_size',1050000000); +/*-----------------------END PHP run-time settings --------*/ -// General Info dirs : new AMDA -define('DATAPATH', BASE_PATH.'generic_data/'); -define('Param', DATAPATH.'Param/'); -define('ParamArgs', Param.'Args/'); -define('LocalData', DATAPATH.'LocalData/'); -define('LocalDataParam', LocalData.'Param/'); -define('EPNResources', DATAPATH.'EPNResources/'); -define('LocalDataTemplate', LocalData.'Templates/'); +// General Info dirs +define('DATAPATH', IHM_SRC_DIR.'generic_data/'); +//define('Param', DATAPATH.'Param/'); +define('LocalData', DATAPATH.'LocalData/'); define('RemoteData', DATAPATH.'RemoteData/'); define('Functions', DATAPATH.'Functions/'); -define('Plot', DATAPATH.'Plot/'); +//define('Plot', DATAPATH.'Plot/'); define('Hst', DATAPATH.'Hst/'); -define('GeneralInfo', DATAPATH.'Info/'); define('SpecialSettingsDir',DATAPATH.'SpecialSettings/'); -// General Info files; new AMDA -define('paramListXml',Param.'LocalParamsList.xml'); -define('paramXml',Param.'LocalParams.xml'); -define('orbitesXml',Param.'Orbites.xml'); -define('spectraXml',Param.'SpectraParamList.xml'); -define('targetsXml',LocalData.'targets.xml'); - -define('missionXml',LocalData.'Missions.xml'); -define('internalParams', LocalData.'DD_InternalParams.xml'); +// General Info files +define('orbitsXml',LocalData.'Orbites.xml'); +// define('targetsXml',LocalData.'targets.xml'); define('FeedbackXml', DATAPATH.'Feedback/Feedback.xml'); -define('TEMPLATES',BASE_PATH.'amda_plus/templates/'); -define('PREDEFINED',BASE_PATH.'amda_plus/predefined/'); -define('PRO',BASE_PATH.'amda_plus/pro/'); define('specialGrpsXml',SpecialSettingsDir.'Groups.xml'); +define('specialSettingsXml',SpecialSettingsDir.'Settings.xml'); //Help info dirs -define('HELPPATH', BASE_PATH."help/"); -define('targetsSimu',HELPPATH.'simu/TargetsSimu.xml'); +define('HELPPATH', IHM_SRC_DIR."help/"); -//Root User dir : new AMDA -// All user dirs are defined in UserMgr.php -define('USERPATH', BASE_PATH.'data/'); +// IMPEX special files +define('SimuTargetsXml', DATAPATH.'SimuTemplate/TargetsSimu.xml'); -// Shared dir -define('SHAREDPATH', BASE_PATH.'shared_data/'); +// Root User dir : All user dirs are defined in UserMgr.php +define('USERPATH', IHM_SRC_DIR.'data/'); -// Web Services result directory -define('WSRESULT', USERPATH.'WSRESULT/'); +// Shared dir +define('SHAREDPATH', IHM_SRC_DIR.'shared_data/'); -// Web Service result file -define('wsResultsXml',WSRESULT.'WSresults.xml'); +/*------------------- WEB SERVICES section ---------*/ +define('WSRESULT', USERPATH.'WSRESULT/'); // Web Services result directory +define('wsResultsXml',WSRESULT.'WSresults.xml'); // Web Service result file -// Web Service getPlot : list of parameters to plot -define('plotsXml', BASE_PATH.'public/WebServices/XML/AmdaPlots.xml'); -// Web Service serveurs WSDL +define('plotsXml', IHM_SRC_DIR.'public/WebServices/XML/AmdaPlots.xml'); // Web Service getPlot : list of parameters to plot -// $_SERVER['SERVER_NAME'] (par apache) gethostname() (par command) +// Web Service servers WSDL : $_SERVER['SERVER_NAME'] (par apache) gethostname() (par command) $SERVER_NAME = $_SERVER['SERVER_NAME'] ? $_SERVER['SERVER_NAME'] : gethostname(); define('wsdl_AMDA', "http://".$SERVER_NAME.APACHE_ALIAS."public/wsdl/Methods_AMDA.wsdl"); - +/*-------------------END WEB SERVICES section ---------*/ + // AKKA - KERNELBIN is now the new kernel bin dir define('KERNELBIN',NEWKERNEL_INSTALL_DIR.'bin/'); putenv("LD_LIBRARY_PATH=".SYS_LIBS.":".DDLIB.":".CEFLIB.":".CDFLIB); -putenv("PATH=./:".DDBIN.":".SYS_BIN.":".BASE_PATH."php/bin"); +putenv("PATH=./:".DDBIN.":".SYS_BIN.":".IHM_SRC_DIR."php/bin"); putenv("DDPATH=".DDRES_DIR); - + +// PHP classes +define('XMLPATH', IHM_SRC_DIR.'php/XML/'); +define('CLASSPATH', IHM_SRC_DIR.'php/classes/'); +define('OLD_CLASSPATH', IHM_SRC_DIR.'php/old_amda/'); + set_include_path(".:".CLASSPATH.":".OLD_CLASSPATH); -global $API; - -if (!function_exists('__autoload')) { - function __autoload($class_name) { - require_once $class_name . '.php'; - } +if (!function_exists('__autoload')) +{ + function __autoload($class_name) { + require_once $class_name . '.php'; + } } - +global $API; $API = array( - 'AmdaAction'=>array( - 'methods'=>array( - 'getTree'=>array( - 'len'=>1 - ), - 'saveTree'=>array( - 'len'=>1 - ), - 'getInfo'=>array( - 'len'=>1 - ), - 'doNothing'=>array( - 'len'=>1 - ), - 'deleteFromTree'=>array( - 'len'=>1 - ), - 'getObject'=>array( - 'len'=>2 - ), - 'getAsciiFile'=>array( - 'len'=>1 - ), - 'getTmpObject'=>array( - 'len'=>3 - ), - 'getUploadedObject'=>array( - 'len'=>3 - ), - 'getMyParamInfo'=>array( - 'len'=>1 - ), - 'deleteObject'=>array( - 'len'=>1 - ), - 'renameObject'=>array( - 'len'=>1 - ), - 'createObject'=>array( - 'len'=>2 - ), - 'modifyObject'=>array( - 'len'=>1 - ), - 'validNameObject'=>array( - 'len'=>1 - ), - 'getJobs'=>array( - 'len'=>0 - ), - 'execute'=>array( - 'len'=>2 - // 'formHandler'=>true - ), - 'compilParam' => array( - 'len'=>1 - ), - 'compilParamDelete' => array( - 'len'=>1 - ), - 'killPlotRequest' =>array( - 'len'=>0 - ), - 'merge'=>array( - 'len'=>1 - ), - 'intersect'=>array( - 'len'=>1 - ), - 'loadTTIntervals'=>array( - 'len'=>1 - ), - 'saveTTCacheIntervalsInTT'=>array( - 'len'=>1 - ), - 'initTTCache' => array ( - 'len'=>2 - ) , - 'initTTCacheFromTT' => array( - 'len'=>2 - ), - 'initForChart' => array( - 'len'=>4 - ), - 'initTTCacheFromTmpObject' => array( - 'len'=>3 - ), - 'initTTCacheFromUploadedFile' => array( - 'len'=>2 - ), - 'readTTCacheIntervals'=>array( - 'len'=>1 - ), - 'readIntervalsForChart'=>array( - 'len'=>1 - ), - 'addTTCacheInterval'=>array ( - 'len'=>1 - ), - 'removeTTCacheIntervalFromId'=>array ( - 'len'=>2 - ), - 'modifyTTCacheInterval' => array( - 'len'=>1 - ), - 'operationTTCacheIntervals' => array( - 'len'=>2 - ), - 'mergeTTCacheIntervals' => array ( - 'len'=>0 - ), - 'getTTCacheStatistics' => array ( - 'len'=>0 - ), - 'sendFeedback'=>array( - 'len'=>1 - ), - 'saveState'=>array( - 'len'=>1 - ), - 'loadState'=>array( - 'len'=>1 - ), - 'sendToSAMP'=>array( - 'len'=>1 - ), - 'getHstImagesUrl'=>array( - 'len'=>1 - ), - 'getAPISImagesUrl'=>array( - 'len'=>1 - ), - 'loadFilterList'=>array( - 'len'=>0 - ), - 'loadFilters'=>array( - 'len'=>1 - ), - 'saveFilter'=>array( - 'len'=>1 - ), - 'createFilter'=>array( - 'len'=>1 - ), - 'destroyFilter'=>array( - 'len'=>1 - ), - 'getCrtFilterId'=>array( - 'len'=>0 - ), - 'getCrtFilterResult'=>array( - 'len'=>0 - ), - 'setCrtFilterId'=>array( - 'len'=>1 - ), - 'resetFilter'=>array( - 'len'=>0 - ), - 'logout'=>array( - 'len'=>1 - ), - 'getUserInfo'=>array( - 'len'=>0 - ), - 'convertWS'=>array( - 'len'=>0 - ), - 'getRun'=>array( - 'len'=>1 - ), - 'addRun'=>array( - 'len'=>1 - ), - //AKKA - New action to clean user WS - 'cleanUserWS'=>array( - 'len'=>0 - ), - 'deleteSpecialInfo'=>array( - 'len'=>1 - ), - 'interactivePlot'=>array( - 'len'=>2 - ), - 'getParamPlotInit'=>array( - 'len'=>1 - ), - 'getParamInfo'=>array( - 'len'=>1 - ), - 'getSharedObjectFolders' => array( - 'len'=>1 - ), - 'shareObjects' => array( - 'len'=>1 - ), - 'isSharedObjectNameAlreadyUsed' => array( - 'len'=>1 - ) - ) - ) + 'AmdaAction'=>array( + 'methods'=>array( + 'getTree'=>array('len'=>1), + 'saveTree'=>array('len'=>1), + 'getInfo'=>array('len'=>1), + 'doNothing'=>array('len'=>1), + 'deleteFromTree'=>array('len'=>1), + 'getObject'=>array('len'=>2), + 'getAsciiFile'=>array('len'=>1), + 'getTmpObject'=>array('len'=>3), + 'getUploadedObject'=>array('len'=>3), + 'getMyParamInfo'=>array('len'=>1), + 'deleteObject'=>array('len'=>1), + 'renameObject'=>array('len'=>1), + 'createObject'=>array('len'=>2), + 'modifyObject'=>array('len'=>1), + 'validNameObject'=>array('len'=>1), + 'getJobs'=>array('len'=>0), + 'execute'=>array('len'=>2), + //'formHandler'=>true + 'compilParam'=>array('len'=>1), + 'compilParamDelete'=>array('len'=>1), + 'killPlotRequest'=>array('len'=>0), + 'merge'=>array('len'=>1), + 'intersect'=>array('len'=>1), + 'loadTTIntervals'=>array('len'=>1), + 'saveTTCacheIntervalsInTT'=>array('len'=>1), + 'initTTCache'=>array ('len'=>2), + 'initTTCacheFromTT'=>array('len'=>2), + 'initForChart'=>array('len'=>4), + 'initTTCacheFromTmpObject'=>array('len'=>3), + 'initTTCacheFromUploadedFile'=>array('len'=>2), + 'readTTCacheIntervals'=>array('len'=>1), + 'readIntervalsForChart'=>array('len'=>1), + 'addTTCacheInterval'=>array('len'=>1), + 'removeTTCacheIntervalFromId'=>array('len'=>2), + 'modifyTTCacheInterval'=>array('len'=>1), + 'operationTTCacheIntervals'=>array('len'=>2), + 'mergeTTCacheIntervals'=>array('len'=>0), + 'getTTCacheStatistics'=>array('len'=>0), + 'sendFeedback'=>array('len'=>1), + 'saveState'=>array('len'=>1), + 'loadState'=>array('len'=>1), + 'sendToSAMP'=>array('len'=>1), + 'getHstImagesUrl'=>array('len'=>1), + 'getAPISImagesUrl'=>array('len'=>1), + 'loadFilterList'=>array('len'=>0), + 'loadFilters'=>array('len'=>1), + 'saveFilter'=>array('len'=>1), + 'createFilter'=>array('len'=>1), + 'destroyFilter'=>array('len'=>1), + 'getCrtFilterId'=>array('len'=>0), + 'getCrtFilterResult'=>array('len'=>0), + 'setCrtFilterId'=>array('len'=>1), + 'resetFilter'=>array('len'=>0), + 'logout'=>array('len'=>1), + 'getUserInfo'=>array('len'=>0), + 'convertWS'=>array('len'=>0), + 'getRun'=>array('len'=>1), + 'addRun'=>array('len'=>1), + //AKKA - New action to clean user WS + 'cleanUserWS'=>array('len'=>0), + 'deleteSpecialInfo'=>array('len'=>1), + 'interactivePlot'=>array('len'=>2), + 'getParamPlotInit'=>array('len'=>1), + 'getParamInfo'=>array('len'=>1), + 'getSharedObjectFolders' => array('len'=>1), + 'shareObjects' => array('len'=>1), + 'isSharedObjectNameAlreadyUsed' => array('len'=>1) + ) + ) ); ?> -- libgit2 0.21.2