You are here

function message_og_example_node_insert in Message 7

Implements hook_node_insert().

File

message_og_example/message_og_example.module, line 43

Code

function message_og_example_node_insert($node) {
  list(, , $bundle) = entity_extract_ids('node', $node);
  if (!og_is_group_content_type('node', $bundle)) {
    return;
  }
  $wrapper = entity_metadata_wrapper('node', $node);
  if (!$wrapper->{'og_membership__' . OG_STATE_ACTIVE}
    ->value()) {

    // Node isn't associate, or doesn't have an active association with
    // any group.
    return;
  }
  $nids = array();
  foreach ($wrapper->{'og_membership__' . OG_STATE_ACTIVE}
    ->value() as $og_membership) {
    if ($og_membership->group_type != 'node') {

      // For simplicity we operate only on membership with node groups.
      continue;
    }
    $nids[] = $og_membership->gid;
  }
  if (!$nids) {
    return;
  }

  // Create a "Post in group" message. We don't use a token replacement
  // here as it needs to get the data from multiple values of the field.
  // Furthermore, this replacement probably doesn't make sense outside of
  // this message-type context, so we don't want to add another token,
  // that will not be used.
  $arguments['!groups'] = array(
    'callback' => 'message_og_example_group_list',
    'pass message' => TRUE,
  );
  $message = message_create('example_og_post_in_group', array(
    'arguments' => $arguments,
    'uid' => $node->uid,
  ));
  $wrapper = entity_metadata_wrapper('message', $message);
  $wrapper->field_node_ref
    ->set($node);
  $wrapper->field_node_groups_ref
    ->set($nids);
  $wrapper->field_published
    ->set($node->status);
  $wrapper
    ->save();
}