You are here

public function AmazonS3StreamWrapper::dir_opendir in AmazonS3 7

Support for opendir().

Parameters

string $uri: A string containing the URI to the directory to open.

array $options: Unknown (parameter is not documented in PHP Manual).

Return value

bool TRUE on success.

Overrides StreamWrapperInterface::dir_opendir

See also

http://php.net/manual/en/streamwrapper.dir-opendir.php

File

./AmazonS3StreamWrapper.inc, line 918
Drupal stream wrapper implementation for Amazon S3

Class

AmazonS3StreamWrapper
@file Drupal stream wrapper implementation for Amazon S3

Code

public function dir_opendir($uri, $options = array()) {
  $this
    ->assertConstructorCalled();
  if ($uri === NULL) {
    return FALSE;
  }
  elseif (!$this
    ->_amazons3_is_dir($uri)) {
    return FALSE;
  }
  $this->dir = array();
  $path = $this
    ->getLocalPath($uri);
  $truncated = TRUE;
  $marker = '';
  if (strlen($path) === 0) {
    $prefix = $path;
  }
  else {
    $prefix = $path . '/';
  }
  $prefix_length = strlen($prefix);
  while ($truncated) {
    try {
      $response = $this
        ->getS3()
        ->list_objects($this->bucket, array(
        'delimiter' => '/',
        'prefix' => $prefix,
        'marker' => urlencode($marker),
      ));
      if ($response
        ->isOK()) {
        $this->dir[] = '.';
        $this->dir[] = '..';

        // Folders.
        if (isset($response->body->CommonPrefixes)) {
          foreach ($response->body->CommonPrefixes as $prefix) {
            $marker = substr($prefix->Prefix, $prefix_length, strlen($prefix->Prefix) - $prefix_length - 1);
            if (strlen($marker) > 0) {
              $this->dir[] = $marker;
            }
          }
        }

        // Files.
        if (isset($response->body->Contents)) {
          $contents = $response->body
            ->to_stdClass()->Contents;
          if (!is_array($contents)) {
            $contents = array(
              $contents,
            );
          }
          foreach ($contents as $content) {
            $key = $content->Key;
            if (substr_compare($key, '/', -1, 1) !== 0) {
              $marker = basename($key);
              $this->dir[] = $marker;
            }
          }
        }
        if (!isset($response->body->IsTruncated) || $response->body->IsTruncated
          ->__toString() === 'false') {
          $truncated = FALSE;
        }
      }
      else {
        return FALSE;
      }
    } catch (Exception $e) {
      watchdog('amazons3', 'Unable to open directory @path', array(
        '@path' => $prefix,
      ), WATCHDOG_NOTICE);
      return FALSE;
    }
  }
  return TRUE;
}