You are here

regcode_roles.module in Registration codes 6.2

File

regcode_roles/regcode_roles.module
View source
<?php

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

/**
 * Implementation of hook_menu()
 */
function regcode_roles_menu() {
  $items = array();
  $items['admin/user/regcode/roles'] = array(
    'title' => t('Roles'),
    'description' => t('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/user/regcode/roles/delete/%'] = array(
    'page callback' => 'regcode_roles_delete_rule_confirm',
    'page arguments' => array(
      5,
    ),
    'type' => MENU_CALLBACK,
    'access arguments' => array(
      'administer registration codes',
    ),
  );
  return $items;
}

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

/**
 * Delete a rule
 */
function regcode_roles_delete_rule($rid) {
  db_query('DELETE FROM {regcode_roles} WHERE id = %d', $rid);
}

/**
 * Admin page for role assignment
 */
function regcode_roles_admin() {
  $form = array();
  $form['regcode_roles']['new'] = array(
    '#type' => 'fieldset',
    '#title' => 'Create a new rule',
  );
  $form['regcode_roles']['new']['role_id'] = array(
    '#type' => 'select',
    '#title' => 'Assign role',
    '#options' => user_roles(),
  );
  $form['regcode_roles']['new']['term_id'] = array(
    '#type' => 'select',
    '#title' => '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(
    '#type' => 'markup',
    '#value' => 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('Role'),
    t('Role ID'),
  );

  // 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'], 'small');
    }
    $row['action'] = l('Remove', 'admin/user/regcode/roles/delete/' . $row['id'], array(
      'query' => array(
        'token' => drupal_get_token($row['id']),
      ),
    ));
  }
  return theme('table', $headings, $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 < 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'));
}

/**
 * List all of the regcode rules
 *
 * @param $tags array Optional list of tags to get the rules for
 */
function regcode_roles_get_rules($tags = array()) {

  // Build field list
  $fields = array(
    'regcode_roles.id',
    'term_data.name',
    'role.name AS role',
    'role.rid as role_id',
  );
  if (module_exists('role_expire')) {
    $fields = array_merge($fields, array(
      'expire_duration',
      'expire_date',
    ));
  }

  // Query
  $query = 'SELECT ' . implode(', ', $fields) . '
            FROM {regcode_roles} AS regcode_roles
            LEFT JOIN {role} AS role ON (regcode_roles.role_id = role.rid)
            LEFT JOIN {term_data} AS term_data ON (regcode_roles.term_id = term_data.tid)';
  if (count($tags)) {
    $tags = implode(',', array_keys($tags));
    $res = db_query($query . " WHERE term_data.tid IN ({$tags})");
  }
  else {
    $res = db_query($query);
  }

  // Build array
  $rules = array();
  while ($row = db_fetch_array($res)) {
    $rules[] = $row;
  }
  return $rules;
}

/**
 * Create a new regcode rule
 */
function regcode_roles_create_rule($term_id, $role_id, $expire_date = NULL, $expire_duration = NULL) {
  $expire_date = !$expire_date ? 'NULL' : (int) $expire_date;
  $expire_duration = !$expire_duration ? 'NULL' : (int) $expire_duration;
  db_query("INSERT INTO {regcode_roles} (term_id, role_id, expire_date, expire_duration) VALUES ('%s', %d, %s, %s)", $term_id, $role_id, $expire_date, $expire_duration);
}

/**
 * Implements hook_regcode_used()
 *
 * Add the new role to the user
 */
function regcode_roles_regcode_used(&$edit, &$account, $regcode) {

  // Do nothing if the regcode is not valid
  if (!is_object($regcode)) {
    return;
  }

  // Grab applicable roles for category used
  $rules = count($regcode->tags) ? regcode_roles_get_rules($regcode->tags) : array();
  if (count($rules)) {

    // If there's no roles fieldset, then simulate the fieldset with an empty array
    if (!is_array($edit['roles'])) {
      $edit['roles'] = array();
    }

    // Merge in any roles the user has already
    foreach ($account->roles as $rid => $role) {
      if (!$rid) {

        // During registration the $account->roles variable contains bogus data
        // which looks like array(0 => authenticated user). Because this is
        // keyed inproperly we need a specific check to avoid creating a dummy role
        // @see http://drupal.org/node/884962
        continue;
      }
      $edit['roles'][$rid] = $role;
    }

    // Add the new roles to the user
    foreach ($rules as $rule) {
      $edit['roles'][$rule['role_id']] = $rule['role'];
    }
  }

  // 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 = 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.
regcode_roles_get_list_markup Return the formatted HTML list
regcode_roles_get_rules List all of the regcode rules
regcode_roles_help Implementation of hook_help()
regcode_roles_menu Implementation of hook_menu()
regcode_roles_regcode_used Implements hook_regcode_used()