Blame view

php/classes/WebServer.php 43.6 KB
16035364   Benjamin Renard   First commit
1
<?php
8f6112a7   Nathanael Jourdane   Reformat webserver
2
3
4
5
6
7
/**
 * @file WebServer.php
 * @brief  Web services AMDA
 *
 * @version $Id: WebServer.php 2968 2015-06-29 13:17:00Z natacha $
 */
47ef4864   Nathanael Jourdane   Set timeLimit in ...
8

16035364   Benjamin Renard   First commit
9
10
class WebResultMgr
{
8f6112a7   Nathanael Jourdane   Reformat webserver
11
12
13
14
15
16
17
    private $resDOM;
    private $rootEl;
    private $resXP;
    private $requestManager = null;
    private $paramLoader = null;

    function __construct()
16035364   Benjamin Renard   First commit
18
    {
8f6112a7   Nathanael Jourdane   Reformat webserver
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
        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;
16035364   Benjamin Renard   First commit
38
    }
8f6112a7   Nathanael Jourdane   Reformat webserver
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55

    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);
16035364   Benjamin Renard   First commit
56
//    $resNode->setAttribute('IP',$IP);
8f6112a7   Nathanael Jourdane   Reformat webserver
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
        $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;
    }
16035364   Benjamin Renard   First commit
77
78
79
80
}

class WebServer
{
8f6112a7   Nathanael Jourdane   Reformat webserver
81
82
83
84
85
86
87
    private $isSoap = false;
    private $userID, $userPWD, $sessionID;
    private $wsUserMgr;
    private $resultMgr, $myParamsInfoMgr;
    private $dataFileName;

    function __construct()
16035364   Benjamin Renard   First commit
88
    {
8f6112a7   Nathanael Jourdane   Reformat webserver
89
90
91
92
93
        $this->userID = 'impex';
        $this->userPWD = 'impexfp7';
        $this->sessionID = $this->userID;
        $this->myParamsInfoMgr = new ParamsInfoMgr();
        $this->resultMgr = new WebResultMgr();
16035364   Benjamin Renard   First commit
94
    }
16035364   Benjamin Renard   First commit
95

8f6112a7   Nathanael Jourdane   Reformat webserver
96
    protected function init($data)
16035364   Benjamin Renard   First commit
97
    {
8f6112a7   Nathanael Jourdane   Reformat webserver
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
        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';
e5ab198f   Nathanael Jourdane   simple getStatus
115

8f6112a7   Nathanael Jourdane   Reformat webserver
116
        return array('success' => true, 'vars' => $vars);
16035364   Benjamin Renard   First commit
117
    }
8f6112a7   Nathanael Jourdane   Reformat webserver
118
119
120
121
122
123
124
125
126
127
128

    private function setID()
    {

        $nb_min = 10000;
        $nb_max = 99999;
        $nombre = mt_rand($nb_min, $nb_max);

        $this->IP = $this->getIPclient();

        return "PP" . $nombre;
16035364   Benjamin Renard   First commit
129
    }
16035364   Benjamin Renard   First commit
130

8f6112a7   Nathanael Jourdane   Reformat webserver
131
132
133
134
135
136
137
138
    /**
     *  Function getIPclient return the IP client sent a request for needs DD scripts (DDHtmlLogin, DDCheckUser, DD_Search)
     *
     * @param   void
     * @return  string
     */
    private function getIPclient()
    {
16035364   Benjamin Renard   First commit
139

8f6112a7   Nathanael Jourdane   Reformat webserver
140
141
142
143
144
145
146
        if (getenv('REMOTE_ADDR')) {
            $realIP = getenv('REMOTE_ADDR');
        } else {
            //get local IP
            $command = "hostname -i";
            $realIP = exec($command);
        }
16035364   Benjamin Renard   First commit
147

8f6112a7   Nathanael Jourdane   Reformat webserver
148
149
        return $realIP;
    }
16035364   Benjamin Renard   First commit
150

8f6112a7   Nathanael Jourdane   Reformat webserver
151
152
    private function timeInterval2Days($TimeInterval)
    {
16035364   Benjamin Renard   First commit
153

8f6112a7   Nathanael Jourdane   Reformat webserver
154
        $divDays = 60 * 60 * 24;
16035364   Benjamin Renard   First commit
155
        $nbDays = floor($TimeInterval / $divDays);
8f6112a7   Nathanael Jourdane   Reformat webserver
156
157
158
159
        $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;
16035364   Benjamin Renard   First commit
160

8f6112a7   Nathanael Jourdane   Reformat webserver
161
162
163
164
        $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
16035364   Benjamin Renard   First commit
165

8f6112a7   Nathanael Jourdane   Reformat webserver
166
        return $DD . ':' . $HH . ':' . $MM . ':' . $SS;
16035364   Benjamin Renard   First commit
167
168
169

    }

8f6112a7   Nathanael Jourdane   Reformat webserver
170
171
172
    /* Start Time into AMDA format YYYY:DOY-1:HH:MM:SS */
    private function startTime2Days($startTime)
    {
16035364   Benjamin Renard   First commit
173

8f6112a7   Nathanael Jourdane   Reformat webserver
174
175
176
177
        $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"]);
16035364   Benjamin Renard   First commit
178
179
180
        return $date_start;
    }

8f6112a7   Nathanael Jourdane   Reformat webserver
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
    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);
16035364   Benjamin Renard   First commit
196
        }
16035364   Benjamin Renard   First commit
197
198
    }

8f6112a7   Nathanael Jourdane   Reformat webserver
199
    protected function initUserMgr()
16035364   Benjamin Renard   First commit
200
    {
f2fdd679   Nathanael Jourdane   fix php warnings
201
        if (isset($this->wsUserMgr)) {
8f6112a7   Nathanael Jourdane   Reformat webserver
202
            return array('success' => true);
f2fdd679   Nathanael Jourdane   fix php warnings
203
204
        }
        $this->wsUserMgr = new WSUserMgr($this->userID, $this->userPWD, $this->sessionID);
8f6112a7   Nathanael Jourdane   Reformat webserver
205
        $this->wsUserMgr->init($this->userID, $this->userPWD, $this->sessionID, $this->isSoap);
16035364   Benjamin Renard   First commit
206

8f6112a7   Nathanael Jourdane   Reformat webserver
207
        return array('success' => true);
16035364   Benjamin Renard   First commit
208
    }
16035364   Benjamin Renard   First commit
209

8f6112a7   Nathanael Jourdane   Reformat webserver
210
211
212
213
214
215
216
217
218
219
220
    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");
        }
16035364   Benjamin Renard   First commit
221

16035364   Benjamin Renard   First commit
222

8f6112a7   Nathanael Jourdane   Reformat webserver
223
224
        $res = $this->init($data);
        $vars = $res['vars'];
16035364   Benjamin Renard   First commit
225

8f6112a7   Nathanael Jourdane   Reformat webserver
226
        $ttListWSresult = $this->resultMgr->getResOutputName(__FUNCTION__, $this->userID);
16035364   Benjamin Renard   First commit
227

8f6112a7   Nathanael Jourdane   Reformat webserver
228
229
230
231
232
233
        $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');
16035364   Benjamin Renard   First commit
234

8f6112a7   Nathanael Jourdane   Reformat webserver
235
236
237
238
        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");
        }
16035364   Benjamin Renard   First commit
239

8f6112a7   Nathanael Jourdane   Reformat webserver
240
        $timetabNode = $dom->documentElement->getElementsByTagName('timetabList');
16035364   Benjamin Renard   First commit
241

8f6112a7   Nathanael Jourdane   Reformat webserver
242
243
244
245
246
247
248
        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;
16035364   Benjamin Renard   First commit
249

8f6112a7   Nathanael Jourdane   Reformat webserver
250
251
        $newNode = $outDOM->importNode($timetabNode->item(0), TRUE);
        $outDOM->appendChild($newNode);
16035364   Benjamin Renard   First commit
252

16035364   Benjamin Renard   First commit
253

8f6112a7   Nathanael Jourdane   Reformat webserver
254
255
256
257
258
259
260
261
262
263
264
265
266
        $outXP = new domxpath($outDOM);
        $ttNodes = $outXP->query('//timetab');

        $outDOM->save($ttListWSresult);

        $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;

16035364   Benjamin Renard   First commit
267
268
    }

8f6112a7   Nathanael Jourdane   Reformat webserver
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
    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);

        $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));
16035364   Benjamin Renard   First commit
303

16035364   Benjamin Renard   First commit
304
    }
8f6112a7   Nathanael Jourdane   Reformat webserver
305
306
307
308
309
310


    public function isAlive()
    {
        $res = $this->init($data);
        return true;
16035364   Benjamin Renard   First commit
311
    }
8f6112a7   Nathanael Jourdane   Reformat webserver
312
313
314
315
316
317
318
319
320
321
322
323


    public function getObsDataTree()
    {

        $res = $this->init();

        $resMgr = $this->initUserMgr();

        $vars = $res['vars'];

        $locParamSrc = USERPATH . $this->userID . '/WS/LocalParams.xml';
16035364   Benjamin Renard   First commit
324
//     $remoteParamSrc = USERPATH.$this->userID.'/WS/RemoteParams.xml';
8f6112a7   Nathanael Jourdane   Reformat webserver
325
326
        $wsParamSrc = USERPATH . $this->userID . '/WS/WsParams.xml';
        $locParamResult = $this->resultMgr->getResOutputName(__FUNCTION__, $this->userID . '_' . 'LocalParams');
16035364   Benjamin Renard   First commit
327
//     $remoteParamResult = $this->resultMgr->getResOutputName(__FUNCTION__,'RemoteParams');
8f6112a7   Nathanael Jourdane   Reformat webserver
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
        $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);
        }
16035364   Benjamin Renard   First commit
355
//     if (!copy($remoteParamSrc,$remoteParamResult))
f2fdd679   Nathanael Jourdane   fix php warnings
356
// 	$remoteParamResult = '';
8f6112a7   Nathanael Jourdane   Reformat webserver
357
358
359
360
        if (!copy($wsParamSrc, $wsParamResult))
            $wsParamResult = '';

        if ($locParamResult != '') $locParamResult = 'http://' . str_replace(BASE_PATH, $_SERVER['SERVER_NAME'] . APACHE_ALIAS, $locParamResult);
16035364   Benjamin Renard   First commit
361
//     if ($remoteParamResult !='') $remoteParamResult = 'http://'.str_replace(BASE_PATH,$_SERVER['SERVER_NAME'].APACHE_ALIAS,$remoteParamResult);
8f6112a7   Nathanael Jourdane   Reformat webserver
362
363
364
365
366
367
368
369
370
371
        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, 'WorkSpace' => array("LocalDataBaseParameters" => $locParamResult, "RemoteDataBaseParameters" => $remoteParamResult));
363cacdd   Benjamin Renard   use new Kernel fo...
372
    }
8f6112a7   Nathanael Jourdane   Reformat webserver
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478

    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;

        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);
363cacdd   Benjamin Renard   use new Kernel fo...
479
    }
aa94fd24   elena   Merge with last svn
480

8f6112a7   Nathanael Jourdane   Reformat webserver
481
482
483
484
485
486
487
488
489
490
491
492
493
    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);

aa94fd24   elena   Merge with last svn
494
    }
aa94fd24   elena   Merge with last svn
495

bae6f5da   Nathanael Jourdane   bugFix fileName f...
496
    public function getStatus($id) {
e5ab198f   Nathanael Jourdane   simple getStatus
497
498
499
500
501
502
503
        $obj = (object)array(
            "username" => $this->userID,
            "password" => $this->userPWD,
            "sessionID" => $this->sessionID
        );

        $aa = new AmdaAction();
9b69cb35   Nathanael Jourdane   Implement batch m...
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
        $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
//	    }

bae6f5da   Nathanael Jourdane   bugFix fileName f...
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
	    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);
			    }
9b69cb35   Nathanael Jourdane   Implement batch m...
538
539
		    }
	    }
9b69cb35   Nathanael Jourdane   Implement batch m...
540
	    return ['success' => false, 'message' => 'No job found for this id.'];
e5ab198f   Nathanael Jourdane   simple getStatus
541
    }
16035364   Benjamin Renard   First commit
542

8f6112a7   Nathanael Jourdane   Reformat webserver
543
544
545
546
    public function getParameterList($data)
    {

        $res = $this->init($data);
16035364   Benjamin Renard   First commit
547

8f6112a7   Nathanael Jourdane   Reformat webserver
548
        $resMgr = $this->initUserMgr();
16035364   Benjamin Renard   First commit
549

8f6112a7   Nathanael Jourdane   Reformat webserver
550
        $vars = $res['vars'];
16035364   Benjamin Renard   First commit
551

8f6112a7   Nathanael Jourdane   Reformat webserver
552
        $locParamSrc = USERPATH . $this->userID . '/WS/LocalParams.xml';
16035364   Benjamin Renard   First commit
553
//     $remoteParamSrc = USERPATH.$this->userID.'/WS/RemoteParams.xml';
8f6112a7   Nathanael Jourdane   Reformat webserver
554
555
        $wsParamSrc = USERPATH . $this->userID . '/WS/WsParams.xml';
        $locParamResult = $this->resultMgr->getResOutputName(__FUNCTION__, $this->userID . '_' . 'LocalParams');
16035364   Benjamin Renard   First commit
556
//     $remoteParamResult = $this->resultMgr->getResOutputName(__FUNCTION__,'RemoteParams');
8f6112a7   Nathanael Jourdane   Reformat webserver
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
        $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);
        }
16035364   Benjamin Renard   First commit
583
//     if (!copy($remoteParamSrc,$remoteParamResult))
f2fdd679   Nathanael Jourdane   fix php warnings
584
// 	$remoteParamResult = '';
8f6112a7   Nathanael Jourdane   Reformat webserver
585
586
587
588
        if (!copy($wsParamSrc, $wsParamResult))
            $wsParamResult = '';

        if ($locParamResult != '') $locParamResult = 'http://' . str_replace(BASE_PATH, $_SERVER['SERVER_NAME'] . APACHE_ALIAS, $locParamResult);
16035364   Benjamin Renard   First commit
589
//     if ($remoteParamResult !='') $remoteParamResult = 'http://'.str_replace(BASE_PATH,$_SERVER['SERVER_NAME'].APACHE_ALIAS,$remoteParamResult);
8f6112a7   Nathanael Jourdane   Reformat webserver
590
        if ($wsParamResult != '') $wsParamResult = 'http://' . str_replace(BASE_PATH, $_SERVER['SERVER_NAME'] . APACHE_ALIAS, $wsParamResult);
16035364   Benjamin Renard   First commit
591

8f6112a7   Nathanael Jourdane   Reformat webserver
592
593
594
595
        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");
        }
16035364   Benjamin Renard   First commit
596

8f6112a7   Nathanael Jourdane   Reformat webserver
597
        $wsres = $this->resultMgr->addResult(__FUNCTION__, $vars, $this->userID, $wsParamResult . ";" . $locParamResult . ";" . $remoteParamResult);
16035364   Benjamin Renard   First commit
598

8f6112a7   Nathanael Jourdane   Reformat webserver
599
600
        return array('success' => true, 'ParameterList' => array("UserDefinedParameters" => $wsParamResult, "LocalDataBaseParameters" => $locParamResult, "RemoteDataBaseParameters" => $remoteParamResult));
    }
6104c71e   Nathanael Jourdane   Replace function ...
601

8f6112a7   Nathanael Jourdane   Reformat webserver
602
603
    public function getNewToken()
    {
bae6f5da   Nathanael Jourdane   bugFix fileName f...
604
605
606
	    require_once(INTEGRATION_SRC_DIR."RequestManager.php");

	    $timeStamp = (new DateTime())->getTimestamp();
8f6112a7   Nathanael Jourdane   Reformat webserver
607
608
609
610
        // generate token from timeStamp and some salt
        $newToken = md5(1321 * (int)($timeStamp / timeLimitQuery));
        return array('success' => true, 'token' => $newToken);
    }
6104c71e   Nathanael Jourdane   Replace function ...
611

16035364   Benjamin Renard   First commit
612
///////////////////////////////////////START GET DATASET   ///////////////////////////////
8f6112a7   Nathanael Jourdane   Reformat webserver
613
614
    public function getParameter($data)
    {
8f6112a7   Nathanael Jourdane   Reformat webserver
615
        $multiParam = false;
16035364   Benjamin Renard   First commit
616

8f6112a7   Nathanael Jourdane   Reformat webserver
617
618
        $res = $this->init($data);
        $resMgr = $this->initUserMgr();
16035364   Benjamin Renard   First commit
619

8f6112a7   Nathanael Jourdane   Reformat webserver
620
621
622
623
        if (!$res['success']) {
            if ($this->isSoap) throw new SoapFault("server01", "Cannot init user manager");
            else return array('success' => false, 'message' => "Cannot init user manager");
        }
16035364   Benjamin Renard   First commit
624

8f6112a7   Nathanael Jourdane   Reformat webserver
625
        $vars = $res['vars'];
16035364   Benjamin Renard   First commit
626

8f6112a7   Nathanael Jourdane   Reformat webserver
627
628
629
630
631
632
633
        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");
        }
16035364   Benjamin Renard   First commit
634

8f6112a7   Nathanael Jourdane   Reformat webserver
635
636
637
638
639
640
641
        $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']);
        }
16035364   Benjamin Renard   First commit
642
643


8f6112a7   Nathanael Jourdane   Reformat webserver
644
645
        $paramId = array();
        array_push($paramId, $vars["parameterID"]);
16035364   Benjamin Renard   First commit
646
647
//     $paramId[] = $vars["parameterID"];

f2fdd679   Nathanael Jourdane   fix php warnings
648
649
650
651
652
        $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;
8f6112a7   Nathanael Jourdane   Reformat webserver
653
654

        $res = $this->doDownloadRequest(
f2fdd679   Nathanael Jourdane   fix php warnings
655
                array("startTime" => $vars["startTime"], "stopTime" => $vars["stopTime"], "sampling" => $sampling),
8f6112a7   Nathanael Jourdane   Reformat webserver
656
657
                array("params" => $paramId),
                array("userName" => $this->userID, "userPwd" => $this->userPWD, "sessionID" => $this->sessionID),
f2fdd679   Nathanael Jourdane   fix php warnings
658
                array("format" => $outputFormat, "timeFormat" => $timeFormat, "gzip" => $gzip, "stream" => $stream),
8f6112a7   Nathanael Jourdane   Reformat webserver
659
660
                $dataFileName);

f2fdd679   Nathanael Jourdane   fix php warnings
661
662
663
664
665
666
667
668
        if ($res['success']) {
            return $res;
        } else {
            if ($this->isSoap) {
                throw new SoapFault("request03", $res['message']);
            } else {
                return array('success' => false, 'message' => $res['message']);
            }
8f6112a7   Nathanael Jourdane   Reformat webserver
669
        }
16035364   Benjamin Renard   First commit
670
    }
8f6112a7   Nathanael Jourdane   Reformat webserver
671

16035364   Benjamin Renard   First commit
672
///////////////////////////////////////START GET ORBITES   ///////////////////////////////
8f6112a7   Nathanael Jourdane   Reformat webserver
673
674
    public function getOrbites($data)
    {
16035364   Benjamin Renard   First commit
675

8f6112a7   Nathanael Jourdane   Reformat webserver
676
        $multiParam = false;
16035364   Benjamin Renard   First commit
677

8f6112a7   Nathanael Jourdane   Reformat webserver
678
        $res = $this->init($data);
16035364   Benjamin Renard   First commit
679

8f6112a7   Nathanael Jourdane   Reformat webserver
680
        $resMgr = $this->initUserMgr();
16035364   Benjamin Renard   First commit
681

8f6112a7   Nathanael Jourdane   Reformat webserver
682
683
684
685
        if (!$resMgr['success']) {
            if ($this->isSoap) throw new SoapFault("server01", "Cannot init user manager");
            else return array('success' => false, 'message' => "Cannot init user manager");
        }
16035364   Benjamin Renard   First commit
686

8f6112a7   Nathanael Jourdane   Reformat webserver
687
        $vars = $res['vars'];
16035364   Benjamin Renard   First commit
688

8f6112a7   Nathanael Jourdane   Reformat webserver
689
690
691
692
693
694
695
        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");
        }
16035364   Benjamin Renard   First commit
696

16035364   Benjamin Renard   First commit
697

8f6112a7   Nathanael Jourdane   Reformat webserver
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
        $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
        );


        $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']);
        }


        $dataFileName = $this->getDataFileName($orbitesParam, $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']);
        }

        array_push($paramId, $orbParam);
16035364   Benjamin Renard   First commit
734
735
//     $paramId[] = $vars["parameterID"];

8f6112a7   Nathanael Jourdane   Reformat webserver
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
        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;
        else {
            if ($this->isSoap) throw new SoapFault("request03", $res['message']);
            else return array('success' => false, 'message' => $res['message']);
        }
16035364   Benjamin Renard   First commit
759
    }
8f6112a7   Nathanael Jourdane   Reformat webserver
760

16035364   Benjamin Renard   First commit
761
762
763
///////////////////////////////////////START GET DATASET   ///////////////////////////////


8f6112a7   Nathanael Jourdane   Reformat webserver
764
765
766
767
768
    public function getDataset($data)
    {
        $multiParam = true;

        $res = $this->init($data);
16035364   Benjamin Renard   First commit
769

8f6112a7   Nathanael Jourdane   Reformat webserver
770
        $resMgr = $this->initUserMgr();
16035364   Benjamin Renard   First commit
771

8f6112a7   Nathanael Jourdane   Reformat webserver
772
        $vars = $res['vars'];
16035364   Benjamin Renard   First commit
773

8f6112a7   Nathanael Jourdane   Reformat webserver
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
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
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
        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);

8f6112a7   Nathanael Jourdane   Reformat webserver
847
848
849
850
851
        if ($res['success']) return $res;
        else {
            if ($this->isSoap) throw new SoapFault("request03", $res['message']);
            else return array('success' => false, 'message' => $res['message']);
        }
16035364   Benjamin Renard   First commit
852
    }
16035364   Benjamin Renard   First commit
853

8f6112a7   Nathanael Jourdane   Reformat webserver
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
////////////////////////////////////////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");
        }
16035364   Benjamin Renard   First commit
886
    }
16035364   Benjamin Renard   First commit
887

bae6f5da   Nathanael Jourdane   bugFix fileName f...
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
	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");
				}
				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
931

8f6112a7   Nathanael Jourdane   Reformat webserver
932
933
934
935
936
937
938
    protected function doDownloadRequest($interval, $paramList, $user, $formatInfo, $dataFileName)
    {
        if ($interval['sampling'])
            $structure = 0;// sampling
        else
            $structure = 2;   // not sampling

bae6f5da   Nathanael Jourdane   bugFix fileName f...
939
	    $fileInfo = $this->getFormatInfo($formatInfo['format'], $formatInfo['timeFormat'], $formatInfo['gzip']);
8f6112a7   Nathanael Jourdane   Reformat webserver
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983

        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(
                "nodeType" => "download",
                "downloadSrc" => "0",
                "structure" => $structure,
                "refparamSampling" => false,
                "sampling" => $interval['sampling'],
                "timesrc" => "Interval",
                "startDate" => $interval['startTime'],
                "stopDate" => $interval['stopTime'],
                "list" => $params,
bae6f5da   Nathanael Jourdane   bugFix fileName f...
984
985
986
987
988
989
                "fileformat" => $fileInfo['fileFormat'],
                "timeformat" => $fileInfo['timeFormat'],
                "compression" => $fileInfo['compression'],
	            "extension" => $fileInfo['wsExtension'],
                "disablebatch" => false,
	            "dataFileName" => $this->dataFileName
8f6112a7   Nathanael Jourdane   Reformat webserver
990
991
992
993
994
995
        );

        if (!isset($this->requestManager))
            $this->requestManager = new RequestManagerClass();

        try {
bae6f5da   Nathanael Jourdane   bugFix fileName f...
996
	        $downloadResult = $this->requestManager->runIHMRequest($this->userID, $this->getIPclient(), FunctionTypeEnumClass::PARAMS, $obj);
8f6112a7   Nathanael Jourdane   Reformat webserver
997
998
999
1000
1001
1002
1003
1004
1005
1006
        } 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']);
        }

9b69cb35   Nathanael Jourdane   Implement batch m...
1007
1008
1009
        if($downloadResult['status'] == 'in_progress') {
	        return ['success' => true, 'status' => 'in_progress', 'id' => $downloadResult['id']];
        } elseif ($downloadResult['status'] == 'done') {
bae6f5da   Nathanael Jourdane   bugFix fileName f...
1010
1011
1012
	        $resTempFilePath = USERPATH . $this->userID . '/RES/' . $downloadResult['folder'] . '/' . $downloadResult['result'] . $fileInfo['kernelExtension'];
	        $resOutputFilePath = WSRESULT.$this->dataFileName.$fileInfo['wsExtension'];
	        return $this->finishDownloadRequest($downloadResult['id'], $resTempFilePath, $resOutputFilePath);
9b69cb35   Nathanael Jourdane   Implement batch m...
1013
1014
        } else {
	        return ['success' => false, 'message' => 'Unknown status ' . $downloadResult['status'] . '.'];
8f6112a7   Nathanael Jourdane   Reformat webserver
1015
        }
9b69cb35   Nathanael Jourdane   Implement batch m...
1016
    }
8f6112a7   Nathanael Jourdane   Reformat webserver
1017

bae6f5da   Nathanael Jourdane   bugFix fileName f...
1018
	private function finishDownloadRequest($id, $resTempFilePath, $resOutputFilePath)
9b69cb35   Nathanael Jourdane   Implement batch m...
1019
    {
bae6f5da   Nathanael Jourdane   bugFix fileName f...
1020
1021
		if (!file_exists($resTempFilePath)) {
		    if ($this->isSoap) throw new SoapFault("server04", 'Cannot retrieve result file ' . $resTempFilePath);
9b69cb35   Nathanael Jourdane   Implement batch m...
1022
1023
1024
		    else return ['success' => false, 'message' => 'Cannot retrieve result file'];
	    }

bae6f5da   Nathanael Jourdane   bugFix fileName f...
1025
1026
1027
	    rename($resTempFilePath, $resOutputFilePath);
	    chmod($resOutputFilePath, 0664);
	    $outputURL = 'http://' . str_replace(BASE_PATH, $_SERVER['SERVER_NAME'] . APACHE_ALIAS, $resOutputFilePath);
9b69cb35   Nathanael Jourdane   Implement batch m...
1028

bae6f5da   Nathanael Jourdane   bugFix fileName f...
1029
1030
		$obj = (object)array(
		    'id' => $id
9b69cb35   Nathanael Jourdane   Implement batch m...
1031
1032
	    );

bae6f5da   Nathanael Jourdane   bugFix fileName f...
1033
1034
1035
1036
	    require_once(INTEGRATION_SRC_DIR . "RequestManager.php");
	    if (!isset($this->requestManager))
		    $this->requestManager = new RequestManagerClass();

9b69cb35   Nathanael Jourdane   Implement batch m...
1037
1038
1039
	    try {
		    $downloadResult = $this->requestManager->runIHMRequest($this->userID, $this->getIPclient(), FunctionTypeEnumClass::PROCESSDELETE, $obj);
	    } catch (Exception $e) {
bae6f5da   Nathanael Jourdane   bugFix fileName f...
1040
	    	error_log("Can not delete file $resOutputFilePath: $e");
9b69cb35   Nathanael Jourdane   Implement batch m...
1041
1042
1043
	    }

	    return array('success' => true, 'status' => 'done', 'dataFileURLs' => $outputURL);
16035364   Benjamin Renard   First commit
1044
    }
16035364   Benjamin Renard   First commit
1045

8f6112a7   Nathanael Jourdane   Reformat webserver
1046
1047
    protected function timeIntervalToDuration($startTime, $stopTime)
    {
8f6112a7   Nathanael Jourdane   Reformat webserver
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
        $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))
16035364   Benjamin Renard   First commit
1060
        );
8f6112a7   Nathanael Jourdane   Reformat webserver
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
    }

    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);
16035364   Benjamin Renard   First commit
1086
        }
16035364   Benjamin Renard   First commit
1087
    }
8f6112a7   Nathanael Jourdane   Reformat webserver
1088

bae6f5da   Nathanael Jourdane   bugFix fileName f...
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
	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.'];
		}

		$fileFormat = $requestXml->getElementsByTagName('fileFormat')->item(0)->nodeValue;
		$timeFormat = $requestXml->getElementsByTagName('timeFormat')->item(0)->nodeValue;
		$gzip = 0; // todo $requestXml->getElementsByTagName('gzip')->item(0)->nodeValue;

		// 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');

		$ddStart    = $requestXml->getElementsByTagName('startTime')->item(0)->nodeValue;
		$ddInterval = $requestXml->getElementsByTagName('timeInterval')->item(0)->nodeValue;
		$vars['startTime'] = $cc->DDTimeToIso($ddStart);
		$vars['stopTime'] = $cc->DDStartIntervalToStopIso($ddStart, $ddInterval);

		$sampling = $requestXml->getElementsByTagName('sampling')->item(0);
		if (!is_null($sampling))
			$vars['sampling'] = $sampling->nodeValue;

		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.'];
		}

		$getDataFileName = $this->getDataFileName($vars, false);
		if (!$getDataFileName['success']) {
			return $getDataFileName;
		}
		$vars['dataFileName'] = $getDataFileName['fileName'];

		return $vars;
	}

	private function compress($srcName, $dstName)
8f6112a7   Nathanael Jourdane   Reformat webserver
1135
1136
1137
1138
1139
1140
1141
1142
1143
    {

        $fp = fopen($srcName, "r");
        $data = fread($fp, filesize($srcName));
        fclose($fp);

        $zp = gzopen($dstName, "w9");
        gzwrite($zp, $data);
        gzclose($zp);
16035364   Benjamin Renard   First commit
1144
1145
1146
    }

}
8f6112a7   Nathanael Jourdane   Reformat webserver
1147

1ec5d7bd   Benjamin Renard   WS getParameter, ...
1148
?>