You are here

weather_es.module in Weather_es 6.3

File

weather_es.module
View source
<?php

/**
 * Weather_es shows the weather forecast of 8112 cities of Spain using the AEMET web information.
 * Copyright (C) 2008 José Mª Sirvent <drupal@hykrion.com>
 *
 * This file is part of the Drupal weather_es module.
 * It is based on the Weather module which was written in 2006 by
 * Tobias Toedter <t.toedter@gmx.net> and on the multipage_form_example.module,v 1.9
 * written by davereid.
 *
 * Weather_es is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * Weather_es is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Weather_es; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */
require_once 'weather_es.inc';

/**
 * hook_help()
 *
 * @author jmsirvent
 */
function weather_es_help($page, $arg) {
  switch ($page) {
    case 'admin/modules#description':
      return t('Spanish forecast by AEMET.');
    case 'admin/settings/weather_es':
      return t('<p>Here you can create a configuration with one or more locations or delete a location from your configuration.</p>');
  }
}

/**
 * Implementation of hook_perm()
 *
 * @author jmsirvent
 */
function weather_es_perm() {
  return array(
    'administer custom weather_es block',
  );
}

/**
 * hook_menu
 *
 * @author jmsirvent
 */
function weather_es_menu() {
  $items['weather_es/update_cities'] = array(
    'page callback' => 'weather_es_update_cities_js',
    'access arguments' => array(
      'administer custom weather_es block',
    ),
    'type' => MENU_CALLBACK,
  );
  $items['admin/settings/weather_es'] = array(
    'title' => 'Weather_es',
    'description' => 'Configure the system weather_es block.',
    'page callback' => 'weather_es_main',
    'page arguments' => array(
      '0',
    ),
    'access arguments' => array(
      'administer site configuration',
    ),
    'type' => MENU_NORMAL_ITEM,
  );
  $items['admin/settings/weather_es/edit'] = array(
    'title' => 'Weather_es',
    'description' => 'Configure the system weather_es block',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'weather_es_edit_form',
      '0',
    ),
    'access arguments' => array(
      'administer site configuration',
    ),
    'type' => MENU_CALLBACK,
  );
  $items['admin/settings/weather_es/delete'] = array(
    'title' => 'Weather_es',
    'description' => 'Configure the system weather_es block',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'weather_es_delete_form',
      '0',
    ),
    'access arguments' => array(
      'administer site configuration',
    ),
    'type' => MENU_CALLBACK,
  );
  $items['user/%/weather_es'] = array(
    'title' => 'My weather_es',
    'description' => 'Configure your custom weather_es block.',
    'page callback' => 'weather_es_main',
    'page arguments' => array(
      1,
    ),
    'access arguments' => array(
      'administer custom weather_es block',
    ),
    'type' => MENU_LOCAL_TASK,
  );
  $items['user/%/weather_es/edit'] = array(
    'title' => 'Edit my weather_es',
    'description' => 'Configure your custom weather_es block',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'weather_es_edit_form',
      '1',
    ),
    'access arguments' => array(
      'administer custom weather_es block',
    ),
    'type' => MENU_CALLBACK,
  );
  $items['user/%/weather_es/delete'] = array(
    'title' => 'Delete a location from my weather_es',
    'description' => 'Delete a location from my weather_es block',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'weather_es_delete_form',
      '1',
    ),
    'access arguments' => array(
      'administer custom weather_es block',
    ),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Main weather_es_page. Show the cities you want to know the weather if there're selected...
 *
 * @author jmsirvent
 */
function weather_es_main($wid) {
  $path = _weather_es_redirect($wid);

  // Table header
  $header = array(
    array(
      'data' => t('City'),
      'field' => 'cit_nam',
    ),
    array(
      'data' => t('Languaje'),
    ),
    array(
      'data' => t('Operation'),
    ),
  );
  $sql = "SELECT wed.cit_nam, wed.cit_cod, wec.lan FROM {weather_es_data} wed INNER JOIN {weather_es_conf} wec ON (wec.cit_cod = wed.cit_cod) WHERE wec.wid = %d" . tablesort_sql($header);
  $result = db_query($sql, $wid);
  while ($row = db_fetch_array($result)) {
    $rows[] = array(
      'cit_nam' => $row['cit_nam'],
      'lan' => $row['lan'],
      l(t('delete'), $path . '/delete/' . $row['cit_cod'] . '/' . $row['cit_nam']),
    );
  }

  //if (count($rows) == 0) {
  if (!$rows) {
    $rows[] = array(
      array(
        'data' => '<em>' . t('There are currently no locations.') . '</em>',
        'colspan' => 3,
      ),
    );
  }
  $output = theme('table', $header, $rows);

  // Create a new location
  $output .= '<p>' . l(t('Create a new configuration or add a new location to an exisiting configuration.'), $path . '/edit') . '</p>';
  return $output;
}

/**
 * @param $form_state, $wid: 0: site, int: user->uid
 *
 * @author jmsirvent
 */
function weather_es_edit_form(&$form_state, $wid) {

  // From: http://jbenner.net/blog/prevent-ahah-the-right-way-from-breaking-with-validation
  $form['#cache'] = TRUE;

  // Make sure the form is cached.
  // Pull the correct action out of form_state if it's there to avoid AHAH+Validation action-rewrite.
  if (isset($form_state['action'])) {
    $form['#action'] = $form_state['action'];
  }
  $form['combo'] = array(
    '#type' => 'fieldset',
    '#title' => t('Select a province and a city'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
    '#tree' => TRUE,
  );
  $form['combo']['provincia'] = array(
    '#title' => t('Province'),
    '#description' => t('Province of the city'),
    '#type' => 'select',
    '#options' => _weather_es_provinces(),
    '#default_value' => '---',
    '#ahah' => array(
      'path' => 'weather_es/update_cities',
      'wrapper' => 'city-dropdown',
      'method' => 'replace',
      'effect' => 'none',
    ),
  );
  $form['combo']['ciudad'] = array(
    '#title' => t('City'),
    '#type' => 'select',
    '#description' => t('City to show the forecast'),
    '#options' => _weather_es_cities($form_state['values']['combo']['provincia']),
    '#prefix' => '<div id="city-dropdown">',
    '#suffix' => '</div>',
  );
  $form['idioma'] = array(
    '#type' => 'radios',
    '#title' => t('Languages'),
    '#options' => array(
      'es' => t('Spanish'),
      'ca' => t('Catalan'),
      'eu' => t('Euskera'),
      'gl' => t('Galician'),
      'en' => t('English'),
      'fr' => t('French'),
    ),
    '#description' => t('Choose the language you will see the weather data.'),
    '#default_value' => 'es',
  );
  $form['informacion'] = array(
    '#type' => 'checkboxes',
    '#title' => t('What information do you want to see?'),
    '#options' => array(
      'rain' => t('Rain probability'),
      'snow' => t('Snow level'),
      'sky' => t('Sky state'),
      'wind' => t('Wind direction and speed'),
      'gust' => t('Gust of wind'),
      'temperature' => t('Temperature'),
      'chill' => t('Chill'),
      'humidity' => t('Humidity'),
      'uv' => t('UV'),
    ),
    '#default_value' => array(
      'rain',
      'sky',
      'temperature',
    ),
  );

  /* TODO template_preprocess_weather_es the full info
    $form['cantidad'] = array(
      '#type' => 'radios',
      '#title' => t('Information'),
      '#options' => array(
        're' => t('Reduced - every 12h or 24h'),
        'fu' => t('Full - every 6h'),
      ),
      '#default_value' => 're',
    );
     */
  $form['save'] = array(
    '#type' => 'submit',
    '#value' => t('Save configuration'),
  );
  $form['add'] = array(
    '#type' => 'submit',
    '#value' => t('Add new location'),
  );
  $form_state['storage']['wid'] = $wid;
  $form['#submit'] = array(
    'weather_es_form_submit',
  );
  $form['#validate'] = array(
    'weather_es_form_validate',
  );
  return $form;
}

/**
 * @author jmsirvent
 */
function weather_es_form_validate($form, &$form_state) {

  // If there's AHAH sent thats only the combo
  if (!empty($form_state['ahah_submission'])) {
    return;
  }
  if ($form_state['values']['combo']['ciudad'] == '0' or !in_array($form_state['values']['idioma'], array(
    'es',
    'ca',
    'gl',
    'eu',
    'en',
    'fr',
  ))) {
    form_set_error('ciudad', t('You must select a valid city and language.'));
  }
}

/**
 * @author jmsirvent
 */
function weather_es_form_submit($form, &$form_state) {

  // There's only a AHAH sent...
  if (!empty($form_state['ahah_submission'])) {
    $form_state['rebuild'] = FALSE;
    return;
  }

  // Get data from AEMET
  $aemet = new weather_es_Aemet($form_state['values']['combo']['ciudad']);
  if ($aemet
    ->getName() != '') {

    // Save a new user configuration or rewrite an existing one

    //if ($_POST['op'] == t('Save configuration')) {
    if ($form_state['clicked_button']['#value'] == t('Save configuration')) {

      // Delete previous user configuration
      $sql = "DELETE FROM {weather_es_conf} WHERE wid = %d";
      db_query($sql, $form_state['storage']['wid']);
    }

    // Avoid add a city already in the user configuration
    if (!db_result(db_query("SELECT COUNT(*) FROM {weather_es_conf} WHERE wid = %d AND cit_cod = %d", $form_state['storage']['wid'], $form_state['values']['combo']['ciudad']))) {

      // Save configuration data
      // TODO full info

      //_weather_es_conf_save($form_state['storage']['wid'], $form_state['values']['combo']['ciudad'], $form_state['values']['idioma'], serialize(array_filter($form_state['values']['informacion'])), $form_state['values']['cantidad']);
      _weather_es_conf_save($form_state['storage']['wid'], $form_state['values']['combo']['ciudad'], $form_state['values']['idioma'], serialize(array_filter($form_state['values']['informacion'])), 're');
    }
    else {

      // Change an old configuration
      // TODO full info

      //_weather_es_conf_update($form_state['storage']['wid'], $form_state['values']['combo']['ciudad'], $form_state['values']['idioma'], $form_state['values']['informacion'], $form_state['values']['cantidad']);
      _weather_es_conf_update($form_state['storage']['wid'], $form_state['values']['combo']['ciudad'], $form_state['values']['idioma'], $form_state['values']['informacion'], 're');
    }

    // Delete the previous city data and save the new one
    db_query("DELETE FROM {weather_es_data} WHERE cit_cod = %d", $form_state['values']['combo']['ciudad']);
    $cities = _weather_es_cities($form_state['values']['combo']['provincia']);
    _weather_es_data_save($form_state['values']['combo']['ciudad'], $cities[$form_state['values']['combo']['ciudad']], serialize($aemet));
    drupal_set_message(t('Config save for: %city.', array(
      '%city' => $cities[$form_state['values']['combo']['ciudad']],
    )));
  }
  else {

    // The connection with AEMET has failt, try in 10'
    db_query("UPDATE {weather_es_data} SET nex_upd = %d WHERE cit_cod = %d", time() + 10 * 60, $form_state['values']['combo']['ciudad']);
    drupal_set_message(t('The connection with AEMET has failt.'));
  }

  // Redirect the user to the table. $form['#redirect'] and $form_state['redirect'] don't work...
  drupal_goto(_weather_es_redirect($form_state['storage']['wid']));
}

/**
 * @param $form_state, int $wid: 0: site, user->uid, int $cit_cod, string $cit_name
 *
 * @author jmsirvent
 */
function weather_es_delete_form(&$form_state, $wid, $cit_cod, $cit_nam) {
  $form['wid'] = array(
    '#type' => 'value',
    '#value' => $wid,
  );
  $form['cit_cod'] = array(
    '#type' => 'value',
    '#value' => $cit_cod,
  );

  // I don't trust in moduleName_formid_submit...
  $form['#submit'][] = 'weather_es_delete_form_submit';
  return confirm_form($form, t('Are you sure you want to delete the location %name?', array(
    '%name' => $cit_nam,
  )), _weather_es_redirect($wid), t('This action cannot be undone.'), t('Delete'), t('Cancel'));
}

/**
 * @author jmsirvent
 */
function weather_es_delete_form_submit($form, &$form_state) {

  // Delete the city
  $sql = "DELETE FROM {weather_es_data} WHERE cit_cod = %d";
  db_query($sql, $form_state['values']['cit_cod']);
  drupal_set_message(t('The location has been deleted.'));
  $form_state['redirect'] = _weather_es_redirect($form_state['values']['wid']);
}

/**
 * hook_block()
 *
 * @author jmsirvent
 */
function weather_es_block($op = 'list', $delta = 0, $edit = array()) {
  switch ($op) {
    case 'list':
      $blocks[0]['info'] = t('Weather_es: system-wide');
      $blocks[1]['info'] = t('Weather_es: custom user');
      return $blocks;
    case 'configure':
      return $form;
    case 'view':
    default:

      //drupal_add_js(drupal_get_path('module', 'weather_es') .'/js/weather_es.js');

      // System weather_es block
      if ($delta == 0 and user_access('access content')) {
        $title = t('System weather');
        $content = block_weather_es_contents(0);
      }
      elseif ($delta == 1 and user_access('administer custom weather_es block')) {
        $title = t('User weather');
        $content = block_weather_es_contents(1);
      }
      $block['subject'] = $title;
      $block['content'] = $content;
      return $block;
  }
}

/**
 * Show the weather_es contents
 *
 * @author jmsirvent
 */
function block_weather_es_contents($which_block) {
  global $user;

  // Cities data for that weather_es user
  $sql = "SELECT wed.cit_cod, wed.cit_nam, wed.nex_upd FROM {weather_es_data} wed LEFT JOIN {weather_es_conf} wec ON wec.cit_cod = wed.cit_cod WHERE wec.wid = %d";

  // Block 0 is about the site, 1 is about the user
  $wid = $user->uid;
  if ($which_block == 0) {
    $wid = 0;
  }
  $usrcnfresult = db_query($sql, $wid);
  $content = '';
  while ($usrcnf = db_fetch_object($usrcnfresult)) {

    // Update ancient data
    if ($usrcnf->nex_upd < time()) {

      // Get data from AEMET (de momento el código a pelo...)
      $aemet = new weather_es_Aemet('03083');
      if ($aemet != -1) {

        // Delete the previous city data and save the new one
        db_query("DELETE FROM {weather_es_data} WHERE cit_cod = %d", $usrcnf->cit_cod);
        _weather_es_data_save($usrcnf->cit_cod, $usrcnf->cit_nam, serialize($aemet));

        // Next connectio to AEMET in 4h
        db_query("UPDATE {weather_es_data} SET nex_upd = %d WHERE cit_cod = %d", time() + 4 * 3600, $usrcnf->cit_cod);
      }
      else {

        // The connection with AEMET has failt, try in 10'
        db_query("UPDATE {weather_es_data} SET nex_upd = %d WHERE cit_cod = %d", time() + 10 * 60, $usrcnf->cit_cod);
      }
    }
    $content .= '<strong>' . check_markup($usrcnf->cit_nam) . '</strong>';
    $content .= t('<small><strong>Weather forecast by AEMET.</strong></small>');
    $sql = "SELECT * FROM {weather_es_data} wed INNER JOIN {weather_es_conf} wec ON wed.cit_cod = wec.cit_cod WHERE wec.wid = %d AND wec.cit_cod = %d";
    $result = db_fetch_object(db_query($sql, $wid, $usrcnf->cit_cod));

    // What information the user wants
    $inf_typ = unserialize($result->inf_typ);
    $objWea = unserialize($result->dat_dat);
    $data = $objWea
      ->getInfo();

    // Day0 and day1 have information every 6h
    // Day2 and day3 every 12h
    // Day4, day5 and day6 every 24h
    foreach ($data as $day => $obj) {
      $page = ceil(($day + 1) / 2);
      $content .= theme('weather_es', $result->inf_amo, $day, $obj, $inf_typ, $page);
    }
    $content .= '<div class="item-list"><ul class="pager">';
    $content .= '<li class="pager-item weather_es-pager-item"><a class="active" rel="1">1</a></li>';
    $content .= '<li class="pager-item weather_es-pager-item"><a class="active" rel="2">2</a></li>';
    $content .= '<li class="pager-item weather_es-pager-item"><a class="active" rel="3">3</a></li>';
    $content .= '<li class="pager-item weather_es-pager-item"><a class="active" rel="4">4</a></li>';
    $content .= '</ul></div>';
  }
  return $content;
}

/**
 * weather_es block theme
 *
 * @author jmsirvent
 */
function weather_es_theme() {
  return array(
    'weather_es' => array(
      'template' => 'weather-es',
      'arguments' => array(
        'inf_amo' => NULL,
        'day' => NULL,
        'obj' => NULL,
        'inf_typ' => NULL,
        'page' => NULL,
      ),
    ),
  );
}

/**
 * Preprocess and sanitaze the data
 *
 * @author jmsirvent
 */
function template_preprocess_weather_es(&$vars) {
  drupal_add_js(drupal_get_path('module', 'weather_es') . '/js/weather_es.js');
  $vars['image_path'] = drupal_get_path(module, 'weather_es') . '/images/';

  // TODO: ver en el template porqué añade el theme_image...
  // Day0 and day1 have information every 6h
  // Day2 and day3 every 12h
  // Day4, day5 and day6 every 24h
  // Wrap the result in an array because the tpl
  $vars['obj']['date'] = array(
    filter_xss($vars['obj']['date']),
  );
  if (in_array('sky', $vars['inf_typ'])) {
    if ($vars['inf_amo'] == 're') {
      if ($vars['day'] < 4) {
        $am = $vars['obj']['sky']['00-12'];
        $pm = $vars['obj']['sky']['12-24'];
        $vars['obj']['sky'] = NULL;
        foreach ($am as $text => $img) {
          $am[filter_xss($text)] = filter_xss($img);
        }
        foreach ($pm as $text => $img) {
          $pm[filter_xss($text)] = filter_xss($img);
        }
        $vars['obj']['sky']['am'] = $am;
        $vars['obj']['sky']['pm'] = $pm;
      }
      else {
        $allDay = $vars['obj']['sky']['00-24'];
        $vars['obj']['sky'] = NULL;
        foreach ($allDay as $text => $img) {
          $allDay[filter_xss($text)] = filter_xss($img);
        }
        $vars['obj']['sky']['day'] = $allDay;
      }
    }
    elseif ($vars['inf_amo'] == 'fu') {

      // TODO
    }
  }
  else {
    unset($vars['obj']['sky']);
  }
  if (in_array('rain', $vars['inf_typ'])) {
    if ($vars['inf_amo'] == 're') {
      if ($vars['day'] < 4) {
        $am = $vars['obj']['rain']['00-12'];
        $pm = $vars['obj']['rain']['12-24'];
        $vars['obj']['rain'] = NULL;
        $vars['obj']['rain']['am'] = filter_xss($am);
        $vars['obj']['rain']['pm'] = filter_xss($pm);
      }
      else {
        $allDay = $vars['obj']['rain']['00-24'];
        $vars['obj']['rain'] = NULL;
        $vars['obj']['rain']['day'] = filter_xss($allDay);
      }
    }
    elseif ($vars['inf_amo'] == 'fu') {

      // TODO
    }
  }
  else {
    unset($vars['obj']['rain']);
  }
  if (in_array('temperature', $vars['inf_typ'])) {
    $min = $vars['obj']['temp']['minima'];
    $max = $vars['obj']['temp']['maxima'];
    $vars['obj']['temp'] = NULL;
    $vars['obj']['temp']['min'] = filter_xss($min);
    $vars['obj']['temp']['max'] = filter_xss($max);
  }
  else {
    unset($vars['obj']['temp']);
  }
  if (in_array('chill', $vars['inf_typ'])) {
    $min = $vars['obj']['chill']['minima'];
    $max = $vars['obj']['chill']['maxima'];
    $vars['obj']['chill'] = NULL;
    $vars['obj']['chill']['min'] = filter_xss($min);
    $vars['obj']['chill']['max'] = filter_xss($max);
  }
  else {
    unset($vars['obj']['chill']);
  }
  if (in_array('snow', $vars['inf_typ'])) {
    if ($vars['inf_amo'] == 're') {
      if ($vars['day'] < 4) {
        $am = strlen($vars['obj']['snow']['00-12']) != 0 ? $vars['obj']['snow']['00-12'] : 'na';
        $pm = strlen($vars['obj']['snow']['12-24']) != 0 ? $vars['obj']['snow']['12-24'] : 'na';
        $vars['obj']['snow'] = NULL;
        $vars['obj']['snow']['am'] = filter_xss($am);
        $vars['obj']['snow']['pm'] = filter_xss($pm);
      }
      else {
        $allDay = strlen($vars['obj']['snow']['00-24']) != 0 ? $vars['obj']['snow']['00-24'] : 'na';
        $vars['obj']['snow'] = NULL;
        $vars['obj']['snow']['day'] = filter_xss($allDay);
      }
    }
    elseif ($vars['inf_amo'] == 'fu') {

      // TODO
    }
  }
  else {
    unset($vars['obj']['snow']);
  }
  if (in_array('wind', $vars['inf_typ'])) {
    if ($vars['inf_amo'] == 're') {
      if ($vars['day'] < 4) {
        $am = $vars['obj']['wind']['00-12'];
        $pm = $vars['obj']['wind']['12-24'];
        $vars['obj']['wind'] = NULL;
        foreach ($am as $dir => $spd) {
          $am[filter_xss($dir)] = filter_xss($spd);
        }
        foreach ($pm as $dir => $spd) {
          $pm[filter_xss($dir)] = filter_xss($spd);
        }
        $vars['obj']['wind']['am'] = $am;
        $vars['obj']['wind']['pm'] = $pm;
      }
      else {
        $allDay = $vars['obj']['wind']['00-24'];
        $vars['obj']['wind'] = NULL;
        foreach ($allDay as $dir => $spd) {
          $allDay[filter_xss($dir)] = filter_xss($spd);
        }
        $vars['obj']['wind']['day'] = $allDay;
      }
    }
    elseif ($vars['inf_amo'] == 'fu') {

      // TODO
    }
  }
  else {
    unset($vars['obj']['wind']);
  }
  if (in_array('gust', $vars['inf_typ'])) {
    if ($vars['inf_amo'] == 're') {
      if ($vars['day'] < 4) {
        $am = strlen($vars['obj']['gust']['00-12']) != 0 ? $vars['obj']['gust']['00-12'] : 'na';
        $pm = strlen($vars['obj']['gust']['12-24']) != 0 ? $vars['obj']['gust']['12-24'] : 'na';
        $vars['obj']['gust'] = NULL;
        $vars['obj']['gust']['am'] = filter_xss($am);
        $vars['obj']['gust']['pm'] = filter_xss($pm);
      }
      else {
        $allDay = strlen($vars['obj']['gust']['00-24']) != 0 ? $vars['obj']['gust']['00-24'] : 'na';
        $vars['obj']['gust'] = NULL;
        $vars['obj']['gust']['day'] = filter_xss($allDay);
      }
    }
    elseif ($vars['inf_amo'] == 'fu') {

      // TODO
    }
  }
  else {
    unset($vars['obj']['gust']);
  }
  if (in_array('humidity', $vars['inf_typ'])) {
    $min = $vars['obj']['hum']['minima'];
    $max = $vars['obj']['hum']['maxima'];
    $vars['obj']['hum'] = NULL;
    $vars['obj']['hum']['min'] = filter_xss($min);
    $vars['obj']['hum']['max'] = filter_xss($max);
  }
  else {
    unset($vars['obj']['hum']);
  }
  if (in_array('uv', $vars['inf_typ'])) {

    // Wrap the result in an array because the tpl
    $vars['obj']['uv'] = strlen($vars['obj']['uv'] != 0) ? array(
      filter_xss($vars['obj']['uv']),
    ) : array(
      'na',
    );
  }
  else {
    unset($vars['obj']['uv']);
  }
}

//-------------------------------------------------------

// All this functions should be included in weather_es.inc

/**
 * Spanish provinces
 *
 * @author jmsirvent
 */
function _weather_es_provinces() {
  $p = array(
    '---' => t('All provinces'),
    '15' => "A Coruña",
    '01' => "Álava",
    '02' => "Albacete",
    '03' => "Alicante",
    '04' => "Almería",
    '33' => "Asturias",
    '05' => "Ávila",
    '06' => "Badajoz",
    '08' => "Barcelona",
    '09' => "Burgos",
    '10' => "Cáceres",
    '11' => "Cádiz",
    '39' => "Cantabria",
    '12' => "Castellón",
    '51' => "Ceuta",
    '13' => "Ciudad Real",
    '14' => "Córdoba",
    '16' => "Cuenca",
    '17' => "Girona",
    '18' => "Granada",
    '19' => "Guadalajara",
    '20' => "Guipúzcoa",
    '21' => "Huelva",
    '22' => "Huesca",
    '07' => "Illes Balears",
    '23' => "Jaén",
    '26' => "La Rioja",
    '35' => "Las Palmas",
    '24' => "León",
    '25' => "Lleida",
    '27' => "Lugo",
    '28' => "Madrid",
    '29' => "Málaga",
    '52' => "Melilla",
    '30' => "Murcia",
    '31' => "Navarra",
    '32' => "Ourense",
    '34' => "Palencia",
    '36' => "Pontevedra",
    '37' => "Salamanca",
    '38' => "Santa Cruz de Tenerife",
    '40' => "Segovia",
    '41' => "Sevilla",
    '42' => "Soria",
    '43' => "Tarragona",
    '44' => "Teruel",
    '45' => "Toledo",
    '46' => "Valencia",
    '47' => "Valladolid",
    '48' => "Vizcaya",
    '49' => "Zamora",
    '50' => "Zaragoza",
  );
  return $p;
}

/**
 * Spanish cities by province
 *
 * @author jmsirvent
 */
function _weather_es_cities($province) {
  $province = !empty($province) ? $province : '---';
  $cities = new weather_es_citPro($province);
  if ($cities
    ->error()) {
    if ($user->uid) {
      drupal_set_message($cities
        ->errorMessage(), 'error');
    }
  }
  return $cities
    ->getCities();
}

/**
 * Redirect the user to her correct path.
 *
 * @author jmsirvent
 */
function _weather_es_path($uid) {
  if ($uid == 0) {
    $path = 'admin/settings/weather_es';
  }
  else {
    $path = 'user/' . $uid . '/weather_es';
  }
  return $path;
}

/**
 * AHAH for the cities
 *
 * @author jmsirvent
 */
function weather_es_update_cities_js() {
  $form = weather_es_ahah_helper();
  $changed_elements = $form['combo']['ciudad'];

  // Prevent duplicate wrappers.
  unset($changed_elements['#prefix'], $changed_elements['#suffix']);

  // It must be this way, but we don't want to see posible errors...

  //$output = theme('status_messages') . drupal_render($changed_elements);
  $output = drupal_render($changed_elements);
  drupal_json(array(
    'status' => TRUE,
    'data' => $output,
  ));
}

/**
 * Does the very standard things that must be done in any normal callback.
 * Used by each callback in this example module.
 *
 * @author jmsirvent
 */
function weather_es_ahah_helper() {

  // From http://drupal.org/node/331941
  $form_state = array(
    'storage' => NULL,
    'submitted' => FALSE,
  );
  $form_build_id = $_POST['form_build_id'];
  $form = form_get_cache($form_build_id, $form_state);
  $args = $form['#parameters'];
  $form_id = array_shift($args);
  $form_state['post'] = $form['#post'] = $_POST;
  $form['#programmed'] = $form['#redirect'] = FALSE;

  // Enable the submit/validate handlers to determine whether AHAH-submittted.
  $form_state['ahah_submission'] = TRUE;

  // From http://jbenner.net/blog/prevent-ahah-the-right-way-from-breaking-with-validation
  // Stash original form action to avoid overwriting with drupal_rebuild_form().
  $form_state['action'] = $form['#action'];
  drupal_process_form($form_id, $form, $form_state);
  $form = drupal_rebuild_form($form_id, $form_state, $args, $form_build_id);
  return $form;
}

/**
 * Redirect the user to his correct path: their weather_es settings or the
 * weather_es site settings
 *
 * @author jmsirvent
 */
function _weather_es_redirect($wid) {
  if ($wid == 0) {
    $path = 'admin/settings/weather_es';
  }
  else {
    $path = 'user/' . $wid . '/weather_es';
  }
  return $path;
}

/**
 * Save the user configuration
 *
 * @author jmsirvent
 */
function _weather_es_conf_save($wid, $cit_cod, $lan, $inf_typ, $inf_amo) {
  db_query("INSERT INTO {weather_es_conf} (wid, cit_cod, lan, inf_typ, inf_amo) VALUES (%d, %d, '%s', '%s', '%s')", $wid, $cit_cod, $lan, $inf_typ, $inf_amo);
}

/**
 * Update an old user configuration
 *
 * @author jmsirvent
 */
function _weather_es_conf_update($wid, $cit_cod, $lan, $inf_typ, $inf_amo) {
  db_query("UPDATE {weather_es_conf} SET lan = '%s', inf_typ = '%s', inf_amo = '%s' WHERE wid = %d AND cit_cod = %d", $lan, $inf_typ, $inf_amo, $wid, $cit_cod);
}

/**
 * Save the AEMET data for a city
 *
 * @author jmsirvent
 */
function _weather_es_data_save($cit_cod, $cit_nam, $aemet) {
  db_query("INSERT INTO {weather_es_data} (cit_cod, cit_nam, nex_upd, dat_dat)\n            VALUES (%d, '%s', %d, '%s')", $cit_cod, $cit_nam, time() + 4 * 3600, $aemet);
}

Functions

Namesort descending Description
block_weather_es_contents Show the weather_es contents
template_preprocess_weather_es Preprocess and sanitaze the data
weather_es_ahah_helper Does the very standard things that must be done in any normal callback. Used by each callback in this example module.
weather_es_block hook_block()
weather_es_delete_form @author jmsirvent
weather_es_delete_form_submit @author jmsirvent
weather_es_edit_form @author jmsirvent
weather_es_form_submit @author jmsirvent
weather_es_form_validate @author jmsirvent
weather_es_help hook_help()
weather_es_main Main weather_es_page. Show the cities you want to know the weather if there're selected...
weather_es_menu hook_menu
weather_es_perm Implementation of hook_perm()
weather_es_theme weather_es block theme
weather_es_update_cities_js AHAH for the cities
_weather_es_cities Spanish cities by province
_weather_es_conf_save Save the user configuration
_weather_es_conf_update Update an old user configuration
_weather_es_data_save Save the AEMET data for a city
_weather_es_path Redirect the user to her correct path.
_weather_es_provinces Spanish provinces
_weather_es_redirect Redirect the user to his correct path: their weather_es settings or the weather_es site settings