Returns a HTTP Response ready to deliver a binary file

@param string $file
@param string $filename
@param string $disposition
@param string|null $mimeType
@param integer $cacheDuration
@return Response
194586
public function deliverFile($file, $filename = null, $disposition = DeliverDataInterface::DISPOSITION_INLINE, $mimeType = null, $cacheDuration = null)
    {
        return $this->getDeliverer()->deliverFile($file, $filename, $disposition, $mimeType, $cacheDuration);
    }
1295783
public function forceDownload($file)
    {
        session_write_close();
        ob_clean();
        header('Content-type: application/octet-stream');
        $filename = basename($file);
        header("Content-Disposition: attachment; filename=\"$filename\"");
        header('Content-Length: ' . filesize($file));
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: private", false);
        header("Content-Transfer-Encoding: binary");
        header("Content-Encoding: plainbinary");

        // This code isn't ready yet. It will allow us to no longer force download

        /*
        $h = Core::make('helper/mime');
        $mimeType = $h->mimeFromExtension($this->getExtension($file));
        header('Content-type: ' . $mimeType);
        */

        $buffer = '';
        $chunk = 1024 * 1024;
        $handle = fopen($file, 'rb');
        if ($handle === false) {
            return false;
        }
        while (!feof($handle)) {
            $buffer = fread($handle, $chunk);
            echo $buffer;
        }

        fclose($handle);
        exit;
    }
322787
public function response($path, $name = null, array $headers = [], $disposition = 'inline')
    {
        $response = new StreamedResponse;

        $disposition = $response->headers->makeDisposition($disposition, $name ?? basename($path));

        $response->headers->replace($headers + [
            'Content-Type' => $this->mimeType($path),
            'Content-Length' => $this->size($path),
            'Content-Disposition' => $disposition,
        ]);

        $response->setCallback(function () use ($path) {
            $stream = $this->readStream($path);
            fpassthru($stream);
            fclose($stream);
        });

        return $response;
    }
201137
protected function downloadResponse($file, $name = null, array $headers = array())
	{
		$response = new BinaryFileResponse($file, 200, $headers, true, 'attachment');

		if ($name !== null) {
			return $response->setContentDisposition('attachment', $name, Str::ascii($name));
		}

		return $response;
	}
1126078
public function uploadUrl($key, $acl, $mimeType = null, $cacheControl = null, $expires = null) {
		try {
			$optionsData = [
				'ACL' => $acl,
				'Bucket' => $this->bucket,
				'ContentType' => $mimeType,
				'Key' => $key
			];

			if(!empty($cacheControl)) {
				$optionsData[] = ['CacheControl' => $cacheControl];
			}

			if(!empty($expires)) {
				$optionsData[] = ['Expires' => $expires];
			}

			$putCommand = $this->client->getCommand('PutObject',$optionsData);
			$request = $this->client->createPresignedRequest($putCommand, '+20 minutes');
			$signedUrl = (string)$request->getUri();

			return new OtherS3UploadInfo($key,$signedUrl,$acl);
		}
		catch(AwsException $ex) {
			Logger::error('S3 Generate File Upload URL Error', ['exception' => $ex->getMessage()]);
			throw new StorageException($ex->getMessage(), $ex->getCode(), $ex);
		}
	}
79614
public final function output( int $quality = 60, string $filename = null )
   {

      \header( 'Expires: 0' );
      \header( 'Cache-Control: private' );
      \header( 'Pragma: cache' );

      if ( empty( $filename ) )
      {
         $filename = \basename( $this->_file );
      }
      else
      {
         $filename = \basename( $filename );
      }

      if ( ! empty( $filename ) )
      {
         \header( "Content-Disposition: inline; filename=\"{$filename}\"" );
         $mime = MimeTypeTool::GetByFileName( $filename );
         \header( "Content-Type: {$mime}" );
         switch ( $mime )
         {
            case 'image/png':
               \imagepng( $this->r );
               break;
            case 'image/gif':
               \imagegif( $this->r );
               break;
            default:
               \imagejpeg( $this->r, null, $quality );
               break;
         }
         exit;
      }

      \header( "Content-Type: {$this->mimeType}" );

      switch ( $this->mimeType )
      {
         case 'image/png':
            \imagepng( $this->r );
            break;
         case 'image/gif':
            \imagegif( $this->r );
            break;
         default:
            \imagejpeg( $this->r, null, $quality );
            break;
      }

      exit;

   }
470315
public function downloadAction(Request $request, SakonninFile $file, $access)
    {
        // TODO: Add access control.
        $path = $this->getFilePath();
        $response = new BinaryFileResponse($path . "/" . $file->getStoredAs());
        $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT);
        return $response;
    }
1344939
public function download(
        string $source,
        string $disk = null,
        string $customId = null,
        string $mimeType = null
    ): ?array {
        // TODO maybe we should add exceptions instead of returning null values?
        if ($customId) {
            if ($resource = $this->getRepository()->find($customId)) {
                return $resource->toArray();
            }
        }

        $fileName = $this->getFileName($source);

        if (!strlen($fileName)) {
            return null;
        }

        $this->createFolder('uploads/tmp', 'local');

        $destination = storage_path('app/uploads/tmp/' . $fileName);

        file_put_contents($destination, file_get_contents($source));

        if (filesize($destination) <= config('resources.max_checksum_size')) {
            $resource = $this->getRepository()->findOneBy(['checksum' => hash_file('sha256', $destination)]);

            if (!$this->allowDuplicates && $resource) {
                //If duplicate found deleting downloaded file
                unlink($destination);

                return $resource->toArray();
            }
        }

        if (!file_exists($destination)) {
            return null;
        }

        if (!$mimeType) {
            $mimeType = mime_content_type($destination);
        }

        $file = new UploadedFile($destination, $fileName, $mimeType, filesize($destination), null, true);

        return $this->upload($file, null, $disk, $customId);
    }
641902
protected function print_file($path, $mime_type, $file_name = ''){
		set_time_limit(0);
		if( !$file_name ){
			$file_name = basename($path);
		}
		foreach( array_merge(wp_get_nocache_headers(), [
			'Content-Type' => $mime_type,
		    'Content-Disposition' => sprintf('attachment; filename="%s"', $file_name),
		    'Content-Length' => filesize($path),
		]) as $header => $value){
			header("{$header}: {$value}");
		}
		readfile($path);
		exit;
	}
636141
static public function getMimeType($contentType, $filename=null)
    {
        if ($contentType = strtolower($contentType)) {
            if (strpos($contentType, '/') !== false) {
                $mimeTypes = array_keys(self::$mime_types, $contentType);
                $ext = $filename ? pathinfo($filename, PATHINFO_EXTENSION) : null;
                
                if (count($mimeTypes) === 1) {
                    return $mimeTypes[0];
                } elseif (count($mimeTypes) > 1) {
                    return $ext && in_array($ext, $mimeTypes) ? $ext : $mimeTypes[0];
                } else {
                    return $ext ? static::getMimeType($ext) : null;
                }
            } else {
                $ext = pathinfo($contentType, PATHINFO_EXTENSION);
                if (isset(static::$mime_types[$ext])) {
                    return $ext;
                }
            }
        } elseif ($filename) {
            return static::getMimeType($filename);
        }
        
        return null;
    }
48472
def get(self, attach, *args, **kwargs):
        
        response = self.make_response(*args, **kwargs)  # type: Response
        response.content_type = self.get_content_type(*args, **kwargs)

        if attach:
            filename = self.get_filename(*args, **kwargs)
            if not filename:
                filename = "file.bin"
            headers = response.headers
            headers.add("Content-Disposition", "attachment", filename=filename)

        self.set_cache_headers(response)
        return response
173872
public static function prepareAttachmentHeaders(
        ResponseInterface $response,
        ?string $filename = null
    ): ResponseInterface {
        $response = $response->withHeader('Content-Type', 'application/octet-stream')
            ->withHeader('Cache-Control', 'no-store, no-cache, must-revalidate')
            ->withHeader('Content-Transfer-Encoding', 'binary')
            ->withHeader('Content-Encoding', 'none');

        if ($filename !== null) {
            $response = $response->withHeader(
                'Content-Disposition',
                'attachment; filename*=utf-8\'\'' . rawurlencode($filename)
            );
        }

        return $response;
    }
188630
public function file(string $file, string $name = null, bool $download = true): ResponseInterface
    {
        if (!\is_file($file)) {
            throw new \LogicException("File '$file' doesn't exist.");
        }

        $extension = \substr($file, \strrpos($file, '.') + 1);
        $this->header->set('Content-Type',
            MimeType::getMimeType($extension) ?? 'application/octet-stream'
        );

        $disposition = $download ? Header::DISPOSITION_ATTACHMENT : Header::DISPOSITION_INLINE;
        $this->header->set('Content-Disposition',
            $this->header->makeDisposition($disposition, $name, \basename($file))
        );

        $size = $length = \filesize($file);

        $this->header->set('Accept-Ranges', 'bytes');
        if (\preg_match('#^bytes=(\d*)-(\d*)\z#', $this->request->header('Range'), $matches)) {
            list(, $start, $end) = $matches;

            if ($start === '') {
                $start = \max(0, $size - $end);
                $end = $size - 1;
            } elseif ($end === '' || $end > $size - 1) {
                $end = $size - 1;
            }

            if ($end < $start) {
                return $this->empty(416); // requested range not satisfiable
            }

            $this->setStatus(206);
            $this->header->set('Content-Range', 'bytes ' . $start . '-' . $end . '/' . $size);
            $length = $end - $start + 1;
        } else {
            $this->header->set('Content-Range', 'bytes 0-' . ($size - 1) . '/' . $size);
        }

        $this->header->set('Content-Length', $length);

        $this->app->emitter(
            $this->emitter ?? Emitter\SapiStream::class
        );

        return $this->response(
            Factory::streamFromFile($file, 'rb')
        );
    }
87254
private function createAttachment(
        string $file,
        string $content = null,
        string $contentType = null,
        string $disposition
    ): MimePart {
        $part = new MimePart;
        if ($content === null) {
            $content = @\file_get_contents($file); // @ is escalated to exception
            if ($content === false) {
                throw new FileNotFoundException("Unable to read file '$file'.");
            }
        }

        if (!$contentType) {
            $contentType = MimeType::getMimeTypeByContent($content);
        }

        if (!\strcasecmp($contentType, 'message/rfc822')) { // not allowed for attached files
            $contentType = 'application/octet-stream';
        } elseif (!\strcasecmp($contentType, 'image/svg')) { // Troublesome for some mailers...
            $contentType = 'image/svg+xml';
        }

        $part->setBody($content);
        $part->setContentType($contentType);
        $part->setEncoding(\preg_match('#(multipart|message)/#A', $contentType) ?
            self::ENCODING_8BIT : self::ENCODING_BASE64);
        $part->setHeader('Content-Disposition',
            $disposition . '; filename="' . Strings::fixEncoding(\basename($file)) . '"');

        return $part;
    }
116005
public function addFile(string $filename, string $name = null, string $mimeType = null): void
    {
        $attachment = new FileAttachment();
        $attachment->filename = $filename;
        if ($name !== null) {
            $attachment->name = $name;
        }
        if ($mimeType !== null) {
            $attachment->mimeType = $mimeType;
        }
        $this->set($attachment);
    }
301482
static function guessMimeType($fileName)
    {
        self::$map = include(__DIR__ . "/mime.types.php");
        $ext = pathinfo($fileName, PATHINFO_EXTENSION);
        return isset(self::$map[$ext]) ? self::$map[$ext] : 'application/octet-stream';
    }
403873
private function _deliver_zipfile($tmpfname, $filename)
    {
        $browser = new rcube_browser;
        $rcmail  = rcmail::get_instance();

        $rcmail->output->nocacheing_headers();

        if ($browser->ie)
            $filename = rawurlencode($filename);
        else
            $filename = addcslashes($filename, '"');

        // send download headers
        header("Content-Type: application/octet-stream");
        if ($browser->ie) {
            header("Content-Type: application/force-download");
        }

        // don't kill the connection if download takes more than 30 sec.
        @set_time_limit(0);
        header("Content-Disposition: attachment; filename=\"". $filename ."\"");
        header("Content-length: " . filesize($tmpfname));
        readfile($tmpfname);
    }