You are here

function gdpr_consent_field_attach_submit in General Data Protection Regulation 7

Implements hook_field_attach_submit().

If consent field changes grant/revoke consent and log audit trail.

File

modules/gdpr_consent/gdpr_consent.module, line 410
Contains hook implementations and shared functions.

Code

function gdpr_consent_field_attach_submit($entity_type, $entity, $form, &$form_state) {
  $is_new = FALSE;
  list($id, , $bundle) = entity_extract_ids($entity_type, $entity);

  // If $entity does not have an id that means it's new.
  if (!isset($id)) {
    $is_new = TRUE;
  }
  $fields = gdpr_consent_get_consent_fields($entity_type, $bundle);
  if (!$is_new) {
    $original = entity_load_unchanged($entity_type, $id);
  }
  foreach ($fields as $field) {
    $info = field_info_field($field);
    $agreement = entity_load_single('gdpr_consent_agreement', $info['settings']['target_id']);

    // Don't log implicit consent.
    if ($agreement->agreement_type != GDPR_CONSENT_TYPE_EXPLICIT) {
      continue;
    }

    // Ignore if field not present in form.
    if (!isset($form[$field])) {
      continue;
    }
    $values = drupal_array_get_nested_value($form_state['values'], $form[$field]['#parents']);
    if (!empty($values)) {
      $new = isset($values[LANGUAGE_NONE][0]['agreed']) ? (int) $values[LANGUAGE_NONE][0]['agreed'] : NULL;

      // Newly created entities should only log accepted agreements.
      $old = !$is_new && isset($original->{$field}[LANGUAGE_NONE][0]['agreed']) ? (int) $original->{$field}[LANGUAGE_NONE][0]['agreed'] : NULL;

      // @todo Needs test coverage to make sure we aren't logging irrelevant changes.
      if ($new !== $old) {
        if ($new) {
          $message = message_create('consent_agreement_accepted', array(
            'uid' => $values[LANGUAGE_NONE][0]['user_consenter'],
          ));
        }
        else {
          $message = message_create('consent_agreement_revoked', array(
            'uid' => $values[LANGUAGE_NONE][0]['user_consenter'],
          ));
        }
        $wrapper = entity_metadata_wrapper('message', $message);

        // @todo fix naming for fields - User owner is giving consent by probably unnecessary?
        $wrapper->user_consenter
          ->set($values[LANGUAGE_NONE][0]['user_consenter']);
        $wrapper->user_recorder
          ->set($values[LANGUAGE_NONE][0]['user_recorder']);
        $wrapper->agreement
          ->set($agreement);
        $wrapper->notes
          ->set($values[LANGUAGE_NONE][0]['notes']);
        $wrapper->agreed
          ->set($values[LANGUAGE_NONE][0]['agreed']);
        $wrapper
          ->save();
      }
    }
  }
}