You are here

function views_bulk_operations_archive_action in Views Bulk Operations (VBO) 7.3

Same name and namespace in other branches
  1. 6.3 archive.action.inc \views_bulk_operations_archive_action()
  2. 6 actions/archive.action.inc \views_bulk_operations_archive_action()

Since Drupal's Archiver doesn't abstract properly the archivers it implements (Archive_Tar and ZipArchive), it can't be used here.

File

actions/archive.action.inc, line 36
Provides an action for creating a zip archive of selected files.

Code

function views_bulk_operations_archive_action($file, $context) {
  global $user;
  static $archive_contents = array();

  // Adding a non-existent file to the archive crashes ZipArchive on close().
  if (file_exists($file->uri)) {
    $destination = $context['destination'];
    $zip = new ZipArchive();

    // If the archive already exists, open it. If not, create it.
    if (file_exists($destination)) {
      $opened = $zip
        ->open(drupal_realpath($destination));
    }
    else {
      $opened = $zip
        ->open(drupal_realpath($destination), ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE);
    }
    if ($opened) {

      // Create a list of all files in the archive. Used for duplicate checking.
      if (empty($archive_contents)) {
        for ($i = 0; $i < $zip->numFiles; $i++) {
          $archive_contents[] = $zip
            ->getNameIndex($i);
        }
      }

      // Make sure that the target filename is unique.
      $filename = _views_bulk_operations_archive_action_create_filename(basename($file->uri), $archive_contents);

      // Note that the actual addition happens on close(), hence the need
      // to open / close the archive each time the action runs.
      $zip
        ->addFile(drupal_realpath($file->uri), $filename);
      $zip
        ->close();
      $archive_contents[] = $filename;
    }
  }

  // The operation is complete, create a file entity and provide a download
  // link to the user.
  if ($context['progress']['current'] == $context['progress']['total']) {
    $archive_file = new stdClass();
    $archive_file->uri = $destination;
    $archive_file->filename = basename($destination);
    $archive_file->filemime = file_get_mimetype($destination);
    $archive_file->uid = $user->uid;
    $archive_file->status = $context['settings']['temporary'] ? FALSE : FILE_STATUS_PERMANENT;

    // Clear filesize() cache to avoid private file system differences in
    // filesize.
    // @see https://www.drupal.org/node/2743999
    clearstatcache();
    file_save($archive_file);
    $url = file_create_url($archive_file->uri);
    $url = l($url, $url, array(
      'absolute' => TRUE,
    ));
    _views_bulk_operations_log(t('An archive has been created and can be downloaded from: !url', array(
      '!url' => $url,
    )));
  }
}