Blame view

php/classes/TimeTableMgr.php 23.5 KB
16035364   Benjamin Renard   First commit
1
2
3
4
5
6
7
8
9
<?php

/**
 * @class TimeTableMgr
 * @version $Id: TimeTableMgr.php 2809 2015-03-05 09:50:52Z natacha $
 * @todo MANAGE TT created by Search and Plot interactive - HERE?
 *
 */

4a438b99   elena   catalog draft
10
11
12
13
14
15
16
17
18
19
20
21
function timeFormat($myString) 
{
	if (format == "Y z H i s")  {
		$tt = getdate(strtotime($myString));
		return sprintf("%04d",$tt["year"])." "
			.sprintf("%03d",$tt["yday"]+1)." "
			.sprintf("%02d",$tt["hours"])." "
			.sprintf("%02d",$tt["minutes"])." "
			.sprintf("%02d",$tt["seconds"]);
	}
	return date(format,strtotime($myString));     
}
16035364   Benjamin Renard   First commit
22

4a438b99   elena   catalog draft
23
24
class TimeTableMgr extends AmdaObjectMgr
{     
e57cb025   Benjamin Renard   Fix most of error...
25
	function __construct($user = NULL, $sharedObject = FALSE) 
4a438b99   elena   catalog draft
26
	{
16035364   Benjamin Renard   First commit
27
28
29
30
31
32
33
34
		parent::__construct('Tt.xml');
		$this->contentRootId = 'timeTable-treeRootNode';
		$this->contentRootTag = 'timetabList';
		$this->attributes = array('name' => '', 'intervals' => '');
		$this->optionalAttributes = array();
		$this->objTagName = 'timetab';
		$this->id_prefix = 'tt_';

169f14d2   Benjamin Renard   Add shared object...
35
		if (!$sharedObject && !file_exists($this->xmlName)) {
16035364   Benjamin Renard   First commit
36
37
38
39
40
			  $this->createDom();
			  $this->xp = new domxpath($this->contentDom); 
		}
	}
	
3ed056c4   Elena.Budnik   redmine #5278
41
42
	protected function createDom() 
	{
16035364   Benjamin Renard   First commit
43
44
45
		$types = array('timetab' => 'timeTable', 'catalog' => 'catalog');

		$rootElement = $this->contentDom->createElement('ws');
3ed056c4   Elena.Budnik   redmine #5278
46
47
48
49
50
51
52
		
		foreach ($types as $key => $value) {
			$contentId = $value.'-treeRootNode';
			$contentTag = $key.'List';
			$typeElement = $this->contentDom->createElement($contentTag);
			$typeElement->setAttribute('xml:id', $contentId);
			$rootElement->appendChild($typeElement);
16035364   Benjamin Renard   First commit
53
		}
4a438b99   elena   catalog draft
54
		$this->contentDom->appendChild($rootElement);
16035364   Benjamin Renard   First commit
55
		$this->contentDom->save($this->xmlName);
3ed056c4   Elena.Budnik   redmine #5278
56
	}
16035364   Benjamin Renard   First commit
57

3ed056c4   Elena.Budnik   redmine #5278
58
59
60
	/*
	*       rename  Time Table in  id.xml
	*/
4a438b99   elena   catalog draft
61
62
	protected function renameInResource($name, $id) 
	{
16035364   Benjamin Renard   First commit
63
64
65
66
67
68
69
70
71
72
		if (!file_exists(USERTTDIR.$id.'.xml')) return false;

		$this->objectDom -> load(USERTTDIR.$id.'.xml');
		if (!($objToRename = $this->objectDom->getElementById($id))) return false;
		$objToRename -> getElementsByTagName('name')->item(0)->nodeValue = $name;
		$this->objectDom ->save(USERTTDIR.$id.'.xml');
		 
		return true;
	}

4a438b99   elena   catalog draft
73
74
	protected function deleteParameter($id)
	{
16035364   Benjamin Renard   First commit
75
76
77
78
		if (file_exists(USERTTDIR.$id.'.xml')) unlink(USERTTDIR.$id.'.xml');
	}

	/*
4a438b99   elena   catalog draft
79
80
	*        Check if difference is name and info only
	*/
16035364   Benjamin Renard   First commit
81
82
83
84
	protected function renameOnly($p) {
		//if (!($p->intervals)) return true;
		return false;
	}
d18b535d   elena   catalog draft + c...
85
86
87
88
89
         
        /*
        *  In case of catalogs
        */
        protected function setParamDescription($param) { }
16035364   Benjamin Renard   First commit
90

d18b535d   elena   catalog draft + c...
91
        
16035364   Benjamin Renard   First commit
92
93
94
	/*
	 *         Create Time Table
	 */
4a438b99   elena   catalog draft
95
96
	protected function createParameter($p, $folder)
	{
16035364   Benjamin Renard   First commit
97
98
99
100
		if ($this -> objectExistsByName($p->name)) {
			$p -> id  = $this -> getObjectIdByName($p->name);
			$this -> deleteObject($p);
		}
3ed056c4   Elena.Budnik   redmine #5278
101
		
16035364   Benjamin Renard   First commit
102
103
104
		$this->id = $this->setId();
		$this->created = date('Y-m-d\TH:i:s');
		if (!$this->id) return array('error' => ID_CREATION_ERROR);
d18b535d   elena   catalog draft + c...
105
		
16035364   Benjamin Renard   First commit
106
		$this->resFileName = USERTTDIR.$this->id.'.xml';
d18b535d   elena   catalog draft + c...
107
		//TODO catalog root element = 'timetable'
16035364   Benjamin Renard   First commit
108
109
110
111
		$rootElement = $this->objectDom->createElement('timetable');
		$rootElement->setAttribute('xml:id',$this->id);
	 
		foreach ($p as $key => $value)		
3ed056c4   Elena.Budnik   redmine #5278
112
113
114
115
116
			if ($key != 'id' && $key != 'leaf' && $key != 'nodeType' &&
				$key != 'objName' && $key != 'objFormat' && $key != 'folderId' && $key != 'cacheToken') {
					if ($key == 'created') {
						$rootElement->appendChild($this->objectDom->createElement($key, $this->created));
					}
3ed056c4   Elena.Budnik   redmine #5278
117
118
119
120
121
122
123
124
					// it is catalog 
					else if ($key == 'parameters') {
					$paramsElement = $this->setParamDescription($value);
					if ($paramsElement) $rootElement->appendChild($paramsElement);
					
					}
					else if ($key != 'intervals')
						$rootElement->appendChild($this->objectDom->createElement($key, htmlspecialchars($value)));
d18b535d   elena   catalog draft + c...
125
			}
16035364   Benjamin Renard   First commit
126
127
128
129
130
131
132
133

		$this->objectDom->appendChild($rootElement);
		$this->objectDom->save($this->resFileName);
		$obj = new stdClass();
		$obj->name = $p->name;
		$obj->intervals = $p->nbIntervals;
		$this -> addToContent($obj, $folder);
		return array('id' => $this->id,'created' => $this->created,'info' =>$obj->intervals.' intervals' );
16035364   Benjamin Renard   First commit
134
135
	}

4a438b99   elena   catalog draft
136
137
138
139
140
141
142
143
	protected function call_intersection($fst, $snd) 
	{
		$inf = ( $fst[0] > $snd[0] ) ? $fst[0] : $snd[0];
		$sup = ( $fst[1] < $snd[1] ) ? $fst[1] : $snd[1];
		if ( $inf >= $sup ) { $inter[] = array(0,0); }
		else {$inter[] = array($inf,$sup); }
		return $inter;
	}
16035364   Benjamin Renard   First commit
144
    
3ed056c4   Elena.Budnik   redmine #5278
145
146
147
	/*
	* Uploaded text file => convert to array
	*/
4a438b99   elena   catalog draft
148
149
150
151
152
153
	protected function text2amda($tmp_file, $onlyDescription = false) 
	{  
		$suffix = explode('.', basename($tmp_file));
		$lines = file($tmp_file,FILE_SKIP_EMPTY_LINES);
		$description="Uploaded Time Table".PHP_EOL; 

f8cd7d84   Elena.Budnik   error msg if cann...
154
155
156
		$recordsNumber = count($lines);
		$descNumber = 0;
		
6207ec14   Elena.Budnik   #5919 non standar...
157
158
159
160
161
		foreach ($lines as $line)
		{  
			if ($line[0] == '#') {
				$description=$description.PHP_EOL.substr($line,1,-1);
			}
4a438b99   elena   catalog draft
162
			else {
6207ec14   Elena.Budnik   #5919 non standar...
163
164
				$date = explode(' ', trim(preg_replace('!\s+!', ' ',$line)));
				
4a438b99   elena   catalog draft
165
				if (!strtotime(trim($date[0]))) {
dca1b251   Elena.Budnik   non standard time...
166
					$description=$description.PHP_EOL.$line;
f8cd7d84   Elena.Budnik   error msg if cann...
167
					$descNumber++;
4a438b99   elena   catalog draft
168
169
					continue;
				}
3ed056c4   Elena.Budnik   redmine #5278
170
				// check if it is ISO format
6207ec14   Elena.Budnik   #5919 non standar...
171
172
173
				if (!isset($isIso)) 
					$isIso = preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})$/', trim($date[0]));
					
3ed056c4   Elena.Budnik   redmine #5278
174
				if (!$isIso) {
6207ec14   Elena.Budnik   #5919 non standar...
175
176
177
178
179
					// y-m-d h:m:s for example
					$dateLength = count($date) / 2;

					$tempStart = $date[0];
					$tempStop = $date[$dateLength];
dca1b251   Elena.Budnik   non standard time...
180
					
6207ec14   Elena.Budnik   #5919 non standar...
181
182
183
184
185
186
187
188
189
190
					if ($dateLength > 1) {
						for ($i = 1; $i < $dateLength; $i++)
							$tempStart.= $date[$i];	
						
						for ($i = $dateLength + 1; $i < $dateLength * 2; $i++)
							$tempStop .= $date[$i];
					}

					$startDate = date('Y-m-d\TH:i:s',strtotime($tempStart));
					$stopDate = date('Y-m-d\TH:i:s',strtotime($tempStop));
dca1b251   Elena.Budnik   non standard time...
191
					
3ed056c4   Elena.Budnik   redmine #5278
192
193
194
195
196
197
198
					if (!$onlyDescription)
							$attributesToReturn['intervals'][] = array('start' => $startDate, 'stop' => $stopDate); 
				}
				else {
					if (!$onlyDescription)
						$attributesToReturn['intervals'][] = array('start' => trim($date[0]), 'stop' => trim($date[1]));
				} 
4a438b99   elena   catalog draft
199
			}
3ed056c4   Elena.Budnik   redmine #5278
200
		}
f8cd7d84   Elena.Budnik   error msg if cann...
201
202
203
      if ( $recordsNumber == $descNumber )
			$description = "Looks like we can not read your time format...".PHP_EOL.$description;
			
4a438b99   elena   catalog draft
204
205
		$attributesToReturn['description'] = $description;
		$attributesToReturn['name'] = basename($tmp_file, '.'.$suffix[1]);
dca1b251   Elena.Budnik   non standard time...
206
		$attributesToReturn['created'] = date('Y-m-d\TH:i:s');
16035364   Benjamin Renard   First commit
207

3ed056c4   Elena.Budnik   redmine #5278
208
		return $attributesToReturn;
16035364   Benjamin Renard   First commit
209
	}
6207ec14   Elena.Budnik   #5919 non standar...
210

16035364   Benjamin Renard   First commit
211
212
213
214
      /*
      * Uploaded vot TT => convert to array
      */
	protected function vot2amda($tmp_file, $onlyDescription = false) {		  
3ed056c4   Elena.Budnik   redmine #5278
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
	// Load Time table		
		$this->objectDom -> load($tmp_file);
		$objToGet = $this->objectDom->getElementsByTagName('TABLEDATA')->item(0);
		$attributesToReturn['name'] = $tmp_file;
		$attributes = $objToGet -> childNodes;
		foreach($attributes as $attribute)
			if ($attribute->tagName == 'TR') {
				$start = $attribute -> getElementsByTagName('TD')->item(0) -> nodeValue;
				$stop = $attribute -> getElementsByTagName('TD')->item(1) -> nodeValue;
				if (!$onlyDescription)
						$attributesToReturn['intervals'][] = array('start' => $start, 'stop' => $stop);
			}
		$suffix = explode('.', basename($tmp_file));   
		$attributesToReturn['name'] = basename($tmp_file, '.'.$suffix[1]); 
		$attributesToReturn['created'] = date('Y-m-d')."T".date('H:i:s');
		$attributesToReturn['description'] = htmlspecialchars($this->objectDom->getElementsByTagName('DESCRIPTION')->item(0) -> nodeValue);
		return($attributesToReturn);
16035364   Benjamin Renard   First commit
232
233
	}
	
16035364   Benjamin Renard   First commit
234
235
236
	/*****************************************************************
	 *                           PUBLIC FUNCTIONS
	 *****************************************************************/
3ed056c4   Elena.Budnik   redmine #5278
237
	 
16035364   Benjamin Renard   First commit
238
239
240
	/*
	 *   Get Object into Edit
	 */
16035364   Benjamin Renard   First commit
241
	function getObject($id, $nodeType) {
169f14d2   Benjamin Renard   Add shared object...
242
243
244
245
		if (substr($nodeType,0,6) == 'shared') {
			//Shared object
			$sharedObjMgr = new SharedObjectsMgr();
			$path = $sharedObjMgr->getDataFilePath(str_replace('shared', '', $nodeType), $id);
16035364   Benjamin Renard   First commit
246
247
		}
		else {
169f14d2   Benjamin Renard   Add shared object...
248
			$path = USERTTDIR.$id.'.xml';
16035364   Benjamin Renard   First commit
249
250
		}

169f14d2   Benjamin Renard   Add shared object...
251
252
		if (!file_exists($path)) return array('error' => NO_OBJECT_FILE);
		$this->objectDom -> load($path);
16035364   Benjamin Renard   First commit
253
254
255
256
257
258
		if (!($objToGet = $this->objectDom->getElementById($id))) return array('error' => NO_SUCH_ID);
		$attributesToReturn['id'] = $objToGet->getAttribute('xml:id');
		$attributes = $objToGet -> childNodes;

		$nbInt = 0;
		foreach($attributes as $attribute)
4a438b99   elena   catalog draft
259
260
261
262
263
264
265
266
267
268
269
270
271
272
			if($attribute->nodeType == XML_ELEMENT_NODE){
			/*if ($attribute->tagName == 'intervals') {
				$start = $attribute -> getElementsByTagName('start')->item(0) -> nodeValue;
				$stop = $attribute -> getElementsByTagName('stop')->item(0) -> nodeValue;
				$attributesToReturn['intervals'][] = array('start' => $start, 'stop' => $stop);
			}
			else
			$attributesToReturn[$attribute->tagName] =  $attribute->nodeValue;*/
				//BRE - load all except intervals - Intervals will be loaded later with 'loadIntervalsFromTT' function
				if ($attribute->tagName != 'intervals')
					$attributesToReturn[$attribute->tagName] =  $attribute->nodeValue;
				else
					$nbInt++;
			}
16035364   Benjamin Renard   First commit
273
274
275
276
277
278
		
		$attributesToReturn['nbIntervals'] = $nbInt;
		
		return  $attributesToReturn;
	}
	
3ed056c4   Elena.Budnik   redmine #5278
279
280
281
	public function createObject($p, $folder)
	{	
		if ($p -> leaf){
16035364   Benjamin Renard   First commit
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
			$result = $this->createParameter($p, $folder);
			if ($result['error'])
				return $result;
			$cacheMgr = new TimeTableCacheMgr();
			if (isset($p->cacheToken) && ($p->cacheToken != ''))
			{
				$resultSaveInt = $cacheMgr->saveInTT($result['id'], "update", $p->cacheToken);
				if (!$resultSaveInt['success'])
				{
					if ($resultSaveInt['message'])
						return array('error' => $resultSaveInt['message']);
					else
						return array('error' => 'Unknown error during intervals save');
				}
			}
			return $result;
		}
		//      else return $this->createFolder($p);
		//TODO check if this is possible?
3ed056c4   Elena.Budnik   redmine #5278
301
		else return array('error' => 'createFolder should be called from RENAME');	
16035364   Benjamin Renard   First commit
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
	}
	
	
	public function modifyObject($p) {
		$folder = $this->getObjectFolder($p->id);
		
		//Copy TT in a tempory file
		$ttFilePath = USERTTDIR.$p->id.'.xml';
		$tmpFileExist = FALSE;
		if (file_exists($ttFilePath))
			$tmpFileExist = copy($ttFilePath,$ttFilePath.".tmp");
		
		//Delete TT
		$this->deleteObject($p);
		
		//Save modifications
		try {
04e66f25   Elena.Budnik   redmine 4596; too...
319
			$result = $this->createObject($p, $folder);			
16035364   Benjamin Renard   First commit
320
321
322
323
			if ($result['error'])
				throw new Exception($result['error']);
			if ($tmpFileExist)
				unlink($ttFilePath.".tmp");
04e66f25   Elena.Budnik   redmine 4596; too...
324
			return array('id' => $p->id, 'info' => $result['info']);
16035364   Benjamin Renard   First commit
325
326
327
328
329
330
331
332
333
334
335
336
		}
		catch (Exception $e) {
			//Restore TT file
			if ($tmpFileExist)
			{
				copy($ttFilePath.".tmp", $ttFilePath);
				unlink($ttFilePath.".tmp");
			}
			return array ('error' => $e->getMessage());
		}
	}
	
3ed056c4   Elena.Budnik   redmine #5278
337
338
339
340
341
342
343
344
345
346
	public function loadIntervalsFromTT($id,$typeTT,$start = NULL, $limit = NULL)
	{
		if ($typeTT == 'sharedtimeTable') {
			//Shared object
			$sharedObjMgr = new SharedObjectsMgr();
			$path = $sharedObjMgr->getDataFilePath('timeTable', $id);
		}
		else {
			$path = USERTTDIR.$id.'.xml';
		}
16035364   Benjamin Renard   First commit
347
348
		
  	 //load intervals from TT id
3ed056c4   Elena.Budnik   redmine #5278
349
350
351
352
353
354
		if (!file_exists($path))
			return array('success' => false, 'message' => "Cannot find TT file ".$id);
			
		$this->objectDom -> load($path);
		if (!($objToGet = $this->objectDom->getElementById($id)))
			return array('success' => false, 'message' => NO_SUCH_ID." ".$id);
16035364   Benjamin Renard   First commit
355
    
3ed056c4   Elena.Budnik   redmine #5278
356
357
358
359
		$xpath = new DOMXPath($this->objectDom);
		$intervals =  $xpath->query('//intervals');
		
		$result = array();
16035364   Benjamin Renard   First commit
360
    
3ed056c4   Elena.Budnik   redmine #5278
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
		if (!isset($start) || !isset($limit)) {
			foreach ($intervals as $interval) {
				$startTime = $interval->getElementsByTagName('start')->item(0)->nodeValue;
				$stopTime  = $interval->getElementsByTagName('stop')->item(0)->nodeValue;
				array_push($result, array('start' => $startTime, 'stop' => $stopTime));
			}
		}
		else {
			for ($i = 0; $i < $limit; ++$i) {
				if ($start+$i >= $intervals->length)
					break;
				$startTime = $intervals->item($start+$i)->getElementsByTagName('start')->item(0)->nodeValue;
				$stopTime  = $intervals->item($start+$i)->getElementsByTagName('stop')->item(0)->nodeValue;
				array_push($result, array('start' => $startTime, 'stop' => $stopTime));
			}
16035364   Benjamin Renard   First commit
376
		}
16035364   Benjamin Renard   First commit
377
    
3ed056c4   Elena.Budnik   redmine #5278
378
		return array(
16035364   Benjamin Renard   First commit
379
380
381
		'totalCount' => $intervals->length,
		'intervals'  => $result,
		'start' => isset($start) ? $start : 0,
d18b535d   elena   catalog draft + c...
382
		'limit' => isset($limit) ? $limit : 0,
16035364   Benjamin Renard   First commit
383
		'success'    => true
3ed056c4   Elena.Budnik   redmine #5278
384
385
		);   
	}
d18b535d   elena   catalog draft + c...
386
  
3ed056c4   Elena.Budnik   redmine #5278
387
388
389
390
391
392
	protected function createIntervalElement($interval) 
	{  
		$newInterval = $this->objectDom->createElement('intervals');
		$newInterval->appendChild($this->objectDom->createElement('start',$interval->start));
		$newInterval->appendChild($this->objectDom->createElement('stop',$interval->stop));
		return $newInterval;
169f14d2   Benjamin Renard   Add shared object...
393
	}
3ed056c4   Elena.Budnik   redmine #5278
394
395
396
397
398
399
400
401
402
403
404
405
	
	public function saveIntervals($id,$intervals,$action)
	{
		if (substr($id,0,6) == 'shared') {
			return array('success' => false, 'message' => "Cannot save shared TimeTable");
		}
		else {
			$path = USERTTDIR.$id.'.xml';		
		} 
		if (!file_exists($path))
			return array('success' => false, 'message' => "Cannot find TT file ".$id);
		$this->objectDom -> load($path);
16035364   Benjamin Renard   First commit
406
    
3ed056c4   Elena.Budnik   redmine #5278
407
408
		if (!($objToGet = $this->objectDom->getElementById($id))) 
			return array('success' => false, 'message' => NO_SUCH_ID." ".$id);
16035364   Benjamin Renard   First commit
409

3ed056c4   Elena.Budnik   redmine #5278
410
411
		//remove old intervals
		$crtNode = $objToGet->firstChild;
16035364   Benjamin Renard   First commit
412
    
3ed056c4   Elena.Budnik   redmine #5278
413
414
415
416
417
418
419
420
421
422
		while ($crtNode) {
			if (($crtNode->nodeType != XML_ELEMENT_NODE) || ($crtNode->tagName != 'intervals')) {	
				$crtNode = $crtNode->nextSibling;
				continue;
			}
			$toRemove = $crtNode;
			$crtNode = $crtNode->nextSibling;
			$objToGet->removeChild($toRemove);
			unset($toRemove);
		}
16035364   Benjamin Renard   First commit
423
      
3ed056c4   Elena.Budnik   redmine #5278
424
425
426
427
428
		//add new intervals
		foreach ($intervals as $interval) {	 
			$newInterval = $this-> createIntervalElement($interval);
			$this->objectDom->documentElement->appendChild($newInterval);
		}
16035364   Benjamin Renard   First commit
429

3ed056c4   Elena.Budnik   redmine #5278
430
431
432
433
		//save modifications
		$this->id = $id;
		$this->resFileName = USERTTDIR.$this->id.'.xml';
		$this->objectDom->save($this->resFileName);
16035364   Benjamin Renard   First commit
434
    
3ed056c4   Elena.Budnik   redmine #5278
435
		unset($this->objectDom);
16035364   Benjamin Renard   First commit
436
    
3ed056c4   Elena.Budnik   redmine #5278
437
438
		return array('success' => true,'action' => $action, 'nbIntervals' => count($intervals));
	}
16035364   Benjamin Renard   First commit
439
440
	
      
3ed056c4   Elena.Budnik   redmine #5278
441
442
443
444
445
446
447
448
	public function getUploadedObject($name, $format, $onlyDescription = false) 
	{
		if (strpos($name,'.txt') !== false || strpos($name,'.asc') !== false || strpos($name,'.') == false) {
			$attributesToReturn = $this->text2amda(USERTEMPDIR.$name, $onlyDescription);
			$attributesToReturn['objName'] = $name;
			$attributesToReturn['objFormat'] = $format;
			
			return $attributesToReturn;
16035364   Benjamin Renard   First commit
449
450
451
452
453
454
		}
		
		if ($format == 'VOT') {
			 $attributesToReturn = $this->vot2amda(USERTEMPDIR.$name, $onlyDescription);
			 $attributesToReturn['objName'] = $name;
			 $attributesToReturn['objFormat'] = $format;
3ed056c4   Elena.Budnik   redmine #5278
455
			 
16035364   Benjamin Renard   First commit
456
457
458
			 return $attributesToReturn;
		}
	 
3ed056c4   Elena.Budnik   redmine #5278
459
460
461
		if (strpos($name,'.xml') !== false) {
			$temp = explode('.xml', $name);
			$name = $temp[0];
16035364   Benjamin Renard   First commit
462
		}
3ed056c4   Elena.Budnik   redmine #5278
463
464
465
466
467
	
		if (!file_exists(USERTEMPDIR.$name.'.xml')) 
				return array('error' => 'no such name');
			  
		$this->objectDom->load(USERTEMPDIR.$name.'.xml');
16035364   Benjamin Renard   First commit
468
		if (!($objToGet = $this->objectDom->getElementsByTagName('timetable')->item(0)) && 
3ed056c4   Elena.Budnik   redmine #5278
469
470
			!($objToGet = $this->objectDom->getElementsByTagName('TimeTable')->item(0))) 
					return array('error' => 'no time table');
16035364   Benjamin Renard   First commit
471
472
473
474
475
476

		$attributes = $objToGet -> childNodes;
		$attributesToReturn['name'] = $name;
		$attributesToReturn['objName'] = $name;
		$attributesToReturn['objFormat'] = $format;

3ed056c4   Elena.Budnik   redmine #5278
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
		foreach($attributes as $attribute) {
			if($attribute->nodeType == XML_ELEMENT_NODE){
				if ($attribute->tagName == 'intervals') {
					$start = $attribute -> getElementsByTagName('start')->item(0) -> nodeValue;
					$stop = $attribute -> getElementsByTagName('stop')->item(0) -> nodeValue;
					if (!$onlyDescription)
						$attributesToReturn['intervals'][] = array('start' => $start, 'stop' => $stop);
				} 
				else if ($attribute->tagName == 'Interval') {
					$start = $attribute -> getElementsByTagName('Start')->item(0) -> nodeValue;
					$stop = $attribute -> getElementsByTagName('Stop')->item(0) -> nodeValue;
					if (!$onlyDescription)
						$attributesToReturn['intervals'][] = array('start' => $start, 'stop' => $stop);
				}
				else {
					switch (strtolower($attribute->tagName)) {
						case 'created' : 
							$attributesToReturn['created'] =  $attribute->nodeValue;
							break;
						case 'chain'  :
						case 'source' :  
							$attributesToReturn['description'] = $attribute->nodeValue;
							break;
						default:  break;
					}
				}
16035364   Benjamin Renard   First commit
503
			}
3ed056c4   Elena.Budnik   redmine #5278
504
		}
16035364   Benjamin Renard   First commit
505
506
507
		return  $attributesToReturn;
	}

3ed056c4   Elena.Budnik   redmine #5278
508
509
	//TODO getObject only!!!! => change DD_Search output
	public function getTmpObject($folderId, $name, $onlyDescription = false) {
16035364   Benjamin Renard   First commit
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
		$filePath = USERWORKINGDIR.$folderId.'/'.$name.'.xml';
		if (!file_exists($filePath)) 
			return array('error' => 'Cannot find result file');
		
		$dom = new DomDocument('1.0'); 
		$dom->formatOutput = true;
		
		if (!$dom -> load($filePath))
			return array('error' => 'Cannot load result file');
		
		$descNodes = $dom->getElementsByTagName('description');
		if ($descNodes->length > 0)
			$attributesToReturn['description'] = $descNodes->item(0)->nodeValue;
		
		$creatNodes = $dom->getElementsByTagName('created');
		if ($creatNodes->length > 0)
			$attributesToReturn['created'] = $creatNodes->item(0)->nodeValue;
		
		$histNodes = $dom->getElementsByTagName('history');
		if ($histNodes->length > 0)
			$attributesToReturn['history'] = $histNodes->item(0)->nodeValue;
	
		$attributesToReturn['objName'] = $name;
		$attributesToReturn['folderId'] = $folderId;
	
		if (!$onlyDescription)
		{
			$intNodes = $dom->getElementsByTagName('intervals');
			foreach ($intNodes as $intNode)
			{
				$startNodes = $intNode->getElementsByTagName('start');
				if ($startNodes->length <= 0)
					return array('error' => 'Error detected in result file');
				$stopNodes = $intNode->getElementsByTagName('stop');
				if ($stopNodes->length <= 0)
					return array('error' => 'Error detected in result file');
				$attributesToReturn['intervals'][] = array('start' => $startNodes->item(0)->nodeValue,
														'stop' => $stopNodes->item(0)->nodeValue);
			}
		}
		
		return  $attributesToReturn;
	}

3ed056c4   Elena.Budnik   redmine #5278
554
555
556
557
558
559
560
561
562
563
564
	/*
	* merge time tables
	*/
	public  function merge($obj)   {
	/**
	* Array of intervals, used like : 
	* [{start:'2010-01-01T23:00:00',stop:'2011-01-01T20:00:00'},{start:'2009-01-01T23:00:00',stop:'2010-01-01T20:00:00'}]
	* $attributesToReturn['intervals'][] = array('start' => $start, 'stop' => $stop);
	*/
		
		$intervals = 0;	
16035364   Benjamin Renard   First commit
565
    		
3ed056c4   Elena.Budnik   redmine #5278
566
567
568
569
570
571
572
573
		for ( $i = 0; $i < count($obj->ids); $i++ ) {
			$table[$i] = $this->loadIntervalsFromTT($obj->ids[$i]);
			for ($j=0; $j < count($table[$i]['intervals']); $j++) {
				$interval[$i][$j][0] = $table[$i]['intervals'][$j]['start'];
				$interval[$i][$j][1] = $table[$i]['intervals'][$j]['stop'];
			}
			$intervals += count($interval[$i]);
		}  
16035364   Benjamin Renard   First commit
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
    		if ( $intervals > 10000) set_time_limit(1800);
    		
    		$final = array();
    		for ( $i = 0; $i < count($obj->ids); $i++ ) {
    			$final = array_merge($final, $interval[$i]);        		
      		}
    		sort($final);
    		
    		// Algorithm of union
    		$line = 0;
        	$i = 0;
        	$a = $final[$i][0];
	        while ($i < count($final)-1) {
	           if ($final[$i+1][1] <= $final[$i][1])
	           {
	                  array_splice($final,$i+1,1);
	           }
	           else if (($final[$i+1][0] <= $final[$i][1]) && ($final[$i+1][1] >= $final[$i][1]))
	           {
	                  $i++;
	           }
	           else {
	                $start[$line] = $a;
	                $stop[$line] = $final[$i][1];
	                $i++;
	                $line++;
	                $a = $final[$i][0];
	           }
	        }
	        $start[$line] = $a;
	        $stop[$line] = $final[$i][1];
	        $line++;
        
		$objTT = new stdClass();	            	        
		$objTT->name = $obj->name;
    	$objTT->nodeType = 'timeTable';
    	$objTT->leaf = true;
    	$objTT->created = null;
    	$objTT->history = $obj->history;
    	for ($i=0; $i < count($start); $i++) {	
							$inter = new stdClass();
							$inter->start = $start[$i];
							$inter->stop = $stop[$i];
							$objTT->intervals[] = $inter;
    	}
    	$objTT->nbIntervals = count($start);
		$this->objectDom = new DomDocument('1.0'); 
		$this->objectDom->formatOutput = true;
 		
		$res = $this->createParameter($objTT, $folder);
		if ($res['error'])
		  return $res;
 		  
		$this->saveIntervals($res['id'],$objTT->intervals,'merge');
 		
		return $res;
		
    } 
    
/*
 * intersect time tables
 */
    public  function intersect($obj)   {
    	
    	for ( $i = 0; $i < count($obj->ids); $i++ ) {
    		$table[$i] = $this->loadIntervalsFromTT($obj->ids[$i]);
    		for ($j=0; $j < count($table[$i]['intervals']); $j++) {
  				$interval[$i][$j][0] = $table[$i]['intervals'][$j]['start'];
  				$interval[$i][$j][1] = $table[$i]['intervals'][$j]['stop'];
  			}
    		$intervals += count($interval[$i]);
    	}  
    	if ( $intervals > 10000) set_time_limit(1800);

    	// Sort intervals in time tables
        sort($interval[0]);
        sort($interval[1]);
            	
    	$i = 0;
	    $j = 0;
	    $line = 0;
	
	    while ( ($i < count($interval[0])) && ($j < count($interval[1])) ) {
	    	$inter = $this->call_intersection($interval[0][$i], $interval[1][$j]);
	
	        if ($inter[0][0] != 0 && $inter[0][1] != 0)
	        {
	        	$start[$line] = $inter[0][0];
	            $stop[$line] = $inter[0][1];
	            $line++;
	        }
	
	        if ( $interval[0][$i][1] < $interval[1][$j][1] ) { $i++; }
	        else {  $j++; }
	    }
	
	    // Intersection is empty
	    if ( $line == 0 ) {
	    	$result ="empty";
	    } 
	    else {
	    	$objTT->name = $obj->name;
    		$objTT->nodeType = 'timeTable';
    		$objTT->leaf = true;
    		$objTT->created = null;
    		$objTT->history = $obj->history;
    		for ($i=0; $i < count($start); $i++) {	
				$inter = new stdClass();
				$inter->start = $start[$i];
				$inter->stop = $stop[$i];
				$objTT->intervals[] = $inter;
    		}
    		$objTT->nbIntervals = count($start);
    		
    		if (count($objTT->intervals) == 0)
    		  $result ="empty";
    		else
    		{
    		  $this->objectDom = new DomDocument('1.0'); 
			     $this->objectDom->formatOutput = true;
	    	  $result = $this->createObject($objTT, $folder);
	    	
	       if (!isset($result['error']))
		        $this->saveIntervals($result['id'],$objTT->intervals,'intersect');
		
		     }  	
	    }
	    return  $result;		
    }
    
16035364   Benjamin Renard   First commit
704
705
706
707
708
709
710
711
712
713
714
715
716
717
         
         function validNameObject($p){
         	// overwritten
         	$res = parent::validNameObject($p);
         	 
         	if (!$res['valid'])
         		return $res;
         	 
         	//no space
         	if (strpos($p->name, ' ') === FALSE)
         		return array('valid' => true);
         	
         	return array('valid' => false, 'error' => 'Space character is not allowed');
         }
169f14d2   Benjamin Renard   Add shared object...
718
         
3ed056c4   Elena.Budnik   redmine #5278
719
720
	public function copyTT($src_path, $dst_path, $newId, $newName, $newDescription = NULL) 
	{
169f14d2   Benjamin Renard   Add shared object...
721
722
723
724
725
726
727
728
729
730
731
732
733
		if (!file_exists($src_path))
			return FALSE;
		
		if (!is_dir($dst_path))
			return FALSE;
		
		$dom = new DomDocument('1.0');
		$dom->formatOutput = true;
		
		if (!$dom->load($src_path))
			return FALSE;
		
		$timeTableNodes = $dom->getElementsByTagName('timetable');
247b38e9   Benjamin Renard   Fix function used...
734
		if ($timeTableNodes->length <= 0)
169f14d2   Benjamin Renard   Add shared object...
735
736
737
738
739
740
741
742
			return FALSE;
		
		$timeTableNode = $timeTableNodes->item(0);
		
		$timeTableNode->setAttribute('xml:id', $newId);
		
		$nameNodes = $timeTableNode->getElementsByTagName('name');
		
247b38e9   Benjamin Renard   Fix function used...
743
		if ($nameNodes->length <= 0) {
169f14d2   Benjamin Renard   Add shared object...
744
745
746
747
748
749
750
751
752
			//create name node (normally never append)
			$nameNode = $dom->createElement('name');
			$timeTableNode->appendChild($nameNode);
		}
		else
			$nameNode = $nameNodes->item(0);
		
		$nameNode->nodeValue = $newName;
		
09eefb2d   Benjamin Renard   Shared TT and Cat...
753
754
		if (isset($newDescription) && !empty($newDescription)) {
			$descriptionNodes = $timeTableNode->getElementsByTagName('description');
247b38e9   Benjamin Renard   Fix function used...
755
			if ($descriptionNodes->length <= 0) {
09eefb2d   Benjamin Renard   Shared TT and Cat...
756
757
758
759
760
761
				//create description node (normally never append)
				$descriptionNode = $dom->createElement('description');
				$timeTableNode->appendChild($descriptionNode);
			}
			else
				$descriptionNode = $descriptionNodes->item(0);
247b38e9   Benjamin Renard   Fix function used...
762
	
09eefb2d   Benjamin Renard   Shared TT and Cat...
763
764
765
			$descriptionNode->nodeValue = $newDescription;
		}
		
169f14d2   Benjamin Renard   Add shared object...
766
767
768
769
770
771
772
773
		$dst_file_path = $dst_path."/".$newId.".xml";
		if ($dom->save($dst_file_path) === FALSE)
			return FALSE;
		
		chgrp($dst_file_path, APACHE_USER);
		chmod($dst_file_path, 0775);
			
		return TRUE;
3ed056c4   Elena.Budnik   redmine #5278
774
	}
16035364   Benjamin Renard   First commit
775
776
}
?>