You are here

referral.module in User Referral 7

Same filename and directory in other branches
  1. 5 referral.module
  2. 6 referral.module

The referral module.

File

referral.module
View source
<?php

/**
 * @file The referral module.
 */

/**
 * Define constants
 */
define('REFERRAL_PAGE_COUNT', 50);
define('REFERRAL_BLOCK_COUNT', 5);
define('REFERRAL_DATE_FORMAT', 'Y-m-d H:i:s');
define('REFERRAL_HEX_START', 7);
define('REFERRAL_HEX_LENGTH', 4);
define('REFERRAL_COOKIE_DEFAULT', 'referral_data');

/**
 * The following constants are not longer used in this module.
 * I define them here for backward-compatibility only
 */
define('REFERRAL_PERM_USE', 'use referral');
define('REFERRAL_PERM_ADMIN', 'administer referral');
define('REFERRAL_UID', 'referral_uid');
define('REFERRAL_TIMESTAMP', 'referral_timestamp');
define('REFERRAL_IP', 'referral_ip_address');
define('REFERRAL_REFERER', 'referral_referer');
define('REFERRAL_GOTO_PATH', 'referral_goto_path');

/**
 * Implements hook_help().
 */
function referral_help($path, $arg) {
  switch ($path) {
    case 'admin/settings/referral':
      $output = t('Track users referring others to your site');
      return $output;
  }
}

/**
 * Implements hook_permission().
 */
function referral_permission() {
  return array(
    'use referral' => array(
      'title' => t('Use referrals'),
      'description' => t('Refer users with personal referral link.'),
    ),
    'administer referral' => array(
      'title' => t('Administer referrals'),
      'description' => t('View, flag, and delete user referrals and view reports.'),
    ),
  );
}

/**
 * Implements hook_menu().
 */
function referral_menu() {
  $items = array();
  $items['admin/config/people/referral'] = array(
    'title' => 'User Referral',
    'description' => 'Settings for the User Referral module.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'referral_settings',
    ),
    'access arguments' => array(
      'administer site configuration',
    ),
    'type' => MENU_NORMAL_ITEM,
  );
  $items['referral'] = array(
    'page callback' => 'referral_get',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  // TODO: Views for this page is at 'my-referrals'. Redirect to the views page.
  $items['referral/view'] = array(
    'title' => 'Your Referrals',
    'page callback' => 'referral_view',
    'access arguments' => array(
      'use referral',
    ),
    'type' => MENU_SUGGESTED_ITEM,
  );

  // TODO: Replace with views
  $items['admin/reports/referral'] = array(
    'title' => 'Referrals summary',
    'description' => 'Admin reports for the User Referral module.',
    'page callback' => 'referral_admin_view_summary',
    'access arguments' => array(
      'administer referral',
    ),
    'type' => MENU_NORMAL_ITEM,
  );

  // TODO: Replace with views
  $items['admin/reports/referral/summary'] = array(
    'title' => 'Referrals summary',
    'page callback' => 'referral_admin_view_summary',
    'access arguments' => array(
      'administer referral',
    ),
    'weight' => 1,
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );

  // TODO: Replace with views
  $items['admin/reports/referral/details'] = array(
    'page callback' => 'referral_admin_view_details',
    'access arguments' => array(
      'administer referral',
    ),
    'weight' => 2,
    'type' => MENU_CALLBACK,
  );

  // TODO: Replace with views
  $items['admin/reports/referral/unflagged'] = array(
    'title' => 'Unflagged referrals',
    'page callback' => 'referral_admin_view_unflagged',
    'access arguments' => array(
      'administer referral',
    ),
    'weight' => 3,
    'type' => MENU_LOCAL_TASK,
  );

  // TODO: Replace with views
  $items['admin/reports/referral/roles'] = array(
    'title' => 'Referral roles',
    'page callback' => 'referral_admin_view_roles',
    'access arguments' => array(
      'administer referral',
    ),
    'type' => MENU_CALLBACK,
  );
  $items['admin/referral/flag'] = array(
    'page callback' => 'referral_admin_flag',
    'access arguments' => array(
      'administer referral',
    ),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Forum builder for admin/config/people/referral
 */
function referral_settings() {
  $options = array(
    0 => t('User page'),
    1 => t('Referrals page'),
  );
  $form['referral_show_on_user_profile'] = array(
    '#type' => 'checkbox',
    '#title' => t('Show referral link on user profile'),
    '#default_value' => variable_get('referral_show_on_user_profile', TRUE),
  );
  $form['referral_goto_path'] = array(
    '#type' => 'textfield',
    '#title' => t('Referral goto path'),
    '#default_value' => variable_get('referral_goto_path', 'user/register'),
    '#description' => t('The path to redirect to after visiting the referral link.'),
    '#required' => TRUE,
  );
  $form['referral_cookie_lifetime'] = array(
    '#type' => 'textfield',
    '#title' => t('Cookie lifetime in days.'),
    '#default_value' => variable_get('referral_cookie_lifetime', '1'),
    '#description' => t('How many days should the referral tracking cookie last.'),
    '#required' => TRUE,
  );
  $form['referral_advanced_settings'] = array(
    '#type' => 'fieldset',
    '#title' => t('Advanced settings'),
    '#collapsed' => TRUE,
    '#collapsible' => TRUE,
    '#description' => t('These settings are for advanced users only. Change only if you know what you are doing.'),
  );
  $form['referral_advanced_settings']['referral_cookie_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Cookie name'),
    '#default_value' => variable_get('referral_cookie_name', REFERRAL_COOKIE_DEFAULT),
    '#description' => t('Advanced: Machine name for the referral tracking cookie. WARNING: Changing it will void all referral cookies that are currently present in user browsers.'),
    '#required' => TRUE,
  );
  return system_settings_form($form);
}

/**
 * Page callback for 'referral'
 */
function referral_get() {
  global $user;
  if (!$user->uid) {

    // User has not logged in, or registered yet
    $uid = _referral_ref2uid(arg(1));
    if ($uid && is_numeric($uid)) {

      // Set the referral cookie
      referral_set_cookie($uid);
    }
    drupal_goto(variable_get('referral_goto_path', 'user/register'));
  }
  drupal_goto();
}

/**
 * Get referring user's uid for a given user
 *
 * @param $uid The user ID of the user who we want fetch its referrer.
 */
function referral_get_user($uid) {
  $referral_uid = FALSE;
  $result = db_query('SELECT referral_uid FROM {referral} WHERE uid = :uid', array(
    ':uid' => $uid,
  ));
  foreach ($result as $data) {
    $referral_uid = $data->referral_uid;
  }
  return $referral_uid;
}

/**
 *
 */
function _referral_user_save($uid) {
  $cookie_name = variable_get('referral_cookie_name', REFERRAL_COOKIE_DEFAULT);
  if (!isset($_COOKIE[$cookie_name])) {
    return;
  }

  // Retrieve referral info from the cookie
  $cookie = unserialize($_COOKIE[$cookie_name]);
  if (empty($cookie)) {

    // Nothing to do ...
    return;
  }
  try {
    $query = db_insert('referral')
      ->fields(array(
      'uid' => $uid,
      'referral_uid' => $cookie['uid'],
      'created' => $cookie['timestamp'],
      'host' => $cookie['ip'],
      'http_referer' => $cookie['referer'],
    ))
      ->execute();
  } catch (Exception $e) {
    watchdog_exception('referral', $e);
    return;
  }

  // Invoke other modules hooks ...
  module_invoke_all('referral', $uid, $cookie['uid']);
  if (module_exists('rules')) {
    rules_invoke_event('referral_recorded', user_load($cookie['uid']), user_load($uid));
  }
}

/**
 *
 */
function _referral_user_delete($uid) {
  $or = db_or()
    ->condition('uid', $uid)
    ->condition('referral_uid', $uid);
  $query = db_delete('referral')
    ->condition($or)
    ->execute();
}

/**
 * Implements hook_user_insert().
 */
function referral_user_insert(&$edit, $account, $category) {
  _referral_user_save($account->uid);
}

/**
 * Implements hook_user_delete().
 */
function referral_user_delete($account) {
  _referral_user_delete($account->uid);
}

/**
 * Implements hook_user_load().
 */
function referral_user_load($users) {
  foreach ($users as $user) {
    $user->referral_link = 'referral/' . _referral_uid2ref($user->uid);
  }
}

/**
 * Implements hook_user_view().
 */
function referral_user_view($account, $view_mode, $langcod) {
  global $user;
  $referrals = array();
  $link = "referral/" . _referral_uid2ref($account->uid);
  if (variable_get('referral_show_on_user_profile', TRUE)) {
    if (user_access('use referral')) {
      if ($user->uid == $account->uid) {

        // User is viewing own page, show referrals
        $referrals[] = array(
          '#title' => t('Your referral link'),
          '#markup' => url($link, array(
            'query' => NULL,
            'fragment' => NULL,
            'absolute' => TRUE,
          )),
          '#type' => 'user_profile_item',
        );
        $referrals[] = array(
          '#title' => t('Referrals'),
          '#markup' => l(t('View users you have referred'), 'referral/view'),
          '#type' => 'user_profile_item',
        );
      }
    }
  }
  if (!$user->uid) {
    $referrals[] = array(
      '#title' => t('Referral link'),
      '#markup' => l(t('Register to this site using my referral link'), $link),
      '#type' => 'user_profile_item',
    );
    referral_set_cookie(arg(1));
  }
  if ($referrals) {
    $referrals['#type'] = 'user_profile_category';
    $referrals['#title'] = t('Referrals');
    $referrals['#weight'] = 10;
    $account->content['Referrals'] = $referrals;
  }
}

/**
 *
 */
function referral_set_cookie($uid) {
  $cookie = array(
    'uid' => $uid,
    'timestamp' => time(),
    'ip' => ip_address(),
    'referer' => $_SERVER['HTTP_REFERER'],
  );
  $cookie_lifetime = variable_get('referral_cookie_lifetime', 1) * 86400;
  $cookie_name = variable_get('referral_cookie_name', REFERRAL_COOKIE_DEFAULT);
  setcookie($cookie_name, serialize($cookie), time() + $cookie_lifetime, '/');
}

/**
 *
 */
function referral_block($op = 'list', $delta = 0) {
  $title[0] = t('Top referring users');
  switch ($op) {
    case 'list':
      $block[0]['info'] = $title[0];
      return $block;
      break;
    case 'view':
      switch ($delta) {
        case 0:
          $block['subject'] = $title[0];
          $block['content'] = referral_block_content();
          break;
      }
      return $block;
      break;
  }
}

/**
 *
 */
function referral_block_content() {
  $header = array();

  /*$query = db_select('referral', 'r');
    $query->innerJoin('users', 'u', 'u.uid = r.referral_uid');
    $query->innerJoin('users', 'u2', 'u2.uid = r.uid');
    $result = $query
      ->fields('r', array('referral_uid'))
  	->fields('u', array('name'))
  	->condition('u2.status', 1)
  	->groupBy('r.referral_uid')
  	->range(0, REFERRAL_BLOCK_COUNT)
  	->execute();
    */
  $sql = 'SELECT r.referral_uid, u.name, COUNT(*) AS num_referrals
    FROM {referral} r INNER JOIN {users} u ON u.uid = r.referral_uid
    INNER JOIN {users} u2 ON u2.uid = r.uid
    WHERE u2.status = 1
    GROUP BY r.referral_uid
    ORDER BY num_referrals DESC
    LIMIT :count';
  $result = db_query($sql, array(
    'count' => REFERRAL_BLOCK_COUNT,
  ));
  $rows = array();
  foreach ($result as $data) {
    $rows[] = array(
      array(
        'data' => l($data->name, "user/{$data->referral_uid}"),
      ),
      array(
        'data' => $data->num_referrals,
      ),
    );
  }
  if (!$rows) {
    $rows[] = array(
      array(
        'data' => t('No data.'),
      ),
    );
  }
  return theme('table', array(
    'header' => $header,
    'rows' => $rows,
  ));
}

/**
 *
 */
function referral_admin_flag() {
  $uid = (int) arg(3);
  $user = user_load($uid);
  db_query('UPDATE {referral}
    SET flag = 1, flag_timestamp = :time
    WHERE uid = :ruid', array(
    'time' => time(),
    'ruid' => $uid,
  ));

  //$num = db_affected_rows();
  drupal_set_message(t('Flagged referral.'));
  drupal_goto('admin/reports/referral/unflagged');
}

/**
 *
 */
function referral_view() {

  // TODO: Views for this page is at 'my-referrals'. Redirect to the views page.
  // TODO: Remove code from this function
  global $user;
  $output = '<div class="referral_link">';
  $output .= t('Your referral link: ');
  $output .= url('referral/' . _referral_uid2ref($user->uid), array(
    'query' => NULL,
    'fragment' => NULL,
    'absolute' => TRUE,
  ));
  $output .= '</div>';
  $header = array(
    array(
      'data' => t('User'),
      'field' => 'u.name',
    ),
    array(
      'data' => t('Roles'),
    ),
    array(
      'data' => t('Flag'),
      'field' => 'r.flag',
    ),
    array(
      'data' => t('Time'),
      'field' => 'r.created',
      'sort' => 'desc',
    ),
  );
  $query = db_select('referral', 'r');
  $query
    ->innerJoin('users', 'u', 'r.uid = u.uid');
  $result = $query
    ->fields('u', array(
    'uid',
    'name',
  ))
    ->fields('r', array(
    'created',
    'flag',
  ))
    ->condition('referral_uid', $user->uid)
    ->condition('u.status', 1)
    ->orderBy('r.created', 'DESC')
    ->extend('PagerDefault')
    ->range(0, REFERRAL_PAGE_COUNT)
    ->extend('TableSort')
    ->orderByHeader($header)
    ->execute();
  $rows = array();
  foreach ($result as $data) {
    $rows[] = array(
      array(
        'data' => l($data->name, "user/{$data->uid}"),
      ),
      array(
        'data' => implode(',', _referral_get_user_roles($data->uid)),
      ),
      array(
        'data' => $data->flag ? 'Yes' : 'No',
      ),
      array(
        'data' => format_date($data->created, 'custom', REFERRAL_DATE_FORMAT),
      ),
    );
  }
  if (!$rows) {
    $rows[] = array(
      array(
        'data' => t('No data.'),
        'colspan' => '4',
      ),
    );
  }
  $pager = theme('pager', array(
    'tags' => array(),
  ));
  if (!empty($pager)) {
    $rows[] = array(
      array(
        'data' => $pager,
        'colspan' => '4',
      ),
    );
  }
  $output .= theme('table', array(
    'header' => $header,
    'rows' => $rows,
  ));
  return $output;
}

/**
 *
 */
function referral_admin_view_details() {
  $uid = (int) arg(4);
  $ref_user = user_load($uid);
  $header = array(
    array(
      'data' => t('User'),
      'field' => 'u.name',
    ),
    array(
      'data' => t('Flag'),
      'field' => 'r.flag',
    ),
    array(
      'data' => t('Roles'),
    ),
    array(
      'data' => t('Time'),
      'field' => 'r.created',
      'sort' => 'desc',
    ),
    array(
      'data' => t('IP Address'),
      'field' => 'r.host',
    ),
    array(
      'data' => t('Referrer'),
      'field' => 'r.http_referer',
    ),
  );
  $query = db_select('referral', 'r');
  $query
    ->innerJoin('users', 'u', 'u.uid = r.uid');
  $result = $query
    ->fields('u', array(
    'uid',
    'name',
  ))
    ->fields('r', array(
    'flag',
    'created',
    'host',
    'http_referer',
  ))
    ->condition('r.referral_uid', $uid)
    ->condition('u.status', 1)
    ->extend('PagerDefault')
    ->range(0, REFERRAL_PAGE_COUNT)
    ->extend('TableSort')
    ->orderByHeader($header)
    ->execute();
  $rows = array();
  foreach ($result as $data) {
    $referer = check_plain(_referral_column_width($data->http_referer));
    $rows[] = array(
      array(
        'data' => l($data->name, "user/{$data->uid}"),
      ),
      array(
        'data' => $data->flag ? 'Yes' : 'No',
      ),
      array(
        'data' => implode(',', _referral_get_user_roles($data->uid)),
      ),
      array(
        'data' => format_date($data->created, 'custom', REFERRAL_DATE_FORMAT),
      ),
      array(
        'data' => l($data->host, "http://whois.domaintools.com/{$data->host}"),
      ),
      array(
        'data' => l($referer, $data->http_referer),
      ),
    );
  }
  if (!$rows) {
    $rows[] = array(
      array(
        'data' => t('No data.'),
        'colspan' => '6',
      ),
    );
  }
  $pager = theme('pager', array(
    'tags' => array(),
  ));
  if (!empty($pager)) {
    $rows[] = array(
      array(
        'data' => $pager,
        'colspan' => '6',
      ),
    );
  }
  return theme('table', array(
    'header' => $header,
    'rows' => $rows,
  ));
}

/**
 *
 */
function referral_admin_view_unflagged() {
  $header = array(
    array(
      'data' => t('Referring User'),
      'field' => 'u.name',
    ),
    array(
      'data' => t('# Unflagged'),
      'field' => 'cnt',
    ),
    array(
      'data' => t('Last'),
      'field' => 'last',
      'sort' => 'desc',
    ),
    array(
      'data' => t('Operations'),
    ),
  );
  $select_condition = db_select('users', 'u')
    ->fields('u', array(
    'uid',
  ))
    ->condition('status', 1);
  $query = db_select('referral', 'r');
  $query
    ->addExpression('COUNT(*)', 'cnt');
  $query
    ->addExpression('MAX(r.created)', 'last');
  $query
    ->innerJoin('users', 'u', 'u.uid = r.referral_uid');
  $result = $query
    ->fields('u', array(
    'name',
  ))
    ->fields('r', array(
    'referral_uid',
    'uid',
  ))
    ->condition('r.flag', 0)
    ->condition('r.uid', $select_condition, 'IN')
    ->groupBy('r.referral_uid')
    ->extend('PagerDefault')
    ->range(0, REFERRAL_PAGE_COUNT)
    ->extend('TableSort')
    ->orderByHeader($header)
    ->execute();

  /*$sql = 'SELECT r.referral_uid, u.name, COUNT(*) AS cnt, MAX(r.created) AS last
    FROM {referral} r INNER JOIN {users} u ON(r.referral_uid = u.uid)
    WHERE r.flag = 0
    AND r.uid IN
    ( SELECT u.uid FROM {users} u WHERE status = 1 )
    GROUP BY r.referral_uid' . tablesort_sql($header);*/
  $rows = array();
  foreach ($result as $data) {
    $rows[] = array(
      array(
        'data' => l($data->name, "user/{$data->referral_uid}"),
      ),
      array(
        'data' => $data->cnt,
      ),
      array(
        'data' => format_date($data->last, 'custom', REFERRAL_DATE_FORMAT),
      ),
      array(
        'data' => l(t('details'), "admin/reports/referral/roles/{$data->referral_uid}") . ' | ' . l(t('flag'), "admin/referral/flag/{$data->uid}"),
      ),
    );
  }
  if (!$rows) {
    $rows[] = array(
      array(
        'data' => t('No data.'),
        'colspan' => '4',
      ),
    );
  }
  $pager = theme('pager', array(
    'tags' => array(),
  ));
  if (!empty($pager)) {
    $rows[] = array(
      array(
        'data' => $pager,
        'colspan' => '4',
      ),
    );
  }
  return theme('table', array(
    'header' => $header,
    'rows' => $rows,
  ));
}

/**
 *
 */
function referral_admin_view_roles() {
  $uid = (int) arg(4);
  $header = array(
    array(
      'data' => t('User'),
      'field' => 'u.name',
    ),
    array(
      'data' => t('Roles'),
    ),
    array(
      'data' => t('Time'),
      'field' => 'r.created',
      'sort' => 'desc',
    ),
    array(
      'data' => t('IP Address'),
      'field' => 'r.host',
    ),
    array(
      'data' => t('Referrer'),
      'field' => 'r.http_referer',
    ),
  );
  $select_condition = db_select('users', 'u')
    ->fields('u', array(
    'uid',
  ))
    ->condition('status', 1);
  $query = db_select('referral', 'r');
  $query
    ->innerJoin('users', 'u', 'u.uid = r.uid');
  $result = $query
    ->fields('u', array(
    'name',
    'uid',
  ))
    ->fields('r', array(
    'created',
    'host',
    'http_referer',
  ))
    ->condition('r.referral_uid', $uid)
    ->condition('r.flag', 0)
    ->condition('r.uid', $select_condition, 'IN')
    ->extend('PagerDefault')
    ->range(0, REFERRAL_PAGE_COUNT)
    ->extend('TableSort')
    ->orderByHeader($header)
    ->execute();

  /*$sql = 'SELECT u.uid, u.name, r.created, r.host, r.http_referer
    FROM {referral} r INNER JOIN {users} u USING(uid)
    WHERE r.referral_uid = %d
    AND r.flag = 0
    AND r.uid IN
    ( SELECT u.uid FROM {users} u WHERE status = 1 )' . tablesort_sql($header);*/
  $rows = array();
  foreach ($result as $data) {
    $referer = check_plain(_referral_column_width($data->http_referer));
    $rows[] = array(
      array(
        'data' => l($data->name, "user/{$data->uid}"),
      ),
      array(
        'data' => implode(',', _referral_get_user_roles($data->uid)),
      ),
      array(
        'data' => format_date($data->created, 'custom', REFERRAL_DATE_FORMAT),
      ),
      array(
        'data' => l($data->host, "http://whois.domaintools.com/{$data->host}"),
      ),
      array(
        'data' => l($referer, $data->http_referer),
      ),
    );
  }
  if (!$rows) {
    $rows[] = array(
      array(
        'data' => t('No data.'),
        'colspan' => '5',
      ),
    );
  }
  $pager = theme('pager', array(
    'tags' => array(),
  ));
  if (!empty($pager)) {
    $rows[] = array(
      array(
        'data' => $pager,
        'colspan' => '5',
      ),
    );
  }
  $user = user_load($uid);
  $output = t('Unflagged referral users with roles for: @user', array(
    '@user' => l($user->name, "user/{$user->uid}"),
  ));
  $output .= theme('table', array(
    'header' => $header,
    'rows' => $rows,
  ));
  return $output;
}

/**
 *
 */
function referral_admin_view_summary() {
  $header = array(
    array(
      'data' => t('Referring User'),
      'field' => 'r.referral_uid',
    ),
    array(
      'data' => t('# Referred'),
      'field' => 'num_referrals',
      'sort' => 'desc',
    ),
    array(
      'data' => t('Last Referral'),
      'field' => 'r.created',
    ),
    array(
      'data' => t('Details'),
    ),
  );
  $query = db_select('referral', 'r');
  $query
    ->addExpression('COUNT(*)', 'num_referrals');
  $query
    ->addExpression('MAX(r.created)', 'last');
  $query
    ->innerJoin('users', 'u', 'u.uid = r.referral_uid');
  $query
    ->innerJoin('users', 'u2', 'u2.uid = r.uid');
  $result = $query
    ->fields('u', array(
    'name',
  ))
    ->fields('r', array(
    'referral_uid',
  ))
    ->condition('u2.status', 1)
    ->groupBy('r.referral_uid')
    ->extend('PagerDefault')
    ->range(0, REFERRAL_PAGE_COUNT)
    ->extend('TableSort')
    ->orderByHeader($header)
    ->execute();
  $rows = array();

  /*$sql = 'SELECT r.referral_uid, u.name, COUNT(*) AS num_referrals, MAX(r.created) AS last
    FROM {referral} r INNER JOIN {users} u ON u.uid = r.referral_uid
    INNER JOIN {users} u2 ON u2.uid = r.uid
    WHERE u2.status = 1
    GROUP BY r.referral_uid' . tablesort_sql($header);*/
  foreach ($result as $data) {
    $rows[] = array(
      array(
        'data' => l($data->name, "user/{$data->referral_uid}"),
      ),
      array(
        'data' => $data->num_referrals,
      ),
      array(
        'data' => format_date($data->last, 'custom', REFERRAL_DATE_FORMAT),
      ),
      array(
        'data' => l(t('details'), "admin/reports/referral/details/{$data->referral_uid}"),
      ),
    );
  }
  if (!$rows) {
    $rows[] = array(
      array(
        'data' => t('No data.'),
        'colspan' => '4',
      ),
    );
  }
  $pager = theme('pager', array(
    'tags' => array(),
  ));
  if (!empty($pager)) {
    $rows[] = array(
      array(
        'data' => $pager,
        'colspan' => '4',
      ),
    );
  }
  return theme('table', array(
    'header' => $header,
    'rows' => $rows,
  ));
}

/**
 *
 */
function _referral_column_width($column, $width = 30) {
  return strlen($column) > $width ? substr($column, 0, $width) . '...' : $column;
}

/**
 * Decode and convert back a referral reference code to UID
 *
 * @param $ref The reference code
 */
function _referral_ref2uid($ref) {
  if ($ref) {
    if (is_numeric('0x' . $ref)) {
      $uid = hexdec($ref) - _referral_hex_seed();
      return $uid;
    }
  }
  return FALSE;
}

/**
 * Convert a UID to a referral reference code
 *
 * @param $uid The numeric user id
 */
function _referral_uid2ref($uid) {
  if ($uid) {
    if (is_numeric($uid)) {
      $ref = dechex(_referral_hex_seed() + $uid);
      return $ref;
    }
  }
  return FALSE;
}

/**
 * Helper function for _referral_ref2uid() and _referral_uid2ref()
 */
function _referral_hex_seed() {
  global $base_url;
  $seed = hexdec(_referral_asc2hex(substr($base_url, REFERRAL_HEX_START, REFERRAL_HEX_LENGTH)));
  return $seed;
}

/**
 * Helper function for _referral_ref2uid() and _referral_uid2ref()
 */
function _referral_asc2hex($asc_str) {
  $hex_str = '';
  for ($i = 0; $i < strlen($asc_str); $i++) {
    $hex_str .= sprintf("%02x", ord(substr($asc_str, $i, 1)));
  }
  return $hex_str;
}

/**
 *
 */
function _referral_get_user_roles($uid) {
  $data = array();
  $result = db_query('SELECT r.name FROM {role} r INNER JOIN {users_roles} ur USING (rid)
    WHERE ur.uid = :uid', array(
    ':uid' => $uid,
  ));
  foreach ($result as $row) {
    $data[] = $row->name;
  }
  return $data;
}

/**
 * Implements hook_tokens().
 */
function referral_tokens($type, $tokens, array $data = array(), array $options = array()) {
  if ($type == 'user' && !empty($data['user'])) {
    $object = $data['user'];
    $replacements = array();
    foreach ($tokens as $name => $original) {
      if ($name == 'referral-link') {
        $replacements[$original] = url('referral/' . _referral_uid2ref($object->uid), array(
          'absolute' => TRUE,
        ));
      }
    }
    return $replacements;
  }
}

/**
 * Implements hook_token_info().
 */
function referral_token_info() {
  $info['tokens']['user']['referral-link'] = array(
    'name' => t('Referral Link'),
    'description' => t('The referral link for this user.'),
  );
  return $info;
}

/**
 * Implements hook_views_api().
 */
function referral_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'referral') . '/views',
  );
}

Functions

Constants