From b8502f4dbc59fce649d8f6b09e9b5ad79172b28b Mon Sep 17 00:00:00 2001
From: Elena.Budnik <ebudnik@irap.omp.eu>
Date: Wed, 28 Feb 2018 19:25:06 +0100
Subject: [PATCH] getStatus(), throwError(), clean up code

---
 php/AMDA_METHODS_WSDL.php |   17 +++++++----------
 php/classes/WSUserMgr.php |   28 ++++++++++++++--------------
 php/classes/WebServer.php | 1970 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 3 files changed, 990 insertions(+), 1025 deletions(-)

diff --git a/php/AMDA_METHODS_WSDL.php b/php/AMDA_METHODS_WSDL.php
index 9393d09..72746c4 100644
--- a/php/AMDA_METHODS_WSDL.php
+++ b/php/AMDA_METHODS_WSDL.php
@@ -2,17 +2,14 @@
 
 /** 
 *   @file AMDA_METHODS_WSDL.php
-*   @brief PHP SoapServer for IMPEx WebServices
-*
-*   @version  $Id: $
-*   
+*   @brief PHP SoapServer for IMPEx WebServices  
 */
  
-  require_once 'config.php';
-
-  ini_set("soap.wsdl_cache_enabled", "0"); // desactive le cache WSDL
-  $server = new SoapServer('../public/wsdl/Methods_AMDA.wsdl');  
-  $server->setClass('WebServer');
-  $server->handle();
+	require_once 'config.php';
 
+	ini_set("soap.wsdl_cache_enabled", "0"); // desactive le cache WSDL
+	$server = new SoapServer('../public/wsdl/Methods_AMDA.wsdl');  
+	$server->setClass('WebServer');
+	$server->handle();
+  
 ?>
\ No newline at end of file
diff --git a/php/classes/WSUserMgr.php b/php/classes/WSUserMgr.php
index 7856596..3fc40bd 100644
--- a/php/classes/WSUserMgr.php
+++ b/php/classes/WSUserMgr.php
@@ -8,7 +8,15 @@
 class WSUserMgr extends UserMgr 
 {
 	protected $isSoap;
-
+	
+	private function throwError($errorType, $msg)
+	{
+		if ($this->isSoap) 
+			throw new SoapFault($errorType, $msg); 
+		else 
+			return array("error" => $msg);
+	}
+	
 	/*****************************************************************
 	 *                           PUBLIC FUNCTIONS
 	 *****************************************************************/
@@ -25,14 +33,11 @@ class WSUserMgr extends UserMgr
 		if ($this->ddCheckUser() != 0) 
 		{
 			if ($this->ddLogin() != 0) { // DD Login if user is not registered
-				if ($this->isSoap) throw new SoapFault("error", "Login procedure failed");
-				else return array("error" => "Login procedure failed");
+				$this->throwError("loginError", "Login procedure failed");
 			}
 
-			if ($this->ddCheckUser() != 0) 
-			{
-				if ($this->isSoap) throw new SoapFault("error", "CheckUser procedure failed");
-				else return array("error" => "CheckUser procedure failed");
+			if ($this->ddCheckUser() != 0) {
+				$this->throwError("loginError", "CheckUser procedure failed");
 			}
 		}
 		
@@ -41,8 +46,7 @@ class WSUserMgr extends UserMgr
 		if (!is_dir($this->userdir)) 
 		{
 			if (!$this->createDir()) {
-				if ($this->isSoap) throw new SoapFault("error", "Cannot create UserDir");
-				else return array("error" => "Cannot create UserDir"); 
+				$this->throwError("loginError", "Cannot create UserDir"); 
 			}
 		}
 		
@@ -57,11 +61,7 @@ class WSUserMgr extends UserMgr
 
 	public function makeUserWS() 
 	{
-		 if (file_exists(USERWSDIR.'LocalParams.xml'))
-			unlink(USERWSDIR.'LocalParams.xml');      
-		// if (!file_exists(USERWSDIR.'LocalParams.xml'))
-		symlink(DATAPATH.'/LocalData/LocalParams.xml', USERWSDIR.'LocalParams.xml');
-		// $this->makeLocalTree();
+		$this->makeLocalTree();
 		$this->makeRemoteTree();
 
 		return $this->user;
diff --git a/php/classes/WebServer.php b/php/classes/WebServer.php
index 105b403..145e61e 100644
--- a/php/classes/WebServer.php
+++ b/php/classes/WebServer.php
@@ -1,898 +1,864 @@
 <?php
-/**
- * @file WebServer.php
- * @brief  Web services AMDA
- *
- * @version $Id: WebServer.php 2968 2015-06-29 13:17:00Z natacha $
- */
-
+/** 
+*   @file WebServer.php
+*   @brief  Web services AMDA
+*/
 class WebResultMgr
 {
-    private $resDOM;
-    private $rootEl;
-    private $resXP;
-    private $requestManager = null;
-    private $paramLoader = null;
-
-    function __construct()
-    {
-        if (!is_dir(WSRESULT))
-            mkdir(WSRESULT);
-        chmod(WSRESULT, 0775);
-
-        $this->resDOM = new DOMDocument("1.0");
-        $this->resDOM->formatOutput = TRUE;
-        $this->resDOM->preserveWhiteSpace = FALSE;
-
-        if (!file_exists(wsResultsXml)) {
-            $this->rootEl = $this->resDOM->createElement('wsresults');
-            $this->resDOM->appendChild($this->rootEl);
-            $this->resDOM->save(wsResultsXml);
-        }
-
-        $this->resDOM->load(wsResultsXml);
-
-        $this->resXP = new DOMXPath($this->resDOM);
-
-        $this->rootEl = $this->resDOM->documentElement;
-    }
-
-    public function addResult($function_name, $vars, $user, $IP, $output)
-    {
-        $nodes = $this->rootEl->getElementsByTagName($function_name);
-        if ($nodes->length < 1) {
-            $funcNode = $this->resDOM->createElement($function_name);
-            $this->rootEl->appendChild($funcNode);
-        } else
-            $funcNode = $nodes->item(0);
-
-        $oldOutput = $this->resXP->query('//' . $function_name . '/result[@output="' . $output . '"]');
-        if ($oldOutput->length > 0)
-            $funcNode->removeChild($oldOutput->item(0));
-
-        $resNode = $this->resDOM->createElement('result');
-        $resNode->setAttribute('date', time());
-        $resNode->setAttribute('user', $user);
-//    $resNode->setAttribute('IP',$IP);
-        $resNode->setAttribute('input', json_encode($vars));
-        $resNode->setAttribute('output', $output);
-        $funcNode->appendChild($resNode);
-
-        $this->resDOM->save(wsResultsXml);
-
-        return $resNode;
-    }
-
-    public function getResOutputName($function_name, $user, $suffixe, $extension)
-    {
-        $outputFile = WSRESULT . $function_name . "_" . $user;
-        if (isset($suffixe))
-            $outputFile .= ("_" . $suffixe);
-        if (isset($extension))
-            $outputFile .= ("." . $extension);
-        else
-            $outputFile .= ".xml";
-        return $outputFile;
-    }
+	private $resDOM;
+	private $rootEl;
+	private $resXP;
+	private $requestManager = null;
+	private $paramLoader = null;
+
+	function __construct()
+	{
+		if (!is_dir(WSRESULT))
+		mkdir(WSRESULT);
+		
+		chmod(WSRESULT,0775);
+
+		$this->resDOM = new DOMDocument("1.0");
+		$this->resDOM->formatOutput = TRUE;
+		$this->resDOM->preserveWhiteSpace = FALSE;
+		
+		if (!file_exists(wsResultsXml))
+		{
+		$this->rootEl = $this->resDOM->createElement('wsresults');
+		$this->resDOM->appendChild($this->rootEl);
+		$this->resDOM->save(wsResultsXml);
+		}
+		
+		$this->resDOM->load(wsResultsXml);
+		
+		$this->resXP = new DOMXPath($this->resDOM);
+		
+		$this->rootEl = $this->resDOM->documentElement;
+	}
+  
+	public function addResult($function_name,$vars,$user,$IP,$output)
+	{
+		$nodes = $this->rootEl->getElementsByTagName($function_name);
+		if($nodes->length < 1){
+			$funcNode = $this->resDOM->createElement($function_name);
+			$this->rootEl->appendChild($funcNode);	 
+		}
+		else
+			$funcNode = $nodes->item(0);
+			
+		$oldOutput = $this->resXP->query('//'.$function_name.'/result[@output="'.$output.'"]');
+		if ($oldOutput->length > 0)
+		$funcNode->removeChild($oldOutput->item(0));
+			
+		$resNode = $this->resDOM->createElement('result');
+		$resNode->setAttribute('date',time());
+		$resNode->setAttribute('user',$user);
+	//    $resNode->setAttribute('IP',$IP);
+		$resNode->setAttribute('input',json_encode($vars));
+		$resNode->setAttribute('output',$output);
+		$funcNode->appendChild($resNode);
+		
+		$this->resDOM->save(wsResultsXml);
+		
+		return $resNode;
+	}
+	
+	public function getResOutputName($function_name,$user,$suffixe,$extension)
+	{
+		$outputFile = WSRESULT.$function_name."_".$user;
+		if (isset($suffixe))
+			$outputFile .= ("_".$suffixe);
+		if (isset($extension))
+			$outputFile .= (".".$extension);
+		else
+			$outputFile .= ".xml";
+		return $outputFile;
+	}
 }
 
 class WebServer
 {
-    private $isSoap = false;
-    private $userID, $userPWD, $sessionID;
-    private $wsUserMgr;
-    private $resultMgr, $myParamsInfoMgr;
-    private $dataFileName;
-
-    function __construct()
-    {
-        $this->userID = 'impex';
-        $this->userPWD = 'impexfp7';
-        $this->sessionID = $this->userID;
-        $this->myParamsInfoMgr = new ParamsInfoMgr();
-        $this->resultMgr = new WebResultMgr();
-    }
-
-    protected function init($data)
-    {
-        if (is_object($data)) {
-            $vars = get_object_vars($data);
-            $this->isSoap = true;
-        } else
-            $vars = $data;
-
-        if (isset($vars['userID'])) {
-            $this->userID = $vars['userID'];
-            $this->sessionID = $this->userID;
-        } else {
-            $this->userID = 'impex';
-            $this->sessionID = $this->userID;
-        }
-        if (isset($vars['password']))
-            $this->userPWD = $vars['password'];
-        else
-            $this->userPWD = 'impexfp7';
-
-        return array('success' => true, 'vars' => $vars);
-    }
-
-    private function setID()
-    {
-
-        $nb_min = 10000;
-        $nb_max = 99999;
-        $nombre = mt_rand($nb_min, $nb_max);
-
-        $this->IP = $this->getIPclient();
-
-        return "PP" . $nombre;
-    }
-
-    /**
-     *  Function getIPclient return the IP client sent a request for needs DD scripts (DDHtmlLogin, DDCheckUser, DD_Search)
-     *
-     * @param   void
-     * @return  string
-     */
-    private function getIPclient()
-    {
-
-        if (getenv('REMOTE_ADDR')) {
-            $realIP = getenv('REMOTE_ADDR');
-        } else {
-            //get local IP
-            $command = "hostname -i";
-            $realIP = exec($command);
-        }
-
-        return $realIP;
-    }
-
-    private function timeInterval2Days($TimeInterval)
-    {
-
-        $divDays = 60 * 60 * 24;
-        $nbDays = floor($TimeInterval / $divDays);
-        $divHours = 60 * 60;
-        $nbHours = floor(($TimeInterval - $divDays * $nbDays) / $divHours);
-        $nbMin = floor(($TimeInterval - $divDays * $nbDays - $divHours * $nbHours) / 60);
-        $nbSec = $TimeInterval - $divDays * $nbDays - $divHours * $nbHours - $nbMin * 60;
-
-        $DD = sprintf("%03d", $nbDays);                       // format ex. 005 not 5
-        $HH = sprintf("%02d", $nbHours);                      // format ex. 25
-        $MM = sprintf("%02d", $nbMin);                        // format ex. 03 not 3
-        $SS = sprintf("%02d", $nbSec);                        // format ex. 02 not 2
-
-        return $DD . ':' . $HH . ':' . $MM . ':' . $SS;
-
-    }
-
-    /* Start Time into AMDA format YYYY:DOY-1:HH:MM:SS */
-    private function startTime2Days($startTime)
-    {
-
-        $ddStart = getdate($startTime);
-        $date_start = sprintf("%04d", $ddStart["year"]) . ":" . sprintf("%03d", $ddStart["yday"]) . ":"
-                . sprintf("%02d", $ddStart["hours"]) . ":" . sprintf("%02d", $ddStart["minutes"]) . ":"
-                . sprintf("%02d", $ddStart["seconds"]);
-        return $date_start;
-    }
-
-    private function rrmdir($dir)
-    {
-        if (is_dir($dir)) {
-            $objects = scandir($dir);
-
-            foreach ($objects as $object) { // Recursively delete a directory that is not empty and directorys in directory
-                if ($object != "." && $object != "..") {  // If object isn't a directory recall recursively this function
-                    if (filetype($dir . "/" . $object) == "dir")
-                        $this->rrmdir($dir . "/" . $object);
-                    else
-                        unlink($dir . "/" . $object);
-                }
-            }
-            reset($objects);
-            rmdir($dir);
-        }
-    }
-
-    protected function initUserMgr()
-    {
-        if (isset($this->wsUserMgr)) {
-            return array('success' => true);
-        }
-        $this->wsUserMgr = new WSUserMgr($this->userID, $this->userPWD, $this->sessionID);
-        $this->wsUserMgr->init($this->userID, $this->userPWD, $this->sessionID, $this->isSoap);
-
-        return array('success' => true);
-    }
-
-    public function getTimeTablesList($data)
-    {
-        if (is_object($data)) {
-            $vars = get_object_vars($data);
-            $this->isSoap = true;
-        } else
-            $vars = $data;
-        if (isset($vars['userID']) && $vars['userID'] == 'impex') {
-            if ($this->isSoap) throw new SoapFault("server00", "Server Error: AMDA Login procedure failed");
-            else return array("error" => "Server Error: AMDA Login procedure failed");
-        }
-
-
-        $res = $this->init($data);
-        $vars = $res['vars'];
-
-        $ttListWSresult = $this->resultMgr->getResOutputName(__FUNCTION__, $this->userID);
-
-        $dom = new DOMDocument("1.0");
-        if ($this->userID == 'impex') {
-            $sharedObjMgr = new SharedObjectsMgr();
-            $loadDom = $dom->load($sharedObjMgr->getTreeFilePath());
-        } else
-            $loadDom = $dom->load(USERPATH . $this->userID . '/WS/Tt.xml');
-
-        if ($loadDom == FALSE) {
-            if ($this->isSoap) throw new SoapFault("server00", "Server Error: AMDA Login procedure failed");
-            else return array("error" => "Server Error: AMDA Login procedure failed");
-        }
-
-        $timetabNode = $dom->documentElement->getElementsByTagName('timetabList');
-
-        if ($timetabNode->length < 1) {
-            if ($this->isSoap) throw new SoapFault("server03", "Cannot reach TT list");
-            else return array('success' => false, 'message' => "Server Error: Cannot reach TT list");
-        }
-        $outDOM = new DOMDocument("1.0");
-        $outDOM->formatOutput = TRUE;
-        $outDOM->preserveWhiteSpace = FALSE;
-
-        $newNode = $outDOM->importNode($timetabNode->item(0), TRUE);
-        $outDOM->appendChild($newNode);
-
-
-        $outXP = new domxpath($outDOM);
-        $ttNodes = $outXP->query('//timetab');
-
-        $outDOM->save($ttListWSresult);
+	private $isSoap = false;
+	private $userID, $userPWD, $sessionID;
+	private $wsUserMgr;
+	private $resultMgr, $myParamsInfoMgr;
+	private $dataFileName;
 
-        $wsres = $this->resultMgr->addResult(__FUNCTION__, $vars, $this->userID, $ttListWSresult);
-
-        $ttListResult = 'http://' . str_replace(BASE_PATH, $_SERVER['SERVER_NAME'] . APACHE_ALIAS, $ttListWSresult);
-
-        $timeTablesList = array('success' => true, 'TimeTablesList' => $ttListResult);
-
-        return $timeTablesList;
-
-    }
-
-    public function getTimeTable($data)
-    {
-        $res = $this->init($data);
-
-        $vars = $res['vars'];
-        $ttID = $vars['ttID'];
-
-        if ($this->userID == 'impex') {
-            $sharedObjMgr = new SharedObjectsMgr();
-            $ttSrc = $sharedObjMgr->getDataFilePath('timeTable', $ttID);
-        } else
-            $ttSrc = USERPATH . $this->userID . '/TT/' . $ttID . '.xml';
-
-        if (!file_exists($ttSrc)) {
-            if ($this->isSoap) throw new SoapFault("server03", "Cannot reach time table");
-            else return array('success' => false, 'message' => "Cannot reach time table");
-        }
-
-        $ttWSresult = $this->resultMgr->getResOutputName(__FUNCTION__, $this->userID, $ttID);
-
-        if (!copy($ttSrc, $ttWSresult)) {
-            if ($this->isSoap) throw new SoapFault("server04", "Cannot copy time table");
-            else return array('success' => false, 'message' => "Cannot copy time table");
-        }
-
-        $wsres = $this->resultMgr->addResult(__FUNCTION__, $vars, $this->userID, $ttWSresult);
+	function __construct() 
+	{
+		$this->userID  = 'impex';
+		$this->userPWD = 'impexfp7';
+		$this->sessionID = $this->userID;
+//		$this->myParamsInfoMgr =  new ParamsInfoMgr();
+		$this->resultMgr = new WebResultMgr();
+	}
+	
+//     [startTime] => 2016-01-14T00:00:00
+//     [stopTime] => 2017-02-15T00:00:00
+//     [parameterID] => imf
+//     [userID] => budnik
+//     [password] => Sacre-Cour
+//     [outputFormat] => ASCII
+//     [timeFormat] => ISO8601
+//     [gzip] => 0
+
+	protected function init($data) 
+	{
+		if(is_object($data)){
+			$vars = get_object_vars($data);
+			$this->isSoap = true; 
+		}
+		else {
+			$vars = $data;
+		}
 
-        $myTimeTableMgr = new TimeTableMgr($this->userID);
-        $ttWSresultVot = $myTimeTableMgr->xsl2vot($ttWSresult);
-        if (file_exists($ttWSresultVot)) {
-            copy($ttWSresultVot, $ttWSresult);
-            unlink($ttWSresultVot);
-        }
-        return array('success' => true, 'ttFileURL' => 'http://' . str_replace(BASE_PATH, $_SERVER['SERVER_NAME'] . APACHE_ALIAS, $ttWSresult));
+		if (isset($vars['userID'])){
+			$this->userID  = $vars['userID'];
+		}
+		else {
+			$this->userID  = 'impex';
+		}
+		
+		$this->sessionID = $this->userID;
+		
+		if (isset($vars['password']))
+			$this->userPWD = $vars['password'];
+		else 
+			$this->userPWD = 'impexfp7';
+			
+		return array('success' => true, 'vars' => $vars);
+	}
+	
+	private function throwError($errorType, $msg)
+	{
+		if ($this->isSoap) 
+			throw new SoapFault($errorType, $msg); 
+		else 
+			return array("error" => $msg);
+	}
+	
+	private function setID()
+	{
+		$nb_min = 10000;
+		$nb_max = 99999;
 
-    }
+		$this->IP = $this->getIPclient();
 
+		return "PP".mt_rand($nb_min,$nb_max);
+	}
 
-    public function isAlive()
-    {
-        $res = $this->init($data);
-        return true;
-    }
+/**
+ *  Function getIPclient return the IP client sent a request for needs DD scripts (DDHtmlLogin, DDCheckUser, DD_Search)
+ *
+ *       @param   void
+ *       @return  string  
+ */
+	private  function getIPclient()
+	{
+		if (getenv('REMOTE_ADDR'))  {
+			$realIP = getenv('REMOTE_ADDR');
+		}
+		else {
+			//get local IP
+			$command="hostname -i";
+			$realIP = exec($command);
+		}
 
+		return $realIP;
+	}
 
-    public function getObsDataTree()
-    {
+	private function timeInterval2Days($TimeInterval)
+	{
+		$divDays = 60*60*24;
+		$nbDays = floor($TimeInterval / $divDays);
+		$divHours = 60*60;
+		$nbHours = floor(($TimeInterval - $divDays*$nbDays)/$divHours);
+		$nbMin = floor(($TimeInterval - $divDays*$nbDays - $divHours*$nbHours)/60);
+		$nbSec = $TimeInterval - $divDays*$nbDays - $divHours*$nbHours - $nbMin*60;
+
+		$DD = sprintf("%03d",   $nbDays);                       // format ex. 005 not 5
+		$HH = sprintf("%02d",   $nbHours);                      // format ex. 25 
+		$MM = sprintf("%02d",   $nbMin);                        // format ex. 03 not 3
+		$SS = sprintf("%02d",   $nbSec);                        // format ex. 02 not 2
+
+		return  $DD.':'.$HH.':'.$MM.':'.$SS;
+	}
 
-        $res = $this->init();
+	/* Start Time into AMDA format YYYY:DOY-1:HH:MM:SS */
+	private function startTime2Days($startTime)
+	{
+		$ddStart = getdate($startTime);
+		$date_start = sprintf("%04d",$ddStart["year"]).":".sprintf("%03d", $ddStart["yday"]).":"
+											.sprintf("%02d",$ddStart["hours"]).":".sprintf("%02d",$ddStart["minutes"]).":"
+											.sprintf("%02d",$ddStart["seconds"]);
+		return $date_start;
+	}
 
-        $resMgr = $this->initUserMgr();
+	private function rrmdir($dir)
+	{
+		if (is_dir($dir)) {
+			$objects = scandir($dir);
+
+			foreach ($objects as $object) { // Recursively delete a directory that is not empty and directorys in directory 
+				if ($object != "." && $object != "..") {  // If object isn't a directory recall recursively this function 
+					if (filetype($dir."/".$object) == "dir")
+						$this->rrmdir($dir."/".$object);
+					else
+						unlink($dir."/".$object);
+				}
+			}
+			reset($objects);
+			rmdir($dir);
+		}
+	}
 
-        $vars = $res['vars'];
+	protected function initUserMgr() 
+	{
+		if (isset($this->wsUserMgr))
+			return array('success' => true);
+			
+		$this->wsUserMgr = new WSUserMgr();
+		$this->wsUserMgr->init($this->userID, $this->userPWD, $this->sessionID, $this->isSoap);
+		
+		return array('success' => true);
+	}
 
-        $locParamSrc = USERPATH . $this->userID . '/WS/LocalParams.xml';
-//     $remoteParamSrc = USERPATH.$this->userID.'/WS/RemoteParams.xml';
-        $wsParamSrc = USERPATH . $this->userID . '/WS/WsParams.xml';
-        $locParamResult = $this->resultMgr->getResOutputName(__FUNCTION__, $this->userID . '_' . 'LocalParams');
-//     $remoteParamResult = $this->resultMgr->getResOutputName(__FUNCTION__,'RemoteParams');
-        $wsParamResult = $this->resultMgr->getResOutputName(__FUNCTION__, $this->userID . '_' . 'WsParams');
+	public function getTimeTablesList($data) 
+	{
+		if(is_object($data))
+		{
+			$vars = get_object_vars($data);
+			$this->isSoap = true; 
+		}
+		else
+			$vars = $data;
+			
+		if (isset($vars['userID']) && $vars['userID'] == 'impex'){
+			$this->throwError('requestError', "Request Error: no time tables for anonymous");
+		}
+          
+		$res = $this->init($data);
+		$vars = $res['vars'];
+
+		$ttListWSresult = $this->resultMgr->getResOutputName(__FUNCTION__,$this->userID);
+    
+		$dom = new DOMDocument("1.0");
+		if ($this->userID == 'impex') {
+			$sharedObjMgr = new SharedObjectsMgr();
+			if (!@$dom->load($sharedObjMgr->getTreeFilePath()))
+					$this->throwError("workspaceError", "Workspace Error : Cannot load Shared Time Table list");
+		}
+		else {
+				if (!@$dom->load(USERPATH.$this->userID.'/WS/Tt.xml'))
+					$this->throwError("workspaceError", "Workspace Error : Cannot load Shared Time Table list for ".$this->userID);
+		}
+    
+		$timetabNode = $dom->getElementsByTagName('timetabList');
 
-        if (!copy($locParamSrc, $locParamResult))
-            $locParamResult = '';
-        else {
-            $piBase = new DomDocument("1.0");
-            $piBase->formatOutput = true;
-            $piBase->preserveWhiteSpace = false;
+		if ($timetabNode->length < 1){
+				$this->throwError("workspaceWarning", "Workspace Warning : No Time Tables");
+		}
+		
+		$outDOM = new DOMDocument("1.0");
+		$outDOM->formatOutput = TRUE;
+		$outDOM->preserveWhiteSpace = FALSE;
+    
+		$newNode = $outDOM->importNode($timetabNode->item(0),TRUE);
+		$outDOM->appendChild($newNode);
+    
+// 		$outXP = new domxpath($outDOM);
+// 		$ttNodes = $outXP->query('//timetab');
 
-            $dom = new DomDocument("1.0");
-            $dom->load($locParamResult);
+		$outDOM->save($ttListWSresult);
 
-            $xsl = new DomDocument("1.0");
-            $xsl->load(XMLPATH . 'dd2WStree.xsl');
+		$wsres = $this->resultMgr->addResult(__FUNCTION__,$vars,$this->userID,$ttListWSresult);
 
-            $xslt = new XSLTProcessor();
-            $xslt->importStylesheet($xsl);
+		$ttListResult = 'http://'.str_replace(BASE_PATH,$_SERVER['SERVER_NAME'].APACHE_ALIAS,$ttListWSresult);
 
-            $dom->loadXML($xslt->transformToXML($dom));
+		$timeTablesList = array('success' => true, 'TimeTablesList' => $ttListResult);
 
-            $dom->formatOutput = true;
-            $dom->preserveWhiteSpace = false;
-            $chum_ger = $dom->getElementById("Rosetta@C-G : Plot Only!");
-            if ($chum_ger != NULL) $chum_ger->setAttribute("target", "Churyumov-Gerasimenko");
+		return $timeTablesList;
+	}
 
-            $dom->save($locParamResult);
-        }
-//     if (!copy($remoteParamSrc,$remoteParamResult))
-// 	$remoteParamResult = '';
-        if (!copy($wsParamSrc, $wsParamResult))
-            $wsParamResult = '';
+	public function getTimeTable($data) 
+	{
+		$res = $this->init($data);
 
-        if ($locParamResult != '') $locParamResult = 'http://' . str_replace(BASE_PATH, $_SERVER['SERVER_NAME'] . APACHE_ALIAS, $locParamResult);
-//     if ($remoteParamResult !='') $remoteParamResult = 'http://'.str_replace(BASE_PATH,$_SERVER['SERVER_NAME'].APACHE_ALIAS,$remoteParamResult);
-        if ($wsParamResult != '') $wsParamResult = 'http://' . str_replace(BASE_PATH, $_SERVER['SERVER_NAME'] . APACHE_ALIAS, $wsParamResult);
+		$vars = $res['vars'];
+		$ttID = $vars['ttID'];
 
-        if (($locParamResult == '') && ($remoteParamResult == '') && ($wsParamResult == '')) {
-            if ($this->isSoap) throw new SoapFault("server05", "No params descriptions .xml files for " . $this->userID . " user");
-            else return array('success' => false, 'message' => "No params descriptions .xml files for " . $this->userID . " user");
-        }
+		if ($this->userID == 'impex') {
+			$sharedObjMgr = new SharedObjectsMgr();
+			$ttSrc = $sharedObjMgr->getDataFilePath('timeTable', $ttID);
+		}
+		else
+			$ttSrc = USERPATH.$this->userID.'/TT/'.$ttID.'.xml';
 
-        $wsres = $this->resultMgr->addResult(__FUNCTION__, $vars, $this->userID, $wsParamResult . ";" . $locParamResult . ";" . $remoteParamResult);
+		if (!file_exists($ttSrc)) {
+			$this->throwError("workspaceError", "No such table ".$ttID.".xml");
+		}
 
-        return array('success' => true, 'WorkSpace' => array("LocalDataBaseParameters" => $locParamResult, "RemoteDataBaseParameters" => $remoteParamResult));
-    }
+		$ttWSresult = $this->resultMgr->getResOutputName(__FUNCTION__,$this->userID,$ttID);
 
-    public function getPlot($data)
-    {
+		if (!copy($ttSrc,$ttWSresult)){
+			$this->throwError("workspaceError", "Cannot copy ".$ttID.".xml");   
+		}
+    
+		$wsres = $this->resultMgr->addResult(__FUNCTION__,$vars,$this->userID, $ttWSresult);
+    
+		$myTimeTableMgr = new TimeTableMgr($this->userID);
+		$ttWSresultVot = $myTimeTableMgr->xsl2vot($ttWSresult);
+		
+		if(file_exists($ttWSresultVot)){
+			copy($ttWSresultVot, $ttWSresult);
+			unlink( $ttWSresultVot ) ;
+		}
+		
+		return array('success' => true, 'ttFileURL' => 'http://'.str_replace(BASE_PATH,$_SERVER['SERVER_NAME'].APACHE_ALIAS,$ttWSresult));
+	}
+   
+	public function isAlive()
+	{
+		$res = $this->init($data);
+		return true;
+	}
+  
+
+	public function getObsDataTree() 
+	{         
+		$res = $this->init();
+		
+		$resMgr = $this->initUserMgr(); 
+
+		$vars = $res['vars'];
+
+		$locParamSrc = USERPATH.$this->userID.'/WS/LocalParams.xml'; 
+		$wsParamSrc = USERPATH.$this->userID.'/WS/WsParams.xml';
+		$locParamResult = $this->resultMgr->getResOutputName(__FUNCTION__,$this->userID.'_'.'LocalParams');
+		$wsParamResult = $this->resultMgr->getResOutputName(__FUNCTION__,$this->userID.'_'.'WsParams');
+
+		if (!copy($locParamSrc,$locParamResult))
+			$locParamResult = '';  
+  
+		if (!copy($wsParamSrc,$wsParamResult))
+			$wsParamResult = '';  
+ 
+		if ($locParamResult !='') $locParamResult = 'http://'.str_replace(BASE_PATH,$_SERVER['SERVER_NAME'].APACHE_ALIAS,$locParamResult);
+		if ($wsParamResult !='') $wsParamResult = 'http://'.str_replace(BASE_PATH,$_SERVER['SERVER_NAME'].APACHE_ALIAS,$wsParamResult);
+
+		if (($locParamResult =='') && ($wsParamResult ==''))
+		{
+			$this->throwError("workspaceError", "No parameter description file");
+		} 
+
+		$wsres = $this->resultMgr->addResult(__FUNCTION__,$vars,$this->userID,$wsParamResult.";".$locParamResult);
+
+		return  array('success' => true,'WorkSpace' => array("LocalDataBaseParameters"=>$locParamResult));
+	}
 
-        $res = $this->init($data);
-        $resMgr = $this->initUserMgr();
+	public function getPlot($data) 
+	{
+		$res = $this->init($data);
+		$resMgr = $this->initUserMgr();
+		
+		$vars = $res['vars'];
+		$mission = $vars["missionID"];
+
+		$ID = $this->setID();        // unique JobID
+		$resDirName = WSRESULT.$ID; // Define a temporary  directory for results
+
+		if (is_dir($resDirName))
+				$this->rrmdir($resDirName);
+				
+		mkdir($resDirName);
+		chmod($resDirName,0775);
+
+		$dom = new DomDocument("1.0");
+		$dom->load(plotsXml);
+
+		$missionTag = $dom->getElementById($mission);
+		$params = $missionTag->getElementsByTagName('param');
+
+		$paramsList = array();
+		foreach ($params as $param)
+			$paramsList[] = $param->getAttribute('name');
+
+		$requestObject = (Object) array(
+			"nodeType" => "request",
+			"file-format" => "PNG",
+			"file-output" => "WS",
+			"ws-result-file" => $resDirName."/request.list.png",
+			"last-plotted-tab" => 1,
+			"timesrc" => "Interval",
+			"startDate" => $vars["startTime"],
+			"stopDate" => $vars["stopTime"],
+			"tabs" => array()
+		);
+    
+		$pageObject = (Object) array(
+			"id" => 1,
+			"multi-plot-linked" => true,
+			"page-margins-activated" => true,
+			"page-margin-x" => 5,
+			"page-margin-y" => 5,
+			"page-orientation" => "portrait",
+			"page-dimension" => "ISO A4",
+			"page-layout-type" => "vertical",
+			"page-layout-object" => (Object) array(
+				"layout-panel-height" => 0.25,
+				"layout-panel-spacing" => 0,
+				"layout-expand" => false
+			),
+			"panels" => array()
+		);
+    
+		foreach ($paramsList as $paramToPlot)
+		{
+			$panelObject = (Object) array(
+				"panel-plot-type" => "timePlot",
+				"axes" => array(),
+				"params" => array()
+			);
+			
+			$timeAxisObject = (Object) array(
+				"id" => "time",
+				"axis-type" => "time",
+					"axis-range-extend" => true
+			);
+			$panelObject->{"axes"}[] = $timeAxisObject;
+
+			$yAxisObject = (Object) array(
+				"id" => "y-left",
+				"axis-type" => "y-left",
+					"axis-range-extend" => true
+			);
+			$panelObject->{"axes"}[] = $yAxisObject;
+			
+			$paramObject = (Object) array(
+				"id" => 1,
+				"param-id" => $paramToPlot,
+				"param-drawing-type" => "serie",
+				"param-drawing-object" => (Object) array(
+					"serie-yaxis" => "y-left",
+					"serie-lines-activated" => true
+				)
+			);
+			$panelObject->{"params"}[] = $paramObject;
+			
+			$pageObject->{"panels"}[] = $panelObject;
+		}
+		
+		$requestObject->{"tabs"}[] = $pageObject;
+    
+		if (!isset($this->requestManager))
+			$this->requestManager = new RequestManagerClass();
+		
+		try {
+			$plotResult = $this->requestManager->runIHMRequest($this->userID, $this->getIPclient(), FunctionTypeEnumClass::PARAMS, $requestObject);
+		} catch (Exception $e) {
+				$this->throwError("plotError", "Exeption detected : ".$e->getMessage());
+		}
 
-        $vars = $res['vars'];
-        $mission = $vars["missionID"];
+		return array('success' => true, 'plotDirectoryURL' => $ID);
+	}
 
-        $ID = $this->setID();  // unique JobID
-        $resDirName = WSRESULT . $ID; // Define a temporary  directory for results
+	public function getResultPlot($data) 
+	{			
+		$res = $this->init($data);
+		$vars = $res['vars'];
+		$ID = $vars["plotDirectoryURL"];
+		$filename = WSRESULT.$ID."/request.list.png";
+		if (file_exists($filename)) {
+			$plotWSresult=WSRESULT.$ID."/request.list.png";
+			return array('success' => true, 'plotFileURL' => 'http://'.str_replace(BASE_PATH,$_SERVER['SERVER_NAME'].APACHE_ALIAS,$plotWSresult));
+		}
+		else
+			return array('success' => false);
+	}
 
-        if (is_dir($resDirName))
-            $this->rrmdir($resDirName);
-        mkdir($resDirName);
-        chmod($resDirName, 0775);
+	public function getStatus($id) 
+	{
+		$processManager = new ProcessManagerClass(IHMConfigClass::getProcessManagerFilePath());
+			
+		try {
+			$res = $processManager->getProcessInfo($id, true);
+		} catch (Exception $e) {
+			$this->throwError("serverError","Exception detected : ".$e->getMessage());
+		}
+//     [success] => 1
+//     [result] => Array
+//         (
+//             [id] => process_ADBCw1_1519836455_19505
+//             [cmd] => /home/budnik/AMDA/AMDA_Kernel/build/Debug/bin/amdaXMLRequestorTool /home/budnik/AMDA/AMDA_IHM/data/budnik/RES/DDnT8PLR_/request_0.xml
+//             [outputfile] => cmd_output
+//             [exitcodefile] => cmd_exitcode
+//             [processfile] => cmd_process
+//             [exitcode] => 0
+//             [PID] => 19505
+//             [runningpath] => /home/budnik/AMDA/AMDA_IHM/data/budnik/RES/DDnT8PLR_/
+//             [runningstart] => 1519836455
+//             [isrunning] => 
+//             [iskilled] => 
+//             [lastupdate] => 1519837450
+//         )
+
+		if (!$res['success']) {
+			$this->throwError("processError","Cannot retrieve process $id info");
+		}
+		
+		$result = $res['result'];
+		
+		if ($result['isrunning']) {
+			return array('success' => true, 'status' => 'in_progress');
+		}
+		
+		if ($result['iskilled']) {
+			$this->throwError("processError","Process $id was killed");
+		}
+		
+		if ($result['exitcode'] !== 0) {
+			$this->throwError("processError","Process $id error code: ".$result['exitcode']);
+		}
+		
+		$vars = $this->getVarsFromRunningPath($result['runningpath']);
+		
+		if (!$vars['success']) {
+			$this->throwError("processError","Process $id : cannot generate file name for result : ".$vars['message']);
+		}
+		
+		$resultFile = glob($result['runningpath']."result_*");
+		
+		$tempFilePath = $result['runningpath'].$resultFile.$vars['kernelExtension'];
+
+		$outputFilePath = WSRESULT.$vars['dataFileName'].$vars['wsExtension'];
+		
+		return $this->finishDownloadRequest($id, $tempFilePath, $outputFilePath);
+	}
+	
+	
+	public function getParameterList($data) 
+	{         
+		$res = $this->init($data);
+		
+		$resMgr = $this->initUserMgr(); 
+
+		$vars = $res['vars'];
+
+		$locParamSrc = USERWSDIR.'/LocalParams.xml'; 
+		$wsParamSrc =  USERWSDIR.'/WsParams.xml';
+		$locParamResult = $this->resultMgr->getResOutputName(__FUNCTION__,$this->userID.'_'.'LocalParams');
+		$wsParamResult = $this->resultMgr->getResOutputName(__FUNCTION__,$this->userID.'_'.'WsParams');
+
+		if (!copy($locParamSrc,$locParamResult))
+			$locParamResult = '';  
+		
+		if (!copy($wsParamSrc,$wsParamResult))
+			$wsParamResult = '';  
+ 
+		if ($locParamResult !='') 
+			$locParamResult = 'http://'.str_replace(BASE_PATH,$_SERVER['SERVER_NAME'].APACHE_ALIAS,$locParamResult);
+		if ($wsParamResult !='') 
+			$wsParamResult = 'http://'.str_replace(BASE_PATH,$_SERVER['SERVER_NAME'].APACHE_ALIAS,$wsParamResult);
+
+		if (($locParamResult =='') && ($wsParamResult =='')){
+			$this->throwError("workspaceError", "No params descriptions for ".$this->userID);
+		} 
+
+		$wsres = $this->resultMgr->addResult(__FUNCTION__,$vars,$this->userID,$wsParamResult.";".$locParamResult.";".$remoteParamResult);
+
+		return  array('success' => true,'ParameterList' => array("UserDefinedParameters"=>$wsParamResult, "LocalDataBaseParameters"=>$locParamResult, "RemoteDataBaseParameters"=>$remoteParamResult));
+	}
+	
+	public function getNewToken()
+	{
+		$timeStamp = (new DateTime())->getTimestamp();
+		// generate token from timeStamp and some salt
+		$newToken = md5(1321 * (int)($timeStamp / timeLimitQuery));
+		return array('success' => true, 'token' => $newToken);
+	}
 
-        $dom = new DomDocument("1.0");
-        $dom->load(plotsXml);
+/*
+*   getParameter 
+*/
+	public function getParameter($data) 
+	{
+		$multiParam = false;
 
-        $missionTag = $dom->getElementById($mission);
-        $params = $missionTag->getElementsByTagName('param');
+		$res = $this->init($data);
+    
+		$resMgr = $this->initUserMgr();
 
-        $paramsList = array();
-        foreach ($params as $param)
-            $paramsList[] = $param->getAttribute('name');
+		if (!$res['success']){
+			$this->throwError("requestError", "Cannot parse request"); 
+		}
 
-        $requestObject = (Object)array(
-                "nodeType" => "request",
-                "file-format" => "PNG",
-                "file-output" => "WS",
-                "ws-result-file" => $resDirName . "/request.list.png",
-                "last-plotted-tab" => 1,
-                "timesrc" => "Interval",
-                "startDate" => $vars["startTime"],
-                "stopDate" => $vars["stopTime"],
-                "tabs" => array()
-        );
+		$vars = $res['vars'];
+		
+		$startTime = strtotime($vars["startTime"]);
+		$stopTime = strtotime($vars["stopTime"]);
 
-        $pageObject = (Object)array(
-                "id" => 1,
-                "multi-plot-linked" => true,
-                "page-margins-activated" => true,
-                "page-margin-x" => 5,
-                "page-margin-y" => 5,
-                "page-orientation" => "portrait",
-                "page-dimension" => "ISO A4",
-                "page-layout-type" => "vertical",
-                "page-layout-object" => (Object)array(
-                        "layout-panel-height" => 0.25,
-                        "layout-panel-spacing" => 0,
-                        "layout-expand" => false
-                ),
-                "panels" => array()
-        );
+		if ($stopTime <= $startTime){
+			$this->throwError("requestError", "Requested time interval should be greater than 0");
+		}
+ 
+		$dataFileName = $this->getDataFileName($vars, $multiParam);
 
-        foreach ($paramsList as $paramToPlot) {
-            $panelObject = (Object)array(
-                    "panel-plot-type" => "timePlot",
-                    "axes" => array(),
-                    "params" => array()
-            );
-
-            $timeAxisObject = (Object)array(
-                    "id" => "time",
-                    "axis-type" => "time",
-                    "axis-range-extend" => true
-            );
-            $panelObject->{"axes"}[] = $timeAxisObject;
-
-            $yAxisObject = (Object)array(
-                    "id" => "y-left",
-                    "axis-type" => "y-left",
-                    "axis-range-extend" => true
-            );
-            $panelObject->{"axes"}[] = $yAxisObject;
-
-            $paramObject = (Object)array(
-                    "id" => 1,
-                    "param-id" => $paramToPlot,
-                    "param-drawing-type" => "serie",
-                    "param-drawing-object" => (Object)array(
-                            "serie-yaxis" => "y-left",
-                            "serie-lines-activated" => true
-                    )
-            );
-            $panelObject->{"params"}[] = $paramObject;
-
-            $pageObject->{"panels"}[] = $panelObject;
-        }
-
-        $requestObject->{"tabs"}[] = $pageObject;
-
-        require_once(INTEGRATION_SRC_DIR . "RequestManager.php");
-        if (!isset($this->requestManager))
-            $this->requestManager = new RequestManagerClass();
-
-        try {
-            $plotResult = $this->requestManager->runIHMRequest($this->userID, $this->getIPclient(), FunctionTypeEnumClass::PARAMS, $requestObject);
-        } catch (Exception $e) {
-            if ($this->isSoap) throw new SoapFault("plot01", 'Exception detected : ' . $e->getMessage());
-            else return array('success' => false, 'message' => 'Exception detected : ' . $e->getMessage());
-        }
-
-        return array('success' => true, 'plotDirectoryURL' => $ID);
-    }
-
-    public function getResultPlot($data)
-    {
-
-        $res = $this->init($data);
-        $vars = $res['vars'];
-        $ID = $vars["plotDirectoryURL"];
-        $filename = WSRESULT . $ID . "/request.list.png";
-        if (file_exists($filename)) {
-            $plotWSresult = WSRESULT . $ID . "/request.list.png";
-            return array('success' => true, 'plotFileURL' => 'http://' . str_replace(BASE_PATH, $_SERVER['SERVER_NAME'] . APACHE_ALIAS, $plotWSresult));
-        } else
-            return array('success' => false);
-
-    }
-
-    public function getStatus($id) {
-        $obj = (object)array(
-            "username" => $this->userID,
-            "password" => $this->userPWD,
-            "sessionID" => $this->sessionID
-        );
+		if ($dataFileName['success']) {
+			$this->dataFileName = $dataFileName['fileName'];
+		}
+		else {
+			$this->throwError("requestError", $dataFileName['message']);
+		}
 
-        $aa = new AmdaAction();
-        $jobs = $aa->getJobs($obj);
-
-//      job =
-//	    {
-//	    	"success":true,
-//		    "id":"process_aiaoh7_1517403874_1372",
-//		    "name":"download_data_1517403886",
-//		    "status":"in_progress",
-//		    "jobType":"download",
-//		    "info":" ",
-//		    "start":"31-01-2018 13:04:34",
-//		    "stop":"unknown",
-//		    "folder":"DDpTDRrk_",
-//		    "result":"result_pTDRrk",
-//		    "format":"unknown",
-//		    "compression":"",
-//		    "sendToSamp":false
-//	    }
-
-	    if (intval($jobs['nInProgress']) > 0) {
-		    foreach ($jobs['jobsInProgress'] as $job) {
-			    if ($job['id'] == $id) {
-				    return ['success' => true, 'status' => 'in_progress'];
-			    }
-		    }
-	    }
-	    if (intval($jobs['nFinished']) > 0) {
-		    foreach ($jobs['jobsFinished'] as $job) {
-			    if ($job['id'] == $id) {
-				    $vars = $this->getVarsFromRunningPath($job['runningPath']);
-				    $resTempFilePath = USERPATH . $this->userID . '/RES/' . $job['folder'] . '/' . $job['result'] . $vars['kernelExtension'];
-				    $resOutputFilePath = WSRESULT.$vars['dataFileName'].$vars['wsExtension'];
-				    return $this->finishDownloadRequest($job['id'], $resTempFilePath, $resOutputFilePath);
-			    }
-		    }
-	    }
-	    return ['success' => false, 'message' => 'No job found for this id.'];
-    }
+		$paramId = array();
+		array_push($paramId, $vars["parameterID"]);
+
+		if (!$vars["timeFormat"])
+			$timeFormat = "ISO8601";
+		else
+			$timeFormat = $vars["timeFormat"];
+
+		if (!$vars["gzip"])
+			$gzip = 0;
+		else
+			$gzip = $vars["gzip"];
+/*
+    if (!$vars["stream"])
+      $stream = 0;
+    else
+      $stream = $vars["stream"];*/
+
+		$res = $this->doDownloadRequest(
+					array("startTime" => $vars["startTime"], "stopTime" => $vars["stopTime"], "sampling" => $vars["sampling"]),
+					array("params" => $paramId),
+					array("userName" => $this->userID, "userPwd" => $this->userPWD, "sessionID" => $this->sessionID),
+					array("format" => $vars["outputFormat"], "timeFormat"=> $timeFormat, "gzip"=>$gzip, "stream"=>$stream),
+			$dataFileName);
+
+ 	 
+		if ($res['success']) 
+			return $res;
+	
+		$this->throwError("serverError", $res['message']);   
+	
+	}
+	
+/*
+*   get Orbites
+*/ 
+	public function getOrbites($data) 
+	{
+		$multiParam = false;
 
-    public function getParameterList($data)
-    {
+		$res = $this->init($data);
 
-        $res = $this->init($data);
+		$resMgr = $this->initUserMgr();
 
-        $resMgr = $this->initUserMgr();
+		if (!$resMgr['success']){
+			$this->throwError("serverError", "Cannot init user manager");
+		}
 
-        $vars = $res['vars'];
-
-        $locParamSrc = USERPATH . $this->userID . '/WS/LocalParams.xml';
-//     $remoteParamSrc = USERPATH.$this->userID.'/WS/RemoteParams.xml';
-        $wsParamSrc = USERPATH . $this->userID . '/WS/WsParams.xml';
-        $locParamResult = $this->resultMgr->getResOutputName(__FUNCTION__, $this->userID . '_' . 'LocalParams');
-//     $remoteParamResult = $this->resultMgr->getResOutputName(__FUNCTION__,'RemoteParams');
-        $wsParamResult = $this->resultMgr->getResOutputName(__FUNCTION__, $this->userID . '_' . 'WsParams');
-
-        if (!copy($locParamSrc, $locParamResult))
-            $locParamResult = '';
-        else {
-            $piBase = new DomDocument("1.0");
-            $piBase->formatOutput = true;
-            $piBase->preserveWhiteSpace = false;
-
-            $dom = new DomDocument("1.0");
-            $dom->load($locParamResult);
-
-            $xsl = new DomDocument("1.0");
-            $xsl->load(XMLPATH . 'dd2WStree.xsl');
-
-            $xslt = new XSLTProcessor();
-            $xslt->importStylesheet($xsl);
-
-            $dom->loadXML($xslt->transformToXML($dom));
-
-            $dom->formatOutput = true;
-            $dom->preserveWhiteSpace = false;
-            $chum_ger = $dom->getElementById("Rosetta@C-G : Plot Only!");
-            if ($chum_ger != NULL) $chum_ger->setAttribute("target", "Churyumov-Gerasimenko");
-            $dom->save($locParamResult);
-        }
-//     if (!copy($remoteParamSrc,$remoteParamResult))
-// 	$remoteParamResult = '';
-        if (!copy($wsParamSrc, $wsParamResult))
-            $wsParamResult = '';
-
-        if ($locParamResult != '') $locParamResult = 'http://' . str_replace(BASE_PATH, $_SERVER['SERVER_NAME'] . APACHE_ALIAS, $locParamResult);
-//     if ($remoteParamResult !='') $remoteParamResult = 'http://'.str_replace(BASE_PATH,$_SERVER['SERVER_NAME'].APACHE_ALIAS,$remoteParamResult);
-        if ($wsParamResult != '') $wsParamResult = 'http://' . str_replace(BASE_PATH, $_SERVER['SERVER_NAME'] . APACHE_ALIAS, $wsParamResult);
-
-        if (($locParamResult == '') && ($remoteParamResult == '') && ($wsParamResult == '')) {
-            if ($this->isSoap) throw new SoapFault("server05", "No params descriptions .xml files for " . $this->userID . " user");
-            else return array('success' => false, 'message' => "No params descriptions .xml files for " . $this->userID . " user");
-        }
-
-        $wsres = $this->resultMgr->addResult(__FUNCTION__, $vars, $this->userID, $wsParamResult . ";" . $locParamResult . ";" . $remoteParamResult);
-
-        return array('success' => true, 'ParameterList' => array("UserDefinedParameters" => $wsParamResult, "LocalDataBaseParameters" => $locParamResult, "RemoteDataBaseParameters" => $remoteParamResult));
-    }
-
-    public function getNewToken()
-    {
-	    require_once(INTEGRATION_SRC_DIR."RequestManager.php");
-
-	    $timeStamp = (new DateTime())->getTimestamp();
-        // generate token from timeStamp and some salt
-        $newToken = md5(1321 * (int)($timeStamp / timeLimitQuery));
-        return array('success' => true, 'token' => $newToken);
-    }
-
-///////////////////////////////////////START GET DATASET   ///////////////////////////////
-    public function getParameter($data)
-    {
-        $multiParam = false;
-
-        $res = $this->init($data);
-        $resMgr = $this->initUserMgr();
-
-        if (!$res['success']) {
-            if ($this->isSoap) throw new SoapFault("server01", "Cannot init user manager");
-            else return array('success' => false, 'message' => "Cannot init user manager");
-        }
-
-        $vars = $res['vars'];
-
-        if ((strtotime($vars["stopTime"]) - strtotime($vars["startTime"])) < 0) {
-            if ($this->isSoap) throw new SoapFault("request01", "Start time must be higher than stop time");
-            else return array('success' => false, 'message' => "Start time must be higher than stop time");
-        } elseif ((strtotime($vars["stopTime"]) - strtotime($vars["startTime"])) == 0) {
-            if ($this->isSoap) throw new SoapFault("request02", "You time interval equal 0 start is " . $vars["stopTime"] . " stop is " . $vars["startTime"]);
-            else return array('success' => false, 'message' => "You time interval equal 0");
-        }
-
-        $dataFileName = $this->getDataFileName($vars, $multiParam);
-
-        if ($dataFileName['success']) $this->dataFileName = $dataFileName['fileName'];
-        else {
-            if ($this->isSoap) throw new SoapFault("request03", $dataFileName['message']);
-            else return array('success' => false, 'message' => $dataFileName['message']);
-        }
-
-
-        $paramId = array();
-        array_push($paramId, $vars["parameterID"]);
-//     $paramId[] = $vars["parameterID"];
-
-        $sampling = key_exists("sampling", $vars) ? $vars["sampling"] : false;
-        $gzip = key_exists("gzip", $vars) ? $vars["gzip"] : 0;
-        $outputFormat = key_exists("outputFormat", $vars) ? $vars["outputFormat"] : false;
-        $timeFormat = key_exists("timeFormat", $vars) ? $vars["timeFormat"] : "ISO8601";
-        $stream = key_exists("stream", $vars) ? $vars["stream"] : 0;
-
-        $res = $this->doDownloadRequest(
-                array("startTime" => $vars["startTime"], "stopTime" => $vars["stopTime"], "sampling" => $sampling),
-                array("params" => $paramId),
-                array("userName" => $this->userID, "userPwd" => $this->userPWD, "sessionID" => $this->sessionID),
-                array("format" => $outputFormat, "timeFormat" => $timeFormat, "gzip" => $gzip, "stream" => $stream),
-                $dataFileName);
-
-        if ($res['success']) {
-            return $res;
-        } else {
-            if ($this->isSoap) {
-                throw new SoapFault("request03", $res['message']);
-            } else {
-                return array('success' => false, 'message' => $res['message']);
-            }
-        }
-    }
-
-///////////////////////////////////////START GET ORBITES   ///////////////////////////////
-    public function getOrbites($data)
-    {
-
-        $multiParam = false;
-
-        $res = $this->init($data);
-
-        $resMgr = $this->initUserMgr();
-
-        if (!$resMgr['success']) {
-            if ($this->isSoap) throw new SoapFault("server01", "Cannot init user manager");
-            else return array('success' => false, 'message' => "Cannot init user manager");
-        }
-
-        $vars = $res['vars'];
-
-        if ((strtotime($vars["stopTime"]) - strtotime($vars["startTime"])) < 0) {
-            if ($this->isSoap) throw new SoapFault("request01", "Start time must be higher than stop time");
-            else return array('success' => false, 'message' => "Start time must be higher than stop time");
-        } elseif ((strtotime($vars["stopTime"]) - strtotime($vars["startTime"])) == 0) {
-            if ($this->isSoap) throw new SoapFault("request02", "You time interval equal 0 start is " . $vars["stopTime"] . " stop is " . $vars["startTime"]);
-            else return array('success' => false, 'message' => "You time interval equal 0");
-        }
-
-
-        $spacecraft = $vars["spacecraft"];
-        $coordinateSystem = $vars["coordinateSystem"];
-        if ($spacecraft == "GALILEO") $spacecraft = ucfirst(strtolower($spacecraft));
-        if (!$vars["units"])
-            $units = "km";
-        else
-            $units = $vars["units"];
-
-        $paramId = array();
-
-        $orbitRequest = array("startTime" => $vars["startTime"],
-                "stopTime" => $vars["stopTime"],
-                "spacecraft" => $spacecraft,
-                "coordinateSystem" => $coordinateSystem,
-                "units" => $units
-        );
+		$vars = $res['vars'];
+		
+		$startTime = strtotime($vars["startTime"]);
+		$stopTime = strtotime($vars["stopTime"]);
 
+		if ($stopTime <= $startTime){
+			$this->throwError("requestError", "Requested time interval should be greater than 0");
+		}
+         
+		$spacecraft = $vars["spacecraft"];
+		$coordinateSystem = $vars["coordinateSystem"];
+		
+		if ($spacecraft == "GALILEO") $spacecraft = ucfirst(strtolower($spacecraft));
+		if (!$vars["units"])
+			$units = "km";
+		else
+			$units = $vars["units"];
+
+		$orbitRequest = array("startTime" => $vars["startTime"],
+				"stopTime"  => $vars["stopTime"],
+				"spacecraft" => $spacecraft,
+				"coordinateSystem" => $coordinateSystem,
+				"units" => $units
+				);
+  
+		$orbitesParam = $this->getOrbitesParameter($orbitRequest);
+		
+		if ($orbitesParam['success']) {
+			$orbParam = $orbitesParam['parameterID'];
+		}
+		else {
+			//$orbParam = 'successEstfalse';
+			$this->throwError("requestError", $orbitesParam['message']);
+		}
+     
+		$dataFileName = $this->getDataFileName($orbitesParam, $multiParam);
 
-        $orbitesParam = $this->getOrbitesParameter($orbitRequest);
-        if ($orbitesParam['success']) $orbParam = $orbitesParam['parameterID'];
-        else {
-            $orbParam = 'successEstfalse';
-            if ($this->isSoap) throw new SoapFault("request03", $orbitesParam['message']);
-            else return array('success' => false, 'message' => $orbitesParam['message']);
-        }
+		if ($dataFileName['success']) {
+			$this->dataFileName = $dataFileName['fileName'];
+		}
+		else {
+			$this->throwError("requestError", $dataFileName['message']); 
+		}
+		
+		$paramId = array();
+		array_push($paramId, $orbParam);
+
+		if (!$vars["timeFormat"])
+			$timeFormat = "ISO8601";
+		else
+			$timeFormat = $vars["timeFormat"];
+
+		if (!$vars["gzip"])
+			$gzip = 0;
+		else
+			$gzip = $vars["gzip"];
+      
+		$res = $this->doDownloadRequest(
+					array("startTime" => $vars["startTime"], "stopTime" => $vars["stopTime"], "sampling" => $vars["sampling"]),
+					array("params" => $paramId),
+					array("userName" => $this->userID, "userPwd" => $this->userPWD, "sessionID" => $this->sessionID),
+					array("format" => $vars["outputFormat"], "timeFormat"=> $timeFormat, "gzip"=>$gzip, "stream"=>$stream),
+			$dataFileName);
+ 	 
+		if ($res['success']) return $res;
+ 
+		$this->throwError("serverError",$res['message']);    
+	}
+  
+/*
+*   get Dataset
+*/
+	public function getDataset($data) 
+	{
+		$multiParam = true;
 
+		$res = $this->init($data);
+		
+		$resMgr = $this->initUserMgr();
 
-        $dataFileName = $this->getDataFileName($orbitesParam, $multiParam);
+		$vars = $res['vars'];
+		
+		$startTime = strtotime($vars["startTime"]);
+		$stopTime = strtotime($vars["stopTime"]);
 
-        if ($dataFileName['success']) $this->dataFileName = $dataFileName['fileName'];
-        else {
-            if ($this->isSoap) throw new SoapFault("request03", $dataFileName['message']);
-            else return array('success' => false, 'message' => $dataFileName['message']);
-        }
+		if ($stopTime <= $startTime){
+			$this->throwError("requestError", "Requested time interval should be greater than 0");
+		}
+          
+		$dataFileName = $this->getDataFileName($vars, $multiParam);
 
-        array_push($paramId, $orbParam);
-//     $paramId[] = $vars["parameterID"];
+		if ($dataFileName['success']) {
+			$this->dataFileName = $dataFileName['fileName'];
+		}
+		else {
+			$this->throeError("requestError",$dataFileName['message']); 
+		}
+		
+		$paramId = array();
+		$localData = simplexml_load_file(USERPATH.$this->userID.'/WS/LocalParams.xml');
+ 
+		if (!$vars["sampling"])
+		{
+			$xpath = "//dataset[@xml:id='".$vars['datasetID']."']/@sampling";
+			$tmp = $localData->xpath($xpath);
+			$vars["sampling"] = (string)$tmp[0];     
+
+			$matches=array();
+			preg_match("/([a-z])$/", $vars["sampling"], $matches);
+
+			$dataFileName = $this->getDataFileName($vars, $multiParam);
+
+			if ($dataFileName['success']) {
+				$this->dataFileName = $dataFileName['fileName'];
+			}
+			else {
+				$this->throwError("requestError",$dataFileName['message']); 
+			}
+
+			$vars["sampling"] = strtr($vars["sampling"], array($matches[1] => ""));
+			switch ($matches[1]) {        
+					case 's':            
+						$sampling = floatval($vars["sampling"]);
+						break; 
+					case 'm':            
+						$sampling = floatval($vars["sampling"])*60;
+						break;
+					case 'h':            
+						$sampling = floatval($vars["sampling"])*60*60;
+						break;
+					default: 
+			}
+		}
 
-        if (!$vars["timeFormat"])
-            $timeFormat = "ISO8601";
-        else
-            $timeFormat = $vars["timeFormat"];
+		$xpath = "//dataset[@xml:id='".$vars['datasetID']."']/parameter/@*[namespace-uri()='http://www.w3.org/XML/1998/namespace' and local-name()='id']";
+		$pars = $localData->xpath($xpath);
+
+		foreach ($pars as $p)
+				$paramId[] = (string)$p[0];
+ 
+		if (!$vars["timeFormat"])
+			$timeFormat = "ISO8601";
+		else
+			$timeFormat = $vars["timeFormat"];
+
+		if (!$vars["gzip"])
+			$gzip = 0;
+		else
+			$gzip = $vars["gzip"];
+
+		$res = $this->doDownloadRequest(
+					array("startTime" => $vars["startTime"], "stopTime" => $vars["stopTime"], "sampling" => $sampling),
+					array("params" => $paramId),
+					array("userName" => $this->userID, "userPwd" => $this->userPWD, "sessionID" => $this->sessionID),
+					array("format" => $vars["outputFormat"], "timeFormat"=> $timeFormat, "gzip"=>$gzip, "stream"=>$stream),
+			$dataFileName);
+  
+		if ($res['success']) return $res;
+
+		$this->throwError("serverError", $res['message']); 
+	}
 
-        if (!$vars["gzip"])
-            $gzip = 0;
-        else
-            $gzip = $vars["gzip"];
-
-        $res = $this->doDownloadRequest(
-                array("startTime" => $vars["startTime"], "stopTime" => $vars["stopTime"], "sampling" => $vars["sampling"]),
-                array("params" => $paramId),
-                array("userName" => $this->userID, "userPwd" => $this->userPWD, "sessionID" => $this->sessionID),
-                array("format" => $vars["outputFormat"], "timeFormat" => $timeFormat, "gzip" => $gzip, "stream" => $stream),
-                $dataFileName);
-
-
-        if ($res['success']) return $res;
-        else {
-            if ($this->isSoap) throw new SoapFault("request03", $res['message']);
-            else return array('success' => false, 'message' => $res['message']);
-        }
-    }
-
-///////////////////////////////////////START GET DATASET   ///////////////////////////////
-
-
-    public function getDataset($data)
-    {
-        $multiParam = true;
-
-        $res = $this->init($data);
-
-        $resMgr = $this->initUserMgr();
-
-        $vars = $res['vars'];
-
-        if ((strtotime($vars["stopTime"]) - strtotime($vars["startTime"])) < 0) {
-            if ($this->isSoap) throw new SoapFault("request01", "Start time must be higher than stop time");
-            else return array('success' => false, 'message' => "Start time must be higher than stop time");
-        } elseif ((strtotime($vars["stopTime"]) - strtotime($vars["startTime"])) == 0) {
-            if ($this->isSoap) throw new SoapFault("request02", "You time interval equal 0");
-            else return array('success' => false, 'message' => "You time interval equal 0");
-        }
-
-        $dataFileName = $this->getDataFileName($vars, $multiParam);
-
-        if ($dataFileName['success']) $this->dataFileName = $dataFileName['fileName'];
-        else {
-            if ($this->isSoap) throw new SoapFault("request03", $dataFileName['message']);
-            else return array('success' => false, 'message' => $dataFileName['message']);
-        }
-        $paramId = array();
-        $localData = simplexml_load_file(USERPATH . $this->userID . '/WS/LocalParams.xml');
-
-        if (!$vars["sampling"]) {
-            $xpath = "//dataset[@xml:id='" . $vars['datasetID'] . "']/@sampling";
-            $tmp = $localData->xpath($xpath);
-            $vars["sampling"] = (string)$tmp[0];
-
-            $matches = array();
-            preg_match("/([a-z])$/", $vars["sampling"], $matches);
-
-
-            $dataFileName = $this->getDataFileName($vars, $multiParam);
-
-            if ($dataFileName['success']) $this->dataFileName = $dataFileName['fileName'];
-            else {
-                if ($this->isSoap) throw new SoapFault("request03", $dataFileName['message']);
-                else return array('success' => false, 'message' => $dataFileName['message']);
-            }
-
-            $vars["sampling"] = strtr($vars["sampling"], array($matches[1] => ""));
-            switch ($matches[1]) {
-                case 's':
-                    $sampling = floatval($vars["sampling"]);
-                    break;
-                case 'm':
-                    $sampling = floatval($vars["sampling"]) * 60;
-                    break;
-                case 'h':
-                    $sampling = floatval($vars["sampling"]) * 60 * 60;
-                    break;
-                default:
-            }
-        }
-
-        $xpath = "//dataset[@xml:id='" . $vars['datasetID'] . "']/parameter/@*[namespace-uri()='http://www.w3.org/XML/1998/namespace' and local-name()='id']";
-        $pars = $localData->xpath($xpath);
-
-        foreach ($pars as $p)
-            $paramId[] = (string)$p[0];
-
-        if (!$vars["timeFormat"])
-            $timeFormat = "ISO8601";
-        else
-            $timeFormat = $vars["timeFormat"];
-
-        if (!$vars["gzip"])
-            $gzip = 0;
-        else
-            $gzip = $vars["gzip"];
-
-        $res = $this->doDownloadRequest(
-                array("startTime" => $vars["startTime"], "stopTime" => $vars["stopTime"], "sampling" => $sampling),
-                array("params" => $paramId),
-                array("userName" => $this->userID, "userPwd" => $this->userPWD, "sessionID" => $this->sessionID),
-                array("format" => $vars["outputFormat"], "timeFormat" => $timeFormat, "gzip" => $gzip, "stream" => $stream),
-                $dataFileName);
-
-        if ($res['success']) return $res;
-        else {
-            if ($this->isSoap) throw new SoapFault("request03", $res['message']);
-            else return array('success' => false, 'message' => $res['message']);
-        }
-    }
-
-////////////////////////////////////////END GET PARAMETERS  /////////////////////////////////
-    protected function getOrbitesParameter($orbitRequest)
-    {
-
-        $orbitesXml = new DomDocument();
-
-        if (file_exists(orbitesXml)) {
-            $orbitesXml->load(orbitesXml);
-            $xpath = new DOMXpath($orbitesXml);
-            $path = '//orbites[@mission="' . $orbitRequest['spacecraft'] . '" and @coordinate_system="' . $orbitRequest['coordinateSystem'] . '" and @units="' . $orbitRequest['units'] . '" ] ';
-
-            $orbites = $xpath->query($path);
-            foreach ($orbites as $orbite) {
-                $paramInfo = $this->myParamsInfoMgr->GetDDInfoFromParameterID($orbite->getAttribute('xml:id'));
-                $paramStart = $paramInfo['dataset']['starttime'];
-                $paramStop = $paramInfo['dataset']['stoptime'];
-
-                if ((strtotime($paramStart) <= strtotime($orbitRequest['startTime']) && (strtotime($orbitRequest['stopTime'])) <= strtotime($paramStop))) {
-
-                    return array('success' => true,
-                            'parameterID' => $orbite->getAttribute('xml:id'),
-                            'startTime' => $orbitRequest['startTime'],
-                            'stopTime' => $orbitRequest['stopTime']
-                    );
-                }
-            }
-            return array('success' => false,
-                    'message' =>
-                            "Cannot find orbites for " . $orbitRequest['spacecraft'] . " between " . $orbitRequest['startTime'] . " in " . $orbitRequest['units'] . "  " . $orbitRequest['coordinateSystem'] . " and " . $orbitRequest['stopTime'] . " ($paramStart  - $paramStop) ");
-        } else {
-            return array('success' => false, 'message' => "Orbits file doesn't exist");
-        }
-    }
-
-	private function getFormatInfo($fileFormat, $timeFormat, $gzip) {
+	protected function getOrbitesParameter($orbitRequest) 
+	{
+		$orbitesXml = new DomDocument();
+	    
+		if (file_exists(orbitesXml)) 
+		{
+			$orbitesXml->load(orbitesXml);
+			$xpath = new DOMXpath($orbitesXml);
+			$path = '//orbites[@mission="'.$orbitRequest['spacecraft'].'" and @coordinate_system="'.$orbitRequest['coordinateSystem'].'" and @units="'.$orbitRequest['units'].'" ] ';
+
+			$orbites = $xpath->query($path);
+			foreach ($orbites as $orbite){
+				$paramInfo = $this->myParamsInfoMgr->GetDDInfoFromParameterID($orbite->getAttribute('xml:id'));  
+				$paramStart = $paramInfo['dataset']['starttime'];
+				$paramStop = $paramInfo['dataset']['stoptime'];
+
+				if((strtotime($paramStart) <= strtotime($orbitRequest['startTime']) && (strtotime($orbitRequest['stopTime'])) <= strtotime($paramStop))) { 
+
+					return array('success' => true, 
+					'parameterID' => $orbite->getAttribute('xml:id'),
+					'startTime'   => $orbitRequest['startTime'],
+					'stopTime'    => $orbitRequest['stopTime']        
+					);
+				}
+			}
+			return array('success' => false, 
+			'message' => 
+			"Cannot find orbites for ".$orbitRequest['spacecraft']." between ".$orbitRequest['startTime']." in ".$orbitRequest['units']."  ".$orbitRequest['coordinateSystem']." and ".$orbitRequest['stopTime']." ($paramStart  - $paramStop) ");
+		}
+		else {
+			return array('success' => false, 'message' => "Orbits file doesn't exist"); 
+		}	
+	}
+	
+	private function getFormatInfo($fileFormat, $timeFormat, $gzip) 
+	{
 		switch ($fileFormat) {
 			case 'netCDF' :
-				if ($this->isSoap) {
-					throw new SoapFault("server01", "netCDF format not implemented");
-				} else {
-					return array('success' => false, 'message' => "netCDF format not implemented");
-				}
+				$this->throwError("serverError", "netCDF format not implemented");
 				break;
 			case 'VOTable' :
 				$fileFormat = "vot";
@@ -929,49 +895,54 @@ class WebServer
 		        'compression'     => $compression];
 	}
 
-    protected function doDownloadRequest($interval, $paramList, $user, $formatInfo, $dataFileName)
-    {
-        if ($interval['sampling'])
-            $structure = 0;// sampling
-        else
-            $structure = 2;   // not sampling
-
-	    $fileInfo = $this->getFormatInfo($formatInfo['format'], $formatInfo['timeFormat'], $formatInfo['gzip']);
-
-        require_once(INTEGRATION_SRC_DIR . "RequestManager.php");
-        IHMConfigClass::setUserName($this->userID);
-        if (!isset($this->paramLoader))
-            $this->paramLoader = new IHMUserParamLoaderClass();
-
-        //Build parameter list
-        $params = array();
-
-        //TODO template arguments to implementer ?
-        foreach ($paramList['params'] as $paramId) {
-            $param = new stdClass;
-
-            if (preg_match("#^ws_#", $paramId)) {
-                $res = $this->paramLoader->getDerivedParameterNameFromId($paramId);
-                if (!$res["success"]) {
-                    if ($this->isSoap) throw new SoapFault("server02", 'Not available derived parameter ' . $paramId);
-                    else return array('success' => false, 'message' => 'Not available derived parameter ' . $paramId);
-                }
-                $param->paramid = "ws_" . $res['name'];
-            } else if (preg_match("#^wsd_#", $paramId)) {
-                $res = $this->paramLoader->getUploadedParameterNameFromId($paramId);
-                if (!$res["success"]) {
-                    if ($this->isSoap) throw new SoapFault("server02", 'Not available user parameter ' . $paramId);
-                    else return array('success' => false, 'message' => 'Not available user parameter ' . $paramId);
-                }
-                $param->paramid = "wsd_" . $res['name'];
-            } else {
-                $param->paramid = $paramId;
-            }
-
-            $params[] = $param;
-        }
-
-        $obj = (object)array(
+	protected function doDownloadRequest($interval,$paramList,$user,$formatInfo,$dataFileName) 
+	{
+		if ($interval['sampling'])
+			$structure = 0;// sampling
+		else
+			$structure = 2;   // not sampling
+
+		$fileInfo = $this->getFormatInfo($formatInfo['format'], $formatInfo['timeFormat'], $formatInfo['gzip']); 
+
+		IHMConfigClass::setUserName($this->userID);
+		
+		if (!isset($this->paramLoader))
+			$this->paramLoader = new IHMUserParamLoaderClass();
+
+		//Build parameter list
+		$params = array();
+		
+		//TODO template arguments to implement ?
+		foreach ($paramList['params'] as $paramId)
+		{
+			$param = new stdClass;
+			
+			if (preg_match("#^ws_#",$paramId))
+			{
+				$res = $this->paramLoader->getDerivedParameterNameFromId($paramId);
+				
+				if (!$res["success"]) {
+					$this->throwError("serverError", "Not available derived parameter $paramId");
+				}
+				$param->paramid = "ws_".$res['name'];
+			}
+			else if (preg_match("#^wsd_#",$paramId))
+			{
+				$res = $this->paramLoader->getUploadedParameterNameFromId($paramId);
+				
+				if (!$res["success"]){
+					$this->throwError("serverError", "Not available parameter $paramId");
+				}
+				$param->paramid = "wsd_".$res['name'];
+			}
+			else{
+				$param->paramid = $paramId;
+			}
+			
+			$params[] = $param;
+		}
+		
+		$obj = (object)array(
                 "nodeType" => "download",
                 "downloadSrc" => "0",
                 "structure" => $structure,
@@ -984,118 +955,118 @@ class WebServer
                 "fileformat" => $fileInfo['fileFormat'],
                 "timeformat" => $fileInfo['timeFormat'],
                 "compression" => $fileInfo['compression'],
-	            "extension" => $fileInfo['wsExtension'],
+	             "extension" => $fileInfo['wsExtension'],
                 "disablebatch" => false,
-	            "dataFileName" => $this->dataFileName
+	             "dataFileName" => $this->dataFileName
         );
-
-        if (!isset($this->requestManager))
-            $this->requestManager = new RequestManagerClass();
-
-        try {
-	        $downloadResult = $this->requestManager->runIHMRequest($this->userID, $this->getIPclient(), FunctionTypeEnumClass::PARAMS, $obj);
-        } catch (Exception $e) {
-            if ($this->isSoap) throw new SoapFault("server02", 'Exception detected : ' . $e->getMessage());
-            else return array('success' => false, 'message' => 'Exception detected : ' . $e->getMessage());
-        }
-
-        if (!$downloadResult['success']) {
-            if ($this->isSoap) throw new SoapFault("server03", $downloadResult['message']);
-            else return array('success' => false, 'message' => $downloadResult['message']);
-        }
-
-        if($downloadResult['status'] == 'in_progress') {
-	        return ['success' => true, 'status' => 'in_progress', 'id' => $downloadResult['id']];
-        } elseif ($downloadResult['status'] == 'done') {
-	        $resTempFilePath = USERPATH . $this->userID . '/RES/' . $downloadResult['folder'] . '/' . $downloadResult['result'] . $fileInfo['kernelExtension'];
-	        $resOutputFilePath = WSRESULT.$this->dataFileName.$fileInfo['wsExtension'];
-	        return $this->finishDownloadRequest($downloadResult['id'], $resTempFilePath, $resOutputFilePath);
-        } else {
-	        return ['success' => false, 'message' => 'Unknown status ' . $downloadResult['status'] . '.'];
-        }
-    }
-
+		
+		if (!isset($this->requestManager))
+			$this->requestManager = new RequestManagerClass();
+		
+		try {
+			$downloadResult = $this->requestManager->runIHMRequest($this->userID, $this->getIPclient(), FunctionTypeEnumClass::PARAMS, $obj);
+		} catch (Exception $e) {
+			$this->throwError("serverError", "Exception detected : ".$e->getMessage()); 
+		}
+			
+		if (!$downloadResult['success']) {
+			$this->throwError("serverError", $downloadResult['message']);
+		}
+		
+		if($downloadResult['status'] == 'in_progress') {
+			return ['success' => true, 'status' => 'in_progress', 'id' => $downloadResult['id']];
+		} elseif ($downloadResult['status'] == 'done') {
+			$resTempFilePath = USERWORKINGDIR.'/'.$downloadResult['folder'].'/'.$downloadResult['result'].$fileInfo['kernelExtension'];
+			$resOutputFilePath = WSRESULT.$this->dataFileName.$fileInfo['wsExtension'];
+			return $this->finishDownloadRequest($downloadResult['id'], $resTempFilePath, $resOutputFilePath);
+		} else {
+			return ['success' => false, 'message' => 'Unknown status ' . $downloadResult['status']];
+		} 
+	}
+	
 	private function finishDownloadRequest($id, $resTempFilePath, $resOutputFilePath)
-    {
+	{
 		if (!file_exists($resTempFilePath)) {
-		    if ($this->isSoap) throw new SoapFault("server04", 'Cannot retrieve result file ' . $resTempFilePath);
-		    else return ['success' => false, 'message' => 'Cannot retrieve result file'];
+			$this->throwError("serverError", "Cannot retrieve result file $resTempFilePath");
 	    }
 
-	    rename($resTempFilePath, $resOutputFilePath);
-	    chmod($resOutputFilePath, 0664);
-	    $outputURL = 'http://' . str_replace(BASE_PATH, $_SERVER['SERVER_NAME'] . APACHE_ALIAS, $resOutputFilePath);
+		rename($resTempFilePath, $resOutputFilePath);
+		chmod($resOutputFilePath, 0664);
+		
+		$outputURL = 'http://' . str_replace(BASE_PATH, $_SERVER['SERVER_NAME'] . APACHE_ALIAS, $resOutputFilePath);
 
 		$obj = (object)array(
-		    'id' => $id
-	    );
-
-	    require_once(INTEGRATION_SRC_DIR . "RequestManager.php");
-	    if (!isset($this->requestManager))
-		    $this->requestManager = new RequestManagerClass();
-
-	    try {
-		    $downloadResult = $this->requestManager->runIHMRequest($this->userID, $this->getIPclient(), FunctionTypeEnumClass::PROCESSDELETE, $obj);
-	    } catch (Exception $e) {
-	    	error_log("Can not delete file $resOutputFilePath: $e");
-	    }
+			'id' => $id
+		);
+   
+		if (!isset($this->requestManager))
+			$this->requestManager = new RequestManagerClass();
+
+		try {
+			$downloadResult = $this->requestManager->runIHMRequest($this->userID, $this->getIPclient(), FunctionTypeEnumClass::PROCESSDELETE, $obj);
+		} catch (Exception $e) {
+			error_log("Can not delete file $resOutputFilePath: $e");
+		}
 
-	    return array('success' => true, 'status' => 'done', 'dataFileURLs' => $outputURL);
-    }
-
-    protected function timeIntervalToDuration($startTime, $stopTime)
-    {
-        $duration = strtotime($stopTime) - strtotime($startTime);
-        $durationDay = intval($duration / (86400));
-        $duration = $duration - $durationDay * 86400;
-        $durationHour = intval($duration / (3600));
-        $duration = $duration - $durationHour * 3600;
-        $durationMin = intval($duration / (60));
-        $durationSec = $duration - $durationMin * 60;
-
-        return array("success" => true, "days" => sprintf("%04s", strval($durationDay)),
-                "hours" => sprintf("%02s", strval($durationHour)),
-                "mins" => sprintf("%02s", strval($durationMin)),
-                "secs" => sprintf("%02s", strval($durationSec))
-        );
-    }
-
-    protected function getDataFileName($vars, $multiParam)
-    {
-        if ($vars['startTime'] && $vars['stopTime'] && $vars['parameterID'] && !$multiParam) {
-            $fileName = $vars['parameterID'] . "-" . strtotime($vars['startTime']) . "-" . strtotime($vars['stopTime']);
-            if (isset($vars['sampling']) && $vars['sampling'] != "" && $vars['sampling'] != 0)
-                $fileName .= "-" . $vars['sampling'];
-            return array('success' => true, 'fileName' => $fileName);
-        } else if ($vars['startTime'] && $vars['stopTime'] && $vars['datasetID'] && $multiParam) {
-            $datasetName = strtr($vars["datasetID"], array(":" => "_"));
-            $fileName = $datasetName . "-" . strtotime($vars['startTime']) . "-" . strtotime($vars['stopTime']);
-            if (isset($vars['sampling']) && $vars['sampling'] != "" && $vars['sampling'] != 0)
-                $fileName .= "-" . $vars['sampling'];
-            return array('success' => true, 'fileName' => $fileName);
-        } else {
-            if (!$vars['startTime'])
-                $message = "Start time not specified";
-            if (!$vars['stopTime'])
-                $message = "Stop time not specified";
-            if (!$vars['parameterID'] && !$multiParam)
-                $message = "Parameter not specified";
-            if (!$vars['datasetID'] && $multiParam)
-                $message = "DataSet not specified";
-            return array('success' => false, 'message' => $message);
-        }
-    }
+		return array('success' => true, 'status' => 'done', 'dataFileURLs' => $outputURL);
+	}
+    
+    
+	protected function timeIntervalToDuration($startTime,$stopTime) 
+	{
+		$duration = strtotime($stopTime) - strtotime($startTime);
+		$durationDay  = intval($duration/(86400)); 
+		$duration = $duration - $durationDay*86400;
+		$durationHour = intval($duration/(3600));
+		$duration = $duration - $durationHour*3600;
+		$durationMin = intval($duration/(60));
+		$durationSec = $duration - $durationMin*60;
+		
+		return array("success" => true, "days"  => sprintf("%04s",   strval($durationDay)),
+						"hours" => sprintf("%02s",   strval($durationHour)),
+						"mins"  => sprintf("%02s",   strval($durationMin)),
+						"secs"  => sprintf("%02s",   strval($durationSec))
+		);
+	}
 
+	protected function getDataFileName($vars, $multiParam)
+	{
+		if ($vars['startTime'] && $vars['stopTime'] && $vars['parameterID'] && !$multiParam){
+			$fileName = $vars['parameterID']."-".strtotime($vars['startTime'])."-".strtotime($vars['stopTime']);
+			if (isset($vars['sampling']) && $vars['sampling'] != "" && $vars['sampling'] != 0)
+				$fileName .= "-".$vars['sampling'];
+			return array('success' => true, 'fileName' => $fileName);
+		}
+		else if ($vars['startTime'] && $vars['stopTime'] && $vars['datasetID'] && $multiParam){
+			$datasetName = strtr($vars["datasetID"], array(":" => "_"));
+			$fileName = $datasetName."-".strtotime($vars['startTime'])."-".strtotime($vars['stopTime']);
+			if (isset($vars['sampling']) && $vars['sampling'] != "" && $vars['sampling'] != 0)
+				$fileName .= "-".$vars['sampling'];
+			return array('success' => true, 'fileName' => $fileName);
+		}
+		else {
+			if (!$vars['startTime'])
+				$message="Start time not specified";
+			if (!$vars['stopTime'])
+				$message="Stop time not specified";
+			if (!$vars['parameterID'] && !$multiParam)
+				$message="Parameter not specified";
+			if (!$vars['datasetID'] && $multiParam)
+				$message="DataSet not specified";
+			return array('success' => false, 'message' => $message);
+		}
+	}
+	
 	private function getVarsFromRunningPath($runningPath)
 	{
 		$filePath = $runningPath . "request_0.xml";
-		if (file_exists($filePath)) {
-			$requestXml = new DOMDocument();
-			$requestXml->load($filePath);
-		} else {
-			return ['success' => false, 'message' => 'Failed to open request file.'];
+		
+		if (!file_exists($filePath)) {
+			return ['success' => false, 'message' => 'Failed to open request file'];
 		}
-
+		
+		$requestXml = new DOMDocument();
+		$requestXml->load($filePath);
 		$fileFormat = $requestXml->getElementsByTagName('fileFormat')->item(0)->nodeValue;
 		$timeFormat = $requestXml->getElementsByTagName('timeFormat')->item(0)->nodeValue;
 		$gzip = 0; // todo $requestXml->getElementsByTagName('gzip')->item(0)->nodeValue;
@@ -1103,7 +1074,6 @@ class WebServer
 		// get kernelExtension, wsExtension, fileFormat, timeFormat, compression:
 		$vars = $this->getFormatInfo($fileFormat, $timeFormat, $gzip);
 
-		require_once(INTEGRATION_SRC_DIR . "InputOutput/IHMImpl/Tools/CommonClass.php");
 		$cc = new CommonClass();
 
 		$vars['parameterID'] = $requestXml->getElementsByTagName('param')->item(0)->getAttribute('id');
@@ -1119,30 +1089,28 @@ class WebServer
 
 		if (in_array(null, $vars, true)) {
 			return ['success' => false,
-				    'message' => 'Can not create data file name because a value is missing in the request file.'];
+				    'message' => 'Can not create data file name - a value is missing in the request file'];
 		}
 
-		$getDataFileName = $this->getDataFileName($vars, false);
-		if (!$getDataFileName['success']) {
-			return $getDataFileName;
+		$dataFileName = $this->getDataFileName($vars, false);
+		if (!$dataFileName['success']) {
+			return $dataFileName;
 		}
-		$vars['dataFileName'] = $getDataFileName['fileName'];
-
+		$vars['dataFileName'] = $dataFileName['fileName'];
+		$vars['success'] = true;
+		
 		return $vars;
 	}
+	
+	private  function compress($srcName, $dstName) 
+	{
+		$fp = fopen($srcName, "r");
+		$data = fread($fp, filesize($srcName));
+		fclose($fp);
 
-	private function compress($srcName, $dstName)
-    {
-
-        $fp = fopen($srcName, "r");
-        $data = fread($fp, filesize($srcName));
-        fclose($fp);
-
-        $zp = gzopen($dstName, "w9");
-        gzwrite($zp, $data);
-        gzclose($zp);
-    }
-
+		$zp = gzopen($dstName, "w9");
+		gzwrite($zp, $data);
+		gzclose($zp);
+	}
 }
-
 ?>
\ No newline at end of file
--
libgit2 0.21.2