You are here

adsense_cse.module in Google AdSense integration 7

Same filename and directory in other branches
  1. 5.3 cse/adsense_cse.module
  2. 6 cse/adsense_cse.module

Displays Google AdSense ads on Drupal pages.

This is the core module of the AdSense package, with the Drupal hooks and other administrative functions.

File

cse/adsense_cse.module
View source
<?php

/**
 * @file
 * Displays Google AdSense ads on Drupal pages.
 *
 * This is the core module of the AdSense package, with the Drupal hooks
 * and other administrative functions.
 */
define('ADSENSE_CSE_RESULTS_PATH', 'adsense/cse');
define('ADSENSE_CSE_V2_RESULTS_PATH', 'csev2/results');
define('ADSENSE_CSE_AD_BLOCK_DEFAULT', '');
define('ADSENSE_CSE_AD_LOCATION_DEFAULT', 'adsense_cse_loc_top_right');
define('ADSENSE_CSE_COLOR_BOX_BACKGROUND_DEFAULT', 'FFFFFF');
define('ADSENSE_CSE_COUNTRY_DEFAULT', 'www.google.com');
define('ADSENSE_CSE_ENCODING_DEFAULT', 'UTF-8');
define('ADSENSE_CSE_FRAME_WIDTH_DEFAULT', 800);
define('ADSENSE_CSE_LOGO_DEFAULT', 'adsense_cse_branding_right');
define('ADSENSE_CSE_NUMBER_BLOCKS_DEFAULT', 2);
define('ADSENSE_CSE_TEXTBOX_LENGTH_DEFAULT', 31);
define('ADSENSE_CSE_LANGUAGE_DEFAULT', 'en');

/**
 * Implements hook_menu().
 */
function adsense_cse_menu() {
  $items = array();
  $results_path = variable_get('clean_url', 0) ? ADSENSE_CSE_RESULTS_PATH : '.';
  $resultsv2_path = variable_get('clean_url', 0) ? ADSENSE_CSE_V2_RESULTS_PATH : '.';
  $items['admin/config/services/adsense/cse'] = array(
    'title' => 'Custom Search',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'adsense_cse_settings',
    ),
    'access arguments' => array(
      'administer adsense',
    ),
    'weight' => 2,
    'type' => MENU_LOCAL_TASK,
    'file' => 'adsense_cse.admin.inc',
  );
  $items[$results_path] = array(
    'title' => 'Search Results',
    'page callback' => '_adsense_cse_results',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
    'file' => 'adsense_cse.results.inc',
  );
  $items[$resultsv2_path . '/%'] = array(
    'title' => 'Search Results',
    'page callback' => '_adsense_csev2_results',
    'page arguments' => array(
      1,
    ),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
    'file' => 'adsense_csev2.results.inc',
  );
  return $items;
}

/**
 * Implements hook_theme_registry_alter().
 */
function adsense_cse_theme_registry_alter(&$theme_registry) {
  $mod_path = drupal_get_path('module', 'adsense_cse');

  // Munge on a copy.
  $theme_registry_copy = $theme_registry;
  _theme_process_registry($theme_registry_copy, 'phptemplate', 'theme_engine', 'pow', $mod_path);
  $theme_registry += array_diff_key($theme_registry_copy, $theme_registry);
}

/**
 * Implements hook_block_info().
 */
function adsense_cse_block_info() {
  $blocks = array();
  $max = variable_get('adsense_cse_number_blocks', ADSENSE_CSE_NUMBER_BLOCKS_DEFAULT);
  for ($count = 0; $count < $max; $count++) {
    if ($ad = _adsense_cse_get_block_config($count)) {
      $title = $ad[0];
    }
    else {
      $title = t('AdSense CSE: unconfigured !d', array(
        '!d' => $count + 1,
      ));
    }
    $blocks[$count] = array(
      'info' => $title,
      'cache' => DRUPAL_NO_CACHE,
    );
  }
  return $blocks;
}

/**
 * Implements hook_block_configure().
 */
function adsense_cse_block_configure($delta = '') {
  $ad = _adsense_cse_get_block_config($delta);
  $form['info'] = array(
    '#type' => 'textfield',
    '#title' => t('Block description'),
    '#default_value' => $ad ? $ad[0] : '',
    '#maxlength' => 64,
    '#description' => t('A brief description of your block. Used on the <a href="@overview">block overview page</a>.', array(
      '@overview' => url('admin/structure/block'),
    )),
    '#required' => TRUE,
    '#weight' => -19,
  );
  $form['ad_slot'] = array(
    '#type' => 'textfield',
    '#title' => t('Ad Slot ID'),
    '#default_value' => $ad ? $ad[1] : '',
    '#description' => t('This is the provided by the AdSense site in the Search Box Code "cx" field. This is usually provided in the form partner-<em>Publisher ID</em>:<em>Slot Id</em>. If the code provided is, for example, partner-pub-0123456789:<strong>abcdefghij</strong>, then insert only <strong>abcdefghij</strong> here.'),
    '#required' => TRUE,
  );

  // If the block has already been saved, but the version is not set, that
  // means it's a version 1, otherwise set to the latest version (2).
  $default = $ad ? isset($ad[2]) ? $ad[2] : '1' : '2';
  $form['version'] = array(
    '#type' => 'radios',
    '#title' => t('CSE version'),
    '#default_value' => $default,
    '#options' => array(
      '1' => t('Version 1'),
      '2' => t('Version 2'),
    ),
    '#description' => t('CSE version. If unsure, choose %default.', array(
      '%default' => 'Version 2',
    )),
    '#required' => TRUE,
  );
  return $form;
}

/**
 * Implements hook_block_save().
 */
function adsense_cse_block_save($delta = '', $edit = array()) {
  $data = implode(':', array(
    urlencode(check_plain($edit['info'])),
    check_plain($edit['ad_slot']),
    check_plain($edit['version']),
  ));
  variable_set('adsense_cse_ad_block_' . $delta, $data);
}

/**
 * Implements hook_block_view().
 */
function adsense_cse_block_view($delta = '') {
  $block = array();
  if (_adsense_page_match()) {
    $ad = _adsense_cse_get_block_config($delta);
    $fo = isset($ad[2]) && $ad[2] === '2' ? 'Search Box v2' : 'Search Box';
    $block['content'] = $ad ? adsense_display(array(
      'title' => $ad[0],
      'format' => $fo,
      'slot' => $ad[1],
    )) : _adsense_configure_block_message(url('admin/structure/block/manage/adsense_cse/' . $delta));
  }
  return $block;
}

/**
 * Configuration of the provided block.
 *
 * @param int $delta
 *   Block number.
 *
 * @return array|bool
 *   array with the block configuration or FALSE if no such block was found
 */
function _adsense_cse_get_block_config($delta = 0) {
  if ($data = variable_get('adsense_cse_ad_block_' . $delta, ADSENSE_CSE_AD_BLOCK_DEFAULT)) {
    $ad = explode(':', $data);
    $ad[0] = urldecode($ad[0]);
    return $ad;
  }
  return FALSE;
}

/**
 * Generates the CSE search box.
 *
 * @param string $client
 *   Publisher ID.
 * @param int $slot
 *   Slot Id for the AdSense for Search.
 *
 * @return string
 *   HTML with the search input form
 */
function _adsense_cse_get_searchbox($client, $slot = '') {
  global $base_url;
  $branding = variable_get('adsense_cse_logo', ADSENSE_CSE_LOGO_DEFAULT);
  $box_background_color = variable_get('adsense_cse_color_box_background', ADSENSE_CSE_COLOR_BOX_BACKGROUND_DEFAULT);
  $ad_location = variable_get('adsense_cse_ad_location', ADSENSE_CSE_AD_LOCATION_DEFAULT);
  $encoding = variable_get('adsense_cse_encoding', ADSENSE_CSE_ENCODING_DEFAULT);
  $textbox_length = variable_get('adsense_cse_textbox_length', ADSENSE_CSE_TEXTBOX_LENGTH_DEFAULT);
  $language = variable_get('adsense_cse_language', ADSENSE_CSE_LANGUAGE_DEFAULT);
  $search = t('Search');
  $custom_search = t('Custom Search');
  if (variable_get('clean_url', 0)) {
    $results_path = url(ADSENSE_CSE_RESULTS_PATH, array(
      'absolute' => TRUE,
    ));
    $hidden_q_field = '';
  }
  else {
    $results_path = $base_url;
    $hidden_q_field = '<input type="hidden" name="q" value="." />';
  }
  if ($box_background_color == '000000') {
    $box_text_color = 'FFFFFF';
  }
  else {
    $box_text_color = '000000';
  }
  switch ($ad_location) {
    default:
    case 'adsense_cse_loc_top_right':
      $forid = 10;
      break;
    case 'adsense_cse_loc_top_bottom':
      $forid = 11;
      break;
    case 'adsense_cse_loc_right':
      $forid = 9;
      break;
  }
  if ($branding == 'adsense_cse_branding_watermark') {

    // Since we use as_q, we must use a modified copy of Google's Javascript.
    $script = $base_url . '/' . drupal_get_path('module', 'adsense_cse') . '/adsense_cse.js';

    // When using a watermark, code is not reusable due to indentation.
    $output = <<<CSE_TXT1
<script type="text/javascript"><!--
drupal_adsense_cse_lang = '{<span class="php-variable">$language</span>}';
//-->
</script>
<form action="{<span class="php-variable">$results_path</span>}" id="cse-search-box">
  <div>{<span class="php-variable">$hidden_q_field</span>}
    <input type="hidden" name="cx" value="partner-{<span class="php-variable">$client</span>}:{<span class="php-variable">$slot</span>}" />
    <input type="hidden" name="cof" value="FORID:{<span class="php-variable">$forid</span>}" />
    <input type="hidden" name="ie" value="{<span class="php-variable">$encoding</span>}" />
    <input type="text" name="as_q" size="{<span class="php-variable">$textbox_length</span>}" />
    <input type="submit" name="sa" value="{<span class="php-variable">$search</span>}" />
  </div>
</form>
<script type="text/javascript" src="{<span class="php-variable">$script</span>}"></script>
CSE_TXT1;

    // @codingStandardsIgnoreStart Drupal.WhiteSpace.ScopeIndent.IncorrectExact
    // <script type="text/javascript" src="http://www.google.com/coop/cse/brand?form=cse-search-box&amp;lang=en"></script>
    // @codingStandardsIgnoreEnd
  }
  else {
    if ($branding == 'adsense_cse_branding_right') {
      $class = 'cse-branding-right';
    }
    else {
      $class = 'cse-branding-bottom';
    }
    $output = <<<CSE_TXT2
<style type="text/css">
@import url(//www.google.com/cse/api/branding.css);
</style>
<div class="{<span class="php-variable">$class</span>}" style="background-color:#{<span class="php-variable">$box_background_color</span>};color:#{<span class="php-variable">$box_text_color</span>}">
  <div class="cse-branding-form">
    <form action="{<span class="php-variable">$results_path</span>}" id="cse-search-box">
      <div>{<span class="php-variable">$hidden_q_field</span>}
        <input type="hidden" name="cx" value="partner-{<span class="php-variable">$client</span>}:{<span class="php-variable">$slot</span>}" />
        <input type="hidden" name="cof" value="FORID:{<span class="php-variable">$forid</span>}" />
        <input type="hidden" name="ie" value="{<span class="php-variable">$encoding</span>}" />
        <input type="text" name="as_q" size="{<span class="php-variable">$textbox_length</span>}" />
        <input type="submit" name="sa" value="{<span class="php-variable">$search</span>}" />
      </div>
    </form>
  </div>
  <div class="cse-branding-logo">
    <img src="//www.google.com/images/poweredby_transparent/poweredby_{<span class="php-variable">$box_background_color</span>}.gif" alt="Google" />
  </div>
  <div class="cse-branding-text">
    {<span class="php-variable">$custom_search</span>}
  </div>
</div>
CSE_TXT2;
  }
  return $output;
}

/**
 * Generates the CSE v2 search box.
 *
 * @param string $client
 *   Publisher ID.
 * @param int $slot
 *   Slot Id for the AdSense for Search.
 *
 * @return string
 *   HTML with the search input form
 */
function _adsense_csev2_get_searchbox($client, $slot = '') {
  if (variable_get('clean_url', 0)) {
    $results_path = url(ADSENSE_CSE_V2_RESULTS_PATH, array(
      'absolute' => TRUE,
    ));
  }
  else {
    $results_path = $base_url;
  }

  // Add data-queryParameterName because of conflicts with Drupal's 'q' query.
  $output = "<script async src='https://cse.google.com/cse.js?cx=partner-{$client}:{$slot}'></script><div class='gcse-searchbox-only' data-resultsUrl='" . $results_path . '/' . $slot . "' data-queryParameterName='as_q'></div>";
  return $output;
}