You are here

function invite_stats_display_user_rank in Invite 7.2

Same name and namespace in other branches
  1. 5.2 invite_stats.module \invite_stats_display_user_rank()
  2. 5 invite_stats.module \invite_stats_display_user_rank()
  3. 6.2 invite_stats.module \invite_stats_display_user_rank()

Render the displayed user's rank block.

1 call to invite_stats_display_user_rank()
invite_stats_block_view in modules/invite_stats/invite_stats.module
Implements hook_block_view().

File

modules/invite_stats/invite_stats.module, line 151
Displays some statistics about sent invitations.

Code

function invite_stats_display_user_rank($uid) {
  $inviters = array();
  $max = variable_get('invite_num_ranks', 5);

  // Get user's invite count.
  $user_invite_stats_count = db_query("SELECT COUNT(*) FROM {invite} WHERE uid = :uid AND joined <> 0", array(
    ':uid' => $uid,
  ))
    ->fetchField();

  // Calculate user's rank.
  $result = db_query("SELECT DISTINCT COUNT(uid) FROM {invite} WHERE joined <> 0 GROUP BY uid HAVING COUNT(uid) > :count", array(
    ':count' => $user_invite_stats_count,
  ))
    ->fetchAll();
  $rank = 1 + count($result);

  // Fetch users with more invites.
  $i = 0;
  $prev_count = 0;
  $result = db_query_range("SELECT uid, COUNT(uid) AS count FROM {invite} WHERE joined <> 0 GROUP BY uid HAVING COUNT(uid) > :count ORDER BY count ASC", 0, $max - 1, array(
    ':count' => $user_invite_stats_count,
  ))
    ->fetchAll();
  foreach ($result as $row) {
    if ($row->count != $prev_count) {
      $prev_count = $row->count;
      $rank--;

      // Decrement initial rank
    }
    array_unshift($inviters, $row);
  }

  // Add current user, now we have invite_num_ranks users at max.
  $inviters[] = (object) array(
    'uid' => $uid,
    'count' => $user_invite_stats_count,
  );
  $user_idx = count($inviters);

  // Add users with equal or less invites.
  $i = 0;
  $prev_count = $user_invite_stats_count;
  $result = db_query_range("SELECT uid, COUNT(uid) AS count FROM {invite} WHERE joined <> 0 GROUP BY uid HAVING COUNT(uid) <= :count AND uid <> :uid ORDER BY count DESC", 0, $max - 1, array(
    ':count' => $user_invite_stats_count,
    ':uid' => $uid,
  ));
  $inviters = $result
    ->fetchAll();

  // Slice result.
  $start = max($user_idx - 1 - floor($max / 2), 0);
  if (count($inviters) - $user_idx < floor($max / 2)) {
    $start -= max(count($inviters) - $user_idx, floor($max / 2));
    $start = max($start, 0);
  }
  $inviters = array_slice($inviters, $start, $max);
  return theme('invite_stats_ranking', array(
    'inviters' => $inviters,
    'rank' => $rank,
  ));
}