Commit 090d1bc7c0956772aa28680e540f482d4a9834a5

Authored by Elena Budnik
2 parents e1e55d6e 42356ea1

Merge branch 'fix-import' into 'master'

Fix import

See merge request !19
js/.eslintrc.yml
... ... @@ -7,18 +7,17 @@ plugins:
7 7 - extjs
8 8 rules:
9 9 indent: [error, 2, SwitchCase: 1]
10   - semi: [warn, never]
  10 + semi: [error, always]
11 11 max-len: [error, code: 120]
12   - max-lines: [error, 600]
  12 + max-lines: [warn, 600]
13 13 linebreak-style: [error, unix]
14 14 quotes: [error, single]
15 15 strict: [error, global]
16 16 quote-props: [error, as-needed]
17 17 max-statements: [warn, 20]
18   - array-bracket-newline: [warn, consistent]
19 18 consistent-this: [error, me]
20 19 padded-blocks: off
21   - no-tabs: off
  20 + newline-per-chained-call: [error, ignoreChainWithDepth: 3]
22 21 no-warning-comments: off
23 22 func-names: off
24 23 function-paren-newline: off
... ...
php/classes/AmdaAction.php
... ... @@ -594,6 +594,9 @@ class AmdaAction
594 594 */
595 595 public function getUploadedObject($name, $format, $nodeType)
596 596 {
  597 + $fileContent = preg_replace(['~\R~u', "/\t/"], ["\n", ' '], trim(file_get_contents(USERTEMPDIR . $name)));
  598 + file_put_contents(USERTEMPDIR . $name, $fileContent);
  599 +
597 600 switch ($nodeType)
598 601 {
599 602 case 'timeTable' :
... ...
php/classes/FilesMgr.php
... ... @@ -277,9 +277,9 @@ class FilesMgr extends AmdaObjectMgr
277 277 $handler = fopen($this->fileName, 'r');
278 278 if ($handler) {
279 279 while (!feof($handler) && !$StartTime) {
280   - $oneLine = trim(fgets($handler));
281   - $elems = explode(" ", preg_replace('/\s+/', ' ', $oneLine));
282   - if ((strlen($elems[0]) < 16) || !($time = strtotime($elems[0]))) {
  280 + $oneLine = trim(preg_replace('/\s+/', ' ', fgets($handler)));
  281 + $elems = explode(' ', $oneLine);
  282 + if ((strlen($elems[0]) < 16) || !($time = strtotime($elems[0]))) {
283 283 $i++;
284 284 continue;
285 285 }
... ... @@ -291,8 +291,9 @@ class FilesMgr extends AmdaObjectMgr
291 291  
292 292 if (feof($handler)) return -10;
293 293  
294   - $oneLine = trim(fgets($handler));
295   - $elems = explode(" ",$oneLine);
  294 + $oneLine = trim(preg_replace('/\s+/', ' ', fgets($handler)));
  295 + $elems = explode(' ',$oneLine);
  296 +
296 297 if (count($elems) < 2) return -10;
297 298  
298 299 // dT else Array
... ... @@ -313,8 +314,8 @@ class FilesMgr extends AmdaObjectMgr
313 314 if ($handler) {
314 315 $i = 0;
315 316 while (!feof($handler) && !$StartTime) {
316   - $oneLine = trim(fgets($handler));
317   - $elems = explode(" ", preg_replace('/\s+/', ' ', $oneLine));
  317 + $oneLine = trim(preg_replace('/\s+/', ' ', fgets($handler)));
  318 + $elems = explode(' ',$oneLine);
318 319 if (strlen($elems[0]) < 16 || !($time = strtotime($elems[0]))) {
319 320 $i++;
320 321 continue;
... ... @@ -327,8 +328,8 @@ class FilesMgr extends AmdaObjectMgr
327 328 }
328 329  
329 330 if (feof($handle)) return array(-10);
330   - $oneLine = trim(fgets($handler));
331   - $elems = explode(" ",$oneLine);
  331 + $oneLine = trim(preg_replace('/\s+/', ' ', fgets($handler)));
  332 + $elems = explode(' ',$oneLine);
332 333 if (count($elems) < 2) return array (-1);
333 334 // dT else Array
334 335 if (!($time = strtotime($elems[0])))
... ... @@ -340,8 +341,9 @@ class FilesMgr extends AmdaObjectMgr
340 341  
341 342 while (!feof($handler))
342 343 {
343   - $oneLine = trim(fgets($handler));
344   - $elems = explode(" ",$oneLine);
  344 + $oneLine = trim(preg_replace('/\s+/', ' ', fgets($handler)));
  345 + $elems = explode(' ',$oneLine);
  346 +
345 347 if (count($elems) < 2) continue;
346 348 $StartTime = $time;
347 349 if (!($time = strtotime($elems[0]))) return array(-1);
... ... @@ -374,8 +376,9 @@ class FilesMgr extends AmdaObjectMgr
374 376 $i = 0;
375 377 while (!$StartTime && !feof($handler))
376 378 {
377   - $oneLine = trim(fgets($handler));
378   - $elems = explode(" ", preg_replace('/\s+/', ' ', $oneLine));
  379 + $oneLine = trim(preg_replace('/\s+/', ' ', fgets($handler)));
  380 + $elems = explode(' ',$oneLine);
  381 +
379 382 if (!($time = strtotime($elems[0])))
380 383 {
381 384 $offset = ftell($handler);
... ... @@ -388,9 +391,10 @@ class FilesMgr extends AmdaObjectMgr
388 391 }
389 392  
390 393 $newfile = fopen(USERDATADIR."temp", "w");
391   -
392   - $oneLine = trim(fgets($handler));
393   - $elems = explode(" " , $oneLine);
  394 +
  395 + $oneLine = trim(preg_replace('/\s+/', ' ', fgets($handler)));
  396 + $elems = explode(' ',$oneLine);
  397 +
394 398 // dT
395 399 if (!($time = strtotime($elems[0])))
396 400 {
... ... @@ -400,8 +404,8 @@ class FilesMgr extends AmdaObjectMgr
400 404 $newtime += $dt;
401 405  
402 406 while (!feof($handler))
403   - {
404   - $oneLine = trim(fgets($handler));
  407 + {
  408 + $oneLine = trim(preg_replace('/\s+/', ' ', fgets($handler)));
405 409 if ($oneLine != PHP_EOL && count($elems) > 0) fwrite($newfile, $newtime." ".$oneLine.PHP_EOL);
406 410 $newtime += $dt;
407 411 }
... ... @@ -411,9 +415,9 @@ class FilesMgr extends AmdaObjectMgr
411 415 {
412 416 fseek($handler, $offset);
413 417 while (!feof($handler))
414   - {
415   - $oneLine = trim(fgets($handler));
416   - $elems = explode(" " ,$oneLine);
  418 + {
  419 + $oneLine = trim(preg_replace('/\s+/', ' ', fgets($handler)));
  420 + $elems = explode(' ',$oneLine);
417 421 // empty lines
418 422 if (count($elems) < 2) continue;
419 423 $newtime = strtotime($elems[0]);
... ... @@ -461,18 +465,18 @@ class FilesMgr extends AmdaObjectMgr
461 465 $newfile = fopen(USERDATADIR."temp", "w");
462 466 while (!feof($handle))
463 467 {
464   - if (($oneLine = fgets($handle)) !== false)
  468 + $oneLine = trim(preg_replace('/\s+/', ' ', fgets($handle)));
  469 +
  470 + if ($oneLine !== false)
465 471 {
466   - $line = $timeLength == 'auto' ? $line = trim(preg_replace('/\s+/', ' ', $oneLine)) : trim($oneLine);
467   -
468   - if (strlen($line) > $formatLength)
  472 + if (strlen($oneLine) > $formatLength)
469 473 {
470 474 try
471 475 {
472   - $date = DateTime::createFromFormat($timeFormat, trim(substr($line,0,$formatLength)));
  476 + $date = DateTime::createFromFormat($timeFormat, trim(substr($oneLine,0,$formatLength)));
473 477 if (!$date)
474 478 {
475   - if (strpos($line,'#') === 0) fwrite($newfile, $line.PHP_EOL);
  479 + if (strpos($oneLine,'#') === 0) fwrite($newfile, $oneLine.PHP_EOL);
476 480 }
477 481 else
478 482 {
... ... @@ -480,7 +484,7 @@ class FilesMgr extends AmdaObjectMgr
480 484 if ($doy) {
481 485 $date->modify('-1 day');
482 486 }
483   - $suffix = preg_replace('/\s+/', ' ',substr($line, $formatLength));
  487 + $suffix = preg_replace('/\s+/', ' ',substr($oneLine, $formatLength));
484 488 fwrite($newfile,$date->format('Y-m-d')."T".$date->format('H:i:s').$suffix.PHP_EOL);
485 489 }
486 490 }
... ... @@ -490,7 +494,7 @@ class FilesMgr extends AmdaObjectMgr
490 494 }
491 495 }
492 496 else
493   - if (strpos($line,'#') === 0) fwrite($newfile,$line.PHP_EOL);
  497 + if (strpos($oneLine,'#') === 0) fwrite($newfile,$oneLine.PHP_EOL);
494 498 }
495 499 }
496 500 }
... ... @@ -501,7 +505,7 @@ class FilesMgr extends AmdaObjectMgr
501 505 fclose($handle);
502 506 unlink($this->fileName);
503 507 }
504   - return $false;
  508 + return false;
505 509 }
506 510  
507 511 fclose($newfile);
... ...
php/classes/TimeTableMgr.php
... ... @@ -7,46 +7,38 @@
7 7 *
8 8 */
9 9  
10   -function timeFormat($myString)
11   -{
12   - if (format == "Y z H i s") {
13   - $tt = getdate(strtotime($myString));
14   - return sprintf("%04d",$tt["year"])." "
15   - .sprintf("%03d",$tt["yday"]+1)." "
16   - .sprintf("%02d",$tt["hours"])." "
17   - .sprintf("%02d",$tt["minutes"])." "
18   - .sprintf("%02d",$tt["seconds"]);
19   - }
20   - return date(format,strtotime($myString));
21   -}
22   -
23 10 class TimeTableMgr extends AmdaObjectMgr
24   -{
25   - function __construct($user = NULL, $sharedObject = FALSE)
  11 +{
  12 + /**
  13 + * TimeTableMgr constructor.
  14 + * @param null $user The user
  15 + * @param bool $sharedObject Shared object
  16 + */
  17 + public function __construct($user = null, $sharedObject = false)
26 18 {
27 19 parent::__construct('Tt.xml');
28 20 $this->contentRootId = 'timeTable-treeRootNode';
29 21 $this->contentRootTag = 'timetabList';
30   - $this->attributes = array('name' => '', 'intervals' => '');
31   - $this->optionalAttributes = array();
  22 + $this->attributes = ['name' => '', 'intervals' => ''];
  23 + $this->optionalAttributes = [];
32 24 $this->objTagName = 'timetab';
33 25 $this->id_prefix = 'tt_';
34 26  
35 27 if (!$sharedObject && !file_exists($this->xmlName)) {
36   - $this->createDom();
37   - $this->xp = new domxpath($this->contentDom);
  28 + $this->createDom();
  29 + $this->xp = new domxpath($this->contentDom);
38 30 }
39 31 }
40   -
41   - protected function createDom()
  32 +
  33 + protected function createDom()
42 34 {
43   - $types = array('timetab' => 'timeTable', 'catalog' => 'catalog');
  35 + $types = ['timetab' => 'timeTable', 'catalog' => 'catalog'];
44 36  
45 37 $rootElement = $this->contentDom->createElement('ws');
46   -
  38 +
47 39 foreach ($types as $key => $value) {
48   - $contentId = $value.'-treeRootNode';
49   - $contentTag = $key.'List';
  40 + $contentId = $value . '-treeRootNode';
  41 + $contentTag = $key . 'List';
50 42 $typeElement = $this->contentDom->createElement($contentTag);
51 43 $typeElement->setAttribute('xml:id', $contentId);
52 44 $rootElement->appendChild($typeElement);
... ... @@ -55,363 +47,600 @@ class TimeTableMgr extends AmdaObjectMgr
55 47 $this->contentDom->save($this->xmlName);
56 48 }
57 49  
58   - /*
59   - * rename Time Table in id.xml
60   - */
61   - protected function renameInResource($name, $id)
  50 + /**
  51 + * Get object
  52 + * @param $id
  53 + * @param $nodeType
  54 + * @return array
  55 + */
  56 + public function getObject($id, $nodeType = null)
62 57 {
63   - if (!file_exists(USERTTDIR.$id.'.xml')) return false;
  58 + if (substr($nodeType, 0, 6) == 'shared') {
  59 + //Shared object
  60 + $sharedObjMgr = new SharedObjectsMgr();
  61 + $path = $sharedObjMgr->getDataFilePath(str_replace('shared', '', $nodeType), $id);
  62 + } else {
  63 + $path = USERTTDIR . $id . '.xml';
  64 + }
64 65  
65   - $this->objectDom -> load(USERTTDIR.$id.'.xml');
66   - if (!($objToRename = $this->objectDom->getElementById($id))) return false;
67   - $objToRename -> getElementsByTagName('name')->item(0)->nodeValue = $name;
68   - $this->objectDom ->save(USERTTDIR.$id.'.xml');
69   -
70   - return true;
  66 + if (!file_exists($path)) {
  67 + return ['error' => NO_OBJECT_FILE];
  68 + }
  69 + $this->objectDom->load($path);
  70 + if (!($objToGet = $this->objectDom->getElementById($id))) {
  71 + return ['error' => NO_SUCH_ID];
  72 + }
  73 + $attributesToReturn['id'] = $objToGet->getAttribute('xml:id');
  74 + $attributes = $objToGet->childNodes;
  75 +
  76 + $nbInt = 0;
  77 + foreach ($attributes as $attribute) {
  78 + if ($attribute->nodeType == XML_ELEMENT_NODE) {
  79 + /*if ($attribute->tagName == 'intervals') {
  80 + $start = $attribute -> getElementsByTagName('start')->item(0) -> nodeValue;
  81 + $stop = $attribute -> getElementsByTagName('stop')->item(0) -> nodeValue;
  82 + $attributesToReturn['intervals'][] = array('start' => $start, 'stop' => $stop);
  83 + }
  84 + else
  85 + $attributesToReturn[$attribute->tagName] = $attribute->nodeValue;*/
  86 + //BRE - load all except intervals - Intervals will be loaded later with 'loadIntervalsFromTT' function
  87 + if ($attribute->tagName != 'intervals') {
  88 + $attributesToReturn[$attribute->tagName] = $attribute->nodeValue;
  89 + } else {
  90 + $nbInt++;
  91 + }
  92 + }
  93 + }
  94 + $attributesToReturn['nbIntervals'] = $nbInt;
  95 +
  96 + return $attributesToReturn;
71 97 }
72 98  
73   - protected function deleteParameter($id)
  99 + /**
  100 + * Modify an object
  101 + * @param $p
  102 + * @return array
  103 + */
  104 + public function modifyObject($p)
74 105 {
75   - if (file_exists(USERTTDIR.$id.'.xml')) unlink(USERTTDIR.$id.'.xml');
  106 + $folder = $this->getObjectFolder($p->id);
  107 +
  108 + //Copy TT in a tempory file
  109 + $ttFilePath = USERTTDIR . $p->id . '.xml';
  110 + $tmpFileExist = false;
  111 + if (file_exists($ttFilePath)) {
  112 + $tmpFileExist = copy($ttFilePath, $ttFilePath . ".tmp");
  113 + }
  114 +
  115 + //Delete TT
  116 + $this->deleteObject($p);
  117 +
  118 + //Save modifications
  119 + try {
  120 + $result = $this->createObject($p, $folder);
  121 + if ($result['error']) {
  122 + throw new Exception($result['error']);
  123 + }
  124 + if ($tmpFileExist) {
  125 + unlink($ttFilePath . ".tmp");
  126 + }
  127 + return ['id' => $p->id, 'info' => $result['info']];
  128 + } catch (Exception $exception) {
  129 + //Restore TT file
  130 + if ($tmpFileExist) {
  131 + copy($ttFilePath . ".tmp", $ttFilePath);
  132 + unlink($ttFilePath . ".tmp");
  133 + }
  134 + return ['error' => $exception->getMessage()];
  135 + }
76 136 }
77 137  
78   - /*
79   - * Check if difference is name and info only
80   - */
81   - protected function renameOnly($p) {
82   - //if (!($p->intervals)) return true;
83   - return false;
  138 + /**
  139 + * Create an object
  140 + * @param $p
  141 + * @param $folder
  142 + * @return array
  143 + */
  144 + public function createObject($p, $folder)
  145 + {
  146 + if ($p->leaf) {
  147 + $result = $this->createParameter($p, $folder);
  148 + if ($result['error']) {
  149 + return $result;
  150 + }
  151 + $cacheMgr = new TimeTableCacheMgr();
  152 + if (isset($p->cacheToken) && ($p->cacheToken != '')) {
  153 + $resultSaveInt = $cacheMgr->saveInTT($result['id'], "update", $p->cacheToken);
  154 + if (!$resultSaveInt['success']) {
  155 + if ($resultSaveInt['message']) {
  156 + return ['error' => $resultSaveInt['message']];
  157 + } else {
  158 + return ['error' => 'Unknown error during intervals save'];
  159 + }
  160 + }
  161 + }
  162 + return $result;
  163 + } else {
  164 + return ['error' => 'createFolder should be called from RENAME'];
  165 + // return $this->createFolder($p);
  166 + // TODO check if this is possible?
  167 + }
84 168 }
85   -
86   - /*
87   - * In case of catalogs
88   - */
89   - protected function setParamDescription($param) { }
90 169  
91   -
92   - /*
93   - * Create Time Table
  170 + /**
  171 + * Create parameter (in case of catalogs)
  172 + * @param $p
  173 + * @param $folder
  174 + * @return array
94 175 */
95 176 protected function createParameter($p, $folder)
96 177 {
97   - if ($this -> objectExistsByName($p->name)) {
98   - $p -> id = $this -> getObjectIdByName($p->name);
99   - $this -> deleteObject($p);
  178 + if ($this->objectExistsByName($p->name)) {
  179 + $p->id = $this->getObjectIdByName($p->name);
  180 + $this->deleteObject($p);
100 181 }
101   -
  182 +
102 183 $this->id = $this->setId();
103 184 $this->created = date('Y-m-d\TH:i:s');
104   - if (!$this->id) return array('error' => ID_CREATION_ERROR);
105   -
106   - $this->resFileName = USERTTDIR.$this->id.'.xml';
107   - //TODO catalog root element = 'timetable'
  185 + if (!$this->id) {
  186 + return ['error' => ID_CREATION_ERROR];
  187 + }
  188 +
  189 + $this->resFileName = USERTTDIR . $this->id . '.xml';
  190 + // TODO catalog root element = 'timetable'
108 191 $rootElement = $this->objectDom->createElement('timetable');
109   - $rootElement->setAttribute('xml:id',$this->id);
110   -
111   - foreach ($p as $key => $value)
  192 + $rootElement->setAttribute('xml:id', $this->id);
  193 +
  194 + foreach ($p as $key => $value) {
112 195 if ($key != 'id' && $key != 'leaf' && $key != 'nodeType' &&
113 196 $key != 'objName' && $key != 'objFormat' && $key != 'folderId' && $key != 'cacheToken') {
114   - if ($key == 'created') {
115   - $rootElement->appendChild($this->objectDom->createElement($key, $this->created));
116   - }
117   - // it is catalog
118   - else if ($key == 'parameters') {
119   - $paramsElement = $this->setParamDescription($value);
120   - if ($paramsElement) $rootElement->appendChild($paramsElement);
121   -
  197 + if ($key == 'created') {
  198 + $rootElement->appendChild($this->objectDom->createElement($key, $this->created));
  199 + } // it is catalog
  200 + else {
  201 + if ($key == 'parameters') {
  202 + $paramsElement = $this->setParamDescription($value);
  203 + if ($paramsElement) {
  204 + $rootElement->appendChild($paramsElement);
  205 + }
  206 + } else {
  207 + if ($key != 'intervals') {
  208 + $rootElement->appendChild($this->objectDom->createElement($key, htmlspecialchars($value)));
  209 + }
122 210 }
123   - else if ($key != 'intervals')
124   - $rootElement->appendChild($this->objectDom->createElement($key, htmlspecialchars($value)));
  211 + }
125 212 }
  213 + }
126 214  
127 215 $this->objectDom->appendChild($rootElement);
128 216 $this->objectDom->save($this->resFileName);
129 217 $obj = new stdClass();
130 218 $obj->name = $p->name;
131 219 $obj->intervals = $p->nbIntervals;
132   - $this -> addToContent($obj, $folder);
133   - return array('id' => $this->id,'created' => $this->created,'info' =>$obj->intervals.' intervals' );
  220 + $this->addToContent($obj, $folder);
  221 + // FIXME field created is undefined
  222 + return ['id' => $this->id, 'created' => $this->created, 'info' => $obj->intervals . ' intervals'];
134 223 }
135 224  
136   - protected function call_intersection($fst, $snd)
  225 + /**
  226 + * Set parameter description
  227 + * TODO
  228 + * @param $param string The parameter
  229 + * @return DOMNode
  230 + */
  231 + protected function setParamDescription($param)
137 232 {
138   - $inf = ( $fst[0] > $snd[0] ) ? $fst[0] : $snd[0];
139   - $sup = ( $fst[1] < $snd[1] ) ? $fst[1] : $snd[1];
140   - if ( $inf >= $sup ) { $inter[] = array(0,0); }
141   - else {$inter[] = array($inf,$sup); }
142   - return $inter;
  233 + return new DOMNode();
143 234 }
144   -
  235 +
  236 + /**
  237 + * Get uploaded object
  238 + * @param $name
  239 + * @param $format
  240 + * @param bool $onlyDescription
  241 + * @return mixed
  242 + */
  243 + public function getUploadedObject($name, $format, $onlyDescription = false)
  244 + {
  245 + if (strpos($name, '.txt') !== false || strpos($name, '.asc') !== false || strpos($name, '.') == false) {
  246 + $attributesToReturn = $this->textToAmda(USERTEMPDIR . $name, $onlyDescription);
  247 + $attributesToReturn['objName'] = $name;
  248 + $attributesToReturn['objFormat'] = $format;
  249 +
  250 + return $attributesToReturn;
  251 + }
  252 +
  253 + if ($format == 'VOT') {
  254 + $attributesToReturn = $this->vot2amda(USERTEMPDIR . $name, $onlyDescription);
  255 + $attributesToReturn['objName'] = $name;
  256 + $attributesToReturn['objFormat'] = $format;
  257 +
  258 + return $attributesToReturn;
  259 + }
  260 +
  261 + if (strpos($name, '.xml') !== false) {
  262 + $temp = explode('.xml', $name);
  263 + $name = $temp[0];
  264 + }
  265 +
  266 + if (!file_exists(USERTEMPDIR . $name . '.xml')) {
  267 + return ['error' => 'no such name'];
  268 + }
  269 +
  270 + $this->objectDom->load(USERTEMPDIR . $name . '.xml');
  271 + if (!($objToGet = $this->objectDom->getElementsByTagName('timetable')->item(0)) &&
  272 + !($objToGet = $this->objectDom->getElementsByTagName('TimeTable')->item(0))) {
  273 + return ['error' => 'no time table'];
  274 + }
  275 +
  276 + $attributes = $objToGet->childNodes;
  277 + $attributesToReturn['name'] = $name;
  278 + $attributesToReturn['objName'] = $name;
  279 + $attributesToReturn['objFormat'] = $format;
  280 +
  281 + /** @var DOMElement $attribute */
  282 + foreach ($attributes as $attribute) {
  283 + if ($attribute->nodeType == XML_ELEMENT_NODE) {
  284 + if ($attribute->tagName == 'intervals') {
  285 + $start = $attribute->getElementsByTagName('start')->item(0)->nodeValue;
  286 + $stop = $attribute->getElementsByTagName('stop')->item(0)->nodeValue;
  287 + if (!$onlyDescription) {
  288 + $attributesToReturn['intervals'][] = ['start' => $start, 'stop' => $stop];
  289 + }
  290 + } else {
  291 + if ($attribute->tagName == 'Interval') {
  292 + $start = $attribute->getElementsByTagName('Start')->item(0)->nodeValue;
  293 + $stop = $attribute->getElementsByTagName('Stop')->item(0)->nodeValue;
  294 + if (!$onlyDescription) {
  295 + $attributesToReturn['intervals'][] = ['start' => $start, 'stop' => $stop];
  296 + }
  297 + } else {
  298 + switch (strtolower($attribute->tagName)) {
  299 + case 'created':
  300 + $attributesToReturn['created'] = $attribute->nodeValue;
  301 + break;
  302 + case 'chain':
  303 + case 'source':
  304 + $attributesToReturn['description'] = $attribute->nodeValue;
  305 + break;
  306 + default:
  307 + break;
  308 + }
  309 + }
  310 + }
  311 + }
  312 + }
  313 + return $attributesToReturn;
  314 + }
  315 +
145 316 /*
146 317 * Uploaded text file => convert to array
147 318 */
148   - protected function text2amda($tmp_file, $onlyDescription = false)
149   - {
  319 +
  320 + /**
  321 + * Convert text to AMDA attributes
  322 + * @param $tmp_file
  323 + * @param bool $onlyDescription
  324 + * @return mixed
  325 + */
  326 + protected function textToAmda($tmp_file, $onlyDescription = false)
  327 + {
150 328 $suffix = explode('.', basename($tmp_file));
151   - $lines = file($tmp_file,FILE_SKIP_EMPTY_LINES);
152   - $description="Uploaded Time Table".PHP_EOL;
  329 + $lines = file($tmp_file, FILE_SKIP_EMPTY_LINES);
  330 + $description = "Uploaded Time Table" . PHP_EOL;
153 331  
154 332 $recordsNumber = count($lines);
155 333 $descNumber = 0;
156   -
157   - foreach ($lines as $line)
158   - {
159   - if ($line[0] == '#') {
160   - $description=$description.PHP_EOL.substr($line,1,-1);
161   - }
162   - else {
163   - $date = explode(' ', trim(preg_replace('!\s+!', ' ',$line)));
164   -
165   - if (!strtotime(trim($date[0]))) {
166   - $description=$description.PHP_EOL.$line;
167   - $descNumber++;
168   - continue;
169   - }
170   - // check if it is ISO format
171   - if (!isset($isIso))
172   - $isIso = preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})$/', trim($date[0]));
173   -
174   - if (!$isIso) {
175   - // y-m-d h:m:s for example
176   - $dateLength = count($date) / 2;
177   -
178   - $tempStart = $date[0];
179   - $tempStop = $date[$dateLength];
180   -
181   - if ($dateLength > 1) {
182   - for ($i = 1; $i < $dateLength; $i++)
183   - $tempStart.= $date[$i];
184   -
185   - for ($i = $dateLength + 1; $i < $dateLength * 2; $i++)
186   - $tempStop .= $date[$i];
  334 +
  335 + foreach ($lines as $line) {
  336 + $line = preg_replace('/[-:\/\s]+/', ' ', trim($line));
  337 + if ($line[0] == '#') { // Comment
  338 + $description = $description . PHP_EOL . substr($line, 1, -1);
  339 + } else {
  340 + $isoFormat = 'Y-m-dTH:i:s';
  341 + $doyFormat = 'Y z H i s';
  342 + $doyRegex = '(\d{4}) (\d{3}) (\d{2}) (\d{2}) (\d{2})( \d{2})?';
  343 +
  344 + if (preg_match('/^' . $doyRegex . ' ' . $doyRegex . '$/', $line)) {
  345 + $start = DateTime::createFromFormat($doyFormat, substr($line, 0, 17));
  346 + $stop = DateTime::createFromFormat($doyFormat, substr($line, 18));
  347 + $startDate = $start->sub(new DateInterval('P1D'))->format($isoFormat);
  348 + $stopDate = $stop->sub(new DateInterval('P1D'))->format($isoFormat);
  349 + } else {
  350 + $dateLength = round((strlen($line)-1) / 2);
  351 +
  352 + $start = explode(' ', substr($line, 0, $dateLength) . ' 00');
  353 + $startTime = strtotime("$start[0]/$start[1]/$start[2] $start[3]:$start[4]:$start[5]");
  354 +
  355 + $stop = explode(' ', substr($line, $dateLength + 1) . ' 00');
  356 + $stopTime = strtotime("$stop[0]/$stop[1]/$stop[2] $stop[3]:$stop[4]:$stop[5]");
  357 + if (is_numeric($startTime) && is_numeric($stopTime)) {
  358 + $startDate = date($isoFormat, $startTime);
  359 + $stopDate = date($isoFormat, $stopTime);
  360 + } else {
  361 + $description = $description . PHP_EOL . $line;
  362 + $descNumber++;
  363 + continue;
187 364 }
  365 + }
188 366  
189   - $startDate = date('Y-m-d\TH:i:s',strtotime($tempStart));
190   - $stopDate = date('Y-m-d\TH:i:s',strtotime($tempStop));
191   -
192   - if (!$onlyDescription)
193   - $attributesToReturn['intervals'][] = array('start' => $startDate, 'stop' => $stopDate);
  367 + if (!$onlyDescription) {
  368 + $attributesToReturn['intervals'][] = ['start' => $startDate, 'stop' => $stopDate];
194 369 }
195   - else {
196   - if (!$onlyDescription)
197   - $attributesToReturn['intervals'][] = array('start' => trim($date[0]), 'stop' => trim($date[1]));
198   - }
199 370 }
200 371 }
201   - if ( $recordsNumber == $descNumber )
202   - $description = "Looks like we can not read your time format...".PHP_EOL.$description;
203   -
  372 + if ($recordsNumber == $descNumber) {
  373 + $description = 'Looks like we can not read your time format...' . PHP_EOL . $description;
  374 + }
  375 +
204 376 $attributesToReturn['description'] = $description;
205   - $attributesToReturn['name'] = basename($tmp_file, '.'.$suffix[1]);
  377 + $attributesToReturn['name'] = basename($tmp_file, '.' . $suffix[1]);
206 378 $attributesToReturn['created'] = date('Y-m-d\TH:i:s');
207   -
208 379 return $attributesToReturn;
209 380 }
210 381  
211   - /*
212   - * Uploaded vot TT => convert to array
213   - */
214   - protected function vot2amda($tmp_file, $onlyDescription = false) {
215   - // Load Time table
216   - $this->objectDom -> load($tmp_file);
  382 + /**
  383 + * Convert VOTable time table to AMDA attributes
  384 + * @param $tmp_file
  385 + * @param bool $onlyDescription
  386 + * @return mixed
  387 + */
  388 + protected function vot2amda($tmp_file, $onlyDescription = false)
  389 + {
  390 + // Load Time table
  391 + $this->objectDom->load($tmp_file);
217 392 $objToGet = $this->objectDom->getElementsByTagName('TABLEDATA')->item(0);
218 393 $attributesToReturn['name'] = $tmp_file;
219   - $attributes = $objToGet -> childNodes;
220   - foreach($attributes as $attribute)
  394 + $attributes = $objToGet->childNodes;
  395 +
  396 + /** @var DOMElement $attribute */
  397 + foreach ($attributes as $attribute) {
221 398 if ($attribute->tagName == 'TR') {
222   - $start = $attribute -> getElementsByTagName('TD')->item(0) -> nodeValue;
223   - $stop = $attribute -> getElementsByTagName('TD')->item(1) -> nodeValue;
224   - if (!$onlyDescription)
225   - $attributesToReturn['intervals'][] = array('start' => $start, 'stop' => $stop);
  399 + $start = $attribute->getElementsByTagName('TD')->item(0)->nodeValue;
  400 + $stop = $attribute->getElementsByTagName('TD')->item(1)->nodeValue;
  401 + if (!$onlyDescription) {
  402 + $attributesToReturn['intervals'][] = ['start' => $start, 'stop' => $stop];
  403 + }
226 404 }
227   - $suffix = explode('.', basename($tmp_file));
228   - $attributesToReturn['name'] = basename($tmp_file, '.'.$suffix[1]);
229   - $attributesToReturn['created'] = date('Y-m-d')."T".date('H:i:s');
230   - $attributesToReturn['description'] = htmlspecialchars($this->objectDom->getElementsByTagName('DESCRIPTION')->item(0) -> nodeValue);
231   - return($attributesToReturn);
  405 + }
  406 + $suffix = explode('.', basename($tmp_file));
  407 + $attributesToReturn['name'] = basename($tmp_file, '.' . $suffix[1]);
  408 + $attributesToReturn['created'] = date('Y-m-d') . "T" . date('H:i:s');
  409 + $description = $this->objectDom->getElementsByTagName('DESCRIPTION')->item(0)->nodeValue;
  410 + $attributesToReturn['description'] = htmlspecialchars($description);
  411 + return ($attributesToReturn);
232 412 }
233   -
  413 +
234 414 /*****************************************************************
235 415 * PUBLIC FUNCTIONS
236 416 *****************************************************************/
237   -
  417 +
238 418 /*
239 419 * Get Object into Edit
240 420 */
241   - function getObject($id, $nodeType) {
242   - if (substr($nodeType,0,6) == 'shared') {
243   - //Shared object
244   - $sharedObjMgr = new SharedObjectsMgr();
245   - $path = $sharedObjMgr->getDataFilePath(str_replace('shared', '', $nodeType), $id);
  421 + public function getTmpObject($folderId, $name, $onlyDescription = false)
  422 + {
  423 + $filePath = USERWORKINGDIR . $folderId . '/' . $name . '.xml';
  424 + if (!file_exists($filePath)) {
  425 + return ['error' => 'Cannot find result file'];
246 426 }
247   - else {
248   - $path = USERTTDIR.$id.'.xml';
  427 +
  428 + $dom = new DomDocument('1.0');
  429 + $dom->formatOutput = true;
  430 +
  431 + if (!$dom->load($filePath)) {
  432 + return ['error' => 'Cannot load result file'];
249 433 }
250 434  
251   - if (!file_exists($path)) return array('error' => NO_OBJECT_FILE);
252   - $this->objectDom -> load($path);
253   - if (!($objToGet = $this->objectDom->getElementById($id))) return array('error' => NO_SUCH_ID);
254   - $attributesToReturn['id'] = $objToGet->getAttribute('xml:id');
255   - $attributes = $objToGet -> childNodes;
  435 + $descNodes = $dom->getElementsByTagName('description');
  436 + if ($descNodes->length > 0) {
  437 + $attributesToReturn['description'] = $descNodes->item(0)->nodeValue;
  438 + }
256 439  
257   - $nbInt = 0;
258   - foreach($attributes as $attribute)
259   - if($attribute->nodeType == XML_ELEMENT_NODE){
260   - /*if ($attribute->tagName == 'intervals') {
261   - $start = $attribute -> getElementsByTagName('start')->item(0) -> nodeValue;
262   - $stop = $attribute -> getElementsByTagName('stop')->item(0) -> nodeValue;
263   - $attributesToReturn['intervals'][] = array('start' => $start, 'stop' => $stop);
264   - }
265   - else
266   - $attributesToReturn[$attribute->tagName] = $attribute->nodeValue;*/
267   - //BRE - load all except intervals - Intervals will be loaded later with 'loadIntervalsFromTT' function
268   - if ($attribute->tagName != 'intervals')
269   - $attributesToReturn[$attribute->tagName] = $attribute->nodeValue;
270   - else
271   - $nbInt++;
272   - }
273   -
274   - $attributesToReturn['nbIntervals'] = $nbInt;
275   -
276   - return $attributesToReturn;
277   - }
278   -
279   - public function createObject($p, $folder)
280   - {
281   - if ($p -> leaf){
282   - $result = $this->createParameter($p, $folder);
283   - if ($result['error'])
284   - return $result;
285   - $cacheMgr = new TimeTableCacheMgr();
286   - if (isset($p->cacheToken) && ($p->cacheToken != ''))
287   - {
288   - $resultSaveInt = $cacheMgr->saveInTT($result['id'], "update", $p->cacheToken);
289   - if (!$resultSaveInt['success'])
290   - {
291   - if ($resultSaveInt['message'])
292   - return array('error' => $resultSaveInt['message']);
293   - else
294   - return array('error' => 'Unknown error during intervals save');
  440 + $creatNodes = $dom->getElementsByTagName('created');
  441 + if ($creatNodes->length > 0) {
  442 + $attributesToReturn['created'] = $creatNodes->item(0)->nodeValue;
  443 + }
  444 +
  445 + $histNodes = $dom->getElementsByTagName('history');
  446 + if ($histNodes->length > 0) {
  447 + $attributesToReturn['history'] = $histNodes->item(0)->nodeValue;
  448 + }
  449 +
  450 + $attributesToReturn['objName'] = $name;
  451 + $attributesToReturn['folderId'] = $folderId;
  452 +
  453 + if (!$onlyDescription) {
  454 + $intNodes = $dom->getElementsByTagName('intervals');
  455 +
  456 + /** @var DOMElement $intNode */
  457 + foreach ($intNodes as $intNode) {
  458 + $startNodes = $intNode->getElementsByTagName('start');
  459 + if ($startNodes->length <= 0) {
  460 + return ['error' => 'Error detected in result file'];
  461 + }
  462 + $stopNodes = $intNode->getElementsByTagName('stop');
  463 + if ($stopNodes->length <= 0) {
  464 + return ['error' => 'Error detected in result file'];
295 465 }
  466 + $attributesToReturn['intervals'][] = [
  467 + 'start' => $startNodes->item(0)->nodeValue,
  468 + 'stop' => $stopNodes->item(0)->nodeValue
  469 + ];
296 470 }
297   - return $result;
298 471 }
299   - // else return $this->createFolder($p);
300   - //TODO check if this is possible?
301   - else return array('error' => 'createFolder should be called from RENAME');
  472 +
  473 + return $attributesToReturn;
302 474 }
303   -
304   -
305   - public function modifyObject($p) {
306   - $folder = $this->getObjectFolder($p->id);
307   -
308   - //Copy TT in a tempory file
309   - $ttFilePath = USERTTDIR.$p->id.'.xml';
310   - $tmpFileExist = FALSE;
311   - if (file_exists($ttFilePath))
312   - $tmpFileExist = copy($ttFilePath,$ttFilePath.".tmp");
313   -
314   - //Delete TT
315   - $this->deleteObject($p);
316   -
317   - //Save modifications
318   - try {
319   - $result = $this->createObject($p, $folder);
320   - if ($result['error'])
321   - throw new Exception($result['error']);
322   - if ($tmpFileExist)
323   - unlink($ttFilePath.".tmp");
324   - return array('id' => $p->id, 'info' => $result['info']);
  475 +
  476 + /**
  477 + * Merge time tables
  478 + * @param $obj
  479 + * @return array
  480 + */
  481 + public function merge($obj)
  482 + {
  483 + /**
  484 + * Array of intervals, used like :
  485 + * [{start:'2010-01-01T23:00:00',stop:'2011-01-01T20:00:00'},{start:'2009-01-01T23:00:00',stop:'2010-01-01T20:00:00'}]
  486 + * $attributesToReturn['intervals'][] = array('start' => $start, 'stop' => $stop);
  487 + */
  488 +
  489 + $intervals = 0;
  490 + for ($iId = 0; $iId < count($obj->ids); $iId++) {
  491 + $table[$iId] = $this->loadIntervalsFromTT($obj->ids[$iId]);
  492 + for ($jId = 0; $jId < count($table[$iId]['intervals']); $jId++) {
  493 + $interval[$iId][$jId][0] = $table[$iId]['intervals'][$jId]['start'];
  494 + $interval[$iId][$jId][1] = $table[$iId]['intervals'][$jId]['stop'];
  495 + }
  496 + $intervals += count($interval[$iId]);
325 497 }
326   - catch (Exception $e) {
327   - //Restore TT file
328   - if ($tmpFileExist)
329   - {
330   - copy($ttFilePath.".tmp", $ttFilePath);
331   - unlink($ttFilePath.".tmp");
  498 + if ($intervals > 10000) {
  499 + set_time_limit(1800);
  500 + }
  501 +
  502 + $final = [];
  503 + for ($iId = 0; $iId < count($obj->ids); $iId++) {
  504 + $final = array_merge($final, $interval[$iId]);
  505 + }
  506 + sort($final);
  507 +
  508 + // Algorithm of union
  509 + $line = 0;
  510 + $iId = 0;
  511 + $val = $final[$iId][0];
  512 + while ($iId < count($final) - 1) {
  513 + if ($final[$iId + 1][1] <= $final[$iId][1]) {
  514 + array_splice($final, $iId + 1, 1);
  515 + } else {
  516 + if (($final[$iId + 1][0] <= $final[$iId][1]) && ($final[$iId + 1][1] >= $final[$iId][1])) {
  517 + $iId++;
  518 + } else {
  519 + $start[$line] = $val;
  520 + $stop[$line] = $final[$iId][1];
  521 + $iId++;
  522 + $line++;
  523 + $val = $final[$iId][0];
  524 + }
332 525 }
333   - return array ('error' => $e->getMessage());
334 526 }
  527 + $start[$line] = $val;
  528 + $stop[$line] = $final[$iId][1];
  529 +
  530 + $objTT = new stdClass();
  531 + $objTT->name = $obj->name;
  532 + $objTT->nodeType = 'timeTable';
  533 + $objTT->leaf = true;
  534 + $objTT->created = null;
  535 + $objTT->history = $obj->history;
  536 + for ($iId = 0; $iId < count($start); $iId++) {
  537 + $inter = new stdClass();
  538 + $inter->start = $start[$iId];
  539 + $inter->stop = $stop[$iId];
  540 + $objTT->intervals[] = $inter;
  541 + }
  542 + $objTT->nbIntervals = count($start);
  543 + $this->objectDom = new DomDocument('1.0');
  544 + $this->objectDom->formatOutput = true;
  545 +
  546 + $res = $this->createParameter($objTT, $folder); // FIXME $folder is undefined
  547 + if ($res['error']) {
  548 + return $res;
  549 + }
  550 +
  551 + $this->saveIntervals($res['id'], $objTT->intervals, 'merge');
  552 + return $res;
335 553 }
336   -
337   - public function loadIntervalsFromTT($id,$typeTT,$start = NULL, $limit = NULL)
  554 +
  555 + /**
  556 + * Load intervals from time table
  557 + * @param $id
  558 + * @param $typeTT
  559 + * @param null $start
  560 + * @param null $limit
  561 + * @return array
  562 + */
  563 + public function loadIntervalsFromTT($id, $typeTT = '', $start = null, $limit = null)
338 564 {
339 565 if ($typeTT == 'sharedtimeTable') {
340 566 //Shared object
341 567 $sharedObjMgr = new SharedObjectsMgr();
342 568 $path = $sharedObjMgr->getDataFilePath('timeTable', $id);
  569 + } else {
  570 + $path = USERTTDIR . $id . '.xml';
  571 + }
  572 +
  573 + //load intervals from TT id
  574 + if (!file_exists($path)) {
  575 + return ['success' => false, 'message' => "Cannot find TT file " . $id];
343 576 }
344   - else {
345   - $path = USERTTDIR.$id.'.xml';
346   - }
347   -
348   - //load intervals from TT id
349   - if (!file_exists($path))
350   - return array('success' => false, 'message' => "Cannot find TT file ".$id);
351   -
352   - $this->objectDom -> load($path);
353   - if (!($objToGet = $this->objectDom->getElementById($id)))
354   - return array('success' => false, 'message' => NO_SUCH_ID." ".$id);
355   -
  577 +
  578 + $this->objectDom->load($path);
  579 + if (!($objToGet = $this->objectDom->getElementById($id))) {
  580 + return ['success' => false, 'message' => NO_SUCH_ID . " " . $id];
  581 + }
  582 +
356 583 $xpath = new DOMXPath($this->objectDom);
357   - $intervals = $xpath->query('//intervals');
358   -
359   - $result = array();
360   -
  584 + $intervals = $xpath->query('//intervals');
  585 +
  586 + $result = [];
  587 +
361 588 if (!isset($start) || !isset($limit)) {
  589 +
  590 + /** @var DOMElement $interval */
362 591 foreach ($intervals as $interval) {
363 592 $startTime = $interval->getElementsByTagName('start')->item(0)->nodeValue;
364   - $stopTime = $interval->getElementsByTagName('stop')->item(0)->nodeValue;
365   - array_push($result, array('start' => $startTime, 'stop' => $stopTime));
  593 + $stopTime = $interval->getElementsByTagName('stop')->item(0)->nodeValue;
  594 + array_push($result, ['start' => $startTime, 'stop' => $stopTime]);
366 595 }
367   - }
368   - else {
369   - for ($i = 0; $i < $limit; ++$i) {
370   - if ($start+$i >= $intervals->length)
  596 + } else {
  597 + for ($iInt = 0; $iInt < $limit; ++$iInt) {
  598 + if ($start + $iInt >= $intervals->length) {
371 599 break;
372   - $startTime = $intervals->item($start+$i)->getElementsByTagName('start')->item(0)->nodeValue;
373   - $stopTime = $intervals->item($start+$i)->getElementsByTagName('stop')->item(0)->nodeValue;
374   - array_push($result, array('start' => $startTime, 'stop' => $stopTime));
  600 + }
  601 + $startTime = $intervals->item($start + $iInt)->getElementsByTagName('start')->item(0)->nodeValue;
  602 + $stopTime = $intervals->item($start + $iInt)->getElementsByTagName('stop')->item(0)->nodeValue;
  603 + array_push($result, ['start' => $startTime, 'stop' => $stopTime]);
375 604 }
376 605 }
377   -
378   - return array(
379   - 'totalCount' => $intervals->length,
380   - 'intervals' => $result,
381   - 'start' => isset($start) ? $start : 0,
382   - 'limit' => isset($limit) ? $limit : 0,
383   - 'success' => true
384   - );
385   - }
386   -
387   - protected function createIntervalElement($interval)
388   - {
389   - $newInterval = $this->objectDom->createElement('intervals');
390   - $newInterval->appendChild($this->objectDom->createElement('start',$interval->start));
391   - $newInterval->appendChild($this->objectDom->createElement('stop',$interval->stop));
392   - return $newInterval;
  606 +
  607 + return [
  608 + 'totalCount' => $intervals->length,
  609 + 'intervals' => $result,
  610 + 'start' => isset($start) ? $start : 0,
  611 + 'limit' => isset($limit) ? $limit : 0,
  612 + 'success' => true
  613 + ];
393 614 }
394   -
395   - public function saveIntervals($id,$intervals,$action)
  615 +
  616 + /**
  617 + * Save intervals
  618 + * @param $id
  619 + * @param $intervals
  620 + * @param $action
  621 + * @return array
  622 + */
  623 + public function saveIntervals($id, $intervals, $action)
396 624 {
397   - if (substr($id,0,6) == 'shared') {
398   - return array('success' => false, 'message' => "Cannot save shared TimeTable");
399   - }
400   - else {
401   - $path = USERTTDIR.$id.'.xml';
402   - }
403   - if (!file_exists($path))
404   - return array('success' => false, 'message' => "Cannot find TT file ".$id);
405   - $this->objectDom -> load($path);
406   -
407   - if (!($objToGet = $this->objectDom->getElementById($id)))
408   - return array('success' => false, 'message' => NO_SUCH_ID." ".$id);
  625 + if (substr($id, 0, 6) == 'shared') {
  626 + return ['success' => false, 'message' => "Cannot save shared TimeTable"];
  627 + } else {
  628 + $path = USERTTDIR . $id . '.xml';
  629 + }
  630 + if (!file_exists($path)) {
  631 + return ['success' => false, 'message' => "Cannot find TT file " . $id];
  632 + }
  633 + $this->objectDom->load($path);
  634 +
  635 + if (!($objToGet = $this->objectDom->getElementById($id))) {
  636 + return ['success' => false, 'message' => NO_SUCH_ID . " " . $id];
  637 + }
409 638  
410 639 //remove old intervals
411 640 $crtNode = $objToGet->firstChild;
412   -
  641 +
413 642 while ($crtNode) {
414   - if (($crtNode->nodeType != XML_ELEMENT_NODE) || ($crtNode->tagName != 'intervals')) {
  643 + if (($crtNode->nodeType != XML_ELEMENT_NODE) || ($crtNode->tagName != 'intervals')) {
415 644 $crtNode = $crtNode->nextSibling;
416 645 continue;
417 646 }
... ... @@ -420,357 +649,261 @@ class TimeTableMgr extends AmdaObjectMgr
420 649 $objToGet->removeChild($toRemove);
421 650 unset($toRemove);
422 651 }
423   -
  652 +
424 653 //add new intervals
425   - foreach ($intervals as $interval) {
426   - $newInterval = $this-> createIntervalElement($interval);
  654 + foreach ($intervals as $interval) {
  655 + $newInterval = $this->createIntervalElement($interval);
427 656 $this->objectDom->documentElement->appendChild($newInterval);
428 657 }
429 658  
430 659 //save modifications
431 660 $this->id = $id;
432   - $this->resFileName = USERTTDIR.$this->id.'.xml';
  661 + $this->resFileName = USERTTDIR . $this->id . '.xml';
433 662 $this->objectDom->save($this->resFileName);
434   -
  663 +
435 664 unset($this->objectDom);
436   -
437   - return array('success' => true,'action' => $action, 'nbIntervals' => count($intervals));
  665 +
  666 + return ['success' => true, 'action' => $action, 'nbIntervals' => count($intervals)];
438 667 }
439   -
440   -
441   - public function getUploadedObject($name, $format, $onlyDescription = false)
  668 +
  669 + /**
  670 + * Create interval element
  671 + * @param $interval
  672 + * @return DOMElement
  673 + */
  674 + protected function createIntervalElement($interval)
442 675 {
443   - if (strpos($name,'.txt') !== false || strpos($name,'.asc') !== false || strpos($name,'.') == false) {
444   - $attributesToReturn = $this->text2amda(USERTEMPDIR.$name, $onlyDescription);
445   - $attributesToReturn['objName'] = $name;
446   - $attributesToReturn['objFormat'] = $format;
447   -
448   - return $attributesToReturn;
  676 + $newInterval = $this->objectDom->createElement('intervals');
  677 + $newInterval->appendChild($this->objectDom->createElement('start', $interval->start));
  678 + $newInterval->appendChild($this->objectDom->createElement('stop', $interval->stop));
  679 + return $newInterval;
  680 + }
  681 +
  682 + /**
  683 + * Intersect time tables
  684 + * @param $obj
  685 + * @return array|string
  686 + */
  687 + public function intersect($obj)
  688 + {
  689 + $intervals = 0;
  690 + for ($iId = 0; $iId < count($obj->ids); $iId++) {
  691 + $table[$iId] = $this->loadIntervalsFromTT($obj->ids[$iId]);
  692 + for ($jId = 0; $jId < count($table[$iId]['intervals']); $jId++) {
  693 + $interval[$iId][$jId][0] = $table[$iId]['intervals'][$jId]['start'];
  694 + $interval[$iId][$jId][1] = $table[$iId]['intervals'][$jId]['stop'];
  695 + }
  696 + $intervals += count($interval[$iId]);
449 697 }
450   -
451   - if ($format == 'VOT') {
452   - $attributesToReturn = $this->vot2amda(USERTEMPDIR.$name, $onlyDescription);
453   - $attributesToReturn['objName'] = $name;
454   - $attributesToReturn['objFormat'] = $format;
455   -
456   - return $attributesToReturn;
457   - }
458   -
459   - if (strpos($name,'.xml') !== false) {
460   - $temp = explode('.xml', $name);
461   - $name = $temp[0];
  698 + if ($intervals > 10000) {
  699 + set_time_limit(1800);
462 700 }
463   -
464   - if (!file_exists(USERTEMPDIR.$name.'.xml'))
465   - return array('error' => 'no such name');
466   -
467   - $this->objectDom->load(USERTEMPDIR.$name.'.xml');
468   - if (!($objToGet = $this->objectDom->getElementsByTagName('timetable')->item(0)) &&
469   - !($objToGet = $this->objectDom->getElementsByTagName('TimeTable')->item(0)))
470   - return array('error' => 'no time table');
471 701  
472   - $attributes = $objToGet -> childNodes;
473   - $attributesToReturn['name'] = $name;
474   - $attributesToReturn['objName'] = $name;
475   - $attributesToReturn['objFormat'] = $format;
  702 + // Sort intervals in time tables
  703 + sort($interval[0]);
  704 + sort($interval[1]);
476 705  
477   - foreach($attributes as $attribute) {
478   - if($attribute->nodeType == XML_ELEMENT_NODE){
479   - if ($attribute->tagName == 'intervals') {
480   - $start = $attribute -> getElementsByTagName('start')->item(0) -> nodeValue;
481   - $stop = $attribute -> getElementsByTagName('stop')->item(0) -> nodeValue;
482   - if (!$onlyDescription)
483   - $attributesToReturn['intervals'][] = array('start' => $start, 'stop' => $stop);
484   - }
485   - else if ($attribute->tagName == 'Interval') {
486   - $start = $attribute -> getElementsByTagName('Start')->item(0) -> nodeValue;
487   - $stop = $attribute -> getElementsByTagName('Stop')->item(0) -> nodeValue;
488   - if (!$onlyDescription)
489   - $attributesToReturn['intervals'][] = array('start' => $start, 'stop' => $stop);
490   - }
491   - else {
492   - switch (strtolower($attribute->tagName)) {
493   - case 'created' :
494   - $attributesToReturn['created'] = $attribute->nodeValue;
495   - break;
496   - case 'chain' :
497   - case 'source' :
498   - $attributesToReturn['description'] = $attribute->nodeValue;
499   - break;
500   - default: break;
501   - }
  706 + $iId = 0;
  707 + $jId = 0;
  708 + $line = 0;
  709 +
  710 + while (($iId < count($interval[0])) && ($jId < count($interval[1]))) {
  711 + $inter = $this->callIntersection($interval[0][$iId], $interval[1][$jId]);
  712 +
  713 + if ($inter[0][0] != 0 && $inter[0][1] != 0) {
  714 + $start[$line] = $inter[0][0];
  715 + $stop[$line] = $inter[0][1];
  716 + $line++;
  717 + }
  718 +
  719 + if ($interval[0][$iId][1] < $interval[1][$jId][1]) {
  720 + $iId++;
  721 + } else {
  722 + $jId++;
  723 + }
  724 + }
  725 +
  726 + // Intersection is empty
  727 + if ($line == 0) {
  728 + $result = "empty";
  729 + } else {
  730 + $objTT->name = $obj->name; // FIXME $objTT is undefined
  731 + $objTT->nodeType = 'timeTable';
  732 + $objTT->leaf = true;
  733 + $objTT->created = null;
  734 + $objTT->history = $obj->history;
  735 + for ($iId = 0; $iId < count($start); $iId++) {
  736 + $inter = new stdClass();
  737 + $inter->start = $start[$iId];
  738 + $inter->stop = $stop[$iId];
  739 + $objTT->intervals[] = $inter;
  740 + }
  741 + $objTT->nbIntervals = count($start);
  742 +
  743 + if (count($objTT->intervals) == 0) {
  744 + $result = "empty";
  745 + } else {
  746 + $this->objectDom = new DomDocument('1.0');
  747 + $this->objectDom->formatOutput = true;
  748 + $result = $this->createObject($objTT, $folder); // FIXME $folder is undefined
  749 +
  750 + if (!isset($result['error'])) {
  751 + $this->saveIntervals($result['id'], $objTT->intervals, 'intersect');
502 752 }
503 753 }
504 754 }
505   - return $attributesToReturn;
  755 + return $result;
506 756 }
507 757  
508   - //TODO getObject only!!!! => change DD_Search output
509   - public function getTmpObject($folderId, $name, $onlyDescription = false) {
510   - $filePath = USERWORKINGDIR.$folderId.'/'.$name.'.xml';
511   - if (!file_exists($filePath))
512   - return array('error' => 'Cannot find result file');
513   -
514   - $dom = new DomDocument('1.0');
515   - $dom->formatOutput = true;
516   -
517   - if (!$dom -> load($filePath))
518   - return array('error' => 'Cannot load result file');
519   -
520   - $descNodes = $dom->getElementsByTagName('description');
521   - if ($descNodes->length > 0)
522   - $attributesToReturn['description'] = $descNodes->item(0)->nodeValue;
523   -
524   - $creatNodes = $dom->getElementsByTagName('created');
525   - if ($creatNodes->length > 0)
526   - $attributesToReturn['created'] = $creatNodes->item(0)->nodeValue;
527   -
528   - $histNodes = $dom->getElementsByTagName('history');
529   - if ($histNodes->length > 0)
530   - $attributesToReturn['history'] = $histNodes->item(0)->nodeValue;
531   -
532   - $attributesToReturn['objName'] = $name;
533   - $attributesToReturn['folderId'] = $folderId;
534   -
535   - if (!$onlyDescription)
536   - {
537   - $intNodes = $dom->getElementsByTagName('intervals');
538   - foreach ($intNodes as $intNode)
539   - {
540   - $startNodes = $intNode->getElementsByTagName('start');
541   - if ($startNodes->length <= 0)
542   - return array('error' => 'Error detected in result file');
543   - $stopNodes = $intNode->getElementsByTagName('stop');
544   - if ($stopNodes->length <= 0)
545   - return array('error' => 'Error detected in result file');
546   - $attributesToReturn['intervals'][] = array('start' => $startNodes->item(0)->nodeValue,
547   - 'stop' => $stopNodes->item(0)->nodeValue);
548   - }
  758 + /**
  759 + * Call intersection
  760 + * @param $fst
  761 + * @param $snd
  762 + * @return array
  763 + */
  764 + protected function callIntersection($fst, $snd)
  765 + {
  766 + $inf = ($fst[0] > $snd[0]) ? $fst[0] : $snd[0];
  767 + $sup = ($fst[1] < $snd[1]) ? $fst[1] : $snd[1];
  768 + $inter[] = ($inf >= $sup) ? [0, 0] : [$inf, $sup];
  769 + return $inter;
  770 + }
  771 +
  772 + /**
  773 + * Valid name object
  774 + * TODO getObject only!!!! => change DD_Search output
  775 + * @param $p
  776 + * @return array
  777 + */
  778 + public function validNameObject($p)
  779 + {
  780 + // overwritten
  781 + $res = parent::validNameObject($p);
  782 +
  783 + if (!$res['valid']) {
  784 + return $res;
  785 + }
  786 +
  787 + //no space
  788 + if (strpos($p->name, ' ') === false) {
  789 + return ['valid' => true];
549 790 }
550   -
551   - return $attributesToReturn;
  791 +
  792 + return ['valid' => false, 'error' => 'Space character is not allowed'];
552 793 }
553 794  
554   - /*
555   - * merge time tables
556   - */
557   - public function merge($obj) {
558 795 /**
559   - * Array of intervals, used like :
560   - * [{start:'2010-01-01T23:00:00',stop:'2011-01-01T20:00:00'},{start:'2009-01-01T23:00:00',stop:'2010-01-01T20:00:00'}]
561   - * $attributesToReturn['intervals'][] = array('start' => $start, 'stop' => $stop);
562   - */
563   -
564   - $intervals = 0;
565   -
566   - for ( $i = 0; $i < count($obj->ids); $i++ ) {
567   - $table[$i] = $this->loadIntervalsFromTT($obj->ids[$i]);
568   - for ($j=0; $j < count($table[$i]['intervals']); $j++) {
569   - $interval[$i][$j][0] = $table[$i]['intervals'][$j]['start'];
570   - $interval[$i][$j][1] = $table[$i]['intervals'][$j]['stop'];
571   - }
572   - $intervals += count($interval[$i]);
573   - }
574   - if ( $intervals > 10000) set_time_limit(1800);
575   -
576   - $final = array();
577   - for ( $i = 0; $i < count($obj->ids); $i++ ) {
578   - $final = array_merge($final, $interval[$i]);
579   - }
580   - sort($final);
581   -
582   - // Algorithm of union
583   - $line = 0;
584   - $i = 0;
585   - $a = $final[$i][0];
586   - while ($i < count($final)-1) {
587   - if ($final[$i+1][1] <= $final[$i][1])
588   - {
589   - array_splice($final,$i+1,1);
590   - }
591   - else if (($final[$i+1][0] <= $final[$i][1]) && ($final[$i+1][1] >= $final[$i][1]))
592   - {
593   - $i++;
594   - }
595   - else {
596   - $start[$line] = $a;
597   - $stop[$line] = $final[$i][1];
598   - $i++;
599   - $line++;
600   - $a = $final[$i][0];
601   - }
602   - }
603   - $start[$line] = $a;
604   - $stop[$line] = $final[$i][1];
605   - $line++;
606   -
607   - $objTT = new stdClass();
608   - $objTT->name = $obj->name;
609   - $objTT->nodeType = 'timeTable';
610   - $objTT->leaf = true;
611   - $objTT->created = null;
612   - $objTT->history = $obj->history;
613   - for ($i=0; $i < count($start); $i++) {
614   - $inter = new stdClass();
615   - $inter->start = $start[$i];
616   - $inter->stop = $stop[$i];
617   - $objTT->intervals[] = $inter;
618   - }
619   - $objTT->nbIntervals = count($start);
620   - $this->objectDom = new DomDocument('1.0');
621   - $this->objectDom->formatOutput = true;
622   -
623   - $res = $this->createParameter($objTT, $folder);
624   - if ($res['error'])
625   - return $res;
626   -
627   - $this->saveIntervals($res['id'],$objTT->intervals,'merge');
628   -
629   - return $res;
630   -
631   - }
632   -
633   -/*
634   - * intersect time tables
635   - */
636   - public function intersect($obj) {
637   -
638   - for ( $i = 0; $i < count($obj->ids); $i++ ) {
639   - $table[$i] = $this->loadIntervalsFromTT($obj->ids[$i]);
640   - for ($j=0; $j < count($table[$i]['intervals']); $j++) {
641   - $interval[$i][$j][0] = $table[$i]['intervals'][$j]['start'];
642   - $interval[$i][$j][1] = $table[$i]['intervals'][$j]['stop'];
643   - }
644   - $intervals += count($interval[$i]);
645   - }
646   - if ( $intervals > 10000) set_time_limit(1800);
647   -
648   - // Sort intervals in time tables
649   - sort($interval[0]);
650   - sort($interval[1]);
651   -
652   - $i = 0;
653   - $j = 0;
654   - $line = 0;
655   -
656   - while ( ($i < count($interval[0])) && ($j < count($interval[1])) ) {
657   - $inter = $this->call_intersection($interval[0][$i], $interval[1][$j]);
658   -
659   - if ($inter[0][0] != 0 && $inter[0][1] != 0)
660   - {
661   - $start[$line] = $inter[0][0];
662   - $stop[$line] = $inter[0][1];
663   - $line++;
664   - }
665   -
666   - if ( $interval[0][$i][1] < $interval[1][$j][1] ) { $i++; }
667   - else { $j++; }
668   - }
669   -
670   - // Intersection is empty
671   - if ( $line == 0 ) {
672   - $result ="empty";
673   - }
674   - else {
675   - $objTT->name = $obj->name;
676   - $objTT->nodeType = 'timeTable';
677   - $objTT->leaf = true;
678   - $objTT->created = null;
679   - $objTT->history = $obj->history;
680   - for ($i=0; $i < count($start); $i++) {
681   - $inter = new stdClass();
682   - $inter->start = $start[$i];
683   - $inter->stop = $stop[$i];
684   - $objTT->intervals[] = $inter;
685   - }
686   - $objTT->nbIntervals = count($start);
687   -
688   - if (count($objTT->intervals) == 0)
689   - $result ="empty";
690   - else
691   - {
692   - $this->objectDom = new DomDocument('1.0');
693   - $this->objectDom->formatOutput = true;
694   - $result = $this->createObject($objTT, $folder);
695   -
696   - if (!isset($result['error']))
697   - $this->saveIntervals($result['id'],$objTT->intervals,'intersect');
698   -
699   - }
700   - }
701   - return $result;
702   - }
703   -
704   -
705   - function validNameObject($p){
706   - // overwritten
707   - $res = parent::validNameObject($p);
708   -
709   - if (!$res['valid'])
710   - return $res;
711   -
712   - //no space
713   - if (strpos($p->name, ' ') === FALSE)
714   - return array('valid' => true);
715   -
716   - return array('valid' => false, 'error' => 'Space character is not allowed');
717   - }
718   -
719   - public function copyTT($src_path, $dst_path, $newId, $newName, $newDescription = NULL)
  796 + * Copy time table
  797 + * @param $src_path
  798 + * @param $dst_path
  799 + * @param $newId
  800 + * @param $newName
  801 + * @param null $newDescription
  802 + * @return bool
  803 + */
  804 + public function copyTT($src_path, $dst_path, $newId, $newName, $newDescription = null)
720 805 {
721   - if (!file_exists($src_path))
722   - return FALSE;
723   -
724   - if (!is_dir($dst_path))
725   - return FALSE;
726   -
  806 + if (!file_exists($src_path)) {
  807 + return false;
  808 + }
  809 +
  810 + if (!is_dir($dst_path)) {
  811 + return false;
  812 + }
  813 +
727 814 $dom = new DomDocument('1.0');
728 815 $dom->formatOutput = true;
729   -
730   - if (!$dom->load($src_path))
731   - return FALSE;
732   -
  816 +
  817 + if (!$dom->load($src_path)) {
  818 + return false;
  819 + }
  820 +
733 821 $timeTableNodes = $dom->getElementsByTagName('timetable');
734   - if ($timeTableNodes->length <= 0)
735   - return FALSE;
736   -
  822 + if ($timeTableNodes->length <= 0) {
  823 + return false;
  824 + }
  825 +
737 826 $timeTableNode = $timeTableNodes->item(0);
738   -
  827 +
739 828 $timeTableNode->setAttribute('xml:id', $newId);
740   -
  829 +
741 830 $nameNodes = $timeTableNode->getElementsByTagName('name');
742   -
  831 +
743 832 if ($nameNodes->length <= 0) {
744 833 //create name node (normally never append)
745 834 $nameNode = $dom->createElement('name');
746 835 $timeTableNode->appendChild($nameNode);
747   - }
748   - else
  836 + } else {
749 837 $nameNode = $nameNodes->item(0);
750   -
  838 + }
  839 +
751 840 $nameNode->nodeValue = $newName;
752   -
  841 +
753 842 if (isset($newDescription) && !empty($newDescription)) {
754 843 $descriptionNodes = $timeTableNode->getElementsByTagName('description');
755 844 if ($descriptionNodes->length <= 0) {
756 845 //create description node (normally never append)
757 846 $descriptionNode = $dom->createElement('description');
758 847 $timeTableNode->appendChild($descriptionNode);
759   - }
760   - else
  848 + } else {
761 849 $descriptionNode = $descriptionNodes->item(0);
762   -
  850 + }
  851 +
763 852 $descriptionNode->nodeValue = $newDescription;
764 853 }
765   -
766   - $dst_file_path = $dst_path."/".$newId.".xml";
767   - if ($dom->save($dst_file_path) === FALSE)
768   - return FALSE;
769   -
770   - chgrp($dst_file_path, APACHE_USER);
771   - chmod($dst_file_path, 0775);
772   -
773   - return TRUE;
  854 +
  855 + $dstFilePath = $dst_path . "/" . $newId . ".xml";
  856 + if ($dom->save($dstFilePath) === false) {
  857 + return false;
  858 + }
  859 +
  860 + chgrp($dstFilePath, APACHE_USER);
  861 + chmod($dstFilePath, 0775);
  862 +
  863 + return true;
  864 + }
  865 +
  866 + /**
  867 + * Rename in resource
  868 + * @param $name
  869 + * @param $id
  870 + * @return bool
  871 + */
  872 + protected function renameInResource($name, $id)
  873 + {
  874 + if (!file_exists(USERTTDIR . $id . '.xml')) {
  875 + return false;
  876 + }
  877 +
  878 + $this->objectDom->load(USERTTDIR . $id . '.xml');
  879 + if (!($objToRename = $this->objectDom->getElementById($id))) {
  880 + return false;
  881 + }
  882 + $objToRename->getElementsByTagName('name')->item(0)->nodeValue = $name;
  883 + $this->objectDom->save(USERTTDIR . $id . '.xml');
  884 +
  885 + return true;
  886 + }
  887 +
  888 + /**
  889 + * Delete parameter
  890 + * @param $id
  891 + */
  892 + protected function deleteParameter($id)
  893 + {
  894 + if (file_exists(USERTTDIR . $id . '.xml')) {
  895 + unlink(USERTTDIR . $id . '.xml');
  896 + }
  897 + }
  898 +
  899 + /**
  900 + * Rename only
  901 + * @param $p
  902 + * @return bool
  903 + */
  904 + protected function renameOnly($p)
  905 + {
  906 + //if (!($p->intervals)) return true;
  907 + return false;
774 908 }
775 909 }
776   -?>
... ...