Exemplo n.º 1
0
        public virtual void __construct(Iterator iterator, int flags = CALL_TOSTRING)
        {
            if (iterator == null)
            {
                PhpException.ArgumentNull(nameof(iterator));
            }

            _iterator = iterator;
            _flags    = flags;

            if (IsFullCacheEnabled)
            {
                _cache = PhpArray.NewEmpty();
            }
        }
Exemplo n.º 2
0
        public static object CallUserFunction(DTypeDesc caller, PhpCallback function, params object[] args)
        {
            if (function == null)
            {
                PhpException.ArgumentNull("function");
                return(null);
            }
            if (function.IsInvalid)
            {
                return(null);
            }

            // invoke the callback:
            return(PhpVariable.Dereference(function.Invoke(caller, args)));
        }
Exemplo n.º 3
0
        public static PhpResource Open(string command, PhpArray descriptors, out PhpArray pipes,
                                       string workingDirectory, PhpArray envVariables, PhpArray options)
        {
            if (descriptors == null)
            {
                PhpException.ArgumentNull("descriptors");
                pipes = null;
                return(null);
            }

            pipes = new PhpArray();
            PhpResource result = Open(command, descriptors, pipes, workingDirectory, envVariables, options);

            return(result);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Starts a process and optionally redirects its input/output/error streams to specified PHP streams.
        /// </summary>
        /// <param name="ctx">Runtime context.</param>
        /// <param name="cmd">The commandline to execute as string. Special characters have to be properly escaped, and proper quoting has to be applied.</param>
        /// <param name="descriptorspec"></param>
        /// Indexed array where the key represents the descriptor number (0 for STDIN, 1 for STDOUT, 2 for STDERR)
        /// and the value represents how to pass that descriptor to the child process.
        /// A descriptor is either an opened file resources or an integer indexed arrays
        /// containing descriptor name followed by options. Supported descriptors:
        /// <list type="bullet">
        /// <term><c>array("pipe",{mode})</c></term><description>Pipe is opened in the specified mode .</description>
        /// <term><c>array("file",{path},{mode})</c></term><description>The file is opened in the specified mode.</description>
        /// </list>
        /// <param name="pipes">
        /// Set to indexed array of file resources corresponding to the current process's ends of created pipes.
        /// </param>
        /// <param name="cwd">
        /// Working directory.
        /// </param>
        /// <param name="env"></param>
        /// <param name="other_options">
        /// Associative array containing following key-value pairs.
        ///   <list type="bullet">
        ///     <term>"suppress_errors"</term><description></description>
        ///   </list>
        /// </param>
        /// <returns>
        /// Resource representing the process.
        /// </returns>
        public static PhpResource proc_open(
            Context ctx,
            string cmd, PhpArray descriptorspec,
            out PhpArray pipes,
            string cwd = null, PhpArray env = null, PhpArray other_options = null)
        {
            if (descriptorspec == null)
            {
                PhpException.ArgumentNull(nameof(descriptorspec));
                pipes = null;
                return(null);
            }

            pipes = new PhpArray();
            return(Open(ctx, cmd, descriptorspec, pipes, cwd, env, other_options));
        }
Exemplo n.º 5
0
        public static PhpResource mssql_init(Context ctx, string procedureName, PhpResource linkIdentifier)
        {
            PhpSqlDbConnection connection = ValidConnection(ctx, linkIdentifier);

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

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

            return(new PhpSqlDbProcedure(connection, procedureName));
        }
Exemplo n.º 6
0
        public static PhpResource CreateProcedure(string procedureName, PhpResource linkIdentifier)
        {
            PhpSqlDbConnection connection = PhpSqlDbConnection.ValidConnection(linkIdentifier);

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

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

            return(new PhpSqlDbProcedure(connection, procedureName));
        }
Exemplo n.º 7
0
        public virtual object /*mixed*/ getValue(ScriptContext context, object @object)
        {
            var dobj = @object as DObject;

            if (property != null)
            {
                if (!property.IsStatic && dobj == null)
                {
                    PhpException.ArgumentNull("object");
                    return(false);
                }

                return(PhpVariable.Dereference(property.Get(dobj)));
            }

            return(false);
        }
Exemplo n.º 8
0
        public static void curl_close(Context ctx, CURLResource ch)
        {
            if (ch != null)
            {
                if (ch.TryGetOption <CurlOption_CookieJar>(out var jar))
                {
                    jar.PrintCookies(ctx, ch);
                }

                //
                ch.Dispose();
            }
            else
            {
                PhpException.ArgumentNull(nameof(ch));
            }
        }
Exemplo n.º 9
0
        public static int Apply(ScriptContext /*!*/ context, PHP.Core.Reflection.DTypeDesc caller, Iterator /*!*/ iterator, PhpCallback function, PhpArray args)
        {
            // check parameters:
            Debug.Assert(context != null);

            Debug.Assert(iterator != null, "Phalanger should not pass a null here.");

            if (function == null)
            {
                PhpException.ArgumentNull("function");
                return(-1);
            }

            // copy args into object array:
            object[] args_array;

            if (args != null)
            {
                args_array = new object[args.Count];
                args.Values.CopyTo(args_array, 0);
            }
            else
            {
                args_array = ArrayUtils.EmptyObjects;
            }

            // iterate through the iterator:
            int n = 0;

            iterator.rewind(context);

            while (PHP.Core.Convert.ObjectToBoolean(iterator.valid(context)))
            {
                if (!PHP.Core.Convert.ObjectToBoolean(function.Invoke(caller, args_array)))
                {
                    break;
                }
                n++;

                iterator.next(context);
            }

            // return amount of iterated elements:
            return(n);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Calls a function or a method defined by callback with given arguments.
        /// </summary>
        /// <param name="ctx">Current runtime context.</param>
        /// <param name="function">Target callback.</param>
        /// <param name="args">The arguments.</param>
        /// <returns>The return value.</returns>
        public static PhpValue call_user_func(Context ctx, IPhpCallable function, params PhpValue[] args)
        {
            if (function == null)
            {
                PhpException.ArgumentNull("function");
                return(PhpValue.Null);
            }
            else if (!PhpVariable.IsValidBoundCallback(ctx, function))
            {
                PhpException.InvalidArgument(nameof(function));
                return(PhpValue.Null);
            }

            Debug.Assert(args != null);

            // invoke the callback:
            return(function.Invoke(ctx, args));
        }
Exemplo n.º 11
0
        public virtual object /*void*/ setValue(ScriptContext context, object arg1, object arg2)
        {
            DObject dobj = null;
            object  value;

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

            if (property.IsStatic)
            {
                if (arg2 != Arg.Default)
                {
                    PhpException.InvalidArgumentCount("ReflectionProperty", "setValue");
                    return(false);
                }

                value = arg1;
            }
            else
            {
                if (arg2 == Arg.Default)
                {
                    PhpException.MissingArgument(2, "setValue");
                    return(false);
                }

                dobj  = arg1 as DObject;
                value = arg2;

                if (dobj == null)
                {
                    PhpException.ArgumentNull("object");
                    return(false);
                }
            }

            property.Set(dobj, value);

            return(null);
        }
        public virtual DateTimeImmutable setTimezone(DateTimeZone timezone)
        {
            if (timezone == null)
            {
                PhpException.ArgumentNull(nameof(timezone));
                return(this);
            }

            if (timezone._timezone == this.TimeZone)
            {
                return(this);
            }
            else
            {
                // convert this.Time from old TZ to new TZ
                var time = TimeZoneInfo.ConvertTime(new System_DateTime(this.Time.Ticks, DateTimeKind.Unspecified), this.TimeZone, timezone._timezone);

                return(new DateTimeImmutable(_ctx, time, timezone._timezone));
            }
        }
Exemplo n.º 13
0
        public static void LoadFile(string path, PhpCallback function)
        {
            string file = string.Empty;

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

            WebClient webclient = new WebClient();

            webclient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(
                delegate(object sender, DownloadStringCompletedEventArgs downEventArgs)
            {
                var canvas = ((ClrObject)ScriptContext.CurrentContext.AutoGlobals.Canvas.Value).RealObject as System.Windows.Controls.Canvas;

                canvas.Dispatcher.BeginInvoke(() =>
                {
                    function.Invoke(downEventArgs.Result);
                });
            }
                );

            var source_root = ((ClrObject)ScriptContext.CurrentContext.AutoGlobals.Addr.Value).RealObject as string;

            Uri baseUri = new Uri(source_root + "/", UriKind.Absolute);
            Uri uriFile = new Uri(path, UriKind.RelativeOrAbsolute);
            Uri uri     = new Uri(baseUri, uriFile);


            webclient.DownloadStringAsync(uri);

            //downloadFinished.WaitOne();

            //return XamlReader.Load(file);
        }
Exemplo n.º 14
0
        static PatternAndReplacement[] PreparePatternArray(Context ctx, PhpArray patterns_and_callbacks)
        {
            if (patterns_and_callbacks == null)
            {
                PhpException.ArgumentNull(nameof(patterns_and_callbacks));
                return(null);
            }

            var regexes = new PatternAndReplacement[patterns_and_callbacks.Count];

            int i          = 0;
            var enumerator = patterns_and_callbacks.GetFastEnumerator();

            while (enumerator.MoveNext())
            {
                var pattern  = enumerator.CurrentKey.String;
                var callback = enumerator.CurrentValue.AsCallable();

                if (TryParseRegexp(pattern, out var regex))
                {
                    var evaluator = new MatchEvaluator(match =>
                    {
                        var matches_arr = new PhpArray();
                        GroupsToPhpArray(match.PcreGroups, false, false, matches_arr);

                        return(callback
                               .Invoke(ctx, (PhpValue)matches_arr)
                               .ToStringOrThrow(ctx));
                    });

                    regexes[i++] = new PatternAndReplacement(regex, evaluator);
                }
                else
                {
                    return(null);
                }
            }

            //
            return(regexes);
        }
Exemplo n.º 15
0
        public static DObject CreateClrThread(PhpCallback /*!*/ callback, params object[] args)
        {
            if (callback == null)
            {
                PhpException.ArgumentNull("callback");
            }

            if (!callback.Bind())
            {
                return(null);
            }

            object[] copies = (args != null) ? new object[args.Length] : ArrayUtils.EmptyObjects;

            for (int i = 0; i < copies.Length; i++)
            {
                copies[i] = PhpVariable.DeepCopy(args[i]);
            }

            return(ClrObject.WrapRealObject(ThreadPool.QueueUserWorkItem(new Worker(ScriptContext.CurrentContext, copies).Run, callback)));
        }
Exemplo n.º 16
0
        /// <summary>
        /// Reads from an open directory entry.
        /// </summary>
        /// <param name="zip_entry">A directory entry returned by <see cref="zip_read(ZipArchiveResource)"/>.</param>
        /// <param name="length">The number of bytes to return.</param>
        /// <returns>Returns the data read, empty string or NULL on end of a file and on error.</returns>
        public static PhpValue zip_entry_read(ZipEntryResource zip_entry, int length = 1024)
        {
            // Although according to the PHP documentation error codes should be retrieved,
            // it returns empty strings or NULL instead
            if (zip_entry == null)
            {
                PhpException.ArgumentNull(nameof(zip_entry));
                return(PhpValue.Null);
            }

            if (zip_entry == null || !zip_entry.IsValid || zip_entry.DataStream == null)
            {
                PhpException.InvalidArgument(nameof(zip_entry));
                return(PhpValue.Create(new PhpString(string.Empty)));
            }

            if (length <= 0)
            {
                PhpException.InvalidArgument(nameof(length));
                return(PhpValue.Create(new PhpString(string.Empty)));
            }

            try
            {
                var buffer = new byte[length];
                int read   = zip_entry.DataStream.Read(buffer, 0, length);

                if (read != length)
                {
                    Array.Resize(ref buffer, read);
                }

                return(PhpValue.Create(new PhpString(buffer)));
            }
            catch (Exception e)
            {
                PhpException.Throw(PhpError.Warning, e.Message);
                return(PhpValue.Create(new PhpString(string.Empty)));
            }
        }
        /// <summary>
        /// Calls a function for every element in an iterator.
        /// </summary>
        /// <param name="ctx">Runtime context.</param>
        /// <param name="iterator">The class to iterate over.</param>
        /// <param name="function">The callback function to call on every element.
        /// Note: The function must return <c>TRUE</c> in order to continue iterating over the iterator.</param>
        /// <param name="args">Arguments to pass to the callback function.</param>
        /// <returns>The iteration count.</returns>
        public static int iterator_apply(Context ctx, Iterator iterator, IPhpCallable function, PhpArray args = null)
        {
            if (iterator == null)
            {
                throw new ArgumentNullException(nameof(iterator));
            }

            if (function == null)
            {
                PhpException.ArgumentNull(nameof(function));
                return(-1);
            }

            // construct callback arguments
            var args_array = args != null
                ? args.GetValues()
                : Array.Empty <PhpValue>();

            //
            int n = 0;

            iterator.rewind();

            while (iterator.valid())
            {
                if (function.Invoke(ctx, args_array).ToBoolean() == false)
                {
                    break;
                }

                //
                n++;
                iterator.next();
            }

            //
            return(n);
        }
Exemplo n.º 18
0
        public static bool curl_setopt_array(CURLResource ch, PhpArray options)
        {
            if (ch == null || !ch.IsValid)
            {
                PhpException.ArgumentNull(nameof(ch));
                return(false);
            }

            if (options != null)
            {
                var enumerator = options.GetFastEnumerator();
                while (enumerator.MoveNext())
                {
                    if (!enumerator.CurrentKey.IsInteger ||
                        !ch.TrySetOption(enumerator.CurrentKey.Integer, enumerator.CurrentValue))
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
Exemplo n.º 19
0
        public object getOffset(ScriptContext /*!*/ context, object datetime)
        {
            if (this.timezone == null)
            {
                return(false);
            }

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

            var dt = datetime as __PHP__DateTime;

            if (dt == null)
            {
                PhpException.InvalidArgumentType("datetime", "DateTime");
                return(false);
            }

            return((int)this.timezone.BaseUtcOffset.TotalSeconds + (this.timezone.IsDaylightSavingTime(dt.Time) ? 3600 : 0));
        }
Exemplo n.º 20
0
        //public static PhpArray stream_socket_pair(ProtocolFamily protocolFamily, SocketType type, ProtocolType protocol)
        //{
        //    PhpException.FunctionNotSupported();
        //    return null;
        //}

        #endregion

        #region Connect

        /// <summary>
        /// Opens a new SocketStream
        /// </summary>
        internal static PhpStream Connect(Context ctx, 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);
            }

            bool IsSsl = false;

            // TODO: extract schema (tcp://, udp://) and port from remoteSocket
            // Uri uri = Uri.TryCreate(remoteSocket);
            const string protoSeparator = "://";
            var          protocol       = ProtocolType.Tcp;
            var          protoIdx       = remoteSocket.IndexOf(protoSeparator, StringComparison.Ordinal);

            if (protoIdx >= 0)
            {
                var protoStr = remoteSocket.AsSpan(0, protoIdx);
                if (protoStr.Equals("udp".AsSpan(), StringComparison.Ordinal))
                {
                    protocol = ProtocolType.Udp;
                }
                else if (protoStr.Equals("ssl".AsSpan(), StringComparison.Ordinal))
                {
                    // use SSL encryption
                    IsSsl = true;
                }

                remoteSocket = remoteSocket.Substring(protoIdx + protoSeparator.Length);
            }

            var colonIdx = remoteSocket.IndexOf(':');

            if (colonIdx >= 0)
            {
                var portStr = remoteSocket.AsSpan(colonIdx + 1);
                if (portStr.Length != 0 &&
                    int.TryParse(portStr.ToString(), out var n) &&    // TODO: (perf) ReadOnlySpan<char>
                    n > 0 && n <= 0xffff)
                {
                    port = n;
                }

                remoteSocket = remoteSocket.Remove(colonIdx);
            }

            if (double.IsNaN(timeout))
            {
                timeout = ctx.Configuration.Core.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
                {
                    var addresses = System.Net.Dns.GetHostAddressesAsync(remoteSocket).Result;
                    if (addresses != null && addresses.Length != 0)
                    {
                        address = addresses[0];
                    }
                    else
                    {
                        throw new ArgumentException(nameof(remoteSocket));
                    }
                }

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

                // socket.Connect(new IPEndPoint(address, port));
                if (socket.ConnectAsync(address, port).Wait((int)(timeout * 1000)))
                {
                    if (IsSsl)
                    {
                        var options = context.GetOptions("ssl");
                        if (options != null)
                        {
                            // TODO: provide parameters based on context[ssl][verify_peer|verify_peer_name|allow_self_signed|cafile]

                            options.TryGetValue("verify_peer", out var vpvalue);
                            options.TryGetValue("verify_peer_name", out var vpnvalue);
                            options.TryGetValue("allow_self_signed", out var assvalue);
                            options.TryGetValue("cafile", out var cafilevalue);

                            Debug.WriteLineIf(vpvalue.IsSet && !vpvalue, "ssl: verify_peer not supported");
                            Debug.WriteLineIf(vpnvalue.IsSet && (bool)vpnvalue, "ssl: verify_peer_name not supported");
                            Debug.WriteLineIf(assvalue.IsSet && !assvalue, "ssl: allow_self_signed not supported");
                            Debug.WriteLineIf(cafilevalue.IsSet, "ssl: cafile not supported");
                        }

                        var sslstream = new SslStream(new NetworkStream(socket, System.IO.FileAccess.ReadWrite, true), false,
                                                      null, //(sender, certificate, chain, sslPolicyErrors) => true,
                                                      null, //(sender, targetHost, localCertificates, remoteCertificate, acceptableIssuers) => ??,
                                                      EncryptionPolicy.AllowNoEncryption);

                        sslstream.AuthenticateAsClient(remoteSocket);

                        return(new NativeStream(ctx, sslstream, null, StreamAccessOptions.Read | StreamAccessOptions.Write, remoteSocket, context)
                        {
                            IsWriteBuffered = false,
                            IsReadBuffered = false,
                        });
                    }
                    else
                    {
                        return(new SocketStream(ctx, socket, remoteSocket, context, (flags & SocketOptions.Asynchronous) != 0));
                    }
                }
                else
                {
                    Debug.Assert(!socket.Connected);
                    PhpException.Throw(PhpError.Warning, string.Format(Resources.LibResources.socket_open_timeout, FileSystemUtils.StripPassword(remoteSocket)));
                    return(null);
                }
            }
            catch (SocketException e)
            {
                errno  = (int)e.SocketErrorCode;
                errstr = e.Message;
            }
            catch (System.Exception e)
            {
                errno  = -1;
                errstr = e.Message;
            }

            PhpException.Throw(PhpError.Warning, string.Format(Resources.LibResources.socket_open_error, FileSystemUtils.StripPassword(remoteSocket), errstr));
            return(null);
        }
Exemplo n.º 21
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.º 22
0
        public static PhpBytes iconv(string in_charset, string out_charset, object str)
        {
            // check args
            if (str == null)
            {
                PhpException.ArgumentNull("str");
                return(null);
            }
            if (out_charset == null)
            {
                PhpException.ArgumentNull("out_charset");
                return(null);
            }

            // resolve out_charset
            bool transliterate, discard_ilseq;

            out_charset = ParseOutputEncoding(out_charset, out transliterate, out discard_ilseq);
            var out_encoding = ResolveEncoding(out_charset);

            if (out_encoding == null)
            {
                PhpException.Throw(PhpError.Notice, string.Format(Strings.wrong_charset, out_charset, in_charset, out_charset));
                return(null);
            }

            // out_encoding.Clone() ensures it is NOT readOnly
            // then set EncoderFallback to catch handle unconvertable characters

            out_encoding = (Encoding)out_encoding.Clone();

            var out_result = new EncoderResult();

            if (transliterate)
            {
                out_encoding.EncoderFallback = new TranslitEncoderFallback();   // transliterate unknown characters
            }
            else if (discard_ilseq)
            {
                out_encoding.EncoderFallback = new IgnoreEncoderFallback();    // ignore character and continue
            }
            else
            {
                out_encoding.EncoderFallback = new StopEncoderFallback(out_result);    // throw notice and discard all remaining characters
            }
            try
            {
                //
                if (str.GetType() == typeof(PhpBytes))
                {
                    // resolve in_charset
                    if (in_charset == null)
                    {
                        PhpException.ArgumentNull("in_charset");
                        return(null);
                    }
                    var in_encoding = ResolveEncoding(in_charset);
                    if (in_encoding == null)
                    {
                        PhpException.Throw(PhpError.Notice, string.Format(Strings.wrong_charset, in_charset, in_charset, out_charset));
                        return(null);
                    }

                    // TODO: in_encoding.Clone() ensures it is NOT readOnly, then set DecoderFallback to catch invalid byte sequences

                    // convert <in_charset> to <out_charset>
                    return(new PhpBytes(out_encoding.GetBytes(in_encoding.GetString(((PhpBytes)str).ReadonlyData))));
                }

                if (str.GetType() == typeof(string) || (str = Core.Convert.ObjectToString(str)) != null)
                {
                    // convert UTF16 to <out_charset>
                    return(new PhpBytes(out_encoding.GetBytes((string)str)));
                }
            }
            finally
            {
                if (out_result.firstFallbackCharIndex >= 0)
                {
                    // Notice: iconv(): Detected an illegal character in input string
                    PHP.Core.PhpException.Throw(Core.PhpError.Notice, Strings.illegal_character);
                }
            }

            return(null);
        }
        //public static PhpArray stream_socket_pair(ProtocolFamily protocolFamily, SocketType type, ProtocolType protocol)
        //{
        //    PhpException.FunctionNotSupported();
        //    return null;
        //}

        #endregion

        #region Connect

        /// <summary>
        /// Opens a new SocketStream
        /// </summary>
        internal static SocketStream Connect(Context ctx, 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 = ctx.Configuration.Core.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
                {
                    var addresses = System.Net.Dns.GetHostAddressesAsync(remoteSocket).Result;
                    if (addresses != null && addresses.Length != 0)
                    {
                        address = addresses[0];
                    }
                    else
                    {
                        throw new ArgumentException(nameof(remoteSocket));
                    }
                }

                var socket = new Socket(address.AddressFamily, SocketType.Stream, protocol);
                if (!socket.ConnectAsync(address, port).Wait((int)(timeout * 1000)))
                {
                    Debug.Assert(!socket.Connected);
                    PhpException.Throw(PhpError.Warning, string.Format(Resources.LibResources.socket_open_timeout, FileSystemUtils.StripPassword(remoteSocket)));
                    return(null);
                }

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

            PhpException.Throw(PhpError.Warning, string.Format(Resources.LibResources.socket_open_error, FileSystemUtils.StripPassword(remoteSocket), errstr));
            return(null);
        }
Exemplo n.º 24
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.º 25
0
        public static int Extract(Dictionary <string, object> localVariables, PhpArray /*!*/ vars, ExtractType type,
                                  string prefix)
        {
            if (vars == null)
            {
                PhpException.ArgumentNull("vars");
                return(0);
            }

            if (vars.Count == 0)
            {
                return(0);
            }

            // unfortunately, type contains flags are combined with enumeration:
            bool refs = (type & ExtractType.Refs) != 0;

            type &= ExtractType.NonFlags;

            //
            // construct the action used to set the variable into the locals/globals
            //
            Action <string /*name*/, object /*value*/> updateVariableFn; // function that writes the value to locals/globals
            Predicate <string /*name*/> containsFn;                      // function that checks if variable exists
            PhpArray globals = (localVariables != null) ? null : ScriptContext.CurrentContext.GlobalVariables;

            #region select function that writes the variable

            if (refs)
            {
                // makes a reference and writes it back (deep copy is not necessary, "no duplicate pointers" rule preserved):

                if (localVariables != null)
                {
                    updateVariableFn = (name, value) =>
                    {
                        localVariables[name] = vars[name] = PhpVariable.MakeReference(value);
                    };
                }
                else
                {
                    updateVariableFn = (name, value) =>
                    {
                        globals[name] = vars[name] = PhpVariable.MakeReference(value);
                    };
                }
            }
            else
            {
                if (localVariables != null)
                {
                    updateVariableFn = (name, value) =>
                    {
                        // deep copy the value
                        value = PhpVariable.DeepCopy(PhpVariable.Dereference(value));

                        // put into locals
                        object       item;
                        PhpReference ref_item;
                        if (localVariables.TryGetValue(name, out item) && (ref_item = item as PhpReference) != null)
                        {
                            ref_item.Value = value;
                        }
                        else
                        {
                            localVariables[name] = value;
                        }
                    };
                }
                else
                {
                    updateVariableFn = (name, value) =>
                    {
                        // deep copy the value
                        value = PhpVariable.DeepCopy(PhpVariable.Dereference(value));

                        // set the value to globals
                        object       item;
                        PhpReference ref_item;
                        if (globals.TryGetValue(name, out item) && (ref_item = item as PhpReference) != null)
                        {
                            ref_item.Value = value;
                        }
                        else
                        {
                            globals[name] = value;
                        }
                    };
                }
            }

            #endregion

            Debug.Assert(updateVariableFn != null);

            #region select function that checks if variable exists

            if (localVariables != null)
            {
                containsFn = (name) => localVariables.ContainsKey(name);
            }
            else
            {
                containsFn = (name) => globals.ContainsKey(name);
            }

            #endregion

            Debug.Assert(containsFn != null);

            //
            //
            //
            int extracted_count = 0;
            foreach (KeyValuePair <IntStringKey, object> entry in vars)
            {
                string name = entry.Key.ToString();
                if (String.IsNullOrEmpty(name) && type != ExtractType.PrefixInvalid)
                {
                    continue;
                }

                switch (type)
                {
                case ExtractType.Overwrite:

                    // anything is overwritten:

                    break;

                case ExtractType.Skip:

                    // skips existing name:
                    if (containsFn(name))
                    {
                        continue;
                    }

                    break;

                case ExtractType.IfExists:

                    // skips nonexistent name:
                    if (!containsFn(name))
                    {
                        continue;
                    }

                    break;

                case ExtractType.PrefixAll:

                    // prefix anything:
                    name = String.Concat(prefix, "_", name);

                    break;

                case ExtractType.PrefixInvalid:

                    // prefixes invalid, others are overwritten:
                    if (!PhpVariable.IsValidName(name))
                    {
                        name = String.Concat(prefix, "_", name);
                    }

                    break;

                case ExtractType.PrefixSame:

                    // prefixes existing, others are overwritten:
                    if (containsFn(name))
                    {
                        name = String.Concat(prefix, "_", name);
                    }

                    break;

                case ExtractType.PrefixIfExists:

                    // prefixes existing, others are skipped:
                    if (containsFn(name))
                    {
                        name = String.Concat(prefix, "_", name);
                    }
                    else
                    {
                        continue;
                    }

                    break;

                default:
                    PhpException.InvalidArgument("type", LibResources.GetString("arg:invalid_value"));
                    return(0);
                }

                // invalid names are skipped:
                if (PhpVariable.IsValidName(name))
                {
                    // write the value to locals or globals:
                    updateVariableFn(name, entry.Value);

                    extracted_count++;
                }
            }

            return(extracted_count);
        }
Exemplo n.º 26
0
        public static PhpString iconv(Context ctx, string in_charset, string out_charset, PhpString str)
        {
            // check args
            if (str.IsDefault)
            {
                PhpException.ArgumentNull("str");
                return(default(PhpString));
            }
            if (out_charset == null)
            {
                PhpException.ArgumentNull("out_charset");
                return(default(PhpString));
            }

            // resolve out_charset
            bool transliterate, discard_ilseq;

            out_charset = ParseOutputEncoding(out_charset, out transliterate, out discard_ilseq);
            var out_encoding = ResolveEncoding(ctx, out_charset);

            if (out_encoding == null)
            {
                PhpException.Throw(PhpError.Notice, Resources.LibResources.wrong_charset, out_charset, in_charset, out_charset);
                return(default(PhpString));
            }

            // encoding fallback
            EncoderFallback enc_fallback;
            var             out_result = new EncoderResult();

            if (transliterate)
            {
                enc_fallback = new TranslitEncoderFallback();   // transliterate unknown characters
            }
            else if (discard_ilseq)
            {
                enc_fallback = new IgnoreEncoderFallback();    // ignore character and continue
            }
            else
            {
                enc_fallback = new StopEncoderFallback(out_result);    // throw notice and discard all remaining characters
            }
            //// out_encoding.Clone() ensures it is NOT readOnly
            //// then set EncoderFallback to catch handle unconvertable characters

            //out_encoding = (Encoding)out_encoding.Clone();
            out_encoding = Encoding.GetEncoding(out_encoding.CodePage, enc_fallback, DecoderFallback.ExceptionFallback);

            try
            {
                //
                if (str.ContainsBinaryData)
                {
                    // resolve in_charset
                    if (in_charset == null)
                    {
                        PhpException.ArgumentNull("in_charset");
                        return(default(PhpString));
                    }
                    var in_encoding = ResolveEncoding(ctx, in_charset);
                    if (in_encoding == null)
                    {
                        PhpException.Throw(PhpError.Notice, Resources.LibResources.wrong_charset, in_charset, in_charset, out_charset);
                        return(default(PhpString));
                    }

                    // TODO: in_encoding.Clone() ensures it is NOT readOnly, then set DecoderFallback to catch invalid byte sequences

                    // convert <in_charset> to <out_charset>
                    return(new PhpString(out_encoding.GetBytes(str.ToString(in_encoding))));
                }
                else
                {
                    // convert UTF16 to <out_charset>
                    return(new PhpString(str.ToBytes(out_encoding)));
                }
            }
            finally
            {
                if (out_result.firstFallbackCharIndex >= 0)
                {
                    // Notice: iconv(): Detected an illegal character in input string
                    PhpException.Throw(Core.PhpError.Notice, Resources.LibResources.illegal_character);
                }
            }
        }