You are here

public function AcquiaDAMStreamWrapper::stream_stat in Media: Acquia DAM 7

Support for fstat().

Overrides DrupalRemoteStreamWrapper::stream_stat

File

includes/AcquiaDAMStreamWrapper.inc, line 53
Create an Acquia DAM Stream Wrapper class for the Media/Resource module.

Class

AcquiaDAMStreamWrapper
Provides a remote stream wrapper for Acquia DAM assets.

Code

public function stream_stat() {
  $stat = [];

  // Skip looking up the size if we already have it stored locally.
  // If we don't do this then file listing pages can issue several requests
  // and have a delay in loading.
  $files = entity_load('file', FALSE, [
    'uri' => $this->uri,
  ]);
  $file = !empty($files) ? reset($files) : FALSE;
  if (!empty($file->filesize)) {
    $stat = [
      'size' => $file->filesize,
    ];
  }
  else {

    // If the asset has an overall large size then we skip trying to get the
    // accurate size of the specific URL we're referencing. This comes into
    // play when the source image or video might be 15MB but we're trying to
    // render a thumbnail.
    $asset = $this
      ->getAssetByUri($this->uri);

    // Filesize can be '0.00' which will count as not empty, so we have to
    // check the size is greater than 0 as well.
    if (!empty($asset['filesize']) && 0 < $asset['filesize']) {
      $stat['size'] = $asset['filesize'] * 1024 * 1024;
    }
    else {

      // Translate our acquiadam:// uri into a remote URL before we make the
      // request.
      $uri = file_create_url($this->uri);
      $scheme = file_uri_scheme($uri);
      if (empty($scheme)) {
        $uri = url($uri, [
          'absolute' => TRUE,
        ]);
      }

      // We have to use a GET request here instead of HEAD because the
      // download links we receive are not valid for a HEAD-type request and
      // will return a 403.
      $request = drupal_http_request($uri, [
        'method' => 'GET',
      ]);
      if (empty($request->error) && isset($request->headers['content-length'])) {
        $stat['size'] = $request->headers['content-length'];
      }
      elseif (!empty($request->error)) {
        watchdog('media_acquiadam', '(@code) Error fetching asset size: @error', [
          '@code' => $request->code,
          '@error' => $request->error,
        ], WATCHDOG_NOTICE, l(t('View'), $uri));
      }
    }
  }
  return !empty($stat) ? $this
    ->getStat($stat) : FALSE;
}