<?php
// $Id: userreference.module,v 1.22.2.9 2006/08/21 03:06:45 JonBob Exp $

/**
 * @file
 * Defines a field type for referencing a user from a node.
 */

/**
 * Implementation of hook_help().
 */
function userreference_help($section) {
  switch ($section) {
    case 'admin/modules#description':
      return t('<strong>CCK:</strong> Defines a field type for referencing a user from a node. <em>Note: Requires content.module.</em>');
  }
}

/**
 * Implementation of hook_field_info().
 */
function userreference_field_info() {
  return array(
    'userreference' => array('label' => 'User Reference'),
  );
}

/**
 * Implementation of hook_field_settings().
 */
function userreference_field_settings($op, $field) {
  switch ($op) {
    case 'form':
      $form = array();
      $form['referenceable_roles'] = array(
        '#type' => 'checkboxes',
        '#title' => t('User roles that can be referenced'),
        '#multiple' => TRUE,
        '#default_value' => isset($field['referenceable_roles']) ? $field['referenceable_roles'] : array(),
        '#options' => user_roles(1),
      );
      return $form;

    case 'save':
      return array('referenceable_roles');

    case 'database columns':
      $columns = array(
        'uid' => array('type' => 'int', 'not null' => TRUE, 'default' => '0'),
      );
      return $columns;

    case 'filters':
      return array(
        'default' => array(
          'list' => '_userreference_filter_handler',
          'list-type' => 'list',
          'operator' => 'views_handler_operator_or',
          'value-type' => 'array',
          'extra' => array('field' => $field),
        ),
      );
  }
}

/**
 * Implementation of hook_field().
 */
function userreference_field($op, &$node, $field, &$items, $teaser, $page) {
  switch ($op) {
    case 'view':
      foreach ($items as $delta => $item) {
        $items[$delta]['view'] = content_format($field, $item, 'default', $node);
      }
      return theme('field', $node, $field, $items, $teaser, $page);
  }
}

/**
 * Implementation of hook_field_formatter_info().
 */
function userreference_field_formatter_info() {
  return array(
    'default' => array(
      'label' => 'Default',
      'field types' => array('userreference'),
    ),
    'plain' => array(
      'label' => 'Plain text',
      'field types' => array('userreference'),
    ),
  );
}

/**
 * Implementation of hook_field_formatter().
 */
function userreference_field_formatter($field, $item, $formatter, $node) {
  $text = '';
  if (isset($item['uid'])) {
    $referenced_user = user_load(array('uid' => $item['uid']));
    if ($referenced_user) {
      $text = theme('username', $referenced_user);
    }
  }
  
  switch ($formatter) {
    case 'plain':
      return strip_tags($text);
    
    default:
      return $text;
  }
}

/**
 * Implementation of hook_widget_info().
 */
function userreference_widget_info() {
  return array(
    'userreference_select' => array(
      'label' => 'Select List',
      'field types' => array('userreference'),
    ),
    'userreference_autocomplete' => array(
      'label' => 'Autocomplete Text Field',
      'field types' => array('userreference'),
    ),
  );
}

/**
 * Implementation of hook_widget().
 */
function userreference_widget($op, &$node, $field, &$node_field) {
  if ($field['widget']['type'] == 'userreference_select') {
    switch ($op) {
      case 'prepare form values':
        $node_field_transposed = content_transpose_array_rows_cols($node_field);
        $node_field['default uids'] = $node_field_transposed['uid'];
        break;

      case 'form':
        $form = array();

        $form[$field['field_name']] = array('#tree' => TRUE);
        $form[$field['field_name']]['uids'] = array(
          '#type' => 'select',
          '#title' => t($field['widget']['label']),
          '#default_value' => $node_field['default uids'],
          '#multiple' => $field['multiple'],
          '#options' => _userreference_potential_references($field),
          '#required' => $field['required'],
          '#description' => $field['widget']['description'],
        );

        return $form;

      case 'process form values':
        if ($field['multiple']) {
          $node_field = content_transpose_array_rows_cols(array('uid' => $node_field['uids']));
        }
        else {
          $node_field[0]['uid'] = $node_field['uids'];
        }
        // Remove the widget's data representation so it isn't saved.
        unset($node_field['uids']);
    }
  }
  else {
    switch ($op) {
      case 'prepare form values':
        foreach($node_field as $delta => $item) {
          $node_field[$delta]['default user_name'] = db_result(db_query("SELECT name FROM {users} WHERE uid = '%d'", $node_field[$delta]['uid']));
        }
        break;

      case 'form':
        $form = array();
        $form[$field['field_name']] = array('#tree' => TRUE);

        if ($field['multiple']) {
          $form[$field['field_name']]['#type'] = 'fieldset';
          $form[$field['field_name']]['#title'] = t($field['widget']['label']);
          $form[$field['field_name']]['#description'] = $field['widget']['description'];
          $delta = 0;
          foreach ($node_field as $item) {
            if ($item['uid']) {
              $form[$field['field_name']][$delta]['user_name'] = array(
                '#type' => 'textfield',
                '#title' => '',
                '#autocomplete_path' => 'user/autocomplete',
                '#default_value' => $item['default user_name'],
                '#required' => ($delta == 0) ? $field['required'] : FALSE,
              );
              $delta++;
            }
          }
          foreach (range($delta, $delta + 2) as $delta) {
            $form[$field['field_name']][$delta]['user_name'] = array(
              '#type' => 'textfield',
              '#title' => '',
              '#autocomplete_path' => 'user/autocomplete',
              '#default_value' => '',
              '#required' => ($delta == 0) ? $field['required'] : FALSE,
            );
          }
        }
        else {
          $form[$field['field_name']][0]['user_name'] = array(
            '#type' => 'textfield',
            '#title' => t($field['widget']['label']),
            '#autocomplete_path' => 'user/autocomplete',
            '#default_value' => $node_field[0]['default user_name'],
            '#required' => $field['required'],
            '#description' => $field['widget']['description'],
          );
        }
        return $form;

      case 'validate':
        foreach ($node_field as $delta => $item) {
          if ($item['user_name'] && !in_array($item['user_name'], _userreference_potential_references($field))) {
            form_set_error($field['field_name'], t('Invalid user name.'));
          }
        }
        return;

      case 'process form values':
        foreach ($node_field as $delta => $item) {
          $uid = db_result(db_query("SELECT uid FROM {users} WHERE name = '%s'", $node_field[$delta]['user_name']));
          // Remove the widget's data representation so it isn't saved.
          unset($node_field[$delta]['user_name']);
          if ($uid) {
            $node_field[$delta]['uid'] = $uid;
          }
          else {
            unset($node_field[$delta]); 
          }
        }
    }
  }
}

/**
 * Fetch an array of all candidate referenced users, for use in presenting the selection form to the user.
 */
function _userreference_potential_references($field) {
  if (!$field['required']) {
    $users = array(0 => '');
  } else {
    $users = array();
  }

  if (!isset($field['referenceable_roles']) || in_array(DRUPAL_AUTHENTICATED_RID, $field['referenceable_roles'])) {
    $result = db_query("SELECT u.name, u.uid FROM {users} u WHERE uid > 0 ORDER BY u.name ASC");
  }
  else {
    $roles = array();
    foreach ($field['referenceable_roles'] as $role) {
      if ($role) {
        $roles[] = $role;
      }
    }
    $result = db_query("SELECT u.name, u.uid FROM {users} u LEFT JOIN {users_roles} r ON u.uid = r.uid WHERE u.uid > 0 AND r.rid IN (" . implode($roles, ',') . ')');
  }

  while ($user = db_fetch_object($result)) {
    $users[$user->uid] = $user->name;
  }

  return $users;
}

/**
 * Provide a list of users to filter on.
 */
function _userreference_filter_handler($op, $filterinfo) {
  $options = views_handler_filter_usercurrent();
  $options = array_merge($options, _userreference_potential_references($filterinfo['extra']['field']));
  return $options;
}
