Пример #1
0
        public static int file_put_contents(Context ctx, string path, PhpValue data, WriteContentsOptions flags = WriteContentsOptions.Empty, PhpResource context = null)
        {
            StreamContext sc = StreamContext.GetValid(context, true);

            if (sc == null)
            {
                return(-1);
            }

            string mode = (flags & WriteContentsOptions.AppendContents) > 0 ? "ab" : "wb";

            using (PhpStream to = PhpStream.Open(ctx, path, mode, ProcessOptions(ctx, (FileOpenOptions)flags), sc))
            {
                if (to == null)
                {
                    return(-1);
                }

                // passing array is equivalent to file_put_contents($filename, join('', $array))
                var array = data.ArrayOrNull();
                if (array != null)
                {
                    int total = 0;

                    var enumerator = array.GetFastEnumerator();
                    while (enumerator.MoveNext())
                    {
                        int written = to.WriteBytes(enumerator.CurrentValue.ToBytes(ctx));
                        if (written == -1)
                        {
                            return(total);
                        }
                        total += written;
                    }

                    return(total);
                }

                // as of PHP 5.1.0, you may also pass a stream resource to the data parameter
                var resource = data.AsResource();
                if (resource != null)
                {
                    PhpStream from = PhpStream.GetValid(resource);
                    if (from == null)
                    {
                        return(-1);
                    }

                    return(PhpStreams.stream_copy_to_stream(from, to));
                }

                return(to.WriteBytes(data.ToBytes(ctx)));
            }
        }
Пример #2
0
        /// <summary>
        /// Check input parameters, resolves absolute path and corresponding stream wrapper.
        /// </summary>
        /// <param name="ctx">Runtime context.</param>
        /// <param name="path">The path passed to stat().</param>
        /// <param name="quiet">Wheter to suppress warning message if argument is empty.</param>
        /// <param name="wrapper">If passed, it will contain valid StremWrapper to the given <paramref name="path"/>.</param>
        /// <returns>True if check passed.</returns>
        internal static bool ResolvePath(Context ctx, ref string path, bool quiet, out StreamWrapper wrapper)
        {
            if (string.IsNullOrEmpty(path))
            {
                wrapper = null;
                PhpException.Throw(PhpError.Warning, Resources.LibResources.arg_empty, nameof(path));
                return(false);
            }

            return(PhpStream.ResolvePath(ctx, ref path, out wrapper, CheckAccessMode.FileOrDirectory, quiet ? CheckAccessOptions.Quiet : CheckAccessOptions.Empty));
        }
Пример #3
0
        public override PhpStream Open(Context ctx, ref string path, string mode, StreamOpenOptions options, StreamContext context)
        {
            int level       = -1;
            var deflateMode = DeflateFilterMode.Normal;

            #region Parse mode options
            // PHP just looks whether there are mode flags in the mode string (skip the first character)
            // last flag is the valid one

            for (int i = 1; i < mode.Length; i++)
            {
                if (Char.IsDigit(mode[i]))
                {
                    level = mode[i] - '0';
                }
                else if (mode[i] == 'f')
                {
                    deflateMode = DeflateFilterMode.Filter;
                }
                else if (mode[i] == 'h')
                {
                    deflateMode = DeflateFilterMode.Huffman;
                }
            }

            #endregion

            #region Path correction

            if (path.StartsWith("compress.zlib://"))
            {
                path = path.Substring(16);
            }
            else if (path.StartsWith("zlib:"))
            {
                path = path.Substring(5);
            }

            #endregion

            var stream = PhpStream.Open(ctx, path, mode, options);

            if (stream != null && stream.CanRead)
            {
                stream.AddFilter(new GzipUncompressionFilter(), FilterChainOptions.Read);
            }

            if (stream != null && stream.CanWrite)
            {
                stream.AddFilter(new GzipCompresionFilter(level, deflateMode), FilterChainOptions.Write);
            }

            return(stream);
        }
Пример #4
0
        /// <summary>
        /// filters (array)
        /// - array containing the names of any filters that have been stacked onto this stream.
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        static PhpArray GetFiltersName(PhpStream /*!*/ stream)
        {
            var array = new PhpArray();

            foreach (PhpFilter f in stream.StreamFilters)
            {
                array.Add(f.FilterName);
            }

            return(array);
        }
Пример #5
0
        public static bool RemoveDirectory(string dirname, StreamContext context)
        {
            StreamWrapper wrapper;

            if (!PhpStream.ResolvePath(ref dirname, out wrapper, CheckAccessMode.Directory, CheckAccessOptions.Empty))
            {
                return(false);
            }

            return(wrapper.RemoveDirectory(dirname, StreamRemoveDirectoryOptions.Empty, StreamContext.Default));
        }
Пример #6
0
        /// <summary>
        /// Open stream using working directory and PHP include directories.
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        internal static System.IO.Stream OpenStream(string filename)
        {
            PhpStream stream = PhpStream.Open(filename, "rb", StreamOpenOptions.Empty, StreamContext.Default);

            if (stream == null)
            {
                return(null);
            }

            return(stream.RawStream);
        }
Пример #7
0
        public static PhpString stream_get_contents(PhpResource handle, int maxLength = -1, int offset = -1)
        {
            var stream = PhpStream.GetValid(handle, FileAccess.Read);

            if (stream == null)
            {
                return(default(PhpString));
            }

            return(stream.ReadContents(maxLength, offset).ToPhpString());
        }
Пример #8
0
        /// <summary>
        /// Gets information about a file using an open file pointer.
        /// </summary>
        /// <param name="handle"></param>
        /// <returns></returns>
        public static PhpArray fstat(PhpResource handle)
        {
            // Note: no cache here.
            PhpStream stream = PhpStream.GetValid(handle);

            if (stream == null)
            {
                return(null);
            }
            return(BuildStatArray(stream.Stat()));
        }
Пример #9
0
        /// <summary>
        /// Retrieves remote_file from the FTP server, and writes it to the given file pointer.
        /// </summary>
        /// <param name="ftp_stream">The link identifier of the FTP connection.</param>
        /// <param name="handle">An open file pointer in which we store the data.</param>
        /// <param name="remotefile">The remote file path.</param>
        /// <param name="mode">The transfer mode. Must be either FTP_ASCII or FTP_BINARY.</param>
        /// <param name="resumepos">The position in the remote file to start downloading from.</param>
        /// <returns>Returns TRUE on success or FALSE on failure.</returns>
        public static bool ftp_fget(PhpResource ftp_stream, PhpResource handle, string remotefile, int mode = FTP_IMAGE, int resumepos = 0)
        {
            // Check file resource
            var stream = PhpStream.GetValid(handle);

            if (stream == null)
            {
                return(false);
            }

            // Check ftp_stream resource
            var resource = ValidateFtpResource(ftp_stream);

            if (resource == null)
            {
                return(false);
            }

            resource.Client.DownloadDataType = (mode == FTP_ASCII) ? FtpDataType.ASCII : FtpDataType.Binary;

            // Ignore autoresume if autoseek is switched off
            if (resource.Autoseek && resumepos == FTP_AUTORESUME)
            {
                resumepos = 0;
            }

            if (resource.Autoseek && resumepos != 0)
            {
                if (resumepos == FTP_AUTORESUME)
                {
                    stream.Seek(0, SeekOrigin.End);
                    resumepos = stream.Tell();
                }
                else
                {
                    stream.Seek(resumepos, SeekOrigin.Begin);
                }
            }

            try
            {
                return(resource.Client.Download(stream.RawStream, remotefile, resumepos));
            }
            catch (FtpException ex)
            {
                PhpException.Throw(PhpError.Warning, ex.InnerException.Message);
            }
            catch (ArgumentException ex)
            {
                PhpException.Throw(PhpError.Warning, Resources.Resources.file_not_exists, ex.ParamName);
            }

            return(false);
        }
Пример #10
0
        public object loadHTMLFile(string sourceFile)
        {
            using (PhpStream stream = PhpStream.Open(sourceFile, "rt"))
            {
                if (stream == null)
                {
                    return(false);
                }

                return(loadHTML(new StreamReader(stream.RawStream), sourceFile));
            }
        }
Пример #11
0
        /// <summary>
        /// Check input parameters, resolves absolute path and corresponding stream wrapper.
        /// </summary>
        /// <param name="ctx">Runtime context.</param>
        /// <param name="path">The path passed to stat().</param>
        /// <param name="quiet">Wheter to suppress warning message if argument is empty.</param>
        /// <param name="wrapper">If passed, it will contain valid StremWrapper to the given <paramref name="path"/>.</param>
        /// <returns>True if check passed.</returns>
        static bool ResolvePath(Context ctx, ref string path, bool quiet, out StreamWrapper wrapper)
        {
            if (string.IsNullOrEmpty(path))
            {
                wrapper = null;
                //PhpException.Throw(PhpError.Warning, LibResources.GetString("arg:empty", "path"));
                //return false;
                throw new ArgumentException(nameof(path));
            }

            return(PhpStream.ResolvePath(ctx, ref path, out wrapper, CheckAccessMode.FileOrDirectory, quiet ? CheckAccessOptions.Quiet : CheckAccessOptions.Empty));
        }
        public virtual string file(string file_name = null, int options = PhpFileInfo.FILEINFO_NONE, PhpResource context = null)
        {
            byte[] bytes;

            using (var stream = PhpStream.Open(_ctx, file_name, "rb" /*ReadBinary*/, StreamOpenOptions.Empty, StreamContext.GetValid(context, allowNull: true)))
            {
                bytes = stream?.ReadBytes(FileType.MaxHeaderSize);
            }

            // TODO: options
            return(FileType.LookupFileTypes(bytes).FirstOrDefault()?.Mime);
        }
Пример #13
0
        private void Clear()
        {
            _memoryStream = null;
            _uriPhpStream?.Dispose();
            _uriPhpStream = null;
            _writer?.Dispose();
            _writer = null;

            _state              = new Stack <State>(2);
            _dtdStart           = false;
            _unclosedNodesCount = 0;
        }
Пример #14
0
        /// <summary>Adds <paramref name="filter"/> to the list of filters attached to <paramref name="stream"/>.</summary>
        /// <param name="stream">The target stream.</param>
        /// <param name="filter">The filter name.</param>
        /// <param name="read_write">Combination of the <see cref="FilterChainOptions"/> flags.</param>
        /// <param name="parameters">Additional parameters for a user filter.</param>
        public static bool stream_filter_prepend(PhpResource stream, string filter, FilterChainOptions read_write, PhpValue parameters)
        {
            var s = PhpStream.GetValid(stream);

            if (s == null)
            {
                return(false);
            }

            var where = (FilterChainOptions)read_write & FilterChainOptions.ReadWrite;
            return(PhpFilter.AddToStream(s, filter, where | FilterChainOptions.Head, parameters));
        }
Пример #15
0
        /// <summary>
        /// Loads HTML from a file.
        /// </summary>
        /// <param name="ctx">Current runtime context.</param>
        /// <param name="sourceFile">Path to a file containing HTML document.</param>
        /// <param name="options">Unsupported.</param>
        public virtual bool loadHTMLFile(Context ctx, string sourceFile, int options = 0)
        {
            using (PhpStream stream = PhpStream.Open(ctx, sourceFile, "rt"))
            {
                if (stream == null)
                {
                    return(false);
                }

                return(loadHTML(ctx, new StreamReader(stream.RawStream), sourceFile));
            }
        }
Пример #16
0
        public static bool MakeDirectory(string pathname, int mode, bool recursive, PhpResource context)
        {
            StreamWrapper wrapper;

            if (!PhpStream.ResolvePath(ref pathname, out wrapper, CheckAccessMode.Directory, CheckAccessOptions.Empty))
            {
                return(false);
            }

            return(wrapper.MakeDirectory(pathname, mode, recursive ?
                                         StreamMakeDirectoryOptions.Recursive : StreamMakeDirectoryOptions.Empty, StreamContext.Default));
        }
Пример #17
0
        public static PhpString fgets(PhpResource handle)
        {
            PhpStream stream = PhpStream.GetValid(handle);

            if (stream == null)
            {
                return(default(PhpString));
            }

            // Use the default accessor to the stream breaking at \n, no superfluous conversion.
            //return Core.Convert.Quote(stream.ReadData(-1, true), ScriptContext.CurrentContext);
            return(stream.ReadData(-1, true).ToPhpString());
        }
Пример #18
0
        public static PhpResource tmpfile(Context ctx)
        {
            string path = tempnam(string.Empty, "php");

            StreamWrapper wrapper;

            if (!PhpStream.ResolvePath(ctx, ref path, out wrapper, CheckAccessMode.FileMayExist, CheckAccessOptions.Empty))
            {
                return(null);
            }

            return(wrapper.Open(ctx, ref path, "w+b", StreamOpenOptions.Temporary, StreamContext.Default));
        }
Пример #19
0
        public static PhpArray fstat(PhpResource handle)
        {
            var stream = PhpStream.GetValid(handle);

            if (stream != null)
            {
                return(BuildStatArray(stream.Stat()));
            }
            else
            {
                return(null); // FALSE
            }
        }
Пример #20
0
        public virtual void __construct(Context ctx, string file_name, string open_mode = "r", bool use_include_path = false, PhpResource context = null)
        {
            _ctx = ctx;
            base.__construct(ctx, file_name);
            _entry = new FileInfo(_fullpath);

            var openFlags = use_include_path ? PhpPath.FileOpenOptions.UseIncludePath : PhpPath.FileOpenOptions.Empty;

            _stream = (PhpStream)PhpPath.fopen(ctx, file_name, open_mode, openFlags, context);
            if (_stream == null)
            {
                throw new RuntimeException(string.Format(Resources.Resources.file_cannot_open, file_name));
            }
        }
Пример #21
0
        public static PhpString fread(Context ctx, PhpResource handle, int length)
        {
            // returns an object (string or PhpBytes depending on fopen mode)
            var stream = PhpStream.GetValid(handle);

            if (stream == null)
            {
                return(default(PhpString));
            }

            return(stream.IsText
                ? new PhpString(stream.ReadString(length))
                : new PhpString(stream.ReadBytes(length)));
        }
Пример #22
0
        public static PhpResource Open(string directory)
        {
            lastDirHandle = null;

            StreamWrapper wrapper;

            if (!PhpStream.ResolvePath(ref directory, out wrapper, CheckAccessMode.Directory, CheckAccessOptions.Empty))
            {
                return(null);
            }

            string[] listing = wrapper.Listing(directory, 0, null);
            return((listing != null) ? (lastDirHandle = new DirectoryListing(listing)) : null);
        }
Пример #23
0
        /// <summary>
        /// Adds a file to a ZIP archive from a given path.
        /// </summary>
        /// <param name="ctx">Current runtime context.</param>
        /// <param name="filename">The path to the file to add.</param>
        /// <param name="localname">If supplied, this is the local name inside the ZIP archive that will override the filename.</param>
        /// <param name="start">For partial copy, start position.</param>
        /// <param name="length">For partial copy, length to be copied, if 0 or -1 the whole file (starting from <paramref name="start"/>) is used.</param>
        /// <returns>TRUE on success or FALSE on failure.</returns>
        public bool addFile(Context ctx, string filename, string localname = null, int start = 0, int length = 0)
        {
            if (!CheckInitialized())
            {
                return(false);
            }

            ZipArchiveEntry entry = null;

            try
            {
                entry = CreateEntryIfNotExists(localname ?? Path.GetFileName(filename));
                entry.LastWriteTime = File.GetLastWriteTime(FileSystemUtils.AbsolutePath(ctx, filename));

                using (var entryStream = entry.Open())
                    using (PhpStream handle = PhpStream.Open(ctx, filename, "r", StreamOpenOptions.Empty))
                    {
                        if (start != 0)
                        {
                            handle.Seek(start, SeekOrigin.Begin);
                        }

                        if (length == 0 || length == -1)
                        {
                            handle.RawStream.CopyTo(entryStream);
                        }
                        else
                        {
                            // We need to copy the contents manually if the length was specified
                            var buffer = new byte[Math.Min(length, PhpStream.DefaultBufferSize)];
                            int copied = 0;
                            while (copied < length)
                            {
                                int lastCopied = handle.RawStream.Read(buffer, 0, Math.Min(buffer.Length, length - copied));
                                entryStream.Write(buffer, 0, lastCopied);
                                copied += lastCopied;
                            }
                        }
                    }

                return(true);
            }
            catch (System.Exception e)
            {
                PhpException.Throw(PhpError.Warning, e.Message);
                entry?.Delete();
                return(false);
            }
        }
Пример #24
0
        /// <summary>Sets file buffering on the given stream.</summary>
        /// <param name="resource">The stream to set write buffer size to.</param>
        /// <param name="buffer">Number of bytes the output buffer holds before
        /// passing to the underlying stream.</param>
        /// <returns><c>true</c> on success.</returns>
        public static bool stream_set_write_buffer(PhpResource resource, int buffer)
        {
            var stream = PhpStream.GetValid(resource);

            if (stream == null)
            {
                return(false);
            }

            if (buffer < 0)
            {
                buffer = 0;
            }
            return(stream.SetParameter(StreamParameterOptions.WriteBufferSize, (PhpValue)buffer));
        }
Пример #25
0
        public static object HighlightFile(string fileName, bool returnHighlighted)
        {
            using (PhpStream stream = PhpStream.Open(fileName, "rt"))
            {
                if (stream == null)
                {
                    return(false);
                }

                string source = stream.ReadStringContents(-1);
                Debug.Assert(source != null);

                return(HighlightString(source, returnHighlighted));
            }
        }
Пример #26
0
        /// <summary>
        /// Dumps the internal document into a file using HTML formatting.
        /// </summary>
        /// <param name="ctx">Current runtime context.</param>
        /// <param name="file">The path to the saved HTML document.</param>
        public virtual PhpValue saveHTMLFile(Context ctx, string file)
        {
            using (PhpStream stream = PhpStream.Open(ctx, file, "wt"))
            {
                if (stream == null)
                {
                    return(PhpValue.Create(false));
                }

                OutputHtmlDoctype(stream.RawStream);
                SaveXMLInternal(ctx, stream.RawStream, null, omitXmlDeclaration: true);

                // TODO:
                return(PhpValue.Create(stream.RawStream.CanSeek ? stream.RawStream.Position : 1));
            }
        }
Пример #27
0
        /// <summary>
        /// Validates the document against the specified XML schema.
        /// </summary>
        /// <param name="ctx">Current runtime context.</param>
        /// <param name="schemaFile">URL for the file containing the XML schema to load.</param>
        /// <param name="flags">Unsupported.</param>
        /// <returns><B>True</B> or <B>false</B>.</returns>
        public virtual bool schemaValidate(Context ctx, string schemaFile, int flags = 0)
        {
            if ((flags & PhpLibXml.LIBXML_SCHEMA_CREATE) == PhpLibXml.LIBXML_SCHEMA_CREATE)
            {
                PhpException.Throw(PhpError.Warning, Resources.SchemaCreateUnsupported);
            }

            XmlSchema schema;

            using (PhpStream stream = PhpStream.Open(ctx, schemaFile, "rt"))
            {
                if (stream == null)
                {
                    return(false);
                }

                try
                {
                    schema = XmlSchema.Read(stream.RawStream, null);
                }
                catch (XmlException e)
                {
                    PhpLibXml.IssueXmlError(ctx, PhpLibXml.LIBXML_ERR_WARNING, 0, 0, 0, e.Message, schemaFile);
                    return(false);
                }
                catch (IOException e)
                {
                    PhpLibXml.IssueXmlError(ctx, PhpLibXml.LIBXML_ERR_ERROR, 0, 0, 0, e.Message, schemaFile);
                    return(false);
                }
            }

            XmlDocument.Schemas.Add(schema);
            try
            {
                XmlDocument.Validate(null);
            }
            catch (XmlException)
            {
                return(false);
            }
            finally
            {
                XmlDocument.Schemas.Remove(schema);
            }
            return(true);
        }
        public static PhpResource opendir(Context ctx, string directory)
        {
            var dirctx = PhpDirectoryContext.GetContext(ctx);

            if (PhpStream.ResolvePath(ctx, ref directory, out var wrapper, CheckAccessMode.Directory, CheckAccessOptions.Empty))
            {
                var listing = wrapper.Listing(ctx.RootPath, directory, StreamListingOptions.Empty, null);
                if (listing != null)
                {
                    return(dirctx.LastDirHandle = new DirectoryListing(dirctx, listing));
                }
            }

            //
            dirctx.LastDirHandle = null;
            return(null);
        }
Пример #29
0
        /// <summary>
        /// Truncates a file to a given length.
        /// </summary>
        /// <param name="handle"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public static bool ftruncate(PhpResource handle, int size)
        {
            PhpStream stream = PhpStream.GetValid(handle);

            if (stream == null)
            {
                return(false);
            }

            if (stream.RawStream != null && stream.RawStream.CanWrite && stream.RawStream.CanSeek)
            {
                stream.RawStream.SetLength(size);
                return(true);
            }

            return(false);
        }
Пример #30
0
        /// <summary>Set timeout period on a stream</summary>
        /// <param name="resource">A handle to a stream opened for reading.</param>
        /// <param name="seconds">The number of seconds.</param>
        /// <param name="microseconds">The number of microseconds.</param>
        /// <returns><c>true</c> if the operation is supported and was successful, <c>false</c> otherwise.</returns>
        public static bool stream_set_timeout(PhpResource resource, int seconds, int microseconds = 0)
        {
            var stream = PhpStream.GetValid(resource);

            if (stream == null)
            {
                return(false);
            }

            double timeout = seconds + (microseconds / 1000000.0);

            if (timeout < 0.0)
            {
                timeout = 0.0;
            }
            return(stream.SetParameter(StreamParameterOptions.ReadTimeout, (PhpValue)timeout));
        }