MultiRequestMgr.php 9.71 KB
<?
/**
  *  MultiRequestMgr.php
  *   
  *  @version $Id: MultiRequestMgr.php 2886 2015-04-29 15:15:46Z myriam $
  */
      
   require 'config.php';
   $userDirs = array('USERWSDIR' => 'WS', 'USERREQDIR' => 'REQ', 'USERDATADIR' => 'DATA',
		     'USERWORKINGDIR' =>'RES', 'USERTTDIR' => 'TT', 'USERJOBDIR' => 'JOBS');	

     
  $request = json_decode($argv[1]);	
  $tempname = $argv[2];
  $user = $argv[3];
  $IP = $argv[4];
  $newname = $argv[5];

   define ("USERDIR", USERPATH."$user/");
 
  foreach ($userDirs as $key => $val) {
	$dir = USERDIR.$val;
	define("$key","$dir/");
    } 
    
   $reqMgr = new RequestMgr();
   $ttMgr = new TimeTableMgr();

    if ($request->nodeType == 'request') copy(USERWORKINGDIR.$tempname.'_/'.$tempname,USERWORKINGDIR.$tempname.'_/request_.list'); 
    
 
   $timeTables = $request->timeTables;
   $i = 0;
   $badIntervals = 0;

// check output file size for download
   $fileSize = 0.0;

   foreach ($timeTables as $timeTable)  { 
 
          $ttType = (substr($timeTable->id,0,6) == 'shared') ?  'sharedtimeTable' : 'timeTable'; 
  
          $tt = $ttMgr->loadIntervalsFromTT($timeTable->id, $ttType);
          $intervals = $tt['intervals'];
 
//Everything is already  ready => just loop over Time Intervals    
          foreach ($intervals as $interval) {
	      switch ($request->nodeType) {
		    case 'condition' : 

				if ((strtotime($interval['stop']) - strtotime($interval['start'])) >= $request->sampling * 2.0) { 

				  $reqMgr->createSearchRequestTime2($interval);			  
		  // Run command
				  $cmd = DDBIN."DD_Search ".$user." ".$IP." ".DDPROJECT." ".DDPROJLIB;  
				  $cmdResult = system($cmd);
		    //              if ($cmdResult === false) 
  //TODO   processError
		      
				  if (file_exists(USERTTDIR.$tempname.'.xml'))
						rename(USERTTDIR.$tempname.'.xml', USERTTDIR.$tempname.'_'.sprintf("%03d",$i).'.xml');
				  if (file_exists(USERTTDIR.'Gaps_'.$tempname.'.xml'))
						rename(USERTTDIR.'Gaps_'.$tempname.'.xml', USERTTDIR.'Gaps_'.$tempname.'_'.sprintf("%03d",$i).'.xml');
				} 
				else {
//TODO create XML file with bad intervals to add to GAPS 
				if (!$badIntervalsXml) {
				    $badIntervalsXml  = new DomDocument("1.0");
				    $badRootElement = $badIntervalsXml->createElement("TimeTable");
				    $badIntervalsXml->appendChild($badRootElement);
				 }
				  $badInt = $badIntervalsXml->createElement('Interval');
				  $badInt->setAttribute('flag', 'less than 2*samplings');
				  $badInt->appendChild($badIntervalsXml->createElement('Start',$interval['start']));
				  $badInt->appendChild($badIntervalsXml->createElement('Stop',$interval['stop']));
				  $badRootElement->appendChild($badInt);
 
				  $badIntervals++;
				}
			      break;
                    case 'request' : 				
				$resultDir = USERWORKINGDIR.$tempname.'_/';
				copy($resultDir.'request_.list', $resultDir.$tempname);
				$reqMgr->updateTime($resultDir.$tempname, $interval);
				$cmd = DDBIN."DD_PS ".$tempname." ".$user." ".$IP." ".DDPROJECT." ".DDPROJLIB;
				$cmdResult = system($cmd);
 			 
				if (file_exists($resultDir.'idl.ps')) {					    
					     rename($resultDir.'idl.ps', $resultDir.$tempname.sprintf("_%03d",$i).'.ps');
				 }
                              break;
		    case 'download' :
				$resultDir = USERWORKINGDIR.$tempname.'_/';
				$reqMgr->updatePrintRequestTime($resultDir, $interval);
                                $deltaT = strtotime($interval['stop']) - strtotime($interval['start']);
                                if ($deltaT < $request->sampling) { 
                                    $newSampling = $deltaT/2.0;
                                    $reqMgr->updatePrintSampling($resultDir, $newSampling);
                                }

                                $outputFileSize = $reqMgr->estimateOutputFileSize($request, $deltaT);
                                if ( $outputFileSize + $fileSize <  DISK_QUOTA ) { 
				    set_time_limit(3000);
                                    $cmd = DDBIN."DD_Print ".$user." ".$IP." ".DDPROJECT." ".DDPROJLIB;
                                    $cmdResult = system($cmd);
                                    foreach (glob($resultDir."*.txt") as $filename)
                                        if ($filename != $resultDir."header.txt") { 
                                            if ($deltaT < $request->sampling*2.0) { 
                                                $new_name = str_replace(".txt", "_NONSTANDARD_SAMPLING_".str_replace(".","_",$newSampling)."_".sprintf("%04d",$i).".asc", $filename);
                                            //sampling info
                                                $str = "Sampling Time : ".$newSampling;
                                                system("sed -i '1i\\#".$str."' '".$filename."'");
                                            }
                                            else {
                                                $new_name = str_replace(".txt", "_".sprintf("%04d",$i).".asc", $filename);
                                            }

                                            rename($filename, $new_name);
                                            $fileSize += filesize($new_name);
                                    }
                                }
                                else {
                                       $new_name = "DISK_QUOTA_EXCEEDED_".sprintf("%04d",$i).".asc";
                                       $error = 'Interval '.$i.': '.$interval['start'].' - '.$interval['stop'].' '.' cannot be downloaded'.PHP_EOL.
                                                 'You\'ve exceded the user disk quota'.PHP_EOL.'Decrease time interval OR put it into another Time Table'.PHP_EOL.
                                                 'And don\'t forget to clean up your workspace from time to time';
                                       file_put_contents($resultDir.$new_name, $error);
                                }
			      break;
		    default :
		  }                   
              $i++;      
          }
      }  
//Postprocessing
       
	      switch ($request->nodeType) {
		    case 'download' :
			$resultDir = USERWORKINGDIR.$tempname.'_/';
			
			//get options
			$opts = $reqMgr->getPrintOptions($resultDir);
			
			//[['0','All In One File'], ['1','One File Per Time Interval'], ['2','One File Per Param/Interval']],
			if ($opts['structure'] == '0')
			{
				 //all in one file
				 exec("cat *.asc > ALL.txt");
				 //remove asc files
				foreach (glob($resultDir."*.asc") as $filename)
				       unlink($filename);
			}
			else
			{
					//rename *.asc files by *.txt
					foreach (glob($resultDir."*.asc") as $filename)
					{
                                            $new_name = str_replace(".asc", ".txt", $filename);
					    rename($filename, $new_name); 
                                        }
			}
			
		      break;
		    case 'condition' : 
		       $resultDir = USERTTDIR;
		       $prefix = '';
		       $buffer = new DomDocument("1.0");
		       for ($i = 0; $i < 2; $i++) {
			$resultTT = new DomDocument("1.0");
			$rootElement = $resultTT->createElement("TimeTable");
			$rootElement->setAttribute("Name","");
			  
			$rootElement->appendChild($resultTT->createElement("Created", date('F j Y H:i:s')));
			
			$history = '';
			foreach ($timeTables as $timeTable)  {
				$history = $history." ".$timeTable->timeTableName;
			} 
			$rootElement->appendChild($resultTT->createElement("History", $history));				
			
  /*			
			  $rootElement->appendChild($tempXml->createElement("Chain",  htmlentities($_POST['SearchCondition'])));
			  $csection =  htmlentities("AMDA Search: Time_Step ".$_POST['TimeAver'].
			  " s; Data_absence_is_gap_for_gaps > ".$_POST['Thresh'].
			  " Data_Sampling_Times; Start_Time: ".$ddStart." Time_Interval: ".$time_int);
			  $rootElement->appendChild($tempXml->createElement("Source", $csection));
  */                                   		     
			 
			foreach (glob($resultDir.$prefix.$tempname.'_*.xml') as $xml) {
			      $buffer->load($xml);
			      $intervals_pp = $buffer->getElementsByTagName('Interval');
			      foreach ($intervals_pp as $interval_pp) {
				  $rootElement->appendChild($resultTT->importNode($interval_pp,true));			      
				}
			      unlink($xml);
			  }
			  $resultTT->appendChild($rootElement);
			  $resultTT->save($resultDir.$prefix.$tempname.'.xml');
			  $prefix = 'Gaps_';
		       }
//add bad intervals to GAPS
 
			if ($badIntervals > 0) {
			      $resultTT->load($resultDir.'Gaps_'.$tempname.'.xml');
			      $rootElement = $resultTT->getElementsByTagName('TimeTable')->item(0);
			      $intervals_bad = $badRootElement->getElementsByTagName('Interval');
 
			      foreach ($intervals_bad as $interval_bad) {
				  $rootElement->appendChild($resultTT->importNode($interval_bad,true));			      
				}
			      $resultTT->save($resultDir.'Gaps_'.$tempname.'.xml');
			}
		      break;
		    case 'request' :  
		      $resultDir = USERWORKINGDIR.$tempname.'_/';
		      switch ($request->format) {                            
			      case 'PS' :
				  $cmd =  "gs -dBATCH -sPAPERSIZE=a4 -dNOPAUSE -q -sDEVICE=pswrite -sOutputFile=".$resultDir."idl.ps ";
				  foreach (glob($resultDir.$tempname."_*.ps") as $aPS) $cmd .=  $aPS." ";
				  exec($cmd);   		     
				  exec("gzip ".$resultDir."idl.ps"); 
                                  rename($resultDir."idl.ps.gz",$resultDir.$newname.".ps.gz");
				break;
			      case 'PDF' : 
				  foreach (glob($resultDir.$tempname."_*.ps") as $aPS) { 
					exec("ps2pdf -sPAPERSIZE=a4 ".$aPS);
					unlink($aPS);
				  }
				  $cmd =  "gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=".$resultDir."idl.pdf ";
				  foreach (glob($resultDir.$tempname."_*.pdf") as $aPDF) $cmd .=  $aPDF." ";
				  exec($cmd);    			 
				break;
			      default : 
			  } 

		      break;
		    default :
               }

?>