You are here

function _weather_retrieve_data in Weather 5

Same name and namespace in other branches
  1. 5.6 weather.module \_weather_retrieve_data()
  2. 6.5 weather.module \_weather_retrieve_data()

Retrieve data from weather.noaa.gov

1 call to _weather_retrieve_data()
weather_get_metar in ./weather.module
Fetches the latest METAR data from the database or internet

File

./weather.module, line 952
Display <acronym title="METeorological Aerodrome Report">METAR</acronym> weather data from anywhere in the world

Code

function _weather_retrieve_data($icao) {
  $icao = strtoupper($icao);
  $metar_raw = FALSE;

  // get information about the last successful data download
  //
  // we want to fetch via FTP, because it's much less bandwidth
  // for downloads. if the FTP access did not work, we use
  // HTTP POST instead.
  $fetch = variable_get('weather_fetch', 'FTP');

  // try alternative methods for fetching the METAR data via FTP
  if ($fetch == 'FTP') {
    $url = 'ftp://tgftp.nws.noaa.gov/data/observations/metar/stations/';
    $url .= $icao . '.TXT';
    if (function_exists('file_get_contents') and ini_get('allow_url_fopen')) {
      $metar_raw = file_get_contents($url);
    }
    else {
      if (function_exists('curl_init')) {
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_TRANSFERTEXT, TRUE);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        $metar_raw = curl_exec($curl);
        curl_close($curl);
      }
      else {
        if (function_exists('exec')) {
          exec("wget --quiet -O- {$url}", $output, $return_val);
          if ($return_val == 0) {
            $metar_raw = join("\n", $output);
          }
        }
      }
    }

    // if we had success, store the method
    if ($metar_raw !== FALSE) {
      variable_set('weather_fetch', 'FTP');
    }
  }

  // if the FTP access does not work, try POSTing the ICAO via HTTP
  if ($metar_raw === FALSE) {
    if (function_exists('fsockopen')) {
      $handle = fsockopen('weather.noaa.gov', 80);
      if ($handle !== FALSE) {
        $request = "POST /cgi-bin/mgetmetar.pl HTTP/1.1\r\n";
        $request .= "Host: weather.noaa.gov\r\n";
        $request .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $request .= "Content-Length: 9\r\n\r\n";
        $request .= "cccc={$icao}\r\n";
        fwrite($handle, $request);
        while (!feof($handle)) {
          $response .= fgets($handle, 1024);
        }
        fclose($handle);

        // extract the valid METAR data from the received webpage
        if (preg_match("/({$icao} [0-9]{6}Z .+)/", $response, $matches)) {
          $metar_raw = $matches[1];

          // store the method
          variable_set('weather_fetch', 'HTTP');
        }
      }
    }
  }

  // check on errors
  if ($metar_raw === FALSE) {
    drupal_set_message(t('Download location for METAR data is not accessible.'), 'error');
  }
  return $metar_raw;
}