/**
  * Wrapper for file_get_file_references().
  *
  * @param \Drupal\file\FileInterface $file
  *   The file object for which to get references.
  *
  * @return array
  *   A multidimensional array. The keys are field_name, entity_type,
  *   entity_id and the value is an entity referencing this file.
  *
  * @see file_get_file_references()
  */
 protected function getFileReferences(FileInterface $file)
 {
     return file_get_file_references($file, NULL, EntityStorageInterface::FIELD_LOAD_REVISION, NULL);
 }
  /**
   * Define access control for the preview page.
   *
   * Deny users access to the preview page unless they have permission to edit
   * an entity (any entity) that references the current image being previewed or
   * if they've provide a valid token as a query string. The later is needed so
   * preview will work when creating a new entity that has not yet been saved.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   The current user.
   * @param int $fid
   *   The file id for the image being previewed from the URL.
   *
   * @return AccessResult
   *   An AccessResult object defining if permission is granted or not.
   */
  public function access(AccountInterface $account, $fid) {
    $access = AccessResult::forbidden();

    // @todo: I should be able to use "magic args" to load the file directly.
    $file = File::load($fid);
    $image = \Drupal::service('image.factory')->get($file->getFileUri());
    if (!$image->isValid()) {
      throw new InvalidArgumentException('The file with id = $fid is not an image.');
    }

    // Check if there was a valid token provided in with the HTTP request so
    // that preview is available on a "create entity" form.
    if ($this->validTokenProvided()) {
      $access = AccessResult::allowed();;
    }

    // If access has not yet been granted and the file module is enabled, check
    // if there is an entity that references this file which the current user
    // has access to edit.
    if (function_exists('file_get_file_references') && !$access->isAllowed()) {
      $references = file_get_file_references($file, NULL, EntityStorageInterface::FIELD_LOAD_REVISION, '');
      foreach ($references as $field_name => $data) {
        foreach (array_keys($data) as $entity_type_id) {
          if ($account->hasPermission($entity_type_id . ".edit")) {
            $access = AccessResult::allowed();
            break;
          }
        }
      }

    }

    return $access;
  }