You are here

regcode_roles.module in Registration codes 7

Main functionality of regcode_role module.

File

regcode_roles/regcode_roles.module
View source
<?php

/**
 * @file
 * Main functionality of regcode_role module.
 */

/**
 * Implements hook_help().
 */
function regcode_roles_help($path, $arg) {
  switch ($path) {
    case 'admin/config/people/regcode/roles':
      return '<p>' . t('Automate role assignment based on regcode. Create a list of rules which are applied when users register.') . '</p>';
  }
}

/**
 * Implements hook_menu().
 */
function regcode_roles_menu() {
  $items = array();
  $items['admin/config/people/regcode/roles'] = array(
    'title' => 'Roles',
    'description' => 'Automate role assignment',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'regcode_roles_admin',
    ),
    'type' => MENU_LOCAL_TASK,
    'access arguments' => array(
      'administer registration codes',
    ),
    'weight' => 100,
  );
  $items['admin/config/people/regcode/roles/delete/%'] = array(
    'page callback' => 'regcode_roles_delete_rule_confirm',
    'page arguments' => array(
      6,
    ),
    'type' => MENU_CALLBACK,
    'access arguments' => array(
      'administer registration codes',
    ),
  );
  return $items;
}

/**
 * Page callback for role-rule deletion; validates the security token as well.
 */
function regcode_roles_delete_rule_confirm($rid) {
  if (empty($_GET['token']) || !drupal_valid_token($_GET['token'], $rid)) {
    return MENU_ACCESS_DENIED;
  }
  regcode_roles_delete_rule($rid);
  drupal_set_message(t('Rule was deleted (Rule #@rule)', array(
    '@rule' => $rid,
  )));
  drupal_goto('admin/config/people/regcode/roles');
}

/**
 * Delete a rule.
 */
function regcode_roles_delete_rule($rid) {
  db_delete('regcode_roles')
    ->condition('id', $rid)
    ->execute();
}

/**
 * Admin page for role assignment.
 */
function regcode_roles_admin($form, &$form_state) {
  $form = array();
  $form['regcode_roles']['new'] = array(
    '#type' => 'fieldset',
    '#title' => 'Create a new rule',
  );
  $form['regcode_roles']['new']['role_id'] = array(
    '#type' => 'select',
    '#options' => user_roles(TRUE),
    '#prefix' => '<h4>' . t('When a user uses a regcode with tag'),
    '#title' => t('Role to assign'),
  );
  $form['regcode_roles']['new']['term_id'] = array(
    '#type' => 'select',
    '#required' => TRUE,
    '#title' => t('tag'),
    '#title_display' => 'invisible',
    '#prefix' => '<h4>' . t('When a user uses a regcode with tag'),
    '#options' => regcode_get_vocab_terms(),
  );
  if (module_exists('role_expire')) {
    $form['regcode_roles']['new']['expiry_duration'] = array(
      '#type' => 'textfield',
      '#title' => 'Which expires in (number of days)',
    );
    $form['regcode_roles']['new']['expiry_date'] = array(
      '#type' => 'textfield',
      '#title' => 'Or expires on (fixed date)',
    );
  }
  $form['regcode_roles']['new']['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Create rule',
  );
  $form['regcode_roles']['list'] = array(
    '#markup' => regcode_roles_get_list_markup(),
  );
  return $form;
}

/**
 * Return the formatted HTML list.
 */
function regcode_roles_get_list_markup() {
  $headings = array(
    t('Rule #'),
    t('Tag #'),
    t('Tag'),
    t('Role'),
  );

  // Display expire rules.
  if (module_exists('role_expire')) {
    $headings[] = t('Expire duration');
    $headings[] = t('Expire date');
  }
  $headings[] = t('Actions');
  $rows = regcode_roles_get_rules();

  // Add actions.
  foreach ($rows as &$row) {
    $row = array_map('check_plain', $row);
    if (!empty($row['expire_date'])) {
      $row['expire_date'] = format_date($row['expire_date'], 'short');
    }
    $row['action'] = l(t('Remove'), 'admin/config/people/regcode/roles/delete/' . $row['id'], array(
      'query' => array(
        'token' => drupal_get_token($row['id']),
      ),
    ));
  }
  return theme('table', array(
    'header' => $headings,
    'rows' => $rows,
  ));
}

/**
 * Validate date input.
 */
function regcode_roles_admin_validate($form, $form_state) {

  // Role expire stuff.
  if (module_exists('role_expire')) {
    if (!empty($form_state['values']['expiry_duration'])) {
      if ((int) $form_state['values']['expiry_duration'] < 1) {
        form_set_error('expiry_duration', t('Invalid duration provided, duration must be greater than or equal to 1 day.'));
      }
    }
    if (!empty($form_state['values']['expiry_date'])) {
      if (!($expire_date = strtotime($form_state['values']['expiry_date']))) {
        form_set_error('expiry_date', t('Invalid date provided, please provide a date in a format strtotime can handle.'));
      }
      elseif ($expire_date < REQUEST_TIME) {
        form_set_error('expiry_date', t('Expiry date must be in the future.'));
      }
    }
  }
}

/**
 * Create the roles.
 */
function regcode_roles_admin_submit($form, $form_state) {
  $role_id = $form_state['values']['role_id'];
  $term_id = $form_state['values']['term_id'];
  $expiry_date = NULL;
  $expiry_duration = NULL;
  if (module_exists('role_expire')) {
    if (!empty($form_state['values']['expiry_date'])) {
      $expiry_date = strtotime($form_state['values']['expiry_date']);
    }
    elseif (!empty($form_state['values']['expiry_duration'])) {
      $expiry_duration = (int) $form_state['values']['expiry_duration'];
    }
  }
  regcode_roles_create_rule($term_id, $role_id, $expiry_date, $expiry_duration);
  drupal_set_message(t('New registration code rule created'));
}

/**
 * Returns rules defined, optionally filtered by tag names.
 *
 * @param array $tags
 *   Optional list of tags to get the rules for.
 *
 * @return array
 *   An array of roles, each element containing a role stdClass.
 */
function regcode_roles_get_rules($tags = array()) {
  $query = db_select('regcode_roles', 'regcode_roles');
  $query
    ->join('role', 'role', 'regcode_roles.role_id = role.rid');
  $query
    ->join('taxonomy_term_data', 'term_data', 'regcode_roles.term_id = term_data.tid');
  $query
    ->fields('regcode_roles', array(
    'id',
    'role_id',
  ));
  $query
    ->addField('term_data', 'name', 'term_name');
  $query
    ->addField('role', 'name', 'role');
  if (count($tags)) {
    $query
      ->condition('term_data.name', $tags, 'IN');
  }

  // Add some extra fields if role_expire is enabled.
  if (module_exists('role_expire')) {
    $query
      ->fields('regcode_roles', array(
      'expire_duration',
      'expire_date',
    ));
  }
  return $query
    ->execute()
    ->fetchAll(PDO::FETCH_ASSOC);
}

/**
 * Create a new regcode rule.
 */
function regcode_roles_create_rule($term_id, $role_id, $expire_date = NULL, $expire_duration = NULL) {
  return db_insert('regcode_roles')
    ->fields(array(
    'term_id' => $term_id,
    'role_id' => $role_id,
    'expire_date' => $expire_date,
    'expire_duration' => $expire_duration,
  ))
    ->execute();
}

/**
 * Implements hook_regcode_used().
 *
 * Add the new role to the user.
 */
function regcode_roles_regcode_used($code, $account) {

  // Grab applicable roles for category used.
  $rules = regcode_roles_get_rules($code->tags);

  // Add the new roles to the user.
  foreach ($rules as $rule) {
    $account->roles[$rule['role_id']] = $rule['role'];
    db_merge('users_roles')
      ->key(array(
      'rid' => $rule['role_id'],
      'uid' => $account->uid,
    ))
      ->fields(array(
      'uid' => $account->uid,
      'rid' => $rule['role_id'],
    ))
      ->execute();
  }

  // Apply role_expire rules.
  if (module_exists('role_expire')) {
    foreach ($rules as $rule) {
      if ($rule['expire_date']) {
        $expiry_timestamp = $rule['expire_date'];
      }
      elseif ($rule['expire_duration']) {
        $expiry_timestamp = REQUEST_TIME + $rule['expire_duration'] * 60 * 60 * 24;
      }
      role_expire_write_record($account->uid, $rule['role_id'], $expiry_timestamp);
    }
  }
}

Functions

Namesort descending Description
regcode_roles_admin Admin page for role assignment.
regcode_roles_admin_submit Create the roles.
regcode_roles_admin_validate Validate date input.
regcode_roles_create_rule Create a new regcode rule.
regcode_roles_delete_rule Delete a rule.
regcode_roles_delete_rule_confirm Page callback for role-rule deletion; validates the security token as well.
regcode_roles_get_list_markup Return the formatted HTML list.
regcode_roles_get_rules Returns rules defined, optionally filtered by tag names.
regcode_roles_help Implements hook_help().
regcode_roles_menu Implements hook_menu().
regcode_roles_regcode_used Implements hook_regcode_used().