You are here

function weather_admin_places_form_submit in Weather 7.2

Same name and namespace in other branches
  1. 7.3 weather.forms.inc \weather_admin_places_form_submit()

Handle the submission of a new place.

File

./weather.forms.inc, line 176
Provide forms for configuration of weather displays.

Code

function weather_admin_places_form_submit($form, &$form_state) {
  module_load_include('inc', 'weather', 'weather_parser');
  $url = $form_state['values']['weather_yrno_url'];

  // Remove whitespace from the string.
  $url = trim($url);

  // Check for the english version.
  if (substr($url, 0, 24) != 'https://www.yr.no/place/') {
    drupal_set_message(t('Please make sure to use the English version of the forecast, starting with "https://www.yr.no/<strong>place</strong>/".'), 'error');
    return;
  }

  // Ensure that the link is not known yet.
  // Remove "https://www.yr.no/place/" from the URL.
  $link = substr($url, 24);

  // Remove trailing slash.
  $link = trim($link, '/');

  // Split by slashes and remove country (first item)
  $link_parts = explode('/', $link);

  // Remove country.
  $country = array_shift($link_parts);
  $link = implode('/', $link_parts);
  $result = db_query('SELECT * FROM {weather_places} WHERE country = :country AND link = :link', array(
    ':country' => $country,
    ':link' => $link,
  ))
    ->fetchObject();
  if ($result) {
    drupal_set_message(t('The place is already in the database.'), 'error');
    return;
  }
  $url .= 'forecast.xml';

  // Try to fetch the forecast, timeout 10 seconds.
  $response = drupal_http_request($url, array(
    'timeout' => 10,
  ));

  // Extract XML data from the received forecast.
  if (!isset($response->error)) {
    if (_weather_parse_forecast($response->data)) {
      drupal_set_message(t('The new place has been saved.'));
      return;
    }
  }
  drupal_set_message(t('The download from the given URL did not succeed.'), 'error');
}