You are here

function og_entity_presave_group_audience_diff in Organic groups 7

Get the difference in group audience for a presaved entity.

Parameters

$entity: The presaved entity (i.e. with "original" key holding the unchanged entity).

$type: The entity type.

Return value

Array with all the differences, or an empty array if none found.

1 call to og_entity_presave_group_audience_diff()
og_entity_presave in ./og.module
Implements hook_entity_presave().

File

./og.module, line 640
Enable users to create and manage groups with roles and permissions.

Code

function og_entity_presave_group_audience_diff($entity, $type) {
  if (empty($entity->original) || empty($entity->{OG_AUDIENCE_FIELD})) {
    return;
  }
  $return = array(
    'insert' => array(),
    'update' => array(),
    'delete' => array(),
  );
  $new_gids = array();
  $original_gids = array();
  $wrapper = entity_metadata_wrapper($type, $entity);
  $group_memberships = array();
  foreach ($wrapper->og_membership
    ->value() as $group_membership) {
    $group_memberships[$group_membership->gid] = $group_membership;
  }
  if (isset($entity->{OG_AUDIENCE_FIELD}) && isset($entity->{OG_AUDIENCE_FIELD}[LANGUAGE_NONE])) {
    foreach ($entity->{OG_AUDIENCE_FIELD}[LANGUAGE_NONE] as $item) {
      $gid = $item['gid'];
      if (empty($group_memberships[$gid])) {

        // Empty group, assign default values.
        $item += array(
          'state' => OG_STATE_ACTIVE,
          'created' => time(),
        );
      }
      elseif (empty($item['state']) && empty($item['created'])) {
        $item['state'] = $group_memberships[$gid]->state;
        $item['created'] = $group_memberships[$gid]->created;
      }
      $new_gids[$gid] = $item;
    }
  }

  // Instead of checking $entity->original, we get the group membership. This
  // will allow egde cases, such as settings the group-audience field widget to
  // accpet only a single group, but later, subscribing a user to another group
  // via og_group(). By checking the group membership directly, we make sure we
  // have all the real membership, not only the ones captured on group-audience
  // field.
  foreach ($wrapper->og_membership
    ->value() as $group_membership) {
    $gid = $group_membership->gid;
    $item = array(
      'gid' => $group_membership->gid,
      'state' => $group_membership->state,
      'created' => $group_membership->created,
    );
    $original_gids[$gid] = $item;
    if (empty($new_gids[$gid])) {
      $return['delete'][] = $item;
    }
  }

  // Check if the membership is new, or updating an existing one.
  foreach ($new_gids as $gid => $item) {
    if (empty($original_gids[$gid])) {
      $return['insert'][] = $item;
    }
    elseif ($item['state'] != $original_gids[$gid]['state']) {

      // This is an existing group. Update the group only if the state has
      // changed.
      $return['update'][] = $item;
    }
  }
  return $return;
}