<?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_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 : '.';

  $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',
  );

  return $items;
}

/**
 * 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') . ' ' . $count;
    }
    $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>abcdef-ghij</strong>, then insert only <strong>abcdef-ghij</strong> here.'),
    '#required' => TRUE,
  );

  return $form;
}

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

/**
 * Implements hook_block_view().
 */
function adsense_cse_block_view($delta = '') {
  if (_adsense_page_match()) {
    $ad = _adsense_cse_get_block_config($delta);
    $block['content'] = ($ad) ? adsense_display(array('format' => 'Search Box', 'slot' => $ad[1])) : t('AdSense unconfigured block. <a href=!url>Click to configure.</a>', array('!url' => url('admin/structure/block/manage/adsense_cse/' . $delta)));
    return $block;
  }
}

/**
 * Configuration of the provided block
 *
 * @param $delta
 *   block number
 * @return
 *   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 $slot
 *   Slot Id for the AdSense for Search
 * @return
 *   HTML with the search input form
 */
function _adsense_cse_get_searchbox($client, $slot = NULL) {
  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) {
    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, Google's Javascript can't be used, so we use a modified local copy
    $script = $base_url . '/' . drupal_get_path('module', 'adsense_cse') . '/adsense_cse.js';
    // If there is a watermark, the indentation of the code makes it impossible to re-use the same text
    $output = <<<CSE_TXT1
<script type="text/javascript"><!--
drupal_adsense_cse_lang = '$language';
//-->
</script>
<form action="$results_path" id="cse-search-box">
  <div>$hidden_q_field
    <input type="hidden" name="cx" value="partner-$client:$slot" />
    <input type="hidden" name="cof" value="FORID:$forid" />
    <input type="hidden" name="ie" value="$encoding" />
    <input type="text" name="as_q" size="$textbox_length" />
    <input type="submit" name="sa" value="$search" />
  </div>
</form>
<script type="text/javascript" src="$script"></script>
CSE_TXT1;
//<script type="text/javascript" src="http://www.google.com/coop/cse/brand?form=cse-search-box&amp;lang=en"></script>
  }
  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(http://www.google.com/cse/api/branding.css);
</style>
<div class="$class" style="background-color:#$box_background_color;color:#$box_text_color">
  <div class="cse-branding-form">
    <form action="$results_path" id="cse-search-box">
      <div>$hidden_q_field
        <input type="hidden" name="cx" value="partner-$client:$slot" />
        <input type="hidden" name="cof" value="FORID:$forid" />
        <input type="hidden" name="ie" value="$encoding" />
        <input type="text" name="as_q" size="$textbox_length" />
        <input type="submit" name="sa" value="$search" />
      </div>
    </form>
  </div>
  <div class="cse-branding-logo">
    <img src="http://www.google.com/images/poweredby_transparent/poweredby_$box_background_color.gif" alt="Google" />
  </div>
  <div class="cse-branding-text">
    $custom_search
  </div>
</div>
CSE_TXT2;
  }

  return $output;
}
