Exemplo n.º 1
0
        public object __construct(ScriptContext __context, object wsdl, [System.Runtime.InteropServices.OptionalAttribute()]
                                  object options)
        {
            string tmp1 = PhpVariable.AsString(wsdl);

            if (tmp1 == null)

            {
                PhpException.InvalidImplicitCast(wsdl, "string", "__construct");
                return(null);
            }

            PhpArray tmp2 = null;

            if (options != Arg.Default)

            {
                tmp2 = options as PhpArray;
                if (tmp2 == null)

                {
                    PhpException.InvalidImplicitCast(options, "PhpArray", "__construct");
                    return(null);
                }
            }
            __construct(tmp1, tmp2);
            return(null);
        }
Exemplo n.º 2
0
        public static object GetField(PhpResource resultHandle, int rowIndex, object field)
        {
            PhpSqlDbResult result = PhpSqlDbResult.ValidResult(resultHandle);

            ScriptContext context = ScriptContext.CurrentContext;

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

            string field_name;
            object field_value;

            if (field == null)
            {
                field_value = result.GetFieldValue(rowIndex, result.CurrentFieldIndex);
            }
            else if ((field_name = PhpVariable.AsString(field)) != null)
            {
                field_value = result.GetFieldValue(rowIndex, field_name);
            }
            else
            {
                field_value = result.GetFieldValue(rowIndex, Core.Convert.ObjectToInteger(field));
            }

            return(Core.Convert.Quote(field_value, context));
        }
Exemplo n.º 3
0
        public virtual object getMethod(ScriptContext /*!*/ context, object name)
        {
            if (typedesc == null)
            {
                return(false);
            }

            var nameStr = PhpVariable.AsString(name);

            if (string.IsNullOrEmpty(nameStr))
            {
                return(false);
            }

            DRoutineDesc method;

            if (typedesc.GetMethod(new Name(nameStr), typedesc, out method) == GetMemberResult.NotFound)
            {
                return(false);
            }

            return(new ReflectionMethod(context, true)
            {
                dtype = method.DeclaringType,
                method = method,
            });
        }
Exemplo n.º 4
0
        /// <summary>
        /// Gets a contents of a specified cell from a specified query result resource.
        /// </summary>
        /// <param name="ctx">PHP context.</param>
        /// <param name="resultHandle">Query result resource.</param>
        /// <param name="rowIndex">Row index.</param>
        /// <param name="field">Column (field) integer index or string name.</param>
        /// <returns>The value of the cell or <B>false</B> on failure (invalid resource or row index).</returns>
        public static PhpValue mssql_result(Context ctx, PhpResource resultHandle, int rowIndex, PhpValue field)
        {
            var result = PhpSqlDbResult.ValidResult(resultHandle);

            if (result == null)
            {
                return(PhpValue.False);
            }

            string field_name;
            object field_value;

            if (field.IsNull)
            {
                field_value = result.GetFieldValue(rowIndex, result.CurrentFieldIndex);
            }
            else if ((field_name = PhpVariable.AsString(field)) != null)
            {
                field_value = result.GetFieldValue(rowIndex, field_name);
            }
            else
            {
                field_value = result.GetFieldValue(rowIndex, (int)field.ToLong());
            }

            if (field_value == null)
            {
                return(PhpValue.False);
            }

            return(PhpValue.FromClr(field_value)); // Core.Convert.Quote(field_value, context);
        }
Exemplo n.º 5
0
        protected void ConstructDirectoryIteratorInternal(ScriptContext /*!*/ context, object path)
        {
            string pathstr = PhpVariable.AsString(path);

            if (string.IsNullOrEmpty(pathstr))
            {
                RuntimeException.ThrowSplException(c => new RuntimeException(c, true), context, @"Directory name must not be empty.", 0, null);
                return;
            }

            string errmessage = null;

            try
            {
                this.fs_info = new DirectoryInfo(Path.Combine(context.WorkingDirectory, pathstr));
                this.CreateEnumeratorInternal();
            }
            catch (System.Exception ex)
            {
                errmessage = ex.Message;
            }

            if (errmessage != null)
            {
                UnexpectedValueException.ThrowSplException(c => new UnexpectedValueException(c, true), context, errmessage, 0, null);
            }
        }
    internal RuntimeTypeHandle ResolveNewScope(object newthis, PhpValue newscope = default(PhpValue))
    {
        if (newscope.IsSet)
        {
            // Operators.TypeNameOrObjectToType(newscope) + handle "static"

            object obj;
            string str;

            if ((obj = (newscope.AsObject())) != null)
            {
                return(obj.GetType().TypeHandle);
            }
            else if ((str = PhpVariable.AsString(newscope)) != null)
            {
                return("static".Equals(str, StringComparison.OrdinalIgnoreCase)
                    ? _scope
                    : _ctx.GetDeclaredTypeOrThrow(str, true).TypeHandle);
            }
            else if (newscope.IsNull)
            {
                return(default(RuntimeTypeHandle));
            }
            else
            {
                throw new ArgumentException(nameof(newscope));
            }
        }

        return(ReferenceEquals(newthis, null) ? _scope : newthis.GetType().TypeHandle);
    }
Exemplo n.º 7
0
        /// <summary>
        /// Gets a contents of a specified cell from a specified query result resource.
        /// </summary>
        /// <param name="resultHandle">Query result resource.</param>
        /// <param name="row">Row index.</param>
        /// <param name="field">Column (field) integer index or string name.</param>
        /// <returns>The value of the cell or a <B>null</B> reference (<B>false</B> in PHP) on failure (invalid resource or row/field index/name).</returns>
        /// <remarks>
        /// Result is affected by run-time quoting.
        /// </remarks>
        public static PhpValue mysql_result(PhpResource resultHandle, int row, PhpValue field)
        {
            var result = MySqlResultResource.ValidResult(resultHandle);

            if (result == null)
            {
                return(PhpValue.False);
            }

            string field_name;
            object field_value;

            if (field.IsEmpty)
            {
                field_value = result.GetFieldValue(row, result.CurrentFieldIndex);
            }
            else if ((field_name = PhpVariable.AsString(field)) != null)
            {
                field_value = result.GetFieldValue(row, field_name);
            }
            else
            {
                field_value = result.GetFieldValue(row, (int)field.ToLong());
            }

            return(PhpValue.FromClr(field_value)); // TODO: Core.Convert.Quote(field_value, context);
        }
Exemplo n.º 8
0
        public object __setLocation(ScriptContext __context, object new_location)
        {
            string tmp1 = PhpVariable.AsString(new_location);

            if (tmp1 == null)

            {
                PhpException.InvalidImplicitCast(new_location, "string", "__setLocation");
                return(null);
            }
            return(__setLocation(tmp1));
        }
Exemplo n.º 9
0
        public virtual object isSubclassOf(ScriptContext /*!*/ context, object @class)
        {
            var classname = PhpVariable.AsString(@class);

            if (!string.IsNullOrEmpty(classname) && this.typedesc != null)
            {
                var dtype = context.ResolveType(classname, null, null, null, ResolveTypeFlags.ThrowErrors | ResolveTypeFlags.UseAutoload);
                return(dtype != null && this.typedesc.IsAssignableFrom(dtype));
            }

            return(false);
        }
Exemplo n.º 10
0
        public static PhpArray Compact(Dictionary <string, object> localVariables, params object[] names)
        {
            if (names == null)
            {
                PhpException.ArgumentNull("names");
                return(null);
            }

            PhpArray globals = (localVariables != null) ? null : ScriptContext.CurrentContext.GlobalVariables;
            PhpArray result  = new PhpArray();

            for (int i = 0; i < names.Length; i++)
            {
                string   name;
                PhpArray array;

                if ((name = PhpVariable.AsString(names[i])) != null)
                {
                    // if variable exists adds a copy of its current value to the result:
                    object value;

                    if (PhpHashtable.TryGetValue(globals, localVariables, name, out value))
                    {
                        result.Add(name, PhpVariable.DeepCopy(value));
                    }
                }
                else if ((array = names[i] as PhpArray) != null)
                {
                    // recursively searches for string variable names:
                    using (PhpHashtable.RecursiveEnumerator iterator = array.GetRecursiveEnumerator(false, true))
                    {
                        while (iterator.MoveNext())
                        {
                            if ((name = PhpVariable.AsString(iterator.Current.Value)) != null)
                            {
                                // if variable exists adds a copy of its current value to the result:
                                object value;
                                if (PhpHashtable.TryGetValue(globals, localVariables, name, out value))
                                {
                                    result.Add(name, PhpVariable.DeepCopy(value));
                                }
                            }
                        }
                    }
                }
            }

            return(result);
        }
Exemplo n.º 11
0
        private Curl_HttpReq setRequestMethod(UserDefined data)
        {
            Curl_HttpReq httpreq = data.Httpreq;

            if ( // (conn->handler->protocol&(CURLPROTO_HTTP|CURLPROTO_FTP)) && //(MB) I'm handeling http request, so I don't need to check this
                data.Upload)
            {
                httpreq = Curl_HttpReq.PUT;
            }

            // Now set the request.Method to the proper request string
            if (data.Str[(int)DupString.CUSTOMREQUEST] != null)
            {
                request.Method = PhpVariable.AsString(data.Str[(int)DupString.CUSTOMREQUEST]);
            }
            else
            {
                if (data.OptNoBody)
                {
                    request.Method = "HEAD";
                }
                else
                {
                    switch (httpreq)
                    {
                    case Curl_HttpReq.POST:
                    case Curl_HttpReq.POST_FORM:
                        request.Method = "POST";
                        break;

                    case Curl_HttpReq.PUT:
                        request.Method = "PUT";
                        break;

                    default:     /* this should never happen */
                    case Curl_HttpReq.GET:
                        request.Method = "GET";
                        break;

                    case Curl_HttpReq.HEAD:
                        request.Method = "HEAD";
                        break;
                    }
                }
            }

            return(httpreq);
        }
Exemplo n.º 12
0
        public virtual object __construct(ScriptContext context, object @class, object propertyname)
        {
            string propertynameStr = PhpVariable.AsString(propertyname);

            if (@class == null || string.IsNullOrEmpty(propertynameStr))
            {
                return(false);
            }

            this.dtype    = null;
            this.property = null;

            DObject dobj;
            string  str;

            if ((dobj = (@class as DObject)) != null)
            {
                this.dtype = dobj.TypeDesc;
            }
            else if ((str = PhpVariable.AsString(@class)) != null)
            {
                this.dtype = context.ResolveType(str, null, null, null, ResolveTypeFlags.UseAutoload);
            }

            if (this.dtype == null)
            {
                return(false);
            }

            if (this.dtype.GetProperty(new VariableName(propertynameStr), dtype, out this.property) == GetMemberResult.NotFound)
            {
                object runtimeValue;
                if (dobj != null && dobj.RuntimeFields != null && dobj.RuntimeFields.TryGetValue(propertynameStr, out runtimeValue))
                {
                    // create desc of runtime field:
                    this.property = new RuntimePhpProperty(dtype,
                                                           (instance) => ((DObject)instance).GetRuntimeField(this.name, null),
                                                           (instance, value) => ((DObject)instance).SetRuntimeField(this.name, value, null, null, null));
                    this.property.Member = new KnownRuntimeProperty(this.property, propertynameStr);
                }
                else
                {
                    return(false);
                }
            }

            return(null);
        }
Exemplo n.º 13
0
        private void setCredentials(UserDefined data)
        {
            if (data.Str[(int)DupString.USERNAME] != null)
            {
                //This is obvious way, but unfortunatelly it doesn't work
                //httpauth set to CURLAUTH_ANY is .NET default because it will use right authentication protocol
                //request.Credentials = new NetworkCredential(
                //    PhpVariable.AsString(data.Str[(int)DupString.USERNAME]),
                //    data.Str[(int)DupString.PASSWORD] != null ? PhpVariable.AsString(data.Str[(int)DupString.PASSWORD]) : String.Empty);

                //We only support BASIC
                HttpUtils.SetBasicAuthHeader(request,
                                             PhpVariable.AsString(data.Str[(int)DupString.USERNAME]),
                                             data.Str[(int)DupString.PASSWORD] != null ? PhpVariable.AsString(data.Str[(int)DupString.PASSWORD]) : String.Empty);
            }
        }
Exemplo n.º 14
0
        public object __construct(ScriptContext /*!*/ context, object filename)
        {
            // check arguments
            string filenamestr = PhpVariable.AsString(filename);

            if (filenamestr == null)
            {
                PhpException.InvalidArgumentType("filename", PhpVariable.TypeNameString);
            }
            else
            {
                // TODO
            }

            return(null);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Get <see cref="PhpTypeInfo"/> from either a class name or a class instance.
        /// </summary>
        /// <returns>Type info instance if object is valid class reference, otherwise <c>null</c>.</returns>
        internal static PhpTypeInfo TypeNameOrObjectToType(Context ctx, PhpValue @object, RuntimeTypeHandle selftype = default(RuntimeTypeHandle), bool autoload = true, bool allowName = true)
        {
            object obj;
            string str;

            if ((obj = (@object.AsObject())) != null)
            {
                return(obj.GetPhpTypeInfo());
            }
            else if ((str = PhpVariable.AsString(@object)) != null)
            {
                return(allowName ? ctx.GetDeclaredType(str, autoload) : null);
            }
            else
            {
                // other @object types are not handled
                return((selftype.Equals(default) || [email protected])
Exemplo n.º 16
0
        private object Filter(object instance, PhpStack /*!*/ stack)
        {
            StringBuilder result = new StringBuilder();

            Debug.Assert(stack.ArgCount >= 1, "Called by output buffering, so should be ok");

            string data = PhpVariable.AsString(stack.PeekValueUnchecked(1));

            stack.RemoveFrame();

            // parse the text
            if (parser == null)
            {
                parser = new TagsUrlRewriter(this);
            }

            return(parser.ParseHtml(parserState, data));
        }
Exemplo n.º 17
0
        public virtual object __construct(ScriptContext context, object arg)
        {
            string name = PhpVariable.AsString(arg);

            if (!string.IsNullOrEmpty(name))
            {
                routine = context.ResolveFunction(name, null, false);
            }
            else
            {
                PhpException.InvalidArgument("arg");
            }

            if (routine == null)
            {
                PhpException.Throw(PhpError.Error, string.Format("Function {0}() does not exist", name));
            }

            return(null);
        }
Exemplo n.º 18
0
        ///// <summary>
        ///// Returns methodName from Args
        ///// </summary>
        ///// <param name="args"></param>
        ///// <returns></returns>
        //protected DynamicMetaObject GetRuntimeMethodName(DynamicMetaObject[] args)
        //{
        //    //if (args.Length == this.genericParamsCount + this.paramsCount + 3) // args contains ClassContext
        //    //    return args[this.genericParamsCount + this.paramsCount + 2];
        //    //else if (args.Length == this.genericParamsCount + this.paramsCount + 2)
        //    //    return args[this.genericParamsCount + this.paramsCount + 1];

        //    //throw new InvalidOperationException();

        //    return args[args.Length - 1];

        //}


        protected override DynamicMetaObject /*!*/ FallbackInvokeMember(
            DynamicMetaObject target,
            DynamicMetaObject[] args)
        {
            Debug.Assert(Types.String[0].IsAssignableFrom(args[args.Length - 1].LimitType), "Wrong field name type!");

            DynamicMetaObject dmoMethodName = args[args.Length - 1];

            string name = PhpVariable.AsString(dmoMethodName.Value);

            if (name == null)
            {
                //PhpException.Throw(PhpError.Error, CoreResources.GetString("invalid_method_name"));
                //return new PhpReference() | null;

                return(DoAndReturnDefault(
                           BinderHelper.ThrowError("invalid_method_name"),
                           target.Restrictions));

                throw new NotImplementedException();
            }
            else
            {
                // Restriction: PhpVariable.AsString(methodName) == |methodName|
                BindingRestrictions restrictions = BindingRestrictions.GetExpressionRestriction(
                    Expression.Equal(
                        Expression.Call(Methods.PhpVariable.AsString, dmoMethodName.Expression),
                        Expression.Constant(dmoMethodName.Value, Types.String[0])));

                actualMethodName = name;

                //transform arguments that it doesn't contains methodName
                Array.Resize <DynamicMetaObject>(ref args, args.Length - 1);

                DynamicMetaObject result = base.FallbackInvokeMember(target, args);

                return(new DynamicMetaObject(
                           result.Expression,
                           result.Restrictions.Merge(restrictions)));//TODO: Creation of this can be saved
            }
        }
Exemplo n.º 19
0
        public object __call(ScriptContext __context, object function_name, object arguments)
        {
            string tmp1 = PhpVariable.AsString(function_name);

            if (tmp1 == null)

            {
                PhpException.InvalidImplicitCast(function_name, "string", "__call");
                return(null);
            }

            PhpArray tmp2 = arguments as PhpArray;

            if (tmp2 == null)

            {
                PhpException.InvalidImplicitCast(arguments, "PhpArray", "__call");
                return(null);
            }
            return(__call(tmp1, tmp2));
        }
Exemplo n.º 20
0
        /// <summary>
        /// Convert handler into <see cref="PhpCallback"/> in XML-extension-manner.
        /// </summary>
        /// <param name="var"></param>
        /// <returns></returns>
        internal PhpCallback ObjectToXmlCallback(object var)
        {
            // empty variable
            if (PhpVariable.IsEmpty(var))
            {
                return(null);
            }

            // function name given as string:
            string name = PhpVariable.AsString(var);

            if (name != null)
            {
                return((this.HandlerObject != null)
                    ? new PhpCallback(this.HandlerObject, name)
                    : new PhpCallback(name));
            }

            // default PHP callback:
            return(Core.Convert.ObjectToCallback(var));
        }
Exemplo n.º 21
0
        public static bool MethodExists(DTypeDesc caller, object obj, string methodName)
        {
            if (obj == null || string.IsNullOrEmpty(methodName))
            {
                return(false);
            }

            DTypeDesc dtype;
            DObject   dobj;
            string    str;

            if ((dobj = (obj as DObject)) != null)
            {
                dtype = dobj.TypeDesc;
                if (dtype == null)
                {
                    Debug.Fail("DObject.TypeDesc should not be null");
                    return(false);
                }
            }
            else if ((str = PhpVariable.AsString(obj)) != null)
            {
                ScriptContext script_context = ScriptContext.CurrentContext;
                dtype = script_context.ResolveType(str, null, caller, null, ResolveTypeFlags.UseAutoload);
                if (dtype == null)
                {
                    return(false);
                }
            }
            else
            {
                // other type names are not handled
                return(false);
            }

            DRoutineDesc method;

            return(dtype.GetMethod(new Name(methodName), dtype, out method) != GetMemberResult.NotFound);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Converts a class name or class instance to <see cref="DTypeDesc"/> object.
        /// </summary>
        /// <param name="scriptContext">Current <see cref="ScriptContext"/>.</param>
        /// <param name="namingContext">Current <see cref="NamingContext"/>.</param>
        /// <param name="caller">The caller of the method to resolve visible properties properly. Can be UnknownTypeDesc.</param>
        /// <param name="classNameOrObject">The class name or class instance (<see cref="DObject"/>).</param>
        /// <param name="useAutoload"><B>True</B> iff the <c>__autoload</c> magic function should be used.</param>
        /// <returns>The type desc that corresponds to <paramref name="classNameOrObject"/> or <B>null</B>
        /// if the type could not be found or <paramref name="classNameOrObject"/> is neither a string
        /// nor <see cref="DObject"/>.</returns>
        internal static DTypeDesc ClassNameOrObjectToType(ScriptContext /*!*/ scriptContext, NamingContext namingContext,
                                                          DTypeDesc caller, object classNameOrObject, bool useAutoload)
        {
            string class_name = PhpVariable.AsString(classNameOrObject);

            if (class_name != null)
            {
                // lookup the Type
                return(scriptContext.ResolveType(class_name, namingContext, caller, null,
                                                 (useAutoload ? ResolveTypeFlags.UseAutoload : ResolveTypeFlags.None)));
            }
            else
            {
                DObject obj = classNameOrObject as DObject;
                if (obj != null)
                {
                    return(obj.TypeDesc);
                }
            }

            return(null);
        }
Exemplo n.º 23
0
        /// <summary>
        /// Calls the method referred by <paramref name="methodName"/> from the user defined
        /// object <paramref name="classNameOrObject"/> with parameters <paramref name="args"/>.
        /// </summary>
        /// <param name="caller">DTypeDesc of the caller's class context. Can be UnknownTypeDesc.</param>
        /// <param name="methodName">The name of the method.</param>
        /// <param name="classNameOrObject">An instance to invoke the method on or a class name.</param>
        /// <param name="args">Parameters to invoke the method with.</param>
        /// <returns>The method's return value (always dereferenced).</returns>
        internal static object CallUserMethodInternal(DTypeDesc caller, string methodName, object classNameOrObject, ICollection args)
        {
            PhpException.Throw(PhpError.Notice, LibResources.GetString("call_user_method_deprecated"));

            object  ret_val = false;
            DObject obj;
            string  class_name;

            ScriptContext context = ScriptContext.CurrentContext;

            //DTypeDesc classContext = PhpStackTrace.GetClassContext();  // TODO: GetClassContext only if needed by context.ResolveType
            if (caller != null && caller.IsUnknown)
            {
                caller = PhpStackTrace.GetClassContext();
            }

            if ((obj = classNameOrObject as DObject) != null)
            {
                // push arguments on stack
                context.Stack.AddFrame(args);
                ret_val = obj.InvokeMethod(methodName, caller, context);
            }
            else if ((class_name = PhpVariable.AsString(classNameOrObject)) != null)
            {
                // push arguments on stack
                context.Stack.AddFrame(args);

                ResolveTypeFlags flags = ResolveTypeFlags.UseAutoload | ResolveTypeFlags.ThrowErrors;
                DTypeDesc        type  = PHP.Core.Convert.ObjectToTypeDesc(class_name, flags, caller, context, null, null);

                ret_val = Operators.InvokeStaticMethod(type, methodName, null, caller, context);
            }
            else
            {
                PhpException.InvalidArgument("classNameOrObject", LibResources.GetString("arg:not_object_or_class_name"));
            }

            return(PhpVariable.Dereference(ret_val));
        }
Exemplo n.º 24
0
        public object __setCookie(ScriptContext __context, object name, object value)
        {
            string tmp1 = PhpVariable.AsString(name);

            if (tmp1 == null)

            {
                PhpException.InvalidImplicitCast(name, "string", "__setCookie");
                return(null);
            }

            string tmp2 = PhpVariable.AsString(value);

            if (tmp2 == null)

            {
                PhpException.InvalidImplicitCast(value, "string", "__setCookie");
                return(null);
            }
            __setCookie(tmp1, tmp2);
            return(null);
        }
Exemplo n.º 25
0
        public void registerPHPFunctions([Optional] object restrict)
        {
            if (xsltUserFunctionHandler == null)
            {
                xsltUserFunctionHandler = new XsltUserFunctionHandler();
                xsltArgumentList.AddExtensionObject(PhpNameSpaceUri, xsltUserFunctionHandler);
            }

            if (restrict == null)
            {
                xsltUserFunctionHandler.RegisterAllFunctions();
            }
            else
            {
                // check for string argument
                string func_name = PhpVariable.AsString(restrict);
                if (func_name != null)
                {
                    xsltUserFunctionHandler.RegisterFunction(func_name);
                }
                else
                {
                    // check for array argument
                    PhpArray func_names = restrict as PhpArray;
                    if (func_names != null)
                    {
                        foreach (KeyValuePair <IntStringKey, object> pair in func_names)
                        {
                            xsltUserFunctionHandler.RegisterFunction(PHP.Core.Convert.ObjectToString(pair.Key.Object));
                        }
                    }
                    else
                    {
                        xsltUserFunctionHandler.RegisterAllFunctions();
                    }
                }
            }
        }
Exemplo n.º 26
0
        private void setProxy(UserDefined data)
        {
            string   proxyAddress;
            WebProxy myProxy;

            if (data.Str[(int)DupString.PROXY] == null)
            {
                return;
            }

            if (data.ProxyType != CURLproxyType.CURLPROXY_HTTP)
            {
                return;
            }

            myProxy      = new WebProxy();
            proxyAddress = PhpVariable.AsString(data.Str[(int)DupString.PROXY]);

            // Create a new Uri object.
            Uri uri = Utils.CompleteUri(proxyAddress, Scheme, data.ProxyPort);

            // Associate the newUri object to 'myProxy' object so that new myProxy settings can be set.
            myProxy.Address = uri;
            // Create a NetworkCredential object and associate it with the
            // Proxy property of request object.

            if (data.Str[(int)DupString.PROXYUSERNAME] != null)
            {
                //data.proxyauth set to CURLAUTH_ANY is .NET default because it will use right authentication protocol

                myProxy.Credentials = new NetworkCredential(
                    PhpVariable.AsString(data.Str[(int)DupString.PROXYUSERNAME]),
                    data.Str[(int)DupString.PROXYPASSWORD] != null ? PhpVariable.AsString(data.Str[(int)DupString.PROXYPASSWORD]) : String.Empty);
            }

            request.Proxy = myProxy;
        }
Exemplo n.º 27
0
        public virtual object __construct(ScriptContext context, object @class, object methodname)
        {
            string methodnameStr = PhpVariable.AsString(methodname);

            this.dtype  = null;
            this.method = null;

            DObject dobj;

            if ((dobj = (@class as DObject)) != null)
            {
                this.dtype = dobj.TypeDesc;
            }
            else
            {
                var str = PhpVariable.AsString(@class);
                if (str != null)
                {
                    this.dtype = context.ResolveType(str, null, null, null, ResolveTypeFlags.UseAutoload);
                }

                if (this.dtype == null)
                {
                    PhpException.Throw(PhpError.Error, string.Format("Class {0} does not exist", str));
                    return(false);
                }
            }

            if (this.dtype.GetMethod(new Name(methodnameStr), dtype, out this.method) == GetMemberResult.NotFound)
            {
                PhpException.Throw(PhpError.Error, string.Format("Method {0}::{1}() does not exist", dtype.MakeFullName(), methodnameStr));
                return(false);
            }

            return(null);
        }
Exemplo n.º 28
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.º 29
0
        /// <summary>
        /// Execute is modified Curl_http() which in Curl gets called from the generic Curl_do() function when a HTTP
        /// request is to be performed. This creates and sends a properly constructed
        /// HTTP request.
        /// </summary>
        /// <param name="curl"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        internal override object Execute(PhpCurlResource curl, ref CURLcode result)
        {
            UserDefined      data = curl.Data;
            HttpBitsUploader uploader;
            bool             terminatedCorrectly = false;
            int  redirectAttempts = 0;
            bool keepVerb         = false;

            result = CURLcode.CURLE_OK;

            if (data.Str[(int)DupString.SET_URL] == null)
            {
                result = CURLcode.CURLE_COULDNT_CONNECT;
                return(false);
            }

            Uri uri = Utils.CompleteUri(PhpVariable.AsString(data.Str[(int)DupString.SET_URL]),
                                        Scheme,
                                        data.UsePort);


            for (; ;)
            {
                request = (HttpWebRequest)HttpWebRequest.Create(uri);

                Curl_HttpReq httpreq = (redirectAttempts == 0) || keepVerb?setRequestMethod(data) : Curl_HttpReq.GET;

                setTimeOut(data);
                setHttpVersion(data);

                request.AllowAutoRedirect            = data.FollowLocation;
                request.MaximumAutomaticRedirections = data.MaxRedirects;

                if (data.Str[(int)DupString.USERAGENT] != null)
                {
                    request.UserAgent = PhpVariable.AsString(data.Str[(int)DupString.USERAGENT]);
                }

                if (data.Str[(int)DupString.SET_REFERER] != null)
                {
                    request.Referer = PhpVariable.AsString(data.Str[(int)DupString.SET_REFERER]);
                }

                if (data.Headers != null)
                {
                    request.SetHttpHeaders(data.Headers);
                }

                setProxy(data);
                setCredentials(data);
                setCookies(data);

                //ssl.VerifyPeer && ssl.VerifyHost == 2 is supported by default .NET
                // other values are currently unsupported

                if (data.Str[(int)DupString.CERT] != null)
                {
                    X509Certificate cert;
                    string          certPath;

                    try
                    {
                        certPath = Path.Combine(ScriptContext.CurrentContext.WorkingDirectory, PhpVariable.AsString(data.Str[(int)DupString.SSL_CAFILE]));

                        if (data.Str[(int)DupString.KEY_PASSWD] == null)
                        {
                            cert = new X509Certificate(certPath);
                        }
                        else
                        {
                            cert = new X509Certificate(certPath, PhpVariable.AsString(data.Str[(int)DupString.KEY_PASSWD]));
                        }

                        request.ClientCertificates.Add(cert);
                    }
                    catch (CryptographicException)
                    {
                        //TODO: here are more caises to differentiate
                        result = CURLcode.CURLE_SSL_CACERT_BADFILE;
                        return(false);
                    }
                }


                switch (httpreq)
                {
                case Curl_HttpReq.POST_FORM:

                    //same as POST but we can send multiple items asform-data


                    if (data.HttpPostForm != null)
                    {
                        try
                        {
                            HttpFormDataUploader formUploader = new HttpFormDataUploader(request);
                            formUploader.UploadForm(data.HttpPostForm);
                        }
                        catch (WebException ex)
                        {
                            switch (ex.Status)
                            {
                            case WebExceptionStatus.Timeout:
                                result = CURLcode.CURLE_OPERATION_TIMEOUTED;
                                break;

                            default:
                                result = CURLcode.CURLE_COULDNT_CONNECT;        // for now just this
                                break;
                            }
                            return(false);
                        }
                    }

                    break;


                case Curl_HttpReq.PUT:     /* Let's PUT the data to the server! */

                    //INFILE & INFILESIZE has to be set

                    NativeStream nativeStream = data.Infile as NativeStream;

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

                    FileStream fs = nativeStream.RawStream as FileStream;

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

                    try
                    {
                        uploader = new HttpBitsUploader(request);
                        uploader.UploadFile(fs);
                    }
                    catch (WebException ex)
                    {
                        switch (ex.Status)
                        {
                        case WebExceptionStatus.Timeout:
                            result = CURLcode.CURLE_OPERATION_TIMEOUTED;
                            break;

                        default:
                            result = CURLcode.CURLE_COULDNT_CONNECT;        // for now just this
                            break;
                        }
                        return(false);
                    }

                    break;

                case Curl_HttpReq.POST:
                    /* this is the simple POST, using x-www-form-urlencoded style */

                    if (String.IsNullOrEmpty(request.ContentType))    // if Content-type isn't set set the default
                    {
                        request.ContentType = "application/x-www-form-urlencoded";
                    }

                    if (data.Postfields != null)
                    {
                        try
                        {
                            uploader = new HttpBitsUploader(request);
                            uploader.UploadData(data.Postfields);
                        }
                        catch (WebException ex)
                        {
                            switch (ex.Status)
                            {
                            case WebExceptionStatus.Timeout:
                                result = CURLcode.CURLE_OPERATION_TIMEOUTED;
                                break;

                            default:
                                result = CURLcode.CURLE_COULDNT_CONNECT;        // for now just this
                                break;
                            }
                            return(false);
                        }
                    }

                    break;
                }

                try
                {
                    // if we got this far, we will turn off AutoRedirect (assuming it was on), since
                    // we are ready to handle manually following certain responses. this is needed
                    // to harvest cookies that are set on any intermediate response (i.e. anything
                    // other than the last one followed), since the .NET HTTP class will use, but
                    // NOT return, cookies set on anything but the last request.
                    request.AllowAutoRedirect = false;
                    response = (HttpWebResponse)request.GetResponse();
                }
                catch (WebException ex)
                {
                    switch (ex.Status)
                    {
                    case WebExceptionStatus.Timeout:
                        result = CURLcode.CURLE_OPERATION_TIMEOUTED;
                        break;

                    case WebExceptionStatus.ConnectFailure:
                        result = CURLcode.CURLE_COULDNT_CONNECT;
                        break;

                    case WebExceptionStatus.TrustFailure:
                        result = CURLcode.CURLE_SSL_CACERT;
                        break;

                    case WebExceptionStatus.ProtocolError:
                        //Response from server was complete, but indicated protocol error as 404, 401 etc.
                        break;

                    default:
                        result = CURLcode.CURLE_COULDNT_CONNECT;    // for now just this
                        break;
                    }
                    //TODO: other errorCodes

                    response = (HttpWebResponse)ex.Response;
                    //return false;
                    //error = true;
                }

                if (response == null)// just to make sure I have the response object
                {
                    return(false);
                }


                if (data.FollowLocation)
                {
                    // see if we need to follow a redirect.
                    switch (response.StatusCode)
                    {
                    case HttpStatusCode.MovedPermanently:
                    case HttpStatusCode.Found:
                    case HttpStatusCode.SeeOther:
                    case HttpStatusCode.RedirectKeepVerb:
                        if (redirectAttempts++ >= data.MaxRedirects)
                        {
                            result = CURLcode.CURLE_TOO_MANY_REDIRECTS;
                            return(false);
                        }
                        string location = response.Headers["Location"];
                        if (!string.IsNullOrWhiteSpace(location))
                        {
                            try
                            {
                                keepVerb = response.StatusCode == HttpStatusCode.RedirectKeepVerb;
                                data.Cookies.Add(response.Cookies);
                                response.Close();
                                uri = new Uri(uri, location);
                                continue;
                            }
                            catch (Exception)
                            {
                                // closest error code though could be confusing as it's not the user-
                                // submitted URL that's the problem
                                result = CURLcode.CURLE_URL_MALFORMAT;
                                return(false);
                            }
                        }
                        break;
                    }
                }

                //Save cookies
                data.Cookies.Add(response.Cookies);
                // break out of the for loop as we aren't following a redirect
                break;
            }

            byte[] headers       = null;
            byte[] content       = null;
            int    headersLength = 0;

            if (data.IncludeHeader)
            {
                //It's necessary to put HTTP header into the result

                //first we need to create it since there isn't anywhere
                headers       = Encoding.ASCII.GetBytes(response.GetHttpHeaderAsString());
                headersLength = headers.Length;
            }

            if (data.FunctionWriteHeader != null)// TODO: probably invoke before
            {
                response.InvokeHeaderFunction(curl, data.FunctionWriteHeader);
            }

            Stream writeStream = null;

            if (data.WriteFunction != null)
            {
                writeStream = new WriteFunctionStream(curl, data.WriteFunction);
            }
            else if (data.OutFile != null)
            {
                var outStream = data.OutFile as PhpStream;

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

                Stream fs = outStream.RawStream as Stream;

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

                writeStream = fs;
            }
            else if (data.ReturnTransfer == false) // Output to standart output
            {
                writeStream = ScriptContext.CurrentContext.OutputStream;
            }


            if (writeStream != null)
            {
                if (headers != null) //there is http header to copy to the result
                {
                    writeStream.Write(headers, 0, headersLength);
                }

                HttpBitsDownloader reader = new HttpBitsDownloader(response);

                try
                {
                    reader.ReadToStream(writeStream, out terminatedCorrectly);
                }
                catch (WebException ex)
                {
                    switch (ex.Status)
                    {
                    case WebExceptionStatus.Timeout:
                        result = CURLcode.CURLE_OPERATION_TIMEOUTED;
                        break;

                    default:
                        result = CURLcode.CURLE_COULDNT_CONNECT;    // for now just this
                        break;
                    }
                }

                if (!terminatedCorrectly)
                {
                    result = CURLcode.CURLE_PARTIAL_FILE;
                }

                return(true);
            }
            else
            {
                // Read the response
                HttpBitsDownloader reader = new HttpBitsDownloader(response);

                try
                {
                    content = reader.ReadToEnd(headersLength, out terminatedCorrectly);
                }
                catch (WebException ex)
                {
                    switch (ex.Status)
                    {
                    case WebExceptionStatus.Timeout:
                        result = CURLcode.CURLE_OPERATION_TIMEOUTED;
                        break;

                    default:
                        result = CURLcode.CURLE_COULDNT_CONNECT;    // for now just this
                        break;
                    }
                }

                if (!terminatedCorrectly)
                {
                    result = CURLcode.CURLE_PARTIAL_FILE;
                }

                if (headers != null) //there is http header to copy to the result
                {
                    if (content != null)
                    {
                        Buffer.BlockCopy(headers, 0, content, 0, headersLength);
                    }
                    else
                    {
                        content = headers;
                    }
                }

                if (content == null)
                {
                    return(PhpBytes.Empty);
                }
                else
                {
                    return(new PhpBytes(content));
                }
            }
        }
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 /*= 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);
        }