I'm trying to set an encrypted file field's value programmatically. I'm using Encrypted Files module. I have successfully configured a file field, and it works for the contents created using the node add form.
In a custom code, I'm getting a file using the HttpClient
and want to attach to a media.
I could get the file, encyrpt and save it. However, if I want to open the file, it is broken.
What I'm doing is like the following:
$client = Drupal::httpClient();
// Get data from remote page and encrypt using the encryption profile
$data = (string) $client->get('https://example.com/download.php?file=123')
->getBody();
$encryptionProfile = Drupal::entityTypeManager()
->getStorage('encryption_profile')
->load('my_encryption_profile');
$encryptedData = Drupal::service('encryption')
->encrypt($data, $encryptionProfile);
// Create media entity and prepare destination directory
$media = Drupal::entityTypeManager()->getStorage('media')
->create(['bundle' => 'my_media_type']);
$destination = 'encrypt://my_encryption_profile/path/to/files'
Drupal::service('file_system')
->prepareDirectory($destination, FileSystemInterface::CREATE_DIRECTORY);
// Save data as file and attach to the media
$filename = 'download.pdf';
$file = file_save_data($encryptedData, $destination . '/' . $filename);
$media->set('encrypted_file', ['target_id' => $file->id()]);
$media->save();
encrypt
stream wrapper is a scheme wrapper which encrypts / decrypts automatically - so you're possibly doubling up by encrypting the data yourself$data
instead of$encryptedData
likefile_save_data($data, $destination . '/' . $filename)
, the file is saved without encryption and I can open it on the file system. Downloading the file over the stream wrapper still doesn't work.httpClient
and then saving it usingfile_save_data
. This was somehow skipping the scheme wrapper for whatever reason. That's why I was trying to encrypt it manually before saving. I changed the code and usedhttpClient
directly to download into the destination, and it worked without manually encrypting! I'll post the detailed solution in the next days as soon as I get some time.