You are here

function mailhandler_user_presave in Mailhandler 8

Implements hook_ENTITY_TYPE_presave().

File

./mailhandler.module, line 12
Hook implementations for Mailhandler module.

Code

function mailhandler_user_presave(EntityInterface $entity) {

  /** @var \Drupal\user\UserInterface $entity */
  if ($entity
    ->hasField('mailhandler_gpg_key') && extension_loaded('gnupg')) {

    /** @var \Drupal\user\UserInterface|null $original */
    $original = $entity->original;
    $gpg_key_field = $entity
      ->get('mailhandler_gpg_key');

    // Update the GPG keyring in case a new user has been created
    // or the GPG key has been changed.
    if (!$original || !$gpg_key_field
      ->equals($original
      ->get('mailhandler_gpg_key'))) {

      // Initialize GnuPG resource.
      $gpg = gnupg_init();
      if ($original) {

        // Delete the old key from GPG keyring.
        gnupg_deletekey($gpg, $original
          ->get('mailhandler_gpg_key')->fingerprint);
      }

      // Import the GPG public key.
      $key_info = gnupg_import($gpg, $gpg_key_field->public_key);

      // Update the fingerprint property.
      $gpg_key_field->fingerprint = $key_info['fingerprint'];
    }
  }
}