C# Class Pchp.Library.Streams.PhpStream

Abstraction of streaming behavior for PHP. PhpStreams are opened by StreamWrappers on a call to fopen().

PhpStream is a descendant of PhpResource, it contains a StreamContext (may be empty) and two ordered lists of StreamFilters (input and output filters). PhpStream may be cast to a .NET stream (using its RawStream property).

Various stream types are defined by overriding the Raw* methods that provide direct access to the underlying physical stream. Corresponding public methods encapsulate these accessors with buffering and filtering. Raw stream access is performed at the byte[] level. ClassLibrary functions may use either the Read/WriteBytes or Read/WriteString depending on the nature of the PHP function. Data are converted using the ApplicationConfiguration.GlobalizationSection.PageEncoding as necessary.

When reading from a stream, the stream data is read in binary format in chunks of predefined size (8kB). Stream filters (if any) are then applied in a cascade to the whole block. Filtered blocks are stored in a Queue of either strings or PhpBytes depending on the last filter output (note that after filtering not all blocks have necessarily the original chunk size; when appending a filter to the filter-chain all the buffered data is passed through this one too). The input queue is being filled until the required data length is available. The readPosition property holds the index into the first chunk of data. When this chunk is entirely consumed it is dequeued.

Writing to a stream is buffered too (unless it is disabled using stream_set_write_buffer). When the data passes through the filter-chain it is appended to the write buffer (using the writePosition property). When the write buffer is full it is flushed to the underlying stream.

Inheritance: Pchp.Core.PhpResource
Show file Open project: iolevel/peachpie Class Usage Examples

Public Properties

Property Type Description
OpenedPath string
Options StreamAccessOptions
Wrapper StreamWrapper

Protected Properties

Property Type Description
_context StreamContext
currentAccess FileAccess
fgetssState int
isPersistent bool
isReadBuffered bool
readBuffers Queue
readChunkSize int
readFilteredCount int
readFilters List
readOffset int
readPosition int
readTimeout double
textReadFilter IFilter
textWriteFilter IFilter
writeBuffer byte[]
writeBufferSize int
writeFilteredCount int
writeOffset int
writePosition int

Public Methods

Method Description
AddFilter ( IFilter filter, FilterChainOptions where ) : void

Adds a filter to one of the read or write filter chains.

CheckAccess ( string filename, CheckAccessMode mode, CheckAccessOptions options ) : bool

Performs all checks on a path passed to a PHP function.

This method performs a check similar to safe_mode.c: php_checkuid_ex() together with open_basedir check.

The filename may be one of the following: A relative path. The path is resolved regarding the include_path too if required and checking continues as in the next case. An absolute path. The file or directory is checked for existence and for access permissions1 according to the given mode. 1 Regarding the open_basedir configuration option. File access permissions are checked at the time of file manipulation (opening, copying etc.).

Flush ( ) : bool

Write all the output buffer to the underlying stream and flush it.

GetNextDataLength ( ) : int

Gets the number of bytes or characters in the first read-buffer or next chunk size.

GetValid ( PhpResource handle ) : PhpStream

Check that the resource handle contains a valid PhpStream resource and cast the handle to PhpStream.

GetValid ( PhpResource handle, FileAccess desiredAccess ) : PhpStream
Open ( Context ctx, string path, string mode ) : PhpStream
Open ( Context ctx, string path, string mode, StreamOpenOptions options ) : PhpStream
Open ( Context ctx, string path, string mode, StreamOpenOptions options, StreamContext context ) : PhpStream

Openes a PhpStream using the appropriate StreamWrapper.

PhpStream ( Context ctx, StreamWrapper openingWrapper, StreamAccessOptions accessOptions, string openedPath, StreamContext context ) : Pchp.Core

PhpStream is created by a StreamWrapper together with the encapsulated RawStream (the actual file opening is handled by the wrapper).

This class newly implements the auto-remove behavior too (see StreamAccessOptions.Temporary).

ReadBinaryContents ( int maxLength ) : byte[]
ReadBytes ( int length ) : byte[]

Reads binary data from the stream. First looks for data into the readBuffers. When length is not satisfied, new data from the underlying stream are processed.

ReadContents ( ) : TextElement
ReadContents ( int maxLength ) : TextElement
ReadContents ( int maxLength, int offset ) : TextElement
ReadData ( int length, bool ending ) : TextElement

Reads a block of data from the stream up to length characters or up to EOLN if length is negative.

ReadData first looks for data into the readBuffers. While length is not satisfied, new data from the underlying stream are processed. The data is buffered as either string or PhpBytes but consistently. The type of the first buffer thus specifies the return type.

ReadLine ( int length, string ending ) : string

Reads one line (text ending with the ending delimiter) from the stream up to length characters long.

ReadMaximumBytes ( ) : byte[]

Effecient access to the buffered and filtered stream consuming one whole buffer at a time.

ReadMaximumData ( ) : TextElement

Most effecient access to the buffered stream consuming one whole buffer at a time. Performs no unnecessary conversions (although attached stream filters may do so).

Use the readChunkSize member to affect the amount of data returned at a time.

ReadMaximumString ( ) : string

Effecient access to the buffered and filtered stream consuming one whole buffer at a time.

ReadString ( int length ) : string

Reads text data from the stream. First looks for data into the readBuffers. When length is not satisfied, new data from the underlying stream are processed.

ReadStringContents ( int maxLength ) : string
ResolvePath ( Context ctx, string &path, StreamWrapper &wrapper, CheckAccessMode mode, CheckAccessOptions options ) : bool

Merges the path with the current working directory to get a canonicalized absolute pathname representing the same file.

This method is an analogy of main/safe_mode.c: php_checkuid. Looks for the file in the include_path and checks for open_basedir restrictions.

Seek ( int offset, SeekOrigin whence ) : bool

Sets the read/write pointer in the stream to a new position.

SetParameter ( StreamParameterOptions option, PhpValue value ) : bool
Stat ( ) : StatStruct
Tell ( ) : int

Gets the current position in the stream.

The problem with tell() in PHP is that although the write offset is calculated in the raw byte stream (just before buffering) the read one is calculated in the filtered string buffers. In other words the value returned by tell() for output streams is the real position in the raw stream but may differ from the number of characters written. On the other hand the value returned for input streams corresponds with the number of characters retreived but not with the position in the raw stream. It is important to remember that seeking on a filtered stream (such as a file opened with a "rt" mode) has undefined behavior.

WriteBytes ( byte data ) : int

Apppends the binary data to the output buffer passing through the output filter-chain. When the buffer is full or buffering is disabled, pass the data to the low-level stream.

WriteString ( string data ) : int

Apppends the text data to the output buffer passing through the output filter-chain. When the buffer is full or buffering is disabled, pass the data to the low-level stream.

Protected Methods

Method Description
DropReadBuffer ( ) : bool

Remove the (entirely consumed) read buffer from the head of the read buffer queue.

FlushWriteBuffer ( ) : bool

Writes all the output buffer to the underlying stream.

FreeManaged ( ) : void

PhpResource.FreeManaged overridden to get rid of the contained context on Dispose.

FreeUnmanaged ( ) : void

PhpResource.FreeUnmanaged overridden to remove a temporary file on Dispose.

RawFlush ( ) : bool
RawLength ( ) : int

Gets the length of the stream.

RawRead ( byte buffer, int offset, int count ) : int
RawSeek ( int offset, SeekOrigin whence ) : bool
RawTell ( ) : int
RawWrite ( byte buffer, int offset, int count ) : int
ReadBinaryBuffer ( int length ) : byte[]

Joins the read buffers to get at least length bytes in a PhpBytes.

ReadFiltered ( int chunkSize ) : TextElement

Fills the readBuffers with more data from the underlying stream passed through all the stream filters.

ReadTextBuffer ( int length ) : string

Joins the read buffers to get at least length characters in a string.

It is assumed that there already is length bytes in the buffers. Otherwise an InvalidOperationException is raised.

WriteData ( TextElement data, bool closing = false ) : int

Passes the data through output filter-chain to the output buffer. When the buffer is full or buffering is disabled, passes the data to the low-level stream.

Private Methods

Method Description
CheckIncludePath ( Context ctx, string relativePath, string &absolutePath ) : bool

Check if the path lays inside of the directory tree specified by the open_basedir configuration option and return the resulting absolutePath.

EnqueueReadBuffer ( TextElement data ) : void

Put a buffer at the end of the readBuffers.

FindEoln ( TextElement data, int from ) : int

Finds the '\n' in a string or PhpBytes and returns its offset or -1 if not found.

GetSchemeInternal ( string path, string &filename ) : string

Checks if the given path is a filesystem path or an URL and returns the corresponding scheme.

Open ( Context ctx, string path, StreamOpenMode mode ) : PhpStream

Simple version of the stream opening function

ReadBufferScan ( int &nlpos ) : int
SeekInternal ( int offset, int current, SeekOrigin whence ) : bool

Perform the actual seek on the stream. Report errors.

SplitData ( TextElement data, int upto, TextElement &left, TextElement &right ) : void

Split a String or PhpBytes to "upto" bytes at left and the rest or null at right.

SplitData ( string s, int upto, string &left, string &right ) : void

Split a string to "upto" bytes at left and the rest or null at right.

TryUnlink ( ) : void

Method Details

AddFilter() public method

Adds a filter to one of the read or write filter chains.
public AddFilter ( IFilter filter, FilterChainOptions where ) : void
filter IFilter The filter.
where FilterChainOptions The position in the chain.
return void

CheckAccess() public static method

Performs all checks on a path passed to a PHP function.

This method performs a check similar to safe_mode.c: php_checkuid_ex() together with open_basedir check.

The filename may be one of the following: A relative path. The path is resolved regarding the include_path too if required and checking continues as in the next case. An absolute path. The file or directory is checked for existence and for access permissions1 according to the given mode. 1 Regarding the open_basedir configuration option. File access permissions are checked at the time of file manipulation (opening, copying etc.).

If the file can not be accessed /// and the is not set.
public static CheckAccess ( string filename, CheckAccessMode mode, CheckAccessOptions options ) : bool
filename string A resolved path. Must be an absolute path to a local file.
mode CheckAccessMode One of the .
options CheckAccessOptions true to suppress error messages.
return bool

DropReadBuffer() protected method

Remove the (entirely consumed) read buffer from the head of the read buffer queue.
protected DropReadBuffer ( ) : bool
return bool

Flush() public method

Write all the output buffer to the underlying stream and flush it.
public Flush ( ) : bool
return bool

FlushWriteBuffer() protected method

Writes all the output buffer to the underlying stream.
protected FlushWriteBuffer ( ) : bool
return bool

FreeManaged() protected method

PhpResource.FreeManaged overridden to get rid of the contained context on Dispose.
protected FreeManaged ( ) : void
return void

FreeUnmanaged() protected method

PhpResource.FreeUnmanaged overridden to remove a temporary file on Dispose.
protected FreeUnmanaged ( ) : void
return void

GetNextDataLength() public method

Gets the number of bytes or characters in the first read-buffer or next chunk size.
public GetNextDataLength ( ) : int
return int

GetValid() public static method

Check that the resource handle contains a valid PhpStream resource and cast the handle to PhpStream.
public static GetValid ( PhpResource handle ) : PhpStream
handle Pchp.Core.PhpResource A PhpResource passed to the PHP function.
return PhpStream

GetValid() public static method

public static GetValid ( PhpResource handle, FileAccess desiredAccess ) : PhpStream
handle Pchp.Core.PhpResource
desiredAccess FileAccess
return PhpStream

Open() public static method

public static Open ( Context ctx, string path, string mode ) : PhpStream
ctx Pchp.Core.Context
path string
mode string
return PhpStream

Open() public static method

public static Open ( Context ctx, string path, string mode, StreamOpenOptions options ) : PhpStream
ctx Pchp.Core.Context
path string
mode string
options StreamOpenOptions
return PhpStream

Open() public static method

Openes a PhpStream using the appropriate StreamWrapper.
public static Open ( Context ctx, string path, string mode, StreamOpenOptions options, StreamContext context ) : PhpStream
ctx Pchp.Core.Context Current runtime context.
path string URI or filename of the resource to be opened.
mode string A file-access mode as passed to the PHP function.
options StreamOpenOptions A combination of .
context StreamContext A valid StreamContext. Must not be null.
return PhpStream

PhpStream() public method

PhpStream is created by a StreamWrapper together with the encapsulated RawStream (the actual file opening is handled by the wrapper).
This class newly implements the auto-remove behavior too (see StreamAccessOptions.Temporary).
public PhpStream ( Context ctx, StreamWrapper openingWrapper, StreamAccessOptions accessOptions, string openedPath, StreamContext context ) : Pchp.Core
ctx Pchp.Core.Context Runtime context.
openingWrapper StreamWrapper The parent instance.
accessOptions StreamAccessOptions The additional options parsed from the fopen() mode.
openedPath string The absolute path to the opened resource.
context StreamContext The stream context passed to fopen().
return Pchp.Core

RawFlush() protected abstract method

protected abstract RawFlush ( ) : bool
return bool

RawLength() protected method

Gets the length of the stream.
protected RawLength ( ) : int
return int

RawRead() protected abstract method

protected abstract RawRead ( byte buffer, int offset, int count ) : int
buffer byte
offset int
count int
return int

RawSeek() protected method

protected RawSeek ( int offset, SeekOrigin whence ) : bool
offset int
whence SeekOrigin
return bool

RawTell() protected method

protected RawTell ( ) : int
return int

RawWrite() protected abstract method

protected abstract RawWrite ( byte buffer, int offset, int count ) : int
buffer byte
offset int
count int
return int

ReadBinaryBuffer() protected method

Joins the read buffers to get at least length bytes in a PhpBytes.
protected ReadBinaryBuffer ( int length ) : byte[]
length int The desired maximum result length.
return byte[]

ReadBinaryContents() public method

public ReadBinaryContents ( int maxLength ) : byte[]
maxLength int
return byte[]

ReadBytes() public method

Reads binary data from the stream. First looks for data into the readBuffers. When length is not satisfied, new data from the underlying stream are processed.
public ReadBytes ( int length ) : byte[]
length int The number of bytes to return.
return byte[]

ReadContents() public method

public ReadContents ( ) : TextElement
return TextElement

ReadContents() public method

public ReadContents ( int maxLength ) : TextElement
maxLength int
return TextElement

ReadContents() public method

public ReadContents ( int maxLength, int offset ) : TextElement
maxLength int
offset int
return TextElement

ReadData() public method

Reads a block of data from the stream up to length characters or up to EOLN if length is negative.
ReadData first looks for data into the readBuffers. While length is not satisfied, new data from the underlying stream are processed. The data is buffered as either string or PhpBytes but consistently. The type of the first buffer thus specifies the return type.
public ReadData ( int length, bool ending ) : TextElement
length int The number of bytes to return, when set to -1 /// reading carries on up to EOLN or EOF.
ending bool If true, the buffers are first searched for \n.
return TextElement

ReadFiltered() protected method

Fills the readBuffers with more data from the underlying stream passed through all the stream filters.
protected ReadFiltered ( int chunkSize ) : TextElement
chunkSize int Maximum number of bytes to be read from the stream.
return TextElement

ReadLine() public method

Reads one line (text ending with the ending delimiter) from the stream up to length characters long.
public ReadLine ( int length, string ending ) : string
length int Maximum length of the returned or -1 for unlimited reslut.
ending string Delimiter of the returned line or null to use the system default.
return string

ReadMaximumBytes() public method

Effecient access to the buffered and filtered stream consuming one whole buffer at a time.
public ReadMaximumBytes ( ) : byte[]
return byte[]

ReadMaximumData() public method

Most effecient access to the buffered stream consuming one whole buffer at a time. Performs no unnecessary conversions (although attached stream filters may do so).
Use the readChunkSize member to affect the amount of data returned at a time.
public ReadMaximumData ( ) : TextElement
return TextElement

ReadMaximumString() public method

Effecient access to the buffered and filtered stream consuming one whole buffer at a time.
public ReadMaximumString ( ) : string
return string

ReadString() public method

Reads text data from the stream. First looks for data into the readBuffers. When length is not satisfied, new data from the underlying stream are processed.
public ReadString ( int length ) : string
length int The number of characters to return.
return string

ReadStringContents() public method

public ReadStringContents ( int maxLength ) : string
maxLength int
return string

ReadTextBuffer() protected method

Joins the read buffers to get at least length characters in a string.
It is assumed that there already is length bytes in the buffers. Otherwise an InvalidOperationException is raised.
If the buffers don't contain enough data.
protected ReadTextBuffer ( int length ) : string
length int The desired maximum result length.
return string

ResolvePath() public static method

Merges the path with the current working directory to get a canonicalized absolute pathname representing the same file.
This method is an analogy of main/safe_mode.c: php_checkuid. Looks for the file in the include_path and checks for open_basedir restrictions.
Security violation - when the target file /// lays outside the tree defined by open_basedir configuration option.
public static ResolvePath ( Context ctx, string &path, StreamWrapper &wrapper, CheckAccessMode mode, CheckAccessOptions options ) : bool
ctx Pchp.Core.Context Current runtime context.
path string An absolute or relative path to a file.
wrapper StreamWrapper The wrapper found for the specified file or null if the path resolution fails.
mode CheckAccessMode The checking mode of the method (file, directory etc.).
options CheckAccessOptions Additional options for the method.
return bool

Seek() public method

Sets the read/write pointer in the stream to a new position.
public Seek ( int offset, SeekOrigin whence ) : bool
offset int The offset from the position denoted by .
whence SeekOrigin One of the flags.
return bool

SetParameter() public method

public SetParameter ( StreamParameterOptions option, PhpValue value ) : bool
option StreamParameterOptions
value Pchp.Core.PhpValue
return bool

Stat() public method

public Stat ( ) : StatStruct
return StatStruct

Tell() public method

Gets the current position in the stream.
The problem with tell() in PHP is that although the write offset is calculated in the raw byte stream (just before buffering) the read one is calculated in the filtered string buffers. In other words the value returned by tell() for output streams is the real position in the raw stream but may differ from the number of characters written. On the other hand the value returned for input streams corresponds with the number of characters retreived but not with the position in the raw stream. It is important to remember that seeking on a filtered stream (such as a file opened with a "rt" mode) has undefined behavior.
public Tell ( ) : int
return int

WriteBytes() public method

Apppends the binary data to the output buffer passing through the output filter-chain. When the buffer is full or buffering is disabled, pass the data to the low-level stream.
public WriteBytes ( byte data ) : int
data byte The to store.
return int

WriteData() protected method

Passes the data through output filter-chain to the output buffer. When the buffer is full or buffering is disabled, passes the data to the low-level stream.
protected WriteData ( TextElement data, bool closing = false ) : int
data TextElement The data to store (filters will handle the type themselves).
closing bool true when this method is called from close() /// to prune all the pending filters with closing set to true.
return int

WriteString() public method

Apppends the text data to the output buffer passing through the output filter-chain. When the buffer is full or buffering is disabled, pass the data to the low-level stream.
public WriteString ( string data ) : int
data string The to store.
return int

Property Details

OpenedPath public property

The absolute path to the resource.
public string OpenedPath
return string

Options public property

Additional stream options defined at open-time.
public StreamAccessOptions Options
return StreamAccessOptions

Wrapper public property

The StreamWrapper responsible for opening this stream.
Used for example to access the correct section of context and for wrapper-notifications too.
public StreamWrapper,Pchp.Library.Streams Wrapper
return StreamWrapper

_context protected property

The stream context options resource.
protected StreamContext,Pchp.Library.Streams _context
return StreamContext

currentAccess protected property

Gets the type of last stream access (initialized to FileAccess.ReadWrite if not accessed yet).
protected FileAccess currentAccess
return FileAccess

fgetssState protected property

For fgetss() to handle multiline tags.
protected int fgetssState
return int

isPersistent protected property

For future use. Persistent streams are not implemented so far.
protected bool isPersistent
return bool

isReadBuffered protected property

Whether the read operations are interated for a single fread call.
protected bool isReadBuffered
return bool

readBuffers protected property

Store the filtered input data queued as either strings or byte[].
protected Queue readBuffers
return Queue

readChunkSize protected property

The default size of a single read chunk in the readBuffers.
protected int readChunkSize
return int

readFilteredCount protected property

Total bytes passed through the ReadData function (after input filtering)
protected int readFilteredCount
return int

readFilters protected property

The lists of StreamFilters associated with this stream.
protected List readFilters
return List

readOffset protected property

The offset from the beginning of the raw stream to the first byte stored in the readBuffers.
This offset is incremented when a consumed buffer is dropped.
protected int readOffset
return int

readPosition protected property

The position in the first buffer in the readBuffers.
protected int readPosition
return int

readTimeout protected property

Timeout for network-based streams in seconds.
protected double readTimeout
return double

textReadFilter protected property

The text-mode conversion filter of this stream used for reading.
protected IFilter textReadFilter
return IFilter

textWriteFilter protected property

The text-mode conversion filter of this stream used for writing.
protected IFilter textWriteFilter
return IFilter

writeBuffer protected property

Store the filtered output data in a byte[] up to writeBufferSize bytes.
protected byte[] writeBuffer
return byte[]

writeBufferSize protected property

The maximum count of buffered output bytes. 0 to disable buffering.
protected int writeBufferSize
return int

writeFilteredCount protected property

Total bytes passed through the WriteData function (before output filtering)
protected int writeFilteredCount
return int

writeOffset protected property

The offset from the beginning of the raw stream to the first byte of the writeBuffer.
This offset is incremented when the buffer is being flushed or the data is written to a non-buffered stream.
protected int writeOffset
return int

writePosition protected property

The actual write position in the writeBuffer.
protected int writePosition
return int