Blame view

php/classes/WebServer.php 26.4 KB
16035364   Benjamin Renard   First commit
1
<?php
b8502f4d   Elena.Budnik   getStatus(), thro...
2
3
4
5
/** 
*   @file WebServer.php
*   @brief  Web services AMDA
*/
16035364   Benjamin Renard   First commit
6
7
class WebResultMgr
{
b8502f4d   Elena.Budnik   getStatus(), thro...
8
9
10
	private $resDOM;
	private $rootEl;
	private $resXP;
b8502f4d   Elena.Budnik   getStatus(), thro...
11
12
13

	function __construct()
	{
8385c27c   Elena.Budnik   interim commit
14
		if (!is_dir(WSConfigClass::getWsResultDir())) mkdir(WSConfigClass::getWsResultDir(), 0775);
b8502f4d   Elena.Budnik   getStatus(), thro...
15
		
b8502f4d   Elena.Budnik   getStatus(), thro...
16
17
18
19
20
21
		$this->resDOM = new DOMDocument("1.0");
		$this->resDOM->formatOutput = TRUE;
		$this->resDOM->preserveWhiteSpace = FALSE;
		
		if (!file_exists(wsResultsXml))
		{
8385c27c   Elena.Budnik   interim commit
22
23
24
25
26
27
28
			$this->rootEl = $this->resDOM->createElement('wsresults');
			$this->resDOM->appendChild($this->rootEl);
			$this->resDOM->save(wsResultsXml);
		}
		else {
			$this->resDOM->load(wsResultsXml);
			$this->rootEl = $this->resDOM->documentElement;
b8502f4d   Elena.Budnik   getStatus(), thro...
29
		}
b8502f4d   Elena.Budnik   getStatus(), thro...
30
31
		
		$this->resXP = new DOMXPath($this->resDOM);
b8502f4d   Elena.Budnik   getStatus(), thro...
32
33
34
35
36
37
38
39
40
41
42
43
44
45
	}
  
	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)
8385c27c   Elena.Budnik   interim commit
46
			$funcNode->removeChild($oldOutput->item(0));
b8502f4d   Elena.Budnik   getStatus(), thro...
47
48
49
50
			
		$resNode = $this->resDOM->createElement('result');
		$resNode->setAttribute('date',time());
		$resNode->setAttribute('user',$user);
b8502f4d   Elena.Budnik   getStatus(), thro...
51
52
53
54
55
56
57
58
59
		$resNode->setAttribute('input',json_encode($vars));
		$resNode->setAttribute('output',$output);
		$funcNode->appendChild($resNode);
		
		$this->resDOM->save(wsResultsXml);
		
		return $resNode;
	}
	
8385c27c   Elena.Budnik   interim commit
60
	public function getResOutputName($function_name,$user,$suffix,$extension)
b8502f4d   Elena.Budnik   getStatus(), thro...
61
62
	{
		$outputFile = WSRESULT.$function_name."_".$user;
8385c27c   Elena.Budnik   interim commit
63
64
		if (isset($suffix))
			$outputFile .= ("_".$suffix);
b8502f4d   Elena.Budnik   getStatus(), thro...
65
66
67
68
69
70
		if (isset($extension))
			$outputFile .= (".".$extension);
		else
			$outputFile .= ".xml";
		return $outputFile;
	}
16035364   Benjamin Renard   First commit
71
72
73
74
}

class WebServer
{
b8502f4d   Elena.Budnik   getStatus(), thro...
75
	private $isSoap = false;
4bdd7ad9   Elena.Budnik   interim commit
76
77
	private $userID, $userPWD, $sessionID, $IPclient;
// 	private $wsUserMgr;
8385c27c   Elena.Budnik   interim commit
78
	private $resultMgr;
b8502f4d   Elena.Budnik   getStatus(), thro...
79
	private $dataFileName;
8385c27c   Elena.Budnik   interim commit
80
81
	private $requestManager = null;
	private $paramLoader = null;
4bc7749a   Elena.Budnik   getParameter (sim...
82
	private $service;
8a92ee19   Elena.Budnik   timeTobatch speci...
83
	
b8502f4d   Elena.Budnik   getStatus(), thro...
84
85
	function __construct() 
	{
a55dc57a   Elena.Budnik   interim commit
86
		if (!is_dir(WSConfigClass::getWsResultDir())) mkdir(WSConfigClass::getWsResultDir(), 0775);
8385c27c   Elena.Budnik   interim commit
87
		// $this->resultMgr = new WebResultMgr();
b8502f4d   Elena.Budnik   getStatus(), thro...
88
89
90
91
92
93
94
95
96
97
98
	}
	
//     [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

8385c27c   Elena.Budnik   interim commit
99
	protected function init($data) 
b8502f4d   Elena.Budnik   getStatus(), thro...
100
101
102
103
104
105
106
107
	{
		if(is_object($data)){
			$vars = get_object_vars($data);
			$this->isSoap = true; 
		}
		else {
			$vars = $data;
		}
8f6112a7   Nathanael Jourdane   Reformat webserver
108

b8502f4d   Elena.Budnik   getStatus(), thro...
109
110
111
112
113
114
115
116
117
118
119
120
121
		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';
8a92ee19   Elena.Budnik   timeTobatch speci...
122
		
b8502f4d   Elena.Budnik   getStatus(), thro...
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
		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;
16035364   Benjamin Renard   First commit
138

b8502f4d   Elena.Budnik   getStatus(), thro...
139
140
		return "PP".mt_rand($nb_min,$nb_max);
	}
8f6112a7   Nathanael Jourdane   Reformat webserver
141

b8502f4d   Elena.Budnik   getStatus(), thro...
142
143
144
145
146
147
148
149
/**
 *  Function getIPclient return the IP client sent a request for needs DD scripts (DDHtmlLogin, DDCheckUser, DD_Search)
 *
 *       @param   void
 *       @return  string  
 */
	private  function getIPclient()
	{
4bdd7ad9   Elena.Budnik   interim commit
150
		return $this->wsUserMgr->getIPClient();
b8502f4d   Elena.Budnik   getStatus(), thro...
151
	}
8f6112a7   Nathanael Jourdane   Reformat webserver
152

b8502f4d   Elena.Budnik   getStatus(), thro...
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
	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);
		}
	}
8f6112a7   Nathanael Jourdane   Reformat webserver
170

b8502f4d   Elena.Budnik   getStatus(), thro...
171
172
	protected function initUserMgr() 
	{
4bdd7ad9   Elena.Budnik   interim commit
173
174
		$wsUserMgr = new WSUserMgr();
		$wsUserMgr->init($this->userID, $this->userPWD, $this->sessionID, $this->isSoap);
b8502f4d   Elena.Budnik   getStatus(), thro...
175
		
4bdd7ad9   Elena.Budnik   interim commit
176
		$this->IPclient = $wsUserMgr->getIPClient();
4bc7749a   Elena.Budnik   getParameter (sim...
177
		
b8502f4d   Elena.Budnik   getStatus(), thro...
178
179
		return array('success' => true);
	}
8f6112a7   Nathanael Jourdane   Reformat webserver
180

b8502f4d   Elena.Budnik   getStatus(), thro...
181
182
	public function getTimeTablesList($data) 
	{
b8502f4d   Elena.Budnik   getStatus(), thro...
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
		$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');
8f6112a7   Nathanael Jourdane   Reformat webserver
200

b8502f4d   Elena.Budnik   getStatus(), thro...
201
202
203
204
205
206
207
208
209
210
211
212
213
		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');
8f6112a7   Nathanael Jourdane   Reformat webserver
214

b8502f4d   Elena.Budnik   getStatus(), thro...
215
		$outDOM->save($ttListWSresult);
8f6112a7   Nathanael Jourdane   Reformat webserver
216

b8502f4d   Elena.Budnik   getStatus(), thro...
217
		$wsres = $this->resultMgr->addResult(__FUNCTION__,$vars,$this->userID,$ttListWSresult);
8f6112a7   Nathanael Jourdane   Reformat webserver
218

b8502f4d   Elena.Budnik   getStatus(), thro...
219
		$ttListResult = 'http://'.str_replace(BASE_PATH,$_SERVER['SERVER_NAME'].APACHE_ALIAS,$ttListWSresult);
8f6112a7   Nathanael Jourdane   Reformat webserver
220

b8502f4d   Elena.Budnik   getStatus(), thro...
221
		$timeTablesList = array('success' => true, 'TimeTablesList' => $ttListResult);
8f6112a7   Nathanael Jourdane   Reformat webserver
222

b8502f4d   Elena.Budnik   getStatus(), thro...
223
224
		return $timeTablesList;
	}
8f6112a7   Nathanael Jourdane   Reformat webserver
225

b8502f4d   Elena.Budnik   getStatus(), thro...
226
227
228
	public function getTimeTable($data) 
	{
		$res = $this->init($data);
8f6112a7   Nathanael Jourdane   Reformat webserver
229

b8502f4d   Elena.Budnik   getStatus(), thro...
230
231
		$vars = $res['vars'];
		$ttID = $vars['ttID'];
8f6112a7   Nathanael Jourdane   Reformat webserver
232

b8502f4d   Elena.Budnik   getStatus(), thro...
233
234
235
236
237
238
		if ($this->userID == 'impex') {
			$sharedObjMgr = new SharedObjectsMgr();
			$ttSrc = $sharedObjMgr->getDataFilePath('timeTable', $ttID);
		}
		else
			$ttSrc = USERPATH.$this->userID.'/TT/'.$ttID.'.xml';
8f6112a7   Nathanael Jourdane   Reformat webserver
239

b8502f4d   Elena.Budnik   getStatus(), thro...
240
241
242
		if (!file_exists($ttSrc)) {
			$this->throwError("workspaceError", "No such table ".$ttID.".xml");
		}
8f6112a7   Nathanael Jourdane   Reformat webserver
243

b8502f4d   Elena.Budnik   getStatus(), thro...
244
		$ttWSresult = $this->resultMgr->getResOutputName(__FUNCTION__,$this->userID,$ttID);
8f6112a7   Nathanael Jourdane   Reformat webserver
245

b8502f4d   Elena.Budnik   getStatus(), thro...
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
		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'];

8385c27c   Elena.Budnik   interim commit
278
279
		$locParamSrc = USERWSDIR.'/LocalParams.xml'; 
		$wsParamSrc = USERWSDIR.'/WsParams.xml';
b8502f4d   Elena.Budnik   getStatus(), thro...
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
		$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));
	}
8f6112a7   Nathanael Jourdane   Reformat webserver
301

b8502f4d   Elena.Budnik   getStatus(), thro...
302
303
304
305
306
307
308
309
310
	public function getPlot($data) 
	{
		$res = $this->init($data);
		$resMgr = $this->initUserMgr();
		
		$vars = $res['vars'];
		$mission = $vars["missionID"];

		$ID = $this->setID();        // unique JobID
8a92ee19   Elena.Budnik   timeTobatch speci...
311
		$resDirName = WSRESULT.$ID;  // Define a temporary  directory for results
b8502f4d   Elena.Budnik   getStatus(), thro...
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368

		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",
8a92ee19   Elena.Budnik   timeTobatch speci...
369
				"axis-range-extend" => true
b8502f4d   Elena.Budnik   getStatus(), thro...
370
371
372
373
374
375
			);
			$panelObject->{"axes"}[] = $timeAxisObject;

			$yAxisObject = (Object) array(
				"id" => "y-left",
				"axis-type" => "y-left",
8a92ee19   Elena.Budnik   timeTobatch speci...
376
				"axis-range-extend" => true
b8502f4d   Elena.Budnik   getStatus(), thro...
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
			);
			$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 {
4bdd7ad9   Elena.Budnik   interim commit
400
			$plotResult = $this->requestManager->runIHMRequest($this->userID, $this->IPclient, FunctionTypeEnumClass::PARAMS, $requestObject);
b8502f4d   Elena.Budnik   getStatus(), thro...
401
402
403
		} catch (Exception $e) {
				$this->throwError("plotError", "Exeption detected : ".$e->getMessage());
		}
8f6112a7   Nathanael Jourdane   Reformat webserver
404

b8502f4d   Elena.Budnik   getStatus(), thro...
405
406
		return array('success' => true, 'plotDirectoryURL' => $ID);
	}
8f6112a7   Nathanael Jourdane   Reformat webserver
407

b8502f4d   Elena.Budnik   getStatus(), thro...
408
409
410
411
412
413
414
415
416
417
418
419
420
	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);
	}
8f6112a7   Nathanael Jourdane   Reformat webserver
421

4bc7749a   Elena.Budnik   getParameter (sim...
422
423
424
/*
*   get status for jobs in batch
*/
d9c16908   Elena.Budnik   getStatus SOAP
425
	public function getStatus($data) 
b8502f4d   Elena.Budnik   getStatus(), thro...
426
	{
d9c16908   Elena.Budnik   getStatus SOAP
427
428
		$result = $this->init($data);
		
d9c16908   Elena.Budnik   getStatus SOAP
429
430
		$id = $result['vars']['id'];
		
a55dc57a   Elena.Budnik   interim commit
431
432
		if (!isset($this->requestManager))
			$this->requestManager = new RequestManagerClass();
b8502f4d   Elena.Budnik   getStatus(), thro...
433
			
00dedb86   Elena.Budnik   getUrlFinishedJob
434
435
		try 
		{
4bc7749a   Elena.Budnik   getParameter (sim...
436
			$res = $this->requestManager->runWSRequest('nobody', 'nobody', FunctionTypeEnumClass::PROCESSGETINFO, null, $id);
00dedb86   Elena.Budnik   getUrlFinishedJob
437
438
439
440
441
		} 
		catch (Exception $e) 
		{
// 			if ($e->getMessage() == "Exception detected : Request execution error  : Cannot get process from id" )
// 			{
4bc7749a   Elena.Budnik   getParameter (sim...
442
				// after first getStatus() call  process is deleted
00dedb86   Elena.Budnik   getUrlFinishedJob
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
				$jobsManager = new WSJobsManagerClass();
				
				try 
				{
					$res = $jobsManager->getResultFromProcessId($id);
					if (!$res['success']) {
						$this->throwError("processError","Cannot retrieve process $id info");
					}
					
					return  array('success' => true, 'status' => 'done',  'dataFileURLs' => WSConfigClass::getUrl().$res['result']);
				} 
				catch (Exception $e) 
				{
					$this->throwError("getResultFromProcessIdError", "Exception detected : ".$e->getMessage());
				}
//			}
// 			else 
// 			{
// 				$this->throwError("getStatusError", "Exception detected : ".$e->getMessage());
// 			}
a55dc57a   Elena.Budnik   interim commit
463
		}
4bdd7ad9   Elena.Budnik   interim commit
464
		
b8502f4d   Elena.Budnik   getStatus(), thro...
465
466
467
		if (!$res['success']) {
			$this->throwError("processError","Cannot retrieve process $id info");
		}
a55dc57a   Elena.Budnik   interim commit
468
469
470

		if ($res['status'] == 'in_progress') {
			return array('success' => true, 'status' => 'in progress');
b8502f4d   Elena.Budnik   getStatus(), thro...
471
472
		}
		
a55dc57a   Elena.Budnik   interim commit
473
474
		if ($res['error']) {
			$this->throwError("processError","Process $id error code");
b8502f4d   Elena.Budnik   getStatus(), thro...
475
		}
4bdd7ad9   Elena.Budnik   interim commit
476
477
478
479
480
481
482
483
484
485
486
487
488
	
//     [success] => 1
//     [id] => process_jckrDz_1520873370_11632
//     [name] => download_1520873382
//     [status] => done
//     [jobType] => download
//     [info] =>  imf
//     [start] => 12-03-2018 16:49:30
//     [stop] => 12-03-2018 16:51:49
//     [folder] => DDfqlbZr_
//     [result] => download_imf_1484352000_1494806400.txt
//     [format] => 
//     [compression] => 0
4bc7749a   Elena.Budnik   getParameter (sim...
489
		$this->deleteProcess($res['id']);
4bdd7ad9   Elena.Budnik   interim commit
490
		return  array('success' => true, 'status' => $res['status'],  'dataFileURLs' => WSConfigClass::getUrl().$res['result']);
b8502f4d   Elena.Budnik   getStatus(), thro...
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
	}
	
	
	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));
	}
	
4bc7749a   Elena.Budnik   getParameter (sim...
527
528
529
/*
*   generate AUTH token for access to REST services 
*/
b8502f4d   Elena.Budnik   getStatus(), thro...
530
531
532
533
534
535
536
	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);
	}
8f6112a7   Nathanael Jourdane   Reformat webserver
537

b8502f4d   Elena.Budnik   getStatus(), thro...
538
539
540
541
542
/*
*   getParameter 
*/
	public function getParameter($data) 
	{
8385c27c   Elena.Budnik   interim commit
543
		$res = $this->init($data);
b8502f4d   Elena.Budnik   getStatus(), thro...
544
    
b8502f4d   Elena.Budnik   getStatus(), thro...
545
546
547
		if (!$res['success']){
			$this->throwError("requestError", "Cannot parse request"); 
		}
8f6112a7   Nathanael Jourdane   Reformat webserver
548

4bc7749a   Elena.Budnik   getParameter (sim...
549
		$this->initUserMgr();
4bdd7ad9   Elena.Budnik   interim commit
550

b8502f4d   Elena.Budnik   getStatus(), thro...
551
		$vars = $res['vars'];
8f6112a7   Nathanael Jourdane   Reformat webserver
552

8a92ee19   Elena.Budnik   timeTobatch speci...
553
		if (strtotime($vars["stopTime"]) <= strtotime($vars["startTime"])){
b8502f4d   Elena.Budnik   getStatus(), thro...
554
555
			$this->throwError("requestError", "Requested time interval should be greater than 0");
		}
4bdd7ad9   Elena.Budnik   interim commit
556
		
b8502f4d   Elena.Budnik   getStatus(), thro...
557
558
559
560
561
562
563
564
565
566
567
568
		$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"];
4bc7749a   Elena.Budnik   getParameter (sim...
569
570
571
572
573
574
575

		if (!$vars["stream"])
			$stream = 0;
		else
			$stream = $vars["stream"];
			
		$this->service = strtolower(__FUNCTION__);
b8502f4d   Elena.Budnik   getStatus(), thro...
576
577
578
579

		$res = $this->doDownloadRequest(
					array("startTime" => $vars["startTime"], "stopTime" => $vars["stopTime"], "sampling" => $vars["sampling"]),
					array("params" => $paramId),
4bdd7ad9   Elena.Budnik   interim commit
580
					array("format" => $vars["outputFormat"], "timeFormat"=> $timeFormat, "gzip"=>$gzip, "stream"=>$stream));
8a92ee19   Elena.Budnik   timeTobatch speci...
581
 
b8502f4d   Elena.Budnik   getStatus(), thro...
582
583
584
		if ($res['success']) 
			return $res;
	
8a92ee19   Elena.Budnik   timeTobatch speci...
585
		$this->throwError("serverError", $res['message']);   	
b8502f4d   Elena.Budnik   getStatus(), thro...
586
587
588
589
590
591
592
	}
	
/*
*   get Orbites
*/ 
	public function getOrbites($data) 
	{
b8502f4d   Elena.Budnik   getStatus(), thro...
593
		$res = $this->init($data);
8f6112a7   Nathanael Jourdane   Reformat webserver
594

b8502f4d   Elena.Budnik   getStatus(), thro...
595
		$resMgr = $this->initUserMgr();
16035364   Benjamin Renard   First commit
596

b8502f4d   Elena.Budnik   getStatus(), thro...
597
598
599
		if (!$resMgr['success']){
			$this->throwError("serverError", "Cannot init user manager");
		}
16035364   Benjamin Renard   First commit
600

b8502f4d   Elena.Budnik   getStatus(), thro...
601
		$vars = $res['vars'];
8f6112a7   Nathanael Jourdane   Reformat webserver
602

8a92ee19   Elena.Budnik   timeTobatch speci...
603
		if (strtotime($vars["stopTime"]) <= strtotime($vars["startTime"])){
b8502f4d   Elena.Budnik   getStatus(), thro...
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
			$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 {
b8502f4d   Elena.Budnik   getStatus(), thro...
629
630
631
			$this->throwError("requestError", $orbitesParam['message']);
		}
     
8a92ee19   Elena.Budnik   timeTobatch speci...
632
		$dataFileName = $this->getDataFileName($orbitesParam);
8f6112a7   Nathanael Jourdane   Reformat webserver
633

b8502f4d   Elena.Budnik   getStatus(), thro...
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
		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),
4bdd7ad9   Elena.Budnik   interim commit
657
					array("format" => $vars["outputFormat"], "timeFormat"=> $timeFormat, "gzip"=>$gzip, "stream"=>$stream));
b8502f4d   Elena.Budnik   getStatus(), thro...
658
659
660
661
662
663
664
665
666
667
668
 	 
		if ($res['success']) return $res;
 
		$this->throwError("serverError",$res['message']);    
	}
  
/*
*   get Dataset
*/
	public function getDataset($data) 
	{
b8502f4d   Elena.Budnik   getStatus(), thro...
669
670
671
		$res = $this->init($data);
		
		$resMgr = $this->initUserMgr();
8f6112a7   Nathanael Jourdane   Reformat webserver
672

b8502f4d   Elena.Budnik   getStatus(), thro...
673
		$vars = $res['vars'];
8f6112a7   Nathanael Jourdane   Reformat webserver
674

8a92ee19   Elena.Budnik   timeTobatch speci...
675
		if (strtotime($vars["stopTime"]) <= strtotime($vars["startTime"])){
b8502f4d   Elena.Budnik   getStatus(), thro...
676
677
678
			$this->throwError("requestError", "Requested time interval should be greater than 0");
		}
          
8a92ee19   Elena.Budnik   timeTobatch speci...
679
		$dataFileName = $this->getDataFileName($vars, true);
8f6112a7   Nathanael Jourdane   Reformat webserver
680

b8502f4d   Elena.Budnik   getStatus(), thro...
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
		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);

8a92ee19   Elena.Budnik   timeTobatch speci...
700
			$dataFileName = $this->getDataFileName($vars, true);
b8502f4d   Elena.Budnik   getStatus(), thro...
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722

			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: 
			}
		}
16035364   Benjamin Renard   First commit
723

b8502f4d   Elena.Budnik   getStatus(), thro...
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
		$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),
4bdd7ad9   Elena.Budnik   interim commit
743
					array("format" => $vars["outputFormat"], "timeFormat"=> $timeFormat, "gzip"=>$gzip, "stream"=>$stream));
b8502f4d   Elena.Budnik   getStatus(), thro...
744
745
746
747
748
  
		if ($res['success']) return $res;

		$this->throwError("serverError", $res['message']); 
	}
8f6112a7   Nathanael Jourdane   Reformat webserver
749

b8502f4d   Elena.Budnik   getStatus(), thro...
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
	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) 
	{
bae6f5da   Nathanael Jourdane   bugFix fileName f...
786
787
		switch ($fileFormat) {
			case 'netCDF' :
b8502f4d   Elena.Budnik   getStatus(), thro...
788
				$this->throwError("serverError", "netCDF format not implemented");
bae6f5da   Nathanael Jourdane   bugFix fileName f...
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
				break;
			case 'VOTable' :
				$fileFormat = "vot";
				$kernelExtension = ".vot";
				$wsExtension = ".xml";
				break;
			case 'ASCII' :
			default :
				$fileFormat = "ASCII";
				$kernelExtension = ".txt";
				$wsExtension = ".txt";
		}

		switch ($timeFormat) {
			case 'unixtime' :
				$timeFormat = 'Timestamp';
				break;
			default :
				$timeFormat = 'YYYY-MM-DDThh:mm:ss';
		}

		if ($gzip == 1) {
			$compression = "gzip";
			$kernelExtension .= ".gz";
			$wsExtension .= ".gz";
		} else
			$compression = "";

    	return ['success'         => true,
		        'kernelExtension' => $kernelExtension,
		        'wsExtension'     => $wsExtension,
		        'fileFormat'      => $fileFormat,
		        'timeFormat'      => $timeFormat,
		        'compression'     => $compression];
	}
16035364   Benjamin Renard   First commit
824

4bdd7ad9   Elena.Budnik   interim commit
825
	protected function doDownloadRequest($interval, $paramList, $formatInfo) 
b8502f4d   Elena.Budnik   getStatus(), thro...
826
	{
b8502f4d   Elena.Budnik   getStatus(), thro...
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
		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'];
			}
4bdd7ad9   Elena.Budnik   interim commit
856
			else {
b8502f4d   Elena.Budnik   getStatus(), thro...
857
858
				$param->paramid = $paramId;
			}
b8502f4d   Elena.Budnik   getStatus(), thro...
859
860
			$params[] = $param;
		}
8385c27c   Elena.Budnik   interim commit
861

b8502f4d   Elena.Budnik   getStatus(), thro...
862
		$obj = (object)array(
8a92ee19   Elena.Budnik   timeTobatch speci...
863
						"sampling" => $interval['sampling'],
8a92ee19   Elena.Budnik   timeTobatch speci...
864
865
866
						"startDate" => $interval['startTime'],
						"stopDate" => $interval['stopTime'],
						"list" => $params,
4bdd7ad9   Elena.Budnik   interim commit
867
868
869
						"fileformat" => $formatInfo['format'],
						"timeformat" => $formatInfo['timeFormat'],
						"compression" => $formatInfo['gzip']
8385c27c   Elena.Budnik   interim commit
870
871
			);	
			
b8502f4d   Elena.Budnik   getStatus(), thro...
872
873
		if (!isset($this->requestManager))
			$this->requestManager = new RequestManagerClass();
8385c27c   Elena.Budnik   interim commit
874
		 
b8502f4d   Elena.Budnik   getStatus(), thro...
875
		try {
4bc7749a   Elena.Budnik   getParameter (sim...
876
			$downloadResult = $this->requestManager->runWSRequest($this->userID, $this->IPclient, FunctionTypeEnumClass::PARAMS, $this->service, $obj);
b8502f4d   Elena.Budnik   getStatus(), thro...
877
		} catch (Exception $e) {
8385c27c   Elena.Budnik   interim commit
878
			$this->throwError("executionError", "Exception detected : ".$e->getMessage()); 
b8502f4d   Elena.Budnik   getStatus(), thro...
879
880
881
882
883
884
885
		}
			
		if (!$downloadResult['success']) {
			$this->throwError("serverError", $downloadResult['message']);
		}
		
		if($downloadResult['status'] == 'in_progress') {
8385c27c   Elena.Budnik   interim commit
886
887
888
			return ['success' => true, 'status' => 'in progress', 'id' => $downloadResult['id']];
		} elseif ($downloadResult['status'] == 'done') 
		{
4bc7749a   Elena.Budnik   getParameter (sim...
889
			$this->deleteProcess($downloadResult['id']);
4bdd7ad9   Elena.Budnik   interim commit
890
			return array('success' => true, 'status' => 'done', 'dataFileURLs' => WSConfigClass::getUrl().$downloadResult['result']);
b8502f4d   Elena.Budnik   getStatus(), thro...
891
892
893
894
895
		} else {
			return ['success' => false, 'message' => 'Unknown status ' . $downloadResult['status']];
		} 
	}
	
4bc7749a   Elena.Budnik   getParameter (sim...
896
897
898
899
900
901
/*
* delete process after execution : 
*         delete temporary files/folders ( JOBS/process_xxxx, RES/DDxxx ); 
*         delete job node in processManager.xml
*/
	private function deleteProcess($id)
b8502f4d   Elena.Budnik   getStatus(), thro...
902
	{
4bdd7ad9   Elena.Budnik   interim commit
903
		$obj = (object)array('id' => $id);
b8502f4d   Elena.Budnik   getStatus(), thro...
904
905
906
907
   
		if (!isset($this->requestManager))
			$this->requestManager = new RequestManagerClass();

4bdd7ad9   Elena.Budnik   interim commit
908
		try {
4bc7749a   Elena.Budnik   getParameter (sim...
909
			$downloadResult = $this->requestManager->runWSRequest($this->userID, $this->IPclient, FunctionTypeEnumClass::PROCESSDELETE, null, $obj);
4bdd7ad9   Elena.Budnik   interim commit
910
		} catch (Exception $e) {
4bc7749a   Elena.Budnik   getParameter (sim...
911
			$this->throwError("deleteProcessError", $e->getMessage());
4bdd7ad9   Elena.Budnik   interim commit
912
		}
b8502f4d   Elena.Budnik   getStatus(), thro...
913
	}
8a92ee19   Elena.Budnik   timeTobatch speci...
914
915

	protected function getDataFileName($vars, $multiParam = false)
b8502f4d   Elena.Budnik   getStatus(), thro...
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
	{
		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);
		}
	}
16035364   Benjamin Renard   First commit
942
}
1ec5d7bd   Benjamin Renard   WS getParameter, ...
943
?>