Stream this file over HTTP

@return void
977189
public function outputWithHeaders($filename = 'output.xls')
    {
        \header("Expires: " . date("r", 0));
        \header("Last-Modified: " . gmdate("r") . " GMT");
        \header("Content-Type: application/x-msexcel");
        \header("Content-Disposition: attachment; filename=" . $filename);
        echo $this->__toString();
    }
892633
public function http()
    {
        $this->writeln('Starting swoole http server...');

        $server = new HttpServer(
            $this->swooleConfig['http']['host'] ?? self::DEFAULT_SWOOLE_HOST,
            $this->swooleConfig['http']['port'] ?? self::DEFAULT_SWOOLE_PORT
        );

        $server->on(
            'Request', function ($request, $response) {

                $swooleRequest = (new SwooleRequest())->setSwooleRequest($request);
                $swooleResponse = (new SwooleResponse())->setSwooleResponse($response);
                $sessionId = $swooleRequest->getCookie('swoole_session_id');
                if (!$sessionId) {
                    $sessionId = IdGenerator::component()->generate();
                    $swooleResponse->setCookie('swoole_session_id', $sessionId);
                }
                $swooleRequest->setSessionId($sessionId);
                $swooleResponse->setSessionId($sessionId);

                (new App($swooleRequest, $swooleResponse))->run();

            }
        );

        $server->start();
    }
189634
public function stream_close()
	{
		if ( !\is_resource($this->resource) )
		{
			return;
		}

		// Close the resource.
		if ( $this->resourceType === static::RESOURCE_TYPE_FILE )
		{
			\fclose( $this->resource );
		}
		else if ( $this->ssl )
		{
			\fclose( $this->resource );
			// Only save the file when not loaded locally.
			$saveFile = $this->getSaveFile();
			\file_put_contents( $saveFile, $this->content );
		}
		else if ( $this->resourceType === static::RESOURCE_TYPE_SOCKET )
		{
			// This could throw errors if the socket is not connected on some systems.
			@\socket_shutdown( $this->resource );
			\socket_close( $this->resource );
			// Only save the file when not loaded locally.
			$saveFile = $this->getSaveFile();
			\file_put_contents( $saveFile, $this->content );
		}

		// Leave the resource for garbage clean-up.
		$this->resource = NULL;

		// Reset so we do not overwrite a file unintentionally for the next request.
		static::clearSaveFile();
	}
1083593
private function setHeaders()
    {
        /*Execution Time unlimited*/
        set_time_limit(0);

        $fileSize = filesize($this->filePath);

        if ($fileSize === false) {
            throw new \Exception('Invalid path exception');
        }

        $_mimeType = $this->getMimeType();

        ob_start();
        header('Content-Description: File Transfer');
        header('Content-Type: '.$_mimeType);
        //header("Content-type: ".mime_content_type($value));
        header('Content-Disposition: attachment; filename='.rawurlencode(basename($this->filePath)));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: '.$fileSize);
        ob_clean();
        ob_end_flush();
        readfile($this->filePath);
    }
528497
public function exec()
    {
        $http = $this->argument('http');
        //
        $process = Router::get($http);
        //
        $this->show($process);
    }
127238
public function stream()
	{
		$fp = fopen("php://memory", 'r+');
		fwrite($fp, $this->_string);
		rewind($fp);
		return $fp;
	}
1053239
public function stream_close()
    {
        @fclose($this->temporaryFileHandle);
        
        // Upload the file?
        if ($this->writeMode) {
            // Make sure the container exists
            if (! $this->containerExists($this->fileName)) {
                $this->getStorageClient($this->fileName)->createContainer($this->getContainerName($this->fileName));
            }
            
            $mimeTypeGuesser = MimeTypeGuesser::getInstance();
            $createBlobOptions = new CreateBlobOptions();
            $createBlobOptions->setBlobContentType($mimeTypeGuesser->guess($this->temporaryFileName));
            
            // Upload the file
            try {
                $result = $this->getStorageClient($this->fileName)->createBlockBlob($this->getContainerName($this->fileName), $this->getFileName($this->fileName), fopen($this->temporaryFileName, "r"), $createBlobOptions);
            } catch (Exception $ex) {
                $this->cleanup();
                
                throw $ex;
            }
        }
        
        $this->cleanup();
    }
579335
public function send()
    {
        header(
            sprintf(
                'HTTP/1.1 %s %s',
                $this->statusCode,
                self::codeToReason($this->statusCode)
            )
        );
        foreach ($this->headers as $k => $v) {
            header(
                sprintf('%s: %s', $k, $v)
            );
        }
        echo $this->body;
    }
5699
public function stream_flush()
    {
        if ($this->fileHandle === null) {
            return false;
        }
        self::restore();
        $success = fflush($this->fileHandle);
        self::register();
        return $success;
    }
234459
public function actionReadFile()
	{
        $target_path = $this->get['path'];
		$target_fullpath = $this->getFullPath($target_path, true);
        Log::info('reading file "' . $target_fullpath . '"');

        if(is_dir($target_fullpath)) {
            $this->error('FORBIDDEN_ACTION_DIR');
        }

        // check if the name is not in "excluded" list
        if(!$this->is_allowed_name($target_fullpath, false)) {
            $this->error('INVALID_DIRECTORY_OR_FILE');
        }

		$filesize = filesize($target_fullpath);
		$length = $filesize;
		$context = null;

		if(isset($_SERVER['HTTP_RANGE'])) {
			if(!preg_match('/bytes=(\d+)-(\d+)?/', $_SERVER['HTTP_RANGE'], $matches)) {
				header('HTTP/1.1 416 Requested Range Not Satisfiable');
				header('Content-Range: bytes */' . $filesize);
				exit;
			}

			$offset = intval($matches[1]);

			if(isset($matches[2])) {
				$end = intval($matches[2]);
				if($offset > $end) {
					header('HTTP/1.1 416 Requested Range Not Satisfiable');
					header('Content-Range: bytes */' . $filesize);
					exit;
				}
				$length = $end - $offset;
			} else {
				$length = $filesize - $offset;
			}

			$bytes_start = $offset;
			$bytes_end = $offset + $length - 1;
			$context = stream_context_create([
				's3' => [
					'seekable' => true,
					'Range' => "bytes={$bytes_start}-{$bytes_end}",
				]
			]);

			header('HTTP/1.1 206 Partial Content');
			// A full-length file will indeed be "bytes 0-x/x+1", think of 0-indexed array counts
			header('Content-Range: bytes ' . $bytes_start . '-' . $bytes_end . '/' . $filesize);
			// While playing media by direct link (not via FM) FireFox and IE doesn't allow seeking (rewind) it in player
			// This header can fix this behavior if to put it out of this condition, but it breaks PDF preview
			header('Accept-Ranges: bytes');
		}

		header('Content-Type: ' . $this->getMimeType($target_fullpath));
		header("Content-Transfer-Encoding: binary");
		header("Content-Length: " . $length);
		header('Content-Disposition: inline; filename="' . basename($target_fullpath) . '"');

		readfile($target_fullpath, null, $context);
		exit;
	}
359668
public function stream_eof()
    {
        if ($this->fileHandle === null) {
            return false;
        }
        self::restore();
        $success = feof($this->fileHandle);
        self::register();
        return $success;
    }
545906
public function connect()
    {
        $this->host = $this->options['host'];
        $this->port = $this->options['port'];
        
        if (isset($this->options['clear']) && $this->options['clear']) {
            $this->stream = stream_socket_client(
                "tcp://{$this->host}:{$this->port}", $error, $error_msg, 10
            );
        } else {
            $options = array(
                'ssl' => array(
                    'verify_peer' => false
                )
            );
            if ($this->options['verify_cert']) {
                $options['ssl']['verify_peer'] = true;
                $options['ssl']['verify_depth'] = 5;
                $options['ssl']['cafile'] = \dirname(\dirname(__FILE__)).'/data/ca-certificates.crt';
            }
            $context = stream_context_create($options);
            $this->stream = stream_socket_client(
                "tls://{$this->host}:{$this->port}", $error, $error_msg, 10,
                STREAM_CLIENT_CONNECT, $context
            );
        }
        if ($this->stream) {
            $this->connected = true;
        } else {
            $error_msg = $error_msg ?: 'Peer certificate rejected';
            throw new NetworkException(
                "Unable to connect to {$this->host}:{$this->port} "
                ."(Error:{$error} {$error_msg})"
            );
        }
    }
971736
private function _serve_file()
    {
        // Set either the source or cache file as our datasource
        if ($this->serve_default) {
            $file_data = $this->source_file;
        } else {
            $file_data = $this->cached_file;
        }
        
        // Output the file
        $this->_output_file($file_data);
    }
526597
public function getStream()
    {
        if(!$this->stream)
            $this->stream = Stream::createFromPath($this->path);

        return $this->stream;
    }
239370
private function getStream() {

        if(!feof($this->loader->getFile())) {
            $this->stream .= fread($this->loader->getFile(), $this->loader->getBytes());
            return true;
        }

        return false;

    }
1299440
public function connect()
  {
    if($this->stream !== null) return;

    $host = strval($this->config["host"]);
    $port = strval($this->config["port"]);

    $address = "tcp://" . (strstr($host, ":") !== FALSE ? "[" . $host . "]" : $host) . ":" . $port;
    $options = empty($this->config["tls"]) ? array() : array("ssl" => array("allow_self_signed" => TRUE, "verify_peer" => FALSE, "verify_peer_name" => FALSE));
    $timeout = (int) $this->config["timeout"];

    $this->stream = @stream_socket_client($address, $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, stream_context_create($options));

    if($this->stream === FALSE)
    {
      throw new Exception(Str::factory($errstr)->toUtf8()->toString(), $errno);
    }

    if(!empty($this->config["tls"]))
    {
      stream_socket_enable_crypto($this->stream, TRUE, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
    }

    @stream_set_timeout($this->stream, $timeout);
    @stream_set_blocking($this->stream, $this->config["blocking"] ? 1 : 0);
  }
1322929
public function stream_flush()
    {
        if (!$this->getResource()) {
            return false;
        }

        $buffer = $this->getDataBuffer();
        $bufferWritten = $buffer;
        $retVal = true;
        if (!empty($buffer)) {

            $object = $this->getResource()->getObject();
            $mimetype = $this->getService()->guessFileType($this->getResource()->getResourceName());
            $object->content_type = $mimetype;
            $object->setData($buffer);
            $object->Create();
        }

       if (strlen($bufferWritten) ==  strlen($buffer)) {
            $this->setDataBuffer(null);
        } else {
            $this->setDataBuffer($buffer);
        }
        $this->setDataBuffer(null);

        return $retVal;
    }