示例#1
0
        public static PhpArray parse_ini_file(Context ctx, string fileName, bool processSections = false, ScannerMode scanner_mode = ScannerMode.Normal)
        {
            if (!ValidateScannerMode(scanner_mode))
            {
                return(null); // FALSE
            }

            // we're using binary mode because CR/LF stuff should be preserved for multiline values
            using (PhpStream stream = PhpStream.Open(ctx, fileName, "rb", StreamOpenOptions.ReportErrors, StreamContext.Default))
            {
                if (stream == null)
                {
                    return(null);//new PhpArray();
                }

                ArrayBuilder builder = new ArrayBuilder(ctx, processSections);
                try
                {
                    // parse the stream and let the builder build the resulting array
                    Parse(ctx, stream, builder, scanner_mode);
                }
                catch (ParseException e)
                {
                    PhpException.Throw(PhpError.Warning, Resources.LibResources.ini_parse_error, e.LineNumber.ToString());
                    return(null);
                }

                // return what we have read so far - even if a parse error occurred
                return(builder.Result);
            }
        }
示例#2
0
        /// <summary>
        /// Reads PhpBytes from file using the PhpStream.
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        internal static PhpBytes ReadPhpBytes(string filename)
        {
            PhpBytes bytes;

            using (PhpStream stream = PhpStream.Open(filename, "rb", StreamOpenOptions.Empty, StreamContext.Default))
            {
                if (stream == null)
                {
                    return(null);
                }

                try
                {
                    bytes = PhpStream.AsBinary(stream.ReadContents());
                    if (bytes == null || bytes.IsEmpty())
                    {
                        return(null);
                    }
                }
                catch
                {
                    return(null);
                }
            }

            return(bytes);
        }
示例#3
0
        public static PhpArray ParseFile(string fileName, bool processSections, int scanner_mode)
        {
            if (scanner_mode != (int)ScannerMode.Normal)  // TODO: handle value 1
            {
                PhpException.ArgumentValueNotSupported("scanner_mode", scanner_mode);
            }

            // we're using binary mode because CR/LF stuff should be preserved for multiline values
            using (PhpStream stream = PhpStream.Open(fileName, "rb", StreamOpenOptions.ReportErrors,
                                                     StreamContext.Default))
            {
                if (stream == null)
                {
                    return(null);               //new PhpArray();
                }
                ArrayBuilder builder = new ArrayBuilder(ScriptContext.CurrentContext, processSections);
                try
                {
                    // parse the stream and let the builder build the resulting array
                    Parse(stream, builder);
                }
                catch (ParseException e)
                {
                    PhpException.Throw(PhpError.Warning, LibResources.GetString("ini_parse_error", e.LineNumber));
                    return(null);
                }

                // return what we have read so far - even if a parse error occurred
                return(builder.Result);
            }
        }
示例#4
0
        public static PhpResource fopen(Context ctx, string path, string mode, FileOpenOptions flags = FileOpenOptions.Empty, PhpResource context = null)
        {
            StreamContext sc = StreamContext.GetValid(context, true);

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

            if (string.IsNullOrEmpty(path))
            {
                //PhpException.Throw(PhpError.Warning, LibResources.GetString("arg_empty", "path"));
                //return null;
                throw new ArgumentException(nameof(path));
            }

            if (string.IsNullOrEmpty(mode))
            {
                //PhpException.Throw(PhpError.Warning, LibResources.GetString("arg_empty", "mode"));
                //return null;
                throw new ArgumentException(nameof(mode));
            }

            return(PhpStream.Open(ctx, path, mode, ProcessOptions(ctx, flags), sc));
        }
示例#5
0
        public object transformToUri(DOMDocument doc, string uri)
        {
            using (PhpStream stream = PhpStream.Open(uri, "wt"))
            {
                if (stream == null)
                {
                    return(false);
                }

                // transform the document
                try
                {
                    TransformToStream(doc.XmlNode, xsltArgumentList, stream.RawStream);
                }
                catch (XsltException e)
                {
                    if (e.InnerException != null)
                    {
                        // ScriptDiedException etc.
                        throw e.InnerException;
                    }

                    PhpException.Throw(PhpError.Warning, e.Message);
                    return(false);
                }
                catch (InvalidOperationException e)
                {
                    PhpException.Throw(PhpError.Warning, e.Message);
                    return(false);
                }

                // TODO:
                return(stream.RawStream.CanSeek ? stream.RawStream.Position : 1);
            }
        }
示例#6
0
        public static PhpString file_get_contents(Context ctx, QueryValue <LocalVariables> localsData, string path, FileOpenOptions flags = FileOpenOptions.Empty, PhpResource context = null, int offset = -1, int maxLength = -1)
        {
            var sc = StreamContext.GetValid(context, true);

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

            using (PhpStream stream = PhpStream.Open(ctx, path, "rb", ProcessOptions(ctx, flags), sc))
            {
                if (stream == null)
                {
                    return(default(PhpString));
                }

                // when HTTP protocol requested, store responded headers into local variable $http_response_header:
                if (string.Compare(stream.Wrapper.Scheme, HttpStreamWrapper.scheme, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    var headers = stream.WrapperSpecificData as PhpArray;
                    localsData.Value.Locals.SetItemValue(new IntStringKey(HttpResponseHeaderName), (PhpValue)headers);
                }

                //
                //return Core.Convert.Quote(stream.ReadContents(maxLength, offset), ScriptContext.CurrentContext);
                return(stream.ReadContents(maxLength, offset).ToPhpString());
            }
        }
示例#7
0
        public void __construct(string file_name, string open_mode = "r", bool use_include_path = false, PhpResource context = null)
        {
            _root         = _ctx.RootPath;
            _originalPath = file_name;

            // fopen:
            var sc        = StreamContext.GetValid(context, allowNull: true) ?? StreamContext.Default;
            var openFlags = StreamOpenOptions.ReportErrors;

            if (use_include_path)
            {
                openFlags |= StreamOpenOptions.UseIncludePath;
            }

            _stream = PhpStream.Open(_ctx, file_name, open_mode, openFlags, sc);

            if (_stream != null)
            {
                _fullpath = _stream.OpenedPath;
            }
            else
            {
                throw new RuntimeException(string.Format(Resources.Resources.file_cannot_open, file_name));
            }
        }
示例#8
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)
        {
            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);
                }
            }

            return(ValidateSchemaInternal(schema, flags));
        }
示例#9
0
        private static bool TryLoadSchema(Context ctx, string url, out XmlSchema schema, out string fullPath)
        {
            schema   = default;
            fullPath = default;

            using var stream = PhpStream.Open(ctx, url, "rt");

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

            try
            {
                schema   = XmlSchema.Read(stream.RawStream, null);
                fullPath = stream.OpenedPath;
                return(true);
            }
            catch (XmlException e)
            {
                PhpLibXml.IssueXmlError(ctx, PhpLibXml.LIBXML_ERR_WARNING, 0, 0, 0, e.Message, url);
                return(false);
            }
            catch (IOException e)
            {
                PhpLibXml.IssueXmlError(ctx, PhpLibXml.LIBXML_ERR_ERROR, 0, 0, 0, e.Message, url);
                return(false);
            }
        }
示例#10
0
        public object addFile(ScriptContext context, object filename, object localname, object start, object length)
        {
            string fpath   = Core.Convert.ObjectToString(filename);
            string flocal  = Core.Convert.ObjectToString(localname);
            int    fstart  = Core.Convert.ObjectToInteger(start);
            int    flength = Core.Convert.ObjectToInteger(length);

            try
            {
                using (PhpStream handle = PhpStream.Open(fpath, "r", StreamOpenOptions.Empty))
                {
                    if (fstart > 0)
                    {
                        PhpFile.Seek(handle, fstart);
                    }

                    FileHandleDataSource src = new FileHandleDataSource(handle, flength);
                    this.m_zip.BeginUpdate();
                    this.m_zip.Add(src, flocal);
                    this.m_zip.CommitUpdate();
                    return(true);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("ZipArchive::addFile", ex.Message);
                return(false);
            }
        }
        /// <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">This parameter is not used.</param>
        /// <param name="length">This parameter is not used.</param>
        /// <returns></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))
                    {
                        handle.RawStream.CopyTo(entryStream);
                    }

                return(true);
            }
            catch (System.Exception e)
            {
                PhpException.Throw(PhpError.Warning, e.Message);
                entry?.Delete();
                return(false);
            }
        }
示例#12
0
        /// <summary>
        /// Reads PhpBytes from file using the PhpStream.
        /// </summary>
        internal static byte[] ReadPhpBytes(Context ctx, string filename)
        {
            byte[] bytes;

            using (PhpStream stream = PhpStream.Open(ctx, filename, "rb", StreamOpenOptions.Empty, StreamContext.Default))
            {
                if (stream == null)
                {
                    return(null);
                }

                try
                {
                    var element = stream.ReadContents();
                    if (element.IsNull)
                    {
                        return(null);
                    }

                    bytes = element.AsBytes(ctx.StringEncoding);
                }
                catch
                {
                    return(null);
                }
            }

            return(bytes);
        }
示例#13
0
        public static object load([This] DOMDocument instance, string fileName, [Optional] int options)
        {
            // this method can be called both statically and via an instance
            bool static_call;

            if (instance == null)
            {
                static_call = true;
                instance    = new DOMDocument();
            }
            else
            {
                static_call = false;
            }

            instance._isHtmlDocument = false;

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

                try
                {
                    if (instance._validateOnParse)
                    {
                        // create a validating XML reader
                        XmlReaderSettings settings = new XmlReaderSettings();
#pragma warning disable 618
                        settings.ValidationType = ValidationType.Auto;
#pragma warning restore 618

                        instance.XmlDocument.Load(XmlReader.Create(stream.RawStream, settings));
                    }
                    else
                    {
                        instance.XmlDocument.Load(stream.RawStream);
                    }
                }
                catch (XmlException e)
                {
                    PhpLibXml.IssueXmlError(new PhpLibXml.XmlError(PhpLibXml.LIBXML_ERR_ERROR, 0, 0, 0, e.Message, fileName));
                    return(false);
                }
                catch (IOException e)
                {
                    PhpLibXml.IssueXmlError(new PhpLibXml.XmlError(PhpLibXml.LIBXML_ERR_ERROR, 0, 0, 0, e.Message, fileName));
                    return(false);
                }
            }

            return(static_call ? instance : (object)true);
        }
示例#14
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);
        }
示例#15
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);
        }
示例#16
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)));
            }
        }
示例#17
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));
            }
        }
        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);
        }
示例#19
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));
            }
        }
示例#20
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);
            }
        }
示例#21
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));
            }
        }
示例#22
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));
            }
        }
示例#23
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);
        }
示例#24
0
        /// <summary>
        /// Loads the XML document from the specified URL.
        /// </summary>
        /// <param name="ctx">Current runtime context.</param>
        /// <param name="filename">URL for the file containing the XML document to load.</param>
        /// <param name="options">Undocumented.</param>
        /// <returns><b>True</b> on success or <b>false</b> on failure.</returns>
        public virtual bool load(Context ctx, string filename, int options = 0)
        {
            // TODO: this method can be called both statically and via an instance

            _isHtmlDocument = false;

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

                try
                {
                    var settings = new XmlReaderSettings()
                    {
                        DtdProcessing = DtdProcessing.Parse
                    };

                    // TODO: options

                    // validating XML reader
                    if (this._validateOnParse)
                    {
#pragma warning disable 618
                        settings.ValidationType = ValidationType.Auto;
#pragma warning restore 618
                    }
                    XmlDocument.Load(XmlReader.Create(stream.RawStream, settings, XIncludeHelper.UriResolver(filename, ctx.WorkingDirectory)));
                }
                catch (XmlException e)
                {
                    PhpLibXml.IssueXmlError(ctx, PhpLibXml.LIBXML_ERR_ERROR, 0, 0, 0, e.Message, filename);
                    return(false);
                }
                catch (IOException e)
                {
                    PhpLibXml.IssueXmlError(ctx, PhpLibXml.LIBXML_ERR_ERROR, 0, 0, 0, e.Message, filename);
                    return(false);
                }
            }

            return(true);
        }
示例#25
0
        /// <summary>
        /// Transforms the source node to an URI applying the stylesheet given by the
        /// <see cref="importStylesheet(DOMDocument)"/> method.
        /// </summary>
        /// <param name="ctx">The current runtime context.</param>
        /// <param name="doc">The document to transform.</param>
        /// <param name="uri">The destination URI.</param>
        /// <returns>Returns the number of bytes written or <B>false</B> if an error occurred.</returns>
        public PhpValue transformToUri(Context ctx, DOMDocument doc, string uri)
        {
            using (PhpStream stream = PhpStream.Open(ctx, uri, "wt"))
            {
                if (stream == null)
                {
                    return(PhpValue.Create(false));
                }

                if (!TransformInternal(doc.XmlNode, stream.RawStream))
                {
                    return(PhpValue.Create(false));
                }

                // TODO:
                return(PhpValue.Create(stream.RawStream.CanSeek ? stream.RawStream.Position : 1));
            }
        }
示例#26
0
        /// <summary>
        /// Loads the XML document from the specified URL.
        /// </summary>
        /// <param name="ctx">Current runtime context.</param>
        /// <param name="fileName">URL for the file containing the XML document to load.</param>
        /// <param name="options">Undocumented.</param>
        /// <returns><b>True</b> on success or <b>false</b> on failure.</returns>
        public virtual bool load(Context ctx, string fileName, int options = 0)
        {
            // TODO: this method can be called both statically and via an instance

            _isHtmlDocument = false;

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

                try
                {
                    if (_validateOnParse)
                    {
                        // create a validating XML reader
                        XmlReaderSettings settings = new XmlReaderSettings();
                        //#pragma warning disable 618
                        //                        settings.ValidationType = ValidationType.Auto;
                        //#pragma warning restore 618

                        XmlDocument.Load(XmlReader.Create(stream.RawStream, settings));
                    }
                    else
                    {
                        XmlDocument.Load(stream.RawStream);
                    }
                }
                catch (XmlException e)
                {
                    PhpLibXml.IssueXmlError(ctx, PhpLibXml.LIBXML_ERR_ERROR, 0, 0, 0, e.Message, fileName);
                    return(false);
                }
                catch (IOException e)
                {
                    PhpLibXml.IssueXmlError(ctx, PhpLibXml.LIBXML_ERR_ERROR, 0, 0, 0, e.Message, fileName);
                    return(false);
                }
            }

            return(true);
        }
示例#27
0
        /// <summary>
        /// Saves the XML document to the specified stream.
        /// </summary>
        /// <param name="ctx">Current runtime context.</param>
        /// <param name="fileName">The location of the file where the document should be saved.</param>
        /// <param name="options">Unsupported.</param>
        /// <returns>The number of bytes written or <B>false</B> on error.</returns>
        public virtual PhpValue save(Context ctx, string fileName, int options = 0)
        {
            using (PhpStream stream = PhpStream.Open(ctx, fileName, "wt"))
            {
                if (stream == null)
                {
                    return(PhpValue.Create(false));
                }

                try
                {
                    // direct stream write indents
                    if (_formatOutput)
                    {
                        XmlDocument.Save(stream.RawStream);
                    }
                    else
                    {
                        var settings = new XmlWriterSettings()
                        {
                            Encoding = Utils.GetNodeEncoding(ctx, XmlNode)
                        };

                        using (var writer = System.Xml.XmlWriter.Create(stream.RawStream, settings))
                        {
                            XmlDocument.Save(writer);
                        }
                    }
                }
                catch (XmlException e)
                {
                    PhpLibXml.IssueXmlError(ctx, PhpLibXml.LIBXML_ERR_ERROR, 0, 0, 0, e.Message, fileName);
                    return(PhpValue.False);
                }
                catch (IOException e)
                {
                    PhpLibXml.IssueXmlError(ctx, PhpLibXml.LIBXML_ERR_ERROR, 0, 0, 0, e.Message, fileName);
                    return(PhpValue.False);
                }

                // TODO:
                return(PhpValue.Create(stream.RawStream.CanSeek ? stream.RawStream.Position : 1));
            }
        }
示例#28
0
        public static PhpArray file(Context ctx, string path, FileOptions flags = FileOptions.Empty, PhpResource context = null)
        {
            var sc = StreamContext.GetValid(context, true);

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

            using (var stream = PhpStream.Open(ctx, path, "rt", ProcessOptions(ctx, (FileOpenOptions)flags), sc))
            {
                if (stream == null)
                {
                    return(null);
                }

                PhpArray rv = new PhpArray();

                while (!stream.Eof)
                {
                    // Note: The last line does not contain the \n delimiter, but may be empty
                    var line = stream.ReadData(-1, true).AsText(ctx.StringEncoding);
                    if ((flags & FileOptions.TrimLineEndings) > 0)
                    {
                        int len = line.Length;
                        if ((len > 0) && (line[len - 1] == '\n'))
                        {
                            line = line.Substring(0, len - 1);
                        }
                    }
                    if ((flags & FileOptions.SkipEmptyLines) > 0)
                    {
                        if (line.Length == 0)
                        {
                            continue;
                        }
                    }

                    rv.Add(line);
                }

                return(rv);
            }
        }
示例#29
0
文件: Standard.cs 项目: dlob/peachpie
        /// <summary>
        /// Return source with stripped comments and whitespace.
        /// </summary>
        /// <returns>The stripped source code will be returned on success, or an empty string on failure.</returns>
        public static string php_strip_whitespace(Context ctx, string filename)
        {
            var stream = PhpStream.Open(ctx, filename, "rt", StreamOpenOptions.Empty, StreamContext.Default)?.RawStream;

            if (stream == null)
            {
                return(string.Empty);
            }

            Tokens t;
            var    result = StringBuilderUtilities.Pool.Get();

            void Append(StringBuilder sb, CharSpan span)
            {
                sb.Append(span.Buffer, span.Start, span.Length);
            }

            using (var tokenizer = new Lexer(new StreamReader(stream, Encoding.UTF8), Encoding.UTF8))
            {
                while ((t = tokenizer.GetNextToken()) != Tokens.EOF)
                {
                    switch (t)
                    {
                    case Tokens.T_COMMENT:
                        // ignore
                        break;

                    case Tokens.T_WHITESPACE:
                        result.Append(' ');
                        break;

                    default:
                        //result.Append(tokenizer.TokenText);
                        // avoid copying and allocating string
                        Append(result, tokenizer.GetTokenSpan());
                        break;
                    }
                }
            }

            stream.Dispose();

            return(StringBuilderUtilities.GetStringAndReturn(result));
        }
示例#30
0
        public object schemaValidate(string schemaFile)
        {
            XmlSchema schema;

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

                try
                {
                    schema = XmlSchema.Read(stream.RawStream, null);
                }
                catch (XmlException e)
                {
                    PhpLibXml.IssueXmlError(new PhpLibXml.XmlError(PhpLibXml.LIBXML_ERR_WARNING, 0, 0, 0, e.Message, schemaFile));
                    return(false);
                }
                catch (IOException e)
                {
                    PhpLibXml.IssueXmlError(new PhpLibXml.XmlError(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);
        }