<?php

/**
 * @file
 * This is a helper module to add blocks and menu items and function
 * to help deal with accounts that might have duplicate email addresses.
 * It is based on the examples module block_example: an example outlining
 * how a module can define blocks to be displayed on each page.
 */

/**
 * Implements hook_views_api().
 */
function duplicatemail_views_api() {
  return array(
    'api' => 3,
  );
}

/**
 * Implements hook_block_info().
 *
 * This hook both declares what blocks are provided by the module, and
 * generates the contents of the blocks themselves.
 */
function duplicatemail_block_info() {
  return array(
    'duplicatemail-list' => array(
      'info' => t('Duplicate Mail: system wide, lists accounts that have the same email as another account'),
      'cache' => DRUPAL_CACHE_GLOBAL,
    )
  );
}

/**
 * Implements hook_block_view().
 */
function duplicatemail_block_view($delta) {
  switch ($delta) {
    case 'duplicatemail-list':
      return array(
        'subject' => t('Duplicate emails'),
        'content' => duplicatemail_list(),
      );
      break;
  }
}

/**
 * A block content function.
 */
function duplicatemail_list() {
  $mails = db_query('SELECT mail FROM {users} GROUP BY mail HAVING count(mail) > 1')->fetchCol();

  // Bail out early if there are no duplicates.
  if (!$mails) {
    return t('All accounts have unique email addresses.');
  }

  // Grab all the user data for accounts with addresses identified as
  // duplicates. This is a little convoluted, but it lets us grab all the user
  // data in one shot.
  $uids = db_select('users', 'u')
    ->fields('u', array('uid'))
    ->condition('mail', $mails, 'IN')
    ->orderBy('mail')
    ->execute()
    ->fetchCol();
  $duplicate_users = user_load_multiple($uids);
  $duplicate_mails = array();
  foreach ($duplicate_users as $duplicate_user) {
    $duplicate_mails[$duplicate_user->mail][] = $duplicate_user;
  }

  // Turn the data we've got into markup.
  $output = t('Accounts with duplicate email address:') . '<br />';
  foreach ($duplicate_mails as $mail => $users) {
    $output .= "$mail<br />";
    foreach ($users as $duplicate_user) {
      $output .= l($duplicate_user->name, "user/{$duplicate_user->uid}");
      $output .= '<br />';
    }
  }

  return $output;
}