You are here

protected function ClipboardJsCommands::downloadFile in Clipboard.js 2.0.x

Same name and namespace in other branches
  1. 8 src/Commands/ClipboardJsCommands.php \Drupal\clipboardjs\Commands\ClipboardJsCommands::downloadFile()

Downloads a file.

Optionally uses user authentication, using either wget or curl, as available.

Parameters

string $url: The URL to download.

string $user: The username for authentication.

string $password: The password for authentication.

string $destination: The destination folder to copy the download to.

bool $overwrite: Whether to overwrite an existing destination folder.

Return value

string The destination folder.

Throws

\Exception

1 call to ClipboardJsCommands::downloadFile()
ClipboardJsCommands::downloadLibrary in src/Commands/ClipboardJsCommands.php
Download and extract a library.

File

src/Commands/ClipboardJsCommands.php, line 115

Class

ClipboardJsCommands
Drush commandfile.

Namespace

Drupal\clipboardjs\Commands

Code

protected function downloadFile($url, $user = '', $password = '', $destination = '', $overwrite = TRUE) {
  static $use_wget;
  if ($use_wget === NULL) {
    $use_wget = ExecTrait::programExists('wget');
  }
  $destination_tmp = drush_tempnam('download_file');
  if ($use_wget) {
    $args = [
      'wget',
      '-q',
      '--timeout=30',
    ];
    if ($user && $password) {
      $args = array_merge($args, [
        "--user={$user}",
        "--password={$password}",
        '-O',
        $destination_tmp,
        $url,
      ]);
    }
    else {
      $args = array_merge($args, [
        '-O',
        $destination_tmp,
        $url,
      ]);
    }
  }
  else {
    $args = [
      'curl',
      '-s',
      '-L',
      '--connect-timeout 30',
    ];
    if ($user && $password) {
      $args = array_merge($args, [
        '--user',
        "{$user}:{$password}",
        '-o',
        $destination_tmp,
        $url,
      ]);
    }
    else {
      $args = array_merge($args, [
        '-o',
        $destination_tmp,
        $url,
      ]);
    }
  }
  $process = Drush::process($args);
  $process
    ->mustRun();
  if (!$this
    ->getConfig()
    ->simulate()) {
    if (!drush_file_not_empty($destination_tmp) && ($file = @file_get_contents($url))) {
      @file_put_contents($destination_tmp, $file);
    }
    if (!drush_file_not_empty($destination_tmp)) {

      // Download failed.
      throw new \Exception(dt("The URL !url could not be downloaded.", [
        '!url' => $url,
      ]));
    }
  }
  if ($destination) {
    \Drupal::service('file_system')
      ->move($destination_tmp, $destination, $overwrite);
    return $destination;
  }
  return $destination_tmp;
}