<?php

/**
 * FeedAPI mapper for user reference CCK fields.
 * Matt Johnson (johnson.matthew.david@gmail.com / xmattus on drupal.org)
 */

/**
 * Implementation of hook_feedapi_mapper for userreference.module (the CCK add-on).
 * This mostly follows the example of the general CCK mapper (feedapi_mapper_content.inc)
 * but has some special logic for handling users. This accepts either user names (as strings) or UIDs (as integers).
 *
 * @param string $op
 * @param Drupal node $node
 * @param string $field_name
 * @param string, number or array of string or number $feed_element
 * @param string or number as id $sub_field
 *
 */
function userreference_feedapi_mapper($op, $node, $feed_element = array(), $field_name = '', $sub_field = '') {
  // Test for the node field that we would like to map to.
  if ($op == 'describe') {
    return t('Maps a user name (string) or uid (integer) to a user reference field.');
  }
  else if ($op == 'list') {
    $info = content_types($node->type);
    $fields = array();
    if (@count($info['fields'])) {
      foreach ($info['fields'] as $field_name => $field) {
        if (in_array($field['type'], array('userreference'))) {
          $fields[$field_name] = isset($field['widget']['label']) ? $field['widget']['label'] : $field_name;
        }
      }
    }
    if (count($fields)) {
      return $fields;
    }
    return FALSE;
  }
  else if ($op == 'map') {
    $field = isset($node->$field_name) ? $node->$field_name : array();
    // Convert a name to UID, or if numeric, use directly as a uid.
    if (!is_array($feed_element)) {
      $feed_element = array($feed_element);
    }
    $i = 0;
    foreach ($feed_element as $value) {
      if (is_numeric($value)) {
        $uid = $value;
      }
      else {
        $uid = db_result(db_query("SELECT uid FROM {users} WHERE name='%s'", $value));
      }
      if ($uid) {
        // User reference fields use 'uid' as the array key in lieu of 'value' like other CCK fields.
        $field[$i]['uid'] = $uid;
        $i++;
      }
    }
    
    $node->$field_name = $field;
    return $node;
  }
}