Esempio n. 1
0
        public void __construct(Context ctx, PhpValue name)
        {
            Debug.Assert(_routine == null, "Subsequent call not allowed.");

            object instance;
            var    str = name.ToStringOrNull();

            if (str != null)
            {
                _closure = null;
                _routine = ctx.GetDeclaredFunction(str) ?? throw new ReflectionException(string.Format(Resources.LibResources.function_does_not_exist, str));
            }
            else if ((instance = name.AsObject()) != null)
            {
                if (instance is Closure closure)
                {
                    _closure = closure;
                    _routine = closure.Callable() as RoutineInfo;
                    // TODO: handle its $this parameter and use parameters
                }
            }

            if (_routine == null)
            {
                throw new ReflectionException();
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Internal image save.
        /// </summary>
        /// <param name="ctx">Runtime context.</param>
        /// <param name="im">Image resource.</param>
        /// <param name="to">Optional. Filename or stream. If not specified the functiona saves the image to output stream.</param>
        /// <param name="saveaction">Callback that actually save the image to given stream. Called when all checks pass.</param>
        /// <returns>True if save succeeded.</returns>
        static bool imagesave(Context ctx, PhpResource im, PhpValue to /* = null*/, Action <Image <Rgba32>, Stream> saveaction)
        {
            Debug.Assert(saveaction != null);

            // check the gd2 resource
            var img = PhpGdImageResource.ValidImage(im);

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

            try
            {
                // not specified stream or filename -> save to the output stream
                if (to.IsEmpty)
                {
                    saveaction(img.Image, ctx.OutputStream);
                    return(true);
                }

                // filename specified?
                var filename = to.ToStringOrNull();
                if (filename != null)
                {
                    using (var stream = File.OpenWrite(Path.Combine(ctx.WorkingDirectory, filename)))
                    {
                        saveaction(img.Image, stream);
                    }

                    return(true);
                }

                // to a PHP stream ?
                // validate the stream resource, outputs warning in case of invalid resource
                var phpstream = PhpStream.GetValid(to.AsObject() as PhpResource, FileAccess.Write);
                if (phpstream == null)
                {
                    return(false);
                }

                // save image to byte[] and pass it to php stream

                var ms = new MemoryStream();

                saveaction(img.Image, ms);

                phpstream.WriteBytes(ms.ToArray());
                phpstream.Flush();

                // stream is closed after the operation
                phpstream.Dispose();
            }
            catch
            {
                return(false);
            }

            return(true);
        }
Esempio n. 3
0
        public void __construct(Context ctx, PhpValue name)
        {
            Debug.Assert(_routine == null, "Subsequent call not allowed.");

            object instance;
            var    str = name.ToStringOrNull();

            if (str != null)
            {
                _routine = ctx.GetDeclaredFunction(str);
            }
            else if ((instance = name.AsObject()) != null)
            {
                if (instance is Closure)
                {
                    // _routine = ((Closure)instance).routine; // TODO: handle its $this parameter and use parameters
                    throw new NotImplementedException();
                }
            }

            if (_routine == null)
            {
                throw new ArgumentException();  // TODO: ReflectionException
            }
        }
Esempio n. 4
0
        //void __clone() { throw new NotImplementedException(); }
        public void __construct(Context ctx, PhpValue @class, string name)
        {
            var classname = @class.ToStringOrNull();

            if (classname != null)
            {
                var tinfo = ctx.GetDeclaredTypeOrThrow(classname, true);
                if (tinfo != null)
                {
                    _pinfo = tinfo.GetDeclaredProperty(name);
                }
            }

            if (_pinfo == null)
            {
                throw new ReflectionException();
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Resolves type of <paramref name="class"/>.
        /// </summary>
        /// <param name="ctx">Context.</param>
        /// <param name="class">Either string or class instance. Otherwise an exception is thrown.</param>
        /// <returns>Type info. Cannot get <c>null</c>.</returns>
        /// <exception cref="ReflectionException">In case <paramref name="class"/> does not exist or <paramref name="class"/> is not a string or object.</exception>
        public static PhpTypeInfo ResolvePhpTypeInfo(Context ctx, PhpValue @class)
        {
            object instance;

            var classname = @class.ToStringOrNull();

            if (classname != null)
            {
                return(ctx.GetDeclaredType(classname, true)
                       ?? throw new ReflectionException(string.Format(Resources.Resources.class_does_not_exist, classname)));
            }
            else if ((instance = @class.AsObject()) != null)
            {
                return(instance.GetPhpTypeInfo());
            }
            else
            {
                throw new ReflectionException(string.Format(ErrResources.invalid_argument_type, nameof(@class), "string or object"));
            }
        }
Esempio n. 6
0
        internal static PhpTypeInfo ResolvePhpTypeInfo(Context ctx, PhpValue @class)
        {
            object instance;

            var classname = @class.ToStringOrNull();

            if (classname != null)
            {
                return(ctx.GetDeclaredType(classname, true));
            }
            else if ((instance = @class.AsObject()) != null)
            {
                return(instance.GetPhpTypeInfo());
            }
            else
            {
                // argument type exception
            }

            return(null);
        }
Esempio n. 7
0
            /// <summary>
            /// Convert value into <see cref="IPhpCallable"/> allowing method names declared on <see cref="HandlerObject"/>.
            /// </summary>
            internal IPhpCallable ToCallback(PhpValue value)
            {
                // empty variable
                if (value.IsEmpty)
                {
                    return(null);
                }

                // method name given as string:
                if (this.HandlerObject != null)
                {
                    var name = value.ToStringOrNull();
                    if (name != null)
                    {
                        return(PhpCallback.Create(this.HandlerObject, name, default(RuntimeTypeHandle)));
                    }
                }

                // default PHP callback:
                return(value.AsCallable(default(RuntimeTypeHandle)));
            }
Esempio n. 8
0
        /// <inheritDoc />
        public bool bindValue(PhpValue parameter, PhpValue value, PDO.PARAM data_type = (PDO.PARAM) PDO.PARAM_STR)
        {
            Debug.Assert(this.m_cmd != null);

            IDbDataParameter param = null;

            if (m_namedAttr)
            {
                // Mixed parameters not allowed
                if (m_positionalAttr)
                {
                    m_pdo.HandleError(new PDOException("Mixed parameters mode not allowed. Use either only positional, or only named parameters."));
                    return(false);
                }

                string key = parameter.AsString();
                if (key == null)
                {
                    m_pdo.HandleError(new PDOException("Supplied parameter name must be a string."));
                    return(false);
                }

                if (key.Length > 0 && key[0] == ':')
                {
                    key = key.Substring(1);
                }

                param = m_cmd.Parameters[key];

                //rewrite the bounded params dictionary
                if (HasParamsBound)
                {
                    if (m_boundParams.ContainsKey(key))
                    {
                        m_boundParams.Remove(key);
                    }
                }
            }
            else if (m_positionalAttr)
            {
                if (!parameter.IsInteger())
                {
                    m_pdo.HandleError(new PDOException("Supplied parameter index must be an integer."));
                    return(false);
                }
                int paramIndex = ((int)parameter) - 1;

                if (paramIndex < m_positionalPlaceholders.Count)
                {
                    param = m_cmd.Parameters[paramIndex];
                }

                //rewrite the bounded params dictionary
                if (HasParamsBound)
                {
                    if (m_boundParams.ContainsKey(paramIndex.ToString()))
                    {
                        m_boundParams.Remove(paramIndex.ToString());
                    }
                }
            }
            else
            {
                m_pdo.HandleError(new PDOException("No parameter mode set yet for this Statement. Possibly no parameters required?"));
                return(false);
            }

            if (param == null)
            {
                m_pdo.HandleError(new PDOException("No matching parameter found."));
                return(false);
            }

            switch (data_type)
            {
            case PDO.PARAM.PARAM_INT:
                if (value.IsInteger())
                {
                    param.DbType = DbType.Int32;
                    param.Value  = (int)value;
                }
                else
                {
                    m_pdo.HandleError(new PDOException("Parameter type does not match the declared type."));
                    return(false);
                }
                break;

            case PDO.PARAM.PARAM_STR:
                string str = null;
                if ((str = value.ToStringOrNull()) != null)
                {
                    param.DbType = DbType.String;
                    param.Value  = str;
                }
                else
                {
                    m_pdo.HandleError(new PDOException("Parameter type does not match the declared type."));
                    return(false);
                }
                break;

            case PDO.PARAM.PARAM_BOOL:
                if (value.IsBoolean())
                {
                    param.DbType = DbType.Boolean;
                    param.Value  = value.ToBoolean();
                }
                else
                {
                    m_pdo.HandleError(new PDOException("Parameter type does not match the declared type."));
                    return(false);
                }
                break;

            case PDO.PARAM.PARAM_LOB:
                byte[] bytes = null;
                if ((bytes = value.ToBytesOrNull()) != null)
                {
                    param.DbType = DbType.Binary;
                    param.Value  = bytes;
                }
                else
                {
                    m_pdo.HandleError(new PDOException("Parameter type does not match the declared type."));
                    return(false);
                }
                break;

            // Currently not supported by any drivers
            case PDO.PARAM.PARAM_NULL:
            case PDO.PARAM.PARAM_STMT:
            default:
                throw new NotImplementedException();
            }

            return(true);
        }
Esempio n. 9
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.ToArray().DeepCopy(); break;

            case CURLOPT_ENCODING: ch.AcceptEncoding = value.ToStringOrNull().EmptyToNull(); 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;

            case CURLINFO_HEADER_OUT: ch.StoreRequestHeaders = value.ToBoolean(); break;

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

            return(true);
        }