Exemplo n.º 1
0
        public bool startDocument(string version = DefaultXmlVersion, string encoding = null, string standalone = null)
        {
            if (version != DefaultXmlVersion)
            {
                PhpException.ArgumentValueNotSupported(nameof(version), version);
            }

            if (encoding != null && !string.Equals(encoding, "utf-8", StringComparison.CurrentCultureIgnoreCase))
            {
                PhpException.ArgumentValueNotSupported(nameof(encoding), encoding);
            }

            if (string.IsNullOrEmpty(standalone))
            {
                bool res = CheckedCall(() => _writer.WriteStartDocument());
                if (!_writer.Settings.Indent) // Php writes a new line character after prolog.
                {
                    res &= CheckedCall(() => _writer.WriteRaw(_writer.Settings.NewLineChars));
                }

                return(res);
            }
            else
            {
                bool res = CheckedCall(() => _writer.WriteStartDocument(standalone == "yes"));
                if (!_writer.Settings.Indent) // Php writes a new line character after prolog.
                {
                    res &= CheckedCall(() => _writer.WriteRaw(_writer.Settings.NewLineChars));
                }

                return(res);
            }
        }
Exemplo n.º 2
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);
            }
        }
Exemplo n.º 3
0
        public static PhpArray ParseString(string ini, bool processSections, int scanner_mode)
        {
            if (scanner_mode != (int)ScannerMode.Normal)  // TODO: handle value 1
            {
                PhpException.ArgumentValueNotSupported("scanner_mode", scanner_mode);
            }

            if (string.IsNullOrEmpty(ini))
            {
                return(null);
            }

            ArrayBuilder builder = new ArrayBuilder(ScriptContext.CurrentContext, processSections);

            try
            {
                // parse the stream and let the builder build the resulting array
                Parse(ini, 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);
        }
Exemplo n.º 4
0
 static void AssertGet(string option, IniAction action)
 {
     if (action != IniAction.Get)
     {
         PhpException.ArgumentValueNotSupported(option, action);
     }
 }
Exemplo n.º 5
0
        /// <summary>
        /// Registeres a standard configuration option.
        /// Not thread safe.
        /// </summary>
        public static void Register <TOptions>(string name, string extension, Func <TOptions, PhpValue> getter, Action <TOptions, PhpValue> setter) where TOptions : class, IPhpConfiguration
        {
            if (getter == null)
            {
                throw new ArgumentNullException(nameof(getter));
            }

            Register(name, IniFlags.Local | IniFlags.Supported,
                     (ctx, config, option, value, action) =>
            {
                var local = config.Get <TOptions>();
                if (local == null)
                {
                    return(PhpValue.False);
                }

                var oldvalue = getter(local);
                if (action == IniAction.Set)
                {
                    if (setter != null)
                    {
                        setter(local, value);
                    }
                    else
                    {
                        PhpException.ArgumentValueNotSupported(option, action);
                    }
                }
                return(oldvalue);
            },
                     extension);
        }
Exemplo n.º 6
0
        public static PhpArray GetExtensionFunctions(string extension)
        {
            if (extension == "zend")                                            // since PHP 5.0
            {
                PhpException.ArgumentValueNotSupported("extension", extension); // TODO: functions in the module zend (php functions in PhpNetCore ?)
                // ...
            }

            ApplicationContext app_context = ScriptContext.CurrentContext.ApplicationContext;

            PhpLibraryDescriptor desc = app_context.GetExtensionImplementor(extension);

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

            PhpArray result = new PhpArray();

            foreach (KeyValuePair <string, DRoutineDesc> function in app_context.Functions)
            {
                if (function.Value.DeclaringType.DeclaringModule == desc.Module)
                {
                    result.Add(function.Key);
                }
            }

            return(result);
        }
Exemplo n.º 7
0
 private static void CheckFlags(int flags, int supported = 0)
 {
     if ((flags & ~supported) != 0)
     {
         PhpException.ArgumentValueNotSupported(nameof(flags), flags);
     }
 }
Exemplo n.º 8
0
        /// <summary>
        /// Binds a PHP variable to an SQL parameter of a statement.
        /// </summary>
        /// <param name="statement">Statement resource.</param>
        /// <param name="parameterName">Parameter name starting with '@' character.</param>
        /// <param name="variable">PHP variable to bind to the parameter.</param>
        /// <param name="type">SQL type of the parameter.</param>
        /// <param name="isOutput">Whether the parameter is an output parameter.</param>
        /// <param name="isNullable">Whether the parameter accepts <B>null</B> values.</param>
        /// <param name="maxLength">Maximum size of input data.</param>
        /// <returns>Whether binding succeeded.</returns>
        public static bool mssql_bind(PhpResource statement, string parameterName, PhpAlias variable, VariableType type,
                                      bool isOutput = false, bool isNullable = false, int maxLength = -1)
        {
            PhpSqlDbProcedure procedure = PhpSqlDbProcedure.ValidProcedure(statement);

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

            if (parameterName == null)
            {
                PhpException.ArgumentNull(nameof(parameterName));
                return(false);
            }

            var param_type = PhpSqlDbProcedure.VariableTypeToParamType(type);

            if (param_type == PhpSqlDbProcedure.ParameterType.Invalid)
            {
                PhpException.ArgumentValueNotSupported("type", (int)type);
                return(false);
            }

            SqlParameter parameter = new SqlParameter();

            parameter.ParameterName = parameterName;

            // it is necessary to set size for in-out params as the results are truncated to this size;
            // 8000 is maximal size of the data according to the doc:
            if (maxLength >= 0)
            {
                parameter.Size = maxLength;
            }
            else
            {
                parameter.Size = 8000;
            }

            if (string.Equals(parameterName, "RETVAL", StringComparison.OrdinalIgnoreCase))
            {
                parameter.Direction = ParameterDirection.ReturnValue;
            }
            else if (isOutput)
            {
                parameter.Direction = ParameterDirection.InputOutput;
            }
            else
            {
                parameter.Direction = ParameterDirection.Input;
            }

            if (!procedure.AddBinding(parameter, variable, param_type))
            {
                PhpException.Throw(PhpError.Notice, Resources.parameter_already_bound, parameterName);
                return(false);
            }

            return(true);
        }
Exemplo n.º 9
0
        public static bool Start(PhpCallback filter, int chunkSize, bool erase)
        {
            if (chunkSize != 0)
            {
                PhpException.ArgumentValueNotSupported("chunkSize", "!= 0");
            }
            if (!erase)
            {
                PhpException.ArgumentValueNotSupported("erase", erase);
            }

            ScriptContext context = ScriptContext.CurrentContext;

            context.BufferedOutput.IncreaseLevel();

            bool result = true;

            // skips filter setting if filter is not specified or valid:
            if (filter != null && (result = filter.Bind()))
            {
                context.BufferedOutput.SetFilter(filter);
            }

            context.IsOutputBuffered = true;
            return(result);
        }
Exemplo n.º 10
0
        public virtual void __construct(Traversable iterator, string classname = null)
        {
            if (classname != null)
            {
                //var downcast = ctx.ResolveType(PhpVariable.AsString(classname), null, this.iterator.TypeDesc, null, ResolveTypeFlags.ThrowErrors);

                PhpException.ArgumentValueNotSupported(nameof(classname), classname);
                throw new NotImplementedException();
            }

            _iterator   = iterator;
            _valid      = false;
            _enumerator = null;

            if (iterator is Iterator)
            {
                // ok
            }
            else
            {
                PhpException.InvalidArgument(nameof(iterator));
            }

            //rewind(context);  // not in PHP, performance reasons (foreach causes rewind() itself)
        }
Exemplo n.º 11
0
        /// <summary>
        /// Get information regarding a specific transfer.
        /// </summary>
        public static PhpValue curl_getinfo(CURLResource ch, int opt = 0)
        {
            if (ch != null && ch.Result != null)
            {
                var r = ch.Result;

                switch (opt)
                {
                case 0:
                    // array of all information
                    return(new PhpArray()
                    {
                        { "url", r.ResponseUri?.AbsoluteUri },
                        { "content_type", r.ContentType },
                        { "http_code", r.StatusCode },
                        { "filetime", DateTimeUtils.UtcToUnixTimeStamp(r.LastModified) },
                        { "total_time", r.TotalTime.TotalSeconds },
                        { "download_content_length", r.ContentLength },
                        { "redirect_url", ch.FollowLocation&& r.ResponseUri != null ? string.Empty : r.ResponseUri.AbsoluteUri }
                    });

                case CURLConstants.CURLINFO_EFFECTIVE_URL:
                    return(r.ResponseUri?.AbsoluteUri);

                case CURLConstants.CURLINFO_REDIRECT_URL:
                    return(ch.FollowLocation && r.ResponseUri != null ? string.Empty : r.ResponseUri.AbsoluteUri);

                case CURLConstants.CURLINFO_HTTP_CODE:
                    return((int)r.StatusCode);

                case CURLConstants.CURLINFO_FILETIME:
                    return(DateTimeUtils.UtcToUnixTimeStamp(r.LastModified));

                case CURLConstants.CURLINFO_CONTENT_TYPE:
                    return(r.ContentType);

                case CURLConstants.CURLINFO_CONTENT_LENGTH_DOWNLOAD:
                    return(r.ContentLength);

                case CURLConstants.CURLINFO_TOTAL_TIME:
                    return(r.TotalTime.TotalSeconds);

                case CURLConstants.CURLINFO_PRIVATE:
                    return(r.Private.IsSet ? r.Private : PhpValue.False);

                case CURLConstants.CURLINFO_COOKIELIST:
                    return((ch.CookieFileSet && ch.Result != null) ? CreateCookieArray(ch.Result.Cookies) : PhpArray.Empty);

                default:
                    PhpException.ArgumentValueNotSupported(nameof(opt), opt);
                    break;
                }
            }

            // failure:
            return(PhpValue.False);
        }
Exemplo n.º 12
0
        public static string SetRegexOptions(string options)
        {
            RegexOptions     newRegexOptions     = RegexOptions.None;
            RegexSyntaxModes newRegexSyntaxModes = RegexSyntaxModes.POSIXExtendedRegex;

            foreach (char c in options)
            {
                switch (c)
                {
                case 'i':
                    newRegexOptions |= RegexOptions.AmbiguityMatch;
                    break;

                case 'x':
                    newRegexOptions |= RegexOptions.ExtendedPatternForm;
                    break;

                case 'm':
                    newRegexOptions |= RegexOptions.DotMatchesNewLine;
                    break;

                case 's':
                    newRegexOptions |= RegexOptions.ConvertMatchBeginEnd;
                    break;

                case 'p':
                    newRegexOptions |= RegexOptions.DotMatchesNewLine | RegexOptions.ConvertMatchBeginEnd;
                    break;

                case 'l':
                    newRegexOptions |= RegexOptions.FindLongestMatch;
                    break;

                case 'n':
                    newRegexOptions |= RegexOptions.IgnoreEmptyMatch;
                    break;

                case 'e':
                    newRegexOptions |= RegexOptions.EvalResultingCode;
                    break;

                case 'd':
                    newRegexSyntaxModes = RegexSyntaxModes.POSIXExtendedRegex;
                    break;

                default:
                    PhpException.ArgumentValueNotSupported("options", c);
                    break;
                }
            }

            //
            _regexOptions    = newRegexOptions;
            _regexSyntaxMode = newRegexSyntaxModes;

            return(GetRegexOptions());
        }
Exemplo n.º 13
0
        /// <summary>
        /// Seed the better random number generator.
        /// No return value.
        /// </summary>
        /// <param name="seed">Optional seed value.</param>
        /// <param name="mode">Seed algorithm implementation.</param>
        public static void mt_srand(int seed, MtMode mode = MtMode.MT19937)
        {
            if (mode != MtMode.MT19937)
            {
                PhpException.ArgumentValueNotSupported(nameof(mode), mode.ToString());
            }

            mt_srand(seed);
        }
Exemplo n.º 14
0
        public static PhpArray Backtrace(bool provideObject)
        {
            if (provideObject == true)
            {
                PhpException.ArgumentValueNotSupported("provideObject", provideObject);
            }

            return(Backtrace());
        }
Exemplo n.º 15
0
        public static void PrintBacktrace(bool provideObject)
        {
            if (provideObject == true)
            {
                PhpException.ArgumentValueNotSupported("provideObject", provideObject);
            }

            ScriptContext context = ScriptContext.CurrentContext;

            context.Output.Write(new PhpStackTrace(context, 1).FormatUserTrace());
        }
Exemplo n.º 16
0
        /// <summary>
        /// Get a MIME charset string for a specific encoding.
        /// </summary>
        /// <param name="encoding_name">The encoding being checked. Its BodyName or PHP/Phalanger name.</param>
        /// <returns>The MIME charset string for given character encoding.</returns>
        public static string mb_preferred_mime_name(string encoding_name)
        {
            var enc = GetEncoding(encoding_name);

            // try PHP internal encodings (by PHP name) and .NET encodings name
            if (enc == null)
            {
                PhpException.ArgumentValueNotSupported(nameof(encoding_name), encoding_name);
                return(null);
            }

            return(enc.BodyName);// it seems to return right MIME
        }
Exemplo n.º 17
0
            public static PhpValue Gsr(Context ctx, IPhpConfigurationService config, string option, PhpValue value, IniAction action)
            {
                var sessionconfig = config.GetSessionConfiguration();

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

                switch (option)
                {
                case "session.auto_start":
                    if (action != IniAction.Get)
                    {
                        PhpException.ArgumentValueNotSupported(option, action);
                    }
                    return(sessionconfig.AutoStart);

                case "session.save_handler":
                    if (action != IniAction.Get)
                    {
                        PhpException.ArgumentValueNotSupported(option, action);
                    }
                    var handler = ctx.HttpPhpContext?.SessionHandler;
                    return(handler != null ? handler.HandlerName : PhpValue.False);

                case "session.serialize_handler":
                    return(GetSet(ref sessionconfig.SerializeHandler, "php", value, action));

                case "session.name":
                    return(GetSet(ref sessionconfig.SessionName, DefaultSessionName, value, action));

                case "session.cookie_lifetime":
                    return(GetSet(ref sessionconfig.CookieLifetime, 0, value, action));

                case "session.cookie_path":
                    return(GetSet(ref sessionconfig.CookiePath, "/", value, action));

                case "session.cookie_domain":
                    return(GetSet(ref sessionconfig.CookieDomain, "", value, action));

                case "session.cookie_secure":
                    return(GetSet(ref sessionconfig.CookieSecure, false, value, action));

                case "session.cookie_httponly":
                    return(GetSet(ref sessionconfig.CookieHttpOnly, false, value, action));

                default:
                    throw new ArgumentOutOfRangeException(nameof(option));
                }
            }
Exemplo n.º 18
0
        public static bool Log(string message, LogAction action, string destination, string extraHeaders)
        {
            switch (action)
            {
            case LogAction.Default:

                bool result = true;

                LocalConfiguration config = Configuration.Local;

                // adds a message to the default log file:
                if (config.ErrorControl.LogFile != null)
                {
                    try { Logger.AppendLine(config.ErrorControl.LogFile, message); }
                    catch (System.Exception) { result = false; }
                }

                // adds a message to an event log:
                if (config.ErrorControl.SysLog)
                {
                    try { Logger.AddToEventLog(message); }
                    catch (System.Exception) { result = false; }
                }

                return(result);

            case LogAction.SendByEmail:
                Mailer.Mail(destination, LibResources.GetString("error_report"), message, extraHeaders);
                return(true);

            case LogAction.ToDebuggingConnection:
                PhpException.ArgumentValueNotSupported("action", (int)action);
                return(false);

            case LogAction.AppendToFile:
                try
                {
                    PHP.Core.Logger.AppendLine(destination, message);
                }
                catch (System.Exception)
                {
                    return(false);
                }
                return(true);

            default:
                PhpException.InvalidArgument("action");
                return(false);
            }
        }
Exemplo n.º 19
0
        public static string GetPreferredMimeName(string encoding_name)
        {
            Encoding encoding;

            if (
                (encoding = Encoding.GetEncoding(encoding_name)) == null && // .NET encodings (by their WebName)
                (encoding = GetEncoding(encoding_name)) == null             //try PHP internal encodings too (by PHP/Phalanger name)
                )
            {
                PhpException.ArgumentValueNotSupported("encoding_name", encoding);
                return(null);
            }

            return(encoding.BodyName);   // it seems to return right MIME
        }
Exemplo n.º 20
0
        /// <summary>
        /// Stores a local file on the FTP server.
        /// </summary>
        /// <param name="context">Runtime context.</param>
        /// <param name="ftp_stream">The link identifier of the FTP connection.</param>
        /// <param name="remote_file">The remote file path.</param>
        /// <param name="local_file">The local file path.</param>
        /// <param name="mode">The transfer mode. Must be either <see cref="FTP_ASCII"/> or <see cref="FTP_BINARY"/>.</param>
        /// <param name="startpos">Not Supported</param>
        /// <returns>Returns TRUE on success or FALSE on failure.</returns>
        public static bool ftp_put(Context context, PhpResource ftp_stream, string remote_file, string local_file, int mode = FTP_IMAGE, int startpos = 0)
        {
            var resource = ValidateFtpResource(ftp_stream);

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

            string localPath = FileSystemUtils.AbsolutePath(context, local_file);

            if (!FileSystemUtils.IsLocalFile(localPath))
            {
                PhpException.Throw(PhpError.Warning, Resources.Resources.file_not_exists, local_file);
                return(false);
            }

            // Two types of data transfer
            resource.Client.UploadDataType = (mode == FTP_ASCII) ? FtpDataType.ASCII : FtpDataType.Binary;

            if (startpos != 0) // There is no API for this parameter in FluentFTP Library.
            {
                PhpException.ArgumentValueNotSupported(nameof(startpos), startpos);
            }

            try
            {
                return(resource.Client.UploadFile(localPath, remote_file, FtpExists.Overwrite));
            }

            /* FtpException everytime wraps other exceptions (Message from server).
             * https://github.com/robinrodricks/FluentFTP/blob/master/FluentFTP/Client/FtpClient_HighLevelUpload.cs#L595 */
            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);
        }
Exemplo n.º 21
0
        public bool startDocument(string version = DefaultXmlVersion, string encoding = null, string standalone = null)
        {
            if (version != DefaultXmlVersion)
            {
                PhpException.ArgumentValueNotSupported(nameof(version), version);
            }

            if (encoding != null && !string.Equals(encoding, "utf-8", StringComparison.CurrentCultureIgnoreCase))
            {
                PhpException.ArgumentValueNotSupported(nameof(encoding), encoding);
            }

            if (string.IsNullOrEmpty(standalone))
            {
                return(CheckedCall(() => _writer.WriteStartDocument()));
            }
            else
            {
                return(CheckedCall(() => _writer.WriteStartDocument(standalone == "yes")));
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// Extract the complete archive to the specified destination.
        /// </summary>
        /// <param name="ctx">Current runtime context.</param>
        /// <param name="destination">Location where to extract the files.</param>
        /// <param name="entries">The entries to extract, currently not supported.</param>
        /// <returns>TRUE on success or FALSE on failure.</returns>
        public bool extractTo(Context ctx, string destination, PhpValue entries = default(PhpValue))
        {
            if (!CheckInitialized())
            {
                return(false);
            }

            if (!Operators.IsEmpty(entries))
            {
                PhpException.ArgumentValueNotSupported(nameof(entries), entries);
                return(false);
            }

            try
            {
                _archive.ExtractToDirectory(FileSystemUtils.AbsolutePath(ctx, destination));
                return(true);
            }
            catch (System.Exception e)
            {
                PhpException.Throw(PhpError.Warning, e.Message);
                return(false);
            }
        }
Exemplo n.º 23
0
        public virtual object getMethods(ScriptContext /*!*/ context, object filter = null)
        {
            if (typedesc == null)
            {
                return(false);
            }

            if (filter != null && filter != Arg.Default)
            {
                PhpException.ArgumentValueNotSupported("filter", filter);
            }

            PhpArray result = new PhpArray();

            foreach (KeyValuePair <Name, DRoutineDesc> method in typedesc.EnumerateMethods())
            {
                result.Add(new ReflectionMethod(context, true)
                {
                    dtype  = method.Value.DeclaringType,
                    method = method.Value,
                });
            }
            return(result);
        }
Exemplo n.º 24
0
        public static PhpArray exif_read_data(Context ctx, string filename, string sections = null, bool arrays = false, bool thumbnail = false)
        {
            if (string.IsNullOrEmpty(filename))
            {
                PhpException.Throw(PhpError.Warning, Resources.filename_cannot_be_empty);
                return(null);
            }

            if (!string.IsNullOrEmpty(sections))
            {
                PhpException.ArgumentValueNotSupported("sections", sections);
            }

            if (arrays)
            {
                PhpException.ArgumentValueNotSupported("arrays", arrays);
            }

            if (thumbnail)
            {
                PhpException.ArgumentValueNotSupported("thumbnail", thumbnail);
            }

            PhpArray array = new PhpArray();


            var bytes = Utils.ReadPhpBytes(ctx, filename);

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

            array.Add("FileName", Path.GetFileName(filename));
            //array.Add("FileDateTime", (int)File.GetCreationTime(filename).ToOADate());
            array.Add("FileSize", (int)bytes.Length);

            IImageInfo image;

            using (var ms = new MemoryStream(bytes))
            {
                try
                {
                    image = Image.Identify(ms);
                }
                catch
                {
                    return(null);
                }

                var encoding = System.Text.Encoding.ASCII;
                var unicode  = System.Text.Encoding.Unicode;

                // TODO: image.MetaData.Properties, image.MetaData.IccProfile, image.MetaData.***Resolution

                if (image.Metadata.ExifProfile != null)
                {
                    foreach (var item in image.Metadata.ExifProfile.Values)
                    {
                        array.Add(item.Tag.ToString(), ExifValueToPhpValue(item.Value));
                    }
                }
            }

            return(array);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Filters a variable with a specified filter.
        /// </summary>
        /// <param name="ctx">Runtime context.</param>
        /// <param name="variable">Value to filter.</param>
        /// <param name="filter">The ID of the filter to apply.</param>
        /// <param name="options">Associative array of options or bitwise disjunction of flags. If filter accepts options, flags can be provided in "flags" field of array. For the "callback" filter, callback type should be passed. The callback must accept one argument, the value to be filtered, and return the value after filtering/sanitizing it.</param>
        /// <returns>Returns the filtered data, or <c>false</c> if the filter fails.</returns>
        public static PhpValue filter_var(Context ctx, PhpValue variable, int filter = FILTER_DEFAULT, PhpValue options = default(PhpValue))
        {
            var      @default    = PhpValue.False; // a default value
            PhpArray options_arr = null;
            long     flags       = 0;

            // process options

            if (options.IsSet)
            {
                options_arr = options.AsArray();
                if (options_arr != null)
                {
                    // [flags]
                    if (options_arr.TryGetValue("flags", out var flagsval))
                    {
                        flagsval.IsLong(out flags);
                    }

                    // [default]
                    if (options_arr.TryGetValue("default", out var defaultval))
                    {
                        @default = defaultval;
                    }

                    // ...
                }
                else
                {
                    options.IsLong(out flags);
                }
            }

            switch (filter)
            {
            //
            // SANITIZE
            //

            case (int)FilterSanitize.FILTER_DEFAULT:
                return((PhpValue)variable.ToString(ctx));

            case (int)FilterSanitize.EMAIL:
                // Remove all characters except letters, digits and !#$%&'*+-/=?^_`{|}~@.[].
                return((PhpValue)FilterSanitizeString(variable.ToString(ctx), (c) =>
                                                      (int)c <= 0x7f && (Char.IsLetterOrDigit(c) ||
                                                                         c == '!' || c == '#' || c == '$' || c == '%' || c == '&' || c == '\'' ||
                                                                         c == '*' || c == '+' || c == '-' || c == '/' || c == '=' || c == '!' ||
                                                                         c == '?' || c == '^' || c == '_' || c == '`' || c == '{' || c == '|' ||
                                                                         c == '}' || c == '~' || c == '@' || c == '.' || c == '[' || c == ']')));

            //
            // VALIDATE
            //

            case (int)FilterValidate.URL:
                return(Uri.TryCreate(variable.ToString(ctx), UriKind.Absolute, out var uri)
                        ? (PhpValue)uri.AbsoluteUri
                        : PhpValue.False);

            case (int)FilterValidate.EMAIL:
            {
                var str = variable.ToString(ctx);
                return(RegexUtilities.IsValidEmail(str)
                            ? (PhpValue)str
                            : PhpValue.False);
            }

            case (int)FilterValidate.INT:
            {
                int result;
                if (int.TryParse((PhpVariable.AsString(variable) ?? string.Empty).Trim(), out result))
                {
                    if (Operators.IsSet(options))
                    {
                        PhpException.ArgumentValueNotSupported("options", "!null");
                    }

                    return((PhpValue)result);         // TODO: options: min_range, max_range
                }
                else
                {
                    return(@default);
                }
            }

            case (int)FilterValidate.BOOLEAN:
            {
                if (variable.IsBoolean(out var b))
                {
                    return(b);
                }

                var varstr = variable.ToString(ctx);

                // TRUE for "1", "true", "on" and "yes".

                if (varstr.EqualsOrdinalIgnoreCase("1") ||
                    varstr.EqualsOrdinalIgnoreCase("true") ||
                    varstr.EqualsOrdinalIgnoreCase("on") ||
                    varstr.EqualsOrdinalIgnoreCase("yes"))
                {
                    return(PhpValue.True);
                }

                //
                if ((flags & FILTER_NULL_ON_FAILURE) == FILTER_NULL_ON_FAILURE)
                {
                    // FALSE is for "0", "false", "off", "no", and "",
                    // NULL for all non-boolean values

                    if (varstr.Length == 0 ||
                        varstr.EqualsOrdinalIgnoreCase("0") ||
                        varstr.EqualsOrdinalIgnoreCase("false") ||
                        varstr.EqualsOrdinalIgnoreCase("off"))
                    {
                        return(PhpValue.False);
                    }
                    else
                    {
                        return(PhpValue.Null);
                    }
                }
                else
                {
                    // FALSE otherwise
                    return(PhpValue.False);
                }
            }

            case (int)FilterValidate.REGEXP:
            {
                // options = options['regexp']
                if (options_arr != null &&
                    options_arr.TryGetValue("regexp", out var regexpval))
                {
                    if (PCRE.preg_match(ctx, regexpval.ToString(ctx), variable.ToString(ctx)) > 0)
                    {
                        return(variable);
                    }
                }
                else
                {
                    PhpException.InvalidArgument("options", string.Format(Resources.LibResources.option_missing, "regexp"));
                }

                return(PhpValue.False);
            }

            default:
                PhpException.ArgumentValueNotSupported(nameof(filter), filter);
                break;
            }

            return(PhpValue.False);
        }
Exemplo n.º 26
0
        public static PhpValue curl_getinfo(CURLResource ch, int option = 0)
        {
            if (ch == null)
            {
                PhpException.ArgumentNull(nameof(ch));
                return(PhpValue.Null);
            }

            var r = ch.Result ?? CURLResponse.Empty;

            switch (option)
            {
            case 0:
                // array of all information
                var arr = new PhpArray(38)
                {
                    { "url", ch.Url ?? string.Empty },
                    { "content_type", r.ContentType },
                    { "http_code", (long)r.StatusCode },
                    { "header_size", r.HeaderSize },
                    { "filetime", r.LastModifiedTimeStamp },
                    { "total_time", r.TotalTime.TotalSeconds },
                    { "download_content_length", r.ContentLength },
                    { "redirect_url", ch.FollowLocation&& r.ResponseUri != null ? r.ResponseUri.AbsoluteUri : string.Empty },
                    //{ "http_version", CURL_HTTP_VERSION_*** }
                    //{ "protocol", CURLPROTO_*** },
                    //{ "scheme", STRING },
                };

                if (ch.RequestHeaders != null)
                {
                    arr["request_header"] = ch.RequestHeaders;
                }

                return(arr);

            case CURLConstants.CURLINFO_EFFECTIVE_URL:
                return(ch.Url ?? string.Empty);

            case CURLConstants.CURLINFO_REDIRECT_URL:
                return(ch.FollowLocation && r.ResponseUri != null ? r.ResponseUri.AbsoluteUri : string.Empty);

            case CURLConstants.CURLINFO_HTTP_CODE:
                return((int)r.StatusCode);

            case CURLConstants.CURLINFO_FILETIME:
                return(r.LastModifiedTimeStamp);

            case CURLConstants.CURLINFO_CONTENT_TYPE:
                return(r.ContentType);

            case CURLConstants.CURLINFO_CONTENT_LENGTH_DOWNLOAD:
                return(r.ContentLength);

            case CURLConstants.CURLINFO_TOTAL_TIME:
                return(r.TotalTime.TotalSeconds);

            case CURLConstants.CURLINFO_PRIVATE:
                return(Operators.IsSet(r.Private) ? r.Private.DeepCopy() : PhpValue.False);

            case CURLConstants.CURLINFO_COOKIELIST:
                return((ch.CookieContainer != null && ch.Result != null) ? CreateCookiePhpArray(ch.Result.Cookies) : PhpArray.Empty);

            case CURLConstants.CURLINFO_HEADER_SIZE:
                return(r.HeaderSize);

            case CURLConstants.CURLINFO_HEADER_OUT:
                return(r.RequestHeaders ?? PhpValue.False);

            default:
                PhpException.ArgumentValueNotSupported(nameof(option), option);
                return(PhpValue.False);
            }
        }
Exemplo n.º 27
0
        internal static bool TrySetOption(this CURLResource ch, int option, PhpValue value)
        {
            switch (option)
            {
            case CURLOPT_URL: return((ch.Url = value.AsString()) != null);

            case CURLOPT_DEFAULT_PROTOCOL: return((ch.DefaultSheme = value.AsString()) != null);

            case CURLOPT_HTTPGET: if (value.ToBoolean())
                {
                    ch.Method = WebRequestMethods.Http.Get;
                }
                break;

            case CURLOPT_POST: if (value.ToBoolean())
                {
                    ch.Method = WebRequestMethods.Http.Post;
                }
                break;

            case CURLOPT_PUT: if (value.ToBoolean())
                {
                    ch.Method = WebRequestMethods.Http.Put;
                }
                break;

            case CURLOPT_NOBODY: if (value.ToBoolean())
                {
                    ch.Method = WebRequestMethods.Http.Head;
                }
                break;

            case CURLOPT_CUSTOMREQUEST: return((ch.Method = value.AsString()) != null);

            case CURLOPT_POSTFIELDS: ch.PostFields = value.GetValue().DeepCopy(); break;

            case CURLOPT_FOLLOWLOCATION: ch.FollowLocation = value.ToBoolean(); break;

            case CURLOPT_MAXREDIRS: ch.MaxRedirects = (int)value.ToLong(); break;

            case CURLOPT_REFERER: return((ch.Referer = value.AsString()) != null);

            case CURLOPT_RETURNTRANSFER:
                ch.ProcessingResponse = value.ToBoolean()
                        ? ProcessMethod.Return
                        : ProcessMethod.StdOut;
                break;

            case CURLOPT_HEADER:
                ch.ProcessingHeaders = value.ToBoolean()
                        ? ProcessMethod.StdOut // NOTE: if ProcessingResponse is RETURN, RETURN headers as well
                        : ProcessMethod.Ignore;
                break;

            case CURLOPT_HTTPHEADER: ch.Headers = value.GetValue().DeepCopy().ToArray(); break;

            case CURLOPT_COOKIE: return((ch.CookieHeader = value.AsString()) != null);

            case CURLOPT_COOKIEFILE: ch.CookieFileSet = true; break;

            case CURLOPT_FILE: return(TryProcessMethodFromStream(value, ProcessMethod.StdOut, ref ch.ProcessingResponse));

            case CURLOPT_INFILE: return(TryProcessMethodFromStream(value, ProcessMethod.Ignore, ref ch.ProcessingRequest, readable: true));

            case CURLOPT_WRITEHEADER: return(TryProcessMethodFromStream(value, ProcessMethod.Ignore, ref ch.ProcessingHeaders));

            //case CURLOPT_STDERR: return TryProcessMethodFromStream(value, ProcessMethod.Ignore, ref ch.ProcessingErr);

            case CURLOPT_HEADERFUNCTION: return(TryProcessMethodFromCallable(value, ProcessMethod.Ignore, ref ch.ProcessingHeaders));

            case CURLOPT_WRITEFUNCTION: return(TryProcessMethodFromCallable(value, ProcessMethod.StdOut, ref ch.ProcessingResponse));

            //case CURLOPT_READFUNCTION:
            //case CURLOPT_PROGRESSFUNCTION:

            case CURLOPT_USERAGENT: return((ch.UserAgent = value.AsString()) != null);

            case CURLOPT_BINARYTRANSFER: break;       // no effect

            case CURLOPT_PRIVATE: ch.Private = value.GetValue().DeepCopy(); break;

            case CURLOPT_TIMEOUT: { if (value.IsLong(out long l))
                                    {
                                        ch.Timeout = (int)l * 1000;
                                    }
                                    break; }

            case CURLOPT_TIMEOUT_MS: { if (value.IsLong(out long l))
                                       {
                                           ch.Timeout = (int)l;
                                       }
                                       break; }

            case CURLOPT_CONNECTTIMEOUT: return(false);         // TODO: is there an alternative in .NET ?

            case CURLOPT_CONNECTTIMEOUT_MS: return(false);      // TODO: is there an alternative in .NET ?

            case CURLOPT_BUFFERSIZE:
            {
                if (value.IsLong(out long l) && l < int.MaxValue && l >= 0)
                {
                    ch.BufferSize = (int)l;
                    return(true);
                }
                return(false);
            }

            case CURLOPT_EXPECT_100_TIMEOUT_MS: { if (value.IsLong(out long l))
                                                  {
                                                      ch.ContinueTimeout = (int)l;
                                                  }
                                                  break; }

            case CURLOPT_HTTP_VERSION:
                switch ((int)value.ToLong())
                {
                case CURL_HTTP_VERSION_NONE: ch.ProtocolVersion = null; break;

                case CURL_HTTP_VERSION_1_0: ch.ProtocolVersion = HttpVersion.Version10; break;

                case CURL_HTTP_VERSION_1_1: ch.ProtocolVersion = HttpVersion.Version11; break;

                case CURL_HTTP_VERSION_2_0:                                                 // == CURL_HTTP_VERSION_2:
                case CURL_HTTP_VERSION_2TLS: ch.ProtocolVersion = new Version(2, 0); break; // HttpVersion.Version20

                default: return(false);
                }
                break;

            case CURLOPT_USERNAME: ch.Username = value.ToString(); break;

            case CURLOPT_USERPWD: (ch.Username, ch.Password) = SplitUserPwd(value.ToString()); break;

            case CURLOPT_PROTOCOLS: ch.Protocols = (int)value.ToLong(); break;

            case CURLOPT_REDIR_PROTOCOLS:
                PhpException.ArgumentValueNotSupported(nameof(option), nameof(CURLOPT_REDIR_PROTOCOLS));
                break;

            case CURLOPT_SSL_VERIFYHOST:
            case CURLOPT_SSL_VERIFYPEER:
            case CURLOPT_SSL_VERIFYSTATUS:
                // always enabled
                break;

            default:
                PhpException.ArgumentValueNotSupported(nameof(option), TryGetOptionName(option));
                return(false);
            }

            return(true);
        }
Exemplo n.º 28
0
        /// <summary>
        /// Opens a new SocketStream
        /// </summary>
        internal static SocketStream Connect(string remoteSocket, int port, out int errno, out string errstr,
                                             double timeout, SocketOptions flags, StreamContext /*!*/ context)
        {
            errno  = 0;
            errstr = null;

            if (remoteSocket == null)
            {
                PhpException.ArgumentNull("remoteSocket");
                return(null);
            }

            // TODO: extract schema (tcp://, udp://) and port from remoteSocket
            // Uri uri = Uri.TryCreate(remoteSocket);
            ProtocolType protocol = ProtocolType.Tcp;

            if (remoteSocket.Contains("://"))
            {
                String[] separator   = { "://" };
                String[] socketParts = remoteSocket.Split(separator, 2, StringSplitOptions.None);
                switch (socketParts[0])
                {
                case "udp":
                    protocol = ProtocolType.Udp;
                    break;

                case "tcp":
                default:
                    protocol = ProtocolType.Tcp;
                    break;
                }
                remoteSocket = socketParts[1];
            }

            if (remoteSocket.Contains(":"))
            {
                Char[]   separator   = { ':' };
                String[] socketParts = remoteSocket.Split(separator, 2, StringSplitOptions.None);
                remoteSocket = socketParts[0];

                int result = 0;
                if (socketParts[1] != "" && int.TryParse(socketParts[1], out result) &&
                    (0 < result && result < 65536))
                {
                    port = result;
                }
            }

            if (Double.IsNaN(timeout))
            {
                timeout = Configuration.Local.FileSystem.DefaultSocketTimeout;
            }

            // TODO:
            if (flags != SocketOptions.None && flags != SocketOptions.Asynchronous)
            {
                PhpException.ArgumentValueNotSupported("flags", (int)flags);
            }

            try
            {
                // workitem 299181; for remoteSocket as IPv4 address it results in IPv6 address
                //IPAddress address = System.Net.Dns.GetHostEntry(remoteSocket).AddressList[0];

                IPAddress address;
                if (!IPAddress.TryParse(remoteSocket, out address)) // if remoteSocket is not a valid IP address then lookup the DNS
                {
                    address = System.Net.Dns.GetHostEntry(remoteSocket).AddressList[0];
                }

                Socket socket = new Socket(address.AddressFamily, SocketType.Stream, protocol);

                IAsyncResult res = socket.BeginConnect(
                    new IPEndPoint(address, port),
                    new AsyncCallback(StreamSocket.ConnectResultCallback),
                    socket);

                int msec = 0;
                while (!res.IsCompleted)
                {
                    Thread.Sleep(100);
                    msec += 100;
                    if (msec / 1000.0 > timeout)
                    {
                        PhpException.Throw(PhpError.Warning, LibResources.GetString("socket_open_timeout",
                                                                                    FileSystemUtils.StripPassword(remoteSocket)));
                        return(null);
                    }
                }
                socket.EndConnect(res);

                //        socket.Connect(new IPEndPoint(address, port));
                return(new SocketStream(socket, remoteSocket, context, (flags & SocketOptions.Asynchronous) == SocketOptions.Asynchronous));
            }
            catch (SocketException e)
            {
                errno  = e.ErrorCode;
                errstr = e.Message;
            }
            catch (System.Exception e)
            {
                errno  = -1;
                errstr = e.Message;
            }

            PhpException.Throw(PhpError.Warning, LibResources.GetString("socket_open_error",
                                                                        FileSystemUtils.StripPassword(remoteSocket), errstr));
            return(null);
        }
Exemplo n.º 29
0
        /// <summary>
        /// Filters a variable with a specified filter.
        /// </summary>
        /// <param name="ctx">Runtime context.</param>
        /// <param name="variable">Value to filter.</param>
        /// <param name="filter">The ID of the filter to apply.</param>
        /// <param name="options">Associative array of options or bitwise disjunction of flags. If filter accepts options, flags can be provided in "flags" field of array. For the "callback" filter, callback type should be passed. The callback must accept one argument, the value to be filtered, and return the value after filtering/sanitizing it.</param>
        /// <returns>Returns the filtered data, or <c>false</c> if the filter fails.</returns>
        public static PhpValue filter_var(Context ctx, PhpValue variable, int filter /*= FILTER_DEFAULT*/, PhpValue options /*= NULL*/)
        {
            switch (filter)
            {
            //
            // SANITIZE
            //

            case (int)FilterSanitize.FILTER_DEFAULT:
                return((PhpValue)variable.ToString(ctx));

            case (int)FilterSanitize.EMAIL:
                // Remove all characters except letters, digits and !#$%&'*+-/=?^_`{|}~@.[].
                return((PhpValue)FilterSanitizeString(variable.ToString(ctx), (c) =>
                                                      (int)c <= 0x7f && (Char.IsLetterOrDigit(c) ||
                                                                         c == '!' || c == '#' || c == '$' || c == '%' || c == '&' || c == '\'' ||
                                                                         c == '*' || c == '+' || c == '-' || c == '/' || c == '=' || c == '!' ||
                                                                         c == '?' || c == '^' || c == '_' || c == '`' || c == '{' || c == '|' ||
                                                                         c == '}' || c == '~' || c == '@' || c == '.' || c == '[' || c == ']')));

            //
            // VALIDATE
            //

            case (int)FilterValidate.EMAIL:
            {
                var str = variable.ToString(ctx);
                return(RegexUtilities.IsValidEmail(str) ? (PhpValue)str : PhpValue.False);
            }

            case (int)FilterValidate.INT:
            {
                int result;
                if (int.TryParse((PhpVariable.AsString(variable) ?? string.Empty).Trim(), out result))
                {
                    if (!options.IsNull)
                    {
                        PhpException.ArgumentValueNotSupported("options", "!null");
                    }
                    return((PhpValue)result);         // TODO: options: min_range, max_range
                }
                else
                {
                    return(PhpValue.False);
                }
            }

            case (int)FilterValidate.REGEXP:
            {
                PhpArray optarray;
                // options = options['options']['regexp']
                if ((optarray = options.ArrayOrNull()) != null &&
                    optarray.TryGetValue("options", out options) && (optarray = options.ArrayOrNull()) != null &&
                    optarray.TryGetValue("regexp", out options))
                {
                    if (PCRE.preg_match(ctx, options.ToString(ctx), variable.ToString(ctx)) > 0)
                    {
                        return(variable);
                    }
                }
                else
                {
                    PhpException.InvalidArgument("options", string.Format(Resources.LibResources.option_missing, "regexp"));
                }

                return(PhpValue.False);
            }

            default:
                PhpException.ArgumentValueNotSupported(nameof(filter), filter);
                break;
            }

            return(PhpValue.False);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Filters a variable with a specified filter.
        /// </summary>
        /// <param name="ctx">Runtime context.</param>
        /// <param name="variable">Value to filter.</param>
        /// <param name="filter">The ID of the filter to apply.</param>
        /// <param name="options">Associative array of options or bitwise disjunction of flags. If filter accepts options, flags can be provided in "flags" field of array. For the "callback" filter, callback type should be passed. The callback must accept one argument, the value to be filtered, and return the value after filtering/sanitizing it.</param>
        /// <returns>Returns the filtered data, or <c>false</c> if the filter fails.</returns>
        public static PhpValue filter_var(Context ctx, PhpValue variable, int filter = FILTER_DEFAULT, PhpValue options = default(PhpValue))
        {
            var      @default    = PhpValue.False; // a default value
            PhpArray options_arr = null;
            long     flags       = 0;

            // process options

            if (Operators.IsSet(options))
            {
                options_arr = options.AsArray();
                if (options_arr != null)
                {
                    // [flags]
                    if (options_arr.TryGetValue("flags", out var flagsval))
                    {
                        flagsval.IsLong(out flags);
                    }

                    // [options] => { "min_range" => ??, "default" => ?? }
                    if (options_arr.TryGetValue("options", out var optionsval) && optionsval.IsPhpArray(out var opts_arr))
                    {
                        // [default]
                        if (opts_arr.TryGetValue("default", out var defaultval))
                        {
                            @default = defaultval;
                        }
                    }
                }
                else
                {
                    options.IsLong(out flags);
                }
            }

            switch (filter)
            {
            //
            // SANITIZE
            //

            case (int)FilterSanitize.FILTER_DEFAULT:
                return((PhpValue)variable.ToString(ctx));

            case (int)FilterSanitize.EMAIL:
                // Remove all characters except letters, digits and !#$%&'*+-/=?^_`{|}~@.[].
                return((PhpValue)FilterSanitizeString(variable.ToString(ctx), (c) =>
                                                      (int)c <= 0x7f && (Char.IsLetterOrDigit(c) ||
                                                                         c == '!' || c == '#' || c == '$' || c == '%' || c == '&' || c == '\'' ||
                                                                         c == '*' || c == '+' || c == '-' || c == '/' || c == '=' || c == '!' ||
                                                                         c == '?' || c == '^' || c == '_' || c == '`' || c == '{' || c == '|' ||
                                                                         c == '}' || c == '~' || c == '@' || c == '.' || c == '[' || c == ']')));

            //
            // VALIDATE
            //

            case (int)FilterValidate.URL:

                // TODO: protocol may be ommited, try to add "http://" if fails

                if (Uri.TryCreate(variable.ToString(ctx), UriKind.Absolute, out var uri))
                {
                    if (uri.IsFile && !uri.OriginalString.StartsWith(uri.Scheme, StringComparison.OrdinalIgnoreCase))
                    {
                        // quick check the file:// was just added on linux impl. of Uri.Parse
                        return(@default);
                    }

                    if (flags != 0)
                    {
                        // CONSIDER: rather use `Web.parse_url()` ...
                        var uriflags = (FilterFlag)flags;
                        //if ((uriflags & FilterFlag.PATH_REQUIRED) == FilterFlag.PATH_REQUIRED && ...)
                    }

                    return(uri.AbsoluteUri);
                }
                return(@default);

            case (int)FilterValidate.EMAIL:
            {
                return(variable.IsString(out var str) && RegexUtilities.IsValidEmail(str)
                            ? (PhpValue)str
                            : @default);
            }

            case (int)FilterValidate.IP:
                if (System.Net.IPAddress.TryParse(variable.ToString(ctx), out var addr))
                {
                    if (flags != 0)
                    {
                        // validate flags:
                        if ((addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6 && (flags & (int)FilterFlag.IPV6) == 0) ||
                            (addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork && (flags & (int)FilterFlag.IPV4) == 0))
                        {
                            return(@default);
                        }

                        if ((flags & (int)FilterFlag.NO_PRIV_RANGE) == (int)FilterFlag.NO_PRIV_RANGE)
                        {
                            /*
                             * Fails validation for the IPv4 ranges: 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16.
                             * Fails validation for the IPv6 addresses starting with FD or FC.
                             */
                            throw new NotImplementedException();
                        }

                        if ((flags & (int)FilterFlag.NO_PRIV_RANGE) == (int)FilterFlag.NO_RES_RANGE)
                        {
                            /*
                             * Fails validation for IPv4 ranges: 0.0.0.0/8, 169.254.0.0/16, 127.0.0.0/8 and 240.0.0.0/4.
                             * Fails validation for IPv6 ranges: ::1/128, ::/128, ::ffff:0:0/96 and fe80::/10.
                             */
                            throw new NotImplementedException();
                        }
                    }

                    return(addr.ToString());
                }
                else
                {
                    return(@default);
                }

            case (int)FilterValidate.INT:
            {
                int result;
                if (int.TryParse((PhpVariable.AsString(variable) ?? string.Empty).Trim(), out result))
                {
                    if (Operators.IsSet(options))
                    {
                        PhpException.ArgumentValueNotSupported("options", "!null");
                    }

                    return((PhpValue)result);         // TODO: options: min_range, max_range
                }
                else
                {
                    return(@default);
                }
            }

            case (int)FilterValidate.BOOLEAN:
            {
                if (variable.IsBoolean(out var b))
                {
                    return(b);
                }

                var varstr = variable.ToString(ctx);

                // TRUE for "1", "true", "on" and "yes".

                if (varstr.EqualsOrdinalIgnoreCase("1") ||
                    varstr.EqualsOrdinalIgnoreCase("true") ||
                    varstr.EqualsOrdinalIgnoreCase("on") ||
                    varstr.EqualsOrdinalIgnoreCase("yes"))
                {
                    return(PhpValue.True);
                }

                //
                if ((flags & FILTER_NULL_ON_FAILURE) == FILTER_NULL_ON_FAILURE)
                {
                    // FALSE is for "0", "false", "off", "no", and "",
                    // NULL for all non-boolean values

                    if (varstr.Length == 0 ||
                        varstr.EqualsOrdinalIgnoreCase("0") ||
                        varstr.EqualsOrdinalIgnoreCase("false") ||
                        varstr.EqualsOrdinalIgnoreCase("off"))
                    {
                        return(PhpValue.False);
                    }
                    else
                    {
                        return(PhpValue.Null);
                    }
                }
                else
                {
                    // FALSE otherwise
                    return(PhpValue.False);
                }
            }

            case (int)FilterValidate.REGEXP:
            {
                // options = options['regexp']
                if (options_arr != null &&
                    options_arr.TryGetValue("regexp", out var regexpval))
                {
                    if (PCRE.preg_match(ctx, regexpval.ToString(ctx), variable.ToString(ctx)) > 0)
                    {
                        return(variable);
                    }
                }
                else
                {
                    PhpException.InvalidArgument("options", string.Format(Resources.LibResources.option_missing, "regexp"));
                }

                return(@default);
            }

            case FILTER_CALLBACK:
                // options = ['options' => $callback]
                if (options_arr != null &&
                    options_arr.TryGetValue("options", out var callbackvar))
                {
                    return(callbackvar.AsCallable().Invoke(ctx, variable));
                }

                return(@default);

            default:
                PhpException.ArgumentValueNotSupported(nameof(filter), filter);
                break;
            }

            return(PhpValue.False);
        }