Download an URL to the temporary directory.

@param string $url
@param string $temporaryDirectory

@throws \Concrete\Core\Error\UserMessageException in case of errors

@return string the local filename
179506
protected function downloadRemoteURL($url, $temporaryDirectory)
    {
        $client = $this->app->make('http/client');
        $request = $client->getRequest()->setUri($url);
        $response = $client->send();
        if (!$response->isSuccess()) {
            throw new UserMessageException(t(/*i18n: %1$s is an URL, %2$s is an error message*/'There was an error downloading "%1$s": %2$s', $url, $response->getReasonPhrase() . ' (' . $response->getStatusCode() . ')'));
        }
        $headers = $response->getHeaders();
        // figure out a filename based on filename, mimetype, ???
        $matches = null;
        if (preg_match('/^[^#\?]+[\\/]([-\w%]+\.[-\w%]+)($|\?|#)/', $request->getUri(), $matches)) {
            // got a filename (with extension)... use it
            $filename = $matches[1];
        } else {
            $contentType = $headers->get('ContentType')->getFieldValue();
            if ($contentType) {
                list($mimeType) = explode(';', $contentType, 2);
                $mimeType = trim($mimeType);
                // use mimetype from http response
                $extension = $this->app->make('helper/mime')->mimeToExtension($mimeType);
                if ($extension === false) {
                    throw new UserMessageException(t('Unknown mime-type: %s', h($mimeType)));
                }
                $filename = date('Y-m-d_H-i_') . mt_rand(100, 999) . '.' . $extension;
            } else {
                throw new UserMessageException(t(/*i18n: %s is an URL*/'Could not determine the name of the file at %s', $url));
            }
        }
        $fullFilename = $temporaryDirectory . '/' . $filename;
        // write the downloaded file to a temporary location on disk
        $handle = fopen($fullFilename, 'wb');
        fwrite($handle, $response->getBody());
        fclose($handle);

        return $fullFilename;
    }
756526
public function download($url, $directory)
    {
        coollect((array) $url)->each(function ($url) use ($directory) {
            $filename = basename($url);

            $destination = $this->toDir("{$directory}/{$filename}");

            $this->message("Downloading to {$destination}");

            $this->mkDir($directory);

            $this->downloadFile($url, $destination);
        });
    }
878584
def _DownloadUrl(self, url, dest_dir):
    
    dest_file = tempfile.NamedTemporaryFile(dir=dest_dir, delete=False)
    dest_file.close()
    dest = dest_file.name

    self.logger.info('Downloading url from %s to %s.', url, dest)
    try:
      urlretrieve.urlretrieve(url, dest)
      return dest
    except (httpclient.HTTPException, socket.error, urlerror.URLError) as e:
      self.logger.warning('Could not download %s. %s.', url, str(e))
    except Exception as e:
      self.logger.warning('Exception downloading %s. %s.', url, str(e))
    return None
721717
private function download(string $fileName, string $tempFilePath): self
    {
        $uri = 'https://github.com/pact-foundation/pact-ruby-standalone/releases/download/v' . self::VERSION . "/{$fileName}";

        $data = \file_get_contents($uri);

        if ($data === false) {
            throw new FileDownloadFailureException('Failed to download binary from Github for Ruby Standalone!');
        }

        $result = \file_put_contents($tempFilePath, $data);

        if ($result === false) {
            throw new FileDownloadFailureException('Failed to save binaries for Ruby Standalone!');
        }

        return $this;
    }
348878
protected function getTemporaryDirectory()
    {
        $result = $this->temporaryDirectory;
        if ($result === '') {
            $fileHelper = $this->app->make('helper/file');
            $temporaryDirectory = (string) $fileHelper->getTemporaryDirectory();
            if ($temporaryDirectory === '' || !$this->filesystem->isDirectory($temporaryDirectory)) {
                throw new UserMessageException(t('Unable to determine the temporary directory.'));
            }
            $this->temporaryDirectory = $temporaryDirectory;
        }

        return $this->temporaryDirectory;
    }
462798
public static function download($url, $output, $verbose=false) {
		$curl = curl_init($url);
		
		$folder = dirname($output);
		if(!is_dir($folder)) {
			mkdir($folder, 0755, true);
		}
		$file = fopen($output, "w");

		if($verbose == true) {
			curl_setopt($curl, CURLOPT_VERBOSE, true);
		}
		curl_setopt($curl, CURLINFO_HEADER_OUT, true);
		curl_setopt($curl, CURLOPT_FAILONERROR, true);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($curl, CURLOPT_FRESH_CONNECT, true);
		curl_setopt($curl, CURLOPT_FILE, $file);

		curl_exec($curl);
		if($verbose == true) {
			echo curl_getinfo($curl, CURLINFO_HEADER_OUT);
			echo "Saved to ".$output.".\n";
		}
		curl_close($curl);
		fclose($file);
	}
210584
def download_data(url:str, fname:PathOrStr=None, data:bool=True, ext:str='.tgz') -> Path:
    ""
    fname = Path(ifnone(fname, _url2tgz(url, data, ext=ext)))
    os.makedirs(fname.parent, exist_ok=True)
    if not fname.exists():
        print(f'Downloading {url}')
        download_url(f'{url}{ext}', fname)
    return fname
1270426
protected function downloadFile() {
		$content = @file_get_contents($this->url);
		if($content) {
			$this->tmp = \Yii::getAlias('@runtime' . DIRECTORY_SEPARATOR . md5($this->url) . '.' . pathinfo($this->url, PATHINFO_EXTENSION));
			file_put_contents($this->tmp, $content);
		}

		return $this->tmp;
	}
194474
public function makeDirectory($mode = FileSystemPermission::NORMAL)
    {
        $directoryId = $this->generateId();
        $path = sys_get_temp_dir() . '/' . $directoryId;
        $directory = new TemporaryDirectory($path, $mode);

        return $directory;
    }
297682
public function downloadAction()
    {
        if (null === $file = (new CmsFileQuery)->byObject($this->object, $this->objectId)
            ->findPk($this->id)) {
            return '';
        }
        $this->getResponse()->redirectToUrl($file->getUrl());
    }
1255383
static function getDownloadUrl($videoUrl) {
		$toplevelDomain = parse_url($videoUrl);
		$toplevelDomain = $toplevelDomain['host'];
		
		if (!is_dir(__DIR__ . DIRECTORY_SEPARATOR . 'ProviderHandler' . DIRECTORY_SEPARATOR . $toplevelDomain)) {
			throw new \Exception('There is no special implementation for the provider ' . $toplevelDomain . '!');
		}
		
		require_once __DIR__ . DIRECTORY_SEPARATOR . 'ProviderHandler' . DIRECTORY_SEPARATOR . $toplevelDomain . DIRECTORY_SEPARATOR . 'Provider.php';
		$provider = new \Provider($videoUrl);
		return $provider->getDownloadUrl();
	}
123863
public static function getPathFromUrl($url) {
        if (substr($url, 0, strlen(ROOT_URL)) != ROOT_URL) {
            throw new common_Exception($url.' does not lie within the tao instalation path');
        }
        $subUrl = substr($url, strlen(ROOT_URL));
        $parts = array();
        foreach (explode('/', $subUrl) as $directory) {
            $parts[] = urldecode($directory);
        }
        $path = ROOT_PATH.implode(DIRECTORY_SEPARATOR, $parts);
        if (self::securityCheck($path)) {
            return $path;
        } else {
            throw new common_Exception($url.' is not secure');
        }
    }
8342
public function temporaryUrl($path, $expiration, array $options = [])
    {
        $adapter = $this->driver->getAdapter();

        if ($adapter instanceof CachedAdapter) {
            $adapter = $adapter->getAdapter();
        }

        if (method_exists($adapter, 'getTemporaryUrl')) {
            return $adapter->getTemporaryUrl($path, $expiration, $options);
        } elseif ($adapter instanceof AwsS3Adapter) {
            return $this->getAwsTemporaryUrl($adapter, $path, $expiration, $options);
        } else {
            throw new RuntimeException('This driver does not support creating temporary URLs.');
        }
    }
741312
public static function getInstanceByRemote($url)
    {
        $validator = new UrlValidator();
        if ($validator->validate($url, $error)) {
            $url = str_replace("&amp;", "&", $url);
            $http = new Client();
            $response = $http->get($url)->send();
            if (!$response->isOk) {
                return null;
            } else {
                $baseName = basename($url);
                $tempPath = FileHelper::getTempFilePath($baseName);
                file_put_contents($tempPath, $response->content);
                return new static([
                    'isUploadedFile' => false,
                    'name' => $baseName,
                    'tempName' => $tempPath,
                    'type' => FileHelper::getMimeType($tempPath),
                    'size' => strlen($response->content),
                    'error' => UPLOAD_ERR_OK,
                ]);
            }
        } else {
            return null;
        }
    }
1241935
public static function temporaryRedirect($url, $externalRedirect = false) {
		/** @var Response $response */
		$response = new static();
		$response->redirect($url, $externalRedirect, self::HTTP_TEMPORARY_REDIRECT);
		return $response;
	}
372060
public function download($url, $pathToStore)
    {
        if (!URL::checkUrl($url)) {
            /**
             * The URL is not valid
             */
            throw new HttpUrlException(
                $this->translator->trans(
                    "Tried to download a file, but the URL was not valid: %url",
                    [
                        "%url" => $url
                    ]
                )
            );
        }

        /**
         * Try to get the file if it is online
         */
        $con = curl_init($url);
        curl_setopt($con, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($con, CURLOPT_FOLLOWLOCATION, true);

        $response = curl_exec($con);
        $errno = curl_errno($con);
        $curlErrorMessage = curl_error($con);

        $httpCode = curl_getinfo($con, CURLINFO_HTTP_CODE);

        curl_close($con);

        if (false === $response || $errno !== 0 ||
            ($httpCode != "200" && $httpCode != "204")
            ) {
            /**
             * The server is down ? The file doesn't exist ? Anything else ?
             */
            $errorMessage = $this->translator->trans(
                "cURL errno %errno, http code %http_code on link \"%path\": %error",
                [
                    "%errno" => $errno,
                    "%path" => $url,
                    "%error" => $curlErrorMessage,
                    "%http_code" => $httpCode,
                ]
            );

            $this->logger
                ->error($errorMessage)
            ;

            throw new FileNotFoundException($errorMessage);
        }

        /**
         * Inform that you've downloaded a file
         */
        $this->logger
            ->info(
                $this->translator->trans(
                    "The file %path has been successfully downloaded",
                    [
                        "%path" => $url
                    ]
                )
            )
        ;

        /**
         * Then try to write it on the disk
         */
        $file = @fopen($pathToStore, "w");

        if ($file === false) {
            $translatedErrorMessage = $this->translator->trans(
                "Failed to open a writing stream on the file: %file",
                [
                    "%file" => $pathToStore
                ]
            );

            $this->logger->error($translatedErrorMessage);
            throw new \ErrorException($translatedErrorMessage);
        }

        fputs($file, $response);
        fclose($file);
    }
1296147
static function downloadRemoteFile($url, $destinationFilename) {
		if (!ini_get('allow_url_fopen')) {
			throw new \Exception('allow_url_fopen is disable', 501);
		}

        $message = "File was not loaded";

		if (function_exists('curl_init')) {
		    try {
                $raw = file_get_contents($url);
            } catch (\Exception $e) {
                throw new \Exception($message, Consts::ERROR_CODE_BAD_REQUEST);
            }
		} else {
			$ch = curl_init($url);

			curl_setopt($ch, CURLOPT_HEADER, 0);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
			curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);// таймаут4

			$response = parse_url($url);
			curl_setopt($ch, CURLOPT_REFERER, $response['scheme'] . '://' . $response['host']);
			curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) ' .
                'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.99 YaBrowser/19.1.1.907 Yowser/2.5 Safari/537.36');


			$raw = curl_exec($ch);

            if (!$raw) {
                throw new \Exception($message, Consts::ERROR_CODE_BAD_REQUEST);
            }

            curl_close($ch);
        }

        if ($raw) {
            file_put_contents($destinationFilename, $raw);
        } else {
			throw new \Exception($message, Consts::ERROR_CODE_BAD_REQUEST);
		}
	}