/** * Sends response to output. * @param IRequest $request * @param IResponse $response */ public function send(IRequest $request, IResponse $response) { // Set response headers for the file download $response->setHeader('Content-Length', $this->stream->getSize()); $response->setHeader('Content-Type', $this->contentType); $response->setHeader('Content-Disposition', 'attachment; filename="' . $this->name . '";'); while (!$this->stream->eof()) { echo $this->stream->read(4000000.0); } $this->stream->close(); }
public function tick() { do { $data = $this->psr7Stream->read(1024); $this->emit('data', [$data, $this]); } while ($data !== ''); if (!$this->psr7Stream->eof()) { $this->queueTick(); return; } $this->close(); }
/** * {@inheritdoc} */ public function read($length) { if ($this->tell() < 0) { throw new RuntimeException('Invalid pointer position'); } return $this->decoratedStream->read($length); }
/** * Move the uploaded file to a new location. * * Use this method as an alternative to move_uploaded_file(). This method is * guaranteed to work in both SAPI and non-SAPI environments. * Implementations must determine which environment they are in, and use the * appropriate method (move_uploaded_file(), rename(), or a stream * operation) to perform the operation. * * $targetPath may be an absolute path, or a relative path. If it is a * relative path, resolution should be the same as used by PHP's rename() * function. * * The original file or stream MUST be removed on completion. * * If this method is called more than once, any subsequent calls MUST raise * an exception. * * When used in an SAPI environment where $_FILES is populated, when writing * files via moveTo(), is_uploaded_file() and move_uploaded_file() SHOULD be * used to ensure permissions and upload status are verified correctly. * * If you wish to move to a stream, use getStream(), as SAPI operations * cannot guarantee writing to stream destinations. * * @see http://php.net/is_uploaded_file * @see http://php.net/move_uploaded_file * @param string $targetPath Path to which to move the uploaded file. * @throws \InvalidArgumentException if the $path specified is invalid. * @throws \RuntimeException on any error during the move operation, or on the second or subsequent call to the method. */ public function moveTo($targetPath) { if (!is_string($targetPath) || empty($targetPath)) { throw new \InvalidArgumentException('Invalid path while moving an uploaded file.', 1436717307); } if ($this->moved) { throw new \RuntimeException('Cannot move uploaded file, as it was already moved.', 1436717308); } // Check if the target path is inside the allowed paths of TYPO3, and make it absolute. $targetPath = GeneralUtility::getFileAbsFileName($targetPath); if (empty($targetPath)) { throw new \RuntimeException('Cannot move uploaded file, as it was already moved.', 1436717309); } if (!empty($this->file) && is_uploaded_file($this->file)) { if (GeneralUtility::upload_copy_move($this->file, $targetPath . basename($this->file)) === false) { throw new \RuntimeException('An error occurred while moving uploaded file', 1436717310); } } elseif ($this->stream) { $handle = fopen($targetPath, 'wb+'); if ($handle === false) { throw new \RuntimeException('Unable to write to target path.', 1436717311); } $this->stream->rewind(); while (!$this->stream->eof()) { fwrite($handle, $this->stream->read(4096)); } fclose($handle); } $this->moved = true; }
/** * Retrieve a single line from the stream. * * Retrieves a line from the stream; a line is defined as a sequence of * characters ending in a CRLF sequence. * * @param StreamInterface $stream * @return string * @throws UnexpectedValueException if the sequence contains a CR or LF in * isolation, or ends in a CR. */ protected static function getLine(StreamInterface $stream) { $line = ''; $crFound = false; while (!$stream->eof()) { $char = $stream->read(1); if ($crFound && $char === self::LF) { $crFound = false; break; } // CR NOT followed by LF if ($crFound && $char !== self::LF) { throw new UnexpectedValueException('Unexpected carriage return detected'); } // LF in isolation if (!$crFound && $char === self::LF) { throw new UnexpectedValueException('Unexpected line feed detected'); } // CR found; do not append if ($char === self::CR) { $crFound = true; continue; } // Any other character: append $line .= $char; } // CR found at end of stream if ($crFound) { throw new UnexpectedValueException("Unexpected end of headers"); } return $line; }
public function moveTo($targetPath) { if (!PHP_SAPI || PHP_SAPI == 'cli') { $handle = fopen($targetPath, Stream::MODE_READ_REPLACE); if ($handle === false) { throw new \RuntimeException('Unable to write to: ' . $targetPath); } $this->stream->rewind(); while (!$this->stream->eof()) { fwrite($handle, $this->stream->read(4096)); } fclose($handle); } else { if (move_uploaded_file($this->filePath, $targetPath) === false) { throw new \RuntimeException('Error moving uploaded file'); } } }
/** * Copy stream to another stream. * * @param StreamInterface $src Source stream. * @param StreamInterface $dest Target stream. * * @return void */ public static function copy(StreamInterface $src, StreamInterface $dest) { if ($src->isSeekable()) { $src->rewind(); } while (!$src->eof()) { $dest->write($src->read(4096)); } }
private function cropContent(StreamInterface $stream = null) { if (null === $stream) { return ''; } if ($stream->getSize() <= $this->maxBodySize) { return (string) $stream; } $stream->seek(0); return '(partial content)' . $stream->read($this->maxBodySize) . '(...)'; }
public function testReadAndWrite() { $this->assertEquals(0, $this->stream->getSize()); $this->stream->write("Hello World, And All Developers!"); $this->assertEquals(32, $this->stream->getSize()); // size $this->assertEquals(32, $this->stream->tell()); // pointer $this->stream->rewind(); $this->assertEquals(0, $this->stream->tell()); $this->assertFalse($this->stream->eof()); $this->assertEquals("Hell", $this->stream->read(4)); $this->assertEquals("o World, ", $this->stream->read(9)); $this->assertEquals("And All Developers!", $this->stream->getContents()); $this->assertTrue($this->stream->eof()); $this->stream->seek(12); $this->assertEquals(6, $this->stream->write('Hum...')); $this->assertEquals("ll Developers!", $this->stream->getContents()); $this->assertEquals("Hello World,Hum...ll Developers!", $this->stream->__toString()); }
/** * Write internal stream to given path * * @param string $path */ protected function writeFile($path) { $handle = fopen($path, Stream::MODE_READ_WRITE_RESET); if ($handle === false) { throw new \RuntimeException('Unable to write to path: ' . $path); } $this->stream->rewind(); while (!$this->stream->eof()) { fwrite($handle, $this->stream->read(4096)); } fclose($handle); }
/** * Write internal stream to given path * * @param string $path */ private function writeFile($path) { $handle = fopen($path, 'wb+'); if (false === $handle) { throw new RuntimeException('Unable to write to designated path'); } $this->stream->rewind(); while (!$this->stream->eof()) { fwrite($handle, $this->stream->read(4096)); } fclose($handle); }
/** * @param StreamInterface $stream * @param $header * @return int */ private function getLengthOfPossibleFilenameHeader(StreamInterface $stream, $header) { $filename_header_length = 0; if (substr(bin2hex($header), 6, 2) === '08') { // we have a filename, read until nil $filename_header_length = 1; while ($stream->read(1) !== chr(0)) { $filename_header_length++; } } return $filename_header_length; }
/** * Get the chars from the blob * * @param $n Number of characters needed * @return string|null */ public function getChars($n) { $response = null; // do we need more data? if ($this->strpos + $n - 1 >= strlen($this->str)) { $end = $this->strpos + $n; while (strlen($this->str) < $end && $response !== false) { // read more from the file handle $need = $end - $this->stream->tell(); if ($response = $this->stream->read($need)) { $this->str .= $response; } else { return null; } } } $result = substr($this->str, $this->strpos, $n); $this->strpos += $n; // we are dealing with bytes here, so force the encoding return $result; }
/** * Write the stream to the given path. * * @param StreamInterface $stream * @param string $path */ protected static function writeStream(StreamInterface $stream, $path) { $dir = dirname($path); if (!is_dir($dir)) { mkdir($dir, 0777, true); } $handle = fopen($path, 'wb+'); if (false === $handle) { throw new RuntimeException('Unable to write to designated path'); } $stream->rewind(); while (!$stream->eof()) { fwrite($handle, $stream->read(4096)); } fclose($handle); }
public function testReads() { $this->assertEquals('foo', $this->b->read(10)); }
/** * @param int $unused1 not used * @param int $unused2 not used * @param int $length amount of data to send to server * @return string */ public function read($unused1, $unused2, $length) { return $this->stream->read($length); }
protected function writeFileContents($file, StreamInterface $stream) { if (!$stream->isReadable()) { throw new \InvalidArgumentException('Resource content stream must be readable'); } $fp = Filesystem::openWriteStream($file, 'wb', 0755, LOCK_EX); try { while (!$stream->eof()) { fwrite($fp, $stream->read(4096)); } } finally { @fclose($fp); } }
/** * {@inheritdoc} */ public function read($length) { return $this->stream->read($length); }
public function it_reads_from_wrapped_stream(StreamInterface $stream) { $stream->read(3)->willReturn('123'); $this->read(null, null, 3)->shouldReturn('123'); }
/** * Sends Body. * * @param Psr\Http\Message\StreamInterface $body The body to send as stream * * @author Benjamin Carl <*****@*****.**> * @return void * @access protected */ protected function sendBody(Stream $body) { // I don't trust that this will be at the beginning of the stream, so reset. $body->rewind(); // writing to an arbitrary stream. // @todo Use stream operations to make this more robust and allow $bytes = 0; if ($bytes = $body->getSize() && $bytes < 500) { print $body->getContents(); } else { while (!$body->eof()) { $data = $body->read(1024); print $data; } } }
/** * Copy the contents of a stream into another stream until the given number * of bytes have been read. * * @param \Psr\Http\Message\StreamInterface $source Stream to read from * @param \Psr\Http\Message\StreamInterface $dest Stream to write to * @param int $maxLen Maximum number of bytes to read. Pass -1 * to read the entire stream. * * @throws \RuntimeException */ public static function copyToStream(StreamInterface $source, StreamInterface $dest, int $maxLen = -1) { if ($maxLen === -1) { while (!$source->eof()) { if (!$dest->write($source->read(1048576))) { break; } } return; } $bufferSize = 8192; if ($maxLen === -1) { while (!$source->eof()) { if (!$dest->write($source->read($bufferSize))) { break; } } } else { $remaining = $maxLen; while ($remaining > 0 && !$source->eof()) { $buf = $source->read(min($bufferSize, $remaining)); $len = strlen($buf); if (!$len) { break; } $remaining -= $len; $dest->write($buf); } } }
/** * addFile_from_Psr7Stream * * dds an open stream to the archive uncompressed * * @param String $name - path of file in archive (including directory). * @param Resource $stream - contents of file as a stream resource * @param array $opt - Hash of options for file (optional, see "File Options" below). * * File Options: * time - Last-modified timestamp (seconds since the epoch) of * this file. Defaults to the current time. * comment - Comment related to this file. * * Examples: * * // create a temporary file stream and write text to it * $fp = tmpfile(); * fwrite($fp, 'The quick brown fox jumped over the lazy dog.'); * * // add a file named 'streamfile.txt' from the content of the stream * $x->addFile_from_stream('streamfile.txt', $fp); * * @return void */ public function addFileFromPsr7Stream($name, \Psr\Http\Message\StreamInterface $stream, $opt = array()) { $name = $this->filterFilename($name); $block_size = 1048576; // process in 1 megabyte chunks $algo = 'crc32b'; $meth = static::METHOD_STORE; // calculate header attributes $stream->seek(0, SEEK_END); $zlen = $len = $stream->tell(); // send file header $hlen = $this->addFileHeader($name, $opt, $meth); // Stream data and calculate CRC32 $stream->rewind(); $hash_ctx = hash_init($algo); while (!$stream->eof()) { $data = $stream->read($block_size); hash_update($hash_ctx, $data); // send data $this->send($data); } $crc = hexdec(hash_final($hash_ctx)); // send file footer + CDR record $this->addFileFooter($name, $opt, $meth, $crc, $zlen, $len, $hlen); }
/** * Parse path to XML document/string content. * * @param resource $parser Parser. * @param StreamInterface $stream XML document stream. * @return AbstractSaxHandler $this Fluent interface. * * @throws \RuntimeException */ private function process($parser, StreamInterface $stream) { if ($stream->eof()) { $stream->rewind(); } while ($data = $stream->read($this->options['buffer_size'])) { xml_parse($parser, $data, $stream->eof()) || $this->onParseError(xml_error_string(xml_get_error_code($parser)), xml_get_error_code($parser), xml_get_current_line_number($parser)); } return $this; }
/** * {@inheritdoc} */ public function read($length) { return $this->decoratedStream->read($length); }
public function stream_read($count) { return $this->stream->read($count); }
/** * @param StreamInterface $stream * @return \Generator * @throws \OutOfBoundsException * @throws \Psr\Log\InvalidArgumentException * @throws \RuntimeException */ public function stream(StreamInterface $stream) : \Generator { while (!$stream->eof()) { $data = $stream->read($this->chunkSize); $output = $this->push($data); if ($output !== null) { (yield $output); } $this->checkSize(); } }
/** * Write a response to the connection as FCGI_STDOUT records. * * @param int $requestId The request id to write to * @param string $headerData The header data to write (including terminating CRLFCRLF) * @param StreamInterface $stream The stream to write */ private function writeResponse($requestId, $headerData, StreamInterface $stream) { $data = $headerData; $eof = false; $stream->rewind(); do { $dataLength = strlen($data); if ($dataLength < 65535 && !$eof && !($eof = $stream->eof())) { $readLength = 65535 - $dataLength; $data .= $stream->read($readLength); $dataLength = strlen($data); } $writeSize = min($dataLength, 65535); $writeData = substr($data, 0, $writeSize); $data = substr($data, $writeSize); $this->writeRecord($requestId, DaemonInterface::FCGI_STDOUT, $writeData); } while ($writeSize === 65535); $this->writeRecord($requestId, DaemonInterface::FCGI_STDOUT); }
private function outputBody(StreamInterface $body) { if ($this->chunkSize > 0) { if ($body->isSeekable()) { $body->rewind(); } while (!$body->eof()) { print $body->read($this->chunkSize); } } else { print (string) $body; } }
/** * Read a line from the stream up to the maximum allowed buffer length * * @param StreamInterface $stream Stream to read from * @param int $maxLength Maximum buffer length * * @return string|bool */ function readline(StreamInterface $stream, $maxLength = null) { $buffer = ''; $size = 0; while (!$stream->eof()) { // Using a loose equality here to match on '' and false. if (null == ($byte = $stream->read(1))) { return $buffer; } $buffer .= $byte; // Break when a new line is found or the max length - 1 is reached if ($byte === "\n" || ++$size === $maxLength - 1) { break; } } return $buffer; }
/** * * @param PsrStreamInterface $stream * @param int $maxLen * @return int */ public function writeFrom(PsrStreamInterface $stream, $maxLen = -1) { $bytes = 0; if ($this->isWritable() && $stream->isReadable()) { if ($maxLen < 0) { while (!$stream->eof()) { $data = $stream->read(1024); $bytes += $this->write($data); } } else { if ($maxLen > 0) { while (!$stream->eof() && $maxLen > 0) { $data = $stream->read($maxLen >= 1024 ? 1024 : $maxLen); $length = \strlen($data); $maxLen -= $length; $bytes += $this->write($data); } } } } return $bytes; }