You are here

function field_encrypt_do_encrypt in Field Encryption 7

Add encryption to a field.

Called when the "Encrypt this field" setting is first applied.

Parameters

array $field_info: The field definition.

bool $has_data: Whether the field has data.

3 calls to field_encrypt_do_encrypt()
field_encrypt_field_create_field in ./field_encrypt.module
Implements hook_field_create_field().
field_encrypt_field_update_field in ./field_encrypt.module
Implements hook_field_update_field().
field_encrypt_update_7000 in ./field_encrypt.install
Update database schema to re-used existing field tables.

File

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

Code

function field_encrypt_do_encrypt($field_info, $has_data) {

  // Column spec for encrypted data.
  $spec = array(
    'type' => 'text',
    'size' => 'medium',
    'description' => 'The encrypted value for this entity field column.',
  );

  // 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 unencrypted data.
      db_delete($table)
        ->execute();
    }

    // Alter field columns to allow for encrypted data.
    foreach ($field_info['storage']['details']['sql'][$age][$table] as $column => $field) {
      if (!isset($field_info['indexes'][$column])) {
        db_change_field($table, $field, $field, $spec);
      }
    }

    // Encrypt 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, NULL values.
          if (empty($record->{$field})) {
            unset($record->{$field});
          }

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