Пример #1
0
        static void Main(string[] args)
        {
            ScriptContext context = ScriptContext.InitApplication(ApplicationContext.Default, null, null, null);

            var sb = new StringBuilder();
            using (TextWriter tw = new StringWriter(sb))
            {
                context.Output = tw;
                context.OutputStream = Console.OpenStandardOutput(); //TODO: Should also redirect binary output.

                context.Include("main.php", true);

                var klass = (PhpObject)context.NewObject("Klass", new object[] { "yipppy" });
                var foo = new PhpCallback(klass, "foo");
                foo.Invoke(null, new object[] { "param" });

                tw.Close();
            }

            string output = sb.ToString();
            const string EXPECTED = "yipppyparam";
            if (output != EXPECTED)
            {
                Console.WriteLine("FAIL");
                Console.Write("Expected: " + EXPECTED);
                Console.Write("Got: ");
                Console.WriteLine(output);
            }
            else
            {
                Console.WriteLine("PASS");
            }
        }
Пример #2
0
        /// <summary>
        /// Invoke the specified method and args.
        /// </summary>
        /// <param name="method">Method.</param>
        /// <param name="args">Arguments.</param>
        /// <param name="func">Func.</param>
        public override object Invoke(string func, params object[] args)
        {
            try
            {
                if (State == PluginState.Loaded && Globals.Contains(func))
                {
                    object result = (object)null;

                    using (new Stopper(Name, func))
                    {
                        var caller = new PhpCallback(Class, func);
                        result = caller.Invoke(args);
                    }
                    return result;
                }
                else
                {
                    Logger.LogWarning("[Plugin] Function: " + func + " not found in plugin: " + Name + ", or plugin is not loaded.");
                    return null;
                }
            }
            catch (Exception ex)
            {
                string fileinfo = (String.Format("{0}<{1}>.{2}()", Name, Type, func) + Environment.NewLine);
                Logger.LogError(fileinfo + FormatException(ex));
                return null;
            }
        }
Пример #3
0
        public static EventHandler RunSilverlightApplication(System.Windows.Controls.Canvas c, string source)
        {
            ApplicationContext app_context = ApplicationContext.Default;

            // try to preload configuration (to prevent exceptions during InitApplication)
            Configuration.Load(app_context);
            ApplicationConfiguration app_config = Configuration.Application;


            string url       = HtmlPage.Document.DocumentUri.AbsoluteUri;
            int    lastSlash = url.Replace('\\', '/').LastIndexOf('/');

            app_config.Compiler.SourceRoot = new FullPath(url.Substring(0, lastSlash), false);

            int    sourcelastSlash = source.Replace('\\', '/').LastIndexOf('/');
            string sourceRelPath   = source.Substring(lastSlash + 1);



            // Silverlight language features
            app_config.Compiler.LanguageFeatures = LanguageFeatures.PhpClr;

            // ..
            ScriptContext context = InitApplication(app_context);

            Debug.Fail("Update versions below!");
            ConfigurationContext.AddLibrary("mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e", null, "");
            ConfigurationContext.AddLibrary("System, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e", null, "");
            ConfigurationContext.AddLibrary("System.Windows, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e", null, "");
            ConfigurationContext.AddLibrary("System.Net, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e", null, "");
            //ConfigurationContext.AddLibrary("System.SilverLight, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", null, "");
            //ConfigurationContext.AddLibrary("agclr, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", null, "");

            ConfigurationContext.AddLibrary("PhpNetClassLibrary, Version=3.0.0.0, Culture=neutral, PublicKeyToken=4af37afe3cde05fb", null, "");

            //
            Configuration.Application.Compiler.Debug = true;

            // ..
            Dictionary <string, object> vars = new Dictionary <string, object>();

            currentContext.AutoGlobals.Canvas.Value = ClrObject.Wrap(c);
            currentContext.AutoGlobals.Addr.Value   = ClrObject.Wrap(app_config.Compiler.SourceRoot.ToString());

            //Operators.SetVariableRef(currentContext, vars, "_CANVAS", Operators.GetItemRef("_CANVAS", ref currentContext.AutoGlobals.Globals.value));
            //Operators.SetVariable(currentContext, vars, "_CANVAS", ClrObject.Wrap(c));


            context.DynamicInclude(source, sourceRelPath, vars, null, null, InclusionTypes.RunSilverlight);

            return(new EventHandler(delegate(object sender, EventArgs e)
            {
                if (context.ResolveFunction("OnLoad", null, true) != null)
                {
                    PhpCallback load = new PhpCallback("OnLoad");
                    load.Invoke(sender, e);
                }
            }));
        }
Пример #4
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));
		}
Пример #5
0
        internal static void InvokeHeaderFunction(this HttpWebResponse response, PhpCurlResource curlResource, PhpCallback headerFunction)
        {
            StringBuilder builder = new StringBuilder(HTTP_HEADER_ROW_LENGTH);
            int startIndex = 0;

            IterateHtppHeaders(response, ref builder,
                delegate(ref StringBuilder sb)
                {
                    headerFunction.Invoke(curlResource, sb.ToString(startIndex, sb.Length - startIndex));
                    startIndex = sb.Length;
                }
                );

        }
Пример #6
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);

        }
Пример #7
0
        /// <summary>
        /// Returns an unitialized instance of the specified type or <see cref="__PHP_Incomplete_Class"/>.
        /// </summary>
        /// <param name="typeName">The type name.</param>
        /// <param name="context">Current <see cref="ScriptContext"/>.</param>
        /// <returns>The newly created instance or <B>null</B> if <paramref name="typeName"/> denotes
        /// a primitive type.</returns>
        /// <remarks>
        /// If the <paramref name="typeName"/> denotes a CLR type, no constructor is executed. If the
        /// <paramref name="typeName"/> denotes a PHP type, no user constructor (e.g. <c>__construct</c>)
        /// is executed.
        /// </remarks>
        public static DObject GetUninitializedInstance(string /*!*/ typeName, ScriptContext /*!*/ context)
        {
            // resolve the specified type
            DTypeDesc type = context.ResolveType(typeName);

            if (type == null || type.IsAbstract)
            {
                PhpCallback callback = context.Config.Variables.DeserializationCallback;
                if (callback != null && !callback.IsInvalid)
                {
                    callback.Invoke(typeName);
                    type = context.ResolveType(typeName);

                    if (type == null || type.IsAbstract)
                    {
                        // unserialize_callback_func failed
                        PhpException.Throw(PhpError.Warning, CoreResources.GetString("unserialize_callback_failed",
                                                                                     ((IPhpConvertible)callback).ToString()));
                    }
                }
            }

            if (type == null || type.IsAbstract)
            {
                // type not found -> create __PHP_Incomplete_Class
                __PHP_Incomplete_Class pic = new __PHP_Incomplete_Class(context, false);
                pic.__PHP_Incomplete_Class_Name.Value = typeName;
                pic.__PHP_Incomplete_Class_Name.IsSet = true;

                return(pic);
            }
            else
            {
                // create the instance
                return(type.New(context) as DObject);
            }
        }
Пример #8
0
		public static PhpArray Filter(PHP.Core.Reflection.DTypeDesc caller, PhpArray array, PhpCallback callback)
		{
			if (callback == null) { PhpException.ArgumentNull("callback"); return null; }
			if (array == null) { PhpException.ArgumentNull("array"); return null; }

			PhpArray result = new PhpArray();
			object[] args = new object[1];

			foreach (KeyValuePair<IntStringKey, object> entry in array)
			{
				// no deep copying needed because it is done so in callback:
				args[0] = entry.Value;

				// adds entry to the resulting array if callback returns true:
                if (Core.Convert.ObjectToBoolean(callback.Invoke(caller, args)))
				{
					result.Add(entry.Key, entry.Value);
				}
			}

			// values should be inplace deeply copied:
			result.InplaceCopyOnReturn = true;
			return result;
		}
Пример #9
0
		/// <summary>
		/// Visits an entyr of array which <see cref="Walk"/> or <see cref="WalkRecursive"/> is walking through.
		/// </summary>
		private static void VisitEntryOnWalk(PHP.Core.Reflection.DTypeDesc caller, KeyValuePair<IntStringKey, object> entry, IDictionary<IntStringKey, object> array,
			PhpCallback callback, object[] args)
		{
			PhpReference ref_item = entry.Value as PhpReference;

			// fills arguments for the callback:
			((PhpReference)args[0]).Value = (ref_item != null) ? ref_item.Value : entry.Value;
			args[1] = entry.Key.Object;

			// invoke callback:
            Core.Convert.ObjectToBoolean(callback.Invoke(caller, args));

			// loads a new value from a reference:
			if (ref_item != null)
			{
				ref_item.Value = ((PhpReference)args[0]).Value;
			}
			else
			{
				array[entry.Key] = ((PhpReference)args[0]).Value;
			}
		}
Пример #10
0
        public static object Reduce(PHP.Core.Reflection.DTypeDesc caller, [PhpRw] PhpArray array, PhpCallback function, [PhpDeepCopy] object initialValue)
		{
			if (array == null) { PhpException.ReferenceNull("array"); return null; }
			if (!PhpArgument.CheckCallback(function, caller, "function", 0, false)) return null;
			if (array.Count == 0) return initialValue;

			object[] args = new object[] { initialValue, null };
			PhpReference holder = new PhpReference();

			foreach (KeyValuePair<IntStringKey, object> entry in array)
			{
				object item = entry.Value;
				PhpReference ref_item = item as PhpReference;

				// array item is a reference:
				if (ref_item != null)
				{
					args[1] = item;
					args[0] = function.Invoke(args);
				}
				else
				{
					// array item is not a reference:

					holder.Value = item;
					args[1] = holder;
					args[0] = function.Invoke(args);

					// updates an item if it has been changed:
					if (item != holder.Value)
						array[entry.Key] = holder.Value;
				}
			}

			// dereferences the last returned value:
			return PhpVariable.Dereference(args[0]);
		}
Пример #11
0
		/// <summary>
		/// Replaces <paramref name="limit"/> occurences of substrings.
		/// </summary>
		/// <param name="converter">
		/// Converter used for replacement if <paramref name="callback"/> is <B>null</B>.
		/// </param>
		/// <param name="self">Instance of object that called the replace method (replace pattern may contain $this)</param>
		/// <param name="definedVariables">Array with local variables - can be used by replace pattern</param>
		/// <param name="callback">Callback to call for replacement strings.</param>
		/// <param name="str">String to search for matches.</param>
		/// <param name="limit">Max number of replacements performed.</param>
		/// <param name="sourceCodeDesc"><see cref="SourceCodeDescriptor"/> for possible lambda function creation.</param>
		/// <param name="count">Cumulated number of replacements.</param>
		/// <returns></returns>
		private static string ReplaceInternal(DObject self, Dictionary<string, object> definedVariables, PerlRegExpConverter converter, PhpCallback callback,
			string str, int limit, SourceCodeDescriptor sourceCodeDesc, ref int count)
		{
			Debug.Assert(limit >= -1);

			if (callback == null)
			{
				// replace without executing code or counting the number of replacements:
				if ((converter.PerlOptions & PerlRegexOptions.Evaluate) == 0 && count < 0)
					return converter.Regex.Replace(str, converter.DotNetReplaceExpression, limit);

				Evaluator evaluator = new Evaluator(converter.Regex, converter.DotNetReplaceExpression, sourceCodeDesc, self, definedVariables);
				MatchEvaluator match_evaluator;

				if ((converter.PerlOptions & PerlRegexOptions.Evaluate) != 0)
					match_evaluator = new MatchEvaluator(evaluator.ReplaceCodeExecute);
				else
					match_evaluator = new MatchEvaluator(evaluator.ReplaceCount);

				string result = converter.Regex.Replace(str, match_evaluator, limit);
				count += evaluator.Count;
				return result;
			}
			else
			{
                StringBuilder result = new StringBuilder((str != null) ? str.Length : 0);
				int last_index = 0;

				Match m = converter.Regex.Match(str);
				while (m.Success && (limit == -1 || limit-- > 0))
				{
					// append everything from input string to current match
					result.Append(str, last_index, m.Index - last_index);

					// move index after current match
					last_index = m.Index + m.Length;

					PhpArray arr = new PhpArray(m.Groups.Count, 0);
					for (int i = 0; i < m.Groups.Count; i++)
						arr[i] = m.Groups[i].Value;

					// append user callback function result
					string replacement = Core.Convert.ObjectToString(callback.Invoke(arr));
					result.Append(replacement);

					m = m.NextMatch();

					count++;
				}

				// remaining string
				result.Append(str, last_index, str.Length - last_index);
				return result.ToString();
			}
		}
Пример #12
0
 /// <summary>
 /// Invokes the callback with the parameters.
 /// </summary>
 /// <param name="caller">Current class context.</param>
 public void Invoke(DTypeDesc caller)
 {
     callback.Invoke(caller, parameters);
 }
Пример #13
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;
        }
Пример #14
0
		/// <summary>
		/// Invoked from <c>ExtManager</c> in order to call a (user or system) function. See <c>call_user_function</c>,
		/// <c>call_user_function_ex</c>, <c>zend_call_function</c> Zend API.
		/// </summary>
		/// <param name="target">Designation of the function/method to call.</param>
		/// <param name="args">Arguments to be passed to the function.</param>
		/// <returns>Return value of the function.</returns>
		public static object CallFunctionDirect(PhpCallback target, object[] args)
		{
			ScriptContext context = ScriptContext.CurrentContext;

            if (target.TargetInstance != null)
                target.TargetInstance = Externals.ParameterTransformation.PostCallObjectTransform(target.TargetInstance, context) as Reflection.DObject;

			// transform parameters (as if they were 'out' parameters)
			if (args != null)
				for (int i = 0; i < args.Length; i++)
                    Externals.ParameterTransformation.TransformOutParameter(context, ref args[i]);

			object ret_value = target.Invoke(args);

			// transform parameters (as if they were 'in' parameters)
			if (args != null)
				for (int i = 0; i < args.Length; i++)
                    Externals.ParameterTransformation.TransformInParameter(context, ref args[i]);

			// transform the return value (as if it was an 'in' parameter)
            Externals.ParameterTransformation.TransformInParameter(context, ref ret_value);
			
			return ret_value;
		}
Пример #15
0
		public static EventHandler RunSilverlightApplication(System.Windows.Controls.Canvas c, string source)
		{
			ApplicationContext app_context = ApplicationContext.Default;

			// try to preload configuration (to prevent exceptions during InitApplication)
			Configuration.Load(app_context);
			ApplicationConfiguration app_config = Configuration.Application;
            

            string url = HtmlPage.Document.DocumentUri.AbsoluteUri;
			int lastSlash = url.Replace('\\','/').LastIndexOf('/');
			app_config.Compiler.SourceRoot = new FullPath(url.Substring(0, lastSlash), false);

            int sourcelastSlash = source.Replace('\\', '/').LastIndexOf('/');
            string sourceRelPath = source.Substring(lastSlash+1);

            

			// Silverlight language features
			app_config.Compiler.LanguageFeatures = LanguageFeatures.PhpClr;

			// ..
			ScriptContext context = InitApplication(app_context);
            
            Debug.Fail("Update versions below!");
            ConfigurationContext.AddLibrary("mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e", null, "");
            ConfigurationContext.AddLibrary("System, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e", null, "");
            ConfigurationContext.AddLibrary("System.Windows, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e", null, "");
            ConfigurationContext.AddLibrary("System.Net, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e", null, "");
            //ConfigurationContext.AddLibrary("System.SilverLight, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", null, "");
            //ConfigurationContext.AddLibrary("agclr, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", null, "");

            ConfigurationContext.AddLibrary("PhpNetClassLibrary, Version=3.0.0.0, Culture=neutral, PublicKeyToken=4af37afe3cde05fb", null, "");

			//
			Configuration.Application.Compiler.Debug = true;

			// ..
			Dictionary<string, object> vars = new Dictionary<string, object>();

			currentContext.AutoGlobals.Canvas.Value = ClrObject.Wrap(c);
            currentContext.AutoGlobals.Addr.Value = ClrObject.Wrap(app_config.Compiler.SourceRoot.ToString());

			//Operators.SetVariableRef(currentContext, vars, "_CANVAS", Operators.GetItemRef("_CANVAS", ref currentContext.AutoGlobals.Globals.value));
			//Operators.SetVariable(currentContext, vars, "_CANVAS", ClrObject.Wrap(c));


            context.DynamicInclude(source, sourceRelPath, vars, null, null, InclusionTypes.RunSilverlight);

			return new EventHandler(delegate(object sender, EventArgs e)
				{
					if (context.ResolveFunction("OnLoad", null, true) != null)
					{
						PhpCallback load = new PhpCallback("OnLoad");
						load.Invoke(sender, e);
					}
				});
		}