You are here

function farm_log_assign_action in farmOS 7

Action function for farm_log_assign_action.

Assigns a log to one or more people.

Parameters

Log $log: The log entity object.

array $context: Array with parameters for this action.

File

modules/farm/farm_log/farm_log.module, line 259
Code for the Farm Log feature.

Code

function farm_log_assign_action(Log $log, $context = array()) {

  // If the operation is invalid, bail.
  if (!in_array($context['operation'], array(
    'append',
    'replace',
  ))) {
    drupal_set_message(t('Invalid operation.'));
    return;
  }

  // If the operation is 'append', and there are no users, bail.
  if ($context['operation'] == 'append' && empty($context['users'])) {
    return;
  }

  // Create an entity wrapper for the log.
  $log_wrapper = entity_metadata_wrapper('log', $log);

  // If the owner field doesn't exist, bail.
  if (!isset($log_wrapper->field_farm_log_owner)) {
    return;
  }

  // Keep track of users that are already assigned.
  $existing_users = array();

  // If we are appending, load existing owner IDs.
  if ($context['operation'] == 'append' && !empty($log_wrapper->field_farm_log_owner)) {
    foreach ($log_wrapper->field_farm_log_owner
      ->getIterator() as $delta => $user_wrapper) {
      $existing_users[] = $user_wrapper->uid
        ->value();
    }
  }
  elseif ($context['operation'] == 'replace') {
    $log_wrapper->field_farm_log_owner = array();
  }

  // Assume that we are not going to save the log.
  $save = FALSE;

  // Iterate through the users.
  foreach ($context['users'] as $uid) {

    // If the ID is empty, skip it.
    if (empty($uid)) {
      continue;
    }

    // Load the user.
    $user = user_load($uid);

    // if the user didn't load, skip it.
    if (empty($user)) {
      continue;
    }

    // If the user is already referenced in the log, skip it.
    if (in_array($user->uid, $existing_users)) {
      continue;
    }

    // Add the user ID to the array of existing users so we don't accidentally
    // add the same one more than once. Shouldn't happen, but be defensive.
    $existing_users[] = $user->uid;

    // Add the user to the log's owner field.
    $log_wrapper->field_farm_log_owner[] = $user;

    // We will save the log.
    $save = TRUE;
  }

  // If we should save the log, then save it.
  if ($save) {
    $log_wrapper
      ->save();
  }
}