DDserverWeb.php 22 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
<?php

/** 
*   @file DDserverWeb.php
*   @brief PHP SoapServer for DD WebServices
*
*   @date 27.05.2008
*   @version  $Id: DDserverWeb.php,v 1.11 2013/04/18 06:54:39 benjamin Exp $
*/

 class DDService 
 
 { 
     private $alias = array(baseDir => webAlias); 
     private $extAlias = array(extBaseDir => extWebAlias);

    function base64url_decode($data) {
        return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT));
    } 

/**     
*  Checks if Remote Data Set has been already added
*/

    function isRemoteViAdded($baseId, $viId) 
    {                 
        $referXML = baseDir."/DDsys.xml";
        $DDsys = new DOMDocument("1.0");
       
        $DDsys->load($referXML);       
        $xp = new domxpath($DDsys);
        $VI = $xp->query("//NAME[.='".$viId."']");
        
        if ($VI->item(0)->nodeValue != NULL)
        {
            $base = $VI->item(0)->getAttribute("base");
            if ($base != $baseId) return false;

            return true;
        }
        return false;
    }

/**     
*  Returns contents of 'Version' file from VI Location dir
*/

        function getVersion($dataSet) 
         {                 
            $referXML = baseDir."/DDsys.xml";
            $DDsys = new DOMDocument("1.0");
            $DDsys->load($referXML);
            $xp = new domxpath($DDsys);
            $VI = $xp->query("//NAME[.='".$dataSet."']");  
            if ($VI->item(0)->nodeValue != NULL)
            {
                $location = $VI->item(0)->parentNode->getElementsByTagName("LOCATION")->item(0)->nodeValue;
            }  
            if (file_exists($location."Version"))  return  file_get_contents($location."Version");
            return null;     
          }

/**
*  Returns list of datasets with TimeRestriction
*/
        function getDatasetsWithTimeRestriction()
         {
            $result = array(
            );
            $referXML = baseDir."/DDsys.xml";
            $DDsys = new DOMDocument("1.0");
            @$DDsys->load($referXML);
            $xp = new domxpath($DDsys);
            $VINodes = $xp->query("//VI");
            if ($VINodes->length == 0) {
                return $result;
            }

            foreach ($VINodes as $VINode)
            {
                $locationNode = $VINode->getElementsByTagName("LOCATION");
                $nameNode = $VINode->getElementsByTagName("NAME");
                if (($locationNode->length > 0) && ($nameNode->length > 0))
                {
                    $locationNode = $locationNode->item(0);
                    $nameNode = $nameNode->item(0);
                    $location = $locationNode->nodeValue;
                    $viName = $nameNode->nodeValue;
                    if (!empty($location) && !empty($viName)) {
                        if (file_exists($location."TimeRestriction"))  {
                            $restr = file($location."TimeRestriction", FILE_IGNORE_NEW_LINES);
                            $result[] = array(
				'vi' => $viName,
                                'restriction' => $restr[0],
                            );
                        }
                    }
                }
            }

            return $result;
         }

/**     
*  Returns restricted TimeRestriction and GlobalStop in case of time restriction
*/

        function getTimeRestriction($dataSet) 
         {                 
            $referXML = baseDir."/DDsys.xml";
            $DDsys = new DOMDocument("1.0");
            $DDsys->load($referXML);
            $xp = new domxpath($DDsys);
            $VI = $xp->query("//NAME[.='".$dataSet."']"); 
 
            if ($VI->item(0)->nodeValue != NULL)
            {
                $location = $VI->item(0)->parentNode->getElementsByTagName("LOCATION")->item(0)->nodeValue;
            }  else {
                return  array("success" => FALSE,
                               "days" => "NOSUCHVI",
                               "globalstop" => NULL
                            );    
            }
            if (file_exists($location."TimeRestriction"))  {
                  $restr = file($location."TimeRestriction", FILE_IGNORE_NEW_LINES);                
                  $infoXmlRestr = $location.$restr[1].".xml";
                  if (file_exists($infoXmlRestr)) {

                                if (!$DDsys->load($infoXmlRestr)) {
                                        $currDir = getcwd();
                                        chdir($location);
                                        $DDsys->loadXML(file_get_contents($restr[1].".xml"));  // NFS connection doesn't load                               
                                        chdir($currDir);                                      
                                }

                                $globalStop = $DDsys->getElementsByTagName("GlobalStop")->item(0)->nodeValue;                                                   
                    }
                  else {
                        $globalStop = NULL;
                    }
                  return  array("success" => TRUE,
                                "days" =>  $restr[0],
                                "globalstop" => $globalStop
                            );

            }
            return  array("success" => FALSE,
                        "days" => "NORESTRICTIONFILE",
                        "globalstop" => NULL
                    );     
          }


/**     Just returns URL addres of AMDA_Users.xml - 
*                            droits d'access
*/

        function getUserGroups() 
         {                 
              if (file_exists(extBaseDir."/AMDA_Users.xml"))  return extWebAlias."AMDA_Users.xml";
              else return NOUSERGROUPSSPECIFIED;     
          }

	function checkProtectedAPI($data, $key, $check)
	{
	  $data_decoded = $this->base64url_decode($data);
          if (empty($data_decoded)) {
              return array(
                  "valid" => FALSE,
              );
          }

          $data_array = json_decode($data_decoded, TRUE);
          if (empty($data_array) || empty($data_array["timestamp"])) {
              return array(
                  "valid" => FALSE,
              );
          }

          if (time() - intval($data_array["timestamp"]) > 300) {
              return $data_array + array("valid" => FALSE);
          }

          $keys_file = rootDir."/ddservice_clients_keys.json";
          if (!file_exists($keys_file)) {
              return $data_array + array("valid" => FALSE);
          }

          $keys_content = file_get_contents($keys_file);
          if (empty($keys_content)) {
              return $data_array + array("valid" => FALSE);
          }

          $existing_keys = json_decode($keys_content, TRUE);
          if (empty($existing_keys)) {
              return $data_array + array("valid" => FALSE);
          }

          $private = "";
          foreach ($existing_keys as $keys) {
              if ($keys["public"] == $key) {
                  $private = $keys["private"];
                  break;
              }
          }

          if (empty($private)) {
              return $data_array + array("valid" => FALSE);
          }

          $computed_check = md5($data.$key.$private);
          if ($computed_check != $check) {
              return $data_array + array("valid" => FALSE);
          }

          return $data_array + array("valid" => TRUE);
	}

/*
*       Return info about a user
*/

	function getUserInfo($data, $key, $check)
	{
          $data_array = $this->checkProtectedAPI($data, $key, $check);
          if ($data_array['valid'] == FALSE) {
            $login = array_key_exists("login", $data_array) ? $data_array["login"] : "undefined";
	    return array("success"     => FALSE,
			 "login"       => $login,
			 "name"        => "undefined",
			 "first_name"  => "undefined",
			 "group"       => "undefined",
			 "email"       => "undefined",
			 "date"        => "undefined",
			 "news"        => "0");
          }

	  $UsrDom = new DomDocument("1.0");
	  $UsrDom->load(extWebAlias."AMDA_Users_Info.xml");
	  $xp = new domxpath($UsrDom);                                                                             
	  $theUser = $xp->query("//user[@login='".$data_array["login"]."']");
          $login = array_key_exists("login", $data_array) ? $data_array["login"] : "undefined";
	  
	  return array("success"     => TRUE,
		       "login"       => $login,
		       "name"        => ($theUser->length > 0) ? $theUser->item(0)->getAttribute("name") : "undefined",
		       "first_name"  => ($theUser->length > 0) ? $theUser->item(0)->getAttribute("first_name") : "undefined",
		       "group"       => $this->getUserMemberGroups($login),
		       "email"       => ($theUser->length > 0) ? $theUser->item(0)->getAttribute("email") : "undefined",
		       "date"        => ($theUser->length > 0) ? $theUser->item(0)->getAttribute("date")  : "undefined",
		       "news"        => ($theUser->length > 0) ? $theUser->item(0)->getAttribute("news")  : "0");
	}

        function createUser($data, $key, $check)
        {
          $data_array = $this->checkProtectedAPI($data, $key, $check);
          if ($data_array['valid'] == FALSE) {
              return FALSE;
          }

          if (empty($data_array['pwd']) || empty($data_array['login'])) {
              return FALSE;
          }

          require_once userMgrDir."/UserManagerClass.php";
          putenv("PATH=./:".DDBASEBIN.":/bin:/usr/bin");
          putenv("DDINFO=".extBaseDir);
          putenv("DDBASE=".baseDir);
          putenv("AMDA_USERS_INFO=AMDA_Users_Info.xml");
          putenv("AMDA_GROUPS_INFO=AMDA_Users.xml");
          $stderr = fopen("php://stderr","w");
          $userManager = new UserManagerClass($stderr);
          $pwd_hash = crypt($data_array['pwd'],chr(rand(97,122)).chr(rand(97,122)));
          $first_name = !array_key_exists('first_name', $data_array) ? "" : $data_array['first_name'];
          $last_name  = !array_key_exists('last_name', $data_array) ? "" : $data_array['last_name'];
          $email = !array_key_exists('email', $data_array) ? "" : $data_array['email'];
          return ($userManager->AddUser($data_array['login'], $pwd_hash, $first_name, $last_name, $email, 1, '') == 1);
        }

/*
*       Return a list of group for which a user is a member
*/

	function getUserMemberGroups($user)
	{
          //get user
          $user_dom = new DomDocument("1.0");
          if (!file_exists(extBaseDir."/AMDA_Users.xml"))
            return  array();
          $user_dom->load(extBaseDir."/AMDA_Users.xml");

          $user_nodes = $user_dom->getElementsByTagName('user');

          foreach ($user_nodes as $user_node)
          {
            if ($user_node->nodeValue == $user)
              return $user_node->getAttribute('group');
          }

          return "";
	}

/**     Return the list of available local missions for 
*                            a given user
*/

	function getUserAvailableLocalMissions($user)
	{
	  //get user groups
          $user_groups = explode(",",preg_replace('/\s+/', '',$this->getUserMemberGroups($user)));

	  //get local missions
	  $mis_dom = new DomDocument("1.0");
	  if (!file_exists(extBaseDir."/Missions.xml"))
	    return array();
	  $mis_dom->load(extBaseDir."/Missions.xml");
	  
	  $local_nodes = $mis_dom->getElementsByTagName('Local');
	  if ($local_nodes->length < 1)
	    return array();

	  $mis_nodes = $local_nodes->item(0)->getElementsByTagName("MissionID");

	  $user_missions = array();

	  foreach ($mis_nodes as $mis_node)
	    {
	      if (!$mis_node->hasAttribute('group') || ($mis_node->getAttribute('group') == ''))
		{
		  //public mission
		  array_push($user_missions,$mis_node->nodeValue);
		}
	      else
		{
		  // private mission
		  $mis_group = $mis_node->getAttribute('group');
                  if (array_search($mis_group,$user_groups) === FALSE)
                    continue;
		  array_push($user_missions,$mis_node->nodeValue);
		}
	    }

	  return $user_missions;
	}

/**     Return the list of available external missions for 
*                            a given user
*/

        function getUserAvailableExternalMissions($user)
        {
          //get user groups
          $user_groups = explode(",",$this->getUserMemberGroups($user));

          //get external missions
          $mis_dom = new DomDocument("1.0");
          if (!file_exists(extBaseDir.extBaseXml))
	    return array();
          $mis_dom->load(extBaseDir.extBaseXml);

          $external_nodes = $mis_dom->getElementsByTagName('External');
          if ($external_nodes->length < 1)
            return array();

          $mis_nodes = $external_nodes->item(0)->getElementsByTagName("CenterID");

          $user_missions = array();

	  foreach ($mis_nodes as $mis_node)
            {
              if (!$mis_node->hasAttribute('group') || ($mis_node->getAttribute('group') == ''))
                {
                  //public mission
                  array_push($user_missions,$mis_node->nodeValue);
                }
              else
                {
                  // private mission
                  $mis_group = $mis_node->getAttribute('group');
                  if (array_search($mis_group,$user_groups) === FALSE)
                    continue;
                  array_push($user_missions,$mis_node->nodeValue);
                }
            }

          return $user_missions;
        }

/**     Just returns URL addres of Missions.xml  - 
*                            description of AMDA local data
*/

        function getAvailableMissions() 
         {                 
              if (file_exists(extBaseDir."Missions.xml"))  return extWebAlias."Missions.xml";
              else return NOLOCALDATA;     
          }

/**     Just returns URL addres of Bases.xml - 
*               description of available external bases 
*/

        function getAvailableExternalBases() 
         {                 
              if (file_exists(extBaseDir.extBaseXml))  return extWebAlias.extBaseXml;
              else return NOEXTERNALBASES;     
          }

/**      Just returns URL addres of base.xml - 
*                  description of available data for particular External Base
*                  produced by DataCenterMgr
*/
 
        function getAvailableExternalData($baseID) 
         {                 
              if (file_exists(extBaseDir.$baseID."/base.xml"))  
                          return extWebAlias.$baseID."/base.xml";
              else return NOEXTERNALDATA;     
          }

/**    Returns URL addres of dataSet.xml - 
*                  description of  particular external DataSet
*                  if there is no such a description 
*                  contacts External Base and gets it
*/ 

    function getDataSetDescription($baseID, $remDataSetID) 
    {                 
        if (file_exists(extBaseDir.$baseID."/".$remDataSetID.".xml"))  
                    return extWebAlias.$baseID."/".$remDataSetID.".xml";
        else 
        {
           

        }
    }

/**     
*       Returns date of last modif of *times.nc  in DD Base 
*/ 

        function getLastUpdate($dataSet) 
         {                  
				$referXML = baseDir."/DDsys.xml";
            $DDsys = new DOMDocument("1.0");
            $DDsys->load($referXML);
            $xp = new domxpath($DDsys);
            $VI = $xp->query("//NAME[.='".$dataSet."']"); 
 
            if ($VI->item(0)->nodeValue != NULL)
            {
					$location = $VI->item(0)->parentNode->getElementsByTagName("LOCATION")->item(0)->nodeValue;           
					$times = $VI->getElementsByTagName("TIMES")->item(0)->nodeValue; 
					if (!file_exists($location.$times))
						return null; 
                
					$cmd = 'date "+%Y-%m-%dT%H:%M:%SZ" -u -r '. $location.$times;  // for NFS      
					$dateModif = exec($cmd);    
						return $dateModif; 
				 }
				 
				 return null;
          }
          
/**     
*        Returns modif date of the last modified data file (*.nc.gz) for a given DataSet 
*/ 

        function getLastRealUpdate($dataSet) 
         {                  
				$referXML = baseDir."/DDsys.xml";
            $DDsys = new DOMDocument("1.0");
            $DDsys->load($referXML);
            $xp = new domxpath($DDsys);
            $VI = $xp->query("//NAME[.='".$dataSet."']"); 
 
            if ($VI->item(0)->nodeValue != NULL)
            {
					$location = $VI->item(0)->parentNode->getElementsByTagName("LOCATION")->item(0)->nodeValue;
					
					$find = 'find '.$location.' -name \'*.nc.gz\' -type f -printf \'%T@ %p\n\' | sort -n | tail -1 | cut -f2- -d" "';
					$lastFile = exec($find);
					if (!file_exists($lastFile))
						exit('NO SUCH FILE '.$lastFile);
					$cmd = 'date "+%Y-%m-%dT%H:%M:%SZ" -u -r '.$lastFile;  // for NFS  
    
					$dateModif = exec($cmd);    
						return $dateModif; 
				 }
				 
				 return null;
          }
          

	function getGranules($dataset)
	{
		$referXML = baseDir."/DDsys.xml";
		$DDsys = new DOMDocument("1.0");
		$DDsys->load($referXML);
		$xp = new domxpath($DDsys);
		$VI = $xp->query("//NAME[.='".$dataSet."']");

		if ($VI->item(0)->nodeValue != NULL)
		{
			$location = $VI->item(0)->parentNode->getElementsByTagName("LOCATION")->item(0)->nodeValue;
			$times = $VI->item(0)->parentNode->getElementsByTagName("TIMES")->item(0)->nodeValue;
			$cmd = "/opt/tools/DDServer/bin/GetGranules ".$location." ".$times;
			exec($cmd, $output, $result_code);
			if ($result_code === 0)
				return implode("\n",$output);
		}
		return NULL;
	}
          
/**     
*       Returns String Start-Stop for local DataSet  in DD Base 
*/ 

        function getStartStop($dataSet) 
          {                  

					$referFile = baseDir."/refer.nc";          
					$cmd = DDBASEBIN."/StartStop ".$referFile." ".$dataSet;  
					$res = system($cmd);
					
					return $res;
          }

/**     
*       Returns String INFO for local DataSet  in DD Base 
*/ 

    function getInfo($dataSet, $infoID) 
    {                          
        $referFile = baseDir."/refer.nc";          
        $cmd = DDBASEBIN."/GetInfo ".$referFile." ".$dataSet." ".$infoID;  
        $res = system($cmd);
        
        return $res;        
    }

/**     
*       Returns Desc attribute for Remote DataSet   in DD Base 
*/ 

    function getRemoteStartStop($baseID, $dataSet) 
    {                              
        $domName = extBaseDir.$baseID."/base.xml";   
        if (!file_exists($domName))
                return NOEXTERNALDATA;

        $dom = new DomDocument("1.0");
        $dom->load($domName);
        $vi = $dom->getElementById($dataSet);
        if (!$vi)
                return NODATASET;

        $res = $vi->getAttribute('desc'); 
        return $res;              
    }

/**     
*       Check Remote Connection
*/ 

	  function checkRemoteConnection($extBaseID){

		switch ($extBaseID) {
		    case "THEMIS" :  return is_dir(THEMIS_DIR);	
			    
		    case "MAPSKP" :  if (fsockopen(MAPSKP_HTTP_SERVER, 80, $errno, $errstr, 30)) return true;
				     else return false;

		    case "CDAWEB" : if (ftp_connect(CDAWEB_FTP_SERVER)) return true;
				    else return false;

		    case "VEXGRAZ" : if (fsockopen(VEXGRAZ_HTTP_SERVER, 80, $errno, $errstr, 30)) return true;
				     else return false;

                    case "LATMOS" : if (fsockopen(LATMOS_HTTP_SERVER, 80, $errno, $errstr, 30)) return true;
                                     else return false;

                    case "LESIA" : if (fsockopen(LESIA_HTTP_SERVER, 80, $errno, $errstr, 30)) return true;
                                     else return false;

                    case "SINP" : if (fsockopen(SINP_HTTP_SERVER, 80, $errno, $errstr, 30)) return true;
                                     else return false;

                    case "FMI_HYBRID" : if (fsockopen(FMI_HYBRID_HTTP_SERVER, 80, $errno, $errstr, 30)) return true;
                                     else return false;

                    case "FMI_GUMICS" : if (fsockopen(FMI_GUMICS_HTTP_SERVER, 80, $errno, $errstr, 30)) return true;
                                     else return false;

                    case "CCMC" : if (fsockopen(CCMC_HTTP_SERVER, 80, $errno, $errstr, 30)) return true;
                                     else return false;

		    case "CLWeb" : if (fsockopen(CLWeb_HTTP_SERVER, 80, $errno, $errstr, 30)) return true;
                                     else return false;

		    default:   return false;             
	        }		
	    }
/**     
*       Returns Array of Data Urls for a given DataSet 
*                     in StartTime - StopTime interval 
*/ 

    function getDataUrl($dataSet, $StartTime, $StopTime) 
    {  
            $tempFile = uniqid("temp");
            if (file_exists($tempFile)) unlink($tempFile);
                            
            $referXML = baseDir."/DDsys.xml";
            $DDsys = new DOMDocument("1.0");
            $DDsys->load($referXML);
            $xp = new domxpath($DDsys);
            $VI = $xp->query("//NAME[.='".$dataSet."']");  
            if ($VI->item(0)->nodeValue != NULL)
            {
                $location = $VI->item(0)->parentNode->getElementsByTagName("LOCATION")->item(0)->nodeValue;
                $times = $VI->item(0)->parentNode->getElementsByTagName("TIMES")->item(0)->nodeValue;
                $timesFile = $location.$times;
                $cmd = DDBASEBIN."/GetFileNames ".$timesFile." ".strtotime($StartTime)." ".strtotime($StopTime)." > $tempFile"; 
                system($cmd);
                if (!file_exists($tempFile)) return 'ERROR';

                $res = file($tempFile);                      
                if ($res[0] == OUTOFTIME) {
                unlink($tempFile);
                return $res;
                }

                $urls = explode(";",$res[0]);
                $url_location = strtr($location, $this->alias); 
                if (count($urls) > 0) {
                unset($urls[count($urls)-1]);
                for ($i = 0; $i < count($urls); $i++) $urls[$i] = $url_location.$urls[$i].".gz";
                }
                unlink($tempFile);

                return $urls; 
            }
        return NODATASET;               
    }
 } 

require_once(dirname(__FILE__) . '/DDserverWeb_ini.php');
ini_set("soap.wsdl_cache_enabled", "0");

 // use_soap_error_handler(false);
  $server = new SoapServer("./dd.wsdl");
  $server->setClass("DDService");
  $server->handle();
?>