<?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.
 */

// Ad types, link or ad.
define('ADSENSE_TYPE_LINK', 1);
define('ADSENSE_TYPE_AD', 2);
define('ADSENSE_TYPE_SEARCH', 3);
define('ADSENSE_TYPE_OTHER', 4);

define('ADSENSE_MAX_CHANNELS', 10);
define('ADSENSE_AD_CHANNEL_DEFAULT', '');

define('ADSENSE_ACCESS_PAGES_DEFAULT', '');
define('ADSENSE_BASIC_ID_DEFAULT', '');
define('ADSENSE_DISABLE_DEFAULT', 0);
define('ADSENSE_ID_MODULE_DEFAULT', 'adsense_basic');
define('ADSENSE_PLACEHOLDER_DEFAULT', 1);
define('ADSENSE_PLACEHOLDER_TEXT_DEFAULT', 'Google AdSense');
define('ADSENSE_TEST_MODE_DEFAULT', 0);
define('ADSENSE_UNBLOCK_ADS_DEFAULT', 0);
define('ADSENSE_VISIBILITY_DEFAULT', 0);

define('ADSENSE_SECRET_LANGUAGE_DEFAULT', '');

/**
 * This is the array that holds all ad formats.
 *
 * All it has is a multi-dimensional array indexed by a key, containing the ad
 * type, the description, Google's javascript ad code and the dimensions.
 *
 * To add a new code:
 * - Make sure the key is not in use by a different format
 * - Go to Google AdSense
 *   . Get the dimensions
 *   . Get the code
 * - Add it below
 *
 * @param string $key
 *   Ad key for which the format is needed (optional).
 * @param bool $newcode
 *   Pass TRUE to get list of new code ads (optional).
 *
 * @return array
 *   if no key is provided: array of supported ad formats as an array (type,
 *   desc(ription), code, width and height)
 *   if a key is provided, the array containing the ad format for that key, or
 *   NULL if there is no ad with that key
 */
function adsense_ad_formats($key = NULL, $newcode = TRUE) {
  // Don't forget to add responsive formats in _adsense_is_responsive().
  $ads = array(
    // @codingStandardsIgnoreStart Drupal.Arrays.Array.LongLineDeclaration
    'responsive' => array('type' => ADSENSE_TYPE_AD, 'desc' => t('Responsive ad unit'), 'code' => 'responsive', 'width' => '', 'height' => ''),
    'custom' => array('type' => ADSENSE_TYPE_AD, 'desc' => t('Custom size ad unit'), 'code' => 'custom', 'width' => '', 'height' => ''),
    'autorelaxed' => array('type' => ADSENSE_TYPE_OTHER, 'desc' => t('Matched content'), 'code' => 'autorelaxed', 'width' => '', 'height' => ''),
    'in-article' => array('type' => ADSENSE_TYPE_OTHER, 'desc' => t('In-article ad'), 'code' => 'in-article', 'width' => '', 'height' => ''),
    'in-feed' => array('type' => ADSENSE_TYPE_OTHER, 'desc' => t('In-feed ad'), 'code' => 'in-feed', 'width' => '', 'height' => ''),
    '120x240' => array('type' => ADSENSE_TYPE_AD, 'desc' => t('Vertical Banner'), 'code' => '120x240_as', 'width' => 120, 'height' => 240),
    '120x600' => array('type' => ADSENSE_TYPE_AD, 'desc' => t('Skyscraper'), 'code' => '120x600_as', 'width' => 120, 'height' => 600),
    '125x125' => array('type' => ADSENSE_TYPE_AD, 'desc' => t('Button'), 'code' => '125x125_as', 'width' => 125, 'height' => 125),
    '160x600' => array('type' => ADSENSE_TYPE_AD, 'desc' => t('Wide Skyscraper'), 'code' => '160x600_as', 'width' => 160, 'height' => 600),
    '180x150' => array('type' => ADSENSE_TYPE_AD, 'desc' => t('Small Rectangle'), 'code' => '180x150_as', 'width' => 180, 'height' => 150),
    '200x200' => array('type' => ADSENSE_TYPE_AD, 'desc' => t('Small Square'), 'code' => '200x200_as', 'width' => 200, 'height' => 200),
    '234x60' => array('type' => ADSENSE_TYPE_AD, 'desc' => t('Half Banner'), 'code' => '234x60_as', 'width' => 234, 'height' => 60),
    '250x250' => array('type' => ADSENSE_TYPE_AD, 'desc' => t('Square'), 'code' => '250x250_as', 'width' => 250, 'height' => 250),
    '300x1050' => array('type' => ADSENSE_TYPE_AD, 'desc' => t('Portrait'), 'code' => '300x1050_as', 'width' => 300, 'height' => 1050),
    '300x250' => array('type' => ADSENSE_TYPE_AD, 'desc' => t('Medium Rectangle'), 'code' => '300x250_as', 'width' => 300, 'height' => 250),
    '300x600' => array('type' => ADSENSE_TYPE_AD, 'desc' => t('Large Skyscraper'), 'code' => '300x600_as', 'width' => 300, 'height' => 600),
    '320x50' => array('type' => ADSENSE_TYPE_AD, 'desc' => t('Mobile Banner'), 'code' => '320x50_as', 'width' => 320, 'height' => 50),
    '320x100' => array('type' => ADSENSE_TYPE_AD, 'desc' => t('Large Mobile Banner'), 'code' => '320x100_as', 'width' => 320, 'height' => 100),
    '336x280' => array('type' => ADSENSE_TYPE_AD, 'desc' => t('Large Rectangle'), 'code' => '336x280_as', 'width' => 336, 'height' => 280),
    '468x60' => array('type' => ADSENSE_TYPE_AD, 'desc' => t('Banner'), 'code' => '468x60_as', 'width' => 468, 'height' => 60),
    '728x90' => array('type' => ADSENSE_TYPE_AD, 'desc' => t('Leaderboard'), 'code' => '728x90_as', 'width' => 728, 'height' => 90),
    '970x250' => array('type' => ADSENSE_TYPE_AD, 'desc' => t('Billboard'), 'code' => '970x250_as', 'width' => 970, 'height' => 250),
    '970x90' => array('type' => ADSENSE_TYPE_AD, 'desc' => t('Large Leaderboard'), 'code' => '970x90_as', 'width' => 970, 'height' => 90),
    'link' => array('type' => ADSENSE_TYPE_LINK, 'desc' => t('Responsive links'), 'code' => 'link', 'width' => '', 'height' => ''),
    '120x90' => array('type' => ADSENSE_TYPE_LINK, 'desc' => t('4-links Vertical Small'), 'code' => '120x90_0ads_al', 'width' => 120, 'height' => 90),
    '160x90' => array('type' => ADSENSE_TYPE_LINK, 'desc' => t('4-links Vertical Medium'), 'code' => '160x90_0ads_al', 'width' => 160, 'height' => 90),
    '180x90' => array('type' => ADSENSE_TYPE_LINK, 'desc' => t('4-links Vertical Large'), 'code' => '180x90_0ads_al', 'width' => 180, 'height' => 90),
    '200x90' => array('type' => ADSENSE_TYPE_LINK, 'desc' => t('4-links Vertical X-Large'), 'code' => '200x90_0ads_al', 'width' => 200, 'height' => 90),
    '468x15' => array('type' => ADSENSE_TYPE_LINK, 'desc' => t('4-links Horizontal Medium'), 'code' => '468x15_0ads_al', 'width' => 468, 'height' => 15),
    '728x15' => array('type' => ADSENSE_TYPE_LINK, 'desc' => t('4-links Horizontal Large'), 'code' => '728x15_0ads_al', 'width' => 728, 'height' => 15),
    '120x90_5' => array('type' => ADSENSE_TYPE_LINK, 'desc' => t('5-links Vertical Small'), 'code' => '120x90_0ads_al_s', 'width' => 120, 'height' => 90),
    '160x90_5' => array('type' => ADSENSE_TYPE_LINK, 'desc' => t('5-links Vertical Medium'), 'code' => '160x90_0ads_al_s', 'width' => 160, 'height' => 90),
    '180x90_5' => array('type' => ADSENSE_TYPE_LINK, 'desc' => t('5-links Vertical Large'), 'code' => '180x90_0ads_al_s', 'width' => 180, 'height' => 90),
    '200x90_5' => array('type' => ADSENSE_TYPE_LINK, 'desc' => t('5-links Vertical X-Large'), 'code' => '200x90_0ads_al_s', 'width' => 200, 'height' => 90),
    '468x15_5' => array('type' => ADSENSE_TYPE_LINK, 'desc' => t('5-links Horizontal Medium'), 'code' => '468x15_0ads_al_s', 'width' => 468, 'height' => 15),
    '728x15_5' => array('type' => ADSENSE_TYPE_LINK, 'desc' => t('5-links Horizontal Large'), 'code' => '728x15_0ads_al_s', 'width' => 728, 'height' => 15),
    // @codingStandardsIgnoreEnd
  );

  if (!$newcode) {
    unset($ads['responsive']);
    unset($ads['custom']);
    unset($ads['autorelaxed']);
    unset($ads['link']);
  }

  if (!empty($key)) {
    if (array_key_exists($key, $ads)) {
      return $ads[$key];
    }
    elseif (substr($key, 0, 10) == 'Search Box') {
      return array('type' => ADSENSE_TYPE_SEARCH, 'desc' => t('AdSense for Search'));
    }
    elseif ($newcode) {
      $ad = _adsense_dimensions($key);
      if (!empty($ad)) {
        return array(
          'type' => ADSENSE_TYPE_AD,
          'desc' => t('Custom'),
          'width' => $ad['width'],
          'height' => $ad['height'],
        );
      }
    }
    return NULL;
  }

  return $ads;
}

/**
 * Implements hook_permission().
 */
function adsense_permission() {
  return array(
    'administer adsense' => array(
      'title' => t('Administer AdSense settings'),
      'description' => t('Perform administration tasks for AdSense.'),
    ),
    'hide adsense' => array(
      'title' => t('Hide AdSense'),
      'description' => t('Hide AdSense ads for this role.'),
    ),
    'show adsense placeholders' => array(
      'title' => t('Show AdSense placeholders'),
      'description' => t('Show AdSense placeholders for this role.'),
    ),
    'use PHP for ad visibility' => array(
      'title' => t('Can use PHP for AdSense visibility'),
    ),
  );
}

/**
 * Implements hook_theme().
 */
function adsense_theme() {
  return array(
    'adsense_ad' => array(
      'variables' => array('ad' => NULL, 'module' => NULL, 'format' => NULL),
    ),
    'adsense_placeholder' => array(
      'variables' => array('text' => NULL, 'width' => 0, 'height' => 0),
    ),
  );
}

/**
 * Implements hook_menu().
 */
function adsense_menu() {
  $items = array();

  $items['admin/config/services/adsense'] = array(
    'title' => 'AdSense',
    'description' => 'Configure Google AdSense Ads.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('adsense_main_settings'),
    'access arguments' => array('administer adsense'),
    'file' => 'adsense.admin.inc',
  );
  $items['admin/config/services/adsense/main'] = array(
    'title' => 'Settings',
    'weight' => 10,
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
  $items['admin/config/services/adsense/publisher'] = array(
    'title' => 'Publisher ID',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('adsense_id_settings'),
    'access arguments' => array('administer adsense'),
    'weight' => 0,
    'type' => MENU_LOCAL_TASK,
    'file' => 'adsense.admin.inc',
  );
  $items['admin/config/services/adsense/publisher/site'] = array(
    'title' => 'Site ID',
    'weight' => -1,
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );

  return $items;
}

/**
 * Implements hook_help().
 */
function adsense_help($path, $arg) {
  switch ($path) {
    case 'admin/help#adsense':
      module_load_include('inc', 'adsense', 'help/adsense.help');
      return adsense_help_text();
  }
  return '';
}

/**
 * Implements hook_filter_info().
 */
function adsense_filter_info() {
  $filters['adsense'] = array(
    'title' => t('AdSense tag'),
    'description' => t('Substitutes an AdSense special tag with an ad. Add this below "Limit allowed HTML tags".'),
    'process callback' => '_adsense_process_tags',
    'tips callback' => '_adsense_filter_tips',
    'cache' => FALSE,
  );

  return $filters;
}

/**
 * Implements callback_filter_tips().
 */
function _adsense_filter_tips($filter, $format, $long = FALSE) {
  return t('Use the special tag [adsense:<em>format</em>:<em>slot</em>] or [adsense:<em>format</em>:<em>[group]</em>:<em>[channel]</em><em>[:slot]</em>] or [adsense:block:<em>location</em>] to display Google AdSense ads.');
}

/**
 * Implements callback_filter_process().
 */
function _adsense_process_tags($text, $filter) {
  $patterns = array(
    'block' => '/\[adsense:block:([^\]]+)\]/x',
    'oldtag' => '/\[adsense:([^:]+):(\d*):(\d*):?(\w*)\]/x',
    'tag' => '/\[adsense:([^:]+):([^\]]+)\]/x',
  );

  foreach ($patterns as $mode => $pattern) {
    if (preg_match_all($pattern, $text, $matches, PREG_SET_ORDER)) {
      foreach ($matches as $match) {
        switch ($mode) {
          case 'block':
            $mods = array(
              'adsense_managed',
              'adsense_cse',
              'adsense_oldcode',
              'adsense_search',
            );
            foreach ($mods as $module) {
              $module_blocks = module_invoke($module, 'block_info');
              if ($module_blocks) {
                foreach ($module_blocks as $delta => $block) {
                  if ($block['info'] == $match[1]) {
                    // Found the block with the same name as the passed arg.
                    $block = module_invoke($module, 'block_view', $delta);
                    $ad = $block['content'];
                  }
                }
              }
            }
            break;

          case 'oldtag':
            // If not specified, default group and channel to 1.
            if (empty($match[2])) {
              $match[2] = 1;
            }
            if (empty($match[3])) {
              $match[3] = 1;
            }
            $args = array(
              'format' => $match[1],
              'group' => $match[2],
              'channel' => $match[3],
              'slot' => $match[4],
            );
            $ad = adsense_display($args);
            unset($args);
            break;

          case 'tag':
            $args = array(
              'format' => $match[1],
              'slot' => $match[2],
            );
            $ad = adsense_display($args);
            unset($args);
            break;
        }
        // Replace the first occurrence of the tag, in case we have the same
        // tag more than once.
        if (!empty($ad)) {
          $str = '/\\' . $match[0] . '/';
          $text = preg_replace($str, $ad, $text, 1);
        }
      }
    }
  }

  return $text;
}

/**
 * Provides the Google AdSense Publisher ID / slot ID to be used in the ad.
 *
 * If revenue sharing modules are installed, this function will call the
 * appropriate function in those modules.
 *
 * @param string $format
 *   Format of the ad being generated (optional).
 *
 * @return mixed
 *   If the format parameter is supplied, array with 'client' and 'slot'
 *   fields, otherwise just the Publisher ID string is returned
 */
function adsense_get_client_slot_id($format = NULL) {
  // Get the configured function.
  /** @var string $function */
  $function = variable_get('adsense_id_module', ADSENSE_ID_MODULE_DEFAULT);

  if ($function != ADSENSE_ID_MODULE_DEFAULT) {
    // Call the function.
    if (function_exists($function)) {
      $client_id = $function('client_id', $format);
      if ($client_id) {
        return $client_id;
      }
    }
  }
  return variable_get('adsense_basic_id', ADSENSE_BASIC_ID_DEFAULT);
}

/**
 * Generates the Google AdSense Ad.
 *
 * This function is capable of handling two types of arguments:
 * 1. an array of arguments (format, group, channel or slot)
 * 2. 0 to 4 arguments:
 *   - 1st arg: format  (default '160x600')
 *   - 2nd arg: group   (default 1)
 *   - 3rd arg: channel (default 1)
 *   - 4th arg: slot    (default '')
 *
 * A valid format must always be provided. If a slot is provided, the ad is
 * generated by the new format modules, if not then the 'old' format modules
 * are attempted.
 *
 * @return string
 *   Publisher ID
 *
 * @see adsense_ad_formats()
 * @see _adsense_page_match()
 * @see _adsense_check_if_enabled()
 * @see theme_adsense_placeholder()
 * @see _adsense_cse_get_searchbox()
 * @see _adsense_search_get_searchbox()
 * @see _adsense_managed_get_ad()
 * @see _adsense_oldcode_get_ad()
 */
function adsense_display() {
  drupal_add_css(drupal_get_path('module', 'adsense') . '/css/adsense.css');

  $numargs = func_num_args();
  if (($numargs == 1) && is_array(func_get_arg(0))) {
    $args = func_get_arg(0);
  }
  else {
    // Handle the 'old' method of calling this function.
    /* adsense_display($format = '160x600', $group = 1, $channel = 1, $slot = '', $referral = 0, $cpa = '') */

    $args['format'] = '160x600';
    $args['group'] = 1;
    $args['channel'] = 1;
    switch ($numargs) {
      // Obsolete, referral [5] and cpa [6].
      case 6:
      case 5:
      case 4:
        $args['slot'] = func_get_arg(3);
      case 3:
        $args['channel'] = func_get_arg(2);
      case 2:
        $args['group'] = func_get_arg(1);
      case 1:
        $args['format'] = func_get_arg(0);
    }
  }

  $ad = adsense_ad_formats($args['format'], !empty($args['slot']));

  if ($ad === NULL) {
    $ad = '<!--adsense: invalid format: ' . $args['format'] . '-->';
  }
  elseif (!_adsense_page_match()) {
    // Check first if disabled or if we are at adsense limit or if this page
    // doesn't allow adsense.
    $ad = '<!--adsense: page not in match list-->';
  }
  elseif (!_adsense_check_if_enabled()) {
    global $user;

    // Ads are disabled.
    if (variable_get('adsense_placeholder', ADSENSE_PLACEHOLDER_DEFAULT) || ($user->uid == 1 || user_access('show adsense placeholders'))) {
      $width = array_key_exists('width', $ad) ? $ad['width'] : 0;
      $height = array_key_exists('height', $ad) ? $ad['height'] : 0;
      // The text to display in the placeholder starts with the block title,
      // and then the default text as specified in the admin settings.
      // @codingStandardsIgnoreStart Drupal.Semantics.FunctionT.ConcatString
      $text = isset($args['title']) ? t('Block') . ': ' . $args['title'] . '<br />' : '';
      // @codingStandardsIgnoreEnd
      $text .= variable_get('adsense_placeholder_text', ADSENSE_PLACEHOLDER_TEXT_DEFAULT) . ' ' . $args['format'];
      if (user_access('show adsense placeholders')) {
        $name = user_is_anonymous() ? variable_get('anonymous', t('Anonymous')) : $user->name;
        $text = t('Ads disabled for %name', array('%name' => $name)) . '<br />' . $text;
      }

      $ad = "<!--adsense: placeholder-->\n" . theme('adsense_placeholder', array(
        'text' => $text,
        'width' => $width,
        'height' => $height,
      ));
    }
    else {
      $ad = '<!--adsense: ads disabled -->';
    }
  }
  else {
    // If site Slot ID for this ad was passed, pass the format as argument
    // in case Publisher ID modules are enabled that can return different
    // Slot IDs per ad format.
    $client_id_arg = !empty($args['slot']) ? $args['format'] : NULL;
    $client = adsense_get_client_slot_id($client_id_arg);

    if (is_array($client)) {
      // An array was received, use that Slot ID.
      $slot = $client['slot'];
      $client = $client['client'];
    }
    elseif (isset($args['slot'])) {
      // Use the original site Slot ID.
      $slot = $args['slot'];
    }

    // Ad should be displayed.
    switch ($args['format']) {
      case 'Search Box':
        if (!empty($slot) && module_exists('adsense_cse')) {
          $ad = _adsense_cse_get_searchbox($client, $slot);
        }
        elseif (module_exists('adsense_search')) {
          $ad = _adsense_search_get_searchbox($client, $args['channel']);
        }
        else {
          $ad = '<!--adsense: no AdSense for Search module found-->';
        }
        break;

      case 'Search Box v2':
        if (!empty($slot) && module_exists('adsense_cse')) {
          $ad = _adsense_csev2_get_searchbox($client, $slot);
        }
        else {
          $ad = '<!--adsense: no AdSense for Search module found-->';
        }
        break;

      default:
        if (!empty($slot) && module_exists('adsense_managed')) {
          $shape = empty($args['shape']) ? 'auto' : $args['shape'];
          $layout_key = empty($args['layout_key']) ? '' : $args['layout_key'];
          $ad = _adsense_managed_get_ad($args['format'], $client, $slot, $shape, $layout_key);
          $module = 'adsense_managed';
        }
        elseif (module_exists('adsense_oldcode')) {
          $ad = _adsense_oldcode_get_ad($args['format'], $client, $args['group'], $args['channel']);
          $module = 'adsense_oldcode';
        }
        else {
          $ad = '<!--adsense: no AdSense for Content module found-->';
          $module = '';
        }

        // Display ad-block disabling request.
        if (variable_get('adsense_unblock_ads', ADSENSE_UNBLOCK_ADS_DEFAULT)) {
          adsense_request_unblock();
        }
        // If test mode, ad is already themed.
        if (!variable_get('adsense_test_mode', ADSENSE_TEST_MODE_DEFAULT)) {
          $ad = theme('adsense_ad', array(
            'ad' => $ad,
            'module' => $module,
            'format' => $args['format'],
          ));
        }

        break;
    }
    // Remove empty lines.
    $ad = str_replace("\n\n", "\n", $ad);
  }

  return $ad;
}

/**
 * Displays a request to disable adblockers, when their use is detected.
 */
function adsense_request_unblock() {
  static $done = FALSE;

  if (!$done) {
    drupal_add_js(file_get_contents(drupal_get_path('module', 'adsense') . '/js/unblock.js'), 'inline');
    $done = TRUE;
  }
}

/**
 * Helper function to determine if an ad format is responsive.
 *
 * @param string $format
 *   Ad format.
 *
 * @return bool
 *   TRUE if the ad is responsive.
 */
function _adsense_is_responsive($format) {
  return in_array($format, array('responsive', 'link', 'autorelaxed'));
}

/**
 * Helper function to determine if an ad format is fluid.
 *
 * @param string $format
 *   Ad format.
 *
 * @return bool
 *   TRUE if the ad is fluid.
 */
function _adsense_is_fluid($format) {
  return in_array($format, array('in-article', 'in-feed'));
}

/**
 * Helper function to get ad width and height from the format.
 *
 * @param string $format
 *   Ad format.
 *
 * @return array|null
 *   Width and height of the ad, or NULL
 */
function _adsense_dimensions($format) {
  if (preg_match('!^(\d+)x(\d+)(.*)$!', $format, $matches)) {
    return array('width' => $matches[1], 'height' => $matches[2]);
  }
  return NULL;
}

/**
 * Default AdSense ad unit theming.
 *
 * Simply add a div with the adsense and $module classes.
 *
 * @param array $vars
 *   Array elements:
 *   'ad': string with the generated ad unit.
 *   'module': module used to generate the ad.
 *
 * @return string
 *   Modified ad unit
 *
 * @ingroup themeable
 */
function theme_adsense_ad(array $vars) {
  $style = '';
  $adclasses = 'adsense';
  if (isset($vars['format'])) {
    if (_adsense_is_responsive($vars['format']) || _adsense_is_fluid($vars['format'])) {
      $adclasses .= ' responsive';
    }
    else {
      $ad_fmt = _adsense_dimensions($vars['format']);
      $style = "style='width:{$ad_fmt['width']}px;height:{$ad_fmt['height']}px;'";
    }
  }

  return "<div class='{$adclasses}' {$style}>\n{$vars['ad']}\n</div>";
}

/**
 * Helper function to verify if ads are currently enabled.
 *
 * @return bool
 *   TRUE if ad display is enabled, FALSE otherwise
 */
function _adsense_check_if_enabled() {
  if (!variable_get('adsense_basic_id', ADSENSE_BASIC_ID_DEFAULT)) {
    // Google AdSense Publisher ID is not configured.
    return FALSE;
  }
  if (variable_get('adsense_disable', ADSENSE_DISABLE_DEFAULT)) {
    return FALSE;
  }
  if (variable_get('adsense_test_mode', ADSENSE_TEST_MODE_DEFAULT)) {
    return TRUE;
  }
  if (user_access('hide adsense')) {
    return FALSE;
  }
  if (user_access('show adsense placeholders')) {
    // AdSense is enabled but this user should only see placeholders instead.
    return FALSE;
  }

  return TRUE;
}

/**
 * Determine if AdSense has permission to be used on the current page.
 *
 * @return bool
 *   TRUE if can render, FALSE if not allowed.
 */
function _adsense_page_match() {
  $pages = variable_get('adsense_access_pages', ADSENSE_ACCESS_PAGES_DEFAULT);
  $visibility = variable_get('adsense_visibility', ADSENSE_VISIBILITY_DEFAULT);

  if ($pages) {
    if ($visibility == 2) {
      return php_eval($pages);
    }
    $path = drupal_get_path_alias($_GET['q']);
    $page_match = drupal_match_path($path, $pages);
    if ($path != $_GET['q']) {
      $page_match = $page_match || drupal_match_path($_GET['q'], $pages);
    }

    return !($visibility xor $page_match);
  }
  else {
    return !$visibility;
  }
}

/**
 * Generate a box to display instead of the ad when it is disabled.
 *
 * @param array $vars
 *   Theme variables.
 *
 * @return string
 *   string with the HTML text to create the box.
 *
 * @ingroup themeable
 */
function theme_adsense_placeholder(array $vars) {
  // Use inline CSS, as some ad-blocking software blocks CSS files.
  $style = ((!empty($vars['width'])) && (!empty($vars['height']))) ? 'width:' . ($vars['width'] - 2) . 'px;height:' . ($vars['height'] - 2) . 'px;' : '';

  return "<div class='adsense adsense-placeholder' style='{$style}'>{$vars['text']}</div>";
}

/**
 * Displays a message for unconfigured blocks.
 *
 * @param array $url
 *   URL of the block admin page.
 *
 * @return string
 *   string with the configure block message.
 */
function _adsense_configure_block_message($url) {
  return user_access('administer adsense') ? t('AdSense unconfigured block. <a href=!url>Click to configure.</a>', array('!url' => $url)) : '';
}
