Force Download
@param  String
@return Download
4336
public static function forceDownload($file)
    {
        if (isset($file)&&(file_exists($file))) {
           header("Content-length: ".filesize($file));  
           header('Content-Type: application/octet-stream');  
           header('Content-Disposition: attachment; filename="' . $file . '"'); 
           readfile($file);
        } else {
            echo "No file selected";
        }
    }
1340505
private function downloadFile()
    {
        /** @var ConfigModel $settings */
        $config = ImagerService::getConfig();

        // url encode filename to account for non-ascii characters in filenames.
        $imageUrlArr = explode('?', $this->url);

        $imageUrlArr[0] = preg_replace_callback('#://([^/]+)/([^?]+)#', function($match) {
            return '://'.$match[1].'/'.implode('/', array_map('rawurlencode', explode('/', $match[2])));
        }, urldecode($imageUrlArr[0]));

        $imageUrl = implode('?', $imageUrlArr);

        if (\function_exists('curl_init')) {
            $ch = curl_init($imageUrl);
            $fp = fopen($this->getFilePath(), 'wb');
            
            $defaultOptions = [
                CURLOPT_FILE => $fp,
                CURLOPT_HEADER => 0,
                CURLOPT_FOLLOWLOCATION => 1,
                CURLOPT_TIMEOUT => 30
            ];

            // merge default options with config setting, config overrides default.
            $options = $config->getSetting('curlOptions') + $defaultOptions;

            curl_setopt_array($ch, $options);
            curl_exec($ch);
            $curlErrorNo = curl_errno($ch);
            $curlError = curl_error($ch);
            $httpStatus = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            fclose(/** @scrutinizer ignore-type */ $fp);

            if ($curlErrorNo !== 0) {
                unlink($this->getFilePath());
                $msg = Craft::t('imager', 'cURL error “{curlErrorNo}” encountered while attempting to download “{imageUrl}”. The error was: “{curlError}”', ['imageUrl' => $imageUrl, 'curlErrorNo' => $curlErrorNo, 'curlError' => $curlError]);
                Craft::error($msg, __METHOD__);
                throw new ImagerException($msg);
            }

            if ($httpStatus !== 200) {
                if (!($httpStatus === 404 && strrpos(mime_content_type($this->getFilePath()), 'image') !== false)) { // remote server returned a 404, but the contents was a valid image file
                    unlink($this->getFilePath());
                    $msg = Craft::t('imager', 'HTTP status “{httpStatus}” encountered while attempting to download “{imageUrl}”', ['imageUrl' => $imageUrl, 'httpStatus' => $httpStatus]);
                    Craft::error($msg, __METHOD__);
                    throw new ImagerException($msg);
                }
            }
        } elseif (ini_get('allow_url_fopen')) {
            if (!@copy($imageUrl, $this->getFilePath())) {
                unlink($this->getFilePath());
                $errors = error_get_last();
                $msg = Craft::t('imager', 'Error “{errorType}” encountered while attempting to download “{imageUrl}”: {errorMessage}', ['imageUrl' => $imageUrl, 'errorType' => $errors['type'], 'errorMessage' => $errors['message']]);
                Craft::error($msg, __METHOD__);
                throw new ImagerException($msg);
            }
        } else {
            $msg = Craft::t('imager', 'Looks like allow_url_fopen is off and cURL is not enabled. To download external files, one of these methods has to be enabled.');
            Craft::error($msg, __METHOD__);
            throw new ImagerException($msg);
        }
    }
813917
public function download()
    {
        $download_path = parse_url($this->links['download_location'], PHP_URL_PATH);
        $download_query = parse_url($this->links['download_location'], PHP_URL_QUERY);
        $link = self::get($download_path . "?" . $download_query);
        $linkClass = \GuzzleHttp\json_decode($link->getBody());
        return $linkClass->url;
    }
598447
public function download($url)
    {
        $localPath = $this->makeLocalTemporaryPath();

        $url = $this->normalizeUrl($url);

        $this->downloadToTempLocalPath($url, $localPath);

        // Remove the query string if it exists, to make sure the extension is valid
        if (false !== strpos($url, '?')) {
            $url = explode('?', $url)[0];
        }

        $pathinfo = pathinfo($url);

        // If the file has no extension, rename the local instance with a guessed extension added.
        if (empty($pathinfo['extension'])) {
            $localPath = $this->renameLocalTemporaryFileWithAddedExtension($localPath, $pathinfo['basename']);
        }

        return $localPath;
    }
952953
public function download($url)
	{
		$getResult = $this->session->get($url);

		if (!$getResult->success) {
			$this->error = array();
			$this->error['file'] = 'Download error (HTTP status: ' . $getResult->status_code . ')';
			$this->error['http'] = $getResult->status_code;
			return null;
		}
		return $getResult->body;
	}
334009
private function forceRead($length)
    {
        $read = '';

        do {
            $read .= $this->stream->read($length - \strlen($read));
        } while (\strlen($read) < $length && !$this->stream->eof());

        return $read;
    }
981892
public function download($url, $target, $callback = null)
    {
        if (!$this->filesystem->fileExists($target)) {
            $this->filesystem->dirCreate(dir($target));

            $request = new Request($url, $callback ?: function ($response) {
            });

            $request->options['file'] = $target;

            $this->add($request);
        }

        return $this;
    }
1080942
function downloadZip($fileName, $contentType = "application/zip")
    {
        if (!$this->isFinalized) {
            $this->finalize();
        }

        $headerFile = null;
        $headerLine = null;
        if (!headers_sent($headerFile, $headerLine)) {
            if ((ob_get_contents() === FALSE || ob_get_contents() == '') or die("\n<p><strong>Error:</strong> Unable to send file <strong>$fileName.epub</strong>. Output buffer contains the following text (typically warnings or errors):<br>" . ob_get_contents() . "</p>")) {
                if (ini_get('zlib.output_compression')) {
                    ini_set('zlib.output_compression', 'Off');
                }

                header("Pragma: public");
                header("Last-Modified: " . gmdate("D, d M Y H:i:s T"));
                header("Expires: 0");
                header("Accept-Ranges: bytes");
                header("Connection: close");
                header("Content-Type: " . $contentType);
                header('Content-Disposition: attachment; filename="' . $fileName . '";');
                header("Content-Transfer-Encoding: binary");
                header("Content-Length: " . $this->getArchiveSize());

                if (!is_resource($this->zipFile)) {
                    echo $this->zipData;
                } else {
                    rewind($this->zipFile);

                    while (!feof($this->zipFile)) {
                        echo fread($this->zipFile, $this->streamChunkSize);
                    }
                }
            }
            return TRUE;
        }
        return FALSE;
    }
544268
public function forceCreate(): bool {
        if (!$this->isFile()) {
            return \mkdir($this->path, 0744, true);
        }
        if ($this->isFile() && !$this->isWritable()) {
            $user = \get_current_user();
            return \chown($this->path, $user);
        }
        return false;
    }
995933
function downloadAndImportPackage( $packageName, $packageUrl, $forceDownload = false )
    {
        $package = eZPackage::fetch( $packageName, false, false, false );

        if ( is_object( $package ) )
        {
            if ( $forceDownload )
            {
                $package->remove();
            }
            else
            {
                eZDebug::writeNotice( "Skipping download of package '$packageName': package already exists." );
                return $package;
            }
        }

        $archiveName = $this->downloadFile( $packageUrl, /* $outDir = */ eZStepSiteTypes::tempDir() );
        if ( $archiveName === false )
        {
            eZDebug::writeWarning( "Download of package '$packageName' from '$packageUrl' failed: $this->ErrorMsg" );
            $this->ErrorMsg = ezpI18n::tr( 'design/standard/setup/init',
                                      'Download of package \'%pkg\' failed. You may upload the package manually.',
                                      false, array( '%pkg' => $packageName ) );

            return false;
        }

        $package = eZPackage::import( $archiveName, $packageName, false );

        // Remove downloaded ezpkg file
        $ezFileHandler = new eZFileHandler();
        $ezFileHandler->unlink( $archiveName );

        if ( !$package instanceof eZPackage )
        {
            if ( $package == eZPackage::STATUS_INVALID_NAME )
            {
                eZDebug::writeNotice( "The package name $packageName is invalid" );
            }
            else
            {
                eZDebug::writeNotice( "Invalid package" );
            }

            $this->ErrorMsg = ezpI18n::tr( 'design/standard/setup/init', 'Invalid package' );
            return false;
        }

        return $package;
    }
145569
public function downloadFileFromURL($url)
    {
        $request     = new \Google_Http_Request($url, 'GET', null, null);
        $httpRequest = $this->service->getClient()
           ->getAuth()
           ->authenticatedRequest($request);
        if ($httpRequest->getResponseHttpCode() == 200) {
            return $httpRequest->getResponseBody();
        } else {
            // An error occurred.
            return null;
        }
    }
547015
public function download()
    {
        try{
            $this->checkIfTaskIdExists();

            $taskLogEntity = $this->getTaskLogService()->getByIdAndUser(
                $this->getRequestParameter(self::PARAMETER_TASK_ID),
                $this->getSessionUserUri()
            );

            if (!$taskLogEntity->getStatus()->isCompleted()) {
                throw new \common_Exception('Task "'. $taskLogEntity->getId() .'" is not downloadable.');
            }

            $fileNameOrSerial = $taskLogEntity->getFileNameFromReport();

            if (empty($fileNameOrSerial)) {
                throw new \common_Exception('Filename not found in report.');
            }

            // first try to get a referenced file is it is a serial
            $file = $this->getReferencedFile($fileNameOrSerial);

            // if no file let's try the task queue storage
            if (is_null($file)) {
                $file = $this->getQueueStorageFile($fileNameOrSerial);
            }

            if (!$file) {
                throw new \common_exception_NotFound('File not found.');
            }

            header('Set-Cookie: fileDownload=true');
            setcookie('fileDownload', 'true', 0, '/');
            header('Content-Disposition: attachment; filename="' . $file->getBasename() . '"');
            header('Content-Type: ' . $file->getMimeType());

            \tao_helpers_Http::returnStream($file->readPsrStream());
            exit();
        } catch (\Exception $e) {
            return $this->returnJson([
                'success' => false,
                'errorMsg' => $e instanceof \common_exception_UserReadableException ? $e->getUserMessage() : $e->getMessage(),
                'errorCode' => $e->getCode(),
            ]);
        }
    }
714017
@GET
  @Path("/download/{file}")
  public Response downloadFile(final @PathParam("file") String file) {
    Config config = createConfig();
    String uploadDir = config.getStringValue(FILE_SYSTEM_DIRECTORY);
    String filePath = uploadDir + "/" + file;
    return getResponseByFile(filePath);
  }
819976
public function download(File $file, Download $command)
    {
        try {
            $response = $this->api->get($file->url);
        } catch (\Exception $e) {
            throw new InvalidDownloadException($e->getMessage());
        }

        if ($response->getStatusCode() == 200) {
            $response = $this->mutateHeaders($response, $file);

            return $response;
        }
    }
499064
public function download($target, $alias = null)
    {
        $this->preload($target, $alias);

        // Count file size in bytes
        $size = filesize($target);

        // multipart-download and download resuming support
        if (isset($_SERVER['HTTP_RANGE'])) {

            list($a, $range) = explode("=", $_SERVER['HTTP_RANGE'], 2);
            list($range) = explode(",", $range, 2);
            list($range, $range_end) = explode("-", $range);

            $range = intval($range);

            if (!$range_end) {
                $range_end = $size - 1;
            } else {
                $range_end = intval($range_end);
            }

            $new_length = $range_end - $range + 1;

            $headers = array(
                'Content-Length' => $new_length,
                'Content-Range' => sprintf('bytes %s', $range - $range_end / $size)
            );

            $this->headerBag->setStatusCode(206)
                            ->setPairs($headers)
                            ->send();
        } else {

            $new_length = $size;
            $this->headerBag->appendPair('Content-Length', $size)
                            ->send()
                            ->clear();
        }

        $chunksize = 1024 * 1024;
        $bytes_send = 0;

        $target = fopen($target, 'r');

        if (isset($_SERVER['HTTP_RANGE'])) {
            fseek($target, $range);
        }

        while (!feof($target) && (!connection_aborted()) && ($bytes_send < $new_length)) {

            $buffer = fread($target, $chunksize);
            print($buffer);
            flush();
            $bytes_send += strlen($buffer);
        }

        fclose($target);
    }
373411
static function download($reqst = '')
    {
        //checando a existencia do arquivo solicitado
        $reqst = static::fileExists($reqst);
        if($reqst == false) return false;

        //gerando header apropriado
        include static::$config.'mimetypes.php';
        $ext = end((explode('.', $reqst)));
        if (!isset($_mimes[$ext])) $mime = 'text/plain';
        else $mime = (is_array($_mimes[$ext])) ? $_mimes[$ext][0] : $_mimes[$ext];

        //get file
        $dt = file_get_contents($reqst);

        //download
        ob_end_clean();
        ob_start('ob_gzhandler');

        header('Vary: Accept-Language, Accept-Encoding');
        header('Content-Type: ' . $mime);
        header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 31536000) . ' GMT');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($reqst)) . ' GMT');
        header('Cache-Control: must_revalidate, public, max-age=31536000');
        header('Content-Length: ' . strlen($dt));
        header('Content-Disposition: attachment; filename='.basename($reqst)); 
        header('ETAG: '.md5($reqst));
        exit($dt);
    }
1265036
protected static function _downloadCoverFile( $filename ) {
		$filepath = static::getCoversFolder() . $filename;
		\Pressbooks\Redirect\force_download( $filepath );
		exit;
	}