FilesMgr.php 43.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 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 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 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 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
<?php
/**
 * @class FilesMgr
 * @brief
 * @author Elena
 * @version $Id: FilesMgr.php 2830 2015-03-26 10:33:05Z elena $ 
 */

// private $userDirs = array('USERWSDIR' => 'WS', 'USERREQDIR' => 'REQ', 'USERDATADIR' => 'DATA',
//			     'USERWORKINGDIR' =>'RES', 'USERTTDIR' => 'TT', 'USERJOBDIR' => 'JOBS');	

class FilesMgr extends AmdaObjectMgr {

    private  $fileName, $fileId, $theFile;     
    public $xp;
    private $fileMgr = NULL; //used when a file format needs to use a specific manager
    private $sampling = -100.0, $maxSampling = -100.0;
    private $ncID = NULL;
    private $simuContentRootId;

    function __construct() 
    {   
        parent::__construct('Files.xml');
        $this->contentRootId = 'myData-treeRootNode';
        $this->contentRootTag = 'fileList';
        $this->attributes = array('name' => '', 'start' => '', 'stop' => '');
        $this->optionalAttributes = array();
        $this->objTagName = 'file';

        if (!file_exists($this->xmlName)) {
                $this->createDom();
                $this->xp = new domxpath($this->contentDom); 
        } 
    }

/*
*       Create Content Dom 'Files.xml' if it doesn't exist 	
*/	
    protected function createDom() 
    {                            
        $rootElement = $this->contentDom->createElement('ws');   
        
        $typeElement = $this->contentDom->createElement($this->contentRootTag);
        $typeElement->setAttribute('xml:id', $this->contentRootId);
        $rootElement->appendChild($typeElement);		
        $this->contentDom->appendChild($rootElement);
        
      //  $typeElement = $this->contentDom->createElement($this->contentRootTag);
      //  $rootElement->appendChild($typeElement);		
      //  $this->contentDom->appendChild($rootElement);
        
        $this->contentDom->save($this->xmlName);          
    }
    
/*
 *    VOTable format processing done by an instance of VOTableMgr
 */

    protected function getVotFileMgr()
    {
        if (!$this->fileMgr)
        {
            $this->fileMgr = new VOTableMgr();
            $this->fileMgr->load($this->fileName);
        }

        return $this->fileMgr;
    }

      
/*
*     CDF format processing
*/      
    protected function getCdfStartStop() 
    {  
        exec('cdfstartstopfromdata '.$this->fileName, $start_stop); 
        return $start_stop[0];  
    }

    protected function getCdfVars() 
    {
        exec('cdfinfo '.$this->fileName, $results);
        return $results;
    }


    protected function getCdfVarInfo($cdfVarId) 
    {
        exec('cdfvarinfo '.$this->fileName.' '.$cdfVarId, $results);
        $tempArr = explode(' ', $results[0]);
        // data type
        switch ($tempArr[0]) 
        {
            case "CDF_FLOAT" :
            case "CDF_REAL4" : $data_type = 'FLOAT';
                            break;
            case "CDF_INT2":  
            case "CDF_UCHAR":  
            case "CDF_UINT1" : $data_type = 'SHORT';
                            break;
            case "CDF_UINT2":
            case "CDF_INT4" : $data_type = 'INTEGER';
                            break;
            case "CDF_DOUBLE":  
            case "CDF_REAL8":   
            case "CDF_UINT4":  $data_type = 'DOUBLE'; 
                            break;
            default : $data_type = 'FLOAT';
        }
        // data dimensions & number of records
        $n_recs = $tempArr[2];

        if ($tempArr[1] != 0) {		 
            $size = $tempArr[3];
            //TODO 2D,3D,4D array no processing	
            //   if ($tempArr[1] > 1) 
        }
        else {
            $size = 1;		  
        } 
 
        return array('type' => $data_type, 'size' => $size, 'n_records' => $n_recs);
    }

    protected function getCdfSampling() 
    {
        copy($this->fileName, "temp.cdf");         
        exec('cdfsamplingfromdata ', $results);
        unlink("temp.cdf");

        return $results;
    }


/*
*       CEF format processing
*/
    protected function getCefStartStop() {  
        exec("cefstartstop ".$this->fileName, $start_stop);
        return $start_stop[0];
    }

    protected function getCefTimeInfo() {  

        $timeinfo = exec("ceftimeinfo ".$this->fileName);

        return $timeinfo;
    }

    protected function getCefVars() {
        exec('cefinfo '.$this->fileName, $results);
        return $results;
    }

    protected function getCefVarInfo($cdfVarId) {
        exec('cefvarinfo '.$this->fileName." ".$cdfVarId, $results);

        $tempArr = explode(' ', $results[0]);
        // data type
        switch ($tempArr[0]) {
            case "CEF_FLOAT" : $data_type = 'FLOAT';
                                break;
            case "CEF_SHORT":  $data_type = 'SHORT';
                                break;
            case "CEF_INT":  $data_type = 'INTEGER';
                            break;
            case "CEF_DOUBLE": $data_type = 'DOUBLE'; 
                            break;
            default : $data_type = 'FLOAT';
            }
        // data dimensions & number of records3
        $n_recs = $tempArr[2];

        if ($tempArr[1] != 0) {		 
            $size = $tempArr[3];
        //TODO 2D,3D,4D array no processing	
        //   if ($tempArr[1] > 1) 
        }
        else {
            $size = 1;		  
        } 
 
        return array('type' => $data_type, 'size' => $size, 'n_records' => 'TBD');       
    }

    protected function getCefSampling() {
        exec('cefsampling '.$this->fileName, $results);        
        return $results;
    }

/*
*       netCDF format processing if needed
*/
    protected function reformatNcTime() {
        exec('nctimestring2double '.$this->fileName, $results); 
        return $results[0]; 
    }
        
    protected function getNcTimeInfo() {
        exec('nctimeinfo '.$this->fileName, $result); 
        return $result[0];  
    }

    protected function  getNcVars(){
        exec('getncvars '.$this->fileName, $result); 
        if ($result[0] < 0)
                    return $result[0];
        $varsArr = explode("#",$result[0]);
	 
        return  $varsArr;
    }

    protected function getNcVarInfo($varId) {

        exec('ncvarinfo '.$this->fileName.' '.$this->param2dd($varId), $results);
        $tempArr = explode(' ', $results[0]); 
    // data type
        switch ($tempArr[0]) {
            case "5": $data_type = 'FLOAT';
                    break;
            case "3": $data_type = 'SHORT';
                    break;
            case "4" : $data_type = 'INTEGER';
                    break;
            case "6": $data_type = 'DOUBLE';               
                    break;
            default: $data_type = 'FLOAT';
            }
        // data dimensions & number of records
        $n_recs = $tempArr[2];

            if (count($tempArr) > 3) {		 
                $size = $tempArr[3];
            //TODO 2D,3D,4D array no processing	
            //   if ($tempArr[1] > 1) 
            }
            else {
                $size = 1;		  
            }  
        return array('type' => $data_type, 'size' => $size, 'n_records' => $n_recs);
    }
    
    protected function param2dd($paramID)
  {
      $pairs = array("-" => "_", "%" => "_","\\" => "_","$" => "_",":" => "_","+" =>" _","-" => "_","#" => "_","@" => "_", "." => "_",">" => "_", "<" => "_");    
      return strtr($paramID, $pairs); 
  }

/*
*      ascii format processing
*/    
    protected function getTxtSampling() {
        
            $StartTime = null;
            if (!file_exists($this->fileName)) return -100;     
            $i = 0;
            $dt = -10;
            
            $handler = fopen($this->fileName, 'r');
            if ($handler) {
                while (!feof($handler) && !$StartTime) {
                        $oneLine = trim(fgets($handler)); 
                        $elems = explode(" ", preg_replace('/\s+/', ' ', $oneLine));
                        if ((strlen($elems[0]) < 16) || !($time = strtotime($elems[0]))) { 
                            $i++;
                            continue;
                    }                   
                    $StartTime = $time;                    
                    if (is_numeric($elems[1])) $dt = $elems[1];  
						  //else Array for sure !!!
                }
            }

            if (feof($handle)) return -10;

            $oneLine = trim(fgets($handler));      
            $elems = explode(" ",$oneLine);
            if (count($elems) < 2) return -10;

            // dT else Array
            if (!($time = strtotime($elems[0]))) {
						return $dt;
            }
           
           return $time  - $StartTime;          
        }

 
    public function getTxtSamplings() {
    
        $StartTime = null;
        if (!file_exists($this->fileName)) return array(-100);

        $handler = fopen($this->fileName, 'r');
        if ($handler) {
            $i = 0;
            while (!feof($handler) && !$StartTime) {
                    $oneLine = trim(fgets($handler)); 
                    $elems = explode(" ", preg_replace('/\s+/', ' ', $oneLine));
                    if (strlen($elems[0]) < 16 || !($time = strtotime($elems[0]))) { 
                            $i++;
                            continue;
                }   
            
                    $StartTime = $time;
                    if (!(is_numeric($elems[1]))) return array(-10); 
                    $dt = $elems[1];                  
            } 
        } 
        
        if (feof($handle)) return array(-10);
        $oneLine = trim(fgets($handler));
        $elems = explode(" ",$oneLine);
        if (count($elems) < 2) return array (-1);
        // dT else Array
        if (!($time = strtotime($elems[0]))) return array($dt);
        else {
                $minSampling = +1.e31;
                $maxSampling = 0.0;

                while (!feof($handler)) {
                    $oneLine = trim(fgets($handler));
                    $elems = explode(" ",$oneLine); 
                    if (count($elems) < 2) continue;
                    $StartTime = $time;
                    if (!($time = strtotime($elems[0]))) return array(-1);                       
                    $deltaT[$time  - $StartTime]++;                                       
                }

                foreach ($deltaT as $key => $value) {
                            if ($value < 5) continue;
                            if ($key < $minSampling) $minSampling = $key;
                            if ($key > $maxSampling) $maxSampling = $key;
                } 

            return array($minSampling,$maxSampling); 
        }         
      }

/*
*        Delete comments and convert time into double
*/
     public function reformatTxt() {
        
         $StartTime = null;
         if (!file_exists($this->fileName)) return  -100;

         $handler = fopen($this->fileName, 'r');
         if ($handler) {  
            $offset = ftell($handle);
            $i = 0;
            while (!$StartTime && !feof($handler)) {
                $oneLine = trim(fgets($handler));
                $elems = explode(" ", preg_replace('/\s+/', ' ', $oneLine));
                if (!($time = strtotime($elems[0]))) {
                        $offset = ftell($handle);
                        $i++;
                        continue;
                }            
                $StartTime = $time;
                $dt = $elems[1];
            }  
        }
                 
        $newfile = fopen(USERDATADIR."temp", "w");
         
        $oneLine = trim(fgets($handler));   
        $elems = explode(" " , $oneLine);
        // dT
           if (!($time = strtotime($elems[0]))) { 

               $newtime = $StartTime;  
               settype($dt, "float"); 
               if ($oneLine != PHP_EOL && count($elems) > 0) fwrite($newfile,  $newtime." ".$oneLine.PHP_EOL);
               $newtime += $dt; 
 
               while (!feof($handler)) { 
                    $oneLine = trim(fgets($handler));                      
                    if ($oneLine != PHP_EOL && count($elems) > 0) fwrite($newfile,  $newtime." ".$oneLine.PHP_EOL);
                    $newtime += $dt;  
                  }
           }
            // Array
          else { 
                fseek($handler, $offset);
                while (!feof($handler)) { 
                    $oneLine = trim(fgets($handler));
                    $elems = explode(" " ,$oneLine);
                    // empty lines
                    if (count($elems) < 2) continue;
                    $newtime = strtotime($elems[0]); 
                    //TODO Error message if wrong time format...???
                    if (!$newtime) continue; 
                    unset($elems[0]); 
                    $newline = join($elems," ");
                    fwrite($newfile,$newtime." ". $newline.PHP_EOL);                                   
                  }
           }
           fclose($newfile);

           rename(USERDATADIR."temp",$this->fileName);     

         return $StartTime." ".$newtime; 
      }

/*
*  Convert time into ISO
*/
    protected function reformatTime($timeFormat, $timeLength, $doy) {
                   
         $formatLength = $timeLength == 'auto' ? strlen($timeFormat) + (strpos($timeFormat,"Y") !== false)*3 + (strpos($timeFormat,"y") !== false)
					     + (strpos($timeFormat,"M") !== false)*2  + (strpos($timeFormat,"m") !== false)
                                             + (strpos($timeFormat,"d") !== false) + (strpos($timeFormat,"H") !== false)
                                             + (strpos($timeFormat,"i") !== false) + (strpos($timeFormat,"s") !== false) 
					     + (strpos($timeFormat,".u") !== false)*2 : $timeLength;
 
	  if (strpos($timeFormat,".u") !== false) {
		$formatLength = $formatLength - 4;
		$timeFormat = substr($timeFormat, 0, strlen($timeFormat)-2);
	  }

         if (strpos($timeFormat,".k") !== false) {
                $formatLength = $formatLength - 2;
                $timeFormat = substr($timeFormat, 0, strlen($timeFormat)-2);
          }

         $handle = fopen($this->fileName,'r');
   
         if ($handle) {    
           $newfile = fopen(USERDATADIR."temp", "w");
           while (!feof($handle)) {
            if (($oneLine = fgets($handle)) !== false) {
                $line = $timeLength == 'auto' ? $line = trim(preg_replace('/\s+/', ' ', $oneLine)) : trim($oneLine);    
        
                if (strlen($line) > $formatLength) {   
                try 
                    {
                        $date = DateTime::createFromFormat($timeFormat, trim(substr($line,0,$formatLength)));
                        if (!$date) {
                            if (strpos($line,'#') === 0)  fwrite($newfile, $line.PHP_EOL);
                            }
                        else {
                            // DOY starts from 1
                            if ($doy) {
                                $date->modify('-1 day');
                            }
                            $suffix =  preg_replace('/\s+/', ' ',substr($line, $formatLength));
                            fwrite($newfile,$date->format('Y-m-d')."T".$date->format('H:i:s').$suffix.PHP_EOL);
                        }
                    }
                    catch (Exception $e) 
                    {		  			  
                        // fwrite($newfile,$line.PHP_EOL);			   
                    }               	       
                } 
                else 
                    if (strpos($line,'#') === 0) fwrite($newfile,$line.PHP_EOL); 
                }
            }
          }
          else {
            if (file_exists($this->fileName)) {
                    fclose($handle); 
                    unlink($this->fileName);
                }
            return $false;
           }

          fclose($newfile); 
          fclose($handle);

         rename(USERDATADIR."temp", $this->fileName);  
         return true; 
      }
   

/*
*       Returns number of columns in text file to create data model fields in MyDataUI.js 
*/
      protected function getTxtColNumber($timeDouble) {
	  
	  if (!file_exists($this->fileName)) return  -100;
          $handle = fopen($this->fileName,'r');

          if ($handle) {
            $found = false;
            $i = 0;
            while (($line = trim(fgets($handle))) !== false && $i < 100) {
                 $elems = explode(" ", preg_replace('/\s+/', ' ', $line));
                 $i++;
                 if (count($elems) < 2 || strpos($elems[0], '#') === 0) continue;
              
                 if (!$timeDouble) {
                        if (strlen($elems[0]) >= 16 && ($time = strtotime($elems[0]))) {
                                        $found = true;
                                        break; 
                            }
                    }
                 else {
                        $found = true;
                        break; 
                    }
                }

            if (!feof($handle) && !$found) {
                fclose($handle);
                unlink($this->fileName);
                return -1;
                }
            }       
         fclose($handle);
 
      	 if (!$found) {
                unlink($this->fileName);
                return 0; 
          }
	 return count($elems);
      }
    
/*
*      new file tag in Files.xml
*/      
	protected function createSimuFile($format) { 
             
                  $newFile = $this->contentDom->createElement('file');
		  $newFile->setAttribute('xml:id', $this->fileId);
		  $newFile->setAttribute('name', $this->fileId);
		  $newFile->setAttribute('format', $format);

		  $start_stop = explode(" ",$this->getVotFileMgr()->getStartStop());
		  $samplings = $this->getVotFileMgr()->getSamplings();
		  $minSamp = $samplings["minSampling"];
		  $maxSamp = $samplings["maxSampling"];
		  $desc = $this->getVotFileMgr()->getDescription();

		  $start =  $start_stop[0];
		  $stop =  $start_stop[1];
                
		  $newFile->setAttribute("start",$start);
		  $newFile->setAttribute("stop",$stop);
		  $newFile->setAttribute('minsampling',$minSamp);
		  $newFile->setAttribute('maxsampling',$maxSamp);
		  $newFile->setAttribute('uploaded', date('Y-m-d H:i:s'));
		  
// generic MASK without datas for simu params
		  if ((strncmp($this->fileId, "impex___", 8) == 0) || (strncmp($this->fileId, "spase___", 8) == 0))
		    $newFile->setAttribute('mask', $this->getGenericMask());

		   $newFile->nodeValue = date('Y-m-d',$start)."T".date('H:i:s',$start)."-".date('Y-m-d',$stop)."T".date('H:i:s',$stop);
		   if ($desc != '')
		   	 $newFile->nodeValue .= (PHP_EOL.$desc);
                   return $newFile;   
     }


          protected function createFile($format) { 
             
                $newFile = $this->contentDom->createElement('file');
		  $newFile->setAttribute('xml:id', $this->fileId);
		  $newFile->setAttribute('name', $this->fileId);
		  $newFile->setAttribute('format', $format);

                  switch ($format){
		    case "cdf":  
			   $start_stop = explode(" ",$this->getCdfStartStop());
			   $result = $this->getCdfSampling();
//TODO process errors
			   $minSamp = $result[count($result)-1];
//TODO if min & max
			   $maxSamp =  $minSamp;
                          break;            
		    case "txt":   
			  $start_stop =  explode(" ",$this->reformatTxt());
                          if ($start_stop[0] < 0)  return $start_stop;
			  $minSamp = $this->sampling;
			  $maxSamp = $this->maxSampling;
                          break; 
                    case "cef":

                          // Test if 'standard' meta exist in CEF
                          $cefMetaTest = $this->getCefStartStop(); 
  
                          if ($cefMetaTest != -1) {
                            $cefStartStop = explode("/",$cefMetaTest); 
                            $start_stop[] = strtotime($cefStartStop[0]);
                            $start_stop[] = strtotime($cefStartStop[1]); 			   
                            $result = $this->getCefSampling();
                            $minSamp = $result[count($result)-1];
                           }
                           else {
                            // no META data - so time processing
                            $timeInfo = $this->getCefTimeInfo();
                            $timeInfoArr = explode(" ", $timeInfo);
                            $start_stop[] =  $timeInfoArr[0];
                            $start_stop[] =  $timeInfoArr[1];
                            $minSamp = $timeInfoArr[2];
                           }
//TODO if min & max
			   $maxSamp =  $minSamp;
                          break;
                    case "vot" :
			  $start_stop = explode(" ",$this->getVotFileMgr()->getStartStop());
			  $samplings = $this->getVotFileMgr()->getSamplings();
			  $minSamp = $samplings["minSampling"];
			  $maxSamp = $samplings["maxSampling"];
			  $desc = $this->getVotFileMgr()->getDescription();
                    	 break;  
		    case "nc":  
			   $ncInfo = $this->getNcTimeInfo();
			   if ($ncInfo < 0) {
				      unlink($this->fileName);
				      return $ncInfo;
			   }
                           $ncInfoArr = explode("#",$ncInfo);
			   $start_stop = explode(":",$ncInfoArr[0]);			   
//TODO process errors
			   $minSamp = $ncInfoArr[1];
//TODO if min & max
			   $maxSamp =  $minSamp;
                          break;   
                    default: 

                  }
		  $start =  $start_stop[0];
		  $stop =  $start_stop[1];
                
		  $newFile->setAttribute("start",$start);
		  $newFile->setAttribute("stop",$stop);
		  $newFile->setAttribute('minsampling',$minSamp);
		  $newFile->setAttribute('maxsampling',$maxSamp);
		  $newFile->setAttribute('uploaded', date('Y-m-d H:i:s'));
		  
// generic MASK without datas for simu params		  
		  if ((strncmp($this->fileId, "impex___", 8) === 0) || (strncmp($this->fileId, "spase___", 8) === 0))
		    $newFile->setAttribute('mask', $this->getGenericMask());
		  else
		    $newFile->setAttribute('mask', $this->fileId);

		   $newFile->nodeValue = date('Y-m-d',$start)."T".date('H:i:s',$start)."-".date('Y-m-d',$stop)."T".date('H:i:s',$stop);
		   if ($desc != '')
		   	 $newFile->nodeValue .= (PHP_EOL.$desc);
		   
                  return $newFile;   
     }
     
     protected function getGenericMask() {
	  if (strncmp($this->fileId, "impex___", 8) == 0) {
	      $prefix = "impex___";
	      $tmpFileName = str_replace ("impex___", "", $this->fileId);
	  }
	  elseif (strncmp($this->fileId, "spase___", 8) == 0) {
	      $prefix = "spase___";
	      $tmpFileName = str_replace ("spase___", "", $this->fileId);
	  }
	  $tmpFileArray = explode( '.', $tmpFileName);
	  $tmpParamArray = explode( '_', $tmpFileArray[0]);
	  array_pop($tmpParamArray);
	  array_pop($tmpParamArray);
	  $tmpName =  implode("_", $tmpParamArray);
	  
	  $mask = $prefix.$tmpName."_*.xml";
	  return $mask;
     }

/*
//TODO  check how to upgrade this
*/
      protected function getFormat() {
         
        $ext = pathinfo($this->fileName, PATHINFO_EXTENSION);   

	if (PHP_VERSION_ID < 50300) {
	    $finfo = new finfo(FILEINFO_MIME, MAGIC_FILE);    
	    $file_info =   explode(";", $finfo->file($this->fileName));
	}
      else {
  // PHP v >= 5.3 comes with its own magic file  !!!!   
	  $finfo = finfo_open(FILEINFO_MIME); 
	  $file_info =  explode(";",finfo_file($finfo, $this->fileName));
	}

	  if (strpos($file_info[0],"plain") !== false) {
	      if (strpos($ext,"cef") !== false) return "cef";
	      return "txt";
	  }

          if (strpos($file_info[0],"application/x-gzip") !== false) {
                      if (strpos($this->fileName,"cef.gz") !== false) return "cef";  
          }

	  if (strpos($file_info[0],"application/xml") !== false)
	  {
		//if ($this->getVotFileMgr()->isValidSchema()) //BRE : No schema validation for the moment due to some trouble with Topcat (it can create not valid VOTable)
				return "vot";
	  }
	  
  // check binary at different machines - if it works.....
	  if (strpos($file_info[0],"octet-stream") !== false) {
	      if (strpos($ext,"cdf") !== false) return "cdf"; 
	      if (strpos($ext,"nc") !== false) return "nc";
    
	  }
	  return "unknown";      
      }

/*
*         PUBLIC FUNCTIONS
*/ 
    
      public function getAsciiFile($name) {
 
	  $this->fileName = USERDATADIR.$name;

	  if (!file_exists(USERDATADIR.$name)) 
 	 	      return  array('success' => false, 'error' => 'No such file');
 	 
	  $handle = fopen($this->fileName, "r");
	  $fileToReturn = array();
          $index = 0;
          $tempFileToReturn =  array();

	  while (!feof($handle)) {
	      $line = trim(fgets($handle));
	      $tempArr = explode(' ', preg_replace('/\s+/', ' ', $line));
              if (count($tempArr) > 1) {
	       for ($i = 0; $i < count($tempArr); $i++) {
		      $name = $i === 0 ? 'Time' : 'n'.$i;
//transform double time to ISO
                      if ($name == 'Time') {
			      $temp = $tempArr[0];
			      settype($temp, 'double');
			      $tempArr[0] = date('Y-m-d H:i:s', $temp);
		      }
		      $tempFileToReturn[$name] = $tempArr[$i];
	      }
	      $fileToReturn[$index] = $tempFileToReturn;
	      $index++;
	      if ($index > MAX_FILE_INDEX_TO_SHOW) break;
	  }
        }
 	  return $fileToReturn;
      }


/*
*     Get  info on parameter
*/
      public function getParamInfo($obj){

	      $this->fileName = USERDATADIR.$obj->file;
	      $varId = $obj->varName;
              $format = $obj->format;

// at first info from Files.xml
	      $file = $this->contentDom->getElementById($obj->file);
	      if ($file) {
                if ($file->parentNode->tagName == 'folder') 
                                     $mask = $file->parentNode->getAttribute('name');
                else 
                                     $mask = $file->getAttribute('mask');
		$dom_info =  array( 'name' => $varId,
				    'minsampling' => $file->getAttribute('minsampling'),
				    'maxsampling' => $file->getAttribute('maxsampling'),
				    'mask' => $mask);		 
	      }
	      else {
	      if ($format == "nc"){ 
	      $status = $this->reformatNcTime();
	      if ($status <= 0) {
                    unlink($this->fileName);
                    return array('success' => false, 'error' => 'error '.$timeFormat.PHP_EOL.'Time Format problem');	
                }
		  $ncInfo = $this->getNcTimeInfo(); 
		  $ncVars = $this->getNcVars();
			      if ($ncInfo < 0) {
					  unlink($this->fileName);
					  return $ncInfo;
			      }
			      $ncInfoArr = explode("#",$ncInfo);
			      $start_stop = explode(":",$ncInfoArr[0]);			   
    //TODO process errors
			      $minSamp = $ncInfoArr[1];
    //TODO if min & max
			      $maxSamp =  $minSamp;
			      
			      $dom_info =  array( 'name' => $varId,
				    'minsampling' => $minSamp,
				    'maxsampling' => $maxSamp,
				    'mask' => $obj->mask);	
		  }
	      }

	      switch ($format){
		      case "cdf":  
			    $info = $this->getCdfVarInfo($varId);			      
			    break;   
		      case "txt":   			  
			    break; 
		      case "cef":   
			     $info = $this->getCefVarInfo($varId);
			    break; 
		      case "nc":  
			     $info = $this->getNcVarInfo($varId);
			    break;
		      case "vot":
		      	 $info = $this->getVotFileMgr()->getFieldInfoByID($varId);
		        break;
		      default: 

		    }
	    return  array('success' => true, 'info' => array_merge($dom_info,$info));
     }

 
    public function deleteObject($obj) 
    {
        $myBaseManager = new BaseManager();
  
        $paramMgr = new DerivedParamMgr('myDataParam');                
        $xpd = new domxpath($paramMgr->contentDom); 

        //File, not a folder
        if ($obj->leaf) {  
            $this->fileName = USERDATADIR.$obj->id;

            if (file_exists($this->fileName)) 
                                    unlink($this->fileName);

            $theFile = $this->contentDom->getElementById($obj->id);
           
    
            // Update data base	                   
            $fileInBase = $myBaseManager->xp->query("//file[@name='".$obj->id."']");
 
            if ($fileInBase->length > 0) { 
                        $viInfo = $myBaseManager->delFile($fileInBase->item(0));

                        $mask = $viInfo['mask'];
                        $length = $viInfo['length'];
                     
                        $params = $xpd->query("//mydata[@mask='".$mask."']"); 
  
                        if ($params->length > 0) {  
                                // NO FILES in the mask;  corresponding parameters are to be deleted
                                if ($length == 0) {
                                    $paramsToDelete = array();
                                    for ($i = $params->length; --$i >= 0; ) {
                                        $id = $params->item($i)->getAttribute('xml:id');
                                        $paramMgr->deleteParameter($id);
                                        $paramMgr->deleteFromContent($params->item($i));
                                        $paramsToDelete[] = $id;
                                    }                                       
                                }
                                // update params description in Content Dom
                                else {
                                    $vi = $myBaseManager->getVi($mask);   
                                    $desc =  $myBaseManager->getStartStop($vi);
                                    foreach ($params as $param) $param->setAttribute("desc",$desc); 
                                    $paramMgr->saveContent();
                                }				  		
                            }                
                        }  
   	   // WS/Files.xml
            if ($theFile) {
                if ($desc) 
                        $theFile->parentNode->setAttribute('info', $desc);
                $theFile->parentNode->removeChild($theFile);               
                $this->contentDom->save($this->xmlName); 
            }
        }
        // Folder
        else {
                $mask = $obj->id;
                $theMask = $this->contentDom->getElementById($obj->id);
                $files = $theMask->getElementsByTagName('file');

                foreach ($files as $file) {
                    $fileName = USERDATADIR.$file->getAttribute('name');  	  
                    if (file_exists($fileName)) unlink($fileName); 
                }

                $this->deleteFromContent($theMask); 
                $myBaseManager->delVI($mask);  

                $params = $xpd->query("//mydata[@mask='".$mask."']");  
                $paramsToDelete = array();
                for ($i = $params->length; --$i >= 0; ) {
                    $id = $params->item($i)->getAttribute('xml:id');
                    $paramMgr->deleteParameter($id);
                    $paramMgr->deleteFromContent($params->item($i));
                    $paramsToDelete[] = $id;
                }
            }
        // No more files for myDataParams	
        if ($paramsToDelete) 
                        return array('id' => $obj->id, 'params' => $paramsToDelete);

        // update info for myDataParams Start Stop were changed
        return  array('id' => $obj->id, 'mask' => $mask, 'maskDesc' => $desc);
    }
        
    
    public function deleteSimuObject($obj) {

	$myBaseManager = new BaseManager();  
	$paramMgr = new DerivedParamMgr('mySimuParam');                
	$xpd = new domxpath($paramMgr->contentDom); 

	 if ($obj->leaf) {  
	      $this->fileName = USERDATADIR.$obj->id;
 
              if (file_exists($this->fileName)) unlink($this->fileName);
	      $theFile = $this->contentDom->getElementById($obj->id);
	      if ($theFile) {
		  $theFile->parentNode->removeChild($theFile);
		  $this->contentDom->save($this->xmlName); 
	      }
    
// update base data	       
               
		$fileInBase = $myBaseManager->xp->query("//file[@name='".$obj->id."']");
                if ($fileInBase->length > 0) { 
                          $mask = $myBaseManager->delFile($fileInBase->item(0));
			 			  
			  $params = $xpd->query("//mydata[@mask='".$mask."']"); 
			  if ($params->length > 0) {
// NO FILES in the mask;  corresponding parameters are to be deleted
				  if (strcmp($mask, "NONEMPTY") != 0) {
				      $paramsToDelete = array();
				       for ($i = $params->length; --$i >= 0; ) {
					$id = $params->item($i)->getAttribute('xml:id');
					$paramMgr->deleteParameter($id);
					$paramMgr->deleteFromContent($params->item($i));
					$paramsToDelete[] = $id;
				      }                                       
				    }
// update params description in Content Dom
				  else {
					$vi = $myBaseManager->getVi($mask);
					$desc =  $myBaseManager->getStartStop($vi);
					foreach ($params as $param) $param->setAttribute("desc",$desc); 
					$paramMgr->saveContent();
				    }				  		
			  }                
		      }     	  
	}
        else {
	      $mask = $obj->id;
	      $theMask = $this->contentDom->getElementById($obj->id);
	      $files = $theMask->getElementsByTagName('file');
	      foreach ($files as $file) {
		  $fileName = USERDATADIR.$file->getAttribute('name');  	  
		  if (file_exists($fileName)) unlink($fileName); 
		}
	      $this->deleteFromContent($theMask); 
	      $myBaseManager->delVI($mask);  

	      $params = $xpd->query("//mydata[@mask='".$mask."']");  
	      $paramsToDelete = array();
	      for ($i = $params->length; --$i >= 0; ) {
		    $id = $params->item($i)->getAttribute('xml:id');
		    $paramMgr->deleteParameter($id);
		    $paramMgr->deleteFromContent($params->item($i));
		    $paramsToDelete[] = $id;
	      }
	  }
	
	  if ($paramsToDelete) return array('id' => $obj->id, 'params' => $paramsToDelete);
	  else return  array('id' => $obj->id);
	}
 
/*
*      recombine files in Files.xml according to new Mask
*/
   public function addMask($fileMask, $type) { 
            if ($this->contentDom ->getElementById($fileMask) != null) return false; 
	    $filesInRoot = $this->xp->query("/ws/fileList/file");                                   
            $newMask = $this->contentDom->createElement("folder");
            $newMask->setAttribute('xml:id', $fileMask);
	    $newMask->setAttribute('name', $fileMask);
     
	    for ($i =  $filesInRoot->length; --$i >= 0;)  {
                 $aFile =  $filesInRoot->item($i);
  
// mask corresponds to file name		 
                 if ($this->fileMask($aFile->getAttribute("name"),$fileMask)) {                          
                                              $newMask->appendChild($aFile); 
                  }                          
	    }

            $files = $newMask->getElementsByTagName("file");
	    if ($files->length == 0) return false;
 
            foreach ($files as $file) {
                   $starts[] =  $file->getAttribute("start");
                   $stops[] =  $file->getAttribute("stop");
            }
 
            $newMask->setAttribute('info',date('Y-m-d',min($starts))."T".date('H:i:s',min($starts))."-".date('Y-m-d',max($stops))."T".date('H:i:s',max($stops)));

	    $fileList = $this->contentDom->getElementById($this->contentRootId);
	      
            $fileList->appendChild($newMask);
            $this->contentDom->save($this->xmlName); 
            return true;
    }

/*
*    check correspondence FleName <=> Mask
*    returns true if Mask fits FileName
*/
  public function fileMask($fileName, $maskName) {
    
        $mask = explode("*", $maskName); 
        if (strpos($fileName, $mask[0]) !== 0) return false; 
        if (count($mask) == 1) return true;

        for ($i = 1; $i < count($mask); $i++)  
          if ($mask[$i] != null)
             if (strpos($fileName, $mask[$i]) === false) return false;  

         return true;
     } 

/*
*    Delete Mask
*/
     public function delMask($oldMask) {
 
            $mask = $this->contentDom->getElementById($oldMask);

            if ($mask != null && $mask->tagName == "folder") {                                                                                                               
                $filesInMask = $mask->getElementsByTagName("file");
                $fileList = $this->contentDom->getElementById($this->contentRootId); 

                while ($filesInMask->length > 0) 
                    $fileList->appendChild($filesInMask->item(0));
                       
                $fileList->removeChild($mask); 
                $this->contentDom->save($this->xmlName);

                return true;
            }

      return false;
     }

/*
*     mask or file
*/
      public function getObject($name) {
 
                $object = $this->contentDom->getElementById($name);
                 
                if (is_object($object)) {   
                    // mask
                    if ($object->tagName == 'folder') {
                        $file = $object->getElementsByTagName('file');
                        if ($file->length > 0) 
                                return $this->getUploadedObject($file->item(0)->getAttribute('name'));
                        else 
                                return array('success' => false, 'error' => 'Mask is empty');
                    }
                }
                else 
                    return array('success' => false, 'error' => 'No such mask in DOM');
            // file
            return $this->getUploadedObject($name);
    }

/*
*  Get generic info on uploaded file
*/
      public function getUploadedObject($name) {

                $this->fileName = USERDATADIR.$name;
                $file = $this->contentDom->getElementById($name);
                if (!$file) 
                        return array('success' => false, 'error' => 'No such file in DOM');

                $format = $file->getAttribute('format');
                $minSamp =  $file->getAttribute('minsampling');
                $maxSamp =  $file->getAttribute('maxsampling');

                $mask = $file->parentNode->tagName  == "folder" ? $file->parentNode->getAttribute("name") : null;
                $maskDesc = $mask ? $file->parentNode->getAttribute('info') : null;
                $desc = $file->nodeValue;
                
                $foundTime = true;
                
                switch ($format){
                        case "cdf":  
                                    $vars = $this->getCdfVars(); 
                                    break;            
                        case "txt":   
                                    $vars = $this->getTxtColNumber(true);                                 
                                    break; 
                        case "nc" :
                                    $vars = $this->getNcVars();
                                    break;
                        case "cef":   
                                    $vars = $this->getCefVars(); 
                                    break;
                        case "vot" :
                                    $vars = $this->getVotFileMgr()->getFieldsInfo();
                                    $foundTime = ($this->getVotFileMgr()->getTimeFieldIndex() > -1);
                                    break;          
                        default: 
                }

            return  array('success' => true, 'format' => $format, 'vars' => $vars, 'fileName' => $name, 
                            'minsampling' => $minSamp, 'maxsampling' => $maxSamp, 'mask' => $mask, 'maskDesc' => $maskDesc,
                            'description' => $desc, 'foundTime' => $foundTime);
        }

/*
*      The very first processing of newly uploaded file file
*      $formats = array('fileFormat', 'timeFormat', 'timeSampling', 'nonStandard', 'doy');
*/
     public function addFile($fileName, $formats) { 
 
        $this->fileName = USERDATADIR.$fileName;
        $this->fileId = $fileName;

        $format = $this->getFormat();

        if ($format === 'unknown'){ 	           
            unlink($this->fileName);                   
            return array('success' => false, 'error' => 'Sorry, unknown format of '.$fileName);	
        }

        if ($format == 'txt') {  
            if ($formats["timeFormat"] == "user") {
                    $res =  $this->reformatTime($formats["nonStandard"], $formats["timeLength"], $formats["doy"]);

                    if (!$res) {
                        unlink($this->fileName); 
                        return array('success' => false, 'error' => 'can\'t reformat time'); 
                    }
            }
            // check if file is not empty
            $vars = $this->getTxtColNumber(false);

            if ($vars == -100) {
                return array('success' => false, 'error' => 'no such file');
            }
            if ($vars == -1) { 
                unlink($this->fileName); 
                return array('success' => false, 'error' => 'while reading file');
            }

            if ($vars === 0) {
                unlink($this->fileName);
                return array('success' => false, 'error' => 'file contains no data');
            }

            if ($formats["timeSampling"] == "constant") {          
                $this->sampling = $this->getTxtSampling();	 
                $this->maxSampling = $this->sampling;
                }
            else {
                $samplings = $this->getTxtSamplings();
                $this->sampling = $samplings[0];
                $this->maxSampling = $samplings[1];
            }

            if ($this->sampling <= 0) {  
                unlink($this->fileName); 
                if ($this->sampling == -10) {
                        return array('success' => false, 'error' => 'Sorry, can\'t process'.$fileName.PHP_EOL.'. Check if there are non numeric chars in the data');
                }
                return array('success' => false, 'error' => 'Sorry, can\'t process Time for '.$fileName.PHP_EOL.'. Check time format, start time (> 1970-01-01) or sampling time (>= 1s)');		           
            }              
        }

        if ($format == 'nc') {  
            $status = $this->reformatNcTime();
            if ($status <= 0) {
                    unlink($this->fileName);
                    return array('success' => false, 'error' => 'error '.$timeFormat.PHP_EOL.'Time Format problem');	
                }
        }

        //create new file tag with all attributes and add it to the content DOM   
        $newFile = $this->createFile($format);
        if ($newFile < 0) { 
                unlink($this->fileName);
                return array( 'success' => false, 'file' => $fileName);
        }

        $isMask = false;
        $masks = $this->contentDom->getElementsByTagName("folder");
 
        foreach ($masks as $mask) {

            $folderMask =  $mask->getAttribute("name");  
            if ($this->fileMask($fileName, $folderMask)) {                                                      
                $mask->appendChild($newFile);
                
                $files = $mask->getElementsByTagName("file");
                foreach ($files as $file) {
                        $starts[] = $file->getAttribute("start");
                        $stops[] =  $file->getAttribute("stop");
                }
                $mask->setAttribute("info", date('Y-m-d',min($starts))."T".date('H:i:s',min($starts))."-".date('Y-m-d',max($stops))."T".date('H:i:s',max($stops)));
                
                $isMask = true;
                break;
            }	
        }                     
        // no corresponding masks => add to fileList      
        if (!$isMask) {					  
                $filesList = $this->contentDom->getElementById($this->contentRootId); 
                $filesList->appendChild($newFile);
        }        
     
        $this->contentDom->save($this->xmlName);

        //if mask exists - add to data base
        $myBaseManager = new BaseManager();
        $mask = $myBaseManager->addFile($fileName); 
        if ($mask != null) {
            $startstop = $myBaseManager->getStartStop($myBaseManager->getVi($mask));
            $myParamMgr = new DerivedParamMgr('myDataParam');
            $myParamMgr->updateMydata($mask,$startstop);      
        }

      return array( 'success' => true, 'file' => $fileName);
     } 
     
}
?>