You are here

weather_es.module in Weather_es 7

File

weather_es.module
View source
<?php

/**
 * @file
 * 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.
 *
 * 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 drupal_get_path('module', 'weather_es') . '/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/config/services/weather_es':
      return t('<p>Here you can create a configuration with one or more locations or delete a location from your configuration.</p>');
  }
}

/**
 * hook_perm()
 *
 * @author jmsirvent
 */
function weather_es_permission() {
  return array(
    'administer custom weather_es block' => array(
      'title' => t('Administer custom weather_es block'),
      'description' => t('Allows users to configure their custom weather_es block.'),
    ),
  );
}

/**
 * hook_menu
 *
 * @author jmsirvent
 */
function weather_es_menu() {
  $items['admin/config/services/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/config/services/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/config/services/weather_es/modify'] = array(
    'title' => 'Weather_es',
    'description' => 'Configure the system weather_es block',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'weather_es_modify_form',
      '0',
    ),
    'access arguments' => array(
      'administer site configuration',
    ),
    'type' => MENU_CALLBACK,
  );
  $items['admin/config/services/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;
}

/**
 * hook_block_info()
 *
 * @author jmsirvent
 */
function weather_es_block_info() {
  $blocks = array();
  $blocks['system'] = array(
    'info' => t('Weather_es: system-wide'),
    'cache' => DRUPAL_NO_CACHE,
  );
  $blocks['user'] = array(
    'info' => t('Weather_es: custom user'),
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

/**
 * hook_block_view()
 *
 * @author jmsirvent
 */
function weather_es_block_view($delta = '') {
  $show_block = FALSE;
  switch ($delta) {
    case 'system':
      if (user_access('access content')) {
        $content = _weather_es_contents($delta);
        $block = array(
          'subject' => t('System weather'),
          'content' => $content,
        );
        $show_block = TRUE;
      }
      break;
    case 'user':
      if (user_access('administer custom weather_es block')) {
        $content = _weather_es_contents($delta);
        $block = array(
          'subject' => t('User weather'),
          'content' => $content,
        );
        $show_block = TRUE;
      }
      break;
  }
  if ($show_block) {
    return $block;
  }
}

/**
 * @param $form_state, $wid: 0: site, int: user->uid
 *
 * @author jmsirvent
 */
function weather_es_edit_form($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(
    '#ajax' => array(
      'callback' => 'weather_es_update_cities_callback',
      'wrapper' => 'city-dropdown',
      'method' => 'replace',
      'effect' => 'none',
    ),
  );
  $province = isset($form_state['values']) ? $form_state['values']['combo']['provincia'] : '---';
  $form['combo']['ciudad'] = array(
    '#title' => t('City'),
    '#type' => 'select',
    '#description' => t('City to show the forecast'),
    '#options' => _weather_es_cities($province),
    '#prefix' => '<div id="city-dropdown">',
    '#suffix' => '</div>',
  );

  /* This doesn't work this way anymore...
    $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;
}

/**
 * @param $form_state; int $wid: 0: site, user->uid; int $cit_cod; string $cit_name
 *
 * @author jmsirvent
 */
function weather_es_modify_form($form, &$form_state, $wid, $cit_cod, $cit_nam) {

  // Get the user previous options
  $result = db_query("SELECT inf_typ FROM {weather_es_conf} WHERE wid = :wid AND cit_cod = :cod", array(
    ':wid' => $wid,
    ':cod' => $cit_cod,
  ))
    ->fetchField();
  $inf_typ = unserialize($result);
  $defaults = array();
  if (is_array($inf_typ)) {
    foreach ($inf_typ as $key => $value) {
      $defaults[$key] = $value;
    }
  }
  $form['informacion'] = array(
    '#type' => 'checkboxes',
    '#title' => t('What kind of 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' => $defaults,
  );
  $form['combo'] = array(
    '#type' => 'hidden',
    '#tree' => TRUE,
  );
  $form['combo']['ciudad'] = array(
    '#type' => 'hidden',
    '#value' => $cit_cod,
  );
  $form_state['storage']['wid'] = $wid;
  $form['#submit'] = array(
    'weather_es_form_submit',
  );
  $form['#validate'] = array(
    'weather_es_form_validate',
  );
  return confirm_form($form, t('Are you sure you want to modify the %name forecast information?', array(
    '%name' => $cit_nam,
  )), _weather_es_redirect($wid), t('This action cannot be undone.'), t('Change configuration'), t('Cancel'));
}

/**
 * @hook_form_FORM_ID_alter
 *
 * @author jmsirvent
 *
function weather_es_form_weather_es_modify_form_alter(&$form, &$form_state, $form_id) {
  $form['combo']['ciudad'] = array(
    '#type' => 'hidden',
    '#value' => $form_state['storage']['cit_cod'],
  );
}
*/

/**
 * @param $form_state; int $wid: 0: site, user->uid; int $cit_cod; string $cit_name
 *
 * @author jmsirvent
 */
function weather_es_delete_form($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
  db_delete('weather_es_data')
    ->condition('cit_cod', $form_state['values']['cit_cod'])
    ->execute();
  drupal_set_message(t('The location has been deleted.'));
  $form_state['redirect'] = _weather_es_redirect($form_state['values']['wid']);
}

/**
 * AHAH for the cities
 *
 * @author jmsirvent
 */
function weather_es_update_cities_callback($form, $form_state) {
  return $form['combo']['ciudad'];
}

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

  // If there's AHAH sent, that's 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'))) {
  if (isset($form_state['values']['combo']['provincia']) && $form_state['values']['combo']['provincia'] == '---') {

    //form_set_error('ciudad', t('You must select a valid city and language.'));
    form_set_error('combo][provincia', t('You must select a valid province.'));
  }

  //if ($form_state['values']['combo']['ciudad'] == '00') {
  if (empty($form_state['values']['combo']['ciudad'])) {
    form_set_error('combo][ciudad', t('You must select a valid city.'));
  }
  if (count(array_filter($form_state['values']['informacion'])) == 0) {
    form_set_error('informacion', t('You must select at last one information type to show it.'));
  }
}

/**
 * @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
      db_delete('weather_es_conf')
        ->condition('wid', array(
        ':wid' => $form_state['storage']['wid'],
      ))
        ->execute();
    }

    // Avoid adding a city already in the user configuration
    if (!db_query("SELECT COUNT(wid) FROM {weather_es_conf} WHERE wid = :wid AND cit_cod = :cod", array(
      ':wid' => $form_state['storage']['wid'],
      ':cod' => $form_state['values']['combo']['ciudad'],
    ))
      ->fetchField()) {

      // 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'], 'en', 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'], 'en', serialize(array_filter($form_state['values']['informacion'])), 're');
    }

    // Delete the previous city data and save the new one
    db_delete('weather_es_data')
      ->condition('cit_cod', array(
      ':cit_cod' => $form_state['values']['combo']['ciudad'],
    ))
      ->execute();

    //$cities = _weather_es_cities($form_state['values']['combo']['provincia']);
    $cities = _weather_es_cities(substr($form_state['values']['combo']['ciudad'], 0, 2));
    _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_update('weather_es_data')
      ->fields(array(
      'nex_upd' => time() + 10 * 60,
    ))
      ->condition('cit_cod', $form_state['values']['combo']['ciudad'])
      ->execute();
    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']));
}

/**
 * Weather_es contents
 *
 * @author jmsirvent
 */
function _weather_es_contents($delta) {
  global $user;
  $wid = $user->uid;
  if ($delta == 'system') {
    $wid = 0;
  }

  // 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 = :wid";
  $usrcnfresult = db_query($sql, array(
    ':wid' => $wid,
  ));
  $content = '';
  while ($usrcnf = $usrcnfresult
    ->fetchObject()) {

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

      // Get data from AEMET
      $aemet = new weather_es_Aemet($usrcnf->cit_cod);
      if ($aemet
        ->isLoadOk()) {

        // Delete the previous city data and save the new one
        db_delete('weather_es_data')
          ->condition('cit_cod', array(
          ':cit_cod' => $usrcnf->cit_cod,
        ))
          ->execute();
        _weather_es_data_save($usrcnf->cit_cod, $usrcnf->cit_nam, serialize($aemet));

        /*
        // Next connectio to AEMET in 4h
        db_update('weather_es_data')
          ->condition('cit_cod', array(':cit_cod' => $usrcnf->cit_cod))
          ->fields(array('nex_upd' => (time() + (4 * 3600))))
          ->execute();
        */
      }
      else {

        // The connection with AEMET has failt, try in 10'
        db_update('weather_es_data')
          ->condition('cit_cod', array(
          ':cit_cod' => $usrcnf->cit_cod,
        ))
          ->fields(array(
          'nex_upd' => time() + 10 * 60,
        ))
          ->execute();
      }
    }
    $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 = :wid AND wec.cit_cod = :cit_cod";
    $result = db_query($sql, array(
      ':wid' => $wid,
      ':cit_cod' => $usrcnf->cit_cod,
    ))
      ->fetchObject();

    // 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', array(
        'inf_amo' => $result->inf_amo,
        'day' => $day,
        'obj' => $obj,
        'inf_typ' => $inf_typ,
        'page' => $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) {

  // We've added weather_es.js in the weather_es.info -> hole site
  // drupal_add_js(drupal_get_path('module', 'weather_es') . '/js/weather_es.js');
  // 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_num) {

          /*
           * <img src="<?php print $image_path .$img; ?>.png" title="<?php print $txt; ?>" alt="<?php print $txt; ?>"/>
           * That isn't correct in all urls...http://drupal7.local --> ok; http://drupal7.local/user/1/weather_es --> nok
           */
          $img = theme('image', array(
            'path' => drupal_get_path('module', 'weather_es') . '/images/' . $img_num . '.png',
            'alt' => $text,
            'title' => $text,
          ));
          $am[filter_xss($text)] = $img;
        }
        foreach ($pm as $text => $img_num) {
          $img = theme('image', array(
            'path' => drupal_get_path('module', 'weather_es') . '/images/' . $img_num . '.png',
            'alt' => $text,
            'title' => $text,
          ));
          $pm[filter_xss($text)] = $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_num) {
          $img = theme('image', array(
            'path' => drupal_get_path('module', 'weather_es') . '/images/' . $img_num . '.png',
            'alt' => $text,
            'title' => $text,
          ));
          $allDay[filter_xss($text)] = $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']);
  }
}

/**
 * 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',
    ),
    //TODO

    //array('data' => t('Languaje')),
    array(
      'data' => t('Operation'),
    ),
  );

  //TODO

  //$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 = :wid";
  $sql = "SELECT wed.cit_nam, wed.cit_cod FROM {weather_es_data} wed INNER JOIN {weather_es_conf} wec ON (wec.cit_cod = wed.cit_cod) WHERE wec.wid = :wid";

  //->orderByHeader($header)
  $result = db_query($sql, array(
    ':wid' => $wid,
  ), array(
    'fetch' => PDO::FETCH_ASSOC,
  ));
  while ($row = $result
    ->fetchAssoc()) {
    $rows[] = array(
      'cit_nam' => $row['cit_nam'],
      //TODO

      //'lan' => $row['lan'],
      'ope' => l(t('edit'), $path . '/modify/' . $row['cit_cod'] . '/' . $row['cit_nam']) . '/' . l(t('delete'), $path . '/delete/' . $row['cit_cod'] . '/' . $row['cit_nam']),
    );
  }

  //if (count($rows) == 0) {

  //if (!$rows) {
  if (!isset($rows)) {
    $rows[] = array(
      array(
        'data' => '<em>' . t('There are currently no locations.') . '</em>',
        'colspan' => 2,
      ),
    );
  }
  $output = theme('table', array(
    'header' => $header,
    'rows' => $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;
}

/**
 * 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/config/services/weather_es';
  }
  else {
    $path = 'user/' . $wid . '/weather_es';
  }
  return $path;
}

/**
 * Save the AEMET data for a city
 *
 * @author jmsirvent
 */
function _weather_es_data_save($cit_cod, $cit_nam, $aemet) {
  db_insert('weather_es_data')
    ->fields(array(
    'cit_cod',
    'cit_nam',
    'nex_upd',
    'dat_dat',
  ))
    ->values(array(
    'cit_cod' => $cit_cod,
    'cit_nam' => $cit_nam,
    'nex_upd' => time() + 4 * 3600,
    'dat_dat' => $aemet,
  ))
    ->execute();
}

/**
 * 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();
}

/**
 * Save the user configuration
 *
 * @author jmsirvent
 */
function _weather_es_conf_save($wid, $cit_cod, $lan, $inf_typ, $inf_amo) {
  db_insert('weather_es_conf')
    ->fields(array(
    'wid',
    'cit_cod',
    'lan',
    'inf_typ',
    'inf_amo',
  ))
    ->values(array(
    'wid' => $wid,
    'cit_cod' => $cit_cod,
    'lan' => $lan,
    'inf_typ' => $inf_typ,
    'inf_amo' => $inf_amo,
  ))
    ->execute();
}

/**
 * Update an old user configuration
 *
 * @author jmsirvent
 */
function _weather_es_conf_update($wid, $cit_cod, $lan, $inf_typ, $inf_amo) {
  $and_q = db_and();
  $and_q
    ->condition('wid', array(
    ':wid' => $wid,
  ))
    ->condition('cit_cod', array(
    ':cit_cod' => $cit_cod,
  ));
  db_update('weather_es_conf')
    ->fields(array(
    'lan' => $lan,
    'inf_typ' => $inf_typ,
    'inf_amo' => $inf_amo,
  ))
    ->condition($and_q)
    ->execute();
}

Functions

Namesort descending Description
template_preprocess_weather_es Preprocess and sanitaze the data
weather_es_block_info hook_block_info()
weather_es_block_view hook_block_view()
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_menu hook_menu
weather_es_modify_form @author jmsirvent
weather_es_permission hook_perm()
weather_es_theme weather_es block theme
weather_es_update_cities_callback 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_contents Weather_es contents
_weather_es_data_save Save the AEMET data for a city
_weather_es_main Main weather_es_page. Show the cities you want to know the weather if there're selected...
_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