You are here

function _photos_access_move_field_image in Album Photos 6.0.x

Same name and namespace in other branches
  1. 8.5 photos_access/photos_access.module \_photos_access_move_field_image()

Helper function to make sure file fields respect album privacy settings.

2 calls to _photos_access_move_field_image()
photos_access_filefield_paths_process_file in photos_access/photos_access.module
Implements hook_filefield_paths_process_file().
photos_access_photos_image_update in photos_access/photos_access.module
Implements hook_ENTITY_TYPE_update().

File

photos_access/photos_access.module, line 1227
Implementation of photos_access.module.

Code

function _photos_access_move_field_image(EntityInterface $entity, FileFieldItemList $field) {

  /** @var \Drupal\photos\Entity\PhotosImage $entity */
  $album_node = \Drupal::entityTypeManager()
    ->getStorage('node')
    ->load($entity
    ->getAlbumId());

  // Check album privacy settings.
  if (isset($album_node->photos_privacy) && isset($album_node->photos_privacy['viewid'])) {
    if ($album_node->photos_privacy['viewid'] != 0) {
      $file_system = \Drupal::service('file_system');

      // Check that the destination is writeable.
      $stream_wrapper_manager = \Drupal::service('stream_wrapper_manager');
      $wrappers = $stream_wrapper_manager
        ->getWrappers(StreamWrapperInterface::WRITE);
      if (PrivateStream::basePath() && !empty($wrappers['private'])) {

        // Make sure private scheme is used.
        $file_wrapper = 'private://';

        /** @var \Drupal\file\FileInterface $file */
        foreach ($field
          ->referencedEntities() as $file) {
          $old_file_wrapper = \Drupal::service('stream_wrapper_manager')
            ->getScheme($file
            ->getFileUri()) . '://';
          if ($old_file_wrapper != $file_wrapper) {
            $new_uri = str_replace($old_file_wrapper, $file_wrapper, $file
              ->getFileUri());
            $dirname = $file_system
              ->dirname($new_uri);
            $file_system
              ->prepareDirectory($dirname, FileSystemInterface::CREATE_DIRECTORY);
            file_move($file, $new_uri);
          }
        }
      }
      else {

        // Set warning that the file could not be moved to private.
        \Drupal::messenger()
          ->addWarning(t('Warning: image files can
          still be accessed by visiting the direct URL. For better security,
          ask your website admin to setup a private file path.'));
      }
    }
  }
}