You are here

function icon_archive_extract in Icon API 8

Same name and namespace in other branches
  1. 7 includes/utilities.inc \icon_archive_extract()

Extracts an uploaded archive file to the specified directory.

Parameters

string $file: The filepath or URI of the archive that should be extracted.

string $directory: The directory or URI the archive should extract into.

Return value

Archiver The Archiver object used to extract the archive.

1 call to icon_archive_extract()
icon_provider_import_form_validate in includes/import.inc
Validate callback for 'icon_provider_import_form'.

File

includes/utilities.inc, line 21
utilities.inc Provides useful functions and common tasks.

Code

function icon_archive_extract($file, $directory) {
  $archiver = archiver_get_archiver($file);
  if (!$archiver) {
    throw new Exception(t('Cannot extract %file, not a valid archive.', array(
      '%file' => $file,
    )));
  }
  $files = $archiver
    ->listContents();

  // Determine if archive lives in a wrapped directory matching filename.
  $info = pathinfo($file);
  $archiver->sub_directory = str_replace('.' . $info['extension'], '', $info['basename']);
  foreach ($files as $_file) {
    $pattern = '/^' . $archiver->sub_directory . '\\//';
    if (!preg_match($pattern, $_file)) {
      $archiver->sub_directory = FALSE;
      break;
    }
  }
  $extract_location = $directory;
  if ($archiver->sub_directory) {
    $extract_location .= '/' . $archiver->sub_directory;
  }
  if (file_exists($extract_location)) {
    file_unmanaged_delete_recursive($extract_location);
  }
  if (!file_prepare_directory($directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
    throw new Exception(t('Unable to extract the archive. Please check that your Drupal <a href="!file">file system</a> is correctly configured.', array(
      '!file' => \Drupal\Core\Url::fromRoute('system.file_system_settings'),
    )));
  }
  try {
    $archiver
      ->extract($directory);
  } catch (Exception $e) {

    // Close opened archive before trying to delete it.
    $archiver
      ->getArchive()
      ->close();
    if (file_exists($extract_location)) {
      file_unmanaged_delete_recursive($extract_location);
    }
    file_delete($file);
    throw new Exception($e
      ->getMessage());
  }
  return $archiver;
}