<?php

/**
 * @file
 * Defines a field type for referencing a role. Based almost entirely on nodereference and userreference modules.
 */

/**
 * Implementation of hook_menu().
 */
function rolereference_menu() {
  $items = array();
  $items['rolereference/autocomplete'] = array(
    'title' => 'Rolereference autocomplete',
    'page callback' => 'rolereference_autocomplete',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK
  );
  return $items;
}

/**
* Implementation of hook_views_api.
*/
function rolereference_views_api() {
  return array(
    'api' => 2,
    'path' => drupal_get_path('module', 'rolereference') .'/views',
  );
}

/**
 * Implementation of hook_theme().
 */
function rolereference_theme() {
  return array(
    'rolereference_select' => array(
      'arguments' => array('element' => NULL),
    ),
    'rolereference_buttons' => array(
      'arguments' => array('element' => NULL),
    ),
    'rolereference_autocomplete' => array(
      'arguments' => array('element' => NULL),
    ),
    'rolereference_formatter_default' => array(
      'arguments' => array('element'),
    ),
    'rolereference_formatter_rid' => array(
      'arguments' => array('element' => NULL),
    ),
    'rolereference_formatter_rid_array' => array(
      'arguments' => array('element' => NULL),
    ),
    'rolereference_tokens_all' => array(
      'arguments' => array('items' => array(), 'type' => 'role-all'),
    ),
  );
}

/**
 * Implementation of hook_field_info().
 */
function rolereference_field_info() {
  return array(
    'rolereference' => array(
      'label' => t('Role reference'),
      'description' => t('Store the ID of a role as an integer value.'),
    ),
  );
}

/**
 * Implementation of hook_field_settings().
 */
function rolereference_field_settings($op, $field) {
  switch ($op) {
    case 'form':
      $form = array();
      $form['referenceable_types'] = array(
        '#type' => 'checkboxes',
        '#title' => t('Roles that can be referenced'),
        '#description' => t('Leaving all boxes unchecked will make all roles referenceable.'),
        '#multiple' => TRUE,
        '#default_value' => is_array($field['referenceable_types']) ? $field['referenceable_types'] : array(),
        '#options' => array_map('check_plain', user_roles(FALSE)),
      );
      if (module_exists('views')) {
        $views = array('--' => '--');
        $all_views = views_get_all_views();
        foreach ($all_views as $view) {
          // Only 'users' views that have fields will work for our purpose.
          if ($view->base_table == 'role' && !empty($view->display['default']->display_options['fields'])) {
            if ($view->type == 'Default') {
              $views[t('Default Views')][$view->name] = $view->name;
            }
            else {
              $views[t('Existing Views')][$view->name] = $view->name;
            }
          }
        }

        $form['advanced'] = array(
           '#type' => 'fieldset',
           '#title' => t('Advanced - Roles that can be referenced (View)'),
           '#collapsible' => TRUE,
           '#collapsed' => !isset($field['advanced_view']) || $field['advanced_view'] == '--',
         );
        if (count($views) > 1) {
          $form['advanced']['advanced_view'] = array(
            '#type' => 'select',
            '#title' => t('View used to select the roles'),
            '#options' => $views,
            '#default_value' => isset($field['advanced_view']) ? $field['advanced_view'] : '--',
            '#description' =>  t('<p>Choose the "Views module" view that selects the roles that can be referenced.<br />Note:</p>') .
              t('<ul><li>Only views that have fields will work for this purpose.</li><li>This will discard the "Referenceable Roles" settings above. Use the view\'s "filters" section instead.</li><li>Use the view\'s "fields" section to display additional informations about candidate users on user creation/edition form.</li><li>Use the view\'s "sort criteria" section to determine the order in which candidate users will be displayed.</li></ul>'),
          );
          $form['advanced']['advanced_view_args'] = array(
            '#type' => 'textfield',
            '#title' => t('View arguments'),
            '#default_value' => isset($field['advanced_view_args']) ? $field['advanced_view_args'] : '',
            '#required' => FALSE,
            '#description' => t('Provide a comma separated list of arguments to pass to the view.'),
          );
        }
        else {
          $form['advanced']['no_view_help'] = array(
            '#value' => t('<p>The list of roles that can be referenced can be based on a "Views module" view but no appropriate views were found. <br />Note:</p>') .
              t('<ul><li>Only views that have fields will work for this purpose.</li><li>This will discard the "Referenceable Roles" settings above. Use the view\'s "filters" section instead.</li><li>Use the view\'s "fields" section to display additional informations about candidate users on user creation/edition form.</li><li>Use the view\'s "sort criteria" section to determine the order in which candidate users will be displayed.</li></ul>'),
          );
        }
      }
      return $form;

    case 'save':
      $settings = array('referenceable_types');
      if (module_exists('views')) {
        $settings[] = 'advanced_view';
        $settings[] = 'advanced_view_args';
      }
      return $settings;

    case 'database columns':
      $columns = array(
        'rid' => array('type' => 'int', 'unsigned' => TRUE, 'not null' => FALSE),
      );
      return $columns;

    case 'views data':
      $data = content_views_field_views_data($field);
      $db_info = content_database_info($field);
      $table_alias = content_views_tablename($field);
      // Filter : swap the handler to the 'in' operator.
      $data[$table_alias][$field['field_name'] .'_rid']['filter']['handler'] = 'content_handler_filter_many_to_one';
      // Argument: get the role name for summaries.
      // We need to join a new instance of the role table.
      $data["role_$table_alias"]['table']['join']['node'] = array(
        'table' => 'role',
        'field' => 'rid',
        'left_table' => $table_alias,
        'left_field' => $field['field_name'] .'_rid',
      );
      $data[$table_alias][$field['field_name'] .'_rid']['argument']['name table'] = "role_$table_alias";
      $data[$table_alias][$field['field_name'] .'_rid']['argument']['name field'] = 'name';
      // Relationship: Add a relationship for related role.
      $data[$table_alias][$field['field_name'] .'_rid']['relationship'] = array(
        'base' => 'role',
        'field' => $db_info['columns']['rid']['column'],
        'handler' => 'content_handler_relationship',
        'label' => t($field['widget']['label']),
        'content_field_name' => $field['field_name'],
      );

      $data["role_$table_alias"][$field['field_name'] .'_name'] = $data["role_$table_alias"][$field['field_name'] .'_rid'];
      $data["role_$table_alias"][$field['field_name'] .'_name'] = array(
        'group' => 'Content',
        'title' => $data[$table_alias][$field['field_name'] . '_rid']['title'],
        'field' => array(
          'table' => 'role',
          'field' => 'name',
          'additional fields' => array('name' => 'name')
        )
      );
      $data["role_$table_alias"][$field['field_name'] .'_name']['filter']['handler'] = 'content_handler_filter_many_to_one';
      $data["role_$table_alias"][$field['field_name'] .'_name']['relationship'] = array(
        'base' => 'role',
        'field' => $db_info['columns']['name']['column'],
        'handler' => 'content_handler_relationship',
        'label' => t($field['widget']['label']),
        'content_field_name' => $field['field_name'],
      );
      return $data;
  }
}

/**
 * Implementation of hook_content_is_empty().
 */
function rolereference_content_is_empty($item, $field) {
  if (empty($item['rid'])) {
    return TRUE;
  }
  return FALSE;
}


/**
 * Implementation of hook_field_formatter_info().
 */
function rolereference_field_formatter_info() {
  return array(
    'default' => array(
      'label' => t('Title (no link)'),
      'field types' => array('rolereference'),
      'multiple values' => CONTENT_HANDLE_CORE,
    ),
    'rid' => array(
      'label' => t('Role ID'),
      'field types' => array('rolereference'),
      'multiple values' => CONTENT_HANDLE_CORE,
    ),
    'rid_array' => array(
      'label' => t('Array of Role IDs'),
      'field types' => array('rolereference'),
      'multiple values' => CONTENT_HANDLE_MODULE,
    ),

  );
}

/**
 * Theme function for 'default' rolereference field formatter.
 */
function theme_rolereference_formatter_default($element) {
  $output = '';
  if (!empty($element['#item']['rid']) && is_numeric($element['#item']['rid']) && ($name = _rolereference_names($element['#item']['rid']))) {
    $output = check_plain($name);
  }
  return $output;
}

/**
 * Theme function for 'rid array' rolereference field formatter.
 */
function theme_rolereference_formatter_rid($element) {
  return $element['#item']['rid'];
}

/**
 * Theme function for 'rid array' rolereference field formatter.
 */
function theme_rolereference_formatter_rid_array($element) {
  foreach (element_children($element) as $key){
    $rid_array[] = $element[$key]['#item']['rid'];
  }
  return serialize($rid_array);
}

/**
 * Helper function for formatters.
 *
 * Store role names collected in the current request.
 */
function _rolereference_names($rid) {
  static $names = array();
  if (!isset($names[$rid])) {
    $name = db_result(db_query("SELECT name FROM {role} WHERE rid = %d", $rid));
    $names[$rid] = $name ? $name : '';
  }
  return $names[$rid];
}

/**
 * Implementation of hook_widget_info().
 *
 * We need custom handling of multiple values for the rolereference_select
 * widget because we need to combine them into a options list rather
 * than display multiple elements.
 *
 * We will use the content module's default handling for default value.
 *
 * Callbacks can be omitted if default handing is used.
 * They're included here just so this module can be used
 * as an example for custom modules that might do things
 * differently.
 */
function rolereference_widget_info() {
  return array(
    'rolereference_select' => array(
      'label' => t('Select list'),
      'field types' => array('rolereference'),
      'multiple values' => CONTENT_HANDLE_MODULE,
      'callbacks' => array(
        'default value' => CONTENT_CALLBACK_DEFAULT,
      ),
    ),
    'rolereference_buttons' => array(
      'label' => t('Check boxes/radio buttons'),
      'field types' => array('rolereference'),
      'multiple values' => CONTENT_HANDLE_MODULE,
      'callbacks' => array(
        'default value' => CONTENT_CALLBACK_DEFAULT,
      ),
    ),
    'rolereference_autocomplete' => array(
      'label' => t('Autocomplete text field'),
      'field types' => array('rolereference'),
      'multiple values' => CONTENT_HANDLE_CORE,
      'callbacks' => array(
        'default value' => CONTENT_CALLBACK_DEFAULT,
      ),
    ),
  );
}

/**
 * Implementation of FAPI hook_elements().
 *
 * Any FAPI callbacks needed for individual widgets can be declared here,
 * and the element will be passed to those callbacks for processing.
 *
 * Drupal will automatically theme the element using a theme with
 * the same name as the hook_elements key.
 *
 * Autocomplete_path is not used by text_widget but other widgets can use it
 * (see nodereference and userreference and rolereference).
 */
function rolereference_elements() {
  return array(
    'rolereference_select' => array(
      '#input' => TRUE,
      '#columns' => array('uid'), '#delta' => 0,
      '#process' => array('rolereference_select_process'),
    ),
    'rolereference_buttons' => array(
      '#input' => TRUE,
      '#columns' => array('uid'), '#delta' => 0,
      '#process' => array('rolereference_buttons_process'),
    ),
    'rolereference_autocomplete' => array(
      '#input' => TRUE,
      '#columns' => array('name'), '#delta' => 0,
      '#process' => array('rolereference_autocomplete_process'),
      '#autocomplete_path' => FALSE,
      ),
    );
}

/**
 * Implementation of hook_widget_settings().
 */
function rolereference_widget_settings($op, $widget) {
  switch ($op) {
    case 'form':
      $form = array();
      $match = isset($widget['autocomplete_match']) ? $widget['autocomplete_match'] : 'contains';
      if ($widget['type'] == 'rolereference_autocomplete') {
        $form['autocomplete_match'] = array(
          '#type' => 'select',
          '#title' => t('Autocomplete matching'),
          '#default_value' => $match,
          '#options' => array(
            'starts_with' => t('Starts with'),
            'contains' => t('Contains'),
          ),
          '#description' => t('Select the method used to collect autocomplete suggestions. Note that <em>Contains</em> can cause performance issues on sites with thousands of roles.'),
        );
      }
      else {
        $form['autocomplete_match'] = array('#type' => 'hidden', '#value' => $match);
      }
      return $form;

    case 'save':
      return array('autocomplete_match');
  }
}

/**
 * Implementation of hook_widget().
 *
 * Attach a single form element to the form. It will be built out and
 * validated in the callback(s) listed in hook_elements. We build it
 * out in the callbacks rather than here in hook_widget so it can be
 * plugged into any module that can provide it with valid
 * $field information.
 *
 * Content module will set the weight, field name and delta values
 * for each form element. This is a change from earlier CCK versions
 * where the widget managed its own multiple values.
 *
 * If there are multiple values for this field, the content module will
 * call this function as many times as needed.
 *
 * @param $form
 *   the entire form array, $form['#node'] holds node information
 * @param $form_state
 *   the form_state, $form_state['values'][$field['field_name']]
 *   holds the field's form values.
 * @param $field
 *   the field array
 * @param $items
 *   array of default values for this field
 * @param $delta
 *   the order of this item in the array of subelements (0, 1, 2, etc)
 *
 * @return
 *   the form item for a single element for this field
 */
function rolereference_widget(&$form, &$form_state, $field, $items, $delta = 0) {
  switch ($field['widget']['type']) {
    case 'rolereference_select':
      $element = array(
        '#type' => 'rolereference_select',
        '#default_value' => $items,
      );
      break;

    case 'rolereference_buttons':
      $element = array(
        '#type' => 'rolereference_buttons',
        '#default_value' => $items,
      );
      break;

    case 'rolereference_autocomplete':
      $element = array(
        '#type' => 'rolereference_autocomplete',
        '#default_value' => isset($items[$delta]) ? $items[$delta] : NULL,
        '#value_callback' => 'rolereference_autocomplete_value',
      );
      break;
  }
  return $element;
}

/**
 * Value for a rolereference autocomplete element.
 *
 * Substitute in the role name for the role rid.
 */
function rolereference_autocomplete_value($element, $edit = FALSE) {
  $field_key  = $element['#columns'][0];
  if (!empty($element['#default_value'][$field_key])) {
    $rid = $element['#default_value'][$field_key];
    $value = db_result(db_query('SELECT name FROM {role} WHERE rid = %d', $rid));
    $value .= ' [rid:'. $rid .']';
    return array($field_key => $value);
  }
  return array($field_key => NULL);
}

/**
 * Process an individual element.
 *
 * Build the form element. When creating a form using FAPI #process,
 * note that $element['#value'] is already set.
 *
 * The $fields array is in $form['#field_info'][$element['#field_name']].
 */
function rolereference_select_process($element, $edit, $form_state, $form) {
  // The rolereference_select widget doesn't need to create its own
  // element, it can wrap around the optionwidgets_select element.
  // This will create a new, nested instance of the field.
  // Add a validation step where the value can be unwrapped.
  $field_key  = $element['#columns'][0];
  $element[$field_key] = array(
    '#type' => 'optionwidgets_select',
    '#default_value' => isset($element['#value']) ? $element['#value'] : '',
    // The following values were set by the content module and need
    // to be passed down to the nested element.
    '#title' => $element['#title'],
    '#required' => $element['#required'],
    '#description' => $element['#description'],
    '#field_name' => $element['#field_name'],
    '#type_name' => $element['#type_name'],
    '#delta' => $element['#delta'],
    '#columns' => $element['#columns'],
  );
  if (empty($element[$field_key]['#element_validate'])) {
    $element[$field_key]['#element_validate'] = array();
  }
  array_unshift($element[$field_key]['#element_validate'], 'rolereference_optionwidgets_validate');
  return $element;
}

/**
 * Process an individual element.
 *
 * Build the form element. When creating a form using FAPI #process,
 * note that $element['#value'] is already set.
 *
 * The $fields array is in $form['#field_info'][$element['#field_name']].
 */
function rolereference_buttons_process($element, $edit, $form_state, $form) {
  // The rolereference_select widget doesn't need to create its own
  // element, it can wrap around the optionwidgets_select element.
  // This will create a new, nested instance of the field.
  // Add a validation step where the value can be unwrapped.
  $field_key  = $element['#columns'][0];
  $element[$field_key] = array(
    '#type' => 'optionwidgets_buttons',
    '#default_value' => isset($element['#value']) ? $element['#value'] : '',
    // The following values were set by the content module and need
    // to be passed down to the nested element.
    '#title' => $element['#title'],
    '#required' => $element['#required'],
    '#description' => $element['#description'],
    '#field_name' => $element['#field_name'],
    '#type_name' => $element['#type_name'],
    '#delta' => $element['#delta'],
    '#columns' => $element['#columns'],
  );
  if (empty($element[$field_key]['#element_validate'])) {
    $element[$field_key]['#element_validate'] = array();
  }
  array_unshift($element[$field_key]['#element_validate'], 'rolereference_optionwidgets_validate');
  return $element;
}

/**
 * Process an individual element.
 *
 * Build the form element. When creating a form using FAPI #process,
 * note that $element['#value'] is already set.
 *
 */
function rolereference_autocomplete_process($element, $edit, $form_state, $form) {

  // The rolereference autocomplete widget doesn't need to create its own
  // element, it can wrap around the text_textfield element and add an autocomplete
  // path and some extra processing to it.
  // Add a validation step where the value can be unwrapped.
  $field_key  = $element['#columns'][0];

  $element[$field_key] = array(
    '#type' => 'text_textfield',
    '#default_value' => isset($element['#value']) ? $element['#value'] : '',
    '#autocomplete_path' => 'rolereference/autocomplete/'. $element['#field_name'],
    // The following values were set by the content module and need
    // to be passed down to the nested element.
    '#title' => $element['#title'],
    '#required' => $element['#required'],
    '#description' => $element['#description'],
    '#field_name' => $element['#field_name'],
    '#type_name' => $element['#type_name'],
    '#delta' => $element['#delta'],
    '#columns' => $element['#columns'],
  );
  if (empty($element[$field_key]['#element_validate'])) {
    $element[$field_key]['#element_validate'] = array();
  }
  array_unshift($element[$field_key]['#element_validate'], 'rolereference_autocomplete_validate');

  // Used so that hook_field('validate') knows where to flag an error.
  $element['_error_element'] = array(
    '#type' => 'value',
    // Wrapping the element around a text_textfield element creates a
    // nested element, so the final id will look like 'field-name-0-rid-rid'.
    '#value' => implode('][', array_merge($element['#parents'], array($field_key, $field_key))),
  );
  return $element;
}

/**
 * Validate a select/buttons element.
 *
 * Remove the wrapper layer and set the right element's value.
 * We don't know exactly where this element is, so we drill down
 * through the element until we get to our key.
 *
 * We use $form_state['values'] instead of $element['#value']
 * to be sure we have the most accurate value when other modules
 * like optionwidgets are using #element_validate to alter the value.
 */
function rolereference_optionwidgets_validate($element, &$form_state) {
  $field_key  = $element['#columns'][0];

  $value = $form_state['values'];
  $new_parents = array();
  foreach ($element['#parents'] as $parent) {
    $value = $value[$parent];
    // Use === to be sure we get right results if parent is a zero (delta) value.
    if ($parent === $field_key) {
      $element['#parents'] = $new_parents;
      form_set_value($element, $value, $form_state);
      break;
    }
    $new_parents[] = $parent;
  }
}

/**
 * Validate an autocomplete element.
 *
 * Remove the wrapper layer and set the right element's value.
 * This will move the nested value at 'field-name-0-rid-rid'
 * back to its original location, 'field-name-0-rid'.
 */
function rolereference_autocomplete_validate($element, &$form_state) {
  $field_name = $element['#field_name'];
  $type_name = $element['#type_name'];
  $field = content_fields($field_name, $type_name);
  $field_key = $element['#columns'][0];
  $delta = $element['#delta'];
  $value = $element['#value'][$field_key];
  $rid = NULL;
  if (!empty($value)) {
    preg_match('/^(?:\s*|(.*) )?\[\s*rid\s*:\s*(\d+)\s*\]$/', $value, $matches);
    if (!empty($matches)) {
      // Explicit [rid:n].
      list(, $name, $rid) = $matches;
      if (!empty($name) && ($r = db_result(db_query("SELECT name FROM {role} WHERE rid = %d", $rid))) && $name != $r) {
        form_error($element[$field_key], t('%name: name mismatch. Please check your selection.', array('%name' => t($field['widget']['label']))));
      }
    }
    else {
      // No explicit rid.
      $reference = _rolereference_potential_references($field, $value);
      if (empty($reference)) {
        form_error($element[$field_key], t('%name: found no valid role with that name.', array('%name' => t($field['widget']['label']))));
      }
      else {
        // TODO:
        // the best thing would be to present the user with an additional form,
        // allowing the user to choose between valid candidates with the same title
        // ATM, we pick the first matching candidate...
        $rid = key($reference);
      }
    }
  }
  form_set_value($element, $rid, $form_state);
}

/**
 * Implementation of hook_allowed_values().
 */
function rolereference_allowed_values($field) {
  $references = _rolereference_potential_references($field);

  $options = array();
  foreach ($references as $key => $value) {
    // Views theming runs check_plain (htmlentities) on the values.
    // We reverse that with html_entity_decode.
    $options[$key] = html_entity_decode(strip_tags($value['rendered']), ENT_QUOTES);
  }
  return $options;
}

/**
 * Fetch an array of all candidate referenced roles.
 *
 * This info is used in various places (allowed values, autocomplete results,
 * input validation...). Some of them only need the rids, others rid + names,
 * others yet rid + names + rendered row (for display in widgets).
 * The array we return contains all the potentially needed information, and lets
 * consumers use the parts they actually need.
 *
 * @param $field
 *   The field description.
 * @param $string
 *   Optional string to filter titles on (used by autocomplete).
 * @param $match
 *   Operator to match filtered name against, can be any of:
 *   'contains', 'equals', 'starts_with'
 * @param $ids
 *   Optional role ids to lookup (the $string and $match arguments will be
 *   ignored).
 * @param $limit
 *   If non-zero, limit the size of the result set.
 *
 * @return
 *   An array of valid roles in the form:
 *   array(
 *     rid => array(
 *       'name' => The role name,
 *       'rendered' => The text to display in widgets (can be HTML)
 *     ),
 *     ...
 *   )
 */
function _rolereference_potential_references($field, $string = '', $match = 'contains', $ids = array(), $limit = NULL) {
  static $results = array();

  // Create unique id for static cache.
  $cid = $field['field_name'] .':'. $match .':'. ($string !== '' ? $string : implode('-', $ids)) .':'. $limit;
  if (!isset($results[$cid])) {
    $references = FALSE;
    if (module_exists('views') && !empty($field['advanced_view']) && $field['advanced_view'] != '--') {
      $references = _rolereference_potential_references_views($field, $string, $match, $ids, $limit);
    }
    // If the view doesn't exist, we got FALSE, and fallback to the regular 'standard mode'.

    if ($references === FALSE) {
      $references = _rolereference_potential_references_standard($field, $string, $match, $ids, $limit);
    }

    // Store the results.
    $results[$cid] = !empty($references) ? $references : array();
  }

  return $results[$cid];
}

/**
 * Helper function for _nodereference_potential_references():
 * case of Views-defined referenceable nodes.
 */
function _rolereference_potential_references_views($field, $string = '', $match = 'contains', $ids = array(), $limit = NULL) {
  $view_name = $field['advanced_view'];

  if ($view = views_get_view($view_name)) {
    // We add a display, and let it derive from the 'default' display.
    // TODO: We should let the user pick a display in the fields settings - sort of requires AHAH...
    $display = $view->add_display('content_references');
    $view->set_display($display);

    // TODO from merlinofchaos on IRC : arguments using summary view can defeat the style setting.
    // We might also need to check if there's an argument, and set *its* style_plugin as well.
    $view->display_handler->set_option('style_plugin', 'content_php_array_autocomplete');
    $view->display_handler->set_option('row_plugin', 'fields');
    // Used in content_plugin_style_php_array::render(), to get
    // the 'field' to be used as title.
    $view->display_handler->set_option('content_title_field', 'name');

    // Additional options to let content_plugin_display_references::query()
    // narrow the results.
    $options = array(
      'table' => 'role',
      'field_string' => 'name',
      'string' => $string,
      'match' => $match,
      'field_id' => 'rid',
      'ids' => $ids,
    );
    $view->display_handler->set_option('content_options', $options);

    // TODO : for consistency, a fair amount of what's below
    // should be moved to content_plugin_display_references

    // Limit result set size.
    if (isset($limit)) {
      $view->display_handler->set_option('items_per_page', $limit);
    }

    // Get arguments for the view.
    if (!empty($field['advanced_view_args'])) {
      // TODO: Support Tokens using token.module ?
      $view_args = array_map('trim', explode(',', $field['advanced_view_args']));
    }
    else {
      $view_args = array();
    }

    // We do need title field, so add it if not present (unlikely, but...)
    $fields = $view->get_items('field', $display);
    if (!isset($fields['title'])) {
      $view->add_item($display, 'field', 'role', 'name');
    }

    // If not set, make all fields inline and define a separator.
    $options = $view->display_handler->get_option('row_options');
    if (empty($options['inline'])) {
      $options['inline'] = drupal_map_assoc(array_keys($view->get_items('field', $display)));
    }
    if (empty($options['separator'])) {
      $options['separator'] = '-';
    }
    $view->display_handler->set_option('row_options', $options);

    // Make sure the query is not cached
    $view->is_cacheable = FALSE;

    // Get the results.
    $result = $view->execute_display($display, $view_args);
  }
  else {
    $result = FALSE;
  }

  return $result;
}

/**
 * Helper function for _nodereference_potential_references():
 * referenceable nodes defined by content types.
 */
function _rolereference_potential_references_standard($field, $string = '', $match = 'contains', $ids = array(), $limit = NULL) {
  $related_types = array();
  $where = array();
  $args = array();
  if (is_array($field['referenceable_types'])) {
    foreach (array_filter($field['referenceable_types']) as $related_type) {
      $related_types[] = "r.rid = %d";
      $args[] = $related_type;
    }
  }
  // Default to all roles if no roles selected.
  if (!count($related_types)) {
    $roles = db_query('SELECT rid, name FROM {role} ORDER BY name');
    while ($role = db_fetch_object($roles)) {
      $related_types[] = "r.rid = %d";
      $args[] = $role->rid;
    }
  }
  $where[] = implode(' OR ', $related_types);

  if ($string !== '') {
    $match_operators = array(
      'contains' => "LIKE '%%%s%%'",
      'equals' => "= '%s'",
      'starts_with' => "LIKE '%s%%'",
    );
    $where[] = 'r.name '. (isset($match_operators[$match]) ? $match_operators[$match] : $match_operators['contains']);
    $args[] = $string;
  }
  elseif ($ids) {
    $where[] = 'r.rid IN (' . db_placeholders($ids) . ')';
    $args = array_merge($args, $ids);
  }

  $references = array();
  $where_clause = $where ? 'WHERE ('. implode(') AND (', $where) .')' : '';
  $result = db_query('SELECT r.rid, r.name FROM {role} r '." $where_clause ORDER BY r.name ASC", $args);
  while ($reference = db_fetch_object($result)) {
    $references[$reference->rid] = array(
      'title' => $reference->name,
      'rendered' => check_plain($reference->name),
    );
  }
  return $references;
}

/**
 * Menu callback; Retrieve a pipe delimited string of autocomplete suggestions for existing roles
 */
function rolereference_autocomplete($field_name, $string = '') {
  $fields = content_fields();
  $field = $fields[$field_name];
  $match = isset($field['widget']['autocomplete_match']) ? $field['widget']['autocomplete_match'] : 'contains';
  $matches = array();

  $references = _rolereference_potential_references($field, $string, $match, array(), 10);
  foreach ($references as $id => $row) {
    // Add a class wrapper for a few required CSS overrides.
    $matches[$row['title'] ." [rid:$id]"] = '<div class="reference-autocomplete">'. $row['rendered'] . '</div>';
  }
  drupal_json($matches);
}

/**
 * FAPI theme for an individual elements.
 *
 * The textfield or select is already rendered by the
 * textfield or select themes and the html output
 * lives in $element['#children']. Override this theme to
 * make custom changes to the output.
 *
 * $element['#field_name'] contains the field name
 * $element['#delta]  is the position of this element in the group
 */
function theme_rolereference_select($element) {
  return $element['#children'];
}

function theme_rolereference_buttons($element) {
  return $element['#children'];
}

function theme_rolereference_autocomplete($element) {
  return $element['#children'];
}

/**
 * Implementation of hook_content_multigroup_allowed_widgets().
 */
function rolereference_content_multigroup_allowed_widgets() {
  return array('rolereference_select', 'rolereference_buttons', 'rolereference_autocomplete');
}

/**
 * Implementation of hook_content_multigroup_no_remove_widgets().
 */
function rolereference_content_multigroup_no_remove_widgets() {
  return array('rolereference_select', 'rolereference_buttons', 'rolereference_autocomplete');
}

/**
 * CCK field Token API hook_token_list implimentation
 * @see content.token.inc and http://drupal.org/node/156860
 *
 * @param string type The type of tokens to list.
 * @return array An array of token-type => token-name => description
 */
function rolereference_token_list($type = 'all') {
  if ($type == 'field' || $type == 'all') {
    $tokens = array();

    $tokens['role referenced']['rid'] =
                              t('The first / single referenced role ID');
    $tokens['role referenced']['role'] =
                              t('The first / single referenced role name');
    $tokens['role referenced']['rid-all'] = t('All referenced rids.');
    $tokens['role referenced']['role-all'] = t('All referenced role names.');

    return $tokens;
  }
}

/*
 * CCK field Token API hook_token_value implimentation
 * @see content.token.inc @ http://drupal.org/node/156860
 *
 * @param String type Type of value to process
 * @param Array object Field values
 * @param Array options Options array
 * @return Array An array of token-name => String value
 */
function rolereference_token_values($type, $object = NULL, $options = array()) {
  if ($type == 'field') {
    $item = $object[0];
    $tokens['rid'] = $item['rid'];
    $tokens['role'] = $item['view'];

    $all = array();
    foreach ( $object as $item ) {
      $all['rid-all'][] = $item['rid'];
      $all['role-all'][] = $item['view'];
    }
    foreach ( $all as $key => $values ) {
      $tokens[$key] = theme('rolereference_tokens_all', $values, $key);
    }
log_debug('tokens=' .print_r($tokens, true));
    return $tokens;
  }
}

/**
 * Theme role reference fields that contain multiple values.  E.g. the -all
 * tokens.  Rid values use the view argument "or" option (e.g. 1+3+8) others
 * use a simple comma (e.g. admin,subscriber,guest);
 *
 * @param array $items Array of role values (e.g. rid or role names).
 * @param string $type Type of values being processed, e.g. rid-all or role-all.
 * @return The formated token string.
 */
function theme_rolereference_tokens_all( $items, $type = 'role-all') {
  switch ( $type ) {
    case 'rid-all':
      $token = implode('+',$items);  // Use view argument or option.
      break;
    case 'role-all':
    default:
      $token = implode(',',$items);
  }
  return $token;
}
