You are here

function field_encrypt_un_encrypt in Field Encryption 7

Remove encryption from a field.

Called when the "Encrypt this field" setting is disabled.

Parameters

array $field_info: The field definition.

bool $has_data: Whether the field has data.

1 call to field_encrypt_un_encrypt()
field_encrypt_field_update_field in ./field_encrypt.module
Implements hook_field_update_field().

File

./field_encrypt.inc, line 86
Encryption functionality for the Field encrypt module.

Code

function field_encrypt_un_encrypt($field_info, $has_data) {

  // Prepare field so the storage details are available.
  $cache = _field_info_field_cache();
  $cache
    ->flush();
  $field_info = $cache
    ->prepareField($field_info);
  foreach (array(
    FIELD_LOAD_CURRENT,
    FIELD_LOAD_REVISION,
  ) as $age) {
    $table = key($field_info['storage']['details']['sql'][$age]);
    if ($has_data) {

      // Get all the current entries.
      $data = db_select($table, 't')
        ->fields('t')
        ->execute()
        ->fetchAll();

      // Delete the existing encrypted data.
      db_delete($table)
        ->execute();
    }

    // Revert the field columns back to their original state.
    foreach ($field_info['storage']['details']['sql'][$age][$table] as $column => $field) {
      if (!isset($field_info['indexes'][$column])) {
        db_change_field($table, $field, $field, $field_info['columns'][$column]);
      }
    }

    // Decrypt and re-insert the data.
    if ($has_data && isset($data)) {
      foreach ($data as $record) {
        $query = db_insert($table);
        foreach ($field_info['storage']['details']['sql'][$age][$table] as $column => $field) {

          // Don't re-write empty or NULL values.
          if (empty($record->{$field})) {
            unset($record->{$field});
          }

          // Don't un-encrypt indexes.
          if (isset($field_info['indexes'][$column])) {
            continue;
          }
          if (isset($record->{$field})) {
            $record->{$field} = field_encrypt_decrypt($record->{$field});
          }
        }
        $query
          ->fields((array) $record)
          ->execute();
      }
    }
  }
  drupal_set_message(t('%field_name is no longer being encrypted', array(
    '%field_name' => $field_info['field_name'],
  )));
}