You are here

block_country.module in Block Country 7

Country_Block - Module for showing the country specific blocks.

File

block_country.module
View source
<?php

/**
 * @file
 * Country_Block - Module for showing the country specific blocks.
 */

// Load locale.inc from the include folder.
include_once DRUPAL_ROOT . '/includes/locale.inc';

/**
 * Implements hook_help().
 */
function block_country_help($path, $arg) {
  switch ($path) {
    case 'admin/help#block_country':
      $output = '';
      $output .= '<p>' . t('This module helps to create country specific Blocks. It Add country setting to block and manages country specific display of block.') . '</p>';
      $output .= '<p>' . t("Block will be only visible for the selected countries. It detects and gets User's country from Ip2Country information and based on this it manages block visibility.") . '</p>';
      return $output;
  }
}

/**
 * Implements hook_boot().
 */
function block_country_boot() {
  if (!isset($_SESSION['user_country_code'])) {

    // We need ip2country_get_country() so make sure it gets loaded.
    drupal_load('module', 'ip2country');

    // Create a session variable to store user country.
    $_SESSION['user_country_code'] = '';

    // Get user IP address.
    $ip = ip_address();

    // Get country code based on user IP address.
    $country_code = ip2country_get_country($ip);

    // Set country code, if not set default.
    $_SESSION['user_country_code'] = !empty($country_code) ? $country_code : variable_get('site_default_country', 'IN');
  }
}

/**
 * Implements hook_permission().
 */
function block_country_permission() {
  return array(
    'administer block country' => array(
      'title' => t('Administer block by Country'),
      'description' => t('Set Countrywise visibility for blocks.'),
    ),
  );
}

/**
 * Implements hook_form_alter().
 *
 * Adds Country specific visibility options to block configuration form.
 *
 * @see block_admin_configure()
 */
function block_country_form_alter(&$form, &$form_state, $form_id) {

  // Check if user have access to configure block country.
  if (user_access('administer block country') && ($form_id == 'block_admin_configure' || $form_id == 'block_add_block_form')) {

    // Get country list for current block.
    $selected_country_query = db_select('block_country', 'bc')
      ->fields('bc', array(
      'country_code',
    ))
      ->condition('bc.delta', $form['delta']['#value'])
      ->condition('bc.module', $form['module']['#value']);
    $selected_country_list = $selected_country_query
      ->execute()
      ->fetchAllKeyed(0, 0);
    $block_visibility_country = TRUE;
    if ($form_id == 'block_admin_configure') {

      // Load statically cached block object.
      $block = block_load($form['module']['#value'], $form['delta']['#value']);
      $block_visibility_country = !empty($block->country_visiblility) ? TRUE : FALSE;
    }
    $form['visibility']['block_country'] = array(
      '#type' => 'fieldset',
      '#title' => t('Country'),
      '#weight' => 31,
      '#collapsible' => TRUE,
      '#group' => 'visibility',
      '#attached' => array(
        'js' => array(
          drupal_get_path('module', 'block_country') . '/block_country.js',
        ),
      ),
    );

    // Block visibility.
    $form['visibility']['block_country']['block_visibility_country'] = array(
      '#title' => t('Visible on all country'),
      '#type' => 'checkbox',
      '#description' => t('If checked block will display in all countries. For displaying block in specific country uncheck it.'),
      '#default_value' => $block_visibility_country,
      '#weight' => 1,
    );

    // Country Option list.
    $form['visibility']['block_country']['country_code'] = array(
      '#type' => 'select',
      '#title' => t('Select Country'),
      '#multiple' => TRUE,
      '#options' => country_get_list(),
      '#default_value' => $selected_country_list,
      '#description' => t('Block will be visible in selected countries'),
      '#weight' => 2,
      '#states' => array(
        'visible' => array(
          ':input[name="block_visibility_country"]' => array(
            'checked' => FALSE,
          ),
        ),
      ),
    );

    // Custom validate to make country list mandatory,
    // if "Visible on all Country" checkbox is unchecked.
    $form['#validate'][] = 'block_country_form_validate';

    // Custom block admin configuration form submit.
    $form['#submit'][] = 'block_country_form_block_admin_configure_submit';
  }
}

/**
 * Custom validate for block_country_form form.
 */
function block_country_form_validate($form, &$form_state) {

  // If checkbox is unchecked and no country is selected from the country_list,
  // then throw appropriate error message.
  if ($form_state['values']['block_visibility_country'] == 0 && empty($form_state['values']['country_code'])) {
    form_set_error('country_code', t('Select country field is required.'));
  }
}

/**
 * Form submit handler for block configuration form.
 *
 * @see block_country_form_alter()
 */
function block_country_form_block_admin_configure_submit($form, &$form_state) {

  // Update block visibility option.
  db_update('block')
    ->fields(array(
    'country_visiblility' => $form_state['values']['block_visibility_country'],
  ))
    ->condition('module', $form_state['values']['module'])
    ->condition('delta', $form_state['values']['delta'])
    ->execute();

  // Delete existing values for current block.
  db_delete('block_country')
    ->condition('module', $form_state['values']['module'])
    ->condition('delta', $form_state['values']['delta'])
    ->execute();

  // Add country details for current block.
  foreach ($form_state['values']['country_code'] as $country_code) {
    $block_details = new stdClass();
    $block_details->module = $form_state['values']['module'];
    $block_details->delta = $form_state['values']['delta'];
    $block_details->country_code = $country_code;
    drupal_write_record('block_country', $block_details);
  }
}

/**
 * Implements hook_block_list_alter().
 *
 * Check country visibility for block
 * Remove block if block is not visible for specific country.
 */
function block_country_block_list_alter(&$blocks) {
  foreach ($blocks as $key => $block) {

    // Check Country settings is enabled for block.
    if (!$block->country_visiblility) {

      // If country settings enabled for a block then validate block visibility
      // in current country.
      $country_query = db_select('block_country', 'cb');
      $country_query
        ->condition('cb.module', $block->module, '=')
        ->condition('cb.delta', $block->delta, '=')
        ->fields('cb', array(
        'country_code',
      ));
      $country_list = $country_query
        ->execute()
        ->fetchAllKeyed(0, 0);

      // Remove block if block is not visible for specific country.
      if (!in_array($_SESSION['user_country_code'], $country_list)) {
        unset($blocks[$key]);
      }
    }
  }
}

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Alter block_custom_block_delete form.
 */
function block_country_form_block_custom_block_delete_alter(&$form, &$form_state) {

  // Add custom submit handler to remove block country specific values.
  $form['#submit'][] = 'block_country_custom_block_delete_submit';
}

/**
 * Confirm the deletion of the block. Deletes its data from the database.
 */
function block_country_custom_block_delete_submit(&$form, &$form_state) {

  // Delete country specific values from block once custom block get deleted.
  db_delete('block_country')
    ->condition('module', 'block')
    ->condition('delta', $form_state['values']['bid'])
    ->execute();
}

Functions

Namesort descending Description
block_country_block_list_alter Implements hook_block_list_alter().
block_country_boot Implements hook_boot().
block_country_custom_block_delete_submit Confirm the deletion of the block. Deletes its data from the database.
block_country_form_alter Implements hook_form_alter().
block_country_form_block_admin_configure_submit Form submit handler for block configuration form.
block_country_form_block_custom_block_delete_alter Implements hook_form_FORM_ID_alter().
block_country_form_validate Custom validate for block_country_form form.
block_country_help Implements hook_help().
block_country_permission Implements hook_permission().